diff --git a/agents/auth/AGENTS.md b/agents/auth/AGENTS.md index e9c4418e..f4b95f1f 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/package-lock.json b/agents/auth/package-lock.json index 8f52ee89..8ee7406e 100644 --- a/agents/auth/package-lock.json +++ b/agents/auth/package-lock.json @@ -1,12 +1,12 @@ { "name": "@frostbase-dev/auth", - "version": "0.7.5", + "version": "0.7.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@frostbase-dev/auth", - "version": "0.7.5", + "version": "0.7.6", "license": "Apache-2.0", "dependencies": { "@sentry/cloudflare": "^10.66.0", diff --git a/agents/auth/package.json b/agents/auth/package.json index b3235609..041d4be2 100644 --- a/agents/auth/package.json +++ b/agents/auth/package.json @@ -1,6 +1,6 @@ { "name": "@frostbase-dev/auth", - "version": "0.7.5", + "version": "0.7.6", "description": "Better Auth on a Cloudflare Durable Object, one instance per project - the auth primitive behind Frostbase.", "license": "Apache-2.0", "type": "module", diff --git a/agents/auth/src/agent.ts b/agents/auth/src/agent.ts index ee2df0ed..9cc5ead5 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 869e8f8f..ff05296f 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/agents/db/package-lock.json b/agents/db/package-lock.json index 24ff617f..9cee302f 100644 --- a/agents/db/package-lock.json +++ b/agents/db/package-lock.json @@ -1,12 +1,12 @@ { "name": "@frostbase-dev/db", - "version": "0.7.2", + "version": "0.7.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@frostbase-dev/db", - "version": "0.7.2", + "version": "0.7.3", "license": "Apache-2.0", "dependencies": { "@sentry/cloudflare": "^10.66.0", diff --git a/agents/db/package.json b/agents/db/package.json index 1cee8f0a..86c74009 100644 --- a/agents/db/package.json +++ b/agents/db/package.json @@ -1,6 +1,6 @@ { "name": "@frostbase-dev/db", - "version": "0.7.2", + "version": "0.7.3", "description": "Documents with live queries and schema-first SQL tables on Cloudflare Durable Objects, one isolated instance per collection or table - the database primitive behind Frostbase.", "license": "Apache-2.0", "type": "module", diff --git a/agents/db/src/access.ts b/agents/db/src/access.ts index f540f7f5..62e09fbe 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 607fccfc..8a00b70e 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 e436dcc6..65802ba9 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-sql.ts b/agents/db/src/table-sql.ts index eee351ee..f7753554 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 86c9ef83..0d509b62 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 466e6160..78c3d322 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'; @@ -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, @@ -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); } @@ -1106,34 +1116,45 @@ 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 ?? [] }); } - // 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 +1178,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/agents/db/src/view.ts b/agents/db/src/view.ts index e3463259..4b40a21f 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/agents/storage/AGENTS.md b/agents/storage/AGENTS.md index 8b5b51c4..bd76b0c3 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-lock.json b/agents/storage/package-lock.json index 898efff7..7425183e 100644 --- a/agents/storage/package-lock.json +++ b/agents/storage/package-lock.json @@ -1,12 +1,12 @@ { "name": "@frostbase-dev/storage", - "version": "0.4.1", + "version": "0.4.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@frostbase-dev/storage", - "version": "0.4.1", + "version": "0.4.2", "license": "Apache-2.0", "dependencies": { "@sentry/cloudflare": "^10.66.0", diff --git a/agents/storage/package.json b/agents/storage/package.json index 800ca9ab..45f45ea2 100644 --- a/agents/storage/package.json +++ b/agents/storage/package.json @@ -1,6 +1,6 @@ { "name": "@frostbase-dev/storage", - "version": "0.4.1", + "version": "0.4.2", "description": "Object storage on Cloudflare R2 - buckets of files with per-bucket access modes, an object index with keyset paging, one Durable Object orchestrator per project - the storage primitive behind Frostbase.", "license": "Apache-2.0", "type": "module", @@ -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 0c01cf3c..79edf026 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 00000000..6a40da07 --- /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 00000000..5a72e21e --- /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/db-readonly.api.spec.ts b/e2e/db-readonly.api.spec.ts index f36e6a52..521cd9d5 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/e2e/db-tables-sql.api.spec.ts b/e2e/db-tables-sql.api.spec.ts index 2d0bf1a7..9bb20ec1 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, diff --git a/e2e/orgs.api.spec.ts b/e2e/orgs.api.spec.ts index 9fec0fd6..0d2b5f59 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/e2e/storage.api.spec.ts b/e2e/storage.api.spec.ts index 742f7380..8e179be3 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' } ]; diff --git a/package.json b/package.json index 691048a8..a9e45d05 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 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 8360cfb3..657c1d4c 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -11,12 +11,18 @@ 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'; import type { AppAgentEntry } from '$lib/agent-registry'; import type { Handle } from '@sveltejs/kit'; +import { movedLocation } from '$lib/safe-redirect'; let platform: App.Platform; @@ -548,11 +554,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); @@ -661,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/agents.ts b/src/lib/agents.ts index 524d4718..eb69896a 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 842ca971..4dff96b5 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: { diff --git a/src/lib/safe-redirect.ts b/src/lib/safe-redirect.ts new file mode 100644 index 00000000..bc968398 --- /dev/null +++ b/src/lib/safe-redirect.ts @@ -0,0 +1,46 @@ +/** + * 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. + for (const char of value) { + const code = char.charCodeAt(0); + if (char === '\\' || code < 0x20 || code === 0x7f) 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 00000000..ffcb3205 --- /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/lib/server/console.ts b/src/lib/server/console.ts index 87e8be0b..09fe09f0 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/lib/server/project-scope.ts b/src/lib/server/project-scope.ts new file mode 100644 index 00000000..c2f9e1f0 --- /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 00000000..2728195a --- /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 3c16ffda..9ba47060 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 8c593c64..6a5ea707 100644 --- a/src/routes/(app)/dashboard/(account)/+page.server.ts +++ b/src/routes/(app)/dashboard/(account)/+page.server.ts @@ -1,7 +1,8 @@ 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 } from '$lib/server/registry'; +import { listProjects, operatorProjectScope } from '$lib/server/registry'; import { redirect } from '@sveltejs/kit'; import type { PageServerLoad } from './$types'; @@ -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, @@ -50,17 +51,36 @@ 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, - 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 f07c191c..fba0354f 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} +