# ProductCraft documentation (full text) Every ProductCraft guide in one file, generated from https://productcraft.co/docs. Per-endpoint details are in each product's OpenAPI document (listed in https://productcraft.co/llms.txt). --- title: "Build with AI" description: "Connect Claude Code, Cursor or Codex to ProductCraft: the MCP server, the docs as Markdown and llms.txt, rules files that teach an agent the SDKs, and scoped access a person approves." url: https://productcraft.co/docs/ai --- [Docs](https://productcraft.co/docs.md) Build with AI # Build with an AI coding agent. Give your agent three things: a connection to your workspace that you approve, the docs in a format it reads well, and a rules file that teaches it the SDKs. It writes the code; you decide what it may touch. 1 ## Connect the MCP server The MCP server turns your workspace's API into tools an agent can call: look up why an email bounced, approve waitlist entries, check a feature flag, start a web extraction. **Claude Code** ```bash title="terminal" claude mcp add --transport http productcraft 'https://mcp.productcraft.co/mcp' # then, inside Claude Code: /mcp # pick "productcraft" and follow the browser prompt ``` **Cursor** ```json title="~/.cursor/mcp.json" { "mcpServers": { "productcraft": { "url": "https://mcp.productcraft.co/mcp" } } } ``` **Codex** ```title="~/.codex/config.toml" [mcp_servers.productcraft] url = "https://mcp.productcraft.co/mcp" # then, in a terminal, approve it in the browser: # codex mcp login productcraft ``` There is no key in any of these. The client opens a browser, you sign in to ProductCraft, and you approve what the connection may do (step 4 below). Claude Desktop and VS Code connect the same way; see [the MCP server docs](https://productcraft.co/docs/mcp.md) for those, the rate limits and the full list of what an agent can never do without you ticking it. 2 ## Point the agent at the docs Every docs page is also plain Markdown, which an agent reads without the page's navigation, styling and scripts. | Address | What it is | | --- | --- | | [/llms.txt](https://productcraft.co/llms.txt) | The index: every guide per product with a one-line summary, and the OpenAPI document of every API. It follows the [llms.txt convention](https://llmstxt.org). | | [/llms-full.txt](https://productcraft.co/llms-full.txt) | Every guide in one file, for tools that load all the docs at once. | | /docs/.md | Any docs page as Markdown: add `.md` to the address, for example [/docs/mail/getting-started.md](https://productcraft.co/docs/mail/getting-started.md). | | Accept: text/markdown | The same Markdown from the normal address, for agents that ask for it. | ```bash title="terminal" curl https://productcraft.co/llms.txt curl https://productcraft.co/docs/auth/getting-started.md curl -H 'Accept: text/markdown' https://productcraft.co/docs/auth/getting-started ``` The Markdown is made from the same pages you are reading, each time the site is deployed, so the two never disagree. 3 ## Add a rules file A rules file is the note a coding agent reads before it starts. Ours tells it how our SDKs work and lists every method they have, so it does not guess at ones that don't exist. Products Auth Mail Waitlist Social Trawl Flags Notify Platform Save as AGENTS.md CLAUDE.md Cursor AGENTS.md ``` curl -fsS \ 'https://productcraft.co/docs/ai/rules?format=agents' \ >> AGENTS.md ``` Or [open the file](https://productcraft.co/docs/ai/rules?format=agents) and paste it in yourself. Each file is built from the README and the method list of the SDK versions on npm today, and our tests check every method it names against the published package. It also sets the habits we want in every integration: keys stay on the server, webhooks are verified on the raw body, retries reuse an idempotency key, and test emails go to a simulator address instead of a real inbox. Claude Code reads `CLAUDE.md`, Codex and many other agents read `AGENTS.md`, and Cursor reads `.cursor/rules/*.mdc` (it also reads `AGENTS.md`). The command adds our rules to the end of an existing file, so nothing you already have is overwritten. 4 ## Give the agent only the access it needs An agent works with an account or a key that a person set up and can take back. Every call it makes is in the audit log. ### An agent in your editor - You approve the MCP connection in the browser: one workspace, the products it may use, and a starting preset such as read-only. - It can never do more than you can, and losing a permission takes it from the agent at its next call. - Creating keys, editing roles, inviting people and emailing outside your domains are never in a preset. You tick each one yourself. - The audit log records you as the actor and marks the row as made by an AI client, with the tool and the outcome. - Disconnect it from **Connected apps** in the console; it stops at its next call. ### An agent in a pipeline - A person creates a workspace API key in the console and binds it to a policy that lists exactly what it may do. A key can never create another key. - Nobody can give a key more than they hold themselves. - The key is shown once; ProductCraft stores only its hash. - `platform.apiKeys.self()` tells the job which workspace and permissions it has, so a wrong key fails on the first line. - Rotate or revoke it from the console at any time. Step by step: [workspace API keys for CI](https://productcraft.co/docs/platform/guides/04-pats-for-cicd.md) and [members, roles and policies](https://productcraft.co/docs/platform/guides/02-members-and-roles.md). Building an app whose own users connect agents to it? [Auth agent access](https://productcraft.co/docs/auth/agent-access.md) gives your users the same approve-in-the-browser flow. --- title: "Documentation" description: "API references, integration guides, and copy-paste examples for every ProductCraft service." url: https://productcraft.co/docs --- Docs # Documentation. API references, integration guides, and working examples for every ProductCraft service. By product ## Pick a service Every service has its own getting-started guide, integration guides, and full API reference. - [Platform](https://productcraft.co/docs/platform.md): AvailableThe administrative surface that powers the console — workspaces, members, roles, service activation, API keys, audit. Hit it directly for CI/CD, infrastructure-as-code, and admin automation.Read more → - [Auth](https://productcraft.co/docs/auth.md): AvailableMulti-tenant auth: users, roles, M2M tokens, per-app JWKS. Quickstart, core concepts, full API reference, and integration guides.Read more → - [Mail](https://productcraft.co/docs/mail.md): AvailableTransactional email with per-domain DKIM, Handlebars templates, and tenancy-scoped API keys. Getting-started guide walks through your first send.Read more → - [Trawl](https://productcraft.co/docs/trawl.md): AvailableSchema-driven web extraction: POST a URL plus a JSON Schema, get structured data back by webhook or polling. Quickstart, core concepts, guides, and full API reference.Read more → - [Flags](https://productcraft.co/docs/flags.md): PreviewFeature flags and remote settings evaluated inside your app: percentage rollouts, targeting rules, segments, environments, change history and signed webhooks. Getting started, concepts, twelve guides and the API reference.Read more → - [Notify](https://productcraft.co/docs/notify.md): PreviewOne call notifies a user across an in-app inbox, email, web push, iOS and Android push, with preferences, fallbacks, quiet hours and delivery history. Bring your own APNs and Firebase credentials for mobile push; web push needs neither.Read more → - [Waitlist](https://productcraft.co/docs/waitlist.md): AvailableWaitlist management as a service. Public signup API, custom fields, referral mechanics, approval workflow, signed webhooks. Quickstart and full API reference.Read more → - [MCP](https://productcraft.co/docs/mcp.md): AvailableConnect Claude, Cursor or VS Code to a workspace over the Model Context Protocol. OAuth in the browser, no key in a config file, scoped by policy and logged call by call.Read more → - [Social](https://productcraft.co/docs/social.md): AvailableSocial infrastructure as an API. Communities, posts, ranked feeds, stories with polls and close-friends, notifications, moderation. Quickstart and full API reference.Read more → Every API ## Shared conventions What works the same way across every ProductCraft API. - [Errors](https://productcraft.co/docs/api/errors.md): AvailableThe one error body every API returns: status_code, message, a stable code to branch on, and details.Read more → - [Error codes](https://productcraft.co/docs/errors.md): AvailableEvery code the APIs return, with its status, what it means and what to do. Generated from the live specs.Read more → - [Build with AI](https://productcraft.co/docs/ai.md): AvailableConnect Claude Code, Cursor or Codex, read the docs as Markdown or llms.txt, and add a rules file that teaches your agent the SDKs.Read more → - [Testing](https://productcraft.co/docs/testing.md): AvailableTest without side effects: the SDK mock fetch, a workspace for tests, and mailbox simulator addresses for Mail.Read more → SDKs ## Official Node.js / TypeScript SDKs Every product on the platform ships a typed npm package. Install one for a single surface, or grab the umbrella for all of them. ```bash title="install" npm install @productcraft/auth # or all surfaces in one install npm install productcraft ``` [Browse all SDKs](https://productcraft.co/docs/sdks.md) [Get notified when new docs are published](https://productcraft.co/waitlist) --- title: "MCP server" description: "Connect Claude, Cursor or VS Code to a ProductCraft workspace over MCP. OAuth in the browser, no API key in a config file, every call in the audit log." url: https://productcraft.co/docs/mcp --- [Docs](https://productcraft.co/docs.md) MCP # Connect an AI client to your workspace. Claude, Cursor and VS Code can work in your ProductCraft workspace over the Model Context Protocol — approved in a browser, scoped by policy, and logged line by line. What it is ## One endpoint, your API as tools ProductCraft runs an MCP server at `https://mcp.productcraft.co/mcp`. Point a client at it and the workspace's API becomes tools the model can call: read a waitlist, look up why a delivery bounced, send a transactional email, kick off a web extraction. **Nothing is pasted.** There is no API key in a config file. The client registers itself, opens a browser, and you approve the connection on a ProductCraft consent screen that names the client, the workspace and exactly what it may do. The credential lives in the client's own store and can be revoked from your account at any time. The tool list is **filtered to what you approved**. A connection set up for Mail sees Mail tools and nothing else — so the model is never choosing between hundreds of tools it would only get a 403 from. Step 1 ## Add the server to your client Every client speaks the same transport (Streamable HTTP) and the same auth (OAuth 2.1 with PKCE). Pick yours. **Claude Code** ```bash title="terminal" claude mcp add --transport http productcraft 'https://mcp.productcraft.co/mcp' # then, inside Claude Code: /mcp # pick "productcraft" and follow the browser prompt ``` **Claude Desktop** ```title="Settings → Connectors" Add custom connector Name: ProductCraft URL: https://mcp.productcraft.co/mcp Claude opens a browser window to finish the connection. ``` **Cursor** ```json title="~/.cursor/mcp.json" { "mcpServers": { "productcraft": { "url": "https://mcp.productcraft.co/mcp" } } } ``` **VS Code** ```json title=".vscode/mcp.json" { "servers": { "productcraft": { "type": "http", "url": "https://mcp.productcraft.co/mcp" } } } ``` Note what is _not_ in any of those snippets: a token, a key, a client id, a secret. The only configuration is the URL. Step 2 ## Approve the connection The client sends you to auth.productcraft.co. What you do there is the whole security model. 1. **Sign in** with your ProductCraft account, if you are not already. 2. **Pick the workspace** this connection acts in. One connection, one workspace. 3. **Tick the products** it works with. Your workspace's switched-on products start ticked; the assistant is offered only their tools, plus a few basic workspace tools. Add `?products=mail,waitlist` to the server URL to start with just those. 4. **Choose what it may do.** Start from a preset and narrow it — you can always grant less than the client asked for. 5. **Approve.** The browser hands the client a token and you are done. The screen marks every dynamically-registered client **unverified**, because that is what it is: the client chose its own name when it registered. Trust the app you just installed, not the string on the screen. Consent is per client — a second client, even one with the same name, faces the same screen and gets nothing from your earlier approval. Scopes ## Presets, and the ceiling above them A connection carries a policy document, not a coarse scope. Presets are named starting points the consent screen can render in one line. | Preset | What it grants | | --- | --- | | readonly | Read-only across the workspace: settings, members, email, waitlists, communities, web-extraction jobs, feature flags and notifications. Changes nothing. | | mail | Read and send email from your verified domains, and manage suppression lists. Email cannot be unsent. | | support | Everything read-only, plus the day-to-day actions a support assistant needs: sending email, updating waitlist entries, moderating posts and running extraction jobs. | | full | Every action the workspace exposes, except creating keys, editing roles and policies, and the other actions that hand out access, listed below. | **A connection can never do more than you can.** Whatever you approve is intersected with your own permissions on that workspace — and re-checked on _every single call_, not frozen when you approved it. Lose a permission, and the connection loses it at the next call. Leave the workspace, and every connection you made stops working, with nobody having to remember to revoke it. Escalation ## The actions no preset contains Some actions create authority that outlives the connection itself. They are excluded from every preset and called out in their own section of the consent screen — you have to tick them deliberately, one at a time. - **Minting credentials** — API keys, machine-to-machine clients, webhook signing secrets, revealing or rotating feature-flag SDK keys, uploading push-notification credentials, end-user password-reset and verification codes. A new key outlives this connection, its policy and its expiry. - **Editing roles and policies** — rewriting the ceiling rather than working under it. - **Handing somebody a seat** — workspace invites, tenant member management, and waitlist invite-to-app. An invite to an address someone else controls is standing access. - **Emailing outside your verified domains** — a separate action from ordinary sending, because it is the one that reaches strangers. Limits ## What a runaway client cannot do Limits are per connection and per workspace — never per IP address, because every client of a given vendor shares one. | Tool kind | Per connection | Per workspace | | --- | --- | --- | | Reads | 120 / min | 600 / min | | Writes | 30 / min | 120 / min | | Sending email | 5 / min | 20 / min | Sending is also capped at 20 emails per connection per hour, and a send counts against the write budget as well as its own. Results are capped at 128 KB and every list tool pages with a cursor, so one question cannot pull your whole mailbox into a model's context. Hit a limit and the tool answers with a `retry_after` the client can wait on. **Notify:** `notify_send` reaches only recipients that already exist (no inline profiles, no `create_missing`) and counts each recipient against the same hourly cap. `notify_explain_send` is a dry run that sends nothing and says why each channel would or would not go out. Uploading push credentials, rotating web push keys and minting recipient tokens are not tools at all. Content that came from outside — email bodies, waitlist notes, extracted web pages — is returned to the model wrapped and labelled as data, never as instructions. That is the containment boundary for prompt injection: a message in your inbox does not get to tell your assistant what to do. API keys, tokens and signing secrets are stripped from every tool result. Audit ## Every call is on the record Each tool call — including the ones that were refused — lands in the workspace audit log the console already shows. The row records you as the actor, because the authority is yours, and marks the actor type `mcp_client` so that "you did this" and "an AI client acting as you did this" are visibly different rows. It carries the client's id, whether it was verified, the tool name, the outcome, and the arguments — redacted and bounded, because an audit row is not a place a secret should end up. Refusals count. A feed that only recorded what succeeded could not show you the hour somebody spent probing. Revoke ## Disconnecting a client Revocation kills the whole family at once — the grant, its refresh tokens and every live access token — in one transaction. The client stops working on its next call. The quickest way is the console. **Connected apps** under your account lists everything you have connected, and the same page under Workspace settings lists every connection any member has made against the workspace — the offboarding view. Both have a disconnect button; the API below is the same thing for scripts. ```bash title="your own connections" # List the clients you have connected curl https://api.platform-auth.productcraft.co/v1/oauth/connections \ -H "Authorization: Bearer " # Disconnect one curl -X DELETE \ https://api.platform-auth.productcraft.co/v1/oauth/connections/ \ -H "Authorization: Bearer " ``` Workspace owners and admins have the other half of the lever: every connection made against the workspace by any member, including people who have since left. That is the **Connected apps** page under Workspace settings, and these endpoints underneath it. ```title="workspace-wide (owner / admin)" GET /v1/oauth/workspaces/{workspace_id}/connections DELETE /v1/oauth/workspaces/{workspace_id}/connections/{grant_id} ``` Those require `workspace.connection.read` and `workspace.connection.revoke`, which owners and admins hold by default. Removing a member also revokes every connection they made — offboarding does not depend on anybody remembering this page. Troubleshooting ## If the client cannot connect - **It asks you to authenticate again and again.** The connection was revoked, or your access to the workspace changed. Approve it again from the client. - **A tool you expected is missing.** The tool list is filtered by what you approved. Reconnect and grant the missing area — or check whether the action is in the escalation list above, which no preset includes. - **A tool answers "not permitted".** Your own role on the workspace is the ceiling. If you lost a permission, the connection lost it too. Everything the server does with a workspace goes through the same policy engine as the rest of the platform — see the [Platform docs](https://productcraft.co/docs/platform.md) for how roles, policies and workspace API keys fit together. --- title: "SDKs | ProductCraft Docs" description: "Official Node.js / TypeScript SDKs for the ProductCraft platform — Auth, Mail, Waitlist, Social, Trawl, Platform-Auth, and the productcraft umbrella package. Generated from the live OpenAPI specs, MIT-licensed, server-side." url: https://productcraft.co/docs/sdks --- [Docs](https://productcraft.co/docs.md) SDKs # Node.js SDKs. Typed, generated from the live OpenAPI specs, MIT-licensed, server-side. Every product on the ProductCraft platform ships an official Node.js / TypeScript SDK published to npm. The SDKs are generated from the same OpenAPI specs the API reference docs render from — so the types you see in your editor always match the wire shape in production. Install ## Pick one product or grab the umbrella Install the per-product package when you only need one surface. Install the umbrella when you call more than one from the same backend — it pulls each per-product package as a dependency. ```bash title="install one product" npm install @productcraft/auth # or pnpm add @productcraft/mail # or yarn add @productcraft/waitlist ``` ```bash title="install the umbrella" npm install productcraft ``` Packages ## What's on npm All packages live under the @productcraft scope. The umbrella is the unscoped 'productcraft' package. - [@productcraft/auth](https://productcraft.co/docs/auth.md): Customer auth & EndUsers: sign-in flows, OAuth (Apple, Google, GitHub), MFA, passkeys, sessions, roles, M2M, JWT verification with a built-in JWKS cache. 1.0 is generated like every other SDK: auth.consumer(slug).signin, auth.admin.app(id), auth.verifyToken, typed errors, retries and pagination (npm install @productcraft/auth).View on npm ↗Read more → - [@productcraft/mail](https://productcraft.co/docs/mail.md): Transactional email on your own domain: raw HTML and template sends, domains with DKIM, the delivery log, contacts, broadcasts, suppression lists and signed webhooks. 1.0 is on the generated runtime: mail.emails.send / templates.send / domains.poll, typed errors, retries, automatic idempotency keys, pagination and webhooks.unwrap.View on npm ↗Read more → - [@productcraft/waitlist](https://productcraft.co/docs/waitlist.md): Waitlist management: public-form signups, variants for A/B/n landing pages, referrals, leaderboard, approvals with invite-to-app, signed webhooks, CSV export. 1.0 is on the generated runtime: waitlist.lists.create / entries.bulk, a keyless waitlist.public({ workspace, waitlist }) client for browser forms, typed errors, retries and webhooks.unwrap.View on npm ↗Read more → - [@productcraft/social](https://productcraft.co/docs/social.md): Social infrastructure as an API: communities, posts, ranked feeds, stories with polls and close-friends, messaging, notifications, moderation. 1.1 adds the generated resource methods: social.community(id).as(actorId).posts.create(), typed errors, retries, pagination and webhooks.unwrap.View on npm ↗Read more → - [@productcraft/trawl](https://productcraft.co/docs/trawl.md): AI web extraction — submit a JSON Schema plus a natural-language description, a browser agent extracts schema-conforming data from the live web, delivered to a signed webhook. 1.0 is on the generated runtime: trawl.jobs.create / createAndPoll / retrieve, typed errors, retries, pagination, webhook verification and a mock fetch for tests.View on npm ↗Read more → - [@productcraft/flags](https://productcraft.co/docs/flags.md): Feature flags and remote settings: FlagsClient downloads the config for one environment and evaluates every flag locally (polling or lazy, a cache and a bootstrap for outages, overrides, evaluation details, a synchronous snapshot), and the Flags management client covers projects, targeting, segments, SDK keys, history, webhooks and the ConfigCat import. Companions: @productcraft/flags-react, @productcraft/flags-openfeature and @productcraft/flags-engine.View on npm ↗Read more → - [@productcraft/notify](https://productcraft.co/docs/notify.md): Notifications across an in-app inbox, email, web push, APNs and FCM: notify.notifications.send with idempotent retries, recipients and devices, preferences, notification types as code, recipient tokens for browsers and apps, channels, the message log and webhook verification. Companions for the browser: @productcraft/notify-js (framework-free inbox store, real-time updates, web push and a service worker) and @productcraft/notify-react (, , hooks).View on npm ↗Read more → - [@productcraft/platform-auth](https://productcraft.co/docs/platform.md): Your ProductCraft account and workspaces: members, invites, roles, IAM policies, workspace API keys, service activation and introspection. 1.0 is on the generated runtime: platform.workspaces.create / apiKeys.create / apiKeys.self, typed errors, retries and pagination. (For your own product users, use @productcraft/auth.)View on npm ↗Read more → - [@productcraft/auth-passport](https://productcraft.co/docs/auth.md): Passport-JWT adapter for Auth. Plug an Auth ConsumerScope into a `passport-jwt` Strategy so existing Passport setups can verify Auth-issued tokens.View on npm ↗Read more → ### productcraft All-in-one umbrella package. One install, one auth credential, one class with every surface attached (`pc.auth`, `pc.mail`, `pc.waitlist`, …). Install this when you call more than one ProductCraft API from the same backend. [View on npm ↗](https://www.npmjs.com/package/productcraft) Read more Configuration ## Credentials from the environment On the server, omit `auth` and every client reads your workspace API key from `PRODUCTCRAFT_API_KEY`. An explicit `auth` always wins. Hosts are never read from the environment: override them in code with `baseUrl`. `auth.consumer()` takes its app slug from `PRODUCTCRAFT_AUTH_APP` when you omit it, and never reads a credential from the environment. Routes that need an app key (PAK) on the consumer side take an explicit `auth`. This is a server-only fallback. Never put a key in a `NEXT_PUBLIC_*` variable or anything else your bundler inlines into browser code. ```dotenv title=".env" PRODUCTCRAFT_API_KEY=pcft_live_... # workspace API key PRODUCTCRAFT_AUTH_APP=my-app-slug # default slug for auth.consumer() ``` Runtime ## What every generated client does Every package is generated from its API's spec onto the same runtime, so each client below behaves the same way. Node 20.3 or later (also Bun, Deno and edge runtimes), ESM and CommonJS. ### Typed errors Every failure is a class you can catch: one per status (`BadRequestError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `RateLimitError`, `InternalServerError`, …) under `APIError`, plus `APIConnectionError` and `APITimeoutError` for the network. Each carries `status`, `code`, `errors[]`, `requestId` and `docUrl`, a link into the [error code catalogue](https://productcraft.co/docs/errors.md). ```ts title="errors.ts" import { Trawl, APIError, RateLimitError } from "@productcraft/trawl"; const trawl = new Trawl(); try { await trawl.jobs.retrieve("3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b"); } catch (err) { if (err instanceof RateLimitError) { console.log("retry in", err.retryAfter, "s"); } else if (err instanceof APIError) { // Every API error: status, code, request_id and a link to /docs/errors console.log(err.status, err.code, err.requestId, err.docUrl); } else { throw err; } } ``` ### Retries and timeouts Network errors, 408, 429, 5xx and `409 IDEMPOTENCY_IN_PROGRESS` are retried twice by default with exponential backoff and jitter, honouring `Retry-After` up to 60 seconds. A POST or PATCH without an idempotency key is never retried. Each attempt times out after 60 seconds; pass an `AbortSignal` for an overall deadline. ```ts title="retries.ts" import { Trawl } from "@productcraft/trawl"; // Client-wide: 3 retries, 20 s per attempt const trawl = new Trawl({ maxRetries: 3, timeout: 20_000 }); // Per request: no retries, 5 s overall deadline await trawl.jobs.list({}, { maxRetries: 0, signal: AbortSignal.timeout(5_000) }); ``` ### Idempotency Every operation that accepts an `Idempotency-Key` gets one automatically, reused on every retry, so a retried create never runs twice. Pass your own key to make a retry from another process or a queue safe as well. ```ts title="idempotency.ts" import { Trawl } from "@productcraft/trawl"; const trawl = new Trawl(); // A key is generated for every create and reused on each retry. // Pass your own to make a retry from another process safe too. const job = await trawl.jobs.create( { description: "Extract the product title.", json_schema: { type: "object", required: ["title"] }, }, { idempotencyKey: "order-1234-extract" }, ); ``` ### Pagination List methods return a page you can `await`, or walk with `for await` across every page. The SDK follows `next_cursor` while `has_more` is true. ```ts title="pagination.ts" import { Trawl } from "@productcraft/trawl"; const trawl = new Trawl(); // Every item across every page for await (const job of trawl.jobs.list({ limit: 50 })) console.log(job.id); // One page at a time const page = await trawl.jobs.list(); if (page.hasNextPage()) await page.getNextPage(); // Collect, with a ceiling const all = await trawl.jobs.list().toArray({ maxItems: 500 }); ``` ### Polling Long-running resources get `poll()` and `createAndPoll()`: they retrieve until the status is terminal, honour `Retry-After`, and throw `APITimeoutError` after `timeoutMs`. ```ts title="polling.ts" import { Trawl } from "@productcraft/trawl"; const trawl = new Trawl(); type Product = { title: string }; const done = await trawl.jobs.createAndPoll( { description: "Extract the product title.", json_schema: { type: "object", required: ["title"] }, }, { intervalMs: 2_000, timeoutMs: 600_000 }, ); console.log(done.status, done.result?.title); ``` ### Webhooks `webhooks.unwrap()` verifies the Standard Webhooks signature and returns a typed event. It needs the **raw** request body: a body your framework has already parsed as JSON no longer matches the signature. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT__WEBHOOK_SECRET`. ```ts title="app/webhooks/route.ts (Next.js)" import { Trawl } from "@productcraft/trawl"; // Secret from PRODUCTCRAFT_TRAWL_WEBHOOK_SECRET const trawl = new Trawl(); export async function POST(req: Request) { // Verify against the RAW body: never JSON.parse it first. const event = await trawl.webhooks.unwrap({ payload: await req.text(), headers: req.headers, }); switch (event.type) { case "job.succeeded": console.log(event.data.job.id, event.data.job.result); break; case "job.failed": console.log(event.data.job.id, event.data.job.error); break; default: break; // credits.low and types added later } return new Response(null, { status: 204 }); } ``` ```ts title="server.ts (Express)" import express from "express"; import { Trawl } from "@productcraft/trawl"; const trawl = new Trawl(); // secret from PRODUCTCRAFT_TRAWL_WEBHOOK_SECRET const app = express(); // express.raw keeps the body as bytes: a parsed body fails verification app.post("/webhooks", express.raw({ type: "application/json" }), async (req, res) => { const event = await trawl.webhooks.unwrap({ payload: req.body, headers: req.headers }); console.log(event.type); res.sendStatus(204); }); ``` ```ts title="server.ts (Hono)" import { Hono } from "hono"; import { Trawl } from "@productcraft/trawl"; const trawl = new Trawl(); const app = new Hono(); app.post("/webhooks", async (c) => { const event = await trawl.webhooks.unwrap({ payload: await c.req.text(), headers: c.req.raw.headers, }); console.log(event.type); return c.body(null, 204); }); ``` ### Raw responses Every returned object has a non-enumerable `lastResponse` (`requestId`, `status`, `headers`). `.withResponse()` adds the `Response` and the parsed rate-limit headers. ```ts title="raw-response.ts" import { Trawl } from "@productcraft/trawl"; const trawl = new Trawl(); const id = "3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b"; const job = await trawl.jobs.retrieve(id); console.log(job.lastResponse.requestId); const { data, response, requestId, rateLimit } = await trawl.jobs .retrieve(id) .withResponse(); console.log(data.status, response.status, requestId, rateLimit?.remaining); ``` ### The .client escape hatch `.client` stays on every package: the typed `openapi-fetch` client over the same credential and base URL, without retries. Use it for anything the resource methods do not cover. Code written against it before the generated methods keeps working. ```ts title="client.ts" import { Trawl } from "@productcraft/trawl"; const trawl = new Trawl(); // .client: the typed openapi-fetch client, same key and base URL, // no retries. For anything the resource methods do not cover. const { data, error } = await trawl.client.GET( "/v1/workspaces/{workspace_id}/credits", { params: { path: { workspace_id: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" } } }, ); console.log(data, error); ``` ### Testing `@productcraft//testing` exports `createMockFetch()`, a `fetch` that answers every operation with its spec example. See [Testing without side effects](https://productcraft.co/docs/testing.md). Quickstart ## Hello, Auth A minimum viable Auth integration through the BFF pattern. End-user routes on `auth.consumer(slug)` need no key; admin routes send your workspace API key, so keep that server-side and never embed it in a browser bundle. ```ts title="server.ts" import { Auth } from "@productcraft/auth"; declare const identityTokenFromAppleSdk: string; declare const rawNonceClientGenerated: string; // Consumer routes need no key (default slug: PRODUCTCRAFT_AUTH_APP) const auth = new Auth(); const consumer = auth.consumer("my-app-slug"); // Email + password sign-in, discriminated on `result` const signin = await consumer.signin({ identifier: "alice@example.com", password: "...", }); if (signin.result === "session") console.log(signin.access_token); // Sign in with Apple (native iOS flow) await consumer.signinWithProvider("apple", { id_token: identityTokenFromAppleSdk, nonce: rawNonceClientGenerated, }); // Verify a token your client sent you declare const bearer: string; const claims = await auth.verifyToken(bearer, { app: "my-app-slug" }); ``` Umbrella ## Hello, ProductCraft Install `productcraft` when you call more than one ProductCraft API from the same backend. One auth credential is shared across all surfaces; per-surface`baseUrl` overrides are available for staging environments. ```ts title="server.ts" import { ProductCraft } from "productcraft"; // Reads PRODUCTCRAFT_API_KEY from the environment // (Mail uses it; Auth's end-user sign-in never sends it) const pc = new ProductCraft(); // Auth: sign in an end user await pc.auth.consumer("my-app").signin({ identifier: "alice@example.com", password: "...", }); // Mail: send a template from the same backend. An Idempotency-Key // is generated for you, so a retried send never mails twice. await pc.mail.templates.send("welcome", { from: "hello@yourbrand.com", to: "alice@example.com", data: { name: "Alice" }, }); ``` How they're built ## Spec-driven, low maintenance Every per-surface SDK regenerates from the live `/docs-json` OpenAPI spec of its API. A nightly CI job in [clauderanelagh/productcraft-node](https://github.com/clauderanelagh/productcraft-node) refreshes the specs, regenerates the typed clients, and opens a PR with the diff. Merging triggers a Changesets release that publishes the affected packages to npm with provenance attestations. What that means for you: the types in your editor always match what production accepts. New endpoints land in the SDK without you (or us) hand-rolling another binding. [View on GitHub](https://github.com/clauderanelagh/productcraft-node) [Auth quickstart](https://productcraft.co/docs/auth/getting-started.md) --- title: "Testing | Docs" description: "How to test a ProductCraft integration without side effects: SDK mock fetch for unit tests, a separate test workspace for integration tests, and mailbox simulator addresses for Mail." url: https://productcraft.co/docs/testing --- [Documentation](https://productcraft.co/docs.md) Every API # Testing without side effects. Unit tests that never touch the network, integration tests in a workspace of their own, and test addresses that never reach a real inbox. ## There is no test mode yet Every ProductCraft API key is live: there are no test keys and no sandbox host. A request made with a key does what it says, whether it comes from production or from your test suite. The three patterns below keep tests from sending real email, spending Trawl credits or changing data your product uses. 1 ## Unit tests: the SDK's mock fetch Every generated SDK package has a testing entry point. createMockFetch() is a fetch that answers each operation with the example from the OpenAPI spec, so code under test runs against realistic responses with no network at all. ```ts title="jobs.test.ts" import { Trawl } from "@productcraft/trawl"; import { createMockFetch } from "@productcraft/trawl/testing"; // Answers every operation with its example from the OpenAPI spec. // No network, no credits, no side effects. const fetch = createMockFetch({ // Override one operation by its resource.method name "jobs.retrieve": { id: "job_1", status: "succeeded", result: { title: "Mug" } }, }); const trawl = new Trawl({ apiKey: "test", workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b", fetch, }); const job = await trawl.jobs.retrieve("job_1"); console.log(job.status, fetch.calls.length); // "succeeded" 1 ``` - Import it from `@productcraft//testing` (today `@productcraft/trawl/testing`; the other packages gain it as they move to the generated runtime, see [SDKs](https://productcraft.co/docs/sdks.md#testing)). - Override an operation by its `resource.method` name with a value (sent as the JSON body with the operation's success status) or a handler that returns a `Response`, for example a 429 to test your retry path. - `fetch.calls` records every request (operation, method, URL, headers, parsed body), so you can assert what your code sent, including the `Idempotency-Key`. 2 ## Integration tests: a workspace of their own Run tests that call the real API against a separate workspace, never the one your product uses. - Create a second workspace in the [console](https://console.productcraft.co) for tests only, and enable just the products the tests call. - Mint its API key with a policy that grants only the actions the tests need (for example `trawl.create` and `trawl.read`), so a test that goes wrong cannot touch anything else. - Create throwaway resources with a recognisable prefix and delete them in your teardown, even when a test fails. - Keep traffic modest. Rate limits apply per workspace and per client IP exactly as in production; the SDK retries 429s for you, but a load test belongs on your own infrastructure. 3 ## Mail: mailbox simulator addresses Mail delivers through Amazon SES, so its mailbox simulator works for every send. Mail to these addresses never reaches a person and never counts against your sending reputation. | Send to | What happens | | --- | --- | | success@simulator.amazonses.com | Accepted and delivered. The message timeline shows it delivered. | | bounce@simulator.amazonses.com | A hard bounce: the message is bounced and the address goes on the workspace suppression list, as a real bounce would. | | complaint@simulator.amazonses.com | Delivered, then reported as spam: the message is complained and the address goes on the suppression list. | | suppressionlist@simulator.amazonses.com | A hard bounce, as if the address were on the global suppression list. | | ooto@simulator.amazonses.com | Delivered, then an out-of-office auto-reply. | Never test with made-up addresses at real domains: each one bounces, and bounces count against the workspace's sending reputation. The bounce and complaint addresses are the way to exercise your [Mail](https://productcraft.co/docs/mail.md) webhook handlers for `message.bounced` and `message.complained`. Afterwards the address is on your suppression list, so later sends to it are suppressed until you remove it there. ## Webhooks and Trawl - **Webhooks:** every product's endpoints have Send test (`webhooks.endpoints.test()` in the SDK), which delivers a signed sample event with `"test": true`. Your handler verifies it like any other. See the [Webhooks guide](https://productcraft.co/docs/platform/webhooks.md). - **Flags:** a `FlagsClient` with overrides (`behaviour: "local_only"`) or `createTestClient` from `@productcraft/flags/testing` needs no network and no SDK key; the test evaluation endpoint checks real targeting without a deploy. See [Testing with overrides](https://productcraft.co/docs/flags/guides/05-testing-with-overrides.md). - **Notify:** `dry_run: true` on a send explains per recipient and channel what would happen and sends nothing; the inbox is a channel your test can read back; email only to the SES mailbox simulator; and `createMockFetch` from `@productcraft/notify/testing` for unit tests. See [Testing without devices](https://productcraft.co/docs/notify/guides/17-testing-without-devices.md). - **Trawl:** every agent step uses a credit, test workspace or not. Unit-test with the mock fetch, and keep integration jobs small: one seed URL, a narrow schema and a low `max_steps`. --- title: "Errors | Docs" description: "The error body every ProductCraft API returns: status_code, message, code and details. How to branch on code, what validation errors look like, and the deprecated statusCode alias." url: https://productcraft.co/docs/api/errors --- [Documentation](https://productcraft.co/docs.md) Every API # Errors. Auth, Mail, Waitlist, Social, Trawl, Flags, Notify and the Platform API all answer a failed request with the same JSON body, so one error handler covers all of them. ## The error body ```json title="404 Not Found" { "status_code": 404, "statusCode": 404, "message": "Webhook endpoint not found", "code": "WEBHOOK_ENDPOINT_NOT_FOUND" } ``` | Field | Type | Meaning | | --- | --- | --- | | status_code | number | The HTTP status of the response, repeated in the body. Always present. | | message | string or string[] | A human-readable explanation. On a validation error, one message per failing field, each naming the field as you sent it. | | code | string | A stable, machine-readable code. Always present. Branch on this, never on message. | | details | object (optional) | Structured context for some errors, with snake_case keys: the unknown fields you sent, the limit you hit and when to retry. | | statusCode | number (deprecated) | The same value as status_code. Kept so existing clients keep working. Read status_code in new code. | ## Branch on code Every error carries a `code`. An error specific to an operation has its own code, for example `USERNAME_TAKEN`, `WEBHOOK_ENDPOINT_LIMIT` or `SERVICE_NOT_ENABLED`; the [error code catalogue](https://productcraft.co/docs/errors.md) lists every code with what to do about it. Any other error gets the generic code for its status: | Status | Generic code | | --- | --- | | 400 | BAD_REQUEST, or VALIDATION_ERROR when the request body or query failed validation | | 401 | UNAUTHORIZED | | 403 | FORBIDDEN | | 404 | NOT_FOUND | | 409 | CONFLICT | | 413 | PAYLOAD_TOO_LARGE | | 422 | UNPROCESSABLE_ENTITY | | 429 | RATE_LIMITED | | 500 | INTERNAL_SERVER_ERROR | | 503 | SERVICE_UNAVAILABLE | Messages are written for people and can change. Codes do not. ## Validation errors A request that fails validation gets a 400 with `code: "VALIDATION_ERROR"` and one message per problem. Each message names the field the way you sent it, in snake_case. A field the operation does not accept is rejected rather than ignored. ```json title="400 Bad Request" { "status_code": 400, "statusCode": 400, "message": ["domain_id must be a UUID"], "code": "VALIDATION_ERROR" } ``` ## statusCode is deprecated Every other key in every ProductCraft API is snake_case. The error body used to be the exception: it carried the status as `statusCode`. It now carries `status_code`, and keeps `statusCode` with the same value so that nothing reading it breaks. While the alias is sent, every error response also carries these headers (RFC 9745): ```http title="response headers" Deprecation: true Link: ; rel="deprecation" ``` There is no removal date. If `statusCode` is ever removed, it will be announced in the [changelog](https://productcraft.co/changelog) well ahead of time. Read `status_code` (or the HTTP status itself) in new code. The official SDKs already read the HTTP status, so they need no change. --- title: "Error codes | Docs" description: "Every error code the ProductCraft APIs return: the HTTP status, what it means and what to do. Generated from the live OpenAPI specs." url: https://productcraft.co/docs/errors --- [Documentation](https://productcraft.co/docs.md) Every API # Error codes. Every code the ProductCraft APIs return, with its status, what it means and what to do. Generated from each API's published OpenAPI spec. Every failed request returns the same body (see [the error body](https://productcraft.co/docs/api/errors.md)). Branch on `code`, never on `message`. The set is open: a new code can appear without notice, so treat one you do not know by its HTTP status. The SDKs raise a class per status and link here from `err.docUrl`. ```ts title="handle-errors.ts" import { Trawl, APIError, RateLimitError } from "@productcraft/trawl"; const trawl = new Trawl(); try { await trawl.jobs.retrieve("3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b"); } catch (err) { if (err instanceof RateLimitError) { console.log("retry in", err.retryAfter, "s"); } else if (err instanceof APIError) { // Every API error: status, code, request_id and a link to /docs/errors console.log(err.status, err.code, err.requestId, err.docUrl); } else { throw err; } } ``` ## Every API Codes any ProductCraft API can return: the generic code for each status, plus the shared authentication, idempotency and webhook codes. [ACTIONS_NOT_GRANTABLE](#ACTIONS_NOT_GRANTABLE) 403 The policy grants actions the caller does not hold. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [BAD_GATEWAY](#BAD_GATEWAY) 502 An upstream service returned an invalid response. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [BAD_REQUEST](#BAD_REQUEST) 400 The request is malformed (not valid JSON, a bad header, an unusable parameter). What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [CONFLICT](#CONFLICT) 409 The request conflicts with the current state of the resource. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [FORBIDDEN](#FORBIDDEN) 403 The caller is authenticated but not allowed to do this. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [GATEWAY_TIMEOUT](#GATEWAY_TIMEOUT) 504 An upstream service did not answer in time; retry. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [GONE](#GONE) 410 The resource existed but has been removed for good. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [IDEMPOTENCY_IN_PROGRESS](#IDEMPOTENCY_IN_PROGRESS) 409 A request with the same Idempotency-Key is still running. Retry after Retry-After seconds with the same key to get its response. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [IDEMPOTENCY_KEY_REQUIRED](#IDEMPOTENCY_KEY_REQUIRED) 400 This operation requires an Idempotency-Key header. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [IDEMPOTENCY_KEY_REUSE](#IDEMPOTENCY_KEY_REUSE) 409 The Idempotency-Key was already used with a different body or route. What to do: Use a new Idempotency-Key for a different request; reuse a key only for a retry of the same one. (IdempotencyKeyReuseError) [INTERNAL_SERVER_ERROR](#INTERNAL_SERVER_ERROR) 500 An unexpected server error. Retrying is safe for idempotent requests; quote request_id to support. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [INVALID_CREDENTIALS](#INVALID_CREDENTIALS) 401 The credentials were not accepted. What to do: Send a valid, unexpired API key or token, or sign in again. (AuthenticationError) [MCP_NOT_PERMITTED](#MCP_NOT_PERMITTED) varies An MCP (agent) token cannot call this route. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [MCP_WORKSPACE_MISMATCH](#MCP_WORKSPACE_MISMATCH) varies The MCP token was issued for a different workspace. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [METHOD_NOT_ALLOWED](#METHOD_NOT_ALLOWED) 405 The route does not accept this HTTP method. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [NOT_ACCEPTABLE](#NOT_ACCEPTABLE) 406 The route cannot produce the requested content type. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [NOT_FOUND](#NOT_FOUND) 404 The resource does not exist, or belongs to another workspace or app. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [NOT_IMPLEMENTED](#NOT_IMPLEMENTED) 501 The server does not support this operation. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [PAK_NOT_PERMITTED](#PAK_NOT_PERMITTED) 403 A workspace API key cannot call this route. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [PAYLOAD_TOO_LARGE](#PAYLOAD_TOO_LARGE) 413 The request body is over the size limit. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [PAYMENT_REQUIRED](#PAYMENT_REQUIRED) 402 The workspace has no credit or plan for this operation. What to do: Add credit or upgrade the plan, then retry. (APIError) [PRECONDITION_FAILED](#PRECONDITION_FAILED) 412 A precondition header did not match. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [PRECONDITION_REQUIRED](#PRECONDITION_REQUIRED) 428 The route requires a precondition header. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [RATE_LIMITED](#RATE_LIMITED) 429 Too many requests; retry after the Retry-After header. What to do: Wait Retry-After seconds. The SDK retries this for you. (RateLimitError) [REQUEST_TIMEOUT](#REQUEST_TIMEOUT) 408 The request took too long to arrive. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [SERVICE_NOT_ENABLED](#SERVICE_NOT_ENABLED) 403, 409 The workspace has not enabled this product. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [SERVICE_UNAVAILABLE](#SERVICE_UNAVAILABLE) 503 The service or one of its dependencies is temporarily unavailable; retry. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [SESSION_REVOKED](#SESSION_REVOKED) 401 The session behind this token was signed out or revoked. What to do: Send a valid, unexpired API key or token, or sign in again. (AuthenticationError) [UNAUTHORIZED](#UNAUTHORIZED) 401 No credentials, or the token or API key is invalid, expired or revoked. What to do: Send a valid, unexpired API key or token, or sign in again. (AuthenticationError) [UNPROCESSABLE_ENTITY](#UNPROCESSABLE_ENTITY) 422 The request is well-formed but cannot be carried out. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [UNSUPPORTED_MEDIA_TYPE](#UNSUPPORTED_MEDIA_TYPE) 415 The request body is not in a content type the route accepts. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [VALIDATION_ERROR](#VALIDATION_ERROR) 400, 422 One or more request fields are invalid; errors lists each field (param, message, code). What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) ## Product codes Codes specific to one or more products. Each lists the APIs that return it. [ACCOUNT_DEACTIVATED](#ACCOUNT_DEACTIVATED) 403 Platform Account deactivated. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [ACCOUNT_EXISTS](#ACCOUNT_EXISTS) 409 Auth An account already exists for this address. Sign in and accept the invite from your account instead. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [account_exists_with_different_provider](#account_exists_with_different_provider) 409 Auth An account with this email exists and signs in with a different method. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [ACCOUNT_NOT_FOUND](#ACCOUNT_NOT_FOUND) 404 Auth Account not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [ACCOUNT_SUSPENDED](#ACCOUNT_SUSPENDED) 403 Auth · Platform Account suspended. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [AGENT_ACCESS_DISABLED](#AGENT_ACCESS_DISABLED) 404 Auth Agent access (OAuth for MCP) is not turned on for this app. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [AGENT_ACCESS_INVALID_CONFIG](#AGENT_ACCESS_INVALID_CONFIG) 400 Auth The agent access settings are invalid; details names the field. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [AGENT_AUTHORIZATION_DECIDED](#AGENT_AUTHORIZATION_DECIDED) 409 Auth This agent authorization request was already approved or denied. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [AGENT_AUTHORIZATION_INVALID](#AGENT_AUTHORIZATION_INVALID) 400 Auth The approval does not match the request: a scope that was not requested, or context over 2 KB. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [AGENT_AUTHORIZATION_NOT_FOUND](#AGENT_AUTHORIZATION_NOT_FOUND) 404 Auth Agent authorization request not found, expired, or opened by another user. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [AGENT_GRANT_NOT_FOUND](#AGENT_GRANT_NOT_FOUND) 404 Auth Agent connection not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [ALREADY_A_MEMBER](#ALREADY_A_MEMBER) 409 Platform Already a member. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [APEX_NOT_SUPPORTED](#APEX_NOT_SUPPORTED) 400 Auth A custom domain must be a subdomain, not the apex of a zone. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [APP_ARCHIVED](#APP_ARCHIVED) 403 Auth The app is archived. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [APP_HAS_NO_WORKSPACE](#APP_HAS_NO_WORKSPACE) 409 Auth App has no workspace. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [APP_NOT_FOUND](#APP_NOT_FOUND) 404 Auth App not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [APP_SUSPENDED](#APP_SUSPENDED) 403 Auth The app is suspended; its consumer routes are closed. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [ASSET_INVALID_CONTAINER](#ASSET_INVALID_CONTAINER) 422 Social Uploaded bytes are not an MP4/MOV/WebM container. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [ASSET_INVALID_SIZE](#ASSET_INVALID_SIZE) varies Social Video must declare a positive integer byte_size. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ASSET_INVALID_TYPE](#ASSET_INVALID_TYPE) varies Social The asset file type is not supported. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ASSET_MAGIC_MISMATCH](#ASSET_MAGIC_MISMATCH) varies Social Asset file content does not match declared type. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ASSET_NOT_OWNED](#ASSET_NOT_OWNED) varies Social The asset belongs to another actor. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ASSET_NOT_READY](#ASSET_NOT_READY) varies Social The asset is still processing. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ASSET_NOT_VIDEO](#ASSET_NOT_VIDEO) 422 Social Only video assets are finalized explicitly. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [ASSET_PROCESSING_FAILED](#ASSET_PROCESSING_FAILED) varies Social Asset could not be processed. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ASSET_TOO_LARGE](#ASSET_TOO_LARGE) 422 Social The asset is over the size limit. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [ASSET_TRANSCODE_FAILED](#ASSET_TRANSCODE_FAILED) varies Social The video could not be transcoded. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ASSET_UPLOAD_INCOMPLETE](#ASSET_UPLOAD_INCOMPLETE) 422 Social No uploaded file was found for the asset. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [AUDIENCE_REQUIRED](#AUDIENCE_REQUIRED) 422 Mail Pass segment_id, topic_id, or both. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [AUTH_SETTINGS_IN_METADATA](#AUTH_SETTINGS_IN_METADATA) 400 Auth Sign-in settings cannot be changed through app metadata. Use PATCH /v1/apps/{appId}/auth-config, or leave the auth key out of metadata. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [AUTH_USER_ALREADY_LINKED](#AUTH_USER_ALREADY_LINKED) 409 Notify The Auth end user is already linked to another recipient in this workspace. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [AVATAR_INVALID_TYPE](#AVATAR_INVALID_TYPE) 415 Auth Avatar file could not be decoded as an image. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [AVATAR_MAGIC_MISMATCH](#AVATAR_MAGIC_MISMATCH) 415 Auth Avatar file content does not match declared type. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [AVATAR_NOT_FOUND](#AVATAR_NOT_FOUND) varies Auth Avatar not found. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [AVATAR_TOO_LARGE](#AVATAR_TOO_LARGE) 413 Auth Avatar exceeds 2 MB. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [BOT_PROTECTION_FAILED](#BOT_PROTECTION_FAILED) 403 Auth The bot-protection token was rejected. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [BOT_PROTECTION_REQUIRED](#BOT_PROTECTION_REQUIRED) 400 Auth The app requires a bot-protection token on sign-up. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [BOT_PROTECTION_UNAVAILABLE](#BOT_PROTECTION_UNAVAILABLE) 503 Auth Bot protection could not be checked; retry. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [BROADCAST_AUDIENCE_EMPTY](#BROADCAST_AUDIENCE_EMPTY) 422 Mail Nobody in this audience can receive the broadcast. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [BROADCAST_CONTENT_CONFLICT](#BROADCAST_CONTENT_CONFLICT) 422 Mail Use a template or inline html, not both. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [BROADCAST_NOT_CANCELABLE](#BROADCAST_NOT_CANCELABLE) 409 Mail The broadcast cannot be canceled in its current status. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [BROADCAST_NOT_DELETABLE](#BROADCAST_NOT_DELETABLE) 409 Mail The broadcast cannot be deleted in its current status; cancel it first. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [BROADCAST_NOT_DRAFT](#BROADCAST_NOT_DRAFT) 409 Mail The broadcast is no longer a draft (details.status). What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [BROADCAST_NOT_FOUND](#BROADCAST_NOT_FOUND) 404 Mail Broadcast not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [BROADCAST_NOT_READY](#BROADCAST_NOT_READY) 422 Mail The broadcast cannot be sent yet (details.problems). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [CANNOT_QUOTE_PRIVATE](#CANNOT_QUOTE_PRIVATE) 422 Social Cannot quote a private post. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [CANNOT_QUOTE_SELF](#CANNOT_QUOTE_SELF) 422 Social Cannot quote your own post. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [CANNOT_REPOST_PRIVATE](#CANNOT_REPOST_PRIVATE) varies Social Cannot repost a private post. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [CANNOT_REPOST_SELF](#CANNOT_REPOST_SELF) varies Social Cannot repost your own post. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [CAPABILITY_NOT_VERIFIED](#CAPABILITY_NOT_VERIFIED) 409 Mail A verified domain cannot gain sending or receiving until the new records verify (details.records). What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CATEGORY_IN_USE](#CATEGORY_IN_USE) 409 Notify The category is used by notification types; move them to another category first. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CATEGORY_KEY_TAKEN](#CATEGORY_KEY_TAKEN) 409 Notify A category with this key already exists in the workspace. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CATEGORY_NOT_FOUND](#CATEGORY_NOT_FOUND) 404, 422 Notify No category with this id or key in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CHANGE_NOT_FOUND](#CHANGE_NOT_FOUND) 404 Flags The change does not exist in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CHANNEL_NOT_CONFIGURED](#CHANNEL_NOT_CONFIGURED) 404 Notify The channel has no credentials configured in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CIRCULAR_PREREQUISITE](#CIRCULAR_PREREQUISITE) 422 Flags The prerequisite would create a cycle between settings. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [COMMENTS_DISABLED](#COMMENTS_DISABLED) varies Social Comments are turned off for this post. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [COMMENTS_FOLLOWERS_ONLY](#COMMENTS_FOLLOWERS_ONLY) varies Social Only followers can comment on this post. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [COMMENTS_MENTIONED_ONLY](#COMMENTS_MENTIONED_ONLY) varies Social Only actors mentioned in this post can comment. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [CONFIDENTIAL_LIST_NOT_EDITABLE](#CONFIDENTIAL_LIST_NOT_EDITABLE) 422 Flags The confidential list was sent pre-hashed, so it has no cleartext to edit, re-hash or reveal; send the full list instead. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [CONFIG_NOT_FOUND](#CONFIG_NOT_FOUND) 404 Flags The config does not exist in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CONFIG_TOO_LARGE](#CONFIG_TOO_LARGE) 422 Flags The rendered config would exceed the maximum config size. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [CONFIRMATION_REQUIRED](#CONFIRMATION_REQUIRED) 409, 422 Flags · Notify The request needs an explicit confirmation parameter. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CONTACT_EXISTS](#CONTACT_EXISTS) 409 Mail A contact with this email already exists. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CONTACT_LIMIT](#CONTACT_LIMIT) 409 Mail The workspace has the maximum number of contacts. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CONTACT_NOT_FOUND](#CONTACT_NOT_FOUND) 404 Mail Contact not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CONTACT_PROPERTY_EXISTS](#CONTACT_PROPERTY_EXISTS) 409 Mail A contact property with this key already exists. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CONTACT_PROPERTY_LIMIT](#CONTACT_PROPERTY_LIMIT) 409 Mail The workspace has the maximum number of contact properties. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CONTACT_PROPERTY_NOT_FOUND](#CONTACT_PROPERTY_NOT_FOUND) 404 Mail Contact property not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CREDENTIAL_INVALID](#CREDENTIAL_INVALID) 422 Notify The uploaded provider credential was rejected (malformed, wrong type or refused by the provider). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [CREDENTIAL_MISMATCH](#CREDENTIAL_MISMATCH) 422 Notify The credential belongs to a different app (bundle id or Firebase project id differs). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [CREDENTIAL_NOT_FOUND](#CREDENTIAL_NOT_FOUND) 404 Notify No channel credential with this id in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CROSS_ORIGIN_REJECTED](#CROSS_ORIGIN_REJECTED) 403 Platform The request came from an origin that is not allowed for this cookie-authenticated route. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [CUSTOM_DOMAIN_EXISTS](#CUSTOM_DOMAIN_EXISTS) 409 Auth This app already has a custom domain; remove it before adding another. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CUSTOM_DOMAIN_NOT_ACTIVE](#CUSTOM_DOMAIN_NOT_ACTIVE) 409 Auth This app has no active custom domain to test on. Finish its setup first. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [CUSTOM_DOMAIN_NOT_FOUND](#CUSTOM_DOMAIN_NOT_FOUND) 404 Auth Custom domain not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [CUSTOM_DOMAIN_OAUTH_ONLY](#CUSTOM_DOMAIN_OAUTH_ONLY) 400 Auth The custom domain only serves OAuth routes; test sign-in on the app domain instead. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [DATA_TOO_LARGE](#DATA_TOO_LARGE) 413 Notify The data object is over the size limit. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [DATE_RANGE_BEYOND_RETENTION](#DATE_RANGE_BEYOND_RETENTION) varies Mail The date range reaches past the data retention window. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [DATE_RANGE_TOO_WIDE](#DATE_RANGE_TOO_WIDE) varies Mail The date range is wider than allowed. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [DATE_WINDOW_TOO_WIDE](#DATE_WINDOW_TOO_WIDE) varies Mail The date window is longer than the message log retention. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [DELIVERY_NOT_FOUND](#DELIVERY_NOT_FOUND) 404 Notify No delivery with this id in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [DEVICE_MOVE_LIMIT](#DEVICE_MOVE_LIMIT) 429 Notify The device was moved between recipients too often; wait before moving it again. What to do: Wait Retry-After seconds. The SDK retries this for you. (RateLimitError) [DEVICE_NOT_FOUND](#DEVICE_NOT_FOUND) 404 Notify The recipient has no device with this id. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [DEVICE_TOKEN_INVALID](#DEVICE_TOKEN_INVALID) 422 Notify The device token or web push subscription is malformed for its platform. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [DKIM_KEY_MISSING](#DKIM_KEY_MISSING) 409 Mail The domain has no DKIM key yet. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [DNS_CONFLICTS](#DNS_CONFLICTS) 409 Auth · Mail Some records cannot be written without breaking existing ones; nothing was changed. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [DOMAIN_CONNECT_DISABLED](#DOMAIN_CONNECT_DISABLED) 409 Mail Domain Connect is turned off. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [DOMAIN_CONNECT_MAIL_FROM_LABEL](#DOMAIN_CONNECT_MAIL_FROM_LABEL) 409 Mail Domain Connect cannot apply a custom MAIL FROM label. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [DOMAIN_CONNECT_NOT_SENDING](#DOMAIN_CONNECT_NOT_SENDING) 409 Mail Domain Connect needs a sending domain. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [DOMAIN_CONNECT_UNAVAILABLE](#DOMAIN_CONNECT_UNAVAILABLE) 409 Mail The DNS provider does not support Domain Connect for this domain. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [DOMAIN_HAS_MAILBOXES](#DOMAIN_HAS_MAILBOXES) 409 Mail The domain still has active mailboxes (details.mailboxes). What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [DOMAIN_NOT_FOUND](#DOMAIN_NOT_FOUND) 404 Mail Domain not found in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [domain_not_verified_by_provider](#domain_not_verified_by_provider) 422 Mail · Waitlist The From domain's DNS records have been broken for over 72 h, so it no longer sends. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [EDIT_WINDOW_EXPIRED](#EDIT_WINDOW_EXPIRED) 422 Social The post can no longer be edited. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [EMAIL_CONTENT_CONFLICT](#EMAIL_CONTENT_CONFLICT) 400 Mail Send either html/text or a template, not both, and at least one of them. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [EMAIL_NOT_FOUND](#EMAIL_NOT_FOUND) 404 Mail Email not found in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [EMAIL_NOT_VERIFIED](#EMAIL_NOT_VERIFIED) 403 Platform Verify the account email first. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [EMAIL_UNAVAILABLE](#EMAIL_UNAVAILABLE) 503 Mail Emailing share links is temporarily unavailable. Create the link without email_to and send it yourself. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [ENVIRONMENT_NOT_FOUND](#ENVIRONMENT_NOT_FOUND) 404 Flags The environment does not exist in this project. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [ENVOI_APP_NOT_BOUND_TO_WORKSPACE](#ENVOI_APP_NOT_BOUND_TO_WORKSPACE) 412 Auth The app is not linked to a workspace, so it cannot send through Mail. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [ENVOI_NOT_ENABLED](#ENVOI_NOT_ENABLED) varies Auth Mail is not enabled for the app's workspace. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ENVOI_NOT_WIRED](#ENVOI_NOT_WIRED) varies Auth Mail client not wired in this deployment. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ENVOI_SENDER_NOT_CONFIGURED](#ENVOI_SENDER_NOT_CONFIGURED) 412 Auth No sender address is set for this notification. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [ENVOI_TEMPLATE_NOT_CONFIGURED](#ENVOI_TEMPLATE_NOT_CONFIGURED) 412 Auth No Mail template is set for this notification. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [EVALUATION_BUDGET_EXCEEDED](#EVALUATION_BUDGET_EXCEEDED) 422 Flags The test evaluation ran over its time budget. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [FEATURE_NOT_ENABLED](#FEATURE_NOT_ENABLED) 403 Auth Custom domains are not available for this workspace yet. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [FROM_DOMAIN_MISMATCH](#FROM_DOMAIN_MISMATCH) 422 Mail The From address is not at this domain. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [from_domain_not_verified](#from_domain_not_verified) 422 Mail · Waitlist The From domain is not an active sending domain of this workspace (details: { fqdn, reason }). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [HOSTNAME_RESERVED](#HOSTNAME_RESERVED) 400 Auth That host name is reserved and cannot be used. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [HOSTNAME_TAKEN](#HOSTNAME_TAKEN) 409 Auth That host name is already used by another app. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [IDEMPOTENCY_KEY_CONFLICTS_WITH_ROW](#IDEMPOTENCY_KEY_CONFLICTS_WITH_ROW) 400 Mail An idempotency_key on a batch row conflicts with the request key. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [idempotency_secret_not_replayable](#idempotency_secret_not_replayable) 409 Auth A repeat of a key-creating request: the secret is never replayed (details.key_id). What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [IMPORT_CREDENTIALS_INVALID](#IMPORT_CREDENTIALS_INVALID) 422 Flags ConfigCat rejected the import credentials. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [IMPORT_EXCEEDS_LIMITS](#IMPORT_EXCEEDS_LIMITS) 422 Flags The ConfigCat product is larger than the Flags workspace limits. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [IMPORT_IN_PROGRESS](#IMPORT_IN_PROGRESS) 409 Mail Another contact import is running for this workspace. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [IMPORT_NOT_FOUND](#IMPORT_NOT_FOUND) 404 Mail Import not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [IMPORT_SOURCE_NOT_FOUND](#IMPORT_SOURCE_NOT_FOUND) 404 Flags The ConfigCat product does not exist or the credentials cannot see it. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [IMPORT_SOURCE_UNAVAILABLE](#IMPORT_SOURCE_UNAVAILABLE) 502 Flags The ConfigCat API could not be reached. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [IMPORT_TOO_LARGE](#IMPORT_TOO_LARGE) 413 Mail The import file is over the size limit. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [IMPORT_UNSUPPORTED](#IMPORT_UNSUPPORTED) 422 Flags The ConfigCat product uses features Flags cannot import; see details.items. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [INBOX_ITEM_NOT_FOUND](#INBOX_ITEM_NOT_FOUND) 404 Notify The recipient has no inbox item with this id (or the sender retracted it). What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [INSUFFICIENT_PERMISSIONS](#INSUFFICIENT_PERMISSIONS) varies Auth The token does not grant the permission this route needs. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_CAPABILITIES](#INVALID_CAPABILITIES) 400 Mail At least one capability (sending or receiving) must be enabled. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [INVALID_CONTACT_PROPERTY_VALUE](#INVALID_CONTACT_PROPERTY_VALUE) 422 Mail A contact property value does not match the property type. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [INVALID_CSV](#INVALID_CSV) 422 Mail The first line must be a header with an "email" column. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [INVALID_CURSOR](#INVALID_CURSOR) 400 Social The cursor is invalid; restart from the first page. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [INVALID_DATE](#INVALID_DATE) varies Mail A date is not valid ISO 8601. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_DATE_FILTER](#INVALID_DATE_FILTER) varies Social A date filter is not valid ISO 8601. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_DATE_RANGE](#INVALID_DATE_RANGE) varies Mail The date range is invalid (start after end). What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_DATE_WINDOW](#INVALID_DATE_WINDOW) varies Mail The date window is invalid. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_EXPAND](#INVALID_EXPAND) 400 Social Unsupported expand value. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [INVALID_FORMAT](#INVALID_FORMAT) 400 Auth · Mail A path or query value is not in the expected format. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [INVALID_FROM_ADDRESS](#INVALID_FROM_ADDRESS) 422 Mail The From address could not be parsed. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [INVALID_HOSTNAME](#INVALID_HOSTNAME) 400 Auth The host name is not valid; use a name such as auth.example.com. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [INVALID_ID_LIST](#INVALID_ID_LIST) 400 Social An id list is malformed. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [INVALID_IDENTIFIER](#INVALID_IDENTIFIER) varies Auth · Social An id in the path or query is not a valid UUID. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_NOTIFICATION_KIND](#INVALID_NOTIFICATION_KIND) varies Social Unknown notification kind. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_ORDER](#INVALID_ORDER) varies Social The order value is not supported. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_PROVIDER](#INVALID_PROVIDER) varies Auth Unsupported DNS provider. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_SEARCH_QUERY](#INVALID_SEARCH_QUERY) varies Social The search query is invalid. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_SEGMENT_RULE](#INVALID_SEGMENT_RULE) 422 Mail The segment rule is invalid (details.problems). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [INVALID_TARGETING](#INVALID_TARGETING) 422 Flags The targeting rules are not valid. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [INVALID_TIMEZONE](#INVALID_TIMEZONE) varies Mail The time zone is not a valid IANA name. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [INVALID_VALUE](#INVALID_VALUE) 422 Flags The value does not match the setting's type or exceeds its size limit. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [INVALID_ZONE](#INVALID_ZONE) 400 Auth · Mail The DNS zone is not one this domain belongs to. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [INVITE_EMAIL_MISMATCH](#INVITE_EMAIL_MISMATCH) 403 Platform The invite was sent to a different email address. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [INVITE_EXHAUSTED](#INVITE_EXHAUSTED) 410 Platform Invite exhausted. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [INVITE_EXPIRED](#INVITE_EXPIRED) 410 Platform Invite expired. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [INVITE_INVALID](#INVITE_INVALID) 404 Platform Invite invalid. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [INVITE_NOT_FOUND](#INVITE_NOT_FOUND) 404 Platform Invite not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [INVITE_REVOKED](#INVITE_REVOKED) 410 Platform Invite revoked. What to do: Read message and errors[] for the detail, then fix the request. (APIError) [KEY_ALREADY_EXISTS](#KEY_ALREADY_EXISTS) 409 Flags Another resource in the same scope already uses this key. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [LAST_ENVIRONMENT](#LAST_ENVIRONMENT) 409 Flags A project needs at least one environment; this is the last one. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [LAST_MEMBER](#LAST_MEMBER) 409 Platform The workspace's last member cannot leave; delete the workspace instead. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [LIMIT_EXCEEDED](#LIMIT_EXCEEDED) 422 Flags · Notify The workspace has reached a Flags limit. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [link_required](#link_required) 409 Auth An account with this email exists; confirm the link to sign in with this provider. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [MAIL_FROM_HOST_IN_USE](#MAIL_FROM_HOST_IN_USE) 409 Mail The MAIL FROM host already has records that are not ours (details.found). What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [MAIL_FROM_NOT_SENDING](#MAIL_FROM_NOT_SENDING) 400 Mail A custom MAIL FROM needs the domain to send. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [MAIL_HEADER_NOT_ALLOWED](#MAIL_HEADER_NOT_ALLOWED) 400 Mail A custom header is not allowed, or its value is invalid (details.headers). What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [MAIL_UNREACHABLE](#MAIL_UNREACHABLE) 503 Auth · Waitlist The Mail service did not answer; try again in a minute. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [MANAGEMENT_UNAVAILABLE](#MANAGEMENT_UNAVAILABLE) 503 Flags The management API is temporarily unavailable; SDK config delivery keeps serving. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [MEMBER_RANK_EXCEEDED](#MEMBER_RANK_EXCEEDED) 403 Platform You cannot manage a member whose role ranks above yours. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [no_default_sender](#no_default_sender) 422 Mail · Waitlist No from and the workspace has no default sender. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [NOT_A_MEMBER](#NOT_A_MEMBER) 403, 404 Platform The caller is not a member of this workspace. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [NOTE_REQUIRED](#NOTE_REQUIRED) 422 Flags This environment requires a change note. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [NOTHING_TO_RESTORE](#NOTHING_TO_RESTORE) 422 Flags The entity already matches the version before this change. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [NOTIFICATION_NOT_FOUND](#NOTIFICATION_NOT_FOUND) 404 Notify No notification with this id in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [NOTIFICATION_TYPE_ARCHIVED](#NOTIFICATION_TYPE_ARCHIVED) 422 Notify The notification type is archived and cannot be sent. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [NOTIFICATION_TYPE_KEY_TAKEN](#NOTIFICATION_TYPE_KEY_TAKEN) 409 Notify A notification type with this key already exists in the workspace. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [NOTIFICATION_TYPE_NOT_FOUND](#NOTIFICATION_TYPE_NOT_FOUND) 404, 422 Notify No notification type with this id or key in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [OAUTH_GRANT_ADMIN_REVOKED](#OAUTH_GRANT_ADMIN_REVOKED) 403 Platform An admin revoked this OAuth grant. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [ORIGIN_NOT_ALLOWED](#ORIGIN_NOT_ALLOWED) 403 Waitlist · Notify Origin not allowed. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [OWNER_NOT_A_MEMBER](#OWNER_NOT_A_MEMBER) 422 Flags The owner_id is not a member of this workspace, or membership could not be checked with this credential. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [OWNER_ROLE_REQUIRED](#OWNER_ROLE_REQUIRED) 403 Platform Only an owner can do this. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [PAK_ALREADY_MINTED](#PAK_ALREADY_MINTED) 409 Platform This Idempotency-Key already minted an API key; its token is shown once. Rotate that key (its id is in details) for a new token. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [PAK_EXPIRED](#PAK_EXPIRED) 409 Platform Pak expired. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [PAK_NAME_REQUIRED](#PAK_NAME_REQUIRED) 400 Platform An API key needs a name. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [PAK_NAME_TOO_LONG](#PAK_NAME_TOO_LONG) 400 Platform The API key name is too long. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [PAK_NOT_FOUND](#PAK_NOT_FOUND) 404 Platform Pak not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [PAK_REVOKED](#PAK_REVOKED) 409 Platform Pak revoked. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [PAK_WORKSPACE_MISMATCH](#PAK_WORKSPACE_MISMATCH) 403 Auth The workspace API key belongs to a different workspace. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [PASSWORD_BREACHED](#PASSWORD_BREACHED) 400 Auth This password has appeared in a known data breach — pick a different one. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [PASSWORD_RESET_INVALID](#PASSWORD_RESET_INVALID) 400 Platform The password reset code is invalid or expired. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [PASSWORD_TOO_COMMON](#PASSWORD_TOO_COMMON) 400 Auth Password is too common — pick something less guessable. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [PERCENTAGES_MUST_SUM_TO_100](#PERCENTAGES_MUST_SUM_TO_100) 422 Flags The percentage options must add up to 100. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [PIN_CAP_REACHED](#PIN_CAP_REACHED) 409 Social The post has the maximum number of pinned comments. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [POLICY_INVALID](#POLICY_INVALID) 400 Platform The policy document is invalid. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [POLICY_NAME_TAKEN](#POLICY_NAME_TAKEN) 409 Platform Policy name taken. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [POLICY_NOT_FOUND](#POLICY_NOT_FOUND) 404 Platform Policy not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [POLL_CLOSED](#POLL_CLOSED) 422 Social This poll is closed. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [PREFERENCE_LOCKED](#PREFERENCE_LOCKED) 422 Notify The channel is mandatory for this category and cannot be turned off. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [PREREQUISITE_NOT_FOUND](#PREREQUISITE_NOT_FOUND) 422 Flags The prerequisite setting does not exist in this config. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [PREREQUISITE_TYPE_MISMATCH](#PREREQUISITE_TYPE_MISMATCH) 422 Flags The comparison value does not match the prerequisite setting's type. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [PROJECT_NOT_FOUND](#PROJECT_NOT_FOUND) 404 Flags The project does not exist in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [PROVIDER_ERROR](#PROVIDER_ERROR) 502 Auth · Mail The DNS provider returned an error. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [PROVIDER_PERMISSION_DENIED](#PROVIDER_PERMISSION_DENIED) 400 Auth · Mail The DNS provider token lacks permission to edit this zone. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [PROVIDER_TOKEN_REJECTED](#PROVIDER_TOKEN_REJECTED) 400 Auth · Mail The DNS provider rejected the token. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [PROVIDER_UNAVAILABLE](#PROVIDER_UNAVAILABLE) 502 Auth · Mail The DNS provider is unavailable; try again later. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [PROVIDER_ZONE_NOT_FOUND](#PROVIDER_ZONE_NOT_FOUND) 400 Auth · Mail The DNS provider has no zone for this domain. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [QUOTE_NOT_ALLOWED](#QUOTE_NOT_ALLOWED) varies Social The author has disabled quoting this post. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [QUOTE_REQUIRES_BODY](#QUOTE_REQUIRES_BODY) varies Social A quote post needs a body. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [QUOTE_REQUIRES_SOURCE](#QUOTE_REQUIRES_SOURCE) varies Social A quote post needs source_post_id. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [RECIPIENT_ERASED](#RECIPIENT_ERASED) 409 Notify The recipient was erased in the last 24 hours (its linked Auth user was deleted) and cannot be recreated yet. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [RECIPIENT_LIMIT](#RECIPIENT_LIMIT) 400 Mail More than 50 recipients across to, cc and bcc. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [RECIPIENT_NOT_FOUND](#RECIPIENT_NOT_FOUND) 404, 422 Notify No recipient with this external id in this workspace (on a send: none of the recipients is usable). What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [RECIPIENT_SUPPRESSED](#RECIPIENT_SUPPRESSED) 422 Mail The recipient is suppressed for this workspace or topic (details.reason). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [RECIPIENT_TOKEN_EXPIRED](#RECIPIENT_TOKEN_EXPIRED) 401 Notify The recipient token has expired; mint a new one from your backend. What to do: Send a valid, unexpired API key or token, or sign in again. (AuthenticationError) [RECIPIENT_TOKEN_INVALID](#RECIPIENT_TOKEN_INVALID) 401 Notify The recipient token is malformed, has a bad signature or was revoked. What to do: Send a valid, unexpired API key or token, or sign in again. (AuthenticationError) [RECIPIENT_TOKEN_SCOPE](#RECIPIENT_TOKEN_SCOPE) 403 Notify The recipient token does not allow this operation. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [REGION_NOT_AVAILABLE](#REGION_NOT_AVAILABLE) 422 Mail region is not the region this deployment sends from (details.available). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [REPOST_NOT_ALLOWED](#REPOST_NOT_ALLOWED) varies Social The author has disabled reposting this post. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [RESERVED_PROPERTY_KEY](#RESERVED_PROPERTY_KEY) 422 Mail The property key is reserved. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [REVERT_NOT_SUPPORTED](#REVERT_NOT_SUPPORTED) 422 Flags This kind of change cannot be restored. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [REVISION_NOT_FOUND](#REVISION_NOT_FOUND) 404 Flags The config revision does not exist for this environment. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [ROLE_HAS_MEMBERS](#ROLE_HAS_MEMBERS) 409 Platform The role still has members; move them first. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [ROLE_IN_USE](#ROLE_IN_USE) varies Auth Role is in use. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [ROLE_NAME_TAKEN](#ROLE_NAME_TAKEN) 409 Platform Role name taken. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [ROLE_NOT_FOUND](#ROLE_NOT_FOUND) 404 Platform Role not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [ROLE_SYSTEM_IMMUTABLE](#ROLE_SYSTEM_IMMUTABLE) 409 Platform System roles (owner, admin, member) cannot be changed or deleted. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [SDK_KEY_NOT_FOUND](#SDK_KEY_NOT_FOUND) 404 Flags The SDK key is unknown, revoked or expired. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [SEGMENT_EXISTS](#SEGMENT_EXISTS) 409 Mail A segment with this name already exists. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [SEGMENT_IN_USE](#SEGMENT_IN_USE) 409 Flags A targeting rule uses this segment. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [SEGMENT_LIMIT](#SEGMENT_LIMIT) 409 Mail The workspace has the maximum number of segments. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [SEGMENT_NOT_FOUND](#SEGMENT_NOT_FOUND) 404, 422 Mail · Flags Segment not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [SEGMENT_RULE_BASED](#SEGMENT_RULE_BASED) 422 Mail Members of a rule segment follow its rule: change the contact or the rule instead. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [SEGMENT_TYPE_FIXED](#SEGMENT_TYPE_FIXED) 422 Mail A static segment cannot take a rule: create a rule segment instead. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [SEND_AT_OUT_OF_RANGE](#SEND_AT_OUT_OF_RANGE) 422 Notify send_at or delay_seconds is in the past or beyond the type TTL. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [SENDER_ADDRESS_REQUIRED](#SENDER_ADDRESS_REQUIRED) 422 Auth A sender address is required for these notification settings. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [sender_domain_not_in_workspace](#sender_domain_not_in_workspace) 422 Mail The address is not on a sending domain of this workspace (details.fqdn). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [SERVICE_NOT_ACTIVATED](#SERVICE_NOT_ACTIVATED) 404 Platform The product is not activated for this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [SERVICE_UNKNOWN](#SERVICE_UNKNOWN) 400 Platform No product with this name. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [SES_IDENTITY_DELETE_FAILED](#SES_IDENTITY_DELETE_FAILED) 503 Mail The sending identity could not be removed from the email provider; retry. What to do: Retry with backoff (the SDK does); quote request_id if it persists. (InternalServerError) [SESSION_EXPIRED](#SESSION_EXPIRED) varies Auth Session expired. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [SETTING_IN_USE](#SETTING_IN_USE) 409 Flags Another setting uses this one as a prerequisite. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [SETTING_NOT_FOUND](#SETTING_NOT_FOUND) 404 Flags The feature flag or setting does not exist in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [SETTING_TYPE_IMMUTABLE](#SETTING_TYPE_IMMUTABLE) 422 Flags A setting's type cannot change; create a new setting instead. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [SHARE_LINK_NOT_FOUND](#SHARE_LINK_NOT_FOUND) 404 Mail This setup link does not exist, has expired or was revoked. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [SIGN_IN_TEST_INVALID](#SIGN_IN_TEST_INVALID) varies Auth This sign-in test link is unknown, already used or expired. Start a new test from the console. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [SLUG_TAKEN](#SLUG_TAKEN) varies Auth The clone needs a slug of its own. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [SLUG_UUID_SHAPED](#SLUG_UUID_SHAPED) varies Auth A slug cannot look like a UUID. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [SMTP_AUTH_PARTIAL](#SMTP_AUTH_PARTIAL) varies Mail SMTP username and password must be set together. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [SMTP_CONFIG_NOT_FOUND](#SMTP_CONFIG_NOT_FOUND) varies Mail No SMTP override saved for this domain. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [SMTP_PASSWORD_REQUIRED](#SMTP_PASSWORD_REQUIRED) varies Mail An SMTP password is required. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [SOLE_OWNER](#SOLE_OWNER) 409 Platform The workspace's only owner cannot leave or be removed; transfer ownership first. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [SOURCE_POST_ID_REQUIRES_QUOTE](#SOURCE_POST_ID_REQUIRES_QUOTE) varies Social source_post_id is only valid on a quote post. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [step_up_required](#step_up_required) 403 Auth Recent MFA is required; verify a factor and retry (details.max_age_minutes). What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [STREAM_LIMIT](#STREAM_LIMIT) 429 Notify The recipient has the maximum number of open real-time streams. What to do: Wait Retry-After seconds. The SDK retries this for you. (RateLimitError) [TEMPLATE_DATA_INVALID](#TEMPLATE_DATA_INVALID) 422 Mail The render data does not match the template schema. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [TEMPLATE_INVALID](#TEMPLATE_INVALID) 422 Notify The template does not parse, uses an unsupported construct or has an invalid field. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [TEMPLATE_KIND_NOT_SENDABLE](#TEMPLATE_KIND_NOT_SENDABLE) varies Mail This template kind (a partial or layout) cannot be sent on its own. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [TEMPLATE_MISSING](#TEMPLATE_MISSING) 422 Notify The notification type has no template for any of the requested channels. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [TEMPLATE_NOT_FOUND](#TEMPLATE_NOT_FOUND) 404 Mail · Notify No template with this name in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [TEMPLATE_RENDER_FAILED](#TEMPLATE_RENDER_FAILED) 422 Mail The template could not be rendered. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [TEMPLATE_VERSION_NOT_FOUND](#TEMPLATE_VERSION_NOT_FOUND) 404 Notify That version of the template is not kept (the last 20 are). What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [TENANT_API_KEY_EXPIRY_INVALID](#TENANT_API_KEY_EXPIRY_INVALID) 400 Auth The requested expiry is not one of the allowed values (details.allowed). What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TENANT_API_KEY_LIMIT](#TENANT_API_KEY_LIMIT) 409 Auth The tenant has the maximum number of active API keys (25); revoke one first. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [TENANT_API_KEY_NOT_ACTIVE](#TENANT_API_KEY_NOT_ACTIVE) 409 Auth Only an active key can be rotated. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [TENANT_API_KEY_NOT_FOUND](#TENANT_API_KEY_NOT_FOUND) 404 Auth API key not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [TENANT_API_KEY_SCOPE_ABOVE_CEILING](#TENANT_API_KEY_SCOPE_ABOVE_CEILING) 403 Auth You cannot rotate a key whose scopes your own tenant role does not hold. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TENANT_API_KEY_SCOPE_NOT_GRANTABLE](#TENANT_API_KEY_SCOPE_NOT_GRANTABLE) 400, 409 Auth Some scopes are not offered by this app. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TENANT_API_KEYS_APP_PROXY_ONLY](#TENANT_API_KEYS_APP_PROXY_ONLY) 403 Auth Tenant API keys for this app are managed through the app, not directly. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TENANT_API_KEYS_FORBIDDEN](#TENANT_API_KEYS_FORBIDDEN) 403 Auth Your tenant role cannot manage API keys. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TENANT_API_KEYS_NO_SCOPES](#TENANT_API_KEYS_NO_SCOPES) 400 Auth Enabling tenant API keys needs at least one grantable scope. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TENANT_API_KEYS_NOT_ENABLED](#TENANT_API_KEYS_NOT_ENABLED) 403 Auth Tenant API keys are not enabled for this app. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TENANT_API_KEYS_SCOPE_INVALID](#TENANT_API_KEYS_SCOPE_INVALID) 400 Auth A scope name is malformed; scopes look like orders.read (details.scopes). What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TENANT_API_KEYS_SUSPENDED](#TENANT_API_KEYS_SUSPENDED) 403 Auth Tenant API keys are suspended for this app. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TENANT_API_KEYS_SUSPENDED_NOT_WRITABLE](#TENANT_API_KEYS_SUSPENDED_NOT_WRITABLE) 400 Auth Tenant API keys are suspended for this app; only suspended can be changed. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TENANT_API_KEYS_UNKNOWN_ROLE](#TENANT_API_KEYS_UNKNOWN_ROLE) 400 Auth manage_roles names a role this app does not have (details.roles). What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TENANT_CONTEXT_REQUIRED](#TENANT_CONTEXT_REQUIRED) 403 Auth No active tenant on this session. Switch to a tenant first (POST /auth/switch-tenant). What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TENANT_MEMBERSHIP_REQUIRED](#TENANT_MEMBERSHIP_REQUIRED) 403 Auth You are not a member of the active tenant. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TENANT_NOT_ACTIVE](#TENANT_NOT_ACTIVE) 403 Auth The active tenant is not active. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) [TLS_ENFORCED_NOT_AVAILABLE](#TLS_ENFORCED_NOT_AVAILABLE) 422 Mail tls: enforced is not available yet. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [TOKEN_EXPIRED](#TOKEN_EXPIRED) varies Auth Token expired. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [TOKEN_INVALID](#TOKEN_INVALID) varies Auth Token invalid. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [TOKEN_REVOKED](#TOKEN_REVOKED) varies Auth Token revoked. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [TOO_MANY_ACTIVE_JOBS](#TOO_MANY_ACTIVE_JOBS) 429 Trawl The workspace has the maximum number of active jobs; wait or cancel some. What to do: Wait Retry-After seconds. The SDK retries this for you. (RateLimitError) [TOO_MANY_ACTIVE_UPLOADS](#TOO_MANY_ACTIVE_UPLOADS) 429 Social The community has the maximum number of videos uploading or processing. What to do: Wait Retry-After seconds. The SDK retries this for you. (RateLimitError) [TOO_MANY_ATTACHMENTS](#TOO_MANY_ATTACHMENTS) varies Social The post has too many attachments. What to do: Read message and errors[] for the detail. Quote request_id if you contact support. (APIError) [TOO_MANY_ATTEMPTS](#TOO_MANY_ATTEMPTS) 429 Platform Too many attempts; wait before trying again. What to do: Wait Retry-After seconds. The SDK retries this for you. (RateLimitError) [TOO_MANY_IDS](#TOO_MANY_IDS) 400 Social Too many ids in one request. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TOO_MANY_RECIPIENTS](#TOO_MANY_RECIPIENTS) 400 Notify The request names more recipients than one call accepts. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [TOPIC_EXISTS](#TOPIC_EXISTS) 409 Mail A topic with this name already exists. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [TOPIC_LIMIT](#TOPIC_LIMIT) 409 Mail The workspace has the maximum number of topics. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [TOPIC_NOT_FOUND](#TOPIC_NOT_FOUND) 404, 422 Mail Topic not found. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [TRACKING_NOT_AVAILABLE](#TRACKING_NOT_AVAILABLE) 422 Mail Open and click tracking are not available yet. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [TRAWL_CREDITS_EXHAUSTED](#TRAWL_CREDITS_EXHAUSTED) 402 Trawl The workspace has no Trawl credits left. What to do: Add credit or upgrade the plan, then retry. (APIError) [UNKNOWN_CONTACT_PROPERTY](#UNKNOWN_CONTACT_PROPERTY) 422 Mail The contact property is not defined; create it first. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [UNSAFE_URL](#UNSAFE_URL) 422 Notify A URL field does not use https (http is accepted only for localhost). What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [UNSUBSCRIBE_LINK_REQUIRED](#UNSUBSCRIBE_LINK_REQUIRED) 422 Mail A broadcast body must contain {{{unsubscribe_url}}}. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [USERNAME_TAKEN](#USERNAME_TAKEN) 409 Auth Username already in use. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [VERSION_CONFLICT](#VERSION_CONFLICT) 409 Flags The resource changed since you read it; reload and apply your change again. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [WAITLIST_NOT_FOUND](#WAITLIST_NOT_FOUND) 404 Waitlist No waitlist with this id or slug in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [WEBHOOK_ENDPOINT_LIMIT](#WEBHOOK_ENDPOINT_LIMIT) 409 Auth · Mail · Waitlist · Social · Trawl · Flags · Notify The workspace has the maximum number of webhook endpoints. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [WEBHOOK_ENDPOINT_NOT_FOUND](#WEBHOOK_ENDPOINT_NOT_FOUND) 404 Auth · Mail · Waitlist · Social · Trawl · Flags · Notify No webhook endpoint with this id in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [WEBHOOK_ENDPOINT_NOT_SUBSCRIBED](#WEBHOOK_ENDPOINT_NOT_SUBSCRIBED) 409 Auth · Mail · Waitlist · Social · Trawl · Flags · Notify The endpoint is not subscribed to this event type. What to do: Re-read the current state and decide; IDEMPOTENCY_IN_PROGRESS is retried by the SDK. (ConflictError) [WEBHOOK_EVENT_NOT_FOUND](#WEBHOOK_EVENT_NOT_FOUND) 404 Auth · Mail · Waitlist · Social · Trawl · Flags · Notify No webhook event with this id in this workspace. What to do: Check the id and that it belongs to this workspace or app. (NotFoundError) [WEBHOOK_EVENT_TYPE_UNKNOWN](#WEBHOOK_EVENT_TYPE_UNKNOWN) 400 Auth · Mail · Waitlist · Social · Trawl · Flags · Notify The event type is not one this product sends. What to do: Fix the request: errors[] names each field. Do not retry it unchanged. (BadRequestError) [WEBPUSH_ENDPOINT_NOT_ALLOWED](#WEBPUSH_ENDPOINT_NOT_ALLOWED) 422 Notify The web push subscription endpoint is not a known push service. What to do: The request is valid but not allowed in this state. Change the state or the request. (UnprocessableEntityError) [WORKSPACE_KEY_REQUIRED](#WORKSPACE_KEY_REQUIRED) 403 Platform This route needs a workspace API key. What to do: Grant the action to the key or role, or enable the product on the workspace. (PermissionDeniedError) 332 codes from 8 APIs. Statuses come from the responses each code is documented on; “varies” means the specs do not tie it to one status yet. --- title: "Platform API Documentation" description: "Programmatic access to workspace setup, members, roles, service activation, and audit. For CI/CD, infrastructure-as-code, and admin automation that lives outside the console UI." url: https://productcraft.co/docs/platform --- Platform docs # Platform API. The administrative surface that powers the console. Hit it directly when you need automation, infrastructure-as-code, or CI/CD-driven workspace management. Everything the ProductCraft console does — creating a workspace, inviting a member, activating Mail or Waitlist, rotating an API key, reading the audit log — is a call against the Platform API. Humans get a friendly UI; your CI/CD pipeline gets the same surface via a workspace API key. Browse ## What you’ll find here - [Getting started](https://productcraft.co/docs/platform/getting-started.md): Mint a workspace API key, hit your first endpoint, and understand the workspace boundary. Five minutes to a working CI/CD integration.Read more → - [Guides](https://productcraft.co/docs/platform/guides.md): Workspaces, members + roles, service activation, API keys for CI/CD, audit + compliance. The run-your-workspace-at-scale series.Read more → - [Webhooks](https://productcraft.co/docs/platform/webhooks.md): How Mail, Auth, Waitlist, Trawl and Social send webhooks: verifying Standard Webhooks signatures in Node, Send test, retries, auto-disable, replay, secret rotation and the older headers’ sunset.Read more → - [API reference](https://productcraft.co/docs/platform/api-reference.md): Every endpoint generated from the live OpenAPI spec. Workspaces, members, roles, policies, services, API keys, audit, introspection — everything the console can do is here.Read more → Reference ## Base URL ``` https://api.platform-auth.productcraft.co/v1 ``` All Platform API endpoints are relative to this base. Browser sessions use the `auth_token` cookie on `.productcraft.co`; programmatic clients send `Authorization: Bearer pcft_live_…`. When to use this ## Console UI vs Platform API The right surface depends on the actor: - **Humans** — use the [console](https://console.productcraft.co). Faster for one-off changes, and the same workspace-role policy gates every action. - **CI/CD** — mint an API key bound to policies covering exactly the actions your pipeline needs. Provision an Auth app per deploy, rotate keys, all from a workflow file. - **Infrastructure-as-code** — Terraform, Pulumi, or any tool that calls REST. The key's bound policies are the cap on what the tool can do. - **Admin automation** — auditing, compliance exports, periodic permission reviews. Read-only keys make this safe. What this is **not**: the Platform API never authenticates your end-users. End-user identity lives on [Auth](https://productcraft.co/docs/auth.md). The Platform API is your workspace + your team — it has no concept of your customers’ users. [Start with the getting-started guide](https://productcraft.co/docs/platform/getting-started.md) --- title: "Platform API — Getting started" description: "Mint a workspace API key, hit your first endpoint, and automate workspace setup. Five-minute walkthrough." url: https://productcraft.co/docs/platform/getting-started --- [Platform docs](https://productcraft.co/docs/platform.md) Getting started # Your first Platform API call. Five minutes. From the console to a working CI/CD integration. Step 1 ## Sign in + pick a workspace Open [auth.productcraft.co](https://auth.productcraft.co/signin). If you don't have a ProductCraft account yet, sign up — every product on this platform shares the same account. Once signed in, create a workspace or open an existing one. The workspace is the boundary for everything you can do programmatically — its domains, mailboxes, Auth apps, Waitlist waitlists, members, roles, and audit log. Your role on the workspace caps what any API key you mint can do: the minter can never grant more than their own effective permissions. Minting requires `workspace.apikey.create` — owners and admins have it by default; members don't. Step 2 ## Mint a workspace API key In the console, open your workspace's API keys page and click New API key. Name it, bind one or more policies, and copy the token — it's only shown once. Policies are authored on the Policies page (owners and admins); each one is a list of allow/deny statements. ```json title="example policy statement (read-only audit)" [ { "effect": "allow", "actions": ["workspace.audit.read", "workspace.member.read"], "resources": ["*"] } ] ``` The token shape is `pcft_live_`. Treat it like a password — store it in your CI secret store, never commit it. Keys never expire automatically; revoke them when the use case ends. Only a signed-in human can mint — a key cannot mint other keys. Step 3 ## Verify the token The /v1/introspect endpoint identifies your bearer. Use it as a one-call check that the token is live and bound to the workspace you expect. ```bash title="curl" curl https://api.platform-auth.productcraft.co/v1/introspect \ -H "Authorization: Bearer pcft_live_..." ``` A 200 confirms the token works: the body shows the principal (`"type": "pak"`) and the workspace the key belongs to, with its enabled services. A 401 means the token is invalid, revoked, or malformed. Step 4 ## Provision an Auth app from CI The canonical CI/CD use case: your deploy pipeline needs an Auth app for the environment it's building. The Platform API lets that happen without a human in the loop. ```bash title="provision script" #!/usr/bin/env bash set -euo pipefail KEY="${PRODUCTCRAFT_API_KEY}" # pcft_live_... WS_ID="${WORKSPACE_ID}" # workspace UUID # 1. Create the Auth app (needs auth.create on the workspace) APP=$(curl -fsS -X POST https://api.auth.productcraft.co/v1/apps \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d "{\"slug\":\"acme-staging\",\"display_name\":\"Acme (staging)\",\"workspace_id\":\"$WS_ID\"}") APP_ID=$(echo "$APP" | jq -r .id) # 2. Mint the new Auth app's own API key (hdk_live_..., not a workspace key) for the running service APP_KEY=$(curl -fsS -X POST https://api.auth.productcraft.co/v1/apps/$APP_ID/api-keys \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{"name":"staging-service","permissions":["user.read","user.list"]}') echo "$APP_KEY" | jq -r .key > /etc/secrets/auth-api-key ``` Both endpoints accept an optional `Idempotency-Key` header — set one in CI so a retried job doesn't create a duplicate app or a second key whose plaintext nobody saw. The same workspace API key works against every backend that respects workspace-scoped policy — Auth-admin, Mail, Waitlist, Social, Trawl. Each service introspects the bearer against the Platform API server-side and enforces the key's bound policy. You don't need a separate token per service. Step 5 ## Tighten the policy The default examples above grant broad scopes for brevity. In production, narrow each workspace API key to exactly what the pipeline needs — see the per-service action list in the API reference. A few patterns worth copying: - **One key per pipeline.** Don't reuse a token across a deploy bot and a compliance exporter — the least-privilege blast radius is bigger than it needs to be. - **Resource URN narrows.** Where the action applies to a per-resource URN (e.g. `pcft:heimdall:app/`), bind the policy statement to that URN — not `*`. - **Review key activity.** Each key's last-used timestamp shows on the API keys page, and administrative actions land in the workspace audit log with the actor recorded. Unused keys are obvious from the activity gap — revoke them. Next ## Browse the full reference Every endpoint is documented at /docs/platform/api-reference, generated from the live OpenAPI spec. Common starting points: /v1/workspaces, /v1/workspaces/:slug/members, /v1/workspaces/:slug/services, /v1/workspaces/:slug/audit-logs. For end-user identity in your customer-facing product, you're looking at the wrong page — [Auth's docs](https://productcraft.co/docs/auth.md) cover signup, signin, per-app JWKS, tenants, M2M, and the Consumer API for external customers. --- title: "Guides | Platform Docs" description: "Comprehensive guides for the Platform API: workspaces, members + roles, service activation, workspace API keys for CI/CD, audit + compliance." url: https://productcraft.co/docs/platform/guides --- [Platform docs](https://productcraft.co/docs/platform.md) Guides # Run your workspace at scale. Five chapters covering the administrative surface that sits underneath every other ProductCraft service. Read these when your workspace setup grows past 'one team in the console' — multiple environments, CI/CD-driven provisioning, compliance asks. Chapters ## The series - [01 · Workspaces](https://productcraft.co/docs/platform/guides/01-workspaces.md): The boundary primitive — what a workspace is, when to create more than one, billing implications.Read more → - [02 · Members + roles](https://productcraft.co/docs/platform/guides/02-members-and-roles.md): Invite teammates, the system role defaults, custom roles, the IAM-style policy model, sole-owner invariants.Read more → - [03 · Service activation](https://productcraft.co/docs/platform/guides/03-service-activation.md): Turning Auth / Mail / Waitlist / Social on for a workspace. Settings + the SERVICE_NOT_ENABLED gate.Read more → - [04 · Workspace API keys for CI/CD](https://productcraft.co/docs/platform/guides/04-pats-for-cicd.md): Mint a workspace API key, scope it tightly, rotate, audit usage. The right way to give a pipeline workspace access.Read more → - [05 · Audit + compliance](https://productcraft.co/docs/platform/guides/05-audit-and-compliance.md): What the workspace audit log captures, querying, exporting for SOC2 / GDPR.Read more → - [Webhooks, in every product](https://productcraft.co/docs/platform/webhooks.md): Verify Standard Webhooks signatures, Send test, retries, auto-disable, replay, secret rotation, and the older headers with their sunset dates.Read more → --- title: "01 · Workspaces | Platform Guides" description: "The workspace primitive: boundary, lifecycle, multi-environment patterns." url: https://productcraft.co/docs/platform/guides/01-workspaces --- [Platform guides](https://productcraft.co/docs/platform/guides.md) 01 · Workspaces # The workspace is the boundary. One workspace = one team's data, one team's settings, one team's billing. Everything ProductCraft owns is keyed by workspace_id. Get the boundary right and the rest follows. 1 ## What a workspace owns Inside one workspace: - **Members** with roles (Chapter 2). - **Service activations** — Auth apps, Mail domains + templates, Waitlist waitlists, Social communities (Chapter 3). - **Workspace API keys** for CI/CD access (Chapter 4). - **Audit log** recording every member + role + service mutation (Chapter 5). Two workspaces are **fully isolated** — no shared service data, no shared roles, no shared audit, no shared policies. One platform account can belong to many workspaces (the console surfaces a switcher); membership and permissions are granted per workspace. 2 ## Create a workspace From the console, sign up + name the workspace. Or via API (rare, but useful for automated team-provisioning): **curl** ```bash title="POST /v1/workspaces" curl https://api.platform-auth.productcraft.co/v1/workspaces \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "slug": "acme", "display_name": "Acme Inc." }' ``` **SDK** ```ts title="@productcraft/platform-auth" import { PlatformAuth } from "@productcraft/platform-auth"; // A signed-in person's session (workspace API keys get 403 here). declare const yourPlatformUserJwt: string; const platform = new PlatformAuth({ auth: { type: "bearer", token: yourPlatformUserJwt }, }); // A taken slug throws ConflictError. A retried create never makes // two workspaces: the SDK sends an Idempotency-Key. const ws = await platform.workspaces.create({ slug: "acme", display_name: "Acme Inc.", }); console.log(ws.id, ws.slug); ``` Caller becomes `owner` automatically. Requires a signed-in platform account (cookie or JWT bearer) with a **verified email** — unverified accounts get 403 `EMAIL_NOT_VERIFIED`. Workspace API keys (`pcft_live_*`) cannot create workspaces: 403 `PAK_NOT_PERMITTED`. 3 ## One workspace or many? A real question new customers ask: separate workspace per environment (prod / staging / dev), or one workspace with multiple apps? The right answer depends on: - **Member overlap.** Same people work on all environments → one workspace, less churn. Different teams own prod vs dev → separate workspaces, blast-radius control. - **Audit boundary.** Need totally separate audit feeds for compliance → separate workspaces. Cross-cutting visibility is fine → one workspace. - **Billing.** One billing relationship per workspace. - **Service data.** Auth, Mail, Waitlist, Social data is per-workspace. If your prod and staging data should never touch, separate workspaces guarantee full isolation. **Recommended for most teams:** one workspace per company, multiple apps inside it (e.g. `acme`, `acme-staging`). The cryptographic + database isolation between Auth apps already prevents staging from touching prod data; member overlap usually outweighs the audit-separation benefit. 4 ## Workspace lifecycle A workspace's `status` is `active` from creation on; the only lifecycle transition today is deletion. Deletion: `DELETE /v1/workspaces/:slug`. Requires the `workspace.delete` permission (owner-only by default) and a human session — workspace API keys get 403. No “empty workspace” check — you can delete a workspace with members + data present, so the console asks for confirmation first. **Deletion is irreversible.** Auth apps, Mail domains, Waitlist waitlists, every audit row — gone. Take an export of anything you care about first. 5 ## The workspace slug The slug identifies the workspace in every workspace-scoped API path. Slug rules: lowercase alphanumeric + hyphens, 2-64 chars, unique across the platform (409 `WORKSPACE_SLUG_TAKEN` on conflict). Renaming is supported — `PATCH /v1/workspaces/:slug` with a new `slug` — but every URL and API call that referenced the old slug breaks immediately, and the old slug is freed for anyone to claim. Treat renames as an exceptional migration, not routine. In the console the slug is shown read-only under **Workspace → General** (only the display name is editable there), so renames go through the API. 6 ## What's not in workspaces - **End-user identity.** Your customers' users (the people signing up for the product you ship) live in Auth, not in the workspace. The workspace owns the Auth _app_ they sign up to. - **Billing details.** Handled outside the platform API today. - **Cross-workspace federation.** No SSO between workspaces; no shared roles. Two workspaces are independent. [Next: Members + roles →](https://productcraft.co/docs/platform/guides/02-members-and-roles.md) --- title: "02 · Members + roles | Platform Guides" description: "Invite teammates, understand the system role defaults, author custom roles, navigate the sole-owner invariant." url: https://productcraft.co/docs/platform/guides/02-members-and-roles --- [Platform guides](https://productcraft.co/docs/platform/guides.md) 02 · Members + roles # Add your team. Scope what they can do. System roles (owner/admin/member) cover most teams. Custom roles let you grant 'invoice exporter' or 'support reader' without making someone an admin. 1 ## System roles Three roles ship with every workspace: - **owner** — every permission in the catalog. Includes destructive verbs like `workspace.delete`. The last owner cannot be demoted or removed (sole-owner invariant — see Section 6). - **admin** — every operational permission. _Excludes_ role authoring (create/update/delete roles) and destructive verbs like `workspace.delete`. Admins can change members' roles up to admin, never to or from owner. Admins manage the day-to-day; owners shape who-can-do-what. - **member** — read-only across most surfaces + personal API keys. 2 ## Invite a member **curl** ```bash title="POST /v1/workspaces/:slug/invites" curl https://api.platform-auth.productcraft.co/v1/workspaces/acme/invites \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "email": "newhire@acme.com", "role": "admin", "expires_in_hours": 168 }' ``` **SDK** ```ts title="@productcraft/platform-auth" import { PlatformAuth } from "@productcraft/platform-auth"; // A signed-in person's session (workspace API keys get 403 here). declare const yourPlatformUserJwt: string; const platform = new PlatformAuth({ auth: { type: "bearer", token: yourPlatformUserJwt }, }); const invite = await platform.workspaces.invites.create("acme", { email: "newhire@acme.com", role: "admin", expires_in_hours: 168, }); console.log(invite.id); // Pages are fetched as you iterate. for await (const member of platform.workspaces.members.list("acme")) { console.log(member.username, member.role); } ``` Requires `workspace.member.invite` (owner + admin by default) and a human session — workspace API keys get 403. The response contains a `code`; when `email` is set, the invite is locked to that address and ProductCraft emails the recipient an accept link. The recipient signs in (or signs up) at `auth.productcraft.co` and accepts the code to join. The invite expires after `expires_in_hours` (168 = 7 days); revoke earlier via `DELETE .../invites/:id`. Only an owner can invite another owner. 3 ## Change a member's role ```bash title="PATCH /v1/workspaces/:slug/members/:id/role" curl -X PATCH https://api.platform-auth.productcraft.co/v1/workspaces/acme/members//role \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "role": "admin" }' ``` Pass `role` for a system role or `role_id` (UUID) for a custom role. Requires `workspace.member.update-role` (owner + admin by default). Owners can set any role. Anyone else can change a role only when both the member's current role and the new one hold no permission the caller lacks, so an admin can make a member an admin or demote an admin, but a narrow custom role can't promote anyone above itself. Otherwise the API returns 403 `MEMBER_RANK_EXCEEDED`. Setting anyone to owner, or changing an owner's role, stays owner-only (403 `OWNER_ROLE_REQUIRED`). 4 ## Custom roles When the three system roles don't fit — e.g. you want a “billing-exporter” role that can read but not write, and can also export the message log: ```bash title="POST /v1/workspaces/:slug/roles" curl https://api.platform-auth.productcraft.co/v1/workspaces/acme/roles \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "name": "billing-exporter", "description": "Read invoices + export message log. No write.", "policy": [ { "effect": "allow", "actions": ["mail.message.read", "mail.message.body.read", "workspace.audit.read"], "resources": ["*"] } ] }' ``` Role authoring requires `workspace.role.create` (owner-only by default) and a human session — workspace API keys get 403. 5 ## The IAM-style policy model The same shape as AWS IAM. Statements have effect (allow|deny), actions, and resources. Explicit deny wins. Action strings — `..`: ``` workspace.settings.update auth.create mail.send workspace.delete auth.audit.read mail.suppression.manage workspace.member.invite waitlist.update social.read workspace.role.create waitlist.export social.flag workspace.audit.read ... ... ``` The full catalog is queryable: `GET /v1/workspaces/:slug/policies/actions/catalog`. Allow statements naming unknown actions are rejected with 400. Resource URNs — `pcft:[/]`: ``` * # workspace-wide pcft:workspace/ # the workspace itself pcft:heimdall:app/ # per-Auth-app narrowing pcft:agora:community/ # per-Social-community narrowing ``` Wildcards work in any segment — `auth.*` matches every Auth verb; `pcft:heimdall:app/*` matches every app in the workspace. Trailing `*` swallows the rest. **Caller-narrowing.** When creating or updating a role, the caller's own policy must include every action they're trying to grant. An admin (whose policy excludes `workspace.delete`) can't hand the role they're editing a `workspace.delete` permission. Defence against self-escalation. **Managed policies: who can change them.** Owners and admins can create, edit and delete policies (`workspace.policy.create` / `.update` / `.delete`), with the same caller-narrowing as roles. Two kinds stay owner-only: a policy that any role uses, because changing it changes everyone who has that role, and a preset policy. An admin who edits or deletes one gets 403 `OWNER_ROLE_REQUIRED`. `PATCH` and `DELETE` on a policy return `bound_key_count`, the number of live API keys the change reached. 6 ## Sole-owner invariant A workspace must always have at least one owner. The API refuses transitions that would leave the workspace ownerless: - Demoting an owner to admin/member when they're the sole owner → 409 `SOLE_OWNER`. - Removing an owner from membership when they're the sole owner → 409 `SOLE_OWNER`. - The sole owner can't leave the workspace via self-leave; they must promote someone else first OR delete the workspace entirely. Edge case: deleting your _account_ (not the workspace) when you're a sole owner. Account deletion auto-promotes the oldest admin (or oldest other member if no admins exist) to owner, so the workspace is never left ownerless. 7 ## Remove a member ```bash title="DELETE /v1/workspaces/:slug/members/:id" curl -X DELETE https://api.platform-auth.productcraft.co/v1/workspaces/acme/members/ \ -H 'authorization: Bearer ' ``` Requires `workspace.member.remove` on the caller's role. Two refusal cases: - **Sole owner** — 409 `SOLE_OWNER` (see Section 6). - **Last member** — 409 `LAST_MEMBER`. Decommission the whole workspace instead via `DELETE /v1/workspaces/:slug`. **Self-leave** is allowed without `workspace.member.remove` — members can always leave their own workspaces, subject to the same sole-owner + last-member invariants. [Next: Service activation →](https://productcraft.co/docs/platform/guides/03-service-activation.md) --- title: "03 · Service activation | Platform Guides" description: "Enabling and disabling Auth, Mail, Waitlist, Social, Trawl per workspace. The SERVICE_NOT_ENABLED gate explained." url: https://productcraft.co/docs/platform/guides/03-service-activation --- [Platform guides](https://productcraft.co/docs/platform/guides.md) 03 · Service activation # Control which services a workspace runs. Each service (Auth, Mail, Waitlist, Social, Trawl) is activated per workspace. New workspaces start with every service enabled; disable the ones you don't use. Endpoints of a disabled service return 403 SERVICE_NOT_ENABLED before any data leaks. 1 ## Why activation is per-workspace - **Scoping** — each of your workspaces (production, dev, per-client) runs only the services it actually needs. - **Defence in depth** — a misconfigured key shouldn't accidentally hit a service the workspace never wanted. The `SERVICE_NOT_ENABLED` check runs before any service-specific logic. Today a new workspace is created with every launched service enabled, so the console shows every product immediately — disabling is how you narrow the surface. 2 ## Enable a service From the console (Workspace → Services, then **Enable** / **Disable** on the service row) or API: ```bash title="POST /v1/workspaces/:slug/services/:service" # Enable (or re-enable) Mail curl -X POST https://api.platform-auth.productcraft.co/v1/workspaces/acme/services/mail \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{}' # → 201, the full service state row: { "workspace_id": "", "service": "mail", "enabled": true, "enabled_at": "2026-07-28T14:20:46.083Z", "enabled_by": "", "disabled_at": null, "disabled_by": null, "settings": {} } ``` Requires the `workspace.service.enable` permission. Valid service names are `auth`, `mail`, `waitlist`, `social`, `trawl`, `flags`, `notify` — anything else is a 400 `SERVICE_UNKNOWN`. 3 ## Per-service settings Each activation row carries a free-form `settings` JSON blob whose shape is up to the service. Update it via `PATCH /v1/workspaces/:slug/services/:service/settings` — the request body is the settings object itself (no wrapper) and **replaces the blob entirely**: ```bash title="PATCH /v1/workspaces/:slug/services/:service/settings" curl -X PATCH https://api.platform-auth.productcraft.co/v1/workspaces/acme/services/mail/settings \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "default_sender": "noreply@acme.com" }' # → 200, the updated service state row (settings included) ``` Requires `workspace.service.enable`. Patching a service that was never activated on the workspace returns 404 `SERVICE_NOT_ACTIVATED`. 4 ## Disable ```bash title="DELETE /v1/workspaces/:slug/services/:service" curl -X DELETE https://api.platform-auth.productcraft.co/v1/workspaces/acme/services/mail \ -H 'authorization: Bearer ' # → 204. Disabling a service that isn't enabled → 409 SERVICE_NOT_ENABLED. ``` Requires `workspace.service.disable`. Disable doesn't delete data — domains, templates, messages, settings are all preserved. Subsequent calls to the service's endpoints return 403 `SERVICE_NOT_ENABLED`. Re-enabling restores access (allow up to a minute for downstream permission caches to refresh). For permanent removal, delete the workspace (Chapter 1). 5 ## List active services **curl** ```bash title="GET /v1/workspaces/:slug/services" curl https://api.platform-auth.productcraft.co/v1/workspaces/acme/services \ -H 'authorization: Bearer ' ``` **SDK** ```ts title="@productcraft/platform-auth" import { PlatformAuth } from "@productcraft/platform-auth"; // Reads PRODUCTCRAFT_API_KEY from the environment const platform = new PlatformAuth(); const { data: services } = await platform.workspaces.services.list("acme"); for (const s of services) console.log(s.service, s.enabled); ``` ```json { "data": [ { "workspace_id": "...", "service": "auth", "enabled": true, "enabled_at": "...", "enabled_by": "...", "disabled_at": null, "disabled_by": null, "settings": {} }, { "workspace_id": "...", "service": "mail", "enabled": true, ... }, { "workspace_id": "...", "service": "social", "enabled": true, ... }, { "workspace_id": "...", "service": "trawl", "enabled": true, ... }, { "workspace_id": "...", "service": "waitlist", "enabled": false, "disabled_at": "...", "disabled_by": "...", ... } ] } ``` Requires `workspace.service.read`. A disabled service keeps its row with `enabled: false` and `disabled_at` set. 6 ## The SERVICE_NOT_ENABLED guard in practice Useful for SDKs and customer support — what error to expect when a service hasn't been turned on. Workspace-scoped endpoints on a service check activation before anything else. With the service disabled you get: ```http HTTP/1.1 403 Forbidden { "statusCode": 403, "message": "mail is not enabled on this workspace", "code": "SERVICE_NOT_ENABLED" } ``` **This 403 isn't a permission failure.** Your role and policies are fine — activation is a structural prerequisite, not an authz outcome. Re-enable the service and the same call succeeds. [Next: Workspace API keys for CI/CD →](https://productcraft.co/docs/platform/guides/04-pats-for-cicd.md) --- title: "04 · Workspace API keys for CI/CD | Platform Guides" description: "Mint a workspace API key, scope tightly, rotate, audit. The right way to give a deploy pipeline workspace access." url: https://productcraft.co/docs/platform/guides/04-pats-for-cicd --- [Platform guides](https://productcraft.co/docs/platform/guides.md) 04 · Workspace API keys for CI/CD # Give CI workspace access without sharing your cookie. A workspace API key (prefix `pcft_live_*`, formerly called a Personal Access Token or PAT) is the right shape for any non-human caller: deploy pipelines, infra-as-code, scheduled exporters, admin scripts. 1 ## When to mint a workspace API key - **Deploy pipeline** needs to provision an Auth app for the new environment + push templates. - **Infra-as-code** (Terraform, Pulumi) manages workspaces + roles declaratively. - **Scheduled job** exports the message log nightly for compliance / analytics. - **Admin script** a human runs from their laptop but doesn't want their cookie embedded in the script. Don't mint a workspace API key for: - **End-user identity**. Customers' end- users go through Auth, not the Platform API. - **Day-to-day operator workflows**. Sign in to the console; that's what it's for. 2 ## Mint a workspace API key Workspace API keys bind to one or more **managed workspace policies** (rows in `workspace_policy`). Author the policy first, then reference its id when minting. The two-step shape — instead of an inline policy on mint — means a teammate can rotate the workspace API key without re-asserting the permission set, and a single policy can be reused across many workspace API keys and roles. **curl** ```bash title="POST /v1/workspaces/:slug/policies — author the policy first" curl https://api.platform-auth.productcraft.co/v1/workspaces/acme/policies \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "name": "ci-staging-deploy", "description": "Auth app provisioning + Mail template ops for CI", "policy": [ { "effect": "allow", "actions": ["auth.create", "auth.read", "auth.update", "mail.create", "mail.update", "mail.read"], "resources": ["*"] } ] }' # → { "id": "", "workspace_id": "...", ... } curl https://api.platform-auth.productcraft.co/v1/workspaces/acme/api-keys \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "name": "github-actions-staging-deploy", "description": "Deploys acme-staging app from CI", "policy_ids": [""] }' ``` **SDK** ```ts title="@productcraft/platform-auth" import { PlatformAuth } from "@productcraft/platform-auth"; // A signed-in person's session (workspace API keys get 403 here). declare const yourPlatformUserJwt: string; const platform = new PlatformAuth({ auth: { type: "bearer", token: yourPlatformUserJwt }, }); // 1. Author (or reuse) a managed policy const policy = await platform.workspaces.policies.create("acme", { name: "ci-staging-deploy", description: "Auth app provisioning + Mail template ops for CI", policy: [ { effect: "allow", actions: ["auth.create", "auth.read", "auth.update", "mail.create", "mail.update", "mail.read"], resources: ["*"], }, ], }); // 2. Mint a workspace API key that binds to that policy const minted = await platform.workspaces.apiKeys.create("acme", { name: "github-actions-staging-deploy", description: "Deploys acme-staging app from CI", policy_ids: [policy.id], }); // minted.token is the plaintext workspace API key, returned exactly once. // minted.record holds the public metadata (id, prefix, bindings). console.log(minted.record.id, minted.record.token_prefix); ``` Response — the only time the plaintext token is returned: ```json { "token": "pcft_live_thatappearsonce...", "record": { "id": "", "workspace_id": "", "created_by": "", "name": "github-actions-staging-deploy", "description": "Deploys acme-staging app from CI", "token_prefix": "pcft_live_thata", "policies": [ { "id": "", "name": "ci-staging-deploy", "description": "..." } ], "last_used_at": null, "revoked_at": null, "created_at": "2026-05-25T...", "updated_at": "2026-05-25T..." } } ``` Platform-Auth stores only the hash. No recovery — if you lose the secret, rotate (Section 5) and update your secret store. Treat the token like a password. **Mint requires a human session.** workspace API key mint/update/revoke is cookie/JWT-only on `api.platform-auth.productcraft.co` — a workspace API key cannot mint another workspace API key. Same for workspace create/delete and role/policy/invite mutations. Reads and API key introspection (the operations downstream services and pipelines need) do work with a workspace API key bearer. In the pipeline, `platform.apiKeys.self()` tells a job which workspace and permissions its key carries, which makes a good first step to fail fast on a wrong secret: ```ts title="check-key.ts" import { PlatformAuth } from "@productcraft/platform-auth"; // In the pipeline: reads PRODUCTCRAFT_API_KEY from the environment const platform = new PlatformAuth(); const me = await platform.apiKeys.self(); console.log(me.workspace_id, me.name, me.allowed); ``` 3 ## Caller-narrowing on mint You cannot grant a workspace API key permissions you don't yourself hold. Same shape as role authoring (Chapter 2 — Section 5), and enforced wherever a policy is authored or bound: an admin (excluded from `workspace.delete`) can't author or bind a policy with `workspace.delete` for a workspace API key. Trying returns 403 `Cannot grant actions you don't have: workspace.delete`. **Implication for CI:** if your pipeline needs broad permissions, mint the workspace API key from an owner account, not from a least-privilege admin. The workspace API key inherits the minter's authority cap. 4 ## Scope tightly Patterns for common pipelines: ```json title="Read-only audit exporter" { "effect": "allow", "actions": ["workspace.audit.read", "mail.message.read"], "resources": ["*"] } ``` ```title="Auth app operator (scoped to one existing app)" { "effect": "allow", "actions": ["auth.update", "auth.read"], "resources": ["pcft:heimdall:app/"] } // App resources are scoped by app *id*, not slug. A provisioner that // creates new apps needs "auth.create" on resources ["*"]. ``` ```json title="Mail template deploy (deny destructive)" [ { "effect": "allow", "actions": ["mail.*"], "resources": ["*"] }, { "effect": "deny", "actions": ["mail.delete"], "resources": ["*"] } ] ``` **Explicit deny wins.** The template-deploy workspace API key above can create, update, send, but not delete — even if a teammate later widens `mail.*` to include something destructive. 5 ## Rotate Periodic rotation (90 days is a reasonable default) + on-suspicion rotation when a former teammate leaves or a secret might have leaked. ```bash title="DELETE old, mint new" # Mint replacement first — re-uses the same managed policy from Section 2. curl -X POST .../v1/workspaces/acme/api-keys \ -H 'authorization: Bearer ' \ -d '{ "name": "github-actions-staging-deploy-v2", "policy_ids": [""] }' > new.json # Update CI secret store with the new value # After CI is using the new workspace API key, revoke the old curl -X DELETE .../v1/workspaces/acme/api-keys/ \ -H 'authorization: Bearer ' ``` **Revocation is immediate** at the source, but services that accept workspace API keys cache introspection results for up to 60 seconds — a revoked workspace API key can still authenticate against a cached entry for that window. Plan rotations assuming a one-minute tail. 6 ## Audit usage Two signals. First, `last_used_at` on the workspace API key record (`GET .../api-keys`, also shown in the console) — workspace API keys with no usage in > 30 days are candidates for cleanup. Second, the workspace audit log: workspace API key lifecycle events (`platform.apikey.created`, `platform.apikey.revoked`, …) and Platform API actions performed with the workspace API key are recorded with the key's id as the actor and the caller IP. Per-service activity (Mail sends, Auth app changes, …) lives in each service's own logs — see Chapter 5. ```bash title="Filter the audit log for one workspace API key (client-side)" curl 'https://api.platform-auth.productcraft.co/v1/workspaces/acme/audit-logs?limit=100' \ -H 'authorization: Bearer ' \ | jq --arg id "" '.data[] | select(.actor_id == $id or .resource_id == $id)' ``` 7 ## Where to store the secret - **GitHub Actions:** repo or org-level secret, accessed via `${{ secrets.PRODUCTCRAFT_API_KEY }}`. - **GitLab CI:** CI/CD variables, masked. - **Vault / Doppler / AWS Secrets Manager:** the right choice if you have multiple environments + CI + production services all needing tokens. - **.env files committed to a repo:** never. Even private repos. The audit trail of who-saw-what is hopeless once it lands in git. 8 ## Provisioning script — a complete example ```yaml title=".github/workflows/provision-staging.yaml" name: Provision staging on: workflow_dispatch: env: API_KEY: ${{ secrets.PRODUCTCRAFT_API_KEY }} WORKSPACE_ID: jobs: provision: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Create Auth app for staging run: | curl -fsS https://api.auth.productcraft.co/v1/apps \ -H "authorization: Bearer $API_KEY" \ -H 'content-type: application/json' \ -d '{ "slug": "acme-staging", "display_name": "Acme (staging)", "workspace_id": "'"$WORKSPACE_ID"'" }' - name: Sync role catalogue run: | curl -fsS https://api.auth.productcraft.co/v1/apps//roles \ -H "authorization: Bearer $API_KEY" \ -H 'content-type: application/json' \ -d '{ "name": "viewer", "description": "Read-only" }' || true - name: Push Mail templates from repo # POST /templates is an idempotent upsert on (workspace, name) run: | for t in templates/*.json; do curl -fsS "https://api.mail.productcraft.co/v1/workspaces/$WORKSPACE_ID/templates" \ -H "authorization: Bearer $API_KEY" \ -H 'content-type: application/json' \ -d @"$t" done ``` One workspace API key, narrowly scoped (`auth.create` + `auth.read` + `mail.create` + `mail.update` on the workspace), workflow-dispatch only. Template files are the create body: `{ "name": "...", "subject": "...", "body_html": "..." }`. [Next: Audit + compliance →](https://productcraft.co/docs/platform/guides/05-audit-and-compliance.md) --- title: "05 · Audit + compliance | Platform Guides" description: "What the workspace audit log captures, querying patterns, exports for SOC2 / GDPR." url: https://productcraft.co/docs/platform/guides/05-audit-and-compliance --- [Platform guides](https://productcraft.co/docs/platform/guides.md) 05 · Audit + compliance # The audit trail. Workspace, member, role, policy and workspace API key operations write append-only audit rows. Read them for support, export them for SOC2, query them for incident response. 1 ## What gets captured The workspace audit log records: - **Member lifecycle** — invites created / accepted / revoked (`workspace.invite.*`), members joined / removed / role-changed (`workspace.member.*`). - **Role + policy mutations** — custom role and managed-policy create / update / delete (`platform.role.*`, `platform.policy.*`). - **Workspace API key lifecycle** — mints, revokes, renames, policy-binding changes (`platform.apikey.*`). - **Workspace mutations** — created / updated (display name, slug) / deleted (`workspace.*`). - **Sensitive reads** — member, invite, settings and audit-log reads write rows too (e.g. `workspace.audit.read`), so the log shows who looked, not just who changed. **What's NOT in workspace audit**: per- service activity lives in the service's own log. Auth app changes → `GET api.auth.productcraft.co/v1/apps/:app_id/audit-logs`. Mail sends → Mail's message log. Social moderation → Social's moderation audit. A unified `/v1/workspaces/:slug/audit-feed` endpoint exists with a stable shape (see Section 3); today it serves the workspace rows, with the per-service sources arriving as a follow-up. 2 ## Read it Requires `workspace.audit.read`. Newest first, cursor-paginated (`limit` up to 100 per page). ```bash title="GET /v1/workspaces/:slug/audit-logs" curl 'https://api.platform-auth.productcraft.co/v1/workspaces/acme/audit-logs?limit=50' \ -H 'authorization: Bearer ' ``` ```json { "data": [ { "id": "...", "workspace_id": "", "action": "workspace.member.role_changed", "actor_id": "", "actor_type": "platform_user", "resource": "workspace_membership", "resource_id": "", "metadata": { "role_id": "", "role_name": "admin" }, "ip": "203.0.113.4", "created_at": "2026-05-11T..." }, { "id": "...", "workspace_id": "", "action": "platform.apikey.created", "actor_id": "", "actor_type": "platform_user", "resource": "platform_api_key", "resource_id": "", "metadata": { "name": "github-actions-staging-deploy", "requested_policy_ids": ["..."], "resolved_policy_ids": ["..."] }, "ip": "192.0.2.1", "created_at": "2026-05-11T..." } ], "pagination": { "next_cursor": "...", "has_more": true } } ``` 3 ## Query patterns `/audit-logs` takes only `limit` + `cursor` — unknown query params are silently ignored, so don't rely on server-side filters that aren't documented here. Two patterns cover the common asks: - **Time-bounded reads** — use the unified feed, which accepts `since` (ISO-8601) and `limit` up to 500: `GET /v1/workspaces/:slug/audit-feed?since=2026-04-01T00:00:00Z`. - **Changes only** — add `changes_only=true` to the feed to leave out reads, successful sign-ins and MCP tool-call rows. This is what the console dashboard's Recent activity panel shows: `GET /v1/workspaces/:slug/audit-feed?changes_only=true&limit=15`. - **Everything else** — filter client-side. Page through and select with `jq`, e.g. `.data[] | select(.action == "workspace.member.role_changed")` for every role change, or `select(.resource == "platform_api_key")` for all workspace API key lifecycle rows. 4 ## Export for compliance For SOC2 / ISO27001 / annual review-style asks, paginate through the log and store it in your own object storage. The feed endpoint is the better export surface: it takes `since` and up to 500 rows per page. ```bash title="Export script (bash, jq)" #!/usr/bin/env bash set -euo pipefail WS=acme SINCE="2026-01-01T00:00:00Z" API_KEY="${PRODUCTCRAFT_API_KEY}" BASE="https://api.platform-auth.productcraft.co/v1/workspaces/$WS/audit-feed" CURSOR="" PAGE=0 > audit-export.jsonl while :; do RESP=$(curl -fsS "$BASE?since=$SINCE&limit=500&cursor=$CURSOR" \ -H "authorization: Bearer $API_KEY") echo "$RESP" | jq -c '.data[]' >> audit-export.jsonl HAS_MORE=$(echo "$RESP" | jq -r '.pagination.has_more') if [[ "$HAS_MORE" != "true" ]]; then break; fi CURSOR=$(echo "$RESP" | jq -r '.pagination.next_cursor') PAGE=$((PAGE+1)) echo "page $PAGE complete" sleep 0.5 done echo "Done. $(wc -l < audit-export.jsonl) rows." # Need an upper bound too? Filter the export afterwards: # jq -c 'select(.timestamp < "2026-07-01T00:00:00Z")' audit-export.jsonl ``` 5 ## Retention + workspace deletion Audit rows are append-only — there is no delete or edit endpoint. **Deleting a workspace deletes its audit log with it.** The rows live inside the workspace, so workspace deletion (Chapter 1) removes them immediately. If you need the trail for compliance, export it (Section 4) before deleting. 6 ## Common compliance asks + how to answer them - **“Who has access to our workspace?”** — list members + workspace API keys, plus their roles + policies. The console splits this across two pages: **Workspace → Members** (people, each with a role selector) and **Workspace → API keys** (workspace API keys, each showing its bound-policy count and last-used date). For the policy statements behind a binding, use the API: `GET .../members` + `GET .../api-keys`. - **“Show me every action taken by the user we just offboarded.”** — export, then `jq 'select(.actor_id == "")'`. Their `platform.apikey.created` rows show which workspace API keys they minted — revoke those too. - **“What changed in the last 30 days?”** — `/audit-feed?since=<30d-ago>`. Group by `action` for the executive view, by `actor_id` for the per-person view. - **“Prove we revoked the leaked workspace API key.”** — the `platform.apikey.revoked` row with `resource_id = ` carries timestamp + actor + the IP that did the revoke. What's next ## You've finished the series From here: - [Full API reference](https://productcraft.co/docs/platform/api-reference.md) for every endpoint with schemas - [Auth guides](https://productcraft.co/docs/auth/guides.md) for the end-user identity layer - [Mail guides](https://productcraft.co/docs/mail/guides.md) for sender configuration + deliverability [Back to Platform docs](https://productcraft.co/docs/platform.md) --- title: "Webhooks | Platform Docs" description: "How every ProductCraft product sends webhooks: add an endpoint, verify Standard Webhooks signatures in Node, send a test, automatic retries, auto-disable, replay, secret rotation, and the older signature headers with their sunset dates." url: https://productcraft.co/docs/platform/webhooks --- [Platform docs](https://productcraft.co/docs/platform.md) Webhooks # One way to receive webhooks, in every product. Mail, Auth, Waitlist, Trawl and Social send events the same way: signed with Standard Webhooks, retried for about 32 hours, switched off if your endpoint keeps failing, and kept for 30 days so you can replay them. This page covers what is the same everywhere. Each product's guide lists its events and anything only that product does. You'll need a workspace API key (`pcft_live_…`) whose policy allows the product's webhook actions, or use the console: every product has a **Webhooks** page with the same screens. 1 ## Where each product's endpoints live The routes under each path are identical in every product; only the host and the scope differ. | Product | Base URL and scope | Events (full list in the guide) | | --- | --- | --- | | [Mail](https://productcraft.co/docs/mail/guides/05-deliverability.md) | https://api.mail.productcraft.co /v1/workspaces/:workspace_id/webhooks | Emails sent, delivered, bounced, complained; domains; the suppression list | | [Auth](https://productcraft.co/docs/auth/guides/08-webhooks-and-audit.md) | https://api.auth.productcraft.co /v1/apps/:app_id/webhooks | Sign-ups, sign-ins, email verification, roles, deletions, organizations | | [Waitlist](https://productcraft.co/docs/waitlist/guides/06-webhooks-and-analytics.md) | https://api.waitlist.productcraft.co /v1/workspaces/:workspace_id/webhooks | Entries created, approved, rejected | | [Trawl](https://productcraft.co/docs/trawl/guides/04-webhooks.md) | https://api.trawl.productcraft.co /v1/workspaces/:workspace_id/webhooks | Jobs succeeded or failed; credits running low | | [Flags](https://productcraft.co/docs/flags/guides/04-webhooks.md) | https://api.flags.productcraft.co /v1/workspaces/:workspace_id/webhooks (filter by project, config or environment) | Configs published (who changed what, which keys); SDK keys rotated | | [Notify](https://productcraft.co/docs/notify/guides/15-webhooks.md) | https://api.notify.productcraft.co /v1/workspaces/:workspace_id/webhooks | Deliveries sent, delivered, failed, bounced or skipped; inbox items read, archived or pressed; devices pruned or moved; invalid push credentials; email paused; recipients erased | | [Social](https://productcraft.co/docs/social/guides/webhooks.md) | https://api.social.productcraft.co /v1/workspaces/:workspace_id/webhooks or /v1/communities/:community_id/webhooks | Posts, comments, reactions, follows, flags, moderation, messages, uploads | Under each scope path: - `GET …/webhooks/event-types`: the product's events, each with a description and an example payload. - `GET`/`POST …/webhooks/endpoints`, `GET`/`PATCH`/`DELETE …/endpoints/:id`: your endpoints (up to 10 per scope). - `POST …/endpoints/:id/test` and `POST …/endpoints/:id/rotate-secret`. - `GET …/webhooks/events`, `GET …/events/:id` and `POST …/events/:id/replay`: the event log. 2 ## Add an endpoint The URL must be public https://. Pick the events you handle; an empty event_types list means every event, including ones added later. ```bash title="POST {base}{scope}/endpoints" curl -X POST https://api.waitlist.productcraft.co/v1/workspaces//webhooks/endpoints \ -H 'authorization: Bearer pcft_live_...' \ -H 'idempotency-key: add-signups-endpoint-1' \ -H 'content-type: application/json' \ -d '{ "url": "https://hooks.acme.com/webhooks/productcraft", "description": "Sign-ups to the CRM", "event_types": ["entry.created"] }' 201 Created { "id": "9c1e5b7d-2f4a-4c8e-b3d6-0f1a2b3c4d5e", "url": "https://hooks.acme.com/webhooks/productcraft", "event_types": ["entry.created"], "enabled": true, "status": "enabled", "signing_secret": "whsec_BDGVRE...", # shown exactly ONCE "signing_secret_hint": "flao", ... } ``` Store `signing_secret` in your secret manager now: later reads show only its last 4 characters. Send an `Idempotency-Key`, so a retried request cannot create a second endpoint with a secret you never saw. `PATCH` changes the URL, description, events or `enabled`; `DELETE` removes the endpoint and drops its queued retries. 3 ## Verify the signature Every delivery is a JSON POST with three Standard Webhooks headers. Check them before you trust the body. ```http POST https://hooks.acme.com/webhooks/productcraft content-type: application/json webhook-id: evt_83cfc794-78e9-4102-96de-3a9a6f5bc31e webhook-timestamp: 1792231074 webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4= { "id": "evt_83cfc794-78e9-4102-96de-3a9a6f5bc31e", "type": "entry.created", "created_at": "2026-10-17T10:00:00.000Z", "data": { ... } } ``` The signature is an HMAC-SHA256 of `".."`, keyed with the bytes of your secret after `whsec_` (base64-decoded), and sent base64-encoded after `v1,`. While a rotated secret is still in its grace period the header carries one signature per secret, separated by a space; accept the delivery if any of them matches. With a ProductCraft Node SDK, `webhooks.unwrap()` on that product's client (`mail`, `waitlist`, `trawl`, `flags`, `notify`, `social`) checks the signature and the timestamp, accepts several secrets during a rotation and the product's older header until its sunset, and returns the event typed by `type`. It throws `WebhookVerificationError` when the delivery does not verify. **Verify without the SDK:** the open-source `standardwebhooks` package (the same verifier works for every product), or the dependency-free version in the last tab. **ProductCraft SDK** ```ts title="@productcraft/waitlist" import express from "express"; import { Waitlist, WebhookVerificationError } from "@productcraft/waitlist"; const app = express(); // Secret defaults to PRODUCTCRAFT_WAITLIST_WEBHOOK_SECRET; // pass webhookSecret: [old, new] during a rotation. const waitlist = new Waitlist(); // express.raw: verify the exact bytes that were signed. app.post( "/webhooks/productcraft", express.raw({ type: "application/json" }), async (req, res) => { try { const event = await waitlist.webhooks.unwrap({ payload: req.body, headers: req.headers, }); // event.id is the same on every retry: skip ones you have handled. if (event.type === "entry.created") console.log(event.data); res.sendStatus(204); } catch (err) { if (err instanceof WebhookVerificationError) { res.sendStatus(400); return; } throw err; } }, ); ``` **standardwebhooks** ```ts title="npm install standardwebhooks" import express from 'express'; import { Webhook } from 'standardwebhooks'; const app = express(); const wh = new Webhook(process.env.WEBHOOK_SECRET); // "whsec_..." // express.raw: verify the exact bytes that were signed, not re-serialised JSON. app.post('/webhooks/productcraft', express.raw({ type: 'application/json' }), (req, res) => { let event; try { event = wh.verify(req.body.toString('utf8'), { 'webhook-id': req.header('webhook-id'), 'webhook-timestamp': req.header('webhook-timestamp'), 'webhook-signature': req.header('webhook-signature'), }); } catch { return res.status(400).send('bad signature'); } // event.id (= webhook-id) is the same on every retry: skip ones you have handled. handle(event); // your code; keep it fast and do slow work in a queue res.status(204).end(); }); ``` **node:crypto only** ```ts title="verify-webhook.js" import crypto from 'node:crypto'; const TOLERANCE_SECONDS = 5 * 60; export function verifyWebhook(rawBody, headers, secret) { const id = headers['webhook-id']; const timestamp = headers['webhook-timestamp']; const signatures = headers['webhook-signature']; if (!id || !timestamp || !signatures) throw new Error('missing webhook headers'); const ts = Number(timestamp); if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > TOLERANCE_SECONDS) { throw new Error('timestamp too old or in the future'); } const key = secret.startsWith('whsec_') ? Buffer.from(secret.slice('whsec_'.length), 'base64') : Buffer.from(secret, 'utf8'); const expected = crypto .createHmac('sha256', key) .update(`${id}.${timestamp}.${rawBody}`) .digest(); // During a secret rotation there is one "v1," per secret, space-separated. const ok = signatures.split(' ').some((part) => { const [version, sig] = part.split(','); if (version !== 'v1' || !sig) return false; const given = Buffer.from(sig, 'base64'); return given.length === expected.length && crypto.timingSafeEqual(given, expected); }); if (!ok) throw new Error('bad signature'); return JSON.parse(rawBody); } // Express: app.post('/webhooks/productcraft', express.raw({ type: 'application/json' }), (req, res) => { // const event = verifyWebhook(req.body.toString('utf8'), req.headers, process.env.WEBHOOK_SECRET); // ... // }); ``` - **Verify the raw body.** Body-parsing middleware that re-serialises the JSON changes the bytes, and the signature no longer matches. - **Reject old timestamps.** All three refuse a `webhook-timestamp` more than five minutes from your clock, which stops someone replaying a captured request. - **Dedupe on `webhook-id`.** It is the event id and stays the same on every retry and replay. 4 ## Send a test Prove your receiver works before a real event arrives: the product sends the example of an event, signed like a real delivery, and tells you what your server answered. ```bash title="POST {base}{scope}/endpoints/:id/test" curl -X POST https://api.waitlist.productcraft.co/v1/workspaces//webhooks/endpoints//test \ -H 'authorization: Bearer pcft_live_...' \ -H 'idempotency-key: test-1' \ -H 'content-type: application/json' \ -d '{ "event_type": "entry.created" }' { "succeeded": true, "status_code": 204, "latency_ms": 112, "trigger": "test", "response_body": "", ... } ``` The test body carries `"test": true`, shows up in the event log, and is never retried. In the console, **Send test** on an endpoint does the same and shows the status code and the start of your response. 5 ## Retries and auto-disable Answer with any 2xx within 15 seconds. Anything else, including a timeout or a redirect, is a failed attempt. - **Automatic retries.** A failed delivery is sent again 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours after each failure: 7 attempts over about 32 hours. Every retry has the same event id and body, freshly signed with a new timestamp. - **Auto-disable.** After 20 failures in a row, or 24 hours of nothing but failures, the endpoint is switched off (`status: "auto_disabled"`, `disabled_reason: "failing"`) and its queued retries are dropped. The console shows a banner on the Webhooks page. Fix the receiver, switch the endpoint back on (`PATCH` with `{ "enabled": true }`), then replay what it missed. - **A success resets the count.** One delivered attempt clears `consecutive_failures` and `first_failure_at`. 6 ## The event log and replay Every event of the last 30 days, with the latest attempt per endpoint and when the next retry is due. ```bash title="GET {base}{scope}/events" curl 'https://api.waitlist.productcraft.co/v1/workspaces//webhooks/events?status=failed&limit=20' \ -H 'authorization: Bearer pcft_live_...' # Send one event again, to one endpoint (omit endpoint_id for every endpoint that receives it) curl -X POST 'https://api.waitlist.productcraft.co/v1/workspaces//webhooks/events//replay?endpoint_id=' \ -H 'authorization: Bearer pcft_live_...' \ -H 'idempotency-key: replay-1' ``` Filter by `endpoint_id`, `type` and `status` (`pending`, `delivered`, `failed`, `not_sent`). `GET …/events/:id` adds every attempt: status code, latency and the first 1 KiB of your response. A replay sends the same body and `webhook-id` again and returns what your server answered. 7 ## Rotate a secret without dropping a delivery The new secret is shown once; the old one keeps working for the grace period you choose. ```bash title="POST {base}{scope}/endpoints/:id/rotate-secret" curl -X POST https://api.waitlist.productcraft.co/v1/workspaces//webhooks/endpoints//rotate-secret \ -H 'authorization: Bearer pcft_live_...' \ -H 'idempotency-key: rotate-1' \ -H 'content-type: application/json' \ -d '{ "grace_hours": 24 }' ``` During the grace period (24 hours by default, up to 168; `0` ends the old secret now) every delivery is signed with both secrets, so a receiver holding either one verifies. Deploy the new secret within the grace period and nothing is rejected. 8 ## Older signature headers and their sunset Endpoints made before a product moved to Standard Webhooks (every product in the table below moved on 17 October 2026) keep receiving that product's older header too, until the sunset date. | Product | Older header | Sent until | | --- | --- | --- | | Mail | X-Mail-Signature | 15 January 2027 | | Auth | X-Auth-Signature | 15 January 2027 | | Waitlist | X-Waitlist-Signature | 15 January 2027 | | Trawl | X-Trawl-Signature | 15 January 2027 | | Social | x-pcft-signature | 15 January 2027 | Every older header is `t=,v1=`, an HMAC-SHA256 of `"."` keyed with the secret string as stored. Switch your verifier to the Standard Webhooks headers before the sunset. A secret from before the move works with any Standard Webhooks verifier as `"whsec_" + base64(secret)` (the dependency-free code above accepts it unchanged); secrets issued since already start with `whsec_`. The older routes of each product (for example `POST …/webhooks` and `…/webhooks/:id`) keep working until the same date. Their responses carry `Deprecation: true` and `Sunset: Fri, 15 Jan 2027 00:00:00 GMT` headers, and endpoints created through them also get the older header. New endpoints get only the Standard Webhooks headers. Each product's guide notes anything else that changed for its older webhooks. --- title: "API Reference | Platform Docs" description: "Platform API reference — workspaces, members, roles, service activation, workspace API keys, audit, introspection. Generated from the live OpenAPI spec served by platform-auth-api." url: https://productcraft.co/docs/platform/api-reference --- [Platform docs](https://productcraft.co/docs/platform.md) API reference # Platform API. The administrative surface that powers the console — workspaces, members, roles, service activation, workspace API keys, audit, introspection. Generated from the live OpenAPI spec. Browser sessions authenticate via the `auth_token` cookie set by `/v1/auth/signin`. CI/CD and other programmatic callers authenticate via a workspace API key (`pcft_live_*`) minted on the console's **API keys** page — pass it as `Authorization: Bearer `. The policies bound to the key determine which actions are allowed, and a key can never carry more than the minter's own permissions. Signed-in users are checked against their workspace role's policy instead. Minting and revoking keys requires a signed-in session — a key cannot mint other keys. Base URL `https://api.platform-auth.productcraft.co` Auth `Authorization: Bearer …` Spec version OpenAPI 3.0.0 · v1.0.0 OpenAPI spec [https://api.platform-auth.productcraft.co/docs-json](https://api.platform-auth.productcraft.co/docs-json) ## OAuth Sign-In Sign in to ProductCraft with Google, GitHub or Apple (browser redirects; not part of the SDKs). - [get `/v1/auth/oauth/{provider}/start` Begin a federated sign-in flow; 302s to the provider authorize URL.](https://productcraft.co/docs/platform/api-reference/get-v1-auth-oauth-provider-start.md) - [post `/v1/auth/oauth/{provider}/callback` Complete a federated sign-in.](https://productcraft.co/docs/platform/api-reference/post-v1-auth-oauth-provider-callback.md) ## Account Close the signed-in ProductCraft account. - [delete `/v1/account` Delete the calling account.](https://productcraft.co/docs/platform/api-reference/delete-v1-account.md) ## Authentication Platform sign-up, sign-in, token refresh, sign-out and password reset for ProductCraft accounts (the people who run workspaces, not your end users: those sign in through Auth). - [post `/v1/auth/signup` Create a new account and sign in](https://productcraft.co/docs/platform/api-reference/post-v1-auth-signup.md) - [post `/v1/auth/signin` Sign in with email/username and password](https://productcraft.co/docs/platform/api-reference/post-v1-auth-signin.md) - [post `/v1/auth/refresh` Refresh access token using refresh token](https://productcraft.co/docs/platform/api-reference/post-v1-auth-refresh.md) - [post `/v1/auth/logout` Logout by revoking refresh token](https://productcraft.co/docs/platform/api-reference/post-v1-auth-logout.md) - [post `/v1/auth/logout-current` Revoke the server-side session tied to the caller’s current access token](https://productcraft.co/docs/platform/api-reference/post-v1-auth-logout-current.md) - [post `/v1/auth/password/request-reset` Request a password reset email.](https://productcraft.co/docs/platform/api-reference/post-v1-auth-password-request-reset.md) - [post `/v1/auth/password/reset` Reset password using the email-delivered reset token.](https://productcraft.co/docs/platform/api-reference/post-v1-auth-password-reset.md) ## Introspect Who is calling: the session, its membership and effective policy in a workspace, and what a workspace API key resolves to. Product APIs call these to authorise requests. - [get `/v1/introspect` Introspect current user with workspace list](https://productcraft.co/docs/platform/api-reference/get-v1-introspect.md) - [get `/v1/introspect/workspaces/{workspace_id}` Introspect caller's membership + effective policy + enabled services in a workspace](https://productcraft.co/docs/platform/api-reference/get-v1-introspect-workspaces-workspace-id.md) - [post `/v1/introspect/api-key` Resolve a Platform API Key (PAK) to its workspace + IAM-style policy.](https://productcraft.co/docs/platform/api-reference/post-v1-introspect-api-key.md) ## Jwks The public keys that verify platform-issued JWTs. - [get `/.well-known/jwks.json` Public JWKS for verifying platform-issued JWTs (issuer `https://api.auth.productcraft.co`).](https://productcraft.co/docs/platform/api-reference/get-well-known-jwks-json.md) ## Me The signed-in account: profile, avatar and console guide preferences. - [get `/v1/me` Read the caller's account profile.](https://productcraft.co/docs/platform/api-reference/get-v1-me.md) - [patch `/v1/me/profile` Update the caller's profile.](https://productcraft.co/docs/platform/api-reference/patch-v1-me-profile.md) - [post `/v1/me/avatar` Upload (or replace) the caller's avatar.](https://productcraft.co/docs/platform/api-reference/post-v1-me-avatar.md) - [delete `/v1/me/avatar` Clear the caller's avatar and delete the stored object.](https://productcraft.co/docs/platform/api-reference/delete-v1-me-avatar.md) - [get `/v1/me/hidden-guides` List the getting-started guides the caller has hidden.](https://productcraft.co/docs/platform/api-reference/get-v1-me-hidden-guides.md) - [delete `/v1/me/hidden-guides` Show every getting-started guide again.](https://productcraft.co/docs/platform/api-reference/delete-v1-me-hidden-guides.md) - [put `/v1/me/hidden-guides/{key}` Hide a getting-started guide for the caller.](https://productcraft.co/docs/platform/api-reference/put-v1-me-hidden-guides-key.md) - [delete `/v1/me/hidden-guides/{key}` Show a hidden getting-started guide again.](https://productcraft.co/docs/platform/api-reference/delete-v1-me-hidden-guides-key.md) ## Oauth-Authorization-Server The OAuth 2.1 authorization server third-party clients (MCP assistants) connect through, and the apps connected to your account or workspace. The protocol endpoints (registration, token, revocation, introspection, consent, delegated decisions) are for OAuth clients and the MCP server, not the SDKs. - [get `/.well-known/oauth-authorization-server` OAuth 2.1 authorization server metadata (RFC 8414)](https://productcraft.co/docs/platform/api-reference/get-well-known-oauth-authorization-server.md) - [post `/v1/oauth/register` Register an OAuth client dynamically (RFC 7591)](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-register.md) - [get `/v1/oauth/register/{client_id}` Read a client registration (RFC 7592)](https://productcraft.co/docs/platform/api-reference/get-v1-oauth-register-client-id.md) - [put `/v1/oauth/register/{client_id}` Update a client registration (RFC 7592)](https://productcraft.co/docs/platform/api-reference/put-v1-oauth-register-client-id.md) - [get `/v1/oauth/authorize` OAuth 2.1 authorization endpoint](https://productcraft.co/docs/platform/api-reference/get-v1-oauth-authorize.md) - [get `/v1/oauth/consent/{request_id}` Read a pending consent request](https://productcraft.co/docs/platform/api-reference/get-v1-oauth-consent-request-id.md) - [post `/v1/oauth/consent/{request_id}` Record the human’s consent decision](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-consent-request-id.md) - [get `/v1/oauth/connections` List clients this human has connected](https://productcraft.co/docs/platform/api-reference/get-v1-oauth-connections.md) - [delete `/v1/oauth/connections/{grant_id}` Disconnect a client](https://productcraft.co/docs/platform/api-reference/delete-v1-oauth-connections-grant-id.md) - [get `/v1/oauth/workspaces/{workspace_id}/connections` List every client connected to a workspace](https://productcraft.co/docs/platform/api-reference/get-v1-oauth-workspaces-workspace-id-connections.md) - [delete `/v1/oauth/workspaces/{workspace_id}/connections/{grant_id}` Disconnect a client on behalf of the workspace](https://productcraft.co/docs/platform/api-reference/delete-v1-oauth-workspaces-workspace-id-connections-grant-id.md) - [post `/v1/oauth/workspaces/{workspace_id}/connections/{grant_id}/restore` Lift a workspace revocation so the member may reconnect](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-workspaces-workspace-id-connections-grant-id-restore.md) - [post `/v1/oauth/token` OAuth 2.1 token endpoint](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-token.md) - [post `/v1/oauth/revoke` Revoke a token (RFC 7009)](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-revoke.md) - [post `/v1/oauth/introspect` Introspect an access token (RFC 7662)](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-introspect.md) - [post `/v1/oauth/delegated/authorize` Decide one action for a delegated access token](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-delegated-authorize.md) - [post `/v1/oauth/delegated/authorize-batch` Decide many actions for a delegated access token](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-delegated-authorize-batch.md) - [post `/v1/oauth/delegated/downstream-assertion` Mint a short-lived assertion for one downstream service](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-delegated-downstream-assertion.md) - [post `/v1/oauth/delegated/authorize-assertion` Decide one action for a downstream assertion](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-delegated-authorize-assertion.md) - [post `/v1/oauth/delegated/first-tool-call` Record that a delegated connection made its first tool call](https://productcraft.co/docs/platform/api-reference/post-v1-oauth-delegated-first-tool-call.md) ## Platform-Api-Keys Workspace API keys (`pcft_live_…`): mint from a preset or managed policies, list, rotate, rebind, revoke, and ask a key what it can do (`api-keys/self`). - [get `/v1/workspaces/{workspace_slug}/api-keys` List the API keys in this workspace](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-api-keys.md) - [post `/v1/workspaces/{workspace_slug}/api-keys` Mint a new PAK.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-api-keys.md) - [get `/v1/workspaces/{workspace_slug}/api-keys/presets` List the ready-made permission sets a workspace key can be minted with (`preset` on create), each with a label, a…](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-api-keys-presets.md) - [post `/v1/workspaces/{workspace_slug}/api-keys/preview` Describe the key a mint with this `preset` or these `policy_ids` would create, without creating anything: what it…](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-api-keys-preview.md) - [post `/v1/workspaces/{workspace_slug}/api-keys/{id}/rotate` Mint a replacement for an existing PAK, carrying its name, description and policy bindings over.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-api-keys-id-rotate.md) - [patch `/v1/workspaces/{workspace_slug}/api-keys/{id}/bindings` Replace the managed-policy bindings on a PAK.](https://productcraft.co/docs/platform/api-reference/patch-v1-workspaces-workspace-slug-api-keys-id-bindings.md) - [get `/v1/workspaces/{workspace_slug}/api-keys/{id}` Get a single PAK by id.](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-api-keys-id.md) - [patch `/v1/workspaces/{workspace_slug}/api-keys/{id}` Update a PAK’s name or description (does not touch bindings).](https://productcraft.co/docs/platform/api-reference/patch-v1-workspaces-workspace-slug-api-keys-id.md) - [delete `/v1/workspaces/{workspace_slug}/api-keys/{id}` Revoke a PAK.](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug-api-keys-id.md) - [get `/v1/api-keys/self` Describe the workspace key making this request: its name, workspace, expiry and what it may do in plain sentences.](https://productcraft.co/docs/platform/api-reference/get-v1-api-keys-self.md) ## Session The signed-in account's sessions: list them and sign out of one or all others. - [get `/v1/session` List active sessions](https://productcraft.co/docs/platform/api-reference/get-v1-session.md) - [post `/v1/session/revoke-others` Sign out every other session of the caller, keeping the one this request was made with.](https://productcraft.co/docs/platform/api-reference/post-v1-session-revoke-others.md) - [delete `/v1/session/{id}` Revoke one of the caller's own sessions.](https://productcraft.co/docs/platform/api-reference/delete-v1-session-id.md) ## Verification Verify the account email address with the emailed code, or send a new code. - [post `/v1/verification/verify` Verify an email code](https://productcraft.co/docs/platform/api-reference/post-v1-verification-verify.md) - [post `/v1/verification/resend` Resend verification email](https://productcraft.co/docs/platform/api-reference/post-v1-verification-resend.md) ## Workspace-Audit-Logs The workspace audit log and the cross-product audit feed, with NDJSON or CSV export. - [get `/v1/workspaces/{workspace_slug}/audit-logs` List workspace audit log entries, newest first.](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-audit-logs.md) - [get `/v1/workspaces/{workspace_slug}/audit-logs/export` Stream the workspace audit log as NDJSON or CSV, applying the same `?action=` / `?actor_id=` / `?since=` / `?until=`…](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-audit-logs-export.md) - [get `/v1/workspaces/{workspace_slug}/audit-feed` Unified workspace audit feed (cursor-paginated)](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-audit-feed.md) ## Workspace-Policies Managed IAM-style policies that roles and API keys are bound to, and the action catalog they are written against. - [get `/v1/workspaces/{workspace_slug}/policies` List managed policies in a workspace, alphabetically.](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-policies.md) - [post `/v1/workspaces/{workspace_slug}/policies` Create a managed policy.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-policies.md) - [get `/v1/workspaces/{workspace_slug}/policies/actions/catalog` List every known workspace action (catalog of statement actions).](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-policies-actions-catalog.md) - [get `/v1/workspaces/{workspace_slug}/policies/{policy_id}` Get a managed policy by id](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-policies-policy-id.md) - [patch `/v1/workspaces/{workspace_slug}/policies/{policy_id}` Update a managed policy.](https://productcraft.co/docs/platform/api-reference/patch-v1-workspaces-workspace-slug-policies-policy-id.md) - [delete `/v1/workspaces/{workspace_slug}/policies/{policy_id}` Delete a managed policy.](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug-policies-policy-id.md) ## Workspace-Roles Custom and system roles in a workspace and the policy each grants. - [get `/v1/workspaces/{workspace_slug}/roles` List roles in a workspace.](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-roles.md) - [post `/v1/workspaces/{workspace_slug}/roles` Create a new custom role.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-roles.md) - [get `/v1/workspaces/{workspace_slug}/roles/{role_id}` Get a role + its permissions](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-roles-role-id.md) - [patch `/v1/workspaces/{workspace_slug}/roles/{role_id}` Update a role or replace its permission set.](https://productcraft.co/docs/platform/api-reference/patch-v1-workspaces-workspace-slug-roles-role-id.md) - [delete `/v1/workspaces/{workspace_slug}/roles/{role_id}` Delete a custom role (fails if it has members).](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug-roles-role-id.md) ## Workspace-Services Turn products (Auth, Mail, Waitlist, Social, Trawl, Flags, Notify) on or off for a workspace, with their settings. - [get `/v1/workspaces/{workspace_slug}/services` List services activated on this workspace.](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-services.md) - [post `/v1/workspaces/{workspace_slug}/services/{service}` Enable (or re-enable) a service for this workspace](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-services-service.md) - [delete `/v1/workspaces/{workspace_slug}/services/{service}` Disable a service (settings are retained)](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug-services-service.md) - [patch `/v1/workspaces/{workspace_slug}/services/{service}/settings` Replace the settings jsonb for an active service](https://productcraft.co/docs/platform/api-reference/patch-v1-workspaces-workspace-slug-services-service-settings.md) ## Workspace-Stats Workspace dashboard totals and a daily series of admin changes. - [get `/v1/workspaces/{workspace_id}/stats` Workspace stats](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-id-stats.md) ## Workspaces Workspaces, their members and invites. Platform routes name a workspace by its slug, positionally (`workspaces.retrieve("acme")`); the product APIs bind `workspace_id` instead. - [get `/v1/workspaces` List workspaces the current user belongs to](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces.md) - [post `/v1/workspaces` Create a new workspace.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces.md) - [get `/v1/workspaces/{workspace_slug}` Get workspace details](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug.md) - [patch `/v1/workspaces/{workspace_slug}` Update workspace display name, slug, or settings.](https://productcraft.co/docs/platform/api-reference/patch-v1-workspaces-workspace-slug.md) - [delete `/v1/workspaces/{workspace_slug}` Delete a workspace (requires workspace.delete).](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug.md) - [post `/v1/workspaces/{workspace_slug}/avatar` Upload (or replace) the workspace identity avatar.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-avatar.md) - [delete `/v1/workspaces/{workspace_slug}/avatar` Clear the workspace avatar and delete the stored object.](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug-avatar.md) - [get `/v1/workspaces/{workspace_slug}/members` List workspace members, oldest join first.](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-members.md) - [patch `/v1/workspaces/{workspace_slug}/members/{account_id}/role` Update a member's role.](https://productcraft.co/docs/platform/api-reference/patch-v1-workspaces-workspace-slug-members-account-id-role.md) - [delete `/v1/workspaces/{workspace_slug}/members/{account_id}` Remove a member from a workspace (or self-leave)](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug-members-account-id.md) - [post `/v1/workspaces/invites/accept` Accept a workspace invite by code.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-invites-accept.md) - [get `/v1/workspaces/{workspace_slug}/invites` List workspace invites, newest first.](https://productcraft.co/docs/platform/api-reference/get-v1-workspaces-workspace-slug-invites.md) - [post `/v1/workspaces/{workspace_slug}/invites` Create a workspace invite link.](https://productcraft.co/docs/platform/api-reference/post-v1-workspaces-workspace-slug-invites.md) - [delete `/v1/workspaces/{workspace_slug}/invites/{invite_id}` Revoke a workspace invite.](https://productcraft.co/docs/platform/api-reference/delete-v1-workspaces-workspace-slug-invites-invite-id.md) --- title: "Auth Documentation" description: "Wire up multi-tenant auth end-to-end: apps, users, roles, tokens, JWKS. Getting started, core concepts, full API reference, and integration guides." url: https://productcraft.co/docs/auth --- Auth docs # Auth. Authentication and authorisation for multi-tenant products. This documentation covers everything you need to integrate Auth into your application — from first API call to production deployment. Browse ## What you’ll find here - [Getting started](https://productcraft.co/docs/auth/getting-started.md): Go from zero to a working auth integration in under ten minutes. Create an App, issue tokens, and verify permissions.Read more → - [Core concepts](https://productcraft.co/docs/auth/concepts.md): Understand Apps, Users, Roles, Permissions, and Tokens. Learn how Auth models multi-tenancy and access control.Read more → - [API reference](https://productcraft.co/docs/auth/api-reference.md): Complete endpoint documentation with request and response examples for every resource in the Auth API.Read more → - [Guides](https://productcraft.co/docs/auth/guides.md): Step-by-step walkthroughs for common patterns: SaaS onboarding, service-to-service auth, invite flows, and more.Read more → - [Node.js SDK](https://productcraft.co/docs/sdks.md): Install @productcraft/auth for typed sign-in, OAuth sign-in (Apple, Google, GitHub), and JWT verification with a built-in JWKS cache.Read more → Reference ## Base URL ``` https://api.auth.productcraft.co/v1 # Auth-admin (workspace + app management) https://api.auth.productcraft.co//v1 # Consumer API (end-user auth for ONE of your apps) ``` All endpoints are relative to this base URL. Requests must include an `Authorization` header with a valid bearer token unless otherwise noted. Reference ## Authentication Auth issues two types of tokens: - **User tokens (JWT)** for authenticating users. Issued on signup or signin, verified locally via JWKS or through the introspection endpoint. - **M2M tokens (JWT)** for service-to-service authentication. Issued via client credentials exchange, scoped to specific permissions. [Start with the quickstart](https://productcraft.co/docs/auth/getting-started.md) --- title: "Getting started | Auth Docs" description: "Add sign-up and sign-in to your product in ten minutes: create an app, sign up a user, read their profile, and verify the token in your backend. Node SDK and curl." url: https://productcraft.co/docs/auth/getting-started --- [Auth docs](https://productcraft.co/docs/auth.md) Getting started # Quickstart. Sign-up and sign-in in seven steps. By the end you have an app, a signed-up user, and a token your own backend verifies. Every step shows the Node SDK first and the same call with curl. Plan ten minutes. ## Before you start - A ProductCraft workspace with Auth turned on. Sign up at [console.productcraft.co](https://console.productcraft.co) if you don't have one. - A **workspace API key** (`pcft_live_…`) with the `auth.*` actions: in the console go to **Workspace → API keys → New API key**. The key is shown once, so put it in an environment variable straight away. - Your workspace id: the `id` this call returns for your workspace: `curl https://api.platform-auth.productcraft.co/v1/workspaces -H "authorization: Bearer $PRODUCTCRAFT_API_KEY"`. - For the SDK: Node 20.3 or later and `npm install @productcraft/auth`. The samples use `@productcraft/auth` 1.0. ```dotenv title=".env" PRODUCTCRAFT_API_KEY=pcft_live_... PRODUCTCRAFT_WORKSPACE_ID= ``` Step 1 ## Create an app An app is one pool of users with its own roles, settings and signing keys. You can also create it in the console (Auth → New app); in code it is one call. Pick the slug with care: it is part of every sign-in URL and of the `iss` and `aud` claims of every token, so changing it later breaks existing tokens and integrations. This guide uses `acme`. **Node SDK** ```ts title="setup.ts" import { Auth } from "@productcraft/auth"; // Your workspace API key: it manages apps, so keep it on the server. // Reads PRODUCTCRAFT_API_KEY from the environment const auth = new Auth(); const app = await auth.apps.create({ slug: "acme", display_name: "Acme", workspace_id: process.env.PRODUCTCRAFT_WORKSPACE_ID!, }); ``` **curl** ```bash title="POST /v1/apps" curl https://api.auth.productcraft.co/v1/apps \ -H "authorization: Bearer $PRODUCTCRAFT_API_KEY" \ -H 'content-type: application/json' \ -d '{ "slug": "acme", "display_name": "Acme", "workspace_id": "" }' ``` The response is the app, including its `id` (used in step 2). Three roles come with it: **owner**, **admin** and **member**; new users get **member**. Step 2 ## Turn on sign-up New apps start with sign-up off, so a sign-up call is refused (403) until you switch it on. In the console: the app's Settings → Sign-in policy → Signup enabled. In code: **Node SDK** ```ts title="setup.ts" await auth.admin.app(app.id).authConfig.update({ signup_enabled: true }); ``` **curl** ```bash title="PATCH /v1/apps/:appId/auth-config" curl -X PATCH https://api.auth.productcraft.co/v1/apps//auth-config \ -H "authorization: Bearer $PRODUCTCRAFT_API_KEY" \ -H 'content-type: application/json' \ -d '{ "signup_enabled": true }' ``` The other defaults suit most products: passwords need 12+ characters with an uppercase letter and a number, sessions last 7 days, access tokens 1 hour. Change them on the same settings page when you need to. Want an invite-only product instead? Leave sign-up off and [invite users](#invite). Step 3 ## Sign up your first user Sign-up and sign-in are public calls: no key, just the app slug. Run them from your backend or straight from your frontend. **Node SDK** ```ts title="signup.ts" import { Auth } from "@productcraft/auth"; const consumer = new Auth().consumer("acme"); const signup = await consumer.signup({ email: "ada@example.com", username: "ada", password: "CorrectHorse42Battery", display_name: "Ada Lovelace", }); // Typed by the response: tokens straight away, unless the app // requires a verified email first. const tokens = "access_token" in signup ? signup : null; ``` **curl** ```bash title="POST /acme/v1/auth/signup" curl https://api.auth.productcraft.co/acme/v1/auth/signup \ -H 'content-type: application/json' \ -d '{ "email": "ada@example.com", "username": "ada", "password": "CorrectHorse42Battery", "display_name": "Ada Lovelace" }' ``` ```json title="Response" { "access_token": "eyJhbGc...", "refresh_token": "eyJhbGc...", "token_type": "Bearer", "expires_in": 3600 } ``` A password that misses the policy returns 400 with a message naming the rule. The email starts unverified; the [verification guide](https://productcraft.co/docs/auth/guides/07-verification-and-reset.md) covers confirming it. **Keep bots out of sign-up.** A public sign-up form attracts bots that sign up with other people's addresses, and every one of those accounts is sent a verification email. Turn on _Bot protection_ in the app's Auth settings (Cloudflare Turnstile or hCaptcha: paste the site key and the secret key), render the provider's widget on your sign-up page, and send its response as `bot_protection_token`. Auth checks the token with the provider before it looks at the email or password. No token is 400 `BOT_PROTECTION_REQUIRED`, a rejected one is 403 `BOT_PROTECTION_FAILED`, and if the provider can't be reached the sign-up is refused with 503 `BOT_PROTECTION_UNAVAILABLE` rather than let through. Tokens are single-use, so reset the widget after a failed attempt. If your backend creates the accounts, turn on `signup_requires_pak` instead (or as well): sign-up then needs a workspace API key, so nobody can call it directly. A backend that also uses bot protection forwards the token its browser received. ```bash title="POST /acme/v1/auth/signup (bot protection on)" curl https://api.auth.productcraft.co/acme/v1/auth/signup \ -H 'content-type: application/json' \ -d '{ "email": "ada@example.com", "username": "ada", "password": "CorrectHorse42Battery", "bot_protection_token": "" }' ``` Step 4 ## Sign in identifier takes the username or the primary email. The response has the same shape as sign-up. **Node SDK** ```ts title="signin.ts" const result = await consumer.signin({ identifier: "ada", password: "CorrectHorse42Battery", }); if (result.result !== "session") { // The user has two-step sign-in (MFA) on: result is a challenge. throw new Error("This user has MFA on: finish the challenge first."); } ``` **curl** ```bash title="POST /acme/v1/auth/signin" curl https://api.auth.productcraft.co/acme/v1/auth/signin \ -H 'content-type: application/json' \ -d '{ "identifier": "ada", "password": "CorrectHorse42Battery" }' ``` A wrong password and an unknown user both return 401 `Invalid credentials`, so nobody can probe which usernames exist. A suspended user gets 403, and too many failed attempts get 429. Step 5 ## Read the user's profile Call /me with the user's access token. It answers who is signed in. **Node SDK** ```ts title="me.ts" // Bind an Auth instance to the user's access token. const asUser = new Auth({ auth: { type: "bearer", token: tokens!.access_token }, }); const me = await asUser.consumer("acme").me.retrieve(); console.log(me.email, me.email_verified_at); ``` **curl** ```bash title="GET /acme/v1/me" curl https://api.auth.productcraft.co/acme/v1/me \ -H 'authorization: Bearer ' ``` ```json title="Response (excerpt)" { "id": "648616c8-...", "username": "ada", "display_name": "Ada Lovelace", "role": "member", "email": "ada@example.com", "email_verified_at": null } ``` For what the user may do, call `GET /acme/v1/me/permissions` with the same token; it returns the role and its permission list. The [roles guide](https://productcraft.co/docs/auth/guides/03-roles-and-permissions.md) covers defining your own. Step 6 ## Verify tokens in your backend Don't call /me on every request. Verify the access token locally against the app's public keys (JWKS): the SDK fetches and caches them for you. **Node SDK** ```ts title="verify.ts" // Checks signature, expiry, issuer and audience for this app. const claims = await consumer.verifyToken(tokens.access_token); console.log(claims.sub, claims.role); ``` **Any JWT library** ```ts title="verify.ts (jose)" import * as jose from "jose"; const APP_SLUG = "acme"; const JWKS = jose.createRemoteJWKSet( new URL(`https://api.auth.productcraft.co/${APP_SLUG}/.well-known/jwks.json`), ); const { payload } = await jose.jwtVerify(accessToken, JWKS, { issuer: `https://api.auth.productcraft.co/${APP_SLUG}`, audience: APP_SLUG, }); ``` Each app has its own signing keys. Pin the issuer `https://api.auth.productcraft.co/acme` and the JWKS URL `https://api.auth.productcraft.co/acme/.well-known/jwks.json` to _your_ app, so a token from another app can never pass. Any JWT library works the same way (PyJWT, jsonwebtoken, golang-jwt); the [token verification guide](https://productcraft.co/docs/auth/guides/06-verify-tokens.md) has more. Step 7 ## Refresh and sign out Access tokens last an hour. Trade the refresh token for a new pair; sign out by revoking the session. **Node SDK** ```ts title="session.ts" const next = await consumer.refresh({ refresh_token: tokens!.refresh_token }); // Later, to sign out: await consumer.logout({ refresh_token: next.refresh_token }); ``` **curl** ```bash title="POST /acme/v1/auth/refresh, /logout" curl https://api.auth.productcraft.co/acme/v1/auth/refresh \ -H 'content-type: application/json' \ -d '{ "refresh_token": "" }' curl https://api.auth.productcraft.co/acme/v1/auth/logout \ -H 'content-type: application/json' \ -d '{ "refresh_token": "" }' ``` Every refresh replaces the refresh token. Reusing an old one after a 60-second grace period is treated as theft and ends the whole session. After sign-out, Auth rejects the access token at once (401); a backend that only verifies locally keeps accepting it until it expires, at most an hour. From your backend ## Call your app with an app key Admin calls from your server (list, read and update users) use an app key. It belongs to one app and can do only what its permissions allow. In the console, open your app: **Get started → Quickstart** shows this code with your app's values, and **Mint a key for this** creates a key that can list and read users and puts it in the code, so it runs as pasted. Keys with other permissions are under **Integration → API keys**. Keys on a production app start with `hdk_live_`, on a staging or development app with `hdk_test_`. **Node SDK** ```bash title="Install" npm install @productcraft/auth ``` ```dotenv title=".env" PRODUCTCRAFT_AUTH_APP_KEY=your-app-key ``` ```ts title="auth.ts" import { Auth } from "@productcraft/auth"; // Sign-up, sign-in and token checks are public: no key needed. const app = new Auth().consumer("acme"); // Sign a user in. `result` is "session", or a step to finish first (MFA). export async function signIn(email: string, password: string) { return app.signin({ identifier: email, password }); } // Verify the access token your frontend sends. Checks the signature, // expiry, issuer (https://api.auth.productcraft.co/acme) and audience. export async function currentUser(accessToken: string) { const claims = await app.verifyToken(accessToken); return { id: claims.sub, role: claims.role }; } // Admin calls from your server use the app key. Never ship it to a browser. const admin = new Auth({ apiKey: process.env.PRODUCTCRAFT_AUTH_APP_KEY }).consumer("acme"); export async function listUsers() { const page = await admin.users.list({ limit: 5 }); return page.data; } ``` **Next.js** ```bash title="Install" npm install jose ``` ```title=".env.local" PRODUCTCRAFT_AUTH_APP_KEY=your-app-key ``` ```ts title="lib/auth.ts" import { createRemoteJWKSet, jwtVerify } from "jose"; const JWKS = createRemoteJWKSet(new URL("https://api.auth.productcraft.co/acme/.well-known/jwks.json")); // Throws when the token is forged, expired or from another app. export async function verifyAccessToken(token: string) { const { payload } = await jwtVerify(token, JWKS, { issuer: "https://api.auth.productcraft.co/acme", audience: "acme", }); return payload; } ``` ```ts title="app/api/users/route.ts" import { verifyAccessToken } from "@/lib/auth"; export async function GET(request: Request) { const token = request.headers.get("authorization")?.replace(/^Bearer /, ""); try { await verifyAccessToken(token ?? ""); } catch { return Response.json({ error: "Sign in first" }, { status: 401 }); } const res = await fetch("https://api.auth.productcraft.co/acme/v1/admin/users?limit=5", { headers: { authorization: `Bearer ${process.env.PRODUCTCRAFT_AUTH_APP_KEY}` }, cache: "no-store", }); return Response.json(await res.json(), { status: res.status }); } ``` **curl** ```bash title="Terminal" export PRODUCTCRAFT_AUTH_APP_KEY=your-app-key # The first five users of this app curl "https://api.auth.productcraft.co/acme/v1/admin/users?limit=5" \ -H "authorization: Bearer $PRODUCTCRAFT_AUTH_APP_KEY" # The public keys your backend verifies access tokens with curl https://api.auth.productcraft.co/acme/.well-known/jwks.json ``` A key without the permission a call needs gets 403, a key for another app or a revoked key gets 401. The workspace API key (`pcft_live_…`) from the steps above is a different credential: it manages apps, not one app's users. Instead of sign-up ## Invite users For an invite-only product, leave sign-up off. Your backend creates an invite with the workspace API key; Auth emails the code and also returns it. The user accepts with a password and is signed in. **Node SDK** ```ts title="invite.ts" const invite = await auth.admin.app(app.id).endUsers.invites.create({ email: "grace@example.com", role_name: "member", }); // The user accepts with the code from the email: const invited = await consumer.acceptInvite({ code: invite.code, password: "CorrectHorse42Battery", }); ``` **curl** ```bash title="POST invites, then accept-invite" curl https://api.auth.productcraft.co/v1/apps//end-users/invites \ -H "authorization: Bearer $PRODUCTCRAFT_API_KEY" \ -H 'content-type: application/json' \ -d '{ "email": "grace@example.com", "role_name": "member" }' curl https://api.auth.productcraft.co/acme/v1/auth/accept-invite \ -H 'content-type: application/json' \ -d '{ "code": "", "password": "CorrectHorse42Battery" }' ``` These are users of _your_ product. Teammates who help run the app are invited to your workspace in the [console](https://console.productcraft.co) instead. Next ## Where to go from here - [Roles and permissions](https://productcraft.co/docs/auth/guides/03-roles-and-permissions.md) — decide who may do what. - [Email verification and password reset](https://productcraft.co/docs/auth/guides/07-verification-and-reset.md). - [Passkeys](https://productcraft.co/docs/auth/guides/10-passkeys.md) and [Sign in with Apple](https://productcraft.co/docs/auth/guides/09-signin-with-apple.md). [Read the guides](https://productcraft.co/docs/auth/guides.md) [Full API reference](https://productcraft.co/docs/auth/api-reference.md) --- title: "Tenant API keys | Auth Docs" description: "API keys your customers create for their own automation against your app: how they differ from Platform API keys and app keys, the key format, expiry, the scope ceiling, rotate vs revoke, revocation latency, orphaned keys and the suspend switch." url: https://productcraft.co/docs/auth/concepts/tenant-api-keys --- [Core concepts](https://productcraft.co/docs/auth/concepts.md) Core concepts # Tenant API keys. Let the members of your customers' tenants create API keys for their own automation, scoped to one tenant and to scopes your app defines. Auth stores, issues and verifies the keys; your app decides what they may do. ## What they are If your product is B2B and built on [tenants](https://productcraft.co/docs/auth/guides/04-tenants.md), your customers will ask for API keys: to drive your API from CI, to run their end-to-end tests, to script a nightly export. A tenant API key is that key. A member of a tenant creates it, it belongs to that tenant, and it carries a subset of the scopes your app offers. A tenant API key never authenticates against any ProductCraft API. Your customer sends it to _your_ API. Your backend asks Auth whether the key is active (one introspection call, which you cache), learns which tenant and scopes it carries, and authorises the request itself. | Key | Prefix | Belongs to | Used for | | --- | --- | --- | --- | | Platform API key | pcft_live_ | A ProductCraft workspace (you) | Your backend calling ProductCraft APIs, including introspecting tenant API keys. | | App API key | hdk_live_ / hdk_test_ | One Auth app (you) | Your backend calling the app's admin lane on Auth. | | Tenant API key | pctk_live_ / pctk_test_ | One tenant of your app, created by one of its members | Your customer's CI, scripts and e2e tests calling YOUR app's API. | Tenant API keys are off until you turn them on for an app. The [adoption guide](https://productcraft.co/docs/auth/guides/14-tenant-api-keys.md) walks through enabling them, verifying them in your backend, and letting your customers manage them. ## Format ```title="pctk___" pctk_live_4fQ2aZ0000000000000000000000000000000000000_1a2B3c │ │ │ │ │ │ │ └─ 6 chars: CRC32 of the body, base62 │ │ └─ 43 chars: 32 random bytes, base62 │ └─ live (production app) or test (staging / development app) └─ the same prefix for every app Regex: ^pctk_(live|test)_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}$ ``` One fixed prefix for every app means one pattern for your log redaction and for secret scanners. The environment comes from your app: a production app mints `pctk_live_` keys, any other app mints `pctk_test_`. **The checksum is a typo filter, not a security control.** Anyone can compute a valid checksum for a random body. Check it before you do anything else, so a mangled or truncated key is refused without a cache lookup or a network call, but never treat a valid checksum as evidence that a key exists. Flood protection is the job of your rate limits and of Auth's per-app introspection limit. Auth keeps only a SHA-256 hash of the key. The secret is returned once, when the key is created or rotated, with `Cache-Control: no-store`. Afterwards a key is recognisable only by its `key_prefix` (the first 16 characters) and `last4`, and by its id, `tak_…`. ## Scopes and the ceiling Your app publishes its _grantable scopes_: the permission strings a key may carry, such as `disputes.read` or `reports.create` (at most 64, each `.`). A key carries at least one of them. **A key can never do more than the person who created it.** When a member creates or rotates a key, every requested scope must be grantable by the app and held by that member's own tenant role (a tenant owner can grant every grantable scope). Otherwise the request is refused with `TENANT_API_KEY_SCOPE_ABOVE_CEILING` and the offending scopes in `details.scopes`. The ceiling keeps applying after the key exists. Introspection returns the creator's _current_ tenant role, and your backend intersects the key's scopes with that role's permissions on every request. If the creator is demoted, their keys shrink with them. Role drift can only narrow what a key does. ## Expiry Every key expires. At creation the member picks 7, 30, 90 or 365 days; your app sets the default (90 unless you change it) and the maximum. There is no “never expires” option: these keys live in CI systems, and a forgotten one should die on its own. Expiry is final. The key's `expires_at` is on every listing and in every introspection answer, so a customer can rotate before it lapses. ## Rotate vs revoke **Rotate** mints a replacement with the same name and scopes and returns its secret once. The outgoing key stops working at once (the default) or keeps working for a grace period of up to 24 hours, so a CI pipeline can switch over without a failed run. The person who rotates becomes the replacement's creator, so the ceiling is checked against _their_ role, and the key now lives as long as _their_ membership. **Revoke** is immediate and final. Revoking a revoked key is a no-op that still succeeds. **If a key leaks, revoke it.** Rotation with a grace period keeps the leaked key alive for that period; rotation exists for planned changes, not for incidents. Revoke the leaked key, then create a new one. ## Revocation latency A revocation takes effect in Auth the moment it is made: the next introspection of that key answers `{"active": false}`. Your backend caches positive answers for up to 30 seconds per server, so a revoked key can keep working against your API until the cached answer runs out. That window is your cache TTL, not a token lifetime: there is no signed token that outlives the revocation. Document it for your customers as “revocation takes effect within 30 seconds” (or whatever TTL you choose below that). ## Orphaned keys A key lives only as long as its creator's membership. When the creator is removed from the tenant or deletes their account, every key they created (or last rotated) is revoked in the same transaction, with reason `member_removed`. When the tenant is deleted, suspended or archived, its keys are revoked with reason `tenant_deleted`; reactivating the tenant does not bring them back. Introspection re-checks membership and tenant status on every call, so a key whose eager revocation was missed is still refused. Such a key shows as `orphaned`. Tell your customers what this means in practice: the CI key Alice created stops working the day Alice leaves the team. Keys that must outlive one person should be rotated by someone who is staying, which makes them the creator. ## Key status | Status | Meaning | | --- | --- | | active | Usable. Introspection answers with the tenant, scopes and creator. | | expired | Past expires_at. Final: an expired key never comes back. | | revoked | Revoked by a tenant member, by you in the console, by a rotation, or because its creator or tenant went away. Final, and it wins over expired. | | orphaned | The creator is no longer a member of the tenant, or the tenant is not active. Introspection treats it as inactive. | | suspended | Every key of the app is switched off (the console's suspend switch, the feature disabled, or the app itself not active). Reversible: keys come back when the switch is turned off. | Introspection deliberately answers `{"active": false}` for every inactive reason, so a caller learns nothing by probing. Your backend can ask why a key it saw go inactive died, for its own audit trail, with `GET /:appSlug/v1/tenant-api-keys/:keyId/status`, which returns the status and the `revoke_reason` (`manual`, `rotated`, `member_removed` or `tenant_deleted`). ## The suspend switch Each app's Settings in the console has a **Suspend all tenant API keys** switch. It is your incident lever: while it is on, introspection answers `{"active": false}` for every key of the app and creating, rotating or revoking keys is refused with `TENANT_API_KEYS_SUSPENDED`. Nothing is revoked, so turning the switch off brings every key that is still within its expiry back. The switch belongs to the console only. Your app pushes its key settings from code on boot, and that push can neither set nor clear the switch, so a deploy in the middle of an incident cannot undo it. For a single tenant, open the app in the console, then **Tenants**, the tenant, and **API keys**: you can see every key (name, prefix and last four characters, scopes, creator, last used, expiry, status) and revoke any of them. ## Who can manage keys Only a signed-in end user can create, rotate or revoke a key, for the tenant they are currently signed into, and only if their tenant role is one of your app's `manage_roles` (by default only `owner`). An M2M token, a Platform API key or a tenant API key can never create a key, so a leaked key cannot mint its replacement. If your app sets a recent-MFA window, creating and rotating also require a second factor verified within that window. Key changes are recorded in the app's audit log (`tenant.api_key.created`, `.rotated`, `.revoked`, `.expired`), each with the tenant it belongs to. Individual introspection calls are not logged; a key's `last_used_at` records use, to the nearest five minutes. ## Limits - 25 active keys per tenant. - Key names are 1 to 64 characters. - At most 64 grantable scopes per app. - Rotation grace: 0 to 24 hours, default 0. - Introspection: 1,200 calls a minute per app, separate from your Platform API key's other calls. Over it the answer is `429` with `Retry-After`, never a false `{"active": false}`. [Adoption guide](https://productcraft.co/docs/auth/guides/14-tenant-api-keys.md) [API reference](https://productcraft.co/docs/auth/api-reference.md) --- title: "Core Concepts | Auth Docs" description: "Understand the building blocks of Auth: Apps, Users, Roles, Permissions, Tokens, and Audit Logs." url: https://productcraft.co/docs/auth/concepts --- [Auth docs](https://productcraft.co/docs/auth.md) Core concepts # Core concepts. Auth is built around seven primitives. Understanding how they relate is the key to a clean integration. ## Apps An App is Auth's isolation boundary — one App per product (or per environment of a product). Your end-users, roles, and signing keys live inside it. If you're modelling B2B customers, those are _Tenants inside_ the App, not separate Apps. All data in Auth is scoped to an App. End-users, roles, permissions, tokens, and audit logs belong to exactly one App and are invisible to all others. Tokens are signed with per-app keys, so a token minted for one App can never verify against another. When you create an App, three system roles for its end-users are provisioned automatically: **owner**, **admin**, and **member**. Managing the App itself (config, roles, credentials) happens through your ProductCraft workspace, not through an end-user account. Key properties - `id` — Unique identifier (UUID) - `slug` — URL-safe identifier, globally unique - `display_name` — Human-readable label - `status` — active, suspended, or archived - `metadata` — JSON blob; Auth keeps the app's auth settings under the `auth` key ## End Users An **End User** is one of the people signing into _your_ product through Auth. Each end-user account belongs to exactly one App — a person who happens to be a customer of two of your apps gets two distinct accounts. (This is a deliberate choice; multi-app identity belongs in a higher-level concept your product owns, not in Auth.) Signup takes a username, an email, and a password. The email becomes the account's primary _contact_ and receives a verification code. At signin the identifier is the username or the primary email — secondary contacts never authenticate. Each user can hold many contacts (email or phone), added through `POST /:appSlug/v1/me/contacts`. OAuth sign-in (Apple, Google, GitHub) and MFA are available per app. Key properties - `id` — Unique identifier (UUID) - `username` — Unique within the app - `display_name` — Human-readable label - `status` — active, suspended, or deactivated - `contacts[]` — One or more email/phone entries with `verified_at`; the primary email doubles as a signin identifier - `metadata` — Arbitrary JSON for your application-specific data ## Roles A Role is a named collection of permissions within an App. Instead of assigning individual permissions to each user, you define roles (like “admin”, “editor”, “viewer”) and assign those roles to users. Roles are App-scoped. An “admin” role in one App is completely independent from an “admin” role in another. Each user holds exactly one role per App, and their effective permissions are the permissions of that role. Every App comes with three system roles that cannot be deleted. Their default grants (editable per app): - **owner** — every permission in the app's catalog - **admin** — manage users and role assignment (`user.read/list/update`, `role.read/assign/revoke`) - **member** — `user.read` and `role.read` only You can create additional custom roles with any combination of the available permissions. ## Permissions Permissions are strings of the form `resource.action`. Auth ships a small system catalog and you can add app-specific entries on top of it. All entries are scoped to the App. ```title="System catalog (shipped with every app)" # User management user.create user.read user.update user.delete user.list # Role management role.create role.read role.update role.delete role.assign role.revoke # Custom permission management permission.create permission.read permission.delete # Sessions and tokens session.revoke token.create ``` Add custom entries through the console — open the app and go to `Identity → Permissions`, then _Create custom permission_ (a resource + action pair) — or via the API (`POST /v1/apps/:appId/permissions`) — for example, `document.read` or `billing.invoice.refund`. Bind both system and custom entries to roles under `Identity → Roles` (each role's _Permissions_ button opens the binding panel). #### Two enforcement lanes — one for end-users, one for M2M Both lanes check the same catalog from the same per-app guard. The token type decides where the perm comes from: - **End-user tokens** carry a `role` claim. The guard resolves the role's permission set per request through a 60-second LRU and checks membership. Permissions are deliberately _not_ baked into the JWT — role-permission edits propagate within ≤60 s without forcing a refresh, and the token stays compact. - **M2M tokens** carry a flat `scopes` claim, set when the credential was minted. The guard checks scope membership directly. #### Admin surface — same auth, both token types The Consumer API exposes an admin lane at `/:appSlug/v1/admin/users/*` that accepts _either_ an end-user token (your signed-in admin user) _or_ an M2M token (a backend cron or service). Both lanes go through the same `@RequireAppPermission` guard — an M2M token with `user.list` scope and an end-user whose role grants `user.list` see the same response shape on `GET /:appSlug/v1/admin/users`. #### Token introspection `POST /:appSlug/v1/oauth/introspect` with `Authorization: Bearer ` returns `{ active, sub, type, exp, iat, iss, aid }` per RFC 7662 — plus `scopes`, `scope`, and `client_id` for M2M tokens. M2M services use it to confirm their own scopes without decoding the JWT by hand. The endpoint refuses cross-token introspection (a body `token` that doesn't match the bearer just returns `{ active: false }`) so a stolen token can't be probed against another active credential. #### Enforcement is opt-in per app New apps default to `enforce_app_permissions: false` — Consumer-API routes accept any valid token regardless of the perm annotation. Once you've authored your roles, flip it to `true` via `PATCH /v1/apps/:appId/auth-config` (or the console's `Settings → Auth config`, where it appears under _Sign-in policy_ as the _Enforce per-app permissions_ toggle). The change propagates within ~60 seconds. #### Reading the effective set For UI gating in your product, call `GET /:appSlug/v1/me/permissions` — it returns the union of the end-user's app-level role and (when the user is signed into a tenant) their tenant-level role. Don't decode the access token looking for a flat list; there isn't one. ## Tokens Auth issues JWTs signed with RS256 by per-app keys. Every token carries claims about the authenticated entity (end-user or service principal). Two flavours: - **End-user tokens** — issued via signup, signin, or refresh. Carry the user's `sub`, `aid` (app id), `role`,`sid` (session), and `org_id` + `org_role` when signed into a tenant. Permissions are _not_ on the token; resolve them from `GET /me/permissions`. - **M2M tokens** — issued via OAuth 2.0 `client_credentials` at `POST /:appSlug/v1/oauth/token`. Carry `type: "m2m"` and a flat `scopes[]` claim drawn from the M2M client's configured scope set. Scopes are present in the token (no per-request resolver needed) because they're explicitly chosen by the customer at credential creation, not inherited from a default role. Access tokens expire after 1 hour. Refresh tokens follow the per-app session duration (default 7 days). Verify tokens locally with the per-app JWKS at `GET /:appSlug/.well-known/jwks.json` (the older `/:appSlug/v1/.well-known/jwks.json` is a permanent alias). ## Tenants (organizations) Optional sub-tenant layer for B2B products. A Tenant is a container _inside_ an App that groups end-users sharing data — your customer's “organization”, “workspace”, or “team”. The wire shape mirrors Auth0/Clerk/WorkOS — JWTs carry `org_id` and `org_role` claims, documented under that name on the API surface. One end-user can be a member of many tenants in one app with a different tenant-scoped role per membership. Switching tenants is a token-rotation step (`POST /:appSlug/v1/auth/switch-tenant`) that re-issues the access + refresh tokens with the new claims. Permission union: when an end-user is signed into a tenant and the route uses `@RequireAppPermission`, the guard merges the app-level role's permissions with the tenant-level role's permissions as a UNION. The tenant role grants _in addition to_ the app role; it never restricts. ## Agent access (OAuth for MCP) Optional, per app. Your users connect an AI agent, such as Claude Code, to your app's MCP server with one command and approve it on your consent page. Auth is the OAuth 2.1 authorization server: client registration, PKCE, tokens bound to your server, rotating refresh tokens, revocation and each user's list of connected agents. Your server applies the user's current role on every call. See [Agent access](https://productcraft.co/docs/auth/agent-access.md). ## Tenant API keys Optional, per app. The members of a tenant can create API keys (`pctk_live_…`) for their own automation: CI jobs, scripts and end-to-end tests that call _your_ API. Each key belongs to one tenant, carries scopes your app defines, never more than its creator's role allows, and always expires. Your backend verifies a key with one cached introspection call. See [Tenant API keys](https://productcraft.co/docs/auth/concepts/tenant-api-keys.md) for the model and [the adoption guide](https://productcraft.co/docs/auth/guides/14-tenant-api-keys.md) to turn them on. ## Audit logs Every state-changing operation in Auth produces an audit log entry. Audit logs are immutable, App-scoped, and queryable via `GET /v1/apps/:appId/audit-logs` (cursor-paginated; filter by `?action=` and `?actor_id=`). Each entry records the actor, action, affected resource, and client IP address. ```json title="Example audit entry" { "id": "...", "app_id": "...", "actor_id": "...", "actor_type": "end_user", "action": "auth.contact_verification.completed", "resource": "account_contact", "resource_id": "...", "metadata": {}, "ip": "203.0.113.42", "created_at": "2026-05-10T15:28:26Z" } ``` ## How it all fits together ``` App (your product, isolated auth boundary) ├── End Users │ ├── username + password │ ├── contacts[] (email, phone) │ └── one app-level Role ├── Tenants (optional B2B sub-orgs) │ ├── memberships[] │ │ └── one tenant-level Role │ └── tenant API keys[] (scopes ⊆ the creator's role) ├── Roles │ └── permissions[] from the per-app catalog ├── M2M credentials │ └── scopes[] from the same catalog ├── Sessions └── Audit log ``` [API reference](https://productcraft.co/docs/auth/api-reference.md) [Guides](https://productcraft.co/docs/auth/guides.md) --- title: "Guides | Auth Docs" description: "Comprehensive guides for integrating Auth: foundations, quickstart, roles + permissions, tenants, M2M, token verification, password and verification flows, webhooks + audit, Sign in with Apple, passkeys, migrating users from another provider, Sign in with Google and GitHub, tenant API keys for your customers." url: https://productcraft.co/docs/auth/guides --- [Auth docs](https://productcraft.co/docs/auth.md) Guides # Build with Auth. Fourteen chapters covering everything from your first authenticated request to multi-tenant role catalogues maintained from CI. Each chapter is self-contained; jump in where the work is. The chapters build on each other but you don't need to read in order. If you've already shipped signup + signin and you want to add roles, jump straight to [03 · Roles + permissions](https://productcraft.co/docs/auth/guides/03-roles-and-permissions.md). If you're wiring a backend cron to call Auth, jump to [05 · M2M](https://productcraft.co/docs/auth/guides/05-m2m-for-backend-services.md) or [06 · Verify tokens](https://productcraft.co/docs/auth/guides/06-verify-tokens.md). Looking for the full HTTP API instead of a guided tour? See [API reference](https://productcraft.co/docs/auth/api-reference.md). Looking for the conceptual model — apps, tenants, the two lanes — see [Core concepts](https://productcraft.co/docs/auth/concepts.md). Chapters ## The series - [01 · Foundations](https://productcraft.co/docs/auth/guides/01-foundations.md): Apps, the two API surfaces (Consumer vs Auth-admin), per-app JWKS, identity primitives, when to reach for each.Read more → - [02 · Quickstart — add Auth to your product](https://productcraft.co/docs/auth/getting-started.md): Create an app, turn on sign-up, sign a user up and in, read /me, verify the token. Node SDK and curl.Read more → - [03 · Roles + permissions](https://productcraft.co/docs/auth/guides/03-roles-and-permissions.md): Per-app RBAC catalogue, system roles, custom roles, granting permissions, caller-narrowing, the Consumer-API admin lane.Read more → - [04 · Multi-tenancy with tenants](https://productcraft.co/docs/auth/guides/04-tenants.md): When to model your customers’ multi-tenancy as Auth tenants, the org_id JWT claim, member roles inside a tenant, switching tenants.Read more → - [05 · M2M for backend services](https://productcraft.co/docs/auth/guides/05-m2m-for-backend-services.md): Issue M2M credentials, exchange for tokens via client_credentials, scope narrowing, last_used_at, secret rotation.Read more → - [06 · Verify tokens in your service](https://productcraft.co/docs/auth/guides/06-verify-tokens.md): Three verification shapes: local JWKS verification, /oauth/introspect for opaque introspection, /verify + /authorize for one-call permission checks.Read more → - [07 · Email verification + password reset](https://productcraft.co/docs/auth/guides/07-verification-and-reset.md): API-key-only mint endpoints, customer-side delivery via your own SMTP, the Mail-integrated shortcut, the consume side.Read more → - [08 · Webhooks + audit](https://productcraft.co/docs/auth/guides/08-webhooks-and-audit.md): Subscribe to user lifecycle events with signed payloads, retry policy, secret rotation. Read the per-app audit log for compliance + debugging.Read more → - [09 · Sign in with Apple](https://productcraft.co/docs/auth/guides/09-signin-with-apple.md): Add federated sign-in to any Auth app. Native iOS / macOS, web redirect flow, encrypted-at-rest provider config, account linking by verified email.Read more → - [10 · Passkeys](https://productcraft.co/docs/auth/guides/10-passkeys.md): Turn on WebAuthn per app, pick a relying-party id you can live with, and ship both flows: a passkey as a second factor, and passwordless sign-in with no password at all.Read more → - [11 · Migrating users from another provider](https://productcraft.co/docs/auth/guides/11-migrating-users.md): Bulk-import your existing users as NDJSON — with their argon2id or bcrypt password hashes, so nobody resets a password — read the per-row error report, watch the credentials upgrade to argon2id on first signin, and export everything back out.Read more → - [12 · Sign in with Google](https://productcraft.co/docs/auth/guides/12-signin-with-google.md): Create a Web application OAuth client in Google Cloud, paste the redirect URI the console shows, save (Auth checks the credentials with Google), Try sign-in, add the button.Read more → - [13 · Sign in with GitHub](https://productcraft.co/docs/auth/guides/13-signin-with-github.md): Register a GitHub OAuth app with the callback URL the console shows, save the Client ID and secret (checked with GitHub on save), Try sign-in, add the button.Read more → - [14 · Let your customers create API keys](https://productcraft.co/docs/auth/guides/14-tenant-api-keys.md): Tenant API keys for your customers’ CI and e2e tests: push the key settings on boot, verify keys with a cache and single-flight, fail closed, proxy key management through your backend, accept keys only on the routes you mark.Read more → Conventions ## What to expect - **Working code in every chapter.** Snippets are `curl` + the `@productcraft/auth` SDK — copy-paste-ready, not pseudocode. Substitute the obvious values (``, ``) and the calls work. - **The hard parts, not just the happy path.** Each chapter calls out the security model, the error paths you care about (409 conflict, 403 policy-deny, 410 expired), and the defaults you should leave alone vs override. - **Cross-references back to the API reference.** Every endpoint mentioned in a guide links to its full definition. Treat guides as the “how do I” and the reference as the “what does this return.” --- title: "01 · Foundations | Auth Guides" description: "The mental model: apps, identities, two API surfaces, per-app JWKS, when to reach for each lane." url: https://productcraft.co/docs/auth/guides/01-foundations --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 01 · Foundations # The Auth mental model. Before any code: what an app is, who an end-user is, why there are two API surfaces, and which one your code should hit. Five minutes of reading saves an hour of confusion. 1 ## What is an Auth app? An **app** in Auth is the identity boundary for one of your products. If you run a SaaS called Acme, you create one Auth app called `acme` and every user of Acme — the people who sign up for Acme, sign in to Acme, hold roles inside Acme — lives inside that app. Apps are owned by a workspace (your team). One workspace can own many apps — useful if you run several products, or if you want a separate `acme-staging` for non-prod environments. Apps are **cryptographically isolated**: each app has its own JWKS (JSON Web Key Set) for signing tokens, so a token signed for `acme` cannot authenticate against `acme-staging`. What apps don't do: they don't talk to each other. Two apps in the same workspace share no identity, no roles, no permissions. If you want unified login across two of your products, that's one app shared by both products — not two apps. 2 ## The two API surfaces Auth serves **two** different HTTP surfaces. They look superficially similar (both speak JSON, both use Bearer auth) but they exist for different actors: For your customer-product ### Consumer API Path: `/:appSlug/v1/*` on `api.auth.productcraft.co`. This is what your customers' end-users authenticate against. Your frontend (or your customer's frontend) hits `/auth/signup`, `/auth/signin`, `/me`, etc. Tokens are signed with the app's own JWKS. Auth lanes here: per-app EndUser JWT (the user's session), per-app M2M JWT (the customer's own backend), or workspace API key on the mint endpoints (workspace-level authority for sensitive flows). For your workspace owners ### Auth-admin Path: `/v1/apps/*` on `api.auth.productcraft.co`. This is what _your_ ops people (or your CI) hit to configure Auth. Create apps, manage app membership, mint M2M credentials, set auth config, read audit logs. Auth lanes: a signed-in ProductCraft account (cookie or platform bearer token), or a workspace API key (`pcft_live_*`) — workspace API keys are accepted on every Auth-admin route, so anything you can do in the console you can do from CI. **Which one do you hit?** If you're building the product itself (your customer signs up here, signs in here), it's the Consumer API. If you're building ops tools (CI provisions a new app for staging; a Terraform module manages your role catalogue), it's Auth-admin. A common mistake: trying to manage Auth apps from the Consumer API (it doesn't expose app CRUD) or trying to sign in an end-user via Auth-admin (it doesn't verify end-user tokens). Pick the surface that matches the actor. 3 ## Identity primitives Three identity primitives live in Auth: - **EndUser** — a person who signed up for one of your apps. Lives in `account` with `app_id` set. Tokens carry a `type: 'end_user'` claim. EndUsers hit the Consumer API. - **M2M client** — a service principal for backend-to-backend traffic. Lives in `m2m_client`. Authenticates via OAuth 2.0 client_credentials grant. Tokens carry a `type: 'm2m'` claim + a `scopes[]` array. - **PlatformUser** — you, the workspace owner. Lives in `platform_auth.account` (different database). Signs in via `auth.productcraft.co`. Hits Auth-admin with a cookie. Plus one credential type that's not a principal: - **Workspace API key** — `pcft_live_*`. A workspace-scoped credential minted by a PlatformUser. Accepted on every Auth-admin route (IaC / CI use) and on the Consumer API mint endpoints (request-verification, request-password-reset). 4 ## Per-app JWKS Every app has its own signing keys. Your service verifies tokens against the app's JWKS, not a global one. When you create an app, Auth provisions a fresh RSA keypair for it. The public half is published at the app's JWKS endpoint; the private half stays inside Auth, encrypted at rest. Tokens for that app (EndUser sessions, M2M access tokens) are signed with the private key. Anyone wanting to verify a token fetches the JWKS and checks the signature. ```http title="JWKS endpoint per app" GET https://api.auth.productcraft.co//.well-known/jwks.json GET https://api.auth.productcraft.co//.well-known/openid-configuration ``` These sit directly under your app's issuer (`https://api.auth.productcraft.co/`), which is what OpenID Connect Discovery specifies — so a conforming client library can be pointed at the issuer and find everything on its own. The older `//v1/.well-known/…` URLs still serve the identical documents and are not going away; existing integrations need no change. `jose` on Node, `PyJWT` on Python,`github.com/lestrrat-go/jwx` on Go — every mainstream JWT library knows how to consume a JWKS endpoint. Cache the response for an hour (the endpoint serves a`Cache-Control: public, max-age=3600`) and refresh on `kid` miss to handle key rotation. When a key rotates, your service doesn't do anything special — your JWKS cache misses on the new `kid`, you refresh, you keep going. Retired keys stay published in the JWKS until every token signed with them has expired, so in-flight tokens don't break mid-rotation. 5 ## What's NOT in Auth Things customers ask about that live elsewhere: - **Workspace identity** — your team's accounts, members, roles inside the workspace. That's the [Platform API](https://productcraft.co/docs/platform.md). - **Transactional email** — the actual SMTP delivery for a verification or reset email. Auth can fire-and-forget an email through [Mail](https://productcraft.co/docs/mail.md) for you, or you can take the code from the response body and route it through your own SMTP. - **Social features** — posts, follows, feeds, moderation. That's [Social](https://productcraft.co/docs/social.md), a different service. [Next: Quickstart →](https://productcraft.co/docs/auth/getting-started.md) --- title: "03 · Roles + permissions | Auth Guides" description: "Per-app RBAC: the system roles you start with, how to add custom roles, how to bind permissions, caller-narrowing, and the M2M-callable admin lane that lets your backend do all of it programmatically." url: https://productcraft.co/docs/auth/guides/03-roles-and-permissions --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 03 · Roles + permissions # Author your role catalogue. Auth ships three system roles per app — owner, admin, member. Most products outgrow that within a quarter. This chapter shows how to add custom roles, bind permissions, and keep the catalogue in sync from your code. 1 ## The per-app permission catalogue Every Auth app sees the same flat list of system permissions out of the box. They're named `.` with dots: ```title="System permissions (app_id IS NULL)" user.create user.read user.update user.delete user.list role.create role.read role.update role.delete role.assign role.revoke permission.create permission.read permission.delete session.revoke token.create ``` On top of those, you can mint **custom** permissions for verbs that only make sense inside your product — `invoice.refund`, `dashboard.export`, `billing.read`. Custom permissions live in the same table with `app_id = your-app-id`; system ones have `app_id NULL`. **Don't confuse these with workspace policy actions.** The strings `auth.read`, `waitlist.update`, `mail.send` also use dots and look similar — but those gate _your workspace owner's_ ability to manage ProductCraft (e.g. mint a workspace API key). The per-app catalogue described here gates _your end-users'_ ability to act inside your app. Two systems, two storage layers, never collide. 2 ## System roles Three roles are seeded when an app is created: - **owner** — every permission in `ALL_APP_PERMISSIONS`. Cannot be deleted. - **admin** — user management (read / list / update) + `role.read` / role assign / revoke. _Not_ role create / update / delete — admins can't mutate the role graph, only assign within it. - **member** — `user.read` + `role.read`. Read-only. The signup default. When Auth adds a permission to the _system_ catalogue, every app's system roles pick it up automatically on the next Auth service restart (owner gets every new system permission; admin + member only their fixed defaults). **Custom permissions are never auto-bound** — not even to owner. After creating one, bind it to roles explicitly (step 4). 3 ## Create a custom role Two lanes do this. Pick the one matching your actor: - **Workspace owner (console, workspace API key from CI)**: `POST /v1/apps//roles` on Auth-admin. Cookie or workspace API key auth. In the console this is the app's `Identity → Roles` tab — _Create role_ takes a name plus an optional description, and each role row then exposes _Permissions_, _Edit_, and _Delete_. - **Customer-product backend (M2M token)**: `POST //v1/admin/roles` on the Consumer admin lane. M2M JWT auth, gated by `role.create`. Both endpoints take the same DTO and create the same row. The difference is who's holding the token. **curl** ```bash title="POST //v1/admin/roles (Consumer admin, M2M token)" curl https://api.auth.productcraft.co/acme/v1/admin/roles \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "name": "billing-admin", "description": "Manages invoices + payment methods. Cannot manage users." }' ``` **SDK (Auth-admin lane)** ```ts title="@productcraft/auth" import { Auth } from "@productcraft/auth"; // Reads PRODUCTCRAFT_API_KEY from the environment const auth = new Auth(); const role = await auth.admin.app("").roles.create({ name: "billing-admin", description: "Manages invoices + payment methods. Cannot manage users.", }); ``` New roles start with **no permissions**. The next step binds them. 4 ## Bind permissions to a role PUT replaces the full permission set on the role. The body is a flat array of . strings — system + custom permissions both accepted. ```bash title="PUT //v1/admin/roles/billing-admin/permissions" curl -X PUT https://api.auth.productcraft.co/acme/v1/admin/roles/billing-admin/permissions \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "permissions": [ "user.read", "invoice.read", "invoice.create", "invoice.refund", "billing.read" ] }' ``` 5 ## Caller-narrowing — the safety net The PUT endpoint enforces a critical rule: the caller cannot grant a permission they don't themselves hold. If your M2M token's `scopes[]` doesn't include `invoice.refund`, the call above 403s with `Cannot grant actions you don't have: invoice.refund`. Same rule for EndUser admins — their effective permission set (from `app_membership.role`) must be a superset of the grant. This prevents an “assign yourself” privilege escalation. A user holding only `role.update` can't use it to rewrite the `owner` role into `[admin, role.assign, *]` and then assign themselves to it. 6 ## Assign a role to a user ```bash title="PATCH //v1/admin/users/:userId/role" curl -X PATCH https://api.auth.productcraft.co/acme/v1/admin/users/648616c8-.../role \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "role_name": "billing-admin" }' ``` For EndUser admin callers, the same caller-narrowing applies: assigning user X to role _billing-admin_ fails if the caller doesn't themselves hold every verb on _billing-admin_. M2M callers only need the `role.assign` scope — the target role's permission set is _not_ narrowed against the M2M scopes, because you already chose what the credential may do when you scoped it. The role change takes effect on the next token refresh — the user's current access token still names the old role until it expires (1h). For instant effect, revoke their sessions via `POST /v1/apps/:appId/end-users/:userId/sessions/revoke-all` — revocation is checked on every request, so existing access tokens die immediately. 7 ## Create custom permissions When you need a verb the system catalogue doesn't have. ```bash title="POST //v1/admin/permissions" curl https://api.auth.productcraft.co/acme/v1/admin/permissions \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "resource": "invoice", "action": "refund", "description": "Mark an invoice as refunded" }' ``` Resource + action each match `^[a-z][a-z0-9_-]{1,47}$`. Conflicts with system permissions (same `resource.action`) return 409. After creating, bind to roles via the `PUT roles/:name/permissions` from step 4. 8 ## Enforce permissions at runtime Two enforcement surfaces: Auth's own Consumer API, and your product's routes. **Auth's Consumer API.** Flip `enforce_app_permissions` to `true` via `PATCH /v1/apps/:appId/auth-config` (or, in the console, the app's `Settings → Auth config` tab — the _Enforce per-app permissions_ toggle under _Sign-in policy_ ). Until you do, permission checks on Consumer-API routes are pass-through — _any valid token for the app can call any admin route_, including `/admin/users`. With the flag on, M2M tokens are checked against their `scopes[]` and EndUser tokens against their role's resolved permissions. The flag is cached for 60s, so flips take up to a minute to bite. **Your own routes.** Resolve the caller's effective permissions with their token via `GET /:appSlug/v1/me/permissions` — `{ role, org_role, permissions[] }` — and check set membership in your middleware. Cache the response for 60s; that's the same TTL Auth's internal resolver uses, so role edits propagate within a minute either way. 9 ## Sync the catalogue from CI The whole point of having an M2M-callable role + permission API: idempotent setup from your deploy pipeline. Pattern your customers like dispute.markets use this for: ```ts title="On-boot role sync (TypeScript)" import { Auth, ConflictError } from "@productcraft/auth"; async function syncRoleCatalogue(appSlug: string, m2mToken: string) { // The consumer-admin lane, authorised by the M2M access token. const app = new Auth({ auth: { type: "bearer", token: m2mToken } }).consumer(appSlug); // 1. Ensure custom permissions exist (409 = already there) const customPerms = [ { resource: "invoice", action: "read", description: "View invoices" }, { resource: "invoice", action: "create", description: "Create invoices" }, { resource: "invoice", action: "refund", description: "Mark invoice refunded" }, ]; for (const p of customPerms) { try { await app.permissions.create(p); } catch (err) { if (!(err instanceof ConflictError)) throw err; } } // 2. Upsert custom roles (list walks every page) const existing = new Set(); for await (const role of app.roles.list()) existing.add(role.name); const desired = [ { name: "billing-admin", description: "Invoices + refunds." }, { name: "support", description: "Read everything; mutate nothing." }, ]; for (const r of desired) { if (!existing.has(r.name)) await app.roles.create(r); } // 3. Bind permissions to roles await app.roles.updatePermissions("billing-admin", { permissions: ["user.read", "invoice.read", "invoice.create", "invoice.refund"], }); await app.roles.updatePermissions("support", { permissions: ["user.read", "user.list", "invoice.read"], }); } ``` Run on every deploy. Idempotent. The M2M token your CI uses needs: `permission.create`, `role.create`, `role.update`, `role.read`, plus every permission it's granting (so the caller-narrowing check passes). **Alternative: workspace API key on Auth-admin.** If you prefer one workspace-level credential to manage all apps in your workspace, hit `/v1/apps/:appId/roles` with a `pcft_live_*` workspace API key. Same idempotent shape, different lane. Use this when your IaC handles multiple apps (staging + prod + dev) from one place. 10 ## When role changes take effect Demoting a user doesn't rewrite their existing access token — the new role name only appears in tokens minted after the change. EndUser access tokens are self-contained 1-hour JWTs that carry the user's role _name_ as a claim. In practice: - **Permissions resolve from the live database, not the token.** The guard uses the role name from the token to look up that role's permissions per request (60s cache), so editing what `admin` can do reaches every `admin`-token holder within a minute. - **Demoting a user is the gap.** A user demoted from `admin` to `member` still has `admin` in their existing access token for up to 1 hour, and the guard will keep returning admin's permissions for it. - **For instant demotion, revoke their sessions** (`POST /v1/apps/:appId/end-users/:userId/sessions/revoke-all`). Session revocation is checked on every request, so the old access token dies immediately and the re-signin mints tokens with the new role. - **Suspending a user is also immediate.** Setting their status to `suspended` (`PATCH .../end-users/:userId/status`) revokes their sessions and 401s every subsequent request — the guard re-checks account status per call. [Next: Multi-tenancy with tenants →](https://productcraft.co/docs/auth/guides/04-tenants.md) --- title: "04 · Multi-tenancy with tenants | Auth Guides" description: "When and how to model your customers’ multi-tenancy as Auth tenants. The org_id JWT claim, tenant memberships, switching tenants, and the tenant-scoped role overlay." url: https://productcraft.co/docs/auth/guides/04-tenants --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 04 · Tenants # Model your customers' multi-tenancy. When the people using your product belong to teams / organisations / workspaces that need separated data, Auth has a built-in primitive for it: tenants. This chapter covers when to use them, how the JWT carries the active-tenant context, and how to switch tenants in-session. 1 ## When do you need tenants? Two product shapes you might be building: - **Flat consumer product.** Each user is their own boundary. Examples: a journaling app, a meditation app. No tenants. The EndUser's account holds everything they own. - **Org-shaped product.** A user belongs to one or more organisations / teams / workspaces (call it what you like in your UI). Data is isolated per org. Examples: a project management tool, a billing platform. _Use tenants._ If your product is org-shaped, you have two choices: - **Tenants in Auth.** Auth manages the membership graph, your JWT carries an `org_id` claim, and your permission resolver unions app-role + tenant-role automatically. - **Roll your own.** Auth just owns identity; your product DB owns the org graph. JWTs only carry the user's app role. Auth's tenants are right when (a) you want a UI primitive for "switch organisation" without a full re-auth, and (b) you want different permissions per-tenant for the same user (admin in one tenant, member in another). Both cases are common; tenants are a real lift but they save a chunk of identity-graph code you'd otherwise write. 2 ## Anatomy of a tenant A tenant has a display_id (tnt_<12hex>) for nice copy-paste, a slug + display name your UI shows, optional metadata, and a list of members each with a role. The schema, at a glance: ``` tenant id uuid display_id "tnt_a1b2c3d4e5f6" (derived from id, short form for UIs) app_id FK → app (tenants are app-scoped) slug "acme-corp" display_name "Acme Corp" status active | suspended | archived metadata jsonb tenant_membership tenant_id FK account_id FK → account role_id FK → role (any role in the same app) joined_at ``` 3 ## Create a tenant Two lanes again — workspace owner via Auth-admin, or customer-product backend via Consumer admin (workspace API key with `auth.tenant.create`). ```bash title="POST //v1/tenants (workspace API key)" curl https://api.auth.productcraft.co/acme/v1/tenants \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "slug": "globex", "display_name": "Globex Corporation", "metadata": { "plan": "team", "seats": 25 } }' ``` ```json { "id": "f9b3...", "display_id": "tnt_a1b2c3d4e5f6", "app_id": "53641fdb-...", "slug": "globex", "display_name": "Globex Corporation", "status": "active", "metadata": { "plan": "team", "seats": 25 }, "created_at": "2026-05-11T...", "updated_at": "2026-05-11T..." } ``` 4 ## Add a member Two shapes: pass account_id for an existing EndUser, or pass email (+ optional username / display_name) to inline-create the account. role_name is required either way — any role in the app. ```bash title="POST //v1/tenants/:id/members" # Existing EndUser curl https://api.auth.productcraft.co/acme/v1/tenants/f9b3.../members \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "account_id": "648616c8-...", "role_name": "admin" }' # New EndUser inline curl https://api.auth.productcraft.co/acme/v1/tenants/f9b3.../members \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "email": "newhire@globex.com", "username": "newhire", "display_name": "New Hire", "role_name": "member" }' ``` The inline-create path creates the account without a password. The customer triggers a password-reset flow to onboard (Chapter 7). 5 ## The org_id JWT claim When the user has signed in 'into' a tenant, their access token carries org_id + org_role. Your routes can read these directly without an extra round-trip. The claim layout: ```json { "sub": "648616c8-...", // EndUser id "aid": "53641fdb-...", // app id "sid": "b1846eb8-...", // session id "role": "member", // app-level role "type": "end_user", "amr": ["pwd"], // auth methods used "org_id": "f9b3...", // active tenant id (if any) "org_role": "admin", // role inside that tenant "iss": "https://api.auth.productcraft.co/acme", // per-app "aud": "acme", // app slug "exp": ... } ``` Your service reads the token, sees `org_id`, scopes the query to that tenant. That's the mechanism — there's no separate "active tenant" sidecar to fetch on every request. 6 ## Tenant-scoped role overlay A user's effective permissions are the **union** of: - The app-level role's permissions (from `app_membership.role`), AND - The tenant-level role's permissions (from `tenant_membership.role`) — only when the token carries an `org_id`. Concretely: Ada is a `member` globally (read-only) but `admin` inside Globex Corp. When her token carries `org_id = globex`, her effective set is member ∪ admin = admin permissions. When she switches out of Globex (org_id absent), she's back to member. This is computed live every request via the `RolePermissionResolver` (60s LRU). Role-permission edits propagate within a minute. 7 ## Switch the active tenant A user with memberships in multiple tenants picks which one is active by calling switch-tenant. Fresh tokens get issued with the new org_id claim; the session row updates so refreshes preserve the context. ```bash title="POST //v1/auth/switch-tenant" curl https://api.auth.productcraft.co/acme/v1/auth/switch-tenant \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "tenant_id": "f9b3..." }' ``` The caller must hold a membership in the target tenant (403 otherwise). Response is a fresh access + refresh token pair, just like signin. Refresh-token rotation runs as usual; the previous refresh token enters the standard 60s grace window. There is no “switch out” call — `tenant_id` is required. Tokens without tenant context come from a fresh signin, which always starts tenant-free. 8 ## List the user's tenants To render a tenant-switcher UI, your frontend asks Auth for the current user's memberships. ```bash title="GET //v1/auth/me/tenants" curl https://api.auth.productcraft.co/acme/v1/auth/me/tenants \ -H 'authorization: Bearer ' ``` ```json { "data": [ { "membership_id": "f36a...", "tenant_id": "f9b3...", "tenant_slug": "globex", "tenant_display_name": "Globex Corp", "tenant_status": "active", "role_id": "0d96...", "role_name": "admin", "app_id": "53641fdb-...", "joined_at": "2026-05-11T..." } ] } ``` 9 ## Webhooks fire on tenant lifecycle events Tenant create / update / delete and member add / remove / role-change all fire webhook events. Useful for syncing the tenant graph into your product DB or for audit. Event names: - `tenant.created`, `tenant.updated`, `tenant.deleted` - `tenant.member.added`, `tenant.member.role_changed`, `tenant.member.removed` Chapter 8 covers the webhook configuration + signature verification. 10 ## Common pitfalls - **Don't confuse tenant with app.** One app = one product. Tenants are _inside_ the app, modelling your customers' orgs. If you find yourself making a new app per customer, you probably want tenants. - **Tenant role ≠ workspace role.** The role graph is per-app, shared across tenants. The same role named `admin` in app _Acme_ means the same thing inside Globex and Wayne Enterprises (both tenants of Acme). - **Plan for users with no active tenant.** Some routes (account settings, billing) should work regardless of tenant context. Your app-level role gates those. Don't require `org_id` on every request. - **Org_role overrides nothing.** The tenant role grants _in addition to_ the app role; it cannot revoke an app-level permission. If a user shouldn't hold `billing.read` inside one tenant, demote their _app-level_ role — there's no tenant-level deny. [Next: M2M for backend services →](https://productcraft.co/docs/auth/guides/05-m2m-for-backend-services.md) --- title: "05 · M2M for backend services | Auth Guides" description: "OAuth 2.0 client_credentials grant for service-to-service auth. Scope narrowing, last_used_at, secret rotation, when M2M is right vs workspace API key." url: https://productcraft.co/docs/auth/guides/05-m2m-for-backend-services --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 05 · M2M # Authenticate backend services. When your code talks to Auth on behalf of an automated process — cron jobs, webhook receivers, internal sync — you want an M2M credential. This chapter walks through minting one, exchanging it for an access token, and using it correctly. 1 ## M2M vs workspace API key — which one? Both are workspace-scoped service credentials. The difference is the lane: - **M2M credential** — bound to one Auth app. Exchange for an access token via `POST /:appSlug/v1/oauth/token`. Use this when your backend acts _inside_ the customer-product context — calling the Consumer admin lane to manage end- users / roles / permissions for that app. - **Workspace API key** — workspace-scoped. Bearer goes on every request directly (no exchange step). Use this when your backend acts on workspace-level resources — minting Auth apps from CI, managing the workspace role catalog, or hitting the verification / reset mint endpoints across multiple apps. If your service only talks to one app, M2M is the obvious shape: one credential, one app, scoped permissions. If your service crosses apps (e.g. infra-as-code provisioning), a workspace API key covers them all with one credential. 2 ## Mint an M2M credential From the console (Auth → your app → Integration → Credentials → Create M2M credential) or via the auth-admin API. Minting takes a name only; scopes are set in a second call. **curl** ```bash title="POST /v1/apps/:appId/credentials (Auth-admin)" curl https://api.auth.productcraft.co/v1/apps//credentials \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "name": "billing-cron" }' # Then bind its scopes (permission strings from the app catalogue): curl -X PUT https://api.auth.productcraft.co/v1/apps//credentials//scopes \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "permissions": ["user.read", "invoice.read", "invoice.update"] }' ``` **SDK** ```ts title="@productcraft/auth" import { Auth } from "@productcraft/auth"; // Reads PRODUCTCRAFT_API_KEY from the environment const auth = new Auth(); const app = auth.admin.app(""); const credential = await app.credentials.create({ name: "billing-cron" }); // credential.client_secret is returned ONCE — save it now await app.credentials.updateScopes(credential.client_id, { permissions: ["user.read", "invoice.read", "invoice.update"], }); ``` Create response (the **only** time the secret is returned): ```json { "id": "5e2a...", "client_id": "m2m_a1b2c3d4e5f6", "client_secret": "secretvaluethatonlyappearsonce", "name": "billing-cron", "created_at": "2026-05-11T..." } ``` Store both `client_id` and `client_secret` in your secret manager. Auth stores only the hash of the secret — there's no recovery. If you lose the secret, rotate (step 6) and update the secret store. A credential with no scopes exchanges fine but gets an empty `scope` — set scopes before relying on it. 3 ## Exchange for an access token Standard OAuth 2.0 client_credentials grant. POST the client_id + client_secret, get an access token (1h TTL) back. **curl** ```bash title="POST //v1/oauth/token" curl https://api.auth.productcraft.co/acme/v1/oauth/token \ -H 'content-type: application/json' \ -d '{ "grant_type": "client_credentials", "client_id": "m2m_a1b2c3d4e5f6", "client_secret": "secretvaluethatonlyappearsonce" }' ``` **SDK** ```ts title="@productcraft/auth" import { Auth } from "@productcraft/auth"; // No platform auth needed — client_credentials carries its own creds. const consumer = new Auth().consumer("acme"); const { access_token, token_type, expires_in, scope } = await consumer.oauth.token({ grant_type: "client_credentials", client_id: "m2m_a1b2c3d4e5f6", client_secret: process.env.M2M_CLIENT_SECRET!, }); ``` ```json { "access_token": "eyJhbGc...", "token_type": "Bearer", "expires_in": 3600, "scope": "user.read invoice.read invoice.update" } ``` The access token is signed with the app's JWKS, same key your EndUser tokens use. Carries `type: "m2m"`, the resolved `scopes[]` array, and the same `aid`/`iss` claims as EndUser tokens. **Cache the token.** Don't exchange on every request — the access token is good for 1h, the exchange is a small but real round-trip. A simple in-memory cache with a 5-minute pre-expiry refresh covers the common case. 4 ## Use the access token Bearer on every request to the Consumer API. The /admin/* lane is what M2M is for; POST /verify checks end-user tokens, POST /oauth/introspect inspects your own. ```bash title="GET //v1/admin/users" curl https://api.auth.productcraft.co/acme/v1/admin/users \ -H 'authorization: Bearer ' ``` 5 ## Scope narrowing The scopes you put on the M2M at mint time bound everything that credential can ever do. The token's `scopes[]` claim is stamped at exchange time from the credential's configured set, and the per-app permission guard checks scope membership on every Consumer-API request. Three things to know: - **Scope checks require enforcement to be on.** Until the app's `enforce_app_permissions` flag is flipped (Chapter 3, step 8), any valid M2M token can call any admin route regardless of scopes. Caller-narrowing on role/permission writes applies either way. - **Grant the minimum.** A billing cron doesn't need `role.assign`. Don't put scopes on the credential “just in case” — they widen the blast radius if the secret leaks. - **Re-scoping is destructive on running clients.** `PUT /v1/apps/:appId/credentials/:clientId/scopes` replaces the scope set. Existing access tokens still carry the old scopes until they expire (1h max). If you widen, fine. If you narrow, the running service has up to 1h of stale-broader-than-allowed access. 6 ## Rotate the secret When you suspect a leak, when a previous owner of the credential leaves, or on a periodic schedule. ```bash title="POST /v1/apps/:appId/credentials/:clientId/rotate" curl -X POST https://api.auth.productcraft.co/v1/apps//credentials/m2m_a1b2c3d4e5f6/rotate \ -H 'authorization: Bearer pcft_live_...' ``` Response is `{ "client_id": ..., "client_secret": ... }` — the **new** secret, returned exactly once. The old secret stops working _immediately_. Already-issued access tokens survive a rotation (they're self-contained JWTs) — to kill those too, deactivate the credential: `PATCH .../credentials/:clientId` with `{ "is_active": false }` (or the **Disable** button on the credential row in the console). The admin lane re-checks `is_active` on every request, so deactivation 401s existing tokens instantly. The row's status badge flips **Active** → **Inactive** and the button becomes **Enable**. `last_rotated_at` is set on the credential row and comes back on `GET /v1/apps/:appId/credentials` — read it from the API if you want to enforce a rotation cadence. The console credential row does not display it today; it shows the credential name, client id, **Last used**, and the active/inactive badge. 7 ## last_used_at — confidence your credential is in use Every successful exchange stamps last_used_at on the credential row. Surfaces on the console credential row as 'Last used · 12m ago' (or 'Never' if it has been minted but not yet exchanged). Useful for cleaning up: credentials with `last_used_at = null` after creation almost certainly belong to a service that never integrated. Old `last_used_at` (months ago) might point to a cron that stopped running. **Caveat:** the stamp is best-effort. A transient DB hiccup at exchange time doesn't fail the grant — the access token is issued and the credential works, but `last_used_at` may not update for that one exchange. Don't treat the field as load-bearing for security decisions; treat it as a signal. 8 ## Caching pattern A reference TypeScript snippet for the common 'cache, refresh on expiry' shape. ```ts title="m2m-token-cache.ts" import { Auth } from "@productcraft/auth"; const consumer = new Auth().consumer("acme"); let cached: { token: string; expiresAt: number } | null = null; async function getM2mToken(): Promise { const now = Date.now(); if (cached && cached.expiresAt > now + 60_000) { return cached.token; } try { const { access_token, expires_in } = await consumer.oauth.token({ grant_type: "client_credentials", client_id: process.env.AUTH_CLIENT_ID!, client_secret: process.env.AUTH_CLIENT_SECRET!, }); cached = { token: access_token, // Refresh 1 minute before expiry to avoid edge of the TTL. expiresAt: now + expires_in * 1000 - 60_000, }; return cached.token; } catch (err) { cached = null; throw err; // an APIError subclass with status, code and requestId } } ``` 9 ## Common pitfalls - **Don't re-exchange on every request.** Cache. Each exchange is a full round-trip plus an argon2 verify on the secret — needlessly slow at request frequency. - **Don't share M2M credentials across services.** One credential per logical caller. Audit entries record the acting credential — sharing kills attribution. - **Don't use M2M for end-user authentication.** M2M = backend service. EndUser = your customers' users. The token `type` claim differs, and several Consumer-API routes (`/me/*`) are EndUser-only by design. - **Don't store the secret in env vars committed to your repo.** Even private repos. Use your secret manager (Vault, Doppler, AWS Secrets Manager, k8s secret). - **Rotate periodically.** No automated rotation today — the credential's up to you. A 90-day cadence matches our managed RSA-key rotation. [Next: Verify tokens in your service →](https://productcraft.co/docs/auth/guides/06-verify-tokens.md) --- title: "06 · Verify tokens | Auth Guides" description: "Three ways to verify a Auth token in your own service: local JWKS verification (fastest), /oauth/introspect (RFC 7662), and /verify + /authorize (one-call permission check). When to use each." url: https://productcraft.co/docs/auth/guides/06-verify-tokens --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 06 · Verify tokens # Trust the bearer your customer sent you. Your backend receives an Authorization header. Before you act on it, prove the token is real, fresh, and authorised. Auth gives you three shapes — pick the right one for the route. 1 ## The three shapes at a glance | Shape | Endpoint | When | | --- | --- | --- | | Local JWKS verify | your service, jose/PyJWT | Per-request, hot paths. Zero Auth round-trip. | | Introspect | POST /:slug/v1/oauth/introspect | RFC 7662 shape, when you need server-side revocation checks. | | Verify + authorize | POST /:slug/v1/verify, /authorize | When you also want a permission check in the same call. | 2 ## Local JWKS verification — the fast path Fetch the app's JWKS once, cache it, verify every token with the cached keys. No network call per request. Auth publishes the public half of each app's signing keys at `//.well-known/jwks.json` — directly under the app's issuer, where OpenID Connect Discovery says to look. (The older `//v1/.well-known/jwks.json` serves the same document and stays live.) Your backend fetches this once on boot (or lazily on first request), caches the result for an hour, and verifies every bearer locally. **SDK** ```ts title="@productcraft/auth — verifyToken()" import { Auth, JwtExpiredError } from "@productcraft/auth"; const auth = new Auth(); export async function verifyToken(bearer: string) { try { // One JWKS cache per app, fetched once and refreshed on rotation. const claims = await auth.verifyToken(bearer, { app: "acme" }); return claims; // { sub, aid, sid, role, type, amr, org_id?, org_role?, iat, exp, iss, aud } } catch (err) { if (err instanceof JwtExpiredError) { // trigger a refresh flow } throw err; } } ``` **jose (raw)** ```ts title="Node — jose" import { createRemoteJWKSet, jwtVerify } from 'jose'; const JWKS = createRemoteJWKSet( new URL('https://api.auth.productcraft.co/acme/.well-known/jwks.json'), { cooldownDuration: 60_000, cacheMaxAge: 3_600_000 }, ); export async function verifyToken(bearer: string) { const { payload } = await jwtVerify(bearer, JWKS, { issuer: 'https://api.auth.productcraft.co/acme', // per-app issuer audience: 'acme', // app slug }); // Refresh tokens are signed with the same key: accept access tokens only. if (payload.type !== 'end_user' && payload.type !== 'm2m') { throw new Error('not an access token'); } return payload; // { sub, aid, sid, role, type, amr, org_id?, org_role?, iat, exp, iss, aud } } ``` The SDK version uses the same primitive (`jose.createRemoteJWKSet` under the hood) but wraps it with a typed claims interface, typed error classes (`JwtExpiredError`, `JwtInvalidError`, ...), automatic issuer pinning to `auth.consumer(slug).expectedIssuer`, and singleflighted JWKS refetch on kid-miss. The jose-direct block is here if you'd rather wire it yourself. On `kid` miss (Auth rotated a key) the library refreshes the JWKS automatically. Rotated-out keys stay published in the JWKS until every token they signed has expired, so rotation never invalidates a live token. ```python title="Python — PyJWT" import jwt from jwt import PyJWKClient JWKS_URL = 'https://api.auth.productcraft.co/acme/.well-known/jwks.json' jwks_client = PyJWKClient(JWKS_URL, cache_keys=True) def verify_token(bearer: str) -> dict: signing_key = jwks_client.get_signing_key_from_jwt(bearer) claims = jwt.decode( bearer, signing_key.key, algorithms=['RS256'], audience='acme', # app slug issuer='https://api.auth.productcraft.co/acme', # per-app ) # Refresh tokens are signed with the same key: accept access tokens only. if claims.get('type') not in ('end_user', 'm2m'): raise jwt.InvalidTokenError('not an access token') return claims ``` Check `type`. A refresh token is signed with the same key, issuer and audience as the access token, and carries `"type": "refresh"`. It belongs in the body of `/auth/refresh` and `/auth/logout`, never in an `Authorization` header, and Auth's own endpoints refuse it there. Local verification cannot see a sign-out: an access token stays valid until its `exp` (at most `access_token_minutes`, one hour by default). For an action that must stop the moment the user signs out, ask `/oauth/introspect` or `/verify` instead; both check the session on every call. 3 ## What the payload tells you An EndUser access token: ```json { "sub": "648616c8-...", // EndUser id "aid": "53641fdb-...", // app id "sid": "c0a35ee6-...", // session id "role": "member", "type": "end_user", "amr": ["pwd"], // how they authenticated "org_id": "f9b3..." | undefined, // tenant when active "org_role": "admin" | undefined, "iat": 1778499565, "exp": 1778503165, // iat + access_token_ttl (1h default) "iss": "https://api.auth.productcraft.co/acme", // per-app "aud": "acme" // app slug } ``` An M2M access token: ```json { "sub": "m2m_a1b2c3...", // client_id "aid": "53641fdb-...", "type": "m2m", "scopes": ["user.read", "invoice.read"], "iat": ..., "exp": ..., "iss": "https://api.auth.productcraft.co/acme", // per-app "aud": "acme" // app slug } ``` Your service reads `sub` + `aid` to establish identity, `type` to branch on EndUser vs M2M behaviour, and `role` / `scopes` for permission gating. 4 ## Resolve permissions per request The role name in the JWT isn't enough — you need the flat permission set to gate routes. Auth provides /me/permissions for this. ```bash title="GET //v1/me/permissions" curl https://api.auth.productcraft.co/acme/v1/me/permissions \ -H 'authorization: Bearer ' ``` ```json { "role": "member", "org_role": "admin", "permissions": ["user.read", "invoice.read", "invoice.create", "invoice.refund"] } ``` The `permissions` array is the _union_ of the app-level role's permissions and (if `org_id` is set) the tenant-level role's permissions. Resolved per-request through Auth's 60s LRU — role-permission edits propagate within a minute. Your service caches the response per token+session for a short window (60s mirrors Auth's own cache) and checks set membership before letting the request through. 5 ## Introspect — when you need server-side revocation Local JWKS verification can't tell you the session was revoked five minutes ago — the token is still cryptographically valid until exp. Introspection asks Auth the live question. ```bash title="POST //v1/oauth/introspect" curl https://api.auth.productcraft.co/acme/v1/oauth/introspect \ -H 'authorization: Bearer ' ``` RFC 7662 shape: ``` # Valid EndUser token { "active": true, "sub": "648616c8-...", "type": "end_user", "exp": ..., "iat": ..., "iss": "https://api.auth.productcraft.co/acme", "aid": "53641fdb-..." } # Valid M2M token — adds client_id + scopes { "active": true, "sub": "m2m_a1b2...", "client_id": "m2m_a1b2...", "type": "m2m", "scopes": ["user.read"], "scope": "user.read", ... } # Revoked / expired / invalid / wrong app { "active": false } ``` Reach for this over local verify on high-value mutations — move money, delete a user, change a billing address. Pay the round-trip to catch a session revoked after the token was issued: local verify keeps passing until `exp`; introspect flips to `{ "active": false }` immediately. **No cross-token introspection.** RFC 7662 allows a body `token` field that differs from the bearer; Auth accepts the field but requires it to match the Authorization header (a mismatch returns `{ "active": false }`). This stops a stolen token being probed under the cover of another credential. To inspect a token, your code makes the call _as_ that token — simplest form: send the token as the bearer with an empty JSON body. 6 ## /verify and /authorize — combined verify + permission check One round-trip, one yes/no answer. Useful when your service doesn't want to manage JWKS or role resolution itself. Both read the token from the Authorization header, or from a body token field if you'd rather pass it explicitly. ```title="POST //v1/verify" # Signature, issuer, audience AND session all checked { "valid": true, "principal": { "sub": "...", "aid": "...", "role": "member", "type": "end_user" } } # Cryptographically valid, but the session behind it is not live. # TOKEN_REVOKED — signed out, password changed, admin revoked, or the # end user was deleted (their session rows go with them) # SESSION_EXPIRED — the session passed its expires_at; an access token # can outlive the session that minted it # TOKEN_INVALID — includes an end_user token whose account no longer exists # ACCOUNT_SUSPENDED — account present but not active { "valid": false, "error": "TOKEN_REVOKED" } ``` ```bash title="POST //v1/authorize" curl https://api.auth.productcraft.co/acme/v1/authorize \ -H 'authorization: Bearer ' \ -H 'content-type: application/json' \ -d '{ "permission": "invoice.refund" }' ``` ``` # Holds the permission { "authorized": true } # Doesn't { "authorized": false, "error": "INSUFFICIENT_PERMISSIONS", "missing_permissions": ["invoice.refund"] } ``` Or pass an array (every permission must be held): ``` # Body { "permissions": ["invoice.read", "invoice.refund"] } ``` For checking many actions in one round-trip use `POST /authorize/batch`: ``` # Body { "checks": [ { "id": "view-invoices", "permission": "invoice.read" }, { "id": "refund-invoices", "permission": "invoice.refund" }, { "id": "manage-team", "permissions": ["user.update", "role.assign"] } ] } # Response { "results": [ { "id": "view-invoices", "authorized": true, "missing_permissions": [] }, { "id": "refund-invoices", "authorized": false, "missing_permissions": ["invoice.refund"] }, { "id": "manage-team", "authorized": true, "missing_permissions": [] } ] } ``` Use the batch shape when rendering a UI: one round-trip tells you which buttons to enable and which to disable. Each result reports the missing permission(s) so the UI can show a tooltip like “needs invoice.refund.” 7 ## Picking the right shape - **Hot path / API server / per-request gating:** local JWKS + `/me/permissions` (cached 60s). No Auth round-trip on most requests. - **High-value mutation, revocation matters:** local JWKS for the signature, then introspect for the live status. Or just introspect (one call, both checks). - **UI permission gating across many actions:** `/authorize/batch` at page load, render with the results. - **A service that doesn't want to manage JWKS caching:** `/verify` on every request. Slow but works. The fastest production setup is local-JWKS for verification + `/me/permissions` with a 60s cache for permission resolution. Zero round-trips on a cache hit; one per minute per (token, route) pair in steady state. 8 ## Caveats - **Local verify cannot catch role demotion.** The JWT still names the user's old role until it expires (1h default). Per-request `/me/permissions` covers this because it re-resolves the role's permission set — but the role _name_ itself stays stale on the wire. For instant effect, revoke the user's sessions when demoting. - **Local verify cannot catch session revocation.** Use introspect or check the session list (`GET /me/sessions`) if revocation latency matters for that route. - **Don't verify expired tokens.** JWT libraries throw on expired tokens by default — let them. Don't catch and re-validate downstream. [Next: Email verification + password reset →](https://productcraft.co/docs/auth/guides/07-verification-and-reset.md) --- title: "07 · Verification + reset | Auth Guides" description: "Email verification and password reset flows. The mint endpoints are API-key-only by design; you deliver the code via your own SMTP or via Mail, then consume on the public route." url: https://productcraft.co/docs/auth/guides/07-verification-and-reset --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 07 · Verification + reset # Email verification + password reset. Auth mints the codes. You deliver them through whatever channel makes sense — your own SMTP, an SMS provider, or our Mail integration. The consume side is public; the mint side is API-key-only by deliberate design. 1 ## Why mint endpoints are API-key-only Public mint endpoints are an account-enumeration vector and a spam-forwarder vector. Auth puts the abuse-mitigation point in your code, not in our pipeline. Two threats every “forgot password” form has to handle: - **Enumeration.** An attacker hits the form with email after email, looks at the response shape, and compiles a list of real accounts. - **Spam forwarding.** An attacker hits the form rapidly with the same email — or with thousands of emails they want to spam — and uses _your_ sender to do it. Defending against both requires per-customer logic: maybe you have a captcha, maybe a paid-tier check, maybe a rate limit per-IP. Auth doesn't know your customer's policy. So we don't expose the mint endpoints publicly — your backend mints with a workspace API key, applies your own abuse-mitigation, and forwards the code to the user. 2 ## Mint a verification code Customer-backend route. Workspace API key with auth.user.verify.create on the app URN. Returns the 6-digit code in the response body — you deliver it however you like. **curl** ```bash title="POST //v1/auth/request-verification" curl https://api.auth.productcraft.co/acme/v1/auth/request-verification \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "email": "ada@example.com" }' ``` **SDK** ```ts title="@productcraft/auth" import { Auth } from "@productcraft/auth"; // The consumer scope never reads PRODUCTCRAFT_API_KEY by itself: // pass the workspace key explicitly for this PAK-gated route. const auth = new Auth({ apiKey: process.env.PRODUCTCRAFT_API_KEY }); const consumer = auth.consumer("acme"); const res = await consumer.requestVerification({ email: "ada@example.com", }); // res: { code, expires_at } — or {} on no match ``` ``` # Match (and email is unverified) { "code": "384201", "expires_at": "2026-05-11T11:46:18Z" } # No match — uniform shape, no enumeration {} ``` 10-minute TTL. Single-use. Auth stores only the hash of the code; the plaintext is returned exactly once. Body also accepts `phone` for SMS verification — Auth doesn't care about the channel, just the contact value. **Latest code wins.** Minting invalidates any previously issued, unconsumed code for the same contact — including the one Auth auto-emails at signup when your Mail integration is configured. Calling `request-verification` right after signup is therefore safe: the user only ever holds one valid code, the one you delivered. 3 ## Deliver the code Two paths. The fast one uses our Mail service; the flexible one uses your own SMTP. ### Path A — Mail If your workspace has Mail enabled and a verified sender domain, Auth can mint _and_ dispatch in one call. Distinct API key permission so customers can mint without opting into outbound Mail: ```bash title="POST //v1/auth/send-verification-email" curl https://api.auth.productcraft.co/acme/v1/auth/send-verification-email \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "email": "ada@example.com" }' ``` ``` # Success (code not returned — Mail delivers it) { "expires_at": "2026-05-11T11:46:18Z" } # No match / already verified — uniform shape {} # Pre-condition failures (412) — Mail not enabled, sender not # configured, template not configured, or app not bound to a workspace: { "statusCode": 412, "message": "Mail notifications are not enabled for this app" } # Dispatch failure (503) { "statusCode": 503, "message": "Failed to dispatch through the Mail service: " } ``` The plaintext code is **not** in the response for this path. Mail delivers it to the customer directly. If you also want to log the code for your own records, use Path B instead. ### Path B — Your own SMTP Hit the bare `request-verification` endpoint (Step 2), get the code back, deliver it however you like. Useful when you have an existing transactional-email pipeline (SendGrid, Postmark, AWS SES) and prefer to keep templates there. ```ts title="Your backend" import { Auth } from "@productcraft/auth"; declare const yourEmailProvider: { send(m: object): Promise }; const consumer = new Auth({ apiKey: process.env.AUTH_PAK }).consumer("acme"); async function sendVerification(email: string) { // 1. Mint the code through Auth const res = await consumer.requestVerification({ email }); if (!res.code) return; // No match — silent (uniform shape) // 2. Deliver however you like await yourEmailProvider.send({ to: email, subject: "Verify your email", template: "verification", data: { code: res.code, expiresAt: res.expires_at }, }); } ``` 4 ## Consume the code Public endpoint — anyone with the code can submit it; that's the point. Single-use; marking the contact verified is atomic. ```bash title="POST //v1/auth/verify" curl https://api.auth.productcraft.co/acme/v1/auth/verify \ -H 'content-type: application/json' \ -d '{ "code": "384201" }' ``` ```json { "account_id": "648616c8-...", "contact_id": "9f2b4e10-...", "type": "email", "value": "ada@example.com", "verified_at": "2026-05-11T11:38:42Z" } ``` Every failure is the same response: 410 `Invalid or expired code` — whether the code is wrong, expired, already consumed, or superseded by a newer one. Deliberately opaque: distinguishing the cases would hand an attacker an oracle. 5 ## Password reset — same shape Mint with a workspace API key (auth.user.password-reset.create), deliver the code, consume on a public route. Same 10-minute TTL, same latest-code-wins rule — a new reset code invalidates any outstanding one for the account. ```bash title="Mint" curl https://api.auth.productcraft.co/acme/v1/auth/request-password-reset \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "email": "ada@example.com" }' # Or hit the Mail shortcut: curl https://api.auth.productcraft.co/acme/v1/auth/send-password-reset-email \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "email": "ada@example.com" }' ``` ```bash title="Consume" curl https://api.auth.productcraft.co/acme/v1/auth/reset-password \ -H 'content-type: application/json' \ -d '{ "code": "718462", "new_password": "NewCorrectHorseBatteryStaple2" }' ``` On success: 204. The user's password is updated AND every active session for the account is revoked. Forces re-signin. Intentional — a password reset always implies a compromise; we don't leave existing access tokens in place. 6 ## Unverified-contact corner case A contact must be verified before it can be used for password reset. Reset against an unverified contact is silently no-op. Why: an attacker who registers an unverified email contact on a victim's account could push reset codes through it. The verified-only requirement breaks that path. Concretely: `request-password-reset` against `{ email: "unverified@example.com" }` returns `{}` — same shape as the no-match case. Customer-product can't enumerate. The fix in your product: when a user adds a new email contact, walk them through the verification flow before anything sensitive can use that email. The Auth`/me/contacts/:id/promote` route — promoting a verified contact to primary — explicitly refuses unverified contacts with 409. 7 ## Customer-side rate limiting The shape is yours. Suggested floor: - **Per email:** 5 mint requests per hour. Counter increments even on no-match so timing doesn't leak existence. - **Per IP:** 10 mint requests per hour. Higher because legit users behind shared NAT (e.g. an office) can collide. - **Captcha threshold:** after 3 attempts in a 10-minute window, require a captcha solve before the next mint. Auth already enforces a coarser per-IP rate limit on both the mint and consume endpoints (429 when blown), but the granular per-user policy lives in your backend. 8 ## Audit Every mint + consume writes an audit row. Useful for incident response and for customer support. Audit actions: - `auth.contact_verification.requested` + `completed` - `auth.password_reset.requested` + `completed` Each row records the actor type (`m2m` for your workspace API key on mint; `end_user` on consume), the contact or account acted on, and the timestamp. Read them via `GET /v1/apps/:appId/audit-logs?action=auth.password_reset.completed` — the `action` filter is an exact match, one action per query. [Next: Webhooks + audit →](https://productcraft.co/docs/auth/guides/08-webhooks-and-audit.md) --- title: "08 · Webhooks + audit | Auth Guides" description: "The Auth webhook events and what they carry (signatures, retries and replay are in the shared Webhooks guide), then the per-app audit log for compliance + debugging." url: https://productcraft.co/docs/auth/guides/08-webhooks-and-audit --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 08 · Webhooks + audit # Hear about lifecycle events. Read the audit log. Two trailing-edge surfaces: webhooks deliver real-time events to your backend (signup, verification, role change, tenant added); the audit log is the durable record of every mutation, queryable for support and compliance. 1 ## What you can subscribe to Every event, with a plain description, its group and an example `data` object, is listed by the API, so your code (and the console's event picker) never has to hard-code the names: ```bash title="GET /v1/apps/:appId/webhooks/event-types" curl https://api.auth.productcraft.co/v1/apps//webhooks/event-types \ -H 'authorization: Bearer pcft_live_...' ``` ```title="Event types" # Users user.signup # by sign-up, admin, invite or first social sign-in user.signin user.suspended user.deactivated user.reinstated user.role_changed user.deleted # data.reason "unverified_expired" when auto-deleted (see below) # Verification and passwords user.contact_verified # any email/phone contact verified user.email_verified # older name, sent too when it's the primary email user.password_reset.requested user.password_reset.completed # Two-step verification user.mfa.factor_enrolled user.mfa.factor_disabled user.mfa.recovery_code_used user.mfa.step_up_succeeded user.mfa.step_up_locked user.mfa.enrollment_required user.mfa.reenrollment_required # Organizations tenant.created tenant.updated tenant.deleted tenant.member.added tenant.member.removed tenant.member.role_changed tenant.invite.created tenant.invite.accepted tenant.invite.revoked # App app.slug_changed # your issuer and JWKS URL are moving: 30-day alias ``` Webhooks are **per app**, and an app can have up to 10 **endpoints**, each with its own URL, events and signing secret: one for your backend, one for analytics, a third for a staging receiver. An endpoint subscribed to no events receives every event. **Unverified accounts are deleted automatically** when the app's `unverified_account_ttl_days` is set (new apps: 7 days; apps created before the setting existed: off). Each nightly deletion sends `user.deleted` with `"reason": "unverified_expired"`, so delete your own copy of the user when it arrives. Only accounts that never verified their email, never signed in, refreshed a session or reset their password after signing up, and have no two-step factor or social login qualify. To protect someone who uses your app without verifying, set `"metadata": { "app_active": true }` on them with `PATCH /v1/apps/:appId/end-users/:userId`. 2 ## Add an endpoint From the console (Auth → your app → Integration → Webhooks) or the API. Endpoints, signatures, tests, retries and replay work the same in every ProductCraft product. ```bash title="POST /v1/apps/:appId/webhooks/endpoints" curl -X POST https://api.auth.productcraft.co/v1/apps//webhooks/endpoints \ -H 'authorization: Bearer pcft_live_...' \ -H 'idempotency-key: add-backend-endpoint-1' \ -H 'content-type: application/json' \ -d '{ "url": "https://acme.example.com/webhooks/auth", "event_types": ["user.signup", "user.email_verified", "user.role_changed"] }' ``` The answer carries the `whsec_…` signing secret exactly once. Endpoints belong to one app; each app can have up to 10. **Verifying the signature, Send test, automatic retries, auto-disable, the event log, replay and secret rotation** are in the [Webhooks guide](https://productcraft.co/docs/platform/webhooks.md), with Node code you can paste. 3 ## What an Auth event looks like Signed with Standard Webhooks like every ProductCraft event; app_id says which app it came from. ```json title="user.email_verified" { "id": "evt_fb580f79-...", "type": "user.email_verified", "created_at": "2026-05-11T11:38:42Z", "app_id": "53641fdb-...", "data": { ...event-specific fields... } } ``` **Upgrading from the single webhook?** Endpoints that existed before 17 October 2026, or that are set up through the older `PUT .../webhook` route, also get the old `x-auth-signature` header plus `x-auth-event-id` and `x-auth-event-type`, until **15 January 2027**. The old `/v1/apps/:appId/webhook` routes keep working until the same date, acting on the app's first endpoint. The [Webhooks guide](https://productcraft.co/docs/platform/webhooks.md) covers the old header and moving your verifier. 4 ## The audit log — the durable record Every state-changing call on Auth writes an audit_log row. Per-app. Append-only. Searchable + exportable. Audit captures the same surface as webhooks plus more: - Every signup / signin (including failures) / logout / token refresh (`auth.*`) - Every verification + password-reset mint and consume - Every member add / remove / role change (`app.member.*`) - Every role CRUD + role-permission change (`app.role.*`) - Every M2M credential mutation (`app.m2m.*`) - Every tenant lifecycle event (`tenant.*`) - Every webhook endpoint change, test and replay (`app.webhook.*`) - Every MFA factor + recovery-code event (`auth.factor.*`) - _Permission denials_ — on apps with permission enforcement enabled, a request that fails the permission gate writes `authz.app_permission_denied` with the missing permission 5 ## Read the audit log ```bash title="GET /v1/apps/:appId/audit-logs" curl 'https://api.auth.productcraft.co/v1/apps//audit-logs?limit=20&action=auth.signin.success' \ -H 'authorization: Bearer pcft_live_...' ``` ```json { "data": [ { "id": "...", "app_id": "53641fdb-...", "actor_id": "648616c8-...", // who did it (account uuid, or null for M2M/system) "actor_type": "end_user", // | platform_user | m2m | api_key | system "action": "auth.signin.success", "resource": "account", "resource_id": "648616c8-...", "metadata": {}, "ip": "203.0.113.4", "created_at": "2026-05-11T..." } ], "pagination": { "next_cursor": "...", "has_more": true } } ``` Filter via query params: `action` (exact match, one action per query) and `actor_id`, plus `limit` (50 default, 200 max) and `cursor` for pagination. “Everything Ada did” is `?actor_id=`; walk the cursor for time ranges. 6 ## Webhook vs audit — when to use which - **Webhook = real-time push.** Use for sync that needs to happen immediately when the event fires — flipping a feature flag on the user's account, kicking off provisioning, sending a confirmation in your own UI. - **Audit = pull, on demand.** Use for support workflows (“what happened to this user 3 days ago?”), compliance exports, security investigations, and post-hoc debugging. The data covers everything; the latency is whatever your query takes. - **Don't treat audit as a stream.** There's no “tail the audit log” primitive today — for that, configure a webhook. The audit log is designed for cursor-paginated point-in-time queries. What's next ## You've finished the series That was the comprehensive tour. From here: - [API reference](https://productcraft.co/docs/auth/api-reference.md) — every endpoint, every status code, generated from the live OpenAPI spec. - [Core concepts](https://productcraft.co/docs/auth/concepts.md) — the conceptual model in one page. - [Platform docs](https://productcraft.co/docs/platform.md) — the administrative surface that sits underneath Auth. Read this if you're managing your workspace from CI or infrastructure-as-code. - [Mail docs](https://productcraft.co/docs/mail.md) — transactional email, the natural pairing for verification + reset flows. [Next: Sign in with Apple →](https://productcraft.co/docs/auth/guides/09-signin-with-apple.md) --- title: "09 · Sign in with Apple | Auth Guides" description: "Add Sign in with Apple to any Auth app. Native iOS / macOS, web redirect flow, account linking by verified email, audit + webhook events on every signin." url: https://productcraft.co/docs/auth/guides/09-signin-with-apple --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 09 · Sign in with Apple # Sign in with Apple. Two integrations, one backend. Native iOS / macOS posts the Apple ID token straight to Auth; web apps redirect through Auth and pick up a single-use code on the callback. No SDK, no PKCE bookkeeping in your frontend, no Apple-specific UI in your product. 1 ## Apple Developer console setup One-time, ~10 minutes. Everything happens inside Certificates, Identifiers & Profiles. By the end you'll have five values to hand to Auth in step 2: a Team ID, a Key ID, a .p8 private key, your App ID's bundle id(s), and — only if you support web — a Services ID. Apple splits a single “Sign in with Apple” integration across three separate artifacts, which is what makes the first run confusing. Here's what each one is and why you need it: - **App ID** — the identifier for your native iOS / macOS app (e.g. `com.acme.ios`). You almost certainly already have one. Its bundle id is the _audience_ Apple stamps into tokens issued to your native app. - **Services ID** — a separate identifier that represents your app _on the web_ (e.g. `com.acme.web`). Apple treats web sign-in as a distinct client, so it gets its own id and its own audience. **Skip this entirely if you only support native.** - **Key** — a private signing key (a `.p8` file) that Auth uses to authenticate itself to Apple on your behalf. One key works for both the native and web flows. Sign in to [Certificates, Identifiers & Profiles](https://developer.apple.com/account/resources/identifiers/list) and work through the following. ### 1a · Enable the capability on your App ID Open your existing **App ID** (under **Identifiers**) and turn on the **Sign in with Apple** capability, then save. That's the only change here. Note the bundle id — it goes into Auth as `bundle_ids`. If you ship a watchOS or iPad companion under the same team, each has its own bundle id and they all go in the array. ### 1b · Create a Services ID — web flow only Skip this if you don't have a browser sign-in flow. Otherwise, create a new **Services ID** (also under **Identifiers** — choose “Services IDs” as the type), give it a reverse-DNS identifier like `com.acme.web`, and enable **Sign in with Apple** on it. Then configure that capability: - **Primary App ID** — point it at the App ID from step 1a. - **Domains** — add `api.auth.productcraft.co`. - **Return URLs** — add exactly `https://api.auth.productcraft.co//v1/auth/oauth/apple/callback`. Apple does a byte-exact match: no trailing slash, no port, https only. Substitute your real app slug for ``. The Services ID identifier (`com.acme.web`) is what you'll send to Auth as `service_id`. ### 1c · Create a Sign in with Apple key Under **Keys**, create a new key, enable the **Sign in with Apple** capability on it, and register it. Apple then lets you **download the `.p8` file exactly once** — download it now and store it somewhere safe; there is no second chance, and losing it means generating a new key. The contents of that file (the PEM block, including the `-----BEGIN PRIVATE KEY-----` lines) become `private_key_pem` in step 2. ### 1d · Collect your Team ID and Key ID - **Team ID** — a 10-character string shown in the top-right of the developer portal (also under **Membership** ). Sent to Auth as `team_id`. - **Key ID** — a 10-character string shown on the key's detail page right after you created it in step 1c. Sent to Auth as `key_id`. That's everything Apple-side. Nothing else gets registered with Apple as you scale — Auth handles the per-customer wiring through one config row, which you upload next. 2 ## Upload your Apple config in the console Take the five values from step 1 into the console — four typed fields plus the .p8 file itself, which you drag onto the page. The private key is encrypted at rest with AES-256-GCM and never appears in any API response after you save it. (Prefer scripting it? The same config is one PUT against the Auth-admin API — see the OpenAPI spec.) In the [ProductCraft console](https://console.productcraft.co), open **Auth**, select the app you're wiring up, then go to **Settings**. Under **Federated sign-in providers**, select **Set up** on the Apple row. The page opens on **Set up Apple sign-in**: five numbered steps (create the client at Apple, paste the redirect URI, scopes, paste the credentials and save, Try sign-in) with your app's Return URL ready to copy. Step 4 points at the form under the steps: - **Services ID** — the Services ID identifier from step 1b (e.g. `com.acme.web`). Web flow only; if you're native-only you still need a value here today, so use your primary bundle id. - **Bundle IDs** — type each bundle id and press Enter to add it as a chip. Add your iOS bundle id plus any watchOS / macOS / iPad companions that share the same Apple team. At least one is required. - **Team ID** and **Key ID** — the two 10-character values from step 1d. - **Signing key** — drag the `.p8` file from step 1c onto the dropzone (or click it to browse). The console reads the file and rejects anything that doesn't contain a `-----BEGIN PRIVATE KEY-----` block. Select **Configure** to save. Auth then checks the values with Apple straight away: it signs a client secret with your key and sends Apple's token endpoint a code that cannot work. Step 4 shows the answer. **Accepted** means Apple knows the Services ID and the key belongs to it. **Rejected** comes with the fix: the key file cannot sign (upload the original `.p8`), or Apple does not accept the combination (check that the Services ID, Team ID and Key ID come from the same team and the key has Sign in with Apple turned on). Then select **Try sign-in with Apple** in step 5: you sign in at Apple in a small window and the console shows who would have signed in, without creating an account. When it works, switch on **Enabled** and save. Left off, the provider is saved but inactive. The key is stored encrypted and never retrievable, so when you come back the dropzone is empty (headed **Replace signing key** ). Saving other edits keeps the key on file; upload a file only to replace it. To retire Apple sign-in without deleting the config, switch **Enabled** off; **Remove provider…** deletes the config entirely (existing Apple users keep their accounts but can't sign in via Apple until it's set up again). Two related settings live one card below, under **Federated sign-in policy**: - **Account-linking policy** — what happens when an Apple sign-in lands on an email that already has an account. Defaults to `confirm` (safe). See section **5**. - **Allowed redirect origins** — the origins the web flow accepts as `return_to`. Empty (the default) disables the web flow entirely. Exact origin match — scheme + host + port, no paths, no wildcards. Add yours before users hit the web flow (section **4** ). 3 ## Native iOS / macOS Use Apple's ASAuthorizationController. Generate a random nonce locally, hash it, pass the hash to Apple, send the raw nonce + identity token to Auth. Build a sign-in button with `ASAuthorizationAppleIDButton`; on tap, kick off an `ASAuthorizationAppleIDRequest` configured with `requestedScopes = [.fullName, .email]` and the SHA-256 hex of a random nonce. When Apple returns, you get an `identityToken` (the JWT) and — on first signin only — a `fullName` + `email`: ```swift title="Swift — sign-in handler" import AuthenticationServices import CryptoKit import Security final class AppleSignInCoordinator: NSObject, ASAuthorizationControllerDelegate { private var currentNonce: String? func startSignIn() { let raw = randomNonceString() currentNonce = raw let provider = ASAuthorizationAppleIDProvider() let request = provider.createRequest() request.requestedScopes = [.fullName, .email] request.nonce = sha256(raw) let controller = ASAuthorizationController(authorizationRequests: [request]) controller.delegate = self controller.performRequests() } func authorizationController( controller: ASAuthorizationController, didCompleteWithAuthorization auth: ASAuthorization ) { guard let credential = auth.credential as? ASAuthorizationAppleIDCredential, let identityTokenData = credential.identityToken, let identityToken = String(data: identityTokenData, encoding: .utf8), let rawNonce = currentNonce else { return } var body: [String: Any] = [ "id_token": identityToken, "nonce": rawNonce, ] // First-signin only — Apple withholds name + email on subsequent runs. // `user.name` is a plain string on the wire. if let givenName = credential.fullName?.givenName, let familyName = credential.fullName?.familyName { body["user"] = ["name": "\(givenName) \(familyName)"] } Task { try await postToAuth(body) } } // 32 random bytes, hex-encoded — the RAW nonce sent to Auth. private func randomNonceString() -> String { var bytes = [UInt8](repeating: 0, count: 32) _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) return bytes.map { String(format: "%02x", $0) }.joined() } // SHA-256 hex of the raw nonce — what Apple gets. private func sha256(_ input: String) -> String { SHA256.hash(data: Data(input.utf8)) .map { String(format: "%02x", $0) }.joined() } } ``` Then one POST. Auth verifies the JWT signature, pins `iss = appleid.apple.com`, checks the audience against your configured `bundle_ids`, recomputes the SHA-256 of `nonce` and compares to the JWT's `nonce` claim, claims the nonce in Redis so it can't be replayed, resolves or creates the account, and mints Auth tokens: **curl** ```bash title="POST //v1/auth/oauth/apple" curl https://api.auth.productcraft.co/acme/v1/auth/oauth/apple \ -H 'content-type: application/json' \ -d '{ "id_token": "", "nonce": "", "user": { "name": "Jane Doe" } }' ``` **SDK** ```ts title="@productcraft/auth" import { Auth } from "@productcraft/auth"; declare const identityTokenFromAppleSdk: string; declare const rawNonceClientGenerated: string; const consumer = new Auth().consumer("acme"); const signin = await consumer.signinWithProvider("apple", { id_token: identityTokenFromAppleSdk, // ASAuthorizationAppleIDCredential.identityToken nonce: rawNonceClientGenerated, // raw — not the hash user: { name: "Jane Doe" }, // first sign-in only }); // signin.access_token, signin.refresh_token, ... ``` ```json { "access_token": "eyJhbGciOi...", "refresh_token": "rt_...", "token_type": "Bearer", "expires_in": 3600 } ``` Same response shape as `/auth/signin` — drop the tokens into your existing storage and your app code doesn't care whether the session came in through password or Apple. The `amr` claim on the access token is `["oauth", "apple"]` if you want to branch on it. 4 ## Web (browser redirect) No SDK. Two redirects + one server-to-server exchange. Tokens never travel through URLs or browser history. Add `allowed_redirect_origins` to your auth config first (see step **2** ). Then put a link on your sign-in page that points users at Auth's authorize endpoint: ```html title="Your sign-in page" Sign in with Apple ``` Auth 302s to Apple → the user does the Apple sheet → Apple posts the result back to Auth's callback → Auth 303s the user to `https://app.acme.com/login/done?heimdall_code=`. Your frontend reads the code and forwards it to your backend, which exchanges it for tokens: ```ts title="Your backend — code → tokens" import { Auth, AuthenticationError } from "@productcraft/auth"; const consumer = new Auth().consumer("acme"); async function completeProviderSignIn(code: string) { try { // code: the heimdall_code query value const { access_token, refresh_token, expires_in } = await consumer.exchangeProviderCode({ code }); // Drop into your session cookie / store as you'd handle a sign-in. return { access_token, refresh_token, expires_in }; } catch (err) { // 401: unknown, expired or already used if (err instanceof AuthenticationError) return null; throw err; } } ``` The code is single-use, 60-second TTL, bound to the`appSlug` it was minted under. Once your backend exchanges it, the code is gone — even if someone intercepts the URL after the fact. Failure modes redirect back to `return_to` with a typed `heimdall_error` query string instead of a Auth-hosted error page you can't style: - `heimdall_error=token_invalid` — signature / iss / audience / nonce check failed. - `heimdall_error=nonce_replayed` — same Apple token reaching the callback twice. - `heimdall_error=link_required` — an account with this email already exists; the user needs to sign in with their original method first. See section **5**. 5 ## Linking policy — what happens on email collision When an Apple sign-in lands on a verified email that already has an account in your app, three policies are available. Default is the safe one. Set the `oauth_link_policy` field on `PATCH /v1/apps//auth-config`: - `confirm` (default) — refuse the auto-link. Native flow returns 409 with `{ "code": "link_required" }`; web flow redirects with `heimdall_error=link_required`. Your UI asks the user to sign in with their original method first; you then bind the Apple identity through a one-shot link-token flow (lands in a follow-up release). - `auto` — link silently when Apple says `email_verified=true` AND the email is not a private relay. Convenient; trades a small amount of security (you're trusting Apple's email verification) for fewer prompts. - `reject` — refuse outright with `account_exists_with_different_provider`. For products that don't want federated and password to mix at all. Private-relay `@privaterelay.appleid.com` emails never auto-link, regardless of policy. They aren't deliverable through your channels and aren't suitable as a linking primitive. 6 ## Webhooks + audit Same events you already wire for password signin, with an extra `provider` field so you can tell which path the user took. ```json title="user.signup" { "type": "user.signup", "data": { "user_id": "648616c8-...", "username": "jane", "email": "jane@example.com", "provider": "apple" } } ``` ```json title="user.signin" { "type": "user.signin", "data": { "user_id": "648616c8-...", "provider": "apple", "linked": false } } ``` `linked: true` when the policy was `auto` and Auth bound the Apple identity to an existing email account. Audit events: `auth.signup.success` and `auth.signin.success` with the same `provider` metadata (`linked` on signins). `amr` claim on issued access tokens is `["oauth", "apple"]`. Your backend can branch on it without an extra round-trip — for example, to require a password set-up step before allowing payment changes on a federated-only account. 7 ## Apple-specific gotchas Three behaviors that surprise people the first time. None of them break sign-in, but they'll save you a half-day each. - **The user's name only arrives once.** Apple delivers `fullName` and `email` on the very first authorization for a given (user, app) pair. Subsequent signins ship neither. Persist the name on first signin or it's gone — Auth stores it on the identity row from the `user` payload, but only if you forward it. - **Private-relay emails look real but aren't deliverable through you.** Apple lets users hide their email behind `xxxxx@privaterelay.appleid.com`; mail to that address only routes if the customer's Apple-registered sender domains include yours. Your transactional email pipeline likely doesn't. Auth flags these on the identity row and refuses to auto-link them, but if you rely on email for password reset / receipts / etc., note in your UI that private relays may bounce. - **The audience is your Services ID for web, your bundle id for native — never the other way.** Auth enforces this; a web-flow token replayed against the native endpoint fails with `audience does not match`. If you switch a flow you'll need a different Services ID / bundle entry; the config field is plural (`bundle_ids`) precisely because companion / watchOS / iPad apps under one team each have their own. 8 ## Going beyond Apple The abstraction is provider-agnostic. Google and GitHub are live on the same surface today. The endpoints under `/auth/oauth/:provider` take the provider id as a URL segment: `apple`, `google`, and `github`. GitHub is web-flow only — it has no ID token, so POSTing the native endpoint with `provider=github` returns 400. The config row shape is provider-specific (Apple wants a private key; Google and GitHub want a `client_id` + `client_secret`) but every other piece — the linking policy, the web flow, the exchange code, the audit trail, the webhook events — is the same surface across providers. Wiring a second provider on an app is one more PUT against `/auth-config/providers/` with that provider's config shape. Step-by-step setup for the other two: [12 · Sign in with Google](https://productcraft.co/docs/auth/guides/12-signin-with-google.md) and [13 · Sign in with GitHub](https://productcraft.co/docs/auth/guides/13-signin-with-github.md). [Back to all guides](https://productcraft.co/docs/auth/guides.md) --- title: "10 · Passkeys | Auth Guides" description: "Add WebAuthn passkeys to an Auth app: the per-app relying-party config, passkeys as a second factor, passwordless sign-in, step-up — one SDK call per ceremony, or the raw HTTP and base64url encoding underneath." url: https://productcraft.co/docs/auth/guides/10-passkeys --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 10 · Passkeys # Passkeys. Face ID, Touch ID, Windows Hello and hardware security keys — as a second factor next to a password, or on their own with no password at all. Auth verifies the WebAuthn ceremony; your frontend calls navigator.credentials and forwards the result. With @productcraft/auth each ceremony is one call. 1 ## Turn passkeys on for the app Passkeys are off by default on every app. Enabling them means writing one thing you should choose carefully: the relying-party id. Open the app in the console, go to **Settings → Passkeys**, and fill in three fields: - **Passkeys enabled** — the master switch. Turning it off later leaves registered passkeys in place; they simply cannot be used until it is turned back on. - **Relying-party id** — a bare domain, no scheme and no port. `example.com`, not `https://app.example.com`. It must be the host of, or a parent domain of, one of the app's allowed redirect origins; `example.com` covers `app.example.com` and `checkout.example.com`, but not `notexample.com`. - **Display name** — what the operating system's passkey prompt calls you (“Save a passkey for Acme”). Cosmetic, changeable at any time, not part of the credential. ### Choose the relying-party id once **The relying-party id is not a setting, it is a binding.** It is hashed into every credential at registration time. Changing it later does not turn those passkeys off — it makes every one of them fail verification with an rp-id-hash mismatch, which to the user looks like their passkey stopped being trusted and to you looks like an attack. Auth refuses the change outright with a `409` while any passkey exists, and the console warns you before you try. The practical consequence: if you might ever move sign-in from `app.example.com` to `accounts.example.com`, set the rp id to the parent `example.com` now. A parent domain covers both. Going the other way — narrowing from a parent to a subdomain, or widening from a subdomain to a parent — is not possible once a single user has enrolled. ### Ceremony origins The Passkeys page also lists the app's **ceremony origins**: the entries of `allowed_redirect_origins` the rp id actually covers. That list is read-only — you edit it under **Auth config → Federated sign-in policy** — but it is worth reading, because an _empty_ list while passkeys are enabled is the one misconfiguration that is otherwise invisible: every ceremony is refused with `412` and nothing else on the app says why. The usual cause is an edit to the origin list that dropped the site users sign in on. The same config is available over HTTP for IaC: ```bash title="PUT /v1/apps/:app_id/webauthn-config" curl -X PUT https://api.auth.productcraft.co/v1/apps/$APP_ID/webauthn-config \ -H "authorization: Bearer $PRODUCTCRAFT_API_KEY" \ -H 'content-type: application/json' \ -d '{ "enabled": true, "rp_id": "example.com", "rp_name": "Acme", "require_user_verification": true }' # => { # "enabled": true, # "rp_id": "example.com", # "rp_name": "Acme", # "require_user_verification": true, # "ceremony_origins": ["https://app.example.com"], # "credential_count": 0 # } ``` `credential_count` is how many passkeys exist on the app. Non-zero means `rp_id` is frozen — read it before you plan a change rather than discovering it from the 409. `require_user_verification` governs _second-factor_ ceremonies only. Passwordless sign-in always requires user verification whatever this says: when the passkey is the only credential, a presence-only tap means “someone is holding this key”, which is not an authentication. 2 ## Two ways to run a ceremony Every passkey flow is the same three steps: ask Auth for options, hand them to navigator.credentials, post the result back. The SDK does all three in one call; the raw HTTP is shown next to it for everyone else. `@productcraft/auth` **0.7.0 or later** adds a `passkeys` group to the consumer scope — `auth.consumer("acme").passkeys` — with one method per ceremony: `enroll()`, `signIn()`, `completeMfaChallenge()` and `stepUp()`. Each wraps the options call, the `navigator.credentials` prompt and the verify call, with the base64url encoding handled in both directions. **These four run in the browser.** The rest of `@productcraft/auth` is typically used server-side, but a passkey ceremony _is_ a call to `navigator.credentials`, so the passkey helpers belong in your frontend bundle, on a page served from one of the app's ceremony origins. Importing the package in Node is still fine — nothing touches a browser global until you call a ceremony — and calling one there rejects with a `PasskeyError` of code `unsupported` rather than throwing on a missing `window`. Gate the button with `isPasskeySupported()`. It answers `true` only in a secure context with a working `PublicKeyCredential` and `navigator.credentials`, never throws, and is `false` in Node: ```ts title="Show the passkey button only where it can work" import { isPasskeySupported } from "@productcraft/auth"; declare function hidePasskeyButton(): void; if (!isPasskeySupported()) { // Old browser, http:// origin, or not a browser at all. hidePasskeyButton(); } ``` Two error types come out of the helpers, and they are worth telling apart. Anything the _browser_ refuses — the user dismissed the prompt, the page's origin is not covered by the rp id, the authenticator already holds this credential — surfaces as a `PasskeyError` with a `code` of `cancelled`, `timeout`, `invalid_state`, `security`, `no_credential`, `unsupported` or `unknown`, and the original `DOMException` on `cause`. Anything _Auth_ refuses — a 401 on verify, a 412 because passkeys are off — is the same `APIError` every other SDK call throws (a 401 is its `AuthenticationError` subclass), carrying `status`, `code`, `body` and `requestId`. In the **HTTP** tabs below, `api(path, body)` is a thin `fetch` wrapper that POSTs JSON to `https://api.auth.productcraft.co//v1` and sends the end-user's bearer token on the `/me/…` routes. `decodeOptions` and `encodeCredential` are the two encoding helpers from section 5 — the SDK exports them too, so you can mix and match. 3 ## Flow A — a passkey as a second factor The user already has a password. They add a passkey the same way they would add an authenticator app, and it then satisfies the MFA step at sign-in. ### 3a · Enrol `POST /:app_slug/v1/me/mfa/factors` with `{ "type": "webauthn" }`, authenticated as the end-user. The response carries a pending factor plus `enrollment.public_key` to hand to `navigator.credentials.create()`. Confirm with `POST /:app_slug/v1/me/mfa/factors/:id/verify`, which returns the user's recovery codes once. **SDK** ```ts title="@productcraft/auth — enrol a passkey" import { Auth } from "@productcraft/auth"; declare const accessToken: string; // Authenticated as the end-user: pass their access token. const me = new Auth({ auth: { type: "bearer", token: accessToken }, }).consumer("acme"); const { factor, recovery_codes } = await me.passkeys.enroll({ label: "MacBook", // optional; shown in the user's factor list }); // factor.enabled === true // recovery_codes — show these once, they are not retrievable later. ``` **HTTP** ```ts title="Enrol a passkey — raw HTTP" const start = await api('/me/mfa/factors', { type: 'webauthn' }); const cred = (await navigator.credentials.create({ publicKey: decodeOptions(start.enrollment.public_key), })) as PublicKeyCredential; const done = await api(`/me/mfa/factors/${start.factor.id}/verify`, { credential: encodeCredential(cred), }); // done.recovery_codes — show these once, they are not retrievable later. ``` The factor stays disabled until the verify call succeeds, so an abandoned enrolment leaves nothing usable behind. ### 3b · Sign in Sign-in is unchanged up to the point where MFA is required. `POST /:app_slug/v1/auth/signin` answers `{ "mfa_required": true, "mfa_token": "…", "factors": [...] }`. When that list contains a `webauthn` factor, ask for assertion options and submit the result as `credential` instead of `code`: **SDK** ```ts title="@productcraft/auth — complete the MFA challenge" import { Auth } from "@productcraft/auth"; declare const identifier: string; declare const password: string; const anon = new Auth().consumer("acme"); const r = await anon.signin({ identifier, password }); // The result is discriminated on `result`. const session = r.result === "mfa_required" ? await anon.passkeys.completeMfaChallenge({ mfa_token: r.mfa_token }) : r; // session.access_token — amr: ["pwd", "webauthn"], mfa_at set to now. ``` **HTTP** ```ts title="Complete the MFA challenge — raw HTTP" const { public_key } = await api('/auth/mfa/webauthn/options', { mfa_token: signin.mfa_token, }); const cred = (await navigator.credentials.get({ publicKey: decodeOptions(public_key), })) as PublicKeyCredential; const session = await api('/auth/mfa/verify', { mfa_token: signin.mfa_token, credential: encodeCredential(cred), }); // session.access_token — amr: ["pwd", "webauthn"], mfa_at set to now. ``` Possession of the `mfa_token` — i.e. a correct password — is the authority for the options call. Nothing before that point reveals whether an account exists or holds passkeys. ### 3c · Step-up The same pair exists for re-confirming identity inside a live session: `POST /:app_slug/v1/me/mfa/step-up/webauthn/options` then `POST /:app_slug/v1/me/mfa/step-up` with `credential`. A passkey assertion is never tried as a recovery code, so a failed step-up never burns one. **SDK** ```ts title="@productcraft/auth — step-up" import { Auth } from "@productcraft/auth"; declare const accessToken: string; const me = new Auth({ auth: { type: "bearer", token: accessToken }, }).consumer("acme"); const { amr, mfa_at } = await me.passkeys.stepUp({ signal: AbortSignal.timeout(60_000), // give up if the prompt sits unanswered }); // amr now includes "webauthn", mfa_at is fresh — call your sensitive endpoint. ``` **HTTP** ```ts title="Step-up — raw HTTP" const { public_key } = await api('/me/mfa/step-up/webauthn/options', {}); const cred = (await navigator.credentials.get({ publicKey: decodeOptions(public_key), })) as PublicKeyCredential; const { amr, mfa_at } = await api('/me/mfa/step-up', { credential: encodeCredential(cred), }); // amr now includes "webauthn", mfa_at is fresh — call your sensitive endpoint. ``` 4 ## Flow B — passwordless sign-in Two calls, no password, no email address. The authenticator finds its own passkey for your relying-party id. **SDK** ```ts title="@productcraft/auth — passwordless sign-in" import { Auth, isPasskeySupported, PasskeyError } from "@productcraft/auth"; declare function hidePasskeyButton(): void; if (!isPasskeySupported()) hidePasskeyButton(); const anon = new Auth().consumer("acme"); try { const session = await anon.passkeys.signIn({ mediation: "conditional", // autofill-style UI; omit for a plain prompt }); // session.access_token — amr: ["webauthn"], fresh mfa_at. } catch (e) { if (e instanceof PasskeyError && e.code === "cancelled") { // The user dismissed the prompt, or no passkey matched. Not an error to show. } else { throw e; // AuthenticationError (401) for a forged / replayed / expired assertion } } ``` **HTTP** ```ts title="Passwordless sign-in — raw HTTP" const { public_key } = await api('/auth/passkey/options', {}); const cred = (await navigator.credentials.get({ publicKey: decodeOptions(public_key), mediation: 'optional', // 'conditional' for autofill-style UI })) as PublicKeyCredential; const session = await api('/auth/passkey/verify', { credential: encodeCredential(cred), }); // session.access_token — amr: ["webauthn"], fresh mfa_at. ``` ### Why the options call takes no email address `/auth/passkey/options` accepts no identifier, looks nothing up, and returns an **always-empty** `allowCredentials`. That is deliberate. An endpoint that returned a credential list for a registered address and an empty list for an unregistered one would answer “does this account exist here?” in a single unauthenticated request — exactly the oracle the sign-in endpoint was hardened against. Discoverable (resident) credentials make the allow-list unnecessary: the authenticator already knows which passkey belongs to your rp id. The SDK holds the same line: `signIn()` has no identifier parameter to pass. The only body member it will send is `tenant_id`, and only when you give one on a multi-tenant app. `/auth/passkey/verify` answers a uniform `401` for a forged assertion, an unknown credential, a challenge that was never issued, one already used, and one that expired. You cannot tell those apart from outside, and neither can anyone else. Because passwordless sign-in mandates user verification, the resulting tokens carry `amr: ["webauthn"]` and a fresh `mfa_at` — a passkey sign-in satisfies an MFA-recency policy on its own, with no second step. 5 ## What the SDK does under the hood — the encoding layer WebAuthn speaks ArrayBuffer; JSON does not. Every buffer crossing the wire is base64url, and getting the alphabet or the padding wrong produces a signature failure rather than a parse error. If you are not on Node or TypeScript, this is the part you write yourself. **base64url, not base64**: `-` and `_` instead of `+` and `/`, and no `=` padding. Two helpers cover every call above; paste them once. This is, character for character, what the SDK ships — and it exports each piece by name if you want them without the ceremony wrappers: `toB64u`, `fromB64u`, `decodeOptions`, `encodeCredential`, plus `createPasskeyCredential(publicKey)` and `getPasskeyCredential(publicKey)` for the `navigator.credentials` step on its own. ```ts title="passkeys.ts — the whole encoding layer" const toB64u = (buf: ArrayBuffer): string => btoa(String.fromCharCode(...new Uint8Array(buf))) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); const fromB64u = (s: string): Uint8Array => { const b64 = s.replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(b64.padEnd(Math.ceil(b64.length / 4) * 4, '=')); return Uint8Array.from(bin, (c) => c.charCodeAt(0)); }; /** Auth returns public_key with every buffer base64url-encoded; * navigator.credentials wants real ArrayBuffers. */ function decodeOptions(publicKey: any) { const out = { ...publicKey, challenge: fromB64u(publicKey.challenge) }; if (publicKey.user) { out.user = { ...publicKey.user, id: fromB64u(publicKey.user.id) }; } for (const list of ['excludeCredentials', 'allowCredentials'] as const) { if (publicKey[list]) { out[list] = publicKey[list].map((c: any) => ({ ...c, id: fromB64u(c.id), })); } } return out; } /** …and the reverse, for the credential you send back. */ function encodeCredential(cred: PublicKeyCredential) { const r = cred.response as any; const response: Record = { clientDataJSON: toB64u(r.clientDataJSON), }; if (r.attestationObject) response.attestationObject = toB64u(r.attestationObject); if (r.authenticatorData) response.authenticatorData = toB64u(r.authenticatorData); if (r.signature) response.signature = toB64u(r.signature); if (r.userHandle) response.userHandle = toB64u(r.userHandle); return { id: cred.id, response }; } ``` The keys _inside_ `public_key` arrive in the WebAuthn spec's camelCase — `rpId`, `pubKeyCredParams`, `authenticatorSelection.residentKey` — exactly as `navigator.credentials` wants them, so the sketch above can hand them over once the buffers are decoded. They are the browser's names, not ours to rename. The SDK's `decodeOptions` additionally accepts a snake_case `public_key` and renames it on the way in (values untouched), so it keeps working against an Auth build from before 2026-09-20 that snake_cased those keys. The member names inside `response` — `clientDataJSON`, `attestationObject`, `authenticatorData` — are fixed by the WebAuthn spec and are sent **verbatim**. Together with the keys inside `public_key`, they are the only places in the Auth API that are not snake_case on the wire, because they are not ours to rename. Everything outside the `credential` and `public_key` objects follows the usual snake_case convention. 6 ## What to expect when it goes wrong The three failures worth recognising on sight. - **The button does nothing and no request is sent.** The browser refused the ceremony client-side with a `SecurityError` because the page's origin is not covered by the rp id. With the SDK this is a `PasskeyError` of code `security`. Check the ceremony-origin list on the Passkeys page against the host you are actually serving from. - **`412` on every ceremony.** Either passkeys are not enabled for the app, or they are enabled and no allowed redirect origin matches the rp id. The error body names which; the SDK throws it as an `APIError` with `status === 412`. - **`409` on the config write.** You are trying to move `rp_id` while passkeys exist. Every one of them is bound to the old value; they have to be removed first. Read `credential_count` on the GET to see how many. Challenges expire five minutes after they are minted and are single-use, so a stale tab retrying an old ceremony gets a `401` rather than a session. Pass an `AbortSignal` to any SDK ceremony to bound how long the prompt may sit open; an aborted prompt surfaces as `PasskeyError` `cancelled`, a browser-side timeout as `timeout`. Next ## Where to go from here - [Quickstart](https://productcraft.co/docs/auth/getting-started.md) — if signup + signin are not wired up yet, start there. - [06 · Verify tokens](https://productcraft.co/docs/auth/guides/06-verify-tokens.md) — what to do with the `amr` and `mfa_at` claims a passkey sign-in produces. - [11 · Migrating users](https://productcraft.co/docs/auth/guides/11-migrating-users.md) — bringing an existing user base over, password hashes included. - [API reference](https://productcraft.co/docs/auth/api-reference.md) — the full request and response schemas for every endpoint above. --- title: "11 · Migrating users | Auth Guides" description: "Bulk-import an existing user base as NDJSON with argon2id or bcrypt password hashes, read the per-row error report, watch credentials upgrade to argon2id on first signin, and export the directory back out." url: https://productcraft.co/docs/auth/guides/11-migrating-users --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 11 · Migrating users # Migrating users from another provider. Bring your directory over in one call — emails, usernames, roles, tenants, metadata and the password hashes you already hold. Nobody resets a password unless their hash is one Auth cannot verify at the same cost as its own. 1 ## What an import row looks like POST /v1/apps/:appId/end-users/import takes NDJSON — one JSON object per line, up to 20 MiB or 50,000 rows per call. Auth-admin lane: a workspace API key or your console session with auth.user.import on the app. ```json title="users.ndjson" {"email":"ada@example.com","username":"ada","display_name":"Ada Lovelace","role":"admin","tenant_slugs":["acme"],"external_id":"auth0|5f3c...","email_verified":true,"metadata":{"plan":"pro"},"password_hash":"$2b$10$R6DYoIs4PvhuM/Id4Xvl1u0MaPH4Bxt.uS0cJGv1CP0y82VnEKnIe","password_hash_algorithm":"bcrypt"} {"email":"grace@example.com","password_hash":"$argon2id$v=19$m=65536,t=3,p=2$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG","password_hash_algorithm":"argon2id"} {"email":"linus@example.com","email_verified":true} ``` Only `email` is required. `username` is derived from the local part when absent, `role` falls back to the app's signup default, and a row without `password_hash` creates an account that signs in once its owner completes a password reset (or a passkey / federated sign-in, if the app offers them). Field names are accepted in snake_case or camelCase. **Re-runs are idempotent.** Rows match on `external_id` first, then on the primary email, and update rather than duplicate. Three things are never overwritten on an update: an existing password credential, an address that is already verified, and an existing member's role unless the row names one. So re-running yesterday's file does not roll anyone's password back or demote your admins. 2 ## Password hashes: argon2id and bcrypt A hash without a password_hash_algorithm is refused — Auth never guesses. Two algorithms are accepted. - **`argon2id`** — any parameters; the PHC string carries them. Verified exactly like a credential Auth produced itself. - **`bcrypt`** — `$2a$`, `$2b$` or `$2y$` (the PHP flavour), 60 characters, **cost 4 to 10**. This covers Auth0, PHP's `password_hash`, Spring Security, node `bcrypt` and Laravel 10 at their defaults. The hash is stored as you sent it and verified the first time the user signs in; that same request replaces it with an argon2id hash of the password they just typed. The user sees an ordinary signin. The upgrade is written to the app's audit log as `auth.password.upgraded`. **Every bcrypt cost is accepted; here is the one trade.** Auth answers every signin attempt in the same time whether or not the identifier exists, so the signin form cannot be used to enumerate your users by timing. That floor is the cost of an argon2id verify. A bcrypt verify at cost 10 or below (Auth0, Spring, node `bcrypt`, PHP defaults) is cheaper than the floor, so Auth pads it up to the floor and an imported account is indistinguishable from any other. A bcrypt verify at cost 11 or 12 (Devise and Rails `has_secure_password`, Laravel 11+, Django's bcrypt hasher) is _slower_ than the floor, and time already spent cannot be padded away — so until such an account signs in once and is re-hashed, it answers roughly a second later than an unknown identifier. We accept those rows anyway: the difference is small, applies only to not-yet-migrated accounts, and disappears on first signin. If that trade is not acceptable for a particular user set, import those rows without `password_hash` and send them through password reset. Shape problems are caught at import too: a hash tagged `argon2id` that does not start `$argon2id$`, or one tagged `bcrypt` that is not a 60-character modular-crypt string, is reported in the job's error list rather than discovered at the user's first signin. 3 ## Queue the import and read the report The call returns 202 with a job id. Send an Idempotency-Key so a retried upload does not queue a second job over the same file. ```bash title="POST /v1/apps/:appId/end-users/import" curl https://api.auth.productcraft.co/v1/apps//end-users/import \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/x-ndjson' \ -H 'idempotency-key: migration-2026-09-24-batch-1' \ --data-binary @users.ndjson # 202 { "id": "", "status": "queued", "total_rows": 3, "processed_rows": 0, ... } ``` ```json title="GET /v1/apps/:appId/end-users/import/:jobId" { "id": "", "status": "succeeded", "total_rows": 3, "processed_rows": 3, "created_count": 2, "updated_count": 0, "failed_count": 1, "errors": [ { "line": 2, "error": "`password_hash` is tagged bcrypt but is not a 60-character `$2a$`/`$2b$`/`$2y$` modular-crypt hash" } ], "started_at": "2026-09-24T09:12:03Z", "finished_at": "2026-09-24T09:12:04Z" } ``` `succeeded` means the job ran to completion, not that every row landed — read `failed_count` and `errors`. Each error carries the 1-based line number of the uploaded file and a message that is actionable on its own. The first 500 errors are recorded; the counts stay exact past that. Split a larger migration into several calls; that is also how you get a report you can read. The import itself is audited as `users.imported` with the row count. Password hashes are never echoed back on the job. 4 ## Watch the migration complete Every first signin against a bcrypt credential writes an audit row when it upgrades the hash. ```json title="GET /v1/apps/:appId/audit-logs?action=auth.password.upgraded" { "data": [ { "id": "0e2b1c6a-…", "app_id": "", "action": "auth.password.upgraded", "resource_type": "account", "resource_id": "", "actor_id": "", "metadata": { "from": "bcrypt", "to": "argon2id" }, "created_at": "2026-09-25T07:41:19Z" } ], "pagination": { "next_cursor": null, "has_more": false } } ``` Once every imported user has signed in once, no bcrypt hash remains in your app. Users who never come back keep a bcrypt credential that still verifies; there is nothing you need to do about them. 5 ## Export the directory The other direction: GET /v1/apps/:appId/end-users/export streams the directory as NDJSON or CSV, with the list's filters. ```bash title="GET /v1/apps/:appId/end-users/export" curl 'https://api.auth.productcraft.co/v1/apps//end-users/export?format=ndjson&status=active' \ -H 'authorization: Bearer pcft_live_...' > users.ndjson ``` Gated on `auth.user.export`, which is escalation class: it hands over every address in the directory in one call. Streamed oldest-first so a re-run is stable; a request matching more than 1,000,000 users is refused with 413 before any byte is written — narrow it with `status`, `search` or `provider`. Password hashes are not exported. [API reference →](https://productcraft.co/docs/auth/api-reference.md) --- title: "12 · Sign in with Google | Auth Guides" description: "Add Sign in with Google to an Auth app: create a Web application OAuth client in Google Cloud, paste the redirect URI the console shows, save the credentials (Auth checks them with Google), Try sign-in, then add the button to your site." url: https://productcraft.co/docs/auth/guides/12-signin-with-google --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 12 · Sign in with Google # Sign in with Google. About ten minutes, most of it in Google Cloud. The console walks you through it in five steps and tells you straight away whether Google accepts what you pasted, so you find a typo now instead of from a user. 1 ## Open the guided setup In the console, open Auth, pick your app, then Settings. Under Federated sign-in providers, select Set up on the Google row. The page opens on **Set up Google sign-in**: five numbered steps with the exact values for your app filled in. Keep it open next to Google Cloud. Each step turns green as you finish it: 1. Create the client at Google 2. Paste the redirect URI 3. Scopes 4. Paste the credentials and save 5. Try sign-in You need a Google account that can create OAuth clients in a Google Cloud project (Owner or Editor on the project). 2 ## Create the OAuth client in Google Cloud Step 1 links straight to Google Cloud Credentials. Pick or create the project your app belongs to. ### 2a · The consent screen, once per project If Google asks you to configure the consent screen first, do that: choose audience **External** (anyone with a Google account) unless only people in your own Google Workspace should sign in, then fill in the app name, a support email and a developer contact email. This is what your users see when Google asks them to continue to your app. Under **Data access**, add the three scopes Auth asks for (step 3 in the console lists them too): - `openid`: proves who the user is. - `email`: their email address and whether Google verified it. - `profile`: their name and picture. Google does not review apps that ask for these three only. While the app is in **Testing**, only the test users you list can sign in; select **Publish app** when you are ready for everyone. ### 2b · The OAuth client 1. Select **Create credentials**, then **OAuth client ID**. 2. Application type: **Web application**. Other types (Android, iOS, Desktop) cannot be used for the website sign-in, and Google rejects their secret. 3. Under **Authorized redirect URIs**, add the URL from step 2 in the console. Use the Copy button: Google compares it character by character. It looks like this, with your app's slug: ```title="Authorized redirect URI" https://api.auth.productcraft.co//v1/auth/oauth/google/callback ``` Leave **Authorized JavaScript origins** empty: the sign-in runs through Auth, not through JavaScript on your page. Select **Create**. Google shows the **Client ID** (ending in `.apps.googleusercontent.com`) and the **Client secret** (starting with `GOCSPX-`). 3 ## Paste the credentials and save Step 4 points at the form under the steps. Paste the Client ID and Client secret and select Configure. When you save, Auth asks Google whether it knows this client: it sends Google's token endpoint a code that cannot work and reads the answer. No one is signed in and nothing is created. The answer shows on step 4 straight away: - **Accepted**: Google knows the client and the secret matches. Go on to Try sign-in. - **Rejected** (`invalid_client`): Google does not know this Client ID, or the secret belongs to another client. Open the client in Google Cloud and copy both values again. If the error is `unauthorized_client`, the client is not of type Web application: create one that is. Sign-in with Google stays blocked until this is fixed. - **Check** (redirect URI): Google accepts the credentials but the redirect URI registered there is different from step 2. Paste it again exactly. - **Could not check**: Google could not be reached. Nothing is blocked; select **Check again** in a minute. The secret is stored encrypted and never shown again. To change it later, paste a new one in **Replace client secret**; leave the field empty to keep the one on file. 4 ## Try sign-in, then switch it on Step 5 runs the whole round trip in a small window: you sign in at Google and the console shows who would have signed in to your app. Try sign-in creates no account and issues no token, and it works before the provider is switched on. If something is wrong, the result names the fix. The most common one is `redirect_uri_mismatch`, with the exact URL to paste into Google Cloud. When the test passes: 1. Switch on **Enabled** at the bottom of the page and save. 2. On the app's Settings, add the site your users sign in from under **Allowed redirect origins** (for example `https://app.acme.com`). Without at least one, Auth refuses every web sign-in and the provider shows **Blocked**. The Google row then shows **Ready**: checked by the server with the same rule sign-in uses. 5 ## Add the button to your site A link to Auth, then one server-side call. Tokens never travel through a URL. ```html title="Your sign-in page" Sign in with Google ``` Auth sends the user to Google, Google sends them back to Auth, and Auth sends them to your `return_to` with a one-time code: `https://app.acme.com/login/done?heimdall_code=…`. The origin of `return_to` must be one of your allowed redirect origins. Your backend swaps the code for tokens: ```ts title="Your backend: code to tokens" import { Auth, AuthenticationError } from "@productcraft/auth"; const consumer = new Auth().consumer("acme"); async function completeProviderSignIn(code: string) { try { // code: the heimdall_code query value const { access_token, refresh_token, expires_in } = await consumer.exchangeProviderCode({ code }); // Drop into your session cookie / store as you'd handle a sign-in. return { access_token, refresh_token, expires_in }; } catch (err) { // 401: unknown, expired or already used if (err instanceof AuthenticationError) return null; throw err; } } ``` The code works once, for 60 seconds, for this app only. When sign-in fails, the user comes back with `heimdall_error` instead of a code: - `provider_error`: the user cancelled at Google or Google refused the request. - `token_invalid`: the ID token from Google failed a check (signature, audience, nonce or hosted domain). - `link_required` or `account_exists_with_different_provider`: an account with this email already exists and your linking policy does not link it automatically (see the [Apple guide](https://productcraft.co/docs/auth/guides/09-signin-with-apple.md), section 5; the policy is the same for every provider). The access token's `amr` claim is `["oauth", "google"]`, and the `user.signup` / `user.signin` webhooks carry `"provider": "google"`. 6 ## Optional settings Both live on the same Google page in the console. - **Hosted domain restriction**: list Google Workspace domains (for example `acme.com`) and only accounts in those domains can sign in. Others are refused with `token_invalid`. Leave it empty to accept any Google account. - **Native sign-in** (iOS and Android): add the client IDs of your native Google clients. Your app gets an ID token from the Google Sign-In SDK (pass the SHA-256 hex of a random nonce to Google) and posts it with the raw nonce to `POST //v1/auth/oauth/google` as `{ "id_token": "…", "nonce": "…" }`. With no native client IDs, that endpoint refuses every request with a 400. [Back to all guides](https://productcraft.co/docs/auth/guides.md) --- title: "13 · Sign in with GitHub | Auth Guides" description: "Add Sign in with GitHub to an Auth app: register a GitHub OAuth app with the callback URL the console shows, save the Client ID and secret (Auth checks them with GitHub), Try sign-in, then add the button to your site." url: https://productcraft.co/docs/auth/guides/13-signin-with-github --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 13 · Sign in with GitHub # Sign in with GitHub. Five minutes. Register an OAuth app at GitHub, paste one URL there and two values back, and the console tells you on save whether GitHub accepts them. Web only: GitHub has no native ID token. 1 ## Open the guided setup In the console, open Auth, pick your app, then Settings. Under Federated sign-in providers, select Set up on the GitHub row. The page opens on **Set up GitHub sign-in**: five numbered steps with your app's values filled in. Each step turns green as you finish it: create the client at GitHub, paste the redirect URI, scopes, paste the credentials and save, Try sign-in. 2 ## Register an OAuth app at GitHub Step 1 links to New OAuth app under your personal Developer settings. For an app owned by your company, register it under the organization instead: Organization settings, Developer settings, OAuth Apps. Choose an **OAuth app**, not a GitHub App. GitHub Apps are for acting on repositories; OAuth apps are for signing people in. - **Application name** and **Homepage URL**: your product. GitHub shows both on the consent screen. - **Authorization callback URL**: the URL from step 2 in the console. Use the Copy button. It looks like this, with your app's slug: ```title="Authorization callback URL" https://api.auth.productcraft.co//v1/auth/oauth/github/callback ``` Leave **Enable Device Flow** off and select **Register application**. On the next page, copy the **Client ID**, then select **Generate a new client secret**. GitHub shows the secret once: copy it now. ### Scopes Nothing to set at GitHub. OAuth apps ask for scopes when the user signs in, and Auth asks for two: - `read:user`: their GitHub profile (a stable user id, login, name and avatar). - `user:email`: their email addresses, so Auth can use the primary verified one even when the user keeps it private on their profile. 3 ## Paste the credentials and save Step 4 points at the form under the steps. Paste the Client ID and the client secret and select Configure. When you save, Auth asks GitHub whether it knows this client: it sends GitHub's token endpoint a code that cannot work and reads the answer. No one is signed in. The answer shows on step 4: - **Accepted**: GitHub knows the client and the secret matches. Go on to Try sign-in. - **Rejected** (`incorrect_client_credentials`): GitHub does not recognise this Client ID and secret pair. The usual causes are a secret that was deleted or regenerated at GitHub, or a Client ID from a different OAuth app. Open the app at GitHub, copy the Client ID, generate a new secret and paste both. If GitHub has never heard of the Client ID at all (a typo, or the ID of a GitHub App), the error is `unknown_client`. Sign-in with GitHub stays blocked until this is fixed. - **Could not check**: GitHub could not be reached. Nothing is blocked; select **Check again** in a minute. The secret is stored encrypted and never shown again. To rotate it, generate a new secret at GitHub, paste it into **Replace client secret** and save, then delete the old secret at GitHub. 4 ## Try sign-in, then switch it on Step 5 runs the whole round trip in a small window: you authorize at GitHub and the console shows who would have signed in. Try sign-in creates no account and issues no token, and works before the provider is switched on. A wrong callback URL shows as `redirect_uri_mismatch` with the exact URL to paste at GitHub. When the test passes: 1. Switch on **Enabled** at the bottom of the page and save. 2. On the app's Settings, add the site your users sign in from under **Allowed redirect origins**. Without at least one, Auth refuses every web sign-in and the provider shows **Blocked**. 5 ## Add the button to your site Same two pieces as every provider: a link to Auth and one server-side call. ```html title="Your sign-in page" Sign in with GitHub ``` The user comes back to your `return_to` with `?heimdall_code=…` (the origin must be one of your allowed redirect origins). Your backend swaps it for tokens: ```ts title="Your backend: code to tokens" import { Auth, AuthenticationError } from "@productcraft/auth"; const consumer = new Auth().consumer("acme"); async function completeProviderSignIn(code: string) { try { // code: the heimdall_code query value const { access_token, refresh_token, expires_in } = await consumer.exchangeProviderCode({ code }); // Drop into your session cookie / store as you'd handle a sign-in. return { access_token, refresh_token, expires_in }; } catch (err) { // 401: unknown, expired or already used if (err instanceof AuthenticationError) return null; throw err; } } ``` The code works once, for 60 seconds. On failure the user comes back with `heimdall_error`: `provider_error` when they cancel at GitHub, `token_invalid` when the user's primary verified email is outside your allowed domains, and `link_required` / `account_exists_with_different_provider` when an account with that email already exists and your linking policy does not link it. The access token's `amr` claim is `["oauth", "github"]`, and the `user.signup` / `user.signin` webhooks carry `"provider": "github"`. 6 ## Optional: allowed email domains On the same GitHub page in the console. List domains (for example `acme.com`) and only users whose primary verified GitHub email is in one of them can sign in. Leave it empty to accept any GitHub user. A user with no verified email on GitHub signs in without an email address. GitHub has no native sign-in: it does not issue ID tokens, so mobile apps use the same web flow in a browser tab. [Back to all guides](https://productcraft.co/docs/auth/guides.md) --- title: "14 · Let your customers create API keys | Auth Guides" description: "Adopt tenant API keys in your app: grant your Platform API key the two actions, push the key settings on boot, verify keys in your API with a cache, single-flight and a failed-verify budget, proxy key management through your backend, and accept keys only on the routes you mark." url: https://productcraft.co/docs/auth/guides/14-tenant-api-keys --- [Auth guides](https://productcraft.co/docs/auth/guides.md) 14 · Tenant API keys # Let your customers create API keys. Your customers want to drive your API from CI and from their end-to-end tests. Tenant API keys let the members of each tenant create keys for exactly that, while Auth stores and verifies them. This chapter adopts them in five steps. Read [Tenant API keys](https://productcraft.co/docs/auth/concepts/tenant-api-keys.md) first for the model: the key format, the scope ceiling, expiry, rotate vs revoke, and what happens when a creator leaves. The examples below use a disputes product with scopes like `disputes.read`; swap in your own. Before you start ## What you need - An Auth app that uses [tenants](https://productcraft.co/docs/auth/guides/04-tenants.md). Keys belong to a tenant, and only a member signed into that tenant can create one. - A Platform API key (`pcft_live_…`) for your app's backend, from the workspace that owns the app. - Your own map from a tenant role to the permissions it holds in your app. You will intersect every key's scopes with it. Every call below goes to `https://api.auth.productcraft.co`. All of the endpoints are in the [API reference](https://productcraft.co/docs/auth/api-reference.md) under _Consumer-Tenant-Api-Keys_. 1 ## Grant your Platform API key the two actions Your backend's key needs auth.tenant.api_keys.introspect (verify keys, read a key's status, proxy management) and auth.tenant.api_keys.configure (push the settings), on this app. ```json title="Policy statement for your backend's Platform API key" { "effect": "allow", "actions": ["auth.tenant.api_keys.introspect", "auth.tenant.api_keys.configure"], "resources": ["pcft:heimdall:app/"] } ``` In the console these show as _Verify tenant API keys_ and _Configure tenant API keys_. See [Workspace API keys for CI/CD](https://productcraft.co/docs/platform/guides/04-pats-for-cicd.md) for creating a policy and binding it to a key. **This step is the one people miss.** A policy that lists actions without a wildcard does not cover the new ones, and every introspection then fails with `403`. The key must also belong to the workspace that owns the app, or the answer is `403 PAK_WORKSPACE_MISMATCH`. The snippets below read it as `PRODUCTCRAFT_API_KEY` and the app slug as `PRODUCTCRAFT_AUTH_APP`, the same names the console's getting-started `.env` writes. It is your workspace key with `auth.tenant.api_keys.introspect` granted, so a key minted from a narrow preset that lacks it gets `403`. 2 ## Enable keys and push your settings on boot Your code knows which permissions a key may carry, so your app pushes the settings itself every time it starts. **curl** ```bash title="PUT /:appSlug/v1/tenant-api-keys/config" curl -X PUT https://api.auth.productcraft.co/acme/v1/tenant-api-keys/config \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -H 'idempotency-key: config-2026-10-23' \ -d '{ "enabled": true, "grantable_scopes": [ { "name": "disputes.read", "description": "Read disputes" }, { "name": "reports.create", "description": "Create reports" }, { "name": "audit.read", "description": "Read the activity log" } ], "manage_roles": ["owner"], "management_lane": "app_proxy_only", "default_expiry_days": 90, "max_expiry_days": 365 }' ``` **TypeScript** ```ts title="boot.ts" // On boot, before you serve traffic. Your code is the source of truth. const res = await fetch( 'https://api.auth.productcraft.co/' + process.env.PRODUCTCRAFT_AUTH_APP + '/v1/tenant-api-keys/config', { method: 'PUT', headers: { authorization: 'Bearer ' + process.env.PRODUCTCRAFT_API_KEY, 'content-type': 'application/json', 'idempotency-key': 'config-' + process.env.GIT_SHA, }, body: JSON.stringify({ enabled: true, grantable_scopes: [ { name: 'disputes.read', description: 'Read disputes' }, { name: 'reports.create', description: 'Create reports' }, { name: 'audit.read', description: 'Read the activity log' }, ], manage_roles: ['owner'], management_lane: 'app_proxy_only', default_expiry_days: 90, max_expiry_days: 365, }), }, ); if (!res.ok) throw new Error('tenant API key config push failed: ' + res.status); ``` The response is the full stored configuration. Fields you leave out keep their stored value; `grantable_scopes` replaces the whole list. - `grantable_scopes`: what a key may carry, at most 64, each `.`. Leave out anything a script should never do (managing keys, the team, billing). Enabling with no scopes is refused (`TENANT_API_KEYS_NO_SCOPES`). - `manage_roles`: the tenant roles allowed to create, rotate and revoke keys. Default `["owner"]`. A role your app does not have is refused (`TENANT_API_KEYS_UNKNOWN_ROLE`). - `management_lane`: `direct` (the default) lets a signed-in user call the management endpoints with their own token. `app_proxy_only` accepts the user's token only together with your PAK, so every create, rotate and revoke passes through your backend (step 4). Choose `app_proxy_only` if you keep your own audit trail. - `default_expiry_days` / `max_expiry_days`: from 7, 30, 90 and 365. - `require_recent_mfa_minutes`: optional. When set, creating or rotating a key needs a second factor verified within that many minutes, else `403 step_up_required`. Leave it `null` if your app has no step-up screen yet. Once your app has pushed its settings, the console shows them read-only (your code owns them). The **Suspend all tenant API keys** switch stays in the console; a push that contains `suspended` is refused. 3 ## Verify keys in your API A request arrives with Authorization: Bearer pctk_live_…. Check the shape, look in your cache, and ask Auth only when you must. ```bash title="POST /:appSlug/v1/tenant-api-keys/introspect" curl https://api.auth.productcraft.co/acme/v1/tenant-api-keys/introspect \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "key": "pctk_live_4fQ2aZ..." }' # Active { "active": true, "key_id": "8b1c…", "display_id": "tak_3a9f2b1c0d4e", "tenant_id": "5e2a…", "tenant_display_id": "tnt_3a9f2b1c0d4e", "name": "CI e2e", "scopes": ["disputes.read", "audit.read"], "created_by": { "account_id": "c41d…", "tenant_role": "agent_full" }, "expires_at": "2027-01-21T10:00:00.000Z", "env": "live" } # Anything else: unknown, malformed, revoked, expired, creator gone, # tenant not active, keys suspended, or a key of another app { "active": false } ``` Introspection puts Auth on your request path, so the verifier has to be careful. These are the rules, and the code below follows all of them: - **Typo filter first.** Check the pattern and the CRC32 checksum, and refuse a bad key without a network call. A valid checksum proves nothing; anyone can make one. - **Cache by the key's SHA-256**, never by the raw key. Positive answers for at most 30 seconds and never past `expires_at`; negative answers for up to 60 seconds. Your positive TTL is your revocation latency. - **Single-flight.** Fifty parallel CI workers with one key make one introspection call, not fifty. - **Cap calls in flight and keep a failed-verify budget.** If someone sprays random well-formed keys at you, stop calling Auth for unknown keys once the budget is spent, while cached active keys keep working. - **Fail closed, for uncached keys only.** A timeout, a network error, a `5xx` or a `429` is not a verdict. Refuse that request (`503` with `Retry-After` tells the client to retry) and cache nothing. Never turn it into a cached `{"active": false}`: that would break a customer's valid key for a minute. - **Intersect scopes with the creator's current role.** `created_by.tenant_role` is read live; the key can do only what is both in `scopes` and allowed to that role in your app. Introspection has its own budget of 1,200 calls a minute for your app, separate from your PAK's other calls. With a 30-second cache, that is far more than real traffic needs; it is there so a flood cannot take your sign-ins down with it. ```ts title="tenant-api-keys.ts" // tenant-api-keys.ts: verify a tenant API key presented to YOUR API. import { createHash } from 'node:crypto'; const AUTH_URL = 'https://api.auth.productcraft.co'; const APP_SLUG = process.env.PRODUCTCRAFT_AUTH_APP!; const PAK = process.env.PRODUCTCRAFT_API_KEY!; // pcft_live_…, holds auth.tenant.api_keys.introspect const POSITIVE_TTL_MS = 30_000; // never more than 30 s, never past expires_at const NEGATIVE_TTL_MS = 60_000; const MAX_IN_FLIGHT = 8; // introspect calls in flight per process const FAILED_VERIFY_BUDGET = 60; // unknown keys per minute per process const TIMEOUT_MS = 2_000; export type Verdict = | { active: false } | { active: true; key_id: string; display_id: string; tenant_id: string; // the same tenant id your end-user tokens carry as org_id tenant_display_id: string; name: string; scopes: string[]; created_by: { account_id: string; tenant_role: string }; expires_at: string; env: 'live' | 'test'; }; /** Auth could not give a verdict. Fail closed: refuse the request, cache nothing. */ export class VerifyUnavailable extends Error {} // ---- 1. Typo filter (shape + CRC32 checksum). Not a security control. ---- const KEY_PATTERN = /^pctk_(live|test)_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}$/; const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; const CRC_TABLE = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; }); function crc32(s: string): number { let crc = 0xffffffff; for (let i = 0; i < s.length; i++) crc = CRC_TABLE[(crc ^ s.charCodeAt(i)) & 0xff] ^ (crc >>> 8); return (crc ^ 0xffffffff) >>> 0; } function base62(n: number, width: number): string { let out = ''; while (n > 0) { out = BASE62[n % 62] + out; n = Math.floor(n / 62); } return out.padStart(width, '0'); } export function isWellFormedTenantKey(key: string): boolean { if (!KEY_PATTERN.test(key)) return false; return base62(crc32(key.slice(10, 53)), 6) === key.slice(-6); } // ---- 2. Cache, single-flight, in-flight cap, failed-verify budget. ---- const cache = new Map(); const inFlight = new Map>(); let budgetWindow = Date.now(); let failedInWindow = 0; export async function verifyTenantKey(key: string): Promise { if (!isWellFormedTenantKey(key)) return { active: false }; const hash = createHash('sha256').update(key).digest('hex'); // never cache by the raw key const now = Date.now(); const hit = cache.get(hash); if (hit && hit.until > now) return hit.verdict; cache.delete(hash); const pending = inFlight.get(hash); if (pending) return pending; // concurrent requests with one key share one call if (now - budgetWindow >= 60_000) { budgetWindow = now; failedInWindow = 0; } // Budget spent (someone is spraying random keys): refuse unknown keys // without calling Auth. Keys already cached as active keep working. if (failedInWindow >= FAILED_VERIFY_BUDGET) return { active: false }; if (inFlight.size >= MAX_IN_FLIGHT) throw new VerifyUnavailable('verify capacity'); const call = introspect(key) .then((verdict) => { const at = Date.now(); if (verdict.active) { const until = Math.min(at + POSITIVE_TTL_MS, Date.parse(verdict.expires_at)); cache.set(hash, { verdict, until }); } else { failedInWindow += 1; cache.set(hash, { verdict, until: at + NEGATIVE_TTL_MS }); } return verdict; }) .finally(() => inFlight.delete(hash)); inFlight.set(hash, call); return call; } async function introspect(key: string): Promise { let res: Response; try { res = await fetch(AUTH_URL + '/' + APP_SLUG + '/v1/tenant-api-keys/introspect', { method: 'POST', headers: { authorization: 'Bearer ' + PAK, 'content-type': 'application/json' }, body: JSON.stringify({ key }), // the key goes in the body, never in a header signal: AbortSignal.timeout(TIMEOUT_MS), }); } catch { throw new VerifyUnavailable('introspect unreachable'); } if (res.status === 200) return (await res.json()) as Verdict; // 429 (your app's introspect bucket), 5xx, or 401/403 (a PAK problem) are // not verdicts. Never cache them as {active:false}. throw new VerifyUnavailable('introspect answered ' + res.status); } ``` The cache and the budget live in each process, so with several replicas each one keeps its own; the numbers above are per replica. Revoking a key takes effect in Auth at once and in your API within your positive TTL. 4 ## Let your customers manage keys through your backend With management_lane: app_proxy_only, your API exposes its own api-keys routes and forwards each call to Auth with the signed-in user's token plus your PAK. Auth still decides who may manage keys: the user must be signed into the tenant, their tenant role must be in `manage_roles`, and every scope must be within their own role. Your backend adds the PAK in `X-Heimdall-App-Key` (it needs `auth.tenant.api_keys.introspect`) and records the change in your own audit trail. **curl** ```bash title="The four management calls" # Create (201; "key" is the secret, returned once) curl https://api.auth.productcraft.co/acme/v1/tenant-api-keys \ -H 'authorization: Bearer ' \ -H 'x-heimdall-app-key: pcft_live_...' \ -H 'idempotency-key: 6f1c2a8e-…' \ -H 'content-type: application/json' \ -d '{ "name": "CI e2e", "scopes": ["disputes.read", "audit.read"], "expires_in_days": 30 }' # List (newest first; ?status=active|expired|revoked, ?limit=, ?cursor=) curl 'https://api.auth.productcraft.co/acme/v1/tenant-api-keys?status=active' \ -H 'authorization: Bearer ' \ -H 'x-heimdall-app-key: pcft_live_...' # Rotate (201; new secret once; old key revoked now, or after grace_hours ≤ 24) curl -X POST https://api.auth.productcraft.co/acme/v1/tenant-api-keys/tak_3a9f2b1c0d4e/rotate \ -H 'authorization: Bearer ' \ -H 'x-heimdall-app-key: pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "grace_hours": 1 }' # Revoke (204, immediate, idempotent) curl -X DELETE https://api.auth.productcraft.co/acme/v1/tenant-api-keys/tak_3a9f2b1c0d4e \ -H 'authorization: Bearer ' \ -H 'x-heimdall-app-key: pcft_live_...' ``` **TypeScript** ```ts title="api-keys.route.ts" // Your API's own route: POST /v1/api-keys (the signed-in user creates a key). app.post('/v1/api-keys', requireUser, async (req, res) => { const upstream = await fetch( 'https://api.auth.productcraft.co/' + process.env.PRODUCTCRAFT_AUTH_APP + '/v1/tenant-api-keys', { method: 'POST', headers: { authorization: 'Bearer ' + req.userAccessToken, // the END USER's token 'x-heimdall-app-key': process.env.PRODUCTCRAFT_API_KEY!, // your app's PAK 'content-type': 'application/json', ...(req.get('idempotency-key') ? { 'idempotency-key': req.get('idempotency-key')! } : {}), }, body: JSON.stringify({ name: req.body.name, scopes: req.body.scopes, expires_in_days: req.body.expires_in_days, }), }, ); const body = await upstream.json(); if (upstream.ok) { await audit.record('api_key.created', { keyId: body.id, by: req.user.id }); // never body.key } res.setHeader('Cache-Control', 'no-store'); res.status(upstream.status).json(body); // body.key is the secret, shown once }); ``` - **The secret is never replayed.** Retrying a create or rotate with the same `Idempotency-Key` returns `409 idempotency_secret_not_replayable` with `details.key_id`, not the secret again. If your user lost the response, revoke that key and create a new one. - **Pass `Cache-Control: no-store` through**, and never log the request or response body of these calls. - Errors your UI should explain: `403` `TENANT_API_KEYS_FORBIDDEN` (role not in `manage_roles`), `TENANT_API_KEY_SCOPE_ABOVE_CEILING` (`details.scopes`), `TENANT_CONTEXT_REQUIRED` (the user has not switched into a tenant), `step_up_required`; `409 TENANT_API_KEY_LIMIT` (25 active keys). Keys can also die without passing through your backend: they expire, their creator leaves the tenant, or you revoke one in the console. When your verifier sees a key go inactive, ask why and record it: ```bash title="GET /:appSlug/v1/tenant-api-keys/:keyId/status" curl https://api.auth.productcraft.co/acme/v1/tenant-api-keys/tak_3a9f2b1c0d4e/status \ -H 'authorization: Bearer pcft_live_...' { "status": "revoked", "revoke_reason": "member_removed" } # status: active | expired | revoked | orphaned | suspended # revoke_reason: manual | rotated | member_removed | tenant_deleted | null ``` 5 ## Accept keys only where you mean to Default deny: a tenant API key works on a route only if that route says so. Mark each route a key may call with the scope it needs, and make your normal authentication refuse any `pctk_` bearer everywhere else. A key should never reach the routes that manage keys, members or billing, whatever its scopes say. ```ts title="accepts-tenant-key.ts" // Accept tenant API keys only on routes that opt in (Express shown). import type { NextFunction, Request, Response } from 'express'; import { verifyTenantKey, VerifyUnavailable } from './tenant-api-keys'; import { permissionsOfTenantRole } from './permissions'; // YOUR role → permission grid export function acceptsTenantKey(scope: string) { return async (req: Request, res: Response, next: NextFunction) => { const header = req.headers.authorization ?? ''; const bearer = header.startsWith('Bearer ') ? header.slice(7).trim() : ''; if (!bearer.startsWith('pctk_')) return next(); // not a key: your normal auth runs let verdict; try { verdict = await verifyTenantKey(bearer); } catch (err) { if (err instanceof VerifyUnavailable) { res.setHeader('Retry-After', '5'); return res.status(503).json({ code: 'AUTH_UNAVAILABLE' }); } throw err; } if (!verdict.active) return res.status(401).json({ code: 'INVALID_API_KEY' }); // The ceiling, again: the key's scopes ∩ what its creator's CURRENT role allows. const allowed = permissionsOfTenantRole(verdict.created_by.tenant_role); const effective = verdict.scopes.filter((s) => allowed.has(s)); if (!effective.includes(scope)) { return res.status(403).json({ code: 'SCOPE_MISSING', scope }); } req.principal = { type: 'api_key', keyId: verdict.key_id, tenantId: verdict.tenant_id, // map to your tenant exactly like org_id scopes: effective, }; next(); }; } // requireUser is your existing JWT middleware. It lets a request through when // req.principal is already set, and REFUSES any other pctk_ bearer: // if (bearer.startsWith('pctk_') && !req.principal) return res.status(401)… app.get('/v1/disputes', acceptsTenantKey('disputes.read'), requireUser, listDisputes); app.post('/v1/reports', acceptsTenantKey('reports.create'), requireUser, createReport); // No acceptsTenantKey on /v1/api-keys, /v1/team, billing…: keys cannot reach them. ``` Checklist ## Before you ship - Introspection with a fresh key of your own test tenant returns `active: true`; a typo'd key is refused without a call to Auth. - A key revoked in your UI stops working within your positive TTL, and your audit trail shows who revoked it. - Removing the creator from the tenant kills the key, and the status endpoint says `member_removed`. - A key calling a route you did not mark gets `401`, and a key without the route's scope gets `403`. - With Auth unreachable, cached keys keep working until their TTL, uncached keys get `503`, and nothing is cached as revoked. - Tell your customers: keys expire, a key dies when its creator leaves the team, and a leaked key should be revoked, not rotated. [Tenant API keys concepts](https://productcraft.co/docs/auth/concepts/tenant-api-keys.md) [API reference](https://productcraft.co/docs/auth/api-reference.md) --- title: "Agent access (OAuth for MCP) | Auth Docs" description: "Let your users connect Claude Code or another AI agent to your app: one command, a browser consent on your own page, and tokens bound to your MCP server. Auth runs the OAuth 2.1 server; your app keeps the consent page and the permission check." url: https://productcraft.co/docs/auth/agent-access --- [Core concepts](https://productcraft.co/docs/auth/concepts.md) Core concepts # Agent access: let AI agents act for your users. Your users connect Claude Code, or any MCP client, to your app with one command and approve it in their browser. The agent then calls your MCP server as that user, within what they allowed. Auth runs the OAuth 2.1 authorization server; you keep the consent page and the permission check. ## What your user does 1. Runs `claude mcp add --transport http your-app https://mcp.example.com/mcp`, then chooses Authenticate. 2. Their browser opens your app. They sign in as usual, including their second factor. 3. Your consent page shows which agent is asking and what it wants. They pick what to allow and press Allow. 4. The browser hands back to the agent, which now has a token for your MCP server only. No API key ends up in a config file, and the user can disconnect the agent at any time from a page in your app. ## Who does what - **Auth** is the authorization server: discovery, client registration, PKCE, the authorization code, access tokens bound to your resource, rotating refresh tokens, revocation and the user's list of connected agents. Every grant, revocation and registration lands in your app's audit log. - **Your app** hosts the consent page (it already signs your users in) and the MCP server. The server checks each token, then applies the user's _current_ role on every call, so an agent never does more than its user can do today. ## 1. Turn it on Push the settings from your backend on boot with a Platform API key that holds `auth.agent_access.configure` on the app. The scopes are yours: name them after what your API does. ```http title="config" PUT https://api.auth.productcraft.co/{slug}/v1/agent-access/config Authorization: Bearer pcft_live_… # auth.agent_access.configure { "enabled": true, "resources": ["https://mcp.example.com/mcp"], "consent_url": "https://app.example.com/oauth/consent", "scopes": [ { "name": "projects:read", "description": "Read your projects" }, { "name": "projects:write", "description": "Change your projects" } ] } ``` ## 2. Your consent page Auth sends the browser to `consent_url?request=pcar_…`. Sign the user in if needed, read the request with their own access token, and show it. When `client.verified` is true, show the client as verified: Auth has fetched its publisher's metadata document and vouches for it (Claude Code today). Otherwise the name is self-declared: say it is unverified. For every client show where the browser will return (`redirect.host`; `loopback: true` means “on this computer”). Isolate every value you place inside a sentence (the client name, the user's address, hosts) with ``, so right-to-left text cannot reorder it. The first signed-in user to open a request is bound to it; anyone else gets `404`. Requests live 10 minutes. On Allow, approve with the scopes they kept and any `context` your server will need later (up to 2 KB, returned on introspection exactly as you sent it). Then send the browser to `redirect_to`. ```http title="approve" POST https://api.auth.productcraft.co/{slug}/v1/agent-access/authorizations/{handle}/approve Authorization: Bearer { "scopes": ["projects:read"], "context": { "workspace_ids": ["ws_123"] } } → 200 { "redirect_to": "http://localhost:53682/callback?code=…&state=…&iss=…", "grant_id": "agr_…" } ``` ## 3. Your MCP server Answer an unauthenticated request with `401` and `WWW-Authenticate: Bearer resource_metadata="…"`, and serve the protected-resource metadata (RFC 9728) naming `https://api.auth.productcraft.co/{slug}` as the authorization server. For each request: 1. Verify the token against your app's JWKS with **issuer and audience** (your resource URL, exactly) and check `type` is `agent_access`. An end-user session token has a different audience and type, so neither can stand in for the other. If any of your own APIs verify Auth tokens without checking the audience, fix that before turning agent access on. 2. Ask `POST /{slug}/v1/agent-access/introspect` whether the connection is still live, and cache a positive answer for a few seconds at most, so Disconnect takes effect quickly. 3. Allow the call only if the scopes allow it and the user's current role does. ```json title="access token claims" { "iss": "https://api.auth.productcraft.co/{slug}", "aud": "https://mcp.example.com/mcp", // exactly your resource "sub": "", "type": "agent_access", "token_use": "agent_access", "client_id": "pcac_…", "grant_id": "agr_…", "scope": "projects:read", "auth_time": 1794830400, // when the user approved "exp": … // 15 minutes } ``` ## 4. Optional: an admin overview Your admins may need to see every agent connected to their organisation and cut one off. List the app's connections with a Platform API key holding `auth.agent_access.grants.manage`, narrowed by the `context` you stored at approval (JSON containment), and disconnect any of them. Record in your own trail who asked; Auth records the revocation with reason `app`. ```http title="grants" GET https://api.auth.productcraft.co/{slug}/v1/agent-access/grants?context={"workspace_ids":["ws_123"]} Authorization: Bearer pcft_live_… # auth.agent_access.grants.manage → 200 { "data": [ { "id": "agr_…", "account": { "id": "…", "username": "dana", "email": "dana@acme.com" }, "client": { "client_id": "https://claude.ai/oauth/claude-code-client-metadata", "name": "Claude Code", "verified": true, "kind": "metadata_document" }, "scopes": ["projects:read"], "last_used_at": "…", … } ], "pagination": { "next_cursor": null, "has_more": false } } ``` ## Endpoints | Route | Credential | Purpose | | --- | --- | --- | | GET /.well-known/oauth-authorization-server/{slug} | public | Discovery (RFC 8414). 404 while agent access is off. | | POST /{slug}/oauth/register | public | Dynamic client registration (RFC 7591). Public clients only; https or localhost redirects. | | GET /{slug}/oauth/authorize | browser | Validates the request (PKCE S256 required) and sends the browser to your consent page. | | POST /{slug}/oauth/token | public | Authorization code and refresh token grants. Refresh tokens rotate on every use. | | POST /{slug}/oauth/revoke | public | Token revocation (RFC 7009). | | GET /{slug}/v1/agent-access/authorizations/{handle} | user's token | Your consent page reads the request. | | POST …/authorizations/{handle}/approve \| deny | user's token | The user decided. Answers the URL to send the browser to. | | GET \| DELETE /{slug}/v1/me/agent-grants | user's token | The user's connected agents, and Disconnect. | | PUT \| GET /{slug}/v1/agent-access/config | Platform API key | Turn it on: your MCP server URL, consent page and scopes. | | POST /{slug}/v1/agent-access/introspect | Platform API key | Your MCP server checks a token is still live. | | GET /{slug}/v1/agent-access/grants | Platform API key | Every user's connected agents, filtered by the context you stored (e.g. one workspace). | | DELETE /{slug}/v1/agent-access/grants/{grant_id} | Platform API key | Disconnect anyone's agent, e.g. from a workspace owner's admin page. | ## Security model - PKCE with S256 is required; `plain` and missing challenges are refused. - Redirect URIs match exactly, with one relaxation: any port on `localhost`, `127.0.0.1` or `[::1]` (RFC 8252), which native agents need. Plain `http` is accepted only there. - Codes live 60 seconds and work once; a replayed code revokes what it issued. Access tokens live 15 minutes. Refresh tokens live 30 days and rotate on every use; presenting an old one revokes the whole connection. A connection ends after 90 days at the latest. - Clients identify themselves with a Client ID Metadata Document (the MCP spec's preferred way; Claude Code uses `https://claude.ai/oauth/claude-code-client-metadata`) or, as a fallback, by dynamic registration. Auth fetches a metadata document over https from public addresses only (no redirects, 5 KB, 5 seconds), checks that its `client_id` is its own URL and that the redirect is one it lists, and caches it for an hour. Only documents whose publisher Auth vouches for are verified; every self-registered client and every other document stays unverified. - Client names are stored without bidi control or invisible characters, so a name cannot reorder the sentence it is shown in. - Registration is limited to 10 clients an hour per address, and an app keeps at most 5,000 registered clients. - Deleting or suspending a user ends their agents' access at once. ## In production dispute.markets uses agent access for its MCP server. Its customers connect Claude Code with one command; see [dispute.markets/docs/mcp](https://dispute.markets/docs/mcp). [API reference](https://productcraft.co/docs/auth/api-reference.md) [Core concepts](https://productcraft.co/docs/auth/concepts.md) --- title: "API Reference | Auth Docs" description: "Auth Consumer API: per-app EndUser signup, signin, sessions, and authorization. Generated from the live OpenAPI spec." url: https://productcraft.co/docs/auth/api-reference --- [Auth docs](https://productcraft.co/docs/auth.md) API reference # Auth Consumer API. Sign in your end-users, verify their tokens, and check permissions. Every endpoint is generated from the live OpenAPI spec. Replace `{app_slug}` in every URL with the slug of your Auth app. Open the app in [the console](https://console.productcraft.co/auth) — the slug is shown on its `Settings` tab, next to the app id. Base URL `https://api.auth.productcraft.co` Auth `Authorization: Bearer …` Spec version OpenAPI 3.0.0 · v1.0.0 OpenAPI spec [https://api.auth.productcraft.co/docs-json](https://api.auth.productcraft.co/docs-json) ## Consumer-Admin Manage the app's users from your backend with an app-scoped token or API key: create, list, update and delete them. - [get `/{app_slug}/v1/admin/users` List end-users in this app](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-admin-users.md) - [post `/{app_slug}/v1/admin/users` Provision a new end-user](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-admin-users.md) - [get `/{app_slug}/v1/admin/users/{user_id}` Read one end-user](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-admin-users-user-id.md) - [patch `/{app_slug}/v1/admin/users/{user_id}` Update an end-user's display name or primary email](https://productcraft.co/docs/auth/api-reference/patch-app-slug-v1-admin-users-user-id.md) - [delete `/{app_slug}/v1/admin/users/{user_id}` Permanently delete an end-user](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-admin-users-user-id.md) - [patch `/{app_slug}/v1/admin/users/{user_id}/status` Change an end-user status (active / suspended / deactivated)](https://productcraft.co/docs/auth/api-reference/patch-app-slug-v1-admin-users-user-id-status.md) - [patch `/{app_slug}/v1/admin/users/{user_id}/role` Assign an end-user a role](https://productcraft.co/docs/auth/api-reference/patch-app-slug-v1-admin-users-user-id-role.md) ## Consumer-Admin-Mfa Provision and remove a user's MFA factors from your backend with a workspace API key (synthetic and agent accounts). - [get `/{app_slug}/v1/users/{user_id}/factors` List a user's MFA factors](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-users-user-id-factors.md) - [post `/{app_slug}/v1/users/{user_id}/factors` Provision an MFA factor on behalf of a user](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-users-user-id-factors.md) - [delete `/{app_slug}/v1/users/{user_id}/factors/{factor_id}` Disable a user's MFA factor](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-users-user-id-factors-factor-id.md) ## Consumer-Admin-Permissions Manage the app's permission catalogue from your backend. - [get `/{app_slug}/v1/admin/permissions` List all permissions visible to this app](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-admin-permissions.md) - [post `/{app_slug}/v1/admin/permissions` Create a custom permission](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-admin-permissions.md) - [delete `/{app_slug}/v1/admin/permissions/{permission_key}` Delete a custom permission](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-admin-permissions-permission-key.md) ## Consumer-Admin-Roles Manage the app's roles and their permissions from your backend. - [get `/{app_slug}/v1/admin/roles` List roles in this app](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-admin-roles.md) - [post `/{app_slug}/v1/admin/roles` Create a role](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-admin-roles.md) - [get `/{app_slug}/v1/admin/roles/{role_name}` Read one role with its permission set](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-admin-roles-role-name.md) - [patch `/{app_slug}/v1/admin/roles/{role_name}` Update a role's description](https://productcraft.co/docs/auth/api-reference/patch-app-slug-v1-admin-roles-role-name.md) - [delete `/{app_slug}/v1/admin/roles/{role_name}` Delete a custom role](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-admin-roles-role-name.md) - [put `/{app_slug}/v1/admin/roles/{role_name}/permissions` Replace a role's permission set](https://productcraft.co/docs/auth/api-reference/put-app-slug-v1-admin-roles-role-name-permissions.md) ## Consumer-Agent-Access Agent access (OAuth for MCP): let an AI agent act for one of your users after their browser consent. The consent API your consent page calls, the user's connected agents, and the PAK lane your backend uses to push settings and verify agent tokens. The OAuth endpoints themselves (discovery, register, authorize, token, revoke) follow RFC 8414 / 7591 / 6749 / 7009 and are documented on productcraft.co/docs/auth/agent-access. - [get `/{app_slug}/v1/agent-access/config` Read this app's agent access settings](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-agent-access-config.md) - [put `/{app_slug}/v1/agent-access/config` Push this app's agent access settings](https://productcraft.co/docs/auth/api-reference/put-app-slug-v1-agent-access-config.md) - [get `/{app_slug}/v1/agent-access/grants` List the app's agent connections (all end users)](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-agent-access-grants.md) - [delete `/{app_slug}/v1/agent-access/grants/{grant_id}` Disconnect an end user's agent](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-agent-access-grants-grant-id.md) - [post `/{app_slug}/v1/agent-access/introspect` Verify an agent access token (RFC 7662 shape)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-agent-access-introspect.md) - [get `/{app_slug}/v1/agent-access/authorizations/{handle}` Read a pending agent authorization (consent screen)](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-agent-access-authorizations-handle.md) - [post `/{app_slug}/v1/agent-access/authorizations/{handle}/approve` Approve an agent authorization](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-agent-access-authorizations-handle-approve.md) - [post `/{app_slug}/v1/agent-access/authorizations/{handle}/deny` Deny an agent authorization](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-agent-access-authorizations-handle-deny.md) - [get `/{app_slug}/v1/me/agent-grants` List the signed-in user's connected agents](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-me-agent-grants.md) - [delete `/{app_slug}/v1/me/agent-grants/{grant_id}` Disconnect an agent](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-me-agent-grants-grant-id.md) ## Consumer-Auth Sign your users up and in: password, passkey and code sign-in, MFA challenges and enrolment, token refresh and sign-out, email verification and password reset, invites and tenant switching. - [post `/{app_slug}/v1/auth/signup` Sign up an EndUser](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-signup.md) - [post `/{app_slug}/v1/auth/accept-invite` Accept an EndUser invite by code](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-accept-invite.md) - [post `/{app_slug}/v1/auth/accept-tenant-invite` Accept a tenant invite by code](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-accept-tenant-invite.md) - [post `/{app_slug}/v1/auth/signin` Sign in an EndUser](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-signin.md) - [post `/{app_slug}/v1/auth/mfa/send-code` Email a sign-in code for an email MFA factor](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-mfa-send-code.md) - [post `/{app_slug}/v1/auth/mfa/verify` Complete an MFA challenge with a TOTP or emailed code](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-mfa-verify.md) - [post `/{app_slug}/v1/auth/mfa/webauthn/options` Get passkey assertion options for an open MFA challenge](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-mfa-webauthn-options.md) - [post `/{app_slug}/v1/auth/passkey/options` Begin a passwordless passkey sign-in](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-passkey-options.md) - [post `/{app_slug}/v1/auth/passkey/verify` Complete a passwordless passkey sign-in](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-passkey-verify.md) - [post `/{app_slug}/v1/auth/mfa/recover` Complete an MFA challenge with a recovery code](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-mfa-recover.md) - [post `/{app_slug}/v1/auth/mfa/enroll` Begin MFA enrolment against an enrolment token](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-mfa-enroll.md) - [post `/{app_slug}/v1/auth/mfa/enroll/verify` Confirm the enrolled factor and receive the withheld session](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-mfa-enroll-verify.md) - [post `/{app_slug}/v1/auth/refresh` Exchange a refresh token for a new access token](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-refresh.md) - [post `/{app_slug}/v1/auth/logout` Revoke a refresh token](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-logout.md) - [post `/{app_slug}/v1/auth/request-verification` Mint a contact-verification code (PAK-required)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-request-verification.md) - [post `/{app_slug}/v1/auth/send-verification-email` Mint + dispatch a verification email via Mail (PAK-required)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-send-verification-email.md) - [post `/{app_slug}/v1/auth/verify` Submit a verification code](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-verify.md) - [post `/{app_slug}/v1/auth/request-password-reset` Mint a password-reset code (PAK-required)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-request-password-reset.md) - [post `/{app_slug}/v1/auth/send-password-reset-email` Mint + dispatch a password-reset email via Mail (PAK-required)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-send-password-reset-email.md) - [post `/{app_slug}/v1/auth/reset-password` Submit a reset code + new password](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-reset-password.md) - [post `/{app_slug}/v1/auth/switch-tenant` Switch the active tenant for this session](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-switch-tenant.md) - [get `/{app_slug}/v1/auth/me/tenants` List the EndUser's tenant memberships in this app](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-auth-me-tenants.md) ## Consumer-Me The signed-in user: profile, avatar, password, sessions, activity, contacts and permissions, and closing the account. - [post `/{app_slug}/v1/me/tenant-invites/accept` Accept a tenant invite as the signed-in EndUser](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-tenant-invites-accept.md) - [get `/{app_slug}/v1/me` Get the signed-in EndUser profile](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-me.md) - [patch `/{app_slug}/v1/me` Update the signed-in EndUser profile](https://productcraft.co/docs/auth/api-reference/patch-app-slug-v1-me.md) - [delete `/{app_slug}/v1/me` Permanently delete the signed-in EndUser account](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-me.md) - [get `/{app_slug}/v1/me/permissions` Resolve the signed-in EndUser's effective permissions](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-me-permissions.md) - [post `/{app_slug}/v1/me/avatar` Upload (or replace) the EndUser avatar](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-avatar.md) - [delete `/{app_slug}/v1/me/avatar` Remove the EndUser avatar](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-me-avatar.md) - [post `/{app_slug}/v1/me/change-password` Change the password of the signed-in EndUser](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-change-password.md) - [get `/{app_slug}/v1/me/sessions` List all active sessions for the EndUser](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-me-sessions.md) - [delete `/{app_slug}/v1/me/sessions/{id}` Revoke a session](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-me-sessions-id.md) - [get `/{app_slug}/v1/me/activity` Recent account activity](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-me-activity.md) - [get `/{app_slug}/v1/me/contacts` List the EndUser's contacts](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-me-contacts.md) - [post `/{app_slug}/v1/me/contacts` Add a new contact (unverified, non-primary)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-contacts.md) - [delete `/{app_slug}/v1/me/contacts/{id}` Delete a contact](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-me-contacts-id.md) - [post `/{app_slug}/v1/me/contacts/{id}/promote` Promote a verified contact to primary](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-contacts-id-promote.md) - [get `/{app_slug}/v1/avatars/{account_id}` Redirect to the current avatar image](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-avatars-account-id.md) ## Consumer-Mfa The signed-in user's MFA: factors (TOTP, email codes, passkeys), recovery codes and step-up. - [get `/{app_slug}/v1/me/mfa/factors` List the authenticated EndUser's MFA factors](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-me-mfa-factors.md) - [post `/{app_slug}/v1/me/mfa/factors` Begin enrollment of a new MFA factor](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-mfa-factors.md) - [post `/{app_slug}/v1/me/mfa/factors/{id}/verify` Confirm enrollment of a pending factor](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-mfa-factors-id-verify.md) - [delete `/{app_slug}/v1/me/mfa/factors/{id}` Disable an MFA factor](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-me-mfa-factors-id.md) - [post `/{app_slug}/v1/me/mfa/recovery-codes/regenerate` Regenerate the recovery-code set](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-mfa-recovery-codes-regenerate.md) - [post `/{app_slug}/v1/me/mfa/step-up/send-code` Email a step-up code](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-mfa-step-up-send-code.md) - [post `/{app_slug}/v1/me/mfa/step-up/webauthn/options` Get passkey assertion options for step-up](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-mfa-step-up-webauthn-options.md) - [post `/{app_slug}/v1/me/mfa/step-up` Bump this session's MFA recency](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-me-mfa-step-up.md) ## Consumer-Oauth-M2m OAuth 2.0 for machines: the client-credentials token endpoint and token introspection (RFC 7662). - [post `/{app_slug}/v1/oauth/token` Exchange client_credentials for an access token](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-oauth-token.md) - [post `/{app_slug}/v1/oauth/introspect` Introspect the bearer access token (RFC 7662)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-oauth-introspect.md) ## Consumer-Oauth-Sign-In Sign in with Google, GitHub or Apple: the native ID-token flow, and the code exchange that finishes the web redirect flow (the redirects themselves are browser routes). - [post `/{app_slug}/v1/auth/oauth/exchange` Exchange a `heimdall_code` (received on the web-flow callback redirect) for Auth access + refresh tokens.](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-oauth-exchange.md) - [post `/{app_slug}/v1/auth/oauth/{provider}` Sign in / sign up with a provider ID token (native flow)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-oauth-provider.md) - [get `/{app_slug}/v1/auth/oauth/{provider}/authorize` Start the web redirect flow.](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-auth-oauth-provider-authorize.md) - [get `/{app_slug}/v1/auth/oauth/{provider}/callback` Provider callback (Google / GitHub redirect with `code` on the query string).](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-auth-oauth-provider-callback.md) - [post `/{app_slug}/v1/auth/oauth/{provider}/callback` Provider callback (Apple uses `response_mode=form_post`).](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-auth-oauth-provider-callback.md) ## Consumer-Tenant-Api-Keys Tenant API keys (`pctk_…`): your users manage keys for their tenant, and your backend introspects them and pushes the key settings. - [post `/{app_slug}/v1/tenant-api-keys/introspect` Verify a tenant API key (RFC 7662 shape)](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-tenant-api-keys-introspect.md) - [get `/{app_slug}/v1/tenant-api-keys/config` Read this app's tenant API key settings](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-tenant-api-keys-config.md) - [put `/{app_slug}/v1/tenant-api-keys/config` Push this app's tenant API key settings](https://productcraft.co/docs/auth/api-reference/put-app-slug-v1-tenant-api-keys-config.md) - [get `/{app_slug}/v1/tenant-api-keys/{key_id}/status` Why a tenant API key is (in)active](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-tenant-api-keys-key-id-status.md) - [get `/{app_slug}/v1/tenant-api-keys` List the active tenant's API keys](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-tenant-api-keys.md) - [post `/{app_slug}/v1/tenant-api-keys` Create an API key for the active tenant](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-tenant-api-keys.md) - [post `/{app_slug}/v1/tenant-api-keys/{key_id}/rotate` Rotate an API key](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-tenant-api-keys-key-id-rotate.md) - [delete `/{app_slug}/v1/tenant-api-keys/{key_id}` Revoke an API key](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-tenant-api-keys-key-id.md) ## Consumer-Tenants Tenants (organisations inside your app) from your backend with a workspace API key: create, update and delete them, their members and invites. - [get `/{app_slug}/v1/tenants` List tenants in this app, paginated by created_at desc.](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-tenants.md) - [post `/{app_slug}/v1/tenants` Create a tenant inside this app.](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-tenants.md) - [get `/{app_slug}/v1/tenants/{tenant_id}` Fetch a single tenant by its UUID or `tnt_<12hex>` display id.](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-tenants-tenant-id.md) - [patch `/{app_slug}/v1/tenants/{tenant_id}` Patch a tenant.](https://productcraft.co/docs/auth/api-reference/patch-app-slug-v1-tenants-tenant-id.md) - [delete `/{app_slug}/v1/tenants/{tenant_id}` Delete a tenant.](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-tenants-tenant-id.md) - [get `/{app_slug}/v1/tenants/{tenant_id}/members` List members of a tenant.](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-tenants-tenant-id-members.md) - [post `/{app_slug}/v1/tenants/{tenant_id}/members` Add a member to a tenant.](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-tenants-tenant-id-members.md) - [patch `/{app_slug}/v1/tenants/{tenant_id}/members/{account_id}` Change a member's role.](https://productcraft.co/docs/auth/api-reference/patch-app-slug-v1-tenants-tenant-id-members-account-id.md) - [delete `/{app_slug}/v1/tenants/{tenant_id}/members/{account_id}` Remove a member from a tenant.](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-tenants-tenant-id-members-account-id.md) - [get `/{app_slug}/v1/tenants/{tenant_id}/invites` List a tenant's invites, newest first.](https://productcraft.co/docs/auth/api-reference/get-app-slug-v1-tenants-tenant-id-invites.md) - [post `/{app_slug}/v1/tenants/{tenant_id}/invites` Invite an email address into a tenant.](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-tenants-tenant-id-invites.md) - [delete `/{app_slug}/v1/tenants/{tenant_id}/invites/{invite_id}` Revoke a pending invite.](https://productcraft.co/docs/auth/api-reference/delete-app-slug-v1-tenants-tenant-id-invites-invite-id.md) ## Consumer-Verify Verify a user's access token and check its permissions from your backend, one check or a batch. - [post `/{app_slug}/v1/verify` Verify a token signature + return its principal](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-verify.md) - [post `/{app_slug}/v1/authorize` Verify a token + check one or more permissions](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-authorize.md) - [post `/{app_slug}/v1/authorize/batch` Multi-permission authorization in a single round-trip](https://productcraft.co/docs/auth/api-reference/post-app-slug-v1-authorize-batch.md) --- title: "Mail Documentation" description: "Ship transactional email from your own domain: verify, template, sign, send. Full Mail guides, API reference, and copy-paste curl examples." url: https://productcraft.co/docs/mail --- Mail docs # Mail documentation. Ship transactional email flows on your own domain, in minutes. Start here ## Guides - [Getting started](https://productcraft.co/docs/mail/getting-started.md): From zero to a signed email landing in an inbox. Verify a domain, write a template, mint an API key, send.Read more → - [API reference](https://productcraft.co/docs/mail/api-reference.md): Every Mail endpoint with request and response schemas, generated from the live OpenAPI spec.Read more → ## Ready to send? Open Mail in the console to pick a workspace, verify your first domain, and start sending. [Open in console](https://console.productcraft.co/mail) [Getting started](https://productcraft.co/docs/mail/getting-started.md) --- title: "Mail — Getting started" description: "From zero to a signed, delivered transactional email: verify a domain, create a template, mint an API key, send." url: https://productcraft.co/docs/mail/getting-started --- [Mail docs](https://productcraft.co/docs/mail.md) Getting started # Send your first transactional email. Ten minutes. DKIM-signed. From your own domain. Step 1 ## Pick a workspace Open [console.productcraft.co/mail](https://console.productcraft.co/mail). If you don't have a ProductCraft account yet, sign up at [auth.productcraft.co](https://auth.productcraft.co/signup) first — every product in the console shares the same account. Once signed in, pick or create a workspace. The workspace is the boundary for your domains, templates, keys, and suppression list. Mail must be enabled for the workspace (sidebar → Workspace → Services). Use separate workspaces for dev / staging / prod isolation. Step 2 ## Add and verify a domain From the Domains tab, click Add domain and enter the fqdn you want to send from. Mail generates a DKIM keypair for the domain and opens a setup checklist with four DNS records to set at your registrar — ownership, MX, DKIM, SPF. ```title="DNS records" MX acme.com → 10 mx.productcraft.co. TXT acme.com → v=spf1 include:_spf.productcraft.co -all TXT productcraft._domainkey.acme.com → v=DKIM1; k=rsa; p=... TXT _productcraft-verify.acme.com → productcraft-verify= ``` Once the records are set, the console re-checks them on its own every 30 seconds and ticks each step green as it lands. To force a lookup, open a record from the checklist and click **Check DNS now**. The domain flips to `active` once all four records pass. Step 3 ## Write a template Templates use Handlebars — subject and body share the same syntax. A plain-text body is optional; if omitted, we derive it from the HTML for clients that can’t render rich content. ```title="welcome template" name: welcome subject: Welcome, {{name}}! body_html:

Hi {{name}},

Thanks for signing up for Acme.

``` Step 4 ## Mint an API key From Workspace → API keys, click New API key. A key's access comes from the managed policies you bind to it (author them under Workspace → Policies); for a typical sender key, bind a policy that allows: ```title="policy actions" ✓ mail.send ✓ mail.read ``` The full key (starting with `pcft_live_`) is shown **once**. Copy it immediately into your secret store; if you lose it, revoke and mint a fresh one. Keys are scoped to the workspace. Step 5 ## Send One HTTP call. :workspaceId is your workspace's UUID — find it on Workspace → General in the console, in the Resource URN field (pcft:workspace/). ```bash title="send a message" curl -X POST \ https://api.mail.productcraft.co/v1/workspaces/:workspaceId/templates/welcome/send \ -H "Authorization: Bearer pcft_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "hello@acme.com", "to": "user@example.com", "data": { "name": "Alice" } }' → HTTP/1.1 202 Accepted { "accepted": true, "from": "hello@acme.com", "to": "user@example.com", "subject": "Welcome, Alice!" } ``` The 202 confirms the message was rendered, DKIM-signed with your domain's private key, and queued. Delivery is async. Retries are safe if you pass an `Idempotency-Key` header — replays return the original response for 24 hours. ## What else you should know - **Rate limits.** Sending is limited per workspace. Over a limit the API answers 429 with `Retry-After` and `ratelimit-*` headers that tell you the limit and when it resets. Contact us if you outgrow the defaults. - **Suppression.** Hard bounces auto-populate your workspace's suppression list. Sends to a suppressed address return 422 before they hit the queue. - **Invite teammates.** Workspace → Members → **Invite** mints an invite link with a role attached (email optional — supply one and we mail the link for you). _admin_ can do everything except destructive ops like deleting the workspace; _member_ is read-only by default. - **Render preview.** Test a template before sending: `POST /v1/workspaces/:workspaceId/templates/:name/render` with your data payload returns the rendered subject, HTML, and text — no mail goes out. `.../test-send` delivers a real `[TEST]`-prefixed email, bypassing suppression and rate limits. - **Inbound mail.** Every verified domain is also listening on `mx.productcraft.co`. Create a mailbox under it and inbound messages land with parsed MIME + attachments, readable via the mailbox endpoints. Something not covered? Email [hello@productcraft.co](mailto:hello@productcraft.co) — most docs gaps turn into features in the next release. --- title: "Guides | Mail Docs" description: "Comprehensive guides for Mail: domain setup with DKIM/SPF, template authoring, sending, deliverability, bounce handling, and message operations." url: https://productcraft.co/docs/mail/guides --- [Mail docs](https://productcraft.co/docs/mail.md) Guides # Build with Mail. Six chapters from your first DNS record to a debuggable production sender. Each chapter assumes you've finished the previous one but cross-references back, so jumping in mid-series works. Looking for the full HTTP API instead? See [API reference](https://productcraft.co/docs/mail/api-reference.md). Chapters ## The series - [01 · Foundations](https://productcraft.co/docs/mail/guides/01-foundations.md): Workspace boundary, domains, mailboxes, templates, the sender model.Read more → - [02 · Domain setup](https://productcraft.co/docs/mail/guides/02-domain-setup.md): DKIM, SPF, MX, the verification flow, and brand customisation.Read more → - [03 · Send your first email](https://productcraft.co/docs/mail/guides/03-first-send.md): Author a Handlebars template, mint an API key, send to a recipient. End to end in fifteen minutes.Read more → - [04 · Template authoring](https://productcraft.co/docs/mail/guides/04-template-authoring.md): Handlebars syntax, variables, partials, lint, preview, test-send.Read more → - [05 · Deliverability](https://productcraft.co/docs/mail/guides/05-deliverability.md): Suppression list, bounce + complaint handling, webhook config, brand-reputation hygiene.Read more → - [06 · Operations](https://productcraft.co/docs/mail/guides/06-operations.md): Message log, batch send, attachments, RTBF deletion, debugging delivery.Read more → - [07 · Contacts, topics, segments and broadcasts](https://productcraft.co/docs/mail/guides/07-audiences.md): Contacts, consent, CSV import, topics, one-click unsubscribe, the hosted preferences page, segments and broadcasts.Read more → Mental model ## Sender → recipient Mail is a transactional email service. You verify a domain (DKIM-signed, SPF-aligned), author a template (Handlebars), then call `POST /v1/workspaces/:ws/templates/:name/send`with a recipient + data. We deliver via your verified sender, signed by your DKIM, with bounce + complaint tracking attached. What we're **not**: a marketing email tool. No campaign send, no opens-clicks-funnels analytics, no list-management primitives. If that's what you need, an ESP like Mailchimp / Customer.io is the right shape. Mail is for the messages your product sends — order confirmations, password resets, invite links, account notifications. --- title: "01 · Foundations | Mail Guides" description: "The Mail mental model: workspace boundary, domains, mailboxes, templates, the suppression list." url: https://productcraft.co/docs/mail/guides/01-foundations --- [Mail guides](https://productcraft.co/docs/mail/guides.md) 01 · Foundations # The Mail mental model. Workspace, domain, mailbox, template, suppression list — the five primitives. Five minutes of reading saves an hour of misconfigured DNS. 1 ## Workspace = boundary Everything in Mail is scoped to your workspace. Your domains, your templates, your suppression list, your API keys, your bounce events. Two workspaces share no data. Activate Mail on the workspace (Console → Workspace → Services → Mail → **Enable**) before anything works — workspaces without Mail enabled return 403 `SERVICE_NOT_ENABLED`. 2 ## Domain A domain is what your customer sees in their `From:` header — e.g. `acme.com` sends as `noreply@acme.com`. Each domain holds its own DKIM keypair, gets independently verified via DNS, and tracks its own deliverability stats. Customers running staging + prod usually verify both `acme.com` and `staging.acme.com`. Domain status moves through: - `pending` — created, required DNS records not yet verified. Cannot send. A failed check keeps the domain `pending` and stores a per-record diff (`dns_check_results`) so you can see exactly which record is missing or wrong. - `active` — DNS verified, can send. Mail re-checks pending domains every ~5 minutes and flips them to `active` automatically once the records land — you don't have to keep clicking Verify. 3 ## Mailbox A mailbox is a specific `localpart@domain` that can _receive_ mail. `support@acme.com` and `billing@acme.com` are two mailboxes on one domain. Inbound mail on your domain is caught, parsed (subject, body, attachments), and stored under the matching mailbox. You can list, fetch, mark-as-read, delete. Useful for support inboxes, reply-tracking, and email-to-API integrations. Sending doesn't require a mailbox — once a domain is verified you can send from any address on it (`noreply@acme.com`, `hello@acme.com`, …). Create mailboxes only for the addresses you want to receive on. 4 ## Template A template is your message body, authored in Handlebars. One template = one logical message (welcome email, order confirmation, password reset). You version templates by editing in place; previous versions aren't retained on this service — keep a copy in your repo if that matters. Templates have: - **name** — unique within the workspace.`welcome`, `password-reset`,`order-confirmation`. Used in the send call.`POST /templates` upserts on name — same name, same template, updated in place. - **subject** + **body_html** — both Handlebars-templated. A plain-text alternative (`body_text`) is auto-derived unless you supply one. - **kind** — `template` (sendable, the default), or `layout` / `partial` for reusable chrome referenced from other templates. - **tags** — optional, used by the console for filtering / organisation. 5 ## Suppression list A workspace-scoped block list. Once a recipient is on it, Mail refuses to send to that address regardless of the template or sender. Entries land on the list automatically when: - The recipient hard-bounces (permanent SMTP 5xx failure → suppression, source `bounce`). - A spam complaint is reported for the recipient (source `complaint`). - You add the address yourself via the API (e.g. from your unsubscribe form — source `manual`). Soft failures (mailbox full, temporary deferral) don't suppress. **The suppression list is a hard wall.** Attempting to send to a suppressed address returns 422 immediately — no message row is created, nothing leaves the building. The address stays suppressed until you explicitly remove it (`DELETE /suppression/:email`). Only test-send bypasses the list. 6 ## Sender model When you call send, two things have to align: - The `from` address's domain must belong to your workspace (403 if not) and be verified (409 if still pending). - The recipient must not be on the suppression list (422). Failing either returns the 4xx immediately. No message row is created; no DKIM signing happens. The send call is the right place to find configuration mistakes — surface 4xx body messages to your operator UI so people see “Domain … is not verified yet” without trawling logs. 7 ## API auth All Mail endpoints are workspace-scoped — paths like`/workspaces/:workspaceId/...`. Auth is the same shared ProductCraft cookie that the console uses, OR a workspace API key (`pcft_live_*`). For programmatic access from your backend, mint a workspace API key with the `mail.*` scopes you need (the API reference calls out each route's gate). **curl** ```bash title="curl with a workspace API key" curl https://api.mail.productcraft.co/v1/workspaces//domains \ -H 'authorization: Bearer pcft_live_...' ``` **SDK** ```ts title="@productcraft/mail" import { Mail } from "@productcraft/mail"; // Reads PRODUCTCRAFT_API_KEY from the environment. A workspace key // finds its own workspace; pass { workspaceId } to skip that lookup. const mail = new Mail(); // Pages are fetched as you iterate. for await (const domain of mail.domains.list()) { console.log(domain.name, domain.status); } ``` [Next: Domain setup →](https://productcraft.co/docs/mail/guides/02-domain-setup.md) --- title: "02 · Domain setup | Mail Guides" description: "DKIM, MX, the verification flow. From `add domain` to `active` in fifteen minutes plus DNS propagation." url: https://productcraft.co/docs/mail/guides/02-domain-setup --- [Mail guides](https://productcraft.co/docs/mail/guides.md) 02 · Domain setup # Verify your sending domain. A sending domain needs one DNS record: its DKIM key. Publish it and Mail flips your domain to active automatically. 1 ## Add the domain Console → Mail → Domains → **Add domain**. Enter the FQDN you want to send from (e.g. `acme.com`; the dialog also asks whether it's a root domain or a subdomain, and whether you want to send, receive, or both). Mail generates a fresh DKIM keypair and drops you on a per-domain setup checklist — one step per record, each with the exact host and value to paste at your registrar (they're also on the API as `dns_instructions` on every domain read). ```title="DNS records to set" # intent: send TXT productcraft._domainkey.mail.acme.com v=DKIM1; k=rsa; p=MIIBIjANBgk... MX bounce.mail.acme.com 10 feedback-smtp.eu-north-1.amazonses.com (recommended) TXT bounce.mail.acme.com v=spf1 include:amazonses.com ~all (recommended) # intent: both (adds inbound) TXT productcraft._domainkey.mail.acme.com v=DKIM1; k=rsa; p=MIIBIjANBgk... MX mail.acme.com 10 mx.productcraft.co # intent: receive MX mail.acme.com 10 mx.productcraft.co TXT _productcraft-verify.mail.acme.com productcraft-verify= ``` Not sure what to add? `GET .../domains/lookup?fqdn=acme.com` creates nothing and tells you the zone, the DNS provider it detected from your nameservers (and whether it supports one-click Domain Connect setup), the SPF, DMARC and MX records already there, and, if you typed an apex, a subdomain to send from instead (`mail.acme.com`, or `send.acme.com` when `mail.` is already in use). To hand the records to whoever manages DNS, or to import them in one go, download them: `GET .../domains/:id/dns-records/export?format=bind` gives a zone-file fragment that Cloudflare (DNS → Records → Import) and Route 53 (Import zone file) accept, and `format=csv` gives `type,name,value,priority,ttl,purpose,required`. Add `&zone=acme.com` to choose the zone the names are relative to, and `&all=true` to include records that already verify. If someone else manages your DNS, send them a share link instead of a console invite: `POST .../domains/:id/share-links` with `{"expires_in_days": 7, "email_to": ["it@acme.com"]}` returns a `url` to a read-only setup page with the records, their live status and the downloads above, no account needed and nothing else about your workspace. It works for 1 to 7 days, is shown only once, and `DELETE .../share-links/:link_id` turns it off at once. `email_to` is optional (up to 5 recipients per domain per day); `GET .../share-links` lists your links with their status and when each was last opened. If your DNS is on Cloudflare or DigitalOcean, Mail can add the records for you with a short-lived API token: `POST .../domains/:id/dns-records/apply` with `{"provider": "digitalocean", "token": "...", "dry_run": true}` and an `Idempotency-Key` header returns the plan (each record as `create`, `update` or `skip`) without changing anything; send it again with `"dry_run": false` to write exactly that plan. It only adds records at or under your domain, never deletes anything, and the only record it ever changes is an existing SPF record our mechanism must be merged into (shown with `before` and `after`). Unless you send `"include_dmarc": false`, it also adds `v=DMARC1; p=none;` at `_dmarc` when no DMARC policy covers the domain yet; an existing policy is never touched. Conflicts stop the whole apply with a 409 and the plan. Use a token that can do as little as possible and expires soon: on Cloudflare, an API token for this one zone with **Zone → DNS → Edit**; on DigitalOcean, a personal access token with the custom scopes `domain:read`, `domain:create` and `domain:update` and a 1-hour expiry. Mail uses it for that one request and never stores or logs it; revoke it when you are done (the response warns you when the token could see more than this zone). The exact values are in the console after you create the domain. Don't copy them from here — the DKIM public key + verify token are per-domain. A domain has an `intent` — `send`, `receive`, or `both` (the default) — which decides which records it is given and which must pass before it goes `active`. Each record in `dns_instructions` carries `required: true|false`. A send-only domain is never asked for an MX record, so adding your apex domain to send from does not touch its inbound mail. We recommend a subdomain such as `mail.acme.com` anyway, so your product mail's reputation stays separate from your team's. 2 ## Verify You don't strictly have to do anything here — Mail re-checks pending domains every ~5 minutes and flips them to `active` on its own once the required records land. To check on demand, open the domain's setup checklist and hit **Check DNS now**, or call `POST .../dns-records/check`. Mail asks your zone's own nameservers and a public resolver for every record and returns one row per record with a `state`: `missing`, `mismatch` (with what it `found`), `propagating` (your nameservers serve it, public resolvers will shortly; the `hint` says roughly when) or `verified`. A failed DNS lookup never turns a record red. When something else at that name stops a record from working, its state is `conflict` and `conflicts[]` says why and how to fix it: a second SPF record (with the merged record to publish instead), an SPF record over the 10-lookup limit, a CNAME where a TXT or MX must go, a second MX on the MAIL FROM host, two DMARC records, or another DKIM key on the `productcraft` selector. Mail never asks you to add a second SPF record: if you already have one, merge. `GET .../dns-records` returns the last result without a lookup, and `?zone=` renders each `name_relative` the way your DNS provider wants it. The older `POST .../verify` still works and answers 400 with a `dns_check_results` diff while a required record is missing. **curl** ```bash title="Or via API" curl -X POST https://api.mail.productcraft.co/v1/workspaces//domains//dns-records/check \ -H 'authorization: Bearer pcft_live_...' # → { "zone": "acme.com", "records": [ { "purpose": "dkim", # "name_relative": "productcraft._domainkey.mail", "state": "propagating", # "hint": "Your nameservers already serve it; public resolvers will within ~30 min ..." } ] } ``` **SDK** ```ts title="@productcraft/mail" import { Mail } from "@productcraft/mail"; // Reads PRODUCTCRAFT_API_KEY from the environment. A workspace key // finds its own workspace; pass { workspaceId } to skip that lookup. const mail = new Mail(); const domainId = "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b"; await mail.domains.verify(domainId); // Retrieves until status is active or disabled, honouring // Retry-After. Throws APITimeoutError after timeoutMs. const domain = await mail.domains.poll(domainId, { intervalMs: 10_000, timeoutMs: 600_000, }); console.log(domain.status, domain.health); ``` **After verification: drift monitoring.** A verified domain stays `active`, but Mail keeps checking it (hourly, and every 5 minutes while something is wrong). If a required record disappears or changes (the DKIM TXT, or the MX on a receiving domain), or DKIM signing stops verifying, the domain's `health` moves from `ok` to `degraded`: mail still flows, every workspace owner gets an email naming the record, and a `domain.updated` webhook fires with the per-record `changes`. If it is still broken 72 hours later (`health_grace_ends_at` on the domain says when), `health` becomes `failing`, owners are emailed again, and sends from the domain are refused with `422 domain_not_verified_by_provider` rather than being accepted and dropped by the provider. Put the record back and the next check returns it to `ok`. A DNS lookup that fails (a timeout, `SERVFAIL`) never counts as drift, and losing a recommended record (MAIL FROM, DMARC) only sends `domain.updated`. Subscribe a webhook to `domain.created`, `domain.verified`, `domain.updated` and `domain.deleted` to follow all of this from your own systems. 3 ## Why these records? - **DKIM** — cryptographic signature on every message. Lets Gmail / Outlook / corporate filters verify the message hasn't been tampered with and was authorised by your domain. Without it, your delivery rate tanks. - **DKIM is also the ownership proof.** The key was generated for your domain alone, so a zone that serves it was edited by someone who could read it from your workspace. Sending domains therefore need no separate verification token. - **Verify token** (receive-only domains) — proves to Mail that you control the domain when there is no DKIM key to publish. Not visible to recipients. You can remove it once the domain is active. - **MX** (receive and both) — routes inbound mail on your domain to Mail (see below). - **MAIL FROM** (recommended, sending domains) — an MX and an SPF TXT on `bounce.mail.acme.com`. Bounces then return to a host under your domain and SPF aligns with your From address, on top of DKIM. Until you publish them, mail still flows with our default envelope sender. Change the label (or turn it off with `null`) with `PATCH .../domains/:id` `{"mail_from_subdomain": "bounce"}`; a label whose host already has other records is refused with 409. - **SPF on your From domain** — no longer requested. Domains added before October 2026 were asked for `v=spf1 include:_spf.productcraft.co -all`; keep it if you have it (it is still reported, as informational), but it never blocks verification. 4 ## DMARC (recommended, not required) DMARC is the policy layer that tells receivers what to do when SPF or DKIM fail. Gmail and Yahoo require it from bulk senders. Mail looks for a policy at `_dmarc.mail.acme.com` and then at each parent (`_dmarc.acme.com`), grades whichever applies in the domain's `dmarc_grade` (policy, `sp=`, alignment, `pct=`, `rua=`, plus a warning when something needs attention), and only if _no_ policy applies does it recommend one, scoped to the sending domain and never your organisation's: ``` TXT _dmarc.mail.acme.com v=DMARC1; p=none; ``` It never asks for a second DMARC record and never touches an existing one. If your team manages DMARC elsewhere, hide the recommendation with `PATCH .../domains/:id {"dmarc_managed": false}`; the grade is still shown. Once the aggregate reports at `rua=` look clean, tighten to `p=quarantine`, then `p=reject`. 5 ## Inbound — the MX record The MX record is what makes mail _to_ your domain (support@, replies, etc.) land in Mail mailboxes. If you only ever want to send, create the domain with `intent: "send"` and skip it — outbound-only. Inbound mail hits `mx.productcraft.co` → parsed + stored under the matching mailbox. List it across every mailbox with `GET /v1/workspaces/:ws/received`, or for one mailbox with `GET /v1/workspaces/:ws/mailboxes/:id/messages`. 6 ## Brand Optional: workspace-wide design tokens your templates can use — name, logo, colours, font stack, footer. They're addressable in any template as `{{brand.*}}` and drive the built-in layout + footer partials, so restyling every email is one API call. All fields are optional; unset fields fall back to platform defaults (GET returns the resolved set, DELETE resets to defaults). ```bash title="PUT /v1/workspaces/:ws/brand" curl -X PUT https://api.mail.productcraft.co/v1/workspaces//brand \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "brand_name": "Acme", "logo_url": "https://cdn.acme.com/logo.png", "primary_color": "#1E40AF" }' ``` More knobs — secondary/text/background colours, `font_stack`, `button_radius`, `footer_html`, `footer_address`, `social_links` — are in the [API reference](https://productcraft.co/docs/mail/api-reference.md). 7 ## Reverse DNS (PTR) One subtle thing ProductCraft handles, not you: every IP we send from keeps matching forward + reverse DNS (PTR). Mentioning so you know it's in the path — without a PTR, Gmail silently spam-filters outbound mail. [Next: Send your first email →](https://productcraft.co/docs/mail/guides/03-first-send.md) --- title: "03 · First send | Mail Guides" description: "Author a template, preview it, send to a recipient. End to end in fifteen minutes." url: https://productcraft.co/docs/mail/guides/03-first-send --- [Mail guides](https://productcraft.co/docs/mail/guides.md) 03 · First send # Send your first transactional email. With a verified domain (Chapter 2), one API call sends your own HTML. Or author a template once and send it by name. No mailbox needed — mailboxes are for receiving. 1 ## Send an email `POST /emails` sends your own `html` and/or `text` as-is. Leave out `text` and the plain-text part is derived from the HTML. Send to one address or up to 50 across `to`, `cc` and `bcc`. Use `reply_to` for replies, `headers` for custom headers (`X-*`, `List-*`, `In-Reply-To`, `References`) and `tags` to label the send. **curl** ```bash title="POST /workspaces/:ws/emails" curl https://api.mail.productcraft.co/v1/workspaces//emails \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -H 'idempotency-key: order-1234-shipped' \ -d '{ "from": "Acme ", "to": ["ada@example.com"], "cc": "finance@acme.com", "reply_to": "support@acme.com", "subject": "Your order has shipped", "html": "

Hi Ada, your order is on its way.

", "headers": { "X-Entity-Ref-ID": "order-1234" }, "tags": [{ "name": "category", "value": "shipping" }] }' ``` **SDK** ```ts title="@productcraft/mail" import { Mail } from "@productcraft/mail"; // Reads PRODUCTCRAFT_API_KEY from the environment. A workspace key // finds its own workspace; pass { workspaceId } to skip that lookup. const mail = new Mail(); const email = await mail.emails.send( { from: "Acme ", to: ["ada@example.com"], cc: "finance@acme.com", reply_to: "support@acme.com", subject: "Your order has shipped", html: "

Hi Ada, your order is on its way.

", headers: { "X-Entity-Ref-ID": "order-1234" }, tags: [{ name: "category", value: "shipping" }], }, // Optional: the SDK sends a generated key on every write. { idempotencyKey: "order-1234-shipped" }, ); const sent = await mail.emails.retrieve(email.id); console.log(sent.last_event); ``` ```json title="202 Accepted" { "id": "4f8b2c1e-9a3d-4e57-b6f0-2d1c8e7a9b05" } ``` Each recipient gets its own copy. Every copy shows the same `To` and `Cc` headers, and no header names a `bcc` recipient. Each recipient also has its own message in `GET /messages` and its own delivery status. `GET /emails/{id}` returns the whole send: its recipients, its tags, and `last_event`, which is the worst status across the recipients. `GET /emails?tag[category]=shipping` finds sends by tag. Each recipient counts as one send against the workspace limits. A recipient on your suppression list is left out: it gets a message with status `suppressed`, and the email is still accepted. To send a saved template here, pass `"template": { "name": "welcome", "data": { … } }` instead of `html`/`text`. `POST /emails/batch` takes up to 100 emails, and each row gets its own status. 2 ## Author a template ```bash title="POST /workspaces/:ws/templates" curl https://api.mail.productcraft.co/v1/workspaces//templates \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "name": "welcome", "subject": "Welcome to {{product}}, {{name}}!", "body_html": "

Hi {{name}},

Thanks for signing up for {{product}}. Get started at {{startUrl}}.

", "body_text": "Hi {{name}}, thanks for signing up for {{product}}. Get started: {{startUrl}}", "tags": ["onboarding"] }' ``` `name` is the lookup key — lowercase letters, digits, `_`, `-`. Posting the same name again overwrites (the endpoint is an upsert). `body_text` is optional — Mail derives a plain-text body from the HTML if you omit it. **Name variables in camelCase** (`{{startUrl}}`, not `{{start_url}}`). Keys inside `data` are normalized on the wire — `start_url` arrives as `startUrl`, so a snake_case variable never receives its value. 3 ## Preview the rendered output Before sending to a real recipient, render the template with sample data and inspect the output. Pure validation; doesn't dispatch anything. ```bash title="POST /workspaces/:ws/templates/:name/render" curl https://api.mail.productcraft.co/v1/workspaces//templates/welcome/render \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "data": { "name": "Ada", "product": "Acme", "startUrl": "https://app.acme.com/onboarding" } }' ``` ```json { "subject": "Welcome to Acme, Ada!", "html": "\n\n...\n

Hi Ada,

Thanks for signing up for Acme. Get started at https://app.acme.com/onboarding.

", "text": "Hi Ada, thanks for signing up for Acme. Get started: https://app.acme.com/onboarding" } ``` The `html` comes back wrapped in a dark-mode-safe document head — that's what actually ships. Missing variables render as empty strings (Handlebars default), not errors — eyeball the preview. 4 ## Send to a test recipient The test-send endpoint targets one address with the template fully rendered — for “does this actually look right in Gmail” checks. It bypasses the suppression list and rate limits, prefixes the subject with `[TEST]`, and renders unsupplied variables as `[varname]` placeholders. ```bash title="POST /workspaces/:ws/templates/:name/test-send" curl https://api.mail.productcraft.co/v1/workspaces//templates/welcome/test-send \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "from": "noreply@acme.com", "to": "yourself@acme.com", "data": { "name": "Ada", "product": "Acme", "startUrl": "https://..." } }' ``` `from` must be an address on a verified workspace domain — same rule as a production send. 5 ## Production send **curl** ```bash title="POST /workspaces/:ws/templates/:name/send" curl https://api.mail.productcraft.co/v1/workspaces//templates/welcome/send \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -H 'idempotency-key: welcome-2026-05-22-ada' \ -d '{ "from": "noreply@acme.com", "to": "ada@example.com", "data": { "name": "Ada", "product": "Acme", "startUrl": "https://app.acme.com/onboarding" } }' ``` **SDK** ```ts title="@productcraft/mail" import { Mail } from "@productcraft/mail"; // Reads PRODUCTCRAFT_API_KEY from the environment. A workspace key // finds its own workspace; pass { workspaceId } to skip that lookup. const mail = new Mail(); const accepted = await mail.templates.send( "welcome", { from: "noreply@acme.com", to: "ada@example.com", data: { name: "Ada", product: "Acme", startUrl: "https://app.acme.com/onboarding", }, }, // The SDK generates an Idempotency-Key and reuses it on retries. // Pass your own to dedupe across processes: a replay returns the // original response with Idempotent-Replay: true for 24 h. { idempotencyKey: "welcome-2026-05-22-ada" }, ); console.log(accepted.id); ``` ```json title="202 Accepted" { "id": "4f8b2c1e-9a3d-4e57-b6f0-2d1c8e7a9b05", "email_id": "4f8b2c1e-9a3d-4e57-b6f0-2d1c8e7a9b05", "accepted": true, "from": "noreply@acme.com", "to": "ada@example.com", "subject": "Welcome to Acme, Ada!" } ``` You can pass a top-level `subject` in the body to override the template's subject. A template send takes the same `to` array, `cc`, `bcc`, `reply_to`, `headers` and `tags` as `POST /emails`. The send is asynchronous — the 202 confirms _queued for delivery_, not _delivered to inbox_. The webhook (Chapter 5) and the message log (Chapter 6) are how you learn what actually happened. **Pre-flight failures (immediate, nothing queued).** Every error body is `{ statusCode, message, code, details? }`. Branch on `code`, not on the status or the message: - 400 `VALIDATION_ERROR` — the request body is malformed; `message` lists each field - 400 `TEMPLATE_DATA_INVALID` — `data` fails the template's variable schema; `details.errors` lists each variable - 403 `FORBIDDEN` / `SERVICE_NOT_ENABLED` — the key lacks the permission, or Mail is off for the workspace - 404 `TEMPLATE_NOT_FOUND` — template name doesn't exist - 409 `IDEMPOTENCY_KEY_REUSE` — same idempotency key reused with a different body - 422 `from_domain_not_verified` — the `from` domain is not a verified sending domain of this workspace (`details.reason`: `not_registered` or `not_verified`) - 422 `RECIPIENT_SUPPRESSED`, `TEMPLATE_RENDER_FAILED`, `INVALID_FROM_ADDRESS` — recipient on the suppression list, render failure, or unparseable `from` - 429 `RATE_LIMITED` — slow down and retry Surface the `message` from the error body in your operator UI so config errors don't silently swallow sends. 6 ## Batch send For sending one template to many recipients with per-recipient data, use the batch endpoint. Each row is processed independently; partial failures don't abort the batch. ```bash title="POST /workspaces/:ws/templates/:name/send-batch" curl https://api.mail.productcraft.co/v1/workspaces//templates/order-receipt/send-batch \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "messages": [ { "from": "billing@acme.com", "to": "ada@example.com", "data": { "name": "Ada", "total": "$29" } }, { "from": "billing@acme.com", "to": "alan@example.com", "data": { "name": "Alan", "total": "$49" } } ] }' ``` ```json title="200 OK" { "data": [ { "index": 0, "id": "6f0c...", "status": "accepted" }, { "index": 1, "status": "rejected", "error": { "code": "INVALID_INPUT", "message": "Recipient \"alan@example.com\" is on this workspace's suppression list" } } ], "summary": { "accepted": 1, "rejected": 1 } } ``` Accepted rows carry the outbound message `id`; rejected rows carry an `error`. Rows can also take `subject` and `idempotency_key` per message; an `Idempotency-Key` header makes the whole request retry-safe (use a value that differs from every row key). Hard limit: 100 messages per call (400 above that) — chunk client-side for larger blasts. An unverified `from` domain fails the whole batch upfront with a 422. [Next: Template authoring →](https://productcraft.co/docs/mail/guides/04-template-authoring.md) --- title: "04 · Template authoring | Mail Guides" description: "Handlebars syntax, variables, partials and layouts, the deliverability lint, and patterns that work in every major mail client." url: https://productcraft.co/docs/mail/guides/04-template-authoring --- [Mail guides](https://productcraft.co/docs/mail/guides.md) 04 · Template authoring # Write templates that actually render. Handlebars syntax, the variables system, partials + layouts, the lint endpoint that scores deliverability before send, and a handful of patterns that survive Outlook. 1 ## Handlebars in a paragraph `{{var}}` interpolates. `{{#if}}` blocks branch. `{{#each}}` iterates. `{{> partial.name}}` includes a partial you authored; `{{> bp.name}}` includes a built-in one. HTML escapes by default — `{{{rawHtml}}}` (triple-stache) opts out. Use sparingly. ```html title="A reasonably complete template"

Hi {{customer.name}},

Your order #{{order.id}} is confirmed.

{{#if order.gift}}

This is a gift for {{order.gift.recipientName}}.

{{/if}} {{#each order.items}} {{/each}}
{{name}} {{quantity}} {{price}}

Total: {{order.total}}

{{> bp.footer}} ``` No ``/`` boilerplate needed — Mail wraps the body in a dark-mode-safe document at render time. 2 ## The variable contract Variables come from the `data` field on send. By default Mail doesn't enforce a schema — pass whatever your template needs. Missing variables render as empty strings (Handlebars default), not errors. **Name variables in camelCase.** Keys inside `data` are normalized on the wire — `recipient_name` arrives as `recipientName`, so a snake_case variable in the template never receives its value. The variable manifest lists every expression a saved template references (dotted paths preserved): ```bash title="GET /workspaces/:ws/templates/:name/variables" curl https://api.mail.productcraft.co/v1/workspaces//templates/welcome/variables \ -H 'authorization: Bearer pcft_live_...' ``` ```json { "data": ["product", "name", "startUrl"] } ``` Use it to render a form in your operator UI, or add a CI check that compares the manifest against what your code passes — catches removed variables before they break production. To make validation strict, set `variables_schema` on the template (shape: `{version: 1, vars: {: {type, required?, default?, options?}}}`). Render and send then 400 with per-variable errors on mismatch. 3 ## Partials + layouts Repeating chrome lives in partials. Create one with `"kind": "partial"` (or `"kind": "layout"` for a full wrapper) on `POST /templates` — same endpoint, the `subject` is ignored for both. Reference them as `{{> partial.}}` / `{{> layout.}}`. Kind can't be changed after create. Mail also ships built-in components under the `bp.` namespace. They're bulletproof-table markup themed by your workspace brand tokens (`{{brand.*}}` — set in Console → Mail → Brand; change a color there and every email picks it up on next send): - `{{> bp.button text="..." href=url}}` — a button that renders correctly in every major client (Outlook included). Optional `variant` / `align`. - `{{> bp.hero title="..." subtitle="..."}}` — heading block, optional `cta_text` + `cta_href`. - `{{> bp.footer}}` — brand footer: logo, footer text, address, © line, all from brand settings. - `{{> bp.divider}}` and `{{> bp.spacer}}` — rules and vertical space that actually render in Outlook. - `{{#> bp.section}}...{{/bp.section}}` — a block partial that wraps your content in the branded card. Use in a template: ```json {{#> bp.section}}

Click the button to verify:

{{> bp.button text="Verify your email" href=verifyUrl}} {{/bp.section}} {{> bp.footer}} ``` 4 ## Lint Lint scores a draft for deliverability before you save it: subject-line problems (empty, all-caps, exclamation pileups), image-heavy bodies, missing alt text, spammy phrases, external stylesheets, oversized HTML, missing unsubscribe link. It returns a 0–100 score — ≥90 looks great, <70 is likely to spam-folder. **curl** ```bash title="POST /workspaces/:ws/templates/lint" curl https://api.mail.productcraft.co/v1/workspaces//templates/lint \ -H 'authorization: Bearer pcft_live_...' \ -H 'content-type: application/json' \ -d '{ "subject": "Welcome!", "body_html": "

Hi {{name}}

CLICK HERE!

" }' ``` **SDK** ```ts title="@productcraft/mail" import { Mail } from "@productcraft/mail"; // Reads PRODUCTCRAFT_API_KEY from the environment. A workspace key // finds its own workspace; pass { workspaceId } to skip that lookup. const mail = new Mail(); const lint = await mail.templates.lint({ subject: "Welcome!", body_html: "

Hi {{name}}

CLICK HERE!

", }); console.log(lint.score, lint.findings); ``` ```json { "score": 86, "findings": [ { "id": "body.spammy_phrases", "severity": "info", "message": "Contains 1 spammy phrase: \"click here\".", "suggestion": "Rewrite to sound like a real human telling someone what happened." }, { "id": "body.no_unsubscribe", "severity": "info", "message": "No \"unsubscribe\" link in the body." } ] } ``` Pass optional `data` to render variables with sample values first. Broken Handlebars (unclosed `{{#if}}`, malformed expression) fails the lint with a 422 and the parse error — the same failure you'd otherwise hit at render or send time. 5 ## Authoring patterns that survive Outlook - **Table-based layout.** Outlook's engine is the Word renderer. Modern CSS layout (flex, grid) doesn't exist there. Wrap your content in ``s with explicit widths — or use the `bp.*` components, which do this for you. - **Inline styles, not stylesheets.** Gmail strips `