Unsafe Mode and the Operator Lane
Leave the scoped db handle on purpose — unsafe mode, credential doors, the operator lane, and the raw SQL policy.
An action reads and writes through the scoped db handle by default. This page covers the declared ways out of it: unsafe mode, credential doors for server grants, the operator lane, and which raw SQL is allowed.
Unsafe Mode
Actions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.
unsafeDb and a raw createDb() handle are unchecked by design: no
firewall WHERE, no claim stamping, no firewall-on-write check. On Postgres a
non-cross-tenant unsafeDb still runs under the caller's RLS claims, so an
insert the policy refuses comes back as 403 FIREWALL_WRITE_DENIED; on D1 it
lands. That is the point of the escape hatch — and why it is audited.
unsafe is the only sanctioned way around the scoped db. It is a compile
error (ACTION_RAW_DB_WITHOUT_UNSAFE) when a non-unsafe action reaches a
raw database handle instead. The check covers the action file and every file
it imports, transitively, from the feature's lib/ and the project's lib/,
hooks/, or plugins/ (relative or ~/ imports). A raw handle is any of:
c.get('db')- a database binding off the environment (
env.DB,c.env.HYPERDRIVE,env.DB.prepare(…), …) - a drizzle driver import (
drizzle-orm/d1,drizzle-orm/postgres-js, …) - a call to
drizzle(…),createDb(), orcreateAuthDb() auth.$context(Better Auth's adapter)- the action's own
unsafeDb
Each error names the action, file, line, and handle. If the access is
intentional, declare unsafe: { reason: "…" } so it is audited (or
firewall: { exception: true } for a deliberately unscoped action). To adopt
the check on an existing project, compiler.securityContracts.failMode: "warn"
downgrades it to a warning. Writes to Better Auth tables are a separate error,
ACTION_AUTH_DB_WRITE, that plain unsafe does not silence: only
unsafe: { reason: "…", crossTenant: false, authWrites: true } does. Call auth.api.* instead
where Better Auth has an endpoint. See
Diagnostics → ACTION_AUTH_DB_WRITE.
Use object form for explicit policy and mandatory audit metadata:
// features/admin/actions/crossTenantReport.ts
import { z } from "zod";
import { defineAction } from "../.quickback/define-action";
import { applications } from "../../applications/applications";
export default defineAction({
description: "Generate cross-org hiring report",
path: "/admin/cross-tenant-report",
input: z.object({ startDate: z.string() }),
access: { roles: ["owner"] },
unsafe: {
reason: "Support investigation for enterprise customer",
adminOnly: true, // default true
crossTenant: true, // default true
targetScope: "all", // "all" | "organization"
},
async execute({ unsafeDb, input }) {
// unsafeDb bypasses scoped filters
const allOrgs = await unsafeDb.select().from(applications);
return allOrgs;
},
});Unsafe cross-tenant actions are generated with:
- Better Auth authentication required (no unauthenticated path)
- sysadmin gate (
ctx.userRole === "sysadmin") - mandatory audit logging on deny/success/error — an
errorrow'serrorMessagenever carries bound values (redacted: SQL and constraint names stay, the values do not)
A same-tenant unsafe action (crossTenant: false) gets no sysadmin gate and
writes no audit row — unless it declares authWrites: true, which adds the
mandatory audit log (with its reason) and nothing else.
Provider note (Neon, PlanetScale Postgres): unsafeDb is the
service-role handle (createServiceDb, wrapped by the audit writer) for
every unsafe action, crossTenant: true or false — the same reach as on
D1. It sets the quickback.service_role transaction marker instead of caller
claims, and generated RLS grants that marker an explicit per-table policy. So
RLS does not narrow unsafeDb to the caller: a PUBLIC door's token lookup
finds the row, and a roster join over member sees every member. The action's
own checks — and unsafeDb.scopeTo(...) — govern, exactly as on D1.
crossTenant decides the gate, not the handle: crossTenant: true adds the
sysadmin guard and mandatory audit log described above. The
audit-logging contract is otherwise identical to D1. On Cloudflare, both HTTP
and Hyperdrive are supported. Hyperdrive is the recommended lane when an unsafe
action also needs an interactive transaction. The deprecated Node/Bun WebSocket
mode is refused for unsafe actions because it cannot provide the same
request-scoped service-role boundary.
PUBLIC actions write to the same audit table only when they opt in with audit: 'full' (Public Access); by default a PUBLIC action writes no per-call row, and every compile lists it in the public endpoints notice.
Without unsafe mode, unsafeDb is undefined in the executor params.
Credential doors (server grants)
A PUBLIC action that turns an application credential (a printed handout code, a legacy pass) into an instance-bound grant has no caller principal: the scoped db and the audited unsafeDb both refuse its writes, because the audit wrapper stamps the writer from ctx.userId and fails closed without one. Such a door:
- declares
unsafe: { reason: '…', crossTenant: false }(no sysadmin gate; every call is audited) and reads and consumes its own credential row through the unwrapped features handle fromsrc/db:createDb(env.DB)on D1,createServiceDb(env)on Postgres (an anonymous caller's claims satisfy no policy); - never reads
ctx.userId, a cookie or a bearer: the user it links and grants comes only from the read of the credential's subject (readScopeGrantSubject); - consumes the credential with one conditional write (
UPDATE … WHERE id = ? AND revoked_at IS NULL AND expires_at > ? RETURNING id) only afterissueScopeGrantreturned, and returns the grant only if exactly one row came back (elsediscardScopeGrant); - answers with
Cache-Control: no-store.
The subject side (reading the subject, linking it, admitting it) goes through readScopeGrantSubject, linkScopeGrantSubject and issueScopeGrant, never through raw access to the subject table, on a platform kind (shared D1 or Postgres) and a tenant-backed one alike. The order, the outcome classes and the squatting guard are in Server-issued grants.
Operator lane: operator:
A platform operator acting on one tenant — set a customer's plan, fix an
event's status, seed an organization — is not a cross-tenant query. Declare the
target instead of reaching for unsafe:
For tenant lifecycle mutations on a Durable Object tenancy (archive, restore, purge, …) call runTenantOperatorOperation from lib/tenants inside the action: it adds the state-machine check, confirmation, begin/outcome audit rows and operation id the generated operator routes have (Lifecycle operations).
// features/events/actions/setEventStatus.ts
import { z } from 'zod';
import { eq } from 'drizzle-orm';
import { defineAction, events } from '../.quickback/define-action';
export default defineAction({
description: "Platform operator: set an event's status in whichever tenant owns it",
path: '/events/operator/set-status',
input: z.object({ eventId: z.string(), status: z.enum(['draft', 'live', 'closed']) }),
access: { userRole: ['sysadmin'] },
operator: { target: { table: 'events', by: 'input.eventId' } }, // or table: 'organizations', by: 'input.organizationId'
async execute({ db, target, input }) {
// `db` is firewalled to target.organizationId — not the operator's own org.
const [row] = await db.update(events).set({ status: input.status })
.where(eq(events.id, target.id)).returning();
return row;
},
});Before execute runs, the route:
- Checks the
userRolelane (403 otherwise). An unauthorized caller never triggers the lookup. - Loads the target row by
input.<field>— across tenants, on purpose (the raw handle on D1, the service-role handle on Postgres; Better Auth's organization table fortable: 'organizations'). - Answers 404
OPERATOR_TARGET_NOT_FOUNDwhen the row is absent or soft-deleted. Settarget: { …, includeDeleted: true }to admit a soft-deleted row. - Hands
executethe row astargetand adbequal tounsafeDb.scopeTo({ organizationId })— the target'sorganizationId, or the organization's ownidwhen the target isorganizations. Every statement after that is firewalled to the target tenant, and inserts are stamped with it.unsafeDbis not passed. On Postgres thatdbwraps the service-role handle, the same asunsafeDb.scopeTo: the firewallWHEREand insert stamps are the boundary, and RLS does not narrow it to the target tenant as a backstop.
Every call writes one audit row (eventKind: 'operator_action') to the same
audit_events table unsafe actions use, on denial, success and
error. A failed audit write fails the request (500 ACCESS_AUDIT_LOG_FAILED).
| Column | Value |
|---|---|
targetOrgId | the target's organization (null when the request was denied before the target loaded) |
resource | the target table (events, organizations) |
targetRecordId | the requested id |
actorUserId / actorOrgId | the operator and their own active org |
metadata.operator | { targetTable, targetId } |
metadata.input | the action input, with every key named like a masked, .encrypted(), .sealed() or vault-ref column in the project replaced by "[REDACTED]" |
errorCode / errorMessage | on error rows: the thrown error's code and message, with bound values redacted — the SQL, constraint and column names stay (details) |
The return value is never stored.
The compiler refuses:
operatorwithout auserRole-only access lane —access: { userRole: [...] }, optionally withauthMethod, and nothing else (noroles,or,principals).operatortogether withunsafe,anchor,recordorfirewall— one or the other.operatoron a record action (nopath:) or under anauthz.namespacesprefix.target.bythat is notinput.<field>of a required field in an inlinez.objectinput.target.tablethat is not an org-firewalled feature table (an org arm bound toctx.activeOrgId) or'organizations';includeDeletedon a table without soft delete.
A row in an org-firewalled table with no organization is refused with 500
OPERATOR_TARGET_TENANT_UNRESOLVED rather than run unscoped.
emit: and invalidates: on an operator action address the target
tenant's org room — the same organization the db is scoped to — never the
operator's own active org. A request whose by field is missing or empty is
rejected with 422 before the lookup.
Transfer a record between organizations
Moving a record to another organization is sometimes legitimate, for example
handing a project over to a client's org. The scoped db refuses it: a SET
of organizationId (or any other stamped tenant or owner column) to anything
except the caller's own value gets 403 FIREWALL_WRITE_DENIED. See
Updates keep the row in your tenant.
Write a transfer through unsafeDb in an unsafe: { crossTenant: true, reason }
action. The action is sysadmin-gated, and every call is audited. The firewall
won't check the destination for you, so the action has to:
- load the record in the caller's current org;
- check the caller's role in the destination org;
- write the update scoped to the source org.
// features/projects/projects.ts
import { q, defineTable } from "@quickback/compiler";
export const projects = q.table("projects", {
id: q.id(),
name: q.text().required(),
organizationId: q.scope("organization"),
...q.audit(),
...q.softDelete(),
});
export default defineTable(projects, {
firewall: [{ field: "organizationId", equals: "ctx.activeOrgId" }],
read: { access: { roles: ["member", "admin"] } },
crud: { update: { access: { roles: ["admin"] } } },
});
// features/projects/actions/transferProject.ts
import { z } from "zod";
import { and, eq } from "drizzle-orm";
import { ActionError } from "@quickback/compiler";
import { defineAction } from "../.quickback/define-action";
import { projects } from "../projects";
import { getOrgMemberRole } from "../../../lib/org-access";
export default defineAction({
description: "Transfer a project to another organization",
path: "/projects/transfer",
input: z.object({ projectId: z.string(), toOrganizationId: z.string() }),
access: { roles: ["admin"] },
unsafe: {
reason: "Transfer a project to a destination org the caller administers",
crossTenant: true,
},
async execute({ unsafeDb, ctx, input, c }) {
// 1. The record must be in the caller's current org.
const [project] = await unsafeDb!.select().from(projects).where(and(
eq(projects.id, input.projectId),
eq(projects.organizationId, ctx.activeOrgId!),
)).limit(1);
if (!project) throw new ActionError("Project not found in your organization", "NOT_FOUND", 404);
// 2. The firewall never sees the destination, so check it here.
const role = await getOrgMemberRole(c.get("authDb"), ctx.userId!, input.toOrganizationId);
if (role !== "owner" && role !== "admin") {
throw new ActionError("You must be an owner or admin of the destination organization", "TRANSFER_DESTINATION_DENIED", 403);
}
// 3. Re-home the row. The WHERE still pins the source org.
const [moved] = await unsafeDb!.update(projects)
.set({ organizationId: input.toOrganizationId })
.where(and(eq(projects.id, project.id), eq(projects.organizationId, ctx.activeOrgId!)))
.returning();
return moved;
},
});crossTenant: true generates the sysadmin gate (ctx.userRole === "sysadmin")
and writes an audit_events row on every denial, success and error. That makes
it a staff or support tool. To let members move their own records, for example
from a personal org to a team org, use crossTenant: false. The checks above
are then the only boundary: there is no sysadmin gate and no audit row.
The operator lane can't make the move. Its db is
scoped to the target's organization, so a SET of that organization column is
refused the same way.
Raw SQL Policy
By default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.
If a specific action must use raw SQL, opt in explicitly:
// features/ledgers/actions/reconcile.ts
import { z } from "zod";
import { sql } from "drizzle-orm";
import { defineAction } from "../.quickback/define-action";
export default defineAction({
description: "Run custom reconciliation query",
input: z.object({}),
access: { roles: ["owner"] },
allowRawSql: true,
async execute({ db }) {
return db.execute(sql`select 1`);
},
});Without allowRawSql: true, compilation fails with a loud error pointing to the action and snippet.
The detector checks for SQL keywords in string arguments, so non-SQL method calls like headers.get("X-Forwarded-For") or map.get("key") will not trigger false positives.
Scoped Database
The security-filtered db handle inside an action — what it filters and enforces. Unsafe mode and raw SQL, concurrency, and sharing code between actions have their own pages.
Race-safe Writes and Batches
insertWhere, updateWhere and ledgers for race-safe writes, atomic D1 batches, and transaction outcomes and recovery.