Share links
Hashed share links, view counts and per-user state. The token is returned once.
share-links creates a link, returns the token once and stores only its SHA-256. resolve_share_link is granted to anon and hashes the token it is given, so a row that still holds a plaintext token keeps working after you store sha256 of it. Revoking, listing, recording a view and setting starred or last-opened state are the other calls.
better-supabase add share-linksimport { createShareLinks } from "better-supabase/blocks/share-links";create(subject, { role, versionId, expiresAt, maxUses, password, downloadAllowed }) takes the subject as a RecordRef ({ type, id }) and acts in the block's tenant. It takes the role (view by default), an optional Temporal.Instant after which the link stops resolving and, with the versions module installed, a version of the subject to pin the link to. An expiresAt that is not in the future fails with SHARE_EXPIRY_INVALID. resolve(token, { password }) returns the link's id, organizationId, subject (a RecordRef), role, versionId, expiresAt, downloadAllowed and passwordRequired, or null when the token is unknown, revoked or expired.
const link = await shareLinks
.create(
{ type: "calendar", id: calendarId },
{ expiresAt: Temporal.Now.instant().add({ hours: 24 * 30 }) },
)
.orThrow();The other calls on a subject take it the same way: list(subject) returns its
links, recordView(subject, viewerKind, viewer?) counts a view in the
block's tenant, and setState(subject, starred) stars or unstars it for the
caller. A call that needs a tenant and has none fails with invalid_request
and the hint TENANT_REQUIRED.
Passwords
Pass password to create to make a link that opens only with it. It needs at least 8 characters (SHARE_LINK_PASSWORD_INVALID otherwise), and the table keeps only its bcrypt hash (extensions.crypt with gen_salt('bf')) in password_hash, which data exports leave out.
const link = await shareLinks
.create({ type: "doc", id: docId }, { password: "correct horse battery" })
.orThrow();
const opened = await shareLinks.resolve(token, { password: input });Until the call passes the right password, resolve fails with unauthorized, the hint SHARE_LINK_PASSWORD_REQUIRED, the code 28P01 and the details {"required":true}, so a guest page can ask for it. Underneath, resolve_share_link(token, password) returns { "passwordRequired": true } instead of raising, which keeps the attempt it counted, and a locked resolve counts no use of the link.
With the rate-limit module installed, each wrong password counts against the link under the scope share_link_password: 10 per 15 minutes, unless set_rate_limit('share_link_password', ...) sets another rule. Once a link is over the limit, every resolve with a password fails with rate_limited and the hint SHARE_LINK_RATE_LIMITED until the window ends, the right password included. Without rate-limit, wrong passwords are not counted.
The functions other modules serve a link through (calendar feeds, booking pages, public forms, drive links, shared AI chats and leave feeds) take no password, so they don't open a link that has one.
Paging
share-links does not take the block list contract. list reads the links to one subject, which is a short list the caller manages, so it takes the subject, includeRevoked and a limit, and does not offer q, sorts, facets or a cursor (ADR 1077).
Download and upload links
downloadAllowed: false makes a view-only link: resolve and list return downloadAllowed: false. The block serves no files itself, so the page or block that serves the subject's files checks the flag before it offers a download; the drive does this in drive_link. It defaults to true.
The roles a link may carry depend on its subject type. A type that another block shares lists them in its contribution (roles, ["view"] unless set), and create refuses any other role with SHARE_LINK_ROLE_INVALID. Public forms take respond. Drive nodes take view, download and upload: creating one needs the drive's share role on the node, an upload link must name a folder (a file request), and the drive leaves the original out when downloadAllowed is false or a download block covers the node. Types from config.recordTypes and blocks["share-links"].on take any role.
Errors
| Hint | When |
|---|---|
SHARE_EXPIRY_INVALID | expiresAt is not in the future |
SHARE_MAX_USES_INVALID | maxUses is below 1 |
SHARE_LINK_PASSWORD_INVALID | the password is shorter than 8 characters, or the links table has no password column |
SHARE_LINK_DOWNLOAD_INVALID | downloadAllowed: false on a links table without a download_allowed column |
SHARE_LINK_ROLE_INVALID | the subject type's links can't carry the role |
SHARE_LINK_PASSWORD_REQUIRED | resolve got no password or a wrong one |
SHARE_LINK_RATE_LIMITED | too many wrong passwords for the link |
Permissions
| Call | Who may call it |
|---|---|
create | a member with share_links.create in the organization |
revoke | the link's creator, or a member with share_links.create; anyone else gets SHARE_NOT_FOUND |
list | the links the caller created, plus every link in organizations where the caller holds share_links.read |
recordView | a member of the organization (SHARE_FORBIDDEN otherwise) |
resolve | anyone, including anon |
The service role may make every call.
blocks["share-links"].on lists the subject types that may be shared, both
config.recordTypes types and the types other blocks share, such as calendar,
calendar_user or leave_feed. Any other type gets SHARE_SUBJECT_UNKNOWN, also for the
service role. Unset, every type can be shared.
Sharing one record
A record type that declares a share action in
config.recordTypes is checked per
record as well: create needs that action on the record, and revoke and
list need it on top of the organization key, so only the creator or someone
who may share the record sees and revokes its links. The action can be a key,
a per-row grant from the authorization provider or an owner column:
export default defineConfig({
records: {
file: {
table: "public.files",
idType: "uuid",
permissions: { share: { key: "file.update", rows: "file" } },
},
thread: {
table: "public.threads",
idType: "uuid",
permissions: { share: { owner: "owner_id" } },
},
},
});Without a share action, the record only has to exist in the link's
organization, as before.
Tokens you make and full rows
Two options fit an app that already has links:
| Option | What it adds |
|---|---|
tokenHash: true | create_share_link(..., token_hash) stores the SHA-256 hex of a token the app made (64 lowercase hex characters, SHARE_TOKEN_HASH_INVALID otherwise) and returns no token; find_share_link(token_hash) returns the live link a hash names without counting a use, for the service role. The client calls them as createHashed(subject, tokenHash, options) and find(tokenHash) |
fullRows: true | list_share_links returns each link's organizationId, subjectType, subjectId, createdBy and createdAt (a createdAt column the block adds to its own table), newest first, and takes include_revoked (the client's list(subject, { includeRevoked: false })) |
Without them the functions keep the signatures of earlier releases.
Events
| Event | When |
|---|---|
share_link.created | create stored a link |
share_link.revoked | revoke revoked one |
subject.viewed | recordView counted a view |
Guest pages
Every module that reads a subject through a link (calendar feeds, booking pages, public forms, drive links, shared AI chats, shared versions) checks the same four things: the token's hash, the subject type, that the link is not revoked and that it has not expired. A guest page has two ways to read the subject:
- Call the module's own function (
calendar_feed(token),get_public_form(token),get_shared_version(token)). It issecurity definer, returns only what the link grants and needs no session. - Exchange the token for a short-lived anonymous session whose claims name the link, then query under row-level security. An authorization provider can do this from the row
resolvereturns; see Authorization providers. Keep the token's lifetime capped by the row'sexpiresAt, and revoke the row to end every session minted from it.
AI chat
AI chat sharing uses this block. share_ai_chat, revoke_ai_chat_share, list_ai_chat_shares and get_shared_ai_chat stay callable and read or write share_links. Existing ai_chat_shares rows are copied, including leaf_id.
Over your own tables
To run over tables you already have, map tables.links, tables.views and tables.state. The block stores a SHA-256 hash of each token, so a table that keeps plaintext tokens needs update ... set token = encode(sha256(convert_to(token, 'utf8')), 'hex') once. Your own view and per-user state tables map onto views and state when their columns fit. views and state are optional: map either to null, over your tables or the block's own, and the block creates no such table, record_view counts no views and set_user_state keeps no state.
Your own columns
Add columns to the share link table with alter table ... add column in your own schema files
(column name to SQL type), then pass a Standard Schema for them as fields.
create (in its options) validates and writes them, and create and list return them parsed under
fields. The block also takes hooks around its methods; see
extending blocks.
Server code calls the share-links instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useShareLinks } = defineDataHooks(
"shareLinks",
(db: AppDb) => db.shareLinks,
);const rows = await db.shareLinks.list({ limit: 50 }).orThrow();"use client";
import { useShareLinks } from "@/lib/supabase/hooks";
const rows = useShareLinks({ limit: 50 });Without the client
db.shareLinks is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createShareLinks } from "better-supabase/blocks/share-links";
import { z } from "zod";
const client = createShareLinks({
transport,
fields: z.object({ priority: z.enum(["low", "high"]) }),
});Rotate a link
rotate({ subject, linkId, options }) creates a replacement link, then revokes the old one. The old link stays valid when the new one fails.
Last updated on
Attachments
Files linked to records in a tenant, uploaded through signed URLs to a private bucket and served only after a malware scan.
Reactions
Emoji reactions and up or down votes on any subject, messages (comments included) and inbox messages, with custom emoji per organization, counts under each subject's read rules and a realtime topic per organization.