Drive
Folders and files on the attachments module. Access is granted to users or teams and inherited down the tree, storage policies enforce it on the objects too, and versions, trash and share-links add revisions, a bin, stars, recent items and folder links.
drive keeps a tree of folders and files per organization. A file is a node that points at an attachment, so uploads, scanning and signed downloads work as they do there. Access is granted on a node to a user, a team or an organization role and applies to everything under it: a viewer on Projects can read Projects/Launch/plan.pdf. The same check runs in the drive functions, in the policies on the attachment rows and in restrictive policies on storage.objects, so a signed URL never opens a file the caller can't read.
better-supabase add drivedrive installs drive-files with it, which adds what needs the attachments module: uploads and revisions, the storage policies, the bin, stars, recent items, folder links and the purge. Install versions, trash, share-links and teams for revisions, the bin, stars and links, and team grants.
Server code calls the drive instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useDrive } = defineDataHooks(
"drive",
(db: AppDb) => db.drive,
);import { createAttachments } from "better-supabase/blocks/attachments";
import { createDrive, rpcTransport } from "better-supabase/blocks/drive";
const transport = rpcTransport(supabase);
const projects = await db.drive
.createFolder(organizationId, { name: "Projects" })
.orThrow();
const upload = await db.drive
.upload(organizationId, {
parentId: projects.id,
name: file.name,
mimeType: file.type,
size: file.size,
})
.orThrow();
await supabase.storage
.from(upload.attachment.bucket)
.uploadToSignedUrl(upload.attachment.path, upload.token, file);
await db.drive.commit(upload.node.id, upload.attachment.id).orThrow();
await db.drive.share(projects.id, { type: "team", id: designTeam }, "editor");
await db.drive.share(projects.id, { type: "role", id: memberRoleId }, "viewer");
const { signedUrl } = await db.drive.download(upload.node.id).orThrow();"use client";
import { useDrive } from "@/lib/supabase/hooks";
const rows = useDrive({ limit: 50 });Access
Each node has a role for the caller: the highest role granted on the node or any folder above it, or null when nothing is granted. Members with drive.manage have the top role on every node in the organization, and the service role always does. Reading anything needs drive.read, and creating a node at the root needs drive.create.
| Role | What it allows |
|---|---|
viewer | List, open and download the node and everything under it |
editor | Create, upload, rename, move, trash and restore revisions under it |
owner | Share and unshare, and everything an editor can do |
Add your own roles to the ladder with roles, lowest first. A commenter between viewer and editor becomes the comment role (commentRole): drive_can_comment(node) is true from that role up, so a commenter reads and comments but doesn't change the file. A manager above editor with shareRole: "manager" lets people share and set download blocks without being the top role. Without a commenter, the comment role is the write role.
The creator of a node gets the top role on it. Grants with an expiresAt stop applying after that time. drive_role(node) and drive_can(node, role) are SQL functions, so your own policies can use them too. The block's own read policy uses id in (select drive_readable_ids()) instead, which returns every node drive_can(node, read) is true for in one call, so Postgres runs it once per statement rather than once per row; prefer it in your policies on large drives.
With roleFunctions.node or roleFunctions.drive, the block calls a schema-qualified function you name with the node or drive id and the caller's user id, and uses the role it returns. The function returns one of roles, or null. It replaces the block's own grants at that level, while the tenant drive.read check still applies. Use it when your own rules already decide who may read a node or a drive, such as an AuthorizationProvider.
When an authorization provider grants access per row, set { rows, roles } instead of a function name: rows is the provider's resource and roles maps each role of roles to the permission key that grants it. The block generates the check through the provider's rowsWith template (blocks.permissions.model: "provider"), and the caller gets the highest role whose key they hold on the node or drive.
drive: {
options: {
roleFunctions: {
node: {
rows: "file_node",
roles: {
viewer: "fileNode.read",
editor: "fileNode.update",
owner: "fileNode.manage",
},
},
},
},
},When the provider's roles are not permission keys, give rows alone. The block then asks the provider's roleOn template for the role on each node.
Roles without grant rows
Set grants: "roles" when your role function is the only place access lives, so the block keeps no copy of it. The block creates no drive_grants table, and database.types.ts no longer has it or its principalType and principalId columns. It needs roleFunctions.node, either a function name or a provider entry, and refuses uploadRole and a tables.grants mapping.
drive: {
options: {
grants: "roles",
roleFunctions: { node: { rows: "file_node" } },
},
},| Function | With grants: "roles" |
|---|---|
drive_role, drive_can | The role function's answer, a role of roles or null |
drive_grants(node) | Each active member the role function gives a role, as a user principal that is never inherited |
drive_share, drive_unshare | Refuse with DRIVE_SHARING_EXTERNAL (SQLSTATE 0A000): change the role where the role function reads |
drive_transfer_ownership | Moves drive grants and drive owners only; node roles move where the role function reads them |
drive_shared(tenant) | Items the role function opens for the caller whose folder they can't open |
| Access requests | Not available, because an approved request has no grant row to write |
Configure
blocks: {
drive: {
options: {
roles: ["viewer", "commenter", "editor", "manager", "owner"],
writeRole: "editor",
shareRole: "manager",
conflict: "rename",
},
},
},| Option | Default | What it does |
|---|---|---|
roles | ["viewer", "editor", "owner"] | The roles, lowest first; the first one reads and the last one is the top role |
writeRole | editor, else the top role | The role that may create, rename, move and trash |
shareRole | the top role | The role that may share and unshare, break locks and block downloads |
commentRole | commenter, else writeRole | The role drive_can_comment checks |
previewPrefix | _previews | The storage folder preview pages go to, in the attachment's bucket |
memberRole | none | A role every member of the organization has on every node |
uploadRole | none | A role, outside roles, that adds files to a folder without reading it |
conflict | fail | What a duplicate name in a folder does: fail, rename (plan (2).pdf) or replace |
subjectType | drive_node | The subject type of nodes in events, audit entries, attachments, versions and trash |
drives | false | Several drives per organization, with drive-level grants and connected drives |
driveKinds | ["shared"] | The kinds a drive can have; the first is the default |
sources | ["google-drive", "onedrive"] | The providers a connection can mirror |
roleFunctions | none | App functions or provider row grants that give the caller's role |
grants | table | roles keeps no grants table and lets roleFunctions.node decide, as Roles without grant rows shows |
readPolicy | true | The block's read policies; false leaves them to the app |
quota | none | { meter }: a usage meter in bytes that uploads must fit, as Quotas shows |
maxTextBytes | 1048576 | The most extracted text kept per file, in bytes |
control | none | { types, reviewMonths, releaseRole }: controlled documents |
Each call that creates, renames or moves a node can pass its own conflict. Names compare case-insensitively within one folder.
Upload-only access
Set uploadRole to give people a folder they can drop files into without seeing what's in it, such as a contributor on an Inbox folder. The role sits outside the roles ladder, and you grant it on a folder like any other role. It needs the node table's createdBy column, because a contributor keeps access to the files they added.
drive: {
options: { uploadRole: "contributor" },
},await db.drive.share(inbox.id, { type: "user", id: vendorId }, "contributor");
// As the contributor:
const file = await db.drive
.contribute(organizationId, {
parentId: inbox.id,
name: invoice.name,
mimeType: invoice.type,
size: invoice.size,
})
.orThrow();
await supabase.storage
.from(file.attachment.bucket)
.uploadToSignedUrl(file.attachment.path, file.token, invoice);
await db.drive.commitContribution(file.id, file.attachment.id).orThrow();A contributor can't list, open or download the folder or anything in it, including their own files: get and list return DRIVE_NOT_FOUND for them. contribute takes a free name (invoice (2).pdf) so a contributor never learns which names the folder already holds, and it returns the new file's id and its upload, not the node. The contributor may upload a revision of a file they added and commit it, and nothing else; renaming, moving, trashing and sharing still need the write or share role. drive_can_upload(folder) is the check in SQL, true for the upload role and for the write role. Granting the upload role on a file fails with DRIVE_ROLE_UNKNOWN.
The upload role works on node grants, not on drive grants. When your grant table's role column is an enum, add the upload role's value to it.
Access requests
With access-requests installed, a member who finds a link to a node they can't open can ask for access instead of asking someone to share it. Turn it on in the subject entry; accessRequests: true lets members ask to read, and a list such as ["read", "write"] names the actions they may ask for:
recordTypes: {
drive_node: driveSubject({ accessRequests: true }),
},Pass the access-requests client to the drive as recordAccess (createBlocks wires it for you), then call requestAccess and accessRequests:
const drive = createDrive({
transport,
recordAccess: createAccessRequests({ transport }),
});
const request = await drive
.requestAccess(nodeId, {
action: "read",
reason: "Preparing the quarter close",
duration: Temporal.Duration.from({ days: 3 }),
})
.orThrow();
const pending = await drive
.accessRequests(nodeId, { status: "pending" })
.orThrow();The users who hold the top role on the node, on a folder above it or on its drive approve the request; without one, the holders of subjects.manage do. On approval the drive adds a node grant marked as an access request, with the read role for read, the comment role for comment and the write role for write, that ends with the request (7 days unless the request names a duration). Ending the request, or expire_access_grants(), removes that grant and never touches a grant someone shared by hand. A client built without recordAccess returns invalid_request with the hint DRIVE_ACCESS_REQUESTS_CLIENT. Over your own grant table, map a boolean accessRequest column and expiresAt in blocks.drive.columns.grants; without them, rendering the SQL fails with an error that names them.
An approved request changes the node's grants, not its record team. Adding someone to the node's team with create_subject_member lets them read the node's comments and attachments, but not the node itself: share the node for that.
Ownership and offboarding
transferOwnership hands everything one member holds at the top role to another member: their top-role grants on nodes, and with drives on, their drive grants and the drives they own. It needs drive.manage or the service role, and the new owner must be a member (DRIVE_PRINCIPAL_NOT_FOUND). Each moved node records drive_node.ownership_transferred and each drive drive.ownership_transferred. A drive the new owner can't own stays with the old owner, together with its drive grants and the top-role grants on its files: when your table keeps one drive of a kind per owner, such as a personal drive, with a unique index or a check over the owner column, the transfer skips that drive instead of failing and returns its id in keptDriveIds. Any other unique or check violation still fails the transfer. driveOffboardingSink passes the kept drives to its onKept option, so you can archive or reassign them, and logs a warning without it.
const moved = await db.drive
.transferOwnership(organizationId, leavingUserId, managerId)
.orThrow();
// { nodes: 12, drives: 1 }driveOffboardingSink runs the transfer from the outbox when a member leaves, on organization.member_removed and on the employees block's employee.offboarded. transferTo names the new owner from the event; return undefined to keep the items where they are. Give it a drive client on the service transport, since the member's grants are gone by the time the event arrives:
import { driveOffboardingSink } from "better-supabase/blocks/drive";
const driveOffboarding = driveOffboardingSink(admin.$blocks.drive, {
transferTo: async (event) => ownerOf(event.organizationId),
});A failed transfer throws, so the outbox retries the event.
Sharing policy
With the settings block installed, an organization can turn sharing down through the drive.sharing organization setting. guests: false refuses guest grants on drive items, and links takes anyone (the default), organization, which lets only signed-in members of the organization open a link, or none, which refuses new share links and stops existing ones from opening. Refusals fail with forbidden and the hint DRIVE_SHARING_DISABLED.
import { driveSettings } from "better-supabase/blocks/drive";
export const settings = defineSettings({
organization: { ...driveSettings.schemas.organization },
});driveSettings declares the setting with its schema and default ({ guests: true, links: "anyone" }), and drive_sharing(tenant) returns the merged value in SQL for your own policies. Sharing with members of the organization is never restricted by this setting.
File requests
A file request lets anyone with a link send files into a folder, without an account. It is a share link with the role upload, so it takes the same expiry, use limit and password. createFileRequest needs the share role on the folder, and the token comes back once:
const request = await db.drive
.createFileRequest(inbox.id, {
expiresAt: Temporal.Now.instant().add({ hours: 72 }),
maxUses: 10,
password: "harbor-pier",
})
.orThrow();
const url = `https://app.example.com/send/${request.token}`;The page behind that URL posts the file to your server, which sends it on with a drive client made from the service transport and the service storage client:
"use server";
const drive = createDrive({
transport: serviceTransport,
storage: serviceStorage,
});
const sent = await drive
.uploadToRequest({ token, file, options: { name: file.name, password } })
.orThrow();
if (sent.passwordRequired) {
return { passwordRequired: true };
}uploadToRequest resolves the token, creates the file in the folder under a free name, uploads the bytes and commits them. Each file counts one use of the link, and the files a link takes are counted per link under the scope drive_link_upload when the rate-limit module is installed: 20 an hour, unless set_rate_limit('drive_link_upload', ...) sets another rule. Past the limit the call fails with rate_limited and the hint DRIVE_LINK_RATE_LIMITED. A wrong or missing password returns { passwordRequired: true } instead of an error. A view or download link fails with DRIVE_LINK_ROLE_INVALID.
A file that came through a request has the source request and no creator, and drive_node.created carries that source, so a sink can tell the folder's owner a file arrived. Unlike files mirrored from a connection, request files aren't read-only: the folder's editors rename, move and trash them like any other file. When your node table's source column is an enum, add request to it.
Pass a Standard Schema for the extra columns
as fields to createDrive: every node the client returns has its fields
parsed, and createFolder and upload validate the ones you set before the
call (see extending blocks).
Drives, connections and legal holds
With drives on, every node belongs to a drive: drive_drives holds the drives of an organization, drive_drive_grants their grants and drive_connections the external accounts they mirror. A top-level node needs a drive; a child stays in its parent's drive. Drive-level grants apply to every node in the drive, on top of node grants, and a drive's owner and members with drive.manage have the top role on it.
const drive = await db.drive
.createDrive({ organizationId, drive: { name: "Projects", kind: "shared" } })
.orThrow();
const folder = await db.drive
.createFolder({
organizationId,
folder: { name: "Launch", driveId: drive.id },
})
.orThrow();
const roots = await db.drive
.list({ organizationId, options: { driveId: drive.id } })
.orThrow();
await db.drive.shareDrive({
id: drive.id,
principal: { type: "team", id: designTeam },
role: "editor",
});drives(organizationId) lists the drives the caller can read, drive(id) reads one, and renameDrive, archiveDrive, restoreDrive, purgeDrive, shareDrive, unshareDrive and driveGrants manage them. An archived drive leaves drives() unless you pass includeArchived: true, and it refuses new items, a rename and a share with DRIVE_ARCHIVED; its content stays readable. purgeDrive removes an archived drive and everything in it, needs permissions.purge (it falls back to drive.manage) and fails with DRIVE_HELD while any node in the drive is under a legal hold.
A connection is the caller's link to an external account: connect(organizationId, provider, name) records one and connections(organizationId) lists the caller's own. createDrive(organizationId, { name, connectionId }) creates a drive that mirrors that account, owned by the connection's user. Mirrored nodes have a source other than internal, an externalId and externalMetadata, and the nodes are read-only: only the service role's drive_sync_batch changes them. Renaming, moving, sharing, uploading and trashing them fails with DRIVE_READ_ONLY.
Sync and pruning
drive_sync_batch(drive, items, root_external_id, sync_run, prune, cursor) applies a page of provider changes. With the imports block installed it records every mirrored node in import_records (source is drive:<connection id>, entity is drive_node, scope is the drive id) with a hash of the name, kind, parent and metadata the provider sent. A node whose hash is unchanged is not written, and the function returns the number of nodes it wrote. Without the imports block it upserts every listed node and stamps sync_run in the node's metadata, as before.
A full listing passes sync_run on every page and prune on the last one. sync.prune decides what happens to the nodes the listing did not reach:
blocks: { drive: { options: { drives: true, sync: { prune: "mark" } } } },sync.prune | Unlisted nodes |
|---|---|
delete (default) | The node is deleted, unless a legal hold keeps it. |
mark | The node stays, and its import_records row gets went_missing_at. A later listing that includes it clears the mark. |
mark needs the imports block and fails at render time without it. Nodes the provider reports as removed are always deleted, and a legal hold always keeps its node.
A legal hold keeps a node and everything under it from being purged. hold(id, until) sets legalHoldUntil, releaseHold(id) clears it, and every node reports held when it or something under it is held. delete(id) fails with DRIVE_HELD while a hold applies, and trash(id) refuses to move a held subtree to the bin. Configure trash with the node's hold column so a held batch stays there:
trash: {
on: {
drive_node: { deletedAt: "archived_at", held: "legal_hold_expires_at" },
},
},purge(binId) then raises TRASH_HELD, and purge_expired_trash skips the batch until the hold ends.
Files and revisions
upload creates the file node and a pending attachment, then signs an upload URL. After the upload, commit makes the attachment the file's content. uploadRevision uploads new content for an existing file the same way; with versions installed, each commit saves a revision, revisions(id) lists them and restoreRevision(id, revisionId) makes an old one current again.
download(id) signs a download URL for the current content through the attachments option, the attachments block over the same transport; createBlocks passes it as the attachments port when the set has attachmentsBlock. Without it, download fails with the hint DRIVE_ATTACHMENTS_CLIENT. With requireScan on the attachments block (the default), a file that isn't scanned clean yet can't be downloaded.
Files in Vercel Blob
The drive keeps its bytes wherever the attachments block does. Pass the same files to both, such as vercelBlobStore(blob), and a service-role transport as service, so commit and commitContribution can confirm an upload that Postgres can't see:
import * as blob from "@vercel/blob";
import { createAttachments } from "better-supabase/blocks/attachments";
import {
createDrive,
rpcTransport,
vercelBlobStore,
} from "better-supabase/blocks/drive";
const files = vercelBlobStore(blob);
export const driveFor = (supabase: SupabaseClient, admin: SupabaseClient) =>
createDrive({
transport: rpcTransport(supabase),
service: rpcTransport(admin),
files,
attachments: createAttachments({
transport: rpcTransport(supabase),
service: rpcTransport(admin),
files,
}),
});upload, uploadRevision and contribute return the presigned upload with its method and headers. commit runs drive_commit as the caller first, so the grants decide who may commit; only when the upload is missing from Storage does it confirm the attachment from the blob's head through service and commit again. put, uploadToRequest, previewUrls, prune, createDrivePreviews and createDriveText take or use the same files. The restrictive policies on storage.objects only guard Supabase Storage; with Blob, the signed URLs the drive and attachments functions hand out are the gate. The full setup, and what stays Supabase-only, is on the attachments page under Files in Vercel Blob.
Text extraction
Files become searchable by their content once their text is extracted. createDriveText reads each clean upload through a TextExtractor and stores its text in drive_node_texts, one row per file, kept at maxTextBytes. It runs as the service role: give it a service-role transport and supabase.storage, and run its sink() on the outbox relay. The sink reacts to attachment.uploaded (and to attachment.scanned, when uploads are scanned first), so a file is read only once it is clean and again for each new revision.
import {
createDriveText,
plainTextExtractor,
} from "better-supabase/blocks/drive";
const driveText = createDriveText({
transport: rpcTransport(admin.$client),
storage: admin.$client.storage,
extractor: plainTextExtractor(),
});
return admin.outbox.relayRoute({
secret: env.CRON_SECRET,
consumers: { driveText: driveText.sink() },
})(request);plainTextExtractor() reads text, JSON, XML and YAML files. For PDFs and office documents, write a TextExtractor over the library or service you use: name is stored with the text, and extract(file, meta, signal) returns the text, or undefined for a file it doesn't read. testTextExtractor from better-supabase/testing checks an extractor against the contract.
import type { TextExtractor } from "better-supabase/blocks/drive";
const pdf: TextExtractor = {
apiVersion: 1,
name: "pdf",
extract: async (file, meta) =>
meta.mimeType === "application/pdf" ? await readPdf(file) : undefined,
};A file larger than maxFileBytes (25 MB by default) isn't read and loses its stored text. An extractor that throws returns internal with the hint DRIVE_TEXT_FAILED, and the sink throws so the relay retries. extract(nodeId) runs one file by hand, and job runs it as a jobs handler with { nodeId }. When a newer revision arrives during the extraction, drive_set_text keeps nothing and the outcome is skipped.
With knowledge, the knowledge block's client, the text also becomes one knowledge document per file, scoped to the node as its subject: each new text replaces the file's earlier document, so the assistant can answer from the file. Text rows follow the node's read grants, and are deleted with the node.
Quotas
Set quota to a usage meter in bytes, and drive_create_file and drive_upload_revision check within_quota(organization, meter, size) before they accept an upload. An upload that doesn't fit fails with quota_exceeded, SQLSTATE 53400 and the hint DRIVE_QUOTA_EXCEEDED, before the object is stored. The service role isn't checked. A computed meter keeps the count true without recording each upload:
blocks: {
usage: {
options: {
meters: {
storage: {
kind: "computed",
unit: "bytes",
query: `select a.organization_id, sum(a.size)
from better_supabase.attachments a
join better_supabase.drive_nodes n on n.attachment_id = a.id
where n.archived_at is null group by 1`,
},
},
},
},
drive: { options: { quota: { meter: "storage" } } },
},Quotas need the usage block in the same set; installing drive-files with a quota and without usage fails.
Check-out, download blocks and previews
lock(id) checks a file out for the caller. Until the lock ends (8 hours by default, at most 30 days), nobody else may upload a revision, commit, restore a revision, rename, move, trash or delete it; trashing or deleting a folder fails while a file under it is checked out. Those calls fail with DRIVE_LOCKED, and the error's detail names lockedBy and lockedUntil. Locking needs the write role. unlock(id) ends the caller's own lock, and unlock(id, { force: true }) lets the share role end someone else's. The service role ignores locks. Every node reports lockedBy, lockedUntil and lockNote while a lock applies; an expired lock reads as no lock.
await db.drive
.lock({
id: fileId,
until: Temporal.Now.instant().add({ hours: 2 }),
note: "Redlining",
})
.orThrow();
// edit, upload a revision, commit
await db.drive.unlock({ id: fileId }).orThrow();blockDownloads(id) keeps the original of a node, and of everything under it, from callers below the write role; blockDownloads(id, false) lifts it. With drives on, blockDriveDownloads(driveId) does the same for a whole drive. Setting a block needs the share role. A blocked caller still lists and opens the node and reads its previews, but the storage policy refuses the original and download(id) fails with the hint DRIVE_DOWNLOAD_BLOCKED. Every node reports downloadBlocked (the flag on the node itself) and downloadable (whether the caller may download it). drive_can_download(node) is the same check in SQL.
A preview is the file's pages rendered as images, stored in the attachment's bucket under previewPrefix/<organization>/<node>/<attachment>/<page>. Readers of the node may open them even when downloads are blocked. previews(id) returns pages, bucket, prefix and the page paths, and previewUrls(id) signs them. Uploading a new revision resets the count until the new pages are rendered.
The drive doesn't render pages itself. Pass a PreviewRenderer (a PDF rasterizer, an office converter, an image resizer) to createDrivePreviews with a service-role transport and storage, then run its job or its sink:
import { createDrivePreviews } from "better-supabase/blocks/drive";
const previews = createDrivePreviews({
transport: serviceTransport,
storage: serviceStorage,
renderer: {
apiVersion: 1,
name: "pdfium",
render: async (file, { maxPages }) => renderPdfPages(file, maxPages),
},
requireClean: true,
});
await outbox.relay({ consumer: "drive-previews", sink: previews.sink() });
// or from a queue: queue.work("drive-previews", previews.job)The sink renders the file behind every attachment.uploaded and attachment.scanned event on a drive node; render(nodeId) renders one file on demand, for example after commit. A renderer returns undefined for a type it doesn't handle. With requireClean, only files the scanner marked clean render; without it, infected and failed files are skipped. For images alone, the attachments block's images() transforms can serve a resized original instead of a preview, but they don't honor a download block.
Labels and approvals
With the tags block installed, label(id, tagId) puts a tag on a node and label(id, tagId, false) takes it off; it needs write access to the node. Every node the client returns carries its labels (id, name, color), and labeled(organizationId, tagId) lists the nodes with a tag that the caller may read. Tags of any kind work as labels. Purging a node deletes its labels.
With the approvals block installed, requestApproval(id) asks for approval of the file's current content, and requestApproval(id, { attachmentId, reason }) asks for one earlier revision. The request records the attachment and the revision number in its payload, so a decision covers exactly those bytes. Add a policy for the approve action on the node subject:
approvals: {
options: {
policies: {
drive_node: {
approve: { steps: [{ approvers: { permission: "approvals.manage" }, required: 1 }] },
},
},
},
},approvals(id) lists the file's requests, newest first, each with attachmentId, revision and current (whether that revision is still the file's content). Every node carries approval: the latest request for its current content, or undefined. Uploading a new revision clears it, and restoring an approved revision brings the approval back. A file has at most one pending request at a time, so a second request fails with APPROVAL_PENDING. Requests stay after the node is purged, as the record of what was decided.
Anyone who can read a node sees its labels and its approval state. Tagging, untagging and requesting approval need write access, and the tags and approvals functions check the same drive grants when they are called directly with the drive_node subject type.
Retention per label and the changes feed
With the tags, trash and data lifecycle modules installed, a label can carry a retention policy. The policy kind is drive_label_ and the label's name in lower case, with every run of other characters as one underscore, so the label "Final contract" has the kind drive_label_final_contract. drive_retention_kind(name) returns it. Set the policy with the retention client like any other, for one organization, a plan or every organization:
await retention
.setPolicy("drive_label_final_contract", "7 years", { organizationId })
.orThrow();sweepRetention() is a service role call that moves every node whose label policy has run out into the bin, oldest first, and returns how many it binned. A node counts as old when it was last changed longer ago than the policy keeps it; moving a node into the bin or back changes it. The shortest policy among a node's labels wins. A node under a drive hold, under a legal hold on the policy kind, or checked out is skipped. Run it from a schedule; batchSize (default 100) bounds one call. The bin's own retention purges the nodes later, so a swept file can still be restored until then.
changes(organizationId, { cursor }) is the feed for sync clients. It returns the nodes the caller can read that changed after the cursor, oldest first, as { removed: false, node } or { removed: true, id } for a node in the bin, together with the next cursor and more. Omit the cursor for the first full sync, store the returned one, and call again until more is false. A restore brings the node back as a node. A node deleted for good leaves no entry, so it is in the bin first unless your code deleted it directly. Changes from the last five seconds wait for the next call, so a transaction that commits late isn't skipped. A cursor from changes is the only valid input; anything else fails with DRIVE_CURSOR_INVALID. Access changes (grants, links) don't appear in the feed.
Controlled documents
With options.control, files become controlled documents: each gets a number, a type, an owner and a review date, a version becomes effective only through an approved release request, and members below the write role read only the effective version. Controlled documents covers the lifecycle, the register and periodic reviews.
Metadata
Typed metadata on files and folders comes from the custom fields block. Define fields on the drive_node entity and set them on a node as its subject; with readAccess: "record" on the node subject, only members who can read a node see its values and only editors set them (see Comments, search and relations on nodes).
const contract = await db.customFields
.saveDefinition({
entity: "drive_node",
key: "contract_type",
label: "Contract type",
type: "option",
})
.orThrow();
await db.customFields
.setValue({
subject: { type: "drive_node", id: fileId },
definitionId: contract.id,
value: "nda",
})
.orThrow();A saved view over drive_node then filters the drive on those fields, such as every contract of type nda.
The bin
With trash installed, trash(id) moves a node and everything under it to the bin as one batch, and bin(organizationId) lists the batches. restore(binId) puts the batch back, applying the conflict policy if the name is taken again. A node whose folder is still in the bin can't come back until the folder does. purge(binId) deletes it for good and records drive_node.purged with the object paths. purge and delete(id) (drive_delete, which skips the bin) need the share role on the node; when the share role is also your editing role (a roles list without owner), set permissions.delete to a tenant key, such as one only admins hold, and both also need that key. Run prune() from the service role to delete the purged objects from storage:
const drive = createDrive({ transport: serviceTransport, storage });
await drive.prune({ maxObjects: 500 }).orThrow();Stars, recent items and links
With share-links installed, star(id) and star(id, false) mark a node for the caller, open(id) records that the caller opened it, and starred and recent list them. A share link on a folder opens it and the nodes under it: link(token) returns the folder and its children, and link(token, { nodeId }) returns one node under it with its stored object.
Creating a link on a node needs the share role. A view or download link opens the item. Its downloadAllowed is false, and the stored object is left out, when the link was created with downloadAllowed: false or a download block covers the item; the previews still come back. An upload link names a folder, and link(token) refuses it with DRIVE_LINK_ROLE_INVALID, since it takes files and opens nothing; file requests send files through one.
With ReUI
driveTree(nodes) shapes the nodes you loaded for a tree view such as the ReUI file tree on headless-tree: it returns rootItemId, getItem, getChildren and isFolder. fileTypeCategory(mimeType, name) and nodeType(node) name a file's kind (image, pdf, spreadsheet, code and others) to pick its icon.
import { driveTree, nodeType } from "better-supabase/blocks/drive";
const data = driveTree(await drive.list({ organizationId }).orThrow());
const tree = useTree({
rootItemId: data.rootItemId,
getItemName: (item) => data.name(item.getId()),
isItemFolder: (item) => data.isFolder(item.getId()),
dataLoader: { getItem: data.getItem, getChildren: data.getChildren },
features: [syncDataLoaderFeature],
});Load a folder's children with list(organizationId, { parentId }) as it opens, and build the tree again from all the nodes loaded so far.
Helpers for a folder page
A folder page needs the node, its children, the breadcrumbs, what the caller may do and who has a grant. drive.folder reads all of it in one call, and returns only the children at the root.
const view = await db.drive.folder({ organizationId, nodeId }).orThrow();
// view.node, view.children, view.breadcrumbs, view.access, view.grantsview.access comes from the SQL function drive_node_access, so the flags (role, read, comment, download, upload, write, share) follow your configured roles. drive.can(id) returns the same flags for one node. drive.search({ organizationId, query }) finds nodes by name or extracted text, and treats % and _ as plain characters.
drive.put uploads a file from the server: it creates the pending node, stores the bytes and commits it, and deletes the node when the upload fails. drive.bulkShare(items) gives each node its own grants ({ id, grants }) and returns { succeeded, failed } named by node id, so one refused node does not stop the others (ADR 1075). drive.shareMany({ ids, grants }) gives every grant on every node and stops at the first failure; it is deprecated and removed in 0.70.
The block stores no member names, so drive.grantsWithNames({ id, names }) takes a names(principal) function that you answer from your own users table. It is called once for each distinct principal.
Comments, search and relations on nodes
driveSubject() describes the node table as a subject, so the subject registry lets comments, reactions and other blocks attach to nodes with the drive's read and write rules. It also carries a search entry: with the search block installed, node names and their extracted text (its first 100,000 characters) are indexed as they are created, renamed and read, trashed nodes drop out of the results, and relations can link a node to any other subject:
import { driveSubject } from "better-supabase/blocks/drive";
export default defineConfig({ records: { drive_node: driveSubject() } });The entry follows the node's grants, not only the tenant keys. Its read action asks drive.read and drive_node_readable(node), its comment action asks drive_can_comment(node) (the comment role), and its fields action asks drive_node_writable(node), all through check functions (see Actions granted per row). With readAccess: "record", custom fields on a node are readable only by members who can read the node, and only editors can set them. can_subject_for can't run the check functions for another user, so it returns false for a node's read.
Over your own tables
Map tables.nodes and tables.grants to run the drive on your own tree and grant tables. A grant table can name its principal with principalType and principalId columns (users, teams and roles), or with a user column and an optional team column (users and teams). With drives on, map tables.drives, tables.driveGrants and tables.connections too; a drive grant table takes the same principal columns as a node grant table. Set attachment to null when your files don't live in attachments: the tree, grants, sharing and checks still work, and uploads stay with your code.
The node columns lockedBy, lockedUntil and lockNote (check-out), downloadBlocked (download blocks) and previewPages (previews), and the drive column downloadBlocked, are optional. Map one to null when your table doesn't have it, and the block leaves that feature out; the block's own tables have them all.
The node kind and source, the role of node and drive grants, the drive kind and the connection provider and status may be enums of yours: the block casts what it writes into them and compares roles as text.
When your schema already has its own read policies, set readPolicy to false so the block leaves reads to them. Name roleFunctions.node or roleFunctions.drive to let your own functions decide the caller's role at that level, as the Access section describes.
drive: {
tables: { nodes: "public.file_node", grants: "public.file_node_grant" },
columns: {
nodes: { tenant: "organization_id", attachment: null, path: null, rank: null, deletedAt: null },
grants: {
tenant: "organization_id",
node: "file_node_id",
principalType: null,
principalId: null,
expiresAt: null,
createdBy: null,
},
},
options: { roles: ["viewer", "commenter", "editor"] },
},Open files in an office editor (WOPI)
createWopiHost answers the WOPI protocol for drive files, so an editor such
as Collabora Online or Microsoft 365 for the web opens, edits and saves a
file in place. It implements CheckFileInfo, GetFile, PutFile, Lock,
Unlock, RefreshLock, GetLock and UnlockAndRelock. The editor's lock
id is stored on the file's check-out lock (the lockNote column), so nobody
else can rename, move or upload over the file while it is open. PutFile
adds a revision through uploadRevision and commit, and answers the
current revision in X-WOPI-ItemVersion.
import { createWopiHost } from "better-supabase/blocks/drive";
export const wopi = createWopiHost({
secret: process.env.WOPI_TOKEN_SECRET!,
// A drive client that acts as the token's user, so grants and audit apply.
driveFor: ({ userId }) => driveForUser(userId),
});
// Any route that passes a Request, for example a Next.js route handler:
// app/wopi/[...path]/route.ts
export const GET = wopi.handle;
export const POST = wopi.handle;
// When a user opens a file, mint a token and send it to the editor as
// `access_token` and `access_token_ttl`.
const { accessToken, accessTokenTtl } = await wopi.token({
fileId,
userId,
userName,
canWrite: node.role !== "viewer",
});Tokens are signed with HMAC-SHA256 through WebCrypto, name one file and one
user, and expire after ten minutes unless you pass ttlSeconds. The host
imports no Node built-ins, so it runs on every WinterTC runtime. A lock
lasts 30 minutes (lockMinutes), and PutFile refuses a body over
maxBytes (100 MiB) with 413. A file locked by a person through lock()
answers 409 with an empty X-WOPI-Lock, so the editor opens it read-only.
Errors
| Hint | When |
|---|---|
DRIVE_NOT_FOUND | The node doesn't exist, or the caller may not read it |
DRIVE_FORBIDDEN | The caller's role on the node doesn't allow the change |
DRIVE_NAME_CONFLICT | The folder already has a node with that name and conflict is fail |
DRIVE_NAME_INVALID | The name isn't 1 to 255 characters, or holds a / or a control character |
DRIVE_CONFLICT_INVALID | conflict isn't fail, rename or replace |
DRIVE_PARENT_NOT_FOUND | The parent folder doesn't exist in the organization |
DRIVE_PARENT_NOT_FOLDER | The parent is a file |
DRIVE_PARENT_TRASHED | restore names a node whose folder is still in the bin |
DRIVE_MOVE_CYCLE | The move puts a folder inside itself |
DRIVE_RANK_INVALID | The rank isn't a rank key |
DRIVE_ROLE_UNKNOWN | The role isn't one of options.roles |
DRIVE_PRINCIPAL_INVALID | The principal type isn't user, team or role, or the id is missing |
DRIVE_PRINCIPAL_NOT_FOUND | The user isn't a member, or the team or role isn't in the organization |
DRIVE_NOT_A_FILE | A file call names a folder |
DRIVE_ATTACHMENT_NOT_FOUND | commit or requestApproval names an upload that doesn't belong to the file, or isn't uploaded yet |
DRIVE_REVISION_NOT_FOUND | The revision doesn't belong to the file |
DRIVE_LINK_NOT_FOUND | The link is unknown, expired or revoked, or the node isn't under it |
DRIVE_STORAGE_CLIENT | A file call ran on a client created without storage |
DRIVE_READ_ONLY | The node mirrors an external account, so only the sync may change it |
DRIVE_HELD | The node or something under it is under a legal hold |
DRIVE_HOLD_INVALID | hold needs an end in the future |
DRIVE_REQUIRED | A top-level node needs a drive |
DRIVE_KIND_INVALID | The drive kind isn't one of options.driveKinds |
DRIVE_CONNECTION_NOT_FOUND | createDrive names a connection that doesn't exist or isn't the caller's |
DRIVE_CONNECTION_EXISTS | The caller already connected this account under that name |
DRIVE_PROVIDER_INVALID | The provider isn't one of options.sources |
DRIVE_NOT_CONNECTED | drive_sync_batch names a drive that doesn't mirror a connection |
DRIVE_OWNER_NOT_MEMBER | The owner isn't an active member of the organization |
DRIVE_LOCKED | Someone else has the file, or a file under the folder, checked out |
DRIVE_LOCK_INVALID | The lock doesn't end in the future within 30 days, or the note is over 500 characters |
DRIVE_DOWNLOAD_BLOCKED | download names a file whose downloads are blocked for the caller |
DRIVE_TARGET_INVALID | A download block names an unknown target type, or blocked isn't true or false |
DRIVE_LINK_ROLE_INVALID | An upload link names a file, link opens an upload link, or a view link takes a file |
DRIVE_LINK_RATE_LIMITED | A file request took more files than its rate limit allows |
DRIVE_PREVIEWS_INVALID | drive_set_previews got no page count or a negative one |
DRIVE_QUOTA_EXCEEDED | The upload would pass the organization's quota meter |
DRIVE_TEXT_FAILED | The text extractor threw while reading the file |
DRIVE_TRANSFER_INVALID | transferOwnership names the same user twice, or no user |
DRIVE_SHARING_DISABLED | The organization's drive.sharing setting turns off that link or guest grant |
DRIVE_ACCESS_REQUESTS_CLIENT | requestAccess or accessRequests ran on a client created without recordAccess |
TRASH_HELD | purge names a batch with a subject under a legal hold |
A read-only support session refuses every write with ACTOR_READ_ONLY. In a
writable support session,
commit first claims the uploaded object for the user the admin acts as,
which records the session on it. A claim Storage refuses returns forbidden
with the hint DRIVE_FORBIDDEN, and the upload stays uncommitted.
Events and hooks
The drive records drive_node.created, drive_node.renamed, drive_node.moved, drive_node.shared, drive_node.unshared, drive_node.purged, drive_node.hold_placed, drive_node.hold_released, drive_node.locked, drive_node.unlocked, drive_node.download_blocked_changed and drive_node.ownership_transferred; with drives on it also records drive.created, drive.renamed, drive.archived, drive.restored, drive.purged, drive.shared, drive.unshared, drive.download_blocked_changed, drive.ownership_transferred, drive.connection_created and drive.connection_removed. The events page lists their payloads. Sharing, unsharing, download blocks and ownership transfers also write an access audit entry. The before_ and after_ SQL hooks run around drive_node_create, drive_node_move, drive_node_rename and drive_node_share, and the client takes withBlockHooks hooks on every method.
Without the client
db.drive is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createAttachments } from "better-supabase/blocks/attachments";
import { createDrive, rpcTransport } from "better-supabase/blocks/drive";
const transport = rpcTransport(supabase);
const drive = createDrive({
transport,
storage: supabase.storage,
attachments: createAttachments({ transport, storage: supabase.storage }),
});
const projects = await drive
.createFolder({ organizationId, folder: { name: "Projects" } })
.orThrow();
const upload = await drive
.upload({
organizationId,
file: {
parentId: projects.id,
name: file.name,
mimeType: file.type,
size: file.size,
},
})
.orThrow();
await supabase.storage
.from(upload.attachment.bucket)
.uploadToSignedUrl(upload.attachment.path, upload.token, file);
await drive
.commit({ id: upload.node.id, attachmentId: upload.attachment.id })
.orThrow();
await drive.share({
id: projects.id,
principal: { type: "team", id: designTeam },
role: "editor",
});
await drive.share({
id: projects.id,
principal: { type: "role", id: memberRoleId },
role: "viewer",
});
const { signedUrl } = await drive.download({ id: upload.node.id }).orThrow();Default document types
Files in the drive take the document types of the attachments block. seed_attachments_defaults creates contract, invoice, receipt, identity, report and other for each organization; see default document types.
Last updated on
Documents
Collaborative Yjs documents attached to any subject. The database keeps an update log and a compacted snapshot, a private Realtime topic carries live edits and presence, and better-supabase/yjs connects a Y.Doc to both.
Controlled documents
Put drive files under document control. Each document gets a number, a type, an owner and a review date, moves from draft through review to effective and obsolete, and is released through an approval, so readers only ever get the released version.