feat(web): personal agent tokens, their management routes and the pilot (#200)

An AI assistant will reach an account through a personal token created by a
user signed in on the site. This commit issues, verifies and revokes those
tokens, and adds the pilot switch. The MCP route (#202) and the page (#205)
come later in the stack.

- origin.ts: the list of allowed origins, moved as is from ws.ts, and
  isAllowedOrigin(). ws.ts imports it; no origin check reads request.url,
  whose origin is the container's in production.
- accountLock.ts: lockAccount(tx, userId), a transaction advisory lock per
  account.
- agentAccess.ts: mcpAllowed() reads MCP_ALLOWED_SUBS at every call (absent
  or empty: nobody; `*`: everyone; else a comma-separated list).
  requireAssistantsSession() guards the management routes: any Authorization
  header answers 401 first, then 401 without a site session, then 404 outside
  the pilot.
- agentTokens.ts: slmcp_ + 43 base64url characters; only the SHA-256 and the
  last four characters are stored. Ten tokens per account, counted under the
  account lock; expiry of 90 days, one year (same UTC day) or never;
  verifyAgentToken() accepts the exact Bearer shape only, refuses an expired
  token and writes last_used_at at most once per minute.
- GET and POST /api/agent-tokens, DELETE /api/agent-tokens/[id]: guard, rate
  limit, Origin on writes (403), body, action. Only the 201 of the POST
  carries the token; the eleventh token answers 409 token_limit.
- requireAuth() answers 401 to a Bearer that starts with slmcp_, before any
  call to Logto.
- .env.template: MCP_ALLOWED_SUBS, empty.

Tests: the real requireAuth with next/headers replaced and fetch spied, the
real /api/sync route with an agent token, the three routes on PGlite (two
accounts, cap, Origin with a request URL on the container's host, any
Authorization header, pilot, what the responses and the columns hold), the
token and pilot modules, the shared origin list and the WebSocket upgrade.

Resolves #200

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-15 00:12:28 -05:00
commit 45595eaee3
16 changed files with 2037 additions and 12 deletions

View file

@ -6,3 +6,9 @@ LOGTO_APP_ID=
LOGTO_APP_SECRET=
LOGTO_COOKIE_SECRET=
LOGTO_BASE_URL=https://liste.lacompagniemaximus.com
# AI assistants (MCP): accounts allowed to use the MCP server and the
# "AI assistants" page, as Logto `sub` values. Empty: nobody. A list
# separated by commas: those accounts only. `*`: every account.
# Emptying it is the emergency switch. No `sub` is ever written in the repo.
MCP_ALLOWED_SUBS=

View file

@ -0,0 +1,30 @@
import { NextResponse } from 'next/server';
import { requireAssistantsSession } from '@/lib/agentAccess';
import { revokeAgentToken } from '@/lib/agentTokens';
import { isAllowedOrigin } from '@/lib/origin';
import { rateLimit } from '@/lib/rateLimit';
// Revoke an agent token of the signed-in account (#200). Same guard and same
// order as POST /api/agent-tokens: session of the site, rate limit, Origin.
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAssistantsSession();
if (auth.error) return auth.error;
const rl = rateLimit(auth.userId, 'create');
if (rl) return rl;
if (!isAllowedOrigin(request.headers.get('origin'))) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { id } = await params;
// An id of another account answers like an unknown one.
if (!(await revokeAgentToken(auth.userId, id))) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,693 @@
import fs from 'node:fs';
import path from 'node:path';
import { inspect } from 'node:util';
import { createHash, randomUUID as u } from 'node:crypto';
import { describe, it, expect, beforeAll, beforeEach, afterEach, afterAll, vi } from 'vitest';
import type { PGlite } from 'electric-sql-pglite';
// Management routes of the agent tokens (#200): the real GET and POST
// /api/agent-tokens and DELETE /api/agent-tokens/[id], against an in-memory
// Postgres (PGlite) with the companion migrations. The real guard
// (requireAssistantsSession), the real pilot, the real Origin check, the real
// parseBody and the real schema run. Three modules are replaced:
// - the Logto session helper gives the account of the test;
// - headers() of next/headers gives the headers of the test request
// (it throws outside a request);
// - the rate limiter records its calls and refuses on demand.
// Every request is built with the container's host in its URL, as in
// production, unless a test says otherwise.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
return {
pg: new PGlite() as PGlite,
session: null as { userId: string } | null,
headers: new Headers(),
limits: [] as [userId: string, category: string][],
limited: false,
};
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => h.session }));
vi.mock('next/headers', () => ({ headers: async () => h.headers }));
vi.mock('@/lib/rateLimit', () => ({
rateLimit: (userId: string, category: string) => {
h.limits.push([userId, category]);
return h.limited ? Response.json({ error: 'Too many requests' }, { status: 429 }) : null;
},
}));
const { GET, POST } = await import('./route');
const { DELETE } = await import('./[id]/route');
const { verifyAgentToken } = await import('@/lib/agentTokens');
const SITE = 'https://liste.lacompagniemaximus.com';
// Origin of `request.url` in production: the container's, not the site's.
const CONTAINER = 'http://0.0.0.0:3000';
const TOKEN = /^slmcp_[A-Za-z0-9_-]{43}$/;
const DAY_MS = 24 * 60 * 60 * 1000;
const VALID = { name: 'Hermes', scope: 'read', duration: '90d' };
const NOT_FOUND = { status: 404, json: { error: 'Not found' } };
const UNAUTHORIZED = { status: 401, json: { error: 'Unauthorized' } };
const FORBIDDEN = { status: 403, json: { error: 'Forbidden' } };
// Authorization headers the routes refuse whatever they hold: a Logto access
// token (the mobile app's), a well-formed agent token, another scheme.
const AUTHORIZATIONS: [label: string, value: string][] = [
['a Logto access token', 'Bearer logto-access-token-of-the-test'],
['a well-formed agent token', `Bearer slmcp_${'A'.repeat(43)}`],
['another scheme', 'Basic not-a-credential'],
];
// Origins a write refuses, each with the host the request is sent to.
const ORIGINS: [label: string, origin: string | null, host: string][] = [
['no Origin header', null, CONTAINER],
['no Origin header on a request sent to the site itself', null, SITE],
['a foreign Origin', 'https://evil.example', CONTAINER],
['the Origin `null`', 'null', CONTAINER],
['an Origin equal to the host of the request, which is not the site', CONTAINER, CONTAINER],
['a foreign Origin equal to the host of the request', 'https://evil.example', 'https://evil.example'],
];
type Json = Record<string, unknown>;
type Send = {
// Origin header. Default: the site. null: no header.
origin?: string | null;
// Authorization header. Default: none.
authorization?: string;
// Origin of the request URL. Default: the container's.
host?: string;
};
type Answer = { status: number; text: string; json: unknown; headers: Headers };
type Created = {
token: string;
id: string;
name: string;
scope: string;
hint: string;
createdAt: string;
expiresAt: string | null;
answer: Answer;
};
// A row of sl_agent_tokens as the database holds it.
type Row = {
id: string;
user_id: string;
name: string;
token_hash: string;
hint: string;
scope: string;
created_at: Date;
last_used_at: Date | null;
expires_at: Date | null;
};
// What the current test created and received: read by scan().
const seen = {
users: [] as string[],
tokens: new Map<string, Answer>(),
answers: [] as Answer[],
};
const CONSOLE = ['log', 'info', 'warn', 'error', 'debug'] as const;
let consoleSpies: { mock: { calls: unknown[][] }; mockRestore(): void }[] = [];
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');
const secretOf = (token: string) => token.slice('slmcp_'.length);
const initialPilot = process.env.MCP_ALLOWED_SUBS;
function pilot(value: string | undefined) {
if (value === undefined) delete process.env.MCP_ALLOWED_SUBS;
else process.env.MCP_ALLOWED_SUBS = value;
}
// Each test creates its own accounts (#148): no test reads or writes the rows
// of another, so the file passes in any order (vitest runs it shuffled).
// Invented ids: no real `sub` in the repository.
function newAccount(): string {
const userId = `user-${u()}`;
seen.users.push(userId);
return userId;
}
// The request of a session (`userId`, null without one), and the headers that
// next/headers gives the guard: the same object.
function request(userId: string | null, method: string, pathname: string, send: Send = {}, body?: unknown): Request {
const { origin = SITE, authorization, host = CONTAINER } = send;
h.session = userId === null ? null : { userId };
const headers = new Headers();
if (origin !== null) headers.set('origin', origin);
if (authorization !== undefined) headers.set('authorization', authorization);
h.headers = headers;
return new Request(`${host}${pathname}`, {
method,
headers,
body: body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body),
});
}
async function answer(res: Response): Promise<Answer> {
const text = await res.text();
const a = { status: res.status, text, json: text === '' ? null : JSON.parse(text) as unknown, headers: res.headers };
seen.answers.push(a);
return a;
}
async function list(userId: string | null, send?: Send): Promise<Answer> {
request(userId, 'GET', '/api/agent-tokens', send);
return answer(await GET());
}
async function post(userId: string | null, body: unknown = VALID, send?: Send): Promise<Answer> {
return answer(await POST(request(userId, 'POST', '/api/agent-tokens', send, body)));
}
async function del(userId: string | null, id: string, send?: Send): Promise<Answer> {
return answer(await DELETE(
request(userId, 'DELETE', `/api/agent-tokens/${id}`, send),
{ params: Promise.resolve({ id }) },
));
}
// A token created through the route by the session of `userId`.
async function create(userId: string, fields: Json = {}): Promise<Created> {
const a = await post(userId, { ...VALID, ...fields });
expect(a.status).toBe(201);
const body = a.json as Omit<Created, 'answer'>;
seen.tokens.set(body.token, a);
return { ...body, answer: a };
}
// A token row written straight to the table: no value was ever issued for it.
async function seedToken(userId: string, fields: { expiresAt?: string } = {}): Promise<string> {
const id = u();
await h.pg.query(
'insert into sl_agent_tokens (id, user_id, name, token_hash, hint, scope, expires_at) values ($1, $2, $3, $4, $5, $6, $7)',
[id, userId, 'Seeded', sha256(u()), 'seed', 'read', fields.expiresAt ?? null],
);
return id;
}
async function rowsOf(userId: string): Promise<Row[]> {
return (await h.pg.query<Row>('select * from sl_agent_tokens where user_id = $1 order by created_at, id', [userId])).rows;
}
async function rowOf(id: string): Promise<Row | undefined> {
return (await h.pg.query<Row>('select * from sl_agent_tokens where id = $1', [id])).rows[0];
}
// What no response and no log line may carry, read on everything the current
// test received: the account, the hash of a token, and the value of a token
// anywhere but in the response of the POST that created it.
function scan() {
for (const a of seen.answers) {
for (const userId of seen.users) expect(a.text).not.toContain(userId);
for (const [token, creation] of seen.tokens) {
expect(a.text).not.toContain(sha256(token));
if (a === creation) continue;
expect(a.text).not.toContain(token);
expect(a.text).not.toContain(secretOf(token));
}
}
const logged = consoleSpies
.flatMap((spy) => spy.mock.calls.flat())
.map((value) => (typeof value === 'string' ? value : inspect(value, { depth: 6 })))
.join('\n');
for (const token of seen.tokens.keys()) expect(logged).not.toContain(secretOf(token));
}
beforeAll(async () => {
const dir = path.join(__dirname, '../../../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await h.pg.exec(stmt);
}
}
});
beforeEach(() => {
pilot('*');
h.session = null;
h.headers = new Headers();
h.limits = [];
h.limited = false;
seen.users = [];
seen.tokens = new Map();
seen.answers = [];
consoleSpies = CONSOLE.map((method) => vi.spyOn(console, method));
});
// Every test ends on the scan: no response of the file leaks, whatever it tests.
afterEach(() => {
try {
scan();
} finally {
for (const spy of consoleSpies) spy.mockRestore();
}
});
afterAll(() => pilot(initialPilot));
describe('POST /api/agent-tokens', () => {
it('creates a token: 201 with its value, and a row that holds its hash', async () => {
const A = newAccount();
const created = await create(A, { name: 'Hermes', scope: 'write', duration: '1y' });
const { answer: a, ...body } = created;
expect(Object.keys(body).sort()).toEqual(['createdAt', 'expiresAt', 'hint', 'id', 'name', 'scope', 'token']);
expect(body.token).toMatch(TOKEN);
expect(body).toMatchObject({ name: 'Hermes', scope: 'write', hint: body.token.slice(-4) });
expect(a.headers.get('cache-control')).toBe('no-store');
const rows = await rowsOf(A);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
id: body.id,
user_id: A,
name: 'Hermes',
token_hash: sha256(body.token),
hint: body.token.slice(-4),
scope: 'write',
last_used_at: null,
});
expect(rows[0].created_at.toISOString()).toBe(body.createdAt);
expect(rows[0].expires_at?.toISOString()).toBe(body.expiresAt);
expect(Math.abs(Date.now() - Date.parse(body.createdAt))).toBeLessThan(60_000);
// 1y: the same day of the next year, in UTC.
const nextYear = new Date(body.createdAt);
nextYear.setUTCFullYear(nextYear.getUTCFullYear() + 1);
expect(body.expiresAt).toBe(nextYear.toISOString());
expect(h.limits).toEqual([[A, 'create']]);
// The value opens the account it was created for.
expect(await verifyAgentToken(`Bearer ${body.token}`)).toEqual({
userId: A, tokenId: body.id, tokenName: 'Hermes', scope: 'write',
});
});
it('90d expires 90 days after the creation, never does not expire', async () => {
const A = newAccount();
const ninety = await create(A, { duration: '90d' });
expect(Date.parse(ninety.expiresAt!) - Date.parse(ninety.createdAt)).toBe(90 * DAY_MS);
const never = await create(A, { duration: 'never' });
expect(never.expiresAt).toBeNull();
expect((await rowOf(never.id))?.expires_at).toBeNull();
});
it('trims the name, and accepts 100 characters', async () => {
const A = newAccount();
const long = 'x'.repeat(100);
const created = await create(A, { name: ` ${long}\t` });
expect(created.name).toBe(long);
expect((await rowOf(created.id))?.name).toBe(long);
});
it('accepts two tokens with the same name', async () => {
const A = newAccount();
const [first, second] = [await create(A, { name: 'Hermes' }), await create(A, { name: 'Hermes' })];
expect(first.token).not.toBe(second.token);
expect(await rowsOf(A)).toHaveLength(2);
});
// The Origin is read against the list of origin.ts, never against the URL
// of the request: in production that URL carries the container's host.
it('accepts the Origin of the site on a request whose URL carries another host', async () => {
const A = newAccount();
const a = await post(A, VALID, { origin: SITE, host: CONTAINER });
expect(a.status).toBe(201);
seen.tokens.set((a.json as Created).token, a);
expect(await rowsOf(A)).toHaveLength(1);
});
it('accepts the Origin of the local dev server', async () => {
const A = newAccount();
const a = await post(A, VALID, { origin: 'http://localhost:3000', host: 'http://localhost:3000' });
expect(a.status).toBe(201);
seen.tokens.set((a.json as Created).token, a);
});
it.each(ORIGINS)('answers 403 to %s, and writes nothing', async (_label, origin, host) => {
const A = newAccount();
expect(await post(A, VALID, { origin, host })).toMatchObject(FORBIDDEN);
expect(await rowsOf(A)).toEqual([]);
});
it.each(AUTHORIZATIONS)('answers 401 to %s in an Authorization header, and writes nothing', async (_label, authorization) => {
const A = newAccount();
expect(await post(A, VALID, { authorization })).toMatchObject(UNAUTHORIZED);
expect(await rowsOf(A)).toEqual([]);
expect(h.limits).toEqual([]);
});
it('answers 401 to a live agent token of the account: a token cannot create another', async () => {
const A = newAccount();
const { token } = await create(A, { scope: 'write', duration: 'never' });
const authorization = `Bearer ${token}`;
// With the session of the site, and without it.
expect(await post(A, VALID, { authorization })).toMatchObject(UNAUTHORIZED);
expect(await post(null, VALID, { authorization })).toMatchObject(UNAUTHORIZED);
expect(await rowsOf(A)).toHaveLength(1);
});
it('answers 401 without a session', async () => {
expect(await post(null)).toMatchObject(UNAUTHORIZED);
expect(h.limits).toEqual([]);
});
it('refuses the eleventh token with 409 token_limit, expired ones counted', async () => {
const [A, B] = [newAccount(), newAccount()];
// One token that expired long ago, then nine created through the route.
const expired = await seedToken(A, { expiresAt: '2020-01-01T00:00:00.000Z' });
for (let i = 0; i < 9; i++) await create(A);
expect(await rowsOf(A)).toHaveLength(10);
const refused = await post(A);
expect(refused.status).toBe(409);
expect(refused.json).toEqual({ error: 'token_limit' });
expect(await rowsOf(A)).toHaveLength(10);
// The cap is per account.
await create(B);
expect(await rowsOf(B)).toHaveLength(1);
// Revoking one, even expired, leaves room for another.
expect((await del(A, expired)).status).toBe(200);
await create(A);
expect(await rowsOf(A)).toHaveLength(10);
expect((await post(A)).status).toBe(409);
});
it.each([
['no name', { scope: 'read', duration: '90d' }, /^name: /],
['an empty name', { ...VALID, name: '' }, /^name: /],
['a name made of spaces', { ...VALID, name: ' ' }, /^name: /],
['a name of 101 characters', { ...VALID, name: 'x'.repeat(101) }, /^name: /],
['a name that is not a string', { ...VALID, name: 42 }, /^name: /],
['no scope', { name: 'Hermes', duration: '90d' }, /^scope: /],
['an unknown scope', { ...VALID, scope: 'admin' }, /^scope: /],
['no duration', { name: 'Hermes', scope: 'read' }, /^duration: /],
['an unknown duration', { ...VALID, duration: '10y' }, /^duration: /],
['an account chosen by the client', { ...VALID, userId: 'someone-else' }, /userId/],
['an expiry chosen by the client', { ...VALID, expiresAt: '2099-01-01T00:00:00.000Z' }, /expiresAt/],
['a body that is not an object', [VALID], /./],
['a body that is not JSON', '{not json', /./],
])('answers 400 to %s, and writes nothing', async (_label, body, message) => {
const A = newAccount();
const a = await post(A, body);
expect(a.status).toBe(400);
expect((a.json as { error: string }).error).toMatch(message);
expect(await rowsOf(A)).toEqual([]);
});
it('checks the session, then the rate limit, then the Origin, then the body', async () => {
const A = newAccount();
const foreign = { origin: 'https://evil.example' };
const nonsense = { nonsense: true };
// Everything wrong at once: the Authorization header decides, before the
// rate limiter is even asked.
h.limited = true;
expect((await post(A, nonsense, { ...foreign, authorization: AUTHORIZATIONS[0][1] })).status).toBe(401);
expect(h.limits).toEqual([]);
// The rate limit before the Origin.
expect((await post(A, nonsense, foreign)).status).toBe(429);
h.limited = false;
// The Origin before the body.
expect((await post(A, nonsense, foreign)).status).toBe(403);
// The body last.
expect((await post(A, nonsense)).status).toBe(400);
expect(h.limits).toEqual([[A, 'create'], [A, 'create'], [A, 'create']]);
expect(await rowsOf(A)).toEqual([]);
});
});
describe('GET /api/agent-tokens', () => {
it('lists the tokens of the account, newest first, named columns only', async () => {
const A = newAccount();
const first = await create(A, { name: 'First', scope: 'read', duration: '90d' });
const second = await create(A, { name: 'Second', scope: 'write', duration: 'never' });
// Two creations may fall in the same millisecond: set them an hour apart.
await h.pg.query("update sl_agent_tokens set created_at = created_at - interval '1 hour' where id = $1", [first.id]);
const firstCreatedAt = (await rowOf(first.id))!.created_at.toISOString();
// A read needs no Origin.
const a = await list(A, { origin: null });
expect(a.status).toBe(200);
expect(a.json).toEqual([
{ id: second.id, name: 'Second', scope: 'write', hint: second.hint, createdAt: second.createdAt, lastUsedAt: null, expiresAt: null },
{ id: first.id, name: 'First', scope: 'read', hint: first.hint, createdAt: firstCreatedAt, lastUsedAt: null, expiresAt: first.expiresAt },
]);
expect(h.limits.at(-1)).toEqual([A, 'read']);
});
it('shows when a token was last used', async () => {
const A = newAccount();
const { token, id } = await create(A);
const usedAt = new Date('2026-11-14T15:30:00.000Z');
expect(await verifyAgentToken(`Bearer ${token}`, usedAt)).not.toBeNull();
expect(((await list(A)).json as Json[]).find((t) => t.id === id)?.lastUsedAt).toBe(usedAt.toISOString());
});
it('lists nothing of another account', async () => {
const [A, B] = [newAccount(), newAccount()];
const [a, b] = [await create(A), await create(B)];
expect(((await list(A)).json as Json[]).map((t) => t.id)).toEqual([a.id]);
expect(((await list(B)).json as Json[]).map((t) => t.id)).toEqual([b.id]);
expect((await list(newAccount())).json).toEqual([]);
});
it.each(AUTHORIZATIONS)('answers 401 to %s in an Authorization header', async (_label, authorization) => {
const A = newAccount();
await create(A);
h.limits = [];
expect(await list(A, { authorization })).toMatchObject(UNAUTHORIZED);
expect(h.limits).toEqual([]);
});
it('answers 401 without a session', async () => {
expect(await list(null)).toMatchObject(UNAUTHORIZED);
});
it('answers 429 when the read limit is reached', async () => {
const A = newAccount();
await create(A);
h.limited = true;
expect((await list(A)).status).toBe(429);
expect(h.limits.at(-1)).toEqual([A, 'read']);
});
});
describe('DELETE /api/agent-tokens/[id]', () => {
it('revokes the token: 200, its row is gone and its value is refused', async () => {
const A = newAccount();
const [kept, revoked] = [await create(A), await create(A)];
expect(await verifyAgentToken(`Bearer ${revoked.token}`)).not.toBeNull();
h.limits = [];
const a = await del(A, revoked.id);
expect(a.status).toBe(200);
expect(a.json).toEqual({ ok: true });
expect(h.limits).toEqual([[A, 'create']]);
expect((await rowsOf(A)).map((r) => r.id)).toEqual([kept.id]);
expect(await verifyAgentToken(`Bearer ${revoked.token}`)).toBeNull();
expect(await verifyAgentToken(`Bearer ${kept.token}`)).not.toBeNull();
// Already revoked: unknown.
expect(await del(A, revoked.id)).toMatchObject(NOT_FOUND);
});
it('answers 404 to the token of another account, and leaves its row intact', async () => {
const [A, B] = [newAccount(), newAccount()];
const b = await create(B);
const before = await rowOf(b.id);
expect(before).toMatchObject({ user_id: B, token_hash: sha256(b.token) });
expect(await del(A, b.id)).toMatchObject(NOT_FOUND);
expect(await rowOf(b.id)).toEqual(before);
// Its owner still sees it, and its value still opens the account.
expect(((await list(B)).json as Json[]).map((t) => t.id)).toEqual([b.id]);
expect(await verifyAgentToken(`Bearer ${b.token}`)).toMatchObject({ userId: B, tokenId: b.id });
});
it.each([
['an unknown id', u()],
['an id that is not a uuid', 'not-a-uuid'],
])('answers 404 to %s', async (_label, id) => {
const A = newAccount();
await create(A);
expect(await del(A, id)).toMatchObject(NOT_FOUND);
expect(await rowsOf(A)).toHaveLength(1);
});
it.each(ORIGINS)('answers 403 to %s, and leaves the row intact', async (_label, origin, host) => {
const A = newAccount();
const { id } = await create(A);
expect(await del(A, id, { origin, host })).toMatchObject(FORBIDDEN);
expect(await rowOf(id)).toBeDefined();
});
it('accepts the Origin of the site on a request whose URL carries another host', async () => {
const A = newAccount();
const { id } = await create(A);
expect((await del(A, id, { origin: SITE, host: CONTAINER })).status).toBe(200);
expect(await rowOf(id)).toBeUndefined();
});
it.each(AUTHORIZATIONS)('answers 401 to %s in an Authorization header, and leaves the row intact', async (_label, authorization) => {
const A = newAccount();
const { id } = await create(A);
h.limits = [];
expect(await del(A, id, { authorization })).toMatchObject(UNAUTHORIZED);
expect(await rowOf(id)).toBeDefined();
expect(h.limits).toEqual([]);
});
it('answers 401 to a live agent token of the account: a token cannot revoke another', async () => {
const A = newAccount();
const [used, target] = [await create(A, { scope: 'write' }), await create(A)];
expect(await del(A, target.id, { authorization: `Bearer ${used.token}` })).toMatchObject(UNAUTHORIZED);
expect(await rowOf(target.id)).toBeDefined();
});
it('answers 401 without a session, and leaves the row intact', async () => {
const A = newAccount();
const { id } = await create(A);
expect(await del(null, id)).toMatchObject(UNAUTHORIZED);
expect(await rowOf(id)).toBeDefined();
});
it('checks the session, then the rate limit, then the Origin, then the id', async () => {
const A = newAccount();
const foreign = { origin: 'https://evil.example' };
h.limited = true;
expect((await del(A, 'not-a-uuid', { ...foreign, authorization: AUTHORIZATIONS[0][1] })).status).toBe(401);
expect(h.limits).toEqual([]);
expect((await del(A, 'not-a-uuid', foreign)).status).toBe(429);
h.limited = false;
expect((await del(A, 'not-a-uuid', foreign)).status).toBe(403);
expect((await del(A, 'not-a-uuid')).status).toBe(404);
expect(h.limits).toEqual([[A, 'create'], [A, 'create'], [A, 'create']]);
});
});
describe('outside the pilot', () => {
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('the three routes answer 404 when MCP_ALLOWED_SUBS is %s', async (_label, value) => {
const [A, B] = [newAccount(), newAccount()];
// Created while the pilot was open to everyone.
const { id } = await create(A);
h.limits = [];
pilot(value === 'others' ? `${B}, ${newAccount()}` : value);
expect(await list(A)).toMatchObject(NOT_FOUND);
expect(await post(A)).toMatchObject(NOT_FOUND);
expect(await del(A, id)).toMatchObject(NOT_FOUND);
// Nothing was written, and the rate limiter was never asked.
expect((await rowsOf(A)).map((r) => r.id)).toEqual([id]);
expect(h.limits).toEqual([]);
});
it('opens the three routes to the accounts of the list, and to no other', async () => {
const [A, B] = [newAccount(), newAccount()];
pilot(` ${A} , ${newAccount()}`);
const { id } = await create(A);
expect((await list(A)).status).toBe(200);
expect((await del(A, id)).status).toBe(200);
expect(await list(B)).toMatchObject(NOT_FOUND);
expect(await post(B)).toMatchObject(NOT_FOUND);
expect(await rowsOf(B)).toEqual([]);
});
it('answers 401, not 404, to an Authorization header and to a missing session', async () => {
const A = newAccount();
pilot('');
expect(await list(A, { authorization: AUTHORIZATIONS[0][1] })).toMatchObject(UNAUTHORIZED);
expect(await post(null)).toMatchObject(UNAUTHORIZED);
});
});
describe('what the responses, the logs and the database hold', () => {
it('only the response of the POST carries the token; none carries its hash or the account', async () => {
const [A, B] = [newAccount(), newAccount()];
const a = await create(A, { scope: 'write', duration: 'never' });
const b = await create(B);
// One response of every kind the routes give.
await list(A); // 200
await list(B);
await post(A, { ...VALID, userId: B }); // 400
await post(A, VALID, { authorization: `Bearer ${a.token}` }); // 401
await post(A, VALID, { origin: null }); // 403
await del(A, b.id); // 404, another account's
await del(B, b.id); // 200
for (let i = 1; i < 10; i++) await create(A);
await post(A); // 409
h.limited = true;
await list(A); // 429
h.limited = false;
pilot('');
await list(A); // 404, outside the pilot
expect([...new Set(seen.answers.map((x) => x.status))].sort()).toEqual([200, 201, 400, 401, 403, 404, 409, 429]);
// The scan every test ends on, called here by name: no account, no hash,
// and no token outside the response of its creation.
scan();
for (const token of seen.tokens.keys()) {
expect(seen.answers.filter((x) => x.text.includes(secretOf(token)))).toEqual([seen.tokens.get(token)]);
}
// Control: the scan had something to find.
expect(seen.tokens.size).toBe(11);
expect(a.answer.text).toContain(a.token);
expect((await rowOf(a.id))?.token_hash).toBe(sha256(a.token));
});
it('no column of any table holds the value of a token', async () => {
const A = newAccount();
const { token, id } = await create(A, { scope: 'write', duration: 'never' });
expect(await verifyAgentToken(`Bearer ${token}`)).not.toBeNull();
const tables = (await h.pg.query<{ table_name: string }>(
"select table_name from information_schema.tables where table_schema = 'public' order by table_name",
)).rows.map((t) => t.table_name);
expect(tables).toEqual(expect.arrayContaining(['sl_agent_actions', 'sl_agent_tokens', 'sl_tasks']));
let own = 0;
for (const table of tables) {
// Every column of every row, as text.
const { rows } = await h.pg.query<{ line: string }>(`select t::text as line from "${table}" t`);
for (const { line } of rows) {
expect(line).not.toContain(token);
expect(line).not.toContain(secretOf(token));
// Control: the row of the token is among the lines read.
if (line.includes(id)) {
own++;
expect(line).toContain(sha256(token));
}
}
}
expect(own).toBe(1);
});
});

