Skip to Content
dimah-s3v2.8.1
Share Links

Share API

share() options, the owner and visitor actions, s3.share on the server, hooks, authorize, authorizeVisit, and the SHARE_* error codes.

The reference for @dimah-s3/share. The plugin needs db() in the same plugins list.

Policy

Set the rules once in share(). A request that breaks one fails with VALIDATION_ERROR. Its params.rule names the rule (passwordRequired, passwordTooShort, expiryRequired, expiryInPast, or expiryTooLong), with minLength or maxExpiresIn, and useFormatError words it.

lib/s3.ts
share({
  client: dimahS3Share,
  url: (token) => `${process.env.APP_URL}/s/${token}`,
  // Every link expires within 30 days; one without expiresAt gets 7.
  expiration: { default: 7 * 86_400, max: 30 * 86_400 },
  password: { required: false, minLength: 8 },
  folders: true,
  authorize: ({ action, settings }) =>
    action !== "createLink" || settings?.maxDownloads !== null,
  onDownloaded: ({ link, object }) =>
    audit.log("share.download", link.id, object.key),
});

Authorize and hooks

authorize runs for every owner action after the caller's scope is resolved and the link or its target is known to be theirs, so it can only narrow access. db's own authorize runs before it, with operation: "plugin" and plugin: { id: "share", action }. On listLinks, target is the object or folder the list is filtered by; without target, the call lists every link of the scope, tokens included.

authorizeVisit is the visitor side. It runs on openLink once the link is unlocked, and on listShared, downloadShared, and sharedFile, after the link is known to open and before anything is counted, listed, or sent. It sees the link, its target, and the folder or file the call reaches. false answers SHARE_TARGET_UNAVAILABLE, the same as a deleted target, so an item your app hides without deleting it, such as one in its trash, stops opening, and opens again once it is back:

lib/s3.ts
share({
  client: dimahS3Share,
  authorizeVisit: ({ folder }) => !folder?.path.split("/").includes("Trash"),
});

It checks the call, not each row: a folder listing or search still shows a hidden file or subfolder by name, and opening or downloading that one is refused. A presigned download URL handed out before it turned false works until it expires; a proxy URL stops at once.

The hooks run after the action. A throw fails the call, so catch errors in an analytics hook. Their contexts never carry the password hash.

Security

  • The token has 192 random bits and is stored as is, so the owner can copy a link again. Treat the share_link table like your session table.
  • Passwords are hashed with PBKDF2-SHA256 (600,000 iterations) through Web Crypto, so the plugin runs on Node.js and edge runtimes.
  • A revoked link stops handing out download URLs at once. A presigned URL already handed out works until downloadExpiresIn passes.
  • A download counts when its URL is handed out, not when the bytes arrive. The count and the limit check are one statement, so concurrent downloads each count and never pass the limit.
  • access proofs and /share/file URLs are signed with the instance secret (DIMAH_S3_SECRET). Rotating it keeps them valid while the old secret is still in the list.

API Reference

share()

share(options) returns the plugin. It throws at dimahS3() without db(), and when a lifetime or a length is not a positive integer.

PropTypeDefaultDescription
clientDimahS3ShareClientrequiredDimahS3Share.client(adapter), with the adapter you give db()
url(token) => string—The page a visitor opens. Owner responses carry it as link.url; without it, url is null
expiration{ default?: number | null; max?: number }{ default: 604800 }Lifetimes in seconds. max makes every link expire and caps default
password{ required?: boolean; minLength?: number }{ minLength: 8 }Password rules for new and updated links
foldersbooleantrueAllow links to folders
downloadExpiresInnumber300Lifetime of a visitor's download URL in seconds, capped by the route's maxExpiresIn
unlockExpiresInnumber3600Lifetime of an access proof in seconds
authorize(context: ShareAuthorizeContext) => boolean | Promise<boolean>—false rejects an owner action with FORBIDDEN
authorizeVisit(context: ShareVisitContext) => boolean | Promise<boolean>—false fails a visitor call with SHARE_TARGET_UNAVAILABLE
onCreated(context) => void | Promise<void>—After a link is created. Context: request, locals, scope, link, target
onUpdated(context) => void | Promise<void>—After a link's settings change. Also previous
onRevoked(context) => void | Promise<void>—After a link is revoked. target is absent once the file or folder is gone
onOpened(context) => void | Promise<void>—After a visitor opens an unlocked link. Context: request, locals, link, target
onDownloaded(context) => void | Promise<void>—After a visitor gets a download URL. Context: request, locals, link, object

ShareAuthorizeContext

Fields marked ? are optional.

PropertyTypeDescription
action"createLink" | "listLinks" | "getLink" | "updateLink" | "revokeLink"The owner action
scopestringThe caller's db scope
requestRequestThe request
localsDimahS3LocalsWhat the guards returned
target?{ type: "object"; object } | { type: "folder"; folder }The db row the link points at, while it exists. On listLinks, the row the list is filtered by
link?ShareLinkThe link as it is, on getLink, updateLink, and revokeLink
settings?{ expiresAt; passwordProtected; maxDownloads; label }The settings it will have, on createLink and updateLink

