/** * WP 1.6 (temporary-first CLI): the measured "Live in N s", the claim link's * `?ref=`, `--watch` for the first request, and `scribase doctor`. */ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, readFileSync, statSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { claimUrlWithRef, parseInitArgs, runInit } from '../src/cli/init.js'; import type { InitIo } from '../src/cli/init.js'; import { envEntries, formatDoctor, jwtRole, leakedSecretVars, runDoctor } from '../src/cli/doctor.js'; import type { DoctorIo } from '../src/cli/doctor.js'; import { installId } from '../src/cli/credentials.js'; const ROOT = '/work/app'; const TMP_ID = 'tmp_0123456789abcdef01234567'; const KEYS = { api_url: 'https://tmp-abc-shop-production.scribase.app', anon_key: 'eyJ.anon.key', service_role_key: 'eyJ.service.key' }; function jwt(payload: Record): string { const part = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url'); return `${part({ alg: 'HS256' })}.${part(payload)}.sig`; } function temporaryIo(extra: Partial = {}, firstRequestAfter = 2) { const files: Record = { [`${ROOT}/package.json`]: JSON.stringify({ dependencies: { next: '15', '@supabase/supabase-js': '2' } }) }; const logs: string[] = []; let clock = 1_000_000; let watches = 0; const paths: string[] = []; const io: InitIo = { cwd: ROOT, env: {}, fetch: (async (url: string | URL | Request, init?: RequestInit) => { const path = new URL(String(url)).pathname; paths.push(`${init?.method ?? 'GET'} ${path}`); const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status }); if (path === '/v1/temporary-projects/challenge') return json(200, { challenge: 'c', bits: 0 }); if (path === '/v1/temporary-projects') { return json(201, { id: TMP_ID, organization_id: 'tmp-0123456789abcdef01234567', project_id: 'shop', environment_id: 'production', agent_token: 'scb_agt_secret', claim_url: `https://console.scribase.com/claim/${TMP_ID}#scb_claim_x`, expires_at: 1_900_000_000, }); } if (path === `/v1/temporary-projects/${TMP_ID}`) { clock += 4_200; // the database takes a while return json(200, { status: 'ready', keys: KEYS }); } if (path.endsWith('/first-request')) { watches += 1; return json(200, { first_request_at: watches >= firstRequestAfter ? 1_800_000_000 : null }); } return json(404, {}); }) as typeof fetch, readFile: (path) => files[path] ?? null, writeFile: (path, contents) => { files[path] = contents; }, exists: (path) => path in files, run: () => ({ ok: true, output: '' }), sleep: async (ms) => { clock += ms; }, log: (line) => logs.push(line), credentials: () => ({}), now: () => clock, installId: () => 'install0123abcd', ...extra, }; return { io, files, logs, paths }; } describe('init: temporary-first front door', () => { it('measures "live in" seconds, adds ?ref= before the claim fragment and saves the temporary id', async () => { const { io, files, paths } = temporaryIo(); const result = await runInit(parseInitArgs(['--json', '--name', 'shop']), io); assert.equal(result.temporary, true); assert.equal(result.live_in_seconds, 4.2); assert.equal(result.claim_url, `https://console.scribase.com/claim/${TMP_ID}?ref=install0123abcd#scb_claim_x`); assert.equal(result.first_request_at, undefined, 'no watch unless asked'); assert.ok(!paths.some((path) => path.endsWith('/first-request'))); const state = JSON.parse(files[`${ROOT}/.scribase/project.json`] ?? '{}') as Record; assert.equal(state.temporary_id, TMP_ID); assert.equal(state.claim_url, result.claim_url); assert.ok(!JSON.stringify(result).includes('scb_agt_secret'), 'the agent token is never in the output'); }); it('--watch waits for the first request and reports when it came', async () => { const { io, logs } = temporaryIo({}, 3); const result = await runInit(parseInitArgs(['--json', '--watch']), io); assert.equal(result.first_request_at, 1_800_000_000); assert.ok(logs.some((line) => /first request/.test(line))); }); it('--watch gives up after --watch-seconds with a next step, never an error', async () => { const { io } = temporaryIo({}, 1_000); const result = await runInit(parseInitArgs(['--json', '--watch-seconds', '10']), io); assert.equal(result.first_request_at, null); assert.ok(result.next_steps.some((step) => /scribase doctor/.test(step))); }); it('sends no ref when there is no install id', async () => { const { io } = temporaryIo({ installId: () => null }); const result = await runInit(parseInitArgs(['--json']), io); assert.equal(result.claim_url, `https://console.scribase.com/claim/${TMP_ID}#scb_claim_x`); }); it('rejects --temp together with --account', () => { assert.throws(() => parseInitArgs(['--temp', '--account'])); assert.equal(parseInitArgs(['--login']).account, true); assert.throws(() => parseInitArgs(['--watch-seconds', '0'])); }); }); describe('claimUrlWithRef', () => { it('puts ref in the query, before the fragment, once', () => { assert.equal(claimUrlWithRef('https://c/claim/x#tok', 'abcdefgh1'), 'https://c/claim/x?ref=abcdefgh1#tok'); assert.equal(claimUrlWithRef('https://c/claim/x?a=1#tok', 'abcdefgh1'), 'https://c/claim/x?a=1&ref=abcdefgh1#tok'); assert.equal(claimUrlWithRef('https://c/claim/x?ref=old#tok', 'abcdefgh1'), 'https://c/claim/x?ref=old#tok'); assert.equal(claimUrlWithRef('https://c/claim/x#tok', 'bad id!'), 'https://c/claim/x#tok'); assert.equal(claimUrlWithRef('https://c/claim/x#tok', null), 'https://c/claim/x#tok'); }); }); describe('installId', () => { it('creates one random id, keeps it, file mode 0600, and honours SCRIBASE_NO_REF', () => { const dir = mkdtempSync(join(tmpdir(), 'scribase-install-')); const env = { XDG_CONFIG_HOME: dir }; const first = installId(env, () => 'abcdef0123456789'); assert.equal(first, 'abcdef0123456789'); assert.equal(installId(env, () => 'different0000000'), 'abcdef0123456789'); const path = join(dir, 'scribase', 'install-id'); assert.equal(readFileSync(path, 'utf8').trim(), 'abcdef0123456789'); assert.equal(statSync(path).mode & 0o777, 0o600); assert.equal(installId({ ...env, SCRIBASE_NO_REF: '1' }), null); }); }); /* --------------------------------- doctor --------------------------------- */ function doctorIo(files: Record, answer: (url: string) => number | Error, now = 1_000_000_000_000): DoctorIo { return { cwd: ROOT, fetch: (async (url: string | URL | Request) => { const outcome = answer(String(url)); if (outcome instanceof Error) throw outcome; return new Response('{}', { status: outcome }); }) as typeof fetch, readFile: (path) => files[path] ?? null, exists: (path) => path in files, now: () => now, }; } const ANON = jwt({ role: 'anon' }); const SERVICE = jwt({ role: 'service_role' }); describe('scribase doctor', () => { it('passes a healthy Next.js app and never prints key values', async () => { const files = { [`${ROOT}/package.json`]: JSON.stringify({ dependencies: { next: '15' } }), [`${ROOT}/.env.local`]: `NEXT_PUBLIC_SUPABASE_URL=https://x.scribase.app\nNEXT_PUBLIC_SUPABASE_ANON_KEY=${ANON}\nSUPABASE_SERVICE_ROLE_KEY=${SERVICE}\n`, [`${ROOT}/.gitignore`]: '.env.local\n', [`${ROOT}/.scribase/project.json`]: JSON.stringify({ organization_id: 'acme', project_id: 'shop', temporary: false }), }; const result = await runDoctor(doctorIo(files, () => 200)); assert.equal(result.ok, true, JSON.stringify(result.checks)); const text = formatDoctor(result) + JSON.stringify(result); assert.ok(!text.includes(ANON) && !text.includes(SERVICE), 'no key values'); assert.match(formatDoctor(result), /No problems found/); }); it('prints one fix per problem: missing key, leaked secret, not ignored, refused key', async () => { const files = { [`${ROOT}/package.json`]: JSON.stringify({ devDependencies: { vite: '6' } }), [`${ROOT}/.env.local`]: `VITE_SUPABASE_URL=https://x.scribase.app\nVITE_SUPABASE_ANON_KEY=${ANON}\nVITE_ADMIN_KEY=${SERVICE}\n`, }; const result = await runDoctor(doctorIo(files, (url) => (url.endsWith('/rest/v1/') ? 401 : 200))); assert.equal(result.ok, false); const problems = result.checks.filter((check) => check.status === 'problem'); assert.deepEqual(problems.map((check) => check.id).sort(), ['gitignore', 'reach_rest', 'secret_exposure']); assert.ok(problems.every((check) => typeof check.fix === 'string' && check.fix.length > 0)); assert.match(problems.find((check) => check.id === 'secret_exposure')?.detail ?? '', /VITE_ADMIN_KEY/); }); it('reports a missing env file, an unreachable host and a temporary project close to expiry', async () => { const now = 1_800_000_000_000; const missing = await runDoctor(doctorIo({ [`${ROOT}/package.json`]: '{}' }, () => 200, now)); assert.equal(missing.checks.find((check) => check.id === 'env_file')?.status, 'problem'); const files = { [`${ROOT}/.env`]: `SUPABASE_URL=https://x.scribase.app\nSUPABASE_ANON_KEY=${ANON}\n`, [`${ROOT}/.gitignore`]: '.env*\n', [`${ROOT}/.scribase/project.json`]: JSON.stringify({ temporary: true, expires_at: now / 1000 + 3600, claim_url: 'https://c/claim/x#t' }), }; const result = await runDoctor(doctorIo(files, () => new Error('getaddrinfo ENOTFOUND'), now)); const byId = new Map(result.checks.map((check) => [check.id, check])); assert.equal(byId.get('reach_auth')?.status, 'problem'); assert.equal(byId.get('temporary_expiry')?.status, 'warning'); assert.match(byId.get('temporary_expiry')?.detail ?? '', /1 h 0 min/); assert.equal(byId.get('agent_token')?.status, 'warning'); }); it('reads roles and env entries', () => { assert.equal(jwtRole(SERVICE), 'service_role'); assert.equal(jwtRole('nope'), null); const entries = envEntries(`A=1\nexport NEXT_PUBLIC_X="${SERVICE}"\n# c\n`); assert.equal(entries.get('A'), '1'); assert.deepEqual(leakedSecretVars(entries, undefined), ['NEXT_PUBLIC_X']); }); });