Access requests
Members ask for a role in their organization, for a set time if they like. The request goes through approvals, the final approval grants the role, and the grant ends early or when it expires.
access-requests lets a member ask for a role (a viewer asking to be an admin for month end, a contractor asking to join). It files the request with the approvals module, so approvers, steps, delegation, notifications and expiry work as they do there. The final approval grants the role, and when the grant has a duration, expire_access_grants() puts the previous role back. Asking needs access_requests.create, reading other people's requests needs access_requests.read, and ending someone else's grant needs access_requests.manage.
better-supabase add access-requestsServer code calls the access-requests instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useAccessRequests } = defineDataHooks(
"accessRequests",
(db: AppDb) => db.accessRequests,
);import { createAccessRequests } from "better-supabase/blocks/access-requests";
import { createApprovals } from "better-supabase/blocks/approvals";
const request = await db.accessRequests
.request({
organizationId,
role: "admin",
reason: "Month end",
duration: Temporal.Duration.from({ days: 3 }),
})
.orThrow();
// An approver decides through approvals.
const approvals = createApprovals({ transport });
await approvals.approve(request.approvalId!).orThrow();"use client";
import { useAccessRequests } from "@/lib/supabase/hooks";
const rows = useAccessRequests({ limit: 50 });Configure
blocks: {
"access-requests": {
options: {
roles: ["admin", "billing"],
maxDuration: "P7D",
policy: { steps: [{ approvers: { role: "owner" } }], expiresIn: "P2D" },
},
},
},| Option | Default | What it does |
|---|---|---|
roles | every role of the access model except owner | The roles a member may ask for (ACCESS_ROLE_INVALID otherwise) |
policy | one step: holders of members.update_role | An approvals policy without run: steps, expiresIn, selfApproval |
maxDuration | none | An ISO 8601 duration that caps a grant and is the default when a request names none |
join | false | Lets someone outside the organization ask to join with a role |
emergency | { maxHours: 8 } | How long emergency access lasts, from 1 to 168 hours |
A member can have one pending request per organization (ACCESS_REQUEST_PENDING), can't ask for the role they hold (ACCESS_ROLE_HELD), and an owner can't ask for another role.
Paging a list
list is the capped convenience list. page is the full contract for requests (ADR 0749, 0939): it takes organizationId, which names the organization per call, and sort, filters whose values are lists (a row matches any of a filter's values), after and limit, and returns { items, hasMore, nextCursor }. Pass the nextCursor back as after. The sort is createdAt; the default order is newest first. The filters are status, role and mine ("true" keeps the caller's own requests, even for readers of the organization). The facets are status and role. Readers of the organization see every request, others see their own. list is the same read with status, mine, pageSize and before. A cursor belongs to the sort it came from, so start again from the first page when sort or direction changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error.
const pending = await access
.page({ organizationId, filters: { status: ["pending"] }, limit: 20 })
.orThrow();
const facets = await access.facets({ organizationId }).orThrow();
const total = await access.count({ organizationId }).orThrow();Record access
With the subjects block installed and a subject type that has a team, a member can ask for access to one record instead of a role. requestRecord names the subject type, the record id and the action (read by default), with a duration of 7 days unless the request names one; maxDuration caps it here too.
const request = await db.accessRequests
.requestRecord({
subjectType: "client",
subjectId: clientId,
reason: "Covering for Ana this week",
duration: Temporal.Duration.from({ days: 2 }),
})
.orThrow();The record's team leads approve it; a record without a lead goes to the holders of subjects.manage. The policy option still sets the expiry and self approval. On the final approval the module adds a subject_members row whose endsAt is the end of the grant, so the requester gets the access the record's team has until then. end(id) and expire_access_grants() close that row, and they never close access the member already had through the team.
A request for a subject type without a team, an unknown action, a record that doesn't exist or access the member already has fails with ACCESS_REQUEST_RECORD_INVALID. A member can have one pending request per record. Read a request's target from request.target: role or record.
records(subjectType, subjectId) lists the requests on one record, newest first. Readers of the organization's requests (access_requests.read), the record's team leads and its approvers see all of them; anyone else sees their own. Pass { status: "pending" } to list the open ones, and pageSize (50 by default, at most 200).
const pending = await db.accessRequests
.records("client", clientId, { status: "pending" })
.orThrow();A block that keeps its own grants, such as the drive, contributes an access grant for its subject type. The module then calls the block's grant function on approval and again with ends_at = now() when the grant ends, instead of adding a subject_members row. The contribution can also name an approvers function, which returns the users who approve a request when the record has no team lead (the drive names the node's owners); without one, the holders of subjects.manage approve.
Emergency access
Emergency access is break-glass access to one record: it starts at once, without an approval, and is reviewed afterwards. It needs access_requests.emergency, which owners and admins hold and members don't (grant it to an on-call role), and a reason of at least 10 characters (ACCESS_REQUEST_REASON_REQUIRED).
const access = await db.accessRequests
.openEmergency({
subjectType: "patient",
subjectId: patientId,
reason: "On call, the patient is in the emergency room",
})
.orThrow();The grant is a subject_members row marked emergency that ends after emergency.maxHours (8 by default). The record's team leads and the holders of access_requests.review get a notification. A reviewer lists the grants with emergencies(organizationId) (unreviewed ones by default; pass { unreviewed: false } for all) and records a verdict:
await db.accessRequests
.reviewEmergency(access.id, {
verdict: "justified",
note: "Confirmed with the shift lead",
})
.orThrow();Reviewing needs access_requests.review, which owners and admins hold. Nobody reviews their own emergency access, and a grant is reviewed once (ACCESS_REQUEST_REVIEW_INVALID). The verdict, the note, the reviewer and the time are on access.review.
Statuses
pending, rejected, cancelled and expired follow the approval request; cancel a request with approvals.cancel(request.approvalId). granted means the role is held, and ended means it was given up, revoked or ran out.
end(id) ends a grant early, for the holder or a manager. Schedule expire_access_grants() to end grants past their expiresAt:
select cron.schedule('expire-access', '*/5 * * * *', 'select better_supabase.expire_access_grants()');When a grant ends, the previous role comes back (or the membership goes, for someone who joined through the request), unless the role was changed in the meantime: a later change wins.
The provider access model
With the provider access model the module doesn't touch memberships. The authorization provider's adapter grants the role when it receives access_request.approved and takes it back on access_request.ended.
Events and hooks
The module records access_request.requested, access_request.approved and access_request.ended (with reason set to expired or revoked), each with organizationId, userId, role, the request id, approvalId and expiresAt, plus target, subjectType, subjectId and action (null for a role request; role is null for a record request). Emergency access records access_request.emergency_opened (with the reason) and access_request.emergency_reviewed (with the verdict) instead. They all go to the audit log. The approvals module records its own approval.* events for the request. The module calls before_access_request and after_access_request for role requests, and before_access_grant and after_access_grant for every grant.
With ReUI
An admin page renders list(organizationId, { status: "pending" }) in a ReUI data grid with approve and reject actions from the approvals client. A member's request form pairs a role select with a duration select and shows their requests from list(organizationId, { mine: true }).
Your own fields
Columns you add to access_requests with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createAccessRequests a Standard Schema
for them as fields: request take them next to the block's own keys and
validate them (a bad value is a validation error), and every read return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createAccessRequests({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.accessRequests is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createAccessRequests } from "better-supabase/blocks/access-requests";
import { createApprovals } from "better-supabase/blocks/approvals";
const access = createAccessRequests({ transport });
const request = await access
.request({
organizationId,
role: "admin",
reason: "Month end",
duration: Temporal.Duration.from({ days: 3 }),
})
.orThrow();
// An approver decides through approvals.
const approvals = createApprovals({ transport });
await approvals.approve(request.approvalId!).orThrow();Last updated on