Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions agents/auth/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<id>`, 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.
Expand Down
4 changes: 2 additions & 2 deletions agents/auth/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion agents/auth/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
71 changes: 51 additions & 20 deletions agents/auth/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ export class AuthAgent extends Agent<Env, AuthAgentState> {
: '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
Expand Down Expand Up @@ -1144,6 +1144,18 @@ export class AuthAgent extends Agent<Env, AuthAgentState> {
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 });
Expand Down Expand Up @@ -1771,25 +1783,44 @@ export class AuthAgent extends Agent<Env, AuthAgentState> {
.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: {
Expand Down
9 changes: 5 additions & 4 deletions agents/auth/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions agents/db/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion agents/db/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
19 changes: 19 additions & 0 deletions agents/db/src/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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
Expand Down
14 changes: 12 additions & 2 deletions agents/db/src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<Response> {
Expand Down
11 changes: 11 additions & 0 deletions agents/db/src/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,17 @@ export abstract class LiveShard extends DurableObject<Env> {
| { 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,
Expand Down
18 changes: 18 additions & 0 deletions agents/db/src/table-sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
25 changes: 24 additions & 1 deletion agents/db/src/table-sql.unit.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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,
);
});
Loading
Loading