Attachments
Files linked to records in a tenant, uploaded through signed URLs to a private bucket and served only after a malware scan.
The attachments block links files to records in a tenant. Each file gets
a row in attachments and an object in a private Storage bucket at
{organization_id}/attachments/{id}. The bucket's policies accept an
upload only when a pending record of the caller expects it, and serve a
file only after your scanner marks it clean.
better-supabase add attachments # adds tenant and access as wellThe block's entity is attachment (the attachments table). It isn't registered as a subject, so files can't be attached to files. Rename it with blocks.attachments.names; the storage paths (.../attachments/...) and the bsb_attachments_* constraint and storage policy names keep the block name, so existing files stay where they are. attachmentInputSchema validates what upload takes.
| Column | Holds |
|---|---|
subject_type, subject_id | The record the file belongs to, or both null |
bucket, object_path | Where the object lives; the path is generated from the id |
name, mime_type, size | The file name, and the type and size Storage stored |
status, scan_detail | pending, clean, infected or failed, and what the scan found |
uploaded_by, uploaded_at | The uploader, and when confirm saw the object |
| Permission | Lets a member | Default roles |
|---|---|---|
attachments.read | list attachments and download clean files | member, admin |
attachments.upload | upload files | member, admin |
attachments.manage | read any file and delete other members' files | admin (attachments.*) |
The uploader can always read and delete their own file.
Options
export default defineConfig({
blocks: {
attachments: {
options: {
bucket: "attachments",
maxSize: 25 * 1024 * 1024,
allowedMimeTypes: ["image/*", "application/pdf"],
requireScan: true,
},
},
},
});The module creates the bucket as private with maxSize (default 50 MiB) as
its file size limit and allowedMimeTypes as its allowed types; an existing
bucket keeps its settings. The table checks the same limits. With
requireScan: false, confirm marks a file clean right away, and files
nobody scanned are served too (an infected one never is). requireScan
defaults to true, or to false with offline. The client reads
requireScan from blocks.generated.ts, which better-supabase gen writes
from this config, so defineBlocks passes it to createAttachments and you
never repeat it (see the generated config).
publicBuckets lists buckets that Storage serves without a signed URL, for
media on a public page such as a product photo or an article image. The
module creates those buckets as public and keeps every other bucket private,
so removing a bucket from the list makes it private again on the next
better-supabase add. A public bucket needs requireScan: false, because
Storage serves its files before any scan could run. attachments.publicUrl(attachment)
and images.publicUrl(attachment, { transform }) return the URL; a file in
a private bucket returns ATTACHMENT_PRIVATE, and an infected one
ATTACHMENT_NOT_SCANNED.
attachments: {
options: { publicBuckets: ["attachments"], requireScan: false },
},When a tenant's file is uploaded, replaced or deleted, a trigger broadcasts
changed to the private topic <topic>:<tenant> with the file's
subjectType and subjectId. topic defaults to
attachments; a policy on realtime.messages lets only the tenant's readers
join it, and files without a tenant broadcast nothing.
attachmentsTopic(organizationId, topic) returns the topic name.
Subjects and buckets
subjects maps each subject type to its table, as in the
subject registry: uploading and reading a file then
also need the subject row to be readable through the subject table's own
policies (and its permission), and an unlisted type is refused. A subject
can keep its files in its own bucket with its own MIME types, so an app with a
bucket per feature keeps them:
options: {
bucket: "attachments",
path: "{organization_id}/{subject_type}/{subject_id}/{id}",
recordTypes: {
chat_message: { table: "chat_messages", bucket: "chat", allowedMimeTypes: ["image/*", "application/pdf"] },
expense: { table: "expenses", bucket: "receipts", allowedMimeTypes: ["image/*"], cascade: true },
},
},The module creates every listed bucket that doesn't exist yet and adds its
storage policies for each, next to any policies the bucket already has. With
subjects, reading an object also needs its subject: the storage read policy
checks that the caller sees the attachment row through its own read policy
(attachment_object_visible), so a member who can't see the subject, or who
isn't in the tenant, can't download its files, uploader and
attachments.manage included.
cascade: true deletes a subject's attachment rows with the subject row;
remove the objects with attachments.remove or a storage cleanup job.
Permissions per subject
permissions gives a subject type its own keys, in place of
attachments.read, attachments.upload and attachments.manage, and
scope names a provider scope whose ids are the subject ids, so a grant on
the record itself counts next to one on the tenant. Both work as they do in
the subject registry, and apply to the table's
policies and to the storage checks in attachment_object_allowed:
recordTypes: {
contract: {
table: "contracts",
permissions: { read: "contracts.read", upload: "contracts.edit", manage: "contracts.manage" },
},
project: { table: "projects", idType: "uuid", scope: "project" },
},From 0.11, a subject the block takes from the registry (config.recordTypes)
also takes its upload and manage keys from
records.<type>.permissions. The registry's read stays the key for
reading the subject itself, so set the files' read key in
blocks.attachments.on.<type>.permissions, which also
overrides the registry's keys one by one.
Without its own keys, a subject's files follow the block-wide keys, so any
member of the tenant with attachments.read reads them, even when the
subject table lets only some members see the row. Doctor reports that case as
BS345 when the table's policies check more than
tenant membership.
upload: "subject" on a subject in blocks.attachments.on makes the subject
row's own policies decide who attaches files: next to attachments.upload,
creating an attachment and deleting your own upload need the caller to be
able to change the subject row. attachment_subject_writable(subject_type, subject_id) checks it as the caller: it needs an update grant on the table
(on any column) and select on its id column, then takes a for key share
lock, which runs the table's update policies without writing the row. A
member who reads an expense but can't change it then can't attach a receipt
to it. A table with row level security off lets in every caller with the
update grant, so the check is only as strict as the table's own policies.
Claiming a pending imported file (claim_attachment_upload), replacing a
file and restoring a version take attachments.manage for such a type,
because those functions run as their owner and can't run the subject
table's policies as the caller. The uploader deletes the stored object only
while they can still change the subject row
(attachment_object_subject_writable); attachments.manage always can. The
default, "permission", checks the keys alone.
blocks: {
attachments: { on: { expense: { table: "expenses", idType: "uuid", upload: "subject" } } },
},A subject without a tenant, such as a user's own notes, takes tenant: false:
its files have no organization_id, their path starts with -, and the
subject table's own policies alone decide who reads and uploads them, without
tenant permissions. Other files still need a tenant. List those types in the
client's tenantless option, so upload, put and list on such a subject
send no tenant and need none:
recordTypes: {
note: { table: "notes", tenant: false },
},Server code calls the attachments instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useAttachments } = defineDataHooks(
"attachments",
(db: AppDb) => db.attachments,
);await db.attachments
.upload(
{ type: "note", id: noteId },
{ name: file.name, mimeType: file.type, size: file.size },
)
.orThrow();"use client";
import { useAttachments } from "@/lib/supabase/hooks";
const rows = useAttachments({ limit: 50 });path sets the object path, from {organization_id} (required first),
{id} (required), {subject_type} and {subject_id} (a file without a
subject gets -), and {ext}, the file name's extension in lowercase
without the dot (empty when the name has none). It defaults to
{organization_id}/attachments/{id}. {organization_id}/attachments/{id}.{ext}
keeps the extension in the object name, for tools that read it.
Changing it later rewrites the column on Postgres 17; on older versions,
recreate the column in a migration. The data file gives a record the new path
only while no object is stored at its old one. A stored object keeps its path,
because Postgres can't move it: to move existing files, copy each object to the
new path with supabase.storage.from(bucket).move(from, to) and update
object_path in the same step.
Paging files
attachmentPage lists files by keyset (ADR 1077) and takes organizationId (a subject type without a tenant needs none). Sorts are createdAt (the default, newest first), name and size. Filters are subjectType, subjectId, status and documentTypeId, each a list of values. q searches the file name. attachmentFacets counts status and subjectType, and attachmentCount returns { value, exact }. Reading with both a subject type and a subject id writes the read-log entry, as list does.
const page = await attachments
.attachmentPage({
organizationId,
filters: { subjectType: ["invoice"], subjectId: [invoiceId] },
q: "scan",
limit: 25,
})
.orThrow();list keeps working and is deprecated. A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
Upload and download
Uploading takes three steps: create the record and a signed upload URL on the server, upload the file from the browser, then confirm.
"use server";
import {
createAttachments,
rpcTransport,
} from "better-supabase/blocks/attachments";
export async function startUpload(projectId: string, file: FileMeta) {
const supabase = await createServerClient();
const attachments = createAttachments({
transport: rpcTransport(supabase),
storage: supabase.storage,
tenant: organizationId,
});
return attachments
.upload(
{ type: "project", id: projectId },
{ name: file.name, mimeType: file.type, size: file.size },
)
.orThrow();
}On a Db with the block installed through .blocks(), db.attachments (or
db.$blocks.attachments) is the same client with the Db's transport,
organization and Storage (db.$storage), so you pass none of them.
The first argument is the record as a RecordRef ({ type, id }), or
null for a file without one. The tenant comes from the block's tenant
option, an organization id or a function that returns the current one;
createBlocks and createBlockClient pass the request's tenant (see
createBlocks). A call
that needs a tenant and has none fails with invalid_request and the hint
TENANT_REQUIRED. Each attachment carries subject (a RecordRef, or
undefined without one) and organizationId.
The browser uploads with the token,
supabase.storage.from(bucket).uploadToSignedUrl(path, token, file), or a
PUT to signedUrl. Then attachments.confirm(id) checks that the object
exists, takes its size and type from Storage and writes
attachment.uploaded to the outbox. confirm returns
not_found with the hint ATTACHMENT_NOT_UPLOADED until the object exists.
upload takes metadata, a JSON object kept with the record in the
metadata column (a caption, where the file came from), and every
attachment returns it as metadata ({} without any). It also takes
width and height in pixels for an image and pages for a document, so a
list can lay out previews and show a page count before any file loads.
download(id) returns a signed URL (300 seconds by default, downloadTtl
changes it; { as: "plan.pdf" } sets the download name). Until the scan
passes it returns invalid_request with the hint ATTACHMENT_NOT_SCANNED.
list({ type, id }) lists a record's files oldest first (list() lists
every file of the tenant), and remove(id) deletes the object and then the
row (with offline, the row first).
With the profiles module installed, each file that
list returns carries author (type Author): the uploader's id, name
and avatarUrl. list_attachments reads them through
attachment_authors(uuid[]), a security definer function that returns only
the uploaders of files the caller may read. author is undefined without
the profiles module and once the account is deleted, and the other methods
leave it out; uploadedBy is always there.
Files the server makes or fetches (an export, a generated PDF, an import
from a URL) go through put(subject, attachment, file), which creates the record,
uploads the bytes with the storage client and confirms it in one call,
without a signed upload URL. Both work in a writable
support session:
there confirm first claims the browser's upload for the user the admin
acts as and records the session on the object. A refused claim returns
forbidden with the hint ATTACHMENT_FORBIDDEN, or not_found with
ATTACHMENT_NOT_UPLOADED, and the record stays pending. When Storage
refuses the signed upload URL or the upload (a bucket policy or a read-only
support session), upload and put delete the record again and return the
refusal, so no pending record is left behind. read(id) returns the bytes as a Blob for server-side processing, behind
the same scan gate as download (ATTACHMENT_NOT_SCANNED until the scan
passes):
const report = await attachments
.put(
{ type: "project", id: projectId },
{ name: "report.pdf", mimeType: "application/pdf", size: pdf.byteLength },
pdf,
)
.orThrow();
const { file } = await attachments.read(attachmentId).orThrow();
const text = await extractText(await file.arrayBuffer());Pass the caller's Supabase client so the table and bucket policies apply;
createAttachments never needs the service role. A service-role client works
too, for jobs that act for no user.
Upload from the browser
useAttachmentUpload runs the three steps for each file, side by side, and
reports progress. It watches each file until the scan answers, so an upload
ends as done or blocked. The hook is a registry item: install it with
npx shadcn add @better-supabase/use-attachments, which writes
hooks/use-attachments.ts into the app. createAttachmentUploadController
is the framework-free controller under it, and Vue, Svelte and Solid run it
with useBlockController from better-supabase/vue, /svelte and /solid
(see Block controllers).
"use client";
import { useAttachmentUpload } from "@/hooks/use-attachments";
export function ProjectFiles({ projectId }: { projectId: string }) {
const { uploads, add, retry, dismiss } = useAttachmentUpload({
subject: { type: "project", id: projectId },
});
return (
<input
type="file"
multiple
onChange={(event) =>
add(
[...(event.target.files ?? [])].map((file) => ({
file,
name: file.name,
})),
)
}
/>
);
}Each upload has a status (uploading, confirming, scanning, done,
blocked for an infected file, or error), a progress from 0 to 1, the
attachment id once created and the error. retry(key) starts a failed
upload again, dismiss(key) stops one and drops it, clear() drops the
uploads that ended, and busy says whether any is still running. Pass
start and confirm server actions to create the record on the server,
onUploaded to refresh the list, and send to replace the default
XMLHttpRequest upload (in React Native, for example).
In Vue, Svelte and Solid, useBlockController passes the controller's
options as they are, so pass start and confirm yourself, and refresh to wait for
the scan. Vue returns state as a shallow ref with the actions on
actions:
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createAttachments,
createAttachmentUploadController,
rpcTransport,
} from "better-supabase/blocks/attachments";
const { projectId } = defineProps<{ projectId: string }>();
const supabase = useSupabase();
const attachments = createAttachments({
transport: rpcTransport(supabase),
storage: supabase.storage,
});
const status = (id: string) =>
attachments.get(id).map((file) => ({ status: file.status }));
const { state, actions } = useBlockController(
createAttachmentUploadController,
{
start: (file) =>
attachments
.upload({ type: "project", id: projectId }, file)
.map((upload) => ({
id: upload.attachment.id,
signedUrl: upload.signedUrl,
})),
confirm: (id) =>
attachments.confirm(id).map((file) => ({ status: file.status })),
refresh: status,
},
false,
);
</script>Svelte runs the same controller with useBlockController from
better-supabase/svelte, which returns a readable store ($uploads.uploads,
with the actions on .actions), and Solid runs it with useBlockController
from better-supabase/solid and reads the snapshot with state():
import { createAttachmentUploadController } from "better-supabase/blocks/attachments";
import { useBlockController } from "better-supabase/svelte";
import { useBlockController as useSolidController } from "better-supabase/solid";
const uploads = useBlockController(
createAttachmentUploadController,
options,
false,
);
const { state, actions } = useSolidController(
createAttachmentUploadController,
options,
false,
);List a record's files
createAttachmentListController lists one record's files with
attachments.list(subject) and lists them again when the record's files
change in another tab or for another member. It joins the tenant's topic
through ports.topic; pass topic: null to load without listening.
import { createAttachmentListController } from "better-supabase/blocks/attachments";
import { blockConfig } from "@/lib/supabase/blocks.config";
const files = createAttachmentListController({
client: attachments,
auth,
ports,
tenant: organizationId,
subject: { type: "task", id: taskId },
topic: blockConfig.attachments.options.topic,
});The snapshot has attachments (undefined until the first load), the topic's
status and the last error; refresh loads again. Vue, Svelte and Solid
run it with useBlockController, which reads auth and ports from the
provider.
Upload a file in one call
uploadFile({ subject, file, attachment?, onProgress? }) creates the record, sends file to its signed upload URL and confirms it. The bucket you pass to createAttachments needs uploadToSignedUrl, which supabase-js storage clients have. When Storage refuses the file, the record is deleted again. supabase-js reports no byte progress, so onProgress is called twice: with loaded: 0 before the bytes go out and with loaded: total once Storage has them.
const attachment = await attachments
.uploadFile({
subject,
file,
onProgress: ({ loaded, total }) => setBar(loaded / total),
})
.orThrow();Files in Vercel Blob
The bytes of a file can live outside Supabase Storage. files takes a
FileStore, and vercelBlobStore(blob) keeps the bytes in
Vercel Blob. The records, who may upload,
the scan gate and the events stay in Postgres; only the bytes move. Without
files, the block uses supabaseFileStore(storage), which is the behaviour
described above.
Install the SDK, an optional peer (@vercel/blob >=2.9.0 <3), and set
BLOB_READ_WRITE_TOKEN on the server (or use Vercel OIDC with
BLOB_STORE_ID):
pnpm add @vercel/blobimport * as blob from "@vercel/blob";
import {
createAttachments,
rpcTransport,
vercelBlobStore,
} from "better-supabase/blocks/attachments";
export const attachmentsFor = (
supabase: SupabaseClient,
admin: SupabaseClient,
organizationId: string,
) =>
createAttachments({
transport: rpcTransport(supabase),
service: rpcTransport(admin),
files: vercelBlobStore(blob),
tenant: organizationId,
});Blobs are private by default (access: "private"), so a file is read only
through the signed URL that download returns after the scan passes.
vercelBlobStore(blob, { prefix: "files/", token, access }) puts a prefix
before every pathname, passes a token instead of the environment one, or
makes the blobs public. A pathname is <prefix><bucket>/<object_path>, the
same path the file would have in Storage.
upload and replace still create the record first, so the table policies
decide who may upload. The signed upload URL they return is a presigned Blob
PUT that only accepts that pathname, the declared MIME type and at most
the declared size, and never overwrites a blob. Send the file with the
method and headers the result carries: useAttachmentUpload and
xhrSend do this when start passes them on, and uploadFile sends the file
with fetch.
const upload = await startUpload(projectId, {
name: file.name,
mimeType: file.type,
size: file.size,
});
await fetch(upload.signedUrl, {
method: upload.method ?? "PUT",
headers: upload.headers,
body: file,
});
await confirmUpload(upload.attachment.id);Postgres can't see a blob, so confirm takes two steps. It first calls
confirm_attachment(id) as the caller, which keeps the rule that only the
uploader confirms; it fails with ATTACHMENT_NOT_UPLOADED because Storage has
no object. Then it reads the blob's size and type with head and passes them
to confirm_attachment(id, object) through service, the only caller whose
object the function accepts. The browser never says what it uploaded. The
function checks the size and type against the bucket's file_size_limit and
allowed_mime_types, and refuses others with ATTACHMENT_OBJECT_REFUSED.
Without service, confirm uses transport, which works when that is a
service-role transport and otherwise fails with ATTACHMENT_SERVICE_REQUIRED.
put, download, read and remove go through the store as well, and
createAttachmentScanner, createObjectScanner and createAttachmentSweeper
take the same files.
A few features need Supabase Storage and stay there. Image transforms
(images().signedUrl with a variant) and publicUrl return
invalid_request with the hint ATTACHMENT_STORE_UNSUPPORTED; an image
without a variant still gets a signed URL. The upload claim of a
support session is a
Storage feature, so it doesn't run. Storage policies on storage.objects don't
apply to blobs, and a download name (as) only asks the browser to save
the file, under its pathname.
Your own file store
FileStore is a versioned interface (apiVersion: 1): put, get,
delete and signedUrl, plus head to confirm uploads and
signedUploadUrl for browser uploads. Every method returns an AsyncResult
and never throws. Check one with testFileStore from
better-supabase/testing against a test bucket:
import { testFileStore } from "better-supabase/testing";
it("conforms", async () => {
await testFileStore(myStore, { bucket: "conformance", fetch });
});It puts a file and reads it back, refuses a second put without upsert,
overwrites with upsert, signs a download URL (and fetches it with fetch),
checks head and signedUploadUrl when the store has them, and deletes the
files it wrote.
Versions
replace(id, file) starts a new version of a file and returns a signed
upload URL, like upload: the current file becomes an earlier version, and
the new one goes through the upload, confirm and the scan before it can be
downloaded. Only the uploader (with attachments.upload) or someone with
attachments.manage can replace a file. versions(id) lists the earlier
versions newest first, download(id, { version }) signs one of them, and
restore(id, version) makes one current again, keeping the current file as
an earlier version. remove(id) deletes every version's file.
const next = await attachments
.replace(attachmentId, {
name: "plan-v2.pdf",
mimeType: "application/pdf",
size: file.size,
})
.orThrow();
// Upload to next.signedUrl, then confirm(attachmentId).
const [previous] = await attachments.versions(attachmentId).orThrow();
await attachments.restore(attachmentId, previous.version).orThrow();Offline
offline: true lets a client that writes to a local database (PowerSync)
create, upload and delete files while it has no network, and replay the
changes later:
attachments: {
options: { offline: true },
},| Change | What it does |
|---|---|
| Client ids | authenticated may insert id, so a record created offline keeps the id the client chose. The insert policy still sets uploaded_by to the caller. |
| Upload trigger | An object written to a pending record's path marks the record uploaded and copies its size and type, as confirm does. confirm stays and returns the record afterwards. |
| No scan by default | requireScan defaults to false, because a file uploaded offline has no scan to wait for. Set requireScan: true to keep the gate. |
| Row-first delete | Deleting a record queues its objects (every version) in attachment_cleanup. Storage lets the caller delete a queued object only once no record uses its path. |
remove(id) deletes the record first and then the files. A file delete
that fails (the client went offline in between) leaves the file queued, and
createAttachmentSweeper deletes it later with the service role.
sweepQueued({ limit }) takes the oldest queued objects (100 by default, at
most 1000), deletes them per bucket and drops them from the queue; a bucket
that refuses keeps its objects queued for the next run. Run it from a cron:
import {
createAttachmentSweeper,
sqlTransport,
} from "better-supabase/blocks/attachments";
const sweeper = createAttachmentSweeper({
transport: sqlTransport(postgres.admin),
storage: supabaseAdmin.storage,
});
export async function GET(): Promise<Response> {
const { removed, failed } = await sweeper
.sweepQueued({ limit: 500 })
.orThrow();
return Response.json({ removed, failed });
}{
"schedules": {
"attachment-cleanup": {
"schedule": "0 * * * *",
"path": "/api/cron/attachment-cleanup",
"requestMethod": "GET"
}
}
}With PowerSync, replay the attachments table through
attachmentQueueRoute, which
creates records under the client's id and deletes them row first.
Image previews
attachments.images(variants) signs resized URLs of image files, in the shape
useImage from better-supabase/react takes. Name the sizes once, and pass
an attachment or its id. The URLs stay behind the scan gate
(ATTACHMENT_NOT_SCANNED), and a file that isn't image/* returns
ATTACHMENT_NOT_IMAGE.
const images = attachments.images({
thumb: { width: 160, height: 160, resize: "cover" },
});
const { src, srcSet, width, height } = useImage(images, attachment, "thumb");The variants use Supabase image transformations, so the project needs them turned on (see image transformations).
Scanning
createAttachmentScanner runs your scanner (ClamAV, a scanning API) on each
uploaded file with a service-role client, and records the verdict with
set_attachment_status, which only the service role can call.
import {
createAttachmentScanner,
sqlTransport,
} from "better-supabase/blocks/attachments";
const scanner = createAttachmentScanner({
transport: sqlTransport(postgres.admin),
storage: supabaseAdmin.storage,
scan: async (file) => {
const result = await clamav.scan(await file.arrayBuffer());
return result.infected
? { status: "infected", detail: result.signature }
: { status: "clean" };
},
});
await outbox.relay("attachment-scans", scanner.sink());scanner.sink() scans the file of each attachment.uploaded event, and
scanner.job is a jobs handler for an
{ attachmentId } payload when you prefer a queue. A file that is already
clean or infected is not scanned again, so replays are safe. When scan
throws, the file is marked failed with the error as scan_detail, the
result is an error with the hint ATTACHMENT_SCAN_FAILED, and the next
attempt scans it again. An event or job for an attachment that was deleted
before its scan is done: the sink skips it and the job completes, so one
deleted file never blocks the events behind it in the relay. Other errors,
such as a failed download or a throwing scan, still throw so the relay or
the queue retries.
Any bucket
The scan gate also works without the attachments table, for a file drive,
avatars or generated exports. scanned_objects holds one row per object,
object_clean(bucket, path) answers in any storage policy, and
createObjectScanner records verdicts with set_object_scan (service role):
create policy "drive files are clean" on storage.objects for select to authenticated
using (bucket_id = 'files' and better_supabase.object_clean(bucket_id, name) and ...);const objects = createObjectScanner({
transport: sqlTransport(postgres.admin),
storage: supabaseAdmin.storage,
scan: (file, { bucket, path }) => scanWithClamav(file),
});
await outbox.relay("object-scans", objects.sink());With scanBuckets: ["files"], a trigger on storage.objects gives each new
or replaced object in those buckets a pending row and writes an
object.uploaded event ({ bucket, path }), which objects.sink() scans;
objects.job takes the same payload from a queue. An object deleted from
storage before its scan (NoSuchKey) is skipped the same way; a missing
bucket or any other error still throws. Scanning an attachment also records
its object in scanned_objects, so both gates agree.
Events
With the outbox installed, the module writes these events with the tenant as
the partition key and attachments/<id> as the subject:
| Event | When | Data |
|---|---|---|
attachment.uploaded | confirm saw the object | attachmentId, subjectType, subjectId, uploadedBy, mimeType, size |
attachment.scanned | a scan result was recorded | attachmentId, status, uploadedBy |
attachment.replaced | replace started a new version | attachmentId, subjectType, subjectId, uploadedBy, version |
attachment.restored | restore made an earlier version current | attachmentId, subjectType, subjectId, version |
object.uploaded | an object landed in a scanBuckets bucket (no tenant) | bucket, path |
Document types and imported files
An organization declares the kinds of document it files, with typed metadata
per kind. documentTypes.define creates or changes a type, and the module
validates every attachment's metadata against it on write:
await attachments.documentTypes
.define({
key: "supplier_invoice",
name: "Supplier invoice",
fields: {
total: { type: "amount", required: true },
issued_on: { type: "date", required: true },
number: { type: "number" },
valid_until: { type: "expiry" },
status: { type: "select", options: ["open", "paid"] },
},
})
.orThrow();
await attachments
.create({
subjectType: "supplier",
subjectId,
name: "invoice-1042.pdf",
mimeType: "application/pdf",
size: 0,
documentType: "supplier_invoice",
source: "legacy_erp",
externalId: "DOC-1042",
metadata: { total: 1250, issued_on: "2026-03-01" },
})
.orThrow();The field types are text, number, amount, date, expiry, boolean
and select. A bad value fails with ATTACHMENT_FIELD_INVALID, an unknown
type with ATTACHMENT_DOCUMENT_TYPE_UNKNOWN, an invalid schema with
ATTACHMENT_DOCUMENT_SCHEMA_INVALID, and documentTypes.remove fails with
ATTACHMENT_DOCUMENT_TYPE_IN_USE while a file uses the type. Any member can
read the types; defining and removing them needs attachments.manage.
source names where the record came from. It must be a value of
options.sources or the source of an import run, otherwise the write fails
with ATTACHMENT_SOURCE_UNKNOWN. (organization, source, externalId) is
unique, so the pair is an organization-wide index of the outside system's
ids (ATTACHMENT_EXTERNAL_ID_TAKEN). subjectType must be a registered
subject type (ATTACHMENT_SUBJECT_UNKNOWN), so a file can belong to any
record type an installed block or config.recordTypes registers.
storageStatus is stored, pending_upload or missing. An import can
register the metadata first (the attachment target of the imports block,
with sourcePath naming where the file lives) and leave the file for later:
claim(id) marks the upload as arrived, and markMissing(id) records that
the file will never come. Both fail with ATTACHMENT_NOT_CLAIMABLE once the
file is stored. A metadata-first record has size 0 and the type
application/octet-stream until the real file replaces them.
A table you adopted for tables.attachments maps the new columns
(documentType, source, externalId, storage, sourcePath) or sets
them to null; the document guard renders only when all five are mapped.
Default document types
seed_attachments_defaults gives each new organization six document types: contract, invoice, receipt, identity, report and other. The first four carry fields, for example counterparty (required), signed_on and expires_on on a contract. A type whose key already exists is kept, so edits to a type survive running the defaults again. The drive uses the same types for its files. Custom mode keeps no types table, so it seeds none.
Your own fields
Columns you add to attachments with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createAttachments a Standard Schema
for them as fields: upload, put take them next to the block's own keys and
validate them (a bad value is a validation error), and every attachment read return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createAttachments({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.attachments is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const attachments = createAttachments({
transport: rpcTransport(supabase),
storage: supabase.storage,
tenantless: ["note"],
});
await attachments
.upload(
{ type: "note", id: noteId },
{ name: file.name, mimeType: file.type, size: file.size },
)
.orThrow();File hashes
The scanner hashes each file it downloads with WebCrypto and records the SHA-256 through set_attachment_status, so sha256 and hashVerifiedAt on an attachment come from the bytes that were scanned. Only the service role can set them, and replace_attachment clears them for the new file. The history table keeps the hash of every version.
Last updated on