View file

@ -0,0 +1,58 @@
import { NextResponse } from 'next/server';
import { parseBody } from '@/lib/api';
import { requireAssistantsSession } from '@/lib/agentAccess';
import { createAgentToken, listAgentTokens } from '@/lib/agentTokens';
import { isAllowedOrigin } from '@/lib/origin';
import { rateLimit } from '@/lib/rateLimit';
import { createAgentTokenSchema } from '@/lib/validators';
// Agent tokens of the signed-in account (#200). These routes do not call
// requireAuth(): requireAssistantsSession() takes the session of the site
// only, refuses any Authorization header, and answers 404 outside the pilot.
// Order of the checks: session, rate limit, Origin (writes), body, action.
export async function GET() {
const auth = await requireAssistantsSession();
if (auth.error) return auth.error;
const rl = rateLimit(auth.userId, 'read');
if (rl) return rl;
// Named columns only: never the hash, never the account.
return NextResponse.json(await listAgentTokens(auth.userId));
}
export async function POST(request: Request) {
const auth = await requireAssistantsSession();
if (auth.error) return auth.error;
const rl = rateLimit(auth.userId, 'create');
if (rl) return rl;
// A write made with the session cookie must come from a page of the site.
// The list is origin.ts: `request.url` holds the container's origin.
if (!isAllowedOrigin(request.headers.get('origin'))) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await parseBody(request, (d) => createAgentTokenSchema.parse(d));
if (body.error) return body.error;
const created = await createAgentToken(auth.userId, body.data);
if (!created.ok) {
return NextResponse.json({ error: created.error }, { status: 409 });
}
// The only response that ever carries the value of the token.
const { token, row } = created;
return NextResponse.json(
{
token,
id: row.id,
name: row.name,
scope: row.scope,
hint: row.hint,
createdAt: row.createdAt,
expiresAt: row.expiresAt,
},
{ status: 201, headers: { 'Cache-Control': 'no-store' } },
);
}

