Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 64 additions & 1 deletion src/lib/port-detection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,73 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { detectPort, getCallbackPath, getSignInPath } from './port-detection.js';
import { detectPort, getCallbackPath, getSignInPath, resolveRedirectUri } from './port-detection.js';
import { buildSignInSection } from './sign-in-route.js';
import type { FrameworkConfig } from './framework-config.js';

describe('port-detection — Next.js dev script and env', () => {
let dir: string;

beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'port-nextjs-'));
});

afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});

async function writeDevScript(dev: string): Promise<void> {
await writeFile(join(dir, 'package.json'), JSON.stringify({ scripts: { dev } }));
}

it.each([
['next dev -p 4000', 4000],
['next dev --port 5000', 5000],
['next dev --port=3123', 3123],
['PORT=3123 next dev', 3123],
['PORT=4000 next dev -p 5000', 5000],
])('detects the port from %s', async (script, port) => {
await writeDevScript(script);
await writeFile(join(dir, '.env.local'), 'PORT=6000\n');
expect(detectPort('nextjs', dir)).toBe(port);
});

it.each(['.env.local', '.env.development', '.env'])('ignores PORT from %s for Next.js', async (file) => {
await writeDevScript('next dev');
await writeFile(join(dir, file), 'PORT=3123\nOTHER_VAR=foo\n');
expect(detectPort('nextjs', dir)).toBe(3000);
expect(resolveRedirectUri('nextjs', { installDir: dir })).toBe(`http://localhost:3000${getCallbackPath('nextjs')}`);
});

it('falls back to 3000 when no PORT setting is present', async () => {
await writeDevScript('APP_PORT=3123 next dev');
expect(detectPort('nextjs', dir)).toBe(3000);
});
});

describe('port-detection — dotenv fallback', () => {
let dir: string;

beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'port-dotenv-'));
});

afterEach(async () => {
await rm(dir, { recursive: true, force: true });
});

it.each(['.env.local', '.env.development', '.env'])('falls back to PORT from %s', async (file) => {
await writeFile(join(dir, file), 'PORT=3123\nOTHER_VAR=foo\n');
expect(detectPort('node', dir)).toBe(3123);
});

it('prefers .env.local over .env', async () => {
await writeFile(join(dir, '.env.local'), 'PORT=3123\n');
await writeFile(join(dir, '.env'), 'PORT=4000\n');
expect(detectPort('node', dir)).toBe(3123);
});
});

