From bff4112f7ce9cacb88758b3a364e0b0f56697e6b Mon Sep 17 00:00:00 2001 From: CJ Brewer Date: Fri, 4 Dec 2026 12:24:10 -0700 Subject: [PATCH 1/7] feat!: run a spool headless, with cipherstash as the one vault A Spool can run as the CRM's server with no interface, behind a front end of your own. Everything the CRM does for whoever asks is an operation, defined once and reached by the interface's server functions, the HTTP API and the server's own code alike. - httpApi and headlessServer: every operation over HTTP, with no web framework - a typed client, and src/crm.types.ts generated from the config - API keys, opt-in, sealed by the vault and ending after 90 days by default - Clerk without TanStack Start, and Better Auth with a bearer session - create-spools --headless - docs for headless mode across the README and the docs site BREAKING CHANGE: the AES vault (@swirls/spools/vault/aes, VAULT_KEY, VAULT_OLD_KEYS) is removed. CipherStash is the vault, and a production server does not start without the CS_* variables. Clerk takes a session only from the front end at APP_URL or the ones named in authorizedParties. See docs/upgrading.md. Co-Authored-By: Claude Fable 5.2 --- .changeset/headless-backend.md | 63 ++ .github/workflows/ci.yml | 2 +- .gitignore | 1 + .oxfmtrc.json | 2 + .oxlintrc.json | 51 +- AGENTS.md | 7 +- README.md | 63 +- apps/docs/src/docs-manifest.json | 120 +++- apps/docs/src/landing/adapters.ts | 8 - apps/docs/src/nav.ts | 1 + apps/starter/.env.example | 18 +- apps/starter/e2e/playwright.config.ts | 8 +- apps/starter/e2e/spool.server.ts | 5 +- apps/starter/prisma/schema.d.ts | 222 +++++- apps/starter/prisma/schema.json | 279 +++++++- apps/starter/prisma/schema.prisma | 28 + apps/starter/src/crm.types.ts | 77 +++ docs/README.md | 3 + docs/adapters.md | 23 +- docs/api.md | 35 +- docs/architecture.md | 6 + docs/auth.md | 22 +- docs/coding-agents.md | 4 + docs/deployment.md | 37 +- docs/extending.md | 11 + docs/files.md | 4 + docs/headless.md | 325 +++++++++ docs/integrations.md | 11 +- docs/quickstart.md | 8 +- docs/roles.md | 3 + docs/security.md | 58 +- docs/server-code.md | 31 +- docs/upgrading.md | 47 ++ docs/when-to-use.md | 16 +- packages/create-spools/README.md | 5 + .../overrides-headless/AGENTS.md | 51 ++ .../overrides-headless/CLAUDE.md | 1 + .../overrides-headless/README.md | 42 ++ .../overrides-headless/_gitignore | 26 + .../overrides-headless/_oxlintrc.json | 30 + .../overrides-headless/examples/client.ts | 49 ++ .../overrides-headless/src/server.ts | 62 ++ .../overrides-headless/tsconfig.json | 20 + packages/create-spools/overrides/AGENTS.md | 2 +- .../create-spools/overrides/_oxlintrc.json | 1 + packages/create-spools/package.json | 3 +- packages/create-spools/scripts/template.ts | 122 +++- packages/create-spools/src/main.ts | 9 +- packages/create-spools/tests/main.test.ts | 39 ++ packages/spools/package.json | 24 +- packages/spools/scripts/assemble.ts | 2 +- .../src/adapters/auth/better-auth/server.ts | 85 ++- .../spools/src/adapters/auth/clerk/backend.ts | 123 ++++ .../spools/src/adapters/auth/clerk/core.ts | 652 +++++++++++++++++ .../spools/src/adapters/auth/clerk/server.ts | 579 +--------------- .../spools/src/adapters/vault/aes/server.ts | 158 ----- .../src/adapters/vault/cipherstash/server.ts | 56 +- .../adapters/vault/cipherstash/stand-in.ts | 64 ++ packages/spools/src/cli/gen.ts | 6 + packages/spools/src/cli/keys.ts | 132 ++++ packages/spools/src/cli/main.ts | 2 + packages/spools/src/client.ts | 218 ++++++ packages/spools/src/crm/codegen-types.ts | 165 +++++ packages/spools/src/headless.ts | 174 +++++ packages/spools/src/server/api-keys.ts | 321 +++++++++ packages/spools/src/server/api.ts | 49 ++ .../spools/src/server/assistant.functions.ts | 126 +--- packages/spools/src/server/callers.ts | 8 +- packages/spools/src/server/crm.functions.ts | 325 ++------- packages/spools/src/server/email.functions.ts | 29 +- packages/spools/src/server/entry.ts | 42 +- packages/spools/src/server/files.functions.ts | 136 +--- packages/spools/src/server/files.ts | 5 +- .../spools/src/server/guides.functions.ts | 25 +- packages/spools/src/server/http.ts | 476 +++++++++++++ packages/spools/src/server/idempotency.ts | 29 +- .../src/server/integrations.functions.ts | 35 +- .../spools/src/server/layouts.functions.ts | 49 +- .../spools/src/server/mailbox.functions.ts | 15 +- .../spools/src/server/marketing.functions.ts | 129 +--- packages/spools/src/server/middleware.ts | 22 - .../spools/src/server/operations/answers.ts | 77 +++ .../spools/src/server/operations/assistant.ts | 129 ++++ packages/spools/src/server/operations/crm.ts | 348 ++++++++++ .../spools/src/server/operations/define.ts | 86 +++ .../spools/src/server/operations/email.ts | 33 + .../spools/src/server/operations/files.ts | 145 ++++ .../spools/src/server/operations/guides.ts | 31 + .../spools/src/server/operations/index.ts | 82 +++ .../src/server/operations/integrations.ts | 46 ++ .../spools/src/server/operations/layouts.ts | 53 ++ .../spools/src/server/operations/mailbox.ts | 27 + .../spools/src/server/operations/marketing.ts | 165 +++++ .../spools/src/server/operations/roles.ts | 35 + .../spools/src/server/operations/workspace.ts | 587 ++++++++++++++++ packages/spools/src/server/roles.functions.ts | 25 +- packages/spools/src/server/runtime/access.ts | 11 + packages/spools/src/server/runtime/auth.ts | 18 +- .../spools/src/server/runtime/boundary.ts | 104 ++- packages/spools/src/server/runtime/host.ts | 53 ++ packages/spools/src/server/runtime/session.ts | 25 +- packages/spools/src/server/runtime/tokens.ts | 7 + packages/spools/src/server/scopes.ts | 19 +- packages/spools/src/server/store/tables.ts | 36 + .../spools/src/server/workspace.functions.ts | 585 ++-------------- packages/spools/src/start.ts | 54 ++ .../fixtures/baseline/example.schema.prisma | 28 + .../fixtures/baseline/example.schema.sql | 24 + .../tests/fixtures/scoped/prisma/schema.d.ts | 222 +++++- .../tests/fixtures/scoped/prisma/schema.json | 279 +++++++- .../fixtures/scoped/prisma/schema.prisma | 28 + .../spools/tests/integration/door.test.ts | 25 + .../spools/tests/integration/files.test.ts | 15 + .../spools/tests/integration/http.test.ts | 653 ++++++++++++++++++ .../tests/integration/idempotency.test.ts | 30 +- .../spools/tests/unit/auth-adapters.test.ts | 34 + .../spools/tests/unit/better-auth.test.ts | 86 +++ .../spools/tests/unit/cipherstash.test.ts | 9 +- .../spools/tests/unit/clerk-backend.test.ts | 200 ++++++ packages/spools/tests/unit/cli.test.ts | 2 +- .../spools/tests/unit/codegen-types.test.ts | 75 ++ .../tests/unit/effects-after-checks.test.ts | 11 +- .../spools/tests/unit/framework-free.test.ts | 140 ++++ packages/spools/tests/unit/guardrails.test.ts | 2 +- .../spools/tests/unit/integrations.test.ts | 18 +- packages/spools/tests/unit/vault.test.ts | 162 +++-- scripts/check-package.ts | 96 ++- 127 files changed, 8912 insertions(+), 2330 deletions(-) create mode 100644 .changeset/headless-backend.md create mode 100644 apps/starter/src/crm.types.ts create mode 100644 docs/headless.md create mode 100644 packages/create-spools/overrides-headless/AGENTS.md create mode 100644 packages/create-spools/overrides-headless/CLAUDE.md create mode 100644 packages/create-spools/overrides-headless/README.md create mode 100644 packages/create-spools/overrides-headless/_gitignore create mode 100644 packages/create-spools/overrides-headless/_oxlintrc.json create mode 100644 packages/create-spools/overrides-headless/examples/client.ts create mode 100644 packages/create-spools/overrides-headless/src/server.ts create mode 100644 packages/create-spools/overrides-headless/tsconfig.json create mode 100644 packages/spools/src/adapters/auth/clerk/backend.ts create mode 100644 packages/spools/src/adapters/auth/clerk/core.ts delete mode 100644 packages/spools/src/adapters/vault/aes/server.ts create mode 100644 packages/spools/src/adapters/vault/cipherstash/stand-in.ts create mode 100644 packages/spools/src/cli/keys.ts create mode 100644 packages/spools/src/client.ts create mode 100644 packages/spools/src/crm/codegen-types.ts create mode 100644 packages/spools/src/headless.ts create mode 100644 packages/spools/src/server/api-keys.ts create mode 100644 packages/spools/src/server/api.ts create mode 100644 packages/spools/src/server/http.ts delete mode 100644 packages/spools/src/server/middleware.ts create mode 100644 packages/spools/src/server/operations/answers.ts create mode 100644 packages/spools/src/server/operations/assistant.ts create mode 100644 packages/spools/src/server/operations/crm.ts create mode 100644 packages/spools/src/server/operations/define.ts create mode 100644 packages/spools/src/server/operations/email.ts create mode 100644 packages/spools/src/server/operations/files.ts create mode 100644 packages/spools/src/server/operations/guides.ts create mode 100644 packages/spools/src/server/operations/index.ts create mode 100644 packages/spools/src/server/operations/integrations.ts create mode 100644 packages/spools/src/server/operations/layouts.ts create mode 100644 packages/spools/src/server/operations/mailbox.ts create mode 100644 packages/spools/src/server/operations/marketing.ts create mode 100644 packages/spools/src/server/operations/roles.ts create mode 100644 packages/spools/src/server/operations/workspace.ts create mode 100644 packages/spools/src/server/runtime/host.ts create mode 100644 packages/spools/src/start.ts create mode 100644 packages/spools/tests/integration/http.test.ts create mode 100644 packages/spools/tests/unit/clerk-backend.test.ts create mode 100644 packages/spools/tests/unit/codegen-types.test.ts create mode 100644 packages/spools/tests/unit/framework-free.test.ts diff --git a/.changeset/headless-backend.md b/.changeset/headless-backend.md new file mode 100644 index 0000000..52b1369 --- /dev/null +++ b/.changeset/headless-backend.md @@ -0,0 +1,63 @@ +--- +'@swirls/spools': minor +'@swirls/create-spools': minor +--- + +A Spool can run headless: the CRM's server with no interface, behind a front end of your own. + +- **Operations.** Everything the CRM does for whoever asks is now defined once, as an + operation (`@swirls/spools/operations`). The interface's server functions run them, and + so does everything below. +- **The HTTP API.** `httpApi()` from `@swirls/spools/http` is one `Request` to `Response` + handler that answers every operation at `POST /api/v1/`, on any server. Whoever + calls is checked as in the interface: the access list, record scopes and role access all + apply. A caller is known by the session cookie on the same site, or by a sign-in token + sent as a bearer token, which is taken only from the front ends you name. +- **A typed client.** `createClient` from `@swirls/spools/client` knows every operation by + name, what it takes and what it answers. +- **Your objects, typed.** `spools gen` writes `src/crm.types.ts` from the config, and + `createClient()` then knows every field: `crm.records('deals').create({ ... })`. + `GET /api/v1/openapi.json` describes the API as OpenAPI 3.1. +- **API keys.** `spools keys create --name ... --as ` makes a key for a script or a + service, once the server says it takes keys (`keys: true`). It acts as that teammate, + with their access and no more, can be read-only, and ends after 90 days unless you say + otherwise. What is kept is sealed by the vault: the hash of the key and what + it may do, so neither reading the table nor writing to it yields a working key. A Spool + with no vault has no keys. +- **CipherStash is the vault.** `@swirls/spools/vault/aes`, `VAULT_KEY` and `VAULT_OLD_KEYS` + are removed. `vault: cipherstash()` seals everything a Spool keeps secret, and a production + server does not start without the `CS_*` variables. Without them outside production a + stand-in seals with a key that is in the source, which protects nothing and which a server + with CipherStash does not open. +- **A headless server and template.** `headlessServer()` from `@swirls/spools/headless` + answers everything a Spool answers except pages, with no TanStack Start, and + `bun create @swirls/spools my-crm --headless` starts a Spool that is only that. +- **Clerk without TanStack Start.** `clerk()` from `@swirls/spools/auth/clerk/backend` reads + the session from the request with Clerk's backend SDK. It takes a session cookie only + from the front end at `APP_URL`, or the origins in `clerk({ authorizedParties })`. +- **Better Auth in an app.** `betterAuth({ bearer: true })` lets a phone or desktop app + carry its session as a bearer token, handed over in a `set-auth-token` header at sign-in. +- **Answers in the API's description.** The reference and the OpenAPI document say what the + record operations answer, not only what they take. +- **No web framework on the server's side.** Nothing but `@swirls/spools/start` and the + server functions imports TanStack Start, and React and TanStack are now optional peer + dependencies. See [Headless](https://spools.codes/docs/headless). + +This version changes the tables: it adds `api_keys`. After updating run `bun run crm:gen`, +then `bun run db:push` or your migration. + +Things to know for an app that uses the interface: + +- `spools gen` now also writes `src/crm.types.ts`. Commit it, and add it to what your + formatter, linter and any generated-files check in CI leave alone or look at. + +- The spans of server functions are named after their operations now (`records.get` where + it was `crm.getRecord`). A dashboard or alert that reads span names needs the new ones. +- **Clerk checks which front end a session was issued to.** On a production server + `clerk()` takes a session only from the origin of `APP_URL`. If people use the CRM at + another address as well, name them all with `clerk({ authorizedParties: [...] })`. +- With Better Auth, a sign-in link opened from another site signs nobody in. +- A write repeated with its `Idempotency-Key` by someone whose access has changed since is + answered with its status and `Idempotent-Body: withheld`. +- The request middleware moved from `src/server/middleware.ts` to `src/start.ts` inside + the package. Apps import it as `@swirls/spools/start`, which is unchanged. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd2f460..9740bd1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: working-directory: apps/starter run: | bun run crm:gen - git diff --exit-code -- prisma crm.config.schema.json \ + git diff --exit-code -- prisma crm.config.schema.json src/crm.types.ts \ || (echo "::error::Run 'bun run crm:gen' in apps/starter and commit the result" && exit 1) # The scope tests run on a Spool of their own, whose Prisma schema is generated too. - name: Check the scope tests' generated schema diff --git a/.gitignore b/.gitignore index 6c8c238..fe913be 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,7 @@ test-results/ # Built from apps/starter when the package is packed packages/create-spools/template/ +packages/create-spools/template-headless/ # Flox .flox/.cache/ diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 99a7fae..3c64343 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -24,10 +24,12 @@ "**/routeTree.gen.ts", "**/prisma/schema.*", "**/crm.config.schema.json", + "**/crm.types.ts", "**/migrations/**", "**/supabase/**", "**/docs-manifest.json", "packages/create-spools/template/**", + "packages/create-spools/template-headless/**", "tools/oxlint/anti-slop/**", "bun.lock", ".agent/**", diff --git a/.oxlintrc.json b/.oxlintrc.json index 79a0b0c..d2b7393 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -17,8 +17,11 @@ "**/.flox/**", "**/routeTree.gen.ts", "**/prisma/schema.d.ts", + "**/crm.types.ts", "**/migrations/**", "packages/create-spools/template/**", + "packages/create-spools/template-headless/**", + "packages/create-spools/overrides-headless/**", ".agent/**", ".agents/**", ".claude/**", @@ -261,8 +264,50 @@ "packages/spools/src/server/env.ts", "packages/spools/src/server/entry.ts", "packages/spools/src/server/spool.ts", - "packages/spools/src/server/store/sql.ts" + "packages/spools/src/server/store/sql.ts", + "packages/spools/src/server/*.functions.ts" ], + "rules": { + "spools/effect-modules": "error", + "no-restricted-imports": [ + "error", + { + "patterns": [ + { + "group": ["@tanstack/**", "react", "react/**", "react-dom", "react-dom/**"], + "message": "The server is free of any web framework, so a Spool can run with none (docs/headless.md). TanStack Start is bound in packages/spools/src/start.ts, and a server function in a *.functions.ts file that only binds an operation (packages/spools/src/server/operations)." + }, + { + "group": ["**/app/extensions", "**/spool.server"], + "message": "The framework never imports the app. Read it from the Spool (packages/spools/src/server/spool.ts)." + }, + { + "group": ["**/adapters/**"], + "message": "The framework never imports an adapter. It asks for the port, and the Spool provides the adapter; see docs/adapters.md." + }, + { + "group": ["@prisma/**", "@effect/sql-*", "@electric-sql/**"], + "message": "Only an adapter (packages/spools/src/adapters/database) talks to a database. Ask for the Store service (packages/spools/src/server/store/store.ts), so reads get a time limit and failures a type." + }, + { + "group": [ + "@clerk/**", + "resend", + "@swirls/sdk", + "@swirls/sdk/*", + "@cipherstash/**", + "better-auth", + "better-auth/*" + ], + "message": "Only an adapter (packages/spools/src/adapters) talks to a vendor's SDK. Ask for the port; see docs/adapters.md." + } + ] + } + ] + } + }, + { + "files": ["packages/spools/src/server/*.functions.ts"], "rules": { "spools/effect-modules": "error", "no-restricted-imports": [ @@ -311,6 +356,10 @@ "error", { "patterns": [ + { + "group": ["@tanstack/**", "react", "react/**", "react-dom", "react-dom/**"], + "message": "The server is free of any web framework, so a Spool can run with none (docs/headless.md). TanStack Start is bound in packages/spools/src/start.ts, and a server function in a *.functions.ts file that only binds an operation (packages/spools/src/server/operations)." + }, { "group": ["**/app/extensions", "**/spool.server"], "message": "The framework never imports the app. Read it from the Spool (packages/spools/src/server/spool.ts)." diff --git a/AGENTS.md b/AGENTS.md index 2081576..ec83adb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,8 +37,8 @@ In the rest of this file `P` is `packages/spools/src`, and a path that starts wi automations, campaigns and an app's own guides live there (contract: `P/crm/config-schema.ts`, docs: `docs/configuration.md`). After editing it, run `bun run crm:gen` then, if `DATABASE_URL` is set, `bun run db:push`. Never hand-edit - `prisma/schema.prisma`, `prisma/schema.json`, `prisma/schema.d.ts` or - `crm.config.schema.json`: they're generated, and CI fails if they drift. + `prisma/schema.prisma`, `prisma/schema.json`, `prisma/schema.d.ts`, + `crm.config.schema.json` or `src/crm.types.ts`: they're generated, and CI fails if they drift. - **A Spool chooses its services in `src/spool.server.ts`** (`defineSpool`), and auth's browser half in `src/spool.ui.ts`. The framework asks for **ports** (`Store`, `Auth`, `FileStore`, `Email`, `Vault`, `Agents`, `RateLimiter`, and `Tokens`, which an auth @@ -168,7 +168,7 @@ In the rest of this file `P` is `packages/spools/src`, and a path that starts wi - **Logged calls and meetings, team activity report.** Kinds, outcomes, date ranges and the per-person counts in `P/crm/activity.ts` (pure, shared); storage and queries in `P/server/workspace.ts` - **Teammates' mail and calendar, sending from their mailbox.** Through the Google or Microsoft account they sign in with (the auth provider keeps its tokens) and any mailbox they connected on the Integrations page. Scopes and what they allow in `P/crm/mailbox.ts` (pure, shared); sign-in accounts and the auth provider's tokens through the `SignIns` service (`P/server/sign-ins.ts`); accounts from both sources, tokens, provider calls (the `mailApi` policy: reads retried on 429/5xx with `Retry-After`, sends never repeated) and sending in `P/server/mailbox.ts`; provider readers (Gmail, Graph), matching addresses to records, `ingest` and the schedule (`syncSchedule`, a fiber started by `startSync` in `src/server.ts`) in `P/server/sync.ts`; cron entry `src/routes/api/cron/mail-sync.ts`; panel `P/crm/ui/mailbox.tsx`. Synced activities carry `externalId` and go through `addActivityOnce`; docs/mailbox.md - **Files.** A file browser over the `FileStore` port (`P/server/runtime/files.ts`), whose adapters are `P/adapters/files/*`. Names and limits in `P/crm/files.ts` (pure, shared); breadcrumbs, listing, record folders (`record_folders`), uploads (`file_uploads`) and the library in `P/server/files.ts`; server functions `P/server/files.functions.ts`; handlers `P/api/file.ts`, `P/api/upload.ts`; the browser `P/crm/ui/files.tsx`, used by the Files page and a record's Files tab. An object opts in with `files: { folders, under }`; top-level `files` names the shared library. Tests of the FlashDrive adapter use ``createFakeStore`from`@swirls/spools/testing` (`P/testing/fake-file-store.ts`)`; an app's hooks reach record folders through `@swirls/spools/extensions`; docs/files.md -- **Accounts teammates connect (more mailboxes, other services).** OAuth flow, token refresh and the built-in Google and Microsoft providers in `P/server/integrations.ts`; tokens are sealed by the `Vault` port (`P/server/runtime/vault.ts`; adapters `P/adapters/vault/*`; no plaintext fallback) before they reach the `integrations` table; token exchange and refresh go through `HttpClient` with the `oauth` policy. Handlers `P/api/integration-*.ts`, page `P/pages/integrations.tsx`. An app adds a provider under `integrations` in `src/app/extensions.ts` and gets tokens from `getAccessToken` in `@swirls/spools/extensions`. A connection is its teammate's own unless its provider says `shared: 'team'` or `shared: 'group'` (with `groups`, and `canManage` for who may connect and disconnect): the row says whose it is (`shared`, `groupKey`), its tokens are sealed for that (`ownerOf`), the signed `state` carries it (`readState`), and nothing about a shared connection may depend on its connector still being on the access list. Who may use one is decided in one place (`usableBy`), who may manage one in another (`mayManage`), and what the page is sent is built in `connectionsOverview`. A token renewal runs beside whoever asked for it (`tokenOnce`), never inside their request: a request is interrupted when its browser goes away, and a renewal must finish. Tests use `Vault.layerTest` through `installStandIns`; docs/integrations.md +- **Accounts teammates connect (more mailboxes, other services).** OAuth flow, token refresh and the built-in Google and Microsoft providers in `P/server/integrations.ts`; tokens are sealed by the `Vault` port (`P/server/runtime/vault.ts`; no plaintext fallback), whose one adapter is CipherStash (`P/adapters/vault/cipherstash`): a production server does not start without the `CS_*` variables, and outside production without them `stand-in.ts` seals with a key that is in the source (`vaultFor` says which), so never add a second vault or a key from the environment before they reach the `integrations` table; token exchange and refresh go through `HttpClient` with the `oauth` policy. Handlers `P/api/integration-*.ts`, page `P/pages/integrations.tsx`. An app adds a provider under `integrations` in `src/app/extensions.ts` and gets tokens from `getAccessToken` in `@swirls/spools/extensions`. A connection is its teammate's own unless its provider says `shared: 'team'` or `shared: 'group'` (with `groups`, and `canManage` for who may connect and disconnect): the row says whose it is (`shared`, `groupKey`), its tokens are sealed for that (`ownerOf`), the signed `state` carries it (`readState`), and nothing about a shared connection may depend on its connector still being on the access list. Who may use one is decided in one place (`usableBy`), who may manage one in another (`mayManage`), and what the page is sent is built in `connectionsOverview`. A token renewal runs beside whoever asked for it (`tokenOnce`), never inside their request: a request is interrupted when its browser goes away, and a renewal must finish. Tests use `Vault.layerTest` through `installStandIns`; docs/integrations.md - **Marketing: the website's tags, social posts, ad results.** Set up under `marketing` in `crm.config.json`, which is what makes the Marketing page appear. Tags (how each is found in a page, its install code), post limits and UTM parameters in `P/crm/marketing.ts` (pure, shared). The engine is `P/server/marketing.ts`: the site scan (the `website` policy), posts (`marketing_posts`) and ad results (`marketing_ads`). Networks are a registry (`P/server/marketing-networks.ts`): the built-in ones (linkedin, x, facebook; meta, google) call each API through `HttpClient` with the `marketingApi` policy (reads retried, a post never), and an app adds or replaces one under `marketing` in `src/app/extensions.ts`. A network gets its token from the environment or from a teammate's connection (`accessToken`); the OAuth providers for the built-in ones are in `P/server/marketing-providers.ts` and are offered on the Integrations page only while the config uses them. A channel or ad account is reached `direct` (that code) or `via: "swirls"` (`publish_` / `ads_` through `Agents.executeWorkflow`, answered by the tools `post_result` and `save_ads`); `site_profile` is always a workflow. A post is taken with one `Store.update` (`hold`) and never sent twice: a `NetworkFailure` that is `uncertain` leaves a note to look at the channel first. Scheduling and publishing are server functions only (`P/server/marketing.functions.ts`): the tool API can draft and nothing more. `tick` publishes what is due (`startMarketing`, or `/api/cron/marketing` on a serverless host). Tests replace `MarketingSource` (`P/server/marketing-source.ts`), `Agents` and `fetch` through `installStandIns`. Workflows: `swirls/marketing.swirls` (`site_profile`) and `examples/swirls/marketing-networks.swirls` (every network, for `via: "swirls"`); docs/marketing.md - **Tasks, notes, favourites, reports, CSV export.** `P/server/workspace.ts` + `P/server/workspace.functions.ts`; CSV parsing in `P/crm/csv.ts` - **Choosing a related record.** `P/crm/ui/relation-picker.tsx`: `RelationInput` (forms), `RelationPopover` (inline editing), `RelationSearch` (the list filter). It searches the server as you type (`searchTitles` in `P/server/records.ts`, through `searchRelationFn`); never send a page the list of records a relation could point at. A value known only by its id gets its title from `titles` when the page has it (a list sends the ones its filters name) or from `relationTitlesFn`. CSV import matches names on the server (`matchTitles`) @@ -194,6 +194,7 @@ In the rest of this file `P` is `packages/spools/src`, and a path that starts wi - **New server function or API route.** `.handler(crmHandler("name", ({ data, user }) => program))` (or `publicHandler` for signed-out pages); routes use an adapter from `P/server/runtime/boundary.ts`. Lint enforces both - **Errors staff see.** A `Schema.TaggedError` with a staff-readable `message` (shared ones in `P/server/runtime/errors.ts`, a module's own next to it), added to `StaffError`. The boundary shows the message as it is; anything else is logged in full and rethrown - **New outside service, time limits and retries.** A port in `P/server/runtime/` with a stand-in, an adapter in `P/adapters//` (only it imports the SDK; HTTP goes through Effect's `HttpClient`, never `fetch`), a row in `policies.ts` (`withPolicy`), its option in `defineSpool` and its layer in `appLayer` (`runtime/app.ts`) +- **Something the CRM does for whoever asks (a new server function).** An operation in `P/server/operations/.ts` (`staff` or `open` from `define.ts`: name `area.verb`, `kind`, `summary`, zod `input`, `run`), listed in `P/server/operations/index.ts`. Its server function in `P/server/.functions.ts` only binds it: `createServerFn({ method }).validator(op.input).handler(crmHandler(op.name, op.run))`, with no program of its own. The HTTP API (`httpApi` in `P/server/http.ts`, `@swirls/spools/http`) answers every listed operation at `POST /`, and the typed client (`P/client.ts`) knows it by name, so the name and the shape of its input and answer are a public contract: changing one is a breaking change. `callAs` (`P/server/api.ts`) runs one from server code as a teammate. The server's side imports no web framework: TanStack Start is bound in `P/start.ts` (which tells the boundary how to reach a server function's request, `P/server/runtime/host.ts`) and the `*.functions.ts` files, and `packages/spools/tests/unit/framework-free.test.ts` fails for anything else. `headlessServer` (`P/headless.ts`, `@swirls/spools/headless`) is a whole Spool with no web framework: the HTTP API and every handler in `P/api` at the addresses the starter's route files give them, so a new endpoint is added to its `routes` as well as to `src/routes/api`. A caller of the HTTP API is known by the session cookie (same site only), a sign-in token (`tokens.authorizedParties`) or an API key (`P/server/api-keys.ts`, the `api_keys` table, `spools keys` in `P/cli/keys.ts`): a key acts as one teammate through `forStaff`, never as the system, and no operation makes one. Keys are taken only with `keys: true` on `httpApi`, end after `DEFAULT_DAYS` unless made with `neverExpires`, and are kept sealed by the `Vault` for their own row (`sealKey`: the hash of the secret and the row's user, read-only flag and expiry), which is what a key is judged by, so a row written by hand or changed opens nothing and a Spool with no vault has no keys: anything new a row says a key may do goes under the seal. A read-only key is refused every `write` operation, and its reads run with `ReadOnlyCaller` (`P/server/runtime/access.ts`) set: anything a read does on the side outside the database (making the file library) checks it. An operation a front end is built on says what it answers (`answer`, schemas in `P/server/operations/answers.ts`), which the OpenAPI document carries and `tests/integration/http.test.ts` holds each real answer to. An idempotent answer is sealed for its caller's access (`accessMark` in `P/server/runtime/boundary.ts`), so a repeat after their access changed is withheld. The types of an app's records for its own front end are written by `spools gen` (`P/crm/codegen-types.ts`, pure, to `src/crm.types.ts`). Clerk's adapter is `P/adapters/auth/clerk/core.ts`, given its client and session by `server.ts` (TanStack Start) or `backend.ts` (no web framework: the cookie only, never a bearer token). `create-spools --headless` builds from `packages/create-spools/overrides-headless`. Tests: `tests/integration/http.test.ts`, `tests/unit/clerk-backend.test.ts`, `tests/unit/codegen-types.test.ts`. docs/headless.md - **Calling Effect code from promise code.** `src/app/extensions.ts`: `@swirls/spools/extensions` (`P/server/extension-api.ts`). Scripts: `runServer(program)` and `disposeRuntime()` from `P/server/runtime/app.ts`. Never `await` a framework function directly: it returns an Effect, and awaiting it does nothing - **Calling promise code from Effect code.** The app's own hooks, handlers and settings: `fromHook` (`runtime/errors.ts`) diff --git a/README.md b/README.md index 08f5107..84911e8 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Your agents write a config, choose the services and add your own code. Spools ha - **Each post sent once.** Social posts go out when a teammate approves them, to LinkedIn, X, Facebook or a network you add, and never twice. - **Secrets kept on the server.** Tokens are sealed before they are stored, and the build fails if server code built on Effect reaches the browser. - **Time limits on outside calls.** Failures are typed with [Effect](https://effect.website), and calls are retried where that is safe. +- **Your own front end, when you want one.** A Spool runs headless: the same server with no interface, behind an HTTP API and a typed client that knows every field of your objects. The rules that hold in the interface hold there too. - **Modules.** A feature set (its objects, code, tables and panels) plugs into any Spool, and a clash with yours is refused, never silently won. - **More than 1,300 tests.** The server tests run on all three database adapters. @@ -38,7 +39,7 @@ bun run db:seed bun run dev ``` -Open http://localhost:3000. You need no accounts. Until you choose real services, records go in a Postgres inside the server and you are signed straight in. A production build refuses to start that way. +Open http://localhost:3000. You need no accounts. For the backend alone, behind a front end of your own, add `--headless` ([Headless](https://spools.codes/docs/headless)). Until you choose real services, records go in a Postgres inside the server and you are signed straight in. A production build refuses to start that way. Or let your coding agent do all of it. Paste this into Claude Code, Cursor or Codex: @@ -62,7 +63,7 @@ import { clerk } from '@swirls/spools/auth/clerk' import { postgres } from '@swirls/spools/database/postgres' import { resend } from '@swirls/spools/email/resend' import { drive, s3Blobs } from '@swirls/spools/files/drive' -import { aes } from '@swirls/spools/vault/aes' +import { cipherstash } from '@swirls/spools/vault/cipherstash' import crm from '../crm.config.json' with { type: 'json' } import extensions from './app/extensions' @@ -74,33 +75,34 @@ export default defineSpool({ database: postgres(), files: drive({ blobs: s3Blobs() }), email: resend(), - vault: aes(), + vault: cipherstash(), agents: swirls(), }) ``` Each page and endpoint is a small file in `src/routes`. Delete one to drop a page, or write your own. -| Import | What it is | -| --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `@swirls/spools` | `defineSpool` | -| `@swirls/spools/extensions` | For `src/app/extensions.ts`: hooks, handlers, and the record functions | -| `@swirls/spools/module`, `ui/slots` | What a [module](https://spools.codes/docs/modules) is written with | -| `@swirls/spools/auth/*`, `database/*`, `files/*`, `email/*`, `vault/*`, `agents/*`, `rate-limits/*` | The adapters that ship with it | -| `@swirls/spools/adapter` | What an adapter is written with | -| `@swirls/spools/pages/*`, `api/*`, `ui/*` | Pages, endpoints, and interface parts for your route files | +| Import | What it is | +| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `@swirls/spools` | `defineSpool` | +| `@swirls/spools/extensions` | For `src/app/extensions.ts`: hooks, handlers, and the record functions | +| `@swirls/spools/module`, `ui/slots` | What a [module](https://spools.codes/docs/modules) is written with | +| `@swirls/spools/auth/*`, `database/*`, `files/*`, `email/*`, `vault/*`, `agents/*`, `rate-limits/*` | The adapters that ship with it | +| `@swirls/spools/adapter` | What an adapter is written with | +| `@swirls/spools/pages/*`, `api/*`, `ui/*` | Pages, endpoints, and interface parts for your route files | +| `@swirls/spools/headless`, `http`, `client`, `operations` | A [headless](https://spools.codes/docs/headless) Spool: its server, the HTTP API, the typed client | ## Parts -| Part | Ships with | Without one | -| ------------ | ----------------------------------------------------------------------------------- | ------------------------------------------- | -| `auth` | Clerk, Better Auth, a development sign-in | Required | -| `database` | Any Postgres through Effect SQL, PGlite in the server, Prisma 8 (release candidate) | Required | -| `files` | Your database with a local disk or any S3 bucket, FlashDrive | The Files pages say files aren't set up | -| `email` | Resend, or your own function | Emails are logged | -| `vault` | CipherStash, AES-256-GCM | No outside tokens are stored | -| `agents` | Swirls | Workflows are skipped, the assistant is off | -| `rateLimits` | Counts in the server's memory, or in your database | Counted in memory, per instance | +| Part | Ships with | Without one | +| ------------ | ----------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| `auth` | Clerk, Better Auth, a development sign-in | Required | +| `database` | Any Postgres through Effect SQL, PGlite in the server, Prisma 8 (release candidate) | Required | +| `files` | Your database with a local disk or any S3 bucket, FlashDrive | The Files pages say files aren't set up | +| `email` | Resend, or your own function | Emails are logged | +| `vault` | CipherStash. Production needs its keys | No secrets are stored, so no connected accounts or API keys | +| `agents` | Swirls | Workflows are skipped, the assistant is off | +| `rateLimits` | Counts in the server's memory, or in your database | Counted in memory, per instance | Every database adapter runs the same integration tests. See [choosing adapters and writing your own](https://spools.codes/docs/adapters). @@ -114,16 +116,17 @@ Spools is early software (0.x). It works end to end, and minor versions may incl ### Status -| Area | State | -| ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| Config, records, views, search, tasks, notes, reports, CSV, actions, sequences | Unit and integration tested on PGlite, Postgres through Effect SQL, and Postgres through Prisma | -| Modules, record rules, role access, live updates, idempotent requests, rate limits | Unit and integration tested on the same three stores, each on a Spool of its own | -| Interface | Browser tests cover access, records, the board, search, import, tasks and the assistant | -| Swirls workflows, assistant, tool API | `swirls doctor` clean and the tool API tested; not yet run against a live project | -| Better Auth, Resend, FlashDrive, S3, the AES vault | Tested against stand-ins; not yet run against live accounts | -| Marketing: the website check, posts, ad results, and each built-in network | Tested against stand-ins; not yet run against live LinkedIn, X, Meta or Google Ads accounts | -| Clerk, CipherStash, the Swirls adapter | Only the code around the service is tested; not yet run against live accounts | -| Field encryption in the database | Not yet | +| Area | State | +| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| Config, records, views, search, tasks, notes, reports, CSV, actions, sequences | Unit and integration tested on PGlite, Postgres through Effect SQL, and Postgres through Prisma | +| Modules, record rules, role access, live updates, idempotent requests, rate limits | Unit and integration tested on the same three stores, each on a Spool of its own | +| Interface | Browser tests cover access, records, the board, search, import, tasks and the assistant | +| Swirls workflows, assistant, tool API | `swirls doctor` clean and the tool API tested; not yet run against a live project | +| Headless: the HTTP API, the typed client, API keys, the server with no interface | Unit and integration tested on the same three stores; a new headless Spool is made from the packed packages and run | +| Better Auth, Resend, FlashDrive, S3 | Tested against stand-ins; not yet run against live accounts | +| Marketing: the website check, posts, ad results, and each built-in network | Tested against stand-ins; not yet run against live LinkedIn, X, Meta or Google Ads accounts | +| Clerk, CipherStash, the Swirls adapter | Only the code around the service is tested; not yet run against live accounts | +| Field encryption in the database | Not yet | What's next is in the [roadmap](./ROADMAP.md). diff --git a/apps/docs/src/docs-manifest.json b/apps/docs/src/docs-manifest.json index bc3db8d..73794c7 100644 --- a/apps/docs/src/docs-manifest.json +++ b/apps/docs/src/docs-manifest.json @@ -20,7 +20,7 @@ "level": 2 } ], - "text": "Introduction Spools is an open source CRM framework. It gives your coding agents the sign-in, data layer, security, search, email and tests, so they only write what is specific to your business. A CRM built with it is called a Spool. A Spool is a config, your services and your own code, put together in one file: What you get Pages for your objects. Spreadsheet tables with inline editing, drag-and-drop boards, record pages with a timeline, forms, reports, and CSV import and export. Search and filters. Cmd+K finds records, notes, emails, calls, tasks, and files. Every list filters by any field, through relations, and by activity. Email. Sequences that keep their place in your database, one-off email from a teammate's own mailbox, and a timeline of the mail and meetings they have with contacts. Marketing. The tracking tags your website carries and the code for the ones it is missing, social posts that a teammate approves before they go out, and ad results. Agents and workflows. A Swirls assistant that reads and updates records, and workflows that run when a record changes or someone presses a button. Rules and roles the server keeps. Record rules (unique, locked, append-only, immutable and server-only fields) hold for every writer. A role can be denied an object or left to read it, and a branch kept to its own records. Your own code. Hooks, handlers, pages, endpoints, and services. Modules. Feature sets that plug into a Spool: objects, code, tables of their own, panels and pages. Where to start If you want to Read Build one with your agent Build with coding agents See one running Quickstart Decide whether it suits you When to use Spools Describe your business Configuration Choose sign-in, a database, and the rest Adapters Keep records right, whoever writes them Record rules Say what each role may reach Roles Add behavior of your own Extending Package a feature set, or use one Modules Let people who are not teammates in Building your own door Put it in production Deployment Move to a new version Upgrading Understand how it works Architecture Where it stands Spools is in its 0.x releases. It works end to end, and minor versions may include breaking changes, which the changelog explains. The status table says what has been tested and how, and the roadmap says what is next." + "text": "Introduction Spools is an open source CRM framework. It gives your coding agents the sign-in, data layer, security, search, email and tests, so they only write what is specific to your business. A CRM built with it is called a Spool. A Spool is a config, your services and your own code, put together in one file: What you get Pages for your objects. Spreadsheet tables with inline editing, drag-and-drop boards, record pages with a timeline, forms, reports, and CSV import and export. Search and filters. Cmd+K finds records, notes, emails, calls, tasks, and files. Every list filters by any field, through relations, and by activity. Email. Sequences that keep their place in your database, one-off email from a teammate's own mailbox, and a timeline of the mail and meetings they have with contacts. Marketing. The tracking tags your website carries and the code for the ones it is missing, social posts that a teammate approves before they go out, and ad results. Agents and workflows. A Swirls assistant that reads and updates records, and workflows that run when a record changes or someone presses a button. Rules and roles the server keeps. Record rules (unique, locked, append-only, immutable and server-only fields) hold for every writer. A role can be denied an object or left to read it, and a branch kept to its own records. Your own code. Hooks, handlers, pages, endpoints, and services. Your own front end. Run the server headless, with no interface, and build the design you want on its HTTP API and typed client. Every rule above holds there too. Modules. Feature sets that plug into a Spool: objects, code, tables of their own, panels and pages. Where to start If you want to Read Build one with your agent Build with coding agents See one running Quickstart Build your own front end on it Headless Decide whether it suits you When to use Spools Describe your business Configuration Choose sign-in, a database, and the rest Adapters Keep records right, whoever writes them Record rules Say what each role may reach Roles Add behavior of your own Extending Package a feature set, or use one Modules Let people who are not teammates in Building your own door Put it in production Deployment Move to a new version Upgrading Understand how it works Architecture Where it stands Spools is in its 0.x releases. It works end to end, and minor versions may include breaking changes, which the changelog explains. The status table says what has been tested and how, and the roadmap says what is next." }, { "path": "/docs/quickstart", @@ -63,7 +63,7 @@ "level": 2 } ], - "text": "Quickstart Make a CRM, add a field and a board, and create a task when a deal is won. You need Bun 1.4 or newer and no accounts. Make a Spool Open http://localhost:3000. You are signed in, and there are companies, contacts, and deals to look at. Records are in a Postgres inside the server, which keeps its data in.data/pglite. The development sign-in lets you straight in. A production build refuses to start with it. Look around File What it holds crm.config.json Objects, fields, views, actions, automations, and email sequences src/spool.server.ts The services your CRM runs on, and the modules it uses src/spool.ui.ts The browser halves of sign-in and of modules src/app/extensions.ts Your hooks and handlers src/routes One small file per page. Delete one to drop a page, or write your own swirls Swirls workflows and the assistant Add a field Contacts have no field for LinkedIn. Add one under objects.contacts.fields in crm.config.json: Check the config and regenerate what is made from it, then restart the server: Open a contact. The field is on the page and in the form, it can be added as a column, and Cmd+K finds people by it. Add a board Views are part of an object. Add one to objects.companies.views that groups companies by industry: Run bun run crm:gen and restart. The view menu on Companies now offers By industry, and dragging a card to another column changes the company's industry. React to a change Hooks run for every change, whoever makes it: a teammate, a CSV import, or the assistant. This one makes a task when a deal is won. Add hooks to what is already in src/app/extensions.ts: Drag a deal to Won and open Tasks. Choose real services Each service is one line in src/spool.server.ts. To keep records in your own Postgres and let people sign in with Clerk: Install what they use and set their variables in.env: The server says at startup which services are on and what the others still need. Create the tables with bun run db:push. Next Say who may sign in with access, and what each role may reach. Keep records right with record rules: unique, locked, append-only and server-only fields. Add a feature set as a module, or let people who are not teammates in through a door of your own. Read about signing in, databases, and writing an adapter. Add workflows and the assistant. Deploy it." + "text": "Quickstart Make a CRM, add a field and a board, and create a task when a deal is won. You need Bun 1.4 or newer and no accounts. Make a Spool Open http://localhost:3000. You are signed in, and there are companies, contacts, and deals to look at. Records are in a Postgres inside the server, which keeps its data in.data/pglite. The development sign-in lets you straight in. A production build refuses to start with it. This is a Spool with its interface. To start with the backend alone, for a front end of your own, run bun create @swirls/spools my-crm --headless and read Headless. The config, hooks and services on this page are the same in both. Look around File What it holds crm.config.json Objects, fields, views, actions, automations, and email sequences src/spool.server.ts The services your CRM runs on, and the modules it uses src/spool.ui.ts The browser halves of sign-in and of modules src/app/extensions.ts Your hooks and handlers src/routes One small file per page. Delete one to drop a page, or write your own swirls Swirls workflows and the assistant Add a field Contacts have no field for LinkedIn. Add one under objects.contacts.fields in crm.config.json: Check the config and regenerate what is made from it, then restart the server: Open a contact. The field is on the page and in the form, it can be added as a column, and Cmd+K finds people by it. Add a board Views are part of an object. Add one to objects.companies.views that groups companies by industry: Run bun run crm:gen and restart. The view menu on Companies now offers By industry, and dragging a card to another column changes the company's industry. React to a change Hooks run for every change, whoever makes it: a teammate, a CSV import, or the assistant. This one makes a task when a deal is won. Add hooks to what is already in src/app/extensions.ts: Drag a deal to Won and open Tasks. Choose real services Each service is one line in src/spool.server.ts. To keep records in your own Postgres and let people sign in with Clerk: Install what they use and set their variables in.env: The server says at startup which services are on and what the others still need. Create the tables with bun run db:push. In production it also needs the vault's keys ( CipherStash), which seal every secret the CRM keeps. Next Say who may sign in with access, and what each role may reach. Keep records right with record rules: unique, locked, append-only and server-only fields. Add a feature set as a module, or let people who are not teammates in through a door of your own. Read about signing in, databases, and writing an adapter. Add workflows and the assistant. Call it from a front end or a script of your own through the HTTP API. Deploy it." }, { "path": "/docs/coding-agents", @@ -96,7 +96,7 @@ "level": 2 } ], - "text": "Build with coding agents Open your Spool in Claude Code, Cursor, Codex or another coding agent and say what you need. This page covers what the agent edits and what checks its work. Start Paste this into your agent. It asks about your business, makes the Spool and builds your CRM in it: The page it reads is plain text, so you can see what your agent is told before you paste. Or make the Spool yourself: Then open the folder in your agent and ask: Build our CRM. We sell commercial insurance, and we track companies, the people at them, policies with a renewal date, and claims. Policies move from quoted to bound to renewed or lost. Email the account manager 60 days before a policy renews. Every new Spool has an AGENTS.md that tells the agent where each kind of change goes, and a CLAUDE.md that points to it. What an agent edits Most changes are a few lines in one of these places. The request Where it goes Track something, show it, or move it along crm.config.json: objects, fields, pipelines, views Never two of these, never changed once sent Record rules in crm.config.json: unique, lock, appendOnly, immutable, readonly This role must not see that, or only read it access on a role in crm.config.json Email people on a schedule campaigns in crm.config.json When something happens, do something automations in the config, or a hook in src/app/extensions.ts A page or an endpoint nobody else needs A file in src/routes An endpoint for people who are not teammates A file in src/routes/api behind publicRoute, built as your own door A feature set to use in more than one Spool A module, listed in src/spool.server.ts and src/spool.ui.ts Use a different sign-in, database, or service src/spool.server.ts The framework is a package, so your agent never edits it and you never merge it. What checks the agent's work Ask the agent to run bun run check before it is done. Each of these stops with a message that says what to change. The config. Every key it knows is checked against a schema: a column for a field that doesn't exist, a board grouped by something that isn't a select, an action that runs nothing. A key the schema doesn't know is ignored, so a misspelt one does nothing. crm.config.schema.json gives the agent the same checks as it types. Who is asking. Lint refuses a server function or an endpoint that doesn't check the session first ( handlers). The rules. A write that breaks a record rule is refused by the server whoever wrote the code. Code reaches past a role's access or a record scope only by saying so with asSystem, which is one word to look for in a review. bun run db:rules lists records that already break a unique rule before the database is given it. The modules. Two parts that define the same object, field, handler or route are refused when the server starts and by bun run crm:gen, naming both. bunx spools modules lists the route files a module still needs. Types. Records, hooks and routes are typed from the config and the route tree. The browser bundle. bun run build fails if Effect, which server code runs on, reached it. The keys. A production server refuses to start without the keys for its sign-in and database, or with the development sign-in on. Spools comes with one access check for every request, role access and record rules kept in the data layer, row-level security on every table, tokens sealed before they are stored, and a time limit on every read from an outside service. Read Architecture and Security for how. What to ask for \"Add a renewals pipeline with a board by status, and a saved view of what is due this quarter.\" \"When a deal is won, create a project from it and give its owner a task to send the welcome pack.\" \"Email new leads on day 0, day 3, and day 10. Stop when they become a customer.\" \"Import this CSV of our contacts. Keep the owner and the last contacted date.\" \"Add a page that shows stock levels from our warehouse API next to the open orders.\" \"Use Better Auth instead of Clerk, and keep files in our S3 bucket.\" \"Designers can read jobs but not change them, and never see the ledger.\" \"One open visit per person per job, and nothing changes on a closeout once it is submitted.\" Moving from another CRM Export your companies, contacts, and deals as CSV from HubSpot, Salesforce, a spreadsheet, or wherever they are now. Describe the fields you use in crm.config.json, then import each file from the list page: columns are matched to fields by key or label, and relations by the related record's title. An import is limited to 1,000 rows and does not fire automations, so split large files, or ask your agent for a script that uses createRecord." + "text": "Build with coding agents Open your Spool in Claude Code, Cursor, Codex or another coding agent and say what you need. This page covers what the agent edits and what checks its work. Start Paste this into your agent. It asks about your business, makes the Spool and builds your CRM in it: The page it reads is plain text, so you can see what your agent is told before you paste. Or make the Spool yourself: For the backend alone, with a front end you design yourself, add --headless ( Headless). Its AGENTS.md tells the agent the same things without the pages. Then open the folder in your agent and ask: Build our CRM. We sell commercial insurance, and we track companies, the people at them, policies with a renewal date, and claims. Policies move from quoted to bound to renewed or lost. Email the account manager 60 days before a policy renews. Every new Spool has an AGENTS.md that tells the agent where each kind of change goes, and a CLAUDE.md that points to it. What an agent edits Most changes are a few lines in one of these places. The request Where it goes Track something, show it, or move it along crm.config.json: objects, fields, pipelines, views Never two of these, never changed once sent Record rules in crm.config.json: unique, lock, appendOnly, immutable, readonly This role must not see that, or only read it access on a role in crm.config.json Email people on a schedule campaigns in crm.config.json When something happens, do something automations in the config, or a hook in src/app/extensions.ts A page or an endpoint nobody else needs A file in src/routes A front end of your own, or a script The HTTP API and its typed client, with src/crm.types.ts for your fields An endpoint for people who are not teammates A file in src/routes/api behind publicRoute, built as your own door A feature set to use in more than one Spool A module, listed in src/spool.server.ts and src/spool.ui.ts Use a different sign-in, database, or service src/spool.server.ts The framework is a package, so your agent never edits it and you never merge it. What checks the agent's work Ask the agent to run bun run check before it is done. Each of these stops with a message that says what to change. The config. Every key it knows is checked against a schema: a column for a field that doesn't exist, a board grouped by something that isn't a select, an action that runs nothing. A key the schema doesn't know is ignored, so a misspelt one does nothing. crm.config.schema.json gives the agent the same checks as it types. Who is asking. Lint refuses a server function or an endpoint that doesn't check the session first ( handlers). The rules. A write that breaks a record rule is refused by the server whoever wrote the code. Code reaches past a role's access or a record scope only by saying so with asSystem, which is one word to look for in a review. bun run db:rules lists records that already break a unique rule before the database is given it. The modules. Two parts that define the same object, field, handler or route are refused when the server starts and by bun run crm:gen, naming both. bunx spools modules lists the route files a module still needs. Types. Records, hooks and routes are typed from the config and the route tree. The browser bundle. bun run build fails if Effect, which server code runs on, reached it. The keys. A production server refuses to start without the keys for its sign-in and database, or with the development sign-in on. Spools comes with one access check for every request, role access and record rules kept in the data layer, row-level security on every table, tokens sealed before they are stored, and a time limit on every read from an outside service. Read Architecture and Security for how. What to ask for \"Add a renewals pipeline with a board by status, and a saved view of what is due this quarter.\" \"When a deal is won, create a project from it and give its owner a task to send the welcome pack.\" \"Email new leads on day 0, day 3, and day 10. Stop when they become a customer.\" \"Import this CSV of our contacts. Keep the owner and the last contacted date.\" \"Add a page that shows stock levels from our warehouse API next to the open orders.\" \"Use Better Auth instead of Clerk, and keep files in our S3 bucket.\" \"Designers can read jobs but not change them, and never see the ledger.\" \"One open visit per person per job, and nothing changes on a closeout once it is submitted.\" Moving from another CRM Export your companies, contacts, and deals as CSV from HubSpot, Salesforce, a spreadsheet, or wherever they are now. Describe the fields you use in crm.config.json, then import each file from the list page: columns are matched to fields by key or label, and relations by the related record's title. An import is limited to 1,000 rows and does not fire automations, so split large files, or ask your agent for a script that uses createRecord." }, { "path": "/docs/when-to-use", @@ -124,7 +124,7 @@ "level": 2 } ], - "text": "When to use Spools Spools is for teams that want a CRM shaped around their work and build software with coding agents or TypeScript. Choose Spools when You want your agents to build it. They write the part that is yours, on sign-in, data, security and email that are already built. Your objects aren't the usual ones. You track jobs, sites, policies, or placements, and you want them to be first-class records with their own pipelines. You want the data in your own database. Records are ordinary tables in your Postgres, which your other software can read. The CRM has to do something particular. Winning a deal should open a project, or a new contact should be checked against another system. Hooks and handlers are plain TypeScript in your repository. You have already chosen your services. You use a certain sign-in provider, mail provider, or cloud, and the CRM should use them too. You want agents working on records. The assistant and your Swirls workflows go through the same checks, hooks, and timeline as your team. Some records are not for everyone. A role can be denied an object or left to read it, and record scopes keep each branch to its own records. The server enforces both. The same feature goes into several CRMs. Write it once as a module: its objects, code, tables and panels, listed in each Spool that uses it. You build CRMs for clients. Each client's CRM is a small repository: a config, a file of services, and whatever is theirs alone. The framework updates as a package. Choose something else when Nobody on the team works with code or coding agents. Views, filters, and reports can be changed in the app, while objects, fields, and services are changed in files. A hosted CRM is a better fit. You need a marketplace of plugins today. Spools has extension points, modules and a handful of adapters. It does not have a catalog of third-party apps. You need a telephone dialer, quoting, or billing. None of these is built in. You need permissions per field or per action. A role is denied a whole object or reads it, and a record scope covers every record of a group. Nothing says who may see one field or press one button. With neither set up, everyone on the access list sees and changes every record. You need a ready-made portal for customers. Spools has no sign-in or pages for people who are not teammates. You can build endpoints for them from small helpers, and the checks are yours to write. You need a stable API today. Spools is in its 0.x releases, and minor versions may include breaking changes. What you need to run one Runtime Bun 1.4 or newer, in a container, on a VM, or on Vercel Database Postgres 15 or newer (tested on 17) Sign-in Clerk, or Better Auth in your own database Optional A mail provider, a place for files, a key for the vault, a Swirls project Spools is written with TanStack Start and Effect. You can configure a Spool and write hooks and pages without knowing either. You need Effect to write an adapter or to work on the framework. Compared with a template Spools began as a template you copied and merged updates into. The framework is now a package. Your repository holds your own files and a version number, so you never merge the framework." + "text": "When to use Spools Spools is for teams that want a CRM shaped around their work and build software with coding agents or TypeScript. Choose Spools when You want your agents to build it. They write the part that is yours, on sign-in, data, security and email that are already built. Your objects aren't the usual ones. You track jobs, sites, policies, or placements, and you want them to be first-class records with their own pipelines. You want the data in your own database. Records are ordinary tables in your Postgres, which your other software can read. The CRM has to do something particular. Winning a deal should open a project, or a new contact should be checked against another system. Hooks and handlers are plain TypeScript in your repository. You have already chosen your services. You use a certain sign-in provider, mail provider, or cloud, and the CRM should use them too. The front end is your own design. A Spool runs headless: the records, rules, roles and automations behind an HTTP API, with a typed client that knows your fields. Use it for a portal, a mobile app or a tool on another framework, and keep the interface Spools comes with for the back office or leave it out. You want agents working on records. The assistant and your Swirls workflows go through the same checks, hooks, and timeline as your team. Some records are not for everyone. A role can be denied an object or left to read it, and record scopes keep each branch to its own records. The server enforces both. The same feature goes into several CRMs. Write it once as a module: its objects, code, tables and panels, listed in each Spool that uses it. You build CRMs for clients. Each client's CRM is a small repository: a config, a file of services, and whatever is theirs alone. The framework updates as a package. Choose something else when Nobody on the team works with code or coding agents. Views, filters, and reports can be changed in the app, while objects, fields, and services are changed in files. A hosted CRM is a better fit. You need a marketplace of plugins today. Spools has extension points, modules and a handful of adapters. It does not have a catalog of third-party apps. You need a telephone dialer, quoting, or billing. None of these is built in. You need permissions per field or per action. A role is denied a whole object or reads it, and a record scope covers every record of a group. Nothing says who may see one field or press one button. With neither set up, everyone on the access list sees and changes every record. You need a ready-made portal for customers. Spools has no sign-in or pages for people who are not teammates. You can build endpoints for them from small helpers, and the checks are yours to write. The HTTP API is for teammates and the scripts that act as them: everyone who calls it is on the access list. You need a stable API today. Spools is in its 0.x releases, and minor versions may include breaking changes. The names of the HTTP API 's operations and the shape of what they take and answer are treated as a public contract, and a change to one is called out as breaking. What you need to run one Runtime Bun 1.4 or newer, in a container, on a VM, or on Vercel Database Postgres 15 or newer (tested on 17) Sign-in Clerk, or Better Auth in your own database Vault A CipherStash workspace, in production Optional A mail provider, a place for files, a Swirls project Spools is written with TanStack Start and Effect. A headless Spool loads neither React nor TanStack Start. You can configure a Spool and write hooks and pages without knowing either. You need Effect to write an adapter or to work on the framework. Compared with a template Spools began as a template you copied and merged updates into. The framework is now a package. Your repository holds your own files and a version number, so you never merge the framework." }, { "path": "/docs/configuration", @@ -360,7 +360,7 @@ "level": 2 } ], - "text": "Extending Most changes are config: see the configuration reference. When config isn't enough, extend in code. Server-side extensions live in one file you own, src/app/extensions.ts: The full contract, with types, is packages/spools/src/crm/extensions.ts. A feature set others could use too (its objects, its code, its own tables, panels and pages) is better written as a module: a package any Spool lists in modules, whose hooks run before yours and whose clashes with yours are refused instead of silently won. Handlers: run your own code from a button or automation ctx is { objectKey, record, actor, trigger }. Import updateRecord and friends from @swirls/spools/extensions so hooks and automations still run. The returned message is shown to the user. Return open as well ( { message, open: \"/deals/\" }) and the record page goes to that page of the CRM once the handler has run. To make one record from another (a lead into a deal), reach for conversions in the config first: a handler is for what a conversion can't say. Hooks: react to record changes Hooks run for every write, whether it comes from the CRM or the assistant. Available hooks: beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete (throw to refuse the delete: nothing is removed) and afterDelete. With modules, each module's hooks run first, in the order they are listed, and yours last. beforeUpdate and afterUpdate receive the previous record. Values returned from a before* hook are still validated against the config. A relations field arrives in values as Ids (a list, or { add, remove }), and on record and previous as , Ids and Count. A change happens in this order: The before* hook runs. Throwing here refuses the change: nothing is written, and staff see the message. The record and its lines on the timeline are written together, as one transaction. The after* hook and the config's automations run, once the change is kept. So an after* hook can read the record it is told about and change it again. If it throws, the change stays, and staff see \"Saved, but a step after it failed\" with the message, so nobody makes the change a second time. For simple \"when X changes, run Y\", prefer automations in the config. Use hooks when you need the previous value, want to change or reject the write, or need logic that doesn't belong in a workflow. Hand a record on to the next step A hook can create the records and tasks the next person needs. Import from @swirls/spools/extensions: its createRecord and updateRecord write through the service, so the new records get their own timeline, hooks and automations, and createTask makes the to-dos. (The framework's own modules return Effects, which do nothing when awaited; this file is their promise version.) A hook that updates the record it is handling runs again for that update: compare with previous (as above) so it does its work once. actor is null for scripts; a CSV import in the CRM has the teammate who ran it. Decide what a hand-off should do with no actor; bulk imports that call records.createRecord directly skip hooks. To give the new record the old one's folder, see shareRecordFolder in Files. Hooks and record scopes In a Spool with record scopes, what a hook, a handler or a run target does through @swirls/spools/extensions is done with the access of whoever caused it: listRecords in a hook lists what that person could, and createRecord makes a record in the scope they are working in. A script has nobody behind it, so a scoped record is refused until it says it is the system: asSystem reaches every scope. Use it in scripts, and in a hook only where the work really is the business's and not the person's. Three things follow from \"whoever caused it\": Nobody caused it, nothing is changed. Code that runs with nobody signed in (a script, a webhook, an endpoint of your own behind publicRoute or cronRoute) reads shared objects and changes no record at all, a shared object's included, until it says it is the system. A before hook is not called for a change that is going to be refused: not for a read-only person's, not for one that names a scope its maker can't write, and not for one nobody is behind. A workflow's write-back is about one record, and so is what it sets off. A workflow started for a record calls the tool API under a grant made for that record ( Swirls). When its update runs your afterUpdate hook or an automation's handler, that code is bound to the same record: getRecord, updateRecord, deleteRecord, addActivity, listActivities, listTasks, createTask, listNotes, createNote, recordFolder and runTarget work when they are about that record, and listRecords, countMatching, createRecord, updateTask, deleteTask and shareRecordFolder are refused, with a message that says why. asSystem lifts the one record with the scope. A change a person makes in the CRM is bound to no record. Reaching past these functions is your own. @swirls/spools/server/* exports the server's modules for code written with Effect. A program built from them and run with runServer inside a hook works with the caller's whole access, grant or not: the binding to one record is what the functions above do. Hooks and role access When the config gives a role access, the same holds for it, with or without record scopes: a hook, a handler, a run target, and your own crmHandler and apiRoute code work through @swirls/spools/extensions with the role access of the teammate they run for. An object their roles deny is not found ( getRecord, listRecords and createRecord reject with the NotFound error), and a change to one they only read is refused in words. So a hook that writes somewhere the person who caused it may not must say it is the server's work: asSystem lifts role access and record scopes together. The line on the timeline still names the actor you pass. Code nobody is signed in for (a script, a cronRoute, a publicRoute, the config's automations) holds no role, so nothing is kept from it, and access.default does not apply. Role access is checked before your hooks: a before hook is not called for a change to an object the person may only read, or not see, as it is not called for one record scopes refuse. The data layer checks it again when the record is written, for code that writes there directly. The same holds for a run target (an action), an email to a record and an enrolment in a sequence: none starts for someone who may only read the record. addActivity from @swirls/spools/extensions is a change to the record: refused, for the teammate your code runs for, on a record of an object they may only read, and not found on one they are kept from. So are createTask, updateTask, deleteTask and createNote, recordFolder for a record that has no folder yet (it would make one), and shareRecordFolder, which changes both records' folders. Wrap the server's own bookkeeping in asSystem. A hook is handed the record it is about. Don't send that on to someone it is kept from. Kept fields: values the server keeps for itself A count of open visits on a job, the time a notice last went out: values no person writes, which your code keeps up to date. Mark the field readonly in the config and write it with writeKeptFields from @swirls/spools/extensions: It writes no timeline line and runs no hook or automation, as the server (role access and record scopes don't refuse it). That is safe because it writes only readonly fields, which no person writes, so no person's change goes untold; any other field is refused. The record's rules still hold (values are checked; unique, lock and appendOnly apply: add a kept field to a lock's except to keep it counting on a locked record), the record is held for the write, and when makes it a compare-and-set. It returns the record, or null when the record is gone or when no longer holds. Scopes: who holds what When your sign-in provider doesn't say which scopes a person holds, say it yourself: Its answer for a person is kept for a minute, so a change takes that long to show. Returning nothing for a person shows them no scoped record. A resolver here wins over the sign-in provider's. A scope grants returns counts only when it is one of this Spool's: an option of a scoped object's scope field where that field is a select, and for a scope field kept as text or as a relation, one that list names. So list is not only for the switcher. Where a scope field is text or a relation, a resolver without list gives nobody a scope, and the server says so when it starts. list is also what a record's scope is checked against when it is saved: a scope it doesn't name is refused. A grant whose role is marked all is head office's and is not a scope's: it counts as you return it. A run target, a handler or an automation runs for whoever may change the record it is run for. Someone who only reads the record starts none of them. Run targets: add a new kind A run target kind handles every \":\" in the config. validate is optional. When present, bun run crm:gen and server start-up use it to reject targets that can't resolve, so a typo fails early. Email: use a different provider Campaign email goes through the Spool's email adapter. To send it some other way without writing an adapter, replace the transport: Keep the headers: they carry the one-click unsubscribe. Marketing: add a social or ad network Add a network under marketing and a channel or an ad account in crm.config.json can name it. posts networks say how long a post may be and how to send one; ads networks say how to read an account's campaigns. The full example is in Marketing. Integrations: let teammates connect another service Add an OAuth provider under integrations and it appears on the Integrations page. The framework runs the connect flow and keeps the tokens encrypted; your handlers find a connection with findConnections and ask for a current token with getAccessToken. The full example is in Integrations. A connection belongs to the teammate who connected it. Add shared: 'team' for an account the whole business uses (one accounting system), or shared: 'group' with groups for one per branch or region, and canManage to say who may connect and disconnect it. See Share a provider with the team. Files: choose where a record's folder goes An object with files in the config gives each record a folder in the drive, at /, or inside a related record's folder with under. Return another path from files.location to lay the drive out your way. It is asked once per record, when its folder is made. See Files. Add a field type A field type is part of the framework, so this is a change to packages/spools: two files, and the compiler lists what's missing. In packages/spools/src/crm/field-types.ts, add the config shape to fieldSchema and an entry to fieldTypes: In packages/spools/src/crm/ui/fields.tsx, add rating to fieldDisplay and fieldInput. Then run bun run crm:gen, and document the type in docs/configuration.md. Add a view type Add the config shape to viewSchema in packages/spools/src/crm/config-schema.ts. Add a component to viewComponents in packages/spools/src/crm/ui/views.tsx. Its props are ViewProps in the same file. Teach sanitise in packages/spools/src/server/views.ts which settings the new type keeps. Pages Each page is a small file in src/routes that mounts one of the framework's: Delete the file and the page is gone. Keep its data and change how it looks: Pages and endpoints of your own A page is a route file. Inside src/routes/_crm it gets the CRM's shell, and only signed-in teammates can open it. The framework's parts are in @swirls/spools/ui/* ( kit for buttons and dialogs, shell for the top bar, workspace, views). Its data comes from a server function, whose handler is one from @swirls/spools/handlers: An endpoint is the same with apiRoute: Handler Who it answers crmHandler A server function, for signed-in teammates on the access list apiRoute An endpoint, for the same people. Anyone else gets 401 cronRoute A scheduled job with CRON_SECRET. Anyone else gets 401 publicHandler A server function that answers anyone. Nothing staff-only belongs here publicRoute An endpoint that answers anyone, such as a webhook. Check its signature before anything else apiRoute also runs a write sent with an Idempotency-Key once with { idempotency: {} } ( Idempotent requests). For people who are not teammates, build your own door behind publicRoute ( Building your own door). Each checks who is asking before your code runs, hands it the person, stops when the browser goes away, and shows the page the message of an error you throw. A new Spool's bun run lint refuses a server function or endpoint that goes without one. Building your own door Spools has no built-in door for people who are not teammates (installation crews, clients, vendors). Your app builds its own endpoints for them behind publicRoute, from small pieces in @swirls/spools/extensions, and decides itself who may do what. Nothing a teammate's request gets (role access, record scopes, the access list) applies to such an endpoint: inside it your code runs with nobody said, so everything it may reach, and everything it hands back, is yours to check. Do the checks in this order, each before anything costs more: Origins. Answer browsers only from your front end's origins (CORS is yours), and name those origins for the token check below. The caller's address, limited before anything else is looked at: callerAddress(headers) reads X-Forwarded-For as far as TRUST_PROXY (1 to 10 proxies) says, and is null when the address can't be known ( TRUST_PROXY unset or mistyped). Never count a limit under null or any one shared value: it would be one counter for every caller. Skip the address limit and say so in production (and limit at the platform in front, a WAF or the host's firewall), or refuse. peekLimit(bucket, key, limit) says how long a key must wait without counting a hit, so an over-limit address is refused before any work. The token. bearerToken(headers), then verifyToken(token, { authorizedParties }): the user id it was issued to, by the auth adapter's own check (with clerk(), locally against keys it holds, and offline with CLERK_JWT_KEY), or null. Name your front end's origins: with none, only a developer's or a test's server takes any token, so a teammate's token from the CRM itself never opens your door. devAuth({ outsiders: [{ id, name, email, token }] }) hands out tokens in development. A limit per user: hitLimit(bucket, userId, { max, windowMs }), peekLimit to look without counting, and consumeLimit for a quota counted in amounts (uploads, megabytes). Your buckets are counted apart from the framework's (as app:). Who they are in your records: a record of an object of yours whose field holds their user id, read with asSystem. Make that field readonly (written only by your code, with writeKeptFields), so no teammate's form, import or the assistant can point a record at someone else. An explicit field allowlist, both ways: write only the fields you name, and answer only the fields you name. Never hand a record back as listRecords gives it. Ownership: every record id the caller sends (in the path or the body, a relation's included) must be one they may reach by your rules. Answer one that isn't exactly as one that doesn't exist. Idempotency for writes an offline front end retries: idempotent(request, { caller: verifiedCaller('crew', userId) }, work). idempotent takes only a caller verifiedCaller made from ids you have verified, never anything the request says. Other pieces your door may want: changedSinceAs(keys, token, mayRead) tells a live front end what changed among the keys your own check lets the caller know of; sealText / openText keep a secret of theirs sealed for its record ( Adapters); file uploads go through the generic startUpload / finishUpload of @swirls/spools/server/files with the declared content type ( Files). Idempotent requests A write (anything but GET and HEAD) sent with an Idempotency-Key header (8 to 128 letters, digits, - or _) runs once per caller, endpoint and key, with idempotent(request, { caller, keepFor?, bodyLimit? }, work) in your own endpoint, or apiRoute(name, answer, { idempotency: {} }) for teammates (whose caller is their user id). The endpoint is the method, path and query ( ?draft=1 and ?draft=0 are two requests). work is handed a request that carries the body again, and the body as text; the body is read first, up to bodyLimit bytes (1 MB unless it says; larger is 413 too_large). The caller is made with verifiedCaller(namespace,...verifiedIds) from identities you have verified (a user id from verifyToken, a record of yours found for it), never anything the request says of itself, or one caller could replay another's answers. It refuses an empty part, or one holding: or a space, and its type ( VerifiedCaller) is the only one idempotent takes; a string shaped otherwise is refused at runtime too. Your callers are kept apart from the framework's ( app:; teammates are staff:). A key changes nothing about what your code reaches: it runs exactly as it would without one. The first answer below 500 is kept and given again to every repeat, with Idempotent-Replayed: true: same status, and, when the Spool has a vault, the same body and type. With a vault, every answer that isn't a stream is kept, however busy the server is: one built in memory ( Response.json, a string, bytes, a blob) or one that declares its Content-Length, read whole up to 256 KB with no clock to lose to. Not kept: a body larger than 256 KB, an event stream ( text/event-stream), one sent Transfer-Encoding: chunked, and a body your code makes as it goes (a ReadableStream) that declares no length. Give such a body a Content-Length to have it kept. Without a vault no answer's body is kept, nor one of those: a repeat is the first answer's status with Idempotent-Body: withheld, Content-Type: application/json and the body { \"replayed\": true, \"body\": \"withheld\" } (none for 204, 205 and 304), and Idempotent-Body-SHA256 (the hex SHA-256 of the body it had) when it was read whole. An answer is never kept in the clear. What a front end does with one: take the status as the outcome of its write (it was made, once), and read what it needs back; never parse the withheld body as the first answer. Once your code has answered, nothing fails the request: keeping the answer is tried again if the database stumbles, and an answer that can't be kept is logged and still sent. Only if the database refuses every try is the key left to go stale, when a repeat would run again. The same key with another body is 409 key_reused. A copy that arrives while the first is still running is 409 in_progress with Retry-After: 2, on this server or any other. A request that fails (500 or worse, a throw, the caller going away) lets its key go, so a retry runs. A running request renews its claim every ten seconds, however long it takes; a claim left by a server that stopped counts as gone a minute after it was last renewed. Only the request holding a claim renews it, answers it or lets it go. Answers are kept a week ( keepFor), sealed by the vault for their own row and caller, so one moved to another row opens for nobody. Expired answers are swept as the caller sends more. The claim is an insert into idempotent_requests, whose unique index lets one copy in, and taking over a stale claim is one conditional update. So it holds across servers on Postgres and on PGlite, and nothing is read and then written. Rate limits hitLimit(bucket, key, { max, windowMs }) counts one for key when it is under the limit, in a sliding window, and answers { allowed: true } or { allowed: false, retryAfter } (seconds). peekLimit(bucket, key, { max, windowMs }) says how many seconds key must wait (0: now) and counts nothing. consumeLimit(bucket, key, amount, { max, windowMs }) is a quota counted in amounts in a fixed window (a day from midnight UTC, a minute on the minute), taken whole or not at all. All three count on the Spool's RateLimiter: in this server's memory unless defineSpool says rateLimits: storeRateLimits(), which counts in the database, the same on every instance ( Adapters). A bucket or key is 1 to 200 characters, and an amount, max or windowMs that isn't a whole number above 0 is refused. Theme the CRM The CRM's colours are CSS variables on.crm, defined in packages/spools/src/crm/ui/theme.css. Override them in your own src/styles.css, after the theme import, instead of editing the theme file: The CRM follows the system light or dark setting until someone uses the toggle in the sidebar. Give the assistant a new capability Add a tool to tools in packages/spools/src/server/tools.ts with a Zod input schema. Add a tool workflow to swirls/assistant.swirls that posts to /api/swirls/tools/, and list it in the agent's tools. Run swirls doctor, then swirls deploy." + "text": "Extending Most changes are config: see the configuration reference. When config isn't enough, extend in code. Server-side extensions live in one file you own, src/app/extensions.ts: The full contract, with types, is packages/spools/src/crm/extensions.ts. A feature set others could use too (its objects, its code, its own tables, panels and pages) is better written as a module: a package any Spool lists in modules, whose hooks run before yours and whose clashes with yours are refused instead of silently won. Handlers: run your own code from a button or automation ctx is { objectKey, record, actor, trigger }. Import updateRecord and friends from @swirls/spools/extensions so hooks and automations still run. The returned message is shown to the user. Return open as well ( { message, open: \"/deals/\" }) and the record page goes to that page of the CRM once the handler has run. To make one record from another (a lead into a deal), reach for conversions in the config first: a handler is for what a conversion can't say. Hooks: react to record changes Hooks run for every write, whether it comes from the CRM or the assistant. Available hooks: beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete (throw to refuse the delete: nothing is removed) and afterDelete. With modules, each module's hooks run first, in the order they are listed, and yours last. beforeUpdate and afterUpdate receive the previous record. Values returned from a before* hook are still validated against the config. A relations field arrives in values as Ids (a list, or { add, remove }), and on record and previous as , Ids and Count. A change happens in this order: The before* hook runs. Throwing here refuses the change: nothing is written, and staff see the message. The record and its lines on the timeline are written together, as one transaction. The after* hook and the config's automations run, once the change is kept. So an after* hook can read the record it is told about and change it again. If it throws, the change stays, and staff see \"Saved, but a step after it failed\" with the message, so nobody makes the change a second time. For simple \"when X changes, run Y\", prefer automations in the config. Use hooks when you need the previous value, want to change or reject the write, or need logic that doesn't belong in a workflow. Hand a record on to the next step A hook can create the records and tasks the next person needs. Import from @swirls/spools/extensions: its createRecord and updateRecord write through the service, so the new records get their own timeline, hooks and automations, and createTask makes the to-dos. (The framework's own modules return Effects, which do nothing when awaited; this file is their promise version.) A hook that updates the record it is handling runs again for that update: compare with previous (as above) so it does its work once. actor is null for scripts; a CSV import in the CRM has the teammate who ran it. Decide what a hand-off should do with no actor; bulk imports that call records.createRecord directly skip hooks. To give the new record the old one's folder, see shareRecordFolder in Files. Hooks and record scopes In a Spool with record scopes, what a hook, a handler or a run target does through @swirls/spools/extensions is done with the access of whoever caused it: listRecords in a hook lists what that person could, and createRecord makes a record in the scope they are working in. A script has nobody behind it, so a scoped record is refused until it says it is the system: asSystem reaches every scope. Use it in scripts, and in a hook only where the work really is the business's and not the person's. Three things follow from \"whoever caused it\": Nobody caused it, nothing is changed. Code that runs with nobody signed in (a script, a webhook, an endpoint of your own behind publicRoute or cronRoute) reads shared objects and changes no record at all, a shared object's included, until it says it is the system. A before hook is not called for a change that is going to be refused: not for a read-only person's, not for one that names a scope its maker can't write, and not for one nobody is behind. A workflow's write-back is about one record, and so is what it sets off. A workflow started for a record calls the tool API under a grant made for that record ( Swirls). When its update runs your afterUpdate hook or an automation's handler, that code is bound to the same record: getRecord, updateRecord, deleteRecord, addActivity, listActivities, listTasks, createTask, listNotes, createNote, recordFolder and runTarget work when they are about that record, and listRecords, countMatching, createRecord, updateTask, deleteTask and shareRecordFolder are refused, with a message that says why. asSystem lifts the one record with the scope. A change a person makes in the CRM is bound to no record. Reaching past these functions is your own. @swirls/spools/server/* exports the server's modules for code written with Effect. A program built from them and run with runServer inside a hook works with the caller's whole access, grant or not: the binding to one record is what the functions above do. Hooks and role access When the config gives a role access, the same holds for it, with or without record scopes: a hook, a handler, a run target, and your own crmHandler and apiRoute code work through @swirls/spools/extensions with the role access of the teammate they run for. An object their roles deny is not found ( getRecord, listRecords and createRecord reject with the NotFound error), and a change to one they only read is refused in words. So a hook that writes somewhere the person who caused it may not must say it is the server's work: asSystem lifts role access and record scopes together. The line on the timeline still names the actor you pass. Code nobody is signed in for (a script, a cronRoute, a publicRoute, the config's automations) holds no role, so nothing is kept from it, and access.default does not apply. Role access is checked before your hooks: a before hook is not called for a change to an object the person may only read, or not see, as it is not called for one record scopes refuse. The data layer checks it again when the record is written, for code that writes there directly. The same holds for a run target (an action), an email to a record and an enrolment in a sequence: none starts for someone who may only read the record. addActivity from @swirls/spools/extensions is a change to the record: refused, for the teammate your code runs for, on a record of an object they may only read, and not found on one they are kept from. So are createTask, updateTask, deleteTask and createNote, recordFolder for a record that has no folder yet (it would make one), and shareRecordFolder, which changes both records' folders. Wrap the server's own bookkeeping in asSystem. A hook is handed the record it is about. Don't send that on to someone it is kept from. Kept fields: values the server keeps for itself A count of open visits on a job, the time a notice last went out: values no person writes, which your code keeps up to date. Mark the field readonly in the config and write it with writeKeptFields from @swirls/spools/extensions: It writes no timeline line and runs no hook or automation, as the server (role access and record scopes don't refuse it). That is safe because it writes only readonly fields, which no person writes, so no person's change goes untold; any other field is refused. The record's rules still hold (values are checked; unique, lock and appendOnly apply: add a kept field to a lock's except to keep it counting on a locked record), the record is held for the write, and when makes it a compare-and-set. It returns the record, or null when the record is gone or when no longer holds. Scopes: who holds what When your sign-in provider doesn't say which scopes a person holds, say it yourself: Its answer for a person is kept for a minute, so a change takes that long to show. Returning nothing for a person shows them no scoped record. A resolver here wins over the sign-in provider's. A scope grants returns counts only when it is one of this Spool's: an option of a scoped object's scope field where that field is a select, and for a scope field kept as text or as a relation, one that list names. So list is not only for the switcher. Where a scope field is text or a relation, a resolver without list gives nobody a scope, and the server says so when it starts. list is also what a record's scope is checked against when it is saved: a scope it doesn't name is refused. A grant whose role is marked all is head office's and is not a scope's: it counts as you return it. A run target, a handler or an automation runs for whoever may change the record it is run for. Someone who only reads the record starts none of them. Run targets: add a new kind A run target kind handles every \":\" in the config. validate is optional. When present, bun run crm:gen and server start-up use it to reject targets that can't resolve, so a typo fails early. Email: use a different provider Campaign email goes through the Spool's email adapter. To send it some other way without writing an adapter, replace the transport: Keep the headers: they carry the one-click unsubscribe. Marketing: add a social or ad network Add a network under marketing and a channel or an ad account in crm.config.json can name it. posts networks say how long a post may be and how to send one; ads networks say how to read an account's campaigns. The full example is in Marketing. Integrations: let teammates connect another service Add an OAuth provider under integrations and it appears on the Integrations page. The framework runs the connect flow and keeps the tokens encrypted; your handlers find a connection with findConnections and ask for a current token with getAccessToken. The full example is in Integrations. A connection belongs to the teammate who connected it. Add shared: 'team' for an account the whole business uses (one accounting system), or shared: 'group' with groups for one per branch or region, and canManage to say who may connect and disconnect it. See Share a provider with the team. Files: choose where a record's folder goes An object with files in the config gives each record a folder in the drive, at /, or inside a related record's folder with under. Return another path from files.location to lay the drive out your way. It is asked once per record, when its folder is made. See Files. Add a field type A field type is part of the framework, so this is a change to packages/spools: two files, and the compiler lists what's missing. In packages/spools/src/crm/field-types.ts, add the config shape to fieldSchema and an entry to fieldTypes: In packages/spools/src/crm/ui/fields.tsx, add rating to fieldDisplay and fieldInput. Then run bun run crm:gen, and document the type in docs/configuration.md. Add a view type Add the config shape to viewSchema in packages/spools/src/crm/config-schema.ts. Add a component to viewComponents in packages/spools/src/crm/ui/views.tsx. Its props are ViewProps in the same file. Teach sanitise in packages/spools/src/server/views.ts which settings the new type keeps. Pages Each page is a small file in src/routes that mounts one of the framework's: Delete the file and the page is gone. Keep its data and change how it looks: Pages and endpoints of your own This section is about a Spool with its interface. In a headless Spool there are no route files: a page is your front end's, and an endpoint of your own is a branch in src/server.ts before the Spool is asked. A page is a route file. Inside src/routes/_crm it gets the CRM's shell, and only signed-in teammates can open it. The framework's parts are in @swirls/spools/ui/* ( kit for buttons and dialogs, shell for the top bar, workspace, views). Its data comes from a server function, whose handler is one from @swirls/spools/handlers: An endpoint is the same with apiRoute: Handler Who it answers crmHandler A server function, for signed-in teammates on the access list apiRoute An endpoint, for the same people. Anyone else gets 401 cronRoute A scheduled job with CRON_SECRET. Anyone else gets 401 publicHandler A server function that answers anyone. Nothing staff-only belongs here publicRoute An endpoint that answers anyone, such as a webhook. Check its signature before anything else apiRoute also runs a write sent with an Idempotency-Key once with { idempotency: {} } ( Idempotent requests). For people who are not teammates, build your own door behind publicRoute ( Building your own door). Each checks who is asking before your code runs, hands it the person, stops when the browser goes away, and shows the page the message of an error you throw. A new Spool's bun run lint refuses a server function or endpoint that goes without one. Building your own door A front end or a script that acts as a teammate needs none of this: it calls the HTTP API, which checks the access list, roles and scopes for it. This section is for callers who are not teammates. Spools has no built-in door for people who are not teammates (installation crews, clients, vendors). Your app builds its own endpoints for them behind publicRoute, from small pieces in @swirls/spools/extensions, and decides itself who may do what. Nothing a teammate's request gets (role access, record scopes, the access list) applies to such an endpoint: inside it your code runs with nobody said, so everything it may reach, and everything it hands back, is yours to check. Do the checks in this order, each before anything costs more: Origins. Answer browsers only from your front end's origins (CORS is yours), and name those origins for the token check below. The caller's address, limited before anything else is looked at: callerAddress(headers) reads X-Forwarded-For as far as TRUST_PROXY (1 to 10 proxies) says, and is null when the address can't be known ( TRUST_PROXY unset or mistyped). Never count a limit under null or any one shared value: it would be one counter for every caller. Skip the address limit and say so in production (and limit at the platform in front, a WAF or the host's firewall), or refuse. peekLimit(bucket, key, limit) says how long a key must wait without counting a hit, so an over-limit address is refused before any work. The token. bearerToken(headers), then verifyToken(token, { authorizedParties }): the user id it was issued to, by the auth adapter's own check (with clerk(), locally against keys it holds, and offline with CLERK_JWT_KEY), or null. Name your front end's origins: with none, only a developer's or a test's server takes any token, so a teammate's token from the CRM itself never opens your door. devAuth({ outsiders: [{ id, name, email, token }] }) hands out tokens in development. A limit per user: hitLimit(bucket, userId, { max, windowMs }), peekLimit to look without counting, and consumeLimit for a quota counted in amounts (uploads, megabytes). Your buckets are counted apart from the framework's (as app:). Who they are in your records: a record of an object of yours whose field holds their user id, read with asSystem. Make that field readonly (written only by your code, with writeKeptFields), so no teammate's form, import or the assistant can point a record at someone else. An explicit field allowlist, both ways: write only the fields you name, and answer only the fields you name. Never hand a record back as listRecords gives it. Ownership: every record id the caller sends (in the path or the body, a relation's included) must be one they may reach by your rules. Answer one that isn't exactly as one that doesn't exist. Idempotency for writes an offline front end retries: idempotent(request, { caller: verifiedCaller('crew', userId) }, work). idempotent takes only a caller verifiedCaller made from ids you have verified, never anything the request says. Other pieces your door may want: changedSinceAs(keys, token, mayRead) tells a live front end what changed among the keys your own check lets the caller know of; sealText / openText keep a secret of theirs sealed for its record ( Adapters); file uploads go through the generic startUpload / finishUpload of @swirls/spools/server/files with the declared content type ( Files). Idempotent requests A write (anything but GET and HEAD) sent with an Idempotency-Key header (8 to 128 letters, digits, - or _) runs once per caller, endpoint and key, with idempotent(request, { caller, keepFor?, bodyLimit? }, work) in your own endpoint, or apiRoute(name, answer, { idempotency: {} }) for teammates (whose caller is their user id). The endpoint is the method, path and query ( ?draft=1 and ?draft=0 are two requests). work is handed a request that carries the body again, and the body as text; the body is read first, up to bodyLimit bytes (1 MB unless it says; larger is 413 too_large). The caller is made with verifiedCaller(namespace,...verifiedIds) from identities you have verified (a user id from verifyToken, a record of yours found for it), never anything the request says of itself, or one caller could replay another's answers. It refuses an empty part, or one holding: or a space, and its type ( VerifiedCaller) is the only one idempotent takes; a string shaped otherwise is refused at runtime too. Your callers are kept apart from the framework's ( app:; teammates are staff:). A key changes nothing about what your code reaches: it runs exactly as it would without one. The first answer below 500 is kept and given again to every repeat, with Idempotent-Replayed: true: same status, and, when the Spool has a vault, the same body and type. With a vault, every answer that isn't a stream is kept, however busy the server is: one built in memory ( Response.json, a string, bytes, a blob) or one that declares its Content-Length, read whole up to 256 KB with no clock to lose to. Not kept: a body larger than 256 KB, an event stream ( text/event-stream), one sent Transfer-Encoding: chunked, and a body your code makes as it goes (a ReadableStream) that declares no length. Give such a body a Content-Length to have it kept. Without a vault no answer's body is kept, nor one of those: a repeat is the first answer's status with Idempotent-Body: withheld, Content-Type: application/json and the body { \"replayed\": true, \"body\": \"withheld\" } (none for 204, 205 and 304), and Idempotent-Body-SHA256 (the hex SHA-256 of the body it had) when it was read whole. An answer is never kept in the clear. What a front end does with one: take the status as the outcome of its write (it was made, once), and read what it needs back; never parse the withheld body as the first answer. An answer is kept for the caller as they were: their record scopes and what their roles keep from them. A repeat by someone whose access has changed since gets the withheld answer too, because what the first answer showed may no longer be theirs to see. Once your code has answered, nothing fails the request: keeping the answer is tried again if the database stumbles, and an answer that can't be kept is logged and still sent. Only if the database refuses every try is the key left to go stale, when a repeat would run again. The same key with another body is 409 key_reused. A copy that arrives while the first is still running is 409 in_progress with Retry-After: 2, on this server or any other. A request that fails (500 or worse, a throw, the caller going away) lets its key go, so a retry runs. A running request renews its claim every ten seconds, however long it takes; a claim left by a server that stopped counts as gone a minute after it was last renewed. Only the request holding a claim renews it, answers it or lets it go. Answers are kept a week ( keepFor), sealed by the vault for their own row and caller, so one moved to another row opens for nobody. Expired answers are swept as the caller sends more. The claim is an insert into idempotent_requests, whose unique index lets one copy in, and taking over a stale claim is one conditional update. So it holds across servers on Postgres and on PGlite, and nothing is read and then written. Rate limits hitLimit(bucket, key, { max, windowMs }) counts one for key when it is under the limit, in a sliding window, and answers { allowed: true } or { allowed: false, retryAfter } (seconds). peekLimit(bucket, key, { max, windowMs }) says how many seconds key must wait (0: now) and counts nothing. consumeLimit(bucket, key, amount, { max, windowMs }) is a quota counted in amounts in a fixed window (a day from midnight UTC, a minute on the minute), taken whole or not at all. All three count on the Spool's RateLimiter: in this server's memory unless defineSpool says rateLimits: storeRateLimits(), which counts in the database, the same on every instance ( Adapters). A bucket or key is 1 to 200 characters, and an amount, max or windowMs that isn't a whole number above 0 is refused. Theme the CRM The CRM's colours are CSS variables on.crm, defined in packages/spools/src/crm/ui/theme.css. Override them in your own src/styles.css, after the theme import, instead of editing the theme file: The CRM follows the system light or dark setting until someone uses the toggle in the sidebar. Give the assistant a new capability Add a tool to tools in packages/spools/src/server/tools.ts with a Zod input schema. Add a tool workflow to swirls/assistant.swirls that posts to /api/swirls/tools/, and list it in the agent's tools. Run swirls doctor, then swirls deploy." }, { "path": "/docs/modules", @@ -420,6 +420,74 @@ ], "text": "Modules A module is a feature set that plugs into a Spool: a package, or a folder of your own, written only with the framework's public APIs. Time tracking, field visits, approvals: each can be a module that any Spool lists, instead of code one app keeps to itself. The framework never learns a module's nouns. A module can bring: Part What it is Config Objects of its own (with fields, views, actions), fields and actions on objects others define, roles, guides, automations Server code Hooks, handlers, run-target kinds, integrations, marketing networks, an email transport, a role or scope source Private tables Tables that are not CRM objects: no page, no search, not reachable by the assistant Settings modules. in crm.config.json, checked with the module's own schema Browser half Panels on record pages and Home, and links in the sidebar Pages and endpoints Route options and handlers the app mounts with a small route file each, as it does the framework's The example used on this page is examples/modules/approvals: records of an object the app chooses are sent for approval, and someone approves or rejects each request. Use a module List its server half in src/spool.server.ts, in the order you want its hooks to run: Give it its settings in crm.config.json, under its name: List its browser half in src/spool.ui.ts, in the same order, and make sure your src/routes/__root.tsx puts SpoolUiProvider around the document. A new Spool's does; one made before modules adds it ( Upgrading): Then: spools modules exits 1 until every page and endpoint the modules have is mounted, and prints each missing file. For the example: How the parts are put together defineSpool puts the modules and the app together when the server starts, and spools gen does the same, so the schema and the server always agree. Order. Modules are taken in the order modules lists them, then the app. A module's objects come after the app's in the sidebar; its automations run before the app's. Nothing is defined twice. Two contributors may not define the same object, field of one object, action of one object, role, guide, handler, run-target kind, integration, marketing network, table or route. The Spool refuses to start, and spools gen refuses to write, with a message that names both: A module may not replace a built-in run-target kind ( swirls, campaign, local). The email transport, the role source, the scope source, files.location and marketing.canManage are one contributor's each. The app wins only where it says so. When the app defines what a module defines, the app's is used only if overrides in defineSpool names it. Anything else is refused: Path The app's replaces objects. The module's object: the app's keys over the module's, fields by key objects..fields. A field a module adds to the app's object: the module's is left out objects..sections.
A section a module adds to the app's object: the module's is left out roles., guides. The module's role or guide handlers., runTargets., integrations. The module's code of that name marketing.posts., marketing.ads. The module's network email, roles, scopes, files.location, marketing.canManage The module's The compiler knows which paths a module's fixed config gives, and refuses one it doesn't. A path that names nothing is refused when the Spool is defined, so a typo can't hide a clash. Two modules that define the same thing can't be reconciled by the app: one of them has to go. The whole is checked. The config with every module's part in it is checked against the contract, as crm.config.json alone was: a module's relation may point at the app's object, and the app's role may hide a module's object. Record rules, role access and live updates come along. A module's objects carry unique, lock, appendOnly and signals, its fields (its own, and those it adds to others' objects) immutable, readonly, audit and untrusted, and its roles access ( Record rules, Roles). It may add uniqueness rules to an object it doesn't own, over its fields or the object's own, with extend..unique: a rule of a name another contributor's rule on that object has is refused, naming both ( objects..unique.). assistant: { deny: [...] } adds objects to those the tool API never reaches, beside the app's. spools rules checks the composed config's rules, and spools modules lists what each module adds of them. Record page sections come along too. A module's own objects carry their sections, and a module adds sections to an object it doesn't own with extend..sections, after the object's own, in the order the modules are listed. A section may name any contributor's fields of the object, and is checked on the composed config: a field in two sections, whoever added them, is refused. A section key another contributor uses on that object is refused, naming both ( objects..sections.); the app keeps its own by naming that path in overrides. A role's record entry, the app's or a module's, may name any of them. Hooks compose Every contributor's hooks run, modules in the order listed, then the app's. beforeCreate, beforeUpdate, beforeDelete run one after the other. Each before* value hook is handed the values the one before it returned. A hook that throws refuses the change: nothing is written or removed, the hooks after it don't run, and staff see its message. afterCreate, afterUpdate, afterDelete all run, even when one before them throws. The change stays either way. If any threw, the first failure is reported as it would be with one hook (\"Saved, but a step after it failed\"), and the config's automations don't run. The rules for record scopes and for work bound to one record are the same for a module's hooks as for the app's ( Hooks and record scopes): they run with the access of whoever caused the change, role access included, and reach further only through asSystem. Write a module A module has a server half and, if it shows anything, a browser half. Keep them in separate files: the server half must never reach the browser bundle, and the browser half never the server's code. Name the server half *.server.ts: TanStack Start refuses to let browser code import a file named so, which keeps it out of the browser bundle even by mistake. The app imports it only from src/spool.server.ts. Server functions go in a *.functions.ts file that exports nothing else, as the framework's do: the browser half imports them, and the compiler keeps their bodies on the server. The server half extensions is the same contract as src/app/extensions.ts ( Extending), and the module's code calls the framework through @swirls/spools/extensions, as the app's does. Handler names and run-target kinds are shared by every contributor, so name them after the module ( approvalsApprove). Settings They are checked when the Spool is defined, and spools gen puts their JSON Schema under modules.approvals in crm.config.schema.json, so an editor checks them too. Server code reads them with settings.read(), typed by the schema. Settings stay on the server: the browser's copy of the config doesn't have them. Private tables It is kept as approvals_decisions (model ApprovalsDecision): the module's name comes first, so two modules can't collide, and a clash with any other table is refused. It is described as the system tables are ( Database), goes into the schema with them, and is made by PGlite as the server starts. It is not a CRM object: no page, no hooks or automations, no search, and the assistant's tools can't reach it. The module reads and writes it with moduleTables, which go through the store, so they work on every database with no SQL: find, first, count, insert, update and remove take only a module's table, and only while the Spool uses that module. A private table has no record scope: in a Spool with record scopes it is shared, as an adapter's tables are. Under a grant made for one record it is reachable, as a connection's token is: it holds no record. Record rules, role access and change signals are about CRM records, and a private table holds none: no unique rule, lock or audit of the config reaches it (give it a unique of its own, as a system table has), no role's access narrows it, and writing to it touches no change mark. Its own unique index refuses a row as the database does, not as a Conflict. The browser half Slot Where The component gets sidebar After the built-in pages, or where ui.nav puts it (a link: label, to, icon) home On Home, after the counts config record On a record's page, under its details, for the objects named in objects or that when accepts (every object without either) objectKey, record, config A sidebar link or a Home panel that names an object is left out for someone whose roles all hide that object or whose role access denies it, and for everyone when the Spool has no such object (the module's server half isn't in src/spool.server.ts). A record's panels go with the record's page: a role that only hides the object from its sidebar still opens the record and sees them, and a role denied the object finds no page. Leaving an entry out is tidiness, not the rule: the module's server functions read through @swirls/spools/extensions, where role access and record scopes are enforced. The app can add entries of its own beside its modules': defineSpoolUi({ modules: [...], home: [...] }). A panel that throws shows a line saying so instead of breaking the page. Panels get their data from the module's own server functions, written as the app's are ( Pages and endpoints of your own): Pages and endpoints A module exports route options and handlers as the framework's pages/* and api/* do, and lists each in routes with the file the app mounts it with. A page's path may not be an object's list ( /_crm/), and two modules can't claim one path or file. Checks What Where it is refused Two contributors define one thing defineSpool (server start) and spools gen Settings the module's schema refuses defineSpool and spools gen Settings for a module that isn't listed defineSpool and spools gen Settings for a module that takes none defineSpool and spools gen A module's page where an object's list is, or two modules claiming one path or file defineSpool and spools gen An override that names nothing defineSpool, and the compiler for a fixed config A table of another module in tables defineModule A route file that is missing spools modules (exit 1); spools gen warns" }, + { + "path": "/docs/headless", + "title": "Headless", + "description": "A Spool comes with a whole CRM to look at: pages, lists, boards, a record page. You can also run it with none of that, as the server behind a front end of your own. The records, the rules, record scopes, roles, automations, sequences and files are the same server either way. What changes is what you put in front of it.", + "sections": [ + { + "id": "what-a-headless-spool-is", + "title": "What a headless Spool is", + "level": 2 + }, + { + "id": "a-server-with-no-interface", + "title": "A server with no interface", + "level": 2 + }, + { + "id": "calling-it", + "title": "Calling it", + "level": 2 + }, + { + "id": "the-typed-client", + "title": "The typed client", + "level": 2 + }, + { + "id": "your-objects-typed", + "title": "Your objects, typed", + "level": 3 + }, + { + "id": "who-is-asking", + "title": "Who is asking", + "level": 2 + }, + { + "id": "sign-in", + "title": "Sign-in", + "level": 3 + }, + { + "id": "better-auth-in-an-app", + "title": "Better Auth in an app", + "level": 3 + }, + { + "id": "api-keys", + "title": "API keys", + "level": 2 + }, + { + "id": "in-production", + "title": "In production", + "level": 2 + }, + { + "id": "from-the-servers-own-code", + "title": "From the server's own code", + "level": 2 + }, + { + "id": "what-isnt-headless-yet", + "title": "What isn't headless yet", + "level": 2 + } + ], + "text": "Headless A Spool comes with a whole CRM to look at: pages, lists, boards, a record page. You can also run it with none of that, as the server behind a front end of your own. The records, the rules, record scopes, roles, automations, sequences and files are the same server either way. What changes is what you put in front of it. Use the interface a Spool comes with when you want a CRM today and are happy to theme it. Go headless when the product is your own design: a customer portal, a mobile app, a back-office tool on another framework, or a script. What a headless Spool is Everything the CRM does for whoever asks is an operation: records.list, records.create, tasks.update, files.startUpload and so on. Each is defined once, with its name, what it takes, who may ask, and the program that answers. The interface's own server functions run these operations, and so does the HTTP API. So a rule that holds in the interface holds for your front end too, and neither has a door the other lacks. Nothing on the server's side imports a web framework. A headless Spool needs Bun, effect and the adapters you chose. It does not load React or TanStack Start. A server with no interface Start a headless Spool with: It is the same config, extensions and services as any Spool, with no pages, no React and no TanStack Start. Its server is one file: headlessServer answers everything a Spool answers except pages, at the same addresses, and starts the schedules (sequences, mailbox sync, marketing): Address /api/v1/* Every operation (below) /api/auth/* The auth adapter's own sign-in, when it has one (Better Auth) /api/files/* Downloads, and uploads relayed through the server /api/assistant* The assistant's chat /api/integrations/* Connecting an account (OAuth) /api/swirls/tools/* The tool API that workflows and the assistant call /api/webhooks/email Bounces and complaints from the email service /api/cron/* What a scheduler calls on a serverless host POST /unsubscribe One-click unsubscribe from an email /healthz ok The pages those addresses once led back to (after sign-in, after connecting an account, the unsubscribe page) are your front end's to draw. It takes the options of httpApi: Option basePath Where the API is mounted. /api/v1 unless it says tokens.authorizedParties The front ends whose sign-in tokens are taken as bearer tokens. Without it, no token opens the API origins Origins a browser on another site may call from (CORS) keys Take API keys as bearer tokens. Off unless it says To put the API alone beside routes of another server, mount httpApi() from @swirls/spools/http instead: it is one handler that answers only paths under basePath. A Spool with the interface can mount it too, and then has both. Calling it Request GET /api/v1 Every operation: its name, whether it reads or writes, who may ask, and its input as JSON Schema POST /api/v1/ Runs an operation. The JSON body is its input GET /api/v1/?input= The same, for an operation that only reads GET /api/v1/openapi.json The same list as an OpenAPI 3.1 document, for tools that read one An answer is { \"data\":... }. A refusal or a failure is { \"error\": { \"code\": \"...\", \"message\": \"...\" } }: Status code When 400 invalid_input The input is not what the operation takes 400 invalid The operation refused what was asked (a rule, a missing field) 401 unauthorized Nobody is signed in, or the token is not one this server takes 403 forbidden Signed in, but not on the access list, or outside their scope 403 cross_site A browser on another site sent a session cookie 403 read_only A read-only API key asked for a change 404 not_found No such operation or record. A record a role hides is also this 405 method_not_allowed A write asked for with GET 409 conflict A uniqueness rule refused it 413 too_large The body is over 1 MB 500 failed Anything else. The server's log has the rest A write sent with an Idempotency-Key header runs once for that teammate, and a repeat gets the first answer again. See idempotent requests. The typed client @swirls/spools/client knows every operation by name, what each takes and what each answers. It imports nothing of the server: only the types cross. Dates arrive as text, as JSON carries them, and the types say so. The types come from the package, so a front end in another repository installs @swirls/spools as a development dependency to get them. Your objects, typed bun run crm:gen writes src/crm.types.ts from the config: for each object, the record as the API gives it and the values a write takes, and Crm, which lists them by key. Give it to the client and records(key) knows every field: A select is one of its options, money is a decimal in text when read ( \"12000.00\") and may be written as a number, and a relation is the related record's id under Id with the record beside it under . A list brings back the fields it asked for, so a row's fields are all optional but its id. Rename a field in the config and the front end stops compiling where it used the old name. The file is generated: never edit it. Who is asking The API decides who is asking exactly as the interface does. Whoever it is must be on the access list, works in the record scope they asked for out of the ones they hold, and reaches what their roles let them. No operation can be called as \"the system\". There are three ways to say who you are: The session cookie, for a front end on the same site as the API. The browser sends it by itself. A request from a page on another site is refused before anything runs, so another site's page can't act through a signed-in teammate. A sign-in token, sent as Authorization: Bearer , for a front end anywhere else. The server takes one only when you name the front ends whose tokens count: An API key, sent the same way, for a script or another service ( below). A request with a bearer token is judged by the token alone. A cookie sent with it counts for nothing. A caller with a token names its record scope in an X-Spools-Scope header: a scope's key, or * for all of theirs. It is a preference, checked against what they hold. Sign-in Adapter In a headless Spool clerk() Import it from @swirls/spools/auth/clerk/backend. It reads Clerk's session cookie from the request with Clerk's backend SDK, and checks bearer tokens. A cookie counts only when Clerk issued it to your front end: the origin of APP_URL, or the ones in clerk({ authorizedParties }). Your front end uses Clerk's kit for its framework betterAuth() Works as it is: sign-in runs from this server under /api/auth, and the cookie is this site's, so a front end of pages is served from the same origin as the API ( APP_URL), behind one proxy if they are two servers. It serves /sign-in, where the emailed link lands. For an app that can't keep a cookie, see below devAuth() Works as it is, for development: every request is you With Clerk, a session Clerk would renew by sending the browser away and back counts as signed out, because an API can't redirect. Clerk's browser kit renews the cookie before that is needed. Better Auth in an app A phone or desktop app has no cookie jar to rely on. betterAuth({ bearer: true }) lets it carry the session as a bearer token instead: The answer that signs someone in ( GET /api/auth/magic-link/verify, or a provider's callback) then carries a set-auth-token header. The app keeps its value and sends it as Authorization: Bearer on every call. The token is the session: it lasts as long as the session does, signing out ends it, and whoever holds it is that person, so keep it where the platform keeps secrets. The server signed it for someone it signed in itself, so there is no front end to name and authorizedParties stays empty. Leave bearer off for a front end of pages in a browser, where the cookie is kept from scripts and a token would not be. API keys A script, a nightly job or another service calls the API with a key in place of a person's session. Keys are off until the server says it takes them: Without that, a key is a token the server doesn't take and the table that holds keys is never read. Then make one: A key is not a new kind of caller. It acts as the teammate named with --as: it reaches the records they reach, in the scopes they hold, with what their roles allow, and its changes are theirs on the timeline. Take them off the access list and the key opens nothing. For a service, make a teammate for it (an address of its own on the access list, with a role that reaches only what it needs) and make the key as them. Option --read-only The key may run operations that read, and is refused every one that writes. A read made with it leaves the file store as it is too: the shared library's folders are not made on its first look --days It stops working after that many days: 90 unless this says --never-expires It works until it is revoked. Say so on purpose: a key that never ends is one nobody remembers to end create prints the key once. What the api_keys table keeps is sealed by the Spool's vault (CipherStash, in a Spool as it is made): the hash of the key's secret together with whose key it is, whether it only reads and when it ends, encrypted for that one row. A key is judged by what its seal says, never by the row's own columns. So: Reading the database gives nobody a key that works, and a lost key is replaced, not recovered. Writing to the database gives nobody one either. A row someone inserts has no seal the vault made, a seal copied from another row was made for that row, and a row whose teammate, reach or expiry someone changes no longer says what its seal says. A revoked key's seal is wiped, so it can't be brought back. A Spool with no vault has no keys: none is made and none is taken. What the vault opened is remembered for a minute, so a busy key is not a call to the vault on every request. Revoking still takes effect at once, because the row is read every time. Keys are managed with the command, by whoever can run commands in the app's folder with its environment: there is no operation that makes one, so no caller of the API can mint more access than they have. In production bun run start runs the server with NODE_ENV=production. It refuses to start with the development sign-in or without the vault's CS_* variables ( CipherStash), which seal API keys, connected accounts and kept answers. Deployment has what a headless Spool needs set, and Security what the API promises. On your own machine none of that is needed: records go in a Postgres inside the server, every request is you, and a stand-in seals in place of the vault. From the server's own code A front end that shares the process (a server-rendered page, a route of your own) skips HTTP and calls the operation: callAs takes a user id and checks it the same way: the access list, scopes and roles all apply. Where the id comes from is yours to get right. Take it from a session the auth adapter read or a token it verified, never from the request's own say-so. What isn't headless yet Better Auth with pages on another origin. Its cookie, its emailed link and its redirects are all on APP_URL, so a front end of pages is served from that origin. A front end on another origin uses Clerk. Answers are described for the record operations only. GET /api/v1 and the OpenAPI document describe every operation's input, and the answer of records.get, records.list, records.create, records.update, records.delete, records.deleteMany, records.titles, records.searchTitles and brand.get. A record is described by what every record has; its own fields are in src/crm.types.ts. The other answers are in the TypeScript types only. React hooks for a front end (lists, a record, filters, inline editing as state without markup) are not there yet. The typed client is what a front end calls today." + }, { "path": "/docs/search-and-filters", "title": "Search and filters", @@ -625,7 +693,7 @@ "level": 2 } ], - "text": "Roles A role is what someone does in the business: sells, designs, runs the office. In Spools a role decides what the CRM puts in front of them: what Home and the sidebar show (and the tiles on Home, which follow the sidebar). With access it also decides which objects they may open and change, and the server enforces that. The two are different things. hide only tidies the sidebar: someone whose sidebar leaves purchase orders out can still open them from search or a link. access is enforced on every read and write: an object a role is denied is not there for its holders, by any path. Roles keep kinds of record apart; to keep groups of people (branches, regions) to their own records, use record scopes. Both can be on, and the stricter wins. Defining roles Roles are in crm.config.json. Without the roles key there are none, and no Team page. Key Required Description label yes What the role is called on the Team page. hide no Objects the sidebar leaves out for this role. home.create no false leaves the New button ( home.create) off this role's Home. home.pipeline no This role's part of home.pipeline, or false to leave the pipeline off its Home. home.pipeline.owner no Which of the pipeline's owner fields make a record this role's: one field or a list. Without it, every one of them does. home.pipeline.team no true shows this role everyone's records, under \"Team pipeline\". access no What the role may reach: { \"deny\": [objects], \"readOnly\": true or [objects] }. See Access. record. no { \"open\": [sections], \"hide\": [sections] }: how that object's record page starts for this role. See Record page sections. With a pipeline whose owner is [\"owner\", \"designer\"], a salesperson's pipeline is the deals they own, a designer's is the deals they design, and management sees the team's. The New button fills in the owner field of the role of whoever presses it. Several roles, or none Someone can hold more than one role, and gets what any of them is given: Their pipeline is the records any of their roles makes theirs. A salesperson who also designs sees the deals they own and the deals they design, each counted once. If any of their roles is shown the team, they are. The sidebar leaves out only what every role they hold hides. The pipeline or the New button is left off Home only when every role they hold leaves it off. Someone with no role sees Home and the sidebar as the config has them, as everyone did before roles. Record page sections An object with sections can start differently for each role: a designer opens Design and Site, the office opens Invoicing and never sees Design. open: these sections start open for the role, and every other one collapsed. Someone holding several roles has open every section any of them opens. When none of their roles says open for the object, each section starts as the config says. hide: these sections are left off the role's record page and new-record form. A section is left off only when every role someone holds hides it, so holding a role with no record entry for the object, or one without hide, keeps every section. Someone with no role sees each section as the config starts it. more is the built-in \"More details\" section, and can be opened or hidden like any other. The keys are checked: an object that isn't there, one without sections, or a section it doesn't have, is refused. A module's sections can be named. hide is presentation only. It tidies a page; it keeps nothing from anyone. The fields of a hidden section are still in the record the browser is sent, and still the role's to read and change in lists, filters, exports, imports, the API and the assistant. To keep an object from a role, use access. A required field is never left off a new-record form, whatever hide says: it is put first, with the title field. Access deny: objects whose records the role's holders never read or change. To them the records are not found, everywhere: lists, record pages, search, relation pickers and titles, saved views, the timeline, tasks and notes, reports, exports, imports, files and actions. A relation to one shows no title, and the timeline of a record the role reads never names one: a change to a relation that leads to an object any role, access.default or assistant.deny keeps from someone is written \"updated Client\" (or \"added Tags: 2\"), for everyone, because a timeline line is kept as it was written. readOnly: true for every object, or a list. Its holders read the records and change nothing of them: not the record, and not what hangs off it. No note, task or logged call is added to one, changed or deleted (a task assigned to them included), no email is sent to it, no action, workflow or sequence is started for it, and no file or folder in its folder, or in the folders inside it, is added, renamed, moved or deleted. Nor is a view everyone shares of that object; they make, change and delete views only they see. They still open, list, search and download it all, and star a favourite, which is their own. The page doesn't offer the controls, and the server refuses in words (\"You can look at jobs but not change them.\") before the app's hooks run or anything is sent. \"readOnly\": true (or every object read-only or denied) is someone who may change no record, and so changes nothing that is the whole business's either, as with record scopes: no task or note on no record, nothing in the shared file library or any folder (\"You can look at these files, but not change them.\"), no view everyone shares, nothing on the Marketing page, and no connection the team or a group shares. Their own things (their mailbox, their favourites, the views only they see) stay theirs. A role without access allows everything. Someone with several roles gets what any of them allows: an object is hidden from them only when every role they hold denies it, and read-only only when none of their roles may change it. A designer who is also in the office edits everything. Someone who holds no role reaches everything, as before roles, unless access.default says otherwise. With \"default\": { \"readOnly\": true } a new teammate looks until an admin gives them a role. A config with no roles at all and an access.default applies it to everyone. Timeline lines written before an object was denied may still name its records. After adding a deny, an access.default or an assistant.deny to a Spool with history, run bunx spools timeline redact: it rewrites those lines as a line written today would say them. It finds a change line by the field it is about, which every change line records from this version on, and an older line by the field's label as it is now. It can't fix an older line written under a label the field no longer has, nor a title in words that aren't a change line (a note, an email, a line your own code or an automation wrote): look for those yourself. The Team page shows what each role may do with each object. The security page says exactly what role access keeps apart and what it doesn't. Notably, the assistant's tool calls can't say which person they are for, so roles don't narrow the assistant: assistant.deny ( configuration) keeps objects from it. Where roles come from What a role means is always in the config. Who holds it comes from one of three places, and a Spool uses one: Source Chosen by Roles are set The CRM itself Nothing: it is the default On the Team page, by the people access.admins names Your sign-in provider The auth adapter, e.g. clerk({ roles: 'metadata' }) At the provider, and on the Team page when the provider takes changes (Clerk's public metadata) Your own code roles in src/app/extensions.ts Wherever your code reads them from Your own code wins over the provider, and the provider over the CRM. Whichever answers, a role counts only when roles in the config has it, and an answer from outside the CRM is kept for a minute per person. The CRM itself: the Team page The Team page lists everyone who has signed in, with a box for each role. Ticking a box saves at once, and the person's Home and sidebar follow on their next page. Only the people access.admins names see the Team page or can change a role: An admin must also be let in by the access list. The server checks the list on every call: a page that hid nothing would still be refused. Roles are kept by email, so someone can be given theirs before they first sign in: add their address at the bottom of the Team page. It must be an address the access list lets in. Their Home is ready the first time they sign in with it. Clerk roles: 'metadata' reads the user's public metadata: a list, { \"roles\": [\"designer\", \"management\"] }, or one, { \"role\": \"designer\" }. Set it on the user in Clerk's dashboard, or with the Backend API. Public metadata is written only with your secret key, never by the person themselves. An invitation can carry it, so someone has their role before they first sign in. roles: { organization: 'org_...' } reads their role in that Clerk organization, without the org: prefix: org:designer is the role designer. Clerk gives a person one role in an organization, so nobody holds two this way. A role in any other organization counts for nothing: unless you have turned it off, anyone can create an organization and be its admin. With roles: 'metadata' the Team page sets roles too. An admin ticks a box, and the CRM writes the list to that person's public metadata through Clerk's Backend API, with the secret key the Spool already has. Whatever else their metadata holds is kept, including roles that are not this CRM's, and the change shows on their next page. Someone has to have signed in once: the roles go on an account, and until there is one the page says so. (An invitation can carry the metadata before that.) With a role in an organization, the Team page lists everyone and what they hold and changes nothing: a membership is changed in Clerk, with its members. Your own code held is given the person's id and email and returns the keys of the roles they hold. Use it when roles are kept in a directory, a payroll system, or a table of your own. A source of your own, in an adapter Roles ( @swirls/spools/server/roles) is the service all three sources are. An auth adapter supplies one as roles on what it returns: held(user) says what a person holds, managedIn names where roles are kept, and an optional set(user, roles, by) lets the Team page write to it. Leave set out and the page only shows. Adding roles to a Spool made before them Add roles and access.admins to crm.config.json. Add the page's route file, src/routes/_crm/team.tsx: Run bun run crm:gen, then bun run db:push or plan a migration: there is one new table, team_roles. Run bun run build so the new route is typed. \"team\" can no longer be the key of an object: it is the page's address." + "text": "Roles A role is what someone does in the business: sells, designs, runs the office. In Spools a role decides what the CRM puts in front of them: what Home and the sidebar show (and the tiles on Home, which follow the sidebar). With access it also decides which objects they may open and change, and the server enforces that. The two are different things. hide only tidies the sidebar: someone whose sidebar leaves purchase orders out can still open them from search or a link. access is enforced on every read and write: an object a role is denied is not there for its holders, by any path. Roles keep kinds of record apart; to keep groups of people (branches, regions) to their own records, use record scopes. Both can be on, and the stricter wins. Defining roles Roles are in crm.config.json. Without the roles key there are none, and no Team page. Key Required Description label yes What the role is called on the Team page. hide no Objects the sidebar leaves out for this role. home.create no false leaves the New button ( home.create) off this role's Home. home.pipeline no This role's part of home.pipeline, or false to leave the pipeline off its Home. home.pipeline.owner no Which of the pipeline's owner fields make a record this role's: one field or a list. Without it, every one of them does. home.pipeline.team no true shows this role everyone's records, under \"Team pipeline\". access no What the role may reach: { \"deny\": [objects], \"readOnly\": true or [objects] }. See Access. record. no { \"open\": [sections], \"hide\": [sections] }: how that object's record page starts for this role. See Record page sections. With a pipeline whose owner is [\"owner\", \"designer\"], a salesperson's pipeline is the deals they own, a designer's is the deals they design, and management sees the team's. The New button fills in the owner field of the role of whoever presses it. Several roles, or none Someone can hold more than one role, and gets what any of them is given: Their pipeline is the records any of their roles makes theirs. A salesperson who also designs sees the deals they own and the deals they design, each counted once. If any of their roles is shown the team, they are. The sidebar leaves out only what every role they hold hides. The pipeline or the New button is left off Home only when every role they hold leaves it off. Someone with no role sees Home and the sidebar as the config has them, as everyone did before roles. Record page sections An object with sections can start differently for each role: a designer opens Design and Site, the office opens Invoicing and never sees Design. open: these sections start open for the role, and every other one collapsed. Someone holding several roles has open every section any of them opens. When none of their roles says open for the object, each section starts as the config says. hide: these sections are left off the role's record page and new-record form. A section is left off only when every role someone holds hides it, so holding a role with no record entry for the object, or one without hide, keeps every section. Someone with no role sees each section as the config starts it. more is the built-in \"More details\" section, and can be opened or hidden like any other. The keys are checked: an object that isn't there, one without sections, or a section it doesn't have, is refused. A module's sections can be named. hide is presentation only. It tidies a page; it keeps nothing from anyone. The fields of a hidden section are still in the record the browser is sent, and still the role's to read and change in lists, filters, exports, imports, the API and the assistant. To keep an object from a role, use access. A required field is never left off a new-record form, whatever hide says: it is put first, with the title field. Access What a role is denied holds for every way in: the interface, the HTTP API, an API key made as someone with that role, the assistant and your own code. deny: objects whose records the role's holders never read or change. To them the records are not found, everywhere: lists, record pages, search, relation pickers and titles, saved views, the timeline, tasks and notes, reports, exports, imports, files and actions. A relation to one shows no title, and the timeline of a record the role reads never names one: a change to a relation that leads to an object any role, access.default or assistant.deny keeps from someone is written \"updated Client\" (or \"added Tags: 2\"), for everyone, because a timeline line is kept as it was written. readOnly: true for every object, or a list. Its holders read the records and change nothing of them: not the record, and not what hangs off it. No note, task or logged call is added to one, changed or deleted (a task assigned to them included), no email is sent to it, no action, workflow or sequence is started for it, and no file or folder in its folder, or in the folders inside it, is added, renamed, moved or deleted. Nor is a view everyone shares of that object; they make, change and delete views only they see. They still open, list, search and download it all, and star a favourite, which is their own. The page doesn't offer the controls, and the server refuses in words (\"You can look at jobs but not change them.\") before the app's hooks run or anything is sent. \"readOnly\": true (or every object read-only or denied) is someone who may change no record, and so changes nothing that is the whole business's either, as with record scopes: no task or note on no record, nothing in the shared file library or any folder (\"You can look at these files, but not change them.\"), no view everyone shares, nothing on the Marketing page, and no connection the team or a group shares. Their own things (their mailbox, their favourites, the views only they see) stay theirs. A role without access allows everything. Someone with several roles gets what any of them allows: an object is hidden from them only when every role they hold denies it, and read-only only when none of their roles may change it. A designer who is also in the office edits everything. Someone who holds no role reaches everything, as before roles, unless access.default says otherwise. With \"default\": { \"readOnly\": true } a new teammate looks until an admin gives them a role. A config with no roles at all and an access.default applies it to everyone. Timeline lines written before an object was denied may still name its records. After adding a deny, an access.default or an assistant.deny to a Spool with history, run bunx spools timeline redact: it rewrites those lines as a line written today would say them. It finds a change line by the field it is about, which every change line records from this version on, and an older line by the field's label as it is now. It can't fix an older line written under a label the field no longer has, nor a title in words that aren't a change line (a note, an email, a line your own code or an automation wrote): look for those yourself. The Team page shows what each role may do with each object. The security page says exactly what role access keeps apart and what it doesn't. Notably, the assistant's tool calls can't say which person they are for, so roles don't narrow the assistant: assistant.deny ( configuration) keeps objects from it. Where roles come from What a role means is always in the config. Who holds it comes from one of three places, and a Spool uses one: Source Chosen by Roles are set The CRM itself Nothing: it is the default On the Team page, by the people access.admins names Your sign-in provider The auth adapter, e.g. clerk({ roles: 'metadata' }) At the provider, and on the Team page when the provider takes changes (Clerk's public metadata) Your own code roles in src/app/extensions.ts Wherever your code reads them from Your own code wins over the provider, and the provider over the CRM. Whichever answers, a role counts only when roles in the config has it, and an answer from outside the CRM is kept for a minute per person. The CRM itself: the Team page The Team page lists everyone who has signed in, with a box for each role. Ticking a box saves at once, and the person's Home and sidebar follow on their next page. Only the people access.admins names see the Team page or can change a role: An admin must also be let in by the access list. The server checks the list on every call: a page that hid nothing would still be refused. Roles are kept by email, so someone can be given theirs before they first sign in: add their address at the bottom of the Team page. It must be an address the access list lets in. Their Home is ready the first time they sign in with it. Clerk roles: 'metadata' reads the user's public metadata: a list, { \"roles\": [\"designer\", \"management\"] }, or one, { \"role\": \"designer\" }. Set it on the user in Clerk's dashboard, or with the Backend API. Public metadata is written only with your secret key, never by the person themselves. An invitation can carry it, so someone has their role before they first sign in. roles: { organization: 'org_...' } reads their role in that Clerk organization, without the org: prefix: org:designer is the role designer. Clerk gives a person one role in an organization, so nobody holds two this way. A role in any other organization counts for nothing: unless you have turned it off, anyone can create an organization and be its admin. With roles: 'metadata' the Team page sets roles too. An admin ticks a box, and the CRM writes the list to that person's public metadata through Clerk's Backend API, with the secret key the Spool already has. Whatever else their metadata holds is kept, including roles that are not this CRM's, and the change shows on their next page. Someone has to have signed in once: the roles go on an account, and until there is one the page says so. (An invitation can carry the metadata before that.) With a role in an organization, the Team page lists everyone and what they hold and changes nothing: a membership is changed in Clerk, with its members. Your own code held is given the person's id and email and returns the keys of the roles they hold. Use it when roles are kept in a directory, a payroll system, or a table of your own. A source of your own, in an adapter Roles ( @swirls/spools/server/roles) is the service all three sources are. An auth adapter supplies one as roles on what it returns: held(user) says what a person holds, managedIn names where roles are kept, and an optional set(user, roles, by) lets the Team page write to it. Leave set out and the page only shows. Adding roles to a Spool made before them Add roles and access.admins to crm.config.json. Add the page's route file, src/routes/_crm/team.tsx: Run bun run crm:gen, then bun run db:push or plan a migration: there is one new table, team_roles. Run bun run build so the new route is typed. \"team\" can no longer be the key of an object: it is the page's address." }, { "path": "/docs/layouts", @@ -814,7 +882,7 @@ "level": 2 } ], - "text": "Integrations: accounts teammates connect The Integrations page ( /integrations) is where a teammate sees every account the CRM works with on their behalf, and connects more: The account they sign in with. A Google or Microsoft sign-in is a mailbox already; nothing is connected and the CRM stores no tokens for it. See Mailbox. More mailboxes. A second address, a shared inbox, or the only mailbox of someone who signs in with an email and password. Google and Microsoft are built in. Other services your app adds, such as an accounting or phone system. See Add a provider. Accounts shared with the team: a service your app says is connected once for everyone, or once for each branch or region. See Shared connections. The accounts your marketing posts through (LinkedIn, X, Google Ads), once a channel or an ad account in the config uses one. These are shared with the team: whoever connects one, any teammate can publish through it from the Marketing page. See Marketing. Each person connects their own accounts. Nobody else can see or remove them, and nobody else can use them. A shared connection is the exception, and the page lists those under their own heading. Status: built and tested against stubbed providers and a stand-in for CipherStash. It has not yet been run against live Google, Microsoft or CipherStash accounts. Connected mailboxes A connected mailbox is treated exactly like the sign-in one: Its mail and finished meetings with known contacts are logged on timelines, on the same schedule, credited to the teammate who connected it. Only the subject, a short preview and the time are kept. The teammate can send from it. \"Compose email\" shows a From choice when they have more than one mailbox that may send. Left alone, the CRM uses the address it knows them by, then their sign-in, then a connected mailbox. A person can connect several mailboxes, including several from one provider. Connecting the address you already sign in with is harmless: the CRM uses whichever of the two has the access it needs, and the sign-in when both do. This is also the way to give the CRM mail access without adding the mail scopes to your Clerk connection. When a teammate is removed from access in crm.config.json, their connected mailboxes stop being read. The stored tokens stay until they are disconnected or the rows are deleted. Connecting asks for the scopes listed in packages/spools/src/crm/mailbox.ts (read mail and calendar, send mail), the same ones the sign-in uses. Shared connections Some accounts are the business's, not a person's: one accounting system for the company, or one for each branch, used by whoever presses \"Create invoice\" and still working after the person who connected it has left. A provider says so with shared (see Share a provider with the team): The provider says A connection belongs to Who may use it nothing The teammate who connected it That teammate shared: 'team' The team. There can be more than one Everyone on the access list shared: 'group' One group, chosen when connecting Everyone on the access list (see below) On the page, shared connections are under Shared with the team, for everyone: which account, the whole team or which group, who connected it and when, and \"Needs reconnecting\" when the provider has turned the stored grant down. Who may connect, reconnect and disconnect. Anyone on the access list, unless the provider has canManage: then only the people it names. In a Spool with record scopes, never someone who can change nothing (a read-only role, or no scope at all), whatever canManage says: they see the connection, can use it, and manage only accounts of their own. Everyone else sees the connection and can use it, without the buttons, and the server refuses them whatever they send. Connecting an account that is already connected for the team (or for that group) replaces its tokens and records who did it; the connection keeps its id. One connection for each account. An account is connected once for the team, or once for each group, whoever connects it: the database refuses a second row, so two people finishing at the same moment end up with one connection holding the tokens of whoever was last. Which account it is comes from the provider, asked with the token it just issued, never from the address the browser was sent back to (see Add a provider). When whoever connected it leaves. Nothing changes. A shared connection belongs to the team, so nothing that uses, lists or manages it asks whether that person is still on the access list. The page goes on saying who connected it, from the name kept at the time. This is the opposite of a connected mailbox, which is a person's and stops being read when they are removed: the built-in Google and Microsoft mailboxes can't be shared, so that rule is as it was. Groups. A group is a key and a label that your app lists: branches, regions, whatever the business is divided by. The key is a plain string of your choosing. Today a group's connection can be used by anyone on the access list who asks for that group; the CRM has no notion yet of which groups a person belongs to. Limit who may manage a group's connection with canManage, which is told the group. Record scopes. Connections are shared across record scopes: which scope a person holds or works in changes nothing about which connections they see and use. A group is not a scope, even when both are named after the same branches: a group picks an account, and a scope decides who reaches a record. A handler that uses a connection still reads and writes records with the access of whoever pressed the button, so group: ctx.record.branch picks that branch's account for a record the person could already open, and gives them no other record. Changing your mind. Whose a connection is was decided when it was made, and is stored with it. Adding shared to a provider people have already connected for themselves does not hand those connections to the team: each stays with its owner, who sees a note on the page, until that person connects the same account again. That turns their connection into the team's; nobody else's is touched. Removing shared leaves existing shared connections shared. How tokens are stored The sign-in's tokens stay with the auth provider. A connected account's tokens are the CRM's to keep, so they are sealed by the vault: by default with CipherStash ( @cipherstash/stack) inside the app before they are written to the integrations table, each value under its own key from ZeroKMS. The database only holds ciphertext, so a database dump or a leaked backup cannot be used to read anyone's mail. There is no plaintext fallback. Without its keys the vault refuses to store anything and the page says more accounts can't be connected yet. The code is in packages/spools/src/server/runtime/vault.ts. Each connection's tokens are sealed for the row they are stored on. For a connection of one's own that is its teammate, the provider and the account. For a shared connection it is the provider, the account, and that it is the team's or which group's. Tokens copied onto another row, or a row edited in the database to turn a personal connection into a shared one or to move it to another group, are refused. Disconnecting deletes the stored copy, and asks the provider to revoke the token where it offers that. There is one case where it does not ask: when another connection holds the same account at the same OAuth client (a teammate's own beside the team's, two people who each connected one shared inbox, a Google mailbox and Google Ads on one Google account). At many providers revoking one token ends every token that account gave the client, which would stop the other connection without a word. The server logs that it left the grant in place. The last connection to an account is revoked as it goes. Setup The sign-in mailbox needs none of this. To let teammates connect more accounts: 1. The vault With vault: aes() there is one thing to set, a key of your own: VAULT_KEY=$(openssl rand -base64 32). Keep it somewhere other than the database: whoever has both can read every connected account. To change it, put the old key in VAULT_OLD_KEYS so what it sealed still opens. With vault: cipherstash(): Create a workspace and an access key, then set: APP_URL (the public address of the app) and APP_SECRET (32+ characters; signs the OAuth state) must be set too. 2. Google In the Google Cloud console, create an OAuth client of type Web application. It can be the same client your Clerk connection uses, with one more redirect URI. Authorised redirect URI: {APP_URL}/api/integrations/google/callback Enable the Gmail API and the Google Calendar API for the project. OAuth consent screen: for a Google Workspace organisation choose Internal, which needs no review by Google. An External app that asks for Gmail scopes must pass Google's verification before people outside your test-user list can connect. 3. Microsoft In Microsoft Entra, register an application with a Web platform (or add the redirect URI to the one your Clerk connection uses): Redirect URI: {APP_URL}/api/integrations/microsoft/callback API permissions (delegated): openid, email, offline_access, User.Read, Mail.Read, Calendars.Read, Mail.Send. Some tenants require an administrator to consent. Create a client secret. A provider is offered once its client id and secret are set; you can set up one and not the other. The server logs which parts are on at start-up. How connecting works Connect opens /api/integrations//connect (with ?group= for a provider shared by group). It checks the CRM session and, for a shared provider, that the group is one the provider lists and that this person may manage the connection. It sets a ten-minute, HttpOnly cookie holding a nonce and a PKCE verifier, and redirects to the provider with a signed state that names the teammate and, for a shared connection, whose it will be: the team's, or which group's. The provider returns to /api/integrations//callback. The callback is accepted only if the state signature is valid and unexpired, it names the signed-in teammate, and the cookie's nonce matches: so it only completes in the browser that started it. Whose the connection is comes from the signed state and nothing else in the callback's address. It is then checked against what the provider says now, so a state made for a personal connection can't make a shared one, one made for a group can't be used for another, and a person who stopped being allowed to manage the connection in the meantime is refused. The code is exchanged for tokens (with the PKCE verifier), the provider is asked which account the new token is for, the tokens are encrypted and the row is written. Connecting the same account again replaces its tokens. The write checks and changes in one step, so two callbacks for the same account can't leave two rows. getAccessToken(connectionId, { as }) (from @swirls/spools/extensions) returns a valid access token, refreshing it when it is about to expire. as is the person the call is for: the token is then only given if they are on the access list and the connection is theirs or is shared. Someone taken off the access list gets no token, not even for a connection of their own. When as names nobody ( ctx.actor is null in a handler an automation ran), the call is refused. Code nobody is behind, such as a schedule, says so by leaving the second argument out: getAccessToken(connectionId). If the provider turns the refresh down (the person revoked access, or a password change invalidated it), the connection shows \"Needs reconnecting\" and is left alone until it is connected again. A provider that is merely unavailable is tried again later. A token renewed while its connection was being connected again, or handed to the team, is thrown away and the new one is used. One renewal runs at a time for a connection, and it runs to its end (or to the provider's time limit) even when the request that asked for it goes away, so a teammate closing a tab never leaves a connection half renewed. Add a provider Anything that speaks OAuth 2 with the authorization-code flow can be added in integrations in src/app/extensions.ts. The framework shows it on the page, runs the flow, encrypts and refreshes the tokens. Your code decides what to do with them. Register {APP_URL}/api/integrations//callback as the redirect URI with the provider. The provider must issue a refresh token; a connection without one is refused. For a provider that only gives a long-lived access token, set refreshToken: 'optional': the connection then works until that token runs out, and shows \"Needs reconnecting\" after. An id is lower-case letters, digits, - or _. google and microsoft are taken. A provider with a bad id is left out, with a warning at start-up. account must ask the provider. get calls the provider's API with the token it just issued, so its answer is about the account that was really authorized. The callback's query string ( query) is not: it came through the browser, and whoever is connecting can change it before it reaches the CRM. Some providers name the account only there (a companyId or realmId parameter). Use that value to know what to ask for, and let the provider confirm it: This matters most for a shared provider. Connecting an account that is already connected for the team replaces the team's tokens, and the account's name is how that connection is found. If the name came from the address, a teammate could authorize a company of their own, change companyId to the team's, and leave the team's connection holding their tokens: every invoice after that would go to the wrong company. So a shared connection is refused unless its account got an answer from the provider through get. The CRM can't check what you asked, so ask for something only the right account can answer. findConnections and getAccessToken are for server code. Never return a token, or another teammate's connection, to the browser. A provider's type is IntegrationProvider, from @swirls/spools/extensions, if you build yours with a function. Share a provider with the team Add shared to the provider and its connections belong to the team, or to a group of it, instead of to whoever connected them. Option What it does shared 'team': a connection is everyone's on the access list. 'group': it is one group's, chosen when connecting. Left out: it is the teammate's who connected it groups For 'group': what a connection can be made for. { key, label } entries (or keys alone), or a function that returns them. A key is at most 100 characters, with no control characters canManage Who may connect, reconnect and disconnect: a list of email addresses, or (user, { group }) => boolean (it may be async; if it throws, nobody may). Left out: anyone on the access list adoptExisting For 'team', when connections to this provider were already used by everyone before you added shared (as marketing accounts were): the ones made before count as the team's without being reconnected What your code can ask for: Call Returns findConnections({ provider, shared: 'team' }) The team's connections findConnections({ provider, group: 'north' }) That group's connections, and no other group's findConnections({ provider, shared: 'group' }) Every group's findConnections({ provider, userId }) That teammate's own. Never a shared one, whoever connected it findConnections({ provider }) Every connection to the provider, whoever's any of them with usableBy: ctx.actor Only the ones that person may use. None when there is no actor getAccessToken(connection.id, { as: ctx.actor }) A token, or a refusal when that person may not use it, or when there is no actor getAccessToken(connection.id) A token, for code nobody is behind (a schedule, a webhook) A connection says whose it is: shared ( 'team', 'group' or null), group, and connectedBy, the name of whoever connected a shared one ( null for one made before names were kept). userId is who connected it. Pass usableBy and as whenever a person caused the call. ctx.actor is null when nobody did (an automation, a script, an import). Passing that null does not make the call trusted: getAccessToken refuses and findConnections finds nothing, because nobody may use nothing. If a handler really should act for the business when no one is signed in, write that out, so it can be seen in the code: A provider whose declaration contradicts itself ( groups without shared: 'group', canManage without shared) is left out, with a warning at start-up. The built-in Google and Microsoft mailboxes are always each person's own. Troubleshooting What you see What it means \"More accounts can't be connected yet\" The list under it names what is missing: APP_URL, APP_SECRET or the CS_* variables \"… hasn't been set up for this CRM yet\" That provider's client id and secret are not set \"That sign-in link expired or was opened in another browser\" The consent screen was left open for more than ten minutes, or finished in a different browser. Connect again \"… didn't grant ongoing access\" The provider sent no refresh token. Remove the CRM from the account's connected apps, then connect again \"Needs reconnecting\" The provider turned the stored grant down. Reconnect and pick the same account \"The CRM already reaches this mailbox through your sign-in\" The connection duplicates the sign-in account and is not used. Disconnect it, or leave it \"Only the people who manage … for this CRM can connect it\" The provider has canManage and it doesn't name you. Ask someone it does \"Who … is connected for changed while you were connecting\" The provider's shared setting was changed while the consent screen was open. Connect again \"Yours alone: it was connected before … was shared\" You connected it before the provider was shared. Connect the account again under Shared with the team \"… which account it is was not confirmed with …\" A shared provider's account took the name from the callback's address without asking the provider. Make it call get (see Add a provider) \"Could not read the … account\" The provider refused the question account asked with the new token: the account named in the address is not the one that was authorized, or the scopes don't cover it \"That account can only be used for someone signed in\" A handler passed as: ctx.actor and nobody was signed in (an automation ran it). Decide in the handler what should happen then" + "text": "Integrations: accounts teammates connect The Integrations page ( /integrations) is where a teammate sees every account the CRM works with on their behalf, and connects more: The account they sign in with. A Google or Microsoft sign-in is a mailbox already; nothing is connected and the CRM stores no tokens for it. See Mailbox. More mailboxes. A second address, a shared inbox, or the only mailbox of someone who signs in with an email and password. Google and Microsoft are built in. Other services your app adds, such as an accounting or phone system. See Add a provider. Accounts shared with the team: a service your app says is connected once for everyone, or once for each branch or region. See Shared connections. The accounts your marketing posts through (LinkedIn, X, Google Ads), once a channel or an ad account in the config uses one. These are shared with the team: whoever connects one, any teammate can publish through it from the Marketing page. See Marketing. Each person connects their own accounts. Nobody else can see or remove them, and nobody else can use them. A shared connection is the exception, and the page lists those under their own heading. Status: built and tested against stubbed providers and a stand-in for CipherStash. It has not yet been run against live Google, Microsoft or CipherStash accounts. Connected mailboxes A connected mailbox is treated exactly like the sign-in one: Its mail and finished meetings with known contacts are logged on timelines, on the same schedule, credited to the teammate who connected it. Only the subject, a short preview and the time are kept. The teammate can send from it. \"Compose email\" shows a From choice when they have more than one mailbox that may send. Left alone, the CRM uses the address it knows them by, then their sign-in, then a connected mailbox. A person can connect several mailboxes, including several from one provider. Connecting the address you already sign in with is harmless: the CRM uses whichever of the two has the access it needs, and the sign-in when both do. This is also the way to give the CRM mail access without adding the mail scopes to your Clerk connection. When a teammate is removed from access in crm.config.json, their connected mailboxes stop being read. The stored tokens stay until they are disconnected or the rows are deleted. Connecting asks for the scopes listed in packages/spools/src/crm/mailbox.ts (read mail and calendar, send mail), the same ones the sign-in uses. Shared connections Some accounts are the business's, not a person's: one accounting system for the company, or one for each branch, used by whoever presses \"Create invoice\" and still working after the person who connected it has left. A provider says so with shared (see Share a provider with the team): The provider says A connection belongs to Who may use it nothing The teammate who connected it That teammate shared: 'team' The team. There can be more than one Everyone on the access list shared: 'group' One group, chosen when connecting Everyone on the access list (see below) On the page, shared connections are under Shared with the team, for everyone: which account, the whole team or which group, who connected it and when, and \"Needs reconnecting\" when the provider has turned the stored grant down. Who may connect, reconnect and disconnect. Anyone on the access list, unless the provider has canManage: then only the people it names. In a Spool with record scopes, never someone who can change nothing (a read-only role, or no scope at all), whatever canManage says: they see the connection, can use it, and manage only accounts of their own. Everyone else sees the connection and can use it, without the buttons, and the server refuses them whatever they send. Connecting an account that is already connected for the team (or for that group) replaces its tokens and records who did it; the connection keeps its id. One connection for each account. An account is connected once for the team, or once for each group, whoever connects it: the database refuses a second row, so two people finishing at the same moment end up with one connection holding the tokens of whoever was last. Which account it is comes from the provider, asked with the token it just issued, never from the address the browser was sent back to (see Add a provider). When whoever connected it leaves. Nothing changes. A shared connection belongs to the team, so nothing that uses, lists or manages it asks whether that person is still on the access list. The page goes on saying who connected it, from the name kept at the time. This is the opposite of a connected mailbox, which is a person's and stops being read when they are removed: the built-in Google and Microsoft mailboxes can't be shared, so that rule is as it was. Groups. A group is a key and a label that your app lists: branches, regions, whatever the business is divided by. The key is a plain string of your choosing. Today a group's connection can be used by anyone on the access list who asks for that group; the CRM has no notion yet of which groups a person belongs to. Limit who may manage a group's connection with canManage, which is told the group. Record scopes. Connections are shared across record scopes: which scope a person holds or works in changes nothing about which connections they see and use. A group is not a scope, even when both are named after the same branches: a group picks an account, and a scope decides who reaches a record. A handler that uses a connection still reads and writes records with the access of whoever pressed the button, so group: ctx.record.branch picks that branch's account for a record the person could already open, and gives them no other record. Changing your mind. Whose a connection is was decided when it was made, and is stored with it. Adding shared to a provider people have already connected for themselves does not hand those connections to the team: each stays with its owner, who sees a note on the page, until that person connects the same account again. That turns their connection into the team's; nobody else's is touched. Removing shared leaves existing shared connections shared. How tokens are stored The sign-in's tokens stay with the auth provider. A connected account's tokens are the CRM's to keep, so they are sealed by the vault: by default with CipherStash ( @cipherstash/stack) inside the app before they are written to the integrations table, each value under its own key from ZeroKMS. The database only holds ciphertext, so a database dump or a leaked backup cannot be used to read anyone's mail. There is no plaintext fallback. Without its keys the vault refuses to store anything and the page says more accounts can't be connected yet. The code is in packages/spools/src/server/runtime/vault.ts. Each connection's tokens are sealed for the row they are stored on. For a connection of one's own that is its teammate, the provider and the account. For a shared connection it is the provider, the account, and that it is the team's or which group's. Tokens copied onto another row, or a row edited in the database to turn a personal connection into a shared one or to move it to another group, are refused. Disconnecting deletes the stored copy, and asks the provider to revoke the token where it offers that. There is one case where it does not ask: when another connection holds the same account at the same OAuth client (a teammate's own beside the team's, two people who each connected one shared inbox, a Google mailbox and Google Ads on one Google account). At many providers revoking one token ends every token that account gave the client, which would stop the other connection without a word. The server logs that it left the grant in place. The last connection to an account is revoked as it goes. Setup The sign-in mailbox needs none of this. To let teammates connect more accounts: 1. The vault The vault is CipherStash ( vault: cipherstash()). Create a workspace and an access key, then set: A production server does not start without them. On your own machine a stand-in seals until they are set, which is enough to try connecting an account and protects nothing. APP_URL (the public address of the app) and APP_SECRET (32+ characters; signs the OAuth state) must be set too. 2. Google In the Google Cloud console, create an OAuth client of type Web application. It can be the same client your Clerk connection uses, with one more redirect URI. Authorised redirect URI: {APP_URL}/api/integrations/google/callback Enable the Gmail API and the Google Calendar API for the project. OAuth consent screen: for a Google Workspace organisation choose Internal, which needs no review by Google. An External app that asks for Gmail scopes must pass Google's verification before people outside your test-user list can connect. 3. Microsoft In Microsoft Entra, register an application with a Web platform (or add the redirect URI to the one your Clerk connection uses): Redirect URI: {APP_URL}/api/integrations/microsoft/callback API permissions (delegated): openid, email, offline_access, User.Read, Mail.Read, Calendars.Read, Mail.Send. Some tenants require an administrator to consent. Create a client secret. A provider is offered once its client id and secret are set; you can set up one and not the other. The server logs which parts are on at start-up. How connecting works Connect opens /api/integrations//connect (with ?group= for a provider shared by group). It checks the CRM session and, for a shared provider, that the group is one the provider lists and that this person may manage the connection. It sets a ten-minute, HttpOnly cookie holding a nonce and a PKCE verifier, and redirects to the provider with a signed state that names the teammate and, for a shared connection, whose it will be: the team's, or which group's. The provider returns to /api/integrations//callback. The callback is accepted only if the state signature is valid and unexpired, it names the signed-in teammate, and the cookie's nonce matches: so it only completes in the browser that started it. Whose the connection is comes from the signed state and nothing else in the callback's address. It is then checked against what the provider says now, so a state made for a personal connection can't make a shared one, one made for a group can't be used for another, and a person who stopped being allowed to manage the connection in the meantime is refused. The code is exchanged for tokens (with the PKCE verifier), the provider is asked which account the new token is for, the tokens are encrypted and the row is written. Connecting the same account again replaces its tokens. The write checks and changes in one step, so two callbacks for the same account can't leave two rows. getAccessToken(connectionId, { as }) (from @swirls/spools/extensions) returns a valid access token, refreshing it when it is about to expire. as is the person the call is for: the token is then only given if they are on the access list and the connection is theirs or is shared. Someone taken off the access list gets no token, not even for a connection of their own. When as names nobody ( ctx.actor is null in a handler an automation ran), the call is refused. Code nobody is behind, such as a schedule, says so by leaving the second argument out: getAccessToken(connectionId). If the provider turns the refresh down (the person revoked access, or a password change invalidated it), the connection shows \"Needs reconnecting\" and is left alone until it is connected again. A provider that is merely unavailable is tried again later. A token renewed while its connection was being connected again, or handed to the team, is thrown away and the new one is used. One renewal runs at a time for a connection, and it runs to its end (or to the provider's time limit) even when the request that asked for it goes away, so a teammate closing a tab never leaves a connection half renewed. Add a provider Anything that speaks OAuth 2 with the authorization-code flow can be added in integrations in src/app/extensions.ts. The framework shows it on the page, runs the flow, encrypts and refreshes the tokens. Your code decides what to do with them. Register {APP_URL}/api/integrations//callback as the redirect URI with the provider. The provider must issue a refresh token; a connection without one is refused. For a provider that only gives a long-lived access token, set refreshToken: 'optional': the connection then works until that token runs out, and shows \"Needs reconnecting\" after. An id is lower-case letters, digits, - or _. google and microsoft are taken. A provider with a bad id is left out, with a warning at start-up. account must ask the provider. get calls the provider's API with the token it just issued, so its answer is about the account that was really authorized. The callback's query string ( query) is not: it came through the browser, and whoever is connecting can change it before it reaches the CRM. Some providers name the account only there (a companyId or realmId parameter). Use that value to know what to ask for, and let the provider confirm it: This matters most for a shared provider. Connecting an account that is already connected for the team replaces the team's tokens, and the account's name is how that connection is found. If the name came from the address, a teammate could authorize a company of their own, change companyId to the team's, and leave the team's connection holding their tokens: every invoice after that would go to the wrong company. So a shared connection is refused unless its account got an answer from the provider through get. The CRM can't check what you asked, so ask for something only the right account can answer. findConnections and getAccessToken are for server code. Never return a token, or another teammate's connection, to the browser. A provider's type is IntegrationProvider, from @swirls/spools/extensions, if you build yours with a function. Share a provider with the team Add shared to the provider and its connections belong to the team, or to a group of it, instead of to whoever connected them. Option What it does shared 'team': a connection is everyone's on the access list. 'group': it is one group's, chosen when connecting. Left out: it is the teammate's who connected it groups For 'group': what a connection can be made for. { key, label } entries (or keys alone), or a function that returns them. A key is at most 100 characters, with no control characters canManage Who may connect, reconnect and disconnect: a list of email addresses, or (user, { group }) => boolean (it may be async; if it throws, nobody may). Left out: anyone on the access list adoptExisting For 'team', when connections to this provider were already used by everyone before you added shared (as marketing accounts were): the ones made before count as the team's without being reconnected What your code can ask for: Call Returns findConnections({ provider, shared: 'team' }) The team's connections findConnections({ provider, group: 'north' }) That group's connections, and no other group's findConnections({ provider, shared: 'group' }) Every group's findConnections({ provider, userId }) That teammate's own. Never a shared one, whoever connected it findConnections({ provider }) Every connection to the provider, whoever's any of them with usableBy: ctx.actor Only the ones that person may use. None when there is no actor getAccessToken(connection.id, { as: ctx.actor }) A token, or a refusal when that person may not use it, or when there is no actor getAccessToken(connection.id) A token, for code nobody is behind (a schedule, a webhook) A connection says whose it is: shared ( 'team', 'group' or null), group, and connectedBy, the name of whoever connected a shared one ( null for one made before names were kept). userId is who connected it. Pass usableBy and as whenever a person caused the call. ctx.actor is null when nobody did (an automation, a script, an import). Passing that null does not make the call trusted: getAccessToken refuses and findConnections finds nothing, because nobody may use nothing. If a handler really should act for the business when no one is signed in, write that out, so it can be seen in the code: A provider whose declaration contradicts itself ( groups without shared: 'group', canManage without shared) is left out, with a warning at start-up. The built-in Google and Microsoft mailboxes are always each person's own. Troubleshooting What you see What it means \"More accounts can't be connected yet\" The list under it names what is missing: APP_URL, APP_SECRET or the CS_* variables \"… hasn't been set up for this CRM yet\" That provider's client id and secret are not set \"That sign-in link expired or was opened in another browser\" The consent screen was left open for more than ten minutes, or finished in a different browser. Connect again \"… didn't grant ongoing access\" The provider sent no refresh token. Remove the CRM from the account's connected apps, then connect again \"Needs reconnecting\" The provider turned the stored grant down. Reconnect and pick the same account \"The CRM already reaches this mailbox through your sign-in\" The connection duplicates the sign-in account and is not used. Disconnect it, or leave it \"Only the people who manage … for this CRM can connect it\" The provider has canManage and it doesn't name you. Ask someone it does \"Who … is connected for changed while you were connecting\" The provider's shared setting was changed while the consent screen was open. Connect again \"Yours alone: it was connected before … was shared\" You connected it before the provider was shared. Connect the account again under Shared with the team \"… which account it is was not confirmed with …\" A shared provider's account took the name from the callback's address without asking the provider. Make it call get (see Add a provider) \"Could not read the … account\" The provider refused the question account asked with the new token: the account named in the address is not the one that was authorized, or the scopes don't cover it \"That account can only be used for someone signed in\" A handler passed as: ctx.actor and nobody was signed in (an automation ran it). Decide in the handler what should happen then" }, { "path": "/docs/marketing", @@ -952,6 +1020,11 @@ "title": "What ships", "level": 2 }, + { + "id": "the-vault-is-cipherstash", + "title": "The vault is CipherStash", + "level": 3 + }, { "id": "changing-one", "title": "Changing one", @@ -1008,7 +1081,7 @@ "level": 2 } ], - "text": "Adapters A Spool runs on services you choose. Each kind of service has a port, a small contract the framework asks for, and one or more adapters that provide it. You choose them in src/spool.server.ts: When the server starts it logs which adapters it uses and what each still needs ( [env] Campaign email (Resend): off (set RESEND_API_KEY, EMAIL_FROM)). A variable an adapter can't do without stops a production server from starting. What ships Port Import Needs Auth @swirls/spools/auth/clerk CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY, @clerk/tanstack-react-start @swirls/spools/auth/better-auth BETTER_AUTH_SECRET, APP_URL, better-auth. See Signing in @swirls/spools/auth/dev Nothing. Refuses to run in production Database @swirls/spools/database/postgres DATABASE_URL, @effect/sql-pg. See Database @swirls/spools/database/pglite Nothing but @effect/sql-pglite @swirls/spools/database/prisma DATABASE_URL, @prisma/orm-postgres Files @swirls/spools/files/drive A Blobs: localBlobs() or s3Blobs(). See Files @swirls/spools/files/flashdrive FLASHDRIVE_API_KEY, FLASHDRIVE_DRIVE_ID Email @swirls/spools/email/resend RESEND_API_KEY, EMAIL_FROM, resend Vault @swirls/spools/vault/cipherstash The CS_* variables, @cipherstash/stack @swirls/spools/vault/aes VAULT_KEY ( openssl rand -base64 32) Agents @swirls/spools/agents/swirls SWIRLS_PROJECT_ID. See Swirls Rate limits @swirls/spools/rate-limits/memory Nothing. The default: counts per server instance @swirls/spools/rate-limits/store The rate_limit_slots table. Counts the same on every instance The packages named here are optional peer dependencies: install the ones your adapters use. Changing one Change its line in src/spool.server.ts. Auth also has a browser half, listed in src/spool.ui.ts; the page uses the one whose id matches the server's and says so if there is none. Three things to know before changing one on a Spool with data in it: Auth. Records keep the user ids of whoever made and owns them, and those ids are the auth provider's. A new provider means new ids: owners and \"created by\" will not match until they are mapped over. Vault. A vault can only open what it sealed. Change it and people reconnect their accounts on the Integrations page, and what your app sealed with sealText must be sealed again. Your app's own secrets The vault also seals text your app stores (a gate code, a site's alarm number), through @swirls/spools/extensions: Owner. Name where the value is kept (1 to 500 characters): it is sealed with the text, and opening it for any other owner is refused, so a value copied onto another row doesn't open there. An app's owners are kept apart from the framework's (sealed as app:): no app value opens as a teammate's tokens or a kept answer, nor the other way round. Never in the clear. Without a vault sealText fails, and vaultProblem() says why. openText takes only what sealText sealed for that owner: text stored in the clear, or a value sealed for another owner, is refused. Files. Each record remembers which store its folder is in, so it gets a new, empty folder in the new store. Nothing is copied. Changing the database adapter between postgres and prisma is safe: they read and write the same tables. Rate limits Your own endpoints count requests through the RateLimiter port ( packages/spools/src/server/runtime/rate-limit.ts, and hitLimit, peekLimit and consumeLimit in @swirls/spools/extensions, Extending): hit counts one when a key is under its limit in a sliding window, wait says how long until it would be, record counts one regardless (a failed sign-in check), and consume counts an amount against a quota in a fixed window (a UTC day, a minute on the minute): all of it when it fits, nothing when it doesn't, in one step. rateLimits in defineSpool chooses where: storeRateLimits() adds the rate_limit_slots table: run bun run crm:gen and bun run db:push (or plan a migration) after choosing it. memoryRateLimits() (the default) keeps counts in this server's memory. Each instance has its own, so N instances allow up to N times each limit, and a restart forgets. A bucket keeps at most 10,000 keys: past that the key idle longest is dropped, and its count with it. So memory stays bounded under a flood of new keys (addresses, made-up tokens), and a key dropped that way starts again from nothing: someone who can send from more than 10,000 addresses a minute can outrun the failed-check limit on one instance. Use storeRateLimits() where that matters. storeRateLimits() keeps them in the Spool's database: each key has as many slots as its limit, each taken by an update that checks and changes in one step, so no instance can let more through than the limit. It is a write or two a request (the rateLimits policy: three seconds, never retried), and relies on the instances' clocks agreeing. A bucket holds at most rowsPerBucket slots inside its window (200,000 unless storeRateLimits({ rowsPerBucket }) says): past that a hit that needs a new slot is refused and a failure is not counted, so a flood of new keys can't grow the table without bound. Slots that have left the window are removed by a new slot's hit, at most once a second per bucket on each instance, so a burst of new keys doesn't queue behind the same delete. A quota ( consume) is one row per key and window, changed by an update that names the count it read, and is not held to the cap. Tests use RateLimiter.layerTest ( @swirls/spools/testing). A limiter of your own (Redis, a KV store) is an adapter like any other. Token checks An auth adapter may check tokens your own front end forwards ( verifyToken in @swirls/spools/extensions): give it tokens, a layer of the Tokens port ( verify(token, { authorizedParties }), a user id or null, never a failure). Its cost must be bounded whatever a stranger sends: check locally, never call out per token. See Building your own door. Write your own An adapter is an object with an id, a label and a layer that provides the port. Everything you need is in @swirls/spools/adapter. An email provider examples/postmark.ts: If all you want is to send email another way, email.send in src/app/extensions.ts takes a plain async function and no Effect ( Extending). A database A store answers a small set of questions about tables: find, count, insert, update, remove, plus running a program as one transaction. Implement Backend and wrap it with makeStore, which adds the time limits and typed failures every store has. For anything that speaks Postgres SQL, sqlBackend does all of it and you supply two things: a function that runs a statement, and one that runs a program as a transaction. callbackTransaction makes the second from a driver whose own transaction takes a callback: examples/bun-postgres.ts: Four promises are easy to break: update checks and changes in one step, and says how many rows it changed. Sequences rely on it so that two servers never send the same email. A transaction keeps everything or nothing. Every statement a program runs inside store.transaction must go to the transaction's connection, not the pool's, and a failure or an interruption must undo it. A record and its timeline rely on it. Values come back as the table describes them: money and days as strings, moments as Date. Columns are read in terms of the table, never of the driver. find with perGroup cuts each group down in the database. The query a backend is handed has perGroup: { by, limit } when the caller wants no more than limit rows for each value of the column by: the first of each group in the query's order, taken after the conditions and before limit and offset ( Database). sqlBackend does it. A backend you write yourself has to. On Postgres, selectSql(table, query) writes the statement (a window function), rowsOf(table, rows) reads what your driver gives back for it, and findWith makes a find of the two, included records and all: the Prisma adapter reads its groups that way and everything else through the ORM. Never read every row and cut in JavaScript, because the rows left out are the reason it is asked for: a tag may be on thirty thousand contacts. A store whose backend gives back more rows for a group than the limit stops with an error that says so. Under record scopes A Spool with record scopes puts every store behind a guard ( store/scope.ts). makeStore does it, so a store you build with makeStore or sqlBackend has it, and your backend is only ever handed queries the guard has already narrowed. Never hand your backend, or anything it is made of ( sqlBackend, findWith, rowsOf, a selectSql statement you run yourself), to code outside the adapter: the framework's own code may not import them, and a test fails if it does. What the guard relies on your backend for: Conditions through relations, both ways and nested. some and none over a relation held on this table ( one) and over one that points back ( many), with a condition inside that may itself hold another. A links table is narrowed through its two relations to the records it joins, inside the condition on an object's links. An order by a related record under a condition ( { related, where }): a row whose related record doesn't meet it sorts as a row with none ( Database). Write the condition, or refuse the order. perGroup after the conditions. The scope is in the conditions. A backend that numbers the rows of each group first and applies the conditions afterwards gives a person the gaps left by rows they can't reach, and one that ignores perGroup is stopped by the store. countValues under the same conditions, which is where a count of links comes from. lock is a real row lock, taken in the order of primary keys, and held until the transaction ends. The guard holds a record while it checks what points at it. A transaction inside another is part of the outer one. The guard wraps a check and its write in one, inside whatever the caller had open. A backend built on sqlBackend does all of it. Run the integration tests on yours ( TEST_STORE): the scope tests run every one of these against the store they are given. Tables of its own An adapter may keep tables in the Spool's database. Describe them with the table definitions the framework uses, list them in tables, and they are created and migrated with the rest ( bun run crm:gen): Its layer may ask for the Store. Don't make tables depend on the environment, or the schema would differ between your machine and production. Check it In a clone of the repository, run the framework's own tests on your adapter. packages/spools/tests/unit/store.test.ts is what a store promises, and TEST_STORE in packages/spools/tests/support/preload.ts puts one under the whole server: How it fits together The framework ( packages/spools/src/crm, src/server, src/pages) never imports an adapter, a vendor's SDK or your app; lint refuses it. It asks for a port ( yield* Store), and the one Effect runtime per process is built from the Spool's adapters ( packages/spools/src/server/runtime/app.ts). Tests build the same runtime with stand-ins." + "text": "Adapters A Spool runs on services you choose. Each kind of service has a port, a small contract the framework asks for, and one or more adapters that provide it. You choose them in src/spool.server.ts: When the server starts it logs which adapters it uses and what each still needs ( [env] Campaign email (Resend): off (set RESEND_API_KEY, EMAIL_FROM)). A variable an adapter can't do without stops a production server from starting. What ships Port Import Needs Auth @swirls/spools/auth/clerk CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY, @clerk/tanstack-react-start @swirls/spools/auth/better-auth BETTER_AUTH_SECRET, APP_URL, better-auth. See Signing in @swirls/spools/auth/dev Nothing. Refuses to run in production Database @swirls/spools/database/postgres DATABASE_URL, @effect/sql-pg. See Database @swirls/spools/database/pglite Nothing but @effect/sql-pglite @swirls/spools/database/prisma DATABASE_URL, @prisma/orm-postgres Files @swirls/spools/files/drive A Blobs: localBlobs() or s3Blobs(). See Files @swirls/spools/files/flashdrive FLASHDRIVE_API_KEY, FLASHDRIVE_DRIVE_ID Email @swirls/spools/email/resend RESEND_API_KEY, EMAIL_FROM, resend Vault @swirls/spools/vault/cipherstash The CS_* variables, @cipherstash/stack. See below Agents @swirls/spools/agents/swirls SWIRLS_PROJECT_ID. See Swirls Rate limits @swirls/spools/rate-limits/memory Nothing. The default: counts per server instance @swirls/spools/rate-limits/store The rate_limit_slots table. Counts the same on every instance The packages named here are optional peer dependencies: install the ones your adapters use. The vault is CipherStash Everything a Spool keeps that must stay secret is sealed by the vault before it reaches the database: the tokens of accounts teammates connect, the seal of an API key, an answer kept for a repeated request, and whatever your own code seals with sealText. There is one vault, CipherStash, which gives each value a key of its own and keeps the root of them outside your database and your server's environment. A production server does not start without the four CS_* variables. On your own machine and in tests, where they are not set, a stand-in seals instead, with a key that is in the framework's source. It protects nothing and the server says so when it starts ( [env] Encryption of stored secrets (CipherStash):...). What the stand-in sealed is not opened by a server with CipherStash, so nothing sealed on a laptop is trusted in production. Changing one Change its line in src/spool.server.ts. Auth also has a browser half, listed in src/spool.ui.ts; the page uses the one whose id matches the server's and says so if there is none. Three things to know before changing one on a Spool with data in it: Auth. Records keep the user ids of whoever made and owns them, and those ids are the auth provider's. A new provider means new ids: owners and \"created by\" will not match until they are mapped over. Vault. A vault can only open what it sealed. Change it and people reconnect their accounts on the Integrations page, and what your app sealed with sealText must be sealed again. Your app's own secrets The vault also seals text your app stores (a gate code, a site's alarm number), through @swirls/spools/extensions: Owner. Name where the value is kept (1 to 500 characters): it is sealed with the text, and opening it for any other owner is refused, so a value copied onto another row doesn't open there. An app's owners are kept apart from the framework's (sealed as app:): no app value opens as a teammate's tokens or a kept answer, nor the other way round. Never in the clear. Without a vault sealText fails, and vaultProblem() says why. openText takes only what sealText sealed for that owner: text stored in the clear, or a value sealed for another owner, is refused. Files. Each record remembers which store its folder is in, so it gets a new, empty folder in the new store. Nothing is copied. Changing the database adapter between postgres and prisma is safe: they read and write the same tables. Rate limits Your own endpoints count requests through the RateLimiter port ( packages/spools/src/server/runtime/rate-limit.ts, and hitLimit, peekLimit and consumeLimit in @swirls/spools/extensions, Extending): hit counts one when a key is under its limit in a sliding window, wait says how long until it would be, record counts one regardless (a failed sign-in check), and consume counts an amount against a quota in a fixed window (a UTC day, a minute on the minute): all of it when it fits, nothing when it doesn't, in one step. rateLimits in defineSpool chooses where: storeRateLimits() adds the rate_limit_slots table: run bun run crm:gen and bun run db:push (or plan a migration) after choosing it. memoryRateLimits() (the default) keeps counts in this server's memory. Each instance has its own, so N instances allow up to N times each limit, and a restart forgets. A bucket keeps at most 10,000 keys: past that the key idle longest is dropped, and its count with it. So memory stays bounded under a flood of new keys (addresses, made-up tokens), and a key dropped that way starts again from nothing: someone who can send from more than 10,000 addresses a minute can outrun the failed-check limit on one instance. Use storeRateLimits() where that matters. storeRateLimits() keeps them in the Spool's database: each key has as many slots as its limit, each taken by an update that checks and changes in one step, so no instance can let more through than the limit. It is a write or two a request (the rateLimits policy: three seconds, never retried), and relies on the instances' clocks agreeing. A bucket holds at most rowsPerBucket slots inside its window (200,000 unless storeRateLimits({ rowsPerBucket }) says): past that a hit that needs a new slot is refused and a failure is not counted, so a flood of new keys can't grow the table without bound. Slots that have left the window are removed by a new slot's hit, at most once a second per bucket on each instance, so a burst of new keys doesn't queue behind the same delete. A quota ( consume) is one row per key and window, changed by an update that names the count it read, and is not held to the cap. Tests use RateLimiter.layerTest ( @swirls/spools/testing). A limiter of your own (Redis, a KV store) is an adapter like any other. Token checks An auth adapter may check tokens your own front end forwards ( verifyToken in @swirls/spools/extensions): give it tokens, a layer of the Tokens port ( verify(token, { authorizedParties }), a user id or null, never a failure). Its cost must be bounded whatever a stranger sends: check locally, never call out per token. See Building your own door. Write your own An adapter is an object with an id, a label and a layer that provides the port. Everything you need is in @swirls/spools/adapter. An email provider examples/postmark.ts: If all you want is to send email another way, email.send in src/app/extensions.ts takes a plain async function and no Effect ( Extending). A database A store answers a small set of questions about tables: find, count, insert, update, remove, plus running a program as one transaction. Implement Backend and wrap it with makeStore, which adds the time limits and typed failures every store has. For anything that speaks Postgres SQL, sqlBackend does all of it and you supply two things: a function that runs a statement, and one that runs a program as a transaction. callbackTransaction makes the second from a driver whose own transaction takes a callback: examples/bun-postgres.ts: Four promises are easy to break: update checks and changes in one step, and says how many rows it changed. Sequences rely on it so that two servers never send the same email. A transaction keeps everything or nothing. Every statement a program runs inside store.transaction must go to the transaction's connection, not the pool's, and a failure or an interruption must undo it. A record and its timeline rely on it. Values come back as the table describes them: money and days as strings, moments as Date. Columns are read in terms of the table, never of the driver. find with perGroup cuts each group down in the database. The query a backend is handed has perGroup: { by, limit } when the caller wants no more than limit rows for each value of the column by: the first of each group in the query's order, taken after the conditions and before limit and offset ( Database). sqlBackend does it. A backend you write yourself has to. On Postgres, selectSql(table, query) writes the statement (a window function), rowsOf(table, rows) reads what your driver gives back for it, and findWith makes a find of the two, included records and all: the Prisma adapter reads its groups that way and everything else through the ORM. Never read every row and cut in JavaScript, because the rows left out are the reason it is asked for: a tag may be on thirty thousand contacts. A store whose backend gives back more rows for a group than the limit stops with an error that says so. Under record scopes A Spool with record scopes puts every store behind a guard ( store/scope.ts). makeStore does it, so a store you build with makeStore or sqlBackend has it, and your backend is only ever handed queries the guard has already narrowed. Never hand your backend, or anything it is made of ( sqlBackend, findWith, rowsOf, a selectSql statement you run yourself), to code outside the adapter: the framework's own code may not import them, and a test fails if it does. What the guard relies on your backend for: Conditions through relations, both ways and nested. some and none over a relation held on this table ( one) and over one that points back ( many), with a condition inside that may itself hold another. A links table is narrowed through its two relations to the records it joins, inside the condition on an object's links. An order by a related record under a condition ( { related, where }): a row whose related record doesn't meet it sorts as a row with none ( Database). Write the condition, or refuse the order. perGroup after the conditions. The scope is in the conditions. A backend that numbers the rows of each group first and applies the conditions afterwards gives a person the gaps left by rows they can't reach, and one that ignores perGroup is stopped by the store. countValues under the same conditions, which is where a count of links comes from. lock is a real row lock, taken in the order of primary keys, and held until the transaction ends. The guard holds a record while it checks what points at it. A transaction inside another is part of the outer one. The guard wraps a check and its write in one, inside whatever the caller had open. A backend built on sqlBackend does all of it. Run the integration tests on yours ( TEST_STORE): the scope tests run every one of these against the store they are given. Tables of its own An adapter may keep tables in the Spool's database. Describe them with the table definitions the framework uses, list them in tables, and they are created and migrated with the rest ( bun run crm:gen): Its layer may ask for the Store. Don't make tables depend on the environment, or the schema would differ between your machine and production. Check it In a clone of the repository, run the framework's own tests on your adapter. packages/spools/tests/unit/store.test.ts is what a store promises, and TEST_STORE in packages/spools/tests/support/preload.ts puts one under the whole server: How it fits together The framework ( packages/spools/src/crm, src/server, src/pages) never imports an adapter, a vendor's SDK or your app; lint refuses it. It asks for a port ( yield* Store), and the one Effect runtime per process is built from the Spool's adapters ( packages/spools/src/server/runtime/app.ts). Tests build the same runtime with stand-ins." }, { "path": "/docs/auth", @@ -1051,7 +1124,7 @@ "level": 2 } ], - "text": "Signing in Two separate things decide who gets into a Spool. The auth adapter says who someone is. You choose it in src/spool.server.ts, and its browser half in src/spool.ui.ts. The access list in crm.config.json says whether they may come in. It compares their email address, and only one the auth provider has verified as theirs, with access.allowedEmails and access.allowedDomains. Anyone else who signs in sees a page saying they have no access. Answers are kept for a minute, so taking someone off the list (or out of the provider) takes effect within one. Adapter When clerk() You want sign-in run for you betterAuth() You want it in your own database, with no outside service devAuth() Development, tests and demos. Refuses to run in production Clerk Set CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY, and install @clerk/tanstack-react-start. Under Restrictions in the Clerk dashboard, limit sign-ups to your team; the access list is checked either way. Clerk holds the Google and Microsoft tokens of the accounts people sign in with, which is how their mail and calendar are read. It can also make the token that signs each person in to Swirls without an API key. Clerk can also say who holds which role: clerk({ roles: 'metadata' }) reads a user's public metadata, and clerk({ roles: { organization: 'org_...' } }) their role in one organization. Better Auth Better Auth runs inside your server and keeps its users, sessions and accounts in your own database. People sign in with a link sent to their address, or with Google or Microsoft. There are no passwords. Only someone on the access list is sent a link or gets an account. Install better-auth, then run bun run crm:gen and bun run db:push to create its four tables ( auth_users, auth_sessions, auth_accounts, auth_verifications). PGlite creates them itself. Variable BETTER_AUTH_SECRET Required in production: 32 or more characters ( openssl rand -base64 32). It signs session cookies and encrypts stored Google and Microsoft tokens. Changing it signs everyone out, and people reconnect their accounts APP_URL Required in production: the app's public address. People must open the app there, or signing in is refused. Cookies are marked secure when it is https GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET Adds Google. Redirect URI: /api/auth/callback/google MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET Adds Microsoft. Redirect URI: /api/auth/callback/microsoft MICROSOFT_TENANT_ID The one organization whose people may sign in. See below TRUST_PROXY How many proxies are in front of the server, so that rate limits count the right visitor In development all of them may be missing: the address is http://localhost:3000, and everyone is signed out when the server restarts. Links by email need an email provider in production ( RESEND_API_KEY and EMAIL_FROM, or another email adapter). In development the link is written to the log. A link works once, for ten minutes. Opening it shows a page with one button, because mail filters open links to check them and would otherwise use it up. The answer to asking for a link is the same, and takes the same time, whether or not the address is on the access list. Microsoft lets any organization put any address in its own people's profiles, so an address counts only when Microsoft says who owns it. Either set MICROSOFT_TENANT_ID to your own organization, whose word is then taken, or add the xms_edov or verified_primary_email optional claim to the ID token in the app's registration. Without one or the other, signing in with Microsoft always fails. Mail and calendar. \"Open profile\" in the mailbox panel asks Google or Microsoft for the mailbox scopes. The account must have the address the person signs in with. If you use the Integrations page too, keep its redirect URIs ( /api/integrations//callback) on the same client. Swirls needs SWIRLS_API_KEY, because Better Auth gives no identity token that Swirls could check. Removing someone. Take them off the access list. Their row in auth_users stays and opens nothing. Sessions last thirty days from signing in, and signing out takes effect at once. Status: tested against stand-ins for Google and Microsoft, and by hand in a browser with links by email. It has not been run against live Google or Microsoft accounts. The development sign-in devAuth() signs every request in as one person: whoever DEV_AUTH_EMAIL names, or the first address the access list lets in. DEV_AUTH_SIGNED_OUT=1 shows the app signed out. A new Spool uses it until you set a real provider's keys. It refuses to run with NODE_ENV=production, and a production build leaves it out. Record scopes With scopes in the config, something has to say which scopes each person holds. Clerk organizations. clerk({ scopes: 'organizations', scopesFrom: ['org_...'] }): a person holds the scope of each organization named in scopesFrom that they belong to, with their role in it. The scope is the organization's id (so org_2abc... is what a record's scope field holds; for a select field, make each option's value an organization's id and its label the name people know it by) and the role is the membership's without Clerk's prefix: org:member is member in scopes.roles. The organization active in the session is the scope the person works in; switching with Clerk's own switcher switches the CRM. Every membership and every organization is read, however many there are. Not run against a live Clerk account yet: the mapping and the paging are tested against a stand-in for Clerk's API. Say which organizations are scopes, and where head office is. In Clerk, unless you have turned it off, anyone can create an organization. Whoever does is its admin, can give anyone any role in it, and Clerk's built-in org:admin is held by whoever runs any organization at all. An organization like that holds no records, but if it counted as a scope its maker would \"write a scope\", and whoever writes a scope may change what is shared: shared objects' records, shared views, the file library, Marketing, the team's connections. So nothing is taken on an organization's word. You name the organizations that are scopes, and the ones a role marked all counts from, by id: A membership in an organization that is not in scopesFrom gives nothing, whatever its role, and that organization is never listed as a scope or accepted as a record's. Without scopesFrom no organization is a scope and nobody holds one, and the server says so when it starts ( [env] Which Clerk organizations are record scopes: no organization is a scope...). A role marked all held anywhere but an organization in everyScopeFrom gives nothing either: not every scope, and not that organization's own. Without everyScopeFrom nobody reaches every scope, and the server says that too. Head office's organization is a scope of its own only if it is in scopesFrom as well. Adding a branch is adding its organization's id to scopesFrom and deploying. Turning organization creation by users off in the Clerk dashboard is still worth doing, so the list of organizations stays yours, but the CRM does not depend on it. Why the id and not the slug. A slug reads better in a config, but it is not Clerk's to keep: an organization's administrators can rename it, and a slug let go of (by a rename, or by deleting the organization) can be taken by another organization. Scopes keyed by slug would hand one group's records to whoever took its slug. An id is never given out twice. If you already hold records whose scope field has slugs in it, change them to the ids before you turn this on. Development. devAuth({ scopes: { list, grants } }), by email address: Better Auth, or anything else. A resolver of your own, in src/app/extensions.ts. What a person holds is kept for a minute, as the access list is, so the provider is not asked on every click. Taking a scope away from someone takes effect within that minute. Switching the scope you work in is not kept: it applies to the next request. Tokens from your own front end A front end of your own for people who are not teammates forwards each person's sign-in token ( Building your own door). Checking it is an optional capability of an auth adapter ( tokens on the adapter, the Tokens port in packages/spools/src/server/runtime/tokens.ts), behind verifyToken(token, { authorizedParties }) in @swirls/spools/extensions: the user id it was issued to, or null, never a failure. Without it every token is null. Adapter Tokens clerk() A session token of the same Clerk instance, issued to one of the origins you name ( azp), checked with Clerk's authenticateRequest on a request that carries only the bearer header. CLERK_JWT_KEY lets it check offline; without it a token naming a key the instance doesn't have is refused before Clerk is asked, and the keys are fetched at most once a minute devAuth() The tokens of outsiders: [{ id, name, email, token }], people the directory knows who are never on the team list. Origins are not checked betterAuth() None. Its session tokens are the session cookie's value, with no audience: a teammate's token from the CRM itself would count, and nothing ties one to your front end. verifyToken gets null for every token A session cookie sent with such a request counts for nothing: only the bearer token is checked. Your own An auth adapter has a server half (a directory of people, the session of a request, and optionally middleware and endpoints under /api/auth) and a browser half (the sign-in form, the account button, signing out). Both contracts are short: packages/spools/src/server/runtime/auth.ts and packages/spools/src/crm/ui/auth.tsx. The one rule that matters is that AuthUser.email is an address the provider has verified, or null. The access list trusts it. Changing provider Records keep the user ids of their owners and of whoever made them, and the ids are the provider's. Moving to another provider gives everyone a new id, so owners, assignees, favourites and \"created by\" won't match until they are mapped across. Plan that before you switch a Spool people use." + "text": "Signing in Two separate things decide who gets into a Spool. The auth adapter says who someone is. You choose it in src/spool.server.ts, and its browser half in src/spool.ui.ts. The access list in crm.config.json says whether they may come in. It compares their email address, and only one the auth provider has verified as theirs, with access.allowedEmails and access.allowedDomains. Anyone else who signs in sees a page saying they have no access. Answers are kept for a minute, so taking someone off the list (or out of the provider) takes effect within one. Adapter When clerk() You want sign-in run for you betterAuth() You want it in your own database, with no outside service devAuth() Development, tests and demos. Refuses to run in production Clerk Set CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY, and install @clerk/tanstack-react-start. Under Restrictions in the Clerk dashboard, limit sign-ups to your team; the access list is checked either way. A headless Spool imports clerk from @swirls/spools/auth/clerk/backend and installs @clerk/backend instead: the same adapter, reading the session from the request itself, with no TanStack Start and no browser half. Both adapters take a session only from your own front end. On TanStack Start, Clerk's middleware is told the origin of APP_URL on a production server (or the origins in clerk({ authorizedParties: [...] }), in any mode), so a session token Clerk issued to another app on the same instance is nobody. The headless adapter takes a session cookie only when Clerk issued it to your own front end: the origin of APP_URL, or the origins you name with clerk({ authorizedParties: [...] }) when the front end lives at another address. A production server that has neither takes no session, so a token made for another app on the same Clerk instance never opens the CRM. Clerk holds the Google and Microsoft tokens of the accounts people sign in with, which is how their mail and calendar are read. It can also make the token that signs each person in to Swirls without an API key. Clerk can also say who holds which role: clerk({ roles: 'metadata' }) reads a user's public metadata, and clerk({ roles: { organization: 'org_...' } }) their role in one organization. Better Auth Better Auth runs inside your server and keeps its users, sessions and accounts in your own database. People sign in with a link sent to their address, or with Google or Microsoft. There are no passwords. Only someone on the access list is sent a link or gets an account. Install better-auth, then run bun run crm:gen and bun run db:push to create its four tables ( auth_users, auth_sessions, auth_accounts, auth_verifications). PGlite creates them itself. Variable BETTER_AUTH_SECRET Required in production: 32 or more characters ( openssl rand -base64 32). It signs session cookies and encrypts stored Google and Microsoft tokens. Changing it signs everyone out, and people reconnect their accounts APP_URL Required in production: the app's public address. People must open the app there, or signing in is refused. Cookies are marked secure when it is https GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET Adds Google. Redirect URI: /api/auth/callback/google MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET Adds Microsoft. Redirect URI: /api/auth/callback/microsoft MICROSOFT_TENANT_ID The one organization whose people may sign in. See below TRUST_PROXY How many proxies are in front of the server, so that rate limits count the right visitor In development all of them may be missing: the address is http://localhost:3000, and everyone is signed out when the server restarts. Links by email need an email provider in production ( RESEND_API_KEY and EMAIL_FROM, or another email adapter). In development the link is written to the log. A link works once, for ten minutes. Opening it shows a page with one button, because mail filters open links to check them and would otherwise use it up. The answer to asking for a link is the same, and takes the same time, whether or not the address is on the access list. Microsoft lets any organization put any address in its own people's profiles, so an address counts only when Microsoft says who owns it. Either set MICROSOFT_TENANT_ID to your own organization, whose word is then taken, or add the xms_edov or verified_primary_email optional claim to the ID token in the app's registration. Without one or the other, signing in with Microsoft always fails. Mail and calendar. \"Open profile\" in the mailbox panel asks Google or Microsoft for the mailbox scopes. The account must have the address the person signs in with. If you use the Integrations page too, keep its redirect URIs ( /api/integrations//callback) on the same client. Swirls needs SWIRLS_API_KEY, because Better Auth gives no identity token that Swirls could check. Removing someone. Take them off the access list. Their row in auth_users stays and opens nothing. Sessions last thirty days from signing in, and signing out takes effect at once. Status: tested against stand-ins for Google and Microsoft, and by hand in a browser with links by email. It has not been run against live Google or Microsoft accounts. The development sign-in devAuth() signs every request in as one person: whoever DEV_AUTH_EMAIL names, or the first address the access list lets in. DEV_AUTH_SIGNED_OUT=1 shows the app signed out. A new Spool uses it until you set a real provider's keys. It refuses to run with NODE_ENV=production, and a production build leaves it out. Record scopes With scopes in the config, something has to say which scopes each person holds. Clerk organizations. clerk({ scopes: 'organizations', scopesFrom: ['org_...'] }): a person holds the scope of each organization named in scopesFrom that they belong to, with their role in it. The scope is the organization's id (so org_2abc... is what a record's scope field holds; for a select field, make each option's value an organization's id and its label the name people know it by) and the role is the membership's without Clerk's prefix: org:member is member in scopes.roles. The organization active in the session is the scope the person works in; switching with Clerk's own switcher switches the CRM. Every membership and every organization is read, however many there are. Not run against a live Clerk account yet: the mapping and the paging are tested against a stand-in for Clerk's API. Say which organizations are scopes, and where head office is. In Clerk, unless you have turned it off, anyone can create an organization. Whoever does is its admin, can give anyone any role in it, and Clerk's built-in org:admin is held by whoever runs any organization at all. An organization like that holds no records, but if it counted as a scope its maker would \"write a scope\", and whoever writes a scope may change what is shared: shared objects' records, shared views, the file library, Marketing, the team's connections. So nothing is taken on an organization's word. You name the organizations that are scopes, and the ones a role marked all counts from, by id: A membership in an organization that is not in scopesFrom gives nothing, whatever its role, and that organization is never listed as a scope or accepted as a record's. Without scopesFrom no organization is a scope and nobody holds one, and the server says so when it starts ( [env] Which Clerk organizations are record scopes: no organization is a scope...). A role marked all held anywhere but an organization in everyScopeFrom gives nothing either: not every scope, and not that organization's own. Without everyScopeFrom nobody reaches every scope, and the server says that too. Head office's organization is a scope of its own only if it is in scopesFrom as well. Adding a branch is adding its organization's id to scopesFrom and deploying. Turning organization creation by users off in the Clerk dashboard is still worth doing, so the list of organizations stays yours, but the CRM does not depend on it. Why the id and not the slug. A slug reads better in a config, but it is not Clerk's to keep: an organization's administrators can rename it, and a slug let go of (by a rename, or by deleting the organization) can be taken by another organization. Scopes keyed by slug would hand one group's records to whoever took its slug. An id is never given out twice. If you already hold records whose scope field has slugs in it, change them to the ids before you turn this on. Development. devAuth({ scopes: { list, grants } }), by email address: Better Auth, or anything else. A resolver of your own, in src/app/extensions.ts. What a person holds is kept for a minute, as the access list is, so the provider is not asked on every click. Taking a scope away from someone takes effect within that minute. Switching the scope you work in is not kept: it applies to the next request. Tokens from your own front end A front end of your own for people who are not teammates forwards each person's sign-in token ( Building your own door). Checking it is an optional capability of an auth adapter ( tokens on the adapter, the Tokens port in packages/spools/src/server/runtime/tokens.ts), behind verifyToken(token, { authorizedParties }) in @swirls/spools/extensions: the user id it was issued to, or null, never a failure. Without it every token is null. Adapter Tokens clerk() A session token of the same Clerk instance, issued to one of the origins you name ( azp), checked with Clerk's authenticateRequest on a request that carries only the bearer header. CLERK_JWT_KEY lets it check offline; without it a token naming a key the instance doesn't have is refused before Clerk is asked, and the keys are fetched at most once a minute devAuth() The tokens of outsiders: [{ id, name, email, token }], people the directory knows who are never on the team list. Origins are not checked betterAuth() None unless you ask: betterAuth({ bearer: true }) takes a session's own token, which the answer that signs someone in then carries in a set-auth-token header. It is the session, with no front end to name, so authorizedParties is not read: a token from the CRM's own pages would count. Its signature is checked before anything is read. Without bearer, verifyToken gets null for every token and an Authorization header is ignored A session cookie sent with such a request counts for nothing: only the bearer token is checked. Your own An auth adapter has a server half (a directory of people, the session of a request, and optionally middleware and endpoints under /api/auth) and a browser half (the sign-in form, the account button, signing out). Both contracts are short: packages/spools/src/server/runtime/auth.ts and packages/spools/src/crm/ui/auth.tsx. The one rule that matters is that AuthUser.email is an address the provider has verified, or null. The access list trusts it. Changing provider Records keep the user ids of their owners and of whoever made them, and the ids are the provider's. Moving to another provider gives everyone a new id, so owners, assignees, favourites and \"created by\" won't match until they are mapped across. Plan that before you switch a Spool people use." }, { "path": "/docs/database", @@ -1197,7 +1270,7 @@ "level": 2 } ], - "text": "Files The CRM has a file browser: folders, drag-and-drop upload, rename, move and search. What it keeps files in is an adapter you choose in src/spool.server.ts: Adapter Files are kept in drive({ blobs: s3Blobs() }) Any S3-compatible bucket, with the folders in the CRM's own database drive({ blobs: localBlobs() }) A disk on the server, with the folders in the CRM's own database flashdrive() A FlashDrive drive, which also mounts as a folder on macOS and Linux Without one, the Files pages say that files aren't set up. The Files page (in the sidebar, under Notes) browses the whole drive. A record's Files tab browses that record's own folder. Give an object a files section in crm.config.json and each of its records gets a folder. Status: tested against stand-ins for FlashDrive and S3, and against a real disk. None of them has been run against a live account yet. What you can do In either place: Open a folder, and climb back with the breadcrumbs or \"Up one folder\". Right-click an empty spot to add a folder or upload files. Right-click a folder or a file to open, rename, move up or delete it; a file's menu also copies its link. Every row also has a ⋯ button for the same menu and a delete button, shown when you point at it or select it. See who added each file and when. A file put in a FlashDrive drive some other way shows no name. Drag files in from your computer to upload them, onto the open folder or onto a folder in the list. Drag a file or folder onto another folder, or onto a breadcrumb, to move it. Switch between a list and a grid. The choice is remembered in the browser. With an item selected: Enter opens it, F2 renames it, Delete removes it. On the Files page, search file names across everything. The folder being shown on the Files page is in the address, so a folder can be linked to. A folder that is a record's own is marked \"Record\" and links to it. A folder per record A record's folder is made the first time its page is opened (or its folder is first asked for), at /: Companies/Acme. folders are made inside each record's folder when it is created. Use plain names: at most 60 characters, none of / \\: * ? \" < > |, no leading or trailing dot or space. under names a relation field. The record's folder is made inside the folder of the record that field points to: Companies/Acme/Website redesign. A record with that field empty gets a folder under its own object's name. Two records with the same name each get a folder; the second carries the first eight characters of its id. An object without files has no Files tab and no folders. The CRM remembers which folder is a record's by the store's id for it, not its path. So a record's folder can be renamed or moved in the drive and still opens from its record; renaming the record does not rename the folder. Deleting a record leaves its folder in the drive. Deleting a record's folder, in the CRM or in the drive, is allowed: the record gets a new, empty one the next time its page is opened. To lay the drive out differently, give your app a files.location in src/app/extensions.ts. It is asked once per record, when its folder is made: When one record hands over to another (a won deal becoming a job), give the new record the old one's folder with shareRecordFolder(from, to) from @swirls/spools/extensions: both then open the same folder. The library A folder at the top of the drive holds files that belong to the business rather than to one record: price lists, templates, forms. It is made the first time the Files page is opened, as \"Company files\". To rename it or give it folders, add files at the top level of crm.config.json: It is an ordinary folder: anything can be added to it, and more folders can be made beside it. files can't be used as an object key: it is the page's address. Setup: a drive of your own The folders, and the name and place of each file, are rows in the CRM's database ( file_nodes). The bytes are in the blob store. After choosing drive, run bun run crm:gen and, with DATABASE_URL set, bun run db:push so the table is there. Back up the database and the blob store together: either is little use without the other. A bucket: s3Blobs() Amazon S3, Cloudflare R2, Supabase Storage, MinIO, or anything else with the S3 API. Keep the bucket private. Files are opened by links the server signs, which last five minutes. The bucket's CORS rules must allow PUT with a content-type header from the CRM's address, because browsers send files straight to it. Upload links last fifteen minutes. A signed link can't hold the browser to a hash, so an upload is checked by its size. Settings can be passed as options, or read from variables with other names: s3Blobs({ env: { bucket: \"R2_BUCKET\" } }). Bun signs with AWS_SESSION_TOKEN when it is set, whatever key it is given. Where that belongs to another key, unset it. A disk: localBlobs() Files go in.data/files unless you name a folder. It suits one server with a disk that lasts: in Docker, mount a volume. It is refused on Vercel or another serverless host, which has no such disk. Uploads pass through the server, so its limit on the size of a request applies: 128 MB, which is Bun's own default ( maxRequestBodySize in server.prod.ts changes it). Size and SHA-256 are checked as the file is written, and a file appears only once all of it is there. Setup: FlashDrive The folders and files in the CRM are the drive's own, so the team can open the same ones in Finder, and whatever is put in the drive there shows up in the CRM. In the FlashDrive Console, create a drive for the CRM. Use a separate drive for development and for production. In Settings → API keys, create a Read-write key for the workspace that holds the drive. It is shown once. Set these where the server runs (never in browser code or a repository): Until both are set, the file browser says what is missing. The server logs whether the feature is on at start-up. A key belongs to a workspace, not to one drive. The CRM only ever uses the drive named in FLASHDRIVE_DRIVE_ID, but anyone holding the key can reach every drive in that workspace, so keep the CRM's drives in a workspace of their own if that matters to you. To try it without a key, in a clone of the repository, run the stand-in store and point the app at it: Every request tells the store about its caller, as FlashDrive's own SDK does: Flashdrive-Client: swirls-crm/1.1.2 and Flashdrive-Write-Protocol: server-v1. The version is the FlashDrive client contract this code was written against, not the CRM's own version. The store refuses a request from a client older than its minimum, and a write that doesn't name the write protocol, with \"This client version is no longer supported\". If it refuses this client under its own name, the request is sent again exactly as the SDK would send it, and the server log says so. How an upload works The browser reads the file and computes its SHA-256. startUpload (server) checks the session, reserves the upload with the store in the chosen folder, and returns where to send that one file. With a bucket or FlashDrive, the browser sends the bytes straight to the store with a link signed for it. They do not pass through the CRM server, so a host's request-size limit (4.5 MB on Vercel) does not apply. With a disk, or when FlashDrive asks for it, the browser sends them to /api/files/uploads/, which checks the session and passes them on. finishUpload (server) asks the store to confirm. Until then nobody is shown the file. A file added from a record's Files tab is noted on that record's timeline. The store's key never reaches the browser, only a link that is good for one upload and expires in minutes. An upload that is started and never finished is removed after a day. A declared type An upload may say what it is ( contentType on startUpload, as a route of your own that takes only photos would: \"image/jpeg\"). The declared type is passed to the file store ( contentType on FileStore.startUpload). What each does with it: Store The declared type drive with s3Blobs Sent as the upload's content-type header, and given to the presigned PUT. Bun signs only the host of a presigned URL, so the bucket does not refuse a PUT of another type drive with localBlobs Not used: a disk takes uploads through this server flashdrive Not passed: FlashDrive tells a file's type from its name. Name the file with the extension the route accepts Whatever the store does, check the type your route takes on the server before anything is reserved; the CRM serves a file by its extension, never by what its uploader said it was. The stored size at finish A quota of your own ( consumeLimit) counts an upload from its declared size, so the CRM must know that what the store kept is no larger. Each store, at finishUpload: Store How the stored size is checked drive ( s3Blobs, or any blobs) The adapter checks it itself: it asks the bucket for the object ( stat, a HEAD) and refuses, and deletes, an object whose size differs from the declared size. A failed stat fails the finish and leaves the upload open to finish again. It reports no size to the CRM (a store that checks sizes itself says nothing). flashdrive After the upload is accepted, the adapter reads the document ( GET /v1/drives//documents/) and reports its source_bytes. FlashDrive stores a file with its size as soon as its bytes are stored, so the size is there at finish. A failed read fails the finish ( upload_size_unavailable) and leaves the upload open to finish again; the file is not deleted. A store of your own whose answer is null The store can't say: the upload is kept. Don't count a quota from a store that can't say. A larger stored file than declared is refused ( upload_size_mismatch) and deleted, for anyone. How a file is opened Through /api/files/, which checks the CRM session. A bucket and FlashDrive get a redirect to a link for that one file. A disk gets the bytes. Anyone on the team can upload anything, and a page opened from the CRM's own address could act as whoever opened it. So only PNG, JPEG, GIF, WebP and PDF are shown in the browser, told by the file's extension. Everything else is downloaded, HTML and SVG included, and what the uploader's browser said a file was is never repeated. What the database holds Table What it is record_folders Which folder is a record's own, so its Files tab opens there file_uploads A file on its way in, until the store confirms it file_nodes With drive: the folders and files, and where each file's bytes are Limits One file added through the CRM 1 GB, or the server's request limit with a disk Files per drop or pick 50 Shown in one folder The first 1,000 folders and 1,000 files Search results The first 200 files A FlashDrive drive 500,000 files, 1 TB, folders 64 levels deep, 10 GB in one file With FlashDrive, a deleted file stays in the store's trash for an hour. With drive, deleting is for good. Deleting a folder deletes everything in it. Two servers adding files with the same name to the same folder at the same moment can end up with two of that name. Folders, and moves, are settled between them. Who can see what Anyone who may use the CRM can see, add, rename, move and delete every file, as they can notes and tasks, unless role access or record scopes say otherwise. Folders give no separate permissions: a record's folder is the record's. Whoever can open a FlashDrive drive, or holds a key to the bucket, can read every file in it. With role access A role's access reaches a record's files as it reaches the record. The CRM checks it for every folder and file it is asked about, before the file store is asked to do anything. The role, for the record's object In the record's folder, and every folder inside it Edits it Everything, as before Only reads it ( readOnly) Lists, searches, opens and downloads. Adds, renames, moves and deletes nothing, makes no folder for a record that has none, and shares none with another record: each is refused in words (\"You can look at jobs but not change them.\") Doesn't see it ( deny) Nothing: the folder isn't listed, searched or opened, and a change to it is told it isn't there A folder inside another record's folder is that record's too. A deal's folder made inside its company's ( files.under) is read-only to someone who only reads companies, whatever they may do with deals, as it is out of reach to someone a scope keeps the company from. Lay the folders out apart ( files.location) where that is not what you want. A folder that holds record folders (\"Companies\") is renamed, moved or deleted only by someone who may change every record whose folder is inside it. A file is reached through the folder it is in (the link carries it), never by its id alone, for anyone role access keeps something from. A role that may change no record ( \"readOnly\": true) changes nothing in the shared library or in a folder the team made either (\"You can look at these files, but not change them.\"), as a read-only person with record scopes changes nothing. The file browser shows no controls for what can't be changed; the server refuses each change itself. With record scopes In a Spool with record scopes the file store still knows nothing of them, so the CRM checks every folder and file it is asked about. What Whose it is A scoped record's folder, and everything under it Its record's scope. Anyone else is told it isn't there: listed, searched, opened or changed A shared object's record's folder Everyone's The library, and folders the team made outside a record Everyone's A file The folder it is in. It is opened, renamed, moved and deleted through that folder (the link carries it), never by its id alone A deleted record's folder Still its scope's: the folder and files stay in the store, and the row that says whose they were is kept A folder from before scopes were on, whose record is gone Nobody's, so everyone's: nothing says whose it was. Move or remove these before turning scopes on Someone who only reads opens and searches what they can reach and changes nothing: no upload, new folder, rename, move or delete, in a record's folder or a shared one. The file browser shows them no controls for it, and the server refuses each change itself. Someone who writes some scopes and only reads others gets the controls folder by folder. A record's folder is made by someone who can change the record. A person who only reads a record with no folder yet is told it has none. Every record's folder carries part of the record's id ( Companies/Acme (1f0c9a2e)), so a name never says whether another scope has a record called the same, and a new record never takes over a folder another left. A shared folder that holds other scopes' record folders (\"Companies\") can be renamed, moved or deleted only by someone who can change every record whose folder is inside it. The number beside it counts what the reader can see inside, not what the store holds; a listing of more than 50 folders shows no counts to someone who can't reach every record. Search returns files in folders the reader can reach. \"And more\" is only said when nothing the store found was held back. The store returns its first 200 matches whoever asks, so a search that mostly matches other scopes' files can miss some of the reader's own: search for more of the name. A folder is never without an owner while it is made. The row that says whose it is, is written before the folder, and learns the folder's id after. If the server stops in between, the row still owns the folder by its path, and the next visit to the record finishes the work. Renaming or moving the parent folder in the store itself during that moment is the one thing that can part them. Anyone with access to the store itself (the FlashDrive drive, the bucket) reads all of it, whatever their scope in the CRM. Troubleshooting What you see What it means \"Files aren't set up yet\" The list under it names what is missing \"The file store refused this CRM's key\" The key is wrong, was revoked, may not write, or doesn't reach this drive or bucket \"AWS_SESSION_TOKEN is set, for another key than this bucket's\" Bun would sign with it. Unset it, or use the key it belongs to \"The file store could not use its disk\" The server can't write to the folder files are kept in. The log has the reason \"The file changed while it was being added\" What arrived isn't what the browser described. Add the file again \"A folder can't be moved into itself\" The destination is the folder, or is inside it \"The file store needs a newer client than this CRM speaks\" FlashDrive has raised its minimum client version past the one this code states ( STORE_CONTRACT in packages/spools/src/adapters/files/flashdrive/client.ts). Update the CRM; the server log names the minimum it asked for \"Something with that name is already there\" A folder or file in that place already has the name \"That changed while you were looking at it\" Someone else renamed, moved or replaced it. Try again \"That is no longer in the file store\" It was deleted or moved out of reach in the drive. Reload the folder \"The file store is full\" The disk is full, or the FlashDrive plan is used up \"The upload was interrupted\" The connection dropped while the bytes were going. Add the file again \"The file store is still working on this file\" The store took longer than usual to confirm. Reload the folder in a moment" + "text": "Files The CRM has a file browser: folders, drag-and-drop upload, rename, move and search. What it keeps files in is an adapter you choose in src/spool.server.ts: Adapter Files are kept in drive({ blobs: s3Blobs() }) Any S3-compatible bucket, with the folders in the CRM's own database drive({ blobs: localBlobs() }) A disk on the server, with the folders in the CRM's own database flashdrive() A FlashDrive drive, which also mounts as a folder on macOS and Linux Without one, the Files pages say that files aren't set up. The Files page (in the sidebar, under Notes) browses the whole drive. A record's Files tab browses that record's own folder. Give an object a files section in crm.config.json and each of its records gets a folder. Status: tested against stand-ins for FlashDrive and S3, and against a real disk. None of them has been run against a live account yet. What you can do In either place: Open a folder, and climb back with the breadcrumbs or \"Up one folder\". Right-click an empty spot to add a folder or upload files. Right-click a folder or a file to open, rename, move up or delete it; a file's menu also copies its link. Every row also has a ⋯ button for the same menu and a delete button, shown when you point at it or select it. See who added each file and when. A file put in a FlashDrive drive some other way shows no name. Drag files in from your computer to upload them, onto the open folder or onto a folder in the list. Drag a file or folder onto another folder, or onto a breadcrumb, to move it. Switch between a list and a grid. The choice is remembered in the browser. With an item selected: Enter opens it, F2 renames it, Delete removes it. On the Files page, search file names across everything. The folder being shown on the Files page is in the address, so a folder can be linked to. A folder that is a record's own is marked \"Record\" and links to it. A folder per record A record's folder is made the first time its page is opened (or its folder is first asked for), at /: Companies/Acme. folders are made inside each record's folder when it is created. Use plain names: at most 60 characters, none of / \\: * ? \" < > |, no leading or trailing dot or space. under names a relation field. The record's folder is made inside the folder of the record that field points to: Companies/Acme/Website redesign. A record with that field empty gets a folder under its own object's name. Two records with the same name each get a folder; the second carries the first eight characters of its id. An object without files has no Files tab and no folders. The CRM remembers which folder is a record's by the store's id for it, not its path. So a record's folder can be renamed or moved in the drive and still opens from its record; renaming the record does not rename the folder. Deleting a record leaves its folder in the drive. Deleting a record's folder, in the CRM or in the drive, is allowed: the record gets a new, empty one the next time its page is opened. To lay the drive out differently, give your app a files.location in src/app/extensions.ts. It is asked once per record, when its folder is made: When one record hands over to another (a won deal becoming a job), give the new record the old one's folder with shareRecordFolder(from, to) from @swirls/spools/extensions: both then open the same folder. The library A folder at the top of the drive holds files that belong to the business rather than to one record: price lists, templates, forms. It is made the first time the Files page is opened, as \"Company files\". To rename it or give it folders, add files at the top level of crm.config.json: It is an ordinary folder: anything can be added to it, and more folders can be made beside it. files can't be used as an object key: it is the page's address. Setup: a drive of your own The folders, and the name and place of each file, are rows in the CRM's database ( file_nodes). The bytes are in the blob store. After choosing drive, run bun run crm:gen and, with DATABASE_URL set, bun run db:push so the table is there. Back up the database and the blob store together: either is little use without the other. A bucket: s3Blobs() Amazon S3, Cloudflare R2, Supabase Storage, MinIO, or anything else with the S3 API. Keep the bucket private. Files are opened by links the server signs, which last five minutes. The bucket's CORS rules must allow PUT with a content-type header from the CRM's address, because browsers send files straight to it. Upload links last fifteen minutes. A signed link can't hold the browser to a hash, so an upload is checked by its size. Settings can be passed as options, or read from variables with other names: s3Blobs({ env: { bucket: \"R2_BUCKET\" } }). Bun signs with AWS_SESSION_TOKEN when it is set, whatever key it is given. Where that belongs to another key, unset it. A disk: localBlobs() Files go in.data/files unless you name a folder. It suits one server with a disk that lasts: in Docker, mount a volume. It is refused on Vercel or another serverless host, which has no such disk. Uploads pass through the server, so its limit on the size of a request applies: 128 MB, which is Bun's own default ( maxRequestBodySize in server.prod.ts changes it). Size and SHA-256 are checked as the file is written, and a file appears only once all of it is there. Setup: FlashDrive The folders and files in the CRM are the drive's own, so the team can open the same ones in Finder, and whatever is put in the drive there shows up in the CRM. In the FlashDrive Console, create a drive for the CRM. Use a separate drive for development and for production. In Settings → API keys, create a Read-write key for the workspace that holds the drive. It is shown once. Set these where the server runs (never in browser code or a repository): Until both are set, the file browser says what is missing. The server logs whether the feature is on at start-up. A key belongs to a workspace, not to one drive. The CRM only ever uses the drive named in FLASHDRIVE_DRIVE_ID, but anyone holding the key can reach every drive in that workspace, so keep the CRM's drives in a workspace of their own if that matters to you. To try it without a key, in a clone of the repository, run the stand-in store and point the app at it: Every request tells the store about its caller, as FlashDrive's own SDK does: Flashdrive-Client: swirls-crm/1.1.2 and Flashdrive-Write-Protocol: server-v1. The version is the FlashDrive client contract this code was written against, not the CRM's own version. The store refuses a request from a client older than its minimum, and a write that doesn't name the write protocol, with \"This client version is no longer supported\". If it refuses this client under its own name, the request is sent again exactly as the SDK would send it, and the server log says so. How an upload works The browser reads the file and computes its SHA-256. startUpload (server) checks the session, reserves the upload with the store in the chosen folder, and returns where to send that one file. With a bucket or FlashDrive, the browser sends the bytes straight to the store with a link signed for it. They do not pass through the CRM server, so a host's request-size limit (4.5 MB on Vercel) does not apply. With a disk, or when FlashDrive asks for it, the browser sends them to /api/files/uploads/, which checks the session and passes them on. finishUpload (server) asks the store to confirm. Until then nobody is shown the file. A file added from a record's Files tab is noted on that record's timeline. The store's key never reaches the browser, only a link that is good for one upload and expires in minutes. An upload that is started and never finished is removed after a day. A declared type An upload may say what it is ( contentType on startUpload, as a route of your own that takes only photos would: \"image/jpeg\"). The declared type is passed to the file store ( contentType on FileStore.startUpload). What each does with it: Store The declared type drive with s3Blobs Sent as the upload's content-type header, and given to the presigned PUT. Bun signs only the host of a presigned URL, so the bucket does not refuse a PUT of another type drive with localBlobs Not used: a disk takes uploads through this server flashdrive Not passed: FlashDrive tells a file's type from its name. Name the file with the extension the route accepts Whatever the store does, check the type your route takes on the server before anything is reserved; the CRM serves a file by its extension, never by what its uploader said it was. The stored size at finish A quota of your own ( consumeLimit) counts an upload from its declared size, so the CRM must know that what the store kept is no larger. Each store, at finishUpload: Store How the stored size is checked drive ( s3Blobs, or any blobs) The adapter checks it itself: it asks the bucket for the object ( stat, a HEAD) and refuses, and deletes, an object whose size differs from the declared size. A failed stat fails the finish and leaves the upload open to finish again. It reports no size to the CRM (a store that checks sizes itself says nothing). flashdrive After the upload is accepted, the adapter reads the document ( GET /v1/drives//documents/) and reports its source_bytes. FlashDrive stores a file with its size as soon as its bytes are stored, so the size is there at finish. A failed read fails the finish ( upload_size_unavailable) and leaves the upload open to finish again; the file is not deleted. A store of your own whose answer is null The store can't say: the upload is kept. Don't count a quota from a store that can't say. A larger stored file than declared is refused ( upload_size_mismatch) and deleted, for anyone. How a file is opened Through /api/files/, which checks the CRM session. A bucket and FlashDrive get a redirect to a link for that one file. A disk gets the bytes. Anyone on the team can upload anything, and a page opened from the CRM's own address could act as whoever opened it. So only PNG, JPEG, GIF, WebP and PDF are shown in the browser, told by the file's extension. Everything else is downloaded, HTML and SVG included, and what the uploader's browser said a file was is never repeated. What the database holds Table What it is record_folders Which folder is a record's own, so its Files tab opens there file_uploads A file on its way in, until the store confirms it file_nodes With drive: the folders and files, and where each file's bytes are Limits One file added through the CRM 1 GB, or the server's request limit with a disk Files per drop or pick 50 Shown in one folder The first 1,000 folders and 1,000 files Search results The first 200 files A FlashDrive drive 500,000 files, 1 TB, folders 64 levels deep, 10 GB in one file With FlashDrive, a deleted file stays in the store's trash for an hour. With drive, deleting is for good. Deleting a folder deletes everything in it. Two servers adding files with the same name to the same folder at the same moment can end up with two of that name. Folders, and moves, are settled between them. Who can see what A headless Spool has the same files behind the files.* operations and /api/files/*, with the same checks. A read-only API key can list and search them, and its first look does not make the library's folders. Anyone who may use the CRM can see, add, rename, move and delete every file, as they can notes and tasks, unless role access or record scopes say otherwise. Folders give no separate permissions: a record's folder is the record's. Whoever can open a FlashDrive drive, or holds a key to the bucket, can read every file in it. With role access A role's access reaches a record's files as it reaches the record. The CRM checks it for every folder and file it is asked about, before the file store is asked to do anything. The role, for the record's object In the record's folder, and every folder inside it Edits it Everything, as before Only reads it ( readOnly) Lists, searches, opens and downloads. Adds, renames, moves and deletes nothing, makes no folder for a record that has none, and shares none with another record: each is refused in words (\"You can look at jobs but not change them.\") Doesn't see it ( deny) Nothing: the folder isn't listed, searched or opened, and a change to it is told it isn't there A folder inside another record's folder is that record's too. A deal's folder made inside its company's ( files.under) is read-only to someone who only reads companies, whatever they may do with deals, as it is out of reach to someone a scope keeps the company from. Lay the folders out apart ( files.location) where that is not what you want. A folder that holds record folders (\"Companies\") is renamed, moved or deleted only by someone who may change every record whose folder is inside it. A file is reached through the folder it is in (the link carries it), never by its id alone, for anyone role access keeps something from. A role that may change no record ( \"readOnly\": true) changes nothing in the shared library or in a folder the team made either (\"You can look at these files, but not change them.\"), as a read-only person with record scopes changes nothing. The file browser shows no controls for what can't be changed; the server refuses each change itself. With record scopes In a Spool with record scopes the file store still knows nothing of them, so the CRM checks every folder and file it is asked about. What Whose it is A scoped record's folder, and everything under it Its record's scope. Anyone else is told it isn't there: listed, searched, opened or changed A shared object's record's folder Everyone's The library, and folders the team made outside a record Everyone's A file The folder it is in. It is opened, renamed, moved and deleted through that folder (the link carries it), never by its id alone A deleted record's folder Still its scope's: the folder and files stay in the store, and the row that says whose they were is kept A folder from before scopes were on, whose record is gone Nobody's, so everyone's: nothing says whose it was. Move or remove these before turning scopes on Someone who only reads opens and searches what they can reach and changes nothing: no upload, new folder, rename, move or delete, in a record's folder or a shared one. The file browser shows them no controls for it, and the server refuses each change itself. Someone who writes some scopes and only reads others gets the controls folder by folder. A record's folder is made by someone who can change the record. A person who only reads a record with no folder yet is told it has none. Every record's folder carries part of the record's id ( Companies/Acme (1f0c9a2e)), so a name never says whether another scope has a record called the same, and a new record never takes over a folder another left. A shared folder that holds other scopes' record folders (\"Companies\") can be renamed, moved or deleted only by someone who can change every record whose folder is inside it. The number beside it counts what the reader can see inside, not what the store holds; a listing of more than 50 folders shows no counts to someone who can't reach every record. Search returns files in folders the reader can reach. \"And more\" is only said when nothing the store found was held back. The store returns its first 200 matches whoever asks, so a search that mostly matches other scopes' files can miss some of the reader's own: search for more of the name. A folder is never without an owner while it is made. The row that says whose it is, is written before the folder, and learns the folder's id after. If the server stops in between, the row still owns the folder by its path, and the next visit to the record finishes the work. Renaming or moving the parent folder in the store itself during that moment is the one thing that can part them. Anyone with access to the store itself (the FlashDrive drive, the bucket) reads all of it, whatever their scope in the CRM. Troubleshooting What you see What it means \"Files aren't set up yet\" The list under it names what is missing \"The file store refused this CRM's key\" The key is wrong, was revoked, may not write, or doesn't reach this drive or bucket \"AWS_SESSION_TOKEN is set, for another key than this bucket's\" Bun would sign with it. Unset it, or use the key it belongs to \"The file store could not use its disk\" The server can't write to the folder files are kept in. The log has the reason \"The file changed while it was being added\" What arrived isn't what the browser described. Add the file again \"A folder can't be moved into itself\" The destination is the folder, or is inside it \"The file store needs a newer client than this CRM speaks\" FlashDrive has raised its minimum client version past the one this code states ( STORE_CONTRACT in packages/spools/src/adapters/files/flashdrive/client.ts). Update the CRM; the server log names the minimum it asked for \"Something with that name is already there\" A folder or file in that place already has the name \"That changed while you were looking at it\" Someone else renamed, moved or replaced it. Try again \"That is no longer in the file store\" It was deleted or moved out of reach in the drive. Reload the folder \"The file store is full\" The disk is full, or the FlashDrive plan is used up \"The upload was interrupted\" The connection dropped while the bytes were going. Add the file again \"The file store is still working on this file\" The store took longer than usual to confirm. Reload the folder in a moment" }, { "path": "/docs/swirls", @@ -1267,6 +1340,11 @@ "title": "Vercel", "level": 2 }, + { + "id": "a-headless-spool", + "title": "A headless Spool", + "level": 2 + }, { "id": "a-host-with-no-long-lived-process", "title": "A host with no long-lived process", @@ -1288,7 +1366,7 @@ "level": 2 } ], - "text": "Deployment The app is one Bun server: the CRM, the API routes and the campaign runtime. Any host that runs a Docker image works (Fly.io, Railway, Render, a VM). 1. Database (Supabase) Create a Supabase project. Copy the session pooler connection string (Project Settings → Database). The app keeps long-lived connections; the transaction pooler isn't needed. Apply the schema: For later changes, edit crm.config.json, then bun run crm:gen, bun run db:plan -- --name , commit, and run db:migrate against production. Prisma refuses destructive changes unless you pass explicit --delete or --rename decisions: --delete Deal.budget to drop a field, --rename Deal.proposalAmount:Deal.contractAmount to keep its data under a new name. db:plan starts from the db ref ( migrations/app/refs/db.json), which bun run db:push moves forward. If you applied the last migration to your local database with db:migrate instead, the ref is still one migration behind, and the new plan branches off the old one; db:migrate then refuses it with MIGRATION.PATH_UNREACHABLE. Plan from the last migration and move the ref yourself: Commit refs/db.json with the migration. 2. Signing in This is for auth: clerk(). Signing in covers the other choices. Create a production instance, add your domain, and copy its keys. Under Restrictions, limit sign-ups to your team (the CRM also enforces access from crm.config.json). 3. Environment Set what your adapters need from.env.example. At minimum DATABASE_URL, your auth provider's keys, APP_URL and APP_SECRET. The server logs which optional features are on at startup, and refuses to start in production without the required variables. 4. Run the image Health check: GET /healthz. Fly.io example: Any number of instances can run: what is due is kept in the database, and two of them never send the same email (see Campaigns). Without Docker: Vercel A Spool also deploys to Vercel with the TanStack Start preset ( vercel.json). Vercel's preset needs the app packaged by Nitro, so vite.config.ts calls vercel() from @swirls/spools/vite. On Vercel, where VERCEL is set, it emits a Bun function in.vercel/output. Every other build is the dist/ server above. Set the environment variables on the Vercel project before the first deploy. vercel() copies the CipherStash packages into the function whole, because they are native. Name a native package of your own with vercel({ traceDeps: ['my-native*'] }). A function is not a long-lived server, and the framework knows it is on Vercel without SERVERLESS=1. The timers are off and cron jobs call the routes in the next section instead: Campaigns. The vercel.json here calls /api/cron/sequences every ten minutes. It needs CRON_SECRET, which Vercel Cron sends as a bearer token. Without it only emails with no wait are sent, and the Workflows page says so. See Campaigns. Mailbox sync and scheduled posts. Add /api/cron/mail-sync and /api/cron/marketing to crons in vercel.json if you use them. They are left out of the starter's, because a schedule your Vercel plan doesn't allow fails the deployment. Cold starts. Vercel puts an idle function away after a couple of minutes, and the next request then waits for it to start again (around three seconds for this app). A CRM with a handful of users is idle most of the time, so keep one instance ready with a cron job that calls /api/cron/warm every minute: A schedule this frequent needs a paid Vercel plan. bun run build checks the browser files Vercel serves (.vercel/output/static) for server code, as it checks dist/client everywhere else. A host with no long-lived process On any other such host, set SERVERLESS=1. The server then keeps no timers, and cron jobs call these instead, with CRON_SECRET as a bearer token: Route What it does /api/cron/sequences Sends the sequence emails that are due. See Campaigns /api/cron/mail-sync Reads teammates' mailboxes. See Mailbox /api/cron/marketing Publishes the scheduled posts that are due. See Marketing /api/cron/warm Does one small database read, to keep an instance from going cold Files need a bucket or FlashDrive, because localBlobs() needs a disk that lasts. Your own door An app with endpoints for people who are not teammates ( Building your own door) needs, wherever it runs: TRUST_PROXY, so callerAddress tells callers apart. On Vercel set TRUST_PROXY=1: its edge is the one proxy, and it sets X-Forwarded-For. Behind one reverse proxy (nginx, Caddy, a load balancer) that appends the caller's address to X-Forwarded-For, set it to 1; behind a CDN and then a load balancer, 2. Never set it higher than the proxies you have: a caller could then name any address they like. Without it, or with a value that isn't a whole number from 1 to 10, callerAddress answers null: the address can't be known, and your endpoint skips its limit by address or refuses. An offline token key. With clerk(), set CLERK_JWT_KEY (the instance's PEM public key, from the Clerk dashboard's API keys) so verifyToken checks tokens without asking Clerk. Without it the server fetches the instance's keys itself, at most once a minute for a key id it hasn't seen and once an hour otherwise, shared by every request, and refuses a token naming a key the instance doesn't have before asking anything. Its front end's origins in a setting of yours, for verifyToken 's authorizedParties: with none, every token is refused outside development and tests. Limits in front of its routes. Put a request-rate limit for them in the platform in front (Vercel's firewall, Cloudflare, nginx limit_req) as well as your own hitLimit, so a flood is turned away before it reaches the server at all. 5. Swirls Deploy swirls/ and set its secrets (see Swirls), with crm_app::CRM_APP_URL set to your APP_URL. Checklist bun run db:migrate (or bun run db:harden) has run, so RLS is on and the Supabase API roles have no access Supabase → Settings → API → Exposed schemas doesn't include public TRUST_PROXY matches the number of proxies in front of the app With a door of your own: its front end's origins set, and CLERK_JWT_KEY with clerk() access in crm.config.json lists your domain or emails Sign-ups restricted at your auth provider APP_SECRET and SWIRLS_APP_TOKEN are 32+ random characters, unique per environment On Vercel or another serverless host: CRON_SECRET set and cron jobs for /api/cron/sequences, /api/cron/mail-sync and, if you schedule posts, /api/cron/marketing Email domain verified and the delivery webhook ( /api/webhooks/email) configured Supabase backups enabled" + "text": "Deployment The app is one Bun server: the CRM, the API routes and the campaign runtime. Any host that runs a Docker image works (Fly.io, Railway, Render, a VM). 1. Database (Supabase) Create a Supabase project. Copy the session pooler connection string (Project Settings → Database). The app keeps long-lived connections; the transaction pooler isn't needed. Apply the schema: For later changes, edit crm.config.json, then bun run crm:gen, bun run db:plan -- --name , commit, and run db:migrate against production. Prisma refuses destructive changes unless you pass explicit --delete or --rename decisions: --delete Deal.budget to drop a field, --rename Deal.proposalAmount:Deal.contractAmount to keep its data under a new name. db:plan starts from the db ref ( migrations/app/refs/db.json), which bun run db:push moves forward. If you applied the last migration to your local database with db:migrate instead, the ref is still one migration behind, and the new plan branches off the old one; db:migrate then refuses it with MIGRATION.PATH_UNREACHABLE. Plan from the last migration and move the ref yourself: Commit refs/db.json with the migration. 2. Signing in This is for auth: clerk(). Signing in covers the other choices. Create a production instance, add your domain, and copy its keys. Under Restrictions, limit sign-ups to your team (the CRM also enforces access from crm.config.json). 3. Environment Set what your adapters need from.env.example. At minimum DATABASE_URL, your auth provider's keys, the vault's four CS_* variables ( CipherStash), APP_URL and APP_SECRET. The server logs which optional features are on at startup, and refuses to start in production without the required variables. 4. Run the image Health check: GET /healthz. Fly.io example: Any number of instances can run: what is due is kept in the database, and two of them never send the same email (see Campaigns). Without Docker: Vercel A Spool also deploys to Vercel with the TanStack Start preset ( vercel.json). Vercel's preset needs the app packaged by Nitro, so vite.config.ts calls vercel() from @swirls/spools/vite. On Vercel, where VERCEL is set, it emits a Bun function in.vercel/output. Every other build is the dist/ server above. Set the environment variables on the Vercel project before the first deploy. vercel() copies the CipherStash packages into the function whole, because they are native. Name a native package of your own with vercel({ traceDeps: ['my-native*'] }). A function is not a long-lived server, and the framework knows it is on Vercel without SERVERLESS=1. The timers are off and cron jobs call the routes in the next section instead: Campaigns. The vercel.json here calls /api/cron/sequences every ten minutes. It needs CRON_SECRET, which Vercel Cron sends as a bearer token. Without it only emails with no wait are sent, and the Workflows page says so. See Campaigns. Mailbox sync and scheduled posts. Add /api/cron/mail-sync and /api/cron/marketing to crons in vercel.json if you use them. They are left out of the starter's, because a schedule your Vercel plan doesn't allow fails the deployment. Cold starts. Vercel puts an idle function away after a couple of minutes, and the next request then waits for it to start again (around three seconds for this app). A CRM with a handful of users is idle most of the time, so keep one instance ready with a cron job that calls /api/cron/warm every minute: A schedule this frequent needs a paid Vercel plan. bun run build checks the browser files Vercel serves (.vercel/output/static) for server code, as it checks dist/client everywhere else. A headless Spool A headless Spool is one Bun process with no build step: bun run start runs src/server.ts with NODE_ENV=production, on PORT (3000 unless it says) and every interface. Steps 1 to 3 above are the same, and so are the health check, the schedules and the cron routes below. What is different: Where the front end is. A front end on the same site as the API needs nothing more: the browser sends the session cookie. One on another site sends each person's sign-in token, so name its origin in src/server.ts, in both tokens.authorizedParties and origins. With neither named, no token opens the API and no other site's page may call it. Clerk. Set APP_URL to the address of your front end, or name the front ends in clerk({ authorizedParties }). A production server with neither takes nobody's cookie. Better Auth. Serve the front end and the API from one origin ( APP_URL), behind one proxy if they are two servers, because its cookie and its emailed link are that origin's. TRUST_PROXY, as for a door of your own: src/server.ts keeps the one address that many proxies from the right of X-Forwarded-For, which is what rate limits count by. API keys. They are taken only with keys: true, and made on the server with bunx spools keys create, by someone with the app's folder and its environment ( API keys). They are sealed by the vault, so the CS_* variables are needed to make one and to take one. A Spool with the interface can serve the API too: mount httpApi() from @swirls/spools/http at a route of its own, and it deploys as any Spool does. A host with no long-lived process On any other such host, set SERVERLESS=1. The server then keeps no timers, and cron jobs call these instead, with CRON_SECRET as a bearer token: Route What it does /api/cron/sequences Sends the sequence emails that are due. See Campaigns /api/cron/mail-sync Reads teammates' mailboxes. See Mailbox /api/cron/marketing Publishes the scheduled posts that are due. See Marketing /api/cron/warm Does one small database read, to keep an instance from going cold Files need a bucket or FlashDrive, because localBlobs() needs a disk that lasts. Your own door An app with endpoints for people who are not teammates ( Building your own door) needs, wherever it runs: TRUST_PROXY, so callerAddress tells callers apart. On Vercel set TRUST_PROXY=1: its edge is the one proxy, and it sets X-Forwarded-For. Behind one reverse proxy (nginx, Caddy, a load balancer) that appends the caller's address to X-Forwarded-For, set it to 1; behind a CDN and then a load balancer, 2. Never set it higher than the proxies you have: a caller could then name any address they like. Without it, or with a value that isn't a whole number from 1 to 10, callerAddress answers null: the address can't be known, and your endpoint skips its limit by address or refuses. An offline token key. With clerk(), set CLERK_JWT_KEY (the instance's PEM public key, from the Clerk dashboard's API keys) so verifyToken checks tokens without asking Clerk. Without it the server fetches the instance's keys itself, at most once a minute for a key id it hasn't seen and once an hour otherwise, shared by every request, and refuses a token naming a key the instance doesn't have before asking anything. Its front end's origins in a setting of yours, for verifyToken 's authorizedParties: with none, every token is refused outside development and tests. Limits in front of its routes. Put a request-rate limit for them in the platform in front (Vercel's firewall, Cloudflare, nginx limit_req) as well as your own hitLimit, so a flood is turned away before it reaches the server at all. 5. Swirls Deploy swirls/ and set its secrets (see Swirls), with crm_app::CRM_APP_URL set to your APP_URL. Checklist bun run db:migrate (or bun run db:harden) has run, so RLS is on and the Supabase API roles have no access Supabase → Settings → API → Exposed schemas doesn't include public TRUST_PROXY matches the number of proxies in front of the app With a door of your own: its front end's origins set, and CLERK_JWT_KEY with clerk() Headless: the front end's origin named in tokens.authorizedParties and origins (or it is on the API's own site), APP_URL set to it for Clerk, and keys: true only if scripts call with keys access in crm.config.json lists your domain or emails Sign-ups restricted at your auth provider The CS_* variables are a CipherStash workspace of this environment's own APP_SECRET and SWIRLS_APP_TOKEN are 32+ random characters, unique per environment On Vercel or another serverless host: CRON_SECRET set and cron jobs for /api/cron/sequences, /api/cron/mail-sync and, if you schedule posts, /api/cron/marketing Email domain verified and the delivery webhook ( /api/webhooks/email) configured Supabase backups enabled" }, { "path": "/docs/security", @@ -1310,6 +1388,11 @@ "title": "Record scopes", "level": 2 }, + { + "id": "the-http-api", + "title": "The HTTP API", + "level": 2 + }, { "id": "your-own-door", "title": "Your own door", @@ -1331,7 +1414,7 @@ "level": 2 } ], - "text": "Security Each deployment of a Spool serves one business. This page says who can do what in one, and what to know before putting customer data in it. A business whose groups (branches, regions, teams) must each see only their own records turns on record scopes, and one whose roles must each reach only some kinds of record gives them role access. To report a vulnerability, see the security policy. Trust model These are the boundaries the code enforces: Who Can do Enforced by Anyone See the sign-in page, unsubscribe with a valid signed link The only public routes; the unsubscribe token is signed with APP_SECRET Signed-in person not on the allowlist Nothing in the CRM The boundary checks a verified email against access in crm.config.json. An auth adapter hands over an address only when its provider has verified it CRM user Read and write every record, run actions, use the assistant, unless role access or record scopes narrow it Every CRM server function and API route goes through the boundary ( crmHandler, apiRoute); lint refuses one that doesn't Swirls (workflows, assistant tools) Call /api/swirls/tools/* Bearer SWIRLS_APP_TOKEN (32+ chars, constant-time compare). Fails closed when unset An outside caller of your own door Call the endpoints you build behind publicRoute. See Your own door Nothing of the framework's: your endpoint's own checks, in the order Building your own door gives A cron job Run one pass of the mailbox sync, the sequences or the scheduled posts, or keep the server warm, through /api/cron/* Bearer CRON_SECRET (16+ chars, constant-time compare). Fails closed when unset The email provider Report bounces and complaints to /api/webhooks/email The email adapter checks the signature (Resend: Svix, with RESEND_WEBHOOK_SECRET). Refused when no secret is set Without scopes in crm.config.json, and without role access, every allowed user has the same access: they read and write every record. With scopes, see Record scopes. Use separate deployments if you need the separation a database gives. Apart from scopes and role access, the one narrower rule is who may connect and disconnect an account shared with the team, when its provider says ( canManage, below). It limits managing the connection, not using it. Role access A role with access says which objects the people holding it may reach, and the server enforces it: { \"deny\": [\"ledger\"], \"readOnly\": [\"jobs\"] }. It keeps kinds of record apart (an office-only ledger, a look-only role); record scopes keep groups of the business apart (one branch's jobs from another's). The two are independent and both apply, so the stricter wins. What it does. For each signed-in request the boundary ( crmHandler, apiRoute) works out what the person's roles allow ( asPerson in packages/spools/src/server/object-access.ts), and the data layer checks it on every read and write: A denied object's records are not found, never \"forbidden\", wherever they would be reached: record pages and lists, counts, related lists, relation pickers and titles, CSV matching, Cmd+K's index and deep search, value suggestions, saved views, the record's timeline, tasks and notes (on it, and in the lists that gather them), favourites, reports, exports and imports, the record's folder and the folders inside it, and actions. A relation to one is returned with its id only: no title, no linked records. Home and the sidebar leave the object out. A read-only object's records are read and never changed, and neither is what hangs off them: a create, change, delete, import or action, a note, task or logged call on one, an email to one, an enrolment in a sequence, a file or folder added, renamed, moved or deleted in its folder (or any folder inside it, a related record's included), a folder made for it or shared with another record, and a change to a view everyone shares of that object are each refused in words (\"You can look at jobs but not change them.\"), and the page doesn't offer them. It is refused before anything else happens: before the app's before hooks run, before a workflow starts or an email is sent, and before the file store is asked to do anything (the test that reads the server's source for every such place lists these checks too). Reading, listing, searching and downloading stay theirs, and so do a favourite and the views only they see. A role that may change no object ( readOnly: true, or every object read-only or denied) changes nothing that is the whole business's either, as a read-only person with record scopes changes nothing: no task or note on no record, nothing in the shared file library or any folder, no view everyone shares, no marketing post and no connection the team or a group shares. Each is refused before it is written, sent or asked of the file store. Several roles: a person gets what any of them allows. Someone with no role reaches everything, unless access.default says otherwise. What it does not do. The tool API is not narrowed by roles. A call from the assistant or a workflow says which deployment it is from ( SWIRLS_APP_TOKEN), not which person it acts for: the chat's tool workflows carry no grant, and a grant is only made in a Spool with record scopes. So the assistant reaches what everyone does, less the objects assistant.deny names, which are not found to it. Keep internal objects there. Code with nobody behind it is not narrowed. A script, a cron route and the config's automations (they run after a change was let through) run with nothing kept from them, and so does code inside asSystem. What the app's code reads through the framework is. An apiRoute, a server function ( crmHandler), a handler or a hook called for a teammate keeps their role access in what it does through @swirls/spools/extensions, as scopes are kept: a denied object is not found to it, a read-only one refuses its changes, and changedSince says nothing of a denied object's records. Code that must reach further says so with asSystem. Your code is still handed what the framework hands it (a hook's record): don't send that on to someone it is kept from. Code nobody is signed in for holds no role. A publicRoute, a cron job or a script runs with nothing kept from it by role access ( access.default applies to people, not to them): an endpoint for outside callers decides itself what they reach. Four ways that would otherwise have reached a denied object are closed: Timeline lines. A line on a record's timeline is kept as it was written and read by everyone who reads the record, so a change to a relation that leads to an object any role, access.default or assistant.deny keeps from someone never names the record it now points at: it says \"updated Client\", or \"added Tags: 2\". Lines written before an object was denied are rewritten by spools timeline redact. Filters and sorts. A condition that looks into a denied object (a field of a related record of it, source.path contains...; the records of it that point here, ~ledger.job; a relation or relations field holding its records) is not there for the person: their list is what it is without it. A sort by a relation to one is by the related record's id. The team activity report counts no call, email, meeting, task or note on a denied object's records. File search finds no file in a denied record's folder or below it, as the folder itself can't be opened. Nor is the folder listed in the one above it (its name is the record's title), and a file is opened, renamed, moved or deleted through the folder it is in (the link carries it), never by its id alone, for anyone role access keeps something from. Record scopes With scopes in the config, each record of a scoped object belongs to one scope, and a person reaches only the scopes they hold. Who Can do A person who holds a scope with a writing role Read and change that scope's records, and what hangs off them: timeline, tasks, notes, files, sequence runs A person whose roles are all read-only Read what they hold, shared objects, Marketing and Integrations. Any change is refused: scoped records, shared objects' records, folders and files, shared views, marketing posts, the team's connections. They start no action, workflow or sequence, and nothing is sent or published for them A person whose role has all The same, in every scope A person on the access list who holds nothing Read shared objects, the shared file library, Marketing and Integrations, which are everyone's by the config's own word. They change nothing of the business's, as a read-only person changes nothing, and see no scoped record and nobody on the team list A workflow calling the tool API What its signed grant says, and no more than the person who started it holds when the call is made: the one record it was started for. With no grant, it reads shared objects and changes no record at all A cron job, a webhook, a script Read shared objects. Nothing scoped, and no change to any record, a shared object's included, unless the code that runs says it is the system ( asSystem) Where it is kept. In one place, under everything: every store is behind a guard ( packages/spools/src/server/store/scope.ts) that narrows each read, count, change and delete to the scopes of whoever the request is for. Pages, search, reports, exports, imports, saved views, the assistant's tools and your own extensions all reach the database through it, on every database adapter. A record of another scope is not found; it is never \"forbidden\". With nobody said, a scoped table refuses the call, and so does a change to any record, so new code that forgets fails closed. A refusal is a failure of its own ( ScopeRefused), with words for staff, and is never reported as a database failure: code that expects one (a unique index keeping one row) doesn't mistake a refusal for it. What to know. A scope counts only when it is one of this Spool's. Whatever a sign-in provider or a resolver says a person holds, a scope gives them something only when it is holdable here: an option of a scoped object's scope field, where that field is a select, and for a field kept as text or as a relation, a scope the resolver lists. This is asked in one place, before anything else is worked out from what a person holds. It matters beyond that scope's own records, because whoever writes some scope may change what is shared: shared objects' records, shared views, the file library, Marketing, the team's connections. A scope nobody defined would otherwise be a way to all of that. With no list, a text or relation scope field has no scopes, nobody holds one, and the server says so when it starts. With Clerk organizations, the organizations that are scopes have to be named, and so does head office. At Clerk, unless you have turned it off, anyone can create an organization, and is its admin there. So an organization is a scope only when its id is in scopesFrom: a membership in any other gives nothing at all, whatever its role, and such an organization is never listed. Without scopesFrom no organization is a scope and nobody holds one, and the server says so when it starts. A role marked all counts only from the organizations listed in everyScopeFrom, by id, for the same reason: Clerk's own org:admin is held by whoever runs any organization. Turning organization creation by users off at Clerk is good housekeeping, and nothing here depends on it. Scopes are keyed by the organization's id ( org_...) and never by its slug, because an organization's administrators can rename its slug, to one that another scope's records were filed under. See Signing in. What a person holds is kept for a minute. A scope taken away at the provider stops working within one. The scope a person works in is a preference, not proof. The spools-scope cookie (or Clerk's active organization) is checked against what the person holds on every request. Relations stay inside a scope. A record can't point at a scoped record of another scope, and can't move to another scope while scoped records point at it: move or unlink those first. Its timeline, tasks, notes, folder and sequence runs move with it, in the same transaction: a move that can't take them all is undone, and a row being added to a record as it moves waits and takes the scope the record came to. A record being pointed at is held until the record that points at it is saved, so a move and a new link to the same record can't pass each other: whichever comes second waits, and is refused. Many-to-many links belong to the records they join. A link of a relations field has no scope of its own: it belongs to the scope of each scoped record it joins. The rules follow from that: Two scoped records are linked only inside one scope, as a relation is. A link across scopes is refused, for a role marked all too. A scoped record and a shared object's record (a contact's tags): the link is the scoped record's. Whoever reads that record reads the link, and adding or removing it takes the right to change that record. So a tag shows each person the contacts of the scopes they hold, and counts only those. Two shared objects' records: the link is everyone's, and anyone who can change something can change it. Reading. A linked record out of reach is left out everywhere, from either side of the relation: its id, its title and its place in Count, in lists, on the record, in the picker, in footer counts, exports, search and the tool API. A filter that asks about one is answered as if the link were not there. A record shows the first hundred of its links: those are the first hundred its reader can reach, not the first hundred there are with the others taken out. Writing. A list of ids that replaces a field's records removes only the links its writer was shown. Someone who writes nothing changes no link. Under a grant made for one record, the tool API adds and removes that record's links and no others. Moving. A record can't move to another scope while it is linked to scoped records that would stay behind: unlink them first, move it, and link it again there. Its links to shared records go with it. A record being linked is held until the link is saved, so a move and a new link can't pass each other. Deleting. The database removes a record's links with it, whoever the record at the other end belongs to. So a record can't be deleted while it is linked to a record of a scope its deleter can't change, a shared record (a tag) included. Someone who can change those records unlinks them first, or a role that writes every scope deletes it. Links that crossed before scopes were turned on are left as they are. Only someone who holds both scopes is shown one; everyone else sees each record without it. Remove such links when you turn scopes on. A shared record's timeline is everyone's. So a line on it never names a scoped record: it says how many records a field gained or lost (\"added Contacts: 2\"), or that a relation changed (\"updated Maker\"). A scoped record's timeline is its scope's, and names them. Deleting a record clears the links to it, so it is refused while that would write another scope. An optional relation is emptied when the record it points at is deleted, by the database, whoever the linking record belongs to. So a shared record (a product) can't be deleted while records of a scope the deleter can't change point at it, and neither can a scoped record that a record of another scope still points at. Someone who can change those records unlinks them first, or a role that writes every scope deletes it. A scope kept in a relation. When an object's scope field is a relation (a depot's region), the record it points at is that scope's key. Nobody deletes that record while any record takes its scope from it, a role marked all and the system included: every one of them would be left with no scope. The database refuses it too ( ON DELETE RESTRICT on that relation). And nobody changes a record's id. What can be a scope. A record can't be given * as its scope, by anyone: it stands for every scope, and the record's timeline, tasks and notes would be everyone's. A select field's scopes are its options. For a text or relation field they are the ones the resolver lists, and a scope it doesn't list is refused when a record is saved. A resolver of your own that lists none ( Extending) leaves such a field with no scopes: nobody holds one, and its records are only there for a role marked all. Records that crossed before scopes were turned on. A relation that already pointed into another scope is left as it is. The related record's title is not shown, filters can't ask about it, and a list sorted by that relation sorts the row as one with no related record. The row keeps the related record's id. Clear such relations when you turn scopes on. A shared object can point at a scoped one (a product's supplier). Whoever can't reach the related record is shown the row without it, can't filter by it, and has it sorted as a row with none. A deleted record's folder stays its scope's. The folder and its files are kept in the file store, and the row that says whose they were is kept with them. Every record's folder carries part of the record's id in its name, so a new record never takes over a folder another left, and a folder's name never says whether another scope has a record called the same. A record deleted before scopes were turned on has no such row: its folder is nobody's, so everyone's, and the backfill can't tell whose it was. Move or remove those folders before turning scopes on. Rows written before scopes were turned on have no scope and are only there for a role with all, until bun run db:scopes ( spools scopes backfill) has given them their record's. A task or note on no record stays with head office: nothing says whose it was. Changing which objects are scoped. Each row that hangs off a record (a line on its timeline, a task, a note, a favourite, its folder, an upload, a sequence run) keeps a copy of its record's scope, and a row on a shared object's record is marked as everyone's. That copy was true when the row was written, so after any change to scopes.objects run bun run db:scopes again. Until it has run: An object that was shared and is now scoped. Its records are scoped at once. The rows already on them are still marked as everyone's, and that mark is no longer taken at its word: they are out of reach of every scope, their own included, and are only there for a role with all. Their folders and files are too, and a sequence run among them is held, not sent. The backfill gives each its record's scope. An object that was scoped and is now shared. Its records are everyone's at once, by the config's own word. The rows already on them stay with the scope they had, read and changed by that scope's people only. The backfill gives them to everyone, as a new row on a shared object's record is. An object taken out of the config. The rows that were on its records keep what they carry: one that has a scope stays that scope's, and one marked as everyone's is only there for a role with all. The backfill leaves them as they are. A scope field changed for another. The records take their scope from the new field at once. The rows already on them keep the scope the old field gave. Where the two fields use the same scope names for different records, this is exposed until the backfill has run: the people of the scope a row still carries read and change that row, a line on the record's timeline, a task, a note, its folder and the files in it, though the record itself is no longer theirs and they can't open it. The guard can't close this by itself. A row's copy is all it has to go by, and that copy is a scope someone really holds. So change a scope field with the server stopped, or run bun run db:scopes in the same deploy, before anyone signs in. The backfill gives every such row its record's scope, and takes away the scope of a row whose record has none. A server that stays up says at start-up when rows are waiting for the backfill, and in which tables. For rows that carry another scope than their record's it holds a few hundred rows of each table against their records and says so in a line of its own, naming what is exposed. That is a sample: finding none is not proof there are none. A serverless host does not look each time it starts: run the backfill there without being told. The backfill never leaves a row behind a record that moves beside it. For a row that carries anything but its record's scope it holds the record, reads its scope again, and writes the row in that same transaction, which is how a move itself takes a record's rows with it. A move that is under way is waited for, and a move that comes after waits and takes the rows on. Synced mail and meetings are lines on a record's timeline, and follow these rules with the rest of it. Which mailbox was read up to where is each person's own and belongs to no record. Marketing posts, ad results and connected accounts hang off no record. * is never a record's scope. A record that has * in its scope field (text typed before scopes were turned on) is a record with no scope: only a role with all sees it, and what is hung on it has no scope either. Give it a real one. Owners and assignees. A user field can name anyone, including someone who can't open the record. The pickers only offer people who share the scope. Saved views are shared by everyone who uses the object, whatever their scope: a view's name and its filters are seen by all. The titles of records a filter names are not. A view everyone shares is renamed, re-filtered, rearranged and deleted only by someone who can change something: a read-only person, and someone who holds nothing, are refused, and so is their resetting a view the config declares. They still sort and filter what is on their own screen, and make, change and delete views only they see. Files. The file store knows nothing of scopes, so the CRM checks every folder and file it is asked about: a record's folder, and everything under it, is only reached by those who reach the record. A file is opened, renamed, moved or deleted through the folder it is in (the link carries it), never by its id alone. Whether it is in that folder is asked of the file itself when the folder holds more than a listing shows. Anyone with access to the store itself still reads all of it. The shared library, and folders the team made outside a record's folder, are everyone's. Grants for the tool API. A workflow started for a record is handed a token signed with APP_SECRET (HMAC-SHA256, compared in constant time). It states the record's scope, the record, who started the work and when it ends: fifteen minutes later unless scopes.grantMinutes says. The tool API answers a call that carries it about that record only, and refuses it once that person is off the access list. That one record goes with the call into your own code: a hook, a handler or a run target that a change made under a grant sets off reads and changes, through @swirls/spools/extensions, that record and no other ( getRecord, updateRecord, its timeline, tasks, notes and folder), and is refused listRecords, createRecord and the rest that reach further. Code that must reach further says so with asSystem. This is what those functions do, not a wall around your code: an extension that goes past them to the server's own modules is working with the grant's whole scope, as it always could. Each time it is used it is cut down to what that person holds at that moment: someone who has lost the scope has lost the grant with it, and someone who may now only read it has a grant that only reads. As with everything a person holds, that is within the minute. Whoever holds a grant has its reach until then, so workflows must keep it out of prompts and messages. See Swirls. Actions, automations, sequences and email are changes. Running an action on a record, writing to its email address, and anything else that starts a workflow, the app's own handler or an email sequence for it, needs the right to change that record. It is checked before anything is started or sent, so a read-only person's click starts no workflow and sends no email. The same goes for everything the server does outside its database: the app's before hooks run, and the file store is asked to take, move or delete something, only for someone who may make that change, and with nobody said none of it happens. A test reads the server's source for every such place and fails when one is added without saying what settles who may do it ( packages/spools/tests/unit/effects-after-checks.test.ts). The assistant. Its chats must be each person's own, which needs federation with your sign-in provider: with a project API key everyone would read everyone's chats, so the assistant is refused and says so. And the assistant's record tools are refused in chat, because a chat has no way to carry a grant that the model can't relay; see Swirls. Workflows started from a record do carry one. Marketing, integrations and guides are not scoped: the Marketing page and its posts are the whole business's, and everyone on the access list reads them. Changing them is for someone who can change something. A person who can change no record, because their roles are all read-only or because they hold nothing, reads Marketing and Integrations and changes neither: they don't draft, edit, schedule, publish, take back or delete a post, have the website checked or read, or have ad results read again, and they don't connect, replace or disconnect an account the team or a group shares. Each is refused before anything is written, started or sent (\"You can look at Marketing, but not change it.\"), and the pages show them no control for it. What is their own stays theirs: a mailbox or another account of their own, the guides they have seen, their favourites, the views only they see. A post that someone who may scheduled goes out at its time with nobody signed in, as before. A Spool without scopes is as it was: every CRM user does all of this. Marketing is written by nobody on a record's behalf. What is on the Marketing page is read by every scope, and by people who hold none. So a call to the tool API under a grant made for one record is refused the tools that write there ( draft_post, save_site_profile, post_result, save_ads): a workflow that can read one scope's record could otherwise be talked into copying it to where everyone reads, by text on that record's timeline. The marketing workflows that answer through those tools are started for no record and carry no grant. And the assistant drafts no post in a chat: a chat's call can't say whose draft it would be, and the person chatting may be one who can change nothing. A person writes it on the Marketing page. A credential is not bound to a record. getAccessToken and findConnections in @swirls/spools/extensions answer a hook that runs under a grant made for one record as they answer any other. A hook that a workflow's write-back sets off is where an app sends a changed record to the books, and a token for another service is no way into the CRM's records. What your code sends with it is your code's to decide. What a refusal gives away. A record that can't be deleted or moved says why, and the reason can be records its reader can't see: \"deals of a branch you can't change point at it\", \"it is linked to contacts of a branch you can't change\", \"parts need it\". So someone who may change a record learns that some record of that kind, out of their reach, points at it. That is all they learn: never how many, which, or of which scope. It is kept on purpose. The alternative is a delete that fails with no reason, which nobody could act on. Connections are shared across scopes, and a group is not a scope. An account connected on the Integrations page is used the same way whatever scope a person works in: a teammate's own by that teammate, one shared with the team or with a group by everyone on the access list. A provider's group is a label that says which account to use (a branch's books). It is not a permission: holding a scope gives nobody a group, and a group reaches no record. A connection is a token for another service and never a way into the CRM's records: a handler that uses one reads and writes records with the access of whoever it runs for, and code with nobody behind it reaches a scoped record only inside asSystem. See Integrations. Read-only people are shown no edit controls. Someone who writes nothing gets no buttons to add, import or delete records, no editing in a table cell, a board card or a record's details, no record actions, and nothing to add a task, a note, a logged call or an email, or to upload, rename, move or delete a file. Nor anything to rename, rearrange or delete a view everyone shares: they are offered \"Save as my view\" instead. Someone who writes some scopes and only reads others gets them record by record. This is the page being tidy, not the rule: the server refuses each change itself, and says why, whatever a page shows. Starring a favourite is a person's own and stays, and so are the views only they see. A record others must have. A required relation is kept by the database ( ON DELETE RESTRICT): the record it points at can't be deleted while any record needs it. Staff are told so in words (\"This product can't be deleted while parts need it\"), with or without scopes, and not shown the database's own, which name its foreign key. Every store is tested, and so is a browser. The scope tests run on PGlite, on Postgres through Effect SQL and through Prisma, in CI. The browser tests run the starter with scopes laid over its config and two branches' records: lists, search, relation pickers, a record's linked records, notes, tasks and files, the address of another branch's record, a read-only person's page and a change sent past it, and head office switching branch and moving a record. The ones that set two changes against each other (a move and a new link, a delete and a new link, for relations and for many-to-many links) run as two connections on a real Postgres, and so do the ones that set changes holding the same records from different ends against each other, a move of scope among them. A database adapter of your own inherits the guard; run the integration tests on it ( TEST_STORE) before relying on it. Your own door Spools has no door for people who are not teammates: an app builds its own behind publicRoute from small helpers ( Building your own door). The framework enforces nothing about who such a caller is or what they reach; each helper does one thing, and stands on its own: Helper What it guarantees verifyToken A user id only for a token the auth adapter checks as issued to one of the origins named ( azp); with none named, only a developer's or a test's server takes any. Never a network call per token ( clerk(): a keyring, or CLERK_JWT_KEY offline) bearerToken Only the Authorization: Bearer header: a session cookie sent alongside counts for nothing callerAddress The address TRUST_PROXY (1 to 10, anything else is none) says to trust, or null when it can't be known: never one shared value to count by hitLimit, peekLimit, consumeLimit Your buckets are counted as app:, apart from the framework's; bad numbers are refused; with storeRateLimits() the same on every instance, no more than the limit however callers race idempotent A key is the caller's alone ( app:, apart from teammates' staff:): the caller must be a verifiedCaller (its type, and a runtime check of its shape), made from ids the app verified. Answers sealed by the vault for their row and caller, never kept in the clear sealText, openText Sealed for an owner you name, kept apart from the framework's secrets ( app:); nothing sealed without a vault; text in the clear is refused writeKeptFields Only readonly fields, so no person's change goes untold; the record's rules still hold changedSinceAs Narrows the answer by your own check; a check that fails says no asSystem Lifts record scopes and role access for what your code does inside it, and nothing else: there is no other guard to lift What is yours, because nothing in the framework knows your callers: Who they are. Map a verified user id to a record of yours by a readonly field, written only by your code, so no teammate, import or the assistant can point a record at someone else. What they reach. Your endpoint runs with nobody signed in: a read through @swirls/spools/extensions reaches every record (record scopes refuse a scoped object until your code says asSystem). Check every id a caller sends against your own rules, and answer one out of reach exactly as one that doesn't exist. What leaves. Answer an explicit list of fields, never a record as it is read. What they write. Write only the fields you name. Hooks and automations run for those writes as for any other; a before hook's values are written as the server's. Residual risks you accept What the framework does not close, by design or for now. Each is yours to weigh: Uniqueness 409s tell anyone whose write clashes that a record with those values exists, across rows and record scopes. An object-level changedSince key tells when any record of the object changed, records out of reach included. Values a before hook returns are written as the server's: not checked against readonly. A write can run twice if storing its idempotent answer fails on every retry: the claim then goes stale and a repeat runs. Quotas count in fixed windows (a UTC day, a minute): about twice a limit can go through around a window's edge. Signing keys Clerk rotates in are picked up within a minute of the first token that names them, and dropped keys within an hour. With the memory limiter, rate limits are per server instance: N instances allow about N times a limit, and a restart forgets. Without TRUST_PROXY callerAddress is null: an app that skips its address limit then relies on the platform in front to tell callers apart. A file store that doesn't enforce an upload's declared type or size relies on the CRM's check at finish, which a store that can't say a size skips. idempotent takes only a verifiedCaller, but what the app verified before making one is its own: an id taken from the request instead of a verified token lets one caller replay another's answers. An endpoint for outside callers is as safe as its own checks: the framework applies no field allowlist, ownership rule or role to it. Locks and deleting A lock or a parentLock keeps a record as it is for everyone, the server's own work included: no change gets past one. Deleting is the one exception, so that data a lock holds is never undeletable for good (an erasure request, a submission made by mistake): the server's own work, said out loud with asSystem, may delete a locked record, a record its parent locks, or the parent, which takes the records it locks with it in one hold. A person, the assistant and code with nobody said are refused. Gate such an action in your app yourself (an admin-only handler or server function that runs it inside asSystem): the framework can't tell a mistaken submission from a wanted one. The records it pointed at say on their timeline who removed it (the actor your code passes) and that it was a system removal. Things to know The development parts don't run in production. A copy with no keys uses a database inside the server and a sign-in that lets everyone in. In a build both are left out: src/spool.server.ts picks them only when NODE_ENV isn't production, which a build fixes, and the development sign-in refuses to start under NODE_ENV=production. A deployment missing its keys stops at start-up. Clerk development instances are for testing. One verifies any address ending in +clerk_test for whoever types a fixed code. A deployment never accepts such an address, and says at start-up when it is running on a development instance's keys ( sk_test_). Use the production instance's keys where real people sign in. Field encryption isn't active yet. Fields marked encrypted are stored as plaintext until @cipherstash/stack-prisma supports Prisma 8. Treat the database as holding plaintext PII and secure it accordingly. AI sees CRM data. Swirls workflows and the assistant receive record contents, including text that came from outside your team (imports, pasted notes). Treat that text as untrusted input to the model. Mark fields people outside the team write \"untrusted\": true ( Record rules): the tool API then hands their values over as { \"untrusted\": true, \"text\": \"...\" }, which the assistant's instructions tell it is data, never instructions. Every timeline line the tool API hands over is wrapped too, whoever wrote it, and a line about a change to an untrusted field doesn't repeat the value. The assistant's tools can only read and modify CRM records and add notes, and they can't change email addresses. A record made through the tool API starts no automations, so nothing emails an address the model chose. Its replies never load an image, so text it read can't have a browser send what it knows to another server. Workflows email your team. Mailboxes. For the account a teammate signs in with, the auth provider holds the Google or Microsoft tokens and the CRM asks it for one when it reads or sends. With Clerk, access to your Clerk secret key is access to those mailboxes. With Better Auth they are in your own database, encrypted with BETTER_AUTH_SECRET, so that secret together with the database is. Only the subject, a short preview and the time of mail involving a known contact are stored; message bodies are never fetched. Whose mail it is comes from the address in the From header, never the name beside it. Only the mailbox itself says a teammate sent a message: Gmail's Sent label, or Microsoft's Sent Items folder. Junk and deleted mail are read past. See docs/mailbox.md. Connected accounts. Tokens for accounts connected on the Integrations page are sealed by the vault in the app before they are stored; the database holds only ciphertext and there is no plaintext fallback. Each is sealed for the row it is stored on, and is refused anywhere else, so someone who can write to the database can't move one teammate's tokens onto a connection of their own. The vault's keys ( CS_*, or VAULT_KEY) together with the database are access to those accounts. The OAuth flow uses PKCE and a state signed with APP_SECRET that names the teammate and is tied to their browser by a cookie. A teammate removed from access keeps their stored tokens until they are deleted, but their mailboxes stop being read, and code acting for them is given no token. Disconnecting revokes the token at the provider unless another connection holds the same account, whose access revoking would end too. See docs/integrations.md. Shared connections. A provider can make its connections the team's, or one group's ( shared in src/app/extensions.ts). Every CRM user can then see that the connection exists and act through it, whoever connected it, and it goes on working after that person is removed from access: it was connected for the business, not for them. So connect an account the business owns, and remember that removing a person does not remove what they connected for the team; disconnect it if it should go with them. Who may connect, reconnect and disconnect one is every CRM user, or only those the provider's canManage names. It is checked on the server when a connection is started, again when the provider sends the browser back, and on disconnect. A rule that fails lets nobody in. The signed state also says whose the connection will be (the team's, or which group's), and the callback reads that from nowhere else, then checks it against what the provider says now. A state for a personal connection can't be replayed to make a shared one, nor one group's for another. Which account a shared connection is comes from the provider, asked with the token it just issued. Nothing in the callback's address is taken as the answer, because the address passes through the browser: a connection whose provider code did not get an answer from the provider is refused. Otherwise a teammate could authorize an account of their own and send it back under the team's name, replacing the team's tokens with theirs. The CRM checks that the provider was asked, not what it was asked: a provider you add must ask for something only the right account can answer. An account is one connection for the team, or one for a group. The database holds it to one row, so two people connecting it at once can't leave two sets of tokens. A shared connection's tokens are sealed for a name that includes whose it is. Editing a row in the database to turn a personal connection into a shared one, or to move it to another group, leaves tokens the CRM refuses to open. Groups are labels today, not permissions: any CRM user can use any group's connection. findConnections({ usableBy }) and getAccessToken(id, { as }) refuse someone who is not a CRM user, their own connections included, and a personal connection to anyone but its owner, when an app's code says who it is acting for. They also refuse when the person named is nobody: as: ctx.actor in a handler that ran with no one signed in is not a way to be trusted. Only code that names no person at all ( getAccessToken(id), findConnections without usableBy) is trusted, so the choice is visible where it is made. No browser is sent a token. The page is sent the account's name, whose it is, who connected it and its state. Marketing. An account connected for marketing (LinkedIn, X, Google Ads) is a shared connection: any CRM user can publish through it from the Marketing page, whoever connected it, and can see, reconnect or disconnect it on the Integrations page, unless the app names who may with marketing.canManage in src/app/extensions.ts. Its tokens are sealed like any other, and no browser is sent one. META_ACCESS_TOKEN is a token for the business's page and ad account: treat it as you treat the database's password. Only a CRM user can schedule or publish a post. The tool API can save a draft and nothing more, so text the assistant read can't put a post out. The website check fetches the address in crm.config.json and no other, and the install code it shows is built only from ids that match their vendor's form. See docs/marketing.md. Files. The file store's keys stay on the server; a browser is only ever given a transfer URL for the one file it is sending, or a five-minute link to the one file it is opening, after the CRM session is checked. Without record scopes or role access, anyone who may use the CRM can open, rename, move and delete any file. With them, a record's folder and what is under it is reached only by those who reach the record, and the shared library and the team's own folders stay everyone's. Anyone with access to the store itself can read all of it: its folders are not permission boundaries. With FlashDrive the key reaches every drive in its workspace. Files the server hands out itself are never run by the browser as a page of the CRM. See docs/files.md. Assistant conversations are shared across CRM users when using a project API key (see docs/swirls.md). Secrets. Every key in.env.example is server-only except CLERK_PUBLISHABLE_KEY, which is meant for the browser. Rotate SWIRLS_APP_TOKEN in both the app and Swirls together. Cross-site requests. Server functions and the assistant endpoint reject requests that don't come from the app's own origin ( csrfMiddleware in src/start.ts), so another site can't act through a signed-in user's session. Keep that middleware first if you add your own. Every answer also tells the browser not to show the CRM in another site's frame and to take each file as the type it is sent as. Send Strict-Transport-Security from the proxy in front of the server, which is where HTTPS ends. Supabase Data API. The app never uses it. supabase/config.toml doesn't expose public. Every generated table has row-level security on with no policies ( @@rls in the Prisma schema), and bun run db:push / db:migrate run spools harden, which revokes the anon and authenticated roles on every table and fails if RLS is off anywhere. On hosted Supabase, also remove public from Settings → API → Exposed schemas." + "text": "Security Each deployment of a Spool serves one business. This page says who can do what in one, and what to know before putting customer data in it. A business whose groups (branches, regions, teams) must each see only their own records turns on record scopes, and one whose roles must each reach only some kinds of record gives them role access. To report a vulnerability, see the security policy. Trust model These are the boundaries the code enforces: Who Can do Enforced by Anyone See the sign-in page, unsubscribe with a valid signed link The only public routes; the unsubscribe token is signed with APP_SECRET Signed-in person not on the allowlist Nothing in the CRM The boundary checks a verified email against access in crm.config.json. An auth adapter hands over an address only when its provider has verified it CRM user Read and write every record, run actions, use the assistant, unless role access or record scopes narrow it Every CRM server function and API route goes through the boundary ( crmHandler, apiRoute); lint refuses one that doesn't A caller of the HTTP API What the teammate it is could do in the interface, and nothing more The same boundary and the same operations. A session cookie from the API's own site, a sign-in token from a front end you named, or an API key the vault sealed Swirls (workflows, assistant tools) Call /api/swirls/tools/* Bearer SWIRLS_APP_TOKEN (32+ chars, constant-time compare). Fails closed when unset An outside caller of your own door Call the endpoints you build behind publicRoute. See Your own door Nothing of the framework's: your endpoint's own checks, in the order Building your own door gives A cron job Run one pass of the mailbox sync, the sequences or the scheduled posts, or keep the server warm, through /api/cron/* Bearer CRON_SECRET (16+ chars, constant-time compare). Fails closed when unset The email provider Report bounces and complaints to /api/webhooks/email The email adapter checks the signature (Resend: Svix, with RESEND_WEBHOOK_SECRET). Refused when no secret is set Without scopes in crm.config.json, and without role access, every allowed user has the same access: they read and write every record. With scopes, see Record scopes. Use separate deployments if you need the separation a database gives. Apart from scopes and role access, the one narrower rule is who may connect and disconnect an account shared with the team, when its provider says ( canManage, below). It limits managing the connection, not using it. Role access A role with access says which objects the people holding it may reach, and the server enforces it: { \"deny\": [\"ledger\"], \"readOnly\": [\"jobs\"] }. It keeps kinds of record apart (an office-only ledger, a look-only role); record scopes keep groups of the business apart (one branch's jobs from another's). The two are independent and both apply, so the stricter wins. What it does. For each signed-in request the boundary ( crmHandler, apiRoute) works out what the person's roles allow ( asPerson in packages/spools/src/server/object-access.ts), and the data layer checks it on every read and write: A denied object's records are not found, never \"forbidden\", wherever they would be reached: record pages and lists, counts, related lists, relation pickers and titles, CSV matching, Cmd+K's index and deep search, value suggestions, saved views, the record's timeline, tasks and notes (on it, and in the lists that gather them), favourites, reports, exports and imports, the record's folder and the folders inside it, and actions. A relation to one is returned with its id only: no title, no linked records. Home and the sidebar leave the object out. A read-only object's records are read and never changed, and neither is what hangs off them: a create, change, delete, import or action, a note, task or logged call on one, an email to one, an enrolment in a sequence, a file or folder added, renamed, moved or deleted in its folder (or any folder inside it, a related record's included), a folder made for it or shared with another record, and a change to a view everyone shares of that object are each refused in words (\"You can look at jobs but not change them.\"), and the page doesn't offer them. It is refused before anything else happens: before the app's before hooks run, before a workflow starts or an email is sent, and before the file store is asked to do anything (the test that reads the server's source for every such place lists these checks too). Reading, listing, searching and downloading stay theirs, and so do a favourite and the views only they see. A role that may change no object ( readOnly: true, or every object read-only or denied) changes nothing that is the whole business's either, as a read-only person with record scopes changes nothing: no task or note on no record, nothing in the shared file library or any folder, no view everyone shares, no marketing post and no connection the team or a group shares. Each is refused before it is written, sent or asked of the file store. Several roles: a person gets what any of them allows. Someone with no role reaches everything, unless access.default says otherwise. What it does not do. The tool API is not narrowed by roles. A call from the assistant or a workflow says which deployment it is from ( SWIRLS_APP_TOKEN), not which person it acts for: the chat's tool workflows carry no grant, and a grant is only made in a Spool with record scopes. So the assistant reaches what everyone does, less the objects assistant.deny names, which are not found to it. Keep internal objects there. Code with nobody behind it is not narrowed. A script, a cron route and the config's automations (they run after a change was let through) run with nothing kept from them, and so does code inside asSystem. What the app's code reads through the framework is. An apiRoute, a server function ( crmHandler), a handler or a hook called for a teammate keeps their role access in what it does through @swirls/spools/extensions, as scopes are kept: a denied object is not found to it, a read-only one refuses its changes, and changedSince says nothing of a denied object's records. Code that must reach further says so with asSystem. Your code is still handed what the framework hands it (a hook's record): don't send that on to someone it is kept from. Code nobody is signed in for holds no role. A publicRoute, a cron job or a script runs with nothing kept from it by role access ( access.default applies to people, not to them): an endpoint for outside callers decides itself what they reach. Four ways that would otherwise have reached a denied object are closed: Timeline lines. A line on a record's timeline is kept as it was written and read by everyone who reads the record, so a change to a relation that leads to an object any role, access.default or assistant.deny keeps from someone never names the record it now points at: it says \"updated Client\", or \"added Tags: 2\". Lines written before an object was denied are rewritten by spools timeline redact. Filters and sorts. A condition that looks into a denied object (a field of a related record of it, source.path contains...; the records of it that point here, ~ledger.job; a relation or relations field holding its records) is not there for the person: their list is what it is without it. A sort by a relation to one is by the related record's id. The team activity report counts no call, email, meeting, task or note on a denied object's records. File search finds no file in a denied record's folder or below it, as the folder itself can't be opened. Nor is the folder listed in the one above it (its name is the record's title), and a file is opened, renamed, moved or deleted through the folder it is in (the link carries it), never by its id alone, for anyone role access keeps something from. Record scopes With scopes in the config, each record of a scoped object belongs to one scope, and a person reaches only the scopes they hold. Who Can do A person who holds a scope with a writing role Read and change that scope's records, and what hangs off them: timeline, tasks, notes, files, sequence runs A person whose roles are all read-only Read what they hold, shared objects, Marketing and Integrations. Any change is refused: scoped records, shared objects' records, folders and files, shared views, marketing posts, the team's connections. They start no action, workflow or sequence, and nothing is sent or published for them A person whose role has all The same, in every scope A person on the access list who holds nothing Read shared objects, the shared file library, Marketing and Integrations, which are everyone's by the config's own word. They change nothing of the business's, as a read-only person changes nothing, and see no scoped record and nobody on the team list A workflow calling the tool API What its signed grant says, and no more than the person who started it holds when the call is made: the one record it was started for. With no grant, it reads shared objects and changes no record at all A cron job, a webhook, a script Read shared objects. Nothing scoped, and no change to any record, a shared object's included, unless the code that runs says it is the system ( asSystem) Where it is kept. In one place, under everything: every store is behind a guard ( packages/spools/src/server/store/scope.ts) that narrows each read, count, change and delete to the scopes of whoever the request is for. Pages, search, reports, exports, imports, saved views, the assistant's tools and your own extensions all reach the database through it, on every database adapter. A record of another scope is not found; it is never \"forbidden\". With nobody said, a scoped table refuses the call, and so does a change to any record, so new code that forgets fails closed. A refusal is a failure of its own ( ScopeRefused), with words for staff, and is never reported as a database failure: code that expects one (a unique index keeping one row) doesn't mistake a refusal for it. What to know. A scope counts only when it is one of this Spool's. Whatever a sign-in provider or a resolver says a person holds, a scope gives them something only when it is holdable here: an option of a scoped object's scope field, where that field is a select, and for a field kept as text or as a relation, a scope the resolver lists. This is asked in one place, before anything else is worked out from what a person holds. It matters beyond that scope's own records, because whoever writes some scope may change what is shared: shared objects' records, shared views, the file library, Marketing, the team's connections. A scope nobody defined would otherwise be a way to all of that. With no list, a text or relation scope field has no scopes, nobody holds one, and the server says so when it starts. With Clerk organizations, the organizations that are scopes have to be named, and so does head office. At Clerk, unless you have turned it off, anyone can create an organization, and is its admin there. So an organization is a scope only when its id is in scopesFrom: a membership in any other gives nothing at all, whatever its role, and such an organization is never listed. Without scopesFrom no organization is a scope and nobody holds one, and the server says so when it starts. A role marked all counts only from the organizations listed in everyScopeFrom, by id, for the same reason: Clerk's own org:admin is held by whoever runs any organization. Turning organization creation by users off at Clerk is good housekeeping, and nothing here depends on it. Scopes are keyed by the organization's id ( org_...) and never by its slug, because an organization's administrators can rename its slug, to one that another scope's records were filed under. See Signing in. What a person holds is kept for a minute. A scope taken away at the provider stops working within one. The scope a person works in is a preference, not proof. The spools-scope cookie (or Clerk's active organization) is checked against what the person holds on every request. Relations stay inside a scope. A record can't point at a scoped record of another scope, and can't move to another scope while scoped records point at it: move or unlink those first. Its timeline, tasks, notes, folder and sequence runs move with it, in the same transaction: a move that can't take them all is undone, and a row being added to a record as it moves waits and takes the scope the record came to. A record being pointed at is held until the record that points at it is saved, so a move and a new link to the same record can't pass each other: whichever comes second waits, and is refused. Many-to-many links belong to the records they join. A link of a relations field has no scope of its own: it belongs to the scope of each scoped record it joins. The rules follow from that: Two scoped records are linked only inside one scope, as a relation is. A link across scopes is refused, for a role marked all too. A scoped record and a shared object's record (a contact's tags): the link is the scoped record's. Whoever reads that record reads the link, and adding or removing it takes the right to change that record. So a tag shows each person the contacts of the scopes they hold, and counts only those. Two shared objects' records: the link is everyone's, and anyone who can change something can change it. Reading. A linked record out of reach is left out everywhere, from either side of the relation: its id, its title and its place in Count, in lists, on the record, in the picker, in footer counts, exports, search and the tool API. A filter that asks about one is answered as if the link were not there. A record shows the first hundred of its links: those are the first hundred its reader can reach, not the first hundred there are with the others taken out. Writing. A list of ids that replaces a field's records removes only the links its writer was shown. Someone who writes nothing changes no link. Under a grant made for one record, the tool API adds and removes that record's links and no others. Moving. A record can't move to another scope while it is linked to scoped records that would stay behind: unlink them first, move it, and link it again there. Its links to shared records go with it. A record being linked is held until the link is saved, so a move and a new link can't pass each other. Deleting. The database removes a record's links with it, whoever the record at the other end belongs to. So a record can't be deleted while it is linked to a record of a scope its deleter can't change, a shared record (a tag) included. Someone who can change those records unlinks them first, or a role that writes every scope deletes it. Links that crossed before scopes were turned on are left as they are. Only someone who holds both scopes is shown one; everyone else sees each record without it. Remove such links when you turn scopes on. A shared record's timeline is everyone's. So a line on it never names a scoped record: it says how many records a field gained or lost (\"added Contacts: 2\"), or that a relation changed (\"updated Maker\"). A scoped record's timeline is its scope's, and names them. Deleting a record clears the links to it, so it is refused while that would write another scope. An optional relation is emptied when the record it points at is deleted, by the database, whoever the linking record belongs to. So a shared record (a product) can't be deleted while records of a scope the deleter can't change point at it, and neither can a scoped record that a record of another scope still points at. Someone who can change those records unlinks them first, or a role that writes every scope deletes it. A scope kept in a relation. When an object's scope field is a relation (a depot's region), the record it points at is that scope's key. Nobody deletes that record while any record takes its scope from it, a role marked all and the system included: every one of them would be left with no scope. The database refuses it too ( ON DELETE RESTRICT on that relation). And nobody changes a record's id. What can be a scope. A record can't be given * as its scope, by anyone: it stands for every scope, and the record's timeline, tasks and notes would be everyone's. A select field's scopes are its options. For a text or relation field they are the ones the resolver lists, and a scope it doesn't list is refused when a record is saved. A resolver of your own that lists none ( Extending) leaves such a field with no scopes: nobody holds one, and its records are only there for a role marked all. Records that crossed before scopes were turned on. A relation that already pointed into another scope is left as it is. The related record's title is not shown, filters can't ask about it, and a list sorted by that relation sorts the row as one with no related record. The row keeps the related record's id. Clear such relations when you turn scopes on. A shared object can point at a scoped one (a product's supplier). Whoever can't reach the related record is shown the row without it, can't filter by it, and has it sorted as a row with none. A deleted record's folder stays its scope's. The folder and its files are kept in the file store, and the row that says whose they were is kept with them. Every record's folder carries part of the record's id in its name, so a new record never takes over a folder another left, and a folder's name never says whether another scope has a record called the same. A record deleted before scopes were turned on has no such row: its folder is nobody's, so everyone's, and the backfill can't tell whose it was. Move or remove those folders before turning scopes on. Rows written before scopes were turned on have no scope and are only there for a role with all, until bun run db:scopes ( spools scopes backfill) has given them their record's. A task or note on no record stays with head office: nothing says whose it was. Changing which objects are scoped. Each row that hangs off a record (a line on its timeline, a task, a note, a favourite, its folder, an upload, a sequence run) keeps a copy of its record's scope, and a row on a shared object's record is marked as everyone's. That copy was true when the row was written, so after any change to scopes.objects run bun run db:scopes again. Until it has run: An object that was shared and is now scoped. Its records are scoped at once. The rows already on them are still marked as everyone's, and that mark is no longer taken at its word: they are out of reach of every scope, their own included, and are only there for a role with all. Their folders and files are too, and a sequence run among them is held, not sent. The backfill gives each its record's scope. An object that was scoped and is now shared. Its records are everyone's at once, by the config's own word. The rows already on them stay with the scope they had, read and changed by that scope's people only. The backfill gives them to everyone, as a new row on a shared object's record is. An object taken out of the config. The rows that were on its records keep what they carry: one that has a scope stays that scope's, and one marked as everyone's is only there for a role with all. The backfill leaves them as they are. A scope field changed for another. The records take their scope from the new field at once. The rows already on them keep the scope the old field gave. Where the two fields use the same scope names for different records, this is exposed until the backfill has run: the people of the scope a row still carries read and change that row, a line on the record's timeline, a task, a note, its folder and the files in it, though the record itself is no longer theirs and they can't open it. The guard can't close this by itself. A row's copy is all it has to go by, and that copy is a scope someone really holds. So change a scope field with the server stopped, or run bun run db:scopes in the same deploy, before anyone signs in. The backfill gives every such row its record's scope, and takes away the scope of a row whose record has none. A server that stays up says at start-up when rows are waiting for the backfill, and in which tables. For rows that carry another scope than their record's it holds a few hundred rows of each table against their records and says so in a line of its own, naming what is exposed. That is a sample: finding none is not proof there are none. A serverless host does not look each time it starts: run the backfill there without being told. The backfill never leaves a row behind a record that moves beside it. For a row that carries anything but its record's scope it holds the record, reads its scope again, and writes the row in that same transaction, which is how a move itself takes a record's rows with it. A move that is under way is waited for, and a move that comes after waits and takes the rows on. Synced mail and meetings are lines on a record's timeline, and follow these rules with the rest of it. Which mailbox was read up to where is each person's own and belongs to no record. Marketing posts, ad results and connected accounts hang off no record. * is never a record's scope. A record that has * in its scope field (text typed before scopes were turned on) is a record with no scope: only a role with all sees it, and what is hung on it has no scope either. Give it a real one. Owners and assignees. A user field can name anyone, including someone who can't open the record. The pickers only offer people who share the scope. Saved views are shared by everyone who uses the object, whatever their scope: a view's name and its filters are seen by all. The titles of records a filter names are not. A view everyone shares is renamed, re-filtered, rearranged and deleted only by someone who can change something: a read-only person, and someone who holds nothing, are refused, and so is their resetting a view the config declares. They still sort and filter what is on their own screen, and make, change and delete views only they see. Files. The file store knows nothing of scopes, so the CRM checks every folder and file it is asked about: a record's folder, and everything under it, is only reached by those who reach the record. A file is opened, renamed, moved or deleted through the folder it is in (the link carries it), never by its id alone. Whether it is in that folder is asked of the file itself when the folder holds more than a listing shows. Anyone with access to the store itself still reads all of it. The shared library, and folders the team made outside a record's folder, are everyone's. Grants for the tool API. A workflow started for a record is handed a token signed with APP_SECRET (HMAC-SHA256, compared in constant time). It states the record's scope, the record, who started the work and when it ends: fifteen minutes later unless scopes.grantMinutes says. The tool API answers a call that carries it about that record only, and refuses it once that person is off the access list. That one record goes with the call into your own code: a hook, a handler or a run target that a change made under a grant sets off reads and changes, through @swirls/spools/extensions, that record and no other ( getRecord, updateRecord, its timeline, tasks, notes and folder), and is refused listRecords, createRecord and the rest that reach further. Code that must reach further says so with asSystem. This is what those functions do, not a wall around your code: an extension that goes past them to the server's own modules is working with the grant's whole scope, as it always could. Each time it is used it is cut down to what that person holds at that moment: someone who has lost the scope has lost the grant with it, and someone who may now only read it has a grant that only reads. As with everything a person holds, that is within the minute. Whoever holds a grant has its reach until then, so workflows must keep it out of prompts and messages. See Swirls. Actions, automations, sequences and email are changes. Running an action on a record, writing to its email address, and anything else that starts a workflow, the app's own handler or an email sequence for it, needs the right to change that record. It is checked before anything is started or sent, so a read-only person's click starts no workflow and sends no email. The same goes for everything the server does outside its database: the app's before hooks run, and the file store is asked to take, move or delete something, only for someone who may make that change, and with nobody said none of it happens. A test reads the server's source for every such place and fails when one is added without saying what settles who may do it ( packages/spools/tests/unit/effects-after-checks.test.ts). The assistant. Its chats must be each person's own, which needs federation with your sign-in provider: with a project API key everyone would read everyone's chats, so the assistant is refused and says so. And the assistant's record tools are refused in chat, because a chat has no way to carry a grant that the model can't relay; see Swirls. Workflows started from a record do carry one. Marketing, integrations and guides are not scoped: the Marketing page and its posts are the whole business's, and everyone on the access list reads them. Changing them is for someone who can change something. A person who can change no record, because their roles are all read-only or because they hold nothing, reads Marketing and Integrations and changes neither: they don't draft, edit, schedule, publish, take back or delete a post, have the website checked or read, or have ad results read again, and they don't connect, replace or disconnect an account the team or a group shares. Each is refused before anything is written, started or sent (\"You can look at Marketing, but not change it.\"), and the pages show them no control for it. What is their own stays theirs: a mailbox or another account of their own, the guides they have seen, their favourites, the views only they see. A post that someone who may scheduled goes out at its time with nobody signed in, as before. A Spool without scopes is as it was: every CRM user does all of this. Marketing is written by nobody on a record's behalf. What is on the Marketing page is read by every scope, and by people who hold none. So a call to the tool API under a grant made for one record is refused the tools that write there ( draft_post, save_site_profile, post_result, save_ads): a workflow that can read one scope's record could otherwise be talked into copying it to where everyone reads, by text on that record's timeline. The marketing workflows that answer through those tools are started for no record and carry no grant. And the assistant drafts no post in a chat: a chat's call can't say whose draft it would be, and the person chatting may be one who can change nothing. A person writes it on the Marketing page. A credential is not bound to a record. getAccessToken and findConnections in @swirls/spools/extensions answer a hook that runs under a grant made for one record as they answer any other. A hook that a workflow's write-back sets off is where an app sends a changed record to the books, and a token for another service is no way into the CRM's records. What your code sends with it is your code's to decide. What a refusal gives away. A record that can't be deleted or moved says why, and the reason can be records its reader can't see: \"deals of a branch you can't change point at it\", \"it is linked to contacts of a branch you can't change\", \"parts need it\". So someone who may change a record learns that some record of that kind, out of their reach, points at it. That is all they learn: never how many, which, or of which scope. It is kept on purpose. The alternative is a delete that fails with no reason, which nobody could act on. Connections are shared across scopes, and a group is not a scope. An account connected on the Integrations page is used the same way whatever scope a person works in: a teammate's own by that teammate, one shared with the team or with a group by everyone on the access list. A provider's group is a label that says which account to use (a branch's books). It is not a permission: holding a scope gives nobody a group, and a group reaches no record. A connection is a token for another service and never a way into the CRM's records: a handler that uses one reads and writes records with the access of whoever it runs for, and code with nobody behind it reaches a scoped record only inside asSystem. See Integrations. Read-only people are shown no edit controls. Someone who writes nothing gets no buttons to add, import or delete records, no editing in a table cell, a board card or a record's details, no record actions, and nothing to add a task, a note, a logged call or an email, or to upload, rename, move or delete a file. Nor anything to rename, rearrange or delete a view everyone shares: they are offered \"Save as my view\" instead. Someone who writes some scopes and only reads others gets them record by record. This is the page being tidy, not the rule: the server refuses each change itself, and says why, whatever a page shows. Starring a favourite is a person's own and stays, and so are the views only they see. A record others must have. A required relation is kept by the database ( ON DELETE RESTRICT): the record it points at can't be deleted while any record needs it. Staff are told so in words (\"This product can't be deleted while parts need it\"), with or without scopes, and not shown the database's own, which name its foreign key. Every store is tested, and so is a browser. The scope tests run on PGlite, on Postgres through Effect SQL and through Prisma, in CI. The browser tests run the starter with scopes laid over its config and two branches' records: lists, search, relation pickers, a record's linked records, notes, tasks and files, the address of another branch's record, a read-only person's page and a change sent past it, and head office switching branch and moving a record. The ones that set two changes against each other (a move and a new link, a delete and a new link, for relations and for many-to-many links) run as two connections on a real Postgres, and so do the ones that set changes holding the same records from different ends against each other, a move of scope among them. A database adapter of your own inherits the guard; run the integration tests on it ( TEST_STORE) before relying on it. The HTTP API A headless Spool, or any Spool that mounts httpApi(), answers the CRM's operations over HTTP. It is the interface's own server functions by another route: each operation is defined once, and the access list, role access, record scopes and record rules are checked in the same place for both. There is no operation that runs as the system, and none that makes a key. Caller says who they are with Taken when The session cookie The request comes from the API's own site. A browser on another site is refused ( cross_site) before anything runs, so another site's page can't act through a signed-in teammate A sign-in token (bearer) You named the front end it was issued to ( tokens.authorizedParties). With none named, no token opens the API in production. A cookie sent beside a token counts for nothing An API key (bearer, spk_) The server was started with keys: true, the vault opens the key's seal for its own row, and the seal agrees with the row. It acts as one teammate, and that teammate's access is its What to know about keys: The database holds no key. A row keeps a seal the vault made for that row: the hash of the secret, whose key it is, whether it only reads and when it ends. Reading the table yields nothing that works, and a row someone writes, copies or edits by hand is refused, because the seal is what a key is judged by. A Spool with no vault has no keys. A key ends. After 90 days unless it was made with another number or --never-expires. Revoking wipes the seal, and takes effect on the next request. A read-only key changes nothing. It is refused every operation that writes, and a read made with it does nothing on the side outside the database either. Whoever can run spools keys can make one as any teammate. That is someone with the app's folder and its environment, who could already read the database. A browser on another site may call only from the origins you name (CORS), a body over 1 MB is refused, and a write with an Idempotency-Key runs once. Its kept answer is sealed for its caller and their access at the time, so a repeat after their access changed gets the status without the body. Your own door The HTTP API above is for teammates. Spools has no door for people who are not teammates: an app builds its own behind publicRoute from small helpers ( Building your own door). The framework enforces nothing about who such a caller is or what they reach; each helper does one thing, and stands on its own: Helper What it guarantees verifyToken A user id only for a token the auth adapter checks as issued to one of the origins named ( azp); with none named, only a developer's or a test's server takes any. Never a network call per token ( clerk(): a keyring, or CLERK_JWT_KEY offline) bearerToken Only the Authorization: Bearer header: a session cookie sent alongside counts for nothing callerAddress The address TRUST_PROXY (1 to 10, anything else is none) says to trust, or null when it can't be known: never one shared value to count by hitLimit, peekLimit, consumeLimit Your buckets are counted as app:, apart from the framework's; bad numbers are refused; with storeRateLimits() the same on every instance, no more than the limit however callers race idempotent A key is the caller's alone ( app:, apart from teammates' staff:): the caller must be a verifiedCaller (its type, and a runtime check of its shape), made from ids the app verified. Answers sealed by the vault for their row and caller, never kept in the clear sealText, openText Sealed for an owner you name, kept apart from the framework's secrets ( app:); nothing sealed without a vault; text in the clear is refused writeKeptFields Only readonly fields, so no person's change goes untold; the record's rules still hold changedSinceAs Narrows the answer by your own check; a check that fails says no asSystem Lifts record scopes and role access for what your code does inside it, and nothing else: there is no other guard to lift What is yours, because nothing in the framework knows your callers: Who they are. Map a verified user id to a record of yours by a readonly field, written only by your code, so no teammate, import or the assistant can point a record at someone else. What they reach. Your endpoint runs with nobody signed in: a read through @swirls/spools/extensions reaches every record (record scopes refuse a scoped object until your code says asSystem). Check every id a caller sends against your own rules, and answer one out of reach exactly as one that doesn't exist. What leaves. Answer an explicit list of fields, never a record as it is read. What they write. Write only the fields you name. Hooks and automations run for those writes as for any other; a before hook's values are written as the server's. Residual risks you accept What the framework does not close, by design or for now. Each is yours to weigh: Uniqueness 409s tell anyone whose write clashes that a record with those values exists, across rows and record scopes. An object-level changedSince key tells when any record of the object changed, records out of reach included. Values a before hook returns are written as the server's: not checked against readonly. A write can run twice if storing its idempotent answer fails on every retry: the claim then goes stale and a repeat runs. Quotas count in fixed windows (a UTC day, a minute): about twice a limit can go through around a window's edge. Signing keys Clerk rotates in are picked up within a minute of the first token that names them, and dropped keys within an hour. With the memory limiter, rate limits are per server instance: N instances allow about N times a limit, and a restart forgets. Without TRUST_PROXY callerAddress is null: an app that skips its address limit then relies on the platform in front to tell callers apart. A file store that doesn't enforce an upload's declared type or size relies on the CRM's check at finish, which a store that can't say a size skips. idempotent takes only a verifiedCaller, but what the app verified before making one is its own: an id taken from the request instead of a verified token lets one caller replay another's answers. An endpoint for outside callers is as safe as its own checks: the framework applies no field allowlist, ownership rule or role to it. Locks and deleting A lock or a parentLock keeps a record as it is for everyone, the server's own work included: no change gets past one. Deleting is the one exception, so that data a lock holds is never undeletable for good (an erasure request, a submission made by mistake): the server's own work, said out loud with asSystem, may delete a locked record, a record its parent locks, or the parent, which takes the records it locks with it in one hold. A person, the assistant and code with nobody said are refused. Gate such an action in your app yourself (an admin-only handler or server function that runs it inside asSystem): the framework can't tell a mistaken submission from a wanted one. The records it pointed at say on their timeline who removed it (the actor your code passes) and that it was a system removal. Things to know The development parts don't run in production. A copy with no keys uses a database inside the server and a sign-in that lets everyone in. In a build both are left out: src/spool.server.ts picks them only when NODE_ENV isn't production, which a build fixes, and the development sign-in refuses to start under NODE_ENV=production. A deployment missing its keys stops at start-up. Clerk development instances are for testing. One verifies any address ending in +clerk_test for whoever types a fixed code. A deployment never accepts such an address, and says at start-up when it is running on a development instance's keys ( sk_test_). Use the production instance's keys where real people sign in. Field encryption isn't active yet. Fields marked encrypted are stored as plaintext until @cipherstash/stack-prisma supports Prisma 8. Treat the database as holding plaintext PII and secure it accordingly. AI sees CRM data. Swirls workflows and the assistant receive record contents, including text that came from outside your team (imports, pasted notes). Treat that text as untrusted input to the model. Mark fields people outside the team write \"untrusted\": true ( Record rules): the tool API then hands their values over as { \"untrusted\": true, \"text\": \"...\" }, which the assistant's instructions tell it is data, never instructions. Every timeline line the tool API hands over is wrapped too, whoever wrote it, and a line about a change to an untrusted field doesn't repeat the value. The assistant's tools can only read and modify CRM records and add notes, and they can't change email addresses. A record made through the tool API starts no automations, so nothing emails an address the model chose. Its replies never load an image, so text it read can't have a browser send what it knows to another server. Workflows email your team. Mailboxes. For the account a teammate signs in with, the auth provider holds the Google or Microsoft tokens and the CRM asks it for one when it reads or sends. With Clerk, access to your Clerk secret key is access to those mailboxes. With Better Auth they are in your own database, encrypted with BETTER_AUTH_SECRET, so that secret together with the database is. Only the subject, a short preview and the time of mail involving a known contact are stored; message bodies are never fetched. Whose mail it is comes from the address in the From header, never the name beside it. Only the mailbox itself says a teammate sent a message: Gmail's Sent label, or Microsoft's Sent Items folder. Junk and deleted mail are read past. See docs/mailbox.md. Connected accounts. Tokens for accounts connected on the Integrations page are sealed by the vault in the app before they are stored; the database holds only ciphertext and there is no plaintext fallback. Each is sealed for the row it is stored on, and is refused anywhere else, so someone who can write to the database can't move one teammate's tokens onto a connection of their own. The vault is CipherStash: its credentials ( CS_*) together with the database are access to those accounts, and a production server does not start without them. The OAuth flow uses PKCE and a state signed with APP_SECRET that names the teammate and is tied to their browser by a cookie. A teammate removed from access keeps their stored tokens until they are deleted, but their mailboxes stop being read, and code acting for them is given no token. Disconnecting revokes the token at the provider unless another connection holds the same account, whose access revoking would end too. See docs/integrations.md. Shared connections. A provider can make its connections the team's, or one group's ( shared in src/app/extensions.ts). Every CRM user can then see that the connection exists and act through it, whoever connected it, and it goes on working after that person is removed from access: it was connected for the business, not for them. So connect an account the business owns, and remember that removing a person does not remove what they connected for the team; disconnect it if it should go with them. Who may connect, reconnect and disconnect one is every CRM user, or only those the provider's canManage names. It is checked on the server when a connection is started, again when the provider sends the browser back, and on disconnect. A rule that fails lets nobody in. The signed state also says whose the connection will be (the team's, or which group's), and the callback reads that from nowhere else, then checks it against what the provider says now. A state for a personal connection can't be replayed to make a shared one, nor one group's for another. Which account a shared connection is comes from the provider, asked with the token it just issued. Nothing in the callback's address is taken as the answer, because the address passes through the browser: a connection whose provider code did not get an answer from the provider is refused. Otherwise a teammate could authorize an account of their own and send it back under the team's name, replacing the team's tokens with theirs. The CRM checks that the provider was asked, not what it was asked: a provider you add must ask for something only the right account can answer. An account is one connection for the team, or one for a group. The database holds it to one row, so two people connecting it at once can't leave two sets of tokens. A shared connection's tokens are sealed for a name that includes whose it is. Editing a row in the database to turn a personal connection into a shared one, or to move it to another group, leaves tokens the CRM refuses to open. Groups are labels today, not permissions: any CRM user can use any group's connection. findConnections({ usableBy }) and getAccessToken(id, { as }) refuse someone who is not a CRM user, their own connections included, and a personal connection to anyone but its owner, when an app's code says who it is acting for. They also refuse when the person named is nobody: as: ctx.actor in a handler that ran with no one signed in is not a way to be trusted. Only code that names no person at all ( getAccessToken(id), findConnections without usableBy) is trusted, so the choice is visible where it is made. No browser is sent a token. The page is sent the account's name, whose it is, who connected it and its state. Marketing. An account connected for marketing (LinkedIn, X, Google Ads) is a shared connection: any CRM user can publish through it from the Marketing page, whoever connected it, and can see, reconnect or disconnect it on the Integrations page, unless the app names who may with marketing.canManage in src/app/extensions.ts. Its tokens are sealed like any other, and no browser is sent one. META_ACCESS_TOKEN is a token for the business's page and ad account: treat it as you treat the database's password. Only a CRM user can schedule or publish a post. The tool API can save a draft and nothing more, so text the assistant read can't put a post out. The website check fetches the address in crm.config.json and no other, and the install code it shows is built only from ids that match their vendor's form. See docs/marketing.md. Files. The file store's keys stay on the server; a browser is only ever given a transfer URL for the one file it is sending, or a five-minute link to the one file it is opening, after the CRM session is checked. Without record scopes or role access, anyone who may use the CRM can open, rename, move and delete any file. With them, a record's folder and what is under it is reached only by those who reach the record, and the shared library and the team's own folders stay everyone's. Anyone with access to the store itself can read all of it: its folders are not permission boundaries. With FlashDrive the key reaches every drive in its workspace. Files the server hands out itself are never run by the browser as a page of the CRM. See docs/files.md. Assistant conversations are shared across CRM users when using a project API key (see docs/swirls.md). Secrets. Every key in.env.example is server-only except CLERK_PUBLISHABLE_KEY, which is meant for the browser. Rotate SWIRLS_APP_TOKEN in both the app and Swirls together. Cross-site requests. Server functions and the assistant endpoint reject requests that don't come from the app's own origin ( csrfMiddleware in src/start.ts), so another site can't act through a signed-in user's session. Keep that middleware first if you add your own. Every answer also tells the browser not to show the CRM in another site's frame and to take each file as the type it is sent as. Send Strict-Transport-Security from the proxy in front of the server, which is where HTTPS ends. Supabase Data API. The app never uses it. supabase/config.toml doesn't expose public. Every generated table has row-level security on with no policies ( @@rls in the Prisma schema), and bun run db:push / db:migrate run spools harden, which revokes the anon and authenticated roles on every table and fails if RLS is off anywhere. On hosted Supabase, also remove public from Settings → API → Exposed schemas." }, { "path": "/docs/upgrading", @@ -1348,6 +1431,11 @@ "title": "Versioning", "level": 2 }, + { + "id": "headless-api-keys-and-record-types-013", + "title": "Headless, API keys and record types (0.13)", + "level": 2 + }, { "id": "layouts-09", "title": "Layouts (0.9)", @@ -1404,7 +1492,7 @@ "level": 2 } ], - "text": "Upgrading The framework is a package, so an update is a version: Read the changelog first. Breaking changes are listed with what to do about them. Your own files ( crm.config.json, src/, swirls/) never change under you. When an update changes the tables The changelog says when a version changes the tables, and what changes. What you run then depends on how each of your databases is kept up: The database What to run after bun run crm:gen A Postgres you push to ( db:push) bun run db:push A Postgres you migrate ( db:plan, db:migrate) bun run db:plan -- --name , commit the migration, then bun run db:migrate PGlite (.data/pglite) Nothing. The server brings it up to date when it starts If you push to a local database and migrate production, plan the migration before you push. db:plan starts from the db ref ( migrations/app/refs/db.json), and db:push moves that ref on to the new tables, which leaves the plan nothing to start from. db:plan then stops with MIGRATION.HASH_NOT_IN_GRAPH. It stops with MIGRATION.PLAN_ORIGIN_UNKNOWN when there is no ref at all, because you have only ever migrated. Either way, say where to start: Read the plan before you apply it: it lists each operation and the SQL. A plan that would delete or rename a column is refused until you say so ( Deployment), and the changelog says when an update needs that. Running db:push or db:migrate a second time changes nothing. PGlite adds what is missing and drops an index a table no longer declares ( Database). It never drops a table or a column, so there is nothing to back up first and nothing to delete. Versioning The framework follows semantic versioning. Before 1.0, minor versions can include breaking changes. \"version\" in crm.config.json is the config format version. It changes only when the format breaks, and bun run crm:gen tells you if your config is on an older one. New pages and endpoints are new route files. The changelog gives them to you to copy; until you do, the feature is off. Layouts (0.9) Nothing changes until crm.config.json has a ui key. To use layouts: For pages of your own ( ui.pages), add the route file src/routes/_crm/pages.$page.tsx: bun run crm:gen says when it is missing. A record page's layout ( ui.records) needs no new file. An object with the key pages can't share a Spool with ui.pages: its list would be at their address. No table changes. Modules, record rules, role access and your own door (0.7) A Spool with no modules and none of the new config keys works as before, apart from what changes without any new key. Everything else is off until the config or src/spool.server.ts says otherwise. The database Table or column When Holds change_signals Always A \"last changed\" mark for each object and record ( Database) idempotent_requests Always Writes sent with an Idempotency-Key ( Extending) activities.field Always For a change line, the key of the field it changed. Empty on lines written before rate_limit_slots Only with rateLimits: storeRateLimits() Rate limits counted in the database ( Adapters) _ Only with a module that keeps tables of its own A module's private tables ( Modules) A unique index Only for each unique rule in the config The rule, partial when it has where ( Database) Nothing is renamed or dropped, so no plan needs to be told it may delete anything. PGlite adds the tables and the column as the server starts. What changes without any new key modules in crm.config.json is now the modules' settings. Before, a key the config's schema didn't know was ignored. Now settings under modules. for a module that src/spool.server.ts doesn't list are refused when the server starts and by bun run crm:gen, and so are settings for a module that takes none. If your config has a modules key of its own, rename it. The tool API wraps every timeline line. The summary, body and author of each line that get hands a workflow or the assistant are now { \"untrusted\": true, \"text\": \"...\" }, not a string, whoever wrote the line. A workflow of yours that reads a record's timeline reads.text. Copy the two lines about wrapped values from the starter's swirls/assistant.swirls into your assistant's instructions, then swirls deploy. See Swirls. New scripts. A new Spool has \"db:rules\": \"spools rules\" in package.json. Add it, or run bunx spools rules. Fixes. The Prisma adapter names each column of an included record once. Times on a record's page are drawn the same on the server and in the browser. A search still loading no longer replaces a filter chosen after it. Modules Listing a module is three edits ( Use a module): modules in src/spool.server.ts, its settings in crm.config.json, and its browser half. A Spool made before this version has no place for the browser half yet. Add it once: Without the provider nothing breaks: the slots are empty, so a module's panels and sidebar links are not shown, while its objects, hooks and tables still work. Then run bunx spools modules, which lists the route files your modules expect and exits 1 until each is there. Record rules Uniqueness rules ( unique on an object) are unique indexes. Run bun run db:rules ( spools rules) after adding one and before db:push or db:plan: Postgres refuses to make the index over records that already break the rule. See Database. A clash is a Conflict, with the rule's name and your message, on every store. Code that relied on a constraint of your own (a migration adding a unique or exclusion constraint, and code that read the database's refusal) can move to unique in the config. Drop your own constraint in the same migration, or keep it: PGlite and Prisma leave a constraint they didn't make alone. Hooks that guarded fields (refusing a change to a field once written, keeping a field to the server, writing a correction trail) can become immutable, lock, readonly and audit ( Record rules). A readonly field is refused from a person's write before your before hook runs. Your hook, and code writing with actor: null, may still set it. An audit.note field must itself be readonly. A locked record is deleted only by the server's own work. A person, the assistant and code with nobody said are refused the delete of a record its lock holds, of a record its parent locks ( parentLock), and of a parent that locks others. Code that must remove one (an erasure request, a submission made by mistake) does it inside asSystem, behind a check of your own for who may ask. See Security. beforeDelete is a new hook: throw in it to refuse a delete. Role access access on a role, access.default and assistant.deny narrow what people and the assistant reach ( Roles). Without any of them nobody's reach changes, and roles still decide only what Home and the sidebar show. Once the config has one: Your own code runs with the role access of the teammate it runs for. A hook, a handler, a run target, a crmHandler or an apiRoute reads and writes through @swirls/spools/extensions as that person: an object their roles deny is not found, and a change to one they only read is refused. A hook that writes an object the person who caused it is kept from (an office-only ledger line when a designer closes a job) now fails until that write is inside asSystem ( Hooks and role access): A read-only object changes nothing of what hangs off its records. Someone who only reads jobs adds no note, task or logged call to one, completes no task on one, sends it no email, starts no action or sequence for it, and adds, renames, moves or deletes no file in its folder or a folder inside it. A role with \"readOnly\": true changes nothing in the file library, shared views, Marketing or shared connections either. Your own code's addActivity, createTask and createNote keep to the same for the teammate it runs for: wrap the server's own bookkeeping in asSystem. A file is opened or changed through the folder it is in (the file browser's links carry it) for anyone role access keeps something from; a link of your own to /api/files/ adds ?folder=. asSystem lifts role access as well as record scopes. Code already inside it reaches every object. Keep its uses few, and never hand what it read to someone it is kept from. Code with nobody behind it holds no role. A cron route, a script, a publicRoute and the config's automations are not narrowed, and access.default does not apply to them. Timeline lines stop naming records of a denied object. A change to a relation that leads to an object any role, access.default or assistant.deny keeps from someone is written \"updated Client\", for everyone who reads the record. Lines written before are not changed until you run bunx spools timeline redact, once, after adding the first deny. It can't fix a line written under a label the field no longer has, nor a title in a note, an email or a line your own code wrote ( Roles). The assistant is not narrowed by roles. Name the objects it must never reach in assistant.deny. Live updates Off until \"live\": { \"seconds\": 20 } is in the config ( Live updates). Pages call one new server function ( changedSinceFn), which needs no route file. Your own door Endpoints for people who are not teammates are built from helpers in @swirls/spools/extensions, behind publicRoute ( Building your own door). Three things to set where it runs ( Deployment): TRUST_PROXY, your front end's origins for verifyToken, and CLERK_JWT_KEY with clerk(). apiRoute(name, answer, { idempotency: {} }) gives a teammate's endpoint the same once-only writes. If you built on this version before it was released, four things changed on the way: callerAddress(headers) answers null when the address can't be known ( TRUST_PROXY unset or mistyped). There is no shared stand-in value. Skip the address limit for null, or refuse: never count a limit under it. idempotent takes only a caller made with verifiedCaller(namespace,...verifiedIds). A rate limiter of your own implements consume and wait beside hit and record. A person who could delete a record under its own lock no longer can (above). Record scopes A Spool without scopes in crm.config.json needs the schema change and nothing more ( bun run crm:gen, bun run db:push): seven system tables gain a scope column that stays empty. Before you add scopes, and each time you change it: Run bun run db:scopes after every change to scopes.objects, not only the first time. It gives the rows that hang off records (timeline, tasks, notes, favourites, folders, uploads, sequence runs) their record's scope, where they have none or carry one from before the change. Until it has run, rows on a newly scoped object's records are only there for a role with all, and their sequence runs are held. A server that stays up says at start-up when rows are waiting. See Security. Code with nobody signed in changes no record until it says it is the system. With scopes on, a script, a webhook or an endpoint of your own that creates or changes records with nobody behind it is refused, for a shared object's records too. Wrap the work in asSystem from @swirls/spools/extensions. A workflow's write-back binds your hooks to its record. With scopes on, a hook or an automation's handler set off by a tool call made under a grant reaches, through @swirls/spools/extensions, the one record the grant was made for. One that lists or creates other records there needs asSystem. See Extending. Remove links that cross scopes. A relations field between two scoped objects may hold links made before scopes were on that join records of two scopes. They are left as they are and shown only to someone who holds both, and such a record can't move scope or be deleted by someone who holds one. Unlink them as head office. Send the grant back. Workflows that write through the tool API send the grant from their input as the X-Spools-Grant header. See Swirls. Name the scopes there are. A scope a person holds counts only when it is one of this Spool's: an option of the scope field where that is a select, and otherwise one the resolver lists. With Clerk organizations, name the ones that are scopes with clerk({ scopes: 'organizations', scopesFrom: ['org_...'] }); without it no organization is a scope. A resolver of your own needs list where a scope field is text or a relation. The server says at start-up when nothing is listed. See Signing in. Someone who can change no record changes nothing else. With scopes on, a read-only person and someone who holds no scope read Marketing and Integrations and are refused every change there: posts, the website's check and profile, ad results, and the accounts the team shares. If the people who run your marketing hold no scope, give them one with a role that writes. Change a scope field with the server stopped. If you move an object's scope to another field, run bun run db:scopes before anyone signs in again: until it has run, rows on a record are still read by the scope the old field gave them. For code of yours that imported the server's modules: what sendEmailFn does is now sendRecordEmail in @swirls/spools/server/workspace, and a store method can fail with ScopeRefused beside DatabaseError. From a copy of the repository Before Spools was a package, a CRM was a copy of the whole repository that merged updates from it. Moving one over changes no data: the tables are the same, column for column, and crm.config.json and every environment variable keep their names. Make a Spool in a folder of its own with bun create @swirls/spools, and copy what is yours over it: crm.config.json, src/app, src/styles.css, swirls, migrations,.env, vercel.json if you changed it, and any pages you added to src/routes. Keep your repository's history by doing this on a branch of it. Say what it runs on in src/spool.server.ts. These are the services a copy used, so nothing behaves differently: Change your imports. In src/app/extensions.ts, '../crm/extensions' and '../server/extension-api' are both '@swirls/spools/extensions'. Change your own server code that used the database: it asks for Store instead of Database ( Database). AuthError replaces ClerkError and AgentsError replaces SwirlsError. Find a home for changes you made to the framework. Most fit an extension point: hooks, handlers, pages, or an adapter. Open an issue for one that doesn't. Run bun run crm:gen and bun run check. crm:gen should leave prisma/schema.json exactly as it was, which is how you know the database needs no change. The Resend webhook keeps its address: /api/webhooks/resend is now the same as /api/webhooks/email. The stubbed-sign-in harness reads DEV_AUTH_EMAIL and DEV_AUTH_SIGNED_OUT where it read E2E_EMAIL and E2E_SIGNED_OUT. On a host with no long-lived process other than Vercel, set SERVERLESS=1. Vercel is still worked out from the host. Its build is now vercel() from @swirls/spools/vite in vite.config.ts, where a copy carried its own Nitro plugin." + "text": "Upgrading The framework is a package, so an update is a version: Read the changelog first. Breaking changes are listed with what to do about them. Your own files ( crm.config.json, src/, swirls/) never change under you. When an update changes the tables The changelog says when a version changes the tables, and what changes. What you run then depends on how each of your databases is kept up: The database What to run after bun run crm:gen A Postgres you push to ( db:push) bun run db:push A Postgres you migrate ( db:plan, db:migrate) bun run db:plan -- --name , commit the migration, then bun run db:migrate PGlite (.data/pglite) Nothing. The server brings it up to date when it starts If you push to a local database and migrate production, plan the migration before you push. db:plan starts from the db ref ( migrations/app/refs/db.json), and db:push moves that ref on to the new tables, which leaves the plan nothing to start from. db:plan then stops with MIGRATION.HASH_NOT_IN_GRAPH. It stops with MIGRATION.PLAN_ORIGIN_UNKNOWN when there is no ref at all, because you have only ever migrated. Either way, say where to start: Read the plan before you apply it: it lists each operation and the SQL. A plan that would delete or rename a column is refused until you say so ( Deployment), and the changelog says when an update needs that. Running db:push or db:migrate a second time changes nothing. PGlite adds what is missing and drops an index a table no longer declares ( Database). It never drops a table or a column, so there is nothing to back up first and nothing to delete. Versioning The framework follows semantic versioning. Before 1.0, minor versions can include breaking changes. \"version\" in crm.config.json is the config format version. It changes only when the format breaks, and bun run crm:gen tells you if your config is on an older one. New pages and endpoints are new route files. The changelog gives them to you to copy; until you do, the feature is off. Headless, API keys and record types (0.13) This version adds a table, so it changes the tables: api_keys holds the keys scripts and services call the HTTP API with ( API keys). Run bun run crm:gen, then bun run db:push or your migration. It is empty until someone runs spools keys create, and never read unless the HTTP API is given keys: true. Nothing else changes for an app that uses the interface. Three things to know: bun run crm:gen now also writes src/crm.types.ts, the types of your records for a front end of your own. Commit it with the other generated files, and add it to what your formatter and linter leave alone. If CI checks that generated files are up to date, add it there too. The spans of server functions are named after their operations ( records.get where it was crm.getRecord). A dashboard or alert that reads span names needs the new ones. @swirls/spools/auth/clerk is unchanged. A Spool with no interface imports Clerk's adapter from @swirls/spools/auth/clerk/backend instead, which needs @clerk/backend and APP_URL set to the address of your front end (or authorizedParties). CipherStash is the vault, and production needs it. @swirls/spools/vault/aes is gone, with VAULT_KEY and VAULT_OLD_KEYS. Use vault: cipherstash() in src/spool.server.ts and set CS_WORKSPACE_CRN, CS_CLIENT_ID, CS_CLIENT_KEY and CS_CLIENT_ACCESS_KEY: a production server no longer starts without them. Nothing the AES vault sealed is opened by CipherStash, so teammates connect their accounts again. On your own machine, with the variables unset, a stand-in seals with a key that is in the framework's source: it lets you work, protects nothing, and what it sealed is refused by a server with CipherStash ( Adapters). Three changes can sign people out or change an answer, on an app that uses the interface too: Clerk checks which front end a session was issued to. On a production server, clerk() now takes a session only when Clerk issued it to the origin of APP_URL. If people use the CRM at another address than APP_URL (a second domain, www), name every one: clerk({ authorizedParties: ['https://crm.example.com', 'https://www.example.com'] }). A deployment whose APP_URL is still a localhost address is left as it was. A sign-in link is spent only from your own site. With Better Auth, /api/auth/magic-link/verify opened from another site goes to /sign-in and signs nobody in. The sign-in page's own button is unaffected. A repeated write shows less once access changes. An Idempotency-Key repeat by someone whose scopes or role access changed since the first answer gets its status with Idempotent-Body: withheld, as a Spool with no vault always answers. To serve the HTTP API from a Spool that has the interface as well, mount httpApi() at a route of your own. To start one with no interface, see Headless. Layouts (0.9) Nothing changes until crm.config.json has a ui key. To use layouts: For pages of your own ( ui.pages), add the route file src/routes/_crm/pages.$page.tsx: bun run crm:gen says when it is missing. A record page's layout ( ui.records) needs no new file. An object with the key pages can't share a Spool with ui.pages: its list would be at their address. No table changes. Modules, record rules, role access and your own door (0.7) A Spool with no modules and none of the new config keys works as before, apart from what changes without any new key. Everything else is off until the config or src/spool.server.ts says otherwise. The database Table or column When Holds change_signals Always A \"last changed\" mark for each object and record ( Database) idempotent_requests Always Writes sent with an Idempotency-Key ( Extending) activities.field Always For a change line, the key of the field it changed. Empty on lines written before rate_limit_slots Only with rateLimits: storeRateLimits() Rate limits counted in the database ( Adapters) _
Only with a module that keeps tables of its own A module's private tables ( Modules) A unique index Only for each unique rule in the config The rule, partial when it has where ( Database) Nothing is renamed or dropped, so no plan needs to be told it may delete anything. PGlite adds the tables and the column as the server starts. What changes without any new key modules in crm.config.json is now the modules' settings. Before, a key the config's schema didn't know was ignored. Now settings under modules. for a module that src/spool.server.ts doesn't list are refused when the server starts and by bun run crm:gen, and so are settings for a module that takes none. If your config has a modules key of its own, rename it. The tool API wraps every timeline line. The summary, body and author of each line that get hands a workflow or the assistant are now { \"untrusted\": true, \"text\": \"...\" }, not a string, whoever wrote the line. A workflow of yours that reads a record's timeline reads.text. Copy the two lines about wrapped values from the starter's swirls/assistant.swirls into your assistant's instructions, then swirls deploy. See Swirls. New scripts. A new Spool has \"db:rules\": \"spools rules\" in package.json. Add it, or run bunx spools rules. Fixes. The Prisma adapter names each column of an included record once. Times on a record's page are drawn the same on the server and in the browser. A search still loading no longer replaces a filter chosen after it. Modules Listing a module is three edits ( Use a module): modules in src/spool.server.ts, its settings in crm.config.json, and its browser half. A Spool made before this version has no place for the browser half yet. Add it once: Without the provider nothing breaks: the slots are empty, so a module's panels and sidebar links are not shown, while its objects, hooks and tables still work. Then run bunx spools modules, which lists the route files your modules expect and exits 1 until each is there. Record rules Uniqueness rules ( unique on an object) are unique indexes. Run bun run db:rules ( spools rules) after adding one and before db:push or db:plan: Postgres refuses to make the index over records that already break the rule. See Database. A clash is a Conflict, with the rule's name and your message, on every store. Code that relied on a constraint of your own (a migration adding a unique or exclusion constraint, and code that read the database's refusal) can move to unique in the config. Drop your own constraint in the same migration, or keep it: PGlite and Prisma leave a constraint they didn't make alone. Hooks that guarded fields (refusing a change to a field once written, keeping a field to the server, writing a correction trail) can become immutable, lock, readonly and audit ( Record rules). A readonly field is refused from a person's write before your before hook runs. Your hook, and code writing with actor: null, may still set it. An audit.note field must itself be readonly. A locked record is deleted only by the server's own work. A person, the assistant and code with nobody said are refused the delete of a record its lock holds, of a record its parent locks ( parentLock), and of a parent that locks others. Code that must remove one (an erasure request, a submission made by mistake) does it inside asSystem, behind a check of your own for who may ask. See Security. beforeDelete is a new hook: throw in it to refuse a delete. Role access access on a role, access.default and assistant.deny narrow what people and the assistant reach ( Roles). Without any of them nobody's reach changes, and roles still decide only what Home and the sidebar show. Once the config has one: Your own code runs with the role access of the teammate it runs for. A hook, a handler, a run target, a crmHandler or an apiRoute reads and writes through @swirls/spools/extensions as that person: an object their roles deny is not found, and a change to one they only read is refused. A hook that writes an object the person who caused it is kept from (an office-only ledger line when a designer closes a job) now fails until that write is inside asSystem ( Hooks and role access): A read-only object changes nothing of what hangs off its records. Someone who only reads jobs adds no note, task or logged call to one, completes no task on one, sends it no email, starts no action or sequence for it, and adds, renames, moves or deletes no file in its folder or a folder inside it. A role with \"readOnly\": true changes nothing in the file library, shared views, Marketing or shared connections either. Your own code's addActivity, createTask and createNote keep to the same for the teammate it runs for: wrap the server's own bookkeeping in asSystem. A file is opened or changed through the folder it is in (the file browser's links carry it) for anyone role access keeps something from; a link of your own to /api/files/ adds ?folder=. asSystem lifts role access as well as record scopes. Code already inside it reaches every object. Keep its uses few, and never hand what it read to someone it is kept from. Code with nobody behind it holds no role. A cron route, a script, a publicRoute and the config's automations are not narrowed, and access.default does not apply to them. Timeline lines stop naming records of a denied object. A change to a relation that leads to an object any role, access.default or assistant.deny keeps from someone is written \"updated Client\", for everyone who reads the record. Lines written before are not changed until you run bunx spools timeline redact, once, after adding the first deny. It can't fix a line written under a label the field no longer has, nor a title in a note, an email or a line your own code wrote ( Roles). The assistant is not narrowed by roles. Name the objects it must never reach in assistant.deny. Live updates Off until \"live\": { \"seconds\": 20 } is in the config ( Live updates). Pages call one new server function ( changedSinceFn), which needs no route file. Your own door Endpoints for people who are not teammates are built from helpers in @swirls/spools/extensions, behind publicRoute ( Building your own door). Three things to set where it runs ( Deployment): TRUST_PROXY, your front end's origins for verifyToken, and CLERK_JWT_KEY with clerk(). apiRoute(name, answer, { idempotency: {} }) gives a teammate's endpoint the same once-only writes. If you built on this version before it was released, four things changed on the way: callerAddress(headers) answers null when the address can't be known ( TRUST_PROXY unset or mistyped). There is no shared stand-in value. Skip the address limit for null, or refuse: never count a limit under it. idempotent takes only a caller made with verifiedCaller(namespace,...verifiedIds). A rate limiter of your own implements consume and wait beside hit and record. A person who could delete a record under its own lock no longer can (above). Record scopes A Spool without scopes in crm.config.json needs the schema change and nothing more ( bun run crm:gen, bun run db:push): seven system tables gain a scope column that stays empty. Before you add scopes, and each time you change it: Run bun run db:scopes after every change to scopes.objects, not only the first time. It gives the rows that hang off records (timeline, tasks, notes, favourites, folders, uploads, sequence runs) their record's scope, where they have none or carry one from before the change. Until it has run, rows on a newly scoped object's records are only there for a role with all, and their sequence runs are held. A server that stays up says at start-up when rows are waiting. See Security. Code with nobody signed in changes no record until it says it is the system. With scopes on, a script, a webhook or an endpoint of your own that creates or changes records with nobody behind it is refused, for a shared object's records too. Wrap the work in asSystem from @swirls/spools/extensions. A workflow's write-back binds your hooks to its record. With scopes on, a hook or an automation's handler set off by a tool call made under a grant reaches, through @swirls/spools/extensions, the one record the grant was made for. One that lists or creates other records there needs asSystem. See Extending. Remove links that cross scopes. A relations field between two scoped objects may hold links made before scopes were on that join records of two scopes. They are left as they are and shown only to someone who holds both, and such a record can't move scope or be deleted by someone who holds one. Unlink them as head office. Send the grant back. Workflows that write through the tool API send the grant from their input as the X-Spools-Grant header. See Swirls. Name the scopes there are. A scope a person holds counts only when it is one of this Spool's: an option of the scope field where that is a select, and otherwise one the resolver lists. With Clerk organizations, name the ones that are scopes with clerk({ scopes: 'organizations', scopesFrom: ['org_...'] }); without it no organization is a scope. A resolver of your own needs list where a scope field is text or a relation. The server says at start-up when nothing is listed. See Signing in. Someone who can change no record changes nothing else. With scopes on, a read-only person and someone who holds no scope read Marketing and Integrations and are refused every change there: posts, the website's check and profile, ad results, and the accounts the team shares. If the people who run your marketing hold no scope, give them one with a role that writes. Change a scope field with the server stopped. If you move an object's scope to another field, run bun run db:scopes before anyone signs in again: until it has run, rows on a record are still read by the scope the old field gave them. For code of yours that imported the server's modules: what sendEmailFn does is now sendRecordEmail in @swirls/spools/server/workspace, and a store method can fail with ScopeRefused beside DatabaseError. From a copy of the repository Before Spools was a package, a CRM was a copy of the whole repository that merged updates from it. Moving one over changes no data: the tables are the same, column for column, and crm.config.json and every environment variable keep their names. Make a Spool in a folder of its own with bun create @swirls/spools, and copy what is yours over it: crm.config.json, src/app, src/styles.css, swirls, migrations,.env, vercel.json if you changed it, and any pages you added to src/routes. Keep your repository's history by doing this on a branch of it. Say what it runs on in src/spool.server.ts. These are the services a copy used, so nothing behaves differently: Change your imports. In src/app/extensions.ts, '../crm/extensions' and '../server/extension-api' are both '@swirls/spools/extensions'. Change your own server code that used the database: it asks for Store instead of Database ( Database). AuthError replaces ClerkError and AgentsError replaces SwirlsError. Find a home for changes you made to the framework. Most fit an extension point: hooks, handlers, pages, or an adapter. Open an issue for one that doesn't. Run bun run crm:gen and bun run check. crm:gen should leave prisma/schema.json exactly as it was, which is how you know the database needs no change. The Resend webhook keeps its address: /api/webhooks/resend is now the same as /api/webhooks/email. The stubbed-sign-in harness reads DEV_AUTH_EMAIL and DEV_AUTH_SIGNED_OUT where it read E2E_EMAIL and E2E_SIGNED_OUT. On a host with no long-lived process other than Vercel, set SERVERLESS=1. Vercel is still worked out from the host. Its build is now vercel() from @swirls/spools/vite in vite.config.ts, where a copy carried its own Nitro plugin." }, { "path": "/docs/architecture", @@ -1447,7 +1535,7 @@ "level": 2 } ], - "text": "Architecture A Spool is three things put together in src/spool.server.ts: a config that describes your business, your own code, and the services it runs on. The framework is a package, @swirls/spools. Your repository holds what is yours and a thin layer of files that mount the framework's pages and endpoints, so a new version is a new version number. Yours and the framework's Yours: edit freely What it is crm.config.json Your CRM: objects, fields, views, actions, automations, sequences, record rules, roles, and your own guides src/spool.server.ts, src/spool.ui.ts Your Spool: which adapters it runs on and which modules it uses, and their browser halves src/app/extensions.ts Handlers, hooks, run-target kinds, email transport, integration providers src/routes/** One small file per page and endpoint. Delete one to drop a page, replace one to write your own, add as many as you like src/styles.css Brand colours and theme overrides swirls/** Your Swirls workflows and assistant scripts/seed.ts Demo data Generated: never edit Source prisma/schema.prisma, prisma/schema.json, prisma/schema.d.ts, crm.config.schema.json bun run crm:gen src/routeTree.gen.ts bun run dev or bun run build migrations/** bun run db:plan The framework: packages/spools ( @swirls/spools) What it is src/crm/** The config contract, field and view registries, the generator, the interface src/server/** Records, the service layer, the tool API, sequences, the ports and the Effect runtime ( src/server/runtime/), the store ( src/server/store/) src/adapters/** The adapters that ship with it, by port src/pages/**, src/views/** Each page's route options, and what it renders (loaded when it is opened) src/api/** The handlers behind /api/* src/cli/** The spools command Feature sets that plug in from outside the app are modules: modules in defineSpool lists them, and src/spool.ui.ts their browser halves. Each brings config, code, private tables, settings, panels and pages, and is put together with the app's when the Spool is defined ( src/crm/compose.ts): in order, refusing anything two of them define. If you need something the extension points don't cover, open an issue: the aim is that nobody has to patch the framework. Layers Paths on this page are inside packages/spools/src unless they start with the name of one of your own files. The boundary is where a request becomes an Effect program. A server function's handler is crmHandler(...) and a route uses an adapter ( apiRoute, cronRoute, publicRoute, toolRoute). It asks the auth adapter for the session and reads the request before the program starts, checks the access list, runs the program on the process's one runtime, interrupts it if the browser goes away, and turns a typed error into the message the page shows. See Writing server code. Ports are the only way to the outside. The framework asks for a port ( yield* Store) and never imports an adapter, a vendor's SDK or your app; lint refuses it. Each has a stand-in for tests, and its time limit and retries come from one table ( policies.ts). See Adapters. records.ts is the data layer: config-driven CRUD, search and filters. It validates every write against the field definitions and the object's record rules ( record-rules.ts), and checks role access on every read and write ( object-access.ts), so both hold whoever calls it. After a change is kept it marks what changed ( signals.ts), which is what live pages ask about. service.ts is what callers use to change records. It wraps the data layer with extension hooks, timeline entries and automations, so a change behaves the same whether it comes from the UI or the assistant. views.ts merges the views in the config with what users saved in the app, and workspace.ts holds tasks, notes, favourites, reports and CSV export. Neither goes through service.ts: they aren't config objects, so hooks and automations don't apply to them. actions.ts resolves \"run\": \":\" targets through a registry: swirls, campaign and local are built in, and extensions can add kinds. Entry points authenticate, then call the service: server functions check the session and the allowlist, and the tool API and the cron routes each check a bearer token. An endpoint behind publicRoute is the one entry the framework checks nothing for: a webhook checks its signature, and a door of your own for people who are not teammates checks its callers with the helpers in @swirls/spools/extensions. Your code stays plain TypeScript. Hooks and handlers in src/app/extensions.ts return promises, and the browser never loads Effect. Modules are put together before anything runs. defineSpool merges each module's part of the config into the app's and checks the whole against the contract, composes their hooks (modules in order, then the app) and refuses clashes. Everything after ( service.ts, the registries, the store, spools gen) sees one config and one set of extensions, as with no modules. All of the framework's server code is written with Effect. The few files that stay plain TypeScript (the Spool itself, the start-up code, the pure SQL compiler) are listed in.oxlintrc.json. Registries Three registries keep features open for extension. Each is typed so the compiler tells you what's missing. A module is the fourth way in: it brings entries for the others' and more. Registry File Adds Field types crm/field-types.ts (schema, column, validation) and crm/ui/fields.tsx (display, input) A new type for fields View types crm/config-schema.ts ( viewSchema) and crm/ui/views.tsx A new way to render a list Run targets runTargets in your src/app/extensions.ts A new \":\" for actions and automations Modules modules in your src/spool.server.ts, their browser halves in src/spool.ui.ts ( crm/modules.ts, crm/compose.ts, crm/ui/slots.tsx) A feature set: objects, hooks, handlers, private tables, settings, panels and pages The rest of what your code adds goes through src/app/extensions.ts (hooks, handlers, integration providers, marketing networks, the email transport, role and scope sources) and through adapters, one for each port. See Extending for worked examples. Routes The CRM is served from the site root. Your src/routes/_crm/route.tsx is a pathless layout: it checks the session, loads the config and renders the shell, and its children map to / (home), /tasks, /notes, /files, /reports, /workflows, /integrations, /marketing, /team, /assistant, / and //, and to the pages your modules bring. Because an object's key is the first path segment, keys that would shadow a built-in route ( tasks, api, unsubscribe and so on) are rejected by the config schema, and an unknown first segment is a 404. /sign-in and /unsubscribe sit outside the layout and need no session. /crm/..., where the CRM used to live, redirects to the same page at the root. Moving between pages A click should not wait for anything the browser already has: The layout's session check runs before every navigation and every link the pointer rests on, so the browser keeps the session it was given (who is signed in, the config, the team, favourites, the task count) and reuses it, checking again in the background once a minute. The same memory holds what relation pickers were given for a search, for a minute, so opening one twice asks once. It lives in crm/memory.ts and is wired up in crm/ui/session.ts. It is a convenience, not access control: every server function still checks the session itself, and nothing is remembered on the server. A page's data is reused for 15 seconds, so going back and forth costs nothing. After that the page is still shown at once, as it was, and refreshed behind ( defaultStaleTime in crm/ui/router.tsx). Data fetched when a link is hovered is used by the click that follows. Anything that changes data calls router.invalidate(), which reloads what is on screen and forgets the remembered session and titles. A change made by a teammate shows up the next time the page is fetched, or within a few seconds when live is in the config: list, board and record pages then ask whether what they show has changed ( crm/ui/live.ts), and reload only when it has. A list brings back a related record's id and title only, and a board only the fields its cards show ( relations and fields in listRecords). Titles for many records are fetched together ( recordTitlesOf). Guides cost no request to offer: what each person has seen of them comes with the session. See Guides. Search matches records in the browser. After the first page has loaded, the browser fetches every record's title and unencrypted searchable fields once and keeps them in memory ( searchIndex in crm/ui/session.ts), so a key press in Cmd+K costs no request. After a change it asks only for what changed since. Notes, emails, calls and tasks are searched on the server once typing pauses. See Search and filters. A page never carries the records a relation could point at. The picker ( crm/ui/relation-picker.tsx) asks for one page of 50 titles when it is opened and searches the server as you type ( searchTitles), so an object with thousands of records costs the same as one with ten, and any of them can be chosen. A list sends the titles of the records its filters name, and nothing else. Request flow: a new record Someone creates a contact in the CRM (or the assistant does, through the tool API). The entry point checks who is asking, then calls service.createRecord. service.createRecord runs beforeCreate hooks (each module's, then yours), validates the record against its fields and rules and inserts it, writes a timeline entry, runs afterCreate hooks, then fires contacts.created automations. The data layer refuses a person whose roles deny contacts, or only read them: nothing is written, and no after hook or automation runs. The swirls:new_contact automation starts a Swirls workflow with { objectKey, record, actor, trigger }. The workflow qualifies the contact with AI, emails your team, and writes its summary back through POST /api/swirls/tools/add_note, which saves a note on the record. Data model Every object in the config becomes a table with real, typed columns, plus id, created_at, updated_at, created_by, and three dates kept from the record's activities and tasks so that lists can filter and sort by them: last_activity_at, last_contacted_at and next_task_due ( refreshStats in server/records.ts). A relations field has a links table of its own ( contacts_tags), with one row per pair of records. With record scopes, a scoped object's records say their scope in a field of their own, the rows that hang off a record carry a copy of it in scope, and a link belongs to the scope of each scoped record it joins. These system tables are always present ( server/store/tables.ts), and an adapter may add its own: Table Holds activities The timeline for any record. Full-text indexed ( activities_search) for search tasks To-dos with a due date and assignee, optionally linked to a record notes Titled notes, optionally linked to a record. Full-text indexed ( notes_search) for search saved_views Views created in the app, and in-app changes to config views favorites Each user's starred records email_suppressions Addresses that bounced, complained or unsubscribed mailbox_sync How far the mail and calendar sync has read each of a teammate's mailboxes. No credentials record_folders Which folder in the file store is a record's own. The folders and files themselves are in the store file_uploads A file on its way into the store, until the store confirms it integrations Accounts connected on the Integrations page, a teammate's own or shared, their OAuth tokens sealed by the vault first sequence_runs Each record's place in an email sequence: which email is next and when it is due guide_progress Which guides each person has finished or dismissed, so each is offered once team_roles The roles the Team page gives each person, by email marketing_sites What the last check of the business's website found, and what the assistant learned from it. See Marketing marketing_posts Social posts: drafts, the ones waiting for their time, and what went out marketing_ads Each ad campaign's results as last read from its network idempotent_requests Writes sent with an Idempotency-Key: who claimed each, and the answer to give again. See Extending change_signals A \"last changed\" mark for each object and record, which live pages ask about. See Database A module may keep tables of its own, named after it ( approvals_decisions). Like an adapter's, they are not CRM objects. Of the adapters that ship, storeRateLimits() counts in rate_limit_slots ( Adapters). Each unique rule of an object is a unique index on its table ( Database). All tables have row-level security enabled with no policies. The app connects as a privileged role, which bypasses RLS. Supabase's Data API roles get nothing." + "text": "Architecture A Spool is three things put together in src/spool.server.ts: a config that describes your business, your own code, and the services it runs on. The framework is a package, @swirls/spools. Your repository holds what is yours and a thin layer of files that mount the framework's pages and endpoints, so a new version is a new version number. Yours and the framework's Yours: edit freely What it is crm.config.json Your CRM: objects, fields, views, actions, automations, sequences, record rules, roles, and your own guides src/spool.server.ts, src/spool.ui.ts Your Spool: which adapters it runs on and which modules it uses, and their browser halves src/app/extensions.ts Handlers, hooks, run-target kinds, email transport, integration providers src/routes/** One small file per page and endpoint. Delete one to drop a page, replace one to write your own, add as many as you like src/styles.css Brand colours and theme overrides swirls/** Your Swirls workflows and assistant scripts/seed.ts Demo data Generated: never edit Source prisma/schema.prisma, prisma/schema.json, prisma/schema.d.ts, crm.config.schema.json bun run crm:gen src/routeTree.gen.ts bun run dev or bun run build migrations/** bun run db:plan The framework: packages/spools ( @swirls/spools) What it is src/crm/** The config contract, field and view registries, the generator, the interface src/server/** Records, the service layer, the tool API, sequences, the ports and the Effect runtime ( src/server/runtime/), the store ( src/server/store/) src/adapters/** The adapters that ship with it, by port src/pages/**, src/views/** Each page's route options, and what it renders (loaded when it is opened) src/api/** The handlers behind /api/* src/cli/** The spools command Feature sets that plug in from outside the app are modules: modules in defineSpool lists them, and src/spool.ui.ts their browser halves. Each brings config, code, private tables, settings, panels and pages, and is put together with the app's when the Spool is defined ( src/crm/compose.ts): in order, refusing anything two of them define. If you need something the extension points don't cover, open an issue: the aim is that nobody has to patch the framework. Layers Paths on this page are inside packages/spools/src unless they start with the name of one of your own files. Operations are what the CRM does for whoever asks, each defined once ( server/operations): its name, what it takes, who may ask, and the program that answers. The interface's server functions only bind them to TanStack Start, and the HTTP API answers the same ones for a front end of your own. Nothing on the server's side imports a web framework but those bindings and src/start.ts. The boundary is where a request becomes an Effect program. A server function's handler is crmHandler(...) and a route uses an adapter ( apiRoute, cronRoute, publicRoute, toolRoute). It asks the auth adapter for the session and reads the request before the program starts, checks the access list, runs the program on the process's one runtime, interrupts it if the browser goes away, and turns a typed error into the message the page shows. See Writing server code. Ports are the only way to the outside. The framework asks for a port ( yield* Store) and never imports an adapter, a vendor's SDK or your app; lint refuses it. Each has a stand-in for tests, and its time limit and retries come from one table ( policies.ts). See Adapters. records.ts is the data layer: config-driven CRUD, search and filters. It validates every write against the field definitions and the object's record rules ( record-rules.ts), and checks role access on every read and write ( object-access.ts), so both hold whoever calls it. After a change is kept it marks what changed ( signals.ts), which is what live pages ask about. service.ts is what callers use to change records. It wraps the data layer with extension hooks, timeline entries and automations, so a change behaves the same whether it comes from the UI or the assistant. views.ts merges the views in the config with what users saved in the app, and workspace.ts holds tasks, notes, favourites, reports and CSV export. Neither goes through service.ts: they aren't config objects, so hooks and automations don't apply to them. actions.ts resolves \"run\": \":\" targets through a registry: swirls, campaign and local are built in, and extensions can add kinds. Entry points authenticate, then call the service: server functions check the session and the allowlist, and the tool API and the cron routes each check a bearer token. An endpoint behind publicRoute is the one entry the framework checks nothing for: a webhook checks its signature, and a door of your own for people who are not teammates checks its callers with the helpers in @swirls/spools/extensions. Your code stays plain TypeScript. Hooks and handlers in src/app/extensions.ts return promises, and the browser never loads Effect. Modules are put together before anything runs. defineSpool merges each module's part of the config into the app's and checks the whole against the contract, composes their hooks (modules in order, then the app) and refuses clashes. Everything after ( service.ts, the registries, the store, spools gen) sees one config and one set of extensions, as with no modules. All of the framework's server code is written with Effect. The few files that stay plain TypeScript (the Spool itself, the start-up code, the pure SQL compiler) are listed in.oxlintrc.json. Registries Three registries keep features open for extension. Each is typed so the compiler tells you what's missing. A module is the fourth way in: it brings entries for the others' and more. Registry File Adds Field types crm/field-types.ts (schema, column, validation) and crm/ui/fields.tsx (display, input) A new type for fields View types crm/config-schema.ts ( viewSchema) and crm/ui/views.tsx A new way to render a list Run targets runTargets in your src/app/extensions.ts A new \":\" for actions and automations Modules modules in your src/spool.server.ts, their browser halves in src/spool.ui.ts ( crm/modules.ts, crm/compose.ts, crm/ui/slots.tsx) A feature set: objects, hooks, handlers, private tables, settings, panels and pages The rest of what your code adds goes through src/app/extensions.ts (hooks, handlers, integration providers, marketing networks, the email transport, role and scope sources) and through adapters, one for each port. See Extending for worked examples. Routes The CRM is served from the site root. Your src/routes/_crm/route.tsx is a pathless layout: it checks the session, loads the config and renders the shell, and its children map to / (home), /tasks, /notes, /files, /reports, /workflows, /integrations, /marketing, /team, /assistant, / and //, and to the pages your modules bring. Because an object's key is the first path segment, keys that would shadow a built-in route ( tasks, api, unsubscribe and so on) are rejected by the config schema, and an unknown first segment is a 404. /sign-in and /unsubscribe sit outside the layout and need no session. /crm/..., where the CRM used to live, redirects to the same page at the root. Moving between pages A click should not wait for anything the browser already has: The layout's session check runs before every navigation and every link the pointer rests on, so the browser keeps the session it was given (who is signed in, the config, the team, favourites, the task count) and reuses it, checking again in the background once a minute. The same memory holds what relation pickers were given for a search, for a minute, so opening one twice asks once. It lives in crm/memory.ts and is wired up in crm/ui/session.ts. It is a convenience, not access control: every server function still checks the session itself, and nothing is remembered on the server. A page's data is reused for 15 seconds, so going back and forth costs nothing. After that the page is still shown at once, as it was, and refreshed behind ( defaultStaleTime in crm/ui/router.tsx). Data fetched when a link is hovered is used by the click that follows. Anything that changes data calls router.invalidate(), which reloads what is on screen and forgets the remembered session and titles. A change made by a teammate shows up the next time the page is fetched, or within a few seconds when live is in the config: list, board and record pages then ask whether what they show has changed ( crm/ui/live.ts), and reload only when it has. A list brings back a related record's id and title only, and a board only the fields its cards show ( relations and fields in listRecords). Titles for many records are fetched together ( recordTitlesOf). Guides cost no request to offer: what each person has seen of them comes with the session. See Guides. Search matches records in the browser. After the first page has loaded, the browser fetches every record's title and unencrypted searchable fields once and keeps them in memory ( searchIndex in crm/ui/session.ts), so a key press in Cmd+K costs no request. After a change it asks only for what changed since. Notes, emails, calls and tasks are searched on the server once typing pauses. See Search and filters. A page never carries the records a relation could point at. The picker ( crm/ui/relation-picker.tsx) asks for one page of 50 titles when it is opened and searches the server as you type ( searchTitles), so an object with thousands of records costs the same as one with ten, and any of them can be chosen. A list sends the titles of the records its filters name, and nothing else. Request flow: a new record Someone creates a contact in the CRM (or the assistant does, through the tool API). The entry point checks who is asking, then calls service.createRecord. service.createRecord runs beforeCreate hooks (each module's, then yours), validates the record against its fields and rules and inserts it, writes a timeline entry, runs afterCreate hooks, then fires contacts.created automations. The data layer refuses a person whose roles deny contacts, or only read them: nothing is written, and no after hook or automation runs. The swirls:new_contact automation starts a Swirls workflow with { objectKey, record, actor, trigger }. The workflow qualifies the contact with AI, emails your team, and writes its summary back through POST /api/swirls/tools/add_note, which saves a note on the record. Data model Every object in the config becomes a table with real, typed columns, plus id, created_at, updated_at, created_by, and three dates kept from the record's activities and tasks so that lists can filter and sort by them: last_activity_at, last_contacted_at and next_task_due ( refreshStats in server/records.ts). A relations field has a links table of its own ( contacts_tags), with one row per pair of records. With record scopes, a scoped object's records say their scope in a field of their own, the rows that hang off a record carry a copy of it in scope, and a link belongs to the scope of each scoped record it joins. These system tables are always present ( server/store/tables.ts), and an adapter may add its own: Table Holds activities The timeline for any record. Full-text indexed ( activities_search) for search tasks To-dos with a due date and assignee, optionally linked to a record notes Titled notes, optionally linked to a record. Full-text indexed ( notes_search) for search saved_views Views created in the app, and in-app changes to config views favorites Each user's starred records email_suppressions Addresses that bounced, complained or unsubscribed mailbox_sync How far the mail and calendar sync has read each of a teammate's mailboxes. No credentials record_folders Which folder in the file store is a record's own. The folders and files themselves are in the store file_uploads A file on its way into the store, until the store confirms it integrations Accounts connected on the Integrations page, a teammate's own or shared, their OAuth tokens sealed by the vault first sequence_runs Each record's place in an email sequence: which email is next and when it is due guide_progress Which guides each person has finished or dismissed, so each is offered once team_roles The roles the Team page gives each person, by email marketing_sites What the last check of the business's website found, and what the assistant learned from it. See Marketing marketing_posts Social posts: drafts, the ones waiting for their time, and what went out marketing_ads Each ad campaign's results as last read from its network idempotent_requests Writes sent with an Idempotency-Key: who claimed each, and the answer to give again. See Extending change_signals A \"last changed\" mark for each object and record, which live pages ask about. See Database A module may keep tables of its own, named after it ( approvals_decisions). Like an adapter's, they are not CRM objects. Of the adapters that ship, storeRateLimits() counts in rate_limit_slots ( Adapters). Each unique rule of an object is a unique index on its table ( Database). All tables have row-level security enabled with no policies. The app connects as a privileged role, which bypasses RLS. Supabase's Data API roles get nothing." }, { "path": "/docs/server-code", @@ -1505,7 +1593,7 @@ "level": 2 } ], - "text": "Writing server code The framework's server side ( packages/spools/src/server, src/api and src/adapters beside it) is written with Effect 4. This page is for changing it; a Spool's own code in src/app/extensions.ts is plain TypeScript, and its hooks and handlers return promises. Effect never reaches the browser. Every server module, server function and API handler is written this way..oxlintrc.json lists the few files the rules leave out, each for a reason: the runtime folder (it is where the request and the environment are touched), env.ts, spool.ts and entry.ts (which run before there is a runtime), and store/sql.ts (pure, with no database of its own). Why Failures are in the type. A function's type says what it can fail with, and the compiler won't let a server function fail with something staff can't read. Outside services have limits. Every call to the auth provider, the database, the file store, Gmail, Graph, the email provider, the agent engine and the vault has a time limit and, where repeating it is safe, retries. They are in one table: packages/spools/src/server/runtime/policies.ts. Tests swap services, not globals. A test provides a fake layer for a service; nothing is patched on a module and left behind for the next test. When the browser goes away, the work stops. The program is interrupted and its cleanup runs. The pieces File What it is packages/spools/src/server/runtime/errors.ts The errors staff can see ( Unauthorized, NotFound, Invalid, NotConfigured, DatabaseError, ScopeRefused, AuthError, Timeout) and the StaffError union packages/spools/src/server/runtime/config.ts Every environment variable, as an Effect Config, and the feature list behind the boot report packages/spools/src/server/runtime/policies.ts Time limits and retries for each outside service, and withPolicy packages/spools/src/server/runtime/adapter.ts What an adapter is: its layer, what it requires of the environment, the tables it keeps packages/spools/src/server/spool.ts defineSpool, and this process's Spool: spool(), crmConfig(), objectTable(key) packages/spools/src/server/store/store.ts Store: the database, as find, count, insert, update and remove over tables ( Database) packages/spools/src/server/store/query.ts, tables.ts, objects.ts Conditions and order as data; the system tables; an object's table, from the config packages/spools/src/server/runtime/auth.ts Auth: the auth provider's directory, with a fake ( Auth.layerTest) packages/spools/src/server/runtime/files.ts FileStore: folders, files and uploads packages/spools/src/server/runtime/agents.ts Agents: starting workflows and the assistant's chat packages/spools/src/server/runtime/http.ts The HTTP client (Effect's HttpClient over fetch) every outside service uses, and appLayer({ fetch }) for a stand-in. A request is aborted when its program is interrupted or times out packages/spools/src/server/runtime/vault.ts Vault: sealing and opening secrets, with Vault.layerTest(cipher) for tests packages/spools/src/server/sign-ins.ts SignIns: the Google and Microsoft accounts teammates sign in with, and the auth provider's tokens for them, with SignIns.layerTest packages/spools/src/server/users.ts Users: who may use the CRM, the team, sign-in accounts packages/spools/src/server/runtime/app.ts appLayer() (every service, from the Spool's adapters or a test's stand-ins), the one runtime per process, runServer for code on promises packages/spools/src/server/runtime/boundary.ts crmHandler, publicHandler, apiRoute, cronRoute, publicRoute, toolRoute: where TanStack Start hands a request to a program packages/spools/src/server/runtime/request.ts CurrentRequest: the request's headers, abort signal and session, set by the boundary packages/spools/src/server/runtime/email.ts Email: sending, and reading delivery webhooks, with Email.layerTest(sender) packages/spools/src/server/sequences.ts Sequences: the campaigns the CRM runs, from the config, with Sequences.layerTest packages/spools/src/server/extension-api.ts The framework as promises, for src/app/extensions.ts and scripts A module Export Effect.fn(\"module.name\")(function* () {... }). The name becomes a span, so a slow request shows which call was slow. Fail with return yield* new SomeError(...), never throw. The return tells TypeScript the function stops there. Ask for a service with yield* Store. Don't import an adapter, the app, fetch, a vendor SDK or process.env: lint refuses them outside packages/spools/src/server/runtime/. Reads have a time limit and writes have none, because giving up on a write leaves its outcome unknown. To expect a particular failure, such as a unique index keeping one row, catch DatabaseError and check: In a Spool with record scopes a store call can also fail with ScopeRefused: the guard refusing it. It is not a DatabaseError, so the catch above never takes a refusal for the failure it expects; let it go on to the boundary, which shows staff its words. The app's config and extensions come from the Spool ( spool() in spool.ts), read when they are used. Read a variable with yield* config.read(config.guidesOffered), declared in runtime/config.ts. Use Config.Redacted for secrets and Config.option for optional ones. Values are read from the environment each time, as process.env was before, so a variable set while the process runs takes effect at once. A server function crmHandler checks the session and the access list, then runs the program with the validated data and the signed-in user. There is no other way for a program to learn who is asking, and nothing inside an Effect asks the auth adapter for the session or calls getRequest(): they belong to the request, and the boundary reads them before the program starts. publicHandler is for the few functions signed-out pages call; nothing staff-only belongs there. Validators stay Zod (.validator(z.object(...))). The rule is: Zod for what comes in, Schema for what comes back. Zod checks what the browser sends and the config; Effect Schema defines errors and, as services are converted, checks what outside services answer. An API route The handlers are exported from src/api, and a Spool mounts them with a file of three lines: cronRoute refuses a request without Authorization: Bearer $CRON_SECRET (401), answers a typed failure as JSON, and stops the run at its limit (50 s by default) with a 504. apiRoute is for routes staff call while signed in ( /api/files/*): the program gets { request, params, user } and answers with a Response. Pass signedOut to answer a signed-out visitor your own way (a redirect to /sign-in, say); by default it is 401 JSON. A typed failure the program doesn't answer itself becomes 500 JSON with its message. Type the program's input as RouteInput<{ id: string }> so params has the route's shape. publicRoute is for routes that prove who is calling some other way: a signed webhook ( /api/webhooks/email) or a token in a link (one-click unsubscribe). The program checks the signature or token first. toolRoute is for the tool API Swirls calls back into ( /api/swirls/tools/*): it refuses a request without Authorization: Bearer $SWIRLS_APP_TOKEN (401). Nobody is signed in; a tool acts as the assistant. What staff see when something fails The program fails with The page shows The server logs A StaffError Its message, exactly (see errors.ts) [server] failed after ms: : (not for Unauthorized) Anything else (a bug) What it threw, as before The whole cause, once, with a reference Interrupted (the browser went away) Nothing: the request is answered 499 Nothing The wording of every message staff can see is in the error's class, so a change of wording is one line in one file. A successful call slower than a second is logged as [server] took ms. A new outside service A port in packages/spools/src/server/runtime/ ( Context.Service), in terms of what the CRM needs and nothing of one vendor's, with a stand-in for tests and, if a Spool can do without it, a layer that says it isn't set up. An adapter in src/adapters///server.ts. Only it imports the vendor's SDK. HTTP goes through HttpClient ( yield* HttpClient.HttpClient from effect/http), never fetch. It names what it requires and the features it switches on. A row in policies.ts: the time limit and how many retries. Retry only what is safe to repeat (reads, writes with an idempotency key), and pass withPolicy a predicate that refuses retries for answers that won't change (a 4xx other than 429). The adapter puts its provider's name to it. Its errors in errors.ts, each with a message staff can read, added to StaffError. Its option in defineSpool ( spool.ts) and its layer in appLayer ( runtime/app.ts). Promises on either side Effect code calling the app's own code. Hooks, handlers and settings in src/app/extensions.ts return promises. They are called through fromHook(\"files.location\", () =>...) ( runtime/errors.ts), which makes a failure an ExtensionError; staff see what was thrown, as before. Promise code calling Effect code. src/app/extensions.ts and scripts import from @swirls/spools/extensions ( recordFolder, shareRecordFolder, filesConfigured, listCrmUsers, getAccessToken, findConnections,...): each runs the Effect version on the process's runtime ( runServer(program) from runtime/app.ts underneath). A typed failure rejects with the error itself, so its message still reaches the page. Don't import the framework modules from promise code: they export Effects, and await ing one does nothing. Tests The helpers below come from @swirls/spools/testing, in this repository's tests and in your app's: run, failure, db, testRuntime, withEnv, runWithEnv, installStandIns, installLiveServices, bodyText, and createFakeStore (a file store held in memory). Unit tests build a runtime from the app layer with stand-ins ( testRuntime(appLayer({ fetch: fake, auth: Auth.layerTest(users) })), where fake answers every outside HTTP call) or read configuration from an object ( runWithEnv({ CRON_SECRET: \"...\" }, program)). packages/spools/tests/unit/flashdrive.test.ts shows the file store's retries, refusals and answer checking tested that way. packages/spools/tests/unit/boundary.test.ts shows the boundary, the access list, the cron secret and the policies tested that way. Integration tests run on the app's own runtime, on the store TEST_STORE names (PGlite in the test process unless you say otherwise; Database): await run(guides.seenGuides(id)), and await failure(program) for the typed error a program fails with. To replace an outside service for the whole app (the boundary and extension-api.ts included), call await installStandIns({ fetch: fake.handle }) (and vault, signIns, auth, tokens, rateLimits for those services; Tokens.layerTest and RateLimiter.layerTest come from @swirls/spools/testing) and await installLiveServices() afterwards. One fetch answers every outside call, so route by URL when a test plays more than one provider, and read bodies with bodyText(init): Effect's client sends them as bytes; packages/spools/tests/integration/files.test.ts does this with createFakeStore(). Each call starts from fresh services, so nothing cached leaks into the next test. packages/spools/tests/unit/guardrails.test.ts lints code written the old way with this repository's lint rules and checks that each one fires. The guardrails bun run lint (part of bun run verify) refuses, outside the files.oxlintrc.json leaves out. The rules are in packages/spools/src/oxlint: a server function handler that isn't crmHandler(...) or publicHandler(...) ( spools/server-function-handlers); anything but server functions exported from a *.functions.ts file, which browser code imports ( spools/server-function-files); an API handler that isn't a route adapter, in a route or exported from src/api ( spools/route-adapters); throw or an exported async function in packages/spools/src/server/** ( spools/effect-modules); fetch, process, @tanstack/react-start/server, a vendor's SDK, a database client, an adapter or the app in packages/spools/src/server/** outside packages/spools/src/server/runtime/ (and the last two even there); an adapter or an auth vendor's SDK in pages, which use useAuth(); effect in browser code ( packages/spools/src/crm/**, src/pages/**, src/views/**, and a Spool's routes and src/app/**). bun run build then fails if Effect reached the browser bundle anyway ( spools check-client, which looks for Effect's internal ids in dist/client, and in.vercel/output/static for a Vercel build. Name a folder to check that one instead: spools check-client build/public)." + "text": "Writing server code The framework's server side ( packages/spools/src/server, src/api and src/adapters beside it) is written with Effect 4. This page is for changing it; a Spool's own code in src/app/extensions.ts is plain TypeScript, and its hooks and handlers return promises. Effect never reaches the browser. Every server module, server function and API handler is written this way..oxlintrc.json lists the few files the rules leave out, each for a reason: the runtime folder (it is where the request and the environment are touched), env.ts, spool.ts and entry.ts (which run before there is a runtime), and store/sql.ts (pure, with no database of its own). Why Failures are in the type. A function's type says what it can fail with, and the compiler won't let a server function fail with something staff can't read. Outside services have limits. Every call to the auth provider, the database, the file store, Gmail, Graph, the email provider, the agent engine and the vault has a time limit and, where repeating it is safe, retries. They are in one table: packages/spools/src/server/runtime/policies.ts. Tests swap services, not globals. A test provides a fake layer for a service; nothing is patched on a module and left behind for the next test. When the browser goes away, the work stops. The program is interrupted and its cleanup runs. The pieces File What it is packages/spools/src/server/runtime/errors.ts The errors staff can see ( Unauthorized, NotFound, Invalid, NotConfigured, DatabaseError, ScopeRefused, AuthError, Timeout) and the StaffError union packages/spools/src/server/runtime/config.ts Every environment variable, as an Effect Config, and the feature list behind the boot report packages/spools/src/server/runtime/policies.ts Time limits and retries for each outside service, and withPolicy packages/spools/src/server/runtime/adapter.ts What an adapter is: its layer, what it requires of the environment, the tables it keeps packages/spools/src/server/spool.ts defineSpool, and this process's Spool: spool(), crmConfig(), objectTable(key) packages/spools/src/server/store/store.ts Store: the database, as find, count, insert, update and remove over tables ( Database) packages/spools/src/server/store/query.ts, tables.ts, objects.ts Conditions and order as data; the system tables; an object's table, from the config packages/spools/src/server/runtime/auth.ts Auth: the auth provider's directory, with a fake ( Auth.layerTest) packages/spools/src/server/runtime/files.ts FileStore: folders, files and uploads packages/spools/src/server/runtime/agents.ts Agents: starting workflows and the assistant's chat packages/spools/src/server/runtime/http.ts The HTTP client (Effect's HttpClient over fetch) every outside service uses, and appLayer({ fetch }) for a stand-in. A request is aborted when its program is interrupted or times out packages/spools/src/server/runtime/vault.ts Vault: sealing and opening secrets, with Vault.layerTest(cipher) for tests packages/spools/src/server/sign-ins.ts SignIns: the Google and Microsoft accounts teammates sign in with, and the auth provider's tokens for them, with SignIns.layerTest packages/spools/src/server/users.ts Users: who may use the CRM, the team, sign-in accounts packages/spools/src/server/runtime/app.ts appLayer() (every service, from the Spool's adapters or a test's stand-ins), the one runtime per process, runServer for code on promises packages/spools/src/server/runtime/boundary.ts crmHandler, publicHandler, apiRoute, cronRoute, publicRoute, toolRoute: where TanStack Start hands a request to a program packages/spools/src/server/operations/*.ts, http.ts, headless.ts Every operation, defined once; the HTTP API that answers them; a whole Spool with no web framework ( Headless) packages/spools/src/server/runtime/request.ts CurrentRequest: the request's headers, abort signal and session, set by the boundary packages/spools/src/server/runtime/email.ts Email: sending, and reading delivery webhooks, with Email.layerTest(sender) packages/spools/src/server/sequences.ts Sequences: the campaigns the CRM runs, from the config, with Sequences.layerTest packages/spools/src/server/extension-api.ts The framework as promises, for src/app/extensions.ts and scripts A module Export Effect.fn(\"module.name\")(function* () {... }). The name becomes a span, so a slow request shows which call was slow. Fail with return yield* new SomeError(...), never throw. The return tells TypeScript the function stops there. Ask for a service with yield* Store. Don't import an adapter, the app, fetch, a vendor SDK or process.env: lint refuses them outside packages/spools/src/server/runtime/. Reads have a time limit and writes have none, because giving up on a write leaves its outcome unknown. To expect a particular failure, such as a unique index keeping one row, catch DatabaseError and check: In a Spool with record scopes a store call can also fail with ScopeRefused: the guard refusing it. It is not a DatabaseError, so the catch above never takes a refusal for the failure it expects; let it go on to the boundary, which shows staff its words. The app's config and extensions come from the Spool ( spool() in spool.ts), read when they are used. Read a variable with yield* config.read(config.guidesOffered), declared in runtime/config.ts. Use Config.Redacted for secrets and Config.option for optional ones. Values are read from the environment each time, as process.env was before, so a variable set while the process runs takes effect at once. A server function What the CRM does for whoever asks is an operation, defined once in packages/spools/src/server/operations/.ts: A server function only binds one to TanStack Start, and holds no program of its own: Listed in operations/index.ts, the operation is also answered by the HTTP API at POST /api/v1/guides.mark and known to the typed client by that name. So its name and the shape of its input and answer are a public contract: changing one is a breaking change. staff operations are for signed-in teammates and open ones answer anyone. An operation a front end is built on says what it answers ( answer, schemas in operations/answers.ts), which the OpenAPI document carries. crmHandler checks the session and the access list, then runs the program with the validated data and the signed-in user. There is no other way for a program to learn who is asking, and nothing inside an Effect asks the auth adapter for the session or calls getRequest(): they belong to the request, and the boundary reads them before the program starts. publicHandler is for the few functions signed-out pages call; nothing staff-only belongs there. Validators stay Zod (.validator(z.object(...))). The rule is: Zod for what comes in, Schema for what comes back. Zod checks what the browser sends and the config; Effect Schema defines errors and, as services are converted, checks what outside services answer. An API route The handlers are exported from src/api, and a Spool mounts them with a file of three lines: cronRoute refuses a request without Authorization: Bearer $CRON_SECRET (401), answers a typed failure as JSON, and stops the run at its limit (50 s by default) with a 504. apiRoute is for routes staff call while signed in ( /api/files/*): the program gets { request, params, user } and answers with a Response. Pass signedOut to answer a signed-out visitor your own way (a redirect to /sign-in, say); by default it is 401 JSON. A typed failure the program doesn't answer itself becomes 500 JSON with its message. Type the program's input as RouteInput<{ id: string }> so params has the route's shape. publicRoute is for routes that prove who is calling some other way: a signed webhook ( /api/webhooks/email) or a token in a link (one-click unsubscribe). The program checks the signature or token first. toolRoute is for the tool API Swirls calls back into ( /api/swirls/tools/*): it refuses a request without Authorization: Bearer $SWIRLS_APP_TOKEN (401). Nobody is signed in; a tool acts as the assistant. What staff see when something fails The program fails with The page shows The server logs A StaffError Its message, exactly (see errors.ts) [server] failed after ms: : (not for Unauthorized) Anything else (a bug) What it threw, as before The whole cause, once, with a reference Interrupted (the browser went away) Nothing: the request is answered 499 Nothing The wording of every message staff can see is in the error's class, so a change of wording is one line in one file. A successful call slower than a second is logged as [server] took ms. A new outside service A port in packages/spools/src/server/runtime/ ( Context.Service), in terms of what the CRM needs and nothing of one vendor's, with a stand-in for tests and, if a Spool can do without it, a layer that says it isn't set up. An adapter in src/adapters///server.ts. Only it imports the vendor's SDK. HTTP goes through HttpClient ( yield* HttpClient.HttpClient from effect/http), never fetch. It names what it requires and the features it switches on. A row in policies.ts: the time limit and how many retries. Retry only what is safe to repeat (reads, writes with an idempotency key), and pass withPolicy a predicate that refuses retries for answers that won't change (a 4xx other than 429). The adapter puts its provider's name to it. Its errors in errors.ts, each with a message staff can read, added to StaffError. Its option in defineSpool ( spool.ts) and its layer in appLayer ( runtime/app.ts). Promises on either side Effect code calling the app's own code. Hooks, handlers and settings in src/app/extensions.ts return promises. They are called through fromHook(\"files.location\", () =>...) ( runtime/errors.ts), which makes a failure an ExtensionError; staff see what was thrown, as before. Promise code calling Effect code. src/app/extensions.ts and scripts import from @swirls/spools/extensions ( recordFolder, shareRecordFolder, filesConfigured, listCrmUsers, getAccessToken, findConnections,...): each runs the Effect version on the process's runtime ( runServer(program) from runtime/app.ts underneath). A typed failure rejects with the error itself, so its message still reaches the page. Don't import the framework modules from promise code: they export Effects, and await ing one does nothing. Tests The helpers below come from @swirls/spools/testing, in this repository's tests and in your app's: run, failure, db, testRuntime, withEnv, runWithEnv, installStandIns, installLiveServices, bodyText, and createFakeStore (a file store held in memory). Unit tests build a runtime from the app layer with stand-ins ( testRuntime(appLayer({ fetch: fake, auth: Auth.layerTest(users) })), where fake answers every outside HTTP call) or read configuration from an object ( runWithEnv({ CRON_SECRET: \"...\" }, program)). packages/spools/tests/unit/flashdrive.test.ts shows the file store's retries, refusals and answer checking tested that way. packages/spools/tests/unit/boundary.test.ts shows the boundary, the access list, the cron secret and the policies tested that way. Integration tests run on the app's own runtime, on the store TEST_STORE names (PGlite in the test process unless you say otherwise; Database): await run(guides.seenGuides(id)), and await failure(program) for the typed error a program fails with. To replace an outside service for the whole app (the boundary and extension-api.ts included), call await installStandIns({ fetch: fake.handle }) (and vault, signIns, auth, tokens, rateLimits for those services; Tokens.layerTest and RateLimiter.layerTest come from @swirls/spools/testing) and await installLiveServices() afterwards. One fetch answers every outside call, so route by URL when a test plays more than one provider, and read bodies with bodyText(init): Effect's client sends them as bytes; packages/spools/tests/integration/files.test.ts does this with createFakeStore(). Each call starts from fresh services, so nothing cached leaks into the next test. packages/spools/tests/unit/guardrails.test.ts lints code written the old way with this repository's lint rules and checks that each one fires. The guardrails bun run lint (part of bun run verify) refuses, outside the files.oxlintrc.json leaves out. The rules are in packages/spools/src/oxlint: a server function handler that isn't crmHandler(...) or publicHandler(...) ( spools/server-function-handlers); anything but server functions exported from a *.functions.ts file, which browser code imports ( spools/server-function-files); an API handler that isn't a route adapter, in a route or exported from src/api ( spools/route-adapters); throw or an exported async function in packages/spools/src/server/** ( spools/effect-modules); fetch, process, @tanstack/react-start/server, a vendor's SDK, a database client, an adapter or the app in packages/spools/src/server/** outside packages/spools/src/server/runtime/ (and the last two even there); an adapter or an auth vendor's SDK in pages, which use useAuth(); effect in browser code ( packages/spools/src/crm/**, src/pages/**, src/views/**, and a Spool's routes and src/app/**). bun run build then fails if Effect reached the browser bundle anyway ( spools check-client, which looks for Effect's internal ids in dist/client, and in.vercel/output/static for a Vercel build. Name a folder to check that one instead: spools check-client build/public)." }, { "path": "/docs/api", @@ -1548,6 +1636,6 @@ "level": 2 } ], - "text": "API reference The package's entry points. Anything that isn't listed here is internal and may change in a patch release. The types are the reference for each function: your editor shows them, and the links lead to the source. Your Spool Import Exports @swirls/spools defineSpool, and the types Spool and SpoolOptions @swirls/spools/extensions defineExtensions, and the framework's functions as promises, for hooks, handlers and your own endpoints. See below @swirls/spools/handlers Handlers for your own server functions and endpoints. See below @swirls/spools/module What a module is written with: defineModule, defineModuleSettings, moduleTable, and table, the column helpers @swirls/spools/ui/slots The browser half of modules: defineSpoolUi, defineModuleUi, SpoolUiProvider, for src/spool.ui.ts and src/routes/__root.tsx @swirls/spools/oxlint Lint rules that refuse a server function or endpoint without a handler @swirls/spools/config-schema The config's schema, for checking a crm.config.json @swirls/spools/server serveSpool, for src/server.ts @swirls/spools/server/* The server's own modules, for code written with Effect. See Writing server code @swirls/spools/start The request middleware, for src/start.ts @swirls/spools/vite vercel, the Vercel build, for vite.config.ts @swirls/spools/testing What tests use: run, failure, installStandIns, createFakeStore, and the Tokens and RateLimiter stand-ins @swirls/spools/theme.css The styles, for src/styles.css defineSpool takes: Option Type crm the config Required. The contents of crm.config.json extensions Extensions Your hooks and handlers auth AuthAdapter Required. See Signing in database StoreAdapter Required. See Database files FilesAdapter Without it, the Files pages say files aren't set up email EmailAdapter Without it, emails are logged vault VaultAdapter Without it, no outside tokens are stored agents AgentsAdapter Without it, workflows are skipped and the assistant is off rateLimits RateLimitAdapter Without it, rate limits are counted in memory, per instance modules SpoolModule[] The modules it uses, in order: their hooks run in that order, then yours overrides paths What your app replaces of a module's part, by path. See Modules @swirls/spools/extensions What src/app/extensions.ts, a module's server code and your own endpoints import. Each function returns a promise and runs with the access of whoever the code runs for: record scopes and role access apply, and asSystem lifts both. The source is packages/spools/src/server/extension-api.ts. For Exports The contract defineExtensions, and the types Extensions, Hooks, Actor, RunContext, RunResult, RunTargetHandler, PostNetwork, AdNetwork Records createRecord, updateRecord, deleteRecord, getRecord, listRecords, countMatching. Writes run hooks, the timeline and automations The timeline, tasks, notes addActivity, listActivities, listTasks, createTask, updateTask, deleteTask, listNotes, createNote Server-kept fields writeKeptFields: writes readonly fields with no timeline line, hooks or automations. See Extending Whose work it is asSystem: runs your code as the server itself. runServer, for a program written with Effect People and connections listCrmUsers, findConnections, getAccessToken. See Integrations Files filesConfigured, recordFolder, shareRecordFolder. See Files Run targets runTarget A module's tables moduleTables: find, first, count, insert, update, remove. See Modules Live updates changedSince(keys, token?) for whoever the code runs for, and changedSinceAs(keys, token, mayRead) with a check of your own An outside caller bearerToken(headers), verifyToken(token, { authorizedParties }), callerAddress(headers) ( null when it can't be known), trustedHops Once-only writes idempotent(request, { caller, keepFor?, bodyLimit? }, work), verifiedCaller(namespace,...verifiedIds), isVerifiedCaller Rate limits hitLimit(bucket, key, limit), peekLimit(bucket, key, limit), consumeLimit(bucket, key, amount, limit), where limit is { max, windowMs } Your own secrets sealText(text, owner), openText(sealed, owner), vaultProblem(). See Adapters The last five rows are what an endpoint for people who are not teammates is built from. See Building your own door. Handlers @swirls/spools/handlers has one for each kind of server function and endpoint. Each checks who is asking before your code runs. Handler Who it answers crmHandler(name, answer) A server function, for signed-in teammates on the access list apiRoute(name, answer, options?) An endpoint, for the same people. With { idempotency: {} }, a write sent with an Idempotency-Key runs once cronRoute(name, answer, options?) A scheduled job's endpoint: needs CRON_SECRET, and answers 504 after limit publicHandler(name, answer) A server function that answers anyone publicRoute(name, answer) An endpoint that answers anyone: a webhook, or your own door. Your code checks who is calling See Pages and endpoints of your own. Adapters Import Exports @swirls/spools/auth/clerk clerk @swirls/spools/auth/better-auth betterAuth @swirls/spools/auth/dev devAuth @swirls/spools/auth//ui The browser half of each, for src/spool.ui.ts @swirls/spools/database/postgres postgres @swirls/spools/database/pglite pglite @swirls/spools/database/prisma prisma @swirls/spools/files/drive drive, localBlobs, s3Blobs @swirls/spools/files/flashdrive flashdrive @swirls/spools/email/resend resend @swirls/spools/vault/aes aes @swirls/spools/vault/cipherstash cipherstash @swirls/spools/agents/swirls swirls @swirls/spools/rate-limits/memory memoryRateLimits @swirls/spools/rate-limits/store storeRateLimits Adapters lists the packages and variables each needs. Writing an adapter @swirls/spools/adapter has the ports, types, and helpers an adapter is made from. Write your own has worked examples. Port Provides Adapter type Auth The people on the team and the accounts they sign in with AuthAdapter Store Reading and writing tables StoreAdapter FileStore Folders, files, uploads, and downloads FilesAdapter Email Sending, and reports of delivery EmailAdapter Vault Sealing and opening tokens VaultAdapter Agents Running workflows and the assistant AgentsAdapter RateLimiter Counting requests in a sliding window, and quotas in a fixed one ( hitLimit, peekLimit, consumeLimit) RateLimitAdapter Tokens Checking a token your front end forwards ( verifyToken) tokens on an AuthAdapter Pages and endpoints Each route file in src/routes mounts one of these: Import What it is @swirls/spools/pages/* Route options for each page: home, list, record, tasks, notes, files, reports, workflows, integrations, marketing, team, assistant, custom, sign-in, unsubscribe, and the layout around them @swirls/spools/api/* Handlers for each endpoint under /api @swirls/spools/ui/* The interface's own components, for pages you write, and ui/slots for modules, and defineLayoutComponent for layouts The spools command Run in a Spool's folder. The scripts in package.json call it for you. Command What it does spools gen Checks crm.config.json, with the modules' parts in it, and regenerates prisma/schema.prisma and crm.config.schema.json, then emits Prisma's contract ( --no-emit leaves that step out) spools init First run: names the CRM, sets who may use it, writes.env with fresh secrets spools harden Takes Supabase's Data API roles off the tables, and fails if row-level security is off anywhere spools stats Recomputes the last activity, last contact, and next task dates on every record spools scopes backfill Gives the rows that hang off records their record's scope. Run after every change to scopes.objects. See Security spools modules Lists what each module adds and the route files they expect. Exits 1 while one is missing, printing what to put in it spools rules [object] Lists the records that already break a unique rule, by id. Exits 1 while any do. Run before db:push or db:plan. See Database spools timeline redact Rewrites old timeline lines that name records of an object someone is now kept from. See Roles spools ui check Says what is wrong with each layout ( ui in the config). Exits 1 when one will not draw; --strict also refuses a component the kit hasn't. See Layouts spools ui prompt Prints what a coding agent needs to write a layout: the language, the kit, the tools, and this Spool's objects and fields spools check-client Fails if Effect, which server code runs on, reached the browser bundle A new Spool's package.json has a script for most of them: crm:gen, init, db:harden, db:stats, db:scopes, db:rules. bun run build ends with spools check-client. check-client reads dist/client, and.vercel/output/static after a Vercel build. To check another folder, name it: spools check-client build/public." + "text": "API reference The package's entry points. Anything that isn't listed here is internal and may change in a patch release. The types are the reference for each function: your editor shows them, and the links lead to the source. Your Spool Import Exports @swirls/spools defineSpool, and the types Spool and SpoolOptions @swirls/spools/extensions defineExtensions, and the framework's functions as promises, for hooks, handlers and your own endpoints. See below @swirls/spools/handlers Handlers for your own server functions and endpoints. See below @swirls/spools/module What a module is written with: defineModule, defineModuleSettings, moduleTable, and table, the column helpers @swirls/spools/ui/slots The browser half of modules: defineSpoolUi, defineModuleUi, SpoolUiProvider, for src/spool.ui.ts and src/routes/__root.tsx @swirls/spools/oxlint Lint rules that refuse a server function or endpoint without a handler @swirls/spools/config-schema The config's schema, for checking a crm.config.json @swirls/spools/server serveSpool, for src/server.ts @swirls/spools/server/* The server's own modules, for code written with Effect. See Writing server code @swirls/spools/http httpApi: the CRM over HTTP as one Request to Response handler, for a server with no interface. See Headless @swirls/spools/headless headlessServer: a whole Spool with no interface and no web framework, as one handler @swirls/spools/client createClient: a typed client for that API ( createClient() knows your objects), and SpoolsError @swirls/spools/operations Every operation by name, and callAs and callOpen to run one from the server's own code @swirls/spools/start The binding to TanStack Start: the request middleware, for src/start.ts @swirls/spools/vite vercel, the Vercel build, for vite.config.ts @swirls/spools/testing What tests use: run, failure, installStandIns, createFakeStore, and the Tokens and RateLimiter stand-ins @swirls/spools/theme.css The styles, for src/styles.css defineSpool takes: Option Type crm the config Required. The contents of crm.config.json extensions Extensions Your hooks and handlers auth AuthAdapter Required. See Signing in database StoreAdapter Required. See Database files FilesAdapter Without it, the Files pages say files aren't set up email EmailAdapter Without it, emails are logged vault VaultAdapter Without it, no outside tokens are stored agents AgentsAdapter Without it, workflows are skipped and the assistant is off rateLimits RateLimitAdapter Without it, rate limits are counted in memory, per instance modules SpoolModule[] The modules it uses, in order: their hooks run in that order, then yours overrides paths What your app replaces of a module's part, by path. See Modules @swirls/spools/extensions What src/app/extensions.ts, a module's server code and your own endpoints import. Each function returns a promise and runs with the access of whoever the code runs for: record scopes and role access apply, and asSystem lifts both. The source is packages/spools/src/server/extension-api.ts. For Exports The contract defineExtensions, and the types Extensions, Hooks, Actor, RunContext, RunResult, RunTargetHandler, PostNetwork, AdNetwork Records createRecord, updateRecord, deleteRecord, getRecord, listRecords, countMatching. Writes run hooks, the timeline and automations The timeline, tasks, notes addActivity, listActivities, listTasks, createTask, updateTask, deleteTask, listNotes, createNote Server-kept fields writeKeptFields: writes readonly fields with no timeline line, hooks or automations. See Extending Whose work it is asSystem: runs your code as the server itself. runServer, for a program written with Effect People and connections listCrmUsers, findConnections, getAccessToken. See Integrations Files filesConfigured, recordFolder, shareRecordFolder. See Files Run targets runTarget A module's tables moduleTables: find, first, count, insert, update, remove. See Modules Live updates changedSince(keys, token?) for whoever the code runs for, and changedSinceAs(keys, token, mayRead) with a check of your own An outside caller bearerToken(headers), verifyToken(token, { authorizedParties }), callerAddress(headers) ( null when it can't be known), trustedHops Once-only writes idempotent(request, { caller, keepFor?, bodyLimit? }, work), verifiedCaller(namespace,...verifiedIds), isVerifiedCaller Rate limits hitLimit(bucket, key, limit), peekLimit(bucket, key, limit), consumeLimit(bucket, key, amount, limit), where limit is { max, windowMs } Your own secrets sealText(text, owner), openText(sealed, owner), vaultProblem(). See Adapters The last five rows are what an endpoint for people who are not teammates is built from. See Building your own door. Handlers @swirls/spools/handlers has one for each kind of server function and endpoint. Each checks who is asking before your code runs. Handler Who it answers crmHandler(name, answer) A server function, for signed-in teammates on the access list apiRoute(name, answer, options?) An endpoint, for the same people. With { idempotency: {} }, a write sent with an Idempotency-Key runs once cronRoute(name, answer, options?) A scheduled job's endpoint: needs CRON_SECRET, and answers 504 after limit publicHandler(name, answer) A server function that answers anyone publicRoute(name, answer) An endpoint that answers anyone: a webhook, or your own door. Your code checks who is calling See Pages and endpoints of your own. Adapters Import Exports @swirls/spools/auth/clerk clerk @swirls/spools/auth/clerk/backend clerk, for a Spool with no web framework @swirls/spools/auth/better-auth betterAuth @swirls/spools/auth/dev devAuth @swirls/spools/auth//ui The browser half of each, for src/spool.ui.ts @swirls/spools/database/postgres postgres @swirls/spools/database/pglite pglite @swirls/spools/database/prisma prisma @swirls/spools/files/drive drive, localBlobs, s3Blobs @swirls/spools/files/flashdrive flashdrive @swirls/spools/email/resend resend @swirls/spools/vault/cipherstash cipherstash @swirls/spools/agents/swirls swirls @swirls/spools/rate-limits/memory memoryRateLimits @swirls/spools/rate-limits/store storeRateLimits Adapters lists the packages and variables each needs. Writing an adapter @swirls/spools/adapter has the ports, types, and helpers an adapter is made from. Write your own has worked examples. Port Provides Adapter type Auth The people on the team and the accounts they sign in with AuthAdapter Store Reading and writing tables StoreAdapter FileStore Folders, files, uploads, and downloads FilesAdapter Email Sending, and reports of delivery EmailAdapter Vault Sealing and opening tokens VaultAdapter Agents Running workflows and the assistant AgentsAdapter RateLimiter Counting requests in a sliding window, and quotas in a fixed one ( hitLimit, peekLimit, consumeLimit) RateLimitAdapter Tokens Checking a token your front end forwards ( verifyToken) tokens on an AuthAdapter Pages and endpoints Each route file in src/routes mounts one of these: Import What it is @swirls/spools/pages/* Route options for each page: home, list, record, tasks, notes, files, reports, workflows, integrations, marketing, team, assistant, custom, sign-in, unsubscribe, and the layout around them @swirls/spools/api/* Handlers for each endpoint under /api @swirls/spools/ui/* The interface's own components, for pages you write, and ui/slots for modules, and defineLayoutComponent for layouts The spools command Run in a Spool's folder. The scripts in package.json call it for you. Command What it does spools gen Checks crm.config.json, with the modules' parts in it, and regenerates prisma/schema.prisma, crm.config.schema.json and src/crm.types.ts, then emits Prisma's contract ( --no-emit leaves that step out) spools keys create --name --as [--read-only] [--days | --never-expires], list, revoke : API keys for scripts and services that call the HTTP API. See Headless spools init First run: names the CRM, sets who may use it, writes.env with fresh secrets spools harden Takes Supabase's Data API roles off the tables, and fails if row-level security is off anywhere spools stats Recomputes the last activity, last contact, and next task dates on every record spools scopes backfill Gives the rows that hang off records their record's scope. Run after every change to scopes.objects. See Security spools modules Lists what each module adds and the route files they expect. Exits 1 while one is missing, printing what to put in it spools rules [object] Lists the records that already break a unique rule, by id. Exits 1 while any do. Run before db:push or db:plan. See Database spools timeline redact Rewrites old timeline lines that name records of an object someone is now kept from. See Roles spools ui check Says what is wrong with each layout ( ui in the config). Exits 1 when one will not draw; --strict also refuses a component the kit hasn't. See Layouts spools ui prompt Prints what a coding agent needs to write a layout: the language, the kit, the tools, and this Spool's objects and fields spools check-client Fails if Effect, which server code runs on, reached the browser bundle A new Spool's package.json has a script for most of them: crm:gen, init, db:harden, db:stats, db:scopes, db:rules. bun run build ends with spools check-client. check-client reads dist/client, and.vercel/output/static after a Vercel build. To check another folder, name it: spools check-client build/public." } ] diff --git a/apps/docs/src/landing/adapters.ts b/apps/docs/src/landing/adapters.ts index 32e0529..f968526 100644 --- a/apps/docs/src/landing/adapters.ts +++ b/apps/docs/src/landing/adapters.ts @@ -120,15 +120,7 @@ export const ports = [ { id: 'vault', label: 'Vault', - optional: true, choices: [ - { - label: 'AES', - call: 'aes()', - module: '@swirls/spools/vault/aes', - names: ['aes'], - variables: ['VAULT_KEY'], - }, { label: 'CipherStash', call: 'cipherstash()', diff --git a/apps/docs/src/nav.ts b/apps/docs/src/nav.ts index 6d2ecbe..7cc65b3 100644 --- a/apps/docs/src/nav.ts +++ b/apps/docs/src/nav.ts @@ -30,6 +30,7 @@ export const docsNav = [ { to: '/docs/configuration', label: 'Configuration' }, { to: '/docs/extending', label: 'Extending' }, { to: '/docs/modules', label: 'Modules' }, + { to: '/docs/headless', label: 'Headless' }, { to: '/docs/search-and-filters', label: 'Search & filters' }, { to: '/docs/campaigns', label: 'Email sequences' }, { to: '/docs/mailbox', label: 'Mailbox & calendar' }, diff --git a/apps/starter/.env.example b/apps/starter/.env.example index 82ba15c..176051b 100644 --- a/apps/starter/.env.example +++ b/apps/starter/.env.example @@ -75,18 +75,20 @@ DEV_ALLOWED_HOSTS= # S3_ACCESS_KEY_ID= # S3_SECRET_ACCESS_KEY= -# ── Integrations (optional: teammates connect more mailboxes and services) ─── -# The account a teammate signs in with needs none of this. To let them connect other -# accounts on the Integrations page, set up the vault that encrypts their tokens, plus -# APP_URL and APP_SECRET above. See docs/integrations.md. -# With vault: cipherstash() +# ── The vault (required in production) ─────────────────────────────────────── +# CipherStash seals everything the CRM keeps that must stay secret: connected accounts' +# tokens, API keys, answers kept for a repeated request. A production server does not +# start without these. Without them on your own machine a stand-in seals, which protects +# nothing. See docs/adapters.md. # CS_WORKSPACE_CRN= # CS_CLIENT_ID= # CS_CLIENT_KEY= # CS_CLIENT_ACCESS_KEY= -# With vault: aes(). `openssl rand -base64 32`. Keep replaced keys in VAULT_OLD_KEYS. -# VAULT_KEY= -# VAULT_OLD_KEYS= + +# ── Integrations (optional: teammates connect more mailboxes and services) ─── +# The account a teammate signs in with needs none of this. To let them connect other +# accounts on the Integrations page, set APP_URL and APP_SECRET above and the vault's +# variables. See docs/integrations.md. # A provider is offered once its client id and secret are set. (Better Auth signs people # in with these too.) # Redirect URI: {APP_URL}/api/integrations/google/callback diff --git a/apps/starter/e2e/playwright.config.ts b/apps/starter/e2e/playwright.config.ts index 9fd1190..1336cbf 100644 --- a/apps/starter/e2e/playwright.config.ts +++ b/apps/starter/e2e/playwright.config.ts @@ -39,7 +39,8 @@ const client = { E2E_OAUTH_CLIENT_ID: 'e2e-client', E2E_OAUTH_CLIENT_SECRET: 'e2 /** * What connecting an account needs, for the server at one port: the stand-in provider, where the - * provider sends the browser back to, and a vault key. None of it is a secret: it is used here + * provider sends the browser back to, and no CipherStash credentials, so the vault's development + * stand-in seals whatever a developer's own .env says. None of it is a secret: it is used here * and nowhere else. */ const connecting = (port: number) => ({ @@ -47,7 +48,10 @@ const connecting = (port: number) => ({ E2E_PROVIDER_URL: origin(providerPort), APP_URL: origin(port), APP_SECRET: 'browser-tests-only-'.padEnd(40, '0'), - VAULT_KEY: Buffer.alloc(32, 1).toString('base64'), + CS_WORKSPACE_CRN: '', + CS_CLIENT_ID: '', + CS_CLIENT_KEY: '', + CS_CLIENT_ACCESS_KEY: '', }) const scopedPort = firstPort + 4 diff --git a/apps/starter/e2e/spool.server.ts b/apps/starter/e2e/spool.server.ts index 386cd59..b7e9b7c 100644 --- a/apps/starter/e2e/spool.server.ts +++ b/apps/starter/e2e/spool.server.ts @@ -6,7 +6,6 @@ import { databaseUrl } from '@swirls/spools/database/postgres' import { prisma } from '@swirls/spools/database/prisma' import { resend } from '@swirls/spools/email/resend' import { flashdrive } from '@swirls/spools/files/flashdrive' -import { aes } from '@swirls/spools/vault/aes' import { cipherstash } from '@swirls/spools/vault/cipherstash' import { approvals } from '../../../examples/modules/approvals/approvals.server' @@ -76,8 +75,8 @@ export default defineSpool({ database: databaseUrl(process.env) ? prisma({ contract }) : pglite(), files: flashdrive(), email: resend(), - // With a key of its own (the browser tests set one) accounts can be connected without CipherStash. - vault: process.env['VAULT_KEY'] ? aes() : cipherstash(), + // With no CipherStash credentials (the browser tests clear them) its development stand-in seals. + vault: cipherstash(), agents: process.env['E2E_ASSISTANT'] === 'stub' ? stubAgents() : swirls(), auth: { ...dev, session }, }) diff --git a/apps/starter/prisma/schema.d.ts b/apps/starter/prisma/schema.d.ts index e4f53dc..a10dd08 100644 --- a/apps/starter/prisma/schema.d.ts +++ b/apps/starter/prisma/schema.d.ts @@ -23,9 +23,9 @@ import type { } from '@prisma/orm-postgres/contract/types'; export type StorageHash = - StorageHashBase<'89464c59400513371569606b2d68b0f28d72d88990b84ae5d65a622ead4fcbbe'>; + StorageHashBase<'b031e71e45bfa65f3f1e58c953c324dc8898ce3a022562b12d93604a7512ff00'>; export type ExecutionHash = - ExecutionHashBase<'46edcf7d60e56ad0bb55ca1d41151bcd3343d1dd48efeeff52204cedee6c9c58'>; + ExecutionHashBase<'17e28539c7a94011a7c8515872735e7bb180ef39f82fb88658ea83abdfac5ecb'>; export type ProfileHash = ProfileHashBase<'3916f444a8a17ad749191acf9e08dad97d1a327b88c2f1d45d12f240296aa8b2'>; @@ -326,6 +326,19 @@ export namespace Models { summary: FieldOutputTypes['public']['Activity']['summary']; readonly [RelationKeys]?: never; }; + export type public_ApiKey = { + createdAt: FieldOutputTypes['public']['ApiKey']['createdAt']; + digest: FieldOutputTypes['public']['ApiKey']['digest']; + expiresAt: FieldOutputTypes['public']['ApiKey']['expiresAt']; + id: FieldOutputTypes['public']['ApiKey']['id']; + lastUsedAt: FieldOutputTypes['public']['ApiKey']['lastUsedAt']; + name: FieldOutputTypes['public']['ApiKey']['name']; + readOnly: FieldOutputTypes['public']['ApiKey']['readOnly']; + revokedAt: FieldOutputTypes['public']['ApiKey']['revokedAt']; + updatedAt: FieldOutputTypes['public']['ApiKey']['updatedAt']; + userId: FieldOutputTypes['public']['ApiKey']['userId']; + readonly [RelationKeys]?: never; + }; export type public_ChangeSignal = { id: FieldOutputTypes['public']['ChangeSignal']['id']; key: FieldOutputTypes['public']['ChangeSignal']['key']; @@ -609,6 +622,7 @@ export namespace Models { export declare const models: { public: { Activity: Models.public_Activity; + ApiKey: Models.public_ApiKey; ChangeSignal: Models.public_ChangeSignal; Company: Models.public_Company; Contact: Models.public_Contact; @@ -777,6 +791,91 @@ type ContractBase = Omit< ]; foreignKeys: readonly []; }; + readonly api_keys: { + columns: { + readonly created_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: false; + readonly default: { readonly kind: 'function'; readonly expression: 'now()' }; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly digest: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + readonly expires_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: true; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly id: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + readonly last_used_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: true; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly name: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + readonly read_only: { + readonly dataType: 'pg/bool'; + readonly codecId: 'pg/bool@1'; + readonly nullable: false; + readonly default: { + readonly kind: 'literal'; + readonly value: DefaultLiteralValue<'pg/bool@1', false>; + }; + readonly many: false; + }; + readonly revoked_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: true; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly updated_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: false; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly user_id: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + }; + primaryKey: { readonly columns: readonly ['id'] }; + uniques: readonly []; + indexes: readonly [ + { + readonly name: 'api_keys_user_id_idx_6c952402'; + readonly prefix: 'api_keys_user_id_idx'; + readonly columns: readonly ['user_id']; + readonly unique: false; + }, + ]; + foreignKeys: readonly []; + }; readonly change_signals: { columns: { readonly id: { @@ -2524,6 +2623,7 @@ type ContractBase = Omit< readonly targetFamily: 'sql'; readonly roots: { readonly activities: { readonly namespace: 'public' & NamespaceId; readonly model: 'Activity' }; + readonly api_keys: { readonly namespace: 'public' & NamespaceId; readonly model: 'ApiKey' }; readonly change_signals: { readonly namespace: 'public' & NamespaceId; readonly model: 'ChangeSignal'; @@ -2677,6 +2777,87 @@ type ContractBase = Omit< }; }; }; + readonly ApiKey: { + readonly fields: { + readonly createdAt: { + readonly nullable: false; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly digest: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + readonly expiresAt: { + readonly nullable: true; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly id: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + readonly lastUsedAt: { + readonly nullable: true; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly name: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + readonly readOnly: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/bool@1' }; + }; + readonly revokedAt: { + readonly nullable: true; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly updatedAt: { + readonly nullable: false; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly userId: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + }; + readonly relations: Record; + readonly storage: { + readonly table: 'api_keys'; + readonly namespaceId: 'public'; + readonly fields: { + readonly createdAt: { readonly column: 'created_at' }; + readonly digest: { readonly column: 'digest' }; + readonly expiresAt: { readonly column: 'expires_at' }; + readonly id: { readonly column: 'id' }; + readonly lastUsedAt: { readonly column: 'last_used_at' }; + readonly name: { readonly column: 'name' }; + readonly readOnly: { readonly column: 'read_only' }; + readonly revokedAt: { readonly column: 'revoked_at' }; + readonly updatedAt: { readonly column: 'updated_at' }; + readonly userId: { readonly column: 'user_id' }; + }; + }; + }; readonly ChangeSignal: { readonly fields: { readonly id: { @@ -4296,6 +4477,43 @@ type ContractBase = Omit< readonly namespace: 'public'; }; }, + { + readonly onCreate: { + readonly id: 'timestampNow'; + readonly kind: 'generator'; + readonly params: { readonly precision: 3 }; + }; + readonly ref: { + readonly entry: 'api_keys'; + readonly field: 'created_at'; + readonly namespace: 'public'; + }; + }, + { + readonly onCreate: { readonly id: 'uuidv4'; readonly kind: 'generator' }; + readonly ref: { + readonly entry: 'api_keys'; + readonly field: 'id'; + readonly namespace: 'public'; + }; + }, + { + readonly onCreate: { + readonly id: 'timestampNow'; + readonly kind: 'generator'; + readonly params: { readonly precision: 3 }; + }; + readonly onUpdate: { + readonly id: 'timestampNow'; + readonly kind: 'generator'; + readonly params: { readonly precision: 3 }; + }; + readonly ref: { + readonly entry: 'api_keys'; + readonly field: 'updated_at'; + readonly namespace: 'public'; + }; + }, { readonly onCreate: { readonly id: 'uuidv4'; readonly kind: 'generator' }; readonly ref: { diff --git a/apps/starter/prisma/schema.json b/apps/starter/prisma/schema.json index 6abc211..a09b719 100644 --- a/apps/starter/prisma/schema.json +++ b/apps/starter/prisma/schema.json @@ -8,6 +8,10 @@ "model": "Activity", "namespace": "public" }, + "api_keys": { + "model": "ApiKey", + "namespace": "public" + }, "change_signals": { "model": "ChangeSignal", "namespace": "public" @@ -250,6 +254,132 @@ "table": "activities" } }, + "ApiKey": { + "fields": { + "createdAt": { + "nullable": false, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "digest": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + }, + "expiresAt": { + "nullable": true, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "id": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + }, + "lastUsedAt": { + "nullable": true, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "name": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + }, + "readOnly": { + "nullable": false, + "type": { + "codecId": "pg/bool@1", + "kind": "scalar" + } + }, + "revokedAt": { + "nullable": true, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "updatedAt": { + "nullable": false, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "userId": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + } + }, + "relations": {}, + "storage": { + "fields": { + "createdAt": { + "column": "created_at" + }, + "digest": { + "column": "digest" + }, + "expiresAt": { + "column": "expires_at" + }, + "id": { + "column": "id" + }, + "lastUsedAt": { + "column": "last_used_at" + }, + "name": { + "column": "name" + }, + "readOnly": { + "column": "read_only" + }, + "revokedAt": { + "column": "revoked_at" + }, + "updatedAt": { + "column": "updated_at" + }, + "userId": { + "column": "user_id" + } + }, + "namespaceId": "public", + "table": "api_keys" + } + }, "ChangeSignal": { "fields": { "id": { @@ -2863,6 +2993,11 @@ "namespaceId": "public", "tableName": "activities" }, + "api_keys": { + "kind": "rls", + "namespaceId": "public", + "tableName": "api_keys" + }, "change_signals": { "kind": "rls", "namespaceId": "public", @@ -3112,6 +3247,100 @@ } ] }, + "api_keys": { + "columns": { + "created_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "default": { + "expression": "now()", + "kind": "function" + }, + "nullable": false, + "typeParams": { + "precision": 3 + } + }, + "digest": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + }, + "expires_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": true, + "typeParams": { + "precision": 3 + } + }, + "id": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + }, + "last_used_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": true, + "typeParams": { + "precision": 3 + } + }, + "name": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + }, + "read_only": { + "codecId": "pg/bool@1", + "dataType": "pg/bool", + "default": { + "kind": "literal", + "value": false + }, + "nullable": false + }, + "revoked_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": true, + "typeParams": { + "precision": 3 + } + }, + "updated_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": false, + "typeParams": { + "precision": 3 + } + }, + "user_id": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + } + }, + "foreignKeys": [], + "indexes": [ + { + "columns": [ + "user_id" + ], + "name": "api_keys_user_id_idx_6c952402", + "prefix": "api_keys_user_id_idx", + "unique": false + } + ], + "primaryKey": { + "columns": [ + "id" + ] + }, + "uniques": [] + }, "change_signals": { "columns": { "id": { @@ -5026,10 +5255,10 @@ "kind": "postgres-schema" } }, - "storageHash": "89464c59400513371569606b2d68b0f28d72d88990b84ae5d65a622ead4fcbbe" + "storageHash": "b031e71e45bfa65f3f1e58c953c324dc8898ce3a022562b12d93604a7512ff00" }, "execution": { - "executionHash": "46edcf7d60e56ad0bb55ca1d41151bcd3343d1dd48efeeff52204cedee6c9c58", + "executionHash": "17e28539c7a94011a7c8515872735e7bb180ef39f82fb88658ea83abdfac5ecb", "mutations": { "defaults": [ { @@ -5057,6 +5286,52 @@ "namespace": "public" } }, + { + "onCreate": { + "id": "timestampNow", + "kind": "generator", + "params": { + "precision": 3 + } + }, + "ref": { + "entry": "api_keys", + "field": "created_at", + "namespace": "public" + } + }, + { + "onCreate": { + "id": "uuidv4", + "kind": "generator" + }, + "ref": { + "entry": "api_keys", + "field": "id", + "namespace": "public" + } + }, + { + "onCreate": { + "id": "timestampNow", + "kind": "generator", + "params": { + "precision": 3 + } + }, + "onUpdate": { + "id": "timestampNow", + "kind": "generator", + "params": { + "precision": 3 + } + }, + "ref": { + "entry": "api_keys", + "field": "updated_at", + "namespace": "public" + } + }, { "onCreate": { "id": "uuidv4", diff --git a/apps/starter/prisma/schema.prisma b/apps/starter/prisma/schema.prisma index c1fb6ca..7dda68d 100644 --- a/apps/starter/prisma/schema.prisma +++ b/apps/starter/prisma/schema.prisma @@ -485,6 +485,34 @@ model IdempotentRequest { @@rls } +/// A key a script or another service calls the HTTP API with, in place of a +/// person's session. It acts as one teammate, with their access and no more, for as +/// long as they are on the access list. Not a CRM object: no page, search or assistant +/// reads it. +model ApiKey { + id String @id @onCreate(uuid()) + createdAt DateTime @default(now()) @onCreate(now()) @map("created_at") + updatedAt temporal.UpdatedAt @map("updated_at") + /// What it is for, as whoever made it said: "nightly export". + name String + /// The teammate it acts as: their id at the auth provider. + userId String @map("user_id") + /// The key's seal, made by the vault for this row: the hash of its secret half and what the key may do. The secret is shown once and never kept. Empty once revoked. + digest String + /// A key that may only read: every operation that changes something refuses it. + readOnly Boolean @default(false) @map("read_only") + /// When it stops working, if it ever does. + expiresAt DateTime? @map("expires_at") + /// When it was revoked. A revoked key never works again. + revokedAt DateTime? @map("revoked_at") + /// When it last opened the API, to within a few minutes. + lastUsedAt DateTime? @map("last_used_at") + + @@index([userId]) + @@map("api_keys") + @@rls +} + /// When something last changed, by key: an object ("jobs") or one record ("jobs:"). /// Touched after every committed change to a record, its timeline, tasks and notes /// (src/server/signals.ts); a page asks whether its keys moved (`changedSince`). diff --git a/apps/starter/src/crm.types.ts b/apps/starter/src/crm.types.ts new file mode 100644 index 0000000..0822fa6 --- /dev/null +++ b/apps/starter/src/crm.types.ts @@ -0,0 +1,77 @@ +// Generated by `spools gen` from crm.config.json. Do not edit: change the config and run it again. +import type { LinksChange, RecordBase, Related } from '@swirls/spools/client' + +/** Company: a record of `companies`, as the API gives one. */ +export type Company = RecordBase & { + name: string + domain: string | null + industry: 'software' | 'finance' | 'health' | 'other' | null + employees: number | null +} + +/** What making a record of `companies` takes. Changing one takes any part of it. */ +export type CompanyValues = { + name: string + domain?: string | null + industry?: 'software' | 'finance' | 'health' | 'other' | null + employees?: number | null +} + +/** Contact: a record of `contacts`, as the API gives one. */ +export type Contact = RecordBase & { + name: string + email: string | null + phone: string | null + companyId: string | null + /** The related record: whole on a record's own page, its title only in a list. */ + company?: Related | null + status: 'lead' | 'qualified' | 'customer' | 'churned' | null + source: 'website' | 'referral' | 'outbound' | null + owner: string | null + notes: string | null +} + +/** What making a record of `contacts` takes. Changing one takes any part of it. */ +export type ContactValues = { + name: string + email?: string | null + phone?: string | null + companyId?: string | null + status?: 'lead' | 'qualified' | 'customer' | 'churned' | null + source?: 'website' | 'referral' | 'outbound' | null + owner?: string | null + notes?: string | null +} + +/** Deal: a record of `deals`, as the API gives one. */ +export type Deal = RecordBase & { + title: string + value: string | null + stage: 'discovery' | 'proposal' | 'negotiation' | 'won' | 'lost' | null + companyId: string | null + /** The related record: whole on a record's own page, its title only in a list. */ + company?: Related | null + contactId: string | null + /** The related record: whole on a record's own page, its title only in a list. */ + contact?: Related | null + closeDate: string | null + owner: string | null +} + +/** What making a record of `deals` takes. Changing one takes any part of it. */ +export type DealValues = { + title: string + value?: number | string | null + stage?: 'discovery' | 'proposal' | 'negotiation' | 'won' | 'lost' | null + companyId?: string | null + contactId?: string | null + closeDate?: string | null + owner?: string | null +} + +/** Every object of this CRM, by its key: what `createClient()` is typed with. */ +export type Crm = { + companies: { record: Company; values: CompanyValues } + contacts: { record: Contact; values: ContactValues } + deals: { record: Deal; values: DealValues } +} diff --git a/docs/README.md b/docs/README.md index fa2907d..8bb9807 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,6 +41,8 @@ export default defineSpool({ and server-only fields) hold for every writer. A role can be denied an object or left to read it, and a branch kept to its own records. - **Your own code.** Hooks, handlers, pages, endpoints, and services. +- **Your own front end.** Run the server [headless](headless.md), with no interface, and build + the design you want on its HTTP API and typed client. Every rule above holds there too. - **Modules.** Feature sets that plug into a Spool: objects, code, tables of their own, panels and pages. @@ -50,6 +52,7 @@ export default defineSpool({ | ---------------------------------------- | ------------------------------------------------------------- | | Build one with your agent | [Build with coding agents](coding-agents.md) | | See one running | [Quickstart](quickstart.md) | +| Build your own front end on it | [Headless](headless.md) | | Decide whether it suits you | [When to use Spools](when-to-use.md) | | Describe your business | [Configuration](configuration.md) | | Choose sign-in, a database, and the rest | [Adapters](adapters.md) | diff --git a/docs/adapters.md b/docs/adapters.md index fa2820d..d8e2890 100644 --- a/docs/adapters.md +++ b/docs/adapters.md @@ -11,7 +11,7 @@ import { clerk } from '@swirls/spools/auth/clerk' import { postgres } from '@swirls/spools/database/postgres' import { resend } from '@swirls/spools/email/resend' import { drive, s3Blobs } from '@swirls/spools/files/drive' -import { aes } from '@swirls/spools/vault/aes' +import { cipherstash } from '@swirls/spools/vault/cipherstash' import crm from '../crm.config.json' with { type: 'json' } import extensions from './app/extensions' @@ -23,7 +23,7 @@ export default defineSpool({ database: postgres(), files: drive({ blobs: s3Blobs() }), email: resend(), - vault: aes(), + vault: cipherstash(), agents: swirls(), }) ``` @@ -45,8 +45,7 @@ an adapter can't do without stops a production server from starting. | Files | `@swirls/spools/files/drive` | A `Blobs`: `localBlobs()` or `s3Blobs()`. See [Files](files.md) | | | `@swirls/spools/files/flashdrive` | `FLASHDRIVE_API_KEY`, `FLASHDRIVE_DRIVE_ID` | | Email | `@swirls/spools/email/resend` | `RESEND_API_KEY`, `EMAIL_FROM`, `resend` | -| Vault | `@swirls/spools/vault/cipherstash` | The `CS_*` variables, `@cipherstash/stack` | -| | `@swirls/spools/vault/aes` | `VAULT_KEY` (`openssl rand -base64 32`) | +| Vault | `@swirls/spools/vault/cipherstash` | The `CS_*` variables, `@cipherstash/stack`. See below | | Agents | `@swirls/spools/agents/swirls` | `SWIRLS_PROJECT_ID`. See [Swirls](swirls.md) | | Rate limits | `@swirls/spools/rate-limits/memory` | Nothing. The default: counts per server instance | | | `@swirls/spools/rate-limits/store` | The `rate_limit_slots` table. Counts the same on every instance | @@ -54,6 +53,22 @@ an adapter can't do without stops a production server from starting. The packages named here are optional peer dependencies: install the ones your adapters use. +### The vault is CipherStash + +Everything a Spool keeps that must stay secret is sealed by the vault before it reaches +the database: the tokens of accounts teammates connect, the seal of an +[API key](headless.md#api-keys), an answer kept for a repeated request, and whatever your +own code seals with `sealText`. There is one vault, [CipherStash](https://cipherstash.com), +which gives each value a key of its own and keeps the root of them outside your database +and your server's environment. + +A production server does not start without the four `CS_*` variables. On your own machine +and in tests, where they are not set, a stand-in seals instead, with a key that is in the +framework's source. It protects nothing and the server says so when it starts +(`[env] Encryption of stored secrets (CipherStash): ...`). What the stand-in sealed is +not opened by a server with CipherStash, so nothing sealed on a laptop is trusted in +production. + ### Changing one Change its line in `src/spool.server.ts`. Auth also has a browser half, listed in diff --git a/docs/api.md b/docs/api.md index 0d9db68..ac67018 100644 --- a/docs/api.md +++ b/docs/api.md @@ -17,7 +17,11 @@ the links lead to the source. | `@swirls/spools/config-schema` | [The config's schema](../packages/spools/src/crm/config-schema.ts), for checking a `crm.config.json` | | `@swirls/spools/server` | [`serveSpool`](../packages/spools/src/server/entry.ts), for `src/server.ts` | | `@swirls/spools/server/*` | The server's own modules, for code written with Effect. See [Writing server code](server-code.md) | -| `@swirls/spools/start` | [The request middleware](../packages/spools/src/server/middleware.ts), for `src/start.ts` | +| `@swirls/spools/http` | [`httpApi`](../packages/spools/src/server/http.ts): the CRM over HTTP as one `Request` to `Response` handler, for a server with no interface. See [Headless](headless.md) | +| `@swirls/spools/headless` | [`headlessServer`](../packages/spools/src/headless.ts): a whole Spool with no interface and no web framework, as one handler | +| `@swirls/spools/client` | [`createClient`](../packages/spools/src/client.ts): a typed client for that API (`createClient()` knows your objects), and `SpoolsError` | +| `@swirls/spools/operations` | [Every operation](../packages/spools/src/server/operations/index.ts) by name, and `callAs` and `callOpen` to run one from the server's own code | +| `@swirls/spools/start` | [The binding to TanStack Start](../packages/spools/src/start.ts): the request middleware, for `src/start.ts` | | `@swirls/spools/vite` | [`vercel`](../packages/spools/src/vite.ts), the Vercel build, for `vite.config.ts` | | `@swirls/spools/testing` | [What tests use](../packages/spools/src/testing/index.ts): `run`, `failure`, `installStandIns`, `createFakeStore`, and the `Tokens` and `RateLimiter` stand-ins | | `@swirls/spools/theme.css` | The styles, for `src/styles.css` | @@ -86,6 +90,7 @@ See [Pages and endpoints of your own](extending.md#pages-and-endpoints-of-your-o | Import | Exports | | ----------------------------------- | ----------------------------------------------- | | `@swirls/spools/auth/clerk` | `clerk` | +| `@swirls/spools/auth/clerk/backend` | `clerk`, for a Spool with no web framework | | `@swirls/spools/auth/better-auth` | `betterAuth` | | `@swirls/spools/auth/dev` | `devAuth` | | `@swirls/spools/auth//ui` | The browser half of each, for `src/spool.ui.ts` | @@ -95,7 +100,6 @@ See [Pages and endpoints of your own](extending.md#pages-and-endpoints-of-your-o | `@swirls/spools/files/drive` | `drive`, `localBlobs`, `s3Blobs` | | `@swirls/spools/files/flashdrive` | `flashdrive` | | `@swirls/spools/email/resend` | `resend` | -| `@swirls/spools/vault/aes` | `aes` | | `@swirls/spools/vault/cipherstash` | `cipherstash` | | `@swirls/spools/agents/swirls` | `swirls` | | `@swirls/spools/rate-limits/memory` | `memoryRateLimits` | @@ -141,19 +145,20 @@ export const Route = createFileRoute('/_crm/tasks')(tasksPage) Run in a Spool's folder. The scripts in `package.json` call it for you. -| Command | What it does | -| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `spools gen` | Checks `crm.config.json`, with the modules' parts in it, and regenerates `prisma/schema.prisma` and `crm.config.schema.json`, then emits Prisma's contract (`--no-emit` leaves that step out) | -| `spools init` | First run: names the CRM, sets who may use it, writes `.env` with fresh secrets | -| `spools harden` | Takes Supabase's Data API roles off the tables, and fails if row-level security is off anywhere | -| `spools stats` | Recomputes the last activity, last contact, and next task dates on every record | -| `spools scopes backfill` | Gives the rows that hang off records their record's scope. Run after every change to `scopes.objects`. See [Security](security.md#record-scopes) | -| `spools modules` | Lists what each module adds and the route files they expect. Exits 1 while one is missing, printing what to put in it | -| `spools rules [object]` | Lists the records that already break a `unique` rule, by id. Exits 1 while any do. Run before `db:push` or `db:plan`. See [Database](database.md#uniqueness-rules) | -| `spools timeline redact` | Rewrites old timeline lines that name records of an object someone is now kept from. See [Roles](roles.md#access) | -| `spools ui check` | Says what is wrong with each layout (`ui` in the config). Exits 1 when one will not draw; `--strict` also refuses a component the kit hasn't. See [Layouts](layouts.md#checking-and-writing-layouts) | -| `spools ui prompt` | Prints what a coding agent needs to write a layout: the language, the kit, the tools, and this Spool's objects and fields | -| `spools check-client` | Fails if Effect, which server code runs on, reached the browser bundle | +| Command | What it does | +| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `spools gen` | Checks `crm.config.json`, with the modules' parts in it, and regenerates `prisma/schema.prisma`, `crm.config.schema.json` and `src/crm.types.ts`, then emits Prisma's contract (`--no-emit` leaves that step out) | +| `spools keys` | `create --name --as [--read-only] [--days \| --never-expires]`, `list`, `revoke `: API keys for scripts and services that call the HTTP API. See [Headless](headless.md#api-keys) | +| `spools init` | First run: names the CRM, sets who may use it, writes `.env` with fresh secrets | +| `spools harden` | Takes Supabase's Data API roles off the tables, and fails if row-level security is off anywhere | +| `spools stats` | Recomputes the last activity, last contact, and next task dates on every record | +| `spools scopes backfill` | Gives the rows that hang off records their record's scope. Run after every change to `scopes.objects`. See [Security](security.md#record-scopes) | +| `spools modules` | Lists what each module adds and the route files they expect. Exits 1 while one is missing, printing what to put in it | +| `spools rules [object]` | Lists the records that already break a `unique` rule, by id. Exits 1 while any do. Run before `db:push` or `db:plan`. See [Database](database.md#uniqueness-rules) | +| `spools timeline redact` | Rewrites old timeline lines that name records of an object someone is now kept from. See [Roles](roles.md#access) | +| `spools ui check` | Says what is wrong with each layout (`ui` in the config). Exits 1 when one will not draw; `--strict` also refuses a component the kit hasn't. See [Layouts](layouts.md#checking-and-writing-layouts) | +| `spools ui prompt` | Prints what a coding agent needs to write a layout: the language, the kit, the tools, and this Spool's objects and fields | +| `spools check-client` | Fails if Effect, which server code runs on, reached the browser bundle | A new Spool's `package.json` has a script for most of them: `crm:gen`, `init`, `db:harden`, `db:stats`, `db:scopes`, `db:rules`. `bun run build` ends with `spools check-client`. diff --git a/docs/architecture.md b/docs/architecture.md index 65bf1a5..18b0330 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -50,6 +50,7 @@ that nobody has to patch the framework. ``` Browser ── server functions (server/*.functions.ts) ─┐ +Your own front end ─ HTTP API (server/http.ts) ──────┤ both run the same operations (server/operations) Swirls ─── tool API (server/tools.ts) ───────────────┤ Scheduler ─ cron routes (api/*) ─────────────────────┤ Outsiders ─ your own endpoints (publicRoute) ────────┤ @@ -72,6 +73,11 @@ Outsiders ─ your own endpoints (publicRoute) ────────┤ Paths on this page are inside `packages/spools/src` unless they start with the name of one of your own files. +- **Operations** are what the CRM does for whoever asks, each defined once + (`server/operations`): its name, what it takes, who may ask, and the program that + answers. The interface's server functions only bind them to TanStack Start, and the + [HTTP API](headless.md) answers the same ones for a front end of your own. Nothing on + the server's side imports a web framework but those bindings and `src/start.ts`. - **The boundary** is where a request becomes an [Effect](https://effect.website) program. A server function's handler is `crmHandler(...)` and a route uses an adapter (`apiRoute`, `cronRoute`, `publicRoute`, `toolRoute`). It asks the auth adapter for the session and reads the request before the diff --git a/docs/auth.md b/docs/auth.md index 84ab8b2..dab59fb 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -38,6 +38,18 @@ Set `CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY`, and install `@clerk/tanstack-react-start`. Under Restrictions in the Clerk dashboard, limit sign-ups to your team; the access list is checked either way. +A [headless](headless.md#sign-in) Spool imports `clerk` from +`@swirls/spools/auth/clerk/backend` and installs `@clerk/backend` instead: the same adapter, +reading the session from the request itself, with no TanStack Start and no browser half. +Both adapters take a session only from your own front end. On TanStack Start, Clerk's +middleware is told the origin of `APP_URL` on a production server (or the origins in +`clerk({ authorizedParties: [...] })`, in any mode), so a session token Clerk issued to +another app on the same instance is nobody. The headless adapter +takes a session cookie only when Clerk issued it to your own front end: the origin of +`APP_URL`, or the origins you name with `clerk({ authorizedParties: [...] })` when the front +end lives at another address. A production server that has neither takes no session, so a +token made for another app on the same Clerk instance never opens the CRM. + Clerk holds the Google and Microsoft tokens of the accounts people sign in with, which is how their [mail and calendar](mailbox.md) are read. It can also make the token that signs each person in to [Swirls](swirls.md) without an API key. @@ -193,11 +205,11 @@ capability of an auth adapter (`tokens` on the adapter, the `Tokens` port in })` in `@swirls/spools/extensions`: the user id it was issued to, or null, never a failure. Without it every token is null. -| Adapter | Tokens | -| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `clerk()` | A session token of the same Clerk instance, issued to one of the origins you name (`azp`), checked with Clerk's `authenticateRequest` on a request that carries only the bearer header. `CLERK_JWT_KEY` lets it check offline; without it a token naming a key the instance doesn't have is refused before Clerk is asked, and the keys are fetched at most once a minute | -| `devAuth()` | The tokens of `outsiders: [{ id, name, email, token }]`, people the directory knows who are never on the team list. Origins are not checked | -| `betterAuth()` | None. Its session tokens are the session cookie's value, with no audience: a teammate's token from the CRM itself would count, and nothing ties one to your front end. `verifyToken` gets null for every token | +| Adapter | Tokens | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `clerk()` | A session token of the same Clerk instance, issued to one of the origins you name (`azp`), checked with Clerk's `authenticateRequest` on a request that carries only the bearer header. `CLERK_JWT_KEY` lets it check offline; without it a token naming a key the instance doesn't have is refused before Clerk is asked, and the keys are fetched at most once a minute | +| `devAuth()` | The tokens of `outsiders: [{ id, name, email, token }]`, people the directory knows who are never on the team list. Origins are not checked | +| `betterAuth()` | None unless you ask: `betterAuth({ bearer: true })` takes a session's own token, which the answer that signs someone in then carries in a `set-auth-token` header. It is the session, with no front end to name, so `authorizedParties` is not read: a token from the CRM's own pages would count. Its signature is checked before anything is read. Without `bearer`, `verifyToken` gets null for every token and an `Authorization` header is ignored | A session cookie sent with such a request counts for nothing: only the bearer token is checked. diff --git a/docs/coding-agents.md b/docs/coding-agents.md index a96524a..43ac3dc 100644 --- a/docs/coding-agents.md +++ b/docs/coding-agents.md @@ -23,6 +23,9 @@ bun run db:seed bun run dev ``` +For the backend alone, with a front end you design yourself, add `--headless` +([Headless](headless.md)). Its `AGENTS.md` tells the agent the same things without the pages. + Then open the folder in your agent and ask: > Build our CRM. We sell commercial insurance, and we track companies, the people at them, policies @@ -44,6 +47,7 @@ Most changes are a few lines in one of these places. | Email people on a schedule | `campaigns` in `crm.config.json` | | When something happens, do something | `automations` in the config, or a hook in `src/app/extensions.ts` | | A page or an endpoint nobody else needs | A file in `src/routes` | +| A front end of your own, or a script | The [HTTP API](headless.md) and its typed client, with `src/crm.types.ts` for your fields | | An endpoint for people who are not teammates | A file in `src/routes/api` behind `publicRoute`, built as [your own door](extending.md#building-your-own-door) | | A feature set to use in more than one Spool | A [module](modules.md), listed in `src/spool.server.ts` and `src/spool.ui.ts` | | Use a different sign-in, database, or service | `src/spool.server.ts` | diff --git a/docs/deployment.md b/docs/deployment.md index a25630d..a377210 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -49,7 +49,8 @@ Restrictions, limit sign-ups to your team (the CRM also enforces ## 3. Environment Set what your adapters need from [`.env.example`](../apps/starter/.env.example). At minimum -`DATABASE_URL`, your auth provider's keys, `APP_URL` and `APP_SECRET`. The server logs which optional +`DATABASE_URL`, your auth provider's keys, the vault's four `CS_*` variables +([CipherStash](adapters.md#the-vault-is-cipherstash)), `APP_URL` and `APP_SECRET`. The server logs which optional features are on at startup, and refuses to start in production without the required variables. @@ -117,6 +118,38 @@ instead: `bun run build` checks the browser files Vercel serves (`.vercel/output/static`) for server code, as it checks `dist/client` everywhere else. +## A headless Spool + +A [headless](headless.md) Spool is one Bun process with no build step: + +```sh +bun install --frozen-lockfile +bun run start +``` + +`bun run start` runs `src/server.ts` with `NODE_ENV=production`, on `PORT` (3000 unless it +says) and every interface. Steps 1 to 3 above are the same, and so are the health check, the +schedules and the cron routes below. What is different: + +- **Where the front end is.** A front end on the same site as the API needs nothing more: + the browser sends the session cookie. One on another site sends each person's sign-in + token, so name its origin in `src/server.ts`, in both `tokens.authorizedParties` and + `origins`. With neither named, no token opens the API and no other site's page may call it. +- **Clerk.** Set `APP_URL` to the address of your front end, or name the front ends in + `clerk({ authorizedParties })`. A production server with neither takes nobody's cookie. +- **Better Auth.** Serve the front end and the API from one origin (`APP_URL`), behind one + proxy if they are two servers, because its cookie and its emailed link are that origin's. +- **`TRUST_PROXY`**, as for [a door of your own](#your-own-door): `src/server.ts` keeps the + one address that many proxies from the right of `X-Forwarded-For`, which is what rate + limits count by. +- **API keys.** They are taken only with `keys: true`, and made on the server with + `bunx spools keys create`, by someone with the app's folder and its environment + ([API keys](headless.md#api-keys)). They are sealed by the vault, so the `CS_*` variables + are needed to make one and to take one. + +A Spool with the interface can serve the API too: mount `httpApi()` from +`@swirls/spools/http` at a route of its own, and it deploys as any Spool does. + ## A host with no long-lived process On any other such host, set `SERVERLESS=1`. The server then keeps no timers, and cron jobs @@ -165,8 +198,10 @@ Deploy `swirls/` and set its secrets (see [Swirls](swirls.md)), with - [ ] Supabase → Settings → API → Exposed schemas doesn't include `public` - [ ] `TRUST_PROXY` matches the number of proxies in front of the app - [ ] With a door of your own: its front end's origins set, and `CLERK_JWT_KEY` with `clerk()` +- [ ] Headless: the front end's origin named in `tokens.authorizedParties` and `origins` (or it is on the API's own site), `APP_URL` set to it for Clerk, and `keys: true` only if scripts call with keys - [ ] `access` in `crm.config.json` lists your domain or emails - [ ] Sign-ups restricted at your auth provider +- [ ] The `CS_*` variables are a CipherStash workspace of this environment's own - [ ] `APP_SECRET` and `SWIRLS_APP_TOKEN` are 32+ random characters, unique per environment - [ ] On Vercel or another serverless host: `CRON_SECRET` set and cron jobs for `/api/cron/sequences`, `/api/cron/mail-sync` and, if you schedule posts, `/api/cron/marketing` - [ ] Email domain verified and the delivery webhook (`/api/webhooks/email`) configured diff --git a/docs/extending.md b/docs/extending.md index 1ceb573..cc77d0c 100644 --- a/docs/extending.md +++ b/docs/extending.md @@ -416,6 +416,10 @@ export const Route = createFileRoute('/_crm/tasks')({ ...tasksPage, component: M ## Pages and endpoints of your own +This section is about a Spool with its interface. In a [headless](headless.md) Spool there +are no route files: a page is your front end's, and an endpoint of your own is a branch in +`src/server.ts` before the Spool is asked. + A page is a route file. Inside `src/routes/_crm` it gets the CRM's shell, and only signed-in teammates can open it. The framework's parts are in `@swirls/spools/ui/*` (`kit` for buttons and dialogs, `shell` for the top bar, `workspace`, `views`). @@ -477,6 +481,10 @@ server function or endpoint that goes without one. ## Building your own door +A front end or a script that acts as a teammate needs none of this: it calls the +[HTTP API](headless.md), which checks the access list, roles and scopes for it. This section +is for callers who are not teammates. + Spools has no built-in door for people who are not teammates (installation crews, clients, vendors). Your app builds its own endpoints for them behind `publicRoute`, from small pieces in `@swirls/spools/extensions`, and decides itself who may do what. Nothing a teammate's request @@ -634,6 +642,9 @@ says; larger is 413 `too_large`). answer is never kept in the clear. **What a front end does with one:** take the status as the outcome of its write (it was made, once), and read what it needs back; never parse the withheld body as the first answer. +- An answer is kept for the caller as they were: their record scopes and what their roles + keep from them. A repeat by someone whose access has changed since gets the withheld + answer too, because what the first answer showed may no longer be theirs to see. - Once your code has answered, nothing fails the request: keeping the answer is tried again if the database stumbles, and an answer that can't be kept is logged and still sent. Only if the database refuses every try is the key left to go stale, when a repeat would run again. diff --git a/docs/files.md b/docs/files.md index 0b48000..246b1d2 100644 --- a/docs/files.md +++ b/docs/files.md @@ -278,6 +278,10 @@ with two of that name. Folders, and moves, are settled between them. ## Who can see what +A [headless](headless.md) Spool has the same files behind the `files.*` operations and +`/api/files/*`, with the same checks. A read-only API key can list and search them, and its +first look does not make the library's folders. + Anyone who may use the CRM can see, add, rename, move and delete every file, as they can notes and tasks, unless [role access](roles.md#access) or [record scopes](#with-record-scopes) say otherwise. Folders give no separate permissions: a record's folder is the record's. diff --git a/docs/headless.md b/docs/headless.md new file mode 100644 index 0000000..763c156 --- /dev/null +++ b/docs/headless.md @@ -0,0 +1,325 @@ +# Headless + +A Spool comes with a whole CRM to look at: pages, lists, boards, a record page. You can +also run it with none of that, as the server behind a front end of your own. The records, +the rules, record scopes, roles, automations, sequences and files are the same server +either way. What changes is what you put in front of it. + +Use the interface a Spool comes with when you want a CRM today and are happy to theme it. +Go headless when the product is your own design: a customer portal, a mobile app, a +back-office tool on another framework, or a script. + +## What a headless Spool is + +Everything the CRM does for whoever asks is an **operation**: `records.list`, +`records.create`, `tasks.update`, `files.startUpload` and so on. Each is defined once, with +its name, what it takes, who may ask, and the program that answers. The interface's own +server functions run these operations, and so does the HTTP API. So a rule that holds in +the interface holds for your front end too, and neither has a door the other lacks. + +Nothing on the server's side imports a web framework. A headless Spool needs Bun, `effect` +and the adapters you chose. It does not load React or TanStack Start. + +## A server with no interface + +Start a headless Spool with: + +```sh +bun create @swirls/spools my-crm --headless +``` + +It is the same config, extensions and services as any Spool, with no pages, no React and no +TanStack Start. Its server is one file: + +```ts +// src/server.ts +import './spool.server' +import { headlessServer } from '@swirls/spools/headless' + +const spools = headlessServer() + +Bun.serve({ port: 3000, fetch: (request) => spools.fetch(request) }) +``` + +`headlessServer` answers everything a Spool answers except pages, at the same addresses, +and starts the schedules (sequences, mailbox sync, marketing): + +| Address | | +| --------------------- | ------------------------------------------------------------- | +| `/api/v1/*` | Every operation (below) | +| `/api/auth/*` | The auth adapter's own sign-in, when it has one (Better Auth) | +| `/api/files/*` | Downloads, and uploads relayed through the server | +| `/api/assistant*` | The assistant's chat | +| `/api/integrations/*` | Connecting an account (OAuth) | +| `/api/swirls/tools/*` | The tool API that workflows and the assistant call | +| `/api/webhooks/email` | Bounces and complaints from the email service | +| `/api/cron/*` | What a scheduler calls on a serverless host | +| `POST /unsubscribe` | One-click unsubscribe from an email | +| `/healthz` | `ok` | + +The pages those addresses once led back to (after sign-in, after connecting an account, the +unsubscribe page) are your front end's to draw. + +It takes the options of `httpApi`: + +| Option | | +| -------------------------- | -------------------------------------------------------------------------------------------------- | +| `basePath` | Where the API is mounted. `/api/v1` unless it says | +| `tokens.authorizedParties` | The front ends whose sign-in tokens are taken as bearer tokens. Without it, no token opens the API | +| `origins` | Origins a browser on another site may call from (CORS) | +| `keys` | Take [API keys](#api-keys) as bearer tokens. Off unless it says | + +To put the API alone beside routes of another server, mount `httpApi()` from +`@swirls/spools/http` instead: it is one handler that answers only paths under `basePath`. +A Spool with the interface can mount it too, and then has both. + +## Calling it + +| Request | | +| --------------------------------- | ------------------------------------------------------------------------------------------------ | +| `GET /api/v1` | Every operation: its name, whether it reads or writes, who may ask, and its input as JSON Schema | +| `POST /api/v1/` | Runs an operation. The JSON body is its input | +| `GET /api/v1/?input=` | The same, for an operation that only reads | +| `GET /api/v1/openapi.json` | The same list as an OpenAPI 3.1 document, for tools that read one | + +An answer is `{ "data": ... }`. A refusal or a failure is +`{ "error": { "code": "...", "message": "..." } }`: + +| Status | `code` | When | +| ------ | -------------------- | --------------------------------------------------------------- | +| 400 | `invalid_input` | The input is not what the operation takes | +| 400 | `invalid` | The operation refused what was asked (a rule, a missing field) | +| 401 | `unauthorized` | Nobody is signed in, or the token is not one this server takes | +| 403 | `forbidden` | Signed in, but not on the access list, or outside their scope | +| 403 | `cross_site` | A browser on another site sent a session cookie | +| 403 | `read_only` | A read-only API key asked for a change | +| 404 | `not_found` | No such operation or record. A record a role hides is also this | +| 405 | `method_not_allowed` | A write asked for with `GET` | +| 409 | `conflict` | A [uniqueness rule](configuration.md#record-rules) refused it | +| 413 | `too_large` | The body is over 1 MB | +| 500 | `failed` | Anything else. The server's log has the rest | + +A write sent with an `Idempotency-Key` header runs once for that teammate, and a repeat +gets the first answer again. See [idempotent requests](extending.md#idempotent-requests). + +```sh +curl -X POST https://crm.example.com/api/v1/records.create \ + -H 'Authorization: Bearer ' \ + -H 'Content-Type: application/json' \ + -H 'Idempotency-Key: 7f1c0a52-4a43-4c0e-9d0b-3f6f6c1f2a10' \ + -d '{ "objectKey": "contacts", "values": { "name": "Pat Lee" } }' +``` + +## The typed client + +`@swirls/spools/client` knows every operation by name, what each takes and what each +answers. It imports nothing of the server: only the types cross. + +```ts +import { createClient, SpoolsError } from '@swirls/spools/client' + +const crm = createClient({ + baseUrl: 'https://crm.example.com/api/v1', + token: () => auth.getToken(), +}) + +const { rows, total } = await crm.call('records.list', { objectKey: 'contacts', q: 'pat' }) + +try { + await crm.call('records.update', { objectKey: 'contacts', id, values: { stage: 'Won' } }) +} catch (error) { + if (error instanceof SpoolsError && error.code === 'conflict') { + // error.message is written for the person who made the change + } +} +``` + +Dates arrive as text, as JSON carries them, and the types say so. The types come from the +package, so a front end in another repository installs `@swirls/spools` as a development +dependency to get them. + +### Your objects, typed + +`bun run crm:gen` writes `src/crm.types.ts` from the config: for each object, the record as +the API gives it and the values a write takes, and `Crm`, which lists them by key. Give it +to the client and `records(key)` knows every field: + +```ts +import type { Crm } from './crm.types' + +const crm = createClient({ baseUrl: 'https://crm.example.com/api/v1' }) +const deals = crm.records('deals') + +const { id } = await deals.create({ title: 'Renewal', stage: 'proposal', value: 12000 }) +await deals.update(id, { stage: 'won' }) + +const { record } = await deals.get(id) // record.stage is 'discovery' | 'proposal' | ... +const { rows } = await deals.list({ q: 'renewal' }) +``` + +A select is one of its options, money is a decimal in text when read (`"12000.00"`) and may +be written as a number, and a relation is the related record's id under `Id` with the +record beside it under ``. A list brings back the fields it asked for, so a row's +fields are all optional but its `id`. Rename a field in the config and the front end stops +compiling where it used the old name. The file is generated: never edit it. + +## Who is asking + +The API decides who is asking exactly as the interface does. Whoever it is must be on the +[access list](security.md), works in the [record scope](security.md#record-scopes) they +asked for out of the ones they hold, and reaches what their [roles](roles.md#access) let +them. No operation can be called as "the system". + +There are three ways to say who you are: + +- **The session cookie**, for a front end on the same site as the API. The browser sends + it by itself. A request from a page on another site is refused before anything runs, so + another site's page can't act through a signed-in teammate. +- **A sign-in token**, sent as `Authorization: Bearer `, for a front end anywhere + else. The server takes one only when you name the front ends whose tokens count: + + ```ts + const spools = headlessServer({ + tokens: { authorizedParties: ['https://app.example.com'] }, + origins: ['https://app.example.com'], + }) + ``` + +- **An API key**, sent the same way, for a script or another service ([below](#api-keys)). + +A request with a bearer token is judged by the token alone. A cookie sent with it counts +for nothing. + +A caller with a token names its record scope in an `X-Spools-Scope` header: a scope's key, +or `*` for all of theirs. It is a preference, checked against what they hold. + +### Sign-in + +| Adapter | In a headless Spool | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `clerk()` | Import it from `@swirls/spools/auth/clerk/backend`. It reads Clerk's session cookie from the request with Clerk's backend SDK, and checks bearer tokens. A cookie counts only when Clerk issued it to your front end: the origin of `APP_URL`, or the ones in `clerk({ authorizedParties })`. Your front end uses Clerk's kit for its framework | +| `betterAuth()` | Works as it is: sign-in runs from this server under `/api/auth`, and the cookie is this site's, so a front end of pages is served from the same origin as the API (`APP_URL`), behind one proxy if they are two servers. It serves `/sign-in`, where the emailed link lands. For an app that can't keep a cookie, see [below](#better-auth-in-an-app) | +| `devAuth()` | Works as it is, for development: every request is you | + +With Clerk, a session Clerk would renew by sending the browser away and back counts as +signed out, because an API can't redirect. Clerk's browser kit renews the cookie before +that is needed. + +### Better Auth in an app + +A phone or desktop app has no cookie jar to rely on. `betterAuth({ bearer: true })` lets it +carry the session as a bearer token instead: + +```ts +auth: betterAuth({ bearer: true }), +``` + +```ts +const spools = headlessServer({ tokens: { authorizedParties: [] } }) +``` + +The answer that signs someone in (`GET /api/auth/magic-link/verify`, or a provider's +callback) then carries a `set-auth-token` header. The app keeps its value and sends it as +`Authorization: Bearer ` on every call. The token is the session: it lasts as long +as the session does, signing out ends it, and whoever holds it is that person, so keep it +where the platform keeps secrets. The server signed it for someone it signed in itself, so +there is no front end to name and `authorizedParties` stays empty. Leave `bearer` off for a +front end of pages in a browser, where the cookie is kept from scripts and a token would +not be. + +## API keys + +A script, a nightly job or another service calls the API with a key in place of a person's +session. Keys are off until the server says it takes them: + +```ts +const spools = headlessServer({ keys: true }) +``` + +Without that, a key is a token the server doesn't take and the table that holds keys is +never read. Then make one: + +```sh +bunx spools keys create --name "nightly export" --as ana@example.com --read-only +bunx spools keys list +bunx spools keys revoke +``` + +```sh +curl -X POST https://crm.example.com/api/v1/records.list \ + -H 'Authorization: Bearer spk_...' \ + -d '{ "objectKey": "contacts" }' +``` + +A key is not a new kind of caller. It acts as the teammate named with `--as`: it reaches the +records they reach, in the scopes they hold, with what their roles allow, and its changes +are theirs on the timeline. Take them off the access list and the key opens nothing. For a +service, make a teammate for it (an address of its own on the access list, with a role that +reaches only what it needs) and make the key as them. + +| Option | | +| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--read-only` | The key may run operations that read, and is refused every one that writes. A read made with it leaves the file store as it is too: the shared library's folders are not made on its first look | +| `--days ` | It stops working after that many days: 90 unless this says | +| `--never-expires` | It works until it is revoked. Say so on purpose: a key that never ends is one nobody remembers to end | + +`create` prints the key once. What the `api_keys` table keeps is sealed by the Spool's +[vault](adapters.md) (CipherStash, in a Spool as it is made): the hash of the key's secret together with whose +key it is, whether it only reads and when it ends, encrypted for that one row. A key is +judged by what its seal says, never by the row's own columns. So: + +- Reading the database gives nobody a key that works, and a lost key is replaced, not + recovered. +- Writing to the database gives nobody one either. A row someone inserts has no seal the + vault made, a seal copied from another row was made for that row, and a row whose + teammate, reach or expiry someone changes no longer says what its seal says. A revoked + key's seal is wiped, so it can't be brought back. +- A Spool with no vault has no keys: none is made and none is taken. + +What the vault opened is remembered for a minute, so a busy key is not a call to the vault +on every request. Revoking still takes effect at once, because the row is read every time. + +Keys are managed with the command, by whoever can run commands in the app's folder with its +environment: there is no operation that makes one, so no caller of the API can mint more +access than they have. + +## In production + +`bun run start` runs the server with `NODE_ENV=production`. It refuses to start with the +development sign-in or without the vault's `CS_*` variables +([CipherStash](adapters.md#the-vault-is-cipherstash)), which seal API keys, connected +accounts and kept answers. [Deployment](deployment.md#a-headless-spool) has what a headless +Spool needs set, and [Security](security.md#the-http-api) what the API promises. + +On your own machine none of that is needed: records go in a Postgres inside the server, +every request is you, and a stand-in seals in place of the vault. + +## From the server's own code + +A front end that shares the process (a server-rendered page, a route of your own) skips +HTTP and calls the operation: + +```ts +import { callAs, crm } from '@swirls/spools/operations' +import { runServer } from '@swirls/spools/server/runtime' + +const { record } = await runServer(callAs({ userId }, crm.getRecord, { objectKey: 'contacts', id })) +``` + +`callAs` takes a user id and checks it the same way: the access list, scopes and roles all +apply. Where the id comes from is yours to get right. Take it from a session the auth +adapter read or a token it verified, never from the request's own say-so. + +## What isn't headless yet + +- **Better Auth with pages on another origin.** Its cookie, its emailed link and its + redirects are all on `APP_URL`, so a front end of pages is served from that origin. A + front end on another origin uses Clerk. +- **Answers are described for the record operations only.** `GET /api/v1` and the OpenAPI + document describe every operation's input, and the answer of `records.get`, + `records.list`, `records.create`, `records.update`, `records.delete`, + `records.deleteMany`, `records.titles`, `records.searchTitles` and `brand.get`. A record + is described by what every record has; its own fields are in `src/crm.types.ts`. The + other answers are in the TypeScript types only. +- **React hooks** for a front end (lists, a record, filters, inline editing as state without + markup) are not there yet. The typed client is what a front end calls today. diff --git a/docs/integrations.md b/docs/integrations.md index 06fb0fb..d84d8fd 100644 --- a/docs/integrations.md +++ b/docs/integrations.md @@ -137,13 +137,7 @@ The sign-in mailbox needs none of this. To let teammates connect more accounts: ### 1. The vault -With `vault: aes()` there is one thing to set, a key of your own: -`VAULT_KEY=$(openssl rand -base64 32)`. Keep it somewhere other than the database: -whoever has both can read every connected account. To change it, put the old key in -`VAULT_OLD_KEYS` so what it sealed still opens. - -With `vault: cipherstash()`: - +The vault is [CipherStash](adapters.md#the-vault-is-cipherstash) (`vault: cipherstash()`). Create a workspace and an access key, then set: ```sh @@ -153,6 +147,9 @@ CS_CLIENT_KEY= CS_CLIENT_ACCESS_KEY= ``` +A production server does not start without them. On your own machine a stand-in seals +until they are set, which is enough to try connecting an account and protects nothing. + `APP_URL` (the public address of the app) and `APP_SECRET` (32+ characters; signs the OAuth `state`) must be set too. diff --git a/docs/quickstart.md b/docs/quickstart.md index 0ff3ce1..352f5dd 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -18,6 +18,10 @@ to look at. Records are in a Postgres inside the server, which keeps its data in `.data/pglite`. The development sign-in lets you straight in. A production build refuses to start with it. +This is a Spool with its interface. To start with the backend alone, for a front end of your +own, run `bun create @swirls/spools my-crm --headless` and read [Headless](headless.md). The +config, hooks and services on this page are the same in both. + ## Look around | File | What it holds | @@ -118,7 +122,8 @@ bun add @clerk/tanstack-react-start @effect/sql-pg ``` The server says at startup which services are on and what the others still need. Create the -tables with `bun run db:push`. +tables with `bun run db:push`. In production it also needs the vault's keys +([CipherStash](adapters.md#the-vault-is-cipherstash)), which seal every secret the CRM keeps. ## Next @@ -131,4 +136,5 @@ tables with `bun run db:push`. - Read about [signing in](auth.md), [databases](database.md), and [writing an adapter](adapters.md#write-your-own). - Add [workflows and the assistant](swirls.md). +- Call it from a front end or a script of your own through the [HTTP API](headless.md). - [Deploy it](deployment.md). diff --git a/docs/roles.md b/docs/roles.md index 7f15461..a5af747 100644 --- a/docs/roles.md +++ b/docs/roles.md @@ -105,6 +105,9 @@ role, use [`access`](#access). A required field is never left off a new-record f ## Access +What a role is denied holds for every way in: the interface, the [HTTP API](headless.md), an +API key made as someone with that role, the assistant and your own code. + ```json "roles": { "office": { "label": "Office" }, diff --git a/docs/security.md b/docs/security.md index f80c74c..81ce98b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -10,15 +10,16 @@ whose roles must each reach only some kinds of record gives them [role access](# These are the boundaries the code enforces: -| Who | Can do | Enforced by | -| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Anyone | See the sign-in page, unsubscribe with a valid signed link | The only public routes; the unsubscribe token is signed with `APP_SECRET` | -| Signed-in person **not** on the allowlist | Nothing in the CRM | The boundary checks a _verified_ email against `access` in `crm.config.json`. An auth adapter hands over an address only when its provider has verified it | -| CRM user | Read and write every record, run actions, use the assistant, unless [role access](#role-access) or [record scopes](#record-scopes) narrow it | Every CRM server function and API route goes through the boundary (`crmHandler`, `apiRoute`); lint refuses one that doesn't | -| Swirls (workflows, assistant tools) | Call `/api/swirls/tools/*` | Bearer `SWIRLS_APP_TOKEN` (32+ chars, constant-time compare). Fails closed when unset | -| An outside caller of your own door | Call the endpoints you build behind `publicRoute`. See [Your own door](#your-own-door) | Nothing of the framework's: your endpoint's own checks, in the order [Building your own door](extending.md#building-your-own-door) gives | -| A cron job | Run one pass of the mailbox sync, the sequences or the scheduled posts, or keep the server warm, through `/api/cron/*` | Bearer `CRON_SECRET` (16+ chars, constant-time compare). Fails closed when unset | -| The email provider | Report bounces and complaints to `/api/webhooks/email` | The email adapter checks the signature (Resend: Svix, with `RESEND_WEBHOOK_SECRET`). Refused when no secret is set | +| Who | Can do | Enforced by | +| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Anyone | See the sign-in page, unsubscribe with a valid signed link | The only public routes; the unsubscribe token is signed with `APP_SECRET` | +| Signed-in person **not** on the allowlist | Nothing in the CRM | The boundary checks a _verified_ email against `access` in `crm.config.json`. An auth adapter hands over an address only when its provider has verified it | +| CRM user | Read and write every record, run actions, use the assistant, unless [role access](#role-access) or [record scopes](#record-scopes) narrow it | Every CRM server function and API route goes through the boundary (`crmHandler`, `apiRoute`); lint refuses one that doesn't | +| A caller of the [HTTP API](#the-http-api) | What the teammate it is could do in the interface, and nothing more | The same boundary and the same operations. A session cookie from the API's own site, a sign-in token from a front end you named, or an API key the vault sealed | +| Swirls (workflows, assistant tools) | Call `/api/swirls/tools/*` | Bearer `SWIRLS_APP_TOKEN` (32+ chars, constant-time compare). Fails closed when unset | +| An outside caller of your own door | Call the endpoints you build behind `publicRoute`. See [Your own door](#your-own-door) | Nothing of the framework's: your endpoint's own checks, in the order [Building your own door](extending.md#building-your-own-door) gives | +| A cron job | Run one pass of the mailbox sync, the sequences or the scheduled posts, or keep the server warm, through `/api/cron/*` | Bearer `CRON_SECRET` (16+ chars, constant-time compare). Fails closed when unset | +| The email provider | Report bounces and complaints to `/api/webhooks/email` | The email adapter checks the signature (Resend: Svix, with `RESEND_WEBHOOK_SECRET`). Refused when no secret is set | Without `scopes` in `crm.config.json`, and without [role access](#role-access), every allowed user has the same access: they read and write every record. With scopes, see @@ -390,9 +391,41 @@ refusal for it. adapter of your own inherits the guard; run the integration tests on it (`TEST_STORE`) before relying on it. +## The HTTP API + +A [headless](headless.md) Spool, or any Spool that mounts `httpApi()`, answers the CRM's +operations over HTTP. It is the interface's own server functions by another route: each +operation is defined once, and the access list, [role access](#role-access), +[record scopes](#record-scopes) and record rules are checked in the same place for both. +There is no operation that runs as the system, and none that makes a key. + +| Caller says who they are with | Taken when | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| The session cookie | The request comes from the API's own site. A browser on another site is refused (`cross_site`) before anything runs, so another site's page can't act through a signed-in teammate | +| A sign-in token (bearer) | You named the front end it was issued to (`tokens.authorizedParties`). With none named, no token opens the API in production. A cookie sent beside a token counts for nothing | +| An API key (bearer, `spk_`) | The server was started with `keys: true`, the vault opens the key's seal for its own row, and the seal agrees with the row. It acts as one teammate, and that teammate's access is its | + +What to know about keys: + +- **The database holds no key.** A row keeps a seal the vault made for that row: the hash of + the secret, whose key it is, whether it only reads and when it ends. Reading the table + yields nothing that works, and a row someone writes, copies or edits by hand is refused, + because the seal is what a key is judged by. A Spool with no vault has no keys. +- **A key ends.** After 90 days unless it was made with another number or `--never-expires`. + Revoking wipes the seal, and takes effect on the next request. +- **A read-only key changes nothing.** It is refused every operation that writes, and a read + made with it does nothing on the side outside the database either. +- **Whoever can run `spools keys` can make one** as any teammate. That is someone with the + app's folder and its environment, who could already read the database. + +A browser on another site may call only from the `origins` you name (CORS), a body over +1 MB is refused, and a write with an `Idempotency-Key` runs once. Its kept answer is sealed +for its caller and their access at the time, so a repeat after their access changed gets the +status without the body. + ## Your own door -Spools has no door for people who are not teammates: an app builds its own behind `publicRoute` +The HTTP API above is for teammates. Spools has no door for people who are not teammates: an app builds its own behind `publicRoute` from small helpers ([Building your own door](extending.md#building-your-own-door)). The framework enforces nothing about who such a caller is or what they reach; each helper does one thing, and stands on its own: @@ -489,8 +522,9 @@ code passes) and that it was a system removal. are sealed by the vault in the app before they are stored; the database holds only ciphertext and there is no plaintext fallback. Each is sealed for the row it is stored on, and is refused anywhere else, so someone who can write to the database can't - move one teammate's tokens onto a connection of their own. The vault's keys (`CS_*`, or - `VAULT_KEY`) together with the database are access to those accounts. + move one teammate's tokens onto a connection of their own. The vault is CipherStash: its + credentials (`CS_*`) together with the database are access to those accounts, and a + production server does not start without them. The OAuth flow uses PKCE and a `state` signed with `APP_SECRET` that names the teammate and is tied to their browser by a cookie. A teammate removed from `access` keeps their stored tokens until they are deleted, but their mailboxes diff --git a/docs/server-code.md b/docs/server-code.md index b44b846..16cb8d6 100644 --- a/docs/server-code.md +++ b/docs/server-code.md @@ -46,6 +46,7 @@ folder (it is where the request and the environment are touched), `env.ts`, | `packages/spools/src/server/users.ts` | `Users`: who may use the CRM, the team, sign-in accounts | | `packages/spools/src/server/runtime/app.ts` | `appLayer()` (every service, from the Spool's adapters or a test's stand-ins), the one runtime per process, `runServer` for code on promises | | `packages/spools/src/server/runtime/boundary.ts` | `crmHandler`, `publicHandler`, `apiRoute`, `cronRoute`, `publicRoute`, `toolRoute`: where TanStack Start hands a request to a program | +| `packages/spools/src/server/operations/*.ts`, `http.ts`, `headless.ts` | Every operation, defined once; the HTTP API that answers them; a whole Spool with no web framework ([Headless](headless.md)) | | `packages/spools/src/server/runtime/request.ts` | `CurrentRequest`: the request's headers, abort signal and session, set by the boundary | | `packages/spools/src/server/runtime/email.ts` | `Email`: sending, and reading delivery webhooks, with `Email.layerTest(sender)` | | `packages/spools/src/server/sequences.ts` | `Sequences`: the campaigns the CRM runs, from the config, with `Sequences.layerTest` | @@ -109,16 +110,34 @@ export const markGuide = Effect.fn('guides.markGuide')(function* (userId: string ## A server function +What the CRM does for whoever asks is an **operation**, defined once in +`packages/spools/src/server/operations/.ts`: + +```ts +export const markGuide = staff('guides.mark', { + kind: 'write', + summary: 'Record that the signed-in person finished or dismissed a guide.', + input: guides.markInput, + run: ({ data, user }) => + guides.markGuide(user.id, data.id, data.outcome).pipe(Effect.as({ ok: true })), +}) +``` + +A server function only binds one to TanStack Start, and holds no program of its own: + ```ts export const markGuideFn = createServerFn({ method: 'POST' }) - .validator(guides.markInput) - .handler( - crmHandler('markGuide', ({ data, user }) => - guides.markGuide(user.id, data.id, data.outcome).pipe(Effect.as({ ok: true })), - ), - ) + .validator(guides.markGuide.input) + .handler(crmHandler(guides.markGuide.name, guides.markGuide.run)) ``` +Listed in `operations/index.ts`, the operation is also answered by the +[HTTP API](headless.md) at `POST /api/v1/guides.mark` and known to the typed client by that +name. So its name and the shape of its input and answer are a public contract: changing one +is a breaking change. `staff` operations are for signed-in teammates and `open` ones answer +anyone. An operation a front end is built on says what it answers (`answer`, schemas in +`operations/answers.ts`), which the OpenAPI document carries. + `crmHandler` checks the session and the access list, then runs the program with the validated `data` and the signed-in `user`. There is no other way for a program to learn who is asking, and nothing inside an Effect asks the auth diff --git a/docs/upgrading.md b/docs/upgrading.md index f7c5524..6bba66b 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -51,6 +51,53 @@ back up first and nothing to delete. - New pages and endpoints are new route files. The changelog gives them to you to copy; until you do, the feature is off. +## Headless, API keys and record types (0.13) + +This version adds a table, so it [changes the tables](#when-an-update-changes-the-tables): + +- **`api_keys`** holds the keys scripts and services call the HTTP API with + ([API keys](headless.md#api-keys)). Run `bun run crm:gen`, then `bun run db:push` or your + migration. It is empty until someone runs `spools keys create`, and never read unless + the HTTP API is given `keys: true`. + +Nothing else changes for an app that uses the interface. Three things to know: + +- `bun run crm:gen` now also writes `src/crm.types.ts`, the types of your records for a + front end of your own. Commit it with the other generated files, and add it to what your + formatter and linter leave alone. If CI checks that generated files are up to date, add + it there too. +- The spans of server functions are named after their operations (`records.get` where it + was `crm.getRecord`). A dashboard or alert that reads span names needs the new ones. +- `@swirls/spools/auth/clerk` is unchanged. A Spool with no interface imports Clerk's + adapter from `@swirls/spools/auth/clerk/backend` instead, which needs `@clerk/backend` + and `APP_URL` set to the address of your front end (or `authorizedParties`). + +**CipherStash is the vault, and production needs it.** `@swirls/spools/vault/aes` is gone, +with `VAULT_KEY` and `VAULT_OLD_KEYS`. Use `vault: cipherstash()` in `src/spool.server.ts` +and set `CS_WORKSPACE_CRN`, `CS_CLIENT_ID`, `CS_CLIENT_KEY` and `CS_CLIENT_ACCESS_KEY`: a +production server no longer starts without them. Nothing the AES vault sealed is opened by +CipherStash, so teammates connect their accounts again. On your own machine, with the +variables unset, a stand-in seals with a key that is in the framework's source: it lets you +work, protects nothing, and what it sealed is refused by a server with CipherStash +([Adapters](adapters.md#the-vault-is-cipherstash)). + +Three changes can sign people out or change an answer, on an app that uses the interface too: + +- **Clerk checks which front end a session was issued to.** On a production server, + `clerk()` now takes a session only when Clerk issued it to the origin of `APP_URL`. If + people use the CRM at another address than `APP_URL` (a second domain, `www`), name every + one: `clerk({ authorizedParties: ['https://crm.example.com', 'https://www.example.com'] })`. + A deployment whose `APP_URL` is still a localhost address is left as it was. +- **A sign-in link is spent only from your own site.** With Better Auth, + `/api/auth/magic-link/verify` opened from another site goes to `/sign-in` and signs nobody + in. The sign-in page's own button is unaffected. +- **A repeated write shows less once access changes.** An `Idempotency-Key` repeat by + someone whose scopes or role access changed since the first answer gets its status with + `Idempotent-Body: withheld`, as a Spool with no vault always answers. + +To serve the HTTP API from a Spool that has the interface as well, mount `httpApi()` at a +route of your own. To start one with no interface, see [Headless](headless.md). + ## Layouts (0.9) Nothing changes until `crm.config.json` has a `ui` key. To use [layouts](layouts.md): diff --git a/docs/when-to-use.md b/docs/when-to-use.md index fc69b47..d9b46ef 100644 --- a/docs/when-to-use.md +++ b/docs/when-to-use.md @@ -16,6 +16,10 @@ TypeScript. in your repository. - **You have already chosen your services.** You use a certain sign-in provider, mail provider, or cloud, and the CRM should use them too. +- **The front end is your own design.** A Spool runs [headless](headless.md): the records, + rules, roles and automations behind an HTTP API, with a typed client that knows your + fields. Use it for a portal, a mobile app or a tool on another framework, and keep the + interface Spools comes with for the back office or leave it out. - **You want agents working on records.** The assistant and your Swirls workflows go through the same checks, hooks, and timeline as your team. - **Some records are not for everyone.** A [role](roles.md#access) can be denied an object or @@ -41,8 +45,12 @@ TypeScript. - **You need a ready-made portal for customers.** Spools has no sign-in or pages for people who are not teammates. You can build endpoints for them from [small helpers](extending.md#building-your-own-door), and the checks are yours to write. + The [HTTP API](headless.md) is for teammates and the scripts that act as them: everyone + who calls it is on the access list. - **You need a stable API today.** Spools is in its 0.x releases, and minor versions may - include breaking changes. + include breaking changes. The names of the [HTTP API](headless.md)'s operations and the + shape of what they take and answer are treated as a public contract, and a change to one + is called out as breaking. ## What you need to run one @@ -51,10 +59,12 @@ TypeScript. | Runtime | [Bun](https://bun.sh) 1.4 or newer, in a container, on a VM, or on Vercel | | Database | Postgres 15 or newer (tested on 17) | | Sign-in | Clerk, or Better Auth in your own database | -| Optional | A mail provider, a place for files, a key for the vault, a Swirls project | +| Vault | A CipherStash workspace, in production | +| Optional | A mail provider, a place for files, a Swirls project | Spools is written with [TanStack Start](https://tanstack.com/start) and -[Effect](https://effect.website). You can configure a Spool and write hooks and pages without knowing either. You need Effect to write +[Effect](https://effect.website). A [headless](headless.md) Spool loads neither React nor +TanStack Start. You can configure a Spool and write hooks and pages without knowing either. You need Effect to write an adapter or to work on the framework. ## Compared with a template diff --git a/packages/create-spools/README.md b/packages/create-spools/README.md index b27cb1e..941aa9a 100644 --- a/packages/create-spools/README.md +++ b/packages/create-spools/README.md @@ -14,6 +14,7 @@ bun run dev | `--name ` | Your business, as the CRM shows it | | `--domain ` | Who may use the CRM: everyone with an address here | | `--email
` | Or one person | +| `--headless` | The backend alone, for a front end of your own | | `--yes` | Take the defaults instead of asking | | `--no-install` | Don't install packages or run the first-time setup | @@ -24,4 +25,8 @@ It is ready for [modules](https://spools.codes/docs/modules): `src/routes/__root made with an earlier version adds both by hand ([Upgrading](https://spools.codes/docs/upgrading#modules)). +With `--headless` the folder has no pages, no React and no TanStack Start: the config, the +services, your hooks and one `src/server.ts` that answers the HTTP API at `/api/v1`, with +`examples/client.ts` to show the typed client ([Headless](https://spools.codes/docs/headless)). + Licensed under [Apache-2.0](./LICENSE). diff --git a/packages/create-spools/overrides-headless/AGENTS.md b/packages/create-spools/overrides-headless/AGENTS.md new file mode 100644 index 0000000..7ba716c --- /dev/null +++ b/packages/create-spools/overrides-headless/AGENTS.md @@ -0,0 +1,51 @@ +# This CRM + +A headless Spool: the backend of a CRM built on `@swirls/spools`, with no interface of its +own. A front end of any design, on any framework, talks to it over HTTP. The framework is in +`node_modules`; what is in this repository is the business's own. + +- **The CRM is defined by `crm.config.json`.** Objects, fields, actions, automations, email + sequences. After editing it run `bun run crm:gen`, then `bun run db:push` if + `DATABASE_URL` is set (without it, restart the dev server). `views`, `ui` and `guides` in + the config describe the stock interface, which this Spool doesn't have. +- **Rules about records go in the config, not in a hook.** `unique` (with `where` for some + records only), `lock`, `parentLock` and `appendOnly` on an object, and `immutable`, + `readonly`, `audit` and `untrusted` on a field. The server keeps them for every writer. + Before adding a `unique` rule to an object that has records, run `bun run db:rules`. +- **What a role may reach goes in the config too**: `access: { deny, readOnly }` on a role, + `access.default` for someone with no role, `assistant.deny` for the assistant. The server + enforces it for every caller of the API, so a front end never decides who may see what. +- **Never hand-edit** `prisma/schema.*`, `crm.config.schema.json` or `src/crm.types.ts`: + they're generated. +- **The API is every operation by name**: `POST /api/v1/` with its input as JSON + (`records.list`, `records.create`, `tasks.create`, ...). `GET /api/v1` lists them with what + each takes, and `GET /api/v1/openapi.json` is the same as OpenAPI. A front end in + TypeScript uses the typed client: `createClient()` from `@swirls/spools/client`, with + `Crm` from `src/crm.types.ts` (see `examples/client.ts`). +- **Who is asking** is a teammate on the config's access list, known by the auth adapter's + session cookie (a front end on the same site), a sign-in token sent as a bearer token (a + front end elsewhere, once `tokens.authorizedParties` in `src/server.ts` names it), or an + API key (`bunx spools keys create --name ... --as `), for a script or a service, + taken once `src/server.ts` says `keys: true`. +- **Code goes in `src/app/extensions.ts`**: handlers (`"run": "local:"`), hooks, + run-target kinds, integration providers. It is plain TypeScript with promises, and imports + from `@swirls/spools/extensions`. Those writes run hooks, the timeline and automations. +- **Services are chosen in `src/spool.server.ts`**: auth, database, files, email, vault, + agents, rate limits. +- **An endpoint of your own** is added in `src/server.ts`, before the request is handed to + the Spool, behind a handler from `@swirls/spools/handlers` (`apiRoute`, `cronRoute`, + `publicRoute`), which checks who is asking before your code runs. +- **Reach for config first**, then a hook or handler, then an endpoint, then an adapter. + Never edit anything in `node_modules`, and never query the database directly. +- **Swirls never touches the database.** Workflows and the assistant in `swirls/` call the + tool API. Run `swirls doctor` after editing a `.swirls` file. + +```sh +bun run dev # the API on http://localhost:3000/api/v1 +bun run crm:gen # after editing crm.config.json +bun run db:rules # before adding a unique rule to an object that has records +bun run check # types, lint, config, tests. Run it before you are done +bun run start # production +``` + +Docs: https://spools.codes/docs/headless diff --git a/packages/create-spools/overrides-headless/CLAUDE.md b/packages/create-spools/overrides-headless/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/packages/create-spools/overrides-headless/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/packages/create-spools/overrides-headless/README.md b/packages/create-spools/overrides-headless/README.md new file mode 100644 index 0000000..d5c2be6 --- /dev/null +++ b/packages/create-spools/overrides-headless/README.md @@ -0,0 +1,42 @@ +# Your CRM's backend + +A headless [Spool](https://github.com/ByteSliceHQ/spools): records, access, the timeline, +automations, email sequences, files and the assistant, with no interface of its own. Build +the front end you want on top of its API. + +```sh +bun run db:seed # demo data, once +bun run dev # the API on http://localhost:3000/api/v1 +``` + +```sh +curl -X POST localhost:3000/api/v1/records.list -d '{"objectKey":"contacts"}' +curl localhost:3000/api/v1 # every operation, with what it takes +curl localhost:3000/api/v1/openapi.json # the same, as OpenAPI 3.1 +``` + +From TypeScript, `examples/client.ts` shows the typed client: it knows every operation and, +through the generated `src/crm.types.ts`, every field of your objects. + +Until you choose real services it keeps its records in a Postgres inside the server +(`.data/pglite`) and takes every request as you. A production server refuses to start that +way. + +| Change | Where | +| --------------------------------------------- | ----------------------------------------- | +| Objects, fields, actions, email sequences | `crm.config.json`, then `bun run crm:gen` | +| Record rules, and what each role may reach | `crm.config.json`, then `bun run crm:gen` | +| Which services it runs on, and which modules | `src/spool.server.ts` | +| Your own handlers and hooks | `src/app/extensions.ts` | +| Which front ends may call it, your own routes | `src/server.ts` | +| Keys for scripts and services | `bunx spools keys` | +| Workflows and the assistant | `swirls/` | + +When you're ready for real services, copy what you need from `.env.example` into `.env`: +`DATABASE_URL` for a Postgres (then `bun run db:push`), Clerk's keys for sign-in. The +[docs](https://spools.codes/docs/headless) cover the rest. + +```sh +bun run check # types, lint, config, tests +bun run start # production +``` diff --git a/packages/create-spools/overrides-headless/_gitignore b/packages/create-spools/overrides-headless/_gitignore new file mode 100644 index 0000000..9fd6284 --- /dev/null +++ b/packages/create-spools/overrides-headless/_gitignore @@ -0,0 +1,26 @@ +# dependencies +node_modules + +# output +dist +.output +.vercel +.tanstack +*.tsbuildinfo + +# secrets +.env +.env.* +!.env.example + +# the database and files of a copy run without any +.data + +# Supabase local +supabase/.temp +supabase/.branches + +# logs and caches +*.log +coverage +.DS_Store diff --git a/packages/create-spools/overrides-headless/_oxlintrc.json b/packages/create-spools/overrides-headless/_oxlintrc.json new file mode 100644 index 0000000..c2c2683 --- /dev/null +++ b/packages/create-spools/overrides-headless/_oxlintrc.json @@ -0,0 +1,30 @@ +{ + "jsPlugins": [ + { + "name": "spools", + "specifier": "@swirls/spools/oxlint" + } + ], + "categories": { + "correctness": "error" + }, + "ignorePatterns": ["dist/**", "migrations/**", "prisma/schema.d.ts", "src/crm.types.ts"], + "overrides": [ + { + "files": ["src/app/**"], + "rules": { + "no-restricted-imports": [ + "error", + { + "patterns": [ + { + "group": ["@swirls/spools/server/*"], + "message": "src/app reaches the framework through @swirls/spools/extensions, which returns promises. The modules themselves return Effects, and awaiting one does nothing." + } + ] + } + ] + } + } + ] +} diff --git a/packages/create-spools/overrides-headless/examples/client.ts b/packages/create-spools/overrides-headless/examples/client.ts new file mode 100644 index 0000000..3b62cfe --- /dev/null +++ b/packages/create-spools/overrides-headless/examples/client.ts @@ -0,0 +1,49 @@ +/** + * The typed client, as a front end or a script of yours would use it: + * + * bun run dev # in one terminal + * bun examples/client.ts # in another + * + * `Crm` is generated from crm.config.json (`bun run crm:gen`), so each object's + * fields are known here: rename a field in the config and this stops compiling. + */ +import { createClient, SpoolsError } from '@swirls/spools/client' + +import type { Crm } from '../src/crm.types' + +const crm = createClient({ + baseUrl: process.env['CRM_URL'] ?? 'http://localhost:3000/api/v1', + // From a script or a service: an API key (`bunx spools keys create --name ... --as `). + // From a front end on another site: the signed-in person's token. + token: () => process.env['CRM_API_KEY'] ?? null, +}) + +try { + const { user } = await crm.call('session.get') + console.log(user ? `Signed in as ${user.name || user.email}` : 'Nobody is signed in') + + const contacts = crm.records('contacts') + const { id } = await contacts.create({ name: 'Ada Lovelace', email: 'ada@example.com' }) + + await contacts.update(id, { status: 'qualified' }) + + const { record, activities } = await contacts.get(id) + console.log( + `${record?.name} is ${record?.status}, with ${activities.length} lines on the timeline`, + ) + + const { rows, total } = await contacts.list({ q: 'ada' }) + console.log( + `${total} contacts match "ada":`, + rows.map((row) => row.name), + ) + + await contacts.delete(id) +} catch (error) { + if (error instanceof SpoolsError) { + console.error(`${error.status} ${error.code}: ${error.message}`) + process.exit(1) + } + + throw error +} diff --git a/packages/create-spools/overrides-headless/src/server.ts b/packages/create-spools/overrides-headless/src/server.ts new file mode 100644 index 0000000..95bf5a0 --- /dev/null +++ b/packages/create-spools/overrides-headless/src/server.ts @@ -0,0 +1,62 @@ +/** + * The server: `bun run dev`, and `bun run start` in production. One handler + * answers everything a Spool answers except pages (the API at /api/v1, sign-in, + * files, the assistant, webhooks, cron), and starts its schedules. + */ +import './spool.server' +import { headlessServer } from '@swirls/spools/headless' +import { clientIp } from '@swirls/spools/server/client-ip' +import { disposeRuntime } from '@swirls/spools/server/runtime' + +const spools = headlessServer({ + // A front end on another site than this server sends each person's sign-in token as a + // bearer token. Name its origin in both, and the server takes its tokens and lets its + // pages call: + // tokens: { authorizedParties: ['https://app.example.com'] }, + // origins: ['https://app.example.com'], + // + // A script or another service calls with an API key (`bunx spools keys create`). Keys are + // taken only when this says so, and are kept sealed by the vault: + // keys: true, +}) + +const trustedHops = Math.max(0, Number.parseInt(process.env['TRUST_PROXY'] ?? '0', 10) || 0) + +const server = Bun.serve({ + port: Number(process.env['PORT'] ?? 3000), + hostname: + process.env['HOST'] ?? (process.env['NODE_ENV'] === 'production' ? '0.0.0.0' : 'localhost'), + fetch(request) { + // An endpoint of your own goes here, before the Spool is asked. + + // Proxies append to X-Forwarded-For, so everything left of the hops we trust is the + // caller's to make up: keep the one address TRUST_PROXY hops from the right. + const headers = new Headers(request.headers) + + const ip = clientIp( + request.headers.get('x-forwarded-for'), + server.requestIP(request)?.address, + trustedHops, + ) + + if (ip) { + headers.set('x-forwarded-for', ip) + } else { + headers.delete('x-forwarded-for') + } + + return spools.fetch(new Request(request, { headers })) + }, +}) + +console.log(`The API is on http://${server.hostname}:${server.port}/api/v1`) + +// Stop taking requests, then let go of the database. +for (const signal of ['SIGTERM', 'SIGINT'] as const) { + process.on(signal, () => { + void server + .stop() + .then(() => disposeRuntime()) + .finally(() => process.exit(0)) + }) +} diff --git a/packages/create-spools/overrides-headless/tsconfig.json b/packages/create-spools/overrides-headless/tsconfig.json new file mode 100644 index 0000000..1813bdf --- /dev/null +++ b/packages/create-spools/overrides-headless/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "lib": ["ESNext", "DOM"], + "target": "ESNext", + "module": "Preserve", + "moduleResolution": "bundler", + "moduleDetection": "force", + "types": ["bun"], + "resolveJsonModule": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": false, + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true + }, + "include": ["src", "scripts", "tests", "examples", "prisma", "*.ts"] +} diff --git a/packages/create-spools/overrides/AGENTS.md b/packages/create-spools/overrides/AGENTS.md index bbe2b04..cbc4810 100644 --- a/packages/create-spools/overrides/AGENTS.md +++ b/packages/create-spools/overrides/AGENTS.md @@ -15,7 +15,7 @@ this repository is the business's own. `access.default` for someone with no role, `assistant.deny` for the assistant. The server enforces it, and your hooks and handlers run with the access of the teammate they run for. A hook that must write an object that person is kept from wraps the write in `asSystem`. -- **Never hand-edit** `prisma/schema.*`, `crm.config.schema.json` or +- **Never hand-edit** `prisma/schema.*`, `crm.config.schema.json`, `src/crm.types.ts` or `src/routeTree.gen.ts`: they're generated. - **Code goes in `src/app/extensions.ts`**: handlers (`"run": "local:"`), hooks, run-target kinds, integration providers. It is plain TypeScript with promises, and diff --git a/packages/create-spools/overrides/_oxlintrc.json b/packages/create-spools/overrides/_oxlintrc.json index d270fcf..bcf2c25 100644 --- a/packages/create-spools/overrides/_oxlintrc.json +++ b/packages/create-spools/overrides/_oxlintrc.json @@ -14,6 +14,7 @@ ".vercel/**", "migrations/**", "prisma/schema.d.ts", + "src/crm.types.ts", "src/routeTree.gen.ts" ], "rules": { diff --git a/packages/create-spools/package.json b/packages/create-spools/package.json index 0da257e..99bd4c2 100644 --- a/packages/create-spools/package.json +++ b/packages/create-spools/package.json @@ -18,6 +18,7 @@ "files": [ "src", "template", + "template-headless", "LICENSE" ], "type": "module", @@ -27,7 +28,7 @@ "scripts": { "template": "bun scripts/template.ts", "prepack": "bun scripts/template.ts", - "postpack": "rm -rf template", + "postpack": "rm -rf template template-headless", "check-types": "tsc --noEmit", "test": "bun test tests" }, diff --git a/packages/create-spools/scripts/template.ts b/packages/create-spools/scripts/template.ts index 54fb0bd..a735509 100644 --- a/packages/create-spools/scripts/template.ts +++ b/packages/create-spools/scripts/template.ts @@ -31,6 +31,44 @@ const FILES = [ 'vite.config.ts', ] +/** + * A headless Spool: the same backend with no interface (`--headless`). It has + * none of the starter's pages, and a server of its own (overrides-headless). + */ +const HEADLESS_FILES = [ + '.env.example', + 'crm.config.json', + 'crm.config.schema.json', + 'prisma.config.ts', + 'prisma', + 'scripts/seed.ts', + 'src/app', + 'src/crm.types.ts', + 'src/spool.server.ts', + 'supabase/config.toml', + 'swirls', + 'tests', +] + +/** What only an interface needs: a headless Spool installs none of it. */ +const INTERFACE_PACKAGES = new Set([ + '@clerk/tanstack-react-start', + '@tanstack/react-router', + '@tanstack/react-start', + 'react', + 'react-dom', + '@tailwindcss/vite', + '@types/react', + '@types/react-dom', + '@vitejs/plugin-react', + 'nitro', + 'tailwindcss', + 'vite', +]) + +/** Scripts that build or serve the interface. */ +const INTERFACE_SCRIPTS = new Set(['dev', 'build', 'start']) + /** Scripts that are about developing the framework. */ const NOT_SCRIPTS = new Set(['dev:e2e', 'demo']) @@ -86,4 +124,86 @@ await Bun.write( )}\n`, ) -console.log(`✓ template (@swirls/spools ^${version})`) +// ── The headless template ─────────────────────────────────────────────────── + +const headless = join(here, 'template-headless') + +await rm(headless, { recursive: true, force: true }) + +for (const file of HEADLESS_FILES) { + if (!existsSync(join(starter, file))) { + throw new Error(`The headless template needs ${file}, which isn't in apps/starter.`) + } + + await mkdir(dirname(join(headless, file)), { recursive: true }) + await cp(join(starter, file), join(headless, file), { recursive: true }) +} + +await cp(join(here, 'overrides-headless'), headless, { recursive: true }) + +for (const file of HEADLESS_FILES.filter((f) => f.startsWith('.'))) { + await rename(join(headless, file), join(headless, `_${file.slice(1)}`)) +} + +// The starter signs people in with Clerk through TanStack Start. A headless Spool reads +// Clerk's session from the request itself. +const spoolFile = join(headless, 'src/spool.server.ts') +const spoolText = await Bun.file(spoolFile).text() +const START_CLERK = "from '@swirls/spools/auth/clerk'" + +if (!spoolText.includes(START_CLERK)) { + throw new Error( + "apps/starter/src/spool.server.ts no longer imports Clerk's adapter as the headless template expects.", + ) +} + +await Bun.write( + spoolFile, + spoolText + .replace(START_CLERK, "from '@swirls/spools/auth/clerk/backend'") + .replace(' (and in spool.ui.ts when it has a browser\n * half)', '') + .replace(', with their browser halves in spool.ui.ts', ''), +) + +const without = (packages: Record) => + Object.fromEntries(Object.entries(packages).filter(([name]) => !INTERFACE_PACKAGES.has(name))) + +const clerkBackend = (await Bun.file(join(here, '../spools/package.json')).json()).peerDependencies[ + '@clerk/backend' +] + +await Bun.write( + join(headless, 'package.json'), + `${JSON.stringify( + { + name: 'my-crm', + version: '0.0.0', + private: true, + type: 'module', + engines: manifest.engines, + scripts: { + dev: 'bun --watch src/server.ts', + start: 'NODE_ENV=production bun src/server.ts', + ...Object.fromEntries( + Object.entries(scripts).filter(([name]) => !INTERFACE_SCRIPTS.has(name)), + ), + lint: 'bunx --bun oxlint --deny-warnings', + check: 'bun run check-types && bun run lint && bun run crm:gen --no-emit && bun run test', + }, + dependencies: { + ...without(manifest.dependencies), + '@clerk/backend': clerkBackend, + '@swirls/spools': `^${version}`, + }, + devDependencies: { + ...without(manifest.devDependencies), + '@oxlint/plugins': root.devDependencies['@oxlint/plugins'], + oxlint: root.devDependencies.oxlint, + }, + }, + null, + 2, + )}\n`, +) + +console.log(`✓ template, template-headless (@swirls/spools ^${version})`) diff --git a/packages/create-spools/src/main.ts b/packages/create-spools/src/main.ts index 384b07a..d9b305e 100755 --- a/packages/create-spools/src/main.ts +++ b/packages/create-spools/src/main.ts @@ -4,6 +4,7 @@ * * bun create @swirls/spools my-crm * bun create @swirls/spools my-crm --name "Acme" --domain acme.com --yes + * bun create @swirls/spools my-crm --headless the backend alone, for a front end of your own * * Nothing it makes needs an account: the new CRM keeps its records in a Postgres * inside the server and signs you straight in until you choose real services. @@ -23,6 +24,7 @@ const { values: args, positionals } = parseArgs({ domain: { type: 'string' }, email: { type: 'string' }, yes: { type: 'boolean', short: 'y' }, + headless: { type: 'boolean' }, 'no-install': { type: 'boolean' }, help: { type: 'boolean', short: 'h' }, }, @@ -34,6 +36,7 @@ if (args.help || positionals.length > 1) { --name your business, as the CRM shows it --domain who may use the CRM: everyone with an address here --email
or one person + --headless the backend alone: an API for a front end of your own, and no pages --yes take the defaults instead of asking --no-install don't install packages (or run the first-time setup)`) @@ -56,7 +59,7 @@ if (existsSync(target) && readdirSync(target).length > 0) { process.exit(1) } -const template = join(import.meta.dir, '../template') +const template = join(import.meta.dir, args.headless ? '../template-headless' : '../template') if (!existsSync(template)) { console.error( @@ -112,7 +115,9 @@ if (args['no-install']) { steps.push( 'bun run db:seed # demo companies, contacts and deals', - 'bun run dev # http://localhost:3000', + args.headless + ? 'bun run dev # the API on http://localhost:3000/api/v1' + : 'bun run dev # http://localhost:3000', ) console.log(`\n${steps.map((s) => ` ${s}`).join('\n')}\n`) diff --git a/packages/create-spools/tests/main.test.ts b/packages/create-spools/tests/main.test.ts index 67db1b8..4df4b94 100644 --- a/packages/create-spools/tests/main.test.ts +++ b/packages/create-spools/tests/main.test.ts @@ -73,6 +73,7 @@ afterAll(async () => { if (!templateWasThere) { await rm(TEMPLATE, { recursive: true, force: true }) + await rm(`${TEMPLATE}-headless`, { recursive: true, force: true }) } }) @@ -105,6 +106,44 @@ describe('create-spools', () => { expect(result.stdout).toContain('bun run init') }) + test('--headless makes the backend alone: a server of its own, no pages and nothing an interface needs', async () => { + const cwd = await place() + const result = await create(cwd, ['api', '--headless', '--no-install', '--yes']) + expect(result.stderr).toBe('') + expect(result.exitCode).toBe(0) + + const target = join(cwd, 'api') + expect(existsSync(join(target, 'src/server.ts'))).toBe(true) + expect(existsSync(join(target, 'src/crm.types.ts'))).toBe(true) + expect(existsSync(join(target, 'examples/client.ts'))).toBe(true) + + for (const gone of [ + 'src/routes', + 'src/router.tsx', + 'src/spool.ui.ts', + 'src/start.ts', + 'vite.config.ts', + ]) { + expect(existsSync(join(target, gone))).toBe(false) + } + + const manifest = await readFile(join(target, 'package.json'), 'utf8') + + expect(manifest).not.toMatch( + /"(react|react-dom|vite|@tanstack\/[^"]+|@clerk\/tanstack-react-start)":/, + ) + + expect(manifest).toContain('"dev": "bun --watch src/server.ts"') + + // Clerk is the one that reads its session from the request itself, and nothing names a browser half. + const spool = await readFile(join(target, 'src/spool.server.ts'), 'utf8') + expect(spool).toContain("from '@swirls/spools/auth/clerk/backend'") + expect(spool).not.toContain('spool.ui') + + expect(await readFile(join(target, 'src/server.ts'), 'utf8')).toContain('headlessServer(') + expect(result.stdout).toContain('http://localhost:3000/api/v1') + }) + test('with --yes and no folder it makes my-crm, and an empty folder that is already there is used', async () => { const cwd = await place() const result = await create(cwd, ['--no-install', '--yes']) diff --git a/packages/spools/package.json b/packages/spools/package.json index 9b0d235..df0bd09 100644 --- a/packages/spools/package.json +++ b/packages/spools/package.json @@ -29,6 +29,7 @@ "type": "module", "sideEffects": [ "./src/crm/ui/theme.css", + "./src/start.ts", "./src/cli/*.ts" ], "exports": { @@ -40,7 +41,11 @@ "./server": "./src/server/entry.ts", "./server/runtime": "./src/server/runtime/index.ts", "./server/*": "./src/server/*.ts", - "./start": "./src/server/middleware.ts", + "./start": "./src/start.ts", + "./headless": "./src/headless.ts", + "./http": "./src/server/http.ts", + "./client": "./src/client.ts", + "./operations": "./src/server/operations/index.ts", "./vite": "./src/vite.ts", "./guides": "./src/crm/guides.ts", "./testing": "./src/testing/index.ts", @@ -52,6 +57,7 @@ "./ui/brand": "./src/crm/ui/brand.ts", "./ui/*": "./src/crm/ui/*.tsx", "./theme.css": "./src/crm/ui/theme.css", + "./auth/clerk/backend": "./src/adapters/auth/clerk/backend.ts", "./auth/*/ui": "./src/adapters/auth/*/client.tsx", "./auth/*": "./src/adapters/auth/*/server.ts", "./database/*": "./src/adapters/database/*/server.ts", @@ -87,6 +93,7 @@ }, "peerDependencies": { "@cipherstash/stack": "1.2.1", + "@clerk/backend": "^3.27.0", "@clerk/tanstack-react-start": "^1.7.11", "@effect/sql-pg": "^4.1.5", "@effect/sql-pglite": "^4.1.5", @@ -104,9 +111,24 @@ "vite": "^8.0.0" }, "peerDependenciesMeta": { + "@tanstack/react-router": { + "optional": true + }, + "@tanstack/react-start": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, "@cipherstash/stack": { "optional": true }, + "@clerk/backend": { + "optional": true + }, "@clerk/tanstack-react-start": { "optional": true }, diff --git a/packages/spools/scripts/assemble.ts b/packages/spools/scripts/assemble.ts index 142157d..52346a2 100644 --- a/packages/spools/scripts/assemble.ts +++ b/packages/spools/scripts/assemble.ts @@ -99,7 +99,7 @@ await writeFile( `${JSON.stringify( { ...kept, - sideEffects: ['./crm/ui/theme.css', './cli/*.js'], + sideEffects: ['./crm/ui/theme.css', './start.js', './cli/*.js'], bin: { spools: './cli/main.js' }, publishConfig, exports: Object.fromEntries( diff --git a/packages/spools/src/adapters/auth/better-auth/server.ts b/packages/spools/src/adapters/auth/better-auth/server.ts index d8af5b3..3b5826b 100644 --- a/packages/spools/src/adapters/auth/better-auth/server.ts +++ b/packages/spools/src/adapters/auth/better-auth/server.ts @@ -1,5 +1,6 @@ import { APIError } from 'better-auth/api' import { betterAuth as createAuth } from 'better-auth/minimal' +import { bearer } from 'better-auth/plugins/bearer' import { magicLink } from 'better-auth/plugins/magic-link' import { Effect, Layer, Option, Schema } from 'effect' @@ -13,6 +14,7 @@ import { type Timeout, } from '../../../server/runtime/errors' import { policies, withPolicy } from '../../../server/runtime/policies' +import { Tokens } from '../../../server/runtime/tokens' import { asc, desc, oneOf } from '../../../server/store/query' import { Store } from '../../../server/store/store' import { isAllowed } from '../../../server/users' @@ -42,6 +44,17 @@ export type BetterAuthAdapterOptions = { * takes the same time, so it doesn't tell whether a link was sent. Default 800. */ answerAfter?: number + /** + * Lets a session be carried as `Authorization: Bearer ` in place of + * the cookie, for a front end that can't keep one: a phone app, a desktop + * app. Off unless this says. With it, the answer that signs someone in also + * carries their session's token in a `set-auth-token` header, which the app + * keeps and sends. The token is the session: signing out ends it, it lasts + * as long as the session does, and whoever holds it is that person. Leave it + * off for a front end that is pages in a browser, where a script on the page + * has no need of the token and the cookie is kept from it. + */ + bearer?: boolean } /** @@ -65,7 +78,7 @@ export function admit(user: { email: string; emailVerified: boolean }): void { } } -const build = (current: Settings, answerAfter: number) => +const build = (current: Settings, answerAfter: number, tokens: boolean) => createAuth({ secret: current.secret, baseURL: current.origin, @@ -84,6 +97,8 @@ const build = (current: Settings, answerAfter: number) => await new Promise((resolve) => setTimeout(resolve, answerAfter)) }, }), + // Only a token this server signed is looked up: a made-up one costs a hash and no read. + ...(tokens ? [bearer({ requireSignature: true })] : []), ], socialProviders: socialProviders(current), session: { @@ -347,8 +362,20 @@ const ANSWERED = new Set([ 'POST /sign-out', ]) +/** A session token as Better Auth signs one: the token, a dot, its signature. */ +const SIGNED = /^[^.\s]{16,256}\.[^.\s]{16,256}$/ + +const withoutAuthorization = (headers: Headers) => { + const kept = new Headers(headers) + kept.delete('authorization') + return kept +} + /** Sign-in with Better Auth, kept in the Spool's own database. */ -export function betterAuth({ answerAfter = 800 }: BetterAuthAdapterOptions = {}): AuthAdapter { +export function betterAuth({ + answerAfter = 800, + bearer: tokens = false, +}: BetterAuthAdapterOptions = {}): AuthAdapter { let built: { key: string; auth: Instance } | undefined // Made on first use, and again if the settings change: a build reads no variables, and a value fixed @@ -358,13 +385,13 @@ export function betterAuth({ answerAfter = 800 }: BetterAuthAdapterOptions = {}) const key = JSON.stringify(current) if (built?.key !== key) { - built = { key, auth: build(current, answerAfter) } + built = { key, auth: build(current, answerAfter, tokens) } } return built.auth } - return { + const adapter: AuthAdapter = { id: 'better-auth', label: 'Better Auth', tables: authTables, @@ -373,7 +400,8 @@ export function betterAuth({ answerAfter = 800 }: BetterAuthAdapterOptions = {}) layer: directory(instance), session: async (request) => { const found = await instance().api.getSession({ - headers: request.headers, + // Without `bearer`, a session is its cookie and an `Authorization` header says nothing. + headers: tokens ? request.headers : withoutAuthorization(request.headers), query: { disableRefresh: true }, }) @@ -393,7 +421,54 @@ export function betterAuth({ answerAfter = 800 }: BetterAuthAdapterOptions = {}) return new Response('Not found', { status: 404 }) } + // A link is spent by the sign-in page's own button, on this site. Opened from another site + // it would sign whoever follows it in as the person the link was sent to, and what they + // then did (connecting a mailbox) would be that person's. A caller that is no browser page + // (an app) says nothing of where it is, and is let through. + const from = request.headers.get('sec-fetch-site') + + if (path === '/magic-link/verify' && from !== null && from !== 'same-origin') { + return Response.redirect(`${settings().origin}${SIGN_IN}`, 302) + } + return instance().fetch(request) }, } + + if (!tokens) { + return adapter + } + + // A session's own token, sent as a bearer token. This server issued it, to someone it signed + // in itself, so there is no other front end's token to tell apart: the origins a caller names + // are not read. Its signature is checked before anything is read, so a stranger's guess costs + // no query. + const verify = (token: string) => + Effect.tryPromise({ + try: () => + instance().api.getSession({ + headers: new Headers({ authorization: `Bearer ${token}` }), + query: { disableRefresh: true }, + }), + catch: (cause) => new AuthError({ message: messageOf(cause), kind: 'unavailable' }), + }).pipe( + Effect.map((found) => found?.user.id ?? null), + Effect.catch((error) => + Effect.as( + Effect.logWarning(`[auth] A session token could not be checked: ${error.message}`), + null, + ), + ), + ) + + return { + ...adapter, + tokens: Layer.succeed( + Tokens, + Tokens.of({ + own: true, + verify: (token) => (SIGNED.test(token) ? verify(token) : Effect.succeed(null)), + }), + ), + } } diff --git a/packages/spools/src/adapters/auth/clerk/backend.ts b/packages/spools/src/adapters/auth/clerk/backend.ts new file mode 100644 index 0000000..3f117c7 --- /dev/null +++ b/packages/spools/src/adapters/auth/clerk/backend.ts @@ -0,0 +1,123 @@ +import { createClerkClient } from '@clerk/backend' + +import type { AuthAdapter } from '../../../server/runtime/auth' +import { type ClerkOptions, clerkIn, frontEnds, signingKeysOf } from './core' +import { kidOf } from './keyring' + +export * from './core' + +/** + * Sign-in with Clerk in a Spool with no web framework (a headless one): the + * session is read from the request itself with Clerk's backend SDK, so nothing + * of TanStack Start is loaded. The front end, whatever it is built with, signs + * people in with Clerk's own kit for it and keeps the session cookie fresh. + * + * CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY from the Clerk dashboard (API keys) + * CLERK_JWT_KEY optional: the instance's public key, so its + * keys are never fetched + * APP_URL the site people use the CRM on: only session + * tokens issued to it count (or `authorizedParties`) + * + * A session Clerk would renew by sending the browser away and back (its + * handshake) counts as nobody here: an API can't redirect, and the front end's + * Clerk kit renews the cookie before that is needed. + */ +const client = () => + createClerkClient({ + secretKey: process.env['CLERK_SECRET_KEY'], + publishableKey: process.env['CLERK_PUBLISHABLE_KEY'], + jwtKey: process.env['CLERK_JWT_KEY'], + apiUrl: process.env['CLERK_API_URL'], + telemetry: { disabled: process.env['CLERK_TELEMETRY_DISABLED'] === '1' }, + }) + +const nobody = { userId: null, getToken: () => Promise.resolve(null) } + +/** What the adapter takes: Clerk's own options. A production server that names no front end takes no session. */ +export type ClerkBackendOptions = ClerkOptions + +const SESSION = /^__session(?:_|$)/ +/** What Clerk's handshake rides on. An API never completes one, and each would be a call to Clerk. */ +const HANDSHAKE = /^__clerk_handshake/ + +/** + * The request as Clerk's SDK is to see it: its cookies and nothing that would + * make the SDK call Clerk. No `Authorization` header, because a bearer token is + * for the token check (`tokens`), which asks which front end it was issued to. + * No handshake, in the address or the cookies. `tokens` are the session tokens + * it carries. + */ +const cookiesOnly = (request: Request) => { + const url = new URL(request.url) + const headers = new Headers(request.headers) + + for (const name of [...url.searchParams.keys()].filter((key) => HANDSHAKE.test(key))) { + url.searchParams.delete(name) + } + + const cookies = (request.headers.get('cookie') ?? '') + .split(';') + .map((cookie) => cookie.trim()) + .filter((cookie) => cookie !== '' && !HANDSHAKE.test(cookie)) + + headers.delete('authorization') + headers.set('cookie', cookies.join('; ')) + + const tokens = cookies + .filter((cookie) => SESSION.test(cookie.split('=', 1)[0] ?? '')) + .map((cookie) => cookie.slice(cookie.indexOf('=') + 1)) + + return { asked: new Request(url, { method: request.method, headers }), tokens } +} + +/** Sign-in with Clerk, read from each request by Clerk's backend SDK. */ +export const clerk = (options: ClerkBackendOptions = {}): AuthAdapter => { + const signingKeys = signingKeysOf(client) + + return clerkIn( + { + client, + signingKeys, + session: async (request) => { + const { asked, tokens } = cookiesOnly(request) + const [token] = tokens + + // No session cookie is nobody, without asking anything. + if (token === undefined) { + return nobody + } + + const parties = frontEnds(options) + + if (parties.length === 0 && process.env['NODE_ENV'] === 'production') { + return nobody + } + + // Checked offline, against the instance's public key or the one key the token names, which + // the keyring fetches at most once a minute whatever is sent. A key the instance doesn't + // have is nobody: a made-up cookie never makes this server call Clerk. + const set = process.env['CLERK_JWT_KEY'] + const kid = set ? null : kidOf(token) + const jwtKey = set ?? (kid === null ? null : await signingKeys.keyFor(kid)) + + if (!jwtKey) { + return nobody + } + + const state = await client().authenticateRequest(asked, { + acceptsToken: 'session_token', + jwtKey, + authorizedParties: parties.length > 0 ? parties : undefined, + }) + + if (!state.isAuthenticated) { + return nobody + } + + const { userId, orgId, getToken } = state.toAuth() + return { userId, orgId, getToken: (template) => getToken(template) } + }, + }, + options, + ) +} diff --git a/packages/spools/src/adapters/auth/clerk/core.ts b/packages/spools/src/adapters/auth/clerk/core.ts new file mode 100644 index 0000000..96007c8 --- /dev/null +++ b/packages/spools/src/adapters/auth/clerk/core.ts @@ -0,0 +1,652 @@ +import { createPublicKey } from 'node:crypto' + +import type { ClerkClient } from '@clerk/backend' +import { Effect, Layer, Option, Schema } from 'effect' +import { z } from 'zod' + +import { isProvider, PROVIDERS, splitScopes } from '../../../crm/mailbox' +import type { ScopeGrant, ScopeInfo } from '../../../crm/scopes' +import { Roles } from '../../../server/roles' +import type { Env } from '../../../server/runtime/adapter' +import { + Auth, + type AuthAdapter, + type AuthUser, + type HostMiddleware, +} from '../../../server/runtime/auth' +import { AuthError, messageOf } from '../../../server/runtime/errors' +import { policies, withPolicy } from '../../../server/runtime/policies' +import { Tokens } from '../../../server/runtime/tokens' +import { Scopes } from '../../../server/scopes' +import { spool } from '../../../server/spool' +import { keyring, kidOf } from './keyring' + +/** + * Sign-in with Clerk (https://clerk.com). The only server code that uses the + * Clerk SDK; the browser half is client.tsx. + * + * CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY from the Clerk dashboard (API keys) + * + * Clerk keeps the Google and Microsoft tokens of the accounts people sign in + * with, so the CRM stores none of its own for them (docs/mailbox.md). + */ + +/** The parts of a Clerk user the CRM reads. */ +export type ClerkUser = { + id: string + firstName: string | null + lastName: string | null + primaryEmailAddressId: string | null + emailAddresses: { id: string; emailAddress: string; verification: { status: string } | null }[] + externalAccounts?: + | { provider: string; emailAddress: string; approvedScopes?: string | null }[] + | null + /** Banned or locked at Clerk: their sessions are ended there, and nothing else of theirs counts here. */ + banned?: boolean + locked?: boolean +} + +/** + * Whether an address is one of Clerk's test addresses (`ada+clerk_test@acme.com`). + * With test mode on, which it is in every development instance, Clerk marks one + * verified for anybody who types the code 424242, and sends no email + * (https://clerk.com/docs/testing/test-emails-and-phones). So it proves nothing + * about who holds the address. + */ +export const isTestAddress = (email: string) => + email.slice(0, email.lastIndexOf('@')).toLowerCase().includes('+clerk_test') + +/** + * A Clerk user as the CRM reads people. Pure, so it can be tested without Clerk. + * `testAddresses` says whether one of Clerk's test addresses counts as verified: + * only on a developer's own machine. + */ +export function toAuthUser(u: ClerkUser, testAddresses = false): AuthUser { + // Only trust verified addresses: an unverified primary email would let anyone claim an allowed domain. + const primary = u.emailAddresses.find((e) => e.id === u.primaryEmailAddressId) + + // Someone banned or locked at Clerk is nobody here either: no address, so not on the access list. + // Clerk ends their sessions itself. This is what stops an API key made for them. + const verified = + primary?.verification?.status === 'verified' && + (testAddresses || !isTestAddress(primary.emailAddress)) && + !u.banned && + !u.locked + + return { + id: u.id, + name: [u.firstName, u.lastName].filter(Boolean).join(' ') || null, + email: primary && verified ? primary.emailAddress : null, + accounts: (u.externalAccounts ?? []).map((a) => ({ + // Clerk names a sign-in method "oauth_google"; its token API calls it "google". + provider: a.provider.replace(/^oauth_/, ''), + email: a.emailAddress, + scopes: splitScopes(a.approvedScopes), + })), + } +} + +/** The HTTP status of an error Clerk answered with; anything else (a network failure) has none. */ +const ClerkStatus = Schema.Struct({ status: Schema.Finite }) + +/** The codes of an error Clerk answered with, first one first. */ +const ClerkCodes = Schema.Struct({ + errors: Schema.Array(Schema.Struct({ code: Schema.optional(Schema.String) })), +}) + +const statusOf = (cause: unknown) => + Option.getOrUndefined(Schema.decodeUnknownOption(ClerkStatus)(cause))?.status + +/** A 4xx (other than 429) is Clerk's answer, not a hiccup: asking again won't change it. */ +const transient = (cause: unknown) => { + const status = statusOf(cause) + return status === undefined || status === 429 || status >= 500 +} + +const asAuthError = (cause: unknown) => + new AuthError({ message: messageOf(cause), kind: transient(cause) ? 'unavailable' : 'answer' }) + +/** What Clerk says when it can't hand out a token, in words a teammate can act on. */ +export function tokenRefusal(provider: string, cause: unknown): AuthError { + const code = + Option.getOrUndefined(Schema.decodeUnknownOption(ClerkCodes)(cause))?.errors[0]?.code ?? '' + + const label = Object.entries(PROVIDERS).find(([id]) => id === provider)?.[1].label ?? provider + + if (code.startsWith('oauth_shared_credentials')) { + return new AuthError({ + message: `Clerk is using its shared development credentials for ${label}, which can't give the CRM mailbox access. Set up custom credentials for ${label} in Clerk.`, + kind: 'setup', + }) + } + + return new AuthError({ + message: `Clerk could not provide a ${label} token${code ? ` (${code})` : ''}. Reconnect the account from your profile.`, + // A moment's trouble at Clerk is tried again (below); a refusal is this account's. + kind: transient(cause) ? 'unavailable' : 'account', + }) +} + +const call = ( + name: string, + request: () => Promise, + refusal: (cause: unknown) => AuthError = asAuthError, +) => + Effect.tryPromise({ try: request, catch: refusal }).pipe( + withPolicy( + { ...policies.authUsers, service: 'Clerk' }, + (error) => error.kind === 'unavailable', + ), + Effect.withSpan(name), + ) + +const directory = (clerkClient: Client) => + Layer.sync(Auth, () => { + // A build is always "production", so a deployment never trusts a test address, whichever keys it has. + const testAddresses = process.env['NODE_ENV'] !== 'production' + const read = (user: ClerkUser) => toAuthUser(user, testAddresses) + + return Auth.of({ + getUser: (id) => + Effect.map( + call('Clerk.getUser', () => clerkClient().users.getUser(id)), + read, + ), + listUsers: call('Clerk.listUsers', async () => { + const { data } = await clerkClient().users.getUserList({ + limit: 200, + orderBy: '+created_at', + }) + + return data.map(read) + }), + accountToken: (userId, provider) => + // The CRM only reads mail from the providers it knows, and those are all Clerk's names too. + isProvider(provider) + ? call( + 'Clerk.accountToken', + async () => { + const { data } = await clerkClient().users.getUserOauthAccessToken(userId, provider) + return data[0]?.token || null + }, + (cause) => tokenRefusal(provider, cause), + ) + : Effect.fail( + new AuthError({ + message: `The CRM reads no mail from ${provider} accounts.`, + kind: 'account', + }), + ), + }) + }) + +const key = (prefix: string) => (value: string) => { + // The template's placeholder passes a prefix check, but Clerk rejects it on every request with a long stack trace. + if (value.endsWith('...')) { + return 'still has the placeholder value from .env.example' + } + + return value.startsWith(prefix) ? null : `must start with "${prefix}"` +} + +/** + * What to say when a deployment runs on a Clerk development instance. It works, + * and a staging copy may want it, but such an instance is for testing: its + * sign-in pages say so, and its test mode is on. + */ +export const developmentInstance = (env: Env): string | null => + env['NODE_ENV'] === 'production' && env['CLERK_SECRET_KEY']?.startsWith('sk_test_') + ? "on a Clerk development instance (CLERK_SECRET_KEY starts with sk_test_). Use the production instance's keys where real people sign in" + : null + +/** The parts of a Clerk organization membership that record scopes read. */ +export type ClerkMembership = { + role: string + organization: { id: string; slug?: string | null; name: string } +} + +/** + * The scope a Clerk organization is: its id (`org_...`), which is what a + * record's scope field holds. Never its slug: whoever administers an + * organization can rename its slug, to one another scope's records carry, and + * an id is Clerk's own and is never given out twice. + */ +export const organizationScope = (organization: ClerkMembership['organization']): string => + organization.id + +/** + * A person's organization memberships as record scopes. The scope is the + * organization's id and the role is the membership's, without Clerk's `org:` + * prefix: `org:admin` is the role `admin` in `scopes.roles`. Pure, so it can be + * tested without Clerk. + * + * `everyScope` is the roles that reach every scope (`all` in `scopes.roles`), + * and the organizations, by id, a membership must be in for one of them to + * count (`everyScopeFrom`). A person can be made anything in an organization + * they created themselves, and Clerk's own `org:admin` is held by whoever runs + * any organization, so such a role held anywhere else gives nothing: not every + * scope, and not that organization's either. With no organization named, no + * membership gives a role that reaches every scope. + * + * `scopesFrom` is the organizations, by id, that are scopes at all. Anyone can + * create an organization at Clerk unless that is turned off, and is its admin: + * a membership in an organization that isn't named gives nothing. With none + * named, no organization is a scope. + */ +export const toGrants = ( + memberships: readonly ClerkMembership[], + everyScope: { readonly roles: readonly string[]; readonly from: readonly string[] }, + scopesFrom: readonly string[], +): ScopeGrant[] => + memberships.flatMap((m) => { + const grant = { scope: organizationScope(m.organization), role: m.role.replace(/^org:/, '') } + + return everyScope.roles.includes(grant.role) + ? everyScope.from.includes(grant.scope) + ? [grant] + : [] + : scopesFrom.includes(grant.scope) + ? [grant] + : [] + }) + +/** How many of a list Clerk is asked for at a time: the most it gives. */ +const PAGE = 100 + +/** One page of one of Clerk's lists, and how many the whole list holds. */ +type Page = { readonly data: readonly A[]; readonly totalCount: number } + +/** + * Every item of one of Clerk's lists, a page at a time. A person in more + * organizations than one page holds would otherwise lose the scopes of the + * rest, and a business with more would be missing them from its switcher. + * Each page is a call of its own, with its own time limit and retries. + */ +const everyPage = Effect.fn('Clerk.everyPage')(function* ( + name: string, + page: (paging: { limit: number; offset: number }) => Promise>, +) { + const all: A[] = [] + + for (;;) { + const { data, totalCount } = yield* call(name, () => page({ limit: PAGE, offset: all.length })) + all.push(...data) + + if (data.length === 0 || all.length >= totalCount) { + return all + } + } +}) + +/** The roles of this Spool's config that reach every scope. */ +const everyScopeRoles = (): string[] => + Object.entries(spool().config.scopes?.roles ?? {}) + .filter(([, role]) => role.all) + .map(([name]) => name) + +/** + * Who holds which record scope, from Clerk organizations. Which organizations + * are scopes (`scopesFrom`), and which a role that reaches every scope counts + * from (`everyScopeFrom`), are carried in the layer they are for. + */ +const organizations = ( + clerkClient: Client, + everyScopeFrom: readonly string[], + scopesFrom: readonly string[], +) => + Layer.succeed( + Scopes, + Scopes.of({ + grants: (user) => + Effect.map( + everyPage('Clerk.organizationMemberships', (paging) => + clerkClient().users.getOrganizationMembershipList({ userId: user.id, ...paging }), + ), + (memberships) => + toGrants(memberships, { roles: everyScopeRoles(), from: everyScopeFrom }, scopesFrom), + ), + // Only the organizations that are scopes: one a person made for themselves is never listed. + list: Effect.map( + everyPage('Clerk.organizations', (paging) => + clerkClient().organizations.getOrganizationList(paging), + ), + (all) => + all + .filter((o) => scopesFrom.includes(organizationScope(o))) + .map((o): ScopeInfo => ({ key: organizationScope(o), label: o.name })), + ), + }), + ) + +/** The origin of an address, as a list: empty when there is none to read. */ +const originOf = (address: string | undefined) => + address && URL.canParse(address) ? [new URL(address).origin] : [] + +/** + * The front ends whose session tokens count (a token's `azp`): the ones the + * app names, else the origin of `APP_URL`. A Clerk instance can serve several + * apps, and a session token it issued to another of them must not open this one. + */ +export const frontEnds = (options: Pick): string[] => [ + ...(options.authorizedParties ?? originOf(process.env['APP_URL'])), +] + +const LOCAL = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/ + +/** + * The front ends Clerk's middleware is told to take session tokens from. The + * ones the app names always count. `APP_URL` counts on a production server + * whose `APP_URL` is its public address: in development the page is often + * served somewhere else (another port, a tunnel), and a deployment still on + * the address from .env.example is told so when it starts. + */ +export const middlewareParties = (options: Pick) => { + if (options.authorizedParties) { + return [...options.authorizedParties] + } + + const named = frontEnds(options) + const counts = process.env['NODE_ENV'] === 'production' && !named.some((at) => LOCAL.test(at)) + return counts && named.length > 0 ? named : undefined +} + +export type ClerkOptions = { + /** + * The origins of the front ends whose session tokens count (a session + * token's `azp`): the site people use the CRM on. `APP_URL`'s origin unless + * this says. A token Clerk issued to another app on the same instance is + * then nobody here. + */ + authorizedParties?: readonly string[] + /** + * `"organizations"`: in a Spool with record scopes, a person holds the scope + * of each Clerk organization they belong to, with their role in it, and the + * organization active in their session is the scope they are working in. A + * scope's key is the organization's id (`org_...`). Only the organizations + * named in `scopesFrom` are scopes. + */ + scopes?: 'organizations' + /** + * The organizations, by id (`org_...`), that are scopes. A membership in any + * other gives nothing: unless you have turned it off, anyone can create an + * organization at Clerk and is its admin. Without it no organization is a + * scope, and nobody holds one: the server says so when it starts. + */ + scopesFrom?: string[] + /** + * The organizations, by id (`org_...`), in which a role that reaches every + * scope counts: head office. Without it no membership gives such a role, and + * nobody reaches every scope: the server says so when it starts. Turn + * organization creation by users off in Clerk as well. + */ + everyScopeFrom?: string[] + /** + * Where a person's roles (`roles` in crm.config.json) come from at Clerk, in + * place of the CRM's own Team page: + * + * - `"metadata"`: the `roles` in the user's public metadata, a list + * (`{ "roles": ["designer", "management"] }`) or one (`{ "role": "designer" }`). + * Public metadata is written only with your secret key or in Clerk's + * dashboard, never by the person themselves. + * The Team page writes it too: an admin ticks a role there, and it is saved + * to the person's Clerk account. + * - `{ organization: "org_..." }`: their role in that organization, by its id, + * without Clerk's `org:` prefix. Clerk gives one role in an organization, + * so nobody holds two this way. A role in any other organization counts for + * nothing: unless you have turned it off, anyone can create one and be its admin. + * + * Either way a role counts only when `roles` in the config has it. + */ + roles?: 'metadata' | { organization: string } +} + +/** + * What to say at start-up when the config has roles that reach every scope and + * nothing says which organizations they count from: nobody will hold one. + */ +export const everyScopeUnnamed = ( + roles: readonly string[], + from: readonly string[], +): string | null => + roles.length > 0 && from.length === 0 + ? `nobody reaches every scope: the role${roles.length === 1 ? '' : 's'} ${roles.map((r) => `"${r}"`).join(', ')} count${roles.length === 1 ? 's' : ''} from no organization. Name head office's with clerk({ everyScopeFrom: ['org_...'] })` + : null + +/** What to say at start-up when organizations are scopes and none is named: nobody will hold one. */ +export const scopesUnnamed = (from: readonly string[]): string | null => + from.length === 0 + ? "no organization is a scope, so nobody holds one. Name the ones that are with clerk({ scopesFrom: ['org_...'] })" + : null + +/** A Clerk user's public metadata, as Clerk's own client types it: whatever the business put there. */ +type PublicMetadata = Awaited>['publicMetadata'] + +/** What `roles: "metadata"` reads from a user's public metadata. Anything else there is ignored. */ +const roleMetadata = z.object({ + roles: z.array(z.string()).optional().catch(undefined), + role: z.string().optional().catch(undefined), +}) + +/** The roles a user's public metadata names: `roles` (a list), and `role` (one). Pure. */ +export function rolesFromMetadata(metadata: PublicMetadata): string[] { + const { roles = [], role } = roleMetadata.safeParse(metadata).data ?? {} + return [...new Set([...roles, ...(role ? [role] : [])])] +} + +/** + * A person's role in the one organization that roles come from: Clerk's role + * key without its `org:` prefix. Memberships anywhere else say nothing. Pure. + */ +export function rolesFromMemberships( + memberships: readonly ClerkMembership[], + organization: string, +): string[] { + return memberships + .filter((m) => m.organization.id === organization) + .map((m) => m.role.replace(/^org:/, '')) +} + +/** + * What to write to a user's public metadata so that they hold exactly `wanted` + * of the roles this CRM has. Roles there that are not this CRM's (another + * system's) are kept, and a lone `role` is folded into the list. Pure. + */ +export function rolesMetadata( + metadata: PublicMetadata, + wanted: readonly string[], + configured: readonly string[], +) { + const others = rolesFromMetadata(metadata).filter((role) => !configured.includes(role)) + // `role: null` takes the lone key away: Clerk removes a key it is sent as null. + return { roles: [...wanted, ...others], role: null } +} + +/** Who holds which role, from Clerk: public metadata, or a role in one organization. */ +const rolesAtClerk = (clerkClient: Client, from: NonNullable) => + Layer.succeed( + Roles, + Roles.of( + from === 'metadata' + ? { + held: (user) => + Effect.map( + call('Clerk.getUser', () => clerkClient().users.getUser(user.id)), + (found) => rolesFromMetadata(found.publicMetadata), + ), + managedIn: 'Clerk', + // The Team page writes here: the roles go onto the person's Clerk account, beside + // whatever else their public metadata holds. Clerk merges what it is sent. + set: Effect.fn('Clerk.setRoles')(function* (user, wanted) { + const found = yield* call('Clerk.getUser', () => clerkClient().users.getUser(user.id)) + + const publicMetadata = rolesMetadata( + found.publicMetadata, + wanted, + Object.keys(spool().config.roles ?? {}), + ) + + yield* call('Clerk.updateUserMetadata', () => + clerkClient().users.updateUserMetadata(user.id, { publicMetadata }), + ) + }), + } + : { + // A role in an organization is a membership: it is changed in Clerk, with its members. + held: (user) => + Effect.map( + everyPage('Clerk.organizationMemberships', (paging) => + clerkClient().users.getOrganizationMembershipList({ userId: user.id, ...paging }), + ), + (memberships) => rolesFromMemberships(memberships, from.organization), + ), + managedIn: 'Clerk', + }, + ), + ) + +/** + * A token an app's own front end forwards, checked by Clerk (runtime/tokens.ts): + * a session token of this Clerk instance, issued to one of the app's + * front-end origins (its `azp`). It is checked on a request that carries + * nothing but the bearer header, so a CRM session cookie sent alongside counts + * for nothing. `CLERK_JWT_KEY`, when set, lets Clerk's SDK check it without + * fetching Clerk's keys. Without it, a token whose key id isn't one of the + * instance's keys (keyring.ts: fetched at most once a minute) is refused + * before the SDK is asked, so made-up tokens never make this server call + * Clerk. The key it names is handed to the SDK (`jwtKey`), so the SDK checks + * the signature offline and never fetches keys itself: every request shares + * the keyring's one fetch, also when keys are due again. A token Clerk + * refuses, or a Clerk that can't be asked, proves nothing: the caller is told + * no more than a bad token tells them, and the log says why. + */ +export const signingKeysOf = (clerkClient: Client) => + keyring(async () => { + const { keys } = await clerkClient().jwks.getJwks() + + return (keys ?? []).flatMap((jwk) => { + if (!jwk.kid) { + return [] + } + + // The key as the SDK takes one offline: a PEM public key. + const pem = createPublicKey({ key: { ...jwk }, format: 'jwk' }).export({ + type: 'spki', + format: 'pem', + }) + + return [[jwk.kid, pem] as const] + }) + }) + +const tokensWith = (clerkClient: Client, signingKeys: ReturnType) => + Layer.succeed( + Tokens, + Tokens.of({ + verify: (token, { authorizedParties }) => + Effect.tryPromise({ + try: async () => { + // With the instance's public key set, the SDK checks offline: nothing to guard. + const set = process.env['CLERK_JWT_KEY'] + const kid = set ? null : kidOf(token) + const jwtKey = set ?? (kid === null ? null : await signingKeys.keyFor(kid)) + + if (!jwtKey) { + return null + } + + const alone = new Request('https://token.invalid/', { + headers: { authorization: `Bearer ${token}` }, + }) + + const state = await clerkClient().authenticateRequest(alone, { + acceptsToken: 'session_token', + jwtKey, + // Empty only in development (the boundary refuses production without origins). + authorizedParties: authorizedParties.length > 0 ? [...authorizedParties] : undefined, + }) + + return state.isAuthenticated ? (state.toAuth().userId ?? null) : null + }, + catch: asAuthError, + }).pipe( + withPolicy({ ...policies.authUsers, service: 'Clerk' }, () => false), + Effect.catch((error) => + Effect.as( + Effect.logError(`[auth] Clerk could not check a token: ${error.message}`), + null, + ), + ), + Effect.withSpan('Clerk.verifyToken'), + ), + }), + ) + +/** + * What differs between the places a Spool with Clerk runs: how the Clerk client + * is made, and how the session of a request is read. On TanStack Start both come + * from Clerk's own package for it (server.ts); with no web framework they come + * from Clerk's backend SDK alone (backend.ts). + */ +export type Client = () => ClerkClient + +export type ClerkHost = { + readonly client: Client + readonly middleware?: HostMiddleware[keyof HostMiddleware] + /** The instance's signing keys, when the host checks sessions against them itself. Shared with the token check. */ + readonly signingKeys?: ReturnType + /** Who the request is from, as Clerk says. A `userId` of null is nobody. */ + readonly session: (request: Request) => Promise<{ + readonly userId: string | null + readonly orgId?: string | null | undefined + readonly getToken: (asked: { template: string }) => Promise + }> +} + +/** Sign-in with Clerk, in the host it is given. */ +export const clerkIn = (host: ClerkHost, options: ClerkOptions = {}): AuthAdapter => { + const asScopes = options.scopes === 'organizations' + const everyScopeFrom = options.everyScopeFrom ?? [] + const scopesFrom = options.scopesFrom ?? [] + + return { + id: 'clerk', + label: 'Clerk', + middleware: host.middleware, + session: async (request) => { + const { userId, getToken, orgId } = await host.session(request) + + if (!userId) { + return null + } + + const session = { userId, getToken: (asked: { template: string }) => getToken(asked) } + // With organizations as scopes, the active one is where this person is working. With none active, the cookie says. + return asScopes && orgId ? { ...session, scope: orgId } : session + }, + scopes: asScopes ? organizations(host.client, everyScopeFrom, scopesFrom) : undefined, + roles: options.roles ? rolesAtClerk(host.client, options.roles) : undefined, + tokens: tokensWith(host.client, host.signingKeys ?? signingKeysOf(host.client)), + layer: directory(host.client), + requires: [ + { name: 'CLERK_SECRET_KEY', check: key('sk_') }, + { name: 'CLERK_PUBLISHABLE_KEY', check: key('pk_') }, + ], + features: [ + { name: 'Sign-in with Clerk', vars: [], check: developmentInstance }, + ...(asScopes + ? [ + { + name: 'Record scopes from Clerk organizations', + vars: [], + check: () => everyScopeUnnamed(everyScopeRoles(), everyScopeFrom), + }, + { + name: 'Which Clerk organizations are record scopes', + vars: [], + check: () => scopesUnnamed(scopesFrom), + }, + ] + : []), + ], + } +} diff --git a/packages/spools/src/adapters/auth/clerk/server.ts b/packages/spools/src/adapters/auth/clerk/server.ts index 5ed1fd6..1517e55 100644 --- a/packages/spools/src/adapters/auth/clerk/server.ts +++ b/packages/spools/src/adapters/auth/clerk/server.ts @@ -1,571 +1,22 @@ -import { createPublicKey } from 'node:crypto' - import { auth, clerkClient, clerkMiddleware } from '@clerk/tanstack-react-start/server' -import { Effect, Layer, Option, Schema } from 'effect' -import { z } from 'zod' - -import { isProvider, PROVIDERS, splitScopes } from '../../../crm/mailbox' -import type { ScopeGrant, ScopeInfo } from '../../../crm/scopes' -import { Roles } from '../../../server/roles' -import type { Env } from '../../../server/runtime/adapter' -import { Auth, type AuthAdapter, type AuthUser } from '../../../server/runtime/auth' -import { AuthError, messageOf } from '../../../server/runtime/errors' -import { policies, withPolicy } from '../../../server/runtime/policies' -import { Tokens } from '../../../server/runtime/tokens' -import { Scopes } from '../../../server/scopes' -import { spool } from '../../../server/spool' -import { keyring, kidOf } from './keyring' -/** - * Sign-in with Clerk (https://clerk.com). The only server code that uses the - * Clerk SDK; the browser half is client.tsx. - * - * CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY from the Clerk dashboard (API keys) - * - * Clerk keeps the Google and Microsoft tokens of the accounts people sign in - * with, so the CRM stores none of its own for them (docs/mailbox.md). - */ +import type { AuthAdapter } from '../../../server/runtime/auth' +import { type ClerkOptions, clerkIn, middlewareParties } from './core' -/** The parts of a Clerk user the CRM reads. */ -export type ClerkUser = { - id: string - firstName: string | null - lastName: string | null - primaryEmailAddressId: string | null - emailAddresses: { id: string; emailAddress: string; verification: { status: string } | null }[] - externalAccounts?: - | { provider: string; emailAddress: string; approvedScopes?: string | null }[] - | null -} +export * from './core' /** - * Whether an address is one of Clerk's test addresses (`ada+clerk_test@acme.com`). - * With test mode on, which it is in every development instance, Clerk marks one - * verified for anybody who types the code 424242, and sends no email - * (https://clerk.com/docs/testing/test-emails-and-phones). So it proves nothing - * about who holds the address. + * Sign-in with Clerk in a Spool on TanStack Start: Clerk's middleware reads the + * session, and `auth()` hands it over. The adapter itself is core.ts; a Spool + * with no web framework uses backend.ts instead. */ -export const isTestAddress = (email: string) => - email.slice(0, email.lastIndexOf('@')).toLowerCase().includes('+clerk_test') - -/** - * A Clerk user as the CRM reads people. Pure, so it can be tested without Clerk. - * `testAddresses` says whether one of Clerk's test addresses counts as verified: - * only on a developer's own machine. - */ -export function toAuthUser(u: ClerkUser, testAddresses = false): AuthUser { - // Only trust verified addresses: an unverified primary email would let anyone claim an allowed domain. - const primary = u.emailAddresses.find((e) => e.id === u.primaryEmailAddressId) - - const verified = - primary?.verification?.status === 'verified' && - (testAddresses || !isTestAddress(primary.emailAddress)) - - return { - id: u.id, - name: [u.firstName, u.lastName].filter(Boolean).join(' ') || null, - email: primary && verified ? primary.emailAddress : null, - accounts: (u.externalAccounts ?? []).map((a) => ({ - // Clerk names a sign-in method "oauth_google"; its token API calls it "google". - provider: a.provider.replace(/^oauth_/, ''), - email: a.emailAddress, - scopes: splitScopes(a.approvedScopes), - })), - } -} - -/** The HTTP status of an error Clerk answered with; anything else (a network failure) has none. */ -const ClerkStatus = Schema.Struct({ status: Schema.Finite }) - -/** The codes of an error Clerk answered with, first one first. */ -const ClerkCodes = Schema.Struct({ - errors: Schema.Array(Schema.Struct({ code: Schema.optional(Schema.String) })), -}) - -const statusOf = (cause: unknown) => - Option.getOrUndefined(Schema.decodeUnknownOption(ClerkStatus)(cause))?.status - -/** A 4xx (other than 429) is Clerk's answer, not a hiccup: asking again won't change it. */ -const transient = (cause: unknown) => { - const status = statusOf(cause) - return status === undefined || status === 429 || status >= 500 -} - -const asAuthError = (cause: unknown) => - new AuthError({ message: messageOf(cause), kind: transient(cause) ? 'unavailable' : 'answer' }) - -/** What Clerk says when it can't hand out a token, in words a teammate can act on. */ -export function tokenRefusal(provider: string, cause: unknown): AuthError { - const code = - Option.getOrUndefined(Schema.decodeUnknownOption(ClerkCodes)(cause))?.errors[0]?.code ?? '' - - const label = Object.entries(PROVIDERS).find(([id]) => id === provider)?.[1].label ?? provider - - if (code.startsWith('oauth_shared_credentials')) { - return new AuthError({ - message: `Clerk is using its shared development credentials for ${label}, which can't give the CRM mailbox access. Set up custom credentials for ${label} in Clerk.`, - kind: 'setup', - }) - } - - return new AuthError({ - message: `Clerk could not provide a ${label} token${code ? ` (${code})` : ''}. Reconnect the account from your profile.`, - // A moment's trouble at Clerk is tried again (below); a refusal is this account's. - kind: transient(cause) ? 'unavailable' : 'account', - }) -} - -const call = ( - name: string, - request: () => Promise, - refusal: (cause: unknown) => AuthError = asAuthError, -) => - Effect.tryPromise({ try: request, catch: refusal }).pipe( - withPolicy( - { ...policies.authUsers, service: 'Clerk' }, - (error) => error.kind === 'unavailable', - ), - Effect.withSpan(name), - ) - -const layer = Layer.sync(Auth, () => { - // A build is always "production", so a deployment never trusts a test address, whichever keys it has. - const testAddresses = process.env['NODE_ENV'] !== 'production' - const read = (user: ClerkUser) => toAuthUser(user, testAddresses) - - return Auth.of({ - getUser: (id) => - Effect.map( - call('Clerk.getUser', () => clerkClient().users.getUser(id)), - read, - ), - listUsers: call('Clerk.listUsers', async () => { - const { data } = await clerkClient().users.getUserList({ limit: 200, orderBy: '+created_at' }) - return data.map(read) - }), - accountToken: (userId, provider) => - // The CRM only reads mail from the providers it knows, and those are all Clerk's names too. - isProvider(provider) - ? call( - 'Clerk.accountToken', - async () => { - const { data } = await clerkClient().users.getUserOauthAccessToken(userId, provider) - return data[0]?.token || null - }, - (cause) => tokenRefusal(provider, cause), - ) - : Effect.fail( - new AuthError({ - message: `The CRM reads no mail from ${provider} accounts.`, - kind: 'account', - }), - ), - }) -}) - -const key = (prefix: string) => (value: string) => { - // The template's placeholder passes a prefix check, but Clerk rejects it on every request with a long stack trace. - if (value.endsWith('...')) { - return 'still has the placeholder value from .env.example' - } - - return value.startsWith(prefix) ? null : `must start with "${prefix}"` -} - -/** - * What to say when a deployment runs on a Clerk development instance. It works, - * and a staging copy may want it, but such an instance is for testing: its - * sign-in pages say so, and its test mode is on. - */ -export const developmentInstance = (env: Env): string | null => - env['NODE_ENV'] === 'production' && env['CLERK_SECRET_KEY']?.startsWith('sk_test_') - ? "on a Clerk development instance (CLERK_SECRET_KEY starts with sk_test_). Use the production instance's keys where real people sign in" - : null - -/** The parts of a Clerk organization membership that record scopes read. */ -export type ClerkMembership = { - role: string - organization: { id: string; slug?: string | null; name: string } -} - -/** - * The scope a Clerk organization is: its id (`org_...`), which is what a - * record's scope field holds. Never its slug: whoever administers an - * organization can rename its slug, to one another scope's records carry, and - * an id is Clerk's own and is never given out twice. - */ -export const organizationScope = (organization: ClerkMembership['organization']): string => - organization.id - -/** - * A person's organization memberships as record scopes. The scope is the - * organization's id and the role is the membership's, without Clerk's `org:` - * prefix: `org:admin` is the role `admin` in `scopes.roles`. Pure, so it can be - * tested without Clerk. - * - * `everyScope` is the roles that reach every scope (`all` in `scopes.roles`), - * and the organizations, by id, a membership must be in for one of them to - * count (`everyScopeFrom`). A person can be made anything in an organization - * they created themselves, and Clerk's own `org:admin` is held by whoever runs - * any organization, so such a role held anywhere else gives nothing: not every - * scope, and not that organization's either. With no organization named, no - * membership gives a role that reaches every scope. - * - * `scopesFrom` is the organizations, by id, that are scopes at all. Anyone can - * create an organization at Clerk unless that is turned off, and is its admin: - * a membership in an organization that isn't named gives nothing. With none - * named, no organization is a scope. - */ -export const toGrants = ( - memberships: readonly ClerkMembership[], - everyScope: { readonly roles: readonly string[]; readonly from: readonly string[] }, - scopesFrom: readonly string[], -): ScopeGrant[] => - memberships.flatMap((m) => { - const grant = { scope: organizationScope(m.organization), role: m.role.replace(/^org:/, '') } - - return everyScope.roles.includes(grant.role) - ? everyScope.from.includes(grant.scope) - ? [grant] - : [] - : scopesFrom.includes(grant.scope) - ? [grant] - : [] - }) - -/** How many of a list Clerk is asked for at a time: the most it gives. */ -const PAGE = 100 - -/** One page of one of Clerk's lists, and how many the whole list holds. */ -type Page = { readonly data: readonly A[]; readonly totalCount: number } - -/** - * Every item of one of Clerk's lists, a page at a time. A person in more - * organizations than one page holds would otherwise lose the scopes of the - * rest, and a business with more would be missing them from its switcher. - * Each page is a call of its own, with its own time limit and retries. - */ -const everyPage = Effect.fn('Clerk.everyPage')(function* ( - name: string, - page: (paging: { limit: number; offset: number }) => Promise>, -) { - const all: A[] = [] - - for (;;) { - const { data, totalCount } = yield* call(name, () => page({ limit: PAGE, offset: all.length })) - all.push(...data) - - if (data.length === 0 || all.length >= totalCount) { - return all - } - } -}) - -/** The roles of this Spool's config that reach every scope. */ -const everyScopeRoles = (): string[] => - Object.entries(spool().config.scopes?.roles ?? {}) - .filter(([, role]) => role.all) - .map(([name]) => name) - -/** - * Who holds which record scope, from Clerk organizations. Which organizations - * are scopes (`scopesFrom`), and which a role that reaches every scope counts - * from (`everyScopeFrom`), are carried in the layer they are for. - */ -const organizations = (everyScopeFrom: readonly string[], scopesFrom: readonly string[]) => - Layer.succeed( - Scopes, - Scopes.of({ - grants: (user) => - Effect.map( - everyPage('Clerk.organizationMemberships', (paging) => - clerkClient().users.getOrganizationMembershipList({ userId: user.id, ...paging }), - ), - (memberships) => - toGrants(memberships, { roles: everyScopeRoles(), from: everyScopeFrom }, scopesFrom), - ), - // Only the organizations that are scopes: one a person made for themselves is never listed. - list: Effect.map( - everyPage('Clerk.organizations', (paging) => - clerkClient().organizations.getOrganizationList(paging), - ), - (all) => - all - .filter((o) => scopesFrom.includes(organizationScope(o))) - .map((o): ScopeInfo => ({ key: organizationScope(o), label: o.name })), - ), - }), - ) - -export type ClerkOptions = { - /** - * `"organizations"`: in a Spool with record scopes, a person holds the scope - * of each Clerk organization they belong to, with their role in it, and the - * organization active in their session is the scope they are working in. A - * scope's key is the organization's id (`org_...`). Only the organizations - * named in `scopesFrom` are scopes. - */ - scopes?: 'organizations' - /** - * The organizations, by id (`org_...`), that are scopes. A membership in any - * other gives nothing: unless you have turned it off, anyone can create an - * organization at Clerk and is its admin. Without it no organization is a - * scope, and nobody holds one: the server says so when it starts. - */ - scopesFrom?: string[] - /** - * The organizations, by id (`org_...`), in which a role that reaches every - * scope counts: head office. Without it no membership gives such a role, and - * nobody reaches every scope: the server says so when it starts. Turn - * organization creation by users off in Clerk as well. - */ - everyScopeFrom?: string[] - /** - * Where a person's roles (`roles` in crm.config.json) come from at Clerk, in - * place of the CRM's own Team page: - * - * - `"metadata"`: the `roles` in the user's public metadata, a list - * (`{ "roles": ["designer", "management"] }`) or one (`{ "role": "designer" }`). - * Public metadata is written only with your secret key or in Clerk's - * dashboard, never by the person themselves. - * The Team page writes it too: an admin ticks a role there, and it is saved - * to the person's Clerk account. - * - `{ organization: "org_..." }`: their role in that organization, by its id, - * without Clerk's `org:` prefix. Clerk gives one role in an organization, - * so nobody holds two this way. A role in any other organization counts for - * nothing: unless you have turned it off, anyone can create one and be its admin. - * - * Either way a role counts only when `roles` in the config has it. - */ - roles?: 'metadata' | { organization: string } -} - -/** - * What to say at start-up when the config has roles that reach every scope and - * nothing says which organizations they count from: nobody will hold one. - */ -export const everyScopeUnnamed = ( - roles: readonly string[], - from: readonly string[], -): string | null => - roles.length > 0 && from.length === 0 - ? `nobody reaches every scope: the role${roles.length === 1 ? '' : 's'} ${roles.map((r) => `"${r}"`).join(', ')} count${roles.length === 1 ? 's' : ''} from no organization. Name head office's with clerk({ everyScopeFrom: ['org_...'] })` - : null - -/** What to say at start-up when organizations are scopes and none is named: nobody will hold one. */ -export const scopesUnnamed = (from: readonly string[]): string | null => - from.length === 0 - ? "no organization is a scope, so nobody holds one. Name the ones that are with clerk({ scopesFrom: ['org_...'] })" - : null - -/** A Clerk user's public metadata, as Clerk's own client types it: whatever the business put there. */ -type PublicMetadata = Awaited< - ReturnType['users']['getUser']> ->['publicMetadata'] - -/** What `roles: "metadata"` reads from a user's public metadata. Anything else there is ignored. */ -const roleMetadata = z.object({ - roles: z.array(z.string()).optional().catch(undefined), - role: z.string().optional().catch(undefined), -}) - -/** The roles a user's public metadata names: `roles` (a list), and `role` (one). Pure. */ -export function rolesFromMetadata(metadata: PublicMetadata): string[] { - const { roles = [], role } = roleMetadata.safeParse(metadata).data ?? {} - return [...new Set([...roles, ...(role ? [role] : [])])] -} - -/** - * A person's role in the one organization that roles come from: Clerk's role - * key without its `org:` prefix. Memberships anywhere else say nothing. Pure. - */ -export function rolesFromMemberships( - memberships: readonly ClerkMembership[], - organization: string, -): string[] { - return memberships - .filter((m) => m.organization.id === organization) - .map((m) => m.role.replace(/^org:/, '')) -} - -/** - * What to write to a user's public metadata so that they hold exactly `wanted` - * of the roles this CRM has. Roles there that are not this CRM's (another - * system's) are kept, and a lone `role` is folded into the list. Pure. - */ -export function rolesMetadata( - metadata: PublicMetadata, - wanted: readonly string[], - configured: readonly string[], -) { - const others = rolesFromMetadata(metadata).filter((role) => !configured.includes(role)) - // `role: null` takes the lone key away: Clerk removes a key it is sent as null. - return { roles: [...wanted, ...others], role: null } -} - -/** Who holds which role, from Clerk: public metadata, or a role in one organization. */ -const rolesAtClerk = (from: NonNullable) => - Layer.succeed( - Roles, - Roles.of( - from === 'metadata' - ? { - held: (user) => - Effect.map( - call('Clerk.getUser', () => clerkClient().users.getUser(user.id)), - (found) => rolesFromMetadata(found.publicMetadata), - ), - managedIn: 'Clerk', - // The Team page writes here: the roles go onto the person's Clerk account, beside - // whatever else their public metadata holds. Clerk merges what it is sent. - set: Effect.fn('Clerk.setRoles')(function* (user, wanted) { - const found = yield* call('Clerk.getUser', () => clerkClient().users.getUser(user.id)) - - const publicMetadata = rolesMetadata( - found.publicMetadata, - wanted, - Object.keys(spool().config.roles ?? {}), - ) - - yield* call('Clerk.updateUserMetadata', () => - clerkClient().users.updateUserMetadata(user.id, { publicMetadata }), - ) - }), - } - : { - // A role in an organization is a membership: it is changed in Clerk, with its members. - held: (user) => - Effect.map( - everyPage('Clerk.organizationMemberships', (paging) => - clerkClient().users.getOrganizationMembershipList({ userId: user.id, ...paging }), - ), - (memberships) => rolesFromMemberships(memberships, from.organization), - ), - managedIn: 'Clerk', - }, - ), - ) - -/** - * A token an app's own front end forwards, checked by Clerk (runtime/tokens.ts): - * a session token of this Clerk instance, issued to one of the app's - * front-end origins (its `azp`). It is checked on a request that carries - * nothing but the bearer header, so a CRM session cookie sent alongside counts - * for nothing. `CLERK_JWT_KEY`, when set, lets Clerk's SDK check it without - * fetching Clerk's keys. Without it, a token whose key id isn't one of the - * instance's keys (keyring.ts: fetched at most once a minute) is refused - * before the SDK is asked, so made-up tokens never make this server call - * Clerk. The key it names is handed to the SDK (`jwtKey`), so the SDK checks - * the signature offline and never fetches keys itself: every request shares - * the keyring's one fetch, also when keys are due again. A token Clerk - * refuses, or a Clerk that can't be asked, proves nothing: the caller is told - * no more than a bad token tells them, and the log says why. - */ -const signingKeys = keyring(async () => { - const { keys } = await clerkClient().jwks.getJwks() - - return (keys ?? []).flatMap((jwk) => { - if (!jwk.kid) { - return [] - } - - // The key as the SDK takes one offline: a PEM public key. - const pem = createPublicKey({ key: { ...jwk }, format: 'jwk' }).export({ - type: 'spki', - format: 'pem', - }) - - return [[jwk.kid, pem] as const] - }) -}) - -const tokens = Layer.succeed( - Tokens, - Tokens.of({ - verify: (token, { authorizedParties }) => - Effect.tryPromise({ - try: async () => { - // With the instance's public key set, the SDK checks offline: nothing to guard. - const set = process.env['CLERK_JWT_KEY'] - const kid = set ? null : kidOf(token) - const jwtKey = set ?? (kid === null ? null : await signingKeys.keyFor(kid)) - - if (!jwtKey) { - return null - } - - const alone = new Request('https://token.invalid/', { - headers: { authorization: `Bearer ${token}` }, - }) - - const state = await clerkClient().authenticateRequest(alone, { - acceptsToken: 'session_token', - jwtKey, - // Empty only in development (the boundary refuses production without origins). - authorizedParties: authorizedParties.length > 0 ? [...authorizedParties] : undefined, - }) - - return state.isAuthenticated ? (state.toAuth().userId ?? null) : null - }, - catch: asAuthError, - }).pipe( - withPolicy({ ...policies.authUsers, service: 'Clerk' }, () => false), - Effect.catch((error) => - Effect.as( - Effect.logError(`[auth] Clerk could not check a token: ${error.message}`), - null, - ), - ), - Effect.withSpan('Clerk.verifyToken'), - ), - }), -) - -/** Sign-in with Clerk. */ -export const clerk = (options: ClerkOptions = {}): AuthAdapter => { - const asScopes = options.scopes === 'organizations' - const everyScopeFrom = options.everyScopeFrom ?? [] - const scopesFrom = options.scopesFrom ?? [] - - return { - id: 'clerk', - label: 'Clerk', - middleware: clerkMiddleware(), - session: async () => { - const { userId, getToken, orgId } = await auth() - - if (!userId) { - return null - } - - const session = { userId, getToken: (asked: { template: string }) => getToken(asked) } - // With organizations as scopes, the active one is where this person is working. With none active, the cookie says. - return asScopes && orgId ? { ...session, scope: orgId } : session +export const clerk = (options: ClerkOptions = {}): AuthAdapter => + clerkIn( + { + client: () => clerkClient(), + // Read on each request: the environment is the server's, not the build's. + middleware: clerkMiddleware(() => ({ authorizedParties: middlewareParties(options) })), + session: () => auth(), }, - scopes: asScopes ? organizations(everyScopeFrom, scopesFrom) : undefined, - roles: options.roles ? rolesAtClerk(options.roles) : undefined, - tokens, - layer, - requires: [ - { name: 'CLERK_SECRET_KEY', check: key('sk_') }, - { name: 'CLERK_PUBLISHABLE_KEY', check: key('pk_') }, - ], - features: [ - { name: 'Sign-in with Clerk', vars: [], check: developmentInstance }, - ...(asScopes - ? [ - { - name: 'Record scopes from Clerk organizations', - vars: [], - check: () => everyScopeUnnamed(everyScopeRoles(), everyScopeFrom), - }, - { - name: 'Which Clerk organizations are record scopes', - vars: [], - check: () => scopesUnnamed(scopesFrom), - }, - ] - : []), - ], - } -} + options, + ) diff --git a/packages/spools/src/adapters/vault/aes/server.ts b/packages/spools/src/adapters/vault/aes/server.ts deleted file mode 100644 index d48b699..0000000 --- a/packages/spools/src/adapters/vault/aes/server.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { Effect, Layer } from 'effect' - -import * as config from '../../../server/runtime/config' -import { type Cipher, Vault, type VaultAdapter, VaultError } from '../../../server/runtime/vault' - -/** - * Secrets encrypted with AES-256-GCM under a key from the environment: no - * outside service. - * - * VAULT_KEY 32 random bytes, base64. `openssl rand -base64 32` - * VAULT_OLD_KEYS optional: keys VAULT_KEY replaced, comma-separated, still used to open what they sealed - * - * The key is as valuable as everything sealed with it: anyone who has it and a - * copy of the database can read the stored tokens. CipherStash gives each value - * its own key and keeps the root of them elsewhere; use it when that matters. - * - * Sealed values are `v1...`, base64url. A fresh - * 96-bit nonce is drawn for each value, and the version and key id are - * authenticated with it, so neither can be swapped. - */ - -const b64url = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64url') -const bytesOf = (text: string) => new Uint8Array(Buffer.from(text, 'base64url')) - -type Key = { id: string; key: CryptoKey } - -/** What is wrong with something given as a key that isn't one. */ -const NOT_A_KEY = 'must be 32 random bytes, base64 (openssl rand -base64 32)' - -/** A key from its base64 form, or null when it isn't one (`NOT_A_KEY`). The id is a hash, so it says nothing about the key. */ -async function importKey(encoded: string): Promise { - const raw = new Uint8Array(Buffer.from(encoded.trim(), 'base64')) - - if (raw.byteLength !== 32) { - return null - } - - const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw)) - return { - id: b64url(digest.slice(0, 6)), - key: await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt']), - } -} - -const associated = (id: string) => new TextEncoder().encode(`spools-vault.v1.${id}`) - -/** The cipher for a current key and any it replaced. Exported for tests. */ -export async function aesCipher(current: string, old: readonly string[] = []): Promise { - const main = await importKey(current) - - if (!main) { - throw new VaultError({ message: `VAULT_KEY ${NOT_A_KEY}` }) - } - - const keys = new Map([[main.id, main.key]]) - - for (const encoded of old) { - const key = await importKey(encoded) - - if (!key) { - throw new VaultError({ message: `VAULT_OLD_KEYS: each ${NOT_A_KEY}` }) - } - - keys.set(key.id, key.key) - } - - return { - async encrypt(plaintext) { - const iv = crypto.getRandomValues(new Uint8Array(12)) - - const sealed = await crypto.subtle.encrypt( - { name: 'AES-GCM', iv, additionalData: associated(main.id) }, - main.key, - new TextEncoder().encode(plaintext), - ) - - return `v1.${main.id}.${b64url(iv)}.${b64url(new Uint8Array(sealed))}` - }, - async decrypt(ciphertext) { - const [version, id, iv, sealed, ...rest] = ciphertext.split('.') - - if (version !== 'v1' || !id || !iv || !sealed || rest.length > 0) { - throw new VaultError({ message: 'Stored secret is not one this vault sealed' }) - } - - const key = keys.get(id) - - if (!key) { - throw new VaultError({ - message: 'Stored secret was sealed with a key this CRM no longer has (VAULT_OLD_KEYS)', - }) - } - - try { - const opened = await crypto.subtle.decrypt( - { name: 'AES-GCM', iv: bytesOf(iv), additionalData: associated(id) }, - key, - bytesOf(sealed), - ) - - return new TextDecoder().decode(opened) - } catch { - throw new VaultError({ - message: 'Stored secret could not be opened: it was changed, or the key is wrong', - }) - } - }, - } -} - -const problemWith = (key: string | undefined): string | null => { - if (!key) { - return 'VAULT_KEY is not set (openssl rand -base64 32)' - } - - return Buffer.from(key.trim(), 'base64').byteLength === 32 - ? null - : 'VAULT_KEY must be 32 random bytes, base64 (openssl rand -base64 32)' -} - -export const aes = (): VaultAdapter => ({ - id: 'aes', - label: 'The vault', - features: [ - { - name: 'Integrations: encrypted token storage (AES)', - vars: ['VAULT_KEY'], - check: (env) => problemWith(env['VAULT_KEY']), - }, - ], - layer: Layer.sync(Vault, () => { - const cipher = Effect.gen(function* () { - const env = yield* config.environment - const problem = problemWith(env['VAULT_KEY']) - - if (problem) { - return yield* new VaultError({ - message: `Encryption isn't set up, so secrets can't be stored. ${problem}`, - }) - } - - const old = (env['VAULT_OLD_KEYS'] ?? '').split(',').filter((k) => k.trim()) - return yield* Effect.tryPromise({ - try: () => aesCipher(env['VAULT_KEY'] ?? '', old), - catch: (cause) => - cause instanceof VaultError - ? cause - : new VaultError({ message: 'Could not set up encryption' }), - }) - }) - - return Vault.make({ - cipher, - service: 'The vault', - problem: Effect.map(config.environment, (env) => problemWith(env['VAULT_KEY'])), - }) - }), -}) diff --git a/packages/spools/src/adapters/vault/cipherstash/server.ts b/packages/spools/src/adapters/vault/cipherstash/server.ts index 443a661..40271e9 100644 --- a/packages/spools/src/adapters/vault/cipherstash/server.ts +++ b/packages/spools/src/adapters/vault/cipherstash/server.ts @@ -1,13 +1,21 @@ import { Effect, Layer, Predicate } from 'effect' +import type { Env } from '../../../server/runtime/adapter' import * as config from '../../../server/runtime/config' import { type Cipher, Vault, type VaultAdapter, VaultError } from '../../../server/runtime/vault' +import { STAND_IN, standInCipher } from './stand-in' /** * Secrets encrypted with CipherStash (https://cipherstash.com) in this process, - * each under its own key from ZeroKMS. + * each under its own key from ZeroKMS. It is the vault Spools has: what a Spool + * keeps that must stay secret (a teammate's tokens, an API key's seal, an + * answer kept for a repeat) is sealed by it. * * CS_WORKSPACE_CRN, CS_CLIENT_ID, CS_CLIENT_KEY, CS_CLIENT_ACCESS_KEY + * + * A production server does not start without them. Anywhere else a stand-in + * seals instead (stand-in.ts), with a key that is in the source, so a Spool can + * be worked on before it has a workspace. It protects nothing, and says so. */ const VARIABLES = [ @@ -72,6 +80,13 @@ export function cipherOver( // What JSON.parse reads is JSON. let payload: Json + if (ciphertext.startsWith(STAND_IN)) { + throw new VaultError({ + message: + 'Stored secret was sealed by the development stand-in, which a server with CipherStash does not open', + }) + } + try { payload = JSON.parse(ciphertext) } catch { @@ -111,19 +126,46 @@ const starting = (cause: unknown) => ? cause : new VaultError({ message: 'Could not reach CipherStash to set up encryption' }) +const NOT_SET_UP = `CipherStash is not set up, so secrets can't be stored. Set ${VARIABLES.join(', ')} (see docs/integrations.md).` + +const STANDING_IN = + 'CipherStash is not set up (CS_* variables), so a development key that is in the source seals secrets: it protects nothing, and a production server does not start this way' + +const production = (env: Env) => env['NODE_ENV'] === 'production' + +/** Which cipher this environment gets: CipherStash, the stand-in outside production, or none. */ +export const vaultFor = (env: Env): 'cipherstash' | 'stand-in' | 'none' => { + if (cipherStashConfigured(env)) { + return 'cipherstash' + } + + return production(env) ? 'none' : 'stand-in' +} + /** Set up the first time a secret is sealed or opened, and again after a failed start. */ export const cipherstash = (): VaultAdapter => ({ id: 'cipherstash', label: 'CipherStash', - features: [{ name: 'Integrations: encrypted token storage (CipherStash)', vars: VARIABLES }], + requires: process.env['NODE_ENV'] === 'production' ? VARIABLES.map((name) => ({ name })) : [], + features: [ + { + name: 'Encryption of stored secrets (CipherStash)', + vars: [], + check: (env) => (vaultFor(env) === 'cipherstash' ? null : STANDING_IN), + }, + ], layer: Layer.sync(Vault, () => { let ready: Promise | undefined const cipher = Effect.gen(function* () { - if (!cipherStashConfigured(yield* config.environment)) { - return yield* new VaultError({ - message: `Encryption isn't set up, so secrets can't be stored. Set ${VARIABLES.join(', ')} (see docs/integrations.md).`, - }) + const which = vaultFor(yield* config.environment) + + if (which === 'none') { + return yield* new VaultError({ message: NOT_SET_UP }) + } + + if (which === 'stand-in') { + return standInCipher } ready ??= cipherStash().catch((cause) => { @@ -139,7 +181,7 @@ export const cipherstash = (): VaultAdapter => ({ cipher, service: 'CipherStash', problem: Effect.map(config.environment, (env) => - cipherStashConfigured(env) ? null : 'CipherStash encryption is not set up (CS_* variables)', + vaultFor(env) === 'none' ? 'CipherStash encryption is not set up (CS_* variables)' : null, ), }) }), diff --git a/packages/spools/src/adapters/vault/cipherstash/stand-in.ts b/packages/spools/src/adapters/vault/cipherstash/stand-in.ts new file mode 100644 index 0000000..e5f3d2d --- /dev/null +++ b/packages/spools/src/adapters/vault/cipherstash/stand-in.ts @@ -0,0 +1,64 @@ +import { type Cipher, VaultError } from '../../../server/runtime/vault' + +/** + * What stands in for CipherStash on a developer's machine and in tests, so a + * Spool can be worked on before it has a workspace. It encrypts with a key that + * is written here, in the source, so it protects nothing: anyone can open what + * it sealed. A production server never uses it (server.ts). + * + * Sealed values are `dev..`, base64url, which is how a + * server with CipherStash knows one and says so rather than failing to read it. + */ + +/** How a value sealed here begins. */ +export const STAND_IN = 'dev.' + +const b64url = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64url') +const bytesOf = (text: string) => new Uint8Array(Buffer.from(text, 'base64url')) +const associated = new TextEncoder().encode('spools-vault.dev') + +let key: Promise | undefined + +const standInKey = () => { + key ??= crypto.subtle + .digest('SHA-256', new TextEncoder().encode('spools development vault: not a secret')) + .then((raw) => crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])) + + return key +} + +export const standInCipher: Cipher = { + async encrypt(plaintext) { + const iv = crypto.getRandomValues(new Uint8Array(12)) + + const sealed = await crypto.subtle.encrypt( + { name: 'AES-GCM', iv, additionalData: associated }, + await standInKey(), + new TextEncoder().encode(plaintext), + ) + + return `${STAND_IN}${b64url(iv)}.${b64url(new Uint8Array(sealed))}` + }, + async decrypt(ciphertext) { + const [version, iv, sealed, ...rest] = ciphertext.split('.') + + if (version !== 'dev' || !iv || !sealed || rest.length > 0) { + throw new VaultError({ + message: + 'Stored secret was not sealed on this machine: it needs the CipherStash workspace that sealed it (CS_* variables)', + }) + } + + try { + const opened = await crypto.subtle.decrypt( + { name: 'AES-GCM', iv: bytesOf(iv), additionalData: associated }, + await standInKey(), + bytesOf(sealed), + ) + + return new TextDecoder().decode(opened) + } catch { + throw new VaultError({ message: 'Stored secret could not be opened: it was changed' }) + } + }, +} diff --git a/packages/spools/src/cli/gen.ts b/packages/spools/src/cli/gen.ts index dbc6f6e..ffff443 100644 --- a/packages/spools/src/cli/gen.ts +++ b/packages/spools/src/cli/gen.ts @@ -5,6 +5,8 @@ import { $ } from 'bun' * - prisma/schema.prisma (Prisma 8 data contract: system tables, one table * per object, one per many-to-many relation) * - crm.config.schema.json (JSON Schema for editor autocomplete) + * - src/crm.types.ts (each object's record and values, for a front end + * of the app's own: `createClient()`) * then run `prisma contract emit`. * * The config is the app's with its modules' parts in it (src/crm/compose.ts), @@ -15,6 +17,7 @@ import { $ } from 'bun' import { z } from 'zod' import { generatePrisma } from '../crm/codegen' +import { generateTypes } from '../crm/codegen-types' import { crmConfigSchema } from '../crm/config-schema' import { ModuleConflict, spool, tableKeepersOf } from '../server/spool' import { linkTables } from '../server/store/objects' @@ -97,6 +100,9 @@ console.log( console.log('✓ crm.config.schema.json') +await Bun.write(`${root}src/crm.types.ts`, generateTypes(config)) +console.log('✓ src/crm.types.ts') + for (const w of warnings) { console.warn(`⚠ ${w}`) } diff --git a/packages/spools/src/cli/keys.ts b/packages/spools/src/cli/keys.ts new file mode 100644 index 0000000..359c5c0 --- /dev/null +++ b/packages/spools/src/cli/keys.ts @@ -0,0 +1,132 @@ +#!/usr/bin/env bun +/** + * API keys, for a script or another service that calls the HTTP API + * (docs/headless.md#api-keys): + * + * spools keys create --name "nightly export" --as ana@example.com [--read-only] [--days 30 | --never-expires] + * spools keys list + * spools keys revoke + * + * A key acts as the teammate named with `--as`: it reaches what they reach and + * stops working when they leave the access list. `create` prints the key once; + * what is kept is sealed by the Spool's vault, so it can't be shown again, and + * a Spool with no vault has no keys. A key ends after 90 + * days unless `--days` or `--never-expires` says otherwise. The server takes + * keys only when its HTTP API says so (`keys: true`). + */ +import { parseArgs } from 'node:util' + +import { Effect } from 'effect' + +import { createKey, type KeyInfo, listKeys, revokeKey } from '../server/api-keys' +import { disposeRuntime, runServer } from '../server/runtime/app' +import { Auth } from '../server/runtime/auth' + +const USAGE = `Usage: + spools keys create --name --as [--read-only] [--days | --never-expires] + spools keys list + spools keys revoke ` + +const { positionals, values } = parseArgs({ + args: process.argv.slice(2), + allowPositionals: true, + options: { + name: { type: 'string' }, + as: { type: 'string' }, + 'read-only': { type: 'boolean', default: false }, + days: { type: 'string' }, + 'never-expires': { type: 'boolean', default: false }, + }, +}) + +const [what, id] = positionals + +const day = (at: Date | null) => (at === null ? null : at.toISOString().slice(0, 10)) + +const stateOf = (key: KeyInfo) => { + if (key.revokedAt !== null) { + return `revoked ${day(key.revokedAt)}` + } + + if (key.expiresAt !== null) { + return key.expiresAt.getTime() <= Date.now() + ? `expired ${day(key.expiresAt)}` + : `expires ${day(key.expiresAt)}` + } + + return 'active' +} + +/** Every key with the email of the teammate it acts as, where the auth provider still knows them. */ +const listed = Effect.gen(function* () { + const keys = yield* listKeys() + const people = keys.length > 0 ? yield* (yield* Auth).listUsers : [] + const emails = new Map(people.map((person) => [person.id, person.email])) + + return keys.map((key) => ({ ...key, email: emails.get(key.userId) ?? key.userId })) +}) + +const run = async (): Promise => { + if (what === 'create') { + if (!values.name || !values.as) { + console.error(USAGE) + return 1 + } + + const { key, info } = await runServer( + createKey({ + name: values.name, + email: values.as, + readOnly: values['read-only'], + days: values.days === undefined ? undefined : Number(values.days), + neverExpires: values['never-expires'], + }), + ) + + console.log(`✓ Made "${info.name}" (${info.id}), acting as ${values.as}: ${stateOf(info)}`) + console.log(info.readOnly ? ' It may only read.' : ' It may read and change what they may.') + console.log('\n Keep it somewhere safe. It is not shown again:\n') + console.log(` ${key}\n`) + console.log(' The server takes keys once its HTTP API says so: `keys: true`.') + return 0 + } + + if (what === 'list') { + const keys = await runServer(listed) + + if (keys.length === 0) { + console.log('No keys yet. Make one with: spools keys create --name --as ') + } + + for (const key of keys) { + const used = key.lastUsedAt === null ? 'never used' : `last used ${day(key.lastUsedAt)}` + const reach = key.readOnly ? 'read only' : 'read and write' + console.log(`${key.id} ${key.name} as ${key.email} ${reach} ${stateOf(key)} ${used}`) + } + + return 0 + } + + if (what === 'revoke' && id) { + const revoked = await runServer(revokeKey(id)) + console.log(revoked ? `✓ Revoked ${id}` : `${id} was revoked already`) + return 0 + } + + console.error(USAGE) + return 1 +} + +// The app's Spool: its config and its database. +await import(`${process.cwd()}/src/spool.server.ts`) + +let code = 1 + +try { + code = await run() +} catch (err) { + console.error(`✗ ${err instanceof Error ? err.message : String(err)}`) +} + +await disposeRuntime() +process.exit(code) diff --git a/packages/spools/src/cli/main.ts b/packages/spools/src/cli/main.ts index f483d38..ac08858 100755 --- a/packages/spools/src/cli/main.ts +++ b/packages/spools/src/cli/main.ts @@ -11,6 +11,7 @@ * spools rules list records that already break a uniqueness rule (`unique` in the config) * spools timeline `spools timeline redact`: stop old timeline lines naming records someone is kept from * spools ui `spools ui check`: what is wrong with the Spool's layouts. `spools ui prompt`: what an agent writes one from + * spools keys `spools keys create|list|revoke`: API keys for scripts and services that call the HTTP API * spools check-client fail if server code reached the browser bundle */ const commands = { @@ -23,6 +24,7 @@ const commands = { rules: () => import('./rules'), timeline: () => import('./timeline'), ui: () => import('./ui'), + keys: () => import('./keys'), 'check-client': () => import('./check-client'), } diff --git a/packages/spools/src/client.ts b/packages/spools/src/client.ts new file mode 100644 index 0000000..0b87435 --- /dev/null +++ b/packages/spools/src/client.ts @@ -0,0 +1,218 @@ +import type { Effect } from 'effect' +import { z } from 'zod' + +import type { Operations } from './server/operations' + +/** + * A client for a Spool's HTTP API (src/server/http.ts), for a front end of your + * own: any framework, a mobile app, a script. It knows every operation by + * name, what each takes and what each answers, from the server's own + * definitions, and imports none of the server: the types are all that cross. + * + * const crm = createClient({ baseUrl: 'https://crm.example.com/api/v1' }) + * const { record } = await crm.call('records.get', { objectKey: 'contacts', id }) + * + * On the CRM's own site the browser's session cookie says who is asking. From + * anywhere else, give `token`: the sign-in token of whoever is using your + * front end, which the server takes only from the front ends it names. + */ + +/** A value as JSON carries it: a date arrives as text, and everything else as it was. */ +export type Sent = unknown extends T + ? T + : T extends Date + ? string + : T extends ReadonlyArray + ? Sent[] + : T extends object + ? { [K in keyof T]: Sent } + : T + +/** The names of the operations. */ +export type OperationName = keyof Operations + +/** What an operation takes. */ +export type InputOf = z.input + +/** What an operation answers. */ +export type AnswerOf = Sent< + Effect.Success> +> + +/** A value as JSON carries one. */ +export type Json = string | number | boolean | null | Json[] | { [key: string]: Json | undefined } + +/** The fields of a record, by key, for a client not told what they are. */ +export type Values = { [key: string]: Json | undefined } + +/** What every record has, whatever its object. Moments are ISO text. */ +export type RecordBase = { + id: string + createdAt: string + updatedAt: string + /** Who made it: a teammate's id, or what the server's own code said ("seed", an automation). */ + createdBy?: string | null + lastActivityAt?: string | null + lastContactedAt?: string | null + nextTaskDue?: string | null +} + +/** A record another points at: its id always, and as many of its fields as the answer brought. */ +export type Related = Partial & { id: string } + +/** A change to the records a many-to-many field holds, instead of the whole list. */ +export type LinksChange = { add?: string[]; remove?: string[] } + +/** + * The objects of one CRM, by key: each one's record and the values a write + * takes. `spools gen` writes it from the config as `Crm` (src/crm.types.ts). + */ +export type Objects = Record + +/** Any CRM's objects, for a client not told which: records are loosely typed. */ +export type AnyObjects = Record + +/** A record in a list: the fields the list asked for, which is rarely all of them. */ +export type Listed = Related + +/** A refusal or a failure, as the server said it: the HTTP status, a code to branch on, and words for a person. */ +export class SpoolsError extends Error { + override readonly name = 'SpoolsError' + + constructor( + readonly status: number, + readonly code: string, + message: string, + ) { + super(message) + } +} + +export type ClientOptions = { + /** Where the API is mounted, with its base path: `https://crm.example.com/api/v1`. */ + readonly baseUrl: string + /** The sign-in token of whoever is asking, for a front end on another site than the CRM's. */ + readonly token?: () => string | null | Promise + /** The record scope to work in, in a Spool that has them: a scope's key, or `*` for all of theirs. */ + readonly scope?: () => string | null + /** `fetch`, if not the global one (a test, a server that adds its own headers). */ + readonly fetch?: (input: string, init: RequestInit) => Promise +} + +export type CallOptions = { + /** Stops waiting for the answer. */ + readonly signal?: AbortSignal + /** For a write: sent twice with one key, it runs once and answers the same. */ + readonly idempotencyKey?: string +} + +/** The two shapes the API answers in (src/server/http.ts). */ +const refusalShape = z.object({ error: z.object({ code: z.string(), message: z.string() }) }) +const answerShape = z.object({ data: z.any() }) + +/** + * A client for the HTTP API at `baseUrl`. Given the app's generated `Crm` + * (`createClient(...)`), `records(key)` knows each object's fields. + */ +export const createClient = (options: ClientOptions) => { + const base = options.baseUrl.replace(/\/+$/, '') + const send = options.fetch ?? ((input: string, init: RequestInit) => fetch(input, init)) + + /** Runs an operation, and gives its answer or throws a `SpoolsError`. */ + const call = async ( + name: N, + // An operation that takes nothing is called with the name alone. + ...[input, more]: undefined extends InputOf + ? [input?: InputOf, more?: CallOptions] + : [input: InputOf, more?: CallOptions] + ): Promise> => { + const headers = new Headers({ 'Content-Type': 'application/json' }) + const token = await options.token?.() + const scope = options.scope?.() + + if (token) { + headers.set('Authorization', `Bearer ${token}`) + } + + if (scope) { + headers.set('X-Spools-Scope', scope) + } + + if (more?.idempotencyKey) { + headers.set('Idempotency-Key', more.idempotencyKey) + } + + const response = await send(`${base}/${name}`, { + method: 'POST', + headers, + body: input === undefined ? null : JSON.stringify(input), + // The session cookie goes to the CRM's own site and nowhere else. + credentials: 'same-origin', + signal: more?.signal ?? null, + }) + + const body = await response.json().catch(() => null) + + if (!response.ok) { + const refusal = refusalShape.safeParse(body) + + throw new SpoolsError( + response.status, + refusal.success ? refusal.data.error.code : 'failed', + refusal.success ? refusal.data.error.message : `The server answered ${response.status}`, + ) + } + + const answer = answerShape.safeParse(body) + + if (!answer.success) { + throw new SpoolsError( + response.status, + 'failed', + 'The server answered something that is not the API', + ) + } + + // `name` is an operation of this server's, and an operation's answer is what its own definition says it + // returns, as JSON carries it (`Sent`). Nothing here checks it again: the server is all that could differ. + const data: AnswerOf = answer.data.data + return data + } + + /** The records of one object, typed by its fields. Each is the operation of the same name. */ + const records = (objectKey: K) => ({ + /** A record with its timeline, related records, tasks and notes. */ + get: async (id: string, more?: CallOptions) => { + const answer: RecordAnswer = await call( + 'records.get', + { objectKey, id }, + more, + ) + + return answer + }, + /** A page of records: searched, filtered and sorted as `query` says. */ + list: async (query: Omit, 'objectKey'> = {}, more?: CallOptions) => { + const answer: ListAnswer = await call( + 'records.list', + { ...query, objectKey }, + more, + ) + + return answer + }, + create: (values: C[K]['values'], more?: CallOptions) => + call('records.create', { objectKey, values }, more), + update: (id: string, values: Partial, more?: CallOptions) => + call('records.update', { objectKey, id, values }, more), + delete: (id: string, more?: CallOptions) => call('records.delete', { objectKey, id }, more), + }) + + return { call, records } +} + +/** What `records.get` answers, with the record as its object's type. */ +export type RecordAnswer = Omit, 'record'> & { record: R | null } + +/** What `records.list` answers, with its rows as their object's type. */ +export type ListAnswer = Omit, 'rows'> & { rows: Listed[] } diff --git a/packages/spools/src/crm/codegen-types.ts b/packages/spools/src/crm/codegen-types.ts new file mode 100644 index 0000000..53787cd --- /dev/null +++ b/packages/spools/src/crm/codegen-types.ts @@ -0,0 +1,165 @@ +import type { CrmConfig } from './config-schema' +import { idsKey } from './links' + +/** + * The types of a Spool's records, written from its config for a front end of + * the app's own (`spools gen` puts them in src/crm.types.ts). For each object: + * the record as the HTTP API gives it, and the values creating or changing one + * takes. `Crm` lists them by object key, which is what the client is typed + * with: `createClient(...)` (src/client.ts). + * + * The types say how values travel as JSON: a date is text, money is a decimal + * in text ("1500.00"), and a relation is the related record's id under + * `Id` with the record itself beside it under ``. + * + * Pure: the config in, text out. + */ + +type Field = CrmConfig['objects'][string]['fields'][string] + +const TEXT = new Set(['text', 'longtext', 'email', 'phone', 'url', 'user']) + +/** A string as a TypeScript literal. */ +const literal = (value: string) => `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'` + +/** A name as a type's: "Work order" is `WorkOrder`. */ +const pascal = (name: string) => + name + .split(/[^A-Za-z0-9]+/) + .filter((word) => word.length > 0) + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join('') + +/** A type name for each object: its label, or its key where a label gives none or one already taken. */ +export function typeNames(config: CrmConfig) { + const names = new Map() + const taken = new Set(['Crm', 'RecordBase', 'Related', 'LinksChange']) + + for (const [key, object] of Object.entries(config.objects)) { + const fromLabel = pascal(object.label) + const wanted = /^[A-Z]/.test(fromLabel) ? fromLabel : pascal(key) + const name = taken.has(wanted) || taken.has(`${wanted}Values`) ? `${pascal(key)}Record` : wanted + + taken.add(name) + taken.add(`${name}Values`) + names.set(key, name) + } + + return names +} + +/** What a field holds when it is read: its type, without the `null` an empty one is. */ +function held(field: Field): string { + if (TEXT.has(field.type) || field.type === 'date' || field.type === 'datetime') { + return 'string' + } + + switch (field.type) { + case 'number': + return 'number' + case 'currency': + return 'string' + case 'boolean': + return 'boolean' + case 'select': + return field.options.map((option) => literal(option.value)).join(' | ') + default: + return 'string' + } +} + +/** What a field takes when it is written. Money may be sent as a number. */ +const taken = (field: Field) => (field.type === 'currency' ? 'number | string' : held(field)) + +const doc = (field: Field, indent = ' ') => + field.description ? `${indent}/** ${field.description.replace(/\*\//g, '* /')} */\n` : '' + +function recordLines(config: CrmConfig, names: Map, objectKey: string) { + const object = config.objects[objectKey] + const lines: string[] = [] + + for (const [key, field] of Object.entries(object?.fields ?? {})) { + const to = 'to' in field ? names.get(field.to) : undefined + + if (field.type === 'relation') { + lines.push(`${doc(field)} ${key}Id: string${field.required ? '' : ' | null'}`) + + lines.push( + ` /** The related record: whole on a record's own page, its title only in a list. */`, + ) + + lines.push(` ${key}?: Related<${to ?? 'RecordBase'}> | null`) + } else if (field.type === 'relations') { + lines.push(`${doc(field)} ${key}?: Related<${to ?? 'RecordBase'}>[]`) + lines.push(` ${idsKey(key)}?: string[]`) + lines.push(` /** How many there are, when a list brought back only the first few. */`) + lines.push(` ${key}Count?: number`) + } else { + lines.push(`${doc(field)} ${key}: ${held(field)}${field.required ? '' : ' | null'}`) + } + } + + return lines +} + +function valueLines(config: CrmConfig, objectKey: string) { + const object = config.objects[objectKey] + const lines: string[] = [] + + for (const [key, field] of Object.entries(object?.fields ?? {})) { + // Only the server's own code writes a read-only field. + if (field.readonly) { + continue + } + + if (field.type === 'relations') { + lines.push(` ${idsKey(key)}?: string[] | LinksChange`) + } else { + const name = field.type === 'relation' ? `${key}Id` : key + // Required to make one, unless the config fills it in. + const must = field.required && !('default' in field && field.default !== undefined) + lines.push(` ${name}${must ? '' : '?'}: ${taken(field)}${field.required ? '' : ' | null'}`) + } + } + + return lines +} + +/** The text of src/crm.types.ts for a config. */ +export function generateTypes(config: CrmConfig): string { + const names = typeNames(config) + const keys = Object.keys(config.objects) + + const blocks = keys.flatMap((key) => { + const name = names.get(key) ?? pascal(key) + const object = config.objects[key] + + return [ + `/** ${object?.label ?? key}: a record of \`${key}\`, as the API gives one. */`, + `export type ${name} = RecordBase & {`, + ...recordLines(config, names, key), + '}', + '', + `/** What making a record of \`${key}\` takes. Changing one takes any part of it. */`, + `export type ${name}Values = {`, + ...valueLines(config, key), + '}', + '', + ] + }) + + return [ + '// Generated by `spools gen` from crm.config.json. Do not edit: change the config and run it again.', + "import type { LinksChange, RecordBase, Related } from '@swirls/spools/client'", + '', + ...blocks, + '/** Every object of this CRM, by its key: what `createClient()` is typed with. */', + 'export type Crm = {', + ...keys.map( + (key) => + ` ${/^[A-Za-z_$][\w$]*$/.test(key) ? key : literal(key)}: { record: ${names.get(key)}; values: ${names.get(key)}Values }`, + ), + '}', + '', + ].join('\n') +} diff --git a/packages/spools/src/headless.ts b/packages/spools/src/headless.ts new file mode 100644 index 0000000..b319fc3 --- /dev/null +++ b/packages/spools/src/headless.ts @@ -0,0 +1,174 @@ +import { assistantHandlers } from './api/assistant' +import { assistantStreamHandlers } from './api/assistant-stream' +import { authHandlers } from './api/auth' +import { emailWebhookHandlers } from './api/email-webhook' +import { fileHandlers } from './api/file' +import { integrationCallbackHandlers } from './api/integration-callback' +import { integrationConnectHandlers } from './api/integration-connect' +import { mailSyncHandlers } from './api/mail-sync' +import { marketingHandlers } from './api/marketing' +import { sequencesHandlers } from './api/sequences' +import { toolsHandlers } from './api/tools' +import { unsubscribeHandlers } from './api/unsubscribe' +import { uploadHandlers } from './api/upload' +import { warmHandlers } from './api/warm' +import { bootSpool } from './server/entry' +import { withSecurityHeaders } from './server/headers' +import { fromThisSite, httpApi, type HttpApiOptions } from './server/http' + +/** + * A whole Spool with no interface of its own and no web framework: the server + * a front end of someone else's design talks to. One handler, for `Bun.serve` + * or anything else that speaks `Request` and `Response`: + * + * // after src/spool.server.ts has defined the Spool + * const spools = headlessServer() + * Bun.serve({ port: 3000, fetch: (request) => spools.fetch(request) }) + * + * It answers what a Spool on TanStack Start answers, at the same addresses, + * except the pages: + * + * /api/v1/* every operation (src/server/http.ts) + * /api/auth/* the auth adapter's own sign-in, when it has one + * /api/files/* downloads, and uploads relayed through the server + * /api/assistant* the assistant's chat + * /api/integrations/* connecting an account (OAuth) + * /api/swirls/tools/* the tool API workflows and the assistant call + * /api/webhooks/email bounces and complaints from the email service + * /api/cron/* what a scheduler calls on a serverless host + * /unsubscribe (POST) one-click unsubscribe from an email + * /healthz + * + * and starts what a Spool's server starts (the schedules, the start-up checks). + * The pages those addresses once led back to (after sign-in, after connecting an + * account, the unsubscribe page) are the front end's to draw. + */ + +export type HeadlessOptions = HttpApiOptions + +type Found = Readonly> +type Answer = (request: Request, found: Found) => Promise + +/** The methods a route answers, each given the request and the route's own params. */ +type Handlers

= Partial< + Record Promise> +> + +/** + * A route: an address with `:name` for a part that varies and a trailing `*` + * for the rest, and the handlers that answer there (src/api), given their + * params as they name them. + */ +const route =

(pattern: string, handlers: Handlers

, params: (found: Found) => P) => { + const source = pattern + .replace(/[.+?^${}()|[\]\\]/g, '\\$&') + .replace(/:(\w+)/g, '(?<$1>[^/]+)') + .replace(/\/\*$/, '/(?.*)') + + const address = new RegExp(`^${source}$`) + + const answer: Answer = (request, found) => { + const handler = handlers[request.method] + + return handler + ? handler({ request, params: params(found) }) + : Promise.resolve( + new Response('Method not allowed', { + status: 405, + headers: { Allow: Object.keys(handlers).join(', ') }, + }), + ) + } + + return { address, answer } +} + +const none = () => ({}) + +/** A part of the address, decoded. One that isn't an address at all is no part: nothing answers to "". */ +const part = (found: Found, name: string) => { + try { + return decodeURIComponent(found[name] ?? '') + } catch { + return '' + } +} + +const routes = [ + route('/api/auth/*', authHandlers, none), + route('/api/assistant', assistantHandlers, none), + route('/api/assistant/:sessionId/stream', assistantStreamHandlers, (found) => ({ + sessionId: part(found, 'sessionId'), + })), + route('/api/files/uploads/:id', uploadHandlers, (found) => ({ id: part(found, 'id') })), + route('/api/files/:id', fileHandlers, (found) => ({ id: part(found, 'id') })), + route('/api/integrations/:provider/connect', integrationConnectHandlers, (found) => ({ + provider: part(found, 'provider'), + })), + route('/api/integrations/:provider/callback', integrationCallbackHandlers, (found) => ({ + provider: part(found, 'provider'), + })), + route('/api/swirls/tools/:tool', toolsHandlers, (found) => ({ tool: part(found, 'tool') })), + route('/api/webhooks/email', emailWebhookHandlers, none), + route('/api/cron/mail-sync', mailSyncHandlers, none), + route('/api/cron/sequences', sequencesHandlers, none), + route('/api/cron/marketing', marketingHandlers, none), + route('/api/cron/warm', warmHandlers, none), + route('/unsubscribe', unsubscribeHandlers, none), +] + +/** + * The addresses a signed-in browser's cookie alone opens for a change, besides + * the HTTP API (which checks for itself): another site's page must not reach + * them through someone's browser. On TanStack Start its CSRF middleware does this. + */ +const cookieOnly = (path: string) => path === '/api/assistant' || path.startsWith('/api/assistant/') + +/** A Spool's server with no web framework. Call once, after src/spool.server.ts has defined the Spool. */ +export function headlessServer(options: HeadlessOptions = {}) { + const base = (options.basePath ?? '/api/v1').replace(/\/+$/, '') + const api = httpApi(options) + + bootSpool() + + const answer = (request: Request): Promise => { + const path = new URL(request.url).pathname + + if (path === '/healthz') { + return Promise.resolve(new Response('ok')) + } + + if (path === base || path.startsWith(`${base}/`)) { + return api(request) + } + + if (cookieOnly(path) && !fromThisSite(request)) { + return Promise.resolve(new Response('Forbidden', { status: 403 })) + } + + for (const { address, answer: answerAt } of routes) { + const found = address.exec(path) + + if (found) { + return answerAt(request, found.groups ?? {}) + } + } + + return Promise.resolve(Response.json({ error: 'Not found' }, { status: 404 })) + } + + return { + fetch: async (request: Request): Promise => { + try { + return withSecurityHeaders(await answer(request)) + } catch (error) { + // Whoever asked went away: nobody is waiting for an answer. + if (request.signal.aborted) { + return new Response(null, { status: 499 }) + } + + throw error + } + }, + } +} diff --git a/packages/spools/src/server/api-keys.ts b/packages/spools/src/server/api-keys.ts new file mode 100644 index 0000000..46bee0d --- /dev/null +++ b/packages/spools/src/server/api-keys.ts @@ -0,0 +1,321 @@ +import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto' + +import { Clock, Effect } from 'effect' +import { z } from 'zod' + +import { Auth } from './runtime/auth' +import { Invalid, NotFound } from './runtime/errors' +import { Vault } from './runtime/vault' +import { isNull, lte, or } from './store/query' +import { Store } from './store/store' +import { ApiKey } from './store/tables' +import { toCrmUser } from './users' + +/** + * API keys: how a script or another service calls the HTTP API (src/server/http.ts) + * with nobody at a browser. A key is sent as `Authorization: Bearer spk_...`. + * + * A key is not a new kind of caller. It acts as one teammate: on the access + * list like them (a key whose teammate was taken off it opens nothing), in the + * record scopes they hold, with what their roles let them reach. What a key can + * do is therefore decided where everything else is, and a key can be narrowed + * further to reading only. + * + * A key is `spk__`. The id finds its row; the secret is 32 random + * bytes. What is kept is sealed by the Spool's vault (CipherStash), for that + * row alone: the secret's SHA-256 together with everything the key may do + * (whose it is, whether it only reads, when it ends). The seal is what a key is + * judged by, never the row's own columns, which are there to list it. So: + * + * - reading the table gives nobody a key that works; + * - writing to the table gives nobody one either. A row someone inserts has no + * seal the vault made, one copied from another row was sealed for that row, + * and a row whose teammate, reach or expiry someone changes no longer says + * what its seal says, and is refused; + * - a revoked key's seal is wiped, so clearing `revokedAt` brings nothing back. + * + * A Spool with no vault has no keys: none is made and none is taken. + * + * Checking one is a read by id, whatever a stranger sends: only a key whose + * row exists is opened by the vault, and what it opened is remembered for a + * minute, so a busy key is not a call to the vault on every request. A made-up + * key is told no more than "no". + * + * Keys are off unless the HTTP API is told to take them (`keys: true`), and + * every key ends: after `DEFAULT_DAYS` unless whoever makes it says otherwise, + * out loud. They are made, listed and revoked from the app's folder + * (`spools keys`), by whoever can run commands there with its environment. + */ + +const PREFIX = 'spk_' +const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ +const SECRET = /^[A-Za-z0-9_-]{43}$/ + +/** How stale "last used" may be: one write every few minutes for a busy key, not one a request. */ +const USED_EVERY_MS = 5 * 60_000 + +/** How long a key works for unless whoever makes it says. */ +export const DEFAULT_DAYS = 90 + +/** How long what the vault opened is remembered, and for how many keys at most. */ +const OPENED_FOR_MS = 60_000 +const OPENED_AT_MOST = 1000 + +const hashOf = (secret: string) => createHash('sha256').update(secret).digest('hex') + +/** What a key's seal holds: the hash of its secret, and all it may do. Moments are milliseconds. */ +const Seal = z.object({ + v: z.literal(1), + hash: z.string(), + userId: z.string(), + readOnly: z.boolean(), + expiresAt: z.number().nullable(), +}) + +type Seal = z.infer + +/** What a seal is for: its own row, so one copied to another row opens nothing there. */ +const ownerOf = (id: string) => `api-key:${id}` + +/** What a row says its key may do. */ +type Says = { + readonly id: string + readonly userId: string + readonly readOnly: boolean + readonly expiresAt: Date | null +} + +/** A key's seal, made by the vault for the row it will be kept on. */ +export const sealKey = Effect.fn('apiKeys.sealKey')(function* (row: Says, secret: string) { + return yield* (yield* Vault).seal( + { + v: 1, + hash: hashOf(secret), + userId: row.userId, + readOnly: row.readOnly, + expiresAt: row.expiresAt === null ? null : row.expiresAt.getTime(), + }, + ownerOf(row.id), + ) +}) + +/** + * Seals the vault opened lately, by the sealed text itself: a row that changes + * is a seal not seen. It holds no secret, only what a key may do and the hash + * of its secret. + */ +const opened = new Map() + +const openSeal = Effect.fn('apiKeys.openSeal')(function* (id: string, sealed: string, now: number) { + const known = opened.get(sealed) + + if (known && now - known.at < OPENED_FOR_MS) { + return known.seal + } + + const { value } = yield* (yield* Vault).open(sealed, ownerOf(id), Seal) + + if (opened.size >= OPENED_AT_MOST) { + opened.clear() + } + + opened.set(sealed, { seal: value, at: now }) + return value +}) + +/** Whether a bearer token is shaped like an API key, so the HTTP API knows which check it is for. */ +export const isApiKey = (token: string): boolean => token.startsWith(PREFIX) + +/** A key's id and secret, or null for anything not shaped like one. */ +const parts = (token: string) => { + const rest = token.slice(PREFIX.length) + const id = rest.slice(0, 36) + const secret = rest.slice(37) + + return isApiKey(token) && rest[36] === '_' && ID.test(id) && SECRET.test(secret) + ? { id, secret } + : null +} + +/** A key as it is listed: everything but what would let someone use it. */ +export type KeyInfo = { + readonly id: string + readonly name: string + readonly userId: string + readonly readOnly: boolean + readonly createdAt: Date + readonly expiresAt: Date | null + readonly revokedAt: Date | null + readonly lastUsedAt: Date | null +} + +const infoOf = (row: NonNullable): KeyInfo => ({ + id: row.id, + name: row.name, + userId: row.userId, + readOnly: row.readOnly, + createdAt: row.createdAt, + expiresAt: row.expiresAt, + revokedAt: row.revokedAt, + lastUsedAt: row.lastUsedAt, +}) + +/** Who a key acts as, and whether it may only read. */ +export type KeyHolder = { readonly userId: string; readonly readOnly: boolean } + +/** + * Who a key acts as, or null: not a key, unknown, revoked, expired, or its + * secret is wrong. Whether that teammate may still use the CRM is checked where + * it is for everyone (`forStaff`), not here. + */ +export const keyHolder = Effect.fn('apiKeys.keyHolder')(function* (token: string) { + const sent = parts(token) + + if (!sent) { + return null + } + + // A Spool with no vault has no keys. + if ((yield* (yield* Vault).problem) !== null) { + return null + } + + const store = yield* Store + const now = yield* Clock.currentTimeMillis + const key = yield* store.first(ApiKey, { where: { id: sent.id } }) + + // No such key, or one revoked (its seal is gone with it): nothing for the vault to open. + if (!key || key.revokedAt !== null || key.digest === '') { + return null + } + + // A seal the vault can't open (a row written by hand, a seal moved here from another row) fails + // here, and whoever asked is told no more than that something went wrong. + const seal = yield* openSeal(key.id, key.digest, now) + + const sent256 = Buffer.from(hashOf(sent.secret), 'hex') + const kept256 = Buffer.from(seal.hash, 'hex') + + if (kept256.length !== sent256.length || !timingSafeEqual(sent256, kept256)) { + return null + } + + // The seal is what the key may do. A row that says otherwise has been changed since. + const says = key.expiresAt === null ? null : key.expiresAt.getTime() + + if (seal.userId !== key.userId || seal.readOnly !== key.readOnly || seal.expiresAt !== says) { + return null + } + + if (seal.expiresAt !== null && seal.expiresAt <= now) { + return null + } + + // One conditional write now and then: of many requests at once, one makes it. + yield* store.update( + ApiKey, + { + where: { id: key.id }, + filter: or(isNull('lastUsedAt'), lte('lastUsedAt', new Date(now - USED_EVERY_MS))), + }, + { lastUsedAt: new Date(now) }, + ) + + return { userId: seal.userId, readOnly: seal.readOnly } satisfies KeyHolder +}) + +export type NewKey = { + /** What it is for. */ + readonly name: string + /** The email of the teammate it acts as. */ + readonly email: string + readonly readOnly?: boolean + /** How many days it works for: `DEFAULT_DAYS` unless this says. */ + readonly days?: number + /** A key that works until it is revoked. Never the default: it has to be asked for. */ + readonly neverExpires?: boolean +} + +/** + * Makes a key for a teammate on the access list. The key itself is in the + * answer and nowhere else: it can't be shown again. + */ +export const createKey = Effect.fn('apiKeys.createKey')(function* (asked: NewKey) { + const name = asked.name.trim() + const email = asked.email.trim().toLowerCase() + + if (name === '' || name.length > 80) { + return yield* new Invalid({ message: 'Give the key a name of up to 80 characters' }) + } + + if (asked.days !== undefined && !(Number.isInteger(asked.days) && asked.days >= 1)) { + return yield* new Invalid({ message: 'A key expires after a whole number of days, 1 or more' }) + } + + if (asked.neverExpires && asked.days !== undefined) { + return yield* new Invalid({ message: 'A key expires after some days or never: say one' }) + } + + const problem = yield* (yield* Vault).problem + + if (problem !== null) { + return yield* new Invalid({ message: `API keys are kept sealed by the vault. ${problem}` }) + } + + const people = yield* (yield* Auth).listUsers + const person = people.map(toCrmUser).find((user) => user?.email.toLowerCase() === email) + + if (!person) { + return yield* new Invalid({ + message: `${asked.email} is not a teammate who can use this CRM: they must have signed in once, and be on the access list`, + }) + } + + const now = yield* Clock.currentTimeMillis + const secret = randomBytes(32).toString('base64url') + + const sealed = { + id: randomUUID(), + userId: person.id, + readOnly: asked.readOnly ?? false, + expiresAt: asked.neverExpires + ? null + : new Date(now + (asked.days ?? DEFAULT_DAYS) * 86_400_000), + } + + const row = yield* (yield* Store).insert(ApiKey, { + ...sealed, + name, + digest: yield* sealKey(sealed, secret), + }) + + return { key: `${PREFIX}${row.id}_${secret}`, info: infoOf(row) } +}) + +/** Every key, newest first, revoked ones included. */ +export const listKeys = Effect.fn('apiKeys.listKeys')(function* () { + const rows = yield* (yield* Store).find(ApiKey, {}) + return rows.map(infoOf).toSorted((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) +}) + +/** Revokes a key, by its id. It stops working with the next request. */ +export const revokeKey = Effect.fn('apiKeys.revokeKey')(function* (id: string) { + if (!ID.test(id)) { + return yield* new NotFound({ what: 'Key' }) + } + + const now = yield* Clock.currentTimeMillis + + const changed = yield* (yield* Store).update( + ApiKey, + { where: { id }, filter: isNull('revokedAt') }, + // Its seal goes with it: a revoked key can't be brought back by clearing the date. + { revokedAt: new Date(now), digest: '' }, + ) + + if (changed === 0 && !(yield* (yield* Store).first(ApiKey, { where: { id } }))) { + return yield* new NotFound({ what: 'Key' }) + } + + return changed === 1 +}) diff --git a/packages/spools/src/server/api.ts b/packages/spools/src/server/api.ts new file mode 100644 index 0000000..74eae5a --- /dev/null +++ b/packages/spools/src/server/api.ts @@ -0,0 +1,49 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import type { OpenOperation, StaffOperation } from './operations/define' +import { forStaff } from './runtime/boundary' +import { Invalid, type StaffError } from './runtime/errors' + +/** + * Operations called from the server's own code, with no HTTP in between: a + * route of the app's own, a script, a server-rendered page of a front end that + * shares the process. The same operation the HTTP API answers + * (src/server/operations), parsed and checked the same way: + * + * const { record } = yield* callAs({ userId }, crm.getRecord, { objectKey: 'contacts', id }) + * + * `callAs` is the only way to run a staff operation here, and it takes a user + * id and nothing else: whoever it names must be on the access list, and the + * program runs in their record scopes and with their roles' access, exactly as + * if they had asked themselves. Where the id comes from is the caller's to get + * right: a session the auth adapter read, a token it verified, never the + * request's own say-so. + */ + +const parsed = (name: string, schema: S, input: z.input) => { + const result = schema.safeParse(input) + + return result.success + ? Effect.succeed(result.data) + : Effect.fail(new Invalid({ message: `${name}: ${z.prettifyError(result.error)}` })) +} + +/** Runs a staff operation as the teammate with this user id, in the scope named if they hold it. */ +export const callAs = ( + who: { readonly userId: string; readonly scope?: string | null | undefined }, + operation: StaffOperation, + input: z.input, +) => + Effect.flatMap(parsed(operation.name, operation.input, input), (data) => + forStaff(who.userId, who.scope, (user) => operation.run({ data, user })), + ).pipe(Effect.withSpan(`api.${operation.name}`)) + +/** Runs an operation that answers anyone. */ +export const callOpen = ( + operation: OpenOperation, + input: z.input, +) => + Effect.flatMap(parsed(operation.name, operation.input, input), (data) => + operation.run({ data }), + ).pipe(Effect.withSpan(`api.${operation.name}`)) diff --git a/packages/spools/src/server/assistant.functions.ts b/packages/spools/src/server/assistant.functions.ts index 18fe0dd..44af8e7 100644 --- a/packages/spools/src/server/assistant.functions.ts +++ b/packages/spools/src/server/assistant.functions.ts @@ -1,128 +1,22 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import { z } from 'zod' -import { TITLE_MAX } from '../crm/assistant' -import { assistantChat } from './assistant-chat' -import { type AssistantChat, CHATS_LISTED } from './runtime/agents' +import * as assistant from './operations/assistant' import { crmHandler } from './runtime/boundary' -import { AgentsError, Invalid, messageOf, NotConfigured } from './runtime/errors' -import { policies, withPolicy } from './runtime/policies' /** - * Sessions for the in-CRM assistant. The agent engine keeps them - * (runtime/agents.ts), so nothing here touches the database. + * The interface's way in to the assistant's chats. What each does is an + * operation (src/server/operations/assistant.ts), shared with the HTTP API; + * here it is only bound to TanStack Start. */ -const notConfigured = new NotConfigured({ - feature: 'assistant', - message: - 'The assistant is not configured (SWIRLS_PROJECT_ID, and SWIRLS_API_KEY or federation with your sign-in provider)', -}) - -/** The assistant's chat for this person, or `NotConfigured`. */ -const chatOrRefuse = assistantChat.pipe( - Effect.filterOrFail( - (chat) => chat !== null, - () => notConfigured, - ), -) - -/** A chat as the assistant's list shows it. */ -type SessionSummary = { sessionId: string; title: string | null; updatedAt: string } - -/** One call to the chat, with the engine's time limit. */ -const ask = (name: string, work: () => Promise) => - Effect.tryPromise({ - try: work, - catch: (cause) => new AgentsError({ message: messageOf(cause) }), - }).pipe( - withPolicy(policies.agentsRun, () => false), - Effect.catchTag('Timeout', (timeout) => - Effect.fail(new AgentsError({ message: timeout.message })), - ), - Effect.withSpan(`assistant.${name}`), - ) - export const assistantStateFn = createServerFn({ method: 'GET' }) - .validator(z.object({ sessionId: z.string().max(200).optional() })) - .handler( - crmHandler('assistant.state', ({ data }) => - Effect.gen(function* () { - const chat: AssistantChat | null = yield* assistantChat - - if (!chat) { - const none: SessionSummary[] = [] - return { - configured: false as const, - canRegenerate: false, - sessions: none, - messagesJson: '[]', - } - } - - const { sessionId } = data - - const [sessions, history] = yield* Effect.all( - [ - ask('listSessions', () => chat.listSessions({ limit: CHATS_LISTED })), - sessionId - ? ask('getMessages', () => chat.getMessages(sessionId)) - : Effect.succeed({ messages: [] }), - ], - { concurrency: 2 }, - ) - - return { - configured: true as const, - canRegenerate: chat.regenerate, - sessions: sessions.map((s) => ({ - sessionId: s.sessionId, - title: s.title, - updatedAt: s.updatedAt.toISOString(), - })), - // UIMessage carries `unknown` metadata, which Start cannot type-check as serializable. - messagesJson: JSON.stringify(history.messages), - } - }), - ), - ) + .validator(assistant.state.input) + .handler(crmHandler(assistant.state.name, assistant.state.run)) export const createAssistantSessionFn = createServerFn({ method: 'POST' }) - // A chat is titled from its first message (`titleFrom`); a longer title is one that was not made by the page. - .validator( - z.object({ - title: z - .string() - .trim() - .min(1) - .max(TITLE_MAX + 1) - .optional(), - }), - ) - .handler( - crmHandler('assistant.createSession', ({ data }) => - Effect.flatMap(chatOrRefuse, (chat) => - ask('createSession', () => chat.createSession({ title: data.title ?? null })), - ), - ), - ) + .validator(assistant.createSession.input) + .handler(crmHandler(assistant.createSession.name, assistant.createSession.run)) export const deleteAssistantSessionFn = createServerFn({ method: 'POST' }) - .validator(z.object({ sessionId: z.string().min(1).max(200) })) - .handler( - crmHandler('assistant.deleteSession', ({ data }) => - Effect.gen(function* () { - const chat = yield* chatOrRefuse - // Only a chat this person is shown may be deleted by them: the id alone is not enough. - const listed = yield* ask('listSessions', () => chat.listSessions({ limit: CHATS_LISTED })) - - if (!listed.some((s) => s.sessionId === data.sessionId)) { - return yield* new Invalid({ message: 'That chat is not in your list' }) - } - - const deleted = yield* ask('deleteSession', () => chat.deleteSession(data.sessionId)) - return { deleted } - }), - ), - ) + .validator(assistant.deleteSession.input) + .handler(crmHandler(assistant.deleteSession.name, assistant.deleteSession.run)) diff --git a/packages/spools/src/server/callers.ts b/packages/spools/src/server/callers.ts index eaafc44..da9d714 100644 --- a/packages/spools/src/server/callers.ts +++ b/packages/spools/src/server/callers.ts @@ -88,9 +88,13 @@ export const verifyToken = Effect.fn('callers.verifyToken')(function* ( .map((party) => party.trim().replace(/\/+$/, '')) .filter((party) => party.length > 0) - if (parties.length === 0 && !(yield* isDevelopment())) { + const tokens = yield* Tokens + + // A provider's token says which front end it was issued to, and production takes none unless + // the app names whose count. A server's own session token has no such front end to name. + if (parties.length === 0 && !tokens.own && !(yield* isDevelopment())) { return null } - return yield* (yield* Tokens).verify(token, { authorizedParties: parties }) + return yield* tokens.verify(token, { authorizedParties: parties }) }) diff --git a/packages/spools/src/server/crm.functions.ts b/packages/spools/src/server/crm.functions.ts index b8ca68d..77c9207 100644 --- a/packages/spools/src/server/crm.functions.ts +++ b/packages/spools/src/server/crm.functions.ts @@ -1,330 +1,83 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import { z } from 'zod' -import { toPublicConfig } from '../crm/config' -import { runTarget } from './actions' -import * as guides from './guides' -import { accessOfPerson, mustEdit, withObjectAccess } from './object-access' -import * as records from './records' -import * as roles from './roles' -import { CurrentRequest } from './runtime/app' -import { crmHandler, publicHandler, signedInUser, wanted as wantedIn } from './runtime/boundary' -import { Invalid, NotFound } from './runtime/errors' -import { asUser, scopeSession } from './scopes' -import * as search from './search' -import * as service from './service' -import { changedSinceFor, changedSinceInput } from './signals' -import { crmConfig, getObject, spool } from './spool' -import { Users } from './users' -import * as workspace from './workspace' +import * as crm from './operations/crm' +import { crmHandler, publicHandler } from './runtime/boundary' /** - * The only bridge between the browser and CRM data. Every function here - * re-checks the session and the config access allowlist. + * The interface's way in to records, search and the session. What each does + * is an operation (src/server/operations/crm.ts), shared with the HTTP API; + * here it is only bound to TanStack Start. Every function re-checks the + * session and the config access allowlist (`crmHandler`). */ -const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') -const recordRef = z.object({ objectKey, id: z.string().uuid() }) - export const getCrmSession = createServerFn({ method: 'GET' }).handler( - publicHandler('crm.getCrmSession', () => - Effect.gen(function* () { - const user = yield* signedInUser - - // The team list feeds owner/assignee pickers; skip asking for it when no object has a `user` field. - const hasUserFields = Object.values(crmConfig().objects).some((o) => - Object.values(o.fields).some((f) => f.type === 'user'), - ) - - // What this person has seen of the guides rides along, so no page asks for it separately. - const nothingSeen: string[] = [] - const signedInAs = (yield* signedInSession) || user !== null - const offers = yield* guides.guidesOffered - - if (!user) { - return { - signedIn: signedInAs, - user, - config: null, - users: [], - favorites: [], - dueTasks: 0, - guides: { seen: nothingSeen, offers }, - scopes: null, - roles: { held: nothingSeen, admin: false }, - access: null, - } - } - - // A session answers signed-out pages too, so the boundary gave it no scope: it takes its own. - const request = yield* CurrentRequest - const wanted = wantedIn(request.session, request.headers) - - const access = yield* accessOfPerson(user) - - const [users, favorites, dueTasks, seen] = yield* asUser( - user, - wanted, - )( - withObjectAccess(access)( - Effect.all( - [ - // The team list feeds owner/assignee pickers; skip asking for it when no object has a `user` field. - hasUserFields ? Effect.flatMap(Users, (all) => all.team) : Effect.succeed([]), - workspace.listFavorites(user.id), - workspace.dueTaskCount(user.id), - guides.seenGuides(user.id), - ], - { concurrency: 'unbounded' }, - ), - ), - ) - - return { - signedIn: signedInAs, - user, - config: toPublicConfig(crmConfig()), - users, - favorites, - dueTasks, - guides: { seen, offers }, - // The scopes this person may switch between, in a Spool that has them. - scopes: yield* scopeSession(user, wanted), - // What they do, and whether they set what others do, in a Spool with roles. - roles: yield* roles.roleSession(user), - // The objects their roles keep from them, and the ones they only read (docs/roles.md#access). - access, - } - }), - ), -) - -/** Whether anyone is signed in, allowed in or not. */ -const signedInSession = Effect.map( - Effect.serviceOption(CurrentRequest), - (request) => request._tag === 'Some' && request.value.session !== null, + publicHandler(crm.session.name, crm.session.run), ) -/** What every page needs, signed in or not: the business's name, and which auth provider signs people in. */ export const getBrandFn = createServerFn({ method: 'GET' }).handler( - publicHandler('crm.getBrand', () => - Effect.sync(() => ({ name: crmConfig().app.name, auth: spool().auth.id })), - ), + publicHandler(crm.brand.name, crm.brand.run), ) -/** These answers hold people's names and messages: no browser, proxy or CDN may keep a copy. */ -const neverStore = { headers: { 'Cache-Control': 'private, no-store' } } - -/** - * What the search box matches in the browser: every record's title, summary - * line and unencrypted searchable fields. With `since`, only what changed after it. - */ export const searchIndexFn = createServerFn({ method: 'GET' }) - .validator(z.object({ since: z.string().datetime().optional() })) + .validator(crm.searchIndex.input) .handler( - crmHandler( - 'crm.searchIndex', - ({ data, user }) => - Effect.gen(function* () { - // As one JSON string: thousands of small arrays cost far more to carry as a structured value. - return JSON.stringify( - yield* search.quickIndex(data.since ? new Date(data.since) : undefined, user.id), - ) - }), - neverStore, - ), + crmHandler(crm.searchIndex.name, crm.searchIndex.run, { headers: crm.searchIndex.headers }), ) -/** Matches the browser can't find itself: other fields, and the text of notes, emails, calls and tasks. */ export const searchDeepFn = createServerFn({ method: 'GET' }) - .validator(z.object({ q: z.string().trim().min(1).max(200) })) - .handler(crmHandler('crm.searchDeep', ({ data }) => search.deepSearch(data.q), neverStore)) + .validator(crm.searchDeep.input) + .handler(crmHandler(crm.searchDeep.name, crm.searchDeep.run, { headers: crm.searchDeep.headers })) -/** Values of an object's text fields that contain what was typed, to offer as filters. */ -/** - * Whether what a page shows changed since it last asked (src/server/signals.ts): - * the list, board and record pages ask this to refresh behind the scenes - * (src/crm/ui/live.ts). A key the person can't read says nothing. - */ export const changedSinceFn = createServerFn({ method: 'GET' }) - .validator(changedSinceInput) - .handler(crmHandler('crm.changedSince', ({ data }) => changedSinceFor(data), neverStore)) + .validator(crm.changedSince.input) + .handler( + crmHandler(crm.changedSince.name, crm.changedSince.run, { headers: crm.changedSince.headers }), + ) export const suggestValuesFn = createServerFn({ method: 'GET' }) - .validator(z.object({ objectKey, q: z.string().trim().min(1).max(100) })) + .validator(crm.suggestValues.input) .handler( - crmHandler( - 'crm.suggestValues', - ({ data }) => search.suggestValues(data.objectKey, data.q), - neverStore, - ), + crmHandler(crm.suggestValues.name, crm.suggestValues.run, { + headers: crm.suggestValues.headers, + }), ) export const deleteRecordsFn = createServerFn({ method: 'POST' }) - .validator(z.object({ objectKey, ids: z.array(z.string().uuid()).min(1).max(200) })) - .handler( - crmHandler('crm.deleteRecords', ({ data, user }) => - Effect.gen(function* () { - let deleted = 0 - - for (const id of data.ids) { - if (yield* service.deleteRecord(data.objectKey, id, user)) { - deleted++ - } - } - - return { deleted } - }), - ), - ) + .validator(crm.deleteRecords.input) + .handler(crmHandler(crm.deleteRecords.name, crm.deleteRecords.run)) export const getRecordFn = createServerFn({ method: 'GET' }) - .validator(recordRef) - .handler( - crmHandler('crm.getRecord', ({ data, user }) => - Effect.gen(function* () { - const [record, activities, related, tasks, notes, favorite] = yield* Effect.all( - [ - records.getRecord(data.objectKey, data.id), - records.listActivities(data.objectKey, data.id), - records.relatedRecords(data.objectKey, data.id), - workspace.listTasks({ objectKey: data.objectKey, recordId: data.id }), - workspace.listNotes({ objectKey: data.objectKey, recordId: data.id }), - workspace.isFavorite(user.id, data.objectKey, data.id), - ], - { concurrency: 'unbounded' }, - ) + .validator(crm.getRecord.input) + .handler(crmHandler(crm.getRecord.name, crm.getRecord.run)) - return { record, activities, related, tasks, notes, favorite } - }), - ), - ) - -/** One page of an object's titles for a relation picker, narrowed by what has been typed. */ export const searchRelationFn = createServerFn({ method: 'GET' }) - .validator(z.object({ objectKey, q: z.string().max(200).default('') })) - .handler( - crmHandler('crm.searchRelation', ({ data }) => records.searchTitles(data.objectKey, data.q)), - ) + .validator(crm.searchRelation.input) + .handler(crmHandler(crm.searchRelation.name, crm.searchRelation.run)) -/** The titles of records a page holds only the ids of (a preset value, a saved filter). */ export const relationTitlesFn = createServerFn({ method: 'GET' }) - .validator(z.object({ objectKey, ids: z.array(z.string().uuid()).min(1).max(100) })) - .handler( - crmHandler('crm.relationTitles', ({ data }) => - Effect.gen(function* () { - const titles = yield* records.recordTitlesOf(data.objectKey, data.ids) - return [...titles].map(([id, title]) => ({ id, title })) - }), - ), - ) + .validator(crm.relationTitles.input) + .handler(crmHandler(crm.relationTitles.name, crm.relationTitles.run)) -/** - * Which of the records a picker lists a record holds in a relations field. The - * page has the first of a record's links only, so for one that holds more it - * asks about the ones it is about to show ticked or unticked. - */ export const heldLinksFn = createServerFn({ method: 'GET' }) - .validator( - recordRef.extend({ - field: z.string().max(200), - ids: z.array(z.string().uuid()).min(1).max(100), - }), - ) - .handler( - crmHandler('crm.heldLinks', ({ data }) => - records.linkedAmong(data.objectKey, data.id, data.field, data.ids), - ), - ) + .validator(crm.heldLinks.input) + .handler(crmHandler(crm.heldLinks.name, crm.heldLinks.run)) export const createRecordFn = createServerFn({ method: 'POST' }) - .validator(z.object({ objectKey, values: z.record(z.string(), z.unknown()) })) - .handler( - crmHandler('crm.createRecord', ({ data, user }) => - Effect.gen(function* () { - const record = yield* service.createRecord(data.objectKey, data.values, user) - return { id: record.id } - }), - ), - ) + .validator(crm.createRecord.input) + .handler(crmHandler(crm.createRecord.name, crm.createRecord.run)) export const updateRecordFn = createServerFn({ method: 'POST' }) - .validator(recordRef.extend({ values: z.record(z.string(), z.unknown()) })) - .handler( - crmHandler('crm.updateRecord', ({ data, user }) => - Effect.gen(function* () { - const record = yield* service.updateRecord(data.objectKey, data.id, data.values, user) - - if (!record) { - return yield* new NotFound({ what: 'Record' }) - } - - return { id: record.id } - }), - ), - ) + .validator(crm.updateRecord.input) + .handler(crmHandler(crm.updateRecord.name, crm.updateRecord.run)) export const deleteRecordFn = createServerFn({ method: 'POST' }) - .validator(recordRef) - .handler( - crmHandler('crm.deleteRecord', ({ data, user }) => - Effect.gen(function* () { - yield* service.deleteRecord(data.objectKey, data.id, user) - return { ok: true } - }), - ), - ) + .validator(crm.deleteRecord.input) + .handler(crmHandler(crm.deleteRecord.name, crm.deleteRecord.run)) export const runActionFn = createServerFn({ method: 'POST' }) - .validator(recordRef.extend({ actionId: z.string() })) - .handler( - crmHandler('crm.runAction', ({ data, user }) => - Effect.gen(function* () { - const action = getObject(data.objectKey).actions.find((a) => a.id === data.actionId) - - if (!action) { - return yield* new Invalid({ message: 'Unknown action' }) - } - - const record = yield* records.getRecord(data.objectKey, data.id) - - if (!record) { - return yield* new NotFound({ what: 'Record' }) - } - - // An action changes things, or sends them: someone who may only read these records can't start one. - yield* mustEdit(data.objectKey) - - return yield* runTarget(action.run, { - objectKey: data.objectKey, - record, - actor: user, - trigger: `action:${action.id}`, - }) - }), - ), - ) + .validator(crm.runAction.input) + .handler(crmHandler(crm.runAction.name, crm.runAction.run)) export const dashboardFn = createServerFn({ method: 'GET' }).handler( - crmHandler('crm.dashboard', ({ user }) => - Effect.gen(function* () { - const [counts, activities, tasks, pipeline] = yield* Effect.all( - [ - records.countRecords(), - records.recentActivities(12), - workspace.listTasks({ assigneeId: user.id }), - Effect.flatMap(roles.rolesOf(user), (held) => workspace.pipelineSummary(user.id, held)), - ], - { concurrency: 'unbounded' }, - ) - - return { - counts, - activities, - tasks: tasks.filter((t) => !t.completedAt).slice(0, 8), - pipeline, - } - }), - ), + crmHandler(crm.dashboard.name, crm.dashboard.run), ) diff --git a/packages/spools/src/server/email.functions.ts b/packages/spools/src/server/email.functions.ts index c23b061..12f6c73 100644 --- a/packages/spools/src/server/email.functions.ts +++ b/packages/spools/src/server/email.functions.ts @@ -1,32 +1,15 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import { z } from 'zod' -import { suppress, verifyUnsubscribeToken } from './email' +import * as email from './operations/email' import { publicHandler } from './runtime/boundary' -import { Invalid } from './runtime/errors' /** - * Unsubscribing, for people who aren't signed in: the page's button proves - * who they are with the signed token in the link. (Mail clients' one-click - * unsubscribe is unsubscribe-route.ts, kept apart so the page's browser code - * never imports it.) + * The interface's way in to unsubscribing, for people who aren't signed in. + * What it does is an operation (src/server/operations/email.ts), shared with + * the HTTP API; here it is only bound to TanStack Start. */ /** The Unsubscribe button on /unsubscribe. */ export const unsubscribeFn = createServerFn({ method: 'POST' }) - .validator(z.object({ token: z.string().max(1000) })) - .handler( - publicHandler('email.unsubscribe', ({ data }) => - Effect.gen(function* () { - const email = yield* verifyUnsubscribeToken(data.token) - - if (!email) { - return yield* new Invalid({ message: 'This unsubscribe link is invalid.' }) - } - - yield* suppress(email, 'unsubscribed') - return { ok: true } - }), - ), - ) + .validator(email.unsubscribe.input) + .handler(publicHandler(email.unsubscribe.name, email.unsubscribe.run)) diff --git a/packages/spools/src/server/entry.ts b/packages/spools/src/server/entry.ts index ad5400b..9a33b8e 100644 --- a/packages/spools/src/server/entry.ts +++ b/packages/spools/src/server/entry.ts @@ -31,6 +31,32 @@ const abort = z.object({ name: z.literal('AbortError') }) * and prod), after src/spool.server.ts has defined the Spool. */ export function serveSpool(start: Handler): Handler { + bootSpool() + + return { + async fetch(request) { + try { + return withSecurityHeaders(await start.fetch(request)) + } catch (err) { + // The browser went away mid-request (a navigation cancels in-flight loads). + // Nobody is waiting for a response, so this is not an error worth logging. + if (request.signal.aborted && abort.safeParse(err).success) { + return new Response(null, { status: 499 }) + } + + throw err + } + }, + } +} + +/** + * What a Spool does once as its server starts, whatever serves its requests: + * reports the environment, checks the config's run targets, and starts the + * schedules. `serveSpool` calls it on TanStack Start, `headlessServer` + * (src/headless.ts) with no web framework. + */ +export function bootSpool(): void { logEnvironment() // Fail loudly if the config references a workflow kind, campaign or handler that doesn't exist. @@ -67,20 +93,4 @@ export function serveSpool(start: Handler): Handler { .catch((cause: unknown) => { console.error('[server] The record scopes check did not run', cause) }) - - return { - async fetch(request) { - try { - return withSecurityHeaders(await start.fetch(request)) - } catch (err) { - // The browser went away mid-request (a navigation cancels in-flight loads). - // Nobody is waiting for a response, so this is not an error worth logging. - if (request.signal.aborted && abort.safeParse(err).success) { - return new Response(null, { status: 499 }) - } - - throw err - } - }, - } } diff --git a/packages/spools/src/server/files.functions.ts b/packages/spools/src/server/files.functions.ts index 4c5887f..167a43f 100644 --- a/packages/spools/src/server/files.functions.ts +++ b/packages/spools/src/server/files.functions.ts @@ -1,142 +1,50 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import { z } from 'zod' -import { - changeFile, - changeFolder, - createFolder, - deleteFile, - deleteFolder, - finishUpload, - listFolder, - recordFolder, - searchFiles, - setupProblems, - startUpload, -} from './files' +import * as files from './operations/files' import { crmHandler } from './runtime/boundary' -import type { FilesError, StaffError } from './runtime/errors' -import { crmConfig } from './spool' /** - * Server functions for the file browser (the Files page and a record's Files - * tab). Anyone who may use the CRM may see and change what is in the file - * store, except what record scopes and role access keep from them (files.ts - * checks every folder and file it is asked about): a record's folder is changed - * only by whoever may change the record. The store's key stays on the server: - * the browser only ever gets a transfer URL for the one file it is sending. + * The interface's way in to the file browser (the Files page and a record's + * Files tab). What each does is an operation (src/server/operations/files.ts), + * shared with the HTTP API; here it is only bound to TanStack Start. */ -const id = z.string().uuid() -const folderId = id.nullable() -const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') -const recordRef = z.object({ objectKey, recordId: id }) -const name = z.string().min(1).max(400) - -/** Errors a teammate can act on travel as data, so the browser can show them where they happened. */ -const told = (program: Effect.Effect) => - program.pipe( - Effect.map((value) => ({ ok: true as const, value })), - Effect.catchIf( - (error): error is Extract => error._tag === 'FilesError', - (error) => Effect.succeed({ ok: false as const, error: error.message }), - ), - ) - /** A folder's contents; `folderId: null` is the store's top level. `problems` says why files can't be used yet. */ export const listFolderFn = createServerFn({ method: 'GET' }) - .validator(z.object({ folderId })) - .handler( - crmHandler('files.listFolder', ({ data }) => - Effect.gen(function* () { - const problems = yield* setupProblems - - if (problems.length > 0) { - return { problems, listing: null, error: null } - } - - const res = yield* told(listFolder(data.folderId)) - return { problems, listing: res.ok ? res.value : null, error: res.ok ? null : res.error } - }), - ), - ) + .validator(files.listFolder.input) + .handler(crmHandler(files.listFolder.name, files.listFolder.run)) /** A record's own folder, made on first use. `null` when the store isn't set up. */ export const recordFolderFn = createServerFn({ method: 'POST' }) - .validator(recordRef) - .handler( - crmHandler('files.recordFolder', ({ data }) => - Effect.gen(function* () { - if ((yield* setupProblems).length > 0) { - return { ok: true as const, value: null } - } - - return yield* told(recordFolder(data.objectKey, data.recordId)) - }), - ), - ) + .validator(files.recordFolder.input) + .handler(crmHandler(files.recordFolder.name, files.recordFolder.run)) export const searchFilesFn = createServerFn({ method: 'GET' }) - .validator(z.object({ q: z.string().max(200) })) - .handler(crmHandler('files.searchFiles', ({ data }) => told(searchFiles(data.q)))) + .validator(files.searchFiles.input) + .handler(crmHandler(files.searchFiles.name, files.searchFiles.run)) export const createFolderFn = createServerFn({ method: 'POST' }) - .validator(z.object({ parentId: folderId, name })) - .handler( - crmHandler('files.createFolder', ({ data }) => told(createFolder(data.parentId, data.name))), - ) - -/** `from`: for a file, the folder it is in (`null` for the top level). A Spool with record scopes needs it. */ -const item = z.object({ kind: z.enum(['folder', 'file']), id, from: folderId.optional() }) + .validator(files.createFolder.input) + .handler(crmHandler(files.createFolder.name, files.createFolder.run)) export const renameItemFn = createServerFn({ method: 'POST' }) - .validator(item.extend({ name })) - .handler( - crmHandler('files.renameItem', ({ data }) => - told( - data.kind === 'folder' - ? changeFolder(data.id, { name: data.name }) - : changeFile(data.id, { name: data.name }, data.from), - ), - ), - ) + .validator(files.renameItem.input) + .handler(crmHandler(files.renameItem.name, files.renameItem.run)) /** Move a file or a folder into `to` (`null` for the store's top level). */ export const moveItemFn = createServerFn({ method: 'POST' }) - .validator(item.extend({ to: folderId })) - .handler( - crmHandler('files.moveItem', ({ data }) => - told( - data.kind === 'folder' - ? changeFolder(data.id, { parentId: data.to }) - : changeFile(data.id, { folderId: data.to }, data.from), - ), - ), - ) + .validator(files.moveItem.input) + .handler(crmHandler(files.moveItem.name, files.moveItem.run)) export const deleteItemFn = createServerFn({ method: 'POST' }) - .validator(item) - .handler( - crmHandler('files.deleteItem', ({ data }) => - told(data.kind === 'folder' ? deleteFolder(data.id) : deleteFile(data.id, data.from)), - ), - ) + .validator(files.deleteItem.input) + .handler(crmHandler(files.deleteItem.name, files.deleteItem.run)) export const startUploadFn = createServerFn({ method: 'POST' }) - .validator( - z.object({ - folderId, - name, - sizeBytes: z.number().int().positive(), - sha256: z.string().regex(/^[0-9a-f]{64}$/), - /** The record whose Files tab this is added from, for its timeline. */ - record: recordRef.nullish(), - }), - ) - .handler(crmHandler('files.startUpload', ({ data, user }) => told(startUpload(data, user)))) + .validator(files.startUpload.input) + .handler(crmHandler(files.startUpload.name, files.startUpload.run)) /** `value` is the file once the store has it, or `null` while the store is still working: ask again. */ export const finishUploadFn = createServerFn({ method: 'POST' }) - .validator(z.object({ id })) - .handler(crmHandler('files.finishUpload', ({ data, user }) => told(finishUpload(data.id, user)))) + .validator(files.finishUpload.input) + .handler(crmHandler(files.finishUpload.name, files.finishUpload.run)) diff --git a/packages/spools/src/server/files.ts b/packages/spools/src/server/files.ts index 1e220b6..655a295 100644 --- a/packages/spools/src/server/files.ts +++ b/packages/spools/src/server/files.ts @@ -7,7 +7,7 @@ import { LIBRARY_LABEL, MAX_UPLOAD_BYTES, safeName } from '../crm/files' import { EVERY_SCOPE, type ScopeAccess } from '../crm/scopes' import { canEdit, editsNothing, hiddenObjects, mustSee, readOnlyMessage } from './object-access' import { addActivity, getRecord, valueText } from './records' -import { CurrentAccess, CurrentObjectAccess } from './runtime/access' +import { CurrentAccess, CurrentObjectAccess, ReadOnlyCaller } from './runtime/access' import { FilesError, fromHook, NotFound, type StaffError } from './runtime/errors' import { type FileChange, FileStore, type FolderChange, type StoredFolder } from './runtime/files' import { asSystem, hungScope, mustWrite, recordScope, scopesOn } from './scopes' @@ -605,7 +605,8 @@ export const listFolder = Effect.fn('files.listFolder')(function* (folderId: str return yield* new NotFound({ what: 'Folder' }) } - if (folderId === null) { + // Made the first time the top level is shown, but never for a caller that may only read. + if (folderId === null && !(yield* ReadOnlyCaller)) { yield* ensureLibrary() } diff --git a/packages/spools/src/server/guides.functions.ts b/packages/spools/src/server/guides.functions.ts index cb82e53..353e4ab 100644 --- a/packages/spools/src/server/guides.functions.ts +++ b/packages/spools/src/server/guides.functions.ts @@ -1,29 +1,20 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import * as guides from './guides' +import * as guides from './operations/guides' import { crmHandler } from './runtime/boundary' /** - * What the browser may change about guides: its own progress, and nothing - * else. Neither function takes a user id; it is always the signed-in person's. - * What they have seen arrives with the session (`getCrmSession`). + * The interface's way in to a person's own progress through the guides. What + * each does is an operation (src/server/operations/guides.ts), shared with the + * HTTP API; here it is only bound to TanStack Start. */ /** A guide was finished or dismissed: don't offer it to this person again. */ export const markGuideFn = createServerFn({ method: 'POST' }) - .validator(guides.markInput) - .handler( - crmHandler('markGuide', ({ data, user }) => - guides.markGuide(user.id, data.id, data.outcome).pipe(Effect.as({ ok: true })), - ), - ) + .validator(guides.markGuide.input) + .handler(crmHandler(guides.markGuide.name, guides.markGuide.run)) /** Stop offering this person guides, or start again. */ export const setGuideOffersFn = createServerFn({ method: 'POST' }) - .validator(guides.offersInput) - .handler( - crmHandler('setGuideOffers', ({ data, user }) => - guides.setGuideOffers(user.id, data.on).pipe(Effect.as({ ok: true })), - ), - ) + .validator(guides.setGuideOffers.input) + .handler(crmHandler(guides.setGuideOffers.name, guides.setGuideOffers.run)) diff --git a/packages/spools/src/server/http.ts b/packages/spools/src/server/http.ts new file mode 100644 index 0000000..f32d32f --- /dev/null +++ b/packages/spools/src/server/http.ts @@ -0,0 +1,476 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import { isApiKey, keyHolder } from './api-keys' +import { bearerToken, verifyToken } from './callers' +import { type AnyOperation, operationNamed, operations } from './operations' +import { ReadOnlyCaller } from './runtime/access' +import { CurrentRequest, runtime } from './runtime/app' +import type { Session } from './runtime/auth' +import { + BODY_LIMIT, + forStaff, + forStrangers, + idempotent, + readBody, + serve, + wanted, +} from './runtime/boundary' +import type { StaffError } from './runtime/errors' +import { SCOPE_HEADER } from './scopes' +import { spool } from './spool' + +/** + * The CRM over HTTP, for a front end that is not the one a Spool comes with: a + * design of your own on any framework, a mobile app, a script. One handler, + * `Request` in and `Response` out, that any server can mount: + * + * const api = httpApi() + * Bun.serve({ fetch: (request) => api(request) }) + * + * It answers every operation (src/server/operations), each at + * `POST /` with its input as the JSON body, and a read also at + * `GET /?input=`. `GET ` lists them with what + * each takes, and `GET /openapi.json` says the same as OpenAPI 3.1. + * An answer is `{ "data": ... }`; a refusal or failure is + * `{ "error": { "code", "message" } }` with the status that fits. + * + * Who is asking is decided here and nowhere else, exactly as for the + * interface's own server functions: a teammate on the access list, in the + * record scope they asked for out of the ones they hold, with what their + * roles let them reach. They are known by + * + * - the session cookie of the Spool's auth adapter, for a front end on the + * same site. A browser's cross-site request is refused before anything runs; + * - a sign-in token sent as `Authorization: Bearer `, for a front end + * elsewhere, taken only when the app names the front ends whose tokens count + * (`tokens.authorizedParties`). A request with a bearer header is judged by + * that header alone: a cookie sent with it counts for nothing; + * - an API key sent the same way (`Authorization: Bearer spk_...`), for a + * script or another service. A key acts as the one teammate it was made for + * (src/server/api-keys.ts, `spools keys`). + */ + +export type HttpApiOptions = { + /** Where the API is mounted. `/api/v1` unless it says. */ + readonly basePath?: string + /** + * Take sign-in tokens as bearer tokens, from these front ends only (the + * origins a token was issued to, its `azp`). Without this no token opens the + * API. The auth adapter must be able to check tokens (docs/auth.md). + */ + readonly tokens?: { readonly authorizedParties: readonly string[] } + /** + * Take API keys (`spk_...`, made with `spools keys create`) as bearer tokens. + * Off unless this says: a Spool that doesn't use keys never reads the table + * that holds them, and a key sent to it is no token it takes. + */ + readonly keys?: boolean + /** + * Origins a browser may call this API from (CORS), for a front end on another + * site that sends a bearer token. Cookies are never taken from another site. + */ + readonly origins?: readonly string[] +} + +type Coded = { readonly code: string; readonly message: string } + +const refusal = (status: number, code: string, message: string, headers?: HeadersInit) => + Response.json({ error: { code, message } satisfies Coded }, { status, headers }) + +/** The status and code of a typed failure. Its message is the error's own, written for staff. */ +const failed = (error: StaffError): Response => { + switch (error._tag) { + case 'Unauthorized': + return error.reason === 'signed-out' + ? refusal(401, 'unauthorized', error.message) + : refusal(403, 'forbidden', error.message) + case 'NotFound': + return refusal(404, 'not_found', error.message) + case 'Invalid': + return refusal(400, 'invalid', error.message) + case 'Conflict': + return refusal(409, 'conflict', error.message) + case 'ScopeRefused': + return refusal(403, 'forbidden', error.message) + case 'Timeout': + return refusal(504, 'timeout', error.message) + default: + return refusal(500, 'failed', error.message) + } +} + +/** + * Whether a request that proves who it is with a cookie came from this site. + * A browser says where a request came from (`Sec-Fetch-Site`, else `Origin`), + * and another site's page can't change either. A caller that sends neither is + * not a browser, so no page is acting through it. + */ +export const fromThisSite = (request: Request): boolean => { + const site = request.headers.get('sec-fetch-site') + + if (site !== null) { + // `none` is someone opening an address themselves: fine for a read, never for a change. + return site === 'same-origin' || (site === 'none' && request.method === 'GET') + } + + const origin = request.headers.get('origin') + + if (origin === null) { + return true + } + + const host = request.headers.get('host') ?? new URL(request.url).host + return URL.canParse(origin) && new URL(origin).host === host +} + +/** A key that could not be looked up: the database did not answer. */ +const UNCHECKED = Symbol('unchecked') + +/** A session for someone known by a token: who they are, and no token of the provider's to hand on. */ +const tokenSession = (userId: string): Session => ({ + userId, + getToken: () => Promise.resolve(null), +}) + +/** What a browser on another site is told it may send, when its origin is one the app named. */ +const corsFor = (request: Request, origins: readonly string[]) => { + const origin = request.headers.get('origin') + + // With origins named, an answer differs by who asks: a cache must never give one origin's to another. + if (origin === null || !origins.includes(origin)) { + return origins.length > 0 ? { Vary: 'Origin' } : {} + } + + return { + 'Access-Control-Allow-Origin': origin, + 'Access-Control-Allow-Methods': 'GET, POST', + 'Access-Control-Allow-Headers': `Authorization, Content-Type, Idempotency-Key, ${SCOPE_HEADER}`, + 'Access-Control-Max-Age': '600', + Vary: 'Origin', + } +} + +/** The list of operations, with what each takes as JSON Schema. */ +const reference = () => + operations().map((operation) => ({ + name: operation.name, + kind: operation.kind, + access: operation.access, + summary: operation.summary, + input: z.toJSONSchema(operation.input, { io: 'input', unrepresentable: 'any' }), + // Said for the operations a front end is built on; the rest answer JSON this doesn't describe. + answer: operation.answer + ? z.toJSONSchema(operation.answer, { io: 'output', unrepresentable: 'any' }) + : null, + })) + +const errorSchema = { + type: 'object', + required: ['error'], + properties: { + error: { + type: 'object', + required: ['code', 'message'], + properties: { + code: { type: 'string', description: 'What went wrong, to branch on.' }, + message: { type: 'string', description: 'What went wrong, in words for a person.' }, + }, + }, + }, +} + +/** + * The API as an OpenAPI 3.1 document, for tools that read one (a client + * generator, an API explorer). It says every operation's address and what it + * takes. What each answers is typed in the client (src/client.ts), from the + * server's own code, and is not described here beyond its envelope. + */ +const openApi = (base: string) => ({ + openapi: '3.1.0', + info: { + title: 'Spools HTTP API', + version: '1', + description: + 'Every operation is a POST with its input as the JSON body, answered as { "data": ... }. A read is also a GET with its input as JSON in ?input=.', + }, + servers: [{ url: base }], + security: [{ session: [] }, { bearer: [] }], + components: { + securitySchemes: { + session: { + type: 'apiKey', + in: 'cookie', + name: 'session', + description: "The auth adapter's session cookie, from the CRM's own site only.", + }, + bearer: { + type: 'http', + scheme: 'bearer', + description: 'An API key (spk_...), or a sign-in token from a front end the server names.', + }, + }, + schemas: { Error: errorSchema }, + }, + paths: Object.fromEntries( + reference().map((operation) => [ + `/${operation.name}`, + { + post: { + operationId: operation.name, + summary: operation.summary, + tags: [operation.name.split('.')[0]], + // An operation for anyone needs no one signed in; the rest need what the document says. + security: operation.access === 'open' ? [] : [{ session: [] }, { bearer: [] }], + requestBody: { content: { 'application/json': { schema: operation.input } } }, + responses: { + 200: { + description: 'The answer.', + content: { + 'application/json': { + schema: { + type: 'object', + required: ['data'], + properties: { data: operation.answer ?? {} }, + }, + }, + }, + }, + default: { + description: 'A refusal or a failure.', + content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } }, + }, + }, + }, + }, + ]), + ), +}) + +/** What an operation's own schema made of what a caller sent. */ +type Parsed = z.output + +/** The JSON a caller sent, if it is JSON. Nothing sent is no input. */ +const sent = (text: string) => { + if (text.trim() === '') { + return { ok: true, value: undefined } as const + } + + try { + return { ok: true, value: JSON.parse(text) } as const + } catch { + return { ok: false } as const + } +} + +/** Runs an operation on the text a caller sent, parsed by the operation's schema, and answers as JSON. */ +const answer = ( + operation: AnyOperation, + text: string, + run: (data: Parsed) => Effect.Effect, +) => { + const json = sent(text) + + if (!json.ok) { + return Effect.succeed(refusal(400, 'invalid_input', 'The input must be JSON')) + } + + const parsed = operation.input.safeParse(json.value) + + if (!parsed.success) { + return Effect.succeed(refusal(400, 'invalid_input', z.prettifyError(parsed.error))) + } + + return run(parsed.data).pipe( + Effect.map((data) => + Response.json( + { data: data ?? null }, + // Nothing here is for a cache unless an operation says otherwise. + { headers: { 'Cache-Control': 'private, no-store', ...operation.headers } }, + ), + ), + ) +} + +/** What a caller sent as input: the body of a POST, or `?input=` of a GET. Null when it is too large. */ +const inputOf = (request: Request) => + Effect.gen(function* () { + if (request.method === 'GET') { + return new URL(request.url).searchParams.get('input') ?? '' + } + + return yield* readBody(request, BODY_LIMIT) + }) + +/** An answer whatever happened: the caller went away, or something broke that `serve` has already logged in full. */ +const settled = async (answering: Promise): Promise => { + try { + return await answering + } catch (error) { + return error instanceof DOMException && error.name === 'AbortError' + ? new Response(null, { status: 499 }) + : refusal(500, 'failed', 'Something went wrong on our side. Try again in a moment.') + } +} + +/** + * The HTTP API of this process's Spool, as one handler. Mount it under + * `basePath` on any server that speaks `Request` and `Response`. + */ +export const httpApi = (options: HttpApiOptions = {}) => { + const base = (options.basePath ?? '/api/v1').replace(/\/+$/, '') + const origins = options.origins ?? [] + + const handle = async (request: Request): Promise => { + const path = new URL(request.url).pathname + + if (path !== base && !path.startsWith(`${base}/`)) { + return refusal(404, 'not_found', 'Not found') + } + + if (request.method === 'OPTIONS') { + return new Response(null, { status: 204 }) + } + + if (path === base || path === `${base}/`) { + return request.method === 'GET' + ? Response.json({ data: reference() }) + : refusal(405, 'method_not_allowed', 'The list of operations is read with GET') + } + + if (path === `${base}/openapi.json`) { + return request.method === 'GET' + ? Response.json(openApi(base)) + : refusal(405, 'method_not_allowed', 'The OpenAPI document is read with GET') + } + + const operation = operationNamed(path.slice(base.length + 1)) + + if (!operation) { + return refusal(404, 'not_found', 'No such operation') + } + + const reads = operation.kind === 'read' && request.method === 'GET' + + if (request.method !== 'POST' && !reads) { + return refusal( + 405, + 'method_not_allowed', + operation.kind === 'read' ? 'Use GET or POST' : 'Use POST', + { Allow: operation.kind === 'read' ? 'GET, POST' : 'POST' }, + ) + } + + // A bearer token, when one is sent, is all that says who is asking: a cookie beside it counts for nothing. + // Any `Authorization` header at all: one this server can't read must not fall through to the cookie, + // where an auth provider's own reading of the header could still count it. + const token = bearerToken(request.headers) + const byToken = request.headers.has('authorization') + + // A cookie proves who is asking only to this site's own pages. + if (!byToken && !fromThisSite(request)) { + return refusal(403, 'cross_site', 'This request came from another site') + } + + // The session belongs to the request: read here, before any Effect, as the auth port asks. + const cookieSession = byToken ? null : await spool().auth.session(request) + + const program = Effect.gen(function* () { + // An API key says so by its shape, and is never also tried as a sign-in token. + // Nobody is known yet, so a failure here says nothing of the database's own words. + const key = + options.keys === true && token !== null && isApiKey(token) + ? yield* keyHolder(token).pipe( + Effect.catch((error) => + Effect.as( + Effect.logError(`[http] A key could not be checked: ${error.message}`), + UNCHECKED, + ), + ), + ) + : null + + if (key === UNCHECKED) { + return refusal(500, 'failed', 'Something went wrong on our side. Try again in a moment.') + } + + const signedInAs = + token !== null && !isApiKey(token) && options.tokens + ? yield* verifyToken(token, options.tokens) + : null + + const tokenUser = key?.userId ?? signedInAs + + if (byToken && tokenUser === null) { + return refusal(401, 'unauthorized', 'This token is not one this server takes') + } + + if (key?.readOnly && operation.kind !== 'read') { + return refusal(403, 'read_only', 'This key may only read') + } + + const session = tokenUser === null ? cookieSession : tokenSession(tokenUser) + + return yield* asCaller(session).pipe( + // The session a program is told of is the caller's, however they proved who they are. + Effect.provideService(CurrentRequest, { + headers: request.headers, + signal: request.signal, + session, + }), + Effect.provideService(ReadOnlyCaller, key?.readOnly === true), + ) + }).pipe(Effect.catch((error: StaffError) => Effect.succeed(failed(error)))) + + const asCaller = (session: Session | null) => { + const scope = wanted(session, request.headers) + + if (operation.access === 'open') { + return Effect.flatMap(inputOf(request), (text) => { + if (text === null) { + return Effect.succeed(refusal(413, 'too_large', 'The input is too large')) + } + + return answer(operation, text, (data) => + forStrangers(operation.name, operation.run({ data })), + ) + }) + } + + return forStaff(session?.userId, scope, (user) => { + const respond = (text: string) => + answer(operation, text, (data) => operation.run({ data, user })) + + // A write sent with an `Idempotency-Key` runs once for this teammate, and repeats get its first answer. + if (operation.kind === 'write') { + return idempotent(request, { caller: `staff:${user.id}` }, (_, body) => respond(body)) + } + + return Effect.flatMap(inputOf(request), (text) => + text === null + ? Effect.succeed(refusal(413, 'too_large', 'The input is too large')) + : respond(text), + ) + }) + } + + return serve( + runtime(), + `http.${operation.name}`, + { headers: request.headers, signal: request.signal, session: cookieSession }, + program, + ) + } + + return async (request: Request): Promise => { + const cors = corsFor(request, origins) + + const response = await settled(handle(request)) + + for (const [name, value] of Object.entries(cors)) { + response.headers.set(name, value) + } + + return response + } +} diff --git a/packages/spools/src/server/idempotency.ts b/packages/spools/src/server/idempotency.ts index f2bcf4e..1d44a39 100644 --- a/packages/spools/src/server/idempotency.ts +++ b/packages/spools/src/server/idempotency.ts @@ -104,6 +104,12 @@ export type Claim = { readonly key: string /** The request's body, as it was read. */ readonly body: string + /** + * What the caller could reach when they asked (`accessMark` in boundary.ts). A kept answer is + * sealed for it, so a repeat by the same caller whose access has since changed gets the first + * answer's status and not its body: what they were shown then may not be theirs to see now. + */ + readonly access?: string | undefined } const PENDING = 0 @@ -117,7 +123,8 @@ const answer = (body: Refusal, status: number, headers: Record = const inProgress = () => answer({ error: 'in_progress' }, 409, { 'Retry-After': '2' }) /** What an answer is sealed for: its own row, caller and key, so it opens nowhere else. */ -const ownerOf = (id: string, claim: Claim) => `idempotent:${id}:${claim.caller}:${claim.key}` +const ownerOf = (id: string, claim: Claim) => + `idempotent:${id}:${claim.caller}:${claim.key}${claim.access === undefined ? '' : `:${claim.access}`}` const digest = (text: string) => createHash('sha256').update(text).digest('hex') @@ -160,11 +167,23 @@ const replayOf = Effect.fn('idempotency.replay')(function* (row: Row, claim: Cla return new Response(bodiless ? null : JSON.stringify(WITHHELD), { status: row.status, headers }) } - const body = row.sealed - ? (yield* (yield* Vault).open(row.answer, ownerOf(row.id, claim), z.string())).value - : row.answer + const withheld = () => { + headers.set('Idempotent-Body', 'withheld') + headers.set('Content-Type', 'application/json') + return new Response(JSON.stringify(WITHHELD), { status: row.status, headers }) + } + + // Nothing is kept in the clear, so an answer that says it was is not given. + if (!row.sealed) { + return withheld() + } - return new Response(body, { status: row.status, headers }) + // Sealed for the caller as they were. One whose access has changed since can't open it, and gets + // the status alone: the change was made, and what it showed is no longer theirs for the asking. + return yield* (yield* Vault).open(row.answer, ownerOf(row.id, claim), z.string()).pipe( + Effect.map((opened) => new Response(opened.value, { status: row.status, headers })), + Effect.catchTag('VaultError', () => Effect.succeed(withheld())), + ) }) /** diff --git a/packages/spools/src/server/integrations.functions.ts b/packages/spools/src/server/integrations.functions.ts index f30e590..00d308d 100644 --- a/packages/spools/src/server/integrations.functions.ts +++ b/packages/spools/src/server/integrations.functions.ts @@ -1,42 +1,21 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import { z } from 'zod' -import { connectionsOverview, disconnect, setupProblems } from './integrations' +import * as integrations from './operations/integrations' import { crmHandler } from './runtime/boundary' -import { mailboxStatus } from './sync' /** - * Server functions for the Integrations page. A teammate is sent their own - * connections and the ones shared with the team, never another person's, and - * tokens are never returned. Removing one is for whoever it belongs to: its - * teammate, or for a shared one whoever may manage it. + * The interface's way in to the Integrations page. What each does is an + * operation (src/server/operations/integrations.ts), shared with the HTTP API; + * here it is only bound to TanStack Start. */ /** What the teammate can connect, what they and the team have connected, and their mailboxes. */ export const listIntegrationsFn = createServerFn({ method: 'GET' }).handler( - crmHandler('integrations.list', ({ user }) => - Effect.gen(function* () { - const [overview, mailboxes, problems] = yield* Effect.all( - [connectionsOverview(user), mailboxStatus(user), setupProblems], - { concurrency: 'unbounded' }, - ) - - return { - /** Why accounts can't be connected on this deployment yet; empty when they can. */ - problems, - ...overview, - /** Every mailbox the CRM uses for this teammate: the sign-in account and the connected ones. */ - mailboxes, - } - }), - ), + crmHandler(integrations.listIntegrations.name, integrations.listIntegrations.run), ) export const disconnectIntegrationFn = createServerFn({ method: 'POST' }) - .validator(z.object({ id: z.string().uuid() })) + .validator(integrations.disconnectIntegration.input) .handler( - crmHandler('integrations.disconnect', ({ data, user }) => - Effect.map(disconnect(user, data.id), (removed) => ({ removed })), - ), + crmHandler(integrations.disconnectIntegration.name, integrations.disconnectIntegration.run), ) diff --git a/packages/spools/src/server/layouts.functions.ts b/packages/spools/src/server/layouts.functions.ts index 71f41b6..718c8af 100644 --- a/packages/spools/src/server/layouts.functions.ts +++ b/packages/spools/src/server/layouts.functions.ts @@ -1,50 +1,19 @@ import { createServerFn } from '@tanstack/react-start' -import { z } from 'zod' -import { MAX_SUMMARY_FIELDS, MAX_SUMMARY_TOP } from '../crm/openui/summary' -import { whereSchema } from '../crm/openui/where' -import { layoutRecords, layoutSummary, MAX_LAYOUT_ROWS } from './layouts' +import * as layouts from './operations/layouts' import { crmHandler } from './runtime/boundary' -import { crmConfig } from './spool' /** - * What a layout's `records` tool reads (src/crm/ui/openui/tools.ts): a page of - * an object's records by `where`, with how many match (src/server/layouts.ts). - * And its `summary` tool: every matching record counted and added up by a - * field. Everything else a layout does goes through the server functions the - * CRM's own pages use. + * The interface's way in to what a layout's `records` and `summary` tools read + * (src/crm/ui/openui/tools.ts). What each does is an operation + * (src/server/operations/layouts.ts), shared with the HTTP API; here it is only + * bound to TanStack Start. */ -const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') - export const layoutRecordsFn = createServerFn({ method: 'GET' }) - .validator( - z.object({ - objectKey, - where: whereSchema.optional(), - q: z - .string() - .transform((q) => q.slice(0, 200)) - .optional(), - sort: z.object({ field: z.string(), dir: z.enum(['asc', 'desc']).default('asc') }).optional(), - // A limit nobody could mean is the default, not an error. - limit: z.number().int().positive().max(MAX_LAYOUT_ROWS).catch(50).default(50), - }), - ) - .handler(crmHandler('layouts.records', ({ data, user }) => layoutRecords(data, user.id))) - -const fieldKey = z.string().min(1).max(80) + .validator(layouts.records.input) + .handler(crmHandler(layouts.records.name, layouts.records.run)) export const layoutSummaryFn = createServerFn({ method: 'GET' }) - .validator( - z.object({ - objectKey, - by: fieldKey.optional(), - sum: fieldKey.optional(), - where: whereSchema.optional(), - // More than a summary hands over is the most it does, not an error. - top: z.number().int().min(0).max(MAX_SUMMARY_TOP).catch(MAX_SUMMARY_TOP).optional(), - fields: z.array(fieldKey).max(MAX_SUMMARY_FIELDS).optional(), - }), - ) - .handler(crmHandler('layouts.summary', ({ data, user }) => layoutSummary(data, user.id))) + .validator(layouts.summary.input) + .handler(crmHandler(layouts.summary.name, layouts.summary.run)) diff --git a/packages/spools/src/server/mailbox.functions.ts b/packages/spools/src/server/mailbox.functions.ts index 84ffcd3..6d82c0d 100644 --- a/packages/spools/src/server/mailbox.functions.ts +++ b/packages/spools/src/server/mailbox.functions.ts @@ -1,17 +1,20 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' +import * as mailbox from './operations/mailbox' import { crmHandler } from './runtime/boundary' -import { mailboxStatus, syncMine } from './sync' + +/** + * The interface's way in to the signed-in teammate's own mailboxes. What each + * does is an operation (src/server/operations/mailbox.ts), shared with the + * HTTP API; here it is only bound to TanStack Start. + */ /** The signed-in teammate's Google and Microsoft accounts, and what the CRM can do with each. */ export const mailboxStatusFn = createServerFn({ method: 'GET' }).handler( - crmHandler('mailbox.status', ({ user }) => - Effect.map(mailboxStatus(user), (accounts) => ({ accounts })), - ), + crmHandler(mailbox.status.name, mailbox.status.run), ) /** Read the teammate's own mailbox and calendar now. */ export const syncMailboxFn = createServerFn({ method: 'POST' }).handler( - crmHandler('mailbox.syncMine', ({ user }) => syncMine(user)), + crmHandler(mailbox.syncMailbox.name, mailbox.syncMailbox.run), ) diff --git a/packages/spools/src/server/marketing.functions.ts b/packages/spools/src/server/marketing.functions.ts index 465bb92..85f4ddf 100644 --- a/packages/spools/src/server/marketing.functions.ts +++ b/packages/spools/src/server/marketing.functions.ts @@ -1,140 +1,51 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import { z } from 'zod' -import * as marketing from './marketing' -import { Agents } from './runtime/agents' +import * as marketing from './operations/marketing' import { crmHandler } from './runtime/boundary' -import * as config from './runtime/config' /** - * Server functions for the Marketing page. Any teammate may use them: the page - * is the business's, not one person's. What goes out is still a person's - * decision, since scheduling and publishing are only here, never in the tool API. + * The interface's way in to the Marketing page. What each does is an operation + * (src/server/operations/marketing.ts), shared with the HTTP API; here it is + * only bound to TanStack Start. */ -const postId = z.object({ id: z.string().uuid() }) - /** Everything the page shows, or `null` when the config has no `marketing`. */ export const getMarketingFn = createServerFn({ method: 'GET' }).handler( - crmHandler('marketing.get', () => - Effect.gen(function* () { - if (!(yield* marketing.current())) { - return null - } - - const [site, posts, ads, reach, engine, key] = yield* Effect.all( - [ - marketing.site(), - marketing.listPosts(), - marketing.listAds(), - marketing.reach(), - (yield* Agents).configured, - config.variable('SWIRLS_API_KEY'), - ], - { concurrency: 'unbounded' }, - ) - - return { - // Written out field by field, so the page's type names nothing from inside the package. - site: { - website: site.website, - scanError: site.scanError, - tags: site.tags && { - gtm: site.tags.gtm, - ga4: site.tags.ga4, - googleAds: site.tags.googleAds, - metaPixel: site.tags.metaPixel, - linkedinInsight: site.tags.linkedinInsight, - }, - profile: site.profile && { - summary: site.profile.summary, - audience: site.profile.audience, - voice: site.profile.voice, - offers: site.profile.offers, - }, - scannedAt: site.scannedAt?.toISOString() ?? null, - profiledAt: site.profiledAt?.toISOString() ?? null, - profileRequestedAt: site.profileRequestedAt?.toISOString() ?? null, - }, - posts: posts.map((post) => ({ - ...post, - scheduledAt: post.scheduledAt?.toISOString() ?? null, - publishedAt: post.publishedAt?.toISOString() ?? null, - createdAt: post.createdAt.toISOString(), - })), - ads: ads.map((ad) => ({ - id: ad.id, - account: ad.account, - name: ad.name, - status: ad.status, - currency: ad.currency ?? null, - spend: ad.spend, - impressions: ad.impressions, - clicks: ad.clicks, - conversions: ad.conversions, - dailyBudget: ad.dailyBudget ?? null, - periodDays: ad.periodDays, - syncedAt: ad.syncedAt.toISOString(), - })), - /** Each channel and ad account: its network, how it is reached, and what stands in the way. */ - channels: reach.channels, - accounts: reach.ads, - /** Whether an agent engine is set up: the website profile needs one, and so does anything reached through it. */ - engine, - /** Whether the engine can run with nobody signed in, which a scheduled post needs. */ - unattended: !!key, - } - }), - ), + crmHandler(marketing.getMarketing.name, marketing.getMarketing.run), ) export const scanSiteFn = createServerFn({ method: 'POST' }).handler( - crmHandler('marketing.scanSite', () => marketing.scanSite().pipe(Effect.as({ ok: true }))), + crmHandler(marketing.scanSite.name, marketing.scanSite.run), ) export const profileSiteFn = createServerFn({ method: 'POST' }).handler( - crmHandler('marketing.profileSite', ({ user }) => marketing.profileSite(user)), + crmHandler(marketing.profileSite.name, marketing.profileSite.run), ) export const draftPostFn = createServerFn({ method: 'POST' }) - .validator(marketing.draftInput.extend({ id: z.string().uuid().optional() })) - .handler( - crmHandler('marketing.draftPost', ({ data: { id, ...draft }, user }) => - id - ? marketing.editPost(id, draft).pipe(Effect.as({ id })) - : marketing - .draftPost(draft, { id: user.id, name: user.name }) - .pipe(Effect.map((post) => ({ id: post.id }))), - ), - ) + .validator(marketing.draftPost.input) + .handler(crmHandler(marketing.draftPost.name, marketing.draftPost.run)) export const schedulePostFn = createServerFn({ method: 'POST' }) - .validator(postId.extend({ at: z.iso.datetime() })) - .handler( - crmHandler('marketing.schedulePost', ({ data, user }) => - marketing.schedulePost(data.id, new Date(data.at), user), - ), - ) + .validator(marketing.schedulePost.input) + .handler(crmHandler(marketing.schedulePost.name, marketing.schedulePost.run)) export const unschedulePostFn = createServerFn({ method: 'POST' }) - .validator(postId) - .handler(crmHandler('marketing.unschedulePost', ({ data }) => marketing.unschedulePost(data.id))) + .validator(marketing.unschedulePost.input) + .handler(crmHandler(marketing.unschedulePost.name, marketing.unschedulePost.run)) export const publishPostFn = createServerFn({ method: 'POST' }) - .validator(postId) - .handler( - crmHandler('marketing.publishPost', ({ data, user }) => marketing.publishPost(data.id, user)), - ) + .validator(marketing.publishPost.input) + .handler(crmHandler(marketing.publishPost.name, marketing.publishPost.run)) export const releasePostFn = createServerFn({ method: 'POST' }) - .validator(postId) - .handler(crmHandler('marketing.releasePost', ({ data }) => marketing.releasePost(data.id))) + .validator(marketing.releasePost.input) + .handler(crmHandler(marketing.releasePost.name, marketing.releasePost.run)) export const deletePostFn = createServerFn({ method: 'POST' }) - .validator(postId) - .handler(crmHandler('marketing.deletePost', ({ data }) => marketing.deletePost(data.id))) + .validator(marketing.deletePost.input) + .handler(crmHandler(marketing.deletePost.name, marketing.deletePost.run)) export const syncAdsFn = createServerFn({ method: 'POST' }).handler( - crmHandler('marketing.syncAds', ({ user }) => marketing.syncAds(user)), + crmHandler(marketing.syncAds.name, marketing.syncAds.run), ) diff --git a/packages/spools/src/server/middleware.ts b/packages/spools/src/server/middleware.ts deleted file mode 100644 index fa57fc2..0000000 --- a/packages/spools/src/server/middleware.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createCsrfMiddleware, createMiddleware } from '@tanstack/react-start' - -import { spool } from './spool' - -/** Request middleware every Spool needs, for `createStart` in the app's src/start.ts. */ - -/** - * Reject cross-site requests to anything a signed-in browser can call with its - * session cookie: server functions and the assistant chat endpoint. Other /api - * routes authenticate with a bearer token or a signature, not the cookie. - */ -export const csrfMiddleware = createCsrfMiddleware({ - filter: (ctx) => - ctx.handlerType === 'serverFn' || - new URL(ctx.request.url).pathname.startsWith('/api/assistant'), -}) - -/** Runs the auth adapter's own middleware, if it has one (Clerk reads its session there). */ -export const authMiddleware = createMiddleware().server((ctx) => { - const own = spool().auth.middleware?.options.server - return own ? own(ctx) : ctx.next() -}) diff --git a/packages/spools/src/server/operations/answers.ts b/packages/spools/src/server/operations/answers.ts new file mode 100644 index 0000000..2512c49 --- /dev/null +++ b/packages/spools/src/server/operations/answers.ts @@ -0,0 +1,77 @@ +import { z } from 'zod' + +/** + * What the operations a front end is built on answer, for the API's own + * description (the OpenAPI document of src/server/http.ts), so a client in any + * language can be generated from it. An answer is never parsed with these as it + * is sent: they say what is always there, and are open to the rest, which + * `packages/spools/tests/integration/http.test.ts` holds each real answer to. + * A TypeScript client needs none of this: `createClient` knows every answer's + * type from the operation itself. + */ + +/** A moment, as JSON carries one: ISO 8601 text. */ +const moment = z.string().describe('A moment, as ISO 8601 text.') + +/** A record of any object: what every record has, and its own fields beside them. */ +export const record = z + .looseObject({ + id: z.string(), + createdAt: moment, + updatedAt: moment, + createdBy: z.string().nullish(), + lastActivityAt: moment.nullish(), + lastContactedAt: moment.nullish(), + nextTaskDue: moment.nullish(), + }) + .describe("A record: what every record has, and its object's own fields by key.") + +/** A record in a list: its id always, and the fields the view asked for. */ +const listed = z + .looseObject({ id: z.string() }) + .describe('A record in a list: its id, and the fields the view shows.') + +/** A record by its title, for a picker. */ +export const titleOption = z.object({ id: z.string(), title: z.string() }) + +/** Something hung off a record (a timeline entry, a task, a note): its id, and what it holds. */ +const hung = z.looseObject({ id: z.string() }) + +const view = z + .looseObject({ id: z.string() }) + .describe('A view of an object: saved or from the config.') + +export const answers = { + made: z.object({ id: z.string() }).describe('The id of the record.'), + done: z.object({ ok: z.boolean() }), + deleted: z.object({ deleted: z.number().int() }).describe('How many records were deleted.'), + titles: z.array(titleOption), + titlePage: z.object({ + options: z.array(titleOption), + more: z.boolean().describe('Whether more records match than this page holds.'), + }), + brand: z.object({ + name: z.string().describe("The business's name."), + auth: z.string().describe('Which auth provider signs people in.'), + }), + record: z.looseObject({ + record: record.nullable().describe('The record, or null when there is none to see.'), + activities: z.array(hung).describe('Its timeline, newest first.'), + tasks: z.array(hung), + notes: z.array(hung), + favorite: z.boolean().describe('Whether whoever asks has it as a favourite.'), + }), + list: z.looseObject({ + rows: z.array(listed), + total: z.number().int().describe('How many records match, on every page together.'), + hasMore: z.boolean(), + views: z.array(view), + view, + active: z + .looseObject({}) + .describe("The filters and sort in force: the view's, or the ones the request carried."), + titles: z + .record(z.string(), z.array(titleOption)) + .describe('By object, the titles of the records the filters name.'), + }), +} diff --git a/packages/spools/src/server/operations/assistant.ts b/packages/spools/src/server/operations/assistant.ts new file mode 100644 index 0000000..a46e905 --- /dev/null +++ b/packages/spools/src/server/operations/assistant.ts @@ -0,0 +1,129 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import { TITLE_MAX } from '../../crm/assistant' +import { assistantChat } from '../assistant-chat' +import { type AssistantChat, CHATS_LISTED } from '../runtime/agents' +import { AgentsError, Invalid, messageOf, NotConfigured } from '../runtime/errors' +import { policies, withPolicy } from '../runtime/policies' +import { staff } from './define' + +/** + * Sessions for the in-CRM assistant. The agent engine keeps them + * (runtime/agents.ts), so nothing here touches the database. Each is defined + * once here (operations/define.ts) and reached by the interface's server + * functions (src/server/assistant.functions.ts), the HTTP API and the server's + * own code alike. + */ + +const notConfigured = new NotConfigured({ + feature: 'assistant', + message: + 'The assistant is not configured (SWIRLS_PROJECT_ID, and SWIRLS_API_KEY or federation with your sign-in provider)', +}) + +/** The assistant's chat for this person, or `NotConfigured`. */ +const chatOrRefuse = assistantChat.pipe( + Effect.filterOrFail( + (chat) => chat !== null, + () => notConfigured, + ), +) + +/** A chat as the assistant's list shows it. */ +type SessionSummary = { sessionId: string; title: string | null; updatedAt: string } + +/** One call to the chat, with the engine's time limit. */ +const ask = (name: string, work: () => Promise) => + Effect.tryPromise({ + try: work, + catch: (cause) => new AgentsError({ message: messageOf(cause) }), + }).pipe( + withPolicy(policies.agentsRun, () => false), + Effect.catchTag('Timeout', (timeout) => + Effect.fail(new AgentsError({ message: timeout.message })), + ), + Effect.withSpan(`assistant.${name}`), + ) + +export const state = staff('assistant.state', { + kind: 'read', + summary: + "Whether the assistant is set up, the signed-in person's chats, and the messages of one chat when given its id.", + input: z.object({ sessionId: z.string().max(200).optional() }), + run: ({ data }) => + Effect.gen(function* () { + const chat: AssistantChat | null = yield* assistantChat + + if (!chat) { + const none: SessionSummary[] = [] + return { + configured: false as const, + canRegenerate: false, + sessions: none, + messagesJson: '[]', + } + } + + const { sessionId } = data + + const [sessions, history] = yield* Effect.all( + [ + ask('listSessions', () => chat.listSessions({ limit: CHATS_LISTED })), + sessionId + ? ask('getMessages', () => chat.getMessages(sessionId)) + : Effect.succeed({ messages: [] }), + ], + { concurrency: 2 }, + ) + + return { + configured: true as const, + canRegenerate: chat.regenerate, + sessions: sessions.map((s) => ({ + sessionId: s.sessionId, + title: s.title, + updatedAt: s.updatedAt.toISOString(), + })), + // UIMessage carries `unknown` metadata, which Start cannot type-check as serializable. + messagesJson: JSON.stringify(history.messages), + } + }), +}) + +export const createSession = staff('assistant.createSession', { + kind: 'write', + summary: 'Start a new chat with the assistant, titled if a title is given.', + // A chat is titled from its first message (`titleFrom`); a longer title is one that was not made by the page. + input: z.object({ + title: z + .string() + .trim() + .min(1) + .max(TITLE_MAX + 1) + .optional(), + }), + run: ({ data }) => + Effect.flatMap(chatOrRefuse, (chat) => + ask('createSession', () => chat.createSession({ title: data.title ?? null })), + ), +}) + +export const deleteSession = staff('assistant.deleteSession', { + kind: 'write', + summary: "Delete one of the signed-in person's chats with the assistant.", + input: z.object({ sessionId: z.string().min(1).max(200) }), + run: ({ data }) => + Effect.gen(function* () { + const chat = yield* chatOrRefuse + // Only a chat this person is shown may be deleted by them: the id alone is not enough. + const listed = yield* ask('listSessions', () => chat.listSessions({ limit: CHATS_LISTED })) + + if (!listed.some((s) => s.sessionId === data.sessionId)) { + return yield* new Invalid({ message: 'That chat is not in your list' }) + } + + const deleted = yield* ask('deleteSession', () => chat.deleteSession(data.sessionId)) + return { deleted } + }), +}) diff --git a/packages/spools/src/server/operations/crm.ts b/packages/spools/src/server/operations/crm.ts new file mode 100644 index 0000000..e985d76 --- /dev/null +++ b/packages/spools/src/server/operations/crm.ts @@ -0,0 +1,348 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import { toPublicConfig } from '../../crm/config' +import { runTarget } from '../actions' +import * as guides from '../guides' +import { accessOfPerson, mustEdit, withObjectAccess } from '../object-access' +import * as records from '../records' +import * as roles from '../roles' +import { CurrentRequest } from '../runtime/app' +import { signedInUser, wanted as wantedIn } from '../runtime/boundary' +import { Invalid, NotFound } from '../runtime/errors' +import { asUser, scopeSession } from '../scopes' +import * as search from '../search' +import * as service from '../service' +import { changedSinceFor, changedSinceInput } from '../signals' +import { crmConfig, getObject, spool } from '../spool' +import { Users } from '../users' +import * as workspace from '../workspace' +import { answers } from './answers' +import { neverStore, nothing, open, staff } from './define' + +/** + * Records, search and the session: what every page of a CRM starts from. + * Each is defined once here (operations/define.ts) and reached by the + * interface's server functions (src/server/crm.functions.ts), the HTTP API and + * the server's own code alike. + */ + +const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') +const recordRef = z.object({ objectKey, id: z.string().uuid() }) + +/** Whether anyone is signed in, allowed in or not. */ +const signedInSession = Effect.map( + Effect.serviceOption(CurrentRequest), + (request) => request._tag === 'Some' && request.value.session !== null, +) + +export const session = open('session.get', { + kind: 'read', + summary: + 'Who is asking, and what they start from: the config, the team, favourites and what their roles and scopes allow.', + input: nothing, + run: () => + Effect.gen(function* () { + const user = yield* signedInUser + + // The team list feeds owner/assignee pickers; skip asking for it when no object has a `user` field. + const hasUserFields = Object.values(crmConfig().objects).some((o) => + Object.values(o.fields).some((f) => f.type === 'user'), + ) + + // What this person has seen of the guides rides along, so no page asks for it separately. + const nothingSeen: string[] = [] + const signedInAs = (yield* signedInSession) || user !== null + const offers = yield* guides.guidesOffered + + if (!user) { + return { + signedIn: signedInAs, + user, + config: null, + users: [], + favorites: [], + dueTasks: 0, + guides: { seen: nothingSeen, offers }, + scopes: null, + roles: { held: nothingSeen, admin: false }, + access: null, + } + } + + // A session answers signed-out pages too, so the boundary gave it no scope: it takes its own. + const request = yield* CurrentRequest + const wanted = wantedIn(request.session, request.headers) + + const access = yield* accessOfPerson(user) + + const [users, favorites, dueTasks, seen] = yield* asUser( + user, + wanted, + )( + withObjectAccess(access)( + Effect.all( + [ + // The team list feeds owner/assignee pickers; skip asking for it when no object has a `user` field. + hasUserFields ? Effect.flatMap(Users, (all) => all.team) : Effect.succeed([]), + workspace.listFavorites(user.id), + workspace.dueTaskCount(user.id), + guides.seenGuides(user.id), + ], + { concurrency: 'unbounded' }, + ), + ), + ) + + return { + signedIn: signedInAs, + user, + config: toPublicConfig(crmConfig()), + users, + favorites, + dueTasks, + guides: { seen, offers }, + // The scopes this person may switch between, in a Spool that has them. + scopes: yield* scopeSession(user, wanted), + // What they do, and whether they set what others do, in a Spool with roles. + roles: yield* roles.roleSession(user), + // The objects their roles keep from them, and the ones they only read (docs/roles.md#access). + access, + } + }), +}) + +/** What every page needs, signed in or not: the business's name, and which auth provider signs people in. */ +export const brand = open('brand.get', { + kind: 'read', + summary: "The business's name, and which auth provider signs people in.", + input: nothing, + answer: answers.brand, + run: () => Effect.sync(() => ({ name: crmConfig().app.name, auth: spool().auth.id })), +}) + +/** + * What the search box matches in the browser: every record's title, summary + * line and unencrypted searchable fields. With `since`, only what changed after it. + */ +export const searchIndex = staff('search.index', { + kind: 'read', + summary: + "Every record's title and unencrypted searchable fields, as one JSON string. With `since`, only what changed after it.", + input: z.object({ since: z.string().datetime().optional() }), + headers: neverStore, + run: ({ data, user }) => + Effect.gen(function* () { + // As one JSON string: thousands of small arrays cost far more to carry as a structured value. + return JSON.stringify( + yield* search.quickIndex(data.since ? new Date(data.since) : undefined, user.id), + ) + }), +}) + +/** Matches the browser can't find itself: other fields, and the text of notes, emails, calls and tasks. */ +export const searchDeep = staff('search.deep', { + kind: 'read', + summary: 'Records, notes, emails, calls and tasks whose text matches.', + input: z.object({ q: z.string().trim().min(1).max(200) }), + headers: neverStore, + run: ({ data }) => search.deepSearch(data.q), +}) + +/** + * Whether what a page shows changed since it last asked (src/server/signals.ts): + * the list, board and record pages ask this to refresh behind the scenes + * (src/crm/ui/live.ts). A key the person can't read says nothing. + */ +export const changedSince = staff('changes.since', { + kind: 'read', + summary: 'Which of up to ten objects or records changed since the token a previous answer gave.', + input: changedSinceInput, + headers: neverStore, + run: ({ data }) => changedSinceFor(data), +}) + +/** Values of an object's text fields that contain what was typed, to offer as filters. */ +export const suggestValues = staff('search.suggest', { + kind: 'read', + summary: "Values of an object's text fields that contain what was typed.", + input: z.object({ objectKey, q: z.string().trim().min(1).max(100) }), + headers: neverStore, + run: ({ data }) => search.suggestValues(data.objectKey, data.q), +}) + +export const deleteRecords = staff('records.deleteMany', { + kind: 'write', + summary: 'Deletes up to 200 records of one object, and says how many it deleted.', + input: z.object({ objectKey, ids: z.array(z.string().uuid()).min(1).max(200) }), + answer: answers.deleted, + run: ({ data, user }) => + Effect.gen(function* () { + let deleted = 0 + + for (const id of data.ids) { + if (yield* service.deleteRecord(data.objectKey, id, user)) { + deleted++ + } + } + + return { deleted } + }), +}) + +export const getRecord = staff('records.get', { + kind: 'read', + summary: 'A record with its timeline, related records, tasks and notes.', + input: recordRef, + answer: answers.record, + run: ({ data, user }) => + Effect.gen(function* () { + const [record, activities, related, tasks, notes, favorite] = yield* Effect.all( + [ + records.getRecord(data.objectKey, data.id), + records.listActivities(data.objectKey, data.id), + records.relatedRecords(data.objectKey, data.id), + workspace.listTasks({ objectKey: data.objectKey, recordId: data.id }), + workspace.listNotes({ objectKey: data.objectKey, recordId: data.id }), + workspace.isFavorite(user.id, data.objectKey, data.id), + ], + { concurrency: 'unbounded' }, + ) + + return { record, activities, related, tasks, notes, favorite } + }), +}) + +/** One page of an object's titles for a relation picker, narrowed by what has been typed. */ +export const searchRelation = staff('records.searchTitles', { + kind: 'read', + summary: "One page of an object's record titles, narrowed by what was typed.", + input: z.object({ objectKey, q: z.string().max(200).default('') }), + answer: answers.titlePage, + run: ({ data }) => records.searchTitles(data.objectKey, data.q), +}) + +/** The titles of records a page holds only the ids of (a preset value, a saved filter). */ +export const relationTitles = staff('records.titles', { + kind: 'read', + summary: 'The titles of up to 100 records, by id.', + input: z.object({ objectKey, ids: z.array(z.string().uuid()).min(1).max(100) }), + answer: answers.titles, + run: ({ data }) => + Effect.gen(function* () { + const titles = yield* records.recordTitlesOf(data.objectKey, data.ids) + return [...titles].map(([id, title]) => ({ id, title })) + }), +}) + +/** + * Which of the records a picker lists a record holds in a relations field. The + * page has the first of a record's links only, so for one that holds more it + * asks about the ones it is about to show ticked or unticked. + */ +export const heldLinks = staff('records.heldLinks', { + kind: 'read', + summary: 'Which of up to 100 records a record holds in one of its relations fields.', + input: recordRef.extend({ + field: z.string().max(200), + ids: z.array(z.string().uuid()).min(1).max(100), + }), + run: ({ data }) => records.linkedAmong(data.objectKey, data.id, data.field, data.ids), +}) + +export const createRecord = staff('records.create', { + kind: 'write', + summary: 'Creates a record: runs hooks, writes the timeline and fires automations.', + input: z.object({ objectKey, values: z.record(z.string(), z.unknown()) }), + answer: answers.made, + run: ({ data, user }) => + Effect.gen(function* () { + const record = yield* service.createRecord(data.objectKey, data.values, user) + return { id: record.id } + }), +}) + +export const updateRecord = staff('records.update', { + kind: 'write', + summary: + 'Changes the fields given of a record: runs hooks, writes the timeline and fires automations.', + input: recordRef.extend({ values: z.record(z.string(), z.unknown()) }), + answer: answers.made, + run: ({ data, user }) => + Effect.gen(function* () { + const record = yield* service.updateRecord(data.objectKey, data.id, data.values, user) + + if (!record) { + return yield* new NotFound({ what: 'Record' }) + } + + return { id: record.id } + }), +}) + +export const deleteRecord = staff('records.delete', { + kind: 'write', + summary: 'Deletes a record.', + input: recordRef, + answer: answers.done, + run: ({ data, user }) => + Effect.gen(function* () { + yield* service.deleteRecord(data.objectKey, data.id, user) + return { ok: true } + }), +}) + +export const runAction = staff('records.runAction', { + kind: 'write', + summary: "Runs one of an object's actions on a record.", + input: recordRef.extend({ actionId: z.string() }), + run: ({ data, user }) => + Effect.gen(function* () { + const action = getObject(data.objectKey).actions.find((a) => a.id === data.actionId) + + if (!action) { + return yield* new Invalid({ message: 'Unknown action' }) + } + + const record = yield* records.getRecord(data.objectKey, data.id) + + if (!record) { + return yield* new NotFound({ what: 'Record' }) + } + + // An action changes things, or sends them: someone who may only read these records can't start one. + yield* mustEdit(data.objectKey) + + return yield* runTarget(action.run, { + objectKey: data.objectKey, + record, + actor: user, + trigger: `action:${action.id}`, + }) + }), +}) + +export const dashboard = staff('home.dashboard', { + kind: 'read', + summary: 'Record counts, recent activity, open tasks and the pipeline summary of whoever asks.', + input: nothing, + run: ({ user }) => + Effect.gen(function* () { + const [counts, activities, tasks, pipeline] = yield* Effect.all( + [ + records.countRecords(), + records.recentActivities(12), + workspace.listTasks({ assigneeId: user.id }), + Effect.flatMap(roles.rolesOf(user), (held) => workspace.pipelineSummary(user.id, held)), + ], + { concurrency: 'unbounded' }, + ) + + return { + counts, + activities, + tasks: tasks.filter((t) => !t.completedAt).slice(0, 8), + pipeline, + } + }), +}) diff --git a/packages/spools/src/server/operations/define.ts b/packages/spools/src/server/operations/define.ts new file mode 100644 index 0000000..57855da --- /dev/null +++ b/packages/spools/src/server/operations/define.ts @@ -0,0 +1,86 @@ +import { z } from 'zod' + +import type { Program } from '../runtime/boundary' +import type { StaffError } from '../runtime/errors' +import type { CrmUser } from '../users' + +/** + * An operation: one thing the CRM does for whoever asks, defined once. Its + * name, what it takes, who may ask and the program that answers are all here, + * and every way in is made from it: the interface's server functions + * (src/server/*.functions.ts), the HTTP API (src/server/http.ts) and calls from + * the server's own code (src/server/api.ts). So a rule that holds for one way + * in holds for all of them, and none of them has a door the others lack. + * + * An operation never checks who is asking: the boundary does, before `run` + * (runtime/boundary.ts). `staff` operations are given the signed-in teammate + * and run in their record scopes and with their roles' access. `open` + * operations answer anyone, signed in or not, and nothing staff-only belongs + * in one. + */ + +/** Whether an operation only reads. A read may be asked for with GET over HTTP; a write never. */ +export type Kind = 'read' | 'write' + +type Described = { + /** Its name everywhere: the HTTP path, the client's method, the span. `area.verb`. */ + readonly name: N + readonly kind: Kind + /** One line for the reference: what it does, as a sentence. */ + readonly summary: string + /** What it takes. Every way in parses with this before `run`. */ + readonly input: S + /** + * What it answers, for the API's own description (answers.ts). Said for the + * operations a front end is built on; the answer itself is never parsed with it. + */ + readonly answer?: z.ZodType | undefined + /** Headers its answer carries (`Cache-Control`, for answers no cache may keep). */ + readonly headers?: Readonly> | undefined +} + +/** An operation for signed-in teammates. */ +export type StaffOperation< + N extends string, + S extends z.ZodType, + A, + E extends StaffError, +> = Described & { + readonly access: 'staff' + // A method, so that operations of every input fit `AnyOperation`. + run(this: void, input: { data: z.output; user: CrmUser }): Program +} + +/** An operation that answers anyone. */ +export type OpenOperation< + N extends string, + S extends z.ZodType, + A, + E extends StaffError, +> = Described & { + readonly access: 'open' + run(this: void, input: { data: z.output }): Program +} + +/** Any operation, whatever it takes and answers. */ +export type AnyOperation = + | StaffOperation + | OpenOperation + +/** What an operation with no input takes: nothing. */ +export const nothing = z.void() + +/** These answers hold people's names and messages: no browser, proxy or CDN may keep a copy. */ +export const neverStore = { 'Cache-Control': 'private, no-store' } + +/** An operation for signed-in teammates: `run` is given the validated `data` and the `user`. */ +export const staff = ( + name: N, + spec: Omit, 'name' | 'access'>, +): StaffOperation => ({ name, access: 'staff', ...spec }) + +/** An operation that also answers signed-out callers. Nothing staff-only belongs here. */ +export const open = ( + name: N, + spec: Omit, 'name' | 'access'>, +): OpenOperation => ({ name, access: 'open', ...spec }) diff --git a/packages/spools/src/server/operations/email.ts b/packages/spools/src/server/operations/email.ts new file mode 100644 index 0000000..8b6dfb4 --- /dev/null +++ b/packages/spools/src/server/operations/email.ts @@ -0,0 +1,33 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import { suppress, verifyUnsubscribeToken } from '../email' +import { Invalid } from '../runtime/errors' +import { open } from './define' + +/** + * Unsubscribing, for people who aren't signed in: the page's button proves + * who they are with the signed token in the link. (Mail clients' one-click + * unsubscribe is unsubscribe-route.ts, kept apart so the page's browser code + * never imports it.) Defined once here (operations/define.ts) and reached by + * the interface's server functions (src/server/email.functions.ts), the HTTP + * API and the server's own code alike. + */ + +/** The Unsubscribe button on /unsubscribe. */ +export const unsubscribe = open('email.unsubscribe', { + kind: 'write', + summary: 'Stop sending email to the address a signed unsubscribe token names.', + input: z.object({ token: z.string().max(1000) }), + run: ({ data }) => + Effect.gen(function* () { + const email = yield* verifyUnsubscribeToken(data.token) + + if (!email) { + return yield* new Invalid({ message: 'This unsubscribe link is invalid.' }) + } + + yield* suppress(email, 'unsubscribed') + return { ok: true } + }), +}) diff --git a/packages/spools/src/server/operations/files.ts b/packages/spools/src/server/operations/files.ts new file mode 100644 index 0000000..485463c --- /dev/null +++ b/packages/spools/src/server/operations/files.ts @@ -0,0 +1,145 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import * as library from '../files' +import type { FilesError, StaffError } from '../runtime/errors' +import { crmConfig } from '../spool' +import { staff } from './define' + +/** + * The file browser (the Files page and a record's Files tab). Anyone who may + * use the CRM may see and change what is in the file store, except what record + * scopes and role access keep from them (files.ts checks every folder and file + * it is asked about): a record's folder is changed only by whoever may change + * the record. The store's key stays on the server: the browser only ever gets a + * transfer URL for the one file it is sending. Each is defined once here + * (operations/define.ts) and reached by the interface's server functions + * (src/server/files.functions.ts), the HTTP API and the server's own code alike. + */ + +const id = z.string().uuid() +const folderId = id.nullable() +const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') +const recordRef = z.object({ objectKey, recordId: id }) +const name = z.string().min(1).max(400) + +/** Errors a teammate can act on travel as data, so the browser can show them where they happened. */ +const told = (program: Effect.Effect) => + program.pipe( + Effect.map((value) => ({ ok: true as const, value })), + Effect.catchIf( + (error): error is Extract => error._tag === 'FilesError', + (error) => Effect.succeed({ ok: false as const, error: error.message }), + ), + ) + +/** A folder's contents; `folderId: null` is the store's top level. `problems` says why files can't be used yet. */ +export const listFolder = staff('files.list', { + kind: 'read', + summary: + "A folder's contents, or the store's top level, with any reasons files can't be used yet.", + input: z.object({ folderId }), + run: ({ data }) => + Effect.gen(function* () { + const problems = yield* library.setupProblems + + if (problems.length > 0) { + return { problems, listing: null, error: null } + } + + const res = yield* told(library.listFolder(data.folderId)) + return { problems, listing: res.ok ? res.value : null, error: res.ok ? null : res.error } + }), +}) + +/** A record's own folder, made on first use. `null` when the store isn't set up. */ +export const recordFolder = staff('files.recordFolder', { + kind: 'write', + summary: "A record's own folder, made the first time it is asked for.", + input: recordRef, + run: ({ data }) => + Effect.gen(function* () { + if ((yield* library.setupProblems).length > 0) { + return { ok: true as const, value: null } + } + + return yield* told(library.recordFolder(data.objectKey, data.recordId)) + }), +}) + +export const searchFiles = staff('files.search', { + kind: 'read', + summary: 'Files and folders whose names match the search text.', + input: z.object({ q: z.string().max(200) }), + run: ({ data }) => told(library.searchFiles(data.q)), +}) + +export const createFolder = staff('files.createFolder', { + kind: 'write', + summary: 'Make a folder inside another folder, or at the top level.', + input: z.object({ parentId: folderId, name }), + run: ({ data }) => told(library.createFolder(data.parentId, data.name)), +}) + +/** `from`: for a file, the folder it is in (`null` for the top level). A Spool with record scopes needs it. */ +const item = z.object({ kind: z.enum(['folder', 'file']), id, from: folderId.optional() }) + +export const renameItem = staff('files.rename', { + kind: 'write', + summary: 'Rename a file or a folder.', + input: item.extend({ name }), + run: ({ data }) => + told( + data.kind === 'folder' + ? library.changeFolder(data.id, { name: data.name }) + : library.changeFile(data.id, { name: data.name }, data.from), + ), +}) + +/** Move a file or a folder into `to` (`null` for the store's top level). */ +export const moveItem = staff('files.move', { + kind: 'write', + summary: 'Move a file or a folder into another folder, or to the top level.', + input: item.extend({ to: folderId }), + run: ({ data }) => + told( + data.kind === 'folder' + ? library.changeFolder(data.id, { parentId: data.to }) + : library.changeFile(data.id, { folderId: data.to }, data.from), + ), +}) + +export const deleteItem = staff('files.delete', { + kind: 'write', + summary: 'Delete a file or a folder.', + input: item, + run: ({ data }) => + told( + data.kind === 'folder' + ? library.deleteFolder(data.id) + : library.deleteFile(data.id, data.from), + ), +}) + +export const startUpload = staff('files.startUpload', { + kind: 'write', + summary: 'Start sending a file to a folder, and get the URL to send its bytes to.', + input: z.object({ + folderId, + name, + sizeBytes: z.number().int().positive(), + sha256: z.string().regex(/^[0-9a-f]{64}$/), + /** The record whose Files tab this is added from, for its timeline. */ + record: recordRef.nullish(), + }), + run: ({ data, user }) => told(library.startUpload(data, user)), +}) + +/** `value` is the file once the store has it, or `null` while the store is still working: ask again. */ +export const finishUpload = staff('files.finishUpload', { + kind: 'write', + summary: + 'Finish an upload once its bytes are sent; asked again while the store is still working.', + input: z.object({ id }), + run: ({ data, user }) => told(library.finishUpload(data.id, user)), +}) diff --git a/packages/spools/src/server/operations/guides.ts b/packages/spools/src/server/operations/guides.ts new file mode 100644 index 0000000..973b630 --- /dev/null +++ b/packages/spools/src/server/operations/guides.ts @@ -0,0 +1,31 @@ +import { Effect } from 'effect' + +import * as guides from '../guides' +import { staff } from './define' + +/** + * What a person may change about guides: their own progress, and nothing + * else. Neither operation takes a user id; it is always the signed-in person's. + * What they have seen arrives with the session (`session.get`). Each is defined + * once here (operations/define.ts) and reached by the interface's server + * functions (src/server/guides.functions.ts), the HTTP API and the server's own + * code alike. + */ + +/** A guide was finished or dismissed: don't offer it to this person again. */ +export const markGuide = staff('guides.mark', { + kind: 'write', + summary: + 'Record that the signed-in person finished or dismissed a guide, so it is not offered again.', + input: guides.markInput, + run: ({ data, user }) => + guides.markGuide(user.id, data.id, data.outcome).pipe(Effect.as({ ok: true })), +}) + +/** Stop offering this person guides, or start again. */ +export const setGuideOffers = staff('guides.setOffers', { + kind: 'write', + summary: 'Stop offering the signed-in person guides, or start again.', + input: guides.offersInput, + run: ({ data, user }) => guides.setGuideOffers(user.id, data.on).pipe(Effect.as({ ok: true })), +}) diff --git a/packages/spools/src/server/operations/index.ts b/packages/spools/src/server/operations/index.ts new file mode 100644 index 0000000..ef7c8d3 --- /dev/null +++ b/packages/spools/src/server/operations/index.ts @@ -0,0 +1,82 @@ +import * as assistant from './assistant' +import * as crm from './crm' +import type { AnyOperation } from './define' +import * as email from './email' +import * as files from './files' +import * as guides from './guides' +import * as integrations from './integrations' +import * as layouts from './layouts' +import * as mailbox from './mailbox' +import * as marketing from './marketing' +import * as roles from './roles' +import * as workspace from './workspace' + +/** + * Every operation the CRM has, by name. The HTTP API answers exactly these + * (src/server/http.ts), and `Operations` is what a typed client is made from + * (src/client.ts). An operation that isn't here has no way in but its own + * server function. + */ + +/** + * Each file's operations under its own name, so two files may export the same + * word (`records`, `status`) without one hiding the other. + */ +const areas = { + assistant, + crm, + email, + files, + guides, + integrations, + layouts, + mailbox, + marketing, + roles, + workspace, +} + +type Areas = typeof areas + +/** One of the operations, whatever file it is in. */ +type Each = { [A in keyof Areas]: Areas[A][keyof Areas[A]] }[keyof Areas] + +/** Every operation, by its public name (`records.get`). */ +export type Operations = { [O in Each as O['name']]: O } + +const named = new Map() + +for (const area of Object.values(areas)) { + for (const operation of Object.values(area)) { + // Two operations of one name would be two answers at one address: a mistake in the framework, found at start-up. + if (named.has(operation.name)) { + console.error(`[operations] "${operation.name}" is defined twice; the first is kept`) + continue + } + + named.set(operation.name, operation) + } +} + +/** The operation of this name, if there is one. */ +export const operationNamed = (name: string): AnyOperation | undefined => named.get(name) + +/** Every operation, in name order. */ +export const operations = (): AnyOperation[] => + [...named.values()].toSorted((a, b) => a.name.localeCompare(b.name)) + +export { + assistant, + crm, + email, + files, + guides, + integrations, + layouts, + mailbox, + marketing, + roles, + workspace, +} +export { callAs, callOpen } from '../api' +export type { AnyOperation, Kind, OpenOperation, StaffOperation } from './define' diff --git a/packages/spools/src/server/operations/integrations.ts b/packages/spools/src/server/operations/integrations.ts new file mode 100644 index 0000000..99147fb --- /dev/null +++ b/packages/spools/src/server/operations/integrations.ts @@ -0,0 +1,46 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import { connectionsOverview, disconnect, setupProblems } from '../integrations' +import { mailboxStatus } from '../sync' +import { nothing, staff } from './define' + +/** + * The Integrations page. A teammate is sent their own connections and the ones + * shared with the team, never another person's, and tokens are never returned. + * Removing one is for whoever it belongs to: its teammate, or for a shared one + * whoever may manage it. Each is defined once here (operations/define.ts) and + * reached by the interface's server functions + * (src/server/integrations.functions.ts), the HTTP API and the server's own + * code alike. + */ + +/** What the teammate can connect, what they and the team have connected, and their mailboxes. */ +export const listIntegrations = staff('integrations.list', { + kind: 'read', + summary: + 'What the signed-in teammate can connect, what they and the team have connected, and their mailboxes.', + input: nothing, + run: ({ user }) => + Effect.gen(function* () { + const [overview, mailboxes, problems] = yield* Effect.all( + [connectionsOverview(user), mailboxStatus(user), setupProblems], + { concurrency: 'unbounded' }, + ) + + return { + /** Why accounts can't be connected on this deployment yet; empty when they can. */ + problems, + ...overview, + /** Every mailbox the CRM uses for this teammate: the sign-in account and the connected ones. */ + mailboxes, + } + }), +}) + +export const disconnectIntegration = staff('integrations.disconnect', { + kind: 'write', + summary: 'Remove a connected account, for whoever it belongs to or may manage it.', + input: z.object({ id: z.string().uuid() }), + run: ({ data, user }) => Effect.map(disconnect(user, data.id), (removed) => ({ removed })), +}) diff --git a/packages/spools/src/server/operations/layouts.ts b/packages/spools/src/server/operations/layouts.ts new file mode 100644 index 0000000..f983ab3 --- /dev/null +++ b/packages/spools/src/server/operations/layouts.ts @@ -0,0 +1,53 @@ +import { z } from 'zod' + +import { MAX_SUMMARY_FIELDS, MAX_SUMMARY_TOP } from '../../crm/openui/summary' +import { whereSchema } from '../../crm/openui/where' +import { layoutRecords, layoutSummary, MAX_LAYOUT_ROWS } from '../layouts' +import { crmConfig } from '../spool' +import { staff } from './define' + +/** + * What a layout's `records` tool reads (src/crm/ui/openui/tools.ts): a page of + * an object's records by `where`, with how many match (src/server/layouts.ts). + * And its `summary` tool: every matching record counted and added up by a + * field. Everything else a layout does goes through the operations the CRM's + * own pages use. Each is defined once here (operations/define.ts) and reached + * by the interface's server functions (src/server/layouts.functions.ts), the + * HTTP API and the server's own code alike. + */ + +const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') + +export const records = staff('layouts.records', { + kind: 'read', + summary: "A page of an object's records matching a `where`, with how many match in all.", + input: z.object({ + objectKey, + where: whereSchema.optional(), + q: z + .string() + .transform((q) => q.slice(0, 200)) + .optional(), + sort: z.object({ field: z.string(), dir: z.enum(['asc', 'desc']).default('asc') }).optional(), + // A limit nobody could mean is the default, not an error. + limit: z.number().int().positive().max(MAX_LAYOUT_ROWS).catch(50).default(50), + }), + run: ({ data, user }) => layoutRecords(data, user.id), +}) + +const fieldKey = z.string().min(1).max(80) + +export const summary = staff('layouts.summary', { + kind: 'read', + summary: "An object's matching records counted, grouped by one field and with another added up.", + input: z.object({ + objectKey, + by: fieldKey.optional(), + sum: fieldKey.optional(), + where: whereSchema.optional(), + // More than a summary hands over is the most it does, not an error. + top: z.number().int().min(0).max(MAX_SUMMARY_TOP).catch(MAX_SUMMARY_TOP).optional(), + fields: z.array(fieldKey).max(MAX_SUMMARY_FIELDS).optional(), + }), + run: ({ data, user }) => layoutSummary(data, user.id), +}) diff --git a/packages/spools/src/server/operations/mailbox.ts b/packages/spools/src/server/operations/mailbox.ts new file mode 100644 index 0000000..06fa121 --- /dev/null +++ b/packages/spools/src/server/operations/mailbox.ts @@ -0,0 +1,27 @@ +import { Effect } from 'effect' + +import { mailboxStatus, syncMine } from '../sync' +import { nothing, staff } from './define' + +/** + * The signed-in teammate's own mailboxes. Each is defined once here + * (operations/define.ts) and reached by the interface's server functions + * (src/server/mailbox.functions.ts), the HTTP API and the server's own code alike. + */ + +/** The signed-in teammate's Google and Microsoft accounts, and what the CRM can do with each. */ +export const status = staff('mailbox.status', { + kind: 'read', + summary: + "The signed-in teammate's Google and Microsoft accounts, and what the CRM can do with each.", + input: nothing, + run: ({ user }) => Effect.map(mailboxStatus(user), (accounts) => ({ accounts })), +}) + +/** Read the teammate's own mailbox and calendar now. */ +export const syncMailbox = staff('mailbox.sync', { + kind: 'write', + summary: "Read the signed-in teammate's own mailbox and calendar into the CRM now.", + input: nothing, + run: ({ user }) => syncMine(user), +}) diff --git a/packages/spools/src/server/operations/marketing.ts b/packages/spools/src/server/operations/marketing.ts new file mode 100644 index 0000000..04319b3 --- /dev/null +++ b/packages/spools/src/server/operations/marketing.ts @@ -0,0 +1,165 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import * as marketing from '../marketing' +import { Agents } from '../runtime/agents' +import * as config from '../runtime/config' +import { nothing, staff } from './define' + +/** + * The Marketing page. Any teammate may use these: the page is the business's, + * not one person's. What goes out is still a person's decision, since + * scheduling and publishing are only here, never in the tool API. Each is + * defined once here (operations/define.ts) and reached by the interface's + * server functions (src/server/marketing.functions.ts), the HTTP API and the + * server's own code alike. + */ + +const postId = z.object({ id: z.string().uuid() }) + +/** Everything the page shows, or `null` when the config has no `marketing`. */ +export const getMarketing = staff('marketing.get', { + kind: 'read', + summary: + "The website's tags and profile, the posts, the ad results and each channel's state, or null when marketing is not set up.", + input: nothing, + run: () => + Effect.gen(function* () { + if (!(yield* marketing.current())) { + return null + } + + const [site, posts, ads, reach, engine, key] = yield* Effect.all( + [ + marketing.site(), + marketing.listPosts(), + marketing.listAds(), + marketing.reach(), + (yield* Agents).configured, + config.variable('SWIRLS_API_KEY'), + ], + { concurrency: 'unbounded' }, + ) + + return { + // Written out field by field, so the page's type names nothing from inside the package. + site: { + website: site.website, + scanError: site.scanError, + tags: site.tags && { + gtm: site.tags.gtm, + ga4: site.tags.ga4, + googleAds: site.tags.googleAds, + metaPixel: site.tags.metaPixel, + linkedinInsight: site.tags.linkedinInsight, + }, + profile: site.profile && { + summary: site.profile.summary, + audience: site.profile.audience, + voice: site.profile.voice, + offers: site.profile.offers, + }, + scannedAt: site.scannedAt?.toISOString() ?? null, + profiledAt: site.profiledAt?.toISOString() ?? null, + profileRequestedAt: site.profileRequestedAt?.toISOString() ?? null, + }, + posts: posts.map((post) => ({ + ...post, + scheduledAt: post.scheduledAt?.toISOString() ?? null, + publishedAt: post.publishedAt?.toISOString() ?? null, + createdAt: post.createdAt.toISOString(), + })), + ads: ads.map((ad) => ({ + id: ad.id, + account: ad.account, + name: ad.name, + status: ad.status, + currency: ad.currency ?? null, + spend: ad.spend, + impressions: ad.impressions, + clicks: ad.clicks, + conversions: ad.conversions, + dailyBudget: ad.dailyBudget ?? null, + periodDays: ad.periodDays, + syncedAt: ad.syncedAt.toISOString(), + })), + /** Each channel and ad account: its network, how it is reached, and what stands in the way. */ + channels: reach.channels, + accounts: reach.ads, + /** Whether an agent engine is set up: the website profile needs one, and so does anything reached through it. */ + engine, + /** Whether the engine can run with nobody signed in, which a scheduled post needs. */ + unattended: !!key, + } + }), +}) + +export const scanSite = staff('marketing.scanSite', { + kind: 'write', + summary: "Read the business's website again for its tracking tags.", + input: nothing, + run: () => marketing.scanSite().pipe(Effect.as({ ok: true })), +}) + +export const profileSite = staff('marketing.profileSite', { + kind: 'write', + summary: + 'Ask the agent engine to read the website and say what the business is, who it serves and how it speaks.', + input: nothing, + run: ({ user }) => marketing.profileSite(user), +}) + +export const draftPost = staff('marketing.draftPost', { + kind: 'write', + summary: 'Save a social post as a draft, or change a draft when given its id.', + input: marketing.draftInput.extend({ id: z.string().uuid().optional() }), + run: ({ data: { id, ...draft }, user }) => + id + ? marketing.editPost(id, draft).pipe(Effect.as({ id })) + : marketing + .draftPost(draft, { id: user.id, name: user.name }) + .pipe(Effect.map((post) => ({ id: post.id }))), +}) + +export const schedulePost = staff('marketing.schedulePost', { + kind: 'write', + summary: 'Schedule a post to be published at a given time.', + input: postId.extend({ at: z.iso.datetime() }), + run: ({ data, user }) => marketing.schedulePost(data.id, new Date(data.at), user), +}) + +export const unschedulePost = staff('marketing.unschedulePost', { + kind: 'write', + summary: 'Take a scheduled post back to a draft.', + input: postId, + run: ({ data }) => marketing.unschedulePost(data.id), +}) + +export const publishPost = staff('marketing.publishPost', { + kind: 'write', + summary: 'Publish a post to its channel now.', + input: postId, + run: ({ data, user }) => marketing.publishPost(data.id, user), +}) + +export const releasePost = staff('marketing.releasePost', { + kind: 'write', + summary: + 'Mark a post whose publish never got an answer as not sent, so it can be published again.', + input: postId, + run: ({ data }) => marketing.releasePost(data.id), +}) + +export const deletePost = staff('marketing.deletePost', { + kind: 'write', + summary: 'Delete a post.', + input: postId, + run: ({ data }) => marketing.deletePost(data.id), +}) + +export const syncAds = staff('marketing.syncAds', { + kind: 'write', + summary: "Read every configured ad account's latest results now.", + input: nothing, + run: ({ user }) => marketing.syncAds(user), +}) diff --git a/packages/spools/src/server/operations/roles.ts b/packages/spools/src/server/operations/roles.ts new file mode 100644 index 0000000..d087007 --- /dev/null +++ b/packages/spools/src/server/operations/roles.ts @@ -0,0 +1,35 @@ +import { Effect } from 'effect' + +import * as roles from '../roles' +import { Users } from '../users' +import { nothing, staff } from './define' + +/** + * The Team page: who holds which role. Both operations are refused for anyone + * `access.admins` doesn't name, here on the server, whatever a page shows. + * Each is defined once here (operations/define.ts) and reached by the + * interface's server functions (src/server/roles.functions.ts), the HTTP API + * and the server's own code alike. + */ + +/** Everyone who has signed in or been given a role, with their roles. */ +export const team = staff('roles.list', { + kind: 'read', + summary: 'Everyone who has signed in or been given a role, with the roles they hold.', + input: nothing, + run: ({ user }) => + Effect.gen(function* () { + return yield* roles.listTeam(user, yield* (yield* Users).team) + }), +}) + +/** Give someone exactly these roles. */ +export const setRoles = staff('roles.assign', { + kind: 'write', + summary: 'Give a teammate exactly these roles, replacing the ones they held.', + input: roles.setInput, + run: ({ data, user }) => + Effect.gen(function* () { + return yield* roles.setRoles(user, data, yield* (yield* Users).team) + }), +}) diff --git a/packages/spools/src/server/operations/workspace.ts b/packages/spools/src/server/operations/workspace.ts new file mode 100644 index 0000000..12f14cc --- /dev/null +++ b/packages/spools/src/server/operations/workspace.ts @@ -0,0 +1,587 @@ +import { Effect } from 'effect' +import { z } from 'zod' + +import { LOGGABLE, loggableKinds } from '../../crm/activity' +import { cleanFilters, relationIds } from '../../crm/filters' +import { activeRuns, sequencesTick } from '../campaigns' +import * as records from '../records' +import * as config from '../runtime/config' +import { NotFound } from '../runtime/errors' +import * as service from '../service' +import { crmConfig, getObject } from '../spool' +import { Users } from '../users' +import * as views from '../views' +import * as workspace from '../workspace' +import { answers } from './answers' +import { nothing, staff } from './define' + +/** + * Everything beside plain record CRUD: views, tasks, notes, favourites, + * reports, CSV and one-to-one email. Each is defined once here + * (operations/define.ts) and reached by the interface's server functions + * (src/server/workspace.functions.ts), the HTTP API and the server's own code + * alike. + */ + +const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') +const id = z.string().uuid() +const recordLink = { objectKey: objectKey.nullish(), recordId: id.nullish() } + +// ── Lists and views ───────────────────────────────────────────────────────── + +const filterValue = z.union([z.string(), z.number(), z.array(z.union([z.string(), z.number()]))]) + +const plainCondition = z.object({ + field: z.string(), + op: z.string(), + value: filterValue.optional(), +}) + +const condition = plainCondition.extend({ where: z.array(plainCondition).optional() }) +/** + * Filters and sort as the browser sends them: the shape only. What they may + * be, and how many, is decided by `cleanFilters` and `cleanSort`, which trim + * and drop rather than refuse, so an address someone edited by hand shows a + * list instead of an error. The page address is what bounds their size. + */ +const filtersInput = z.array(z.array(condition)) +const sortInput = z.array(z.object({ field: z.string(), dir: z.enum(['asc', 'desc']) })) +/** Search text, cut to a length worth searching for. */ +const searchText = z.string().transform((q) => q.slice(0, 200)) + +/** + * Everything a list page needs: the object's views, the active one, a page of + * rows, counts and footer calculations. `filters` and `sort` are what the page + * address carries when they differ from the saved view; without them the + * view's own are used. + */ +export const getList = staff('records.list', { + kind: 'read', + summary: + "A page of an object's records through one of its views, with the views, the total, footer calculations and the titles its filters name.", + input: z.object({ + objectKey, + viewId: z.string().optional(), + q: searchText.optional(), + // A page number nobody could mean is the first page, not an error. + page: z.number().int().positive().max(10_000).catch(1).default(1), + filters: filtersInput.optional(), + sort: sortInput.optional(), + }), + answer: answers.list, + run: ({ data, user }) => + Effect.gen(function* () { + const all = yield* views.resolveViews(data.objectKey, user.id) + const view = all.find((v) => v.id === data.viewId) ?? all[0] + + if (!view) { + return yield* new NotFound({ what: 'View' }) + } + + const board = view.type === 'board' + const pageSize = board ? 500 : 50 + const page = board ? 1 : data.page + const { filters, sort } = views.activeSettings(data.objectKey, view, data) + const query = { objectKey: data.objectKey, q: data.q, filters, viewerId: user.id } + // A board puts up to 500 cards on the page and shows a few fields on each: fetch those and no more. + const obj = getObject(data.objectKey) + const totalled = Object.keys(obj.fields).find((k) => obj.fields[k]?.type === 'currency') + + const cardFields = board + ? [obj.titleField, view.settings.groupBy, ...view.settings.cardFields, totalled].filter( + (f) => f !== undefined, + ) + : undefined + + // A filter on a relation holds the related records' ids; the page shows their titles. + const named = Object.entries(relationIds(crmConfig().objects, data.objectKey, filters)) + + const [rows, total, calculations, filterTitles] = yield* Effect.all( + [ + records.listRecords({ + ...query, + sort, + limit: pageSize, + offset: (page - 1) * pageSize, + // A list shows a related record's title and links to it; it needs no more of it. + relations: 'titles', + fields: cardFields, + }), + records.countMatching(query), + views.calculate(data.objectKey, query, view.settings.calculations), + Effect.forEach( + named, + ([to, ids]) => + Effect.map(records.recordTitlesOf(to, ids), (found) => [to, found] as const), + { + concurrency: 'unbounded', + }, + ), + ], + { concurrency: 'unbounded' }, + ) + + const titles: Record = {} + + for (const [to, found] of filterTitles) { + titles[to] = [...found].map(([recordId, title]) => ({ id: recordId, title })) + } + + return { + views: all, + view, + /** The filters and sort in force: the view's, or the ones the page address carries. */ + active: { filters, sort }, + rows, + total, + hasMore: page * pageSize < total, + calculations, + titles, + } + }), +}) + +const viewPatch = z.object({ + label: z.string().trim().min(1).max(80).optional(), + columns: z.array(z.string()).max(60).optional(), + sort: sortInput.optional(), + filters: filtersInput.optional(), + groupBy: z.string().optional(), + cardFields: z.array(z.string()).max(12).optional(), + calculations: z + .record(z.string(), z.enum(['sum', 'avg', 'min', 'max', 'filled', 'empty'])) + .optional(), +}) + +export const saveView = staff('views.save', { + kind: 'write', + summary: "Changes the settings given of one of an object's views.", + input: z.object({ objectKey, viewId: z.string(), patch: viewPatch }), + run: ({ data, user }) => + Effect.gen(function* () { + const { filters, ...rest } = data.patch + // Filters left out of the patch keep the view's own. + const patch: views.ViewPatch = { ...rest } + + if (filters) { + patch.filters = cleanFilters(crmConfig().objects, data.objectKey, filters) + } + + yield* views.saveView(data.objectKey, data.viewId, patch, user.id) + + return { ok: true } + }), +}) + +export const createView = staff('views.create', { + kind: 'write', + summary: + 'Creates a table or board view of an object, copying what it is not given from another view.', + input: z.object({ + objectKey, + label: z.string().trim().min(1).max(80), + type: z.enum(['table', 'board']), + copyFrom: z.string().optional(), + /** The filters and sort on screen, to save with the new view. */ + filters: filtersInput.optional(), + sort: sortInput.optional(), + /** Only the person creating it will see it. */ + private: z.boolean().optional(), + }), + run: ({ data, user }) => + Effect.gen(function* () { + const { filters, sort: sorted, ...input } = data + + // What isn't given is copied from the view it starts from. + const settings: Partial> = {} + + if (filters) { + settings.filters = cleanFilters(crmConfig().objects, data.objectKey, filters) + } + + if (sorted) { + settings.sort = sorted + } + + return { id: yield* views.createView(data.objectKey, { ...input, settings }, user.id) } + }), +}) + +export const deleteView = staff('views.delete', { + kind: 'write', + summary: "Deletes one of an object's views.", + input: z.object({ objectKey, viewId: z.string() }), + run: ({ data, user }) => + Effect.gen(function* () { + yield* views.deleteView(data.objectKey, data.viewId, user.id) + return { ok: true } + }), +}) + +// ── Import / export ───────────────────────────────────────────────────────── + +export const exportCsv = staff('records.exportCsv', { + kind: 'read', + summary: + "An object's records through one of its views, with the search, filters and sort given, as CSV.", + input: z.object({ + objectKey, + viewId: z.string().optional(), + q: searchText.optional(), + filters: filtersInput.optional(), + sort: sortInput.optional(), + }), + run: ({ data, user }) => + Effect.gen(function* () { + const all = yield* views.resolveViews(data.objectKey, user.id) + const view = all.find((v) => v.id === data.viewId) ?? all[0] + + if (!view) { + return yield* new NotFound({ what: 'View' }) + } + + // What is on screen: the filters and sort in the page address when it carries them, else the view's. + const { filters, sort: sorted } = views.activeSettings(data.objectKey, view, data) + return { + csv: yield* workspace.exportCsv(data.objectKey, { + q: data.q, + filters, + sort: sorted, + viewerId: user.id, + }), + } + }), +}) + +/** + * The records of one object that an import's relation cells name, by title or + * id. Matching happens here, against every record of the object, so the browser + * needn't hold (and be limited to) a list of titles. + */ +export const matchRelationTitles = staff('records.matchTitles', { + kind: 'read', + summary: 'The records of one object that up to 1,000 titles or ids name.', + input: z.object({ objectKey, values: z.array(z.string().max(2000)).min(1).max(1000) }), + run: ({ data }) => records.matchTitles(data.objectKey, data.values), +}) + +/** Create records from parsed CSV rows: `service.importRecords`. */ +export const importRecords = staff('records.import', { + kind: 'write', + summary: + 'Creates up to 1,000 records of one object from rows of text values, as a CSV import does.', + input: z.object({ + objectKey, + rows: z + .array(z.record(z.string().max(60), z.string().max(20_000))) + .min(1) + .max(1000), + }), + run: ({ data, user }) => service.importRecords(data.objectKey, data.rows, user), +}) + +// ── Tasks ─────────────────────────────────────────────────────────────────── + +const dueDate = z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .nullish() + +export const listTasks = staff('tasks.list', { + kind: 'read', + summary: "Tasks: the asker's own, everyone's, or a record's.", + input: z.object({ scope: z.enum(['mine', 'all']).default('mine'), ...recordLink }), + run: ({ data, user }) => + workspace.listTasks({ + assigneeId: data.scope === 'mine' && !data.recordId ? user.id : undefined, + objectKey: data.objectKey ?? undefined, + recordId: data.recordId ?? undefined, + }), +}) + +export const createTask = staff('tasks.create', { + kind: 'write', + summary: "Creates a task, on a record's timeline when it is for one.", + input: z.object({ + title: z.string().trim().min(1).max(500), + dueDate, + assigneeId: z.string().max(200).nullish(), + ...recordLink, + }), + run: ({ data, user }) => + Effect.gen(function* () { + const task = yield* workspace.createTask(data, user.id) + + if (data.objectKey && data.recordId) { + yield* records.addActivity({ + objectKey: data.objectKey, + recordId: data.recordId, + kind: 'task', + summary: `added a task: ${data.title}`, + actor: user.name, + actorId: user.id, + }) + } + + return { id: task.id } + }), +}) + +export const updateTask = staff('tasks.update', { + kind: 'write', + summary: "Changes a task's title, due date, assignee or whether it is done.", + input: z.object({ + id, + title: z.string().trim().min(1).max(500).optional(), + dueDate, + assigneeId: z.string().max(200).nullish(), + completed: z.boolean().optional(), + }), + run: ({ data, user }) => + Effect.gen(function* () { + const { id: taskId, ...patch } = data + const task = yield* workspace.updateTask(taskId, patch, user.id) + + if (task && data.completed && task.objectKey && task.recordId) { + yield* records.addActivity({ + objectKey: task.objectKey, + recordId: task.recordId, + kind: 'task', + summary: `completed a task: ${task.title}`, + actor: user.name, + actorId: user.id, + }) + } + + return { ok: true } + }), +}) + +export const deleteTask = staff('tasks.delete', { + kind: 'write', + summary: 'Deletes a task.', + input: z.object({ id }), + run: ({ data }) => + Effect.gen(function* () { + yield* workspace.deleteTask(data.id) + return { ok: true } + }), +}) + +// ── Notes ─────────────────────────────────────────────────────────────────── + +export const listNotes = staff('notes.list', { + kind: 'read', + summary: "Notes: every note, or a record's.", + input: z.object(recordLink), + run: ({ data }) => + workspace.listNotes({ + objectKey: data.objectKey ?? undefined, + recordId: data.recordId ?? undefined, + }), +}) + +export const saveNote = staff('notes.save', { + kind: 'write', + summary: + "Creates a note, on a record's timeline when it is for one, or changes one given its id.", + input: z.object({ + id: id.optional(), + title: z.string().trim().max(200), + body: z.string().max(50_000), + ...recordLink, + }), + run: ({ data, user }) => + Effect.gen(function* () { + if (data.id) { + yield* workspace.updateNote(data.id, { + title: data.title || 'Untitled note', + body: data.body, + }) + + return { id: data.id } + } + + const note = yield* workspace.createNote(data, user) + + if (data.objectKey && data.recordId) { + yield* records.addActivity({ + objectKey: data.objectKey, + recordId: data.recordId, + kind: 'note', + summary: `added a note: ${note.title}`, + actor: user.name, + actorId: user.id, + }) + } + + return { id: note.id } + }), +}) + +export const deleteNote = staff('notes.delete', { + kind: 'write', + summary: 'Deletes a note.', + input: z.object({ id }), + run: ({ data }) => + Effect.gen(function* () { + yield* workspace.deleteNote(data.id) + return { ok: true } + }), +}) + +// ── Favourites ────────────────────────────────────────────────────────────── + +export const toggleFavorite = staff('favorites.toggle', { + kind: 'write', + summary: "Adds a record to the asker's favourites, or takes it off, and says which it is now.", + input: z.object({ objectKey, recordId: id }), + run: ({ data, user }) => + Effect.gen(function* () { + return { favorite: yield* workspace.toggleFavorite(user.id, data.objectKey, data.recordId) } + }), +}) + +// ── Reports ───────────────────────────────────────────────────────────────── + +export const reports = staff('reports.overview', { + kind: 'read', + summary: "The Reports page's figures for the whole team.", + input: nothing, + run: () => + Effect.gen(function* () { + return yield* workspace.buildReports(yield* (yield* Users).team) + }), +}) + +// ── Logged activities and the activity report ─────────────────────────────── + +/** Log a call or meeting on a record. */ +export const logActivity = staff('activities.log', { + kind: 'write', + summary: "Logs a call or meeting, with its outcome and notes, on a record's timeline.", + input: z + .object({ + objectKey, + recordId: id, + kind: z.literal(loggableKinds), + outcome: z.string().max(40).nullish(), + /** When it took place; now if omitted. */ + occurredAt: z.coerce.date().nullish(), + notes: z.string().max(20_000).nullish(), + }) + .refine((d) => !d.outcome || LOGGABLE[d.kind].outcomes.some((o) => o.value === d.outcome), { + message: 'Unknown outcome', + path: ['outcome'], + }), + run: ({ data, user }) => + Effect.gen(function* () { + if (!(yield* records.getRecord(data.objectKey, data.recordId))) { + return yield* new NotFound({ what: 'Record' }) + } + + const activity = yield* workspace.logActivity(data, user) + + return { id: activity.id } + }), +}) + +/** A report range: `from` inclusive, `to` exclusive, at most two years apart. */ +const reportRange = z + .object({ from: z.coerce.date(), to: z.coerce.date() }) + .refine( + (r) => r.to > r.from && r.to.getTime() - r.from.getTime() <= 732 * 86_400_000, + 'Pick a range of up to two years', + ) + +/** Calls, emails, meetings, completed tasks and notes per teammate. */ +export const activityReport = staff('reports.activity', { + kind: 'read', + summary: + 'Calls, emails, meetings, completed tasks and notes per teammate over a range of up to two years.', + input: reportRange, + run: ({ data }) => + Effect.gen(function* () { + return yield* workspace.activityReport(data, yield* (yield* Users).team) + }), +}) + +export const activityReportCsv = staff('reports.activityCsv', { + kind: 'read', + summary: 'The activity report over a range of up to two years, as CSV.', + input: reportRange, + run: ({ data }) => + Effect.gen(function* () { + return { + csv: workspace.activityReportCsv( + yield* workspace.activityReport(data, yield* (yield* Users).team), + ), + } + }), +}) + +// ── Email ─────────────────────────────────────────────────────────────────── + +/** Send a one-to-one email to a record's address and keep it on the timeline. */ +export const sendEmail = staff('email.send', { + kind: 'write', + summary: + "Sends a one-to-one email to an address on a record, and keeps it on the record's timeline.", + input: z.object({ + objectKey, + recordId: id, + field: z.string(), + subject: z.string().trim().min(1).max(300), + body: z.string().trim().min(1).max(20_000), + /** Which of their mailboxes to send from, when the teammate has more than one. */ + from: z + .object({ provider: z.enum(['google', 'microsoft']), accountEmail: z.string().max(320) }) + .optional(), + }), + run: ({ data, user }) => workspace.sendRecordEmail(data, user), +}) + +// ── Workflows ─────────────────────────────────────────────────────────────── + +/** What runs automatically: config automations, record actions, and email sequences, with recent runs. */ +export const workflows = staff('workflows.overview', { + kind: 'read', + summary: + 'What runs automatically (automations, record actions and email sequences), whether it is set up to run, and recent runs.', + input: nothing, + run: () => + Effect.gen(function* () { + const recent = (yield* records.recentActivities(200)).filter( + (a) => a.kind === 'workflow' || a.kind === 'campaign' || a.kind === 'email', + ) + + const [titles, active] = yield* Effect.all([workspace.recordTitles(recent), activeRuns()], { + concurrency: 2, + }) + + return { + swirlsConfigured: !!(yield* config.variable('SWIRLS_PROJECT_ID')), + emailConfigured: + !!(yield* config.variable('RESEND_API_KEY')) && !!(yield* config.variable('EMAIL_FROM')), + // Only worth saying when there are sequences to run. + sequencesTick: + Object.keys(crmConfig().campaigns).length === 0 || + sequencesTick(yield* config.environment), + automations: crmConfig().automations, + actions: Object.entries(crmConfig().objects).flatMap(([key, obj]) => + obj.actions.map((a) => ({ objectKey: key, label: a.label, run: a.run })), + ), + sequences: Object.entries(crmConfig().campaigns).map(([key, c]) => ({ + key, + label: c.label, + objectKey: c.object, + steps: c.steps.map((s) => ({ id: s.id, wait: s.wait, subject: s.subject })), + stopWhen: c.stopWhen, + active: active[key] ?? 0, + })), + runs: recent + .slice(0, 30) + .map((a) => ({ ...a, recordTitle: titles[`${a.objectKey}:${a.recordId}`] ?? null })), + } + }), +}) diff --git a/packages/spools/src/server/roles.functions.ts b/packages/spools/src/server/roles.functions.ts index 03f0977..a037ace 100644 --- a/packages/spools/src/server/roles.functions.ts +++ b/packages/spools/src/server/roles.functions.ts @@ -1,31 +1,20 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import * as roles from './roles' +import * as roles from './operations/roles' import { crmHandler } from './runtime/boundary' -import { Users } from './users' /** - * The Team page: who holds which role. Both functions are refused for anyone - * `access.admins` doesn't name, here on the server, whatever a page shows. + * The interface's way in to the Team page: who holds which role. What each + * does is an operation (src/server/operations/roles.ts), shared with the HTTP + * API; here it is only bound to TanStack Start. */ /** Everyone who has signed in or been given a role, with their roles. */ export const teamFn = createServerFn({ method: 'GET' }).handler( - crmHandler('roles.team', ({ user }) => - Effect.gen(function* () { - return yield* roles.listTeam(user, yield* (yield* Users).team) - }), - ), + crmHandler(roles.team.name, roles.team.run), ) /** Give someone exactly these roles. */ export const setRolesFn = createServerFn({ method: 'POST' }) - .validator(roles.setInput) - .handler( - crmHandler('roles.set', ({ data, user }) => - Effect.gen(function* () { - return yield* roles.setRoles(user, data, yield* (yield* Users).team) - }), - ), - ) + .validator(roles.setRoles.input) + .handler(crmHandler(roles.setRoles.name, roles.setRoles.run)) diff --git a/packages/spools/src/server/runtime/access.ts b/packages/spools/src/server/runtime/access.ts index 5e4b6ed..a6de655 100644 --- a/packages/spools/src/server/runtime/access.ts +++ b/packages/spools/src/server/runtime/access.ts @@ -67,6 +67,17 @@ export const SystemWork = Context.Reference('spools/access/system-work' defaultValue: () => false, }) +/** + * Whether the program running is for a caller that may only read: an API key + * made read-only (src/server/api-keys.ts). The HTTP API refuses such a key + * every operation that writes; this is for the little a read does on the side + * outside its database, such as making the file library the first time it is + * shown, which a read-only caller leaves undone. + */ +export const ReadOnlyCaller = Context.Reference('spools/access/read-only', { + defaultValue: () => false, +}) + /** * An app's own code (a hook, a handler, a run target) is plain promises: it * calls back in through `@swirls/spools/extensions`, which starts a new program diff --git a/packages/spools/src/server/runtime/auth.ts b/packages/spools/src/server/runtime/auth.ts index 7d26fe2..528373c 100644 --- a/packages/spools/src/server/runtime/auth.ts +++ b/packages/spools/src/server/runtime/auth.ts @@ -1,4 +1,3 @@ -import type { AnyRequestMiddleware } from '@tanstack/react-start' import { Context, Effect, Layer } from 'effect' import type { Roles } from '../roles' @@ -98,10 +97,23 @@ export class Auth extends Context.Service< ) } +/** + * What a request middleware is, by web framework. The port names none: a + * framework's binding adds its own here (src/start.ts adds TanStack Start's), + * so the server's types need no web framework to be installed. + */ +// oxlint-disable-next-line typescript/no-empty-object-type, typescript/consistent-type-definitions -- an interface, and empty, so that a binding can add to it +export interface HostMiddleware {} + /** An auth provider behind the `Auth` port, with the half of it that belongs to a request. */ export type AuthAdapter = Adapter & { - /** Middleware the provider needs on every request, if any. */ - readonly middleware?: AnyRequestMiddleware + /** + * Middleware the provider needs on every request, if any, in the shape of the + * web framework the Spool is mounted in (`HostMiddleware`). The binding runs + * it (src/start.ts, for TanStack Start); a Spool with no web framework has + * no use for one. + */ + readonly middleware?: HostMiddleware[keyof HostMiddleware] /** * The session of the request being served, or null. Called in the request's * own async context, after the middleware, and never from inside an Effect. diff --git a/packages/spools/src/server/runtime/boundary.ts b/packages/spools/src/server/runtime/boundary.ts index 381eae7..f9a6bac 100644 --- a/packages/spools/src/server/runtime/boundary.ts +++ b/packages/spools/src/server/runtime/boundary.ts @@ -1,4 +1,5 @@ -import { getRequest, setResponseHeader, setResponseStatus } from '@tanstack/react-start/server' +import { createHash } from 'node:crypto' + import { Cause, Duration, Effect, Exit, type ManagedRuntime, Option } from 'effect' import { grantNow } from '../../crm/scopes' @@ -16,17 +17,20 @@ import { } from '../scopes' import { spool } from '../spool' import { type CrmUser, Users } from '../users' +import { CurrentAccess, CurrentObjectAccess } from './access' import { type AppServices, CurrentRequest, runtime, type Services } from './app' import type { Session } from './auth' import { bearerMatches } from './bearer' import * as config from './config' import { cronSecret, reveal } from './config' import { Invalid, type StaffError, Unauthorized } from './errors' +import { host } from './host' import { isCount } from './rate-limit' /** - * Where TanStack Start hands a request to an Effect program, and gets back - * what the browser sees. Every server function and API route goes through one + * Where a request becomes an Effect program, and its answer what the caller + * sees. Nothing here imports a web framework: a route is handed its `Request`, + * and a server function asks the installed host for it (runtime/host.ts). Every server function and API route goes through one * of these (lint refuses one that doesn't; see docs/server-code.md). An app's * own use the same, as promises (server/handlers.ts): * @@ -55,11 +59,12 @@ const SLOW_MS = 1000 const reference = () => crypto.randomUUID().slice(0, 8) -/** The request TanStack Start is serving, read outside Effect. */ -function currentRequest(session: Session | null): CurrentRequest['Service'] { - const request = getRequest() - return { headers: request.headers, signal: request.signal, session } -} +/** A request as a program is given it. */ +const currentRequest = (request: Request, session: Session | null): CurrentRequest['Service'] => ({ + headers: request.headers, + signal: request.signal, + session, +}) /** The session of the request being served, from the Spool's auth adapter, read outside Effect. */ const sessionOf = (request: Request): Promise => spool().auth.session(request) @@ -83,6 +88,22 @@ export const signedIn = Effect.fn('signedIn')(function* (userId: string | null | return user }) +/** + * A program as a teammate runs it, whichever way they came in: on the access + * list (`Unauthorized` otherwise), in the record scope they asked to work in + * out of the ones they hold, and with what their roles let them reach. The + * HTTP API and the server's own calls go through this; a server function and a + * route do the same in `crmHandler` and `apiRoute`. + */ +export const forStaff = ( + userId: string | null | undefined, + scope: string | null | undefined, + program: (user: CrmUser) => Effect.Effect, +) => + signedIn(userId).pipe( + Effect.flatMap((user) => asUser(user, scope)(asPerson(user)(program(user)))), + ) + /** * Runs a program for one request and settles it the way the browser expects. * Exported for tests, which pass a runtime built from fake layers; app code @@ -152,7 +173,7 @@ const refusedPage = (request: Request) => (error: StaffError) => error.reason === 'not-allowed' && !request.headers.has('x-tsr-serverFn') ) { - setResponseStatus(403) + host().setStatus(403) } }) @@ -166,13 +187,14 @@ export function crmHandler( options: { headers?: Record } = {}, ): (ctx: { data: I }) => Promise { return async ({ data }) => { - const asked = getRequest() + const serving = host() + const asked = serving.request() const session = await sessionOf(asked) - const request = currentRequest(session) + const request = currentRequest(asked, session) // Response headers belong to the request too: set here, never from inside the program. for (const [header, value] of Object.entries(options.headers ?? {})) { - setResponseHeader(header, value) + serving.setHeader(header, value) } return serve( @@ -224,13 +246,16 @@ export function publicHandler( name: string, program: (input: { data: I }) => Program, ): (ctx: { data: I }) => Promise { - return async ({ data }) => - serve( + return async ({ data }) => { + const asked = host().request() + + return serve( runtime(), name, - currentRequest(await sessionOf(getRequest())), + currentRequest(asked, await sessionOf(asked)), forStrangers(name, program({ data })), ) + } } /** The CRM user signed in to this request, or null (signed out, or not on the access list). */ @@ -331,13 +356,13 @@ export function publicRoute( } /** A request body larger than a route takes, by default (1 MB). */ -const BODY_LIMIT = 1_000_000 +export const BODY_LIMIT = 1_000_000 /** * A request's body as text, read a chunk at a time and given up on as soon as * it passes `limit` bytes, whatever its length header said. Null when too large. */ -const readBody = (request: Request, limit: number) => +export const readBody = (request: Request, limit: number) => Effect.tryPromise({ try: async (): Promise => { const declared = Number(request.headers.get('content-length') ?? '0') @@ -407,6 +432,35 @@ export type IdempotentOptions = { readonly bodyLimit?: number | undefined } +const sorted = (scopes: 'all' | readonly string[]) => + scopes === 'all' ? scopes : scopes.toSorted() + +/** + * What the program running may reach, as one short mark: its record scopes and + * what role access keeps from it. A kept answer is sealed for the mark its + * caller had (src/server/idempotency.ts), so once someone's access changes, a + * repeat of their own request no longer shows them what the first answer did. + */ +export const accessMark = Effect.gen(function* () { + const scopes = yield* CurrentAccess + const objects = yield* CurrentObjectAccess + + const held = { + scopes: scopes && { + read: sorted(scopes.read), + write: sorted(scopes.write), + active: scopes.active, + system: scopes.system === true, + }, + objects: objects && { + hidden: objects.hidden.toSorted(), + readOnly: objects.readOnly.toSorted(), + }, + } + + return createHash('sha256').update(JSON.stringify(held)).digest('base64url') +}) + /** * Runs a write once per `Idempotency-Key` for `caller` (src/server/idempotency.ts): * its body is read here, bounded, and the program is handed a request that @@ -453,11 +507,17 @@ export const idempotent = ( const url = new URL(request.url) const endpoint = `${request.method} ${url.pathname}${url.search}` - return yield* read === 'none' - ? program(again, body) - : replayable({ caller, endpoint, key: read.key, body }, program(again, body), { - keepFor: options.keepFor, - }) + if (read === 'none') { + return yield* program(again, body) + } + + const access = yield* accessMark + + return yield* replayable( + { caller, endpoint, key: read.key, body, access }, + program(again, body), + { keepFor: options.keepFor }, + ) }) /** Whether a request is from Swirls: `SWIRLS_APP_TOKEN` set (32+ characters) and sent as a bearer token. */ diff --git a/packages/spools/src/server/runtime/host.ts b/packages/spools/src/server/runtime/host.ts new file mode 100644 index 0000000..691014f --- /dev/null +++ b/packages/spools/src/server/runtime/host.ts @@ -0,0 +1,53 @@ +/** + * The web framework a Spool is mounted in, as far as the boundary needs it. + * + * Most of the boundary is handed its `Request` (a route, the HTTP API). A server + * function is not: TanStack Start keeps the request it is serving to itself, and + * says the answer's status and headers the same way. So the binding for a + * framework that works like that tells the boundary how to ask + * (src/start.ts does, for TanStack Start), and nothing in the + * framework-free server imports a web framework to find out. + * + * A Spool with no such framework (a headless one, a script, a test) installs + * none: its requests arrive as arguments. + */ +export type Host = { + /** The request being served. Throws outside one. */ + readonly request: () => Request + /** Sets a header on the answer to the request being served. */ + readonly setHeader: (name: string, value: string) => void + /** Sets the status of the answer to the request being served. */ + readonly setStatus: (status: number) => void +} + +declare global { + // Kept on `globalThis` like the runtime, so a dev reload doesn't lose it. + var spoolsHost: Host | undefined +} + +/** Says which web framework serves this process. Called once, by the framework's binding. */ +export const installHost = (host: Host): void => { + globalThis.spoolsHost = host +} + +/** The installed host. A server function with none is a mistake in how the Spool is mounted. */ +export const host = (): Host => { + const installed = globalThis.spoolsHost + + if (!installed) { + throw new Error( + 'A server function was called with no web framework installed. Import `@swirls/spools/start` in src/start.ts (TanStack Start), or call the operation through the HTTP API instead.', + ) + } + + return installed +} + +/** The request being served, or null: with no host, or outside a request (a schedule, a script). */ +export const hostRequest = (): Request | null => { + try { + return globalThis.spoolsHost?.request() ?? null + } catch { + return null + } +} diff --git a/packages/spools/src/server/runtime/session.ts b/packages/spools/src/server/runtime/session.ts index 217e75a..04bad74 100644 --- a/packages/spools/src/server/runtime/session.ts +++ b/packages/spools/src/server/runtime/session.ts @@ -1,8 +1,8 @@ -import { getRequest } from '@tanstack/react-start/server' import { Effect, Option } from 'effect' import { spool } from '../spool' import type { Session } from './auth' +import { hostRequest } from './host' import { CurrentRequest } from './request' /** @@ -12,7 +12,8 @@ import { CurrentRequest } from './request' * It comes from the request the boundary read (`CurrentRequest`). An app's own * code (a hook or handler in src/app/extensions.ts) calls back in through * src/server/extension-api.ts, outside the request's program, so it has none; - * for that, and only that, the auth adapter is asked here. + * for that, and only that, the auth adapter is asked here, about the request + * the installed host (runtime/host.ts) says it is serving. */ export const currentSession: Effect.Effect = Effect.gen(function* () { const request = yield* Effect.serviceOption(CurrentRequest) @@ -21,12 +22,16 @@ export const currentSession: Effect.Effect = Effect.gen(function return request.value.session } - return yield* Effect.promise(async () => { - try { - // Throws outside a request (a schedule, a script). - return await spool().auth.session(getRequest()) - } catch { - return null - } - }) + // Null outside a request (a schedule, a script), and in a Spool with no host. + const serving = hostRequest() + + if (!serving) { + return null + } + + return yield* Effect.promise(() => + spool() + .auth.session(serving) + .catch(() => null), + ) }) diff --git a/packages/spools/src/server/runtime/tokens.ts b/packages/spools/src/server/runtime/tokens.ts index 360716e..df7b5a3 100644 --- a/packages/spools/src/server/runtime/tokens.ts +++ b/packages/spools/src/server/runtime/tokens.ts @@ -37,6 +37,13 @@ export class Tokens extends Context.Service< * token would tell them, and the adapter logs why. */ readonly verify: (token: string, options: VerifyOptions) => Effect.Effect + /** + * True when the tokens are this server's own sessions (Better Auth with + * `bearer`): it signed each one for someone it signed in itself, so there + * is no other front end's token to tell apart, and `authorizedParties` is + * not read. `verifyToken` then takes a token in production with none named. + */ + readonly own?: boolean } >()('spools/Tokens') { /** A Spool whose auth adapter can't check a token: every token proves nothing. */ diff --git a/packages/spools/src/server/scopes.ts b/packages/spools/src/server/scopes.ts index ed0e493..5f2f8e3 100644 --- a/packages/spools/src/server/scopes.ts +++ b/packages/spools/src/server/scopes.ts @@ -439,10 +439,25 @@ export const asUser = export const SCOPE_COOKIE = 'spools-scope' /** - * The scope a request asks to work in, from its `SCOPE_COOKIE`: a scope's key, - * null for "all of mine" (`*`), undefined when it doesn't say. + * The header a caller of the HTTP API names its scope in (src/server/http.ts): + * a scope's key, or `*` for all of theirs. A preference like the cookie, and + * checked the same way. + */ +export const SCOPE_HEADER = 'x-spools-scope' + +/** + * The scope a request asks to work in, from its `SCOPE_HEADER` or else its + * `SCOPE_COOKIE`: a scope's key, null for "all of mine" (`*`), undefined when + * it doesn't say. */ export const wantedScope = (headers: Headers): string | null | undefined => { + // A caller that isn't a page of the CRM's own (the HTTP API) says it in a header instead. + const named = headers.get(SCOPE_HEADER)?.trim() + + if (named) { + return named === EVERY_SCOPE ? null : named + } + for (const part of (headers.get('cookie') ?? '').split(';')) { const at = part.indexOf('=') diff --git a/packages/spools/src/server/store/tables.ts b/packages/spools/src/server/store/tables.ts index 2fe6969..0c03bf1 100644 --- a/packages/spools/src/server/store/tables.ts +++ b/packages/spools/src/server/store/tables.ts @@ -511,6 +511,41 @@ repeat. Not a CRM object: no page, search or assistant reads it.`, indexes: [['caller', 'expiresAt']], }) +// ── API keys (src/server/api-keys.ts) ─────────────────────────────────────── + +export const ApiKey = defineTable({ + model: 'ApiKey', + name: 'api_keys', + doc: `A key a script or another service calls the HTTP API with, in place of a +person's session. It acts as one teammate, with their access and no more, for as +long as they are on the access list. Not a CRM object: no page, search or assistant +reads it.`, + columns: { + id: id(), + createdAt: createdAt(), + updatedAt: updatedAt(), + name: text({ doc: 'What it is for, as whoever made it said: "nightly export".' }), + userId: text({ doc: 'The teammate it acts as: their id at the auth provider.' }), + digest: text({ + doc: "The key's seal, made by the vault for this row: the hash of its secret half and what the key may do. The secret is shown once and never kept. Empty once revoked.", + }), + readOnly: withDefault( + boolean({ + doc: 'A key that may only read: every operation that changes something refuses it.', + }), + false, + ), + expiresAt: optional(timestamp({ doc: 'When it stops working, if it ever does.' })), + revokedAt: optional( + timestamp({ doc: 'When it was revoked. A revoked key never works again.' }), + ), + lastUsedAt: optional( + timestamp({ doc: 'When it last opened the API, to within a few minutes.' }), + ), + }, + indexes: [['userId']], +}) + // ── Change signals (src/server/signals.ts) ────────────────────────────────── /** @@ -551,5 +586,6 @@ export const systemTables: readonly AnyTable[] = [ MarketingPost, MarketingAd, IdempotentRequest, + ApiKey, ChangeSignal, ] diff --git a/packages/spools/src/server/workspace.functions.ts b/packages/spools/src/server/workspace.functions.ts index 449260b..1a89d80 100644 --- a/packages/spools/src/server/workspace.functions.ts +++ b/packages/spools/src/server/workspace.functions.ts @@ -1,590 +1,95 @@ import { createServerFn } from '@tanstack/react-start' -import { Effect } from 'effect' -import { z } from 'zod' -import { LOGGABLE, loggableKinds } from '../crm/activity' -import { cleanFilters, relationIds } from '../crm/filters' -import { activeRuns, sequencesTick } from './campaigns' -import * as records from './records' +import * as workspace from './operations/workspace' import { crmHandler } from './runtime/boundary' -import * as config from './runtime/config' -import { NotFound } from './runtime/errors' -import * as service from './service' -import { crmConfig, getObject } from './spool' -import { Users } from './users' -import * as views from './views' -import * as workspace from './workspace' /** - * Server functions for everything beside plain record CRUD: views, tasks, notes, - * favourites, reports, CSV and one-to-one email. Each checks the CRM session first. + * The interface's way in to views, tasks, notes, favourites, reports, CSV and + * one-to-one email. What each does is an operation + * (src/server/operations/workspace.ts), shared with the HTTP API; here it is + * only bound to TanStack Start. Each checks the CRM session first (`crmHandler`). */ -const objectKey = z.string().refine((k) => Object.hasOwn(crmConfig().objects, k), 'Unknown object') -const id = z.string().uuid() -const recordLink = { objectKey: objectKey.nullish(), recordId: id.nullish() } - -// ── Lists and views ───────────────────────────────────────────────────────── - -const filterValue = z.union([z.string(), z.number(), z.array(z.union([z.string(), z.number()]))]) - -const plainCondition = z.object({ - field: z.string(), - op: z.string(), - value: filterValue.optional(), -}) - -const condition = plainCondition.extend({ where: z.array(plainCondition).optional() }) -/** - * Filters and sort as the browser sends them: the shape only. What they may - * be, and how many, is decided by `cleanFilters` and `cleanSort`, which trim - * and drop rather than refuse, so an address someone edited by hand shows a - * list instead of an error. The page address is what bounds their size. - */ -const filtersInput = z.array(z.array(condition)) -const sortInput = z.array(z.object({ field: z.string(), dir: z.enum(['asc', 'desc']) })) -/** Search text, cut to a length worth searching for. */ -const searchText = z.string().transform((q) => q.slice(0, 200)) - -/** - * Everything a list page needs: the object's views, the active one, a page of - * rows, counts and footer calculations. `filters` and `sort` are what the page - * address carries when they differ from the saved view; without them the - * view's own are used. - */ export const getListFn = createServerFn({ method: 'GET' }) - .validator( - z.object({ - objectKey, - viewId: z.string().optional(), - q: searchText.optional(), - // A page number nobody could mean is the first page, not an error. - page: z.number().int().positive().max(10_000).catch(1).default(1), - filters: filtersInput.optional(), - sort: sortInput.optional(), - }), - ) - .handler( - crmHandler('workspace.getList', ({ data, user }) => - Effect.gen(function* () { - const all = yield* views.resolveViews(data.objectKey, user.id) - const view = all.find((v) => v.id === data.viewId) ?? all[0] - - if (!view) { - return yield* new NotFound({ what: 'View' }) - } - - const board = view.type === 'board' - const pageSize = board ? 500 : 50 - const page = board ? 1 : data.page - const { filters, sort } = views.activeSettings(data.objectKey, view, data) - const query = { objectKey: data.objectKey, q: data.q, filters, viewerId: user.id } - // A board puts up to 500 cards on the page and shows a few fields on each: fetch those and no more. - const obj = getObject(data.objectKey) - const totalled = Object.keys(obj.fields).find((k) => obj.fields[k]?.type === 'currency') - - const cardFields = board - ? [obj.titleField, view.settings.groupBy, ...view.settings.cardFields, totalled].filter( - (f) => f !== undefined, - ) - : undefined - - // A filter on a relation holds the related records' ids; the page shows their titles. - const named = Object.entries(relationIds(crmConfig().objects, data.objectKey, filters)) - - const [rows, total, calculations, filterTitles] = yield* Effect.all( - [ - records.listRecords({ - ...query, - sort, - limit: pageSize, - offset: (page - 1) * pageSize, - // A list shows a related record's title and links to it; it needs no more of it. - relations: 'titles', - fields: cardFields, - }), - records.countMatching(query), - views.calculate(data.objectKey, query, view.settings.calculations), - Effect.forEach( - named, - ([to, ids]) => - Effect.map(records.recordTitlesOf(to, ids), (found) => [to, found] as const), - { - concurrency: 'unbounded', - }, - ), - ], - { concurrency: 'unbounded' }, - ) - - const titles: Record = {} - - for (const [to, found] of filterTitles) { - titles[to] = [...found].map(([recordId, title]) => ({ id: recordId, title })) - } - - return { - views: all, - view, - /** The filters and sort in force: the view's, or the ones the page address carries. */ - active: { filters, sort }, - rows, - total, - hasMore: page * pageSize < total, - calculations, - titles, - } - }), - ), - ) - -const viewPatch = z.object({ - label: z.string().trim().min(1).max(80).optional(), - columns: z.array(z.string()).max(60).optional(), - sort: sortInput.optional(), - filters: filtersInput.optional(), - groupBy: z.string().optional(), - cardFields: z.array(z.string()).max(12).optional(), - calculations: z - .record(z.string(), z.enum(['sum', 'avg', 'min', 'max', 'filled', 'empty'])) - .optional(), -}) + .validator(workspace.getList.input) + .handler(crmHandler(workspace.getList.name, workspace.getList.run)) export const saveViewFn = createServerFn({ method: 'POST' }) - .validator(z.object({ objectKey, viewId: z.string(), patch: viewPatch })) - .handler( - crmHandler('workspace.saveView', ({ data, user }) => - Effect.gen(function* () { - const { filters, ...rest } = data.patch - // Filters left out of the patch keep the view's own. - const patch: views.ViewPatch = { ...rest } - - if (filters) { - patch.filters = cleanFilters(crmConfig().objects, data.objectKey, filters) - } - - yield* views.saveView(data.objectKey, data.viewId, patch, user.id) - - return { ok: true } - }), - ), - ) + .validator(workspace.saveView.input) + .handler(crmHandler(workspace.saveView.name, workspace.saveView.run)) export const createViewFn = createServerFn({ method: 'POST' }) - .validator( - z.object({ - objectKey, - label: z.string().trim().min(1).max(80), - type: z.enum(['table', 'board']), - copyFrom: z.string().optional(), - /** The filters and sort on screen, to save with the new view. */ - filters: filtersInput.optional(), - sort: sortInput.optional(), - /** Only the person creating it will see it. */ - private: z.boolean().optional(), - }), - ) - .handler( - crmHandler('workspace.createView', ({ data, user }) => - Effect.gen(function* () { - const { filters, sort: sorted, ...input } = data - - // What isn't given is copied from the view it starts from. - const settings: Partial> = {} - - if (filters) { - settings.filters = cleanFilters(crmConfig().objects, data.objectKey, filters) - } - - if (sorted) { - settings.sort = sorted - } - - return { id: yield* views.createView(data.objectKey, { ...input, settings }, user.id) } - }), - ), - ) + .validator(workspace.createView.input) + .handler(crmHandler(workspace.createView.name, workspace.createView.run)) export const deleteViewFn = createServerFn({ method: 'POST' }) - .validator(z.object({ objectKey, viewId: z.string() })) - .handler( - crmHandler('workspace.deleteView', ({ data, user }) => - Effect.gen(function* () { - yield* views.deleteView(data.objectKey, data.viewId, user.id) - return { ok: true } - }), - ), - ) - -// ── Import / export ───────────────────────────────────────────────────────── + .validator(workspace.deleteView.input) + .handler(crmHandler(workspace.deleteView.name, workspace.deleteView.run)) export const exportCsvFn = createServerFn({ method: 'GET' }) - .validator( - z.object({ - objectKey, - viewId: z.string().optional(), - q: searchText.optional(), - filters: filtersInput.optional(), - sort: sortInput.optional(), - }), - ) - .handler( - crmHandler('workspace.exportCsv', ({ data, user }) => - Effect.gen(function* () { - const all = yield* views.resolveViews(data.objectKey, user.id) - const view = all.find((v) => v.id === data.viewId) ?? all[0] + .validator(workspace.exportCsv.input) + .handler(crmHandler(workspace.exportCsv.name, workspace.exportCsv.run)) - if (!view) { - return yield* new NotFound({ what: 'View' }) - } - - // What is on screen: the filters and sort in the page address when it carries them, else the view's. - const { filters, sort: sorted } = views.activeSettings(data.objectKey, view, data) - return { - csv: yield* workspace.exportCsv(data.objectKey, { - q: data.q, - filters, - sort: sorted, - viewerId: user.id, - }), - } - }), - ), - ) - -/** - * The records of one object that an import's relation cells name, by title or - * id. Matching happens here, against every record of the object, so the browser - * needn't hold (and be limited to) a list of titles. - */ export const matchRelationTitlesFn = createServerFn({ method: 'POST' }) - .validator(z.object({ objectKey, values: z.array(z.string().max(2000)).min(1).max(1000) })) - .handler( - crmHandler('workspace.matchRelationTitles', ({ data }) => - records.matchTitles(data.objectKey, data.values), - ), - ) + .validator(workspace.matchRelationTitles.input) + .handler(crmHandler(workspace.matchRelationTitles.name, workspace.matchRelationTitles.run)) -/** Create records from parsed CSV rows: `service.importRecords`. */ export const importRecordsFn = createServerFn({ method: 'POST' }) - .validator( - z.object({ - objectKey, - rows: z - .array(z.record(z.string().max(60), z.string().max(20_000))) - .min(1) - .max(1000), - }), - ) - .handler( - crmHandler('workspace.importRecords', ({ data, user }) => - service.importRecords(data.objectKey, data.rows, user), - ), - ) - -// ── Tasks ─────────────────────────────────────────────────────────────────── - -const dueDate = z - .string() - .regex(/^\d{4}-\d{2}-\d{2}$/) - .nullish() + .validator(workspace.importRecords.input) + .handler(crmHandler(workspace.importRecords.name, workspace.importRecords.run)) export const listTasksFn = createServerFn({ method: 'GET' }) - .validator(z.object({ scope: z.enum(['mine', 'all']).default('mine'), ...recordLink })) - .handler( - crmHandler('workspace.listTasks', ({ data, user }) => - workspace.listTasks({ - assigneeId: data.scope === 'mine' && !data.recordId ? user.id : undefined, - objectKey: data.objectKey ?? undefined, - recordId: data.recordId ?? undefined, - }), - ), - ) + .validator(workspace.listTasks.input) + .handler(crmHandler(workspace.listTasks.name, workspace.listTasks.run)) export const createTaskFn = createServerFn({ method: 'POST' }) - .validator( - z.object({ - title: z.string().trim().min(1).max(500), - dueDate, - assigneeId: z.string().max(200).nullish(), - ...recordLink, - }), - ) - .handler( - crmHandler('workspace.createTask', ({ data, user }) => - Effect.gen(function* () { - const task = yield* workspace.createTask(data, user.id) - - if (data.objectKey && data.recordId) { - yield* records.addActivity({ - objectKey: data.objectKey, - recordId: data.recordId, - kind: 'task', - summary: `added a task: ${data.title}`, - actor: user.name, - actorId: user.id, - }) - } - - return { id: task.id } - }), - ), - ) + .validator(workspace.createTask.input) + .handler(crmHandler(workspace.createTask.name, workspace.createTask.run)) export const updateTaskFn = createServerFn({ method: 'POST' }) - .validator( - z.object({ - id, - title: z.string().trim().min(1).max(500).optional(), - dueDate, - assigneeId: z.string().max(200).nullish(), - completed: z.boolean().optional(), - }), - ) - .handler( - crmHandler('workspace.updateTask', ({ data, user }) => - Effect.gen(function* () { - const { id: taskId, ...patch } = data - const task = yield* workspace.updateTask(taskId, patch, user.id) - - if (task && data.completed && task.objectKey && task.recordId) { - yield* records.addActivity({ - objectKey: task.objectKey, - recordId: task.recordId, - kind: 'task', - summary: `completed a task: ${task.title}`, - actor: user.name, - actorId: user.id, - }) - } - - return { ok: true } - }), - ), - ) + .validator(workspace.updateTask.input) + .handler(crmHandler(workspace.updateTask.name, workspace.updateTask.run)) export const deleteTaskFn = createServerFn({ method: 'POST' }) - .validator(z.object({ id })) - .handler( - crmHandler('workspace.deleteTask', ({ data }) => - Effect.gen(function* () { - yield* workspace.deleteTask(data.id) - return { ok: true } - }), - ), - ) - -// ── Notes ─────────────────────────────────────────────────────────────────── + .validator(workspace.deleteTask.input) + .handler(crmHandler(workspace.deleteTask.name, workspace.deleteTask.run)) export const listNotesFn = createServerFn({ method: 'GET' }) - .validator(z.object(recordLink)) - .handler( - crmHandler('workspace.listNotes', ({ data }) => - workspace.listNotes({ - objectKey: data.objectKey ?? undefined, - recordId: data.recordId ?? undefined, - }), - ), - ) + .validator(workspace.listNotes.input) + .handler(crmHandler(workspace.listNotes.name, workspace.listNotes.run)) export const saveNoteFn = createServerFn({ method: 'POST' }) - .validator( - z.object({ - id: id.optional(), - title: z.string().trim().max(200), - body: z.string().max(50_000), - ...recordLink, - }), - ) - .handler( - crmHandler('workspace.saveNote', ({ data, user }) => - Effect.gen(function* () { - if (data.id) { - yield* workspace.updateNote(data.id, { - title: data.title || 'Untitled note', - body: data.body, - }) - - return { id: data.id } - } - - const note = yield* workspace.createNote(data, user) - - if (data.objectKey && data.recordId) { - yield* records.addActivity({ - objectKey: data.objectKey, - recordId: data.recordId, - kind: 'note', - summary: `added a note: ${note.title}`, - actor: user.name, - actorId: user.id, - }) - } - - return { id: note.id } - }), - ), - ) + .validator(workspace.saveNote.input) + .handler(crmHandler(workspace.saveNote.name, workspace.saveNote.run)) export const deleteNoteFn = createServerFn({ method: 'POST' }) - .validator(z.object({ id })) - .handler( - crmHandler('workspace.deleteNote', ({ data }) => - Effect.gen(function* () { - yield* workspace.deleteNote(data.id) - return { ok: true } - }), - ), - ) - -// ── Favourites ────────────────────────────────────────────────────────────── + .validator(workspace.deleteNote.input) + .handler(crmHandler(workspace.deleteNote.name, workspace.deleteNote.run)) export const toggleFavoriteFn = createServerFn({ method: 'POST' }) - .validator(z.object({ objectKey, recordId: id })) - .handler( - crmHandler('workspace.toggleFavorite', ({ data, user }) => - Effect.gen(function* () { - return { favorite: yield* workspace.toggleFavorite(user.id, data.objectKey, data.recordId) } - }), - ), - ) - -// ── Reports ───────────────────────────────────────────────────────────────── + .validator(workspace.toggleFavorite.input) + .handler(crmHandler(workspace.toggleFavorite.name, workspace.toggleFavorite.run)) export const reportsFn = createServerFn({ method: 'GET' }).handler( - crmHandler('workspace.reports', () => - Effect.gen(function* () { - return yield* workspace.buildReports(yield* (yield* Users).team) - }), - ), + crmHandler(workspace.reports.name, workspace.reports.run), ) -// ── Logged activities and the activity report ─────────────────────────────── - -/** Log a call or meeting on a record. */ export const logActivityFn = createServerFn({ method: 'POST' }) - .validator( - z - .object({ - objectKey, - recordId: id, - kind: z.literal(loggableKinds), - outcome: z.string().max(40).nullish(), - /** When it took place; now if omitted. */ - occurredAt: z.coerce.date().nullish(), - notes: z.string().max(20_000).nullish(), - }) - .refine((d) => !d.outcome || LOGGABLE[d.kind].outcomes.some((o) => o.value === d.outcome), { - message: 'Unknown outcome', - path: ['outcome'], - }), - ) - .handler( - crmHandler('workspace.logActivity', ({ data, user }) => - Effect.gen(function* () { - if (!(yield* records.getRecord(data.objectKey, data.recordId))) { - return yield* new NotFound({ what: 'Record' }) - } - - const activity = yield* workspace.logActivity(data, user) + .validator(workspace.logActivity.input) + .handler(crmHandler(workspace.logActivity.name, workspace.logActivity.run)) - return { id: activity.id } - }), - ), - ) - -/** A report range: `from` inclusive, `to` exclusive, at most two years apart. */ -const reportRange = z - .object({ from: z.coerce.date(), to: z.coerce.date() }) - .refine( - (r) => r.to > r.from && r.to.getTime() - r.from.getTime() <= 732 * 86_400_000, - 'Pick a range of up to two years', - ) - -/** Calls, emails, meetings, completed tasks and notes per teammate. */ export const activityReportFn = createServerFn({ method: 'GET' }) - .validator(reportRange) - .handler( - crmHandler('workspace.activityReport', ({ data }) => - Effect.gen(function* () { - return yield* workspace.activityReport(data, yield* (yield* Users).team) - }), - ), - ) + .validator(workspace.activityReport.input) + .handler(crmHandler(workspace.activityReport.name, workspace.activityReport.run)) export const activityReportCsvFn = createServerFn({ method: 'GET' }) - .validator(reportRange) - .handler( - crmHandler('workspace.activityReportCsv', ({ data }) => - Effect.gen(function* () { - return { - csv: workspace.activityReportCsv( - yield* workspace.activityReport(data, yield* (yield* Users).team), - ), - } - }), - ), - ) - -// ── Email ─────────────────────────────────────────────────────────────────── + .validator(workspace.activityReportCsv.input) + .handler(crmHandler(workspace.activityReportCsv.name, workspace.activityReportCsv.run)) -/** Send a one-to-one email to a record's address and keep it on the timeline. */ export const sendEmailFn = createServerFn({ method: 'POST' }) - .validator( - z.object({ - objectKey, - recordId: id, - field: z.string(), - subject: z.string().trim().min(1).max(300), - body: z.string().trim().min(1).max(20_000), - /** Which of their mailboxes to send from, when the teammate has more than one. */ - from: z - .object({ provider: z.enum(['google', 'microsoft']), accountEmail: z.string().max(320) }) - .optional(), - }), - ) - .handler( - crmHandler('workspace.sendEmail', ({ data, user }) => workspace.sendRecordEmail(data, user)), - ) + .validator(workspace.sendEmail.input) + .handler(crmHandler(workspace.sendEmail.name, workspace.sendEmail.run)) -// ── Workflows ─────────────────────────────────────────────────────────────── - -/** What runs automatically: config automations, record actions, and email sequences, with recent runs. */ export const workflowsFn = createServerFn({ method: 'GET' }).handler( - crmHandler('workspace.workflows', () => - Effect.gen(function* () { - const recent = (yield* records.recentActivities(200)).filter( - (a) => a.kind === 'workflow' || a.kind === 'campaign' || a.kind === 'email', - ) - - const [titles, active] = yield* Effect.all([workspace.recordTitles(recent), activeRuns()], { - concurrency: 2, - }) - - return { - swirlsConfigured: !!(yield* config.variable('SWIRLS_PROJECT_ID')), - emailConfigured: - !!(yield* config.variable('RESEND_API_KEY')) && !!(yield* config.variable('EMAIL_FROM')), - // Only worth saying when there are sequences to run. - sequencesTick: - Object.keys(crmConfig().campaigns).length === 0 || - sequencesTick(yield* config.environment), - automations: crmConfig().automations, - actions: Object.entries(crmConfig().objects).flatMap(([key, obj]) => - obj.actions.map((a) => ({ objectKey: key, label: a.label, run: a.run })), - ), - sequences: Object.entries(crmConfig().campaigns).map(([key, c]) => ({ - key, - label: c.label, - objectKey: c.object, - steps: c.steps.map((s) => ({ id: s.id, wait: s.wait, subject: s.subject })), - stopWhen: c.stopWhen, - active: active[key] ?? 0, - })), - runs: recent - .slice(0, 30) - .map((a) => ({ ...a, recordTitle: titles[`${a.objectKey}:${a.recordId}`] ?? null })), - } - }), - ), + crmHandler(workspace.workflows.name, workspace.workflows.run), ) diff --git a/packages/spools/src/start.ts b/packages/spools/src/start.ts new file mode 100644 index 0000000..8efa974 --- /dev/null +++ b/packages/spools/src/start.ts @@ -0,0 +1,54 @@ +import { + type AnyRequestMiddleware, + createCsrfMiddleware, + createIsomorphicFn, + createMiddleware, +} from '@tanstack/react-start' +import { getRequest, setResponseHeader, setResponseStatus } from '@tanstack/react-start/server' + +import { installHost } from './server/runtime/host' +import { spool } from './server/spool' + +declare module './server/runtime/auth' { + interface HostMiddleware { + /** A TanStack Start request middleware (Clerk's, which reads its session there). */ + start: AnyRequestMiddleware + } +} + +/** + * A Spool's binding to TanStack Start: the request middleware every Spool on it + * needs, for `createStart` in the app's src/start.ts, and how the boundary + * reaches the request a server function is serving (server/runtime/host.ts). + * Besides the server functions themselves (server/*.functions.ts), this is the + * only file on the server's side that imports TanStack Start. + */ + +// This file is loaded in the browser too (src/start.ts is), so the server's half +// is said in a way the compiler takes out of the browser's copy, imports and all. +const bindHost = createIsomorphicFn().server(() => { + installHost({ + request: getRequest, + setHeader: setResponseHeader, + setStatus: setResponseStatus, + }) +}) + +bindHost() + +/** + * Reject cross-site requests to anything a signed-in browser can call with its + * session cookie: server functions and the assistant chat endpoint. Other /api + * routes authenticate with a bearer token or a signature, not the cookie. + */ +export const csrfMiddleware = createCsrfMiddleware({ + filter: (ctx) => + ctx.handlerType === 'serverFn' || + new URL(ctx.request.url).pathname.startsWith('/api/assistant'), +}) + +/** Runs the auth adapter's own middleware, if it has one (Clerk reads its session there). */ +export const authMiddleware = createMiddleware().server((ctx) => { + const own = spool().auth.middleware?.options.server + return own ? own(ctx) : ctx.next() +}) diff --git a/packages/spools/tests/fixtures/baseline/example.schema.prisma b/packages/spools/tests/fixtures/baseline/example.schema.prisma index c1fb6ca..7dda68d 100644 --- a/packages/spools/tests/fixtures/baseline/example.schema.prisma +++ b/packages/spools/tests/fixtures/baseline/example.schema.prisma @@ -485,6 +485,34 @@ model IdempotentRequest { @@rls } +/// A key a script or another service calls the HTTP API with, in place of a +/// person's session. It acts as one teammate, with their access and no more, for as +/// long as they are on the access list. Not a CRM object: no page, search or assistant +/// reads it. +model ApiKey { + id String @id @onCreate(uuid()) + createdAt DateTime @default(now()) @onCreate(now()) @map("created_at") + updatedAt temporal.UpdatedAt @map("updated_at") + /// What it is for, as whoever made it said: "nightly export". + name String + /// The teammate it acts as: their id at the auth provider. + userId String @map("user_id") + /// The key's seal, made by the vault for this row: the hash of its secret half and what the key may do. The secret is shown once and never kept. Empty once revoked. + digest String + /// A key that may only read: every operation that changes something refuses it. + readOnly Boolean @default(false) @map("read_only") + /// When it stops working, if it ever does. + expiresAt DateTime? @map("expires_at") + /// When it was revoked. A revoked key never works again. + revokedAt DateTime? @map("revoked_at") + /// When it last opened the API, to within a few minutes. + lastUsedAt DateTime? @map("last_used_at") + + @@index([userId]) + @@map("api_keys") + @@rls +} + /// When something last changed, by key: an object ("jobs") or one record ("jobs:"). /// Touched after every committed change to a record, its timeline, tasks and notes /// (src/server/signals.ts); a page asks whether its keys moved (`changedSince`). diff --git a/packages/spools/tests/fixtures/baseline/example.schema.sql b/packages/spools/tests/fixtures/baseline/example.schema.sql index c31bffa..2f68a37 100644 --- a/packages/spools/tests/fixtures/baseline/example.schema.sql +++ b/packages/spools/tests/fixtures/baseline/example.schema.sql @@ -260,6 +260,18 @@ ALTER TABLE "public"."idempotent_requests" ADD COLUMN IF NOT EXISTS "content_typ ALTER TABLE "public"."idempotent_requests" ADD COLUMN IF NOT EXISTS "claim" text; ALTER TABLE "public"."idempotent_requests" ADD COLUMN IF NOT EXISTS "expires_at" timestamptz(3); ALTER TABLE "public"."idempotent_requests" ENABLE ROW LEVEL SECURITY; +CREATE TABLE IF NOT EXISTS "public"."api_keys" ("id" text NOT NULL PRIMARY KEY, "created_at" timestamptz(3) NOT NULL DEFAULT now(), "updated_at" timestamptz(3) NOT NULL, "name" text NOT NULL, "user_id" text NOT NULL, "digest" text NOT NULL, "read_only" boolean NOT NULL DEFAULT false, "expires_at" timestamptz(3), "revoked_at" timestamptz(3), "last_used_at" timestamptz(3)); +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "id" text; +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "created_at" timestamptz(3) DEFAULT now(); +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "updated_at" timestamptz(3); +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "name" text; +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "user_id" text; +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "digest" text; +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "read_only" boolean DEFAULT false; +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "expires_at" timestamptz(3); +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "revoked_at" timestamptz(3); +ALTER TABLE "public"."api_keys" ADD COLUMN IF NOT EXISTS "last_used_at" timestamptz(3); +ALTER TABLE "public"."api_keys" ENABLE ROW LEVEL SECURITY; CREATE TABLE IF NOT EXISTS "public"."change_signals" ("id" text NOT NULL PRIMARY KEY, "key" text NOT NULL, "stamp" text NOT NULL, "updated_at" timestamptz(3) NOT NULL); ALTER TABLE "public"."change_signals" ADD COLUMN IF NOT EXISTS "id" text; ALTER TABLE "public"."change_signals" ADD COLUMN IF NOT EXISTS "key" text; @@ -486,6 +498,17 @@ DO $$ DECLARE stale record; BEGIN EXECUTE format('DROP INDEX "public".%I', stale.name); END LOOP; END $$; +DO $$ DECLARE stale record; BEGIN + FOR stale IN + SELECT c.relname AS name FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid + WHERE i.indrelid = '"public"."api_keys"'::regclass + AND NOT i.indisprimary + AND NOT EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conindid = i.indexrelid) + AND c.relname <> ALL (ARRAY['api_keys_user_id_idx']::text[]) + LOOP + EXECUTE format('DROP INDEX "public".%I', stale.name); + END LOOP; +END $$; DO $$ DECLARE stale record; BEGIN FOR stale IN SELECT c.relname AS name FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid @@ -531,6 +554,7 @@ CREATE INDEX IF NOT EXISTS "marketing_posts_created_at_idx" ON "public"."marketi CREATE UNIQUE INDEX IF NOT EXISTS "marketing_ads_account_external_id_key" ON "public"."marketing_ads" ("account", "external_id"); CREATE UNIQUE INDEX IF NOT EXISTS "idempotent_requests_caller_endpoint_key_key" ON "public"."idempotent_requests" ("caller", "endpoint", "key"); CREATE INDEX IF NOT EXISTS "idempotent_requests_caller_expires_at_idx" ON "public"."idempotent_requests" ("caller", "expires_at"); +CREATE INDEX IF NOT EXISTS "api_keys_user_id_idx" ON "public"."api_keys" ("user_id"); CREATE UNIQUE INDEX IF NOT EXISTS "change_signals_key_key" ON "public"."change_signals" ("key"); DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'contacts_company_id_fkey' AND conrelid = '"public"."contacts"'::regclass) THEN diff --git a/packages/spools/tests/fixtures/scoped/prisma/schema.d.ts b/packages/spools/tests/fixtures/scoped/prisma/schema.d.ts index a28794a..27878a6 100644 --- a/packages/spools/tests/fixtures/scoped/prisma/schema.d.ts +++ b/packages/spools/tests/fixtures/scoped/prisma/schema.d.ts @@ -23,9 +23,9 @@ import type { } from '@internal/contract/types'; export type StorageHash = - StorageHashBase<'fada8402e686c2065f31b35da711cfed40fa0a8e4a5ac0fb14174c76e322aa75'>; + StorageHashBase<'ebaeeeef35bdf29971c5d02e8630d078f2aadb287758fcd4f6a85232854e32b9'>; export type ExecutionHash = - ExecutionHashBase<'571130d7991375dbce3e8b6266c99aa28248fe510f2a545830414a81425ad407'>; + ExecutionHashBase<'8a48ad2178718d87bf0c8f5f4e99c221732655233cf296caf97fea9598d9d3d1'>; export type ProfileHash = ProfileHashBase<'3916f444a8a17ad749191acf9e08dad97d1a327b88c2f1d45d12f240296aa8b2'>; @@ -326,6 +326,19 @@ export namespace Models { summary: FieldOutputTypes['public']['Activity']['summary']; readonly [RelationKeys]?: never; }; + export type public_ApiKey = { + createdAt: FieldOutputTypes['public']['ApiKey']['createdAt']; + digest: FieldOutputTypes['public']['ApiKey']['digest']; + expiresAt: FieldOutputTypes['public']['ApiKey']['expiresAt']; + id: FieldOutputTypes['public']['ApiKey']['id']; + lastUsedAt: FieldOutputTypes['public']['ApiKey']['lastUsedAt']; + name: FieldOutputTypes['public']['ApiKey']['name']; + readOnly: FieldOutputTypes['public']['ApiKey']['readOnly']; + revokedAt: FieldOutputTypes['public']['ApiKey']['revokedAt']; + updatedAt: FieldOutputTypes['public']['ApiKey']['updatedAt']; + userId: FieldOutputTypes['public']['ApiKey']['userId']; + readonly [RelationKeys]?: never; + }; export type public_ChangeSignal = { id: FieldOutputTypes['public']['ChangeSignal']['id']; key: FieldOutputTypes['public']['ChangeSignal']['key']; @@ -732,6 +745,7 @@ export namespace Models { export declare const models: { public: { Activity: Models.public_Activity; + ApiKey: Models.public_ApiKey; ChangeSignal: Models.public_ChangeSignal; Company: Models.public_Company; Contact: Models.public_Contact; @@ -910,6 +924,91 @@ type ContractBase = Omit< ]; foreignKeys: readonly []; }; + readonly api_keys: { + columns: { + readonly created_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: false; + readonly default: { readonly kind: 'function'; readonly expression: 'now()' }; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly digest: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + readonly expires_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: true; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly id: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + readonly last_used_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: true; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly name: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + readonly read_only: { + readonly dataType: 'pg/bool'; + readonly codecId: 'pg/bool@1'; + readonly nullable: false; + readonly default: { + readonly kind: 'literal'; + readonly value: DefaultLiteralValue<'pg/bool@1', false>; + }; + readonly many: false; + }; + readonly revoked_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: true; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly updated_at: { + readonly dataType: 'pg/timestamptz'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly nullable: false; + readonly typeParams: { readonly precision: 3 }; + readonly many: false; + }; + readonly user_id: { + readonly dataType: 'pg/text'; + readonly codecId: 'pg/text@1'; + readonly nullable: false; + readonly many: false; + }; + }; + primaryKey: { readonly columns: readonly ['id'] }; + uniques: readonly []; + indexes: readonly [ + { + readonly name: 'api_keys_user_id_idx_6c952402'; + readonly prefix: 'api_keys_user_id_idx'; + readonly columns: readonly ['user_id']; + readonly unique: false; + }, + ]; + foreignKeys: readonly []; + }; readonly change_signals: { columns: { readonly id: { @@ -3427,6 +3526,7 @@ type ContractBase = Omit< readonly targetFamily: 'sql'; readonly roots: { readonly activities: { readonly namespace: 'public' & NamespaceId; readonly model: 'Activity' }; + readonly api_keys: { readonly namespace: 'public' & NamespaceId; readonly model: 'ApiKey' }; readonly change_signals: { readonly namespace: 'public' & NamespaceId; readonly model: 'ChangeSignal'; @@ -3602,6 +3702,87 @@ type ContractBase = Omit< }; }; }; + readonly ApiKey: { + readonly fields: { + readonly createdAt: { + readonly nullable: false; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly digest: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + readonly expiresAt: { + readonly nullable: true; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly id: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + readonly lastUsedAt: { + readonly nullable: true; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly name: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + readonly readOnly: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/bool@1' }; + }; + readonly revokedAt: { + readonly nullable: true; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly updatedAt: { + readonly nullable: false; + readonly type: { + readonly kind: 'scalar'; + readonly codecId: 'pg/timestamptz-date@1'; + readonly typeParams: { readonly precision: 3 }; + }; + }; + readonly userId: { + readonly nullable: false; + readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' }; + }; + }; + readonly relations: Record; + readonly storage: { + readonly table: 'api_keys'; + readonly namespaceId: 'public'; + readonly fields: { + readonly createdAt: { readonly column: 'created_at' }; + readonly digest: { readonly column: 'digest' }; + readonly expiresAt: { readonly column: 'expires_at' }; + readonly id: { readonly column: 'id' }; + readonly lastUsedAt: { readonly column: 'last_used_at' }; + readonly name: { readonly column: 'name' }; + readonly readOnly: { readonly column: 'read_only' }; + readonly revokedAt: { readonly column: 'revoked_at' }; + readonly updatedAt: { readonly column: 'updated_at' }; + readonly userId: { readonly column: 'user_id' }; + }; + }; + }; readonly ChangeSignal: { readonly fields: { readonly id: { @@ -6045,6 +6226,43 @@ type ContractBase = Omit< readonly namespace: 'public'; }; }, + { + readonly onCreate: { + readonly id: 'timestampNow'; + readonly kind: 'generator'; + readonly params: { readonly precision: 3 }; + }; + readonly ref: { + readonly entry: 'api_keys'; + readonly field: 'created_at'; + readonly namespace: 'public'; + }; + }, + { + readonly onCreate: { readonly id: 'uuidv4'; readonly kind: 'generator' }; + readonly ref: { + readonly entry: 'api_keys'; + readonly field: 'id'; + readonly namespace: 'public'; + }; + }, + { + readonly onCreate: { + readonly id: 'timestampNow'; + readonly kind: 'generator'; + readonly params: { readonly precision: 3 }; + }; + readonly onUpdate: { + readonly id: 'timestampNow'; + readonly kind: 'generator'; + readonly params: { readonly precision: 3 }; + }; + readonly ref: { + readonly entry: 'api_keys'; + readonly field: 'updated_at'; + readonly namespace: 'public'; + }; + }, { readonly onCreate: { readonly id: 'uuidv4'; readonly kind: 'generator' }; readonly ref: { diff --git a/packages/spools/tests/fixtures/scoped/prisma/schema.json b/packages/spools/tests/fixtures/scoped/prisma/schema.json index 3db6e81..ab56492 100644 --- a/packages/spools/tests/fixtures/scoped/prisma/schema.json +++ b/packages/spools/tests/fixtures/scoped/prisma/schema.json @@ -8,6 +8,10 @@ "model": "Activity", "namespace": "public" }, + "api_keys": { + "model": "ApiKey", + "namespace": "public" + }, "change_signals": { "model": "ChangeSignal", "namespace": "public" @@ -290,6 +294,132 @@ "table": "activities" } }, + "ApiKey": { + "fields": { + "createdAt": { + "nullable": false, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "digest": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + }, + "expiresAt": { + "nullable": true, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "id": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + }, + "lastUsedAt": { + "nullable": true, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "name": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + }, + "readOnly": { + "nullable": false, + "type": { + "codecId": "pg/bool@1", + "kind": "scalar" + } + }, + "revokedAt": { + "nullable": true, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "updatedAt": { + "nullable": false, + "type": { + "codecId": "pg/timestamptz-date@1", + "kind": "scalar", + "typeParams": { + "precision": 3 + } + } + }, + "userId": { + "nullable": false, + "type": { + "codecId": "pg/text@1", + "kind": "scalar" + } + } + }, + "relations": {}, + "storage": { + "fields": { + "createdAt": { + "column": "created_at" + }, + "digest": { + "column": "digest" + }, + "expiresAt": { + "column": "expires_at" + }, + "id": { + "column": "id" + }, + "lastUsedAt": { + "column": "last_used_at" + }, + "name": { + "column": "name" + }, + "readOnly": { + "column": "read_only" + }, + "revokedAt": { + "column": "revoked_at" + }, + "updatedAt": { + "column": "updated_at" + }, + "userId": { + "column": "user_id" + } + }, + "namespaceId": "public", + "table": "api_keys" + } + }, "ChangeSignal": { "fields": { "id": { @@ -4152,6 +4282,11 @@ "namespaceId": "public", "tableName": "activities" }, + "api_keys": { + "kind": "rls", + "namespaceId": "public", + "tableName": "api_keys" + }, "change_signals": { "kind": "rls", "namespaceId": "public", @@ -4451,6 +4586,100 @@ } ] }, + "api_keys": { + "columns": { + "created_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "default": { + "expression": "now()", + "kind": "function" + }, + "nullable": false, + "typeParams": { + "precision": 3 + } + }, + "digest": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + }, + "expires_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": true, + "typeParams": { + "precision": 3 + } + }, + "id": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + }, + "last_used_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": true, + "typeParams": { + "precision": 3 + } + }, + "name": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + }, + "read_only": { + "codecId": "pg/bool@1", + "dataType": "pg/bool", + "default": { + "kind": "literal", + "value": false + }, + "nullable": false + }, + "revoked_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": true, + "typeParams": { + "precision": 3 + } + }, + "updated_at": { + "codecId": "pg/timestamptz-date@1", + "dataType": "pg/timestamptz", + "nullable": false, + "typeParams": { + "precision": 3 + } + }, + "user_id": { + "codecId": "pg/text@1", + "dataType": "pg/text", + "nullable": false + } + }, + "foreignKeys": [], + "indexes": [ + { + "columns": [ + "user_id" + ], + "name": "api_keys_user_id_idx_6c952402", + "prefix": "api_keys_user_id_idx", + "unique": false + } + ], + "primaryKey": { + "columns": [ + "id" + ] + }, + "uniques": [] + }, "change_signals": { "columns": { "id": { @@ -7338,10 +7567,10 @@ "kind": "postgres-schema" } }, - "storageHash": "fada8402e686c2065f31b35da711cfed40fa0a8e4a5ac0fb14174c76e322aa75" + "storageHash": "ebaeeeef35bdf29971c5d02e8630d078f2aadb287758fcd4f6a85232854e32b9" }, "execution": { - "executionHash": "571130d7991375dbce3e8b6266c99aa28248fe510f2a545830414a81425ad407", + "executionHash": "8a48ad2178718d87bf0c8f5f4e99c221732655233cf296caf97fea9598d9d3d1", "mutations": { "defaults": [ { @@ -7369,6 +7598,52 @@ "namespace": "public" } }, + { + "onCreate": { + "id": "timestampNow", + "kind": "generator", + "params": { + "precision": 3 + } + }, + "ref": { + "entry": "api_keys", + "field": "created_at", + "namespace": "public" + } + }, + { + "onCreate": { + "id": "uuidv4", + "kind": "generator" + }, + "ref": { + "entry": "api_keys", + "field": "id", + "namespace": "public" + } + }, + { + "onCreate": { + "id": "timestampNow", + "kind": "generator", + "params": { + "precision": 3 + } + }, + "onUpdate": { + "id": "timestampNow", + "kind": "generator", + "params": { + "precision": 3 + } + }, + "ref": { + "entry": "api_keys", + "field": "updated_at", + "namespace": "public" + } + }, { "onCreate": { "id": "uuidv4", diff --git a/packages/spools/tests/fixtures/scoped/prisma/schema.prisma b/packages/spools/tests/fixtures/scoped/prisma/schema.prisma index 15fb7e8..bde0574 100644 --- a/packages/spools/tests/fixtures/scoped/prisma/schema.prisma +++ b/packages/spools/tests/fixtures/scoped/prisma/schema.prisma @@ -649,6 +649,34 @@ model IdempotentRequest { @@rls } +/// A key a script or another service calls the HTTP API with, in place of a +/// person's session. It acts as one teammate, with their access and no more, for as +/// long as they are on the access list. Not a CRM object: no page, search or assistant +/// reads it. +model ApiKey { + id String @id @onCreate(uuid()) + createdAt DateTime @default(now()) @onCreate(now()) @map("created_at") + updatedAt temporal.UpdatedAt @map("updated_at") + /// What it is for, as whoever made it said: "nightly export". + name String + /// The teammate it acts as: their id at the auth provider. + userId String @map("user_id") + /// The key's seal, made by the vault for this row: the hash of its secret half and what the key may do. The secret is shown once and never kept. Empty once revoked. + digest String + /// A key that may only read: every operation that changes something refuses it. + readOnly Boolean @default(false) @map("read_only") + /// When it stops working, if it ever does. + expiresAt DateTime? @map("expires_at") + /// When it was revoked. A revoked key never works again. + revokedAt DateTime? @map("revoked_at") + /// When it last opened the API, to within a few minutes. + lastUsedAt DateTime? @map("last_used_at") + + @@index([userId]) + @@map("api_keys") + @@rls +} + /// When something last changed, by key: an object ("jobs") or one record ("jobs:"). /// Touched after every committed change to a record, its timeline, tasks and notes /// (src/server/signals.ts); a page asks whether its keys moved (`changedSince`). diff --git a/packages/spools/tests/integration/door.test.ts b/packages/spools/tests/integration/door.test.ts index 5087db1..16b4427 100644 --- a/packages/spools/tests/integration/door.test.ts +++ b/packages/spools/tests/integration/door.test.ts @@ -1,8 +1,12 @@ import { beforeEach, describe, expect, test } from 'bun:test' +import { Effect } from 'effect' + +import { verifyToken } from '../../src/server/callers' import * as api from '../../src/server/extension-api' import { publicRoute } from '../../src/server/handlers' import * as records from '../../src/server/records' +import { Tokens } from '../../src/server/runtime/tokens' import { Vault } from '../../src/server/runtime/vault' import { asSystem } from '../../src/server/scopes' import { run } from '../../src/testing/run' @@ -59,6 +63,27 @@ describe('a bearer token', () => { process.env['NODE_ENV'] = was } }) + + test("a server's own session tokens have no front end to name, and are taken in production", async () => { + const own = Tokens.of({ + own: true, + verify: (token) => Effect.succeed(token === 'mine' ? 'u1' : null), + }) + + const was = process.env['NODE_ENV'] + + try { + process.env['NODE_ENV'] = 'production' + + const check = (token: string) => + run(verifyToken(token, { authorizedParties: [] }).pipe(Effect.provideService(Tokens, own))) + + expect(await check('mine')).toBe('u1') + expect(await check('made-up')).toBeNull() + } finally { + process.env['NODE_ENV'] = was + } + }) }) describe('a caller’s address', () => { diff --git a/packages/spools/tests/integration/files.test.ts b/packages/spools/tests/integration/files.test.ts index 46067e3..d3a5f81 100644 --- a/packages/spools/tests/integration/files.test.ts +++ b/packages/spools/tests/integration/files.test.ts @@ -21,6 +21,7 @@ import { } from '../../src/server/files' import { withObjectAccess } from '../../src/server/object-access' import * as records from '../../src/server/records' +import { ReadOnlyCaller } from '../../src/server/runtime/access' import type { AppServices } from '../../src/server/runtime/app' import { crmConfig } from '../../src/server/spool' import { FileUpload, RecordFolder } from '../../src/server/store/tables' @@ -734,6 +735,20 @@ test("a record's folder is changed only by whoever may change the record: a read await run(records.deleteRecord('companies', fresh.id)) }) +test('a caller that may only read (a read-only API key) lists the top level and makes nothing there', async () => { + const before = crmConfig().files + crmConfig().files = { label: `Reader files ${tag}`, folders: ['Kept'] } + + try { + const asReader = Effect.provideService(listFolder(null), ReadOnlyCaller, true) + expect(names((await run(asReader)).folders)).not.toContain(`Reader files ${tag}`) + // Anyone else's first look makes it. + expect(names((await run(listFolder(null))).folders)).toContain(`Reader files ${tag}`) + } finally { + crmConfig().files = before + } +}) + test('a role that may change no record (`readOnly: true`) changes nothing in the shared library either', async () => { const everything = Object.keys(crmConfig().objects) const reads = withObjectAccess({ hidden: [], readOnly: everything }) diff --git a/packages/spools/tests/integration/http.test.ts b/packages/spools/tests/integration/http.test.ts new file mode 100644 index 0000000..6dfe4da --- /dev/null +++ b/packages/spools/tests/integration/http.test.ts @@ -0,0 +1,653 @@ +import { afterAll, beforeAll, expect } from 'bun:test' +import { createHash } from 'node:crypto' + +import { Effect } from 'effect' + +import { createClient, SpoolsError } from '../../src/client' +import { + createKey, + DEFAULT_DAYS, + keyHolder, + listKeys, + revokeKey, + sealKey, +} from '../../src/server/api-keys' +import { httpApi } from '../../src/server/http' +import { operationNamed } from '../../src/server/operations' +import { deleteRecord, getRecord } from '../../src/server/records' +import { Auth } from '../../src/server/runtime/auth' +import { Tokens } from '../../src/server/runtime/tokens' +import { Vault, VaultError } from '../../src/server/runtime/vault' +import { Store } from '../../src/server/store/store' +import { ApiKey } from '../../src/server/store/tables' +import { installLiveServices, installStandIns, run } from '../../src/testing/run' +import { exampleTest } from './example-app' + +/** + * The CRM over HTTP (src/server/http.ts), with no web framework anywhere: the + * handler is mounted on a plain `Bun.serve` and called with `fetch`, as a front + * end of someone's own would. On the starter's objects, signed in by the + * development sign-in (whose session stands for a cookie), and by the tokens + * the stand-in below hands out. + */ + +const FRONT_END = 'https://app.example.com' +const TOKEN = 'tok-dev-0001' +const tag = `http${Date.now()}` +const made: string[] = [] + +// A reversible stand-in for a vault's cipher, so these tests need no credentials. +const cipher = { + encrypt: async (plaintext: string) => + JSON.stringify({ c: Buffer.from(plaintext).toString('base64') }), + decrypt: async (ciphertext: string) => Buffer.from(JSON.parse(ciphertext).c, 'base64').toString(), +} + +// API keys are taken only where the app says so. +const api = httpApi({ keys: true }) +const withoutKeys = httpApi() +const withTokens = httpApi({ tokens: { authorizedParties: [FRONT_END] }, origins: [FRONT_END] }) + +let server: ReturnType +let base = '' + +beforeAll(async () => { + // The development sign-in's one person, known by a token issued to the front end above. + await installStandIns({ + tokens: Tokens.layerTest({ [TOKEN]: { userId: 'user_dev', parties: [FRONT_END] } }), + // What seals an API key, and a kept answer before it is stored. + vault: Vault.layerTest(cipher), + }) + + server = Bun.serve({ port: 0, fetch: (request) => api(request) }) + base = `http://localhost:${server.port}/api/v1` +}) + +afterAll(async () => { + delete process.env['DEV_AUTH_SIGNED_OUT'] + + await server.stop(true) + + for (const id of made) { + await run(deleteRecord('companies', id)) + } + + await installLiveServices() +}) + +/** An operation's input, as the text of a request's body. */ +const json = (input: Parameters[0]) => JSON.stringify(input) + +const post = (name: string, body?: string, headers: Record = {}) => + fetch(`${base}/${name}`, { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body: body ?? null, + }) + +/** A request straight to a handler, for what `fetch` won't send (a browser's own headers). */ +const direct = (name: string, init: RequestInit = {}) => + new Request(`https://crm.example.com/api/v1/${name}`, { method: 'POST', ...init }) + +const create = async (name: string, headers?: Record) => { + const response = await post( + 'records.create', + json({ objectKey: 'companies', values: { name } }), + headers, + ) + + const body = await response.json() + made.push(body.data.id) + return { response, id: String(body.data.id) } +} + +exampleTest('lists every operation with what it takes', async () => { + const response = await fetch(base) + const { data } = await response.json() + const get = data.find((operation: { name: string }) => operation.name === 'records.get') + + expect(response.status).toBe(200) + expect(get).toMatchObject({ kind: 'read', access: 'staff' }) + expect(get.input.required).toEqual(['objectKey', 'id']) + // Every operation of the interface is here: nothing has a server function and no address. + expect(data.length).toBeGreaterThan(60) +}) + +exampleTest('a teammate creates, reads, changes and lists records on a plain server', async () => { + const { response, id } = await create(`Co ${tag}`) + expect(response.status).toBe(200) + expect(response.headers.get('cache-control')).toBe('private, no-store') + + const read = await (await post('records.get', json({ objectKey: 'companies', id }))).json() + expect(read.data.record.name).toBe(`Co ${tag}`) + // It went through the service, as a change in the interface does: the timeline says who made it. + expect(read.data.activities.length).toBeGreaterThan(0) + + const changed = await post( + 'records.update', + json({ + objectKey: 'companies', + id, + values: { name: `Co ${tag} Ltd` }, + }), + ) + + expect(changed.status).toBe(200) + + // A read is also a GET, its input in the query. + const input = encodeURIComponent(JSON.stringify({ objectKey: 'companies', q: tag })) + const listed = await (await fetch(`${base}/records.list?input=${input}`)).json() + expect(listed.data.rows.map((row: { name: string }) => row.name)).toEqual([`Co ${tag} Ltd`]) +}) + +exampleTest('refuses what it cannot answer, with a code and the status that fits', async () => { + const missing = await post('records.nope', json({})) + expect(missing.status).toBe(404) + + const invalid = await post('records.get', json({ objectKey: 'nothing', id: 'x' })) + expect(invalid.status).toBe(400) + expect((await invalid.json()).error.code).toBe('invalid_input') + + const notJson = await fetch(`${base}/records.get`, { method: 'POST', body: '{' }) + expect(notJson.status).toBe(400) + + // A change is never a GET, so a link or an image tag can't make one. + const viaGet = await fetch(`${base}/records.delete?input=%7B%7D`) + expect(viaGet.status).toBe(405) + expect(viaGet.headers.get('allow')).toBe('POST') + + const gone = await post( + 'records.update', + json({ + objectKey: 'companies', + id: crypto.randomUUID(), + values: { name: 'x' }, + }), + ) + + expect(gone.status).toBe(404) + expect((await gone.json()).error.code).toBe('not_found') +}) + +exampleTest('a write sent twice with one Idempotency-Key runs once', async () => { + const key = { 'idempotency-key': crypto.randomUUID() } + const first = await create(`Once ${tag}`, key) + const again = await create(`Once ${tag}`, key) + + expect(again.id).toBe(first.id) + expect(again.response.headers.get('idempotent-replayed')).toBe('true') + + const listed = await ( + await post('records.list', json({ objectKey: 'companies', q: `Once ${tag}` })) + ).json() + + expect(listed.data.total).toBe(1) +}) + +exampleTest("another site's page can't act through a teammate's cookie", async () => { + const crossSite = await api( + direct('records.deleteMany', { + headers: { 'sec-fetch-site': 'cross-site', 'content-type': 'application/json' }, + body: JSON.stringify({ objectKey: 'companies', ids: made }), + }), + ) + + expect(crossSite.status).toBe(403) + expect((await crossSite.json()).error.code).toBe('cross_site') + + // An older browser says where a request came from with `Origin` alone. + const otherOrigin = await api( + direct('home.dashboard', { headers: { origin: 'https://evil.example' } }), + ) + + expect(otherOrigin.status).toBe(403) + + const sameSite = await api( + direct('home.dashboard', { headers: { 'sec-fetch-site': 'same-origin' } }), + ) + + expect(sameSite.status).toBe(200) + + // Nothing was deleted. + expect(await run(getRecord('companies', made[0] ?? ''))).not.toBeNull() +}) + +exampleTest('signed out, only what answers anyone is answered', async () => { + process.env['DEV_AUTH_SIGNED_OUT'] = '1' + + try { + const refused = await post('records.list', json({ objectKey: 'companies' })) + expect(refused.status).toBe(401) + expect((await refused.json()).error.code).toBe('unauthorized') + + const brand = await post('brand.get') + expect(brand.status).toBe(200) + + const session = await (await post('session.get')).json() + expect(session.data).toMatchObject({ signedIn: false, user: null, config: null }) + } finally { + delete process.env['DEV_AUTH_SIGNED_OUT'] + } +}) + +exampleTest('a bearer token opens the API only where the app says whose tokens count', async () => { + // Nobody has a cookie here: whoever gets in, gets in by the token. + process.env['DEV_AUTH_SIGNED_OUT'] = '1' + + try { + const bearer = { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' } + + const ask = (handler: typeof api, headers: Record) => + handler(direct('session.get', { headers })) + + // This API was mounted without `tokens`: a sign-in token is not a key to it. + expect((await ask(api, bearer)).status).toBe(401) + + const taken = await ask(withTokens, bearer) + expect(taken.status).toBe(200) + expect((await taken.json()).data).toMatchObject({ signedIn: true, user: { id: 'user_dev' } }) + + const forged = await ask(withTokens, { ...bearer, authorization: 'Bearer tok-made-up' }) + expect(forged.status).toBe(401) + + const staff = await withTokens( + direct('records.list', { headers: bearer, body: JSON.stringify({ objectKey: 'companies' }) }), + ) + + expect(staff.status).toBe(200) + } finally { + delete process.env['DEV_AUTH_SIGNED_OUT'] + } +}) + +exampleTest('a token sent with a cookie is judged alone', async () => { + // The cookie's session is a teammate's; the token is nobody's. The token decides. + const response = await withTokens( + direct('home.dashboard', { headers: { authorization: 'Bearer tok-made-up' } }), + ) + + expect(response.status).toBe(401) +}) + +exampleTest('a browser on a named origin is told it may call, and no other', async () => { + const from = (origin: string) => + withTokens(direct('brand.get', { method: 'OPTIONS', headers: { origin } })) + + expect((await from(FRONT_END)).headers.get('access-control-allow-origin')).toBe(FRONT_END) + expect((await from('https://evil.example')).headers.get('access-control-allow-origin')).toBeNull() + // Cookies are never taken from another site, so no answer says they may be sent. + expect((await from(FRONT_END)).headers.get('access-control-allow-credentials')).toBeNull() +}) + +exampleTest( + 'the typed client calls it by name, and a refusal is an error with its code', + async () => { + const crm = createClient({ baseUrl: base }) + + const { id } = await crm.call('records.create', { + objectKey: 'companies', + values: { name: `Client ${tag}` }, + }) + + made.push(id) + + const { record } = await crm.call('records.get', { objectKey: 'companies', id }) + expect(record?.['name']).toBe(`Client ${tag}`) + + // An operation that takes nothing is called by name alone. + expect((await crm.call('brand.get')).name.length).toBeGreaterThan(0) + + const refused = await crm + .call('records.update', { objectKey: 'companies', id: crypto.randomUUID(), values: {} }) + .catch((error: unknown) => error) + + expect(refused).toBeInstanceOf(SpoolsError) + expect(refused).toMatchObject({ status: 404, code: 'not_found' }) + }, +) + +/** A key for the development sign-in's one person. */ +const keyFor = async ( + change: { readOnly?: boolean; days?: number; neverExpires?: boolean } = {}, +) => { + const [me] = await run(Effect.flatMap(Auth, (auth) => auth.listUsers)) + return run(createKey({ name: `test ${tag}`, email: me?.email ?? '', ...change })) +} + +const bearer = (key: string) => ({ authorization: `Bearer ${key}` }) + +/** A change to a key's row, as someone who can write to the database would make it. */ +const changeKey = (id: string, changes: Partial>) => + run(Effect.flatMap(Store, (store) => store.update(ApiKey, { where: { id } }, changes))) + +exampleTest( + 'an API key opens the API as the teammate it was made for, until it is revoked', + async () => { + const { key, info } = await keyFor() + + // Only a seal is kept: the table holds nothing that opens the API. + const row = await run( + Effect.flatMap(Store, (store) => store.first(ApiKey, { where: { id: info.id } })), + ) + + expect(key.includes(row?.digest ?? 'none')).toBe(false) + expect(JSON.stringify(row)).not.toContain(key.slice(-43)) + + // It needs no cookie and no sign-in token. + process.env['DEV_AUTH_SIGNED_OUT'] = '1' + + try { + const { response, id } = await create(`Keyed ${tag}`, bearer(key)) + expect(response.status).toBe(200) + + const read = await ( + await post('records.get', json({ objectKey: 'companies', id }), bearer(key)) + ).json() + + // The change is the teammate's, as one they made in the interface would be. + expect(JSON.stringify(read.data.activities)).toContain('user_dev') + + // The same key with one character of its secret changed, a key that never was, and half a key. + const last = key.at(-1) === 'A' ? 'B' : 'A' + + for (const bad of [ + `${key.slice(0, -1)}${last}`, + `spk_${crypto.randomUUID()}_${'a'.repeat(43)}`, + 'spk_nothing', + ]) { + expect((await post('session.get', undefined, bearer(bad))).status).toBe(401) + } + + expect(await run(revokeKey(info.id))).toBe(true) + expect((await post('session.get', undefined, bearer(key))).status).toBe(401) + } finally { + delete process.env['DEV_AUTH_SIGNED_OUT'] + } + + const listed = await run(listKeys()) + expect(listed.find((one) => one.id === info.id)?.revokedAt).not.toBeNull() + expect(listed.find((one) => one.id === info.id)?.lastUsedAt).not.toBeNull() + }, +) + +exampleTest('a read-only key reads and changes nothing; an expired key opens nothing', async () => { + const reader = await keyFor({ readOnly: true }) + + expect((await post('session.get', undefined, bearer(reader.key))).status).toBe(200) + + const refused = await post( + 'records.create', + json({ objectKey: 'companies', values: { name: `Never ${tag}` } }), + bearer(reader.key), + ) + + expect(refused.status).toBe(403) + expect((await refused.json()).error.code).toBe('read_only') + + // A key whose time has come: its row as the server itself would have sealed it, a second ago. + const brief = await keyFor({ days: 1 }) + const secret = brief.key.slice(-43) + const row = { id: brief.info.id, userId: brief.info.userId, readOnly: false } + + const ending = async (expiresAt: Date) => + changeKey(brief.info.id, { + expiresAt, + digest: await run(sealKey({ ...row, expiresAt }, secret)), + }) + + await ending(new Date(Date.now() - 1000)) + expect((await post('session.get', undefined, bearer(brief.key))).status).toBe(401) + // The same row with a day left is taken, so it was the time that refused it. + await ending(new Date(Date.now() + 86_400_000)) + + expect((await post('session.get', undefined, bearer(brief.key))).status).toBe(200) + + await run(revokeKey(reader.info.id)) + await run(revokeKey(brief.info.id)) +}) + +exampleTest('a server takes keys only when its API says so', async () => { + const { key, info } = await keyFor() + const asking = () => direct('session.get', { headers: bearer(key) }) + + expect((await api(asking())).status).toBe(200) + expect((await withoutKeys(asking())).status).toBe(401) + + await run(revokeKey(info.id)) +}) + +exampleTest('a key ends after ninety days unless whoever makes it says otherwise', async () => { + const usual = await keyFor() + const days = ((usual.info.expiresAt?.getTime() ?? 0) - Date.now()) / 86_400_000 + expect(DEFAULT_DAYS).toBe(90) + expect(Math.round(days)).toBe(90) + + const kept = await keyFor({ neverExpires: true }) + expect(kept.info.expiresAt).toBeNull() + expect((await post('session.get', undefined, bearer(kept.key))).status).toBe(200) + + const both = await keyFor({ days: 5, neverExpires: true }).catch((error: unknown) => error) + expect(String(both)).toContain('say one') + + await run(revokeKey(usual.info.id)) + await run(revokeKey(kept.info.id)) +}) + +exampleTest('writing to the table makes no key, and widens none', async () => { + const status = async (key: string, name = 'session.get', body?: string) => + (await post(name, body, bearer(key))).status + + // A row put there by hand, with the hash of a secret its maker knows: no seal the vault made. + const secret = 'f'.repeat(43) + const [me] = await run(Effect.flatMap(Auth, (auth) => auth.listUsers)) + + const forged = await run( + Effect.flatMap(Store, (store) => + store.insert(ApiKey, { + name: `forged ${tag}`, + userId: me?.id ?? '', + digest: createHash('sha256').update(secret).digest('hex'), + }), + ), + ) + + const forgedKey = `spk_${forged.id}_${secret}` + const quiet = console.error + console.error = () => undefined + + try { + expect(await status(forgedKey)).toBe(500) + + // Nor with a real key's seal copied onto it: that was sealed for the row it came from. + const real = await keyFor() + + const theirs = await run( + Effect.flatMap(Store, (store) => store.first(ApiKey, { where: { id: real.info.id } })), + ) + + await changeKey(forged.id, { digest: theirs?.digest ?? '', expiresAt: real.info.expiresAt }) + expect(await status(`spk_${forged.id}_${real.key.slice(-43)}`)).toBe(500) + await run(revokeKey(real.info.id)) + } finally { + console.error = quiet + } + + // A real key, read-only and short-lived, whose holder can write to the database. + const narrow = await keyFor({ readOnly: true, days: 1 }) + expect(await status(narrow.key)).toBe(200) + + for (const change of [ + { readOnly: false }, + { userId: 'someone_else' }, + { expiresAt: new Date(Date.now() + 365 * 86_400_000) }, + { expiresAt: null }, + ]) { + await changeKey(narrow.info.id, change) + expect(await status(narrow.key), JSON.stringify(change)).toBe(401) + } + + // Put back as it was, it is the key it was. + await changeKey(narrow.info.id, { + readOnly: true, + userId: narrow.info.userId, + expiresAt: narrow.info.expiresAt, + }) + + expect(await status(narrow.key)).toBe(200) + + // Revoked, it can't be brought back by clearing the date. + await run(revokeKey(narrow.info.id)) + await changeKey(narrow.info.id, { revokedAt: null }) + expect(await status(narrow.key)).toBe(401) + + await run(Effect.flatMap(Store, (store) => store.remove(ApiKey, { where: { id: forged.id } }))) +}) + +exampleTest('a Spool with no vault has no keys: none is made and none is taken', async () => { + const { key, info } = await keyFor() + + const none = Vault.make({ + cipher: Effect.fail(new VaultError({ message: 'No vault' })), + problem: Effect.succeed('No vault is set up to encrypt stored secrets'), + }) + + const without = (program: Effect.Effect) => + run(Effect.provideService(program, Vault, none)) + + const [me] = await run(Effect.flatMap(Auth, (auth) => auth.listUsers)) + const made = without(createKey({ name: `no vault ${tag}`, email: me?.email ?? '' })) + + expect(String(await made.catch((error: unknown) => error))).toContain('No vault is set up') + expect(await without(keyHolder(key))).toBeNull() + expect((await run(keyHolder(key)))?.userId).toBe(info.userId) + + await run(revokeKey(info.id)) +}) + +exampleTest('a key is made only for a teammate on the access list', async () => { + const refused = await run(createKey({ name: 'x', email: 'stranger@elsewhere.example' })).catch( + (error: unknown) => error, + ) + + expect(String(refused)).toContain('not a teammate') +}) + +/** The part of the example's objects these tests use, as `spools gen` would write it. */ +type Crm = { + companies: { + record: { id: string; createdAt: string; updatedAt: string; name: string } + values: { name: string; employees?: number | null } + } +} + +exampleTest('the client knows an object by its fields, and the API describes itself', async () => { + const crm = createClient({ baseUrl: base }) + const companies = crm.records('companies') + + const { id } = await companies.create({ name: `Typed ${tag}` }) + made.push(id) + await companies.update(id, { employees: 12 }) + + const { record } = await companies.get(id) + expect(record?.name).toBe(`Typed ${tag}`) + + const { rows } = await companies.list({ q: `Typed ${tag}` }) + expect(rows.map((row) => row.name)).toEqual([`Typed ${tag}`]) + + const document = await (await fetch(`${base}/openapi.json`)).json() + + expect(document.openapi).toBe('3.1.0') + + expect( + document.paths['/records.get'].post.requestBody.content['application/json'].schema.required, + ).toEqual(['objectKey', 'id']) + + // An operation for anyone says it needs no one signed in. + expect(document.paths['/email.unsubscribe'].post.security).toEqual([]) + expect(Object.keys(document.paths).length).toBeGreaterThan(60) +}) + +exampleTest( + 'the headless server answers the API and the rest of a Spool, pages aside', + async () => { + const { headlessServer } = await import('../../src/headless') + const spools = headlessServer() + + const ask = (path: string, init: RequestInit = {}) => + spools.fetch(new Request(`https://crm.example.com${path}`, init)) + + expect(await (await ask('/healthz')).text()).toBe('ok') + + const session = await ask('/api/v1/session.get', { method: 'POST' }) + expect(session.status).toBe(200) + // Every answer carries the headers a Spool's pages do. + expect(session.headers.get('x-content-type-options')).toBe('nosniff') + + // A route with a part that varies reaches its handler with it: no such file, said by the handler. + expect((await ask(`/api/files/${crypto.randomUUID()}`)).status).toBe(404) + expect((await ask('/api/files/not-an-id')).status).toBe(404) + // A cron route with no secret set is closed, and a method a route has no handler for is refused. + expect((await ask('/api/cron/warm')).status).toBeGreaterThanOrEqual(401) + expect((await ask('/api/cron/warm', { method: 'DELETE' })).status).toBe(405) + + // The assistant's chat is opened by the cookie alone, so never by another site's page. + const crossSite = await ask('/api/assistant', { + method: 'POST', + headers: { 'sec-fetch-site': 'cross-site' }, + }) + + expect(crossSite.status).toBe(403) + + // There are no pages. + expect((await ask('/')).status).toBe(404) + expect((await ask('/contacts')).status).toBe(404) + }, +) + +exampleTest( + 'an Authorization header this server cannot read is refused, never passed over for the cookie', + async () => { + // The development sign-in would let a request with no header in. + for (const authorization of ['abc.def.ghi', 'Basic dXNlcjpwYXNz', 'Bearer']) { + const response = await post('session.get', undefined, { authorization }) + expect(response.status).toBe(401) + } + }, +) + +exampleTest('what the API says an operation answers is what it answers', async () => { + const { id } = await create(`Described ${tag}`) + const ref = { objectKey: 'companies', id } + + const asked: Record = { + 'brand.get': undefined, + 'records.get': ref, + 'records.list': { objectKey: 'companies', q: `Described ${tag}` }, + 'records.titles': { objectKey: 'companies', ids: [id] }, + 'records.searchTitles': { objectKey: 'companies', q: 'Described' }, + 'records.update': { ...ref, values: { employees: 3 } }, + 'records.deleteMany': { objectKey: 'companies', ids: [crypto.randomUUID()] }, + } + + for (const [name, input] of Object.entries(asked)) { + const response = await post(name, input && json(input)) + const { data } = await response.json() + const said = operationNamed(name)?.answer?.safeParse(data) + + expect(response.status, name).toBe(200) + expect(said?.error?.message, name).toBeUndefined() + expect(said?.success, name).toBe(true) + } + + // The same, where a client in another language reads it. + const document = await (await fetch(`${base}/openapi.json`)).json() + + const answer = (name: string) => + document.paths[`/${name}`].post.responses[200].content['application/json'].schema.properties + .data + + expect(answer('records.create').required).toEqual(['id']) + expect(answer('records.list').required).toContain('rows') + // An operation that says nothing of its answer is still JSON, of any shape. + expect(answer('search.deep')).toEqual({}) +}) diff --git a/packages/spools/tests/integration/idempotency.test.ts b/packages/spools/tests/integration/idempotency.test.ts index a3b4172..97324c4 100644 --- a/packages/spools/tests/integration/idempotency.test.ts +++ b/packages/spools/tests/integration/idempotency.test.ts @@ -544,15 +544,9 @@ describe('kept answers', () => { { caller: `app:outside:${users.ben.id}` }, ) - const original = console.error - console.error = () => undefined - - try { - const moved = await send(key, { note: 'hi' }, users.ben.id) - expect(moved.status).toBe(500) - } finally { - console.error = original - } + const moved = await send(key, { note: 'hi' }, users.ben.id) + expect(moved.headers.get('idempotent-body')).toBe('withheld') + expect(await moved.text()).not.toContain('kept') }) }) @@ -986,3 +980,21 @@ describe('apiRoute', () => { expect(ran).toBe(1) }) }) + +test("a repeat by a caller whose access has changed gets the first answer's status and not its body", async () => { + const claim = { caller: 'app:narrowed', endpoint: 'POST /narrowed', key: freshKey(), body: '{}' } + const work = Effect.sync(() => Response.json({ secret: 'north' }, { status: 201 })) + + expect((await run(replayable({ ...claim, access: 'north' }, work))).status).toBe(201) + + // The same access: the answer as it was. + const same = await run(replayable({ ...claim, access: 'north' }, work)) + expect(await same.json()).toEqual({ secret: 'north' }) + + // Narrowed since: the change was made once, and what it showed is withheld. + const narrowed = await run(replayable({ ...claim, access: 'none' }, work)) + expect(narrowed.status).toBe(201) + expect(narrowed.headers.get('idempotent-replayed')).toBe('true') + expect(narrowed.headers.get('idempotent-body')).toBe('withheld') + expect(await narrowed.text()).not.toContain('north') +}) diff --git a/packages/spools/tests/unit/auth-adapters.test.ts b/packages/spools/tests/unit/auth-adapters.test.ts index 9daba1d..072fee2 100644 --- a/packages/spools/tests/unit/auth-adapters.test.ts +++ b/packages/spools/tests/unit/auth-adapters.test.ts @@ -7,6 +7,7 @@ import { clerk, developmentInstance, isTestAddress, + middlewareParties, toAuthUser, tokenRefusal, } from '../../src/adapters/auth/clerk/server' @@ -38,6 +39,39 @@ describe('Clerk', () => { expect(toAuthUser(clerkUser({ firstName: null, lastName: null })).name).toBeNull() }) + test("on TanStack Start, Clerk's middleware is told whose session tokens count", () => { + const saved = { app: process.env['APP_URL'], node: process.env['NODE_ENV'] } + + try { + process.env['APP_URL'] = 'https://crm.example.com/' + process.env['NODE_ENV'] = 'production' + expect(middlewareParties({})).toEqual(['https://crm.example.com']) + + // The app's own word comes first, in any mode. + expect(middlewareParties({ authorizedParties: ['https://a.example'] })).toEqual([ + 'https://a.example', + ]) + + // In development the page is often served elsewhere, so APP_URL alone decides nothing. + process.env['NODE_ENV'] = 'development' + expect(middlewareParties({})).toBeUndefined() + + // Nor does a deployment still on the address from .env.example lock everyone out. + process.env['NODE_ENV'] = 'production' + process.env['APP_URL'] = 'http://localhost:3000' + expect(middlewareParties({})).toBeUndefined() + } finally { + process.env['APP_URL'] = saved.app + process.env['NODE_ENV'] = saved.node + } + }) + + test('someone banned or locked at Clerk has no address, so nothing of theirs opens the CRM', () => { + expect(toAuthUser(clerkUser({ banned: true })).email).toBeNull() + expect(toAuthUser(clerkUser({ locked: true })).email).toBeNull() + expect(toAuthUser(clerkUser({ banned: false, locked: false })).email).toBe('ana@example.com') + }) + test("an address Clerk hasn't verified is no address: it must not open an allowed domain", () => { const unverified = [ { id: 'e1', emailAddress: 'ana@example.com', verification: { status: 'unverified' } }, diff --git a/packages/spools/tests/unit/better-auth.test.ts b/packages/spools/tests/unit/better-auth.test.ts index 777e5b1..f11fd1a 100644 --- a/packages/spools/tests/unit/better-auth.test.ts +++ b/packages/spools/tests/unit/better-auth.test.ts @@ -29,6 +29,7 @@ import { Auth } from '../../src/server/runtime/auth' import { Email, type OutboundEmail } from '../../src/server/runtime/email' import { DatabaseError } from '../../src/server/runtime/errors' import { httpLayer } from '../../src/server/runtime/http' +import { Tokens } from '../../src/server/runtime/tokens' import { defineSpool, type Spool, spool } from '../../src/server/spool' import { allTables, schemaSql } from '../../src/server/store/schema-sql' import { makeStore, Store } from '../../src/server/store/store' @@ -1879,3 +1880,88 @@ describe('the browser half', () => { expect(explain('') - - expect(html).not.toContain(' { - expect(draw('[site](https://example.com)')).toContain( - ' { const saved = { app: process.env['APP_URL'], node: process.env['NODE_ENV'] } try { - process.env['APP_URL'] = 'https://crm.example.com/' + process.env['APP_URL'] = 'https://api.example.com/' process.env['NODE_ENV'] = 'production' - expect(middlewareParties({})).toEqual(['https://crm.example.com']) + expect(middlewareParties({})).toEqual(['https://api.example.com']) // The app's own word comes first, in any mode. expect(middlewareParties({ authorizedParties: ['https://a.example'] })).toEqual([ @@ -66,7 +66,7 @@ describe('Clerk', () => { } }) - test('someone banned or locked at Clerk has no address, so nothing of theirs opens the CRM', () => { + test('someone banned or locked at Clerk has no address, so nothing of theirs opens the Spool', () => { expect(toAuthUser(clerkUser({ banned: true })).email).toBeNull() expect(toAuthUser(clerkUser({ locked: true })).email).toBeNull() expect(toAuthUser(clerkUser({ banned: false, locked: false })).email).toBe('ana@example.com') diff --git a/packages/spools/tests/unit/better-auth.test.ts b/packages/spools/tests/unit/better-auth.test.ts index f11fd1a..3dade61 100644 --- a/packages/spools/tests/unit/better-auth.test.ts +++ b/packages/spools/tests/unit/better-auth.test.ts @@ -2,10 +2,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, te import { PGlite } from '@electric-sql/pglite' import { Effect, Layer } from 'effect' -import { createElement } from 'react' -import { renderToString } from 'react-dom/server' -import { betterAuthClient, explain } from '../../src/adapters/auth/better-auth/client' import { storeDatabase } from '../../src/adapters/auth/better-auth/database' import { microsoftVouches } from '../../src/adapters/auth/better-auth/providers' import { @@ -22,7 +19,7 @@ import { authTables, } from '../../src/adapters/auth/better-auth/tables' import { pglite } from '../../src/adapters/database/pglite/server' -import { PROVIDERS } from '../../src/crm/mailbox' +import { PROVIDERS } from '../../src/core/mailbox' import { environmentProblems } from '../../src/server/env' import { disposeRuntime } from '../../src/server/runtime/app' import { Auth } from '../../src/server/runtime/auth' @@ -30,17 +27,18 @@ import { Email, type OutboundEmail } from '../../src/server/runtime/email' import { DatabaseError } from '../../src/server/runtime/errors' import { httpLayer } from '../../src/server/runtime/http' import { Tokens } from '../../src/server/runtime/tokens' -import { defineSpool, type Spool, spool } from '../../src/server/spool' +import { defineSpool, restoreSpool, spool, type Spool } from '../../src/server/spool' import { allTables, schemaSql } from '../../src/server/store/schema-sql' import { makeStore, Store } from '../../src/server/store/store' import { isAllowed, Users } from '../../src/server/users' import { db, failure, installStandIns, run, testRuntime } from '../../src/testing/run' import example from '../fixtures/example.config.json' with { type: 'json' } +import { everyFeature } from '../support/features' // Sign-in kept in the Spool's own database, on Postgres in this process. Google // and Microsoft are stand-ins for `fetch`; nothing here reaches the network. -const ORIGIN = 'https://crm.acme.test' +const ORIGIN = 'https://api.acme.test' const crm = { ...example, @@ -103,7 +101,13 @@ beforeAll(async () => { usualEnv() client = await PGlite.create() const auth = adapter - const made = defineSpool({ crm, auth, database: pglite({ client }) }) + + const made = defineSpool({ + config: crm, + auth, + database: pglite({ client }), + modules: everyFeature, + }) for (const statement of schemaSql(allTables(made.config, [auth]))) { await client.exec(statement) @@ -116,7 +120,7 @@ afterAll(async () => { globalThis.fetch = realFetch setEnv(saved) // The other test files in this process go on with the Spool and the services they had. - const back = defineSpool({ ...before, crm: before.config }) + const back = restoreSpool(before) await disposeRuntime() await client.close() expect(back.config).toEqual(before.config) @@ -637,8 +641,8 @@ describe('signing in with a link by email', () => { expect(session?.userId).toBe(user!.id) expect(await session?.getToken({ template: 'swirls' })).toBeNull() - // And the CRM lets them in. - expect(await run(Users.use((u) => u.crmUser(user!.id)))).toEqual({ + // And the Spool lets them in. + expect(await run(Users.use((u) => u.staffUser(user!.id)))).toEqual({ id: user!.id, email: 'ana@acme.test', name: 'ana@acme.test', @@ -1420,7 +1424,7 @@ describe('who may have an account', () => { expect(() => admit({ email: 'ana@acme.test', emailVerified: true })).not.toThrow() expect(() => admit({ email: 'ana@elsewhere.test', emailVerified: true })).toThrow( - 'may not use this CRM', + 'may not use this Spool', ) expect(() => admit({ email: 'ana@acme.test', emailVerified: false })).toThrow( @@ -1553,7 +1557,7 @@ describe('the directory', () => { expect([everyone.length, everyone[0]?.id, everyone.at(-1)?.id]).toEqual([200, 'u001', 'u200']) }) - test("an address that isn't verified never reaches the CRM, though it is on the list", async () => { + test("an address that isn't verified never reaches the Spool, though it is on the list", async () => { const user = await db.insert(AuthUser, { name: 'Mallory', email: 'boss@acme.test', @@ -1561,7 +1565,7 @@ describe('the directory', () => { }) expect((await directory(Auth.use((a) => a.getUser(user.id)))).email).toBeNull() - expect(await run(Users.use((u) => u.crmUser(user.id)))).toBeNull() + expect(await run(Users.use((u) => u.staffUser(user.id)))).toBeNull() expect( toPerson({ id: '1', name: '', email: 'boss@acme.test', emailVerified: false }, []), @@ -1698,7 +1702,7 @@ describe("a token for someone's account", () => { expect(requests.length).toBe(1) }) - test("refused because of this CRM's own client id or secret is the deployment's to fix", async () => { + test("refused because of this Spool's own client id or secret is the deployment's to fix", async () => { await runOut() provider(() => Response.json({ error: 'invalid_client' }, { status: 401 })) const refused = await failure(token(userId)) @@ -1773,15 +1777,15 @@ describe('what must be set', () => { process.env['NODE_ENV'] = 'production' expect(problems({})).toEqual(['BETTER_AUTH_SECRET is not set', 'APP_URL is not set']) - expect(problems({ BETTER_AUTH_SECRET: 'short', APP_URL: 'crm.example.com' })).toEqual([ + expect(problems({ BETTER_AUTH_SECRET: 'short', APP_URL: 'api.example.com' })).toEqual([ 'BETTER_AUTH_SECRET must be at least 32 characters', - "APP_URL must be the app's address, like https://crm.example.com", + "APP_URL must be the app's address, like https://api.example.com", ]) expect(problems({ BETTER_AUTH_SECRET: 'x'.repeat(32), APP_URL: 'ftp://x' }).length).toBe(1) expect( - problems({ BETTER_AUTH_SECRET: 'x'.repeat(32), APP_URL: 'https://crm.example.com' }), + problems({ BETTER_AUTH_SECRET: 'x'.repeat(32), APP_URL: 'https://api.example.com' }), ).toEqual([]) }) @@ -1847,40 +1851,6 @@ describe('what must be set', () => { }) }) -// ── The browser half ──────────────────────────────────────────────────────── - -describe('the browser half', () => { - test("is the same provider's", () => { - expect(betterAuthClient.id).toBe(adapter.id) - }) - - test("the first page drawn is the plain form, which can't be sent before the page is running", () => { - const html = renderToString( - createElement(betterAuthClient.SignIn, { path: '/sign-in', redirectTo: '/' }), - ) - - expect(html).toContain('