View file

@ -0,0 +1,86 @@
import { describe, it, expect, vi, beforeEach, afterEach, afterAll, type MockInstance } from 'vitest';
// An agent token on the sync route (#200): the real GET and POST /api/sync
// with the real requireAuth. Unlike every other route test, @/lib/api is not
// replaced, nor the rate limiter or the database client. Two modules are:
// - headers() of next/headers, which throws outside a request;
// - the Logto session helper, which vitest cannot load (@logto/next imports
// `next/navigation`, unresolvable outside the Next build). A request with
// a Bearer never reads the session: the stub throws if it is called.
// fetch is spied: an agent token must never reach Logto. No test goes as far
// as the database.
const h = vi.hoisted(() => ({ headers: new Headers() }));
vi.mock('next/headers', async (importOriginal) => ({
...(await importOriginal<typeof import('next/headers')>()),
headers: async () => h.headers,
}));
vi.mock('@/lib/auth', () => ({
getAuthenticatedUser: async () => {
throw new Error('the session of the site is never read for a Bearer');
},
}));
const { GET, POST } = await import('./route');
const { NextRequest } = await import('next/server');
const { generateToken } = await import('@/lib/agentTokens');
// The URL carries the container's host, as in production.
const URL_BASE = 'http://0.0.0.0:3000/api/sync';
// An endpoint that exists nowhere: every call to it lands on the spy.
const LOGTO = 'https://logto.test';
const initial = process.env.LOGTO_ENDPOINT;
let logto: MockInstance<typeof fetch>;
beforeEach(() => {
process.env.LOGTO_ENDPOINT = LOGTO;
// This Logto accepts any token: a call to it would authenticate the request.
logto = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => Response.json({ sub: 'user-from-logto' }));
});
afterEach(() => {
logto.mockRestore();
});
afterAll(() => {
if (initial === undefined) delete process.env.LOGTO_ENDPOINT;
else process.env.LOGTO_ENDPOINT = initial;
});
function pull(authorization: string, query: string) {
h.headers = new Headers({ authorization });
return GET(new NextRequest(`${URL_BASE}${query}`, { headers: h.headers }));
}
function push(authorization: string) {
h.headers = new Headers({ authorization });
return POST(new Request(URL_BASE, { method: 'POST', headers: h.headers, body: JSON.stringify({ operations: [] }) }));
}
describe('/api/sync with an agent token', () => {
it('GET answers 401, without calling Logto', async () => {
const res = await pull(`Bearer ${generateToken()}`, '?since=2026-01-01T00:00:00.000Z');
expect(res.status).toBe(401);
expect(await res.json()).toEqual({ error: 'Invalid token' });
expect(logto).not.toHaveBeenCalled();
});
it('POST answers 401, without calling Logto', async () => {
const res = await push(`Bearer ${generateToken()}`);
expect(res.status).toBe(401);
expect(await res.json()).toEqual({ error: 'Invalid token' });
expect(logto).not.toHaveBeenCalled();
});
// Control: in this setup a Bearer that Logto accepts does get past
// requireAuth. The request stops at the missing `since`, before any query.
it('GET lets a Logto access token past the authentication', async () => {
const res = await pull('Bearer logto-access-token-of-the-test', '');
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'Missing "since" parameter' });
expect(logto).toHaveBeenCalledTimes(1);
expect(logto.mock.calls[0][0]).toBe(`${LOGTO}/oidc/me`);
});
});

