diff --git a/packages/void/package.json b/packages/void/package.json index b49d88995..93312e5f9 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -328,6 +328,7 @@ "@cloudflare/config": "0.20.0", "@cloudflare/sandbox": "^0.12.9", "@cloudflare/vite-plugin": "1.54.7", + "@cloudflare/workers-auth": "0.9.4", "@cloudflare/workers-types": "catalog:", "@napi-rs/keyring": "2.0.0", "@void/deploy-cloudflare": "workspace:*", diff --git a/packages/void/src/cli/cf-compat.ts b/packages/void/src/cli/cf-compat.ts index 8b0717fd2..a87a8c8e0 100644 --- a/packages/void/src/cli/cf-compat.ts +++ b/packages/void/src/cli/cf-compat.ts @@ -5,27 +5,24 @@ * process translates them to the pinned cf CLI. It never invokes Wrangler. */ import { spawnSync } from 'node:child_process'; -import { - copyFileSync, - mkdtempSync, - readFileSync, - readdirSync, - rmSync, - writeFileSync, -} from 'node:fs'; +import { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { fileURLToPath, pathToFileURL } from 'node:url'; +import { fileURLToPath } from 'node:url'; import { readBuildOutput } from '@cloudflare/build-output-utils'; import { parse } from 'jsonc-parser'; import { dirname, join, resolve } from 'pathslash'; import { EnvHttpProxyAgent, fetch as httpFetch } from 'undici'; import { prepareCfBuildOutput } from './cf-build-output.ts'; +import { persistCfKeyringPreference, readCfSessionCredential } from './cf-session.ts'; type Result = { status: number; stdout: string; stderr: string }; type Json = Record; const cf = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'bin', 'cf'); const args = process.argv.slice(2); +// This dedicated transport process uses the same encrypted OAuth store for +// login, deployment, and ancillary API calls. API-token overrides still win. +process.env.CLOUDFLARE_AUTH_USE_KEYRING = 'true'; function cfEnvironment(): NodeJS.ProcessEnv { // The pinned bin otherwise delegates to any cf installed by the project. @@ -416,37 +413,17 @@ async function sessionCredential(): Promise<{ type: 'oauth' | 'api_token'; token if (state.authenticated !== true || state.tokenValid !== true) { return null; } - if (typeof state.authSource !== 'string' || !state.authSource.startsWith('OAuth token')) { - return null; - } - // cf's encrypted store is authoritative. Reading the path from whoami would - // fail after cf migrates and deletes the old plaintext credential file. - const dist = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'dist'); - const entry = readdirSync(dist).find((name) => /^cf-[^/]+\.mjs$/.test(name)); - if (!entry) { - throw new Error('The bundled Cloudflare credential reader is unavailable.'); - } - const module = (await import(pathToFileURL(join(dist, entry)).href)) as { - t?: (options: { logger: Record) => void> }) => { - readAuthCredentials: () => unknown; - }; - }; - if (typeof module.t !== 'function') { - throw new Error('The bundled Cloudflare credential reader is unavailable.'); - } - const noop = () => {}; - const stored = module - .t({ logger: { debug: noop, info: noop, log: noop, warn: noop, error: noop } }) - .readAuthCredentials(); - const credential = stored && typeof stored === 'object' ? (stored as Json) : null; - return credential && typeof credential.oauth_token === 'string' && credential.oauth_token - ? { type: 'oauth', token: credential.oauth_token } - : null; + const credential = readCfSessionCredential(process.cwd(), state); + return credential ? { type: 'oauth', token: credential } : null; } async function auth(): Promise { if (args[0] === 'login') { - return runInteractiveCf(['auth', 'login', '--force']); + const loggedIn = runInteractiveCf(['auth', 'login', '--force']); + if (loggedIn.status === 0) { + persistCfKeyringPreference(process.cwd()); + } + return loggedIn; } if (args[0] === 'logout') { return runCf(['auth', 'logout']); @@ -464,6 +441,9 @@ async function auth(): Promise { 'Cloudflare authentication is required.', ); } + if (String(identity.authSource).startsWith('OAuth token from ')) { + persistCfKeyringPreference(process.cwd()); + } return result( 0, JSON.stringify({ diff --git a/packages/void/src/cli/cf-session.ts b/packages/void/src/cli/cf-session.ts new file mode 100644 index 000000000..00d9a32b1 --- /dev/null +++ b/packages/void/src/cli/cf-session.ts @@ -0,0 +1,58 @@ +import { + createCfAuth, + createCfProfileStore, + setKeyringPreference, +} from '@cloudflare/workers-auth/cf'; + +const logger = { + debug() {}, + info() {}, + log() {}, + warn() {}, + error() {}, +}; + +function session(root: string) { + const auth = createCfAuth({ + logger, + userAgent: 'void', + prompt: async () => { + throw new Error('Cloudflare session reads cannot prompt.'); + }, + select: async () => { + throw new Error('Cloudflare session reads cannot prompt.'); + }, + isNoDefaultValueProvidedError: () => false, + }); + auth.setProfile(createCfProfileStore({ logger }).resolve({ cwd: root })); + return auth; +} + +/** Borrow only the profile just verified by cf, including its encrypted store. */ +export function readCfSessionCredential( + root: string, + identity: Record, +): string | null { + if (identity.authenticated !== true || identity.tokenValid !== true) { + return null; + } + const auth = session(root); + if (identity.authSource !== `OAuth token from ${auth.getCredentialStore().path()}`) { + return null; + } + const token = auth.readAuthCredentials()?.oauth_token; + if (typeof token === 'string' && token.length > 0) { + persistCfKeyringPreference(root); + } + return typeof token === 'string' && token.length > 0 ? token : null; +} + +/** Keep subsequent cf logins on the encrypted profile adopted by Void. */ +export function persistCfKeyringPreference(root: string): void { + const auth = session(root); + if ( + !setKeyringPreference(true, { logger, getCredentialStore: auth.getCredentialStore }).enabled + ) { + throw new Error('Cloudflare encrypted credential storage is unavailable.'); + } +} diff --git a/packages/void/test/unit/cf-compat.test.ts b/packages/void/test/unit/cf-compat.test.ts index a0d983659..b02c2f326 100644 --- a/packages/void/test/unit/cf-compat.test.ts +++ b/packages/void/test/unit/cf-compat.test.ts @@ -1,11 +1,11 @@ import { execFile } from 'node:child_process'; -import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, request as httpRequest } from 'node:http'; import type { AddressInfo } from 'node:net'; import { connect } from 'node:net'; import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; import { expect, it } from 'vite-plus/test'; import { resolveWranglerArgv } from '../../src/cli/preset.ts'; @@ -64,94 +64,97 @@ it('clears Worker Cron Triggers through the pinned account API', async () => { } }, 30_000); -it('reads OAuth credentials through cf instead of using the whoami source as a file path', async () => { - const directory = mkdtempSync(join(tmpdir(), 'void-cf-clear-crons-oauth-')); - const server = createServer((request, response) => { - expect(request.headers.authorization).toBe('Bearer synthetic-oauth-token'); - request.resume(); - response.setHeader('Content-Type', 'application/json'); - response.end(JSON.stringify({ success: true, result: { schedules: [] } })); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - try { - const configPath = join(directory, 'wrangler.json'); - const cfDist = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'dist'); - const cfModule = readdirSync(cfDist).find((name) => /^cf-[^/]+\.mjs$/.test(name)); - if (!cfModule) { - throw new Error('The pinned Cloudflare auth module is missing.'); - } - const preload = join(directory, 'mock-cf.mjs'); - writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' })); - writeFileSync( - preload, - `import child from 'node:child_process'; +it.each(['clear-crons'])( + 'uses encrypted browser credentials for %s', + async (operation) => { + const directory = mkdtempSync(join(tmpdir(), 'void-cf-clear-crons-oauth-')); + const server = createServer((request, response) => { + expect(request.headers.authorization).toBe('Bearer synthetic-oauth-token'); + request.resume(); + response.setHeader('Content-Type', 'application/json'); + response.end(JSON.stringify({ success: true, result: { schedules: [] } })); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const configPath = join(directory, 'wrangler.json'); + const preload = join(directory, 'mock-cf.mjs'); + writeFileSync( + configPath, + JSON.stringify({ name: 'test-worker', account_id: 'test-account' }), + ); + writeFileSync( + preload, + `import child from 'node:child_process'; import os from 'node:os'; import { syncBuiltinESMExports } from 'node:module'; os.homedir = () => process.env.VOID_TEST_HOME; syncBuiltinESMExports(); -process.env.CLOUDFLARE_AUTH_USE_KEYRING = 'false'; -const cf = await import(${JSON.stringify(pathToFileURL(join(cfDist, cfModule)).href)}); -const noop = () => {}; -cf.t({ logger: { debug: noop, info: noop, log: noop, warn: noop, error: noop } }) - .writeAuthCredentials({ oauth_token: 'synthetic-oauth-token' }); +import { setKeyProviderFactoryForTesting } from ${JSON.stringify(import.meta.resolve('@cloudflare/workers-auth'))}; +import { createCfAuth } from ${JSON.stringify(import.meta.resolve('@cloudflare/workers-auth/cf'))}; +let key; +setKeyProviderFactoryForTesting(() => ({ getKey: () => key, setKey: (value) => { key = value; }, deleteKey: () => { key = undefined; }, describe: () => 'synthetic provider' })); +const logger = { debug() {}, info() {}, log() {}, warn() {}, error() {} }; +const auth = createCfAuth({ logger, userAgent: 'void-test', prompt: async () => '', select: async () => '', isNoDefaultValueProvidedError: () => false }); +auth.writeAuthCredentials({ oauth_token: 'synthetic-oauth-token', refresh_token: 'synthetic-refresh', expiration_time: new Date(Date.now() + 3600000).toISOString(), scopes: [] }); +const credentialPath = auth.getCredentialStore().path(); child.spawnSync = (_binary, args, options) => { if (args[1] !== 'auth' || args[2] !== 'whoami' || options.env.CLOUDFLARE_AUTH_USE_KEYRING !== 'true') { return { status: 1, stdout: '', stderr: 'Wrong authentication source.' }; } - // Keep this synthetic test independent of the host OS keyring. The cf - // subprocess still has to receive the keyring pin. - return { status: 0, stdout: JSON.stringify({ authenticated: true, tokenValid: true, authSource: 'OAuth token from encrypted store' }), stderr: '' }; + return { status: 0, stdout: JSON.stringify({ authenticated: true, tokenValid: true, authSource: 'OAuth token from ' + credentialPath }), stderr: '' }; }; syncBuiltinESMExports(); `, - ); - const entry = join(import.meta.dirname, '..', '..', 'src', 'cli', 'cf-compat.ts'); - const output = await new Promise<{ status: number; stderr: string }>((resolve) => { - execFile( - process.execPath, - [ - '--import', - pathToFileURL(preload).href, - entry, - 'triggers', - 'clear-crons', - '-c', - configPath, - '--name', - 'test-worker', - ], - { - cwd: directory, - encoding: 'utf8', - timeout: 20_000, - env: { - PATH: process.env.PATH, - SYSTEMROOT: process.env.SYSTEMROOT, - WINDIR: process.env.WINDIR, - CI: 'true', - HOME: directory, - USERPROFILE: directory, - XDG_CONFIG_HOME: join(directory, '.config'), - APPDATA: join(directory, 'AppData', 'Roaming'), - LOCALAPPDATA: join(directory, 'AppData', 'Local'), - CLOUDFLARE_AUTH_USE_KEYRING: 'true', - CLOUDFLARE_ACCOUNT_ID: 'test-account', - CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`, - VOID_TEST_HOME: directory, - }, - }, - (error, _stdout, stderr) => resolve({ status: error ? 1 : 0, stderr }), ); - }); - expect(output.status, output.stderr).toBe(0); - } finally { - await new Promise((resolve) => { - server.close(() => resolve()); - server.closeAllConnections(); - }); - rmSync(directory, { recursive: true, force: true }); - } -}, 30_000); + const entry = join(import.meta.dirname, '..', '..', 'src', 'cli', 'cf-compat.ts'); + const output = await new Promise<{ status: number; stderr: string }>((resolve) => { + execFile( + process.execPath, + [ + '--import', + pathToFileURL(preload).href, + entry, + 'triggers', + operation, + '-c', + configPath, + '--name', + 'test-worker', + ], + { + cwd: directory, + encoding: 'utf8', + timeout: 20_000, + env: { + PATH: process.env.PATH, + SYSTEMROOT: process.env.SYSTEMROOT, + WINDIR: process.env.WINDIR, + CI: 'true', + CLOUDFLARE_AUTH_USE_KEYRING: 'true', + CLOUDFLARE_ACCOUNT_ID: 'test-account', + CLOUDFLARE_API_BASE_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/client/v4`, + HOME: directory, + USERPROFILE: directory, + XDG_CONFIG_HOME: join(directory, '.config'), + APPDATA: join(directory, 'AppData', 'Roaming'), + LOCALAPPDATA: join(directory, 'AppData', 'Local'), + VOID_TEST_HOME: directory, + }, + }, + (error, _stdout, stderr) => resolve({ status: error ? 1 : 0, stderr }), + ); + }); + expect(output.status, output.stderr).toBe(0); + } finally { + await new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }); + rmSync(directory, { recursive: true, force: true }); + } + }, + 30_000, +); it('reports an absent cf session as authentication failure', async () => { const directory = mkdtempSync(join(tmpdir(), 'void-cf-no-auth-')); diff --git a/packages/void/test/unit/cf-session.test.ts b/packages/void/test/unit/cf-session.test.ts new file mode 100644 index 000000000..e5444c30a --- /dev/null +++ b/packages/void/test/unit/cf-session.test.ts @@ -0,0 +1,124 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + clearCredentialStorageState, + setKeyProviderFactoryForTesting, +} from '@cloudflare/workers-auth'; +import { + createCfAuth, + createCfProfileStore, + readUserPreferences, + writeAuthConfigFile, +} from '@cloudflare/workers-auth/cf'; +import { afterEach, beforeEach, expect, it, vi } from 'vite-plus/test'; +import { persistCfKeyringPreference, readCfSessionCredential } from '../../src/cli/cf-session.ts'; + +let root: string; +const logger = { debug() {}, info() {}, log() {}, warn() {}, error() {} }; +const authContext = { + logger, + userAgent: 'void-test', + prompt: async () => { + throw new Error('Unexpected prompt'); + }, + select: async () => { + throw new Error('Unexpected prompt'); + }, + isNoDefaultValueProvidedError: () => false, +}; + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'void-cf-session-')); + for (const key of ['HOME', 'USERPROFILE', 'XDG_CONFIG_HOME', 'APPDATA', 'LOCALAPPDATA']) { + vi.stubEnv(key, root); + } + vi.stubEnv('CLOUDFLARE_AUTH_USE_KEYRING', 'true'); + vi.stubEnv('CLOUDFLARE_API_TOKEN', ''); + vi.stubEnv('CF_API_TOKEN', ''); + clearCredentialStorageState(); + const keys = new Map(); + setKeyProviderFactoryForTesting((service, profile) => { + const name = `${service}:${profile}`; + return { + getKey: () => keys.get(name), + setKey: (key) => { + keys.set(name, key); + }, + deleteKey: () => { + keys.delete(name); + }, + describe: () => 'synthetic key provider', + }; + }); +}); +afterEach(() => { + setKeyProviderFactoryForTesting(undefined); + clearCredentialStorageState(); + vi.unstubAllEnvs(); + rmSync(root, { recursive: true, force: true }); +}); + +function stored(profile = 'default') { + const auth = createCfAuth(authContext); + auth.setProfile(profile); + auth.writeAuthCredentials({ + oauth_token: `synthetic-${profile}`, + refresh_token: 'synthetic-refresh', + expiration_time: new Date(Date.now() + 3600_000).toISOString(), + scopes: [], + }); + const path = auth.getCredentialStore().path(); + expect(path).toMatch(/\.enc$/); + expect(readFileSync(path, 'utf8')).not.toContain(`synthetic-${profile}`); + return { authenticated: true, tokenValid: true, authSource: `OAuth token from ${path}` }; +} + +it('borrows a verified encrypted session and persists the store preference', () => { + expect(readCfSessionCredential(root, stored())).toBe('synthetic-default'); + expect(readUserPreferences().keyring_enabled).toBe(true); +}); + +it('uses the named profile bound to the project, never another profile', () => { + const other = stored(); + const team = stored('team'); + createCfProfileStore({ logger }).bindings.activate('team', root); + expect(readCfSessionCredential(root, other)).toBeNull(); + expect(readCfSessionCredential(root, team)).toBe('synthetic-team'); +}); + +it('does not borrow an invalid session or a different credential source', () => { + const identity = stored(); + expect(readCfSessionCredential(root, { ...identity, tokenValid: false })).toBeNull(); + expect(readCfSessionCredential(root, { ...identity, authenticated: false })).toBeNull(); + expect( + readCfSessionCredential(root, { ...identity, authSource: 'OAuth token from /untrusted/path' }), + ).toBeNull(); +}); + +it('adopts a legacy plaintext profile through Cloudflare encrypted storage', () => { + writeAuthConfigFile({ + oauth_token: 'synthetic-legacy', + refresh_token: 'synthetic-refresh', + expiration_time: new Date(Date.now() + 3600_000).toISOString(), + scopes: [], + }); + const auth = createCfAuth(authContext); + const path = auth.getCredentialStore().path(); + expect( + readCfSessionCredential(root, { + authenticated: true, + tokenValid: true, + authSource: `OAuth token from ${path}`, + }), + ).toBe('synthetic-legacy'); + expect(readFileSync(path, 'utf8')).not.toContain('synthetic-legacy'); + expect(readUserPreferences().keyring_enabled).toBe(true); +}); + +it('retains the encrypted preference for later compatible CLI logins', () => { + stored(); + persistCfKeyringPreference(root); + vi.stubEnv('CLOUDFLARE_AUTH_USE_KEYRING', undefined); + expect(createCfAuth(authContext).getCredentialStore().kind).toBe('encrypted-file'); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9c3daebe3..35443ef6b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -649,6 +649,9 @@ importers: vite: specifier: npm:@voidzero-dev/vite-plus-core@0.3.1 version: '@voidzero-dev/vite-plus-core@0.3.1(@types/node@26.5.1)(esbuild@0.27.7)(jiti@2.7.0)(sass@1.99.0)(terser@5.51.2)(tsx@4.23.0)(typescript@7.0.2)(yaml@2.9.0)' + "@cloudflare/workers-auth": + specifier: 0.9.4 + version: 0.9.4(vitest@4.1.11) devDependencies: '@clack/core': specifier: 1.5.0 @@ -10919,6 +10922,29 @@ packages: zwitch@2.0.4: resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} + "@cloudflare/workers-auth@0.9.4": + resolution: {integrity: sha512-Rmia49NzDLU+tHEwzv2yKkoDb4k4Gk1kAEyUe8nJ+BfhcfUwJ2otSaN/4PbP4QRjUBH9g/ERzniIgktb6K/QuQ==} + peerDependencies: + msw: 2.14.6 + vitest: ^4.1.0 + peerDependenciesMeta: + msw: + optional: true + vitest: + optional: true + "@cloudflare/workers-utils@0.44.0": + resolution: {integrity: sha512-3IpuKdIXpkICftrg75IO5rKLTweOfY82gH1cTqnP1Zj5lS40VOW7OJ3j9ZlI+TnP1IzeCsN8nk6R7FMypXQTtg==} + peerDependencies: + vitest: ^4.1.0 + peerDependenciesMeta: + vitest: + optional: true + dotenv@16.3.1: + resolution: {integrity: sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==} + engines: {node: '>=12'} + chalk@5.3.0: + resolution: {integrity: sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==} + engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} snapshots: @@ -22124,3 +22150,18 @@ snapshots: zod@4.6.5: {} zwitch@2.0.4: {} + "@cloudflare/workers-auth@0.9.4(vitest@4.1.11)": + dependencies: + '@cloudflare/workers-utils': 0.44.0(vitest@4.1.11) + undici: 7.29.0 + optionalDependencies: + vitest: 4.1.11(@types/node@26.5.1)(@vitest/browser-preview@4.1.11)(@voidzero-dev/vite-plus-core@0.3.1(@types/node@26.5.1)(esbuild@0.27.7)(jiti@2.7.0)(sass@1.99.0)(terser@5.51.2)(tsx@4.23.0)(typescript@7.0.2)(yaml@2.9.0)) + "@cloudflare/workers-utils@0.44.0(vitest@4.1.11)": + dependencies: + chalk: 5.3.0 + dotenv: 16.3.1 + undici: 7.29.0 + optionalDependencies: + vitest: 4.1.11(@types/node@26.5.1)(@vitest/browser-preview@4.1.11)(@voidzero-dev/vite-plus-core@0.3.1(@types/node@26.5.1)(esbuild@0.27.7)(jiti@2.7.0)(sass@1.99.0)(terser@5.51.2)(tsx@4.23.0)(typescript@7.0.2)(yaml@2.9.0)) + dotenv@16.3.1: {} + chalk@5.3.0: {}