import { execFileSync } from 'node:child_process'; import { existsSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { describe, expect, it } from 'vitest'; /** * The reason the homegrown JWT existed was the guarantee that the identical * code runs in the CommonJS api and the ESM collab server (ADR 0020). With * `jose` that property must be PROVEN, not assumed — jose v6 is ESM-only * and reaches CJS via Node's `require(esm)`. This test loads the actually * built dist artefacts (what api and collab load at runtime) in child * processes of both module systems and round-trips a token in each * direction. Requires a current `pnpm --filter @dorfteich/shared build` * (CI builds before testing). */ const here = path.dirname(fileURLToPath(import.meta.url)); const distCjs = path.resolve(here, '../dist/token-crypto.js'); const distEsm = path.resolve(here, '../dist/token-crypto.mjs'); const secret = 'cross-runtime-secret-32-characters'; const claims = { userId: 'user-x', pageId: 'page-x', mode: 'rw' } as const; function run(args: string[], extraEnv: Record): string { return execFileSync(process.execPath, args, { cwd: path.resolve(here, '..'), env: { ...process.env, SECRET: secret, ...extraEnv }, encoding: 'utf8', }); } const signCjs = `require(process.env.DIST).signCollabToken(JSON.parse(process.env.CLAIMS), process.env.SECRET, 60).then((t) => process.stdout.write(t));`; const verifyCjs = `require(process.env.DIST).verifyCollabToken(process.env.TOKEN, process.env.SECRET).then((r) => process.stdout.write(JSON.stringify(r)));`; const signEsm = `const m = await import(process.env.DIST_URL); process.stdout.write(await m.signCollabToken(JSON.parse(process.env.CLAIMS), process.env.SECRET, 60));`; const verifyEsm = `const m = await import(process.env.DIST_URL); process.stdout.write(JSON.stringify(await m.verifyCollabToken(process.env.TOKEN, process.env.SECRET)));`; describe('token crypto across module systems (built dist)', () => { it('has a built dist to test against', () => { for (const file of [distCjs, distEsm]) { if (!existsSync(file)) { throw new Error(`${file} missing — run \`pnpm --filter @dorfteich/shared build\` first`); } } }); it('verifies a CommonJS-signed token in an ESM runtime', () => { const token = run(['-e', signCjs], { DIST: distCjs, CLAIMS: JSON.stringify(claims) }); expect(token.split('.')).toHaveLength(3); const result = run(['--input-type=module', '-e', verifyEsm], { DIST_URL: pathToFileURL(distEsm).href, TOKEN: token, }); expect(JSON.parse(result)).toEqual({ valid: true, claims }); }); it('verifies an ESM-signed token in a CommonJS runtime', () => { const token = run(['--input-type=module', '-e', signEsm], { DIST_URL: pathToFileURL(distEsm).href, CLAIMS: JSON.stringify(claims), }); expect(token.split('.')).toHaveLength(3); const result = run(['-e', verifyCjs], { DIST: distCjs, TOKEN: token }); expect(JSON.parse(result)).toEqual({ valid: true, claims }); }); });