Namespace Mounts
Hoist relationship middleware onto a route prefix with namespaces — single-feature and cross-feature mounts, multi-lane via, bulk-grant lanes, requirements and ctx typing.
A namespace mounts relationship admission once on a route prefix such as /event/:eventId, so every route under it is admitted through the same lanes. This page covers declaring namespaces, lane matching, and what namespace actions receive. For grouping features under an auth boundary, see Feature Areas.
Namespace mounts (hoisted relationship middleware)
When several standalone actions share a path prefix and the same relationship gate — /event/:eventId/announce, /event/:eventId/cancel, /event/:eventId/respond — declaring the gate per-action means writing the same roles: ['attendee'] over and over AND paying the relationship-resolver cost N times per request (one subquery + one row-load, multiplied by the number of actions).
Namespace mounts hoist the resolver into one Hono middleware that runs once per request. Every action under the prefix skips the inline gate; ctx.<exposeAs> is hydrated by the middleware before the action's execute() runs. With the per-namespace helper, that field is also statically typed as the loaded row.
Tables whose path: sits under the prefix are claimed too, and pinned to the URL instance for every lane.
When to use roles vs. relationships
A user is authorized for a row when any of the following is true:
- they have a per-row relationship to it (e.g. an attendee row, a named organizer row), or
- they have a role on the row's tenant (org admin/owner of the row's
organizationId), or - they have team membership matching the row's
teamId.
Use relationships when membership is specific to this row — external collaborators who aren't in your org, attendees, anyone connected to the resource by virtue of data rather than payroll. Use roles / team when staff at your org/team should see everything in their scope by default.
The two compose at the action level (access.or accepts both relationship-roles and tenant roles) and at the namespace level: namespace.via accepts an array of lanes, first match wins.
Rule of thumb. If the answer is "yes if you work here," reach for org/team roles. If the answer is "yes if you have something to do with this row," reach for a per-row relationship. Reach for both together — at the namespace or via
access.or— when an action should let either side in.
Two declaration sites depending on whether the participating actions live in one feature or many:
Single feature: defineTable({ namespace })
Use when every action under the prefix lives in the same feature directory. The namespace travels with the table that owns it — no addition to quickback.config.ts needed.
// features/events/events.ts
import { q, defineTable } from '@quickback/compiler';
export const events = q.table('events', {
id: q.id(),
name: q.text().required(),
organizationId: q.scope('organization'),
...q.audit(),
...q.softDelete(),
});
export default defineTable(events, {
firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
namespace: {
prefix: '/event/:eventId', // absolute URL path
via: 'attendeeOf', // relationship gate (must exist in authz.relationships)
},
});
// features/events/actions/postAnnouncement.ts
import { z } from "zod";
import { defineAction } from "../.quickback/define-action";
export default defineAction({
description: "Post an announcement to everyone attending the event.",
path: '/event/:eventId/announcements',
method: 'POST',
input: z.object({ body: z.string().max(2000) }),
// No `via:` gate boilerplate — the namespace already ran the resolver, so
// `access` only names roles and ctx.event is typed inside execute().
access: { roles: ['admin', 'member'] },
async execute({ db, input, ctx }) { /* … */ },
});The compiler emits one app.use(...) on the events feature's Hono app. Every standalone action in features/events/actions/ whose path starts with /event/:eventId/ joins the namespace automatically.
Multi-lane and bulk-grant lanes work identically on the table-level declaration — via: accepts the same shapes documented below for the project-level form.
Cross-feature: authz.namespaces
Use when the namespace spans multiple features. The declaration sits next to your other authz config in quickback.config.ts.
// quickback.config.ts
authz: {
relationships: {
attendeeOf: {
from: 'guests',
subject: { column: 'userId', equals: 'ctx.userId' },
resource: { column: 'eventId' },
loads: 'events',
exposeAs: 'event',
},
},
namespaces: {
eventScope: { prefix: '/event/:eventId', via: 'attendeeOf' },
},
}With the namespace declared, any standalone action whose path: matches the prefix joins the gate — regardless of which feature owns it:
// features/feeds/actions/feedMoments.ts (in one feature)
import { z } from "zod";
import { defineAction } from "../.quickback/define-action";
export default defineAction({
description: "Publish a moment to the event's live feed.",
path: '/event/:eventId/feed-moments',
method: 'POST',
input: z.object({ caption: z.string().max(280), photoId: z.string().optional() }),
access: { roles: ['admin', 'member'] },
async execute({ db, input, ctx }) { /* … */ },
});
// features/rsvp/actions/respond.ts (in a different feature)
import { z } from "zod";
import { defineAction } from "../.quickback/define-action";
export default defineAction({
description: "Record the caller's RSVP for the event.",
path: '/event/:eventId/respond',
method: 'POST',
input: z.object({ response: z.enum(['yes', 'no', 'maybe']) }),
access: { roles: ['admin', 'member'] },
async execute({ db, input, ctx }) { /* … */ },
});The compiler emits one synthetic src/routes/__namespace-event-scope.routes.ts that imports each contributing feature's actions map under a distinct alias, mounts the resolver middleware once, and dispatches to the matching action. Worker-root mount order ensures the middleware fires before any per-feature route handler under the prefix.
Multi-lane via — first match wins
When more than one relationship can authorize a caller for the namespaced resource, pass via: as an array. The middleware starts every lane's probe at once and takes the first match in declaration order — a later lane never wins over an earlier lane that also matches, and ctx.<exposeAs> is hydrated from the lane that won. A probe that fails surfaces only when every earlier lane missed; a failure in a lane after the winner is ignored.
authz: {
relationships: {
attendeeOf: {
from: 'guests',
subject: { column: 'linkedUserId', equals: 'ctx.userId' },
resource: { column: 'eventId' },
where: { status: 'confirmed' },
loads: 'events',
exposeAs: 'event',
},
// Named per-event organizers (potentially EXTERNAL — these users may
// not be a member of the event's org. That's the point: lets you grant
// event-level access to freelancers / partner staff without adding
// them to the org's member list.)
organizerOf: {
from: 'eventOrganizers',
subject: { column: 'linkedUserId', equals: 'ctx.userId' },
resource: { column: 'eventId' },
loads: 'events',
exposeAs: 'event',
},
},
namespaces: {
eventScope: {
prefix: '/event/:eventId',
via: ['attendeeOf', 'organizerOf'],
},
},
}The gate records the admitting lane on ctx.lane; declare lanes: 'all' to also record every lane the caller satisfies on ctx.lanes — see Recording every matched lane.
Hydration is per matched lane: each lane fills ctx.<its own exposeAs> from its own loads: table, so lanes may load different tables into different keys. Both lanes above name events / event, so ctx.event is populated whichever fires. A lane declaring neither loads: nor exposeAs: is authorization-only — it opens the gate and hydrates nothing.
Recording every matched lane — lanes: 'all'
The gate stamps ctx.lane on every request it admits: the lane that let
the caller in — a relationship lane's name, 'roles' for a { roles } lane,
'team' for { team: true }, 'link' for a
share link landing on its own
instance. The bulk-grant role check runs before the
relationship probes and short-circuits them, so an org admin who is also a
named organizer is admitted as 'roles', and nothing records the organizer
relationship. A body that needs to know ("may this admin also act as the
event's organizer?") would have to re-query it.
Declare lanes: 'all' and the gate also stamps ctx.lanes — every lane the
caller satisfies, in via: declaration order:
namespaces: {
eventScope: {
prefix: '/event/:eventId',
via: ['organizerOf', 'attendeeOf', { roles: ['admin', 'owner'] }],
lanes: 'all',
},
}
// An org owner who is also a named organizer:
// ctx.lane → 'roles' (the lane that admitted them)
// ctx.lanes → ['organizerOf', 'roles'] (everything they hold)- Every relationship lane is evaluated even when an earlier lane already opened the gate. Probes the gate started are awaited, not re-run; only lanes the gate skipped (the role arm matched) cost a query each.
- A probe that throws fails the request rather than silently dropping a lane —
ctx.lanes.includes(...)never lies by omission. - With the default (
lanes: 'first') onlyctx.laneis stamped;ctx.lanesis absent, so code cannot mistake a partial list for a complete one. ctx.lanesis what decides a relationship arm inaccess.armsand avia:rule inctx.is.- The per-namespace helper types both:
ctx.laneas the union of this namespace's lane labels,ctx.lanesas an array of them. lanesis accepted onauthz.namespacesentries and feature-areadefineAreagates. On a table-leveldefineTable({ namespace })it is a compile error.- The scope-claim refresh still stamps the role of the lane that admitted
the request (
ctx.lane), not of every lane inctx.lanes.
Bulk-grant lanes
Relationship lanes cover "specifically connected to this row." Bulk-grant lanes cover "anyone with this role / team membership in the row's tenant" — the case where an org admin or a team member should see every event in their scope without writing per-event relationship rows.
namespaces: {
eventScope: {
prefix: '/event/:eventId',
via: [
'attendeeOf',
'organizerOf',
{ roles: ['admin', 'owner'] }, // org-role bulk grant
{ team: true }, // active-team-membership bulk grant
],
},
}Each bulk-grant lane:
{ roles: [...] }— passes when the caller's BA org-role for the loaded resource's tenant includes any listed role. Short-circuits the relationship loop entirely; the role check is in-memory and cheap. Use for the "company admin sees everything" case.{ team: true }— passes whenctx.activeTeamIdis set. The loads-table firewall does the actualevents.teamId === ctx.activeTeamIdcheck during hydration. Use when the resource is team-scoped and you want active-team membership to grant access.
Both bulk-grant lanes piggyback on the namespace's relationship lane(s) for hydration — they don't fetch a separate per-row subject; they just gate access and let the loads-table firewall handle the tenant scoping. When a relationship lane anchors hydration, declare loads: + exposeAs: on that lane.
When a request misses every lane, the 403 deny payload lists every authorization path the caller could have taken — relationship names, role names, and "team-membership" for { team: true } lanes — so a developer debugging an unexpected 403 sees the full surface they need to satisfy.
When a relationship lane matches, the gate also stamps the lane's scope role into ctx.scope.<kind> for the request — see Scopes → Namespace scope-claim refresh. To carry a scope across requests, add oauth to the kind and issue instance-bound OAuth tokens; mintScope and acceptScope are removed and fail the build with SCOPE_MINT_REMOVED.
Discovery is path-prefix-only
Actions opt in by matching path: against a declared namespace prefix. There's no namespace: 'foo' field on defineAction — the path string is the discoverable surface, consistent with how path: already determines an action's URL.
Requirements (enforced at compile time)
Both forms share the same shape checks:
via:accepts one of three shapes. A single relationship name, an array of relationship names (first match wins), or an array mixing relationship names with bulk-grant guards ({ roles: [...] },{ team: true }). A bare string is always a relationship name. There is no string form for a role:{ roles: [...] }is a bulk-grant lane against Better Auth org roles, even when the name you put in it is a composed role definedviaa relationship.- Each relationship lane declares
loads+exposeAs, or neither. Both → the lane hydratesctx.<exposeAs>fromloadswhen it matches. Neither → an authorization-only lane. Exactly one is a compile error. - Bulk-grant lanes inherit
loads:+exposeAs:from sibling relationship lanes. Pure bulk-grant namespaces (no relationship lane at all) are also accepted — setloads:+exposeAs:directly on the namespace declaration so hydration has somewhere to anchor. prefix:must contain at least one:paramsegment (e.g./event/:eventId). The middleware reads the relationship key fromc.req.param()because no request body has been parsed at middleware time.- One declaration per namespace name. The same name in both
defineTable({ namespace })andauthz.namespacesis rejected. The project-level form is canonical for cross-feature; the table-level form is the single-feature shorthand.
Project-level only:
- Ambiguous prefixes like
/a/:xand/a/:y(same shape, different:paramnames) are rejected. Strict super/sub-set relationships (/event/:evs/event/:e/admin) are fine — the harvester routes each action to the longest matching prefix. - Unused namespace emits a
[quickback:authz]warning when no action's path matches the declared prefix. Not a hard error — the namespace may be staged ahead of the actions.
What namespace actions get for free
Inside a namespace action's execute():
ctx.<exposeAs>is populated by the middleware with the loaded resource row. Staticallyanyby default — narrowed totypeof <loadsTable>.$inferSelectwhen the action's import points at the per-namespace helper (see below).- Nothing is stamped from the matched relationship row: an org or team firewall arm means membership, so a relationship caller (an attendee) keeps no active organization or team and reaches rows through the arms that name it —
ctx.<exposeAs>andctx.scope.<kind>. See Relationships. - The action's own
access:block (additional roles, userRole, record predicates, OTHER relationship arms) still runs after the namespace gate — namespace handles entry, per-action gates further.
Narrow ctx.<exposeAs> typing
The namespace middleware hydrates ctx.<exposeAs> at runtime. The static type of that field is any via the AppContext index signature: useful for not blocking access, but a missed opportunity for autocomplete and typo-catching.
The compiler emits one per-namespace defineAction helper alongside the standard <feature>/.quickback/define-action.ts. Importing from the narrowed helper retypes ctx.<exposeAs> inside execute({ ctx }) to the loaded row's $inferSelect shape. Runtime behavior, action discovery, and the path: namespace match are identical.
The narrowed helper also knows what the namespace gate did before execute ran. A namespace whose lanes are all bulk-grant lanes ({ roles }, { team }) admits only callers carrying their own org, so its helper credits every access lane the org claim in the scoped db type gate. A namespace with a relationship lane does not: the relationship caller has no active organization, so a roles: ['member+', 'scope:event:attendee'] action under /event/:eventId that reads an org-only table is a tsc error — at runtime the attendee would get 403 FIREWALL_CLAIM_MISSING. Read such tables through an arm that names the attendee ({ field: 'eventId', equals: 'ctx.scope.event' } beside the org arm), or pin by ctx.event.organizationId yourself.
// One-line flip per namespace-scoped action:
import { z } from 'zod';
import { defineAction } from '../.quickback/define-action.event-scope';
// └──────┬──────┘
// kebab(namespaceName)
export default defineAction({
description: "Publish a moment to the event's live feed.",
path: '/event/:eventId/feed-moments',
method: 'POST',
input: z.object({ body: z.string() }),
access: { roles: ['attendee'] },
async execute({ ctx, input }) {
ctx.event.id // ✓ string
ctx.event.startsAt // ✓ Date — autocomplete works
ctx.event.organizerId // ✓ narrows on the field's declared type
ctx.event.idd // ✗ TS2339 — typo caught at compile time
},
});The compiler emits one helper per (feature, namespace) pair where the feature owns at least one action whose path: falls under the namespace prefix. Filename is define-action.<kebab(namespaceName)>.ts — eventScope becomes define-action.event-scope.ts. Helpers live next to the standard define-action.ts in <feature>/.quickback/, so the relative import is the same shape as every other action file in your project.
Opt-in, not breaking
Actions that import defineAction from ../.quickback/define-action compile with ctx.<exposeAs> as any via the AppContext index signature. Use the per-namespace helper for the narrowed type.
Compile-time advisory
When quickback build sees a namespace-scoped action still importing the generic helper, it emits a one-line advisory pointing at the narrowed path:
[quickback:typing] action "feedMoments" in feature "feeds" lives under
namespace "eventScope" — switch its import to
`../.quickback/define-action.event-scope` for narrow ctx.<exposeAs> typing.
(Runtime behavior is unchanged; the narrowed helper only refines TS types.)Non-blocking — same [quickback:typing] family as [quickback:authz]. The advisory only mentions actions the compiler can be confident about (namespace-claimed actions whose source still imports the generic helper).
Multi-namespace features
A single feature can contribute actions to several namespaces — say, an interviews feature with actions under both interviewScope and eventScope. The compiler emits one narrowed helper per namespace the feature participates in, and each action picks the import that matches its path.
src/features/interviews/.quickback/
├── define-action.ts # generic — standard fallback
├── define-action.interview-scope.ts # ctx.interview typed
└── define-action.event-scope.ts # ctx.event typedWhy per-namespace and not per-action
A defineAction helper that's narrow to one exposed key (the namespace's exposeAs) is enough — every action under a namespace sees the same hydrated key. The alternative (per-action emit) duplicates the same prelude N times for the same shape; per-namespace keeps emission proportional to the number of distinct hydration shapes in the project.
Feature Areas - Hierarchical Authz Grouping
Group features under an area folder with _area.ts. The area declares a route prefix, admission lanes, and an authz vocabulary that only its own subtree may reference.
Diagnostics
The compile-time authz / authn analyzer. Reads the lowered policy IR and flags empty or shadowed permissions, unreachable roles and views, capability-ceiling breaches, the not-over-resource null-trap, and pushdown cost. Zero-false-positive checks fail the compile with an explicit authz.analyzer.allow override surface; heuristic checks warn, with a QUICKBACK_AUTHZ_STRICT opt-in that promotes warnings too. Source-analysis codes check authored action, lib, and template files for raw database handles, Better Auth table writes, in-body role checks, undeclared env reads, and unescaped HTML.