From 4baceaebc9d73faad14a08f67ffe513742d45890 Mon Sep 17 00:00:00 2001 From: clibequilibrium <105135724+clibequilibrium@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:29:04 -0500 Subject: [PATCH 1/8] db: closed read modes hold on live subscriptions and write responses readAccess `none` and `owner` were enforced by checkAccess on REST reads, but three other paths hand rows back without asking it: - Live subscriptions. authorizeSubscribe special-cased `public` and otherwise only verified the token, so any valid project token - a self-minted guest token included, since guests are on by default - got the snapshot and every later change of a `none` collection or table, through /realtime and the table's own /subscribe socket. It now refuses `none` before reading the token, as REST does. - Raw SQL writes. A batch carrying any write was judged on writeAccess alone, and every write gets RETURNING over the full row. On the documented "append-only ingest" shape (read `none`, write `auth`), `UPDATE t SET c = c` returned every row unchanged, and a SELECT tucked into a write batch rode past the read mode. Each side a batch touches is now judged on its own mode, and on a table the caller may not read writes still land but return no rows - drizzle inserts keep working. - Typed PUT/PATCH on tables and collections returned the merged stored record. They now return only { id } when the caller would not pass the read gate (mayReadBack in the shared access module), and the OpenAPI document declares that as DbWriteResult. Both attacks are pinned in db-readonly.api.spec.ts and were confirmed to fail against the previous code: the socket answered with a snapshot, and the no-op UPDATE returned another user's rows. --- agents/db/src/access.ts | 19 +++++ agents/db/src/collection.ts | 14 +++- agents/db/src/live.ts | 11 +++ agents/db/src/table.ts | 91 +++++++++++++++------- e2e/db-readonly.api.spec.ts | 151 ++++++++++++++++++++++++++++++++++++ src/lib/agents.ts | 12 +++ src/lib/openapi/db.ts | 26 +++++-- 7 files changed, 290 insertions(+), 34 deletions(-) diff --git a/agents/db/src/access.ts b/agents/db/src/access.ts index f540f7f..62e09fb 100644 --- a/agents/db/src/access.ts +++ b/agents/db/src/access.ts @@ -78,6 +78,25 @@ export async function checkAccess( return { ok: true, owner: mode === 'owner' ? result.claims.sub : null }; } +/** + * Whether the caller of a WRITE may see the record it produced. A write is + * gated on the write side only, but an update's response carries the whole + * stored record - PATCH merges over fields the caller never sent - so echoing + * it is a read. On `readAccess: 'none'` (append-only ingest) or an `owner` + * read over someone else's record, that read is exactly what the mode exists + * to refuse. Answered by the same gate a GET would pass through. + */ +export async function mayReadBack( + request: Request, + mode: AccessMode, + permission: string | null, + verifier: ProjectJwtVerifier, + recordOwner: string | null, +): Promise { + const decision = await checkAccess(request, mode, permission, verifier); + return decision.ok && (decision.owner === null || decision.owner === recordOwner); +} + /** * Exact-origin CORS echo over the deployment's own origin, environment * TRUSTED_ORIGINS, and the project's allowed origins - null means the origin diff --git a/agents/db/src/collection.ts b/agents/db/src/collection.ts index 607fccf..8a00b70 100644 --- a/agents/db/src/collection.ts +++ b/agents/db/src/collection.ts @@ -4,7 +4,7 @@ import { count, eq } from 'drizzle-orm'; import { migrate } from 'drizzle-orm/durable-sqlite/migrator'; import { z } from 'zod'; import migrations from './migrations.js'; -import { checkAccess, corsHeadersFor, drainUnusedBody, withCors } from './access.js'; +import { checkAccess, corsHeadersFor, drainUnusedBody, mayReadBack, withCors } from './access.js'; import { primaryLocation } from './colo.js'; import { collectionMeta, documents } from './db/schema.js'; import { ProjectJwtVerifier } from './jwt.js'; @@ -957,7 +957,17 @@ export class DbCollection extends LiveShard { owner: existing.owner, upsert: false, }); - return this.withLsn(Response.json(written)); + // The merged document is a read the write gate never authorized. + const readable = + this.config !== null && + (await mayReadBack( + request, + this.config.readAccess, + this.config.readPermission, + this.getVerifier(), + existing.owner, + )); + return this.withLsn(Response.json(readable ? written : { id: docId })); } private async handleDelete(docId: string, owner: string | null): Promise { diff --git a/agents/db/src/live.ts b/agents/db/src/live.ts index e436dcc..65802ba 100644 --- a/agents/db/src/live.ts +++ b/agents/db/src/live.ts @@ -208,6 +208,17 @@ export abstract class LiveShard extends DurableObject { | { ok: false; code: 'unauthorized'; message: string } > { if (gate.readAccess === 'public') return { ok: true, ownerSub: null, tokenExp: null }; + // `none` closes the public read plane outright, exactly as checkAccess + // does for REST - and BEFORE the token is read, because no token opens + // it. Without this a closed collection streamed its snapshot and every + // later write to any caller holding a valid token, a guest's included. + if (gate.readAccess === 'none') { + return { + ok: false, + code: 'unauthorized', + message: 'this collection is not readable over the public API - it is operator-only', + }; + } if (!token) { return { ok: false, diff --git a/agents/db/src/table.ts b/agents/db/src/table.ts index 466e616..8c62fd5 100644 --- a/agents/db/src/table.ts +++ b/agents/db/src/table.ts @@ -3,7 +3,7 @@ import { getAgentByName, type AgentNamespace } from 'agents'; import { migrate } from 'drizzle-orm/durable-sqlite/migrator'; import { z } from 'zod'; import migrations from './migrations.js'; -import { checkAccess, corsHeadersFor, drainUnusedBody, withCors } from './access.js'; +import { checkAccess, corsHeadersFor, drainUnusedBody, mayReadBack, withCors } from './access.js'; import { primaryLocation } from './colo.js'; import { collectionMeta } from './db/schema.js'; import { ProjectJwtVerifier } from './jwt.js'; @@ -984,7 +984,17 @@ export class DbTable extends LiveShard { const written = await this.writeRow(rowId, merged, { owner: (existing.owner as string | null) ?? null, }); - return this.withLsn(Response.json(written)); + // The merged row is a read the write gate never authorized. + const readable = + !!this.config && + (await mayReadBack( + request, + this.config.readAccess, + this.config.readPermission, + this.getVerifier(), + (existing.owner as string | null) ?? null, + )); + return this.withLsn(Response.json(readable ? written : { id: rowId })); } catch (error) { return this.uniqueViolationResponse(error) ?? this.rethrow(error); } @@ -1109,31 +1119,40 @@ export class DbTable extends LiveShard { prepared.push({ ...gate, params: statement.params ?? [] }); } - // A batch carrying ANY write is judged on the write side - a mixed batch - // is a write. + // Each side a batch touches is judged on its OWN mode. A batch used to be + // judged on the write side alone whenever it carried any write, which let + // a SELECT ride inside a write batch past a read mode that refuses it. + const wantsRead = prepared.some((statement) => statement.kind === 'select'); const wantsWrite = prepared.some((statement) => statement.kind !== 'select'); - const mode = wantsWrite ? config.writeAccess : config.readAccess; + const sides: ('read' | 'write')[] = [ + ...(wantsWrite ? (['write'] as const) : []), + ...(wantsRead ? (['read'] as const) : []), + ]; // This path deliberately does NOT go through checkAccess (raw SQL always // demands a token, whatever the mode says), so every mode the gate // refuses has to be refused again HERE. Miss one and raw SQL becomes the // way around it - which is exactly the bypass `none` exists to prevent. - if (mode === 'owner') { - return Response.json( - { success: false, error: 'owner-scoped tables refuse raw SQL - use the typed API' }, - { status: 403 }, - ); - } - if (mode === 'none') { - return Response.json( - { - success: false, - error: wantsWrite - ? 'this table is read-only over the public API' - : 'this table is not readable over the public API', - }, - { status: 403 }, - ); + for (const side of sides) { + const mode = side === 'write' ? config.writeAccess : config.readAccess; + if (mode === 'owner') { + return Response.json( + { success: false, error: 'owner-scoped tables refuse raw SQL - use the typed API' }, + { status: 403 }, + ); + } + if (mode === 'none') { + return Response.json( + { + success: false, + error: + side === 'write' + ? 'this table is read-only over the public API' + : 'this table is not readable over the public API', + }, + { status: 403 }, + ); + } } const header = request.headers.get('authorization'); @@ -1157,16 +1176,34 @@ export class DbTable extends LiveShard { { status: verified.code === 'not-configured' ? 503 : 401 }, ); } - const required = wantsWrite ? config.writePermission : config.readPermission; - if (!hasPermission(required, verified.claims.permissions)) { - return Response.json( - { success: false, error: 'the token does not carry the required permission' }, - { status: 403 }, - ); + for (const side of sides) { + const required = side === 'write' ? config.writePermission : config.readPermission; + if (!hasPermission(required, verified.claims.permissions)) { + return Response.json( + { success: false, error: 'the token does not carry the required permission' }, + { status: 403 }, + ); + } } + // Every write comes back with RETURNING over the full row, and that is a + // READ. On a table the caller may write but not read - `readAccess: + // 'none'` is append-only ingest, `owner` hides other people's rows - the + // write still lands but its rows do not come back; otherwise + // `UPDATE t SET c = c` would read the whole table out. + const mayReadBack = + config.readAccess !== 'none' && + config.readAccess !== 'owner' && + hasPermission(config.readPermission, verified.claims.permissions); + try { const outcome = this.runSqlStatements(prepared); + if (!mayReadBack) { + for (const result of outcome.results) { + result.results = []; + result.raw = []; + } + } for (const notice of outcome.notifications) { if (notice.kind === 'delete') { await this.notifySubscribers(notice.row, null); diff --git a/e2e/db-readonly.api.spec.ts b/e2e/db-readonly.api.spec.ts index f36e6a5..521cd9d 100644 --- a/e2e/db-readonly.api.spec.ts +++ b/e2e/db-readonly.api.spec.ts @@ -15,9 +15,11 @@ import { dbDocumentPath, dbDocumentsPath, dbQueryPath, + dbRowPath, dbRowsPath, uniqueEmail } from './helpers'; +import { LiveSocket, WEB_WS } from './live-socket'; /** * The `none` access mode - the closed one. @@ -214,6 +216,155 @@ test.describe('db agent (the none access mode)', () => { expect(docs.some((doc: { id: string }) => doc.id === `report-${run}`)).toBeTruthy(); }); + test('a closed collection or table cannot be read through a live subscription', async ({ + request, + baseURL + }) => { + const collection = `livein-${run}`; + const table = `liveint-${run}`; + const provisionCollection = await request.put(dbAdminCollectionPath(DB_PROJECT, collection), { + data: { readAccess: 'none', writeAccess: 'public', replication: 'off' } + }); + expect(provisionCollection.ok(), await provisionCollection.text()).toBeTruthy(); + const declareTable = await request.put(dbAdminTablePath(DB_PROJECT, table), { + data: { + readAccess: 'none', + writeAccess: 'auth', + replication: 'off', + columns: [{ name: 'message', type: 'text' }] + } + }); + expect(declareTable.ok(), await declareTable.text()).toBeTruthy(); + + const seedDoc = await request.put(adminDocumentPath(collection, 'secret-doc'), { + data: { data: { message: 'operator eyes only' } } + }); + expect(seedDoc.ok(), await seedDoc.text()).toBeTruthy(); + const seedRow = await request.put(dbAdminTableRowPath(DB_PROJECT, table, 'secret-row'), { + data: { data: { message: 'operator eyes only' } } + }); + expect(seedRow.ok(), await seedRow.text()).toBeTruthy(); + + // The socket re-implements the read gate rather than calling + // checkAccess, so it is attacked with a real token on both doors: the + // one-socket gateway and the table's own direct socket. + const token = await projectUserToken(baseURL, 'readonly-live'); + const gateway = await LiveSocket.connect( + `${WEB_WS}/agents/db-agent/${DB_PROJECT}/realtime?cfb-region=weur` + ); + const direct = await LiveSocket.connect( + `${WEB_WS}/agents/db-agent/${DB_PROJECT}/tables/${table}/subscribe` + ); + try { + gateway.send({ + type: 'subscribe', + id: 'c1', + shard: { kind: 'collection', name: collection }, + query: {}, + token + }); + gateway.send({ + type: 'subscribe', + id: 't1', + shard: { kind: 'table', name: table }, + query: {}, + token + }); + direct.send({ type: 'subscribe', id: 's1', query: {}, token }); + + for (const [socket, id] of [ + [gateway, 'c1'], + [gateway, 't1'], + [direct, 's1'] + ] as const) { + const refused = await socket.next( + (frame) => frame.id === id && (frame.type === 'error' || frame.type === 'snapshot'), + `the answer to ${id}` + ); + expect(refused.type, `${id} must be refused, not snapshotted`).toBe('error'); + expect(refused.code).toBe('unauthorized'); + } + } finally { + gateway.close(); + direct.close(); + } + }); + + test('an ingest table or collection cannot be read back through a write', async ({ + request, + baseURL + }) => { + const table = `inbox-${run}`; + const collection = `inboxc-${run}`; + const declare = await request.put(dbAdminTablePath(DB_PROJECT, table), { + data: { + readAccess: 'none', + writeAccess: 'auth', + replication: 'off', + columns: [{ name: 'message', type: 'text' }] + } + }); + expect(declare.ok(), await declare.text()).toBeTruthy(); + const provision = await request.put(dbAdminCollectionPath(DB_PROJECT, collection), { + data: { readAccess: 'none', writeAccess: 'auth', replication: 'off' } + }); + expect(provision.ok(), await provision.text()).toBeTruthy(); + + // Somebody else's submissions - the thing the attacker is after. + const seedRow = await request.put(dbAdminTableRowPath(DB_PROJECT, table, 'victim-row'), { + data: { data: { message: 'someone else wrote this' } } + }); + expect(seedRow.ok(), await seedRow.text()).toBeTruthy(); + const seedDoc = await request.put(adminDocumentPath(collection, 'victim-doc'), { + data: { data: { message: 'someone else wrote this' } } + }); + expect(seedDoc.ok(), await seedDoc.text()).toBeTruthy(); + + const token = await projectUserToken(baseURL, 'readonly-readback'); + const anon = await anonymousContext(baseURL); + try { + const authed = { authorization: `Bearer ${token}` }; + + // A write is allowed, and a no-op UPDATE over every row used to answer + // with every row - RETURNING is appended to all DML. + const dump = await anon.post(sqlPath(table), { + headers: authed, + data: { sql: `UPDATE "${table}" SET message = message` } + }); + expect(dump.ok(), await dump.text()).toBeTruthy(); + const dumped = (await dump.json()).result; + expect(dumped.results).toEqual([]); + expect(dumped.raw).toEqual([]); + expect(JSON.stringify(dumped)).not.toContain('someone else wrote this'); + + // A SELECT hidden in a write batch is judged as the read it is. + const smuggled = await anon.post(sqlPath(table), { + headers: authed, + data: { + batch: [ + { sql: `SELECT message FROM "${table}"` }, + { sql: `UPDATE "${table}" SET message = message WHERE 0` } + ] + } + }); + expect(smuggled.status()).toBe(403); + + // The typed update merges over fields the caller never sent; an empty + // PATCH must not hand them back. + for (const [label, path] of [ + ['row', dbRowPath(DB_PROJECT, table, 'victim-row')], + ['document', dbDocumentPath(DB_PROJECT, collection, 'victim-doc')] + ] as const) { + const patched = await anon.patch(path, { headers: authed, data: {} }); + expect(patched.ok(), `${label}: ${await patched.text()}`).toBeTruthy(); + const body = await patched.json(); + expect(body, label).toEqual({ id: label === 'row' ? 'victim-row' : 'victim-doc' }); + } + } finally { + await anon.dispose(); + } + }); + test('raw SQL cannot write a read-only table', async ({ request, baseURL }) => { const table = `catalog-${run}`; const declare = await request.put(dbAdminTablePath(DB_PROJECT, table), { diff --git a/src/lib/agents.ts b/src/lib/agents.ts index 524d471..eb69896 100644 --- a/src/lib/agents.ts +++ b/src/lib/agents.ts @@ -243,6 +243,18 @@ export const dbDocumentSchema = z }) .meta({ id: 'DbDocument', description: 'A document: metadata outside data, no collisions.' }); +export const dbWriteAckSchema = z.object({ id: z.string() }).meta({ + id: 'DbWriteAck', + description: + "The write landed, but the caller may not read the record back (readAccess `none`, or another owner's record under `owner` reads), so only its id is returned." +}); + +export const dbWriteResultSchema = z.union([dbDocumentSchema, dbWriteAckSchema]).meta({ + id: 'DbWriteResult', + description: + 'An update answers with the full record when the caller may read it, otherwise only its id - the merged record is a read the write gate never authorized.' +}); + export const dbQueryResultSchema = z .object({ docs: z.array(dbDocumentSchema), nextCursor: z.string().optional() }) .meta({ id: 'DbQueryResult' }); diff --git a/src/lib/openapi/db.ts b/src/lib/openapi/db.ts index 842ca97..4dff96b 100644 --- a/src/lib/openapi/db.ts +++ b/src/lib/openapi/db.ts @@ -5,6 +5,8 @@ import { dbCollectionConfigSchema, dbCreateRequestSchema, dbDocumentSchema, + dbWriteAckSchema, + dbWriteResultSchema, dbFieldRuleSchema, dbImportReportSchema, dbOverviewSchema, @@ -100,6 +102,8 @@ export const dbOpenApi: AgentOpenApiModule = { schemas: [ dbQuerySchema, dbDocumentSchema, + dbWriteAckSchema, + dbWriteResultSchema, dbQueryResultSchema, dbCreateRequestSchema, dbWriteRequestSchema, @@ -162,7 +166,10 @@ export const dbOpenApi: AgentOpenApiModule = { security: PUBLIC_SECURITY, requestBody: jsonBody(dbWriteRequestSchema, 'The full replacement data.'), responses: { - '200': jsonResponse(dbDocumentSchema, 'The updated document.'), + '200': jsonResponse( + dbWriteResultSchema, + 'The updated document, or only its id when the caller may not read it back.' + ), '404': { description: 'No such document.' } } }, @@ -173,7 +180,10 @@ export const dbOpenApi: AgentOpenApiModule = { security: PUBLIC_SECURITY, requestBody: jsonBody(dbWriteRequestSchema, 'Fields to shallow-merge.'), responses: { - '200': jsonResponse(dbDocumentSchema, 'The updated document.'), + '200': jsonResponse( + dbWriteResultSchema, + 'The updated document, or only its id when the caller may not read it back.' + ), '404': { description: 'No such document.' } } }, @@ -267,7 +277,10 @@ export const dbOpenApi: AgentOpenApiModule = { security: PUBLIC_SECURITY, requestBody: jsonBody(dbWriteRequestSchema, 'The full replacement column map.'), responses: { - '200': jsonResponse(dbDocumentSchema, 'The updated row.'), + '200': jsonResponse( + dbWriteResultSchema, + 'The updated row, or only its id when the caller may not read it back.' + ), '400': { description: 'The row failed the declared schema.' }, '404': { description: 'No such row.' }, '409': { description: 'Unique-column conflict.' } @@ -280,7 +293,10 @@ export const dbOpenApi: AgentOpenApiModule = { security: PUBLIC_SECURITY, requestBody: jsonBody(dbWriteRequestSchema, 'Columns to set; the rest keep their values.'), responses: { - '200': jsonResponse(dbDocumentSchema, 'The updated row.'), + '200': jsonResponse( + dbWriteResultSchema, + 'The updated row, or only its id when the caller may not read it back.' + ), '400': { description: 'The merged row failed the declared schema.' }, '404': { description: 'No such row.' }, '409': { description: 'Unique-column conflict.' } @@ -331,7 +347,7 @@ export const dbOpenApi: AgentOpenApiModule = { tags: [DB_TAG], summary: 'Run single-table SQL (ORM-grade, D1-shaped)', description: - 'One SELECT/INSERT/UPDATE/DELETE (or an atomic `batch`) over this table alone - what `@frostbase-dev/db/drizzle` drives. DML gains automatic RETURNING and feeds the change log and live queries. ALWAYS requires a project JWT (public modes never open raw SQL); owner-scoped tables refuse it. Results carry objects plus `raw` value arrays with `columns` order for drivers. SELECTs serve from region replicas when replication is on.', + 'One SELECT/INSERT/UPDATE/DELETE (or an atomic `batch`) over this table alone - what `@frostbase-dev/db/drizzle` drives. DML gains automatic RETURNING and feeds the change log and live queries; on a table whose read mode the caller does not pass (`none`, `owner`, or a missing read permission) writes still land but return no rows. ALWAYS requires a project JWT (public modes never open raw SQL); owner-scoped tables refuse it. Results carry objects plus `raw` value arrays with `columns` order for drivers. SELECTs serve from region replicas when replication is on.', parameters: [tableParam], security: PUBLIC_SECURITY, requestBody: { From eaf28bfe7dcb4808a317f8843890822d4a54606e Mon Sep 17 00:00:00 2001 From: clibequilibrium <105135724+clibequilibrium@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:29:16 -0500 Subject: [PATCH 2/8] db: refuse recursive CTEs on the public SQL paths The raw-SQL gate admitted `WITH RECURSIVE`, and a table's /sql and a view's /sql run synchronously inside a single-threaded Durable Object. `WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT count(*) FROM c` never terminates on its own, so any project token - a free guest token is enough - could hold a tenant's table until the runtime's CPU limit, and then do it again. This was reproduced on the local stack: with the old gate, the new e2e case froze the shard and every later SQL test in the run timed out. publicSqlRefusal binds only the public paths; operator SQL (console, copilot) keeps the full dialect. It is the same literal word match the internal-name scan uses, so a literal "recursive" has to be bound as a parameter. --- agents/db/src/table-sql.ts | 18 ++++++++++++++++++ agents/db/src/table-sql.unit.test.ts | 25 ++++++++++++++++++++++++- agents/db/src/table.ts | 4 +++- agents/db/src/view.ts | 4 +++- e2e/db-tables-sql.api.spec.ts | 7 ++++++- 5 files changed, 54 insertions(+), 4 deletions(-) diff --git a/agents/db/src/table-sql.ts b/agents/db/src/table-sql.ts index eee351e..f775355 100644 --- a/agents/db/src/table-sql.ts +++ b/agents/db/src/table-sql.ts @@ -126,6 +126,24 @@ function gateStatement(rawSql: string, selectOnly: boolean): PreparedSql { return { ok: true, kind, sql }; } +/** + * Refusals that bind the PUBLIC SQL paths only (a table's `/sql`, a view's), + * layered on top of the shared gate; operator SQL keeps the full dialect. + * + * A recursive CTE is the one construct whose cost is unbounded by anything + * the caller has to supply: `WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL + * SELECT x + 1 FROM c) SELECT count(*) FROM c` never terminates on its own, + * and it runs synchronously inside a single-threaded shard - so any guest + * token could hold a tenant's table until the runtime's CPU limit, then do it + * again. Same dumb word match as the internal-name scan, literals included. + */ +export function publicSqlRefusal(rawSql: string): string | null { + if (/\brecursive\b/i.test(rawSql)) { + return 'recursive CTEs do not run on the public API - if you meant the literal string, bind it as a parameter'; + } + return null; +} + /** * The join-view gate (JOIN1): SELECT only, over the view's own SQLite. * diff --git a/agents/db/src/table-sql.unit.test.ts b/agents/db/src/table-sql.unit.test.ts index 86c9ef8..0d509b6 100644 --- a/agents/db/src/table-sql.unit.test.ts +++ b/agents/db/src/table-sql.unit.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { prepareTableSql, prepareViewSql } from './table-sql.js'; +import { prepareTableSql, prepareViewSql, publicSqlRefusal } from './table-sql.js'; import { compileTableAggregate } from './table-query.js'; import { tableColumnsSchema, type TableColumn } from './schemas.js'; @@ -249,3 +249,26 @@ test('table aggregates: typed columns sum directly, json paths stay gated', () = ); assert.equal(unknown.ok, false); }); + +test('public sql: recursive CTEs are refused, ordinary CTEs and operator SQL are not', () => { + // The unbounded one: it never terminates on its own inside a shard. + for (const sql of [ + 'WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT count(*) FROM c', + 'with recursive c(x) as (select 1 union all select x+1 from c) select x from c', + 'WITH\nRECURSIVE c(x) AS (SELECT 1) SELECT x FROM c', + 'WITH a AS (SELECT 1), RECURSIVE b(x) AS (SELECT 1) SELECT 1', + ]) { + assert.match(publicSqlRefusal(sql) ?? '', /recursive CTEs/, sql); + } + assert.equal(publicSqlRefusal('WITH top AS (SELECT * FROM todos) SELECT * FROM top'), null); + assert.equal(publicSqlRefusal('SELECT * FROM todos WHERE title = ?'), null); + // The shared gate still admits it - the refusal binds the public paths only. + assert.equal( + prepareTableSql( + 'WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c LIMIT 3) SELECT x FROM c', + 'todos', + TODO, + ).ok, + true, + ); +}); diff --git a/agents/db/src/table.ts b/agents/db/src/table.ts index 8c62fd5..78c3d32 100644 --- a/agents/db/src/table.ts +++ b/agents/db/src/table.ts @@ -29,7 +29,7 @@ import { import { getPath, encodeCursor, decodeCursor, type DecodedCursor } from './query.js'; import { shardBookmarkForTime, shardCurrentBookmark, shardRestoreTo } from './pitr.js'; import { hasPermission } from './rules.js'; -import { prepareTableSql } from './table-sql.js'; +import { prepareTableSql, publicSqlRefusal } from './table-sql.js'; import { applyColumnDefaults, isDuplicateColumnError, @@ -1116,6 +1116,8 @@ export class DbTable extends LiveShard { if (!gate.ok) { return Response.json({ success: false, error: gate.error }, { status: 400 }); } + const refusal = publicSqlRefusal(statement.sql); + if (refusal) return Response.json({ success: false, error: refusal }, { status: 400 }); prepared.push({ ...gate, params: statement.params ?? [] }); } diff --git a/agents/db/src/view.ts b/agents/db/src/view.ts index e346325..4b40a21 100644 --- a/agents/db/src/view.ts +++ b/agents/db/src/view.ts @@ -17,7 +17,7 @@ import { } from './replication.js'; import { hasPermission } from './rules.js'; import { planDdl, quoteIdent, toSqlValue } from './table-schema.js'; -import { prepareViewSql } from './table-sql.js'; +import { prepareViewSql, publicSqlRefusal } from './table-sql.js'; import { logEntrySchema, storedViewConfigSchema, @@ -232,6 +232,8 @@ export class DbView extends DurableObject { for (const statement of statements) { const gate = prepareViewSql(statement.sql); if (!gate.ok) return Response.json({ success: false, error: gate.error }, { status: 400 }); + const refusal = publicSqlRefusal(statement.sql); + if (refusal) return Response.json({ success: false, error: refusal }, { status: 400 }); prepared.push({ sql: gate.sql, params: statement.params ?? [] }); } diff --git a/e2e/db-tables-sql.api.spec.ts b/e2e/db-tables-sql.api.spec.ts index 2d0bf1a..9bb20ec 100644 --- a/e2e/db-tables-sql.api.spec.ts +++ b/e2e/db-tables-sql.api.spec.ts @@ -178,7 +178,12 @@ test.describe('db agent (SQL endpoint)', () => { ['SELECT token_exp FROM subscriptions', 'internal storage'], ['DROP TABLE ' + table, 'SELECT, INSERT'], ['SELECT 1; SELECT 2', 'one statement'], - ['INSERT INTO elsewhere (id) VALUES (?)', 'must target'] + ['INSERT INTO elsewhere (id) VALUES (?)', 'must target'], + // Never terminates on its own, inside a single-threaded shard. + [ + 'WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) SELECT count(*) FROM c', + 'recursive CTEs' + ] ] as const) { const refusedSql = await anon.post(sqlPath(table), { headers: asUser, From 2f53f2d380c343347f6a3683b3e14d78ca99446e Mon Sep 17 00:00:00 2001 From: clibequilibrium <105135724+clibequilibrium@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:29:17 -0500 Subject: [PATCH 3/8] storage: inline rendering is an allowlist of exact types The serve-time allowlist accepted any `video/` and `audio/`, and the stored content type is whatever the uploader sent. `video/x+xml` therefore went out `Content-Disposition: inline` - and browsers render every `+xml` subtype as an XML document, so an XHTML body uploaded under that label runs script. On the managed service the agent object path shares the console's origin, which is exactly the stored-XSS-against-operators case the allowlist exists to prevent; any console sign-up could upload one to their own public bucket. The list moves to src/inline.ts as exact types (common video and audio spelled out) with a unit test that attacks it; the e2e disposition case gains the +xml vectors and failed on the old pattern ("inline" served). AGENTS.md now says why the list must never go back to a pattern. --- agents/storage/AGENTS.md | 16 +++--- agents/storage/package.json | 2 +- agents/storage/src/index.ts | 18 ++----- agents/storage/src/inline.ts | 60 +++++++++++++++++++++++ agents/storage/src/inline.unit.test.ts | 68 ++++++++++++++++++++++++++ e2e/storage.api.spec.ts | 5 ++ 6 files changed, 146 insertions(+), 23 deletions(-) create mode 100644 agents/storage/src/inline.ts create mode 100644 agents/storage/src/inline.unit.test.ts diff --git a/agents/storage/AGENTS.md b/agents/storage/AGENTS.md index 8b5b51c..bd76b0c 100644 --- a/agents/storage/AGENTS.md +++ b/agents/storage/AGENTS.md @@ -28,13 +28,15 @@ serving. `src/agent.ts` is control plane only. no `.`/`..` segments, no empty segments, no leading/trailing slashes, no control characters, and the full key stays under R2's 1024-byte ceiling. Use the normalized key `parseObjectKey` returns — never the raw path. -- **Inline rendering is an allowlist**, not a denylist: raster images, video, - audio, `text/plain`, PDF. Everything else goes out - `Content-Disposition: attachment`, and every object response carries - `X-Content-Type-Options: nosniff`. HTML, SVG, and anything `+xml` are absent - by design — on the managed service the agent path shares the console's origin, - so an attacker-uploaded HTML file rendered inline is stored XSS against every - operator session. +- **Inline rendering is an allowlist of exact types** (`src/inline.ts`), not a + denylist and not a pattern: raster images, common video and audio, `text/plain`, + PDF. Everything else goes out `Content-Disposition: attachment`, and every + object response carries `X-Content-Type-Options: nosniff`. HTML, SVG, and + anything `+xml` are absent by design — on the managed service the agent path + shares the console's origin, so an attacker-uploaded HTML file rendered inline + is stored XSS against every operator session. Never widen it back to a + `video/*`-style pattern: browsers render *any* `+xml` subtype as an XML + document, so `video/x+xml` carrying XHTML runs script. - **The R2 bucket must NEVER carry r2.dev or a custom domain.** That serves every tenant's keys raw, bypassing all of the above. `STORAGE_SERVE_DOMAIN` is a *worker* route with identical enforcement. diff --git a/agents/storage/package.json b/agents/storage/package.json index 800ca9a..72b81b4 100644 --- a/agents/storage/package.json +++ b/agents/storage/package.json @@ -52,7 +52,7 @@ "scripts": { "build": "tsc -p tsconfig.build.json", "typecheck": "tsc --noEmit", - "test:unit": "node --import tsx --test src/route-access.unit.test.ts src/access.unit.test.ts src/keys.unit.test.ts src/signing.unit.test.ts src/reconcile.unit.test.ts", + "test:unit": "node --import tsx --test src/route-access.unit.test.ts src/access.unit.test.ts src/inline.unit.test.ts src/keys.unit.test.ts src/signing.unit.test.ts src/reconcile.unit.test.ts", "prepublishOnly": "npm run build", "deploy": "wrangler deploy", "deploy:preview": "wrangler deploy --env preview", diff --git a/agents/storage/src/index.ts b/agents/storage/src/index.ts index 0c01cf3..79edf02 100644 --- a/agents/storage/src/index.ts +++ b/agents/storage/src/index.ts @@ -14,6 +14,7 @@ import { demoRefusal, type DemoObjectSummary, } from './demo.js'; +import { contentDisposition } from './inline.js'; import { gateOperatorRoutes } from './route-access.js'; import { DEMO_PROJECT_PATTERN, @@ -96,14 +97,6 @@ const NEGATIVE_CACHE_TTL_MS = 5_000; const ACCESS_CACHE_MAX = 5_000; const DEFAULT_PUBLIC_CACHE_CONTROL = 'public, max-age=60'; -/** - * Content types a browser may render INLINE from our origin. Everything else - * downloads. Notably absent by design: text/html, image/svg+xml, anything - * +xml (all scriptable), text/css and javascript (style/script injection). - */ -const INLINE_CONTENT_TYPES = - /^(image\/(png|jpe?g|gif|webp|avif|bmp|x-icon)|video\/[a-z0-9.+-]+|audio\/[a-z0-9.+-]+|text\/plain|application\/pdf)$/i; - interface AccessCacheEntry { answer: BucketAccessAnswer; expires: number; @@ -433,9 +426,7 @@ class StorageService extends WorkerEntrypoint { etag: summary.etag, 'accept-ranges': 'bytes', 'x-content-type-options': 'nosniff', - 'content-disposition': INLINE_CONTENT_TYPES.test(summary.contentType) - ? 'inline' - : 'attachment', + 'content-disposition': contentDisposition(summary.contentType), 'cache-control': DEFAULT_PUBLIC_CACHE_CONTROL, 'content-length': String(summary.size), }); @@ -1263,10 +1254,7 @@ class StorageService extends WorkerEntrypoint { // Serve-time policy, not write-time: presigned writes (S2.5) bypass // write-time checks by design, so the serving layer decides what may // render inline - and HTML/SVG/XML never do. - headers.set( - 'content-disposition', - INLINE_CONTENT_TYPES.test(contentType) ? 'inline' : 'attachment', - ); + headers.set('content-disposition', contentDisposition(contentType)); headers.set( 'cache-control', publicRead ? (config.cacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL) : 'private, no-store', diff --git a/agents/storage/src/inline.ts b/agents/storage/src/inline.ts new file mode 100644 index 0000000..6a40da0 --- /dev/null +++ b/agents/storage/src/inline.ts @@ -0,0 +1,60 @@ +/** + * Which stored content types a browser may render INLINE from our origin. + * Everything else goes out `Content-Disposition: attachment`. + * + * The stored type is whatever the uploader sent, and on the managed service + * the object path shares the console's origin - so anything scriptable that + * renders inline is stored XSS against every operator session. Absent by + * design: text/html, image/svg+xml, text/css, javascript. + * + * This is a list of EXACT types, not a pattern over a top-level type. It used + * to accept any `video/` and `audio/`, which admitted + * `video/x+xml`: browsers treat every `+xml` subtype as an XML document, and + * an XHTML body served that way runs its scripts. + */ +const INLINE_CONTENT_TYPES = new Set([ + 'image/png', + 'image/jpeg', + 'image/jpg', + 'image/gif', + 'image/webp', + 'image/avif', + 'image/bmp', + 'image/x-icon', + 'video/mp4', + 'video/webm', + 'video/ogg', + 'video/quicktime', + 'video/mpeg', + 'video/x-matroska', + 'video/3gpp', + 'video/3gpp2', + 'video/mp2t', + 'audio/mpeg', + 'audio/mp4', + 'audio/aac', + 'audio/ogg', + 'audio/opus', + 'audio/wav', + 'audio/x-wav', + 'audio/webm', + 'audio/flac', + 'audio/x-flac', + 'audio/x-m4a', + 'audio/3gpp', + 'audio/aiff', + 'audio/x-aiff', + 'text/plain', + 'application/pdf', +]); + +/** True only for an exact allowlisted type - parameters, whitespace or any + * other spelling download rather than render. */ +export function rendersInline(contentType: string): boolean { + return INLINE_CONTENT_TYPES.has(contentType.toLowerCase()); +} + +/** The serve-time disposition for a stored content type. */ +export function contentDisposition(contentType: string): 'inline' | 'attachment' { + return rendersInline(contentType) ? 'inline' : 'attachment'; +} diff --git a/agents/storage/src/inline.unit.test.ts b/agents/storage/src/inline.unit.test.ts new file mode 100644 index 0000000..5a72e21 --- /dev/null +++ b/agents/storage/src/inline.unit.test.ts @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { contentDisposition } from './inline.js'; + +/** The stored type is uploader-chosen and the agent path shares the console's + * origin, so every refusal here is a stored-XSS vector closed. */ + +test('scriptable types never render inline', () => { + for (const type of [ + 'text/html', + 'TEXT/HTML', + 'application/xhtml+xml', + 'image/svg+xml', + 'text/xml', + 'application/xml', + 'text/css', + 'text/javascript', + 'application/javascript', + 'application/octet-stream', + ]) { + assert.equal(contentDisposition(type), 'attachment', type); + } +}); + +test('an +xml subtype under video/ or audio/ is not a media type', () => { + // Browsers render ANY +xml subtype as an XML document, top-level type + // regardless - the old video/* and audio/* patterns served these inline. + for (const type of [ + 'video/x+xml', + 'video/xhtml+xml', + 'audio/a+xml', + 'video/svg+xml', + 'audio/mpeg+xml', + ]) { + assert.equal(contentDisposition(type), 'attachment', type); + } +}); + +test('near-miss spellings download rather than render', () => { + for (const type of [ + ' image/png', + 'image/png; charset=utf-8', + 'image/png\n', + 'image/pngx', + 'video/', + 'video/mp4/x', + '', + ]) { + assert.equal(contentDisposition(type), 'attachment', JSON.stringify(type)); + } +}); + +test('ordinary media, text and PDF still render inline', () => { + for (const type of [ + 'image/png', + 'IMAGE/PNG', + 'image/jpeg', + 'image/webp', + 'video/mp4', + 'video/webm', + 'audio/mpeg', + 'audio/ogg', + 'text/plain', + 'application/pdf', + ]) { + assert.equal(contentDisposition(type), 'inline', type); + } +}); diff --git a/e2e/storage.api.spec.ts b/e2e/storage.api.spec.ts index 742f738..8e179be 100644 --- a/e2e/storage.api.spec.ts +++ b/e2e/storage.api.spec.ts @@ -410,6 +410,11 @@ test.describe('storage agent (S1)', () => { { key: `${run}/page.html`, type: 'text/html', disposition: 'attachment' }, { key: `${run}/vector.svg`, type: 'image/svg+xml', disposition: 'attachment' }, { key: `${run}/feed.xml`, type: 'application/xml', disposition: 'attachment' }, + // Any +xml subtype renders as an XML document whatever its top-level + // type, so an XHTML body behind a "video" label is still script. + { key: `${run}/clip.xhtml`, type: 'video/x+xml', disposition: 'attachment' }, + { key: `${run}/track.xhtml`, type: 'audio/a+xml', disposition: 'attachment' }, + { key: `${run}/clip.mp4`, type: 'video/mp4', disposition: 'inline' }, { key: `${run}/note.txt`, type: 'text/plain', disposition: 'inline' }, { key: `${run}/doc.pdf`, type: 'application/pdf', disposition: 'inline' } ]; From 5b9d0fccc5e81c65a7f92a274db87ed11403363f Mon Sep 17 00:00:00 2001 From: clibequilibrium <105135724+clibequilibrium@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:29:52 -0500 Subject: [PATCH 4/8] console: unowned projects belong to the console admin Registry rows with a null org predate organizations (or were released by a console reset) and were open to ANY operator - "the self-hosted contract, where every operator is the same person". The managed console runs CONSOLE_SIGNUPS=open, where every stranger who registers is an operator, so any such row was full operator access for anyone with an account. The same assumption sat in the dashboard overview: an account with no active org called listProjects with no scope at all, which returns the whole registry - every tenant's project names and ids. Both legitimate holders of an unowned row are the console admin (the first account on a single-operator install is made admin automatically, and so is the owner reclaiming a reset console), so the admin role is now the key whatever the sign-up mode: the guard refuses everyone else, operator lists take an explicit ProjectScope that can never be "unscoped", and a non-admin with no org may not mint an unowned row it could never open. The rule is a pure module pinned by a unit test. Not covered end to end: the e2e stack has no way to create an unowned row through the API, which is the point. --- package.json | 2 +- src/hooks.server.ts | 14 ++++-- src/lib/server/project-scope.ts | 35 +++++++++++++ src/lib/server/project-scope.unit.test.ts | 49 +++++++++++++++++++ src/lib/server/registry.ts | 32 +++++++----- .../(app)/dashboard/(account)/+page.server.ts | 13 +++-- .../dashboard/[projectId]/+layout.server.ts | 6 +-- src/routes/api/registry/projects/+server.ts | 25 +++++++--- 8 files changed, 144 insertions(+), 32 deletions(-) create mode 100644 src/lib/server/project-scope.ts create mode 100644 src/lib/server/project-scope.unit.test.ts diff --git a/package.json b/package.json index 691048a..de63637 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "cf-typegen": "wrangler types ./src/worker-configuration.d.ts", "postinstall": "cross-env POSTINSTALL=true node scripts/dev.js", "test": "playwright test", - "test:unit": "node --import tsx --test src/lib/server/crawler.unit.test.ts src/lib/stale-build.unit.test.ts", + "test:unit": "node --import tsx --test src/lib/server/crawler.unit.test.ts src/lib/stale-build.unit.test.ts src/lib/server/project-scope.unit.test.ts", "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui", "deploy:production": "npm run build && wrangler deploy --env production" diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 8360cfb..165b0b7 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -11,7 +11,12 @@ import { agentFetcher, agentUrl, serverError } from '$lib/server/agents'; import { isDemoMode, isDemoProjectId, resolveConsoleIdentity } from '$lib/server/console'; import { guardConsoleClaim } from '$lib/server/console-setup'; import { isServiceKeySurface, verifyServiceKey } from '$lib/server/service-keys'; -import { getProjectOwnership, projectExists, type ProjectOwnership } from '$lib/server/registry'; +import { + getProjectOwnership, + mayReachUnownedProjects, + projectExists, + type ProjectOwnership +} from '$lib/server/registry'; import { handleErrorWithSentry, initCloudflareSentryHandle, sentryHandle } from '@sentry/sveltekit'; import { redirect } from '@sveltejs/kit'; import { sequence } from '@sveltejs/kit/hooks'; @@ -548,11 +553,14 @@ const consoleGuardHandle: Handle = async ({ event, resolve }) => { if (!ownership.registered) return noSuchProject(access.kind); // Owned rows require membership in the owning org. Rows with a null - // org predate ownership and stay visible to any operator - the - // self-hosted contract, where every operator is the same person. + // org predate ownership (or were released by a console reset) and + // belong to the console admin alone - "any operator" stopped meaning + // "the same person" once sign-ups could be open. if (ownership.orgId) { const isMember = identity.organizations.some((org) => org.id === ownership.orgId); if (!isMember) return noSuchProject(access.kind); + } else if (!mayReachUnownedProjects(identity)) { + return noSuchProject(access.kind); } } return resolve(event); diff --git a/src/lib/server/project-scope.ts b/src/lib/server/project-scope.ts new file mode 100644 index 0000000..c2f9e1f --- /dev/null +++ b/src/lib/server/project-scope.ts @@ -0,0 +1,35 @@ +/** + * Who may see which registry rows - pure, so a unit test can pin it without + * a database or a Worker. + */ +import type { ConsoleIdentity } from '../console'; + +/** Which registry rows an operator-facing list may show. */ +export interface ProjectScope { + orgIds: string[]; + includeUnowned: boolean; +} + +/** + * Whether an operator may reach an unowned (org_id NULL) registry row. + * + * Those rows predate organizations, or were released by a console reset, and + * used to be open to ANY operator - "the self-hosted contract, where every + * operator is the same person". That premise fails the moment sign-ups are + * open: every stranger who registers is an operator. Both legitimate holders + * of such rows are the console admin (a single-operator install's first + * account is made admin automatically, and so is the owner reclaiming a reset + * console), so the admin role is the key, whatever the sign-up mode. + */ +export function mayReachUnownedProjects(identity: ConsoleIdentity | null): boolean { + return identity?.user.role === 'admin'; +} + +/** The project-list scope for an operator: their orgs' rows, plus unowned + * rows for the console admin only. */ +export function operatorProjectScope( + identity: ConsoleIdentity | null, + orgIds: string[] = identity?.organizations.map((org) => org.id) ?? [] +): ProjectScope { + return { orgIds, includeUnowned: mayReachUnownedProjects(identity) }; +} diff --git a/src/lib/server/project-scope.unit.test.ts b/src/lib/server/project-scope.unit.test.ts new file mode 100644 index 0000000..2728195 --- /dev/null +++ b/src/lib/server/project-scope.unit.test.ts @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import type { ConsoleIdentity } from '../console'; +import { mayReachUnownedProjects, operatorProjectScope } from './project-scope'; + +function identity(role: string, orgIds: string[]): ConsoleIdentity { + return { + user: { + id: 'u1', + email: 'u1@example.test', + name: 'U1', + role, + emailVerified: true, + image: null + }, + activeOrganizationId: orgIds[0] ?? null, + organizations: orgIds.map((id) => ({ id, name: id, slug: id, role: 'owner' })), + pendingInvitations: [] + }; +} + +// On an open-signup console every stranger who registers is an operator, so +// an unowned row open to "any operator" is open to the internet. +test('a self-registered operator never reaches unowned projects', () => { + for (const role of ['user', '', 'member', 'owner', 'Admin']) { + assert.equal(mayReachUnownedProjects(identity(role, ['org-a'])), false, role); + } + assert.equal(mayReachUnownedProjects(null), false); +}); + +test('only the console admin reaches unowned projects', () => { + assert.equal(mayReachUnownedProjects(identity('admin', [])), true); +}); + +test('an operator with no orgs gets an empty scope, never an unscoped one', () => { + const scope = operatorProjectScope(identity('user', [])); + assert.deepEqual(scope, { orgIds: [], includeUnowned: false }); +}); + +test('the scope carries the operator memberships, or an explicit override', () => { + assert.deepEqual(operatorProjectScope(identity('user', ['org-a', 'org-b'])), { + orgIds: ['org-a', 'org-b'], + includeUnowned: false + }); + assert.deepEqual(operatorProjectScope(identity('admin', ['org-a', 'org-b']), ['org-b']), { + orgIds: ['org-b'], + includeUnowned: true + }); +}); diff --git a/src/lib/server/registry.ts b/src/lib/server/registry.ts index 3c16ffd..9ba4706 100644 --- a/src/lib/server/registry.ts +++ b/src/lib/server/registry.ts @@ -7,13 +7,14 @@ import { } from '$lib/console'; import { AGENT_REGISTRY, type AppAgentEntry } from '$lib/agent-registry'; import type { RegistryProject } from '$lib/agents'; +import type { ProjectScope } from './project-scope'; import { getDb } from '$lib/server/db'; import { project, projectAgent } from '$lib/server/db/schema'; import { deleteProjectServiceKeys } from '$lib/server/service-keys'; import { requireAgent } from '$lib/server/agents'; import { projectIdSchema } from '$lib/schemas/auth'; import type { Cookies } from '@sveltejs/kit'; -import { and, asc, eq, inArray, isNotNull, isNull, or } from 'drizzle-orm'; +import { and, asc, eq, inArray, isNotNull, isNull, or, type SQL } from 'drizzle-orm'; import { z } from 'zod'; /** @@ -90,29 +91,34 @@ function toDto(row: { }; } +export { mayReachUnownedProjects, operatorProjectScope, type ProjectScope } from './project-scope'; + /** * Lists the installation's projects, oldest first. Returns an empty list * rather than throwing when the database cannot be reached, so a first-run * console renders its empty state instead of an error page. * - * `orgIds` scopes the list to rows those organizations own PLUS unowned - * (org_id NULL) legacy/self-hosted rows, which every operator may see. - * Omitting it returns everything - for callers that predate ownership or - * genuinely need the whole registry (the erase fan-out, tests). + * `scope` limits the list to rows the given organizations own, plus unowned + * (org_id NULL) rows when `includeUnowned` is set - see `operatorProjectScope` + * for who gets them. Omitting `scope` returns everything, and only callers + * that genuinely need the whole registry may do that (the erase fan-out, + * tests) - never an operator-facing list. */ export async function listProjects( platform: App.Platform | undefined, - orgIds?: string[] + scope?: ProjectScope ): Promise { try { + let where: SQL | undefined; + if (scope) { + const parts: SQL[] = []; + if (scope.orgIds.length) parts.push(inArray(project.orgId, scope.orgIds)); + if (scope.includeUnowned) parts.push(isNull(project.orgId)); + if (!parts.length) return []; + where = or(...parts); + } const db = await getDb(platform); - const scope = - orgIds === undefined - ? undefined - : orgIds.length - ? or(isNull(project.orgId), inArray(project.orgId, orgIds)) - : isNull(project.orgId); - const rows = await db.select().from(project).where(scope).orderBy(asc(project.createdAt)); + const rows = await db.select().from(project).where(where).orderBy(asc(project.createdAt)); return rows.map(toDto); } catch (cause) { // Degrading to "no projects" is right for a first run but wrong to do diff --git a/src/routes/(app)/dashboard/(account)/+page.server.ts b/src/routes/(app)/dashboard/(account)/+page.server.ts index 8c593c6..857954b 100644 --- a/src/routes/(app)/dashboard/(account)/+page.server.ts +++ b/src/routes/(app)/dashboard/(account)/+page.server.ts @@ -1,7 +1,7 @@ import { activeOrg } from '$lib/console'; import { isCrawler } from '$lib/server/crawler'; import { recordDemoProject } from '$lib/server/demo-log'; -import { listProjects } from '$lib/server/registry'; +import { listProjects, operatorProjectScope } from '$lib/server/registry'; import { redirect } from '@sveltejs/kit'; import type { PageServerLoad } from './$types'; @@ -50,14 +50,17 @@ export const load: PageServerLoad = async ({ cookies, locals, platform, request redirect(307, `/dashboard/${projectId}`); } - // The overview lists the ACTIVE org's projects (plus unowned rows every - // operator may see); accounts with no orgs - agents from before - // organizations - keep the unscoped list they always had. + // The overview lists the ACTIVE org's projects, plus unowned rows for the + // console admin. An account with no org gets no org rows - never the + // unscoped registry, which on an open-signup console is every tenant's. // The sidebar's org data comes from the (account) layout load; this page // adds the active org's project list and the invitation banner. const identity = locals.consoleIdentity; const active = identity ? activeOrg(identity) : null; - const projects = await listProjects(platform, active ? [active.id] : undefined); + const projects = await listProjects( + platform, + operatorProjectScope(identity ?? null, active ? [active.id] : []) + ); return { projects, diff --git a/src/routes/(app)/dashboard/[projectId]/+layout.server.ts b/src/routes/(app)/dashboard/[projectId]/+layout.server.ts index 81acbc8..9123d25 100644 --- a/src/routes/(app)/dashboard/[projectId]/+layout.server.ts +++ b/src/routes/(app)/dashboard/[projectId]/+layout.server.ts @@ -3,6 +3,7 @@ import { demoBranchContext, getBranchContext, listProjects, + operatorProjectScope, rememberDemoBranch } from '$lib/server/registry'; import type { LayoutServerLoad } from './$types'; @@ -36,10 +37,7 @@ export const load: LayoutServerLoad = async ({ cookies, params, platform, locals // visitors, and the installation's project registry must never appear // in their page data. locals.consoleUser - ? listProjects( - platform, - locals.consoleIdentity?.organizations.map((org) => org.id) - ) + ? listProjects(platform, operatorProjectScope(locals.consoleIdentity ?? null)) : Promise.resolve(null) ]); diff --git a/src/routes/api/registry/projects/+server.ts b/src/routes/api/registry/projects/+server.ts index 16780fe..a689ea1 100644 --- a/src/routes/api/registry/projects/+server.ts +++ b/src/routes/api/registry/projects/+server.ts @@ -1,5 +1,10 @@ import { activeOrg } from '$lib/console'; -import { createProject, listProjects } from '$lib/server/registry'; +import { + createProject, + listProjects, + mayReachUnownedProjects, + operatorProjectScope +} from '$lib/server/registry'; import type { RequestHandler } from './$types'; /** @@ -10,11 +15,11 @@ import type { RequestHandler } from './$types'; */ export const GET: RequestHandler = async ({ locals, platform }) => { - // Scoped to the operator's memberships plus unowned rows; an identity with - // no orgs (a pre-orgs agent, the 404 fallback) sees unowned rows only - - // which on a legacy install is everything. - const orgIds = locals.consoleIdentity?.organizations.map((org) => org.id); - return Response.json({ projects: await listProjects(platform, orgIds) }); + // Scoped to the operator's memberships; unowned rows only for the console + // admin (see mayReachUnownedProjects). + return Response.json({ + projects: await listProjects(platform, operatorProjectScope(locals.consoleIdentity)) + }); }; export const POST: RequestHandler = async ({ locals, platform, request }) => { @@ -22,6 +27,14 @@ export const POST: RequestHandler = async ({ locals, platform, request }) => { // (agents from before organizations) keep minting unowned rows - exactly // the legacy visibility they already have. const org = locals.consoleIdentity ? activeOrg(locals.consoleIdentity) : null; + // An unowned row is reachable by the console admin alone, so anyone else + // minting one would create a project they could never open again. + if (!org && !mayReachUnownedProjects(locals.consoleIdentity)) { + return Response.json( + { error: 'create or join an organization before creating a project' }, + { status: 409 } + ); + } const result = await createProject( platform, await request.json().catch(() => null), From 1597b19b2c4457a452de6551ab4a6d0a3b98cf11 Mon Sep 17 00:00:00 2001 From: clibequilibrium <105135724+clibequilibrium@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:29:52 -0500 Subject: [PATCH 5/8] console: redirect targets cannot leave the origin Two redirects were built from request input with checks a browser does not share: - /login?next= kept any value starting with "/" but not "//". Browsers treat "\" as "/" in http(s) URLs, so next=/%5Cevil.example sent a signed-in operator from the console straight to evil.example. - The cloudflarebase.com -> frostbase.dev 301 resolved the raw pathname as a URL reference against the canonical origin, so a request for //evil.example/x answered Location: https://evil.example/x on our domain (if the edge passes the doubled slash through). safeNext now resolves the value the way a browser will and keeps it only if it stayed on the origin; movedLocation appends the path to the fixed canonical origin instead of resolving it. Both live in a pure module with a unit test that walks the bypass spellings. --- package.json | 2 +- src/hooks.server.ts | 5 ++- src/lib/safe-redirect.ts | 43 ++++++++++++++++++++ src/lib/safe-redirect.unit.test.ts | 56 ++++++++++++++++++++++++++ src/routes/(app)/login/+page.server.ts | 7 +--- 5 files changed, 104 insertions(+), 9 deletions(-) create mode 100644 src/lib/safe-redirect.ts create mode 100644 src/lib/safe-redirect.unit.test.ts diff --git a/package.json b/package.json index de63637..a9e45d0 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "cf-typegen": "wrangler types ./src/worker-configuration.d.ts", "postinstall": "cross-env POSTINSTALL=true node scripts/dev.js", "test": "playwright test", - "test:unit": "node --import tsx --test src/lib/server/crawler.unit.test.ts src/lib/stale-build.unit.test.ts src/lib/server/project-scope.unit.test.ts", + "test:unit": "node --import tsx --test src/lib/server/crawler.unit.test.ts src/lib/stale-build.unit.test.ts src/lib/server/project-scope.unit.test.ts src/lib/safe-redirect.unit.test.ts", "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui", "deploy:production": "npm run build && wrangler deploy --env production" diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 165b0b7..657c1d4 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -22,6 +22,7 @@ import { redirect } from '@sveltejs/kit'; import { sequence } from '@sveltejs/kit/hooks'; import type { AppAgentEntry } from '$lib/agent-registry'; import type { Handle } from '@sveltejs/kit'; +import { movedLocation } from '$lib/safe-redirect'; let platform: App.Platform; @@ -669,10 +670,10 @@ const domainMoveHandle: Handle = async ({ event, resolve }) => { const moved = env?.MOVED_FROM_HOSTS?.split(',').map((host) => host.trim().toLowerCase()); if (!canonical || !moved?.includes(event.url.hostname.toLowerCase())) return resolve(event); if (/^\/(api|agents)(\/|$)/.test(event.url.pathname)) return resolve(event); - const target = new URL(`${event.url.pathname}${event.url.search}`, canonical); + const target = movedLocation(event.url.pathname, event.url.search, canonical); // 308 keeps the method for the odd form POST; navigations get a plain 301. const status = event.request.method === 'GET' || event.request.method === 'HEAD' ? 301 : 308; - return new Response(null, { status, headers: { location: target.href } }); + return new Response(null, { status, headers: { location: target } }); }; export const handle = sequence( diff --git a/src/lib/safe-redirect.ts b/src/lib/safe-redirect.ts new file mode 100644 index 0000000..19cb734 --- /dev/null +++ b/src/lib/safe-redirect.ts @@ -0,0 +1,43 @@ +/** + * Redirect targets the console builds from request input. Pure, so a unit + * test can pin every spelling that used to escape. + */ + +const PROBE_ORIGIN = 'https://same-origin.invalid'; + +/** + * A `?next=` value as a same-origin path, or the fallback. + * + * Checking the string's prefix is not enough: browsers treat `\` as `/` in + * http(s) URLs, so `/\evil.example` passed a "starts with `/`, not `//`" test + * and landed on evil.example. Resolve it the way a browser will, against a + * placeholder origin, and keep it only if it stayed there. + */ +export function safeNext(value: string | null, fallback = '/dashboard'): string { + if (!value || !value.startsWith('/')) return fallback; + // Backslashes and control characters have no business in a path we hand + // out, and each is a parser disagreement waiting for the next browser. + if (/[\\\u0000-\u001f\u007f]/.test(value)) return fallback; + let resolved: URL; + try { + resolved = new URL(value, PROBE_ORIGIN); + } catch { + return fallback; + } + if (resolved.origin !== PROBE_ORIGIN) return fallback; + return `${resolved.pathname}${resolved.search}${resolved.hash}`; +} + +/** + * The `Location` for a request on a moved hostname: the same path on the + * canonical origin. + * + * Resolving the raw pathname as a URL reference made `//evil.example/x` a + * network-path reference to evil.example. The canonical origin is fixed here + * and the path is only ever appended to it. + */ +export function movedLocation(pathname: string, search: string, canonicalOrigin: string): string { + const origin = new URL(canonicalOrigin).origin; + const path = `/${pathname.replace(/^[/\\]+/, '')}`; + return `${origin}${path}${search}`; +} diff --git a/src/lib/safe-redirect.unit.test.ts b/src/lib/safe-redirect.unit.test.ts new file mode 100644 index 0000000..ffcb320 --- /dev/null +++ b/src/lib/safe-redirect.unit.test.ts @@ -0,0 +1,56 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { movedLocation, safeNext } from './safe-redirect'; + +/** What a browser does with a Location header relative to the console. */ +function browserTarget(location: string): string { + return new URL(location, 'https://frostbase.dev/login').host; +} + +test('safeNext refuses every spelling that leaves the origin', () => { + for (const value of [ + '//evil.example', + '/\\evil.example', + '/\\/evil.example', + '\\\\evil.example', + '/%5Cevil.example'.replace('%5C', '\\'), + 'https://evil.example', + 'javascript:alert(1)', + '/\tevil', + '/\nevil', + 'evil.example', + '', + null + ]) { + const next = safeNext(value); + assert.equal(next, '/dashboard', JSON.stringify(value)); + } +}); + +test('safeNext keeps same-origin paths, query and hash intact', () => { + for (const [value, expected] of [ + ['/dashboard/e2e-seed', '/dashboard/e2e-seed'], + ['/cli-auth?port=4123&code=abc', '/cli-auth?port=4123&code=abc'], + ['/dashboard#members', '/dashboard#members'], + ['/a/../dashboard', '/dashboard'] + ] as const) { + const next = safeNext(value); + assert.equal(next, expected, value); + assert.equal(browserTarget(next), 'frostbase.dev', value); + } +}); + +test('movedLocation never leaves the canonical origin', () => { + for (const pathname of ['//evil.example/x', '///evil.example', '/\\evil.example', '/']) { + const location = movedLocation(pathname, '', 'https://frostbase.dev'); + assert.equal(browserTarget(location), 'frostbase.dev', pathname); + } +}); + +test('movedLocation keeps the path and query', () => { + assert.equal( + movedLocation('/docs/db', '?tab=sql', 'https://frostbase.dev'), + 'https://frostbase.dev/docs/db?tab=sql' + ); + assert.equal(movedLocation('/', '', 'https://frostbase.dev/'), 'https://frostbase.dev/'); +}); diff --git a/src/routes/(app)/login/+page.server.ts b/src/routes/(app)/login/+page.server.ts index 4c89d46..6c9554b 100644 --- a/src/routes/(app)/login/+page.server.ts +++ b/src/routes/(app)/login/+page.server.ts @@ -1,14 +1,9 @@ import { consoleAuthConfig, consoleOwnerExists, getConsoleIdentity } from '$lib/server/console'; import { CONSOLE_SETUP_COOKIE, consoleSetupState } from '$lib/server/console-setup'; +import { safeNext } from '$lib/safe-redirect'; import { redirect } from '@sveltejs/kit'; import type { PageServerLoad } from './$types'; -/** Same-origin paths only - never let ?next= drive an open redirect. */ -function safeNext(value: string | null): string { - if (!value || !value.startsWith('/') || value.startsWith('//')) return '/dashboard'; - return value; -} - /** * The console sign-in page. Sign-in, first-run owner claim, and - when the * console reports open sign-ups - registration all POST from the browser to From aa5778b043d3d79b218688f756fd19ff8ad8717a Mon Sep 17 00:00:00 2001 From: clibequilibrium <105135724+clibequilibrium@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:38:44 -0500 Subject: [PATCH 6/8] auth: an invitation id reaches only a proven inbox or the invite link On a claimed console (the self-host default) sign-up skips email verification, yet a pending invitation admits any sign-up for its address, /console/me listed invitations - ids included - by a bare email match, and Better Auth's accept-invitation only compares the session email with the invited one. Whoever registered an invited address before its owner could read the id and join the org with the invited role, reaching every project it owns. The id is now treated as the credential it is. /console/me lists invitations only for a verified address; an unverified account sees just the one whose id it presents (?invitation=, from the invite link). The console refuses Better Auth's by-email list-user-invitations. The invitation email links to /dashboard?invitation=, and the org page offers "Copy link" so consoles without outbound mail can hand it over. Residual: someone can still register an invited address first and so block its owner from signing up - squatting, no longer a takeover. orgs.api.spec.ts now asserts the unlinked list is empty, the by-email endpoint is closed, and the link resolves; against the old agent the first assertion failed with the invitation listed. --- agents/auth/AGENTS.md | 8 +++ agents/auth/src/agent.ts | 71 +++++++++++++------ agents/auth/src/auth.ts | 9 +-- e2e/orgs.api.spec.ts | 29 ++++++-- src/lib/server/console.ts | 28 ++++++-- .../(app)/dashboard/(account)/+page.server.ts | 27 +++++-- .../(account)/organization/+page.svelte | 28 +++++++- src/routes/(app)/login/+page.svelte | 3 +- 8 files changed, 162 insertions(+), 41 deletions(-) diff --git a/agents/auth/AGENTS.md b/agents/auth/AGENTS.md index e9c4418..f4b95f1 100644 --- a/agents/auth/AGENTS.md +++ b/agents/auth/AGENTS.md @@ -62,6 +62,14 @@ turns every project JWT into an admin token. (`src/email-callback.ts`). Better Auth re-validates the absolute URL against the same allowlist at click time, so both halves must agree before anyone is redirected. +- **An invitation id is a credential** — it is what accepts the invitation, + and Better Auth's accept only compares the session email to the invited one. + A claimed console skips email verification, so registering an address proves + nothing. The id therefore reaches an account only through a verified address + or the invite link (`/dashboard?invitation=`, mailed or copied from the + org page); `/console/me` gates its list on that and the console refuses + Better Auth's by-email `list-user-invitations`. Never list invitation ids by + email match alone. - **Outbound mail is attacker-influenced.** Org names, inviter addresses, and reset URLs all land inside an HTML body sent from the deployment's verified sender. Interpolate through `escapeHtml` / `headerSafe`, never raw. diff --git a/agents/auth/src/agent.ts b/agents/auth/src/agent.ts index ee2df0e..9cc5ead 100644 --- a/agents/auth/src/agent.ts +++ b/agents/auth/src/agent.ts @@ -784,7 +784,7 @@ export class AuthAgent extends Agent { : 'Verify your email'; const intro = message.type === 'invitation' - ? `${message.invitation?.inviter ?? 'A team member'} invited you to "${message.invitation?.organization ?? 'their organization'}" on Frostbase. Sign in - or create an account with this email address - to accept.` + ? `${message.invitation?.inviter ?? 'A team member'} invited you to "${message.invitation?.organization ?? 'their organization'}" on Frostbase. Open the link, then sign in - or create an account with this email address - to accept. The link is what accepts the invitation, so do not forward it.` : 'Continue securely with the button below.'; const text = `${action}: ${message.url}\n\n${intro}\n\nIf you did not request this, you can ignore this email.`; // EVERY interpolation is escaped, not just the URL. An organization name @@ -1144,6 +1144,18 @@ export class AuthAgent extends Agent { return Response.json({ status: true }); } + // Better Auth's own list of "invitations addressed to my email" hands out + // the ids that accept them to anyone holding the session's address - + // unproven in claimed mode, where console sign-up skips verification. + // The console never calls it; /console/me gates the same list on a + // verified address or the invite link. + if ( + this.name === CONSOLE_PROJECT_ID && + subPath === '/api/auth/organization/list-user-invitations' + ) { + return Response.json({ error: 'not found' }, { status: 404 }); + } + if (subPath === '/api/auth' || subPath.startsWith('/api/auth/')) { if (!this.signingSecret) { return Response.json({ error: 'auth agent failed to start' }, { status: 500 }); @@ -1771,25 +1783,44 @@ export class AuthAgent extends Agent { .where(eq(schema.member.userId, user.id)) .orderBy(asc(schema.member.createdAt)); - const invitations = await this.db - .select({ - id: schema.invitation.id, - organizationId: schema.invitation.organizationId, - organizationName: schema.organization.name, - role: schema.invitation.role, - inviterEmail: schema.user.email, - expiresAt: schema.invitation.expiresAt, - }) - .from(schema.invitation) - .innerJoin(schema.organization, eq(schema.organization.id, schema.invitation.organizationId)) - .leftJoin(schema.user, eq(schema.user.id, schema.invitation.inviterId)) - .where( - and( - eq(sql`lower(${schema.invitation.email})`, user.email.toLowerCase()), - eq(schema.invitation.status, 'pending'), - gt(schema.invitation.expiresAt, new Date()), - ), - ); + // An invitation's id is the credential that accepts it, so it is handed + // out only to someone who has PROVED the invited inbox: a verified + // address, or a caller who already holds the id because it arrived by + // the invite link (?invitation=). Listing by a mere email match used to + // let anyone who registered an invited address first - verification is + // off in claimed mode - read the id and join the org. + const linkedId = new URL(request.url).searchParams.get('invitation'); + const scope = user.emailVerified + ? undefined + : linkedId + ? eq(schema.invitation.id, linkedId) + : null; + const invitations = + scope === null + ? [] + : await this.db + .select({ + id: schema.invitation.id, + organizationId: schema.invitation.organizationId, + organizationName: schema.organization.name, + role: schema.invitation.role, + inviterEmail: schema.user.email, + expiresAt: schema.invitation.expiresAt, + }) + .from(schema.invitation) + .innerJoin( + schema.organization, + eq(schema.organization.id, schema.invitation.organizationId), + ) + .leftJoin(schema.user, eq(schema.user.id, schema.invitation.inviterId)) + .where( + and( + eq(sql`lower(${schema.invitation.email})`, user.email.toLowerCase()), + eq(schema.invitation.status, 'pending'), + gt(schema.invitation.expiresAt, new Date()), + scope, + ), + ); return Response.json({ user: { diff --git a/agents/auth/src/auth.ts b/agents/auth/src/auth.ts index 869e8f8..ff05296 100644 --- a/agents/auth/src/auth.ts +++ b/agents/auth/src/auth.ts @@ -270,14 +270,15 @@ export function createProjectAuth(config: ProjectAuthConfig) { organizationLimit: config.orgLimit, sendInvitationEmail: config.sendEmail ? async (data, request) => { - // The console surfaces pending invitations after sign-in, so - // the link only needs to land the invitee on the login page - // of the deployment the invite was minted from. + // The link carries the invitation id, and the id is what + // accepts it: the console only shows an unverified account + // the invitation it holds the link to. Landing on /dashboard + // sends a signed-out invitee through /login and back. const origin = request ? new URL(request.url).origin : config.trustedOrigins[0]; await config.sendEmail?.({ type: 'invitation', to: data.email, - url: origin ? `${origin}/login` : '', + url: origin ? `${origin}/dashboard?invitation=${encodeURIComponent(data.id)}` : '', invitation: { organization: data.organization.name, inviter: data.inviter.user.email, diff --git a/e2e/orgs.api.spec.ts b/e2e/orgs.api.spec.ts index 9fec0fd..0d2b5f5 100644 --- a/e2e/orgs.api.spec.ts +++ b/e2e/orgs.api.spec.ts @@ -73,15 +73,34 @@ test.describe('organizations and ownership', () => { expect(token, 'the console issues bearer tokens like any project').toBeTruthy(); const asInvitee = { authorization: `Bearer ${token}` }; - // The invitee's identity: their own personal org plus the pending - // invitation, in one round trip. + // The invitee's identity: their own personal org - and NOT the + // invitation. Registering an address proves nothing here (claimed + // consoles skip verification), and the id is what accepts the + // invitation, so anyone who registered an invited address first used + // to read it from this list and join the org. Only a verified + // address, or the invite link, reveals it. const inviteeMe = await anon.get('/api/console/me', { headers: asInvitee }); expect(inviteeMe.ok(), await inviteeMe.text()).toBeTruthy(); const inviteeIdentity = await inviteeMe.json(); + expect(inviteeIdentity.user.emailVerified).toBe(false); expect(inviteeIdentity.organizations.length).toBeGreaterThanOrEqual(1); - expect(inviteeIdentity.pendingInvitations.map((entry: { id: string }) => entry.id)).toContain( - invitation.id - ); + expect(inviteeIdentity.pendingInvitations).toEqual([]); + + // Nor through Better Auth's own by-email listing. + const listed = await anon.get(consoleAuthPath('organization/list-user-invitations'), { + headers: asInvitee + }); + expect(listed.status()).toBe(404); + + // The invite link carries the id; holding it is the proof, and the + // projects page then offers exactly that invitation. + const viaLink = await anon.get(`/dashboard?invitation=${encodeURIComponent(invitation.id)}`, { + headers: asInvitee + }); + expect(viaLink.ok(), `${viaLink.status()}`).toBeTruthy(); + expect(await viaLink.text()).toContain('data-testid="accept-invitation"'); + const withoutLink = await anon.get('/dashboard', { headers: asInvitee }); + expect(await withoutLink.text()).not.toContain('data-testid="accept-invitation"'); const inviteeOrgId: string = inviteeIdentity.organizations[0].id; expect(inviteeOrgId).not.toBe(operatorOrgId); diff --git a/src/lib/server/console.ts b/src/lib/server/console.ts index 87e8be0..09fe09f 100644 --- a/src/lib/server/console.ts +++ b/src/lib/server/console.ts @@ -251,7 +251,10 @@ export async function resolveConsoleIdentity( origin: string, cookie: string | null, authorization: string | null = null, - clientIp: string | null = null + clientIp: string | null = null, + /** An invitation id the caller holds (from the invite link). An account + * whose email is unverified is shown only the invitation it holds. */ + invitationId: string | null = null ): Promise { if (!cookie && !authorization) return ANONYMOUS; @@ -260,7 +263,16 @@ export async function resolveConsoleIdentity( const agent = requireAuthAgent(platform); const attempt = () => agent - .fetch(agentUrl(origin, CONSOLE_PROJECT_ID, '/console/me'), { method: 'GET', headers }) + .fetch( + agentUrl( + origin, + CONSOLE_PROJECT_ID, + invitationId + ? `/console/me?invitation=${encodeURIComponent(invitationId)}` + : '/console/me' + ), + { method: 'GET', headers } + ) .catch((cause: unknown) => { Sentry.captureException(cause, { level: 'error', @@ -346,9 +358,17 @@ export async function getConsoleIdentity( origin: string, cookie: string | null, authorization: string | null = null, - clientIp: string | null = null + clientIp: string | null = null, + invitationId: string | null = null ): Promise { - const resolved = await resolveConsoleIdentity(platform, origin, cookie, authorization, clientIp); + const resolved = await resolveConsoleIdentity( + platform, + origin, + cookie, + authorization, + clientIp, + invitationId + ); return resolved.status === 'ok' ? resolved.identity : null; } diff --git a/src/routes/(app)/dashboard/(account)/+page.server.ts b/src/routes/(app)/dashboard/(account)/+page.server.ts index 857954b..6a5ea70 100644 --- a/src/routes/(app)/dashboard/(account)/+page.server.ts +++ b/src/routes/(app)/dashboard/(account)/+page.server.ts @@ -1,4 +1,5 @@ import { activeOrg } from '$lib/console'; +import { getConsoleIdentity } from '$lib/server/console'; import { isCrawler } from '$lib/server/crawler'; import { recordDemoProject } from '$lib/server/demo-log'; import { listProjects, operatorProjectScope } from '$lib/server/registry'; @@ -25,7 +26,7 @@ const PROJECT_PATTERN = /^demo-[a-f0-9]{12,20}$/; * org - made "All projects" bounce straight back and left the org surfaces * unreachable. */ -export const load: PageServerLoad = async ({ cookies, locals, platform, request }) => { +export const load: PageServerLoad = async ({ cookies, locals, platform, request, url }) => { if (locals.demoMode && !locals.consoleUser) { // A crawler is an anonymous visitor, so it used to be handed a real demo // project - one Durable Object and one all-time counter row per crawl, @@ -62,8 +63,24 @@ export const load: PageServerLoad = async ({ cookies, locals, platform, request operatorProjectScope(identity ?? null, active ? [active.id] : []) ); - return { - projects, - pendingInvitations: identity?.pendingInvitations ?? [] - }; + // An invite link (?invitation=) is how an account with an unverified + // address - every account on a claimed console without mail - reaches its + // invitation: the guard's identity lists invitations only for verified + // addresses, because the id is what accepts one. Holding the link is the + // proof, so resolve that one invitation for this session. + let pendingInvitations = identity?.pendingInvitations ?? []; + const linked = url.searchParams.get('invitation'); + if (identity && linked && !pendingInvitations.some((entry) => entry.id === linked)) { + const withLinked = await getConsoleIdentity( + platform, + url.origin, + request.headers.get('cookie'), + request.headers.get('authorization'), + request.headers.get('cf-connecting-ip'), + linked + ); + pendingInvitations = withLinked?.pendingInvitations ?? pendingInvitations; + } + + return { projects, pendingInvitations }; }; diff --git a/src/routes/(app)/dashboard/(account)/organization/+page.svelte b/src/routes/(app)/dashboard/(account)/organization/+page.svelte index f07c191..fba0354 100644 --- a/src/routes/(app)/dashboard/(account)/organization/+page.svelte +++ b/src/routes/(app)/dashboard/(account)/organization/+page.svelte @@ -147,6 +147,21 @@ } } + // The invite link is what accepts an invitation - the console shows an + // account whose address is unverified only the invitation it holds the link + // to - so the inviter hands it over directly whenever mail cannot. + let copiedInvitation = $state(null); + + async function copyInviteLink(invitationId: string) { + const link = new URL('/dashboard', location.origin); + link.searchParams.set('invitation', invitationId); + await navigator.clipboard.writeText(link.toString()); + copiedInvitation = invitationId; + setTimeout(() => { + if (copiedInvitation === invitationId) copiedInvitation = null; + }, 2000); + } + let cancelBusy = $state(null); async function cancelInvitation(invitationId: string) { @@ -235,8 +250,9 @@

{inviteError}

{:else if inviteSent}

- Invitation created. The invitee signs up (or in) with that email and accepts from their - projects page. + Invitation created. Send the invitee its link - copy it below; an invitation email, when + this console can send mail, carries the same link. They open it, then sign up (or in) with + that email to accept.

{/if} @@ -250,6 +266,14 @@

Pending invitation

{#if canAdminister} +