View file

@ -0,0 +1,19 @@
import { sql } from 'drizzle-orm';
import type { db } from '@/db/client';
type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
// One writer at a time per account (#200): an advisory lock keyed on the
// account, held until the transaction ends. A transaction that counts rows of
// an account before writing one (the cap of agent tokens), or creates a row
// only when none exists, takes it first: two requests of the same account
// then run one after the other, and two accounts never wait for each other.
//
// The key is the 64-bit hash of the `sub` (hashtextextended, seed 0). Two
// accounts whose hashes collide would only queue behind each other.
//
// Call it as the first statement of the transaction. PGlite has a single
// connection: no test sees two transactions wait, the rule is read.
export async function lockAccount(tx: Tx, userId: string): Promise<void> {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${userId}, 0))`);
}

View file

@ -0,0 +1,171 @@
import { randomUUID as u } from 'node:crypto';
import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
// The pilot of the AI assistants and the guard of their management routes
// (#200). The real requireAssistantsSession runs: next/headers gives the
// headers of the test (headers() throws outside a request), and the Logto
// session helper gives the session of the test.
const h = vi.hoisted(() => ({
headers: new Headers(),
session: null as { userId: string } | null,
sessionReads: 0,
}));
vi.mock('next/headers', () => ({ headers: async () => h.headers }));
vi.mock('@/lib/auth', () => ({
getAuthenticatedUser: async () => {
h.sessionReads++;
return h.session;
},
}));
const { mcpAllowed, requireAssistantsSession } = await import('./agentAccess');
const initial = process.env.MCP_ALLOWED_SUBS;
function pilot(value: string | undefined) {
if (value === undefined) delete process.env.MCP_ALLOWED_SUBS;
else process.env.MCP_ALLOWED_SUBS = value;
}
// Invented accounts: no real `sub` in the repository.
const newUser = () => `user-${u()}`;
beforeEach(() => {
pilot(undefined);
h.headers = new Headers();
h.session = null;
h.sessionReads = 0;
});
afterAll(() => pilot(initial));
describe('mcpAllowed', () => {
it('allows nobody when the variable is absent', () => {
expect(mcpAllowed(newUser())).toBe(false);
});
it.each([[''], [' '], [','], [' , ,']])('allows nobody when the variable is %j', (value) => {
pilot(value);
expect(mcpAllowed(newUser())).toBe(false);
// An empty entry never matches an empty id.
expect(mcpAllowed('')).toBe(false);
});
it('allows the accounts of a comma-separated list, and no other', () => {
const [A, B, C] = [newUser(), newUser(), newUser()];
pilot(`${A},${B}`);
expect(mcpAllowed(A)).toBe(true);
expect(mcpAllowed(B)).toBe(true);
expect(mcpAllowed(C)).toBe(false);
});
it('ignores the spaces around each account of the list', () => {
const [A, B, C] = [newUser(), newUser(), newUser()];
pilot(` ${A} ,\t${B} , `);
expect(mcpAllowed(A)).toBe(true);
expect(mcpAllowed(B)).toBe(true);
expect(mcpAllowed(C)).toBe(false);
});
it('compares whole ids: no prefix, no other case', () => {
const A = newUser();
pilot(A);
expect(mcpAllowed(A)).toBe(true);
expect(mcpAllowed(A.slice(0, -1))).toBe(false);
expect(mcpAllowed(`${A}x`)).toBe(false);
expect(mcpAllowed(A.toUpperCase())).toBe(false);
});
it.each([['*'], [' * ']])('allows every account when the variable is %j', (value) => {
pilot(value);
expect(mcpAllowed(newUser())).toBe(true);
expect(mcpAllowed(newUser())).toBe(true);
});
it('reads `*` as "everyone" only when it is the whole value', () => {
const [A, B] = [newUser(), newUser()];
pilot(`${A},*`);
expect(mcpAllowed(A)).toBe(true);
expect(mcpAllowed(B)).toBe(false);
});
it('reads the variable at every call', () => {
const A = newUser();
pilot(A);
expect(mcpAllowed(A)).toBe(true);
pilot('');
expect(mcpAllowed(A)).toBe(false);
pilot('*');
expect(mcpAllowed(A)).toBe(true);
pilot(undefined);
expect(mcpAllowed(A)).toBe(false);
});
});
describe('requireAssistantsSession', () => {
// The status and the body of a refusal; the body never names the account.
async function refusal(userId?: string) {
const r = await requireAssistantsSession();
expect(r.userId).toBeUndefined();
const text = await r.error!.text();
if (userId) expect(text).not.toContain(userId);
return { status: r.error!.status, body: JSON.parse(text) as unknown };
}
it('returns the account of the site session when it is in the pilot', async () => {
const A = newUser();
pilot(A);
h.session = { userId: A };
expect(await requireAssistantsSession()).toEqual({ userId: A });
});
// An agent token, a Logto access token (the mobile app's), another scheme,
// an empty value: the header alone is refused.
it.each([
['an agent token', `Bearer slmcp_${'A'.repeat(43)}`],
['a Logto access token', 'Bearer logto-access-token-of-the-test'],
['another scheme', 'Basic not-a-credential'],
['an empty value', ''],
])('answers 401 to an Authorization header (%s), before reading the session', async (_label, authorization) => {
const A = newUser();
pilot(A);
h.session = { userId: A };
h.headers = new Headers({ authorization });
expect(await refusal(A)).toEqual({ status: 401, body: { error: 'Unauthorized' } });
expect(h.sessionReads).toBe(0);
});
it('answers 401, not 404, to an Authorization header from an account outside the pilot', async () => {
const A = newUser();
h.session = { userId: A };
h.headers = new Headers({ authorization: 'Bearer logto-access-token-of-the-test' });
expect(await refusal(A)).toEqual({ status: 401, body: { error: 'Unauthorized' } });
});
it('answers 401 without a session, whatever the pilot', async () => {
expect(await refusal()).toEqual({ status: 401, body: { error: 'Unauthorized' } });
pilot('*');
expect(await refusal()).toEqual({ status: 401, body: { error: 'Unauthorized' } });
expect(h.sessionReads).toBe(2);
});
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', `${newUser()}, ${newUser()}`],
])('answers 404 to a session outside the pilot (variable %s)', async (_label, value) => {
const A = newUser();
pilot(value);
h.session = { userId: A };
expect(await refusal(A)).toEqual({ status: 404, body: { error: 'Not found' } });
});
it('lets every session in when the pilot is `*`', async () => {
const A = newUser();
pilot('*');
h.session = { userId: A };
expect(await requireAssistantsSession()).toEqual({ userId: A });
});
});

View file

@ -0,0 +1,55 @@
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { getAuthenticatedUser } from '@/lib/auth';
/**
* Pilot of the AI assistants (#200): whether this account may use the MCP
* server and its management page. MCP_ALLOWED_SUBS is read at every call, so
* the answer follows the environment of the running process:
* - absent or empty: nobody (a variable forgotten at deploy opens nothing);
* - `*`: every account;
* - otherwise a comma-separated list of Logto `sub` values, spaces around
* each one ignored. In a list, `*` is an entry like another: it opens
* nothing.
* The variable is also the emergency switch: emptying it closes everything.
*/
export function mcpAllowed(userId: string): boolean {
const value = (process.env.MCP_ALLOWED_SUBS ?? '').trim();
if (value === '') return false;
if (value === '*') return true;
return value.split(',').some((sub) => {
const allowed = sub.trim();
return allowed !== '' && allowed === userId;
});
}
/**
* Guard of the routes that manage agent tokens and read the agent journal.
* They take the session of the site only (decision of Max, 2026-11-14): a
* short-lived Logto access token, the mobile app's or another app's, must not
* be able to mint a token that never expires. In this order:
* 1. an Authorization header, whatever it holds: 401, before anything else;
* 2. no session of the site: 401;
* 3. an account outside the pilot: 404, as if the route did not exist.
* Returns `{ userId }` or `{ error }`, like requireAuth().
*/
export async function requireAssistantsSession(): Promise<
| { userId: string; error?: never }
| { userId?: never; error: NextResponse }
> {
const headersList = await headers();
if (headersList.get('authorization') !== null) {
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
}
const user = await getAuthenticatedUser();
if (!user) {
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
}
if (!mcpAllowed(user.userId)) {
return { error: NextResponse.json({ error: 'Not found' }, { status: 404 }) };
}
return { userId: user.userId };
}

View file

@ -0,0 +1,491 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID as u } from 'node:crypto';
import { describe, it, expect, beforeAll, vi } from 'vitest';
import { sql } from 'drizzle-orm';
import type { PGlite } from 'electric-sql-pglite';
// Agent tokens (#200): the real module against an in-memory Postgres (PGlite)
// with the companion migrations. Time is passed to the functions (`now`), so
// no test waits or depends on the clock. The real lockAccount runs; its calls
// are recorded.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
return { pg: new PGlite() as PGlite, locked: [] as string[] };
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/accountLock', async (importOriginal) => {
const mod = await importOriginal<typeof import('@/lib/accountLock')>();
return {
...mod,
lockAccount: async (...args: Parameters<typeof mod.lockAccount>) => {
h.locked.push(args[1]);
return mod.lockAccount(...args);
},
};
});
const { db } = await import('@/db/client');
const { lockAccount } = await import('@/lib/accountLock');
const {
AGENT_TOKEN_PREFIX,
MAX_AGENT_TOKENS,
generateToken,
hashToken,
expiresAtFor,
createAgentToken,
listAgentTokens,
revokeAgentToken,
verifyAgentToken,
} = await import('./agentTokens');
type Tx = Parameters<typeof lockAccount>[0];
// A row of sl_agent_tokens as the database holds it.
type Row = {
id: string;
user_id: string;
name: string;
token_hash: string;
hint: string;
scope: string;
created_at: Date;
last_used_at: Date | null;
expires_at: Date | null;
};
const TOKEN = /^slmcp_[A-Za-z0-9_-]{43}$/;
const UUID = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
const DAY_MS = 24 * 60 * 60 * 1000;
// Each test creates its own accounts (#148): no test reads or writes the rows
// of another, so the file passes in any order (vitest runs it shuffled).
// Invented ids: no real `sub` in the repository.
const newUser = () => `user-${u()}`;
const bearer = (token: string) => `Bearer ${token}`;
const secretOf = (token: string) => token.slice(AGENT_TOKEN_PREFIX.length);
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');
async function rowsOf(userId: string): Promise<Row[]> {
return (await h.pg.query<Row>('select * from sl_agent_tokens where user_id = $1 order by created_at, id', [userId])).rows;
}
async function rowOf(id: string): Promise<Row | undefined> {
return (await h.pg.query<Row>('select * from sl_agent_tokens where id = $1', [id])).rows[0];
}
type Fields = Partial<Parameters<typeof createAgentToken>[1]>;
// A token of the account: write scope, no expiry, unless `fields` says otherwise.
async function create(userId: string, fields: Fields = {}, now?: Date) {
const result = await createAgentToken(userId, { name: 'Assistant', scope: 'write', duration: 'never', ...fields }, now);
if (!result.ok) throw new Error(`token refused: ${result.error}`);
return result;
}
beforeAll(async () => {
const dir = path.join(__dirname, '../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await h.pg.exec(stmt);
}
}
});
describe('generateToken', () => {
it('is slmcp_ followed by 43 base64url characters: 32 random bytes', () => {
const token = generateToken();
expect(token).toMatch(TOKEN);
expect(token).toHaveLength(49);
expect(token.startsWith(AGENT_TOKEN_PREFIX)).toBe(true);
expect(Buffer.from(secretOf(token), 'base64url')).toHaveLength(32);
});
it('never gives the same token twice', () => {
const tokens = new Set(Array.from({ length: 200 }, () => generateToken()));
expect(tokens.size).toBe(200);
});
});
describe('hashToken', () => {
it('is the SHA-256 of its input, in hexadecimal', () => {
// Known vector: SHA-256("abc"), FIPS 180-2.
expect(hashToken('abc')).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
});
it('is stable, covers the whole token and differs from one token to another', () => {
const [a, b] = [generateToken(), generateToken()];
expect(hashToken(a)).toMatch(/^[0-9a-f]{64}$/);
expect(hashToken(a)).toBe(hashToken(a));
expect(hashToken(a)).toBe(sha256(a));
expect(hashToken(a)).not.toBe(hashToken(secretOf(a)));
expect(hashToken(a)).not.toBe(hashToken(b));
});
});
describe('expiresAtFor', () => {
const at = (iso: string) => new Date(iso);
it('never: no expiry', () => {
expect(expiresAtFor('never', at('2026-11-14T15:30:00.123Z'))).toBeNull();
});
it('90d: exactly 90 days later', () => {
const from = at('2026-11-14T15:30:00.123Z');
const expiry = expiresAtFor('90d', from)!;
expect(expiry.toISOString()).toBe('2027-02-12T15:30:00.123Z');
expect(expiry.getTime() - from.getTime()).toBe(90 * DAY_MS);
});
it('1y: the same day of the next year in UTC, at the same time', () => {
expect(expiresAtFor('1y', at('2026-11-14T15:30:00.123Z'))!.toISOString()).toBe('2027-11-14T15:30:00.123Z');
});
it('1y across a leap day: the same date, 366 days later', () => {
const from = at('2027-11-14T15:30:00.000Z');
const expiry = expiresAtFor('1y', from)!;
expect(expiry.toISOString()).toBe('2028-11-14T15:30:00.000Z');
expect(expiry.getTime() - from.getTime()).toBe(366 * DAY_MS);
});
it('1y from February 29: March 1 of the next year', () => {
expect(expiresAtFor('1y', at('2028-02-29T10:00:00.000Z'))!.toISOString()).toBe('2029-03-01T10:00:00.000Z');
});
// 18:30 on December 31 in Quebec (EST) is already 23:30 UTC: the day that
// is kept is the UTC one, and the instant is the same hour a year later.
it('1y late in the UTC day: the UTC date is kept', () => {
expect(expiresAtFor('1y', at('2026-12-31T23:30:00.000Z'))!.toISOString()).toBe('2027-12-31T23:30:00.000Z');
});
it('leaves the date it was given untouched', () => {
const from = at('2026-11-14T15:30:00.123Z');
expiresAtFor('1y', from);
expiresAtFor('90d', from);
expect(from.toISOString()).toBe('2026-11-14T15:30:00.123Z');
});
});
describe('lockAccount', () => {
// Advisory locks held by the session, each as the signed 64-bit key it was
// taken with (pg_locks splits the key in two 32-bit halves).
async function held(tx: Tx): Promise<string[]> {
const result = await tx.execute<{ key: string }>(sql`
select ((classid::bigint << 32) | objid::bigint)::text as key
from pg_locks
where locktype = 'advisory' and pid = pg_backend_pid()
order by 1`);
return result.rows.map((r) => r.key);
}
async function keyOf(userId: string): Promise<string> {
return (await h.pg.query<{ key: string }>('select hashtextextended($1, 0)::text as key', [userId])).rows[0].key;
}
it('holds an advisory lock keyed on the account until the transaction ends', async () => {
const [A, B] = [newUser(), newUser()];
const [keyA, keyB] = [await keyOf(A), await keyOf(B)];
expect(keyA).not.toBe(keyB);
await db.transaction(async (tx) => {
expect(await held(tx)).toEqual([]);
await lockAccount(tx, A);
expect(await held(tx)).toEqual([keyA]);
// The same account again: the same lock.
await lockAccount(tx, A);
expect(await held(tx)).toEqual([keyA]);
// Another account: another lock.
await lockAccount(tx, B);
expect((await held(tx)).sort()).toEqual([keyA, keyB].sort());
});
// Released with the transaction.
await db.transaction(async (tx) => {
expect(await held(tx)).toEqual([]);
});
});
});
describe('createAgentToken', () => {
it('returns the token and the named columns, and stores its hash and its last four characters', async () => {
const A = newUser();
const now = new Date('2026-11-14T15:30:00.123Z');
const expiry = new Date('2027-02-12T15:30:00.123Z');
const { token, row } = await create(A, { name: 'Hermes', scope: 'read', duration: '90d' }, now);
expect(token).toMatch(TOKEN);
expect(row).toEqual({
id: expect.stringMatching(UUID),
name: 'Hermes',
scope: 'read',
hint: token.slice(-4),
createdAt: now,
lastUsedAt: null,
expiresAt: expiry,
});
expect(await rowsOf(A)).toEqual([{
id: row.id,
user_id: A,
name: 'Hermes',
token_hash: sha256(token),
hint: token.slice(-4),
scope: 'read',
created_at: now,
last_used_at: null,
expires_at: expiry,
}]);
});
it.each([
['90d', '2026-11-14T15:30:00.000Z', '2027-02-12T15:30:00.000Z'],
['1y', '2026-11-14T15:30:00.000Z', '2027-11-14T15:30:00.000Z'],
['1y', '2028-02-29T10:00:00.000Z', '2029-03-01T10:00:00.000Z'],
['never', '2026-11-14T15:30:00.000Z', null],
] as const)('stores the expiry of a %s token created at %s: %s', async (duration, from, expected) => {
const A = newUser();
const { row } = await create(A, { duration }, new Date(from));
const [stored] = await rowsOf(A);
expect(stored.created_at.toISOString()).toBe(from);
expect(stored.expires_at?.toISOString() ?? null).toBe(expected);
expect(row.expiresAt?.toISOString() ?? null).toBe(expected);
});
it('stores the token in no column: its hash, and a hint of four characters', async () => {
const A = newUser();
const { token } = await create(A);
const [stored] = await rowsOf(A);
for (const [column, value] of Object.entries(stored)) {
const text = value instanceof Date ? value.toISOString() : String(value);
expect(text, column).not.toContain(token);
expect(text, column).not.toContain(secretOf(token));
}
expect(stored.hint).toHaveLength(4);
expect(token.endsWith(stored.hint)).toBe(true);
});
it('lets two tokens of an account share a name', async () => {
const A = newUser();
const [first, second] = [await create(A, { name: 'Hermes' }), await create(A, { name: 'Hermes' })];
expect(first.token).not.toBe(second.token);
expect((await rowsOf(A)).map((r) => r.name)).toEqual(['Hermes', 'Hermes']);
});
it('refuses the eleventh token of an account, expired ones counted', async () => {
const [A, B] = [newUser(), newUser()];
const now = new Date('2026-11-14T12:00:00.000Z');
expect(MAX_AGENT_TOKENS).toBe(10);
// One token that expired long ago, then nine live ones.
await create(A, { duration: '90d' }, new Date('2025-01-01T00:00:00.000Z'));
for (let i = 1; i < MAX_AGENT_TOKENS; i++) await create(A, {}, now);
expect(await rowsOf(A)).toHaveLength(10);
const refused = await createAgentToken(A, { name: 'One too many', scope: 'read', duration: '90d' }, now);
expect(refused).toEqual({ ok: false, error: 'token_limit' });
expect(await rowsOf(A)).toHaveLength(10);
// The cap is per account.
await create(B, {}, now);
expect(await rowsOf(B)).toHaveLength(1);
// A revoked token leaves its place.
const [expired] = await rowsOf(A);
expect(await revokeAgentToken(A, expired.id)).toBe(true);
await create(A, {}, now);
expect(await rowsOf(A)).toHaveLength(10);
});
it('takes the lock of the account at every creation, refused or not', async () => {
const A = newUser();
for (let i = 0; i < MAX_AGENT_TOKENS; i++) await create(A);
expect((await createAgentToken(A, { name: 'One too many', scope: 'read', duration: 'never' })).ok).toBe(false);
expect(h.locked.filter((userId) => userId === A)).toHaveLength(MAX_AGENT_TOKENS + 1);
});
});
describe('listAgentTokens', () => {
it('gives the named columns of the tokens of the account, newest first', async () => {
const [A, B] = [newUser(), newUser()];
// Created out of order; the oldest one has expired since.
const old = await create(A, { name: 'Old', scope: 'read', duration: '90d' }, new Date('2026-01-01T00:00:00.000Z'));
const recent = await create(A, { name: 'Recent' }, new Date('2026-11-01T00:00:00.000Z'));
const middle = await create(A, { name: 'Middle', duration: '1y' }, new Date('2026-06-01T00:00:00.000Z'));
await create(B, { name: 'Other account' }, new Date('2026-11-10T00:00:00.000Z'));
const list = await listAgentTokens(A);
expect(list).toEqual([recent.row, middle.row, old.row]);
for (const token of list) {
expect(Object.keys(token).sort()).toEqual(['createdAt', 'expiresAt', 'hint', 'id', 'lastUsedAt', 'name', 'scope']);
}
const text = JSON.stringify(list);
for (const created of [old, recent, middle]) {
expect(text).not.toContain(secretOf(created.token));
expect(text).not.toContain(sha256(created.token));
}
expect(text).not.toContain(A);
});
it('gives nothing for an account without token', async () => {
await create(newUser());
expect(await listAgentTokens(newUser())).toEqual([]);
});
});
describe('revokeAgentToken', () => {
it('deletes the token of the account', async () => {
const A = newUser();
const [kept, revoked] = [await create(A), await create(A)];
expect(await revokeAgentToken(A, revoked.row.id)).toBe(true);
expect((await rowsOf(A)).map((r) => r.id)).toEqual([kept.row.id]);
// Already gone: nothing left to revoke.
expect(await revokeAgentToken(A, revoked.row.id)).toBe(false);
});
it('leaves the token of another account as it is', async () => {
const [A, B] = [newUser(), newUser()];
const { row } = await create(B);
const before = await rowOf(row.id);
expect(await revokeAgentToken(A, row.id)).toBe(false);
expect(await rowOf(row.id)).toEqual(before);
expect(before?.user_id).toBe(B);
});
it.each([
['an unknown id', u()],
['an id that is not a uuid', 'not-a-uuid'],
['an empty id', ''],
['a uuid followed by SQL', `${u()}' or '1'='1`],
])('answers false to %s, without an error', async (_label, id) => {
const A = newUser();
await create(A);
expect(await revokeAgentToken(A, id)).toBe(false);
expect(await rowsOf(A)).toHaveLength(1);
});
});
describe('verifyAgentToken', () => {
it('gives the account, the token and its scope, and nothing of its value', async () => {
const [A, B] = [newUser(), newUser()];
const read = await create(A, { name: 'Hermes', scope: 'read' });
const write = await create(B, { name: 'Claude', scope: 'write' });
const context = await verifyAgentToken(bearer(read.token));
expect(context).toEqual({ userId: A, tokenId: read.row.id, tokenName: 'Hermes', scope: 'read' });
expect(JSON.stringify(context)).not.toContain(secretOf(read.token));
expect(await verifyAgentToken(bearer(write.token))).toEqual({
userId: B, tokenId: write.row.id, tokenName: 'Claude', scope: 'write',
});
});
it('refuses a header that is not exactly `Bearer slmcp_` and 43 base64url characters', async () => {
const A = newUser();
const { token } = await create(A);
const short = token.slice(0, -1);
const first = new Date('2026-11-14T15:30:00.000Z');
const later = new Date('2026-11-14T15:40:00.000Z');
// Control: the token itself is accepted.
expect(await verifyAgentToken(bearer(token), first)).not.toBeNull();
const refused = [
null,
'',
token,
`bearer ${token}`,
`BEARER ${token}`,
`Bearer ${token}`,
` Bearer ${token}`,
`Bearer ${token} `,
`Bearer ${token}\n`,
`Basic ${token}`,
`Bearer ${secretOf(token)}`,
`Bearer SLMCP_${secretOf(token)}`,
`Bearer ${token}A`,
`Bearer ${short}`,
`Bearer ${short}=`,
`Bearer ${short}+`,
`Bearer ${short}/`,
`Bearer ${token}, Bearer ${token}`,
];
// Labelled by position: a failure must not print a token.
for (const [i, header] of refused.entries()) {
expect(await verifyAgentToken(header, later), `header ${i}`).toBeNull();
}
// None of them counted as a use: ten minutes later, an accepted call
// would have moved last_used_at.
expect((await rowsOf(A))[0].last_used_at?.toISOString()).toBe(first.toISOString());
});
it('refuses a well-formed token that no row holds', async () => {
await create(newUser());
expect(await verifyAgentToken(bearer(generateToken()))).toBeNull();
});
it('refuses an expired token, to the second', async () => {
const A = newUser();
const { token } = await create(A, { duration: '90d' }, new Date('2026-11-14T15:30:00.000Z'));
const expiry = new Date('2027-02-12T15:30:00.000Z');
const at = (ms: number) => new Date(expiry.getTime() + ms);
expect(await verifyAgentToken(bearer(token), at(-1000))).not.toBeNull();
expect(await verifyAgentToken(bearer(token), at(-1))).not.toBeNull();
expect(await verifyAgentToken(bearer(token), expiry)).toBeNull();
expect(await verifyAgentToken(bearer(token), at(1000))).toBeNull();
expect(await verifyAgentToken(bearer(token), at(365 * DAY_MS))).toBeNull();
// A refused use is not recorded: the last one is the first accepted call.
expect((await rowsOf(A))[0].last_used_at?.toISOString()).toBe(at(-1000).toISOString());
});
it('accepts a token without expiry long after its creation', async () => {
const A = newUser();
const { token } = await create(A, { duration: 'never' }, new Date('2026-11-14T15:30:00.000Z'));
expect(await verifyAgentToken(bearer(token), new Date('2099-01-01T00:00:00.000Z'))).not.toBeNull();
});
it('refuses a revoked token, and still accepts the other token of the account', async () => {
const A = newUser();
const [revoked, kept] = [await create(A), await create(A)];
expect(await verifyAgentToken(bearer(revoked.token))).not.toBeNull();
expect(await revokeAgentToken(A, revoked.row.id)).toBe(true);
expect(await verifyAgentToken(bearer(revoked.token))).toBeNull();
expect(await verifyAgentToken(bearer(kept.token))).not.toBeNull();
});
it('writes last_used_at at most once per minute and per token', async () => {
const A = newUser();
const t0 = new Date('2026-11-14T15:30:00.000Z');
const at = (ms: number) => new Date(t0.getTime() + ms);
const used = await create(A, {}, t0);
const unused = await create(A, {}, t0);
const lastUsed = async (id: string) => (await rowOf(id))?.last_used_at?.toISOString() ?? null;
expect(await lastUsed(used.row.id)).toBeNull();
// First use: written.
expect(await verifyAgentToken(bearer(used.token), at(1000))).not.toBeNull();
expect(await lastUsed(used.row.id)).toBe(at(1000).toISOString());
// Within the minute that follows: accepted, not written.
expect(await verifyAgentToken(bearer(used.token), at(31_000))).not.toBeNull();
expect(await verifyAgentToken(bearer(used.token), at(60_999))).not.toBeNull();
expect(await lastUsed(used.row.id)).toBe(at(1000).toISOString());
// One minute after the last write: written again.
expect(await verifyAgentToken(bearer(used.token), at(61_000))).not.toBeNull();
expect(await lastUsed(used.row.id)).toBe(at(61_000).toISOString());
// The other token of the account was never used; the list shows both.
expect(await lastUsed(unused.row.id)).toBeNull();
const list = await listAgentTokens(A);
expect(list.find((t) => t.id === used.row.id)?.lastUsedAt).toEqual(at(61_000));
expect(list.find((t) => t.id === unused.row.id)?.lastUsedAt).toBeNull();
});
});

198
web/src/lib/agentTokens.ts Normal file
View file

@ -0,0 +1,198 @@
import { createHash, randomBytes } from 'node:crypto';
import { and, count, desc, eq, isNull, lte, or } from 'drizzle-orm';
import { db } from '@/db/client';
import { slAgentTokens } from '@/db/schema';
import { lockAccount } from '@/lib/accountLock';
// Personal tokens that link an AI assistant (MCP) to an account (#200).
//
// A token is `slmcp_` followed by 43 base64url characters (32 random bytes).
// Its value exists in two places only: the answer of the POST that creates
// it, and the assistant's configuration. The database keeps its SHA-256 and
// its last four characters; nothing here logs a token, and no function
// returns the hash or reads a token back.
//
// A token opens POST /api/mcp only (#202): requireAuth() refuses it on every
// other route (api.ts).
export const AGENT_TOKEN_PREFIX = 'slmcp_';
// Tokens an account may hold, expired ones included: the table and the page
// stay bounded.
export const MAX_AGENT_TOKENS = 10;
export type AgentTokenScope = 'read' | 'write';
export type AgentTokenDuration = '90d' | '1y' | 'never';
// What a response or a page may show of a token.
export type AgentToken = {
id: string;
name: string;
scope: AgentTokenScope;
hint: string;
createdAt: Date;
lastUsedAt: Date | null;
expiresAt: Date | null;
};
// Whom a verified token speaks for; the token itself is not part of it.
export type AgentTokenContext = {
userId: string;
tokenId: string;
tokenName: string;
scope: AgentTokenScope;
};
export type CreateAgentTokenResult =
| { ok: true; token: string; row: AgentToken }
| { ok: false; error: 'token_limit' };
// Columns named one by one: `tokenHash` and `userId` never leave this module.
const PUBLIC_COLUMNS = {
id: slAgentTokens.id,
name: slAgentTokens.name,
scope: slAgentTokens.scope,
hint: slAgentTokens.hint,
createdAt: slAgentTokens.createdAt,
lastUsedAt: slAgentTokens.lastUsedAt,
expiresAt: slAgentTokens.expiresAt,
};
// The only Authorization value verifyAgentToken reads: 32 bytes in base64url
// are 43 characters, without padding.
const BEARER = new RegExp(`^Bearer ${AGENT_TOKEN_PREFIX}[A-Za-z0-9_-]{43}$`);
// The id column is a uuid: anything else would be refused by PostgreSQL with
// an error instead of matching no row.
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const DAY_MS = 24 * 60 * 60 * 1000;
// last_used_at is written at most once per minute and per token.
const LAST_USED_INTERVAL_MS = 60 * 1000;
export function generateToken(): string {
return AGENT_TOKEN_PREFIX + randomBytes(32).toString('base64url');
}
// SHA-256 of the whole token, prefix included, in hexadecimal.
export function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
// When a token created at `from` stops being accepted; null: never.
// `1y` is the same day of the next year in UTC, at the same time (a token
// created on February 29 expires on March 1): 365 days would shift the date
// shown by one day after a leap year.
export function expiresAtFor(duration: AgentTokenDuration, from: Date): Date | null {
if (duration === 'never') return null;
if (duration === '90d') return new Date(from.getTime() + 90 * DAY_MS);
const at = new Date(from.getTime());
at.setUTCFullYear(at.getUTCFullYear() + 1);
return at;
}
// Create a token for the account, unless it already holds MAX_AGENT_TOKENS
// (expired ones count). The count and the insert run under the account lock:
// two simultaneous requests of one account cannot both pass the cap.
// The returned `token` is the only copy of the value.
export async function createAgentToken(
userId: string,
{ name, scope, duration }: { name: string; scope: AgentTokenScope; duration: AgentTokenDuration },
now: Date = new Date(),
): Promise<CreateAgentTokenResult> {
return db.transaction(async (tx): Promise<CreateAgentTokenResult> => {
await lockAccount(tx, userId);
const [{ held }] = await tx
.select({ held: count() })
.from(slAgentTokens)
.where(eq(slAgentTokens.userId, userId));
if (held >= MAX_AGENT_TOKENS) return { ok: false, error: 'token_limit' };
const token = generateToken();
const [row] = await tx
.insert(slAgentTokens)
.values({
userId,
name,
tokenHash: hashToken(token),
hint: token.slice(-4),
scope,
createdAt: now,
expiresAt: expiresAtFor(duration, now),
})
.returning(PUBLIC_COLUMNS);
return { ok: true, token, row: row as AgentToken };
});
}
// The tokens of the account, expired ones included, newest first.
export async function listAgentTokens(userId: string): Promise<AgentToken[]> {
const rows = await db
.select(PUBLIC_COLUMNS)
.from(slAgentTokens)
.where(eq(slAgentTokens.userId, userId))
.orderBy(desc(slAgentTokens.createdAt), desc(slAgentTokens.id));
return rows as AgentToken[];
}
// Revoking a token deletes its row (its journal lines stay, #199). False when
// the id matches no token of this account: unknown, malformed, or another
// account's, which is left as it is.
export async function revokeAgentToken(userId: string, id: string): Promise<boolean> {
if (!UUID.test(id)) return false;
const deleted = await db
.delete(slAgentTokens)
.where(and(eq(slAgentTokens.id, id), eq(slAgentTokens.userId, userId)))
.returning({ id: slAgentTokens.id });
return deleted.length > 0;
}
// Whom the Authorization header of an MCP request speaks for, or null: header
// absent or not exactly `Bearer slmcp_` + 43 base64url characters, token
// unknown or revoked (its row is gone), token expired (refused from the very
// instant of `expiresAt`).
//
// The pilot is not checked here: the route calls mcpAllowed() next (#202), so
// that the future OAuth verification goes through the same switch.
export async function verifyAgentToken(
authorization: string | null,
now: Date = new Date(),
): Promise<AgentTokenContext | null> {
if (authorization === null || !BEARER.test(authorization)) return null;
const token = authorization.slice('Bearer '.length);
// Read by the unique index on the hash: the token itself is never compared.
const [row] = await db
.select({
id: slAgentTokens.id,
userId: slAgentTokens.userId,
name: slAgentTokens.name,
scope: slAgentTokens.scope,
expiresAt: slAgentTokens.expiresAt,
})
.from(slAgentTokens)
.where(eq(slAgentTokens.tokenHash, hashToken(token)));
if (!row) return null;
if (row.expiresAt !== null && row.expiresAt.getTime() <= now.getTime()) return null;
// One conditional UPDATE: a token used many times in a minute costs one
// write, and two simultaneous requests cannot both write.
await db
.update(slAgentTokens)
.set({ lastUsedAt: now })
.where(and(
eq(slAgentTokens.id, row.id),
or(
isNull(slAgentTokens.lastUsedAt),
lte(slAgentTokens.lastUsedAt, new Date(now.getTime() - LAST_USED_INTERVAL_MS)),
),
));
return {
userId: row.userId,
tokenId: row.id,
tokenName: row.name,
scope: row.scope as AgentTokenScope,
};
}

View file

@ -1,11 +1,20 @@
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach, afterAll, type MockInstance } from 'vitest';
import { z } from 'zod';
// parseBody returns a bounded 400 (#147). The Logto session helper is not
// under test.
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null }));
// parseBody returns a bounded 400 (#147), and the real requireAuth refuses an
// agent token without calling Logto (#200). headers() of next/headers throws
// outside a request: it gives the headers of the test instead. The Logto
// session helper gives the session of the test (none by default).
const h = vi.hoisted(() => ({
headers: new Headers(),
session: null as { userId: string } | null,
}));
const { parseBody } = await import('./api');
vi.mock('next/headers', () => ({ headers: async () => h.headers }));
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => h.session }));
const { parseBody, requireAuth } = await import('./api');
const { generateToken } = await import('./agentTokens');
function request(body: string) {
return new Request('http://localhost/api/x', { method: 'POST', body });
@ -49,3 +58,83 @@ describe('parseBody', () => {
expect(await parseBody(request('{"a":1}'), (d) => d)).toEqual({ data: { a: 1 } });
});
});
// The real requireAuth (#200): every route test replaces it, so the refusal
// of an agent token is proven here, on the function itself.
describe('requireAuth', () => {
// An endpoint that exists nowhere: every call to it lands on the spy.
const LOGTO = 'https://logto.test';
const LOGTO_BEARER = 'Bearer logto-access-token-of-the-test';
const initial = process.env.LOGTO_ENDPOINT;
let logto: MockInstance<typeof fetch>;
beforeEach(() => {
process.env.LOGTO_ENDPOINT = LOGTO;
h.headers = new Headers();
h.session = null;
// This Logto accepts any token: a call to it would authenticate the request.
logto = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => Response.json({ sub: 'user-from-logto' }));
});
afterEach(() => {
logto.mockRestore();
});
afterAll(() => {
if (initial === undefined) delete process.env.LOGTO_ENDPOINT;
else process.env.LOGTO_ENDPOINT = initial;
});
async function refusal() {
const r = await requireAuth();
expect(r.userId).toBeUndefined();
return { status: r.error!.status, body: await r.error!.json() as unknown };
}
it('answers 401 to an agent token, without calling Logto', async () => {
h.headers = new Headers({ authorization: `Bearer ${generateToken()}` });
expect(await refusal()).toEqual({ status: 401, body: { error: 'Invalid token' } });
expect(logto).not.toHaveBeenCalled();
});
it('answers 401 to an agent token even when the request carries a session of the site', async () => {
h.session = { userId: 'user-of-the-session' };
h.headers = new Headers({ authorization: `Bearer ${generateToken()}` });
expect(await refusal()).toEqual({ status: 401, body: { error: 'Invalid token' } });
expect(logto).not.toHaveBeenCalled();
});
it.each([
['the prefix alone', 'Bearer slmcp_'],
['a token cut short', `Bearer slmcp_${'A'.repeat(10)}`],
['a token after two spaces', `Bearer slmcp_${'A'.repeat(43)}`],
['a token followed by something else', `Bearer slmcp_${'A'.repeat(43)} x`],
])('answers 401 to %s, without calling Logto', async (_label, authorization) => {
h.headers = new Headers({ authorization });
expect(await refusal()).toEqual({ status: 401, body: { error: 'Invalid token' } });
expect(logto).not.toHaveBeenCalled();
});
// Controls: the spy does see a call to Logto, and Logto still decides for
// every Bearer that is not an agent token.
it('still validates another Bearer with Logto', async () => {
h.headers = new Headers({ authorization: LOGTO_BEARER });
expect(await requireAuth()).toEqual({ userId: 'user-from-logto' });
expect(logto).toHaveBeenCalledTimes(1);
expect(logto).toHaveBeenCalledWith(`${LOGTO}/oidc/me`, { headers: { Authorization: LOGTO_BEARER } });
});
it('answers 401 to a Bearer that Logto refuses', async () => {
logto.mockImplementation(async () => new Response(null, { status: 401 }));
h.headers = new Headers({ authorization: LOGTO_BEARER });
expect(await refusal()).toEqual({ status: 401, body: { error: 'Invalid token' } });
expect(logto).toHaveBeenCalledTimes(1);
});
it('reads the session of the site when the request has no Authorization header', async () => {
expect(await refusal()).toEqual({ status: 401, body: { error: 'Unauthorized' } });
h.session = { userId: 'user-of-the-session' };
expect(await requireAuth()).toEqual({ userId: 'user-of-the-session' });
expect(logto).not.toHaveBeenCalled();
});
});

View file

@ -1,4 +1,5 @@
import { getAuthenticatedUser } from '@/lib/auth';
import { AGENT_TOKEN_PREFIX } from '@/lib/agentTokens';
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { ZodError } from 'zod';
@ -43,6 +44,11 @@ export async function requireAuth(): Promise<
const authHeader = headersList.get('authorization');
if (authHeader?.startsWith('Bearer ')) {
const token = authHeader.slice(7);
// An agent token (#200) opens POST /api/mcp only: it is refused here,
// before any call to Logto, so its value never leaves the companion.
if (token.trimStart().startsWith(AGENT_TOKEN_PREFIX)) {
return { error: NextResponse.json({ error: 'Invalid token' }, { status: 401 }) };
}
const user = await authenticateBearer(token);
if (user) return { userId: user.userId };
return { error: NextResponse.json({ error: 'Invalid token' }, { status: 401 }) };

View file

@ -0,0 +1,95 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID as u } from 'node:crypto';
import { EventEmitter } from 'node:events';
import type { Server } from 'node:http';
import { describe, it, expect, vi } from 'vitest';
import { ALLOWED_ORIGINS, isAllowedOrigin } from './origin';
import { getTicketStore, setupWebSocket } from './ws';
// The one list of origins of the companion (#200), read by the WebSocket
// upgrade (ws.ts) and by the routes that write for the site session.
const SITE = 'https://liste.lacompagniemaximus.com';
// Origin of `request.url` in production: the container's, not the site's.
const CONTAINER = 'http://0.0.0.0:3000';
describe('ALLOWED_ORIGINS', () => {
it('holds the two origins ws.ts held: the site and the local dev server', () => {
expect(ALLOWED_ORIGINS).toEqual([SITE, 'http://localhost:3000']);
});
});
describe('isAllowedOrigin', () => {
it.each(ALLOWED_ORIGINS)('accepts %s', (origin) => {
expect(isAllowedOrigin(origin)).toBe(true);
});
it.each([
[null],
[''],
['null'],
[CONTAINER],
['http://127.0.0.1:3000'],
['http://localhost:3001'],
['https://localhost:3000'],
['https://evil.example'],
['http://liste.lacompagniemaximus.com'],
[`${SITE}/`],
[`${SITE}:8443`],
[`${SITE}.evil.example`],
[`https://evil.example/${SITE}`],
['https://LISTE.lacompagniemaximus.com'],
['https://lacompagniemaximus.com'],
[` ${SITE}`],
[`${SITE},${SITE}`],
])('refuses %j', (origin) => {
expect(isAllowedOrigin(origin)).toBe(false);
});
});
// ws.ts imports the list: the upgrade of /ws behaves as before #200.
describe('WebSocket upgrade', () => {
// One upgrade request on /ws with a valid ticket. The handshake itself is
// left incomplete: what is read is whether the Origin check let the request
// reach the ticket (consumed) or cut it before (socket destroyed, ticket kept).
function upgrade(origin: string | undefined) {
const server = new EventEmitter();
const wss = setupWebSocket(server as unknown as Server);
const ticket = `ticket-${u()}`;
getTicketStore().set(ticket, { userId: `user-${u()}`, expiresAt: Date.now() + 30_000 });
const socket = Object.assign(new EventEmitter(), { destroy: vi.fn(), end: vi.fn(), write: vi.fn() });
const headers: Record<string, string> = { host: '0.0.0.0:3000' };
if (origin !== undefined) headers.origin = origin;
server.emit('upgrade', { url: `/ws?ticket=${ticket}`, method: 'GET', headers }, socket, Buffer.alloc(0));
const consumed = !getTicketStore().has(ticket);
getTicketStore().delete(ticket);
wss.close();
return { consumed, destroyed: socket.destroy.mock.calls.length };
}
it.each(ALLOWED_ORIGINS)('lets %s reach the ticket', (origin) => {
expect(upgrade(origin)).toEqual({ consumed: true, destroyed: 0 });
});
it('lets a request without Origin reach the ticket (the mobile app sends none)', () => {
expect(upgrade(undefined)).toEqual({ consumed: true, destroyed: 0 });
});
it.each([
['a foreign origin', 'https://evil.example'],
['the host the request was sent to, which is not the site', CONTAINER],
['the site over http', 'http://liste.lacompagniemaximus.com'],
])('cuts %s before the ticket is read', (_label, origin) => {
expect(upgrade(origin)).toEqual({ consumed: false, destroyed: 1 });
});
it('ws.ts declares no origin of its own', () => {
const src = fs.readFileSync(path.join(__dirname, 'ws.ts'), 'utf8');
expect(src).toContain("import { isAllowedOrigin } from './origin'");
expect(src).not.toContain('lacompagniemaximus.com');
expect(src).not.toContain('localhost');
});
});

