# Share API (https://s3.dimah.dev/docs/share/api)

The reference for [`@dimah-s3/share`](https://s3.dimah.dev/docs/share). The plugin needs
[`db()`](https://s3.dimah.dev/docs/db) in the same `plugins` list.

## Policy [#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`](https://s3.dimah.dev/docs/react/helpers#errors) words it.

```ts title="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-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:

```ts title="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 [#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 [#api-reference]

### share() [#share]

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

| Prop                | Type                                                              | Default               | Description                                                                                   |
| ------------------- | ----------------------------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------- |
| `client`            | `DimahS3ShareClient`                                              | required              | `DimahS3Share.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                                                      |
| `folders`           | `boolean`                                                         | `true`                | Allow links to folders                                                                        |
| `downloadExpiresIn` | `number`                                                          | `300`                 | Lifetime of a visitor's download URL in seconds, capped by the route's `maxExpiresIn`         |
| `unlockExpiresIn`   | `number`                                                          | `3600`                | Lifetime 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 [#shareauthorizecontext]

Fields marked `?` are optional.

| Property    | Type                                                                       | Description                                                                                     |
| ----------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `action`    | `"createLink" \| "listLinks" \| "getLink" \| "updateLink" \| "revokeLink"` | The owner action                                                                                |
| `scope`     | `string`                                                                   | The caller's db scope                                                                           |
| `request`   | `Request`                                                                  | The request                                                                                     |
| `locals`    | `DimahS3Locals`                                                            | What 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?`     | `ShareLink`                                                                | The link as it is, on `getLink`, `updateLink`, and `revokeLink`                                 |
| `settings?` | `{ expiresAt; passwordProtected; maxDownloads; label }`                    | The settings it will have, on `createLink` and `updateLink`                                     |

### ShareVisitContext [#sharevisitcontext]

| Property  | Type                                                             | Description                                                                                   |
| --------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `action`  | `"openLink" \| "listShared" \| "downloadShared" \| "sharedFile"` | The visitor action                                                                            |
| `link`    | `ShareLink`                                                      | The link, with its `scope`                                                                    |
| `target`  | `{ type: "object"; object } \| { type: "folder"; folder }`       | The db row the link points at                                                                 |
| `folder?` | `StorageFolder`                                                  | The folder `listShared` lists or searches, or the one that holds `object`. Absent at the root |
| `object?` | `StorageObject`                                                  | The file `downloadShared` and `sharedFile` send, or an object link's file                     |
| `request` | `Request`                                                        | The request                                                                                   |
| `locals`  | `DimahS3Locals`                                                  | What the guards returned                                                                      |

### Client actions [#client-actions]

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

| Action           | Endpoint               | Who     | Returns                      |
| ---------------- | ---------------------- | ------- | ---------------------------- |
| `createLink`     | `POST /share/link`     | Owner   | `{ link: ShareClientLink }`  |
| `listLinks`      | `GET /share/links`     | Owner   | `{ links, nextCursor }`      |
| `getLink`        | `GET /share/link`      | Owner   | `{ link }`                   |
| `updateLink`     | `PATCH /share/link`    | Owner   | `{ link }`                   |
| `revokeLink`     | `DELETE /share/link`   | Owner   | `{ link }`                   |
| `openLink`       | `GET /share/open`      | Visitor | `{ link: ShareVisitorLink }` |
| `unlockLink`     | `POST /share/unlock`   | Visitor | `{ access, expiresAt }`      |
| `listShared`     | `GET /share/items`     | Visitor | `ShareListSharedResponse`    |
| `downloadShared` | `POST /share/download` | Visitor | `ShareDownloadResponse`      |

`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`.

### createLink input [#createlink-input]

| Prop           | Type                                                               | Default              | Description                                                                       |
| -------------- | ------------------------------------------------------------------ | -------------------- | --------------------------------------------------------------------------------- |
| `target`       | `{ type: "object"; key; bucket? } \| { type: "folder"; folderId }` | required             | What to share. `bucket` only when the routes use several                          |
| `expiresAt`    | `Date \| string \| null`                                           | `expiration.default` | When the link stops opening. `null` never expires, unless `expiration.max` is set |
| `expiresIn`    | `number`                                                           | —                    | Lifetime in whole seconds, from the server's clock. Instead of `expiresAt`        |
| `password`     | `string \| null`                                                   | —                    | Visitors enter it first                                                           |
| `maxDownloads` | `number \| null`                                                   | —                    | Downloads the link hands out, 1 to 1,000,000                                      |
| `label`        | `string \| 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`:

```ts
// The links of a file that still open.
const { links } = await s3Client.share.listLinks({
  target: { type: "object", key },
  status: "active",
});
```

### ShareClientLink [#shareclientlink]

| Property            | Type                                                | Description                                                            |
| ------------------- | --------------------------------------------------- | ---------------------------------------------------------------------- |
| `id`                | `string`                                            | The link id                                                            |
| `token`             | `string`                                            | The secret of the link                                                 |
| `url`               | `string \| null`                                    | From 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 |
| `label`             | `string \| null`                                    | Your note                                                              |
| `passwordProtected` | `boolean`                                           | Visitors enter a password first                                        |
| `expiresAt`         | `string \| null`                                    | ISO date                                                               |
| `maxDownloads`      | `number \| null`                                    | The download limit                                                     |
| `downloadCount`     | `number`                                            | Download URLs handed out                                               |
| `viewCount`         | `number`                                            | Unlocked opens, each one counted                                       |
| `lastAccessedAt`    | `string \| null`                                    | Last open or download                                                  |
| `revokedAt`         | `string \| null`                                    | When it was turned off                                                 |
| `createdAt`         | `string`                                            | ISO date                                                               |
| `updatedAt`         | `string`                                            | ISO date                                                               |

### Visitor inputs and responses [#visitor-inputs-and-responses]

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

| Action           | Also takes                                      | Response                                                                                                            |
| ---------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `openLink`       | —                                               | `link`: `type`, `locked`, `passwordProtected`, `expiresAt`, `downloadsLeft`, and `object` or `folder` once unlocked |
| `unlockLink`     | `password`                                      | `access`, `expiresAt`                                                                                               |
| `listShared`     | `folderId`, `search`, `sort`, `limit`, `cursor` | `objects`, `nextCursor`; the first page adds `folders` and `trail`, a search `locations` and `total`                |
| `downloadShared` | `id` (required on a folder link), `disposition` | `url`, `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 [#s3share]

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

| Property      | Type                                                                        | Description                                                                                                                                                                                                |
| ------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `api`         | `ShareServerApi`                                                            | Every client action as `(input, options?)`, behind the instance guard. `options` is `S3ServerCallOptions`                                                                                                  |
| `links`       | `ShareLinks`                                                                | `find`, `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() [#usesharelinks]

`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.

```tsx
"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 });
```

| Option           | Type                                   | Default | Description                                                                                                     |
| ---------------- | -------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| `includeRevoked` | `boolean`                              | `false` | Also list revoked links, and keep a link once it is revoked. Ignored with `status`                              |
| `status`         | `ShareLinkStatus \| ShareLinkStatus[]` | —       | Only links in these statuses. A create, change, or revoke that moves a link out of them takes it out of `links` |
| `limit`          | `number`                               | `100`   | Links per page, 1 to 100                                                                                        |

| Property        | Type                                                                          | Description                                                                            |
| --------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `target`        | `ShareTargetInput \| null`                                                    | The object or folder the links belong to                                               |
| `links`         | `readonly ShareClientLink[]`                                                  | The target's links, newest first                                                       |
| `status`        | `"idle" \| "loading" \| "refreshing" \| "loading-more" \| "ready" \| "error"` | `idle` without a target, as in `useObjectList`                                         |
| `error`         | `APIError \| null`                                                            | Why the last load failed, while `status` is `error`                                    |
| `isLoading`     | `boolean`                                                                     | The first page is on its way, and there is nothing to show                             |
| `isRefreshing`  | `boolean`                                                                     | The first page loads again; `links` stay                                               |
| `isLoadingMore` | `boolean`                                                                     | The next page is on its way                                                            |
| `hasMore`       | `boolean`                                                                     | Another 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`](https://s3.dimah.dev/docs/ui/components/share-link-dialog) takes the hook's
return.

### useShareVisit() [#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`](#s3share) to render at once.

```tsx
"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);
```

| Option | Type               | Default | Description                                         |
| ------ | ------------------ | ------- | --------------------------------------------------- |
| `link` | `ShareVisitorLink` | —       | The link from a server `openLink`, for this `token` |

| Property   | Type                                                        | Description                                                     |
| ---------- | ----------------------------------------------------------- | --------------------------------------------------------------- |
| `status`   | `"loading" \| "locked" \| "ready" \| "error"`               | Where the visit stands                                          |
| `link`     | `ShareVisitorLockedLink \| ShareVisitorOpenLink \| null`    | The locked link while `locked`, the opened one while `ready`    |
| `error`    | `APIError \| null`                                          | Why the link does not open, while `status` is `error`           |
| `token`    | `string`                                                    | The token the visit is for                                      |
| `access`   | `string \| undefined`                                       | The 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`  | `() => void`                                                | Opens the link again, such as after a network error             |
| `source`   | `ShareObjectSource`                                         | A 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`](https://s3.dimah.dev/docs/ui/components/shared-view) takes the hook's return.

### shareObjectSource() [#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 [#errors]

| Situation                                                                      | Status | Code                                   |
| ------------------------------------------------------------------------------ | ------ | -------------------------------------- |
| No link has the token, or the owner asked for another scope's                  | `404`  | `SHARE_LINK_NOT_FOUND`                 |
| The link expired                                                               | `410`  | `SHARE_LINK_EXPIRED`                   |
| The owner revoked it                                                           | `410`  | `SHARE_LINK_REVOKED`                   |
| It reached `maxDownloads`                                                      | `410`  | `SHARE_LINK_EXHAUSTED`                 |
| Its file or folder was deleted, its route removed, or `authorizeVisit` refused | `410`  | `SHARE_TARGET_UNAVAILABLE`             |
| A visitor call on a locked link without a valid `access`                       | `401`  | `SHARE_PASSWORD_REQUIRED`              |
| `unlockLink` with the wrong password                                           | `401`  | `SHARE_PASSWORD_INVALID`               |
| A folder link while `folders: false`                                           | `400`  | `SHARE_FOLDER_LINKS_DISABLED`          |
| A forged or expired `/share/file` URL                                          | `403`  | `SHARE_DOWNLOAD_URL_INVALID`           |
| A file or folder id outside the share                                          | `404`  | `OBJECT_NOT_FOUND`, `FOLDER_NOT_FOUND` |
| A route without downloads                                                      | `404`  | `FEATURE_DISABLED`                     |

The `SHARE_*` codes are in the core catalog, `S3_ERROR_CODES` from
`@dimah-s3/core`, so [`useFormatError`](https://s3.dimah.dev/docs/react/helpers#errors) words
them with the rest, in your `translations`. `SHARE_ERROR_CODES` names the same
entries.

## Frequently asked questions [#frequently-asked-questions]

<Accordions>
<Accordion title="Can I share with another signed-in user instead of a link?">
Not with this plugin. Sharing between accounts needs roles and inheritance
through folders, which depend on your user model. For a team, give its
members one db scope, such as `org:acme`.
</Accordion>

<Accordion title="Does a link follow a file that is replaced?">
Yes, when a route sets `plugins: { db: { replace: "overwrite" } }`: the db
row keeps its id. A file deleted and uploaded again gets a new id, so its
old links stop opening.
</Accordion>

<Accordion title="How do I turn off every link before I hide a file?">
`await s3.share.links.revokeTarget({ type: "object", objectId: object.id })`.
</Accordion>
</Accordions>