# Deployment

Deploy a test environment to your Cloudflare account, step by step.

OrbCart runs in **your** Cloudflare account. There is no OrbCart server in between.

## What runs where

| Piece                      | What it does                                                  |
| -------------------------- | ------------------------------------------------------------- |
| One Worker per environment | Serves the API and calls your systems.                        |
| Durable Objects            | Hold Carts, Payments and Orders. The source of truth.         |
| Your Postgres (optional)   | The lists for the Admin API and the admin's Orders area.      |
| Cron trigger               | The daily EU VAT import, if you use `eu-standard`.            |
| Your storefront            | Anywhere you like. Only the commerce Worker needs Cloudflare. |

`test` and `live` are separate environments with separate keys and data.

## Set up Catalog and OrbPage from code

Choose Catalog's [private media store](/docs/catalog/media-storage) before importing media.
The default is its native `MEDIA` R2 binding; an existing private AWS S3 or compatible
bucket uses server-side endpoint/bucket/region vars and private credentials instead.
Reserve an unused managed root per environment. Delivery settings (`MEDIA_ORIGIN`,
`MEDIA_TRANSFORM`) do not choose storage or make a private bucket public.
For registered originals, follow the separate [Cloudflare](/docs/catalog/media-storage#cloudflare-recipe-private-r2-public-catalog-delivery)
or [CloudFront](/docs/catalog/media-storage#cloudfront-recipe-private-s3-catalog-as-custom-origin)
protected-storage recipe. Keep locator JSON private and route public media-ID URLs
through Catalog, not straight to the bucket. Those recipes document prerequisites,
not permission to change an account or evidence of live-provider acceptance.

An operator can configure a fresh Catalog and OrbPage without starting the admin or
signing in. Staff still use the merchant's sign-in; the operator is a separate,
deployment-scoped identity, never a human owner.

Issue a key offline, once per product and environment:

```sh
pnpm exec orbcatalog operator-key --out "$HOME/.config/shop/catalog-test.key"
pnpm exec orbcatalog operator-key --out "$HOME/.config/shop/page-test.key"
```

Each command writes 32 random bytes as an `op_…` credential to a **new**, mode-0600
file and prints **only its SHA-256 hash**. Create the private parent directory first.
Install that hash as `OPERATOR_KEY_HASH` in the corresponding Worker's environment
(for example through `wrangler secret put OPERATOR_KEY_HASH`). Only the hash belongs
on the server. Load the original key into your deployment script from your secret
store; never put it in a URL, log, browser bundle or repository. Replacing/removing
the configured hash rotates/revokes the credential immediately. Missing or malformed
configuration and wrong keys refuse access. `STAFF_ISSUER` may be absent until the
merchant installs the admin; staff and consent routes then refuse access.

Use Catalog's existing staff client, not a runtime import:

```ts worker
import { staffCatalog } from "@orbcatalog/client/staff";
import type { SchemaDocument, SettingsDocument } from "@orbcatalog/client/staff";
import { manageContent } from "@orbpage/client";
import type { Declarations, Settings } from "@orbpage/client";

export async function applySetup(input: {
  catalogUrl: string;
  catalogKey: string;
  pageUrl: string;
  pageKey: string;
  settings: SettingsDocument;
  schema: SchemaDocument;
  site: Settings;
  declarations: Declarations;
}) {
  const { catalogUrl, catalogKey, pageUrl, pageKey, settings, schema, site } = input;
  const run = crypto.randomUUID();
  const catalog = staffCatalog({
    url: catalogUrl,
    operatorKey: catalogKey,
    fetch: (request) => fetch(request),
  });
  const page = manageContent({ baseUrl: pageUrl, operatorKey: pageKey });

  const settingsResult = await catalog.applySettings(settings, {
    idempotencyKey: `${run}:settings`,
  });
  if (!settingsResult.ok) throw new Error(settingsResult.problem.code);
  const schemaResult = await catalog.applySchema(schema, {
    idempotencyKey: `${run}:schema`,
  });
  if (!schemaResult.ok) throw new Error(schemaResult.problem.code);

  const configured = await page.configure(site);
  if (!configured.ok) throw new Error(configured.problem.code);
  const declared = await page.declare(input.declarations, `${run}:declarations`);
  if (!declared.ok) throw new Error(declared.problem.code);
}
```

`applySettings` and `applySchema` compare parsed documents **before saving** and
answer `applied` or `unchanged`. A different pending draft is a conflict unless you
explicitly supply its `basedOn` revision. Locations and Resources use
`applyLocation(id, { basedOn, location }, key)` and
`applyResource(id, { basedOn, resource }, key)`; read their current revisions through
`locations()` and `resources()`. Equal records keep their revision. Stale revisions
still fail, even when the requested content happens to match.

The rest of a setup follows the public seams in order:

1. Apply Catalog settings, then Schema, then Locations and Resources.
2. Find the existing Source in `connections()`, or provision it once with `addSource`.
   Securely retain its returned key outside the repository: retries deliberately do
   not return the secret again. A lost Source key requires explicit `newSourceKey`,
   not another Source. Use `@orbcatalog/client/source` for product/category/register,
   media, offer and stock sync; the operator key is **not** a Source key.
3. Configure OrbPage from the published Catalog identity, then declare sections.
   `page.declare` is the same operation as `declareSections` in
   [Declare sections and slots](/docs/shop/sections#push-them-to-orbpage), with an operator key.
4. `ensurePage({ locale, title, slug }, key)` finds or creates the page without
   replacing its content. Resolve **all** page identities before writing cross-page
   links. It refuses to recreate an archived address. Keep the returned ids for
   subsequent deployments; do not interpret an editor's renamed address as new content.
5. Import media through the Catalog's media/Source clients. Open each eligible page
   with `page(id, locale)`, then call
   `applyPage(id, locale, { basedOn, content }, key)`. This is an explicit revisioned
   replacement and publish, not a reset. Only pass revisions of content your import
   owns or you reviewed; never reread an editor's revision merely to overwrite it.
   [Write content from code](/docs/page/write-content) shows the bodies and ids.
6. `addMenu`, `menu`, `applyMenu` work the same way after linked pages are published.
   Forms use `addForm`, `form`, `applyForm`; templates and category content have typed
   open/save/publish methods too. Keep editorial/form adoption separate when the
   deployment does not own those documents.

Page, menu and form apply compare both the draft and the currently published version:
an identical later run answers `unchanged` without a draft, version or publication.
An unpublished matching draft is still audited and published, never mistaken for
already-live content. All writes retain native revision checks, publication audits,
immutable history and transactional outboxes. Give each **new intent** a fresh key;
retry a lost request with the same key. An unchanged later apply is not an idempotency
replay. A failed publish can leave its saved draft for review; setup is not a
cross-product transaction.

Snapshots and cache purges still follow the durable outbox. Wait for the intended
`/v1` reads to become ready before opening the storefront; no storefront request
should configure the site. Setup never resets shared data or restores/republishes
an archived page automatically.

The operator credential accepts only Catalog settings/Schema/Location/Resource setup,
Source provisioning/rotation, non-destructive media setup and `product(ref)` ownership
reads. That read retains Source/editorial ownership metadata so a repeated import can
skip editorial products instead of reclaiming them; it grants no product mutation,
handover or publication permission. Stale Resources must be surfaced to authorized
staff for review, not silently deleted or reported as fully reconciled. On OrbPage it accepts
configuration, declarations and the typed content reads/create/save/publish operations.
It cannot read the inbox or submission files, erase customer data, delete/archive/
restore/withdraw content, manage staff, override publication errors, authorize MCP
chat proposals, or perform Cart payments/refunds. Staff authentication and human-only
MCP consent are unchanged. No key dashboard or key database is required.

## Deploy changes to public delivery

Catalog and OrbPage keep their Workers Cache across compatible deployments.
If cached responses from the previous version are no longer valid, raise
`deliveryShape` in the affected product before deploying. Catalog tracks its
shape in Postgres; run its migrations before deploying the Worker. OrbPage
tracks its own shape in the site object.

The next dispatcher run queues the affected product's delivery tags for purge.
Rolling back to a different shape queues them again. Catalog's Search feed
changes its ETag with the shape, not on every deployment.

A [100% deployment or rollback](https://developers.cloudflare.com/workers/versions-and-deployments/#default-behavior)
can still run both versions during propagation. If both versions cannot
serve the same cached answers during rollout or rollback, disable
`cross_version_cache` for that deployment and use an isolated cache on rollback.
Re-enable sharing only after the old shared entries have been purged or expired.

OrbPage checks the shape on its minute [Cron Trigger](https://developers.cloudflare.com/workers/configuration/cron-triggers/).
Allow time for the trigger to propagate on first deployment. If you roll back
to a version without the shape check, restore its trigger configuration too.

## Deploy a test environment

Until `orbcart deploy` exists, a test environment is a few Wrangler commands. Run
them from your commerce Worker's directory. `apps/nordgrat-cart-worker` is the reference.

### Give the lists a database

The Orders, the Carts that need a person, the Events with their deliveries and the
Checkout numbers live in a Postgres of yours, in the schema `cart` with a role `orbcart`
of its own: one database per merchant, which every OrbCommerce product shares. They are a
copy without personal data; the Durable Objects stay the truth. Keep the database in the EU.

Make the role and the schema, now and after every runtime update, with the database
owner's connection string in `OWNER_URL` and the role's in `ORBCART_URL`:

```sh
ORBCOMMERCE_OWNER_DATABASE_URL="$OWNER_URL" ORBCART_DATABASE_URL="$ORBCART_URL" \
  pnpm dlx tsx node_modules/@orbcart/runtime/scripts/migrate.ts
```

Then connect the Worker through Hyperdrive with its cache off, so a list never answers
from before a write, and put the ID it prints into the `HYPERDRIVE` binding of
`wrangler.jsonc`:

```sh
pnpm exec wrangler hyperdrive create shop-commerce-test-lists --connection-string="$ORBCART_URL" --caching-disabled
```

A preview may go without: its Worker then keeps no list and answers `projection_unavailable`.

A Worker with lists also needs a Cron Trigger, which drops events older than 30 days from
the event list, a bounded share each run:

```jsonc title="wrangler.jsonc"
"triggers": { "crons": ["*/15 * * * *"] }
```

It is the same trigger [EU VAT](/docs/integrate/tax) uses for its daily import.
### Deploy the Worker

```sh
pnpm exec wrangler deploy --name shop-commerce-test
```
### Set the root secret

Generated and piped straight in, so it never appears on screen or in your history:

```sh
openssl rand -base64 32 | tr '+/' '-_' | tr -d '=\n' | pnpm exec wrangler secret put ROOT_SECRET --name shop-commerce-test
```
### Set your provider keys

Only for the providers your Channels use. [Which keys →](/docs/shop/payments)

```sh
pnpm exec wrangler secret put STRIPE_SECRET_KEY --name shop-commerce-test
pnpm exec wrangler secret put STRIPE_PUBLISHABLE_KEY --name shop-commerce-test
pnpm exec wrangler secret put STRIPE_WEBHOOK_SECRET --name shop-commerce-test
```

Until every required secret is set, the Worker answers each request with
`internal`. `pnpm exec wrangler tail --name shop-commerce-test` shows what's missing.
### Point the webhooks at it

| Provider | URL                                                                |
| -------- | ------------------------------------------------------------------ |
| Stripe   | `https://shop-commerce-test.<account>.workers.dev/webhooks/stripe` |
| Adyen    | `https://shop-commerce-test.<account>.workers.dev/webhooks/adyen`  |
| PayPal   | `https://shop-commerce-test.<account>.workers.dev/webhooks/paypal` |
### Issue keys for the storefront

```sh
pnpm exec orbcart keys issue --env test --channel de --url https://shop-commerce-test.<account>.workers.dev
```

This writes the URL, a publishable key and a secret key to
`.orbcart/keys/test-de.env`. Give the storefront what it needs from there.
### Prime EU VAT

Only for Channels with `tax: "eu-standard"`:

```sh
pnpm exec orbcart tax sync --env test
```
### Open the admin to your staff

Set `STAFF_ISSUER` to the address of your OrbCommerce Admin and invite your staff there with
their areas. Its Orders area holds the Overview, the Orders with their refunds, the Carts that
need a person and the Checkout view. [Security →](/docs/cart/security#the-admin-and-your-staff)

## Connect the storefront

- Add the storefront's origin to the Channel's `origins` and set `returnUrl` to its return page. Then deploy the Worker again.
- Give the storefront `ORBCART_URL` and `ORBCART_PUBLISHABLE_KEY`. Only a server-side part gets `ORBCART_SECRET_KEY`.
- With Apple Pay, register the storefront's domain with your provider. [Express →](/docs/shop/express-checkout#setup-checklist)

## Protect cart creation and checkout

On your Cloudflare zone, put a [WAF rate limiting rule](https://developers.cloudflare.com/waf/rate-limiting-rules/)
on `POST /v1/carts`. If your storefront proxies cart creation, protect the
public route that forwards it too. Put a Managed Challenge in front of the
browser checkout page, not on the commerce API or provider webhooks. Choose
the threshold and test both rules with your normal checkout traffic before
enabling them in production.

OrbCart limits discount code entry separately. Configure
`CODE_ENTRIES_PER_ADDRESS` as a Workers rate limit binding (30 attempts per
60 seconds, with a distinct namespace ID per Environment).
[OrbCart's exact budgets](/docs/cart/security#rate-limits) still apply when the
edge binding admits a request.

## Updating

```sh
ORBCOMMERCE_OWNER_DATABASE_URL="$OWNER_URL" ORBCART_DATABASE_URL="$ORBCART_URL" \
  pnpm dlx tsx node_modules/@orbcart/runtime/scripts/migrate.ts
pnpm exec wrangler deploy --name shop-commerce-test
```

Secrets stay on the Worker between deploys. Open Carts keep working: a Cart
remembers its Channel, so don't rename or remove a Channel that still has Carts.

## Checklist before real money

- [ ] The [cart creation rate rule and checkout challenge](#protect-cart-creation-and-checkout) are tested.
- [ ] Everything on the [security checklist](/docs/cart/security#before-you-go-live) is done: keys, secrets, `origins`, webhooks.
- [ ] `orbcart tax status` shows today in `availableOn`, if you use EU VAT.
- [ ] `deliverOrder` deduplicates by `order.id`.
- [ ] Every Channel names its `withdrawal_policy` and `privacy_policy` in [`legal`](/docs/shop/configuration#legal). Without them a `live` Worker serves nothing.
- [ ] Your confirmation email and an [order page](/docs/shop/order-page) are in place.

<Callout type="warn" title="Pre-release">
`orbcart keys issue` only supports `test` today. A guided `live` setup arrives with `orbcart
deploy`. Check the [status page](/docs/cart/status) before taking real orders.
</Callout>