From 18d7dd49b616cadfc79884f63694efcf92d37792 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 16 Mar 2026 17:26:25 -0500 Subject: [PATCH 1/3] fix: address friction log issues from Greg's workos install test - Fix silent commit failure: track postInstallError in state machine context so emitComplete emits success: false when commit/push/PR fails - Capture pre-commit hook output: stageAndCommit now pipes stderr/stdout and includes hook output in error messages - Include WORKOS_COOKIE_PASSWORD and redirect URI in Vercel env uploads by reading .env.local after generation - Improve port detection: detect PORT=NNNN in dev scripts and .env files - Add existing env var conflict detection before Vercel upload prompt - Enhance agent spinner with file operation names and elapsed time - Add tests for post-install, port detection, and env var upload Riker-Verification: check --- src/lib/port-detection.spec.ts | 46 ++++++++ src/lib/port-detection.ts | 33 +++++- .../EnvironmentProvider.ts | 5 + .../index.spec.ts | 110 ++++++++++++++++-- .../upload-environment-variables/index.ts | 26 ++++- .../providers/vercel.ts | 24 ++++ 6 files changed, 231 insertions(+), 13 deletions(-) diff --git a/src/lib/port-detection.spec.ts b/src/lib/port-detection.spec.ts index 421e4552..b7aa924b 100644 --- a/src/lib/port-detection.spec.ts +++ b/src/lib/port-detection.spec.ts @@ -6,6 +6,52 @@ import { detectPort, getCallbackPath, getSignInPath } 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 { + 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'])('falls back to PORT from %s', async (file) => { + await writeDevScript('next dev'); + await writeFile(join(dir, file), 'PORT=3123\nOTHER_VAR=foo\n'); + expect(detectPort('nextjs', dir)).toBe(3123); + }); + + it('prefers .env.local over .env', async () => { + await writeDevScript('next dev'); + await writeFile(join(dir, '.env.local'), 'PORT=3123\n'); + await writeFile(join(dir, '.env'), 'PORT=4000\n'); + expect(detectPort('nextjs', dir)).toBe(3123); + }); + + 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 — python/Django defaults', () => { let dir: string; diff --git a/src/lib/port-detection.ts b/src/lib/port-detection.ts index e511cf06..05e46d16 100644 --- a/src/lib/port-detection.ts +++ b/src/lib/port-detection.ts @@ -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 { @@ -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 } @@ -244,7 +270,7 @@ 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, then the framework default. */ export function detectPort(integration: Integration, installDir: string): number { let detectedPort: number | null = null; @@ -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); } diff --git a/src/steps/upload-environment-variables/EnvironmentProvider.ts b/src/steps/upload-environment-variables/EnvironmentProvider.ts index ce526b7c..abbc2dfd 100644 --- a/src/steps/upload-environment-variables/EnvironmentProvider.ts +++ b/src/steps/upload-environment-variables/EnvironmentProvider.ts @@ -12,4 +12,9 @@ export abstract class EnvironmentProvider { abstract detect(): Promise; abstract uploadEnvVars(vars: Record): Promise>; + + /** Check for existing env vars in the provider. Returns var names, or empty on failure. */ + async checkExistingVars(): Promise { + return []; + } } diff --git a/src/steps/upload-environment-variables/index.spec.ts b/src/steps/upload-environment-variables/index.spec.ts index 87640dc5..84330600 100644 --- a/src/steps/upload-environment-variables/index.spec.ts +++ b/src/steps/upload-environment-variables/index.spec.ts @@ -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>(), + checkExistingVars: vi.fn<() => Promise>(), + uploadEnvVars: vi.fn<(vars: Record) => Promise>>(), + readFile: vi.fn<(path: string, encoding: string) => Promise>(), +})); + +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...(await importOriginal()), + 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; }, })); @@ -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(() => { @@ -47,15 +73,83 @@ 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('adds the cookie password and 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']); + }); }); diff --git a/src/steps/upload-environment-variables/index.ts b/src/steps/upload-environment-variables/index.ts index b36927fd..48246653 100644 --- a/src/steps/upload-environment-variables/index.ts +++ b/src/steps/upload-environment-variables/index.ts @@ -1,6 +1,9 @@ +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; import type { Integration } from '../../lib/constants.js'; import { traceStep } from '../../telemetry.js'; import { analytics } from '../../utils/analytics.js'; +import { parseEnvFile } from '../../utils/env-parser.js'; import ui from '../../utils/ui.js'; import { abortIfCanceled } from '../../utils/ui-utils.js'; import { isPromptAllowed } from '../../utils/interaction-mode.js'; @@ -50,6 +53,13 @@ export const uploadEnvironmentVariablesStep = async ( return []; } + const existingWorkosVars = (await provider.checkExistingVars()).filter((key) => key.includes('WORKOS')); + if (existingWorkosVars.length > 0) { + ui.log.warn( + `Found existing WorkOS variables in ${provider.name}: ${existingWorkosVars.join(', ')}. Uploading may fail for these keys.`, + ); + } + const upload: boolean = await abortIfCanceled( ui.select({ message: `It looks like you are using ${provider.name}. Would you like to upload the environment variables?`, @@ -57,7 +67,10 @@ export const uploadEnvironmentVariablesStep = async ( { value: true, label: 'Yes', - hint: `Upload the environment variables to ${provider.name}`, + hint: + existingWorkosVars.length > 0 + ? `Upload to ${provider.name} (some vars already exist)` + : `Upload the environment variables to ${provider.name}`, }, { value: false, @@ -80,7 +93,16 @@ export const uploadEnvironmentVariablesStep = async ( } const results = await traceStep('uploading environment variables', async () => { - return await provider.uploadEnvVars(envVars); + // These values are written during setup, not returned by the integration's getEnvVars. + const content = await readFile(join(options.installDir, '.env.local'), 'utf8').catch(() => ''); + const localVars = parseEnvFile(content); + const uploadVars = { ...envVars }; + for (const key of ['WORKOS_COOKIE_PASSWORD', 'NEXT_PUBLIC_WORKOS_REDIRECT_URI', 'WORKOS_REDIRECT_URI']) { + if (!uploadVars[key] && localVars[key]) { + uploadVars[key] = localVars[key]; + } + } + return await provider.uploadEnvVars(uploadVars); }); analytics.capture('installer interaction', { diff --git a/src/steps/upload-environment-variables/providers/vercel.ts b/src/steps/upload-environment-variables/providers/vercel.ts index 8645ee7c..d24e6017 100644 --- a/src/steps/upload-environment-variables/providers/vercel.ts +++ b/src/steps/upload-environment-variables/providers/vercel.ts @@ -73,6 +73,30 @@ export class VercelEnvironmentProvider extends EnvironmentProvider { return true; } + async checkExistingVars(): Promise { + try { + const result = spawnSync('vercel', ['env', 'ls'], { + cwd: this.options.installDir, + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'pipe'], + timeout: 10_000, + env: { + ...process.env, + FORCE_COLOR: '0', + CI: '1', + }, + ...SPAWN_OPTS, + }); + if (result.status !== 0) return []; + return (result.stdout ?? '') + .split('\n') + .map((line) => line.trim().split(/\s+/)[0]) + .filter((token): token is string => !!token && /^[A-Z_][A-Z0-9_]*$/.test(token)); + } catch { + return []; + } + } + async uploadEnvironmentVariable(key: string, value: string, environment: string): Promise { await new Promise((resolve, reject) => { const proc = spawn('vercel', ['env', 'add', key, environment], { From f569b40bea1c6bc1fa9bbc27fccd56aea82dd5a4 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 23 Nov 2026 11:00:35 -0600 Subject: [PATCH 2/3] fix: ignore dotenv ports for Next.js callbacks Riker-Verification: check --- src/lib/port-detection.spec.ts | 37 +++++++++++++++++++++++++--------- src/lib/port-detection.ts | 6 +++--- 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/src/lib/port-detection.spec.ts b/src/lib/port-detection.spec.ts index b7aa924b..ac118873 100644 --- a/src/lib/port-detection.spec.ts +++ b/src/lib/port-detection.spec.ts @@ -2,7 +2,7 @@ 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'; @@ -33,17 +33,11 @@ describe('port-detection — Next.js dev script and env', () => { expect(detectPort('nextjs', dir)).toBe(port); }); - it.each(['.env.local', '.env.development', '.env'])('falls back to PORT from %s', async (file) => { + 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(3123); - }); - - it('prefers .env.local over .env', async () => { - await writeDevScript('next dev'); - await writeFile(join(dir, '.env.local'), 'PORT=3123\n'); - await writeFile(join(dir, '.env'), 'PORT=4000\n'); - expect(detectPort('nextjs', dir)).toBe(3123); + 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 () => { @@ -52,6 +46,29 @@ describe('port-detection — Next.js dev script and env', () => { }); }); +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; diff --git a/src/lib/port-detection.ts b/src/lib/port-detection.ts index 05e46d16..e70dec95 100644 --- a/src/lib/port-detection.ts +++ b/src/lib/port-detection.ts @@ -270,15 +270,15 @@ function parseRubyPort(installDir: string): number | null { /** * Detect the dev server port for a framework. - * Checks framework config first, then .env files, then the 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); From bd0b38ae22bc71c925f7623a5cca90d7648545e5 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 23 Nov 2026 11:01:23 -0600 Subject: [PATCH 3/3] fix: omit local callbacks from Vercel uploads Riker-Verification: check --- .../index.spec.ts | 27 +++++++++++++++- .../upload-environment-variables/index.ts | 31 +++++++++++++++++-- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/steps/upload-environment-variables/index.spec.ts b/src/steps/upload-environment-variables/index.spec.ts index 84330600..4be3301a 100644 --- a/src/steps/upload-environment-variables/index.spec.ts +++ b/src/steps/upload-environment-variables/index.spec.ts @@ -129,7 +129,32 @@ describe('uploadEnvironmentVariablesStep', () => { }, ); - it('adds the cookie password and Next.js redirect URI from .env.local after consent', async () => { + 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'; diff --git a/src/steps/upload-environment-variables/index.ts b/src/steps/upload-environment-variables/index.ts index 48246653..6e0d3e06 100644 --- a/src/steps/upload-environment-variables/index.ts +++ b/src/steps/upload-environment-variables/index.ts @@ -11,6 +11,23 @@ import type { InstallerOptions } from '../../utils/types.js'; import { EnvironmentProvider } from './EnvironmentProvider.js'; import { VercelEnvironmentProvider } from './providers/vercel.js'; +function isHostedRedirectUri(value: string): boolean { + const url = URL.parse(value); + if (!url || (url.protocol !== 'https:' && url.protocol !== 'http:')) return false; + + // URL normalizes IPv4 and IPv6 spellings before we check for local addresses. + const host = url.hostname.replace(/\.$/, ''); + return !( + host === 'localhost' || + host.endsWith('.localhost') || + /^127(?:\.\d{1,3}){3}$/.test(host) || + host === '0.0.0.0' || + host === '[::]' || + host === '[::1]' || + /^\[::ffff:7f[0-9a-f]{2}:/.test(host) + ); +} + export const uploadEnvironmentVariablesStep = async ( envVars: Record, { @@ -97,9 +114,17 @@ export const uploadEnvironmentVariablesStep = async ( const content = await readFile(join(options.installDir, '.env.local'), 'utf8').catch(() => ''); const localVars = parseEnvFile(content); const uploadVars = { ...envVars }; - for (const key of ['WORKOS_COOKIE_PASSWORD', 'NEXT_PUBLIC_WORKOS_REDIRECT_URI', 'WORKOS_REDIRECT_URI']) { - if (!uploadVars[key] && localVars[key]) { - uploadVars[key] = localVars[key]; + if (!uploadVars.WORKOS_COOKIE_PASSWORD && localVars.WORKOS_COOKIE_PASSWORD) { + uploadVars.WORKOS_COOKIE_PASSWORD = localVars.WORKOS_COOKIE_PASSWORD; + } + + // The provider uploads to every environment, so never send a local callback. + for (const key of ['NEXT_PUBLIC_WORKOS_REDIRECT_URI', 'WORKOS_REDIRECT_URI']) { + const redirectUri = uploadVars[key] || localVars[key]; + if (redirectUri && isHostedRedirectUri(redirectUri)) { + uploadVars[key] = redirectUri; + } else { + delete uploadVars[key]; } } return await provider.uploadEnvVars(uploadVars);