scribase-cli/tests/add.test.ts
caelum0x 92f7df83c4 scribase CLI + TypeScript SDK (public edge repo)
Extracted from the private caelum0x/scribase monorepo's
packages/scribase-js with a fresh, single-commit history (no core
history leaks). The npx scribase CLI and the typed /v1 API client,
unchanged except: prepublishOnly simplified (the monorepo-only tarball
gitleaks gate dropped), repository/homepage/bugs fields added, and one
test that cross-checked embedded template strings against the
monorepo's templates/ directory removed (nothing it tested changed;
that directory isn't shipped here).
2026-11-12 18:10:58 +03:00

222 lines
10 KiB
TypeScript

/**
* Tests for `npx scribase add` (SP-D1): argument parsing, the add request,
* the connect-link wait, proof output, and that no secret ever reaches stdout
* or the env file (no network, in-memory files).
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { addMain, formatAdd, parseAddArgs, runAdd } from '../src/cli/add.js';
import type { AddIo } from '../src/cli/add.js';
import { isSecretEnv, publicEnvOnly } from '../src/cli/envfile.js';
import { InitError } from '../src/cli/init.js';
const ROOT = '/work/app';
const TOKEN = 'scb_agt_live_token_value_never_printed';
const SECRET_KEY = 'sb_secret_abcdefghijklmnop';
const STATE = JSON.stringify({
organization_id: 'acme',
project_id: 'shop',
environment_id: 'production',
api_url: 'https://api.example.test',
});
interface Call {
method: string;
url: string;
auth: string | null;
body: unknown;
}
function harness(answers: { status: number; body: unknown }[], files: Record<string, string> = {}) {
const calls: Call[] = [];
const logs: string[] = [];
const opened: string[] = [];
const written: Record<string, string> = {};
let clock = 1_700_000_000_000;
const store: Record<string, string> = { [`${ROOT}/.scribase/project.json`]: STATE, ...files };
const io: AddIo = {
cwd: ROOT,
env: {},
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
calls.push({
method: init?.method ?? 'GET',
url: String(url),
auth: new Headers(init?.headers).get('authorization'),
body: init?.body ? JSON.parse(String(init.body)) : undefined,
});
const answer = answers.shift() ?? { status: 500, body: { code: 'no_answer', detail: 'test ran out of answers' } };
return new Response(JSON.stringify(answer.body), { status: answer.status });
}) as typeof fetch,
readFile: (path) => store[path] ?? null,
writeFile: (path, contents) => {
store[path] = contents;
written[path] = contents;
},
credentials: () => ({ token: TOKEN }),
sleep: async (ms) => {
clock += ms;
},
now: () => clock,
log: (line) => logs.push(line),
openBrowser: (url) => opened.push(url),
};
return { io, calls, logs, opened, written, store };
}
const LIVE = {
slot: 'email',
title: 'Email',
status: 'live',
state: 'live',
live: true,
configured: true,
provider: 'scribase',
proof: { kind: 'email_sent', id: '42', at: 1_700_000_001, detail: 'a***@example.com' },
connect_url: null,
next: null,
env: {},
sent: true,
};
const CONNECT_URL = 'https://console.example.test/connect/email?org=acme&project=shop&env=production';
describe('scribase add', () => {
it('parses a slot and flags, and refuses bad input', () => {
const options = parseAddArgs(['email', '--own', '--json', '--wait', '30', '--no-browser']);
assert.equal(options.slot, 'email');
assert.equal(options.own, true);
assert.equal(options.json, true);
assert.equal(options.waitSeconds, 30);
assert.equal(options.browser, false);
assert.equal(parseAddArgs(['--list']).list, true);
assert.throws(() => parseAddArgs([]), InitError);
assert.throws(() => parseAddArgs(['Email!']), InitError);
assert.throws(() => parseAddArgs(['email', '--wait', '0']), InitError);
assert.throws(() => parseAddArgs(['email', '--password', 'x']), InitError);
});
it('adds email and prints the proof, never the token', async () => {
const { io, calls } = harness([{ status: 200, body: LIVE }]);
const out: string[] = [];
const code = await addMain(['email', '--json'], io, (text) => out.push(text));
assert.equal(code, 0);
assert.equal(calls.length, 1);
assert.equal(calls[0]?.method, 'POST');
assert.equal(calls[0]?.url, 'https://api.example.test/v1/organizations/acme/projects/shop/environments/production/capabilities/email');
assert.equal(calls[0]?.auth, `Bearer ${TOKEN}`);
assert.deepEqual(calls[0]?.body, {});
const result = JSON.parse(out.join('')) as { live: boolean; proof: { kind: string; id: string; at: number } };
assert.equal(result.live, true);
assert.deepEqual([result.proof.kind, result.proof.id, result.proof.at], ['email_sent', '42', 1_700_000_001]);
assert.ok(!out.join('').includes(TOKEN));
});
it('with --own opens the connect link, waits for a fresh proof, and prints no secret', async () => {
const needsConnect = { ...LIVE, state: 'needs_connect', live: false, provider: null, proof: null, connect_url: CONNECT_URL, sent: false };
const stale = { ...LIVE, proof: { ...LIVE.proof, at: 1_600_000_000 } };
const fresh = { ...LIVE, provider: 'own', proof: { ...LIVE.proof, id: '43', at: 1_700_000_010 } };
const { io, calls, logs, opened } = harness([
{ status: 200, body: needsConnect },
{ status: 200, body: needsConnect },
{ status: 200, body: stale },
{ status: 200, body: fresh },
]);
const out: string[] = [];
const code = await addMain(['email', '--own'], io, (text) => out.push(text));
assert.equal(code, 0);
assert.deepEqual(calls[0]?.body, { provider: 'own' });
assert.deepEqual(opened, [CONNECT_URL]);
assert.equal(calls.filter((call) => call.method === 'GET').length, 3);
const printed = `${logs.join('\n')}\n${out.join('')}`;
assert.match(printed, /email_sent #43/);
assert.match(printed, /your mail server/);
for (const secret of [TOKEN, 'smtp_pass', 'password']) assert.ok(!printed.includes(secret), secret);
});
it('with --no-wait prints the link and exits 3', async () => {
const needsConnect = { ...LIVE, state: 'needs_connect', live: false, provider: null, proof: null, connect_url: CONNECT_URL, sent: false };
const { io } = harness([{ status: 200, body: needsConnect }]);
const out: string[] = [];
assert.equal(await addMain(['email', '--own', '--no-wait', '--no-browser', '--json'], io, (text) => out.push(text)), 3);
const result = JSON.parse(out.join('')) as { status: string; connect_url: string };
assert.equal(result.status, 'needs_connect');
assert.equal(result.connect_url, CONNECT_URL);
});
it('times out with a next step when no proof arrives', async () => {
const needsConnect = { ...LIVE, state: 'needs_connect', live: false, provider: null, proof: null, connect_url: CONNECT_URL, sent: false };
const { io } = harness(Array.from({ length: 50 }, () => ({ status: 200, body: needsConnect })));
await assert.rejects(
runAdd({ ...parseAddArgs(['email', '--own', '--no-browser']), waitSeconds: 6 }, io),
(error: unknown) => error instanceof InitError && error.code === 'connect_timeout',
);
});
it('writes public env values only, and refuses secrets by name', async () => {
const body = { ...LIVE, env: { PUBLIC_DSN_HOST: 'errors.example.test', SERVICE_SECRET: SECRET_KEY, OTHER: SECRET_KEY } };
const { io, written } = harness([{ status: 200, body }], { [`${ROOT}/.env.local`]: 'EXISTING=1\n' });
const out: string[] = [];
await addMain(['email'], io, (text) => out.push(text));
const file = written[`${ROOT}/.env.local`] ?? '';
assert.match(file, /EXISTING=1/);
assert.match(file, /PUBLIC_DSN_HOST=errors.example.test/);
assert.ok(!file.includes(SECRET_KEY));
const printed = out.join('');
assert.match(printed, /refused \(secret\): SERVICE_SECRET, OTHER/);
assert.ok(!printed.includes(SECRET_KEY));
});
it('reports server refusals with a next step', async () => {
const { io } = harness([{ status: 409, body: { code: 'capability_arriving', detail: 'S3 protocol for Storage is arriving' } }]);
const out: string[] = [];
assert.equal(await addMain(['storage-s3', '--json'], io, (text) => out.push(text)), 1);
const failure = JSON.parse(out.join('')) as { ok: boolean; error: { code: string; next: string } };
assert.equal(failure.error.code, 'capability_arriving');
assert.match(failure.error.next, /--list/);
});
it('lists the registry without a token', async () => {
const { io, calls } = harness([
{ status: 200, body: { capabilities: [{ slot: 'email', title: 'Email', summary: 'Auth email.', status: 'live', compat: ['17-capabilities:email add'] }] } },
]);
const result = await runAdd(parseAddArgs(['--list']), io);
assert.equal(calls[0]?.auth, null);
assert.equal(calls[0]?.url, 'https://api.example.test/v1/capabilities');
assert.match(formatAdd(result), /email\s+Live/);
});
it('needs a connected folder and a token', async () => {
const { io } = harness([]);
await assert.rejects(runAdd(parseAddArgs(['email']), { ...io, readFile: () => null }), (error: unknown) => error instanceof InitError && error.code === 'not_initialized');
await assert.rejects(runAdd(parseAddArgs(['email']), { ...io, credentials: () => ({}) }), (error: unknown) => error instanceof InitError && error.code === 'not_signed_in');
});
});
describe('secret guard', () => {
it('flags secret names and secret-shaped values', () => {
assert.equal(isSecretEnv('SMTP_PASS', 'x'), true);
assert.equal(isSecretEnv('SUPABASE_SERVICE_ROLE_KEY', 'x'), true);
assert.equal(isSecretEnv('ANYTHING', SECRET_KEY), true);
assert.equal(isSecretEnv('ANYTHING', TOKEN), true);
assert.equal(isSecretEnv('DATABASE_URL', 'postgres://user:pw@host/db'), true);
const serviceJwt = `eyJhbGciOiJIUzI1NiJ9.${Buffer.from(JSON.stringify({ role: 'service_role' })).toString('base64url')}.sig`;
const anonJwt = `eyJhbGciOiJIUzI1NiJ9.${Buffer.from(JSON.stringify({ role: 'anon' })).toString('base64url')}.sig`;
assert.equal(isSecretEnv('X', serviceJwt), true);
assert.equal(isSecretEnv('NEXT_PUBLIC_SUPABASE_ANON_KEY', anonJwt), false);
assert.equal(isSecretEnv('NEXT_PUBLIC_SUPABASE_URL', 'https://x.scribase.app'), false);
assert.deepEqual(publicEnvOnly({ A: 'https://x', B: SECRET_KEY }), { safe: { A: 'https://x' }, refused: ['B'] });
});
});
describe('command aliases (PS2.0, P-Y4)', () => {
it('`scribase deploy` runs `scribase add deploy` with its options', async () => {
const { expandAlias } = await import('../src/cli/aliases.js');
assert.deepEqual(expandAlias(['deploy']), ['add', 'deploy']);
assert.deepEqual(expandAlias(['deploy', '--json', '--no-wait']), ['add', 'deploy', '--json', '--no-wait']);
assert.deepEqual(expandAlias(['add', 'email']), ['add', 'email']);
assert.deepEqual(expandAlias([]), []);
});
});