ShareVisitContext

PropertyTypeDescription
action"openLink" | "listShared" | "downloadShared" | "sharedFile"The visitor action
linkShareLinkThe link, with its scope
target{ type: "object"; object } | { type: "folder"; folder }The db row the link points at
folder?StorageFolderThe folder listShared lists or searches, or the one that holds object. Absent at the root
object?StorageObjectThe file downloadShared and sharedFile send, or an object link's file
requestRequestThe request
localsDimahS3LocalsWhat the guards returned

Client actions

shareClient() from @dimah-s3/share/client puts these on api.share. Each takes (input, options?), with options { signal, headers }.

ActionEndpointWhoReturns
createLinkPOST /share/linkOwner{ link: ShareClientLink }
listLinksGET /share/linksOwner{ links, nextCursor }
getLinkGET /share/linkOwner{ link }
updateLinkPATCH /share/linkOwner{ link }
revokeLinkDELETE /share/linkOwner{ link }
openLinkGET /share/openVisitor{ link: ShareVisitorLink }
unlockLinkPOST /share/unlockVisitor{ access, expiresAt }
listSharedGET /share/itemsVisitorShareListSharedResponse
downloadSharedPOST /share/downloadVisitorShareDownloadResponse

GET /share/file (sharedFile) streams a file from a signed URL that downloadShared returns on a proxy route. Guards see every one as operation: "plugin" with plugin: { id: "share", action }. isSharePublicAction(context) is true for the visitor actions and sharedFile.

PropTypeDefaultDescription
target{ type: "object"; key; bucket? } | { type: "folder"; folderId }requiredWhat to share. bucket only when the routes use several
expiresAtDate | string | nullexpiration.defaultWhen the link stops opening. null never expires, unless expiration.max is set
expiresInnumber—Lifetime in whole seconds, from the server's clock. Instead of expiresAt
passwordstring | null—Visitors enter it first
maxDownloadsnumber | null—Downloads the link hands out, 1 to 1,000,000
labelstring | null—Your note. Visitors never see it

updateLink takes id and the same settings. An omitted field stays; null clears a password, an expiry, or a limit. Send expiresIn from a browser: its clock can run ahead of the server's, and an expiresAt at the longest lifetime then fails expiration.max. Sending both fails with VALIDATION_ERROR.

listLinks takes target, includeRevoked, status, limit (1 to 100), and cursor. status is one of active, expired, exhausted, and revoked, or an array of them, judged by the server's clock the way shareLinkStatus tells them apart. It takes precedence over includeRevoked:

// The links of a file that still open.
const { links } = await s3Client.share.listLinks({
  target: { type: "object", key },
  status: "active",
});
PropertyTypeDescription
idstringThe link id
tokenstringThe secret of the link
urlstring | nullFrom the url option
status"active" | "expired" | "revoked" | "exhausted"Whether it opens
target{ type; id; name; available; key | path }The object (key) or folder (path). available: false once deleted
labelstring | nullYour note
passwordProtectedbooleanVisitors enter a password first
expiresAtstring | nullISO date
maxDownloadsnumber | nullThe download limit
downloadCountnumberDownload URLs handed out
viewCountnumberUnlocked opens, each one counted
lastAccessedAtstring | nullLast open or download
revokedAtstring | nullWhen it was turned off
createdAtstringISO date
updatedAtstringISO date

Visitor inputs and responses

Every visitor input takes token, and access for an unlocked password-protected link.

ActionAlso takesResponse
openLink—link: type, locked, passwordProtected, expiresAt, downloadsLeft, and object or folder once unlocked
unlockLinkpasswordaccess, expiresAt
listSharedfolderId, search, sort, limit, cursorobjects, nextCursor; the first page adds folders and trail, a search locations and total
downloadSharedid (required on a folder link), dispositionurl, mode, expiresIn, disposition, downloadsLeft

A visitor sees a file as id, name, size, contentType, updatedAt, and folderId; never its key, route, or scope. folderId: null is the top of the shared folder.

s3.share

The plugin's context on the server (SharePluginContext).

PropertyTypeDescription
apiShareServerApiEvery client action as (input, options?), behind the instance guard. options is S3ServerCallOptions
linksShareLinksfind, findByToken, list(scope, filter?), count(scope, filter?), revoke(id), and revokeTarget(target), with no guard. A filter takes objectId or folderId, includeRevoked, and status
pruneLinks(options: { olderThan: Date | number }) => Promise<{ pruned; orphaned }>Removes links revoked or expired before olderThan, and links created before it whose target was deleted (orphaned). Reads every older live link
checkSchema() => Promise<void>Throws unless the database is at share schema 1.0.0. The first query runs it too

useShareLinks(api.share, target, options?) from @dimah-s3/share/react keeps the links of one object or folder in React state, for an owner screen. react is an optional peer of @dimah-s3/share, needed only for this entry. A null target waits, so a dialog can pass its target only while it is open.