20
web/src/lib/origin.ts Normal file
View file

@ -0,0 +1,20 @@
// Origins a page of the companion is served from (#200): the site, and the
// local dev server. One list for every origin check of the companion: the
// WebSocket upgrade (ws.ts) and the routes that write on behalf of the site
// session (agent tokens).
//
// An origin check never compares against `request.url`: in production its
// origin is the container's (`0.0.0.0:3000`), not the site's.
//
// No import here: server.ts bundles ws.ts, and this module with it, apart
// from the Next routes (web/Dockerfile, esbuild).
export const ALLOWED_ORIGINS = [
'https://liste.lacompagniemaximus.com',
'http://localhost:3000',
];
// Exact match on the `Origin` header value: no header (null), `null` as a
// string (sandboxed frame), another scheme, host or port are all refused.
export function isAllowedOrigin(origin: string | null): boolean {
return origin !== null && ALLOWED_ORIGINS.includes(origin);
}

View file

@ -125,3 +125,14 @@ export const syncPushSchema = z.object({
}).strict();
export type SyncOperation = z.infer<typeof syncPushSchema>['operations'][number];
// Agent tokens (#200)
// Body of POST /api/agent-tokens. The three fields are required: the form of
// the page preselects, the API does not guess. The name is trimmed before its
// length is checked; two tokens of an account may share a name.
export const createAgentTokenSchema = z.object({
name: z.string().trim().min(1).max(100),
scope: z.enum(['read', 'write']),
duration: z.enum(['90d', '1y', 'never']),
}).strict();

View file

@ -1,6 +1,7 @@
import { WebSocketServer, WebSocket } from 'ws';
import type { IncomingMessage } from 'http';
import type { Server } from 'http';
import { isAllowedOrigin } from './origin';
// A sync message carries no detail: a socket stays bound to its userId up to
// 15 min after a web sign-out (REVALIDATION_INTERVAL), so it must never learn
@ -28,11 +29,6 @@ export function getTicketStore() {
return ticketStore.__wsTickets;
}
const ALLOWED_ORIGINS = [
'https://liste.lacompagniemaximus.com',
'http://localhost:3000',
];
const REVALIDATION_INTERVAL = 15 * 60 * 1000; // 15 minutes
const HEARTBEAT_INTERVAL = 30 * 1000; // 30 seconds
@ -76,9 +72,10 @@ export function setupWebSocket(server: Server) {
return;
}
// Validate Origin
// Validate Origin against the list shared with the routes (origin.ts).
// A request without the header goes on: the mobile app sends none.
const origin = request.headers.origin;
if (origin && !ALLOWED_ORIGINS.includes(origin)) {
if (origin && !isAllowedOrigin(origin)) {
socket.destroy();
return;
}