/** * SAUTH-01..09 — `superadmin.auth` (catalogue §8.1). * * `login` is `publicProcedure`; `me` is `superadminProcedure`, which rejects * anonymous, staff and user tokens. A superadmin token is not trusted on its * claims alone: `createContext` re-reads the `superadmins` row by id, so a token * for a removed id no longer resolves (SAUTH-09). */ import fs from 'node:fs' import path from 'node:path' import crypto from 'node:crypto' import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api' import { anonClient, staffSession, superadminClient, superadminSession, userSession, } from '../helpers/sessions' import { superadminCredentials } from '../helpers/env' jest.setTimeout(180_000) /* -------------------------------------------------------------------------- */ /* JWT helpers — the dev secret lives in wrangler.dev.toml */ /* -------------------------------------------------------------------------- */ function jwtSecret(): string { const toml = fs.readFileSync(path.resolve(__dirname, '../../wrangler.dev.toml'), 'utf8') const match = toml.match(/JWT_SECRET\s*=\s*"([^"]+)"/) if (!match) throw new Error('[api-tests] JWT_SECRET not found in wrangler.dev.toml') return match[1] } /** Sign an HS256 JWT with node:crypto (avoids loading jose's ESM build). */ function signToken(payload: Record, secret: string, expiresAtEpoch: number): string { const b64url = (value: Buffer | string) => Buffer.from(value).toString('base64url') const header = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' })) const body = b64url(JSON.stringify({ ...payload, exp: expiresAtEpoch })) const data = `${header}.${body}` const signature = crypto.createHmac('sha256', secret).update(data).digest('base64url') return `${data}.${signature}` } /** Decode (without verifying) a JWT payload. */ function decodeJwt(token: string): Record { const [, payload] = token.split('.') return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) } describe('superadmin.auth.login (SAUTH-01..04)', () => { it('SAUTH-01: valid username/password returns a token + superadmin id/username', async () => { const { username, password } = superadminCredentials() const res: any = await apiClient().superadmin.auth.login.mutate({ username, password }) expect(res.message).toEqual('Login successful') expect(res.token).toEqual(expect.any(String)) expect(res.token.length).toBeGreaterThan(20) expect(res.superadmin).toEqual( expect.objectContaining({ id: expect.any(Number), username }) ) expect(res.superadmin.id).toBeGreaterThan(0) }) it('SAUTH-02: an unknown username is 401 invalid credentials', async () => { await expectTrpcError( () => apiClient().superadmin.auth.login.mutate({ username: `nobody-${uniqueSuffix()}`, password: 'whatever-password', }), 'UNAUTHORIZED', 'invalid credentials' ) }) it('SAUTH-03: a wrong password is 401 invalid credentials', async () => { const { username } = superadminCredentials() await expectTrpcError( () => apiClient().superadmin.auth.login.mutate({ username, password: 'definitely-wrong' }), 'UNAUTHORIZED', 'invalid credentials' ) }) it('SAUTH-04: empty username/password is 400 BAD_REQUEST', async () => { await expectTrpcError( () => apiClient().superadmin.auth.login.mutate({ username: '', password: '' }), 'BAD_REQUEST' ) // Missing keys are rejected by the zod schema as well. await expectTrpcError( () => apiClient().superadmin.auth.login.mutate({ username: '' } as any), 'BAD_REQUEST' ) await expectTrpcError( () => apiClient().superadmin.auth.login.mutate({} as any), 'BAD_REQUEST' ) }) }) describe('superadmin.auth.me (SAUTH-05..09)', () => { it('SAUTH-05: me returns the superadmin identity', async () => { const session = await superadminSession() const me: any = await (await superadminClient()).superadmin.auth.me.query() expect(me.superadmin).toEqual( expect.objectContaining({ id: session.superadminId, username: session.username }) ) }) it('SAUTH-06: me without a token is 401', async () => { await expectTrpcError(() => anonClient().superadmin.auth.me.query(), 'UNAUTHORIZED') }) it('SAUTH-07: a staff or user token is 401 on me', async () => { const staff = await staffSession() const user = await userSession() await expectTrpcError(() => apiClient(staff.token).superadmin.auth.me.query(), 'UNAUTHORIZED') await expectTrpcError(() => apiClient(user.token).superadmin.auth.me.query(), 'UNAUTHORIZED') }) it('SAUTH-08: the login token carries superadminId/identityType claims and resolves to that id', async () => { const session = await superadminSession() const claims = decodeJwt(session.token) expect(claims.identityType).toBe('superadmin') expect(Number(claims.superadminId)).toBe(session.superadminId) expect(claims.username).toBe(session.username) expect(Number(claims.exp)).toBeGreaterThan(Math.floor(Date.now() / 1000)) const me: any = await (await superadminClient()).superadmin.auth.me.query() expect(me.superadmin.id).toBe(session.superadminId) }) it('(current) SAUTH-09: a token for a removed superadmin id no longer resolves (401)', async () => { // There is no superadmin suspension/removal API; the reachable contract is // that identity is re-read from D1. A correctly-signed token whose // superadminId does not exist resolves to no superadmin -> 401. const missingId = 987_654_321 const future = Math.floor(Date.now() / 1000) + 3_600 const token = signToken( { identityType: 'superadmin', superadminId: missingId, username: 'ghost' }, jwtSecret(), future ) await expectTrpcError(() => apiClient(token).superadmin.auth.me.query(), 'UNAUTHORIZED') // Positive control: the same signing routine with the seeded id resolves. const session = await superadminSession() const live = signToken( { identityType: 'superadmin', superadminId: session.superadminId, username: session.username }, jwtSecret(), future ) const me: any = await apiClient(live).superadmin.auth.me.query() expect(me.superadmin.id).toBe(session.superadminId) }) })