"use client";

import { useShareLinks } from "@dimah-s3/share/react";

const api = s3Client.useApi();
const { links, status, create, update, revoke } = useShareLinks(api.share, {
  type: "object",
  key,
});
await create({ maxDownloads: 3 });
OptionTypeDefaultDescription
includeRevokedbooleanfalseAlso list revoked links, and keep a link once it is revoked. Ignored with status
statusShareLinkStatus | ShareLinkStatus[]—Only links in these statuses. A create, change, or revoke that moves a link out of them takes it out of links
limitnumber100Links per page, 1 to 100
PropertyTypeDescription
targetShareTargetInput | nullThe object or folder the links belong to
linksreadonly ShareClientLink[]The target's links, newest first
status"idle" | "loading" | "refreshing" | "loading-more" | "ready" | "error"idle without a target, as in useObjectList
errorAPIError | nullWhy the last load failed, while status is error
isLoadingbooleanThe first page is on its way, and there is nothing to show
isRefreshingbooleanThe first page loads again; links stay
isLoadingMorebooleanThe next page is on its way
hasMorebooleanAnother page follows
loadMore() => Promise<void>Appends the next page; ignored while a load is on its way
refresh() => Promise<void>Loads the first page again, keeping links until it arrives
retry() => Promise<void>Repeats the load that failed
create(settings?) => Promise<ShareClientLink>Creates a link to the target and puts it first
update(id, settings) => Promise<ShareClientLink>Changes a link's settings
revoke(id) => Promise<ShareClientLink>Turns a link off; it leaves links unless includeRevoked, or status has revoked

A failed load never rejects: it sets error, and a failed next page keeps the links already loaded. create, update, and revoke reject with an APIError, such as VALIDATION_ERROR. The ShareLinkDialog takes the hook's return.

useShareVisit()

useShareVisit(api.share, token, options?) from @dimah-s3/share/react holds the page a link opens, for a visitor without a session: it opens the link, unlocks it with the password, and downloads its files. Pass link from a server openLink to render at once.

"use client";

import { useShareVisit } from "@dimah-s3/share/react";

const visit = useShareVisit(s3Client.share, token);

if (visit.status === "locked") await visit.unlock(password);
if (visit.status === "ready") await visit.download(fileId);
OptionTypeDefaultDescription
linkShareVisitorLink—The link from a server openLink, for this token
PropertyTypeDescription
status"loading" | "locked" | "ready" | "error"Where the visit stands
linkShareVisitorLockedLink | ShareVisitorOpenLink | nullThe locked link while locked, the opened one while ready
errorAPIError | nullWhy the link does not open, while status is error
tokenstringThe token the visit is for
accessstring | undefinedThe password proof from unlock; every later call sends it
unlock(password) => Promise<void>Trades the password for access, then opens the link again
download(id?, { disposition? }) => Promise<ShareDownloadResponse>Sends the browser to a file and updates link.downloadsLeft
refresh() => voidOpens the link again, such as after a network error
sourceShareObjectSourceA read-only useObjectList source over the link, with access

status tells the rest apart, so visit.link is the opened link inside if (visit.status === "ready"). A call that finds the link gone, such as a download after the owner revoked it, moves the visit to error; one whose password proof expired moves it back to locked. unlock and download reject with an APIError, such as SHARE_PASSWORD_INVALID. The SharedView takes the hook's return.

shareObjectSource()

shareObjectSource(api.share, { token, access?, limit? }) from @dimah-s3/share/client returns a read-only useObjectList source. It lists one folder per page, searches every folder below the open one, and maps a file's objectKey to its share id.

downloadSharedFile(api.share, id, { token, access?, disposition?, signal? }) gets a download URL, navigates to it, and resolves with the downloadShared response, so a page can show the new downloadsLeft.

Errors

SituationStatusCode
No link has the token, or the owner asked for another scope's404SHARE_LINK_NOT_FOUND
The link expired410SHARE_LINK_EXPIRED
The owner revoked it410SHARE_LINK_REVOKED
It reached maxDownloads410SHARE_LINK_EXHAUSTED
Its file or folder was deleted, its route removed, or authorizeVisit refused410SHARE_TARGET_UNAVAILABLE
A visitor call on a locked link without a valid access401SHARE_PASSWORD_REQUIRED
unlockLink with the wrong password401SHARE_PASSWORD_INVALID
A folder link while folders: false400SHARE_FOLDER_LINKS_DISABLED
A forged or expired /share/file URL403SHARE_DOWNLOAD_URL_INVALID
A file or folder id outside the share404OBJECT_NOT_FOUND, FOLDER_NOT_FOUND
A route without downloads404FEATURE_DISABLED

The SHARE_* codes are in the core catalog, S3_ERROR_CODES from @dimah-s3/core, so useFormatError words them with the rest, in your translations. SHARE_ERROR_CODES names the same entries.

Frequently asked questions

On this page