describe('port-detection — python/Django defaults', () => {
let dir: string;

Expand Down
37 changes: 32 additions & 5 deletions src/lib/port-detection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ function parseViteConfigPortFromDir(installDir: string): number | null {

/**
* Parse port from Next.js package.json scripts.
* Next.js uses: "dev": "next dev -p 4000" or --port 4000
* Checks for: -p 4000, --port 4000, --port=4000, PORT=4000
*/
function parseNextConfigPort(installDir: string): number | null {
try {
Expand All @@ -117,12 +117,38 @@ function parseNextConfigPort(installDir: string): number | null {
if (portMatch) {
return parseInt(portMatch[1] || portMatch[2], 10);
}

// Match: PORT=4000 (inline env var in script)
const portEnvMatch = devScript.match(/(?:^|\s)PORT=(\d+)(?=\s|$)/);
if (portEnvMatch) {
return parseInt(portEnvMatch[1], 10);
}
} catch {
// Can't read package.json
}
return null;
}

/**
* Parse PORT from .env files.
* Checks .env.local, .env.development, .env in order.
*/
function parseEnvFilePort(installDir: string): number | null {
const envFiles = ['.env.local', '.env.development', '.env'];
for (const file of envFiles) {
try {
const content = fs.readFileSync(join(installDir, file), 'utf-8');
const match = content.match(/^PORT=(\d+)/m);
if (match) {
return parseInt(match[1], 10);
}
} catch {
// File doesn't exist
}
}
return null;
}

/**
* Parse port from TanStack Start app.config.ts.
* Uses Vinxi: server: { port: N }
Expand Down Expand Up @@ -244,15 +270,15 @@ function parseRubyPort(installDir: string): number | null {

/**
* Detect the dev server port for a framework.
* Checks config files first, falls back to framework default.
* Checks framework config first, then .env files (except for Next.js), then the framework default.
*/
export function detectPort(integration: Integration, installDir: string): number {
let detectedPort: number | null = null;

switch (integration) {
case 'nextjs':
detectedPort = parseNextConfigPort(installDir);
break;
// Next.js chooses its listening port before it loads .env files.
return parseNextConfigPort(installDir) ?? getDefaultPort(integration);

case 'tanstack-start':
// Modern @tanstack/react-start is Vite-based (port in vite.config.ts);
Expand Down Expand Up @@ -285,5 +311,6 @@ export function detectPort(integration: Integration, installDir: string): number
break;
}

return detectedPort ?? getDefaultPort(integration);
// Fallback: check .env files for PORT before using framework default
return detectedPort ?? parseEnvFilePort(installDir) ?? getDefaultPort(integration);
}
5 changes: 5 additions & 0 deletions src/steps/upload-environment-variables/EnvironmentProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,9 @@ export abstract class EnvironmentProvider {
abstract detect(): Promise<boolean>;

abstract uploadEnvVars(vars: Record<string, string>): Promise<Record<string, boolean>>;

/** Check for existing env vars in the provider. Returns var names, or empty on failure. */
async checkExistingVars(): Promise<string[]> {
return [];
}
}
135 changes: 127 additions & 8 deletions src/steps/upload-environment-variables/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { join } from 'node:path';
import type { InstallerOptions } from '../../utils/types.js';

// Force a provider to be detected so we reach the upload decision point.
const { detect, checkExistingVars, uploadEnvVars, readFile } = vi.hoisted(() => ({
detect: vi.fn<() => Promise<boolean>>(),
checkExistingVars: vi.fn<() => Promise<string[]>>(),
uploadEnvVars: vi.fn<(vars: Record<string, string>) => Promise<Record<string, boolean>>>(),
readFile: vi.fn<(path: string, encoding: string) => Promise<string>>(),
}));

vi.mock('node:fs/promises', async (importOriginal) => ({
...(await importOriginal<typeof import('node:fs/promises')>()),
readFile,
}));

// Default to a detected provider so we reach the upload decision point.
// Use a class (not an arrow fn) so `new VercelEnvironmentProvider()` constructs.
vi.mock('./providers/vercel.js', () => ({
VercelEnvironmentProvider: class {
name = 'Vercel';
detect = vi.fn(async () => true);
uploadEnvVars = vi.fn(async () => ({}));
detect = detect;
checkExistingVars = checkExistingVars;
uploadEnvVars = uploadEnvVars;
},
}));

Expand All @@ -19,21 +34,32 @@ vi.mock('../../utils/ui.js', () => ({
}));

vi.mock('../../utils/analytics.js', () => ({
analytics: { capture: vi.fn(), shutdown: vi.fn(), setTag: vi.fn() },
analytics: { capture: vi.fn(), shutdown: vi.fn(), setTag: vi.fn(), stepCompleted: vi.fn() },
}));

const ui = (await import('../../utils/ui.js')).default;
const { uploadEnvironmentVariablesStep } = await import('./index.js');
const { setInteractionMode, resetInteractionModeForTests } = await import('../../utils/interaction-mode.js');

const integration = 'nextjs' as never;
const options = { installDir: '/proj' } as never;
const integration = 'nextjs' as const;
const options: InstallerOptions = {
installDir: '/proj',
debug: false,
forceInstall: false,
local: false,
ci: false,
skipAuth: false,
};

describe('uploadEnvironmentVariablesStep — non-interactive skip', () => {
describe('uploadEnvironmentVariablesStep', () => {
beforeEach(() => {
resetInteractionModeForTests();
vi.clearAllMocks();
vi.mocked(ui.isCancel).mockReturnValue(false);
detect.mockReset().mockResolvedValue(true);
checkExistingVars.mockReset().mockResolvedValue([]);
uploadEnvVars.mockReset().mockResolvedValue({});
readFile.mockReset().mockRejectedValue(new Error('ENOENT'));
});

afterEach(() => {
Expand All @@ -47,15 +73,108 @@ describe('uploadEnvironmentVariablesStep — non-interactive skip', () => {

expect(result).toEqual([]);
expect(ui.select).not.toHaveBeenCalled();
expect(checkExistingVars).not.toHaveBeenCalled();
expect(readFile).not.toHaveBeenCalled();
expect(uploadEnvVars).not.toHaveBeenCalled();
});

it('human mode reaches the prompt', async () => {
setInteractionMode({ mode: 'human', source: 'default' });
vi.mocked(ui.select).mockResolvedValueOnce(false as never);
vi.mocked(ui.select).mockResolvedValueOnce(false);

const result = await uploadEnvironmentVariablesStep({}, { integration, options });

expect(result).toEqual([]);
expect(ui.select).toHaveBeenCalledOnce();
});

it('returns empty when no provider is detected', async () => {
setInteractionMode({ mode: 'human', source: 'default' });
detect.mockResolvedValue(false);

expect(await uploadEnvironmentVariablesStep({ WORKOS_API_KEY: 'sk_test' }, { integration, options })).toEqual([]);
expect(ui.select).not.toHaveBeenCalled();
expect(checkExistingVars).not.toHaveBeenCalled();
});

it('warns about existing WorkOS vars before prompting', async () => {
setInteractionMode({ mode: 'human', source: 'default' });
checkExistingVars.mockResolvedValue(['WORKOS_API_KEY', 'WORKOS_CLIENT_ID', 'NODE_ENV']);
vi.mocked(ui.select).mockResolvedValueOnce(false);

await uploadEnvironmentVariablesStep({ WORKOS_API_KEY: 'sk_test' }, { integration, options });

expect(ui.log.warn).toHaveBeenCalledWith(
'Found existing WorkOS variables in Vercel: WORKOS_API_KEY, WORKOS_CLIENT_ID. Uploading may fail for these keys.',
);
expect(ui.log.warn).toHaveBeenCalledBefore(ui.select);
expect(readFile).not.toHaveBeenCalled();
expect(uploadEnvVars).not.toHaveBeenCalled();
});

it.each([{ existing: [] }, { existing: ['NODE_ENV', 'VERCEL_URL'] }])(
'uploads without warning when listed vars are $existing',
async ({ existing }) => {
setInteractionMode({ mode: 'human', source: 'default' });
checkExistingVars.mockResolvedValue(existing);
vi.mocked(ui.select).mockResolvedValueOnce(true);
uploadEnvVars.mockResolvedValue({ WORKOS_API_KEY: true });
const envVars = { WORKOS_API_KEY: 'sk_test' };

const result = await uploadEnvironmentVariablesStep(envVars, { integration, options });

expect(ui.log.warn).not.toHaveBeenCalled();
expect(uploadEnvVars).toHaveBeenCalledWith(envVars);
expect(result).toEqual(['WORKOS_API_KEY']);
},
);

it.each([
'http://localhost:3000/auth/callback',
'http://app.localhost.:3000/auth/callback',
'http://127.0.0.2:3000/auth/callback',
'http://[::1]:3000/auth/callback',
'http://[::ffff:127.0.0.1]:3000/auth/callback',
'http://0.0.0.0:3000/auth/callback',
'http://[::]:3000/auth/callback',
'/auth/callback',
'ftp://example.com/auth/callback',
])('omits %s from the Vercel upload without dropping the cookie password', async (redirectUri) => {
setInteractionMode({ mode: 'human', source: 'default' });
vi.mocked(ui.select).mockResolvedValueOnce(true);
readFile.mockResolvedValue(
`WORKOS_COOKIE_PASSWORD=test-password\nNEXT_PUBLIC_WORKOS_REDIRECT_URI=${redirectUri}\n`,
);
uploadEnvVars.mockResolvedValue({ WORKOS_COOKIE_PASSWORD: true });

// Check both a value read from .env.local and a value supplied by the caller.
const result = await uploadEnvironmentVariablesStep({ WORKOS_REDIRECT_URI: redirectUri }, { integration, options });

expect(uploadEnvVars).toHaveBeenCalledWith({ WORKOS_COOKIE_PASSWORD: 'test-password' });
expect(result).toEqual(['WORKOS_COOKIE_PASSWORD']);
});

it('adds the cookie password and hosted Next.js redirect URI from .env.local after consent', async () => {
setInteractionMode({ mode: 'human', source: 'default' });
vi.mocked(ui.select).mockResolvedValueOnce(true);
const redirectUri = 'https://example.com/auth/callback';
readFile.mockResolvedValue(
`WORKOS_COOKIE_PASSWORD=test-password\nNEXT_PUBLIC_WORKOS_REDIRECT_URI=${redirectUri}\nWORKOS_API_KEY=stale\nWORKOS_CLAIM_TOKEN=local-only\n`,
);
uploadEnvVars.mockResolvedValue({
WORKOS_API_KEY: true,
WORKOS_COOKIE_PASSWORD: true,
NEXT_PUBLIC_WORKOS_REDIRECT_URI: true,
});

const result = await uploadEnvironmentVariablesStep({ WORKOS_API_KEY: 'sk_test' }, { integration, options });

expect(readFile).toHaveBeenCalledWith(join(options.installDir, '.env.local'), 'utf8');
expect(uploadEnvVars).toHaveBeenCalledWith({
WORKOS_API_KEY: 'sk_test',
WORKOS_COOKIE_PASSWORD: 'test-password',
NEXT_PUBLIC_WORKOS_REDIRECT_URI: redirectUri,
});
expect(result).toEqual(['WORKOS_API_KEY', 'WORKOS_COOKIE_PASSWORD', 'NEXT_PUBLIC_WORKOS_REDIRECT_URI']);
});
});
Loading