# Accounts, plans and usage

Shipwave uses Supabase Auth for email/password accounts and PostgreSQL for entitlements, owned API keys, usage and checkout coordination. The browser receives only the public Supabase URL and publishable key. The service credential stays on the server. PDF contents are not stored in these account tables.

## Server setup

Set these Railway variables:

```dotenv
SUPABASE_URL=https://YOUR_PROJECT.supabase.co
SUPABASE_PUBLISHABLE_KEY=YOUR_PUBLIC_PUBLISHABLE_KEY
SUPABASE_SERVICE_ROLE_KEY=YOUR_PRIVATE_SERVER_CREDENTIAL
```

`SUPABASE_ANON_KEY` is accepted as the publishable-key fallback; `SUPABASE_SECRET_KEY` is accepted as the server-secret fallback. Never expose the private server credential in browser code, screenshots, logs or a public repository. Use the existing project `zmutagholkalvddnpnxx` only with its matching keys.

When `SUPABASE_URL` is set, account authentication takes precedence over legacy shared Basic/API-key authentication. An incomplete setup or unavailable database returns **503** for protected processing; it does not grant anonymous access. Without this URL, the original shared-auth mode remains available. `SUPABASE_ENABLED=false` is a test-only override when `NODE_ENV=test`.

In Supabase Auth, keep email confirmation enabled, enable email/password signup, set the production Site URL, and allow the exact production and local redirect URLs you use. Local defaults are `http://localhost:3000` and `http://127.0.0.1:3000`. **Public signup is not ready until custom SMTP is configured.** Supabase's default sender delivers only to pre-authorized email addresses belonging to the project's organization team; other addresses are rejected. Its documented development limit is currently 2 messages per hour and can change. Use custom SMTP for confirmation, password recovery and email-change delivery to customers. See [Supabase SMTP restrictions](https://supabase.com/docs/guides/auth/auth-smtp). The hosted project currently has email confirmation enabled, Site URL `https://shipwavepdf.com`, exact callbacks for `https://shipwavepdf.com/` and `https://www.shipwavepdf.com/` (including recovery and `#account` variants), and localhost/127.0.0.1:3000 development callbacks. Setting these callbacks does not deploy the site or configure DNS. Custom SMTP is still absent. Deploying `supabase/config.toml` is a separate action: do not push its full local defaults over an existing hosted project's Auth configuration.

The browser signs in through Supabase, then sends `Authorization: Bearer <access-token>`. The server validates every session with Supabase Auth's user endpoint and requires a confirmed email. It does not authorize a decoded JWT or a role stored in user metadata. Display name may come from metadata; entitlement and owner membership come from server-controlled database records.

## Database migrations

Migration files are created with `supabase migration new`. The account schema is additive and prefixed `shipwave_`; it does not replace existing application tables or add a trigger to `auth.users`. The server creates/refreshes the account profile after a verified session.

For a new project, link it, review the SQL, and apply migrations through the normal Supabase migration workflow. For this project's hosted setup, the account and plan-index migrations were applied through the authenticated CLI query endpoint and recorded in migration history. Never re-run a previously applied migration manually.

`20261120162824_native_editor_access.sql` adds independent native-editor feature arrays and includes them in the account snapshot. It retains the existing tables, RLS policies, service-only function grants, prices, API features and quota amounts. The native HTTP API uses the existing atomic quota function with a server-selected `native:` feature namespace; this does not give browser roles permission to call that function directly.

All 12 account tables have row-level security. Browsers may read active plans and their own safe profile/subscription/override/monthly-usage rows. They have no write grants. API-key hashes, reservations, minute windows, owner membership, audit records, checkout locks and Stripe-event records are service-only. Privileged functions use `SECURITY INVOKER`, an empty search path and explicit execution grants for `service_role`; `anon`, `authenticated` and `PUBLIC` cannot execute them.

## Plans and owner management

There is no public administrator API or administrator screen in this release. Manage plans and account exceptions in the Supabase dashboard. No initial owner is automatically granted access. `shipwave_admins` and the audited service-only owner RPC are reserved for a future owner application.

Initial monthly prices and allowances are:

- **Free:** CAD $0, 100 web operations, 100 API operations, 10 requests/minute, 1 active API key; `core` features.
- **Starter:** CAD $9, 1,000 web operations, 2,000 API operations, 30 requests/minute, 3 active API keys; `core`, `office`, `ocr`, `pdfa`.
- **Pro:** CAD $19, 5,000 web operations, 20,000 API operations, 120 requests/minute, 10 active API keys; all listed features including `ai` and `signatures`.
- **Business:** CAD $49, 25,000 web operations, 100,000 API operations, 300 requests/minute, 25 active API keys; all listed features.

The current database rows are authoritative. These prices exclude any taxes collected at checkout. Feature entitlement does not configure the underlying AI, signing or conversion provider; that provider must also be available.

Edit `shipwave_plans` to change prices, allowances, feature arrays, API-key limits or availability. Set `active=false` to stop offering a plan to new subscribers. Existing subscriptions retain their plan entitlement while paid and in term. Stripe prices are immutable: the billing service reconciles a changed database amount/currency to a new Stripe Price for new checkouts; it does not rewrite existing subscription agreements.

To grant an account exception, add/edit `shipwave_account_overrides` using the profile's `user_id`. Nullable limits/features inherit the plan; a non-null feature array replaces the plan array. Zero monthly allowance blocks that usage channel; there is no unlimited sentinel. Set `shipwave_profiles.disabled=true` to block processing and new key creation. A billing review uses `shipwave_subscriptions.billing_hold=true` plus a short `risk_reason`; processing returns 403 while Account remains readable. Clear the hold after review. Direct dashboard edits update `updated_at`; the future owner RPC additionally records its actor and changes in `shipwave_admin_audit`.

Avoid manually editing usage or Stripe-event rows. Paid access requires `active`/`trialing` status **and** a future `current_period_end`. Canceled, past-due, expired or incomplete subscriptions receive Free allowances. A billing hold blocks processing regardless of plan. Stripe webhooks are the normal source of subscription state.

## Native editor subscription access

The original server tools and native PDFCraft editor have **independent** feature arrays:

- `shipwave_plans.features` / `shipwave_account_overrides.features` control the original PDF APIs. These retain their existing behavior.
- `shipwave_plans.native_features` / `shipwave_account_overrides.native_features` control the native editor and native HTTP tools. The account API exposes these as `plan.nativeFeatures` and effective `limits.nativeFeatures`.

The native feature names are `core`, `advanced`, `office`, `ocr`, `pdfa`, `signatures` and `ai`. `core` enables native mutations and basic page/comment tools; `advanced` adds content editing, images/forms and advanced production tools. `office`, `ocr`, `pdfa`, `signatures` and `ai` enable their corresponding native commands. Visual signing remains basic/core; actual certificate signing requires `signatures`. Providers, conversion engines and signing certificates must also be configured or supplied where a tool requires them. A subscription is not an AI key or signing certificate.

Initial native access is Free → `core`; Starter → `core, advanced, office, ocr, pdfa`; Pro/Business → all seven. A per-user `native_features=NULL` inherits the effective plan. An empty array `[]` disables native editing for that account while leaving its original API feature array unchanged. Every native mutation also requires `core`, so an array without `core` does not enable editing. Unknown native feature names are rejected by database constraints.

For example, run this only as the project owner in Supabase to grant a native-editor exception without changing API rights:

```sql
insert into public.shipwave_account_overrides (user_id, native_features)
values ('USER_UUID', array['core','advanced'])
on conflict (user_id) do update set native_features=excluded.native_features;
```

Set `native_features=null` to inherit again, or `array[]::text[]` to disable editing. The future service-only owner RPC also accepts `nativeFeatures` and records it in the audit log; no administrator HTTP route is exposed.

Local native editing is **unmetered within allowed features**. It does not consume the monthly web/API allowance. The editor obtains a nonce-bound, Ed25519-signed feature lease lasting at most five minutes; a paid lease is additionally capped at its paid period's expiry. The native build verifies the signature against a public key compiled into WASM and checks features/expiry at its mutation boundary. Editing starts locked without a valid proof. Viewing, opening, saving existing work, navigation, undo/redo and recovery remain available without paid editing access.

The browser refreshes these short leases after session/profile changes and periodically while in use. Owner changes or a billing hold stop subsequent leases immediately; an already-issued proof can remain valid until its short expiry. Sign-out clears the browser's installed access. This protects the shipped application flow; a user who modifies an open-source local engine is not subject to tamper-proof DRM. Native HTTP execution is separately enforced on the server and continues to use authoritative Supabase quotas.

### Native signing-key setup

Run `node scripts/setup-editor-access.js` locally before building the native editor. It creates or reuses `SHIPWAVE_EDITOR_LEASE_SEED`, stores that 32-byte base64url private seed in local `.env` with mode `0600`, and writes **only** its Ed25519 public verification key to `public/pdfcraft/editor-public-key.json`. The native build pins that public key through `SHIPWAVE_EDITOR_LEASE_PUBLIC_KEY`. Neither the private seed nor a Supabase/Stripe secret belongs in browser assets.

Deployment must supply the **same private seed that matches the bundled public key** as a server secret. All application replicas need the matching seed. The server refuses to sign when the seed is missing, invalid or mismatched; it never generates a replacement signing key at request time. The release archive excludes `.env`, so it does not include this private seed. Rebuilding for a different deployment requires generating its key and rebuilding the native WASM with the corresponding public key.

The bundled public-key manifest is authoritative. If `SHIPWAVE_EDITOR_LEASE_PUBLIC_KEY` is also set on the server, it must match that bundled key; a different matching seed/environment-key pair cannot override the native pin. A malformed or unreadable manifest fails closed. Environment-only public keys are a fallback for isolated fixtures without a bundled manifest, not a way to rotate a deployed browser bundle.

Rotate the seed and native public-key pin together in one release. Old tabs may need to save their work and reload after rotation; rotating only the server seed makes their existing native bundle reject new proofs. Ordinary save/recovery does not require a lease.

## Usage accounting

An authenticated browser session uses the **web** allowance. An owned `X-API-Key` uses the **API** allowance. A bearer token takes precedence if both are supplied; request bodies and caller-selected headers cannot choose a different channel or feature tier.

One successful processing request consumes one operation, independent of PDF pages or output files. Both channels reset at **00:00 UTC on the first day of each calendar month**. This reset is independent of the Stripe subscription renewal date. The per-minute limit is shared by both channels and uses fixed minute windows.

A database transaction reserves monthly allowance before processing and records a unique reservation. A per-user database lock serializes concurrent reservations across Railway instances. Failed processing responses refund the monthly reservation once. Minute attempts stay counted, including feature/quota denials and invalid processing requests. An upload abandoned before processing starts refunds its monthly reservation. If the browser disconnects while work is running, settlement waits for the actual operation outcome: successful work counts and failed work refunds. An unavailable settlement service retains the reservation rather than granting untracked work.

Health/config/account/billing requests, temporary uploads (`/api/upload/temp`) and PDF inspection (`/api/pdf/analyze`, `/pdf-info`) do not consume the processing allowance. They still require authentication where applicable. These setup calls do not enter the processing minute counter; server capacity and general request limits apply separately.

Native local feature leases do not consume quota. A native HTTP processing batch is one processing request: it reserves the caller's existing web or API allowance, checks `core` plus every requested native operation's server-defined features, and refunds the monthly reservation on failure. It cannot choose a cheaper feature through request headers/body fields. Native HTTP authentication accepts the same verified sessions/personal API keys as the other processing routes; a signed local-editor proof is not an API credential.

Server feature mapping:

- `office`: Office/RTF to PDF and PDF to Word/Excel/PowerPoint.
- `ocr`: `/api/tools/ocr`.
- `pdfa`: `/api/convert/pdf-to-pdfa`.
- `ai`: `/api/ai/run`.
- `signatures`: external signature requests at `/api/tools/request-signatures`.
- `core`: other PDF processing, including visual signing and PDF password tools.

A missing feature returns 403 `FEATURE_NOT_INCLUDED`. Exhausted monthly or minute allowance returns 429 `MONTHLY_LIMIT` / `RATE_LIMIT` with `Retry-After`. A disabled account or billing hold returns 403. Authentication errors return 401. Provider/database failures return a generic 503 without private upstream details.

## Account HTTP API

These paths are separate from the PDF processing routes. Responses containing account/key data use `Cache-Control: no-store`.

`GET /api/account/config` is public:

```json
{"enabled":true,"ready":true,"supabaseUrl":"https://YOUR_PROJECT.supabase.co","publishableKey":"PUBLIC_KEY"}
```

`GET /api/account/me` requires a verified bearer session. It returns `user`, `profile`, `subscription`, `plan`, `limits`, `usage` and `isAdmin`:

```json
{
  "user":{"id":"USER_UUID","email":"you@example.com","name":"Your name"},
  "profile":{"id":"USER_UUID","email":"you@example.com","displayName":"Your name","disabled":false,"createdAt":"ISO_TIMESTAMP"},
  "subscription":{"planId":"free","status":"free","currentPeriodStart":null,"currentPeriodEnd":null,"cancelAtPeriodEnd":false,"billingHold":false,"riskReason":null},
  "plan":{"id":"free","name":"Free","priceCents":0,"currency":"cad","features":["core"],"nativeFeatures":["core"]},
  "limits":{"webMonthly":100,"apiMonthly":100,"requestsPerMinute":10,"maxApiKeys":1,"features":["core"],"nativeFeatures":["core"]},
  "usage":{"period":"2026-11","webUsed":0,"apiUsed":0,"webRemaining":100,"apiRemaining":100},
  "isAdmin":false
}
```

Profile is read-only through this API. `plan` describes the effective plan; `subscription` retains the actual billing record, so a lapsed paid subscription can appear alongside effective Free limits.

### Editor access endpoints

`GET /api/account/editor-access` requires a verified bearer session in account mode and returns metadata, not a mutation credential:

```json
{"enabled":true,"ready":true,"mode":"local","plan":{"id":"free","name":"Free","priceCents":0,"currency":"cad","features":["core"],"nativeFeatures":["core"]},"features":["core"],"leaseSeconds":300,"localEditsMetered":false}
```

`POST /api/account/editor-access` accepts exactly `{"nonce":"THE_NONCE_FROM_THE_NATIVE_TAB"}`. Use the tab nonce returned by the native bridge state; do not invent a new nonce when installing access into an existing tab. A nonce is 16–128 base64url/hex-compatible characters (`A–Z`, `a–z`, `0–9`, `_`, `-`). The response is `{"payload":"<raw JSON string>","signature":"<base64url Ed25519 signature>"}`. The decoded payload shape is:

```json
{"v":1,"nonce":"THE_NONCE_FROM_THE_NATIVE_TAB","issuedAt":1800000000,"expiresAt":1800000300,"features":["core"],"mode":"local"}
```

Times are Unix seconds. Verify the **original raw payload bytes**, not re-serialized JSON. The native bridge installs this response with `install-access`; the WASM pin/nonce/expiry check grants the signed features. No access token, API key, private signing key or PDF contents appear in the payload. A caller-supplied feature array or extra request field returns 400 `INVALID_EDITOR_NONCE`. Missing signing setup returns 503 `EDITOR_ACCESS_NOT_CONFIGURED`. Disabled accounts/billing holds return 403. Personal API keys cannot obtain browser-editor leases; use the native HTTP execution API for API-key automation. When Supabase is completely omitted, these endpoints follow the existing legacy authentication policy; unrestricted legacy access requires authentication to have been explicitly disabled.

Owned-key endpoints require a bearer session; API keys cannot manage an account or create/revoke keys:

- `GET /api/account/api-keys` → `{"keys":[{"id":"UUID","name":"Automation","prefix":"sw_live_ABCDEFGH","createdAt":"ISO_TIMESTAMP","lastUsedAt":null,"revokedAt":null}]}`. Returns up to 100 owned records: active keys first, newest created first, followed by most recently revoked keys. This keeps older active keys visible even after many revocations. Returns neither raw keys nor hashes.
- `POST /api/account/api-keys` with JSON `{"name":"Automation"}` → 201 `{"key":"sw_live_...","apiKey":{...metadata}}`. Name is 1–80 characters. The full secret is returned **once**. Exceeding the active-key limit returns 409 `API_KEY_LIMIT`.
- `DELETE /api/account/api-keys/:id` → `{"success":true}`. Only the signed-in owner's key can be revoked. Other owners' key identifiers return 404.

Raw keys contain 256 bits of random material. Only their SHA-256 hashes, a short visible prefix and metadata are persisted. Keep the raw key in your application's secret store and send it through `X-API-Key`; query-string keys and legacy shared keys are not accepted in account mode.

```sh
curl -X POST https://YOUR_APP/api/tools/rotate \
  -H "X-API-Key: $SHIPWAVE_API_KEY" \
  -F pdfFile=@document.pdf -F angle=90
```

Billing checkout/portal/invoice/webhook contracts are documented with the billing integration. No customer is granted paid access from a browser success URL alone.

The Account interface calls these same endpoints. Its key name field creates a key with `POST`; its Copy button copies only that once-returned secret; Revoke uses `DELETE` with the owned key ID. Sign-in/signup/recovery/password changes and sign-out use the Supabase Auth SDK directly. See [API account examples](API.md#accounts-and-api-keys) for password-session acquisition, token refresh and complete key-management requests. There is no public administrator API, signup proxy, profile-update route or document-history API.

## Service integration and tests

`createAccountService(options)` exposes `configured`, `ready`, `publicConfig()`, `router`, `middleware`, `authenticate(req,{sessionOnly})`, `getEntitlements(userId)`, `editorContext(req)`, `editorSigner`, `assertNativeFeature(req,featuresArray)` and `db`. The router must be mounted before protected PDF middleware. The outer server supplies JSON parsing for account request bodies and leaves health/docs/static pages public.

Pass `nativeFeatureForRequest(req)` as a server-owned resolver when constructing the service. Native HTTP batch routes return `native:core`; original routes keep their existing feature map. The native handler then calls `assertNativeFeature(req, requiredFeatures)` with the validated operation catalog's features before running the CLI. It throws 403 `NATIVE_FEATURE_NOT_INCLUDED` for missing native rights and also enforces disabled/held accounts. Never accept this required-feature list from the client. An optional `authorizeLegacyEditor(req)` callback lets the outer server reuse its fully resolved legacy authentication settings; configured Supabase mode never uses that callback as a bypass.

The database adapter returns arrays from `select(table,filters,options)`, `insert(table,row)`, `upsert(table,row,onConflict)` and `update(table,filters,patch)`. Equality filters, null and array `in` filters are supported; select options are `select`, `limit`, `offset`, and `order` (for example `sort_order.asc`). `rpc(name,args)` returns the raw JSON/scalar RPC result. These methods use the server credential and must never be exposed as a caller-controlled query endpoint.

Processing attaches `req.account` and, once reserved, `req.accountUsage = {reservationId,complete(success)}`. Completion is idempotent. Completed HTTP responses settle from `finish`, after the final response status is known. The operation lifecycle settles disconnected work after it actually finishes. The async operation lifecycle must keep reservations for work continuing after a client disconnect.

`shipwave_sync_subscription` records unique Stripe event IDs and ignores stale lifecycle updates. A stale dispute/refund risk hold can still set the hold without overwriting newer plan state. Omitted hold arguments preserve an existing hold. Explicit `p_billing_hold=false` clears it. `shipwave_acquire_checkout` / `shipwave_release_checkout` provide a token-matched, five-minute per-user database lease so concurrent Railway replicas cannot create overlapping checkout workflows.

Run `node --test test/accounts.test.js` (or `npm test`). Development dependency PGlite executes the real migration and PostgreSQL functions for RLS/grants, quota races/refunds, key ownership/revocation, billing holds, event ordering and checkout leases; local HTTP fixtures test account routes and Auth verification. Tests make no real Supabase/Stripe/AI calls. Native checks additionally cover independent plan/owner features, signed nonce-bound proofs, paid-term expiry, signature tampering and signing-key mismatch, legacy auth, native HTTP channel quotas, and local-lease requests leaving counters unchanged. Hosted deployment verification additionally checked RLS, function grants, foreign-key indexes and database lint. The native-feature migration preserves the existing RLS and service-only execution boundary. The November 20 security advisor check reports the existing Auth leaked-password-protection warning and seven informational findings for intentionally service-only tables without browser policies; no new native-table exposure was introduced. A disposable confirmed synthetic account also verified real hosted login, API-key creation/revocation, PDF processing usage, invalid-request refunds and a persisted quota denial without sending emails or making Stripe calls. Configure a production log/retention policy for usage reservations, historical month counters, revoked keys and processed Stripe events; retain Stripe event IDs long enough for webhook retries and investigations.

Official references: [Supabase Auth user verification](https://supabase.com/docs/reference/javascript/auth-getuser), [JWT verification](https://supabase.com/docs/guides/auth/jwts), [row-level security](https://supabase.com/docs/guides/database/postgres/row-level-security), [database functions](https://supabase.com/docs/guides/database/functions), [production email delivery](https://supabase.com/docs/guides/auth/auth-smtp).
