From 3e3ca21897add776d31ae90bfbb606fb6c886849 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 17:46:32 +0000 Subject: [PATCH 1/8] Add one-shot environment runbooks for the Bench Ticket demo. Publish Local Docker, Cloudflare, Azure, and AWS runbooks on the site, backed by a CI-tested support-queue-slice fixture. AWS uses the forthcoming @pegma/storage-dynamodb adapter (storage-core#7) as the Store; Docker, Cloudflare, and Azure do not wait on that PR. Co-authored-by: Fly Over Coder --- .claude/skills/pegma/SKILL.md | 1 + .dockerignore | 10 + README.md | 3 + docs/catalog/RECIPE_BACKLOG.md | 22 +- evals/assembly-cases.ts | 12 + package.json | 2 + pnpm-lock.yaml | 59 ++- public/llms.txt | 19 +- public/skill.md | 1 + recipes/README.md | 4 +- recipes/bench-ticket/Dockerfile | 10 + recipes/bench-ticket/README.md | 16 + recipes/bench-ticket/cloudflare/worker.ts | 56 +++ .../bench-ticket/cloudflare/wrangler.jsonc | 22 + recipes/bench-ticket/composition.test.ts | 139 ++++++ recipes/bench-ticket/composition.ts | 333 +++++++++++++++ recipes/bench-ticket/docker-compose.yml | 36 ++ recipes/bench-ticket/handler.test.ts | 143 +++++++ recipes/bench-ticket/handler.ts | 404 ++++++++++++++++++ recipes/bench-ticket/host.ts | 135 ++++++ recipes/bench-ticket/mail-catcher.ts | 33 ++ recipes/bench-ticket/mail-smtp.ts | 104 +++++ src/data/catalog-enrichment.ts | 7 + src/data/compile-catalog.test.ts | 14 +- src/data/recipe-backlog.ts | 66 ++- src/layouts/Base.astro | 3 +- src/layouts/MarkdownDoc.astro | 20 + src/pages/examples.astro | 28 +- src/pages/runbooks.md | 24 ++ src/pages/runbooks/aws.md | 196 +++++++++ src/pages/runbooks/azure.md | 177 ++++++++ src/pages/runbooks/cloudflare.md | 160 +++++++ src/pages/runbooks/local-docker.md | 142 ++++++ src/pages/skill.astro | 1 + src/pages/start.astro | 2 +- src/styles/global.css | 25 ++ 36 files changed, 2375 insertions(+), 54 deletions(-) create mode 100644 .dockerignore create mode 100644 recipes/bench-ticket/Dockerfile create mode 100644 recipes/bench-ticket/README.md create mode 100644 recipes/bench-ticket/cloudflare/worker.ts create mode 100644 recipes/bench-ticket/cloudflare/wrangler.jsonc create mode 100644 recipes/bench-ticket/composition.test.ts create mode 100644 recipes/bench-ticket/composition.ts create mode 100644 recipes/bench-ticket/docker-compose.yml create mode 100644 recipes/bench-ticket/handler.test.ts create mode 100644 recipes/bench-ticket/handler.ts create mode 100644 recipes/bench-ticket/host.ts create mode 100644 recipes/bench-ticket/mail-catcher.ts create mode 100644 recipes/bench-ticket/mail-smtp.ts create mode 100644 src/layouts/MarkdownDoc.astro create mode 100644 src/pages/runbooks.md create mode 100644 src/pages/runbooks/aws.md create mode 100644 src/pages/runbooks/azure.md create mode 100644 src/pages/runbooks/cloudflare.md create mode 100644 src/pages/runbooks/local-docker.md diff --git a/.claude/skills/pegma/SKILL.md b/.claude/skills/pegma/SKILL.md index a5707e8..97a9db5 100644 --- a/.claude/skills/pegma/SKILL.md +++ b/.claude/skills/pegma/SKILL.md @@ -71,6 +71,7 @@ decision: Index (short): `https://pegma.dev/llms.txt` Human stack pages: `https://pegma.dev/stack` Recipe index: `https://pegma.dev/examples` +Environment runbooks: `https://pegma.dev/runbooks` This skill (judgment only): `https://pegma.dev/skill.md` Optional MCP (same catalog facts): `https://pegma.dev/api/mcp` diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b14f266 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +node_modules +.git +.astro +dist +coverage +.wrangler +worker/.dev.vars +*.tsbuildinfo +.env +.env.* diff --git a/README.md b/README.md index 37e848d..8bcd598 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,9 @@ retiregolden.org, runs the stack on Azure). Identity and its Authorization adapter remain fail-closed injected ports until their first exact public versions can replace the release boundary in `worker/src/identity-runtime.ts`. +- **Environment runbooks** for a synthetic Bench Ticket demo (email-code + identity, sessions, mail catcher, support desk, health): + [https://pegma.dev/runbooks](https://pegma.dev/runbooks). ## Local development diff --git a/docs/catalog/RECIPE_BACKLOG.md b/docs/catalog/RECIPE_BACKLOG.md index 5c8fc13..62894b6 100644 --- a/docs/catalog/RECIPE_BACKLOG.md +++ b/docs/catalog/RECIPE_BACKLOG.md @@ -84,6 +84,20 @@ deferred). | **capabilityTags** | `static_host` only (not bare `cloudflare` — host-tag alone must not select this scaffold) | | **Fixture** | green — [`recipes/scaffold-cf-minimal/`](../../recipes/scaffold-cf-minimal/) | +### P7 — `support-queue-slice` (Bench Ticket) + +| | | +| --- | --- | +| **Intent** | A fictional makerspace helpdesk (“Bench Ticket”) runs a small support-desk site with first-party email-code login, sessions, mail to a catcher, and ticket create/list/reply. | +| **Packages (published)** | `@pegma/identity`, `@pegma/sessions`, `@pegma/mail`, `@pegma/rate-limit`, `@pegma/health`, `@pegma/support-desk-*`, `@pegma/storage-core`, `@pegma/spine` | +| **Adapters** | memory (local Docker); `storage-cloudflare-d1`; `storage-azure-tables`; forthcoming `storage-dynamodb` | +| **Host must provide** | HTTP, cookies, injected Store, mail catcher, email-code secret | +| **Non-goals** | Auth0/Entra/Cognito, Stripe, production email, passkeys-required login | +| **Anti-patterns** | Treating Support Desk as hosted SaaS; giving Audit/Mail their own store | +| **requiresPublished** | identity, sessions, mail, rate-limit, health, support-desk, storage-core, spine, authorization-core | +| **Fixture** | green — [`recipes/bench-ticket/`](../../recipes/bench-ticket/) | +| **Runbooks** | `/runbooks` (Local Docker, Cloudflare, Azure, AWS) | + ## Deferred (missing package or fixture) Do not offer for production assembly until required packages are on npm and a @@ -97,14 +111,6 @@ CI-tested fixture is green. | **Blocks** | CI-tested synthetic fixture not yet built | | **Anti-patterns** | Exactly-once claims; storing full payloads in the receipt ledger; ordering guarantees | -### D2 — `support-queue-slice` (when Support Desk packages are published) - -| | | -| --- | --- | -| **Intent** | A fictional maker-space helpdesk (“Bench Ticket”) runs a composable support queue for web and email with permission-checked agents and outbox-backed mail. | -| **Blocks** | support-desk packages unpublished | -| **Anti-patterns** | Treating Support Desk as hosted SaaS; AI on ticket bodies before the host documents egress | - ## Explicitly out of backlog (non-goals) - Recipes that copy pegma.dev or retiregolden.org route maps, schemas, or ops topology diff --git a/evals/assembly-cases.ts b/evals/assembly-cases.ts index cb96023..9e7acea 100644 --- a/evals/assembly-cases.ts +++ b/evals/assembly-cases.ts @@ -81,4 +81,16 @@ export const ASSEMBLY_EVAL_CASES: readonly AssemblyEvalCase[] = [ mustNotRecommendSubstrings: ['password'], mustSurfaceRefusalSubstrings: ['password'], }, + { + id: 'support-desk-email-code', + prompt: + 'Small support desk with first-party email-code login. No Stripe, no Auth0, no passwords.', + capabilityTags: ['support_queue', 'accounts', 'email_codes'], + mustPrimaryRecipeId: 'support-queue-slice', + mustIncludePackageNames: [ + '@pegma/identity', + '@pegma/support-desk-application', + ], + mustNotRecommendSubstrings: ['stripe', 'auth0', 'password'], + }, ]; diff --git a/package.json b/package.json index 20f2001..b02b136 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "test:d1": "vitest run --config vitest.d1.config.ts", "eval:assembly": "vitest run --config vitest.config.ts evals/assembly-eval.test.ts", "preview": "astro preview", + "demo:bench-ticket": "tsx recipes/bench-ticket/host.ts", "worker:dev": "wrangler dev -c worker/wrangler.jsonc", "worker:deploy": "wrangler deploy -c worker/wrangler.jsonc", "worker:tail": "wrangler tail pegma-dev-api", @@ -50,6 +51,7 @@ "@cloudflare/vitest-pool-workers": "0.18.8", "@types/node": "26.1.1", "astro": "7.1.4", + "tsx": "^4.23.13", "typescript": "^5.9.2", "vitest": "4.1.10", "wrangler": "^4.114.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 63c38a2..310204f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -79,7 +79,7 @@ importers: version: 0.1.1 agents: specifier: ^0.20.1 - version: 0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0))(zod@4.4.3) + version: 0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3) zod: specifier: ^4.4.3 version: 4.4.3 @@ -89,19 +89,22 @@ importers: version: 0.9.10(prettier@3.9.6)(typescript@5.9.3) '@cloudflare/vitest-pool-workers': specifier: 0.18.8 - version: 0.18.8(@cloudflare/workers-types@5.20260729.1)(@vitest/runner@4.1.10)(@vitest/snapshot@4.1.10)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0))) + version: 0.18.8(@cloudflare/workers-types@5.20260729.1)(@vitest/runner@4.1.10)(@vitest/snapshot@4.1.10)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))) '@types/node': specifier: 26.1.1 version: 26.1.1 astro: specifier: 7.1.4 - version: 7.1.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@26.1.1)(yaml@2.9.0) + version: 7.1.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@26.1.1)(tsx@4.23.13)(yaml@2.9.0) + tsx: + specifier: ^4.23.13 + version: 4.23.13 typescript: specifier: ^5.9.2 version: 5.9.3 vitest: specifier: 4.1.10 - version: 4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)) + version: 4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) wrangler: specifier: ^4.114.0 version: 4.114.0(@cloudflare/workers-types@5.20260729.1) @@ -2629,6 +2632,11 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsx@4.23.13: + resolution: {integrity: sha512-BL5MGkRln6aDYhb0xbQlEAGw743BaZYWdbWtdJOBriYJboKgUUYCadFp2/FpBBZquBC/ezNBn7wMMPx7FDZUDw==} + engines: {node: '>=18.0.0'} + hasBin: true + tsyringe@4.10.0: resolution: {integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==} engines: {node: '>= 6.0.0'} @@ -3411,14 +3419,14 @@ snapshots: optionalDependencies: workerd: 1.20260722.1 - '@cloudflare/vitest-pool-workers@0.18.8(@cloudflare/workers-types@5.20260729.1)(@vitest/runner@4.1.10)(@vitest/snapshot@4.1.10)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)))': + '@cloudflare/vitest-pool-workers@0.18.8(@cloudflare/workers-types@5.20260729.1)(@vitest/runner@4.1.10)(@vitest/snapshot@4.1.10)(vitest@4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)))': dependencies: '@vitest/runner': 4.1.10 '@vitest/snapshot': 4.1.10 cjs-module-lexer: 1.2.3 esbuild: 0.28.1 miniflare: 4.20260722.0 - vitest: 4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)) + vitest: 4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) wrangler: 4.114.0(@cloudflare/workers-types@5.20260729.1) zod: 3.25.76 transitivePeerDependencies: @@ -4140,14 +4148,14 @@ snapshots: '@rolldown/binding-win32-x64-msvc@1.1.5': optional: true - '@rolldown/plugin-babel@0.2.3(@babel/core@8.0.1)(@babel/runtime@7.29.7)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0))': + '@rolldown/plugin-babel@0.2.3(@babel/core@8.0.1)(@babel/runtime@7.29.7)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))': dependencies: '@babel/core': 8.0.1 picomatch: 4.0.5 rolldown: 1.1.5 optionalDependencies: '@babel/runtime': 7.29.7 - vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0) + vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0) '@rolldown/pluginutils@1.0.1': {} @@ -4265,13 +4273,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.10(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0))': + '@vitest/mocker@4.1.10(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))': dependencies: '@vitest/spy': 4.1.10 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0) + vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0) '@vitest/pretty-format@4.1.10': dependencies: @@ -4352,14 +4360,14 @@ snapshots: mime-types: 3.0.2 negotiator: 1.0.0 - agents@0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0))(zod@4.4.3): + agents@0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3): dependencies: '@babel/plugin-proposal-decorators': 8.0.2(@babel/core@8.0.1) '@cfworker/json-schema': 4.1.1 '@modelcontextprotocol/client': 2.0.0 '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3) '@modelcontextprotocol/server': 2.0.0 - '@rolldown/plugin-babel': 0.2.3(@babel/core@8.0.1)(@babel/runtime@7.29.7)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)) + '@rolldown/plugin-babel': 0.2.3(@babel/core@8.0.1)(@babel/runtime@7.29.7)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) cron-schedule: 6.0.0 esbuild: 0.28.1 mimetext: 3.0.28 @@ -4371,7 +4379,7 @@ snapshots: yargs: 18.1.0 zod: 4.4.3 optionalDependencies: - vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0) + vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0) transitivePeerDependencies: - '@babel/core' - '@babel/plugin-transform-runtime' @@ -4423,7 +4431,7 @@ snapshots: assertion-error@2.0.1: {} - astro@7.1.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@26.1.1)(yaml@2.9.0): + astro@7.1.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@26.1.1)(tsx@4.23.13)(yaml@2.9.0): dependencies: '@astrojs/compiler-rs': 0.3.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3) '@astrojs/internal-helpers': 0.10.1 @@ -4473,8 +4481,8 @@ snapshots: ultrahtml: 1.7.0 unifont: 0.7.4 unstorage: 1.17.5 - vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0) - vitefu: 1.1.3(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)) + vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0) + vitefu: 1.1.3(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) xxhash-wasm: 1.1.0 yargs-parser: 22.0.0 zod: 4.4.3 @@ -5630,6 +5638,12 @@ snapshots: tslib@2.8.1: {} + tsx@4.23.13: + dependencies: + esbuild: 0.28.1 + optionalDependencies: + fsevents: 2.3.3 + tsyringe@4.10.0: dependencies: tslib: 1.14.1 @@ -5741,7 +5755,7 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0): + vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0): dependencies: lightningcss: 1.33.0 picomatch: 4.0.5 @@ -5752,16 +5766,17 @@ snapshots: '@types/node': 26.1.1 esbuild: 0.28.1 fsevents: 2.3.3 + tsx: 4.23.13 yaml: 2.9.0 - vitefu@1.1.3(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)): + vitefu@1.1.3(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)): optionalDependencies: - vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0) + vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0) - vitest@4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)): + vitest@4.1.10(@types/node@26.1.1)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.10 - '@vitest/mocker': 4.1.10(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0)) + '@vitest/mocker': 4.1.10(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) '@vitest/pretty-format': 4.1.10 '@vitest/runner': 4.1.10 '@vitest/snapshot': 4.1.10 @@ -5778,7 +5793,7 @@ snapshots: tinyexec: 1.2.4 tinyglobby: 0.2.17 tinyrainbow: 3.1.0 - vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(yaml@2.9.0) + vite: 8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 26.1.1 diff --git a/public/llms.txt b/public/llms.txt index 61948cb..5e6cb73 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -117,6 +117,18 @@ status, design decisions, and non-goals. `get_recipe`, `plan_composition`. Public catalog facts only; no private data plane; no auth for reads. Config notes: https://pegma.dev/skill +## Environment runbooks (agents) + +One-shot a small support-desk demo (Bench Ticket: email-code identity, sessions, +mail catcher, storage, health). No Stripe, Auth0, Entra, or production email. + +- Index: https://pegma.dev/runbooks +- Local Docker (template): https://pegma.dev/runbooks/local-docker +- Cloudflare (D1 + R2): https://pegma.dev/runbooks/cloudflare +- Azure (Tables + Blob): https://pegma.dev/runbooks/azure +- AWS (DynamoDB via forthcoming `@pegma/storage-dynamodb`): https://pegma.dev/runbooks/aws +- Fixture: https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket + ## Scaffold (agents) - Minimal Cloudflare-shaped composition root (Glass Wing synthetic scaffold): @@ -132,8 +144,11 @@ status, design decisions, and non-goals. - [Roadmap](https://pegma.dev/roadmap): the aggregate view; status compiled at build time from the repos' plans. - [Examples](https://pegma.dev/examples): composition recipes with CI-tested - fixtures under recipes/ (P1 accounts, P2 audit/mail outbox) plus snippets - lifted from package READMEs; each block cites its source. + fixtures under recipes/ (P1 accounts, P2 audit/mail outbox, Bench Ticket + support queue) plus snippets lifted from package READMEs; each block cites + its source. +- [Runbooks](https://pegma.dev/runbooks): one-shot Local Docker, Cloudflare, + Azure, and AWS environments for the Bench Ticket demo. - [Skill](https://pegma.dev/skill): install notes for the assembly skill. - [Account](https://pegma.dev/account): the static shell for pegma.dev's D1-backed first-party Identity reference consumer. The Worker pins the exact diff --git a/public/skill.md b/public/skill.md index a5707e8..97a9db5 100644 --- a/public/skill.md +++ b/public/skill.md @@ -71,6 +71,7 @@ decision: Index (short): `https://pegma.dev/llms.txt` Human stack pages: `https://pegma.dev/stack` Recipe index: `https://pegma.dev/examples` +Environment runbooks: `https://pegma.dev/runbooks` This skill (judgment only): `https://pegma.dev/skill.md` Optional MCP (same catalog facts): `https://pegma.dev/api/mcp` diff --git a/recipes/README.md b/recipes/README.md index 635291d..309d1c6 100644 --- a/recipes/README.md +++ b/recipes/README.md @@ -7,6 +7,7 @@ CI-tested composition sketches for agents. Product names and domains are | --- | --- | --- | | `cf-passkey-accounts` | Northshelf Branch — passkey + email-code accounts on a Cloudflare-shaped host | [`cf-passkey-accounts/`](./cf-passkey-accounts/) | | `storage-audit-mail-outbox` | Yard Loan — inventory mutation + audit + mail job in one transaction | [`storage-audit-mail-outbox/`](./storage-audit-mail-outbox/) | +| `support-queue-slice` | Bench Ticket — email-code support desk (environment runbooks) | [`bench-ticket/`](./bench-ticket/) | | `static-brochure-minimal` (scaffold) | Glass Wing — empty-ish CF composition root; optional health is host-owned | [`scaffold-cf-minimal/`](./scaffold-cf-minimal/) | ## Rules @@ -22,7 +23,8 @@ CI-tested composition sketches for agents. Product names and domains are ## Production vs test adapters Fixtures that use Storage Core (`cf-passkey-accounts`, -`storage-audit-mail-outbox`) **require** an injected `Store`. Tests pass +`storage-audit-mail-outbox`, `support-queue-slice` / Bench Ticket) +**require** an injected `Store`. Tests pass `createMemoryStore()` explicitly so CI stays fast and free of cloud credentials; production hosts inject a durable adapter (for example Cloudflare D1 for `cf-passkey-accounts`). Memory is never a silent default diff --git a/recipes/bench-ticket/Dockerfile b/recipes/bench-ticket/Dockerfile new file mode 100644 index 0000000..66611ea --- /dev/null +++ b/recipes/bench-ticket/Dockerfile @@ -0,0 +1,10 @@ +# syntax=docker/dockerfile:1 +FROM node:22-bookworm-slim +WORKDIR /app +RUN corepack enable +COPY package.json pnpm-lock.yaml ./ +COPY . . +RUN pnpm install --frozen-lockfile +ENV NODE_ENV=production +EXPOSE 8787 +CMD ["pnpm", "exec", "tsx", "recipes/bench-ticket/host.ts"] diff --git a/recipes/bench-ticket/README.md b/recipes/bench-ticket/README.md new file mode 100644 index 0000000..fdf5ef5 --- /dev/null +++ b/recipes/bench-ticket/README.md @@ -0,0 +1,16 @@ +# Bench Ticket (support-queue-slice) + +Synthetic makerspace helpdesk used by the public environment runbooks. + +- Composition: [`composition.ts`](./composition.ts) (CI-tested) +- HTTP host: [`handler.ts`](./handler.ts) + Node [`host.ts`](./host.ts) +- Cloudflare Worker: [`cloudflare/`](./cloudflare/) +- Local Docker: [`docker-compose.yml`](./docker-compose.yml) + +Follow the runbooks on the site, not this file: + +- https://pegma.dev/runbooks +- https://pegma.dev/runbooks/local-docker +- https://pegma.dev/runbooks/cloudflare +- https://pegma.dev/runbooks/azure +- https://pegma.dev/runbooks/aws diff --git a/recipes/bench-ticket/cloudflare/worker.ts b/recipes/bench-ticket/cloudflare/worker.ts new file mode 100644 index 0000000..5dac82e --- /dev/null +++ b/recipes/bench-ticket/cloudflare/worker.ts @@ -0,0 +1,56 @@ +/** + * Cloudflare Worker host for Bench Ticket. + * Record store: `@pegma/storage-cloudflare-d1`. Mail: console catcher. + * + * Requires the storage-core D1 adapter (already published). Blobs: create an + * R2 bucket in the runbook even though this demo does not store attachments. + */ +import { + createCloudflareD1Store, + type CloudflareD1Database, +} from '@pegma/storage-cloudflare-d1'; +import { + createBenchTicketComposition, + createBenchTicketMailRenderer, +} from '../composition'; +import { handleBenchTicketRequest } from '../handler'; +import { + createCatcherReconciliation, + createConsoleMailProvider, +} from '../mail-catcher'; + +export interface BenchTicketEnv { + readonly BENCH_TICKET_DB: CloudflareD1Database; + readonly BENCH_TICKET_EMAIL_CODE_SECRET_BASE64: string; + readonly BENCH_TICKET_ORIGIN: string; +} + +let cached: ReturnType | undefined; +let cachedOrigin: string | undefined; + +function compositionFor(env: BenchTicketEnv) { + if (cached && cachedOrigin === env.BENCH_TICKET_ORIGIN) { + return cached; + } + cachedOrigin = env.BENCH_TICKET_ORIGIN; + cached = createBenchTicketComposition({ + store: createCloudflareD1Store({ + database: env.BENCH_TICKET_DB, + createSchemaIfMissing: true, + }), + origin: env.BENCH_TICKET_ORIGIN, + emailCodeSecretBase64: env.BENCH_TICKET_EMAIL_CODE_SECRET_BASE64, + mailDelivery: { + provider: createConsoleMailProvider(), + reconciliation: createCatcherReconciliation(), + renderer: createBenchTicketMailRenderer(), + }, + }); + return cached; +} + +export default { + async fetch(request: Request, env: BenchTicketEnv): Promise { + return handleBenchTicketRequest(request, compositionFor(env)); + }, +}; diff --git a/recipes/bench-ticket/cloudflare/wrangler.jsonc b/recipes/bench-ticket/cloudflare/wrangler.jsonc new file mode 100644 index 0000000..973a246 --- /dev/null +++ b/recipes/bench-ticket/cloudflare/wrangler.jsonc @@ -0,0 +1,22 @@ +{ + "name": "bench-ticket", + "main": "worker.ts", + "compatibility_date": "2026-07-28", + "workers_dev": true, + "d1_databases": [ + { + "binding": "BENCH_TICKET_DB", + "database_name": "bench-ticket", + "database_id": "REPLACE_AFTER_D1_CREATE" + } + ], + "r2_buckets": [ + { + "binding": "BENCH_TICKET_BLOBS", + "bucket_name": "bench-ticket-blobs" + } + ], + "vars": { + "BENCH_TICKET_ORIGIN": "https://bench-ticket.REPLACE.workers.dev" + } +} diff --git a/recipes/bench-ticket/composition.test.ts b/recipes/bench-ticket/composition.test.ts new file mode 100644 index 0000000..6fd01d5 --- /dev/null +++ b/recipes/bench-ticket/composition.test.ts @@ -0,0 +1,139 @@ +import { fixedClock, type PrincipalId } from '@pegma/spine'; +import { createMemoryStore } from '@pegma/storage-core'; +import { describe, expect, it } from 'vitest'; +import { + BENCH_TICKET, + createBenchTicketComposition, + createBenchTicketMailRenderer, + openBenchTicketSession, + type BenchTicketMailDelivery, +} from './composition'; + +/** Deterministic 32-byte secret, base64 — tests only. */ +const TEST_SECRET = btoa(String.fromCharCode(...new Uint8Array(32).fill(11))); + +function recordingMailDelivery(): BenchTicketMailDelivery & { + readonly sent: { readonly recipient: string; readonly subject: string; readonly text: string }[]; +} { + const sent: { recipient: string; subject: string; text: string }[] = []; + return { + sent, + provider: { + async send(request) { + sent.push({ + recipient: request.mail.recipient, + subject: request.mail.subject, + text: request.mail.text, + }); + return { providerMessageRef: `stub-${sent.length}` }; + }, + }, + reconciliation: { + async reconcile() { + return { status: 'delivered' as const }; + }, + }, + renderer: createBenchTicketMailRenderer(), + }; +} + +function makeComposition(mail = recordingMailDelivery()) { + return { + composition: createBenchTicketComposition({ + store: createMemoryStore(), + origin: BENCH_TICKET.defaultOrigin, + emailCodeSecretBase64: TEST_SECRET, + mailDelivery: mail, + clock: fixedClock('2026-09-11T12:00:00.000Z'), + }), + mail, + }; +} + +describe('support-queue-slice (Bench Ticket)', () => { + it('wires Identity, Sessions, Support Desk, Health, and a mail worker', async () => { + const { composition } = makeComposition(); + const health = await composition.health(); + expect(health.status).toBe(200); + expect(health.body.ok).toBe(true); + expect(health.body.service).toBe(BENCH_TICKET.service); + expect(health.body.checks.process?.status).toBe('ok'); + expect(health.body.checks.storage?.status).toBe('ok'); + + const user = await composition.identity.provisionVerifiedUser({ + principalId: 'prn_bench_member' as PrincipalId, + email: 'member@bench.example', + }); + const claims = await composition.identity.claimsFor(user.principalId); + expect(claims).toMatchObject({ + issuer: BENCH_TICKET.defaultOrigin, + subject: user.principalId, + emailVerified: true, + }); + + const sessionId = 'b'.repeat(43); + await openBenchTicketSession(composition, sessionId, claims); + const session = await composition.sessions.get(sessionId); + expect(session?.principalId).toBe(user.principalId); + }); + + it('starts email-code account creation and drains the code through the mail worker', async () => { + const { composition, mail } = makeComposition(); + const started = await composition.identity.beginAccountCreation( + 'new.member@bench.example', + '203.0.113.20', + ); + expect(typeof started.codeHandle).toBe('string'); + expect(started.codeHandle.length).toBeGreaterThan(8); + + const page = await composition.mailWorker.runSendPage({ limit: 20 }); + expect(page.examined).toBeGreaterThan(0); + expect(mail.sent.length).toBeGreaterThan(0); + expect(mail.sent[0]?.subject).toMatch(/Your Bench Ticket code is /); + expect(mail.sent[0]?.text).toMatch(/Your Bench Ticket code is /); + }); + + it('creates, lists, and replies to a customer ticket for a signed-in principal', async () => { + const { composition } = makeComposition(); + const user = await composition.identity.provisionVerifiedUser({ + principalId: 'prn_bench_filer' as PrincipalId, + email: 'filer@bench.example', + }); + const access = composition.customerAccess(user.principalId); + const ticketId = 'ticket-bench-1'; + const created = await composition.support.createCustomerTicket(access, { + commandId: 'cmd-create-1', + correlationId: 'corr-create-1', + ticketId, + messageId: 'msg-1', + subject: 'Laser cutter jammed', + body: 'The bed will not home.', + category: 'tools', + }); + expect(created.ticket.id).toBe(ticketId); + expect(created.ticket.subject).toMatch(/Laser cutter/); + + const listed = await composition.support.listCustomerTickets(access); + expect(listed.some((row) => row.id === ticketId)).toBe(true); + + const replied = await composition.support.replyToCustomerTicket(access, { + commandId: 'cmd-reply-1', + correlationId: 'corr-reply-1', + ticketId, + messageId: 'msg-2', + body: 'I cleared the gantry. Still stuck.', + }); + expect(replied.messages.length).toBeGreaterThan(1); + }); + + it('refuses a missing or invalid email-code secret', () => { + expect(() => + createBenchTicketComposition({ + store: createMemoryStore(), + origin: BENCH_TICKET.defaultOrigin, + emailCodeSecretBase64: 'short', + mailDelivery: recordingMailDelivery(), + }), + ).toThrow(/missing or invalid/); + }); +}); diff --git a/recipes/bench-ticket/composition.ts b/recipes/bench-ticket/composition.ts new file mode 100644 index 0000000..cb68cad --- /dev/null +++ b/recipes/bench-ticket/composition.ts @@ -0,0 +1,333 @@ +/** + * Recipe: support-queue-slice (Bench Ticket) + * + * Synthetic host: a fictional makerspace helpdesk. Teaches a small + * support-desk site with first-party Identity **email-code** login (not + * Auth0, Entra, or passkeys-required), Sessions, Mail to a catcher, + * Support Desk create/list/reply, and Health. Tests inject + * `createMemoryStore()`. Cloud runbooks inject D1, Azure Tables, or the + * forthcoming `@pegma/storage-dynamodb` adapter — same composition shape. + * + * Not pegma.dev’s production feedback API. Do not copy commercial route + * maps, cookie names, or CSRF tokens from any live product. + */ + +import type { AccessContext } from '@pegma/authorization-core'; +import { + createProcessCheck, + createStorePingCheck, + healthProbeCollection, + runHealthChecks, + toHealthResponse, + type HealthHttpResponse, +} from '@pegma/health'; +import { + createHmacEmailCodeProtector, + createIdentity, + type Identity, + type IdentityMailRenderer, + type MailProvider, + type MailReconciliationPort, + type MailWorker, + type VerifiedIdentityClaims, +} from '@pegma/identity'; +import { + createDurableLimiter, + createMemoryLimiter, + defineRateLimitPolicy, + type DurableRateLimiter, +} from '@pegma/rate-limit'; +import { createSessionStore, type SessionStore } from '@pegma/sessions'; +import { + systemClock, + type Clock, + type Logger, + type PrincipalId, +} from '@pegma/spine'; +import type { Store } from '@pegma/storage-core'; +import { + createSupportDeskApplication, + supportPermissions, + type SupportDeskApplication, +} from '@pegma/support-desk-application'; + +/** Fictional makerspace helpdesk. */ +export const BENCH_TICKET = { + service: 'bench-ticket', + policyVersion: 'bench-ticket-policy-1', + defaultOrigin: 'http://localhost:8787', +} as const; + +export const BENCH_TICKET_CATEGORIES = Object.freeze(['general', 'tools', 'access'] as const); + +/** Host-owned mail delivery ports — required for email-code account flows. */ +export interface BenchTicketMailDelivery { + readonly provider: MailProvider; + readonly reconciliation: MailReconciliationPort; + readonly renderer: IdentityMailRenderer; + readonly workerId?: string; +} + +export interface BenchTicketCompositionOptions { + /** + * Required injected store. Local Docker tests and compose use + * `createMemoryStore()`. Production-shaped hosts pass a durable adapter + * (D1, Azure Tables, or `@pegma/storage-dynamodb` once published). + * Memory is never the silent default. + */ + readonly store: Store; + /** + * Public origin of this host (`http://localhost:8787` locally). Used as + * Identity issuer and the sole relying-party origin. HTTP is allowed only + * for local development hostnames. + */ + readonly origin: string; + /** + * Base64-encoded email-code HMAC secret (≥32 raw bytes). + * Host-managed; never generated at process start in production. + */ + readonly emailCodeSecretBase64: string; + readonly mailDelivery: BenchTicketMailDelivery; + readonly clock?: Clock; + readonly logger?: Logger; +} + +export interface BenchTicketComposition { + readonly store: Store; + readonly origin: string; + readonly identity: Identity; + readonly sessions: SessionStore; + readonly support: SupportDeskApplication; + readonly mailWorker: MailWorker; + readonly emailCodeRequestLimiter: DurableRateLimiter; + readonly emailCodeVerificationLimiter: DurableRateLimiter; + readonly clock: Clock; + readonly health: () => Promise; + readonly customerAccess: (principalId: PrincipalId) => AccessContext; +} + +function decodeEmailCodeSecret(value: string): Uint8Array { + if ( + value.length < 44 || + value.length > 172 || + !/^[A-Za-z0-9+/]+={0,2}$/u.test(value) + ) { + throw new Error( + 'Bench Ticket email-code secret is missing or invalid (expected base64 of 32–128 raw bytes).', + ); + } + let binary: string; + try { + binary = atob(value); + } catch { + throw new Error( + 'Bench Ticket email-code secret is missing or invalid (expected base64 of 32–128 raw bytes).', + ); + } + if (binary.length < 32 || binary.length > 128) { + throw new Error( + 'Bench Ticket email-code secret is missing or invalid (expected base64 of 32–128 raw bytes).', + ); + } + return Uint8Array.from(binary, (c) => c.charCodeAt(0)); +} + +function originParts(origin: string): { readonly issuer: string; readonly rpID: string } { + let url: URL; + try { + url = new URL(origin); + } catch (cause) { + throw new Error('Bench Ticket origin is invalid.', { cause }); + } + if (url.origin !== origin) { + throw new Error('Bench Ticket origin must be a full origin with no path, query, or fragment.'); + } + return { issuer: url.origin, rpID: url.hostname.toLowerCase() }; +} + +const CUSTOMER_PERMISSIONS = Object.freeze([ + supportPermissions.create, + supportPermissions.readOwn, + supportPermissions.replyOwn, +]); + +/** + * Authenticated-customer AccessContext. This demo grants ticket create / + * read-own / reply-own to every signed-in principal (host defaults, not a + * paid entitlement and not an external IdP). + */ +export function benchTicketCustomerAccess( + principalId: PrincipalId, +): AccessContext { + return { + principalId, + policyVersion: BENCH_TICKET.policyVersion, + roles: [], + entitlements: [], + permissions: [...CUSTOMER_PERMISSIONS], + }; +} + +/** + * Identity mail renderer. The one-time code is in the subject and body so + * Mailpit and console catchers are greppable (`Your Bench Ticket code is …`). + */ +export function createBenchTicketMailRenderer(): IdentityMailRenderer { + return { + async render(content) { + if (content.expired) { + throw new Error('code expired'); + } + if (content.purpose === 'email_changed') { + return { + subject: 'Bench Ticket email changed', + text: `Changed to ${content.newEmail ?? ''}`, + }; + } + const code = content.code ?? 'unknown'; + return { + subject: `Your Bench Ticket code is ${code}`, + text: `Your Bench Ticket code is ${code}\n\nIt expires at ${content.expiresAt ?? 'unknown'}.`, + }; + }, + }; +} + +/** + * Explicit composition root. Wire once. Hosts still own HTTP, cookies, + * the mail catcher, and the Store adapter. + */ +export function createBenchTicketComposition( + options: BenchTicketCompositionOptions, +): BenchTicketComposition { + const store = options.store; + const clock = options.clock ?? systemClock; + const { issuer, rpID } = originParts(options.origin); + const emailCodeProtector = createHmacEmailCodeProtector( + decodeEmailCodeSecret(options.emailCodeSecretBase64), + ); + + // Passkey limiters exist because Identity requires them. This demo does not + // require passkeys; email-code is the login path. + const registrationLimiter = createMemoryLimiter( + defineRateLimitPolicy({ + name: 'bench-ticket-passkey-registration', + limit: 10, + windowMs: 5 * 60_000, + }), + { clock }, + ); + const authenticationLimiter = createMemoryLimiter( + defineRateLimitPolicy({ + name: 'bench-ticket-passkey-authentication', + limit: 30, + windowMs: 5 * 60_000, + }), + { clock }, + ); + const emailCodeRequestLimiter = createDurableLimiter( + defineRateLimitPolicy({ + name: 'bench-ticket-email-code-request', + limit: 10, + windowMs: 10 * 60_000, + }), + store, + { clock }, + ); + const emailCodeVerificationLimiter = createDurableLimiter( + defineRateLimitPolicy({ + name: 'bench-ticket-email-code-verification', + limit: 20, + windowMs: 10 * 60_000, + }), + store, + { clock }, + ); + + const identity = createIdentity({ + store, + issuer, + rpName: 'Bench Ticket', + rpID, + origins: [options.origin], + registrationLimiter, + authenticationLimiter, + emailCodeProtector, + emailCodeRequestLimiter, + emailCodeVerificationLimiter, + clock, + }); + + const sessions = createSessionStore(store, { + clock, + ...(options.logger === undefined ? {} : { logger: options.logger }), + }); + + const support = createSupportDeskApplication({ + store, + clock, + ...(options.logger === undefined ? {} : { logger: options.logger }), + allowedCategories: BENCH_TICKET_CATEGORIES, + }); + + const mailWorker = identity.createMailWorker({ + workerId: options.mailDelivery.workerId ?? 'bench-ticket-identity-mail', + provider: options.mailDelivery.provider, + reconciliation: options.mailDelivery.reconciliation, + renderer: options.mailDelivery.renderer, + leaseMilliseconds: 30_000, + acceptedCallbackMilliseconds: 5 * 60_000, + }); + + const health = async (): Promise => { + const result = await runHealthChecks({ + service: BENCH_TICKET.service, + clock, + ...(options.logger === undefined ? {} : { logger: options.logger }), + checks: [ + createProcessCheck('process'), + createStorePingCheck({ + store, + collection: healthProbeCollection, + name: 'storage', + clock, + }), + ], + }); + return toHealthResponse(result); + }; + + return Object.freeze({ + store, + origin: options.origin, + identity, + sessions, + support, + mailWorker, + emailCodeRequestLimiter, + emailCodeVerificationLimiter, + clock, + health, + customerAccess: benchTicketCustomerAccess, + }); +} + +/** + * After Identity verifies a principal, open a server-side session. + * Session `data` is opaque to `@pegma/sessions` — never put IdP tokens here. + */ +export async function openBenchTicketSession( + composition: BenchTicketComposition, + sessionId: string, + claims: VerifiedIdentityClaims, +): Promise { + const principalId = claims.subject as PrincipalId; + await composition.sessions.create(sessionId, { + principalId, + data: JSON.stringify({ + version: 1, + issuer: claims.issuer, + subject: claims.subject, + }), + }); +} diff --git a/recipes/bench-ticket/docker-compose.yml b/recipes/bench-ticket/docker-compose.yml new file mode 100644 index 0000000..4bbffce --- /dev/null +++ b/recipes/bench-ticket/docker-compose.yml @@ -0,0 +1,36 @@ +name: bench-ticket +services: + app: + build: + context: ../.. + dockerfile: recipes/bench-ticket/Dockerfile + ports: + - "8787:8787" + environment: + PORT: "8787" + BENCH_TICKET_ORIGIN: http://localhost:8787 + BENCH_TICKET_MAIL_CATCHER: mailpit + MAILPIT_SMTP_HOST: mailpit + MAILPIT_SMTP_PORT: "1025" + BENCH_TICKET_EMAIL_FROM: bench-ticket@localhost + # 32 bytes of 0x0b, base64. Local demo only — never reuse in a cloud deploy. + BENCH_TICKET_EMAIL_CODE_SECRET_BASE64: CwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCws= + depends_on: + mailpit: + condition: service_started + healthcheck: + test: + [ + "CMD", + "node", + "-e", + "fetch('http://127.0.0.1:8787/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))", + ] + interval: 5s + timeout: 5s + retries: 12 + mailpit: + image: axllent/mailpit:v1.27 + ports: + - "8025:8025" + - "1025:1025" diff --git a/recipes/bench-ticket/handler.test.ts b/recipes/bench-ticket/handler.test.ts new file mode 100644 index 0000000..0f34e3d --- /dev/null +++ b/recipes/bench-ticket/handler.test.ts @@ -0,0 +1,143 @@ +import { fixedClock } from '@pegma/spine'; +import { createMemoryStore } from '@pegma/storage-core'; +import { describe, expect, it } from 'vitest'; +import { + BENCH_TICKET, + createBenchTicketComposition, + createBenchTicketMailRenderer, + type BenchTicketMailDelivery, +} from './composition'; +import { handleBenchTicketRequest, SESSION_COOKIE } from './handler'; + +const TEST_SECRET = btoa(String.fromCharCode(...new Uint8Array(32).fill(11))); +const ORIGIN = BENCH_TICKET.defaultOrigin; + +function recordingMail(): BenchTicketMailDelivery & { + readonly sent: { readonly subject: string; readonly text: string }[]; +} { + const sent: { subject: string; text: string }[] = []; + return { + sent, + provider: { + async send(request) { + sent.push({ subject: request.mail.subject, text: request.mail.text }); + return { providerMessageRef: `stub-${sent.length}` }; + }, + }, + reconciliation: { + async reconcile() { + return { status: 'delivered' as const }; + }, + }, + renderer: createBenchTicketMailRenderer(), + }; +} + +function cookieFrom(response: Response): string { + const header = response.headers.get('set-cookie') ?? ''; + const match = new RegExp(`${SESSION_COOKIE}=([^;]+)`).exec(header); + if (!match?.[1]) throw new Error('missing session cookie'); + return `${SESSION_COOKIE}=${match[1]}`; +} + +describe('Bench Ticket HTTP host', () => { + it('serves health, email-code sign-up, and a ticket round-trip', async () => { + const mail = recordingMail(); + const composition = createBenchTicketComposition({ + store: createMemoryStore(), + origin: ORIGIN, + emailCodeSecretBase64: TEST_SECRET, + mailDelivery: mail, + clock: fixedClock('2026-09-11T12:00:00.000Z'), + }); + + const health = await handleBenchTicketRequest( + new Request(`${ORIGIN}/health`), + composition, + ); + expect(health.status).toBe(200); + const healthBody = (await health.json()) as { ok: boolean; service: string }; + expect(healthBody.ok).toBe(true); + expect(healthBody.service).toBe(BENCH_TICKET.service); + + const home = await handleBenchTicketRequest( + new Request(`${ORIGIN}/`), + composition, + ); + expect(home.status).toBe(200); + expect(await home.text()).toMatch(/Bench Ticket/); + + const begin = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/auth/begin`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'member@bench.example', flow: 'create' }), + }), + composition, + ); + expect(begin.status).toBe(200); + const started = (await begin.json()) as { codeHandle: string }; + expect(mail.sent.length).toBeGreaterThan(0); + const codeMatch = /Your Bench Ticket code is (\d{8})/.exec(mail.sent[0]?.subject ?? ''); + expect(codeMatch?.[1]).toMatch(/^\d{8}$/); + + const finish = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/auth/finish`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + flow: 'create', + codeHandle: started.codeHandle, + code: codeMatch?.[1], + }), + }), + composition, + ); + expect(finish.status).toBe(200); + const cookie = cookieFrom(finish); + + const filed = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/tickets`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + cookie, + }, + body: JSON.stringify({ + subject: 'Laser cutter jammed', + body: 'The bed will not home.', + category: 'tools', + }), + }), + composition, + ); + expect(filed.status).toBe(201); + const created = (await filed.json()) as { + ticket: { id: string; subject: string }; + }; + expect(created.ticket.subject).toMatch(/Laser cutter/); + + const listed = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/tickets`, { headers: { cookie } }), + composition, + ); + expect(listed.status).toBe(200); + const queue = (await listed.json()) as { tickets: { id: string }[] }; + expect(queue.tickets.some((row) => row.id === created.ticket.id)).toBe(true); + + const replied = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/tickets/${created.ticket.id}/replies`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + cookie, + }, + body: JSON.stringify({ body: 'Cleared the gantry. Still stuck.' }), + }), + composition, + ); + expect(replied.status).toBe(200); + const view = (await replied.json()) as { messages: unknown[] }; + expect(view.messages.length).toBeGreaterThan(1); + }); +}); diff --git a/recipes/bench-ticket/handler.ts b/recipes/bench-ticket/handler.ts new file mode 100644 index 0000000..836fc17 --- /dev/null +++ b/recipes/bench-ticket/handler.ts @@ -0,0 +1,404 @@ +/** + * Fetch-API HTTP host for Bench Ticket. Used by the Node Docker process and + * the Cloudflare Worker. Not pegma.dev’s production routes. + */ +import { IdentityError } from '@pegma/identity'; +import { + SupportDeskAuthorizationError, + SupportDeskConflictError, + SupportDeskLimitError, + SupportDeskNotFoundError, +} from '@pegma/support-desk-application'; +import type { PrincipalId } from '@pegma/spine'; +import { + openBenchTicketSession, + type BenchTicketComposition, +} from './composition'; + +export const SESSION_COOKIE = 'bench_ticket_session'; + +const PAGE_HTML = ` + + + + + Bench Ticket + + + +
+

Bench Ticket

+

Makerspace helpdesk demo — email-code login, then file and reply to a ticket. Codes land in Mailpit (local) or process logs (cloud).

+

+
+ + + + + +
+ +
+ + + +`; + +function json(status: number, body: unknown, headers?: HeadersInit): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json; charset=utf-8', ...headers }, + }); +} + +function parseCookies(header: string | null): Record { + const out: Record = {}; + if (!header) return out; + for (const part of header.split(';')) { + const idx = part.indexOf('='); + if (idx < 0) continue; + const key = part.slice(0, idx).trim(); + const value = part.slice(idx + 1).trim(); + if (key.length > 0) out[key] = decodeURIComponent(value); + } + return out; +} + +function sessionCookie(sessionId: string, origin: string): string { + const secure = origin.startsWith('https:'); + return `${SESSION_COOKIE}=${encodeURIComponent(sessionId)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800${secure ? '; Secure' : ''}`; +} + +function clearSessionCookie(origin: string): string { + const secure = origin.startsWith('https:'); + return `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secure ? '; Secure' : ''}`; +} + +function mintId(): string { + return crypto.randomUUID(); +} + +function mintSessionId(): string { + const bytes = new Uint8Array(32); + crypto.getRandomValues(bytes); + let binary = ''; + for (const b of bytes) binary += String.fromCharCode(b); + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); +} + +function mapError(error: unknown): Response { + if (error instanceof IdentityError) { + const status = + error.code === 'rate_limited' + ? 429 + : error.code === 'verification_failed' || error.code === 'invalid_input' + ? 400 + : error.code === 'not_found' + ? 404 + : error.code === 'conflict' + ? 409 + : 400; + return json(status, { error: error.code }); + } + if (error instanceof SupportDeskAuthorizationError) { + return json(403, { error: 'forbidden' }); + } + if (error instanceof SupportDeskNotFoundError) { + return json(404, { error: 'not_found' }); + } + if (error instanceof SupportDeskConflictError) { + return json(409, { error: 'conflict' }); + } + if (error instanceof SupportDeskLimitError) { + return json(413, { error: 'limit_exceeded' }); + } + return json(500, { error: 'internal_error' }); +} + +async function readJson(request: Request): Promise> { + const text = await request.text(); + if (text.trim().length === 0) return {}; + const parsed: unknown = JSON.parse(text); + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + throw new IdentityError('invalid_input', 'JSON object required.'); + } + return parsed as Record; +} + +async function currentPrincipal( + request: Request, + composition: BenchTicketComposition, +): Promise { + const cookies = parseCookies(request.headers.get('cookie')); + const sessionId = cookies[SESSION_COOKIE]; + if (!sessionId) return null; + const session = await composition.sessions.get(sessionId); + return session?.principalId ?? null; +} + +async function drainMail(composition: BenchTicketComposition): Promise { + await composition.mailWorker.runSendPage({ limit: 20 }); +} + +export async function handleBenchTicketRequest( + request: Request, + composition: BenchTicketComposition, +): Promise { + const url = new URL(request.url); + const path = url.pathname; + const method = request.method.toUpperCase(); + + try { + if (method === 'GET' && (path === '/' || path === '/index.html')) { + return new Response(PAGE_HTML, { + headers: { 'content-type': 'text/html; charset=utf-8' }, + }); + } + if (method === 'GET' && path === '/health') { + const health = await composition.health(); + return json(health.status, health.body); + } + + if (method === 'POST' && path === '/api/auth/begin') { + const body = await readJson(request); + const email = String(body.email ?? ''); + const flow = body.flow === 'signin' ? 'signin' : 'create'; + const rateLimitKey = request.headers.get('cf-connecting-ip') ?? 'local'; + const started = + flow === 'signin' + ? await composition.identity.beginEmailSignIn(email, rateLimitKey) + : await composition.identity.beginAccountCreation(email, rateLimitKey); + await drainMail(composition); + return json(200, { codeHandle: started.codeHandle, expiresAt: started.expiresAt }); + } + + if (method === 'POST' && path === '/api/auth/finish') { + const body = await readJson(request); + const flow = body.flow === 'signin' ? 'signin' : 'create'; + const input = { + codeHandle: String(body.codeHandle ?? ''), + code: String(body.code ?? ''), + rateLimitKey: request.headers.get('cf-connecting-ip') ?? 'local', + }; + const claims = + flow === 'signin' + ? await composition.identity.finishEmailSignIn(input) + : await composition.identity.finishAccountCreation(input); + const sessionId = mintSessionId(); + await openBenchTicketSession(composition, sessionId, claims); + return json( + 200, + { principalId: claims.subject }, + { 'set-cookie': sessionCookie(sessionId, composition.origin) }, + ); + } + + if (method === 'POST' && path === '/api/auth/signout') { + const cookies = parseCookies(request.headers.get('cookie')); + const sessionId = cookies[SESSION_COOKIE]; + if (sessionId) await composition.sessions.destroy(sessionId); + return json(200, { ok: true }, { 'set-cookie': clearSessionCookie(composition.origin) }); + } + + if (method === 'GET' && path === '/api/me') { + const principalId = await currentPrincipal(request, composition); + if (!principalId) return json(401, { error: 'unauthenticated' }); + const user = await composition.identity.getUser(principalId); + return json(200, { principalId, email: user?.email ?? null }); + } + + if (method === 'GET' && path === '/api/tickets') { + const principalId = await currentPrincipal(request, composition); + if (!principalId) return json(401, { error: 'unauthenticated' }); + const tickets = await composition.support.listCustomerTickets( + composition.customerAccess(principalId), + ); + return json(200, { tickets }); + } + + if (method === 'POST' && path === '/api/tickets') { + const principalId = await currentPrincipal(request, composition); + if (!principalId) return json(401, { error: 'unauthenticated' }); + const body = await readJson(request); + const created = await composition.support.createCustomerTicket( + composition.customerAccess(principalId), + { + commandId: mintId(), + correlationId: mintId(), + ticketId: mintId(), + messageId: mintId(), + subject: String(body.subject ?? ''), + body: String(body.body ?? ''), + ...(typeof body.category === 'string' ? { category: body.category } : {}), + }, + ); + return json(201, created); + } + + const ticketMatch = /^\/api\/tickets\/([^/]+)$/.exec(path); + if (method === 'GET' && ticketMatch) { + const principalId = await currentPrincipal(request, composition); + if (!principalId) return json(401, { error: 'unauthenticated' }); + const view = await composition.support.readCustomerTicket( + composition.customerAccess(principalId), + decodeURIComponent(ticketMatch[1] ?? ''), + ); + return json(200, view); + } + + const replyMatch = /^\/api\/tickets\/([^/]+)\/replies$/.exec(path); + if (method === 'POST' && replyMatch) { + const principalId = await currentPrincipal(request, composition); + if (!principalId) return json(401, { error: 'unauthenticated' }); + const body = await readJson(request); + const replied = await composition.support.replyToCustomerTicket( + composition.customerAccess(principalId), + { + commandId: mintId(), + correlationId: mintId(), + ticketId: decodeURIComponent(replyMatch[1] ?? ''), + messageId: mintId(), + body: String(body.body ?? ''), + }, + ); + return json(200, replied); + } + + return json(404, { error: 'not_found' }); + } catch (error) { + if (error instanceof SyntaxError) { + return json(400, { error: 'invalid_json' }); + } + return mapError(error); + } +} diff --git a/recipes/bench-ticket/host.ts b/recipes/bench-ticket/host.ts new file mode 100644 index 0000000..bdaf88e --- /dev/null +++ b/recipes/bench-ticket/host.ts @@ -0,0 +1,135 @@ +/** + * Node entrypoint for the Bench Ticket demo (Local Docker / Azure Container + * Apps / AWS App Runner). Cloudflare uses `cloudflare/worker.ts` instead. + * + * Store: in-memory (default). Cloud runbooks replace `createMemoryStore()` + * with the matching adapter factory — same `createBenchTicketComposition`. + */ +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import { pathToFileURL } from 'node:url'; +import { createMemoryStore } from '@pegma/storage-core'; +import { + BENCH_TICKET, + createBenchTicketComposition, + createBenchTicketMailRenderer, +} from './composition'; +import { handleBenchTicketRequest } from './handler'; +import { + createCatcherReconciliation, + createConsoleMailProvider, +} from './mail-catcher'; +import { createMailpitSmtpProvider } from './mail-smtp'; + +function requiredEnv(name: string): string { + const value = process.env[name]; + if (typeof value !== 'string' || value.length === 0) { + throw new Error(`${name} is required`); + } + return value; +} + +function mailDelivery() { + const renderer = createBenchTicketMailRenderer(); + const reconciliation = createCatcherReconciliation(); + const catcher = process.env.BENCH_TICKET_MAIL_CATCHER ?? 'mailpit'; + if (catcher === 'console') { + return { + provider: createConsoleMailProvider(), + reconciliation, + renderer, + }; + } + return { + provider: createMailpitSmtpProvider({ + host: process.env.MAILPIT_SMTP_HOST ?? '127.0.0.1', + port: Number.parseInt(process.env.MAILPIT_SMTP_PORT ?? '1025', 10), + from: process.env.BENCH_TICKET_EMAIL_FROM ?? 'bench-ticket@localhost', + }), + reconciliation, + renderer, + }; +} + +export function createBenchTicketNodeHandler() { + const origin = process.env.BENCH_TICKET_ORIGIN ?? BENCH_TICKET.defaultOrigin; + const composition = createBenchTicketComposition({ + store: createMemoryStore(), + origin, + emailCodeSecretBase64: requiredEnv('BENCH_TICKET_EMAIL_CODE_SECRET_BASE64'), + mailDelivery: mailDelivery(), + }); + + return { + composition, + async handle(request: Request): Promise { + return handleBenchTicketRequest(request, composition); + }, + }; +} + +async function requestFromNode( + req: IncomingMessage, + origin: string, +): Promise { + const url = new URL(req.url ?? '/', origin); + const headers = new Headers(); + for (const [name, value] of Object.entries(req.headers)) { + if (value === undefined) continue; + if (Array.isArray(value)) headers.set(name, value.join(', ')); + else headers.set(name, value); + } + const method = req.method ?? 'GET'; + if (method === 'GET' || method === 'HEAD') { + return new Request(url, { method, headers }); + } + const chunks: Buffer[] = []; + for await (const chunk of req) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + const body = new Uint8Array(Buffer.concat(chunks)); + return new Request(url, { + method, + headers, + body, + duplex: 'half', + }); +} + +async function writeNodeResponse( + res: ServerResponse, + response: Response, +): Promise { + const headers: Record = {}; + response.headers.forEach((value, key) => { + headers[key] = value; + }); + res.writeHead(response.status, headers); + const body = Buffer.from(await response.arrayBuffer()); + res.end(body); +} + +function isMainModule(): boolean { + const entry = process.argv[1]; + if (typeof entry !== 'string' || entry.length === 0) return false; + return import.meta.url === pathToFileURL(entry).href; +} + +if (isMainModule()) { + const port = Number.parseInt(process.env.PORT ?? '8787', 10); + const origin = process.env.BENCH_TICKET_ORIGIN ?? BENCH_TICKET.defaultOrigin; + const runtime = createBenchTicketNodeHandler(); + const server = createServer((req, res) => { + void requestFromNode(req, origin) + .then((request) => runtime.handle(request)) + .then((response) => writeNodeResponse(res, response)) + .catch((error: unknown) => { + console.error(error); + res.writeHead(500, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'internal_error' })); + }); + }); + + server.listen(port, '0.0.0.0', () => { + console.log(`Bench Ticket listening on ${origin} (bound 0.0.0.0:${port})`); + }); +} diff --git a/recipes/bench-ticket/mail-catcher.ts b/recipes/bench-ticket/mail-catcher.ts new file mode 100644 index 0000000..faf0181 --- /dev/null +++ b/recipes/bench-ticket/mail-catcher.ts @@ -0,0 +1,33 @@ +/** + * Console / log mail catcher for cloud runbooks. Safe on Workers. + * Local Docker SMTP lives in `mail-smtp.ts` (Node `net`). + */ +import type { MailProvider, MailReconciliationPort } from '@pegma/mail'; + +export interface ConsoleMailOptions { + readonly log?: (line: string) => void; +} + +/** Logs subject + body. Cloud runbooks use this instead of a vendor. */ +export function createConsoleMailProvider( + options: ConsoleMailOptions = {}, +): MailProvider { + const log = options.log ?? ((line: string) => console.log(line)); + return { + async send(request) { + log( + `[bench-ticket mail] to=${request.mail.recipient} subject=${request.mail.subject}`, + ); + log(request.mail.text); + return { providerMessageRef: `console:${request.idempotencyKey}` }; + }, + }; +} + +export function createCatcherReconciliation(): MailReconciliationPort { + return { + async reconcile() { + return { status: 'delivered' }; + }, + }; +} diff --git a/recipes/bench-ticket/mail-smtp.ts b/recipes/bench-ticket/mail-smtp.ts new file mode 100644 index 0000000..fd142b0 --- /dev/null +++ b/recipes/bench-ticket/mail-smtp.ts @@ -0,0 +1,104 @@ +/** + * Mailpit SMTP catcher for Local Docker. Node-only (`node:net`). + */ +import { connect } from 'node:net'; +import type { MailProvider } from '@pegma/mail'; + +export interface MailpitSmtpOptions { + readonly host: string; + readonly port: number; + readonly from: string; +} + +function headerSafe(value: string): string { + return value.replace(/[\u0000-\u001F\u007F]/g, ' '); +} + +function smtpDialog( + host: string, + port: number, + lines: readonly string[], +): Promise { + return new Promise((resolve, reject) => { + const socket = connect({ host, port }); + let buffer = ''; + const pending = [...lines]; + const timer = setTimeout(() => { + socket.destroy(); + reject(new Error('Mailpit SMTP timed out')); + }, 8_000); + + function fail(error: unknown): void { + clearTimeout(timer); + socket.destroy(); + reject(error instanceof Error ? error : new Error(String(error))); + } + + socket.setEncoding('utf8'); + socket.on('error', fail); + socket.on('data', (chunk: string) => { + buffer += chunk; + while (buffer.includes('\n')) { + const idx = buffer.indexOf('\n'); + const line = buffer.slice(0, idx).replace(/\r$/, ''); + buffer = buffer.slice(idx + 1); + const code = Number.parseInt(line.slice(0, 3), 10); + if (!Number.isInteger(code) || line[3] === '-') { + continue; + } + if (code >= 400) { + fail(new Error(`Mailpit SMTP ${line}`)); + return; + } + if (pending.length === 0) { + clearTimeout(timer); + socket.end(); + resolve('mailpit'); + return; + } + const next = pending.shift(); + if (next === undefined) { + return; + } + socket.write(next.endsWith('\r\n') ? next : `${next}\r\n`); + } + }); + }); +} + +/** + * Sends Identity mail through Mailpit’s unauthenticated SMTP. Honors the + * provider idempotency key as a Message-ID local part. + */ +export function createMailpitSmtpProvider( + options: MailpitSmtpOptions, +): MailProvider { + return { + async send(request) { + const subject = headerSafe(request.mail.subject); + const from = headerSafe(options.from); + const to = headerSafe(request.mail.recipient); + const id = request.idempotencyKey.replace(/[^A-Za-z0-9._-]/g, ''); + const body = [ + `From: ${from}`, + `To: ${to}`, + `Subject: ${subject}`, + `Message-ID: <${id}@bench-ticket.local>`, + 'MIME-Version: 1.0', + 'Content-Type: text/plain; charset=utf-8', + '', + request.mail.text, + '', + ].join('\r\n'); + await smtpDialog(options.host, options.port, [ + 'EHLO bench-ticket', + `MAIL FROM:<${from}>`, + `RCPT TO:<${to}>`, + 'DATA', + `${body}\r\n.`, + 'QUIT', + ]); + return { providerMessageRef: `mailpit:${id}` }; + }, + }; +} diff --git a/src/data/catalog-enrichment.ts b/src/data/catalog-enrichment.ts index 3f38079..8938774 100644 --- a/src/data/catalog-enrichment.ts +++ b/src/data/catalog-enrichment.ts @@ -52,6 +52,13 @@ export const COMPONENT_ENRICHMENT: Readonly> host: 'cloudflare', when: 'Cloudflare Workers/Pages with D1', }, + { + id: 'dynamodb', + packageName: '@pegma/storage-dynamodb', + host: 'other', + when: + 'AWS-hosted apps using DynamoDB. Requires pegma-dev/storage-core#7 to be merged; factory is createDynamoDbStore. Not yet on npm.', + }, ], hostMustProvide: [ 'Chosen adapter binding (D1 database, Azure connection, or memory for tests)', diff --git a/src/data/compile-catalog.test.ts b/src/data/compile-catalog.test.ts index d40d40e..b9ca31e 100644 --- a/src/data/compile-catalog.test.ts +++ b/src/data/compile-catalog.test.ts @@ -138,6 +138,12 @@ describe('compileCompositionCatalog', () => { expect(outbox.fixture.citation).toContain( 'recipes/storage-audit-mail-outbox', ); + const bench = catalog.recipes.find((r) => r.id === 'support-queue-slice')!; + expect(bench.fixture).toMatchObject({ + kind: 'recipe_package', + status: 'green', + }); + expect(bench.fixture.citation).toContain('recipes/bench-ticket'); for (const recipe of catalog.recipes) { expect(recipe.intent).not.toMatch(/retiregolden/i); } @@ -152,6 +158,7 @@ describe('compileCompositionCatalog', () => { 'cf-passkey-accounts', 'storage-audit-mail-outbox', 'static-brochure-minimal', + 'support-queue-slice', ]); const pendingOrNone = catalog.recipes.filter((r) => !greenIds.has(r.id)); for (const recipe of pendingOrNone) { @@ -169,7 +176,12 @@ describe('compileCompositionCatalog', () => { const storage = catalog.components.find((c) => c.id === 'storage-core')!; expect(storage.dependencies.some((d) => d.componentId === 'spine')).toBe(true); expect(storage.adapters.map((a) => a.id)).toEqual( - expect.arrayContaining(['memory', 'azure-tables', 'cloudflare-d1']), + expect.arrayContaining([ + 'memory', + 'azure-tables', + 'cloudflare-d1', + 'dynamodb', + ]), ); expect(storage.capabilityTags).toContain('storage'); }); diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index ba6ba40..dd320d1 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -239,33 +239,65 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ { id: 'support-queue-slice', intent: - 'A fictional maker-space helpdesk (Bench Ticket) runs a composable support queue for web and email. Deferred until Support Desk packages are published.', + 'A fictional makerspace helpdesk (Bench Ticket) runs a small support-desk site with first-party email-code login (not Auth0, Entra, or passkeys-required), server-side sessions, mail to a catcher, and ticket create/list/reply. Environment runbooks one-shot it on Docker, Cloudflare D1, Azure Tables, and AWS DynamoDB once @pegma/storage-dynamodb is published.', packages: [ - '@pegma/support-desk-contracts', - '@pegma/support-desk-core', - '@pegma/support-desk-application', - '@pegma/mail', - '@pegma/storage-core', - '@pegma/spine', + '@pegma/identity@0.1.2', + '@pegma/sessions@0.2.0', + '@pegma/mail@0.1.1', + '@pegma/rate-limit@0.2.0', + '@pegma/health@0.2.0', + '@pegma/support-desk-application@0.1.1', + '@pegma/support-desk-contracts@0.1.1', + '@pegma/support-desk-core@0.1.1', + '@pegma/authorization-core@0.4.0', + '@pegma/storage-core@0.4.0', + '@pegma/spine@0.1.1', ], adapters: [], hostResponsibilities: [ - 'Host runtime and data ownership', - 'Permission model and mail provider', + 'HTTP routes and cookie/session boundary', + 'Injected Store (memory locally; D1 / Azure Tables / @pegma/storage-dynamodb in cloud runbooks)', + 'Mail catcher (Mailpit locally; console/log on cloud)', + 'Email-code HMAC secret', + ], + nonGoals: [ + 'Auth0, Entra, Cognito, or social login', + 'Stripe or Billing Core', + 'Production email vendors', + 'Passkeys as the required login', ], - nonGoals: ['Hosted SaaS Support Desk', 'AI on ticket bodies without documented egress'], antiPatterns: [ 'Treating Support Desk as multi-tenant SaaS', - 'AI processing before the host documents what may leave its boundary', + 'Password table or an external IdP for this demo', + 'Giving Audit or Mail their own store', ], fixture: { - kind: 'pending', + kind: 'recipe_package', citation: - 'docs/catalog/RECIPE_BACKLOG.md#d2--support-queue-slice-when-support-desk-packages-are-published', - status: 'none', + 'https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket', + status: 'green', }, - capabilityTags: ['support_queue', 'mail_transactional'], - requiresPublished: ['support-desk', 'mail', 'storage-core', 'spine'], - backlogPriority: 91, + capabilityTags: [ + 'support_queue', + 'accounts', + 'email_codes', + 'sessions', + 'health', + 'storage', + 'mail_transactional', + 'rate_limit_memory', + ], + requiresPublished: [ + 'identity', + 'sessions', + 'mail', + 'rate-limit', + 'health', + 'support-desk', + 'storage-core', + 'spine', + 'authorization-core', + ], + backlogPriority: 8, }, ]; diff --git a/src/layouts/Base.astro b/src/layouts/Base.astro index cc89439..4d75e86 100644 --- a/src/layouts/Base.astro +++ b/src/layouts/Base.astro @@ -14,6 +14,7 @@ const nav = [ { href: '/stack', label: 'The stack' }, { href: '/roadmap', label: 'Roadmap' }, { href: '/examples', label: 'Examples' }, + { href: '/runbooks', label: 'Runbooks' }, { href: '/feedback', label: 'Feedback' }, { href: '/account', label: 'Account' }, ]; @@ -66,7 +67,7 @@ const nav = [ it deploys on Cloudflare, the ecosystem's second reference environment.

- Agents: get started · install skill · skill.md · catalog.json · MCP · llms.txt + Agents: get started · install skill · skill.md · catalog.json · runbooks · MCP · llms.txt

diff --git a/src/layouts/MarkdownDoc.astro b/src/layouts/MarkdownDoc.astro new file mode 100644 index 0000000..0c3e7b4 --- /dev/null +++ b/src/layouts/MarkdownDoc.astro @@ -0,0 +1,20 @@ +--- +import Base from './Base.astro'; + +interface Frontmatter { + readonly title: string; + readonly description: string; +} + +interface Props { + frontmatter: Frontmatter; +} + +const { frontmatter } = Astro.props; +--- + + +
+ +
+ diff --git a/src/pages/examples.astro b/src/pages/examples.astro index 1ea893d..8be8551 100644 --- a/src/pages/examples.astro +++ b/src/pages/examples.astro @@ -3,6 +3,7 @@ import Base from '../layouts/Base.astro'; import { RECIPE_BACKLOG } from '../data/recipe-backlog'; import northshelfComposition from '../../recipes/cf-passkey-accounts/composition.ts?raw'; import yardLoanComposition from '../../recipes/storage-audit-mail-outbox/composition.ts?raw'; +import benchTicketComposition from '../../recipes/bench-ticket/composition.ts?raw'; /* Examples are LIFTED FROM REAL CODE, per the site's hard rule — each block cites its source. Do not invent example code for this page. */ @@ -129,6 +130,10 @@ const yardLoanExcerpt = excerptFunction( yardLoanComposition, 'checkoutEquipment', ); +const benchTicketExcerpt = excerptFunction( + benchTicketComposition, + 'createBenchTicketComposition', +); const greenRecipes = RECIPE_BACKLOG.filter((r) => r.fixture.status === 'green'); const pendingRecipes = RECIPE_BACKLOG.filter( @@ -154,7 +159,9 @@ const pendingRecipes = RECIPE_BACKLOG.filter( catalog.json. Agents should fetch the catalog rather than inventing package sets — these examples assume your agent has the assembly skill and catalog installed; - the get-started page covers that setup. + the get-started page covers that setup. One-shot + environment runbooks for the Bench Ticket demo live + at /runbooks.

@@ -232,6 +239,25 @@ const pendingRecipes = RECIPE_BACKLOG.filter(

+
+

Support desk with email-code login

+

+ Bench Ticket (synthetic): first-party Identity email-code + (not Auth0/Entra/passkeys-required), Sessions, Support Desk create/list/reply, + Health, and mail to a catcher. Tests inject memory; environment runbooks + inject D1, Azure Tables, or @pegma/storage-dynamodb (requires + the storage-core adapter PR to be merged). + See environment runbooks. +

+
{benchTicketExcerpt}
+

+ Source:{' '} + recipes/bench-ticket/composition.ts +

+
+

Declare what you keep

diff --git a/src/pages/runbooks.md b/src/pages/runbooks.md new file mode 100644 index 0000000..da1fc24 --- /dev/null +++ b/src/pages/runbooks.md @@ -0,0 +1,24 @@ +--- +layout: ../layouts/MarkdownDoc.astro +title: Environment runbooks — Pegma +description: One-shot environment runbooks for a small Pegma support-desk demo. Local Docker, Cloudflare, Azure, and AWS. +--- + +# Environment runbooks + +An agent with the right CLI (and nothing else) can one-shot a working **Bench Ticket** demo: a small makerspace helpdesk, not this marketing site and not a new product. + +Logged-out: sign in with a first-party **email code**. Logged-in: file a ticket, see the queue, add a reply. That path exercises Identity, Sessions, Mail, Storage Core, Support Desk, and Health. No Stripe, Auth0, Entra, Cognito, passkeys-required login, or production email vendor. + +| Environment | Record store | Blobs | Mail | Runbook | +| --- | --- | --- | --- | --- | +| Local Docker | `createMemoryStore()` | none (no attachments) | Mailpit | [Local Docker](/runbooks/local-docker) | +| Cloudflare | `@pegma/storage-cloudflare-d1` | R2 bucket (provisioned) | console / `wrangler tail` | [Cloudflare](/runbooks/cloudflare) | +| Azure | `@pegma/storage-azure-tables` | Blob container (provisioned) | console / container logs | [Azure](/runbooks/azure) | +| AWS | `@pegma/storage-dynamodb` | S3 (`@pegma/storage-s3`) | console / CloudWatch | [AWS](/runbooks/aws) | + +The AWS record adapter is `@pegma/storage-dynamodb` (`createDynamoDbStore`) from [storage-core#7](https://github.com/pegma-dev/storage-core/pull/7). The AWS runbook uses the same one-shot shape as Azure and D1; it requires that adapter PR to be merged before `pnpm add` succeeds. + +**Fixture (CI-tested):** [`recipes/bench-ticket`](https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket) — catalog recipe `support-queue-slice`. Pin versions from [`catalog.json`](/catalog.json). Do not invent Auth0, Entra, or Stripe steps. + +Start with [Local Docker](/runbooks/local-docker). Use it as the template for the cloud runbooks. diff --git a/src/pages/runbooks/aws.md b/src/pages/runbooks/aws.md new file mode 100644 index 0000000..94ba437 --- /dev/null +++ b/src/pages/runbooks/aws.md @@ -0,0 +1,196 @@ +--- +layout: ../../layouts/MarkdownDoc.astro +title: AWS runbook — Pegma +description: One-shot AWS runbook for the Bench Ticket Pegma demo. DynamoDB records via @pegma/storage-dynamodb, S3 blobs, console mail catcher. +--- + +# AWS runbook + +Same one-shot as [Local Docker](/runbooks/local-docker), [Cloudflare](/runbooks/cloudflare), and [Azure](/runbooks/azure): Bench Ticket with first-party email-code login, Sessions, Support Desk create/list/reply, Health. Mail is a **console catcher** (CloudWatch logs) — do not sign up for SES, SendGrid, ACS, or Resend. Do not add Stripe, Auth0, Entra, or Cognito. + +## Requires the storage-core DynamoDB adapter PR + +Record persistence on AWS uses the Storage Core adapter that passes `packages/storage-core/src/conformance.ts`. That package is being added in [pegma-dev/storage-core#7](https://github.com/pegma-dev/storage-core/pull/7) as **DynamoDB**, named to match siblings: + +| Sibling | Package | Factory | +| --- | --- | --- | +| Azure Tables | `@pegma/storage-azure-tables` | `createAzureTablesStore` | +| Cloudflare D1 | `@pegma/storage-cloudflare-d1` | `createCloudflareD1Store` | +| AWS DynamoDB | `@pegma/storage-dynamodb` | `createDynamoDbStore` | + +**Do not implement that adapter in pegma.dev.** If `pnpm add @pegma/storage-dynamodb` fails because the package is not on npm yet, stop and merge/publish [storage-core#7](https://github.com/pegma-dev/storage-core/pull/7) first, then resume at step 4. Blobs are already published (`@pegma/storage-s3` / `createS3BlobStore`). + +Until that package is on npm, Local Docker, Cloudflare, and Azure still one-shot from this same fixture. + +## Prerequisites + +- Git, Docker, Node 22/24 with Corepack. +- AWS account. +- Authenticated AWS CLI: `aws sts get-caller-identity` must print an account. If it fails: `aws login` or `aws configure sso` (or export keys) and retry. +- Region default: `us-east-1`. + +## 1. Get the source + +```sh +git clone https://github.com/pegma-dev/pegma.dev.git +cd pegma.dev +git checkout main +npm install -g corepack +corepack enable +pnpm install --frozen-lockfile +``` + +## 2. Default names + +| Resource | Default name | +| --- | --- | +| Region | `us-east-1` | +| DynamoDB table | `bench-ticket` (every Storage Core collection shares one table) | +| S3 bucket | `bench-ticket-blobs-` (globally unique) | +| App Runner / container service | `bench-ticket` | +| Email-code secret | `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | + +The adapter README’s table schema is `pk` (HASH) + `sk` (RANGE), on-demand billing. Mirror Azure: **one table for every collection**, not one table per collection. + +## 3. Create AWS resources + +```sh +ACCOUNT=$(aws sts get-caller-identity --query Account --output text) +REGION=us-east-1 +BUCKET="bench-ticket-blobs-${ACCOUNT}" + +aws dynamodb create-table \ + --region "$REGION" \ + --table-name bench-ticket \ + --billing-mode PAY_PER_REQUEST \ + --attribute-definitions \ + AttributeName=pk,AttributeType=S \ + AttributeName=sk,AttributeType=S \ + --key-schema \ + AttributeName=pk,KeyType=HASH \ + AttributeName=sk,KeyType=RANGE + +aws dynamodb wait table-exists --region "$REGION" --table-name bench-ticket + +aws s3api create-bucket --bucket "$BUCKET" --region "$REGION" +``` + +The adapter can create the table on first use (`createTableIfMissing` defaults to true). This runbook provisions it in infrastructure instead, then passes `createTableIfMissing: false` so the task role does not need `CreateTable`. Do not invent a second table “for audit”. + +## 4. Point the host at DynamoDB (after the adapter is on npm) + +```sh +pnpm add @pegma/storage-dynamodb @aws-sdk/client-dynamodb @pegma/storage-s3 @aws-sdk/client-s3 +``` + +Pin `@pegma/storage-dynamodb` to the exact version in [catalog.json](/catalog.json) once the compiler lists it. Until then, use the version the storage-core release publishes (do not invent a caret range). + +In `recipes/bench-ticket/host.ts`, replace `createMemoryStore()` with the sibling-shaped factory: + +```ts +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; +import { createDynamoDbStore } from "@pegma/storage-dynamodb"; + +const store = createDynamoDbStore({ + client: new DynamoDBClient({ region: process.env.AWS_REGION ?? "us-east-1" }), + tableName: process.env.BENCH_TICKET_TABLE ?? "bench-ticket", + createTableIfMissing: false, +}); +``` + +If the published factory options differ, copy them from that package’s README — keep the call site a single `createDynamoDbStore({ … })` returning a Storage Core `Store`, then pass it to `createBenchTicketComposition` unchanged. + +Optional blobs (provisioned above; not required for the ticket round-trip): + +```ts +import { S3Client } from "@aws-sdk/client-s3"; +import { createS3BlobStore } from "@pegma/storage-s3"; + +const blobs = createS3BlobStore({ + client: new S3Client({ region: process.env.AWS_REGION ?? "us-east-1" }), + bucket: process.env.BENCH_TICKET_BLOB_BUCKET!, + endpoint: `https://s3.${process.env.AWS_REGION ?? "us-east-1"}.amazonaws.com`, + maxObjectBytes: 16 * 1024 * 1024, +}); +``` + +Set `BENCH_TICKET_MAIL_CATCHER=console`. + +## 5. Deploy the container + +Use the same Dockerfile as Local Docker. Example with App Runner (any container host that can reach DynamoDB is fine): + +```sh +SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))") +ACCOUNT=$(aws sts get-caller-identity --query Account --output text) +REGION=us-east-1 +ECR="$ACCOUNT.dkr.ecr.$REGION.amazonaws.com" +aws ecr create-repository --repository-name bench-ticket --region "$REGION" || true +aws ecr get-login-password --region "$REGION" \ + | docker login --username AWS --password-stdin "$ECR" +docker build -f recipes/bench-ticket/Dockerfile -t "$ECR/bench-ticket:local" . +docker push "$ECR/bench-ticket:local" +``` + +Create an App Runner service (or ECS/Fargate) with: + +| Env var | Value | +| --- | --- | +| `PORT` | `8787` | +| `BENCH_TICKET_MAIL_CATCHER` | `console` | +| `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | `$SECRET` | +| `BENCH_TICKET_TABLE` | `bench-ticket` | +| `AWS_REGION` | `us-east-1` | +| `BENCH_TICKET_ORIGIN` | `https://` (set after first URL exists, then redeploy) | + +Give the task role DynamoDB access to table `bench-ticket` and `s3:GetObject`/`PutObject` on the blob bucket. Do not put AWS keys in the image. + +## 6. Verify + +```sh +ORIGIN=https://REPLACE.awsapprunner.com +curl -sS "$ORIGIN/health" +``` + +Expect HTTP 200, `"ok": true`, `"service": "bench-ticket"`. Then the same begin / 8-digit code from logs / finish / file ticket / reply sequence as Local Docker. Log prefix: `[bench-ticket mail]`. + +Follow logs with the platform’s tail (`aws logs tail … --follow` or App Runner application logs). + +## Failure signs + +| Sign | Next command | +| --- | --- | +| `aws sts get-caller-identity` fails | `aws login` / `aws configure sso` | +| `pnpm add @pegma/storage-dynamodb` 404 | Adapter PR not merged/published. Do **not** implement DynamoDB here. Finish Local Docker / Cloudflare / Azure instead. See [storage-core#7](https://github.com/pegma-dev/storage-core/pull/7). | +| `Cannot find module '@pegma/storage-dynamodb'` | Same — wait for the storage-core AWS package; name it `@pegma/storage-dynamodb` / `createDynamoDbStore`. | +| `ResourceNotFoundException` | `aws dynamodb describe-table --table-name bench-ticket`. Recreate using `pk` HASH + `sk` RANGE. | +| Health 503 / storage fail | IAM: the task role needs DynamoDB on that table. `aws dynamodb scan --table-name bench-ticket --max-items 1`. | +| Origin invalid / finish 400 | `BENCH_TICKET_ORIGIN` must be the public HTTPS origin with no path. | +| No code in logs | Tail logs **before** begin. `BENCH_TICKET_MAIL_CATCHER=console`. | +| Temptation to use Cognito | Stop. This demo is `@pegma/identity` email-code only. | + +## Teardown + +```sh +aws dynamodb delete-table --table-name bench-ticket --region us-east-1 +aws s3 rb "s3://bench-ticket-blobs-${ACCOUNT}" --force +aws ecr delete-repository --repository-name bench-ticket --force --region us-east-1 +# plus delete the App Runner / ECS service +rm -f /tmp/bench-ticket.cookies +``` + +## Store wiring (same composition) + +After the adapter exists, the host is the Azure/D1 shape: + +```ts +import { createDynamoDbStore } from "@pegma/storage-dynamodb"; + +const store = createDynamoDbStore({ + client, + tableName: "bench-ticket", + createTableIfMissing: false, +}); +``` + +Pass `store` into `createBenchTicketComposition`. Do not give Audit, Mail, Identity, or Support Desk a second DynamoDB table. diff --git a/src/pages/runbooks/azure.md b/src/pages/runbooks/azure.md new file mode 100644 index 0000000..a2c04fd --- /dev/null +++ b/src/pages/runbooks/azure.md @@ -0,0 +1,177 @@ +--- +layout: ../../layouts/MarkdownDoc.astro +title: Azure runbook — Pegma +description: One-shot Azure runbook for the Bench Ticket Pegma demo. Azure Tables records, Blob container, console mail catcher. +--- + +# Azure runbook + +One-shot the same **Bench Ticket** demo as [Local Docker](/runbooks/local-docker) on Azure: first-party email-code login, Sessions, Support Desk create/list/reply, Health. Record store is `@pegma/storage-azure-tables`. Provision a Blob container for `@pegma/storage-azure-blob` (the demo does not store attachments). Mail is a **console catcher** on container logs — do not sign up for ACS, SES, SendGrid, or Resend. + +Do not add Stripe, Auth0, Entra, or passkeys-required login. Entra is an IdP adapter for hosts that already authenticate with Entra; this demo uses `@pegma/identity` email codes. + +**Fixture:** [`recipes/bench-ticket`](https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket). Reuse the Node host (`host.ts`) with the store factory swapped to Azure Tables — same `createBenchTicketComposition`. + +## Prerequisites + +- Git, Docker (to build the existing demo image), Node 22/24 with Corepack. +- Azure account. +- Authenticated Azure CLI: `az account show` must print a subscription. If it fails: `az login` and complete the browser flow. + +## 1. Get the source + +```sh +git clone https://github.com/pegma-dev/pegma.dev.git +cd pegma.dev +git checkout main +npm install -g corepack +corepack enable +pnpm install --frozen-lockfile +``` + +## 2. Default names + +| Resource | Default name | +| --- | --- | +| Resource group | `rg-bench-ticket` | +| Region | `eastus` | +| Storage account | `stbenchticket` plus a unique suffix (Azure names are global) | +| Table | `pegma` (every Storage Core collection shares one table) | +| Blob container | `bench-ticket-blobs` | +| Container Apps env | `cae-bench-ticket` | +| Container app | `ca-bench-ticket` | +| Email-code secret | `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | + +## 3. Create Azure resources + +```sh +az group create --name rg-bench-ticket --location eastus + +az storage account create \ + --name stbenchticket$RANDOM \ + --resource-group rg-bench-ticket \ + --location eastus \ + --sku Standard_LRS + +ACCOUNT=$(az storage account list -g rg-bench-ticket --query '[0].name' -o tsv) +CONN=$(az storage account show-connection-string -g rg-bench-ticket -n "$ACCOUNT" --query connectionString -o tsv) + +az storage table create --name pegma --connection-string "$CONN" +az storage container create --name bench-ticket-blobs --connection-string "$CONN" +``` + +Save `$CONN`. Do not commit it. + +## 4. Point the host at Azure Tables + +The published demo `host.ts` uses `createMemoryStore()`. For Azure, add the published adapter and swap the factory. Exact packages (pin from [catalog.json](/catalog.json) if these drifted): + +```sh +pnpm add @pegma/storage-azure-tables@0.4.0 @azure/data-tables +``` + +In `recipes/bench-ticket/host.ts`, replace `createMemoryStore()` with: + +```ts +import { TableClient, AzureNamedKeyCredential } from "@azure/data-tables"; +import { createAzureTablesStore } from "@pegma/storage-azure-tables"; + +const account = process.env.AZURE_STORAGE_ACCOUNT!; +const key = process.env.AZURE_STORAGE_ACCOUNT_KEY!; +const endpoint = `https://${account}.table.core.windows.net`; +const client = new TableClient(endpoint, "pegma", new AzureNamedKeyCredential(account, key)); +const store = createAzureTablesStore({ client, createTableIfMissing: false }); +``` + +Set `BENCH_TICKET_MAIL_CATCHER=console` so codes go to stdout (container logs), not Mailpit. + +Keep `createBenchTicketComposition({ store, origin, … })` unchanged. + +## 5. Deploy the container + +```sh +SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))") +ACCOUNT=$(az storage account list -g rg-bench-ticket --query '[0].name' -o tsv) +KEY=$(az storage account keys list -g rg-bench-ticket -n "$ACCOUNT" --query '[0].value' -o tsv) + +az acr create -g rg-bench-ticket -n benchticketacr$RANDOM --sku Basic +ACR=$(az acr list -g rg-bench-ticket --query '[0].name' -o tsv) +az acr login -n "$ACR" +IMAGE="${ACR}.azurecr.io/bench-ticket:local" +docker build -f recipes/bench-ticket/Dockerfile -t "$IMAGE" . +docker push "$IMAGE" + +az containerapp env create -g rg-bench-ticket -n cae-bench-ticket -l eastus + +# First create without origin, then set origin from the assigned FQDN. +az containerapp create \ + -g rg-bench-ticket \ + -n ca-bench-ticket \ + --environment cae-bench-ticket \ + --image "$IMAGE" \ + --ingress external \ + --target-port 8787 \ + --registry-server "${ACR}.azurecr.io" \ + --env-vars \ + BENCH_TICKET_MAIL_CATCHER=console \ + BENCH_TICKET_EMAIL_CODE_SECRET_BASE64="$SECRET" \ + AZURE_STORAGE_ACCOUNT="$ACCOUNT" \ + AZURE_STORAGE_ACCOUNT_KEY="$KEY" \ + PORT=8787 + +FQDN=$(az containerapp show -g rg-bench-ticket -n ca-bench-ticket --query properties.configuration.ingress.fqdn -o tsv) +ORIGIN="https://$FQDN" +az containerapp update -g rg-bench-ticket -n ca-bench-ticket \ + --set-env-vars "BENCH_TICKET_ORIGIN=$ORIGIN" +``` + +Identity requires the live HTTPS origin. Redeploy/update env after the FQDN exists. + +## 6. Verify + +```sh +ORIGIN=https://$(az containerapp show -g rg-bench-ticket -n ca-bench-ticket --query properties.configuration.ingress.fqdn -o tsv) +curl -sS "$ORIGIN/health" +``` + +Expect HTTP 200, `"ok": true`, `"service": "bench-ticket"`. + +```sh +az containerapp logs show -g rg-bench-ticket -n ca-bench-ticket --follow +``` + +Then the same begin / copy 8-digit code from logs / finish / file ticket / reply sequence as Local Docker, using `$ORIGIN` instead of `http://localhost:8787`. Log line prefix: `[bench-ticket mail]`. + +## Failure signs + +| Sign | Next command | +| --- | --- | +| `az account show` fails | `az login` | +| Storage account name taken | Add a longer suffix; Azure storage names are global and lowercase. | +| `TableNotFound` | `az storage table create --name pegma --connection-string "$CONN"` | +| Health 503 / storage fail | Confirm `AZURE_STORAGE_ACCOUNT` / `AZURE_STORAGE_ACCOUNT_KEY` on the container app: `az containerapp show -g rg-bench-ticket -n ca-bench-ticket`. | +| Origin invalid / finish 400 | `BENCH_TICKET_ORIGIN` must be `https://` with no path. `az containerapp update … --set-env-vars BENCH_TICKET_ORIGIN=…` | +| No code in logs | `az containerapp logs show … --follow` **before** calling begin. `BENCH_TICKET_MAIL_CATCHER` must be `console`. | +| Building image fails on `tsx` | Image must `pnpm install` **before** `NODE_ENV=production` (the checked-in Dockerfile already does). | + +## Teardown + +```sh +az group delete --name rg-bench-ticket --yes --no-wait +rm -f /tmp/bench-ticket.cookies +``` + +That removes the storage account, table, blob container, ACR, and Container App. + +## Store wiring (same composition) + +```ts +import { createAzureTablesStore } from "@pegma/storage-azure-tables"; + +const store = createAzureTablesStore({ + client, + createTableIfMissing: false, +}); +``` + +Hand that `Store` to `createBenchTicketComposition`. Blob: `@pegma/storage-azure-blob` + `createAzureBlobStore({ containerClient })` when the host grows attachments; this demo’s ticket round-trip does not need it. diff --git a/src/pages/runbooks/cloudflare.md b/src/pages/runbooks/cloudflare.md new file mode 100644 index 0000000..cbf935d --- /dev/null +++ b/src/pages/runbooks/cloudflare.md @@ -0,0 +1,160 @@ +--- +layout: ../../layouts/MarkdownDoc.astro +title: Cloudflare runbook — Pegma +description: One-shot Cloudflare runbook for the Bench Ticket Pegma demo. D1 records, R2 bucket, console mail catcher. +--- + +# Cloudflare runbook + +One-shot the same **Bench Ticket** demo as [Local Docker](/runbooks/local-docker) on Cloudflare: first-party email-code login, Sessions, Support Desk create/list/reply, Health. Record store is `@pegma/storage-cloudflare-d1`. Provision an R2 bucket for blobs (the demo does not store attachments; the bucket is the host-owned blob binding the stack expects). Mail is a **console catcher** (`wrangler tail`) — do not sign up for Resend, SES, SendGrid, or ACS. + +Do not add Stripe, Auth0, Entra, or passkeys-required login. + +**Fixture:** [`recipes/bench-ticket`](https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket) — Worker entry [`cloudflare/worker.ts`](https://github.com/pegma-dev/pegma.dev/blob/main/recipes/bench-ticket/cloudflare/worker.ts), Wrangler config [`cloudflare/wrangler.jsonc`](https://github.com/pegma-dev/pegma.dev/blob/main/recipes/bench-ticket/cloudflare/wrangler.jsonc). + +## Prerequisites + +- Git. +- Node 22 or 24 with Corepack (`corepack enable`). +- Cloudflare account. +- Authenticated Wrangler: `npx wrangler whoami` must print your account. If it fails: `npx wrangler login` and complete the browser flow. + +## 1. Get the source + +```sh +git clone https://github.com/pegma-dev/pegma.dev.git +cd pegma.dev +git checkout main +npm install -g corepack +corepack enable +pnpm install --frozen-lockfile +``` + +## 2. Default names + +| Resource | Default name | Binding | +| --- | --- | --- | +| Worker script | `bench-ticket` | — | +| D1 database | `bench-ticket` | `BENCH_TICKET_DB` | +| R2 bucket | `bench-ticket-blobs` | `BENCH_TICKET_BLOBS` | +| Origin var | `BENCH_TICKET_ORIGIN` | Worker `vars` | +| Email-code secret | `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | Worker **secret** | + +## 3. Create D1 and R2 + +```sh +npx wrangler d1 create bench-ticket +npx wrangler r2 bucket create bench-ticket-blobs +``` + +Copy the D1 `database_id` UUID from the `d1 create` output into `recipes/bench-ticket/cloudflare/wrangler.jsonc`, replacing `REPLACE_AFTER_D1_CREATE`. Leave `database_name` as `bench-ticket`. + +The D1 adapter creates its schema on first use (`createSchemaIfMissing: true`). Do not invent a second database “just for audit” — Audit records live in the caller collection on this same D1. + +## 4. Origin and secret + +After first deploy Wrangler prints a `*.workers.dev` URL. Set `vars.BENCH_TICKET_ORIGIN` in `wrangler.jsonc` to that origin with **no trailing slash** (example: `https://bench-ticket..workers.dev`). Identity refuses origins that are not a full origin. + +Generate a 32-byte secret and put it as a Worker secret (not a `vars` value): + +```sh +SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))") +echo "$SECRET" +npx wrangler secret put BENCH_TICKET_EMAIL_CODE_SECRET_BASE64 \ + -c recipes/bench-ticket/cloudflare/wrangler.jsonc +``` + +Paste `$SECRET` at the prompt. Do not commit it. + +## 5. Deploy + +```sh +npx wrangler deploy -c recipes/bench-ticket/cloudflare/wrangler.jsonc +``` + +If origin was still `REPLACE`, set `BENCH_TICKET_ORIGIN` to the printed `workers.dev` URL and deploy a second time so Identity’s allowed origin matches the live host. + +```sh +npx wrangler deploy -c recipes/bench-ticket/cloudflare/wrangler.jsonc +``` + +## 6. Verify + +Replace `$ORIGIN` with the Worker origin. + +```sh +ORIGIN=https://bench-ticket.REPLACE.workers.dev +curl -sS "$ORIGIN/health" +``` + +Expect HTTP 200, `"ok": true`, `"service": "bench-ticket"`. + +In a second terminal: + +```sh +npx wrangler tail bench-ticket -c recipes/bench-ticket/cloudflare/wrangler.jsonc +``` + +Ticket round-trip: + +```sh +BEGIN=$(curl -sS -X POST "$ORIGIN/api/auth/begin" \ + -H 'content-type: application/json' \ + -d '{"email":"member@bench.example","flow":"create"}') +HANDLE=$(printf '%s' "$BEGIN" | node -e "let s='';process.stdin.on('data',d=>s+=d);process.stdin.on('end',()=>console.log(JSON.parse(s).codeHandle))") +``` + +The tail session logs a line `[bench-ticket mail] … subject=Your Bench Ticket code is ########`. Copy the eight digits. + +```sh +CODE=12345678 # from wrangler tail +curl -sS -c /tmp/bench-ticket.cookies -X POST "$ORIGIN/api/auth/finish" \ + -H 'content-type: application/json' \ + -d "{\"flow\":\"create\",\"codeHandle\":\"$HANDLE\",\"code\":\"$CODE\"}" + +curl -sS -b /tmp/bench-ticket.cookies -X POST "$ORIGIN/api/tickets" \ + -H 'content-type: application/json' \ + -d '{"subject":"Laser cutter jammed","body":"The bed will not home.","category":"tools"}' + +curl -sS -b /tmp/bench-ticket.cookies "$ORIGIN/api/tickets" +``` + +Open `$ORIGIN` in a browser for the same path. Codes are **not** in Mailpit; they are in `wrangler tail`. + +## Failure signs + +| Sign | Next command | +| --- | --- | +| `wrangler whoami` not authenticated | `npx wrangler login` | +| `D1 database not found` / binding error | Confirm `database_id` in `wrangler.jsonc` matches `npx wrangler d1 list`. | +| Health 503 / storage fail | `npx wrangler d1 execute bench-ticket --command 'SELECT name FROM sqlite_master;'` then redeploy. First-request schema create needs the D1 binding. | +| `Bench Ticket origin is invalid` / finish 400 | `BENCH_TICKET_ORIGIN` must equal the URL you curl (`https://…workers.dev`, no path, no slash). Redeploy after editing `vars`. | +| Begin 200, no code in tail | Tail must be running **before** begin. `npx wrangler tail bench-ticket -c recipes/bench-ticket/cloudflare/wrangler.jsonc` | +| `Identity email-code secret is missing` | `npx wrangler secret put BENCH_TICKET_EMAIL_CODE_SECRET_BASE64 -c recipes/bench-ticket/cloudflare/wrangler.jsonc` | +| KV mentioned as a store | Stop. Storage Core **rejects KV**. Use D1 only. | + +## Teardown + +```sh +npx wrangler delete -c recipes/bench-ticket/cloudflare/wrangler.jsonc +npx wrangler d1 delete bench-ticket +npx wrangler r2 bucket delete bench-ticket-blobs +rm -f /tmp/bench-ticket.cookies +``` + +Confirm each delete. D1 delete is irreversible. + +## Store wiring (same composition) + +The Worker already injects D1: + +```ts +import { createCloudflareD1Store } from "@pegma/storage-cloudflare-d1"; + +const store = createCloudflareD1Store({ + database: env.BENCH_TICKET_DB, + createSchemaIfMissing: true, +}); +``` + +That `Store` is passed to `createBenchTicketComposition` — identical to Local Docker’s memory store and Azure Tables / AWS DynamoDB in the sibling runbooks. diff --git a/src/pages/runbooks/local-docker.md b/src/pages/runbooks/local-docker.md new file mode 100644 index 0000000..2131c17 --- /dev/null +++ b/src/pages/runbooks/local-docker.md @@ -0,0 +1,142 @@ +--- +layout: ../../layouts/MarkdownDoc.astro +title: Local Docker runbook — Pegma +description: One-shot Local Docker runbook for the Bench Ticket Pegma demo. Docker plus this repo; Mailpit for email codes. +--- + +# Local Docker runbook + +One-shot a working **Bench Ticket** site on a laptop that has Docker and nothing else (no cloud account, no npm token, no IdP). The user starts empty. You end with a site at `http://localhost:8787`, Mailpit at `http://localhost:8025` for login codes, a passing health check, and a ticket create/list/reply round-trip. + +This is the template for the [Cloudflare](/runbooks/cloudflare), [Azure](/runbooks/azure), and [AWS](/runbooks/aws) runbooks. Do not add Stripe, Auth0, Entra, Cognito, SES, SendGrid, or ACS. + +**Fixture:** [`recipes/bench-ticket`](https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket) in this repository. Composition is CI-tested. Local Docker uses `createMemoryStore()` from `@pegma/storage-core` — honest for a laptop, not a durability claim. + +## Prerequisites + +- Docker Engine with Compose v2 (`docker compose version`). +- Git. +- Ports **8787** (app), **8025** (Mailpit UI), and **1025** (Mailpit SMTP) free on localhost. +- No cloud login. Authenticated CLIs are not required. + +If `docker` is missing, install Docker Desktop or Engine for the OS, then continue. Do not substitute Podman unless Compose is confirmed (`docker compose version` prints v2). + +## 1. Get the source + +```sh +git clone https://github.com/pegma-dev/pegma.dev.git +cd pegma.dev +git checkout main +``` + +If you already have a clone, `cd` into it and `git pull origin main`. + +## 2. Default names and env vars + +Compose file: `recipes/bench-ticket/docker-compose.yml`. + +| Name | Value | +| --- | --- | +| App origin | `http://localhost:8787` | +| Mailpit UI | `http://localhost:8025` | +| Mailpit SMTP | `mailpit:1025` (from the app container) | +| Email-code HMAC secret | `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` (32 bytes of `0x0b`, base64; **local demo only**) | +| Store | in-memory (`createMemoryStore()`) | +| Mail catcher | Mailpit SMTP (`BENCH_TICKET_MAIL_CATCHER=mailpit`) | + +The compose file already sets these. Do not invent a production email vendor. Do not enable passkeys. + +## 3. Start + +From the repository root: + +```sh +docker compose -f recipes/bench-ticket/docker-compose.yml up --build +``` + +Wait until the app healthcheck is healthy (compose prints `Started` / health passing, usually under a minute). Leave this terminal running. + +## 4. Verify + +In a **second** terminal: + +```sh +curl -sS http://localhost:8787/health +``` + +Expect HTTP 200 and JSON with `"ok": true`, `"service": "bench-ticket"`, and checks named `process` and `storage`. + +Open the site: [http://localhost:8787](http://localhost:8787). You should see the Bench Ticket sign-in form. + +Mailpit UI: [http://localhost:8025](http://localhost:8025). It should load empty until a code is requested. + +### Ticket round-trip (agent, no browser required) + +```sh +# 1. Request an email code +BEGIN=$(curl -sS -X POST http://localhost:8787/api/auth/begin \ + -H 'content-type: application/json' \ + -d '{"email":"member@bench.example","flow":"create"}') +echo "$BEGIN" +HANDLE=$(printf '%s' "$BEGIN" | node -e "let s='';process.stdin.on('data',d=>s+=d);process.stdin.on('end',()=>console.log(JSON.parse(s).codeHandle))") + +# 2. Read the 8-digit code from Mailpit +sleep 1 +CODE=$(curl -sS 'http://localhost:8025/api/v1/messages' \ + | node -e "let s='';process.stdin.on('data',d=>s+=d);process.stdin.on('end',()=>{const j=JSON.parse(s);const sub=(j.messages||j)||[];const m=JSON.stringify(sub).match(/Your Bench Ticket code is (\\d{8})/); if(!m) {console.error(s); process.exit(1);} console.log(m[1]);})") +echo "code=$CODE" + +# 3. Finish sign-up (saves the session cookie) +curl -sS -c /tmp/bench-ticket.cookies -X POST http://localhost:8787/api/auth/finish \ + -H 'content-type: application/json' \ + -d "{\"flow\":\"create\",\"codeHandle\":\"$HANDLE\",\"code\":\"$CODE\"}" + +# 4. File a ticket, list the queue, reply +curl -sS -b /tmp/bench-ticket.cookies -X POST http://localhost:8787/api/tickets \ + -H 'content-type: application/json' \ + -d '{"subject":"Laser cutter jammed","body":"The bed will not home.","category":"tools"}' + +curl -sS -b /tmp/bench-ticket.cookies http://localhost:8787/api/tickets + +TICKET_ID=$(curl -sS -b /tmp/bench-ticket.cookies http://localhost:8787/api/tickets \ + | node -e "let s='';process.stdin.on('data',d=>s+=d);process.stdin.on('end',()=>console.log(JSON.parse(s).tickets[0].id))") + +curl -sS -b /tmp/bench-ticket.cookies -X POST \ + "http://localhost:8787/api/tickets/$TICKET_ID/replies" \ + -H 'content-type: application/json' \ + -d '{"body":"Cleared the gantry. Still stuck."}' +``` + +Expect: health 200, Mailpit message whose subject contains `Your Bench Ticket code is` plus eight digits, finish returns a `principalId`, create returns **201**, list includes that ticket, reply returns **200** with more than one message. + +A person can do the same in the browser: enter an email, Create account, copy the code from Mailpit, verify, file a ticket, reply. + +## Failure signs + +| Sign | Next command | +| --- | --- | +| `Cannot connect to the Docker daemon` | Start Docker, then rerun `docker compose … up --build`. | +| Port already allocated (`8787` / `8025` / `1025`) | `ss -ltnp \| grep -E '8787\|8025\|1025'` then stop the other process, or change the left-hand ports in the compose file. | +| App unhealthy / `curl: Failed to connect` | `docker compose -f recipes/bench-ticket/docker-compose.yml logs app --tail=80` | +| Health 503 / `storage` check fail | Rebuild: `docker compose -f recipes/bench-ticket/docker-compose.yml up --build --force-recreate`. Memory store should not fail a ping; this is almost always a crash looping before listen. | +| `Mailpit SMTP timed out` / begin 500 | `docker compose -f recipes/bench-ticket/docker-compose.yml logs mailpit --tail=40`. Confirm `MAILPIT_SMTP_HOST=mailpit` (the **service** name, not localhost) from the app container. | +| Begin 200 but Mailpit empty | Wait 2s, `curl -sS http://localhost:8025/api/v1/messages`. If still empty: `docker compose … logs app --tail=80` and look for SMTP errors. | +| Finish `verification_failed` | Code is 8 digits from the **latest** Mailpit message. Do not reuse a code. Request a new one. | +| Finish `invalid_input` / origin errors | Origin must stay `http://localhost:8787` (no path). Do not change `BENCH_TICKET_ORIGIN` without matching the published host. | +| Ticket `401 unauthenticated` | Cookie file missing. Rerun finish with `-c /tmp/bench-ticket.cookies` then `-b` the same file. | + +## Teardown + +```sh +docker compose -f recipes/bench-ticket/docker-compose.yml down -v +rm -f /tmp/bench-ticket.cookies +``` + +That stops the app and Mailpit and removes the compose network. There is no cloud resource to delete. Memory store state dies with the container — that is expected. + +## What this demo refuses + +- Passwords, Auth0, Entra, Cognito, social login. +- Stripe / Billing Core. +- Production email (Resend, SES, ACS, SendGrid). +- Passkeys as the **required** login (optional extra only after email-code works, and only on HTTPS with a stable origin). diff --git a/src/pages/skill.astro b/src/pages/skill.astro index f3873fa..56b1df3 100644 --- a/src/pages/skill.astro +++ b/src/pages/skill.astro @@ -97,6 +97,7 @@ import SkillInstallTabs from '../components/SkillInstallTabs.astro'; Related: catalog.json · examples · + runbooks · llms.txt · stack · MCP diff --git a/src/pages/start.astro b/src/pages/start.astro index 9356b2f..82ea003 100644 --- a/src/pages/start.astro +++ b/src/pages/start.astro @@ -127,7 +127,7 @@ Do not invent passwords.

- Related: skill install notes · catalog.json · examples · the stack · llms.txt + Related: skill install notes · catalog.json · examples · runbooks · the stack · llms.txt

diff --git a/src/styles/global.css b/src/styles/global.css index 086a3fa..11ad970 100644 --- a/src/styles/global.css +++ b/src/styles/global.css @@ -657,3 +657,28 @@ th { color: var(--slate); margin-top: 0.4rem; } + +/* Environment runbooks (MarkdownDoc layout) */ +.runbook h1 { + font-size: 2rem; + letter-spacing: -0.03em; + margin: 0 0 0.75rem; +} +.runbook h2 { + margin-top: 2rem; +} +.runbook h3 { + margin-top: 1.4rem; + font-size: 1.05rem; +} +.runbook ul, +.runbook ol { + padding-left: 1.25rem; +} +.runbook li { + margin: 0.35rem 0; +} +.runbook > p:first-of-type { + font-size: 1.15rem; + color: var(--slate); +} From d868547f8e9162c964c7702693650937a06a9ea5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 17:49:49 +0000 Subject: [PATCH 2/8] Fix Bench Ticket typecheck and assembly-eval pins. Drop DOM-only HeadersInit from the Node recipe host, and align the offline eval npm map with the recipe backlog pins so support-queue-slice can be selected as the primary recipe. Co-authored-by: Fly Over Coder --- evals/assembly-eval.test.ts | 43 ++++++++++++++++++--------------- recipes/bench-ticket/handler.ts | 6 ++++- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/evals/assembly-eval.test.ts b/evals/assembly-eval.test.ts index 4c97802..bc3a2d7 100644 --- a/evals/assembly-eval.test.ts +++ b/evals/assembly-eval.test.ts @@ -21,27 +21,28 @@ const EVAL_NPM: Record = { '@pegma/spine': '0.1.1', '@pegma/storage-core': '0.4.0', '@pegma/storage-azure-tables': '0.4.0', - '@pegma/storage-cloudflare-d1': '0.4.0', + '@pegma/storage-cloudflare-d1': '0.4.1', '@pegma/storage-blobs': '0.1.0', '@pegma/storage-azure-blob': '0.1.0', '@pegma/storage-cloudflare-r2': '0.1.0', '@pegma/storage-s3': '0.1.0', - '@pegma/authorization-contracts': '0.1.2', - '@pegma/authorization-core': '0.1.2', - '@pegma/authorization-policy': '0.1.2', - '@pegma/authorization-auth0': '0.1.2', - '@pegma/authorization-stripe': '0.1.2', - '@pegma/authorization-storage': '0.1.2', - '@pegma/authorization-tokens': '0.1.2', - '@pegma/authorization-identity': '0.1.2', - '@pegma/audit': '0.1.0', - '@pegma/support-desk-contracts': '0.1.0', - '@pegma/support-desk-core': '0.1.0', - '@pegma/support-desk-application': '0.1.0', - '@pegma/support-desk-templates': '0.1.0', - '@pegma/webhooks': '0.1.0', - '@pegma/sessions': '0.1.0', - '@pegma/mail': '0.1.0', + '@pegma/authorization-contracts': '0.4.0', + '@pegma/authorization-core': '0.4.0', + '@pegma/authorization-policy': '0.4.0', + '@pegma/authorization-auth0': '0.4.0', + '@pegma/authorization-entra': '0.4.0', + '@pegma/authorization-stripe': '0.4.0', + '@pegma/authorization-storage': '0.4.0', + '@pegma/authorization-tokens': '0.4.0', + '@pegma/authorization-identity': '0.4.0', + '@pegma/audit': '0.2.0', + '@pegma/support-desk-contracts': '0.1.1', + '@pegma/support-desk-core': '0.1.1', + '@pegma/support-desk-application': '0.1.1', + '@pegma/support-desk-templates': '0.1.1', + '@pegma/webhooks': '0.1.1', + '@pegma/sessions': '0.2.0', + '@pegma/mail': '0.1.1', '@pegma/billing-core': '0.1.1', '@pegma/billing-stripe': '0.1.1', '@pegma/cache-core': '0.1.1', @@ -58,13 +59,13 @@ const EVAL_NPM: Record = { '@pegma/flags-cloudflare-flagship': '0.1.1', '@pegma/flags-flagd': '0.1.1', '@pegma/flags-launchdarkly': '0.1.1', - '@pegma/identity': '0.1.0', - '@pegma/rate-limit': '0.1.0', + '@pegma/identity': '0.1.2', + '@pegma/rate-limit': '0.2.0', '@pegma/logger-tee': '0.1.1', '@pegma/logger-applicationinsights': '0.1.1', '@pegma/logger-cloudflare': '0.1.1', '@pegma/logger-datadog': '0.1.1', - '@pegma/health': '0.1.1', + '@pegma/health': '0.2.0', }; async function compileEvalCatalog(): Promise { @@ -93,6 +94,7 @@ describe('assembly eval harness (Phase 5)', () => { 'no-passwords', 'passkey-accounts-workers', 'static-brochure', + 'support-desk-email-code', ].sort(), ); }); @@ -116,6 +118,7 @@ describe('assembly eval harness (Phase 5)', () => { expect(byId['passkey-accounts-workers']?.pass).toBe(false); expect(byId['health-endpoint-only']?.pass).toBe(false); expect(byId['no-passwords']?.pass).toBe(false); + expect(byId['support-desk-email-code']?.pass).toBe(false); expect(report.passRate).toBeGreaterThan(0); expect(report.passRate).toBeLessThan(1); }); diff --git a/recipes/bench-ticket/handler.ts b/recipes/bench-ticket/handler.ts index 836fc17..7514f9f 100644 --- a/recipes/bench-ticket/handler.ts +++ b/recipes/bench-ticket/handler.ts @@ -174,7 +174,11 @@ const PAGE_HTML = ` `; -function json(status: number, body: unknown, headers?: HeadersInit): Response { +function json( + status: number, + body: unknown, + headers?: Record, +): Response { return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', ...headers }, From 306cb1a4178d551ffbdef3113b846a593d8b1612 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 18:06:02 +0000 Subject: [PATCH 3/8] Harden Bench Ticket against stored XSS and malformed cookies. Render ticket subjects with DOM text nodes, treat undecodable cookies and ticket ids as 4xx, cache the Cloudflare composition on origin plus secret, and join Cookie headers with semicolons. Co-authored-by: Fly Over Coder --- recipes/bench-ticket/cloudflare/worker.ts | 23 ++++--- recipes/bench-ticket/handler.test.ts | 77 +++++++++++++++++++++++ recipes/bench-ticket/handler.ts | 43 ++++++++++--- recipes/bench-ticket/host.test.ts | 21 +++++++ recipes/bench-ticket/host.ts | 12 +++- 5 files changed, 159 insertions(+), 17 deletions(-) create mode 100644 recipes/bench-ticket/host.test.ts diff --git a/recipes/bench-ticket/cloudflare/worker.ts b/recipes/bench-ticket/cloudflare/worker.ts index 5dac82e..48e95fb 100644 --- a/recipes/bench-ticket/cloudflare/worker.ts +++ b/recipes/bench-ticket/cloudflare/worker.ts @@ -25,15 +25,23 @@ export interface BenchTicketEnv { readonly BENCH_TICKET_ORIGIN: string; } -let cached: ReturnType | undefined; -let cachedOrigin: string | undefined; +let cached: + | { + readonly key: string; + readonly composition: ReturnType; + } + | undefined; + +function compositionCacheKey(env: BenchTicketEnv): string { + return `${env.BENCH_TICKET_ORIGIN}\n${env.BENCH_TICKET_EMAIL_CODE_SECRET_BASE64}`; +} function compositionFor(env: BenchTicketEnv) { - if (cached && cachedOrigin === env.BENCH_TICKET_ORIGIN) { - return cached; + const key = compositionCacheKey(env); + if (cached && cached.key === key) { + return cached.composition; } - cachedOrigin = env.BENCH_TICKET_ORIGIN; - cached = createBenchTicketComposition({ + const composition = createBenchTicketComposition({ store: createCloudflareD1Store({ database: env.BENCH_TICKET_DB, createSchemaIfMissing: true, @@ -46,7 +54,8 @@ function compositionFor(env: BenchTicketEnv) { renderer: createBenchTicketMailRenderer(), }, }); - return cached; + cached = { key, composition }; + return composition; } export default { diff --git a/recipes/bench-ticket/handler.test.ts b/recipes/bench-ticket/handler.test.ts index 0f34e3d..d136917 100644 --- a/recipes/bench-ticket/handler.test.ts +++ b/recipes/bench-ticket/handler.test.ts @@ -140,4 +140,81 @@ describe('Bench Ticket HTTP host', () => { const view = (await replied.json()) as { messages: unknown[] }; expect(view.messages.length).toBeGreaterThan(1); }); + + it('renders ticket subjects with textContent, not innerHTML', async () => { + const composition = createBenchTicketComposition({ + store: createMemoryStore(), + origin: ORIGIN, + emailCodeSecretBase64: TEST_SECRET, + mailDelivery: recordingMail(), + clock: fixedClock('2026-09-11T12:00:00.000Z'), + }); + const home = await handleBenchTicketRequest( + new Request(`${ORIGIN}/`), + composition, + ); + const html = await home.text(); + expect(html).not.toMatch(/innerHTML/); + expect(html).toContain('title.textContent'); + expect(html).toContain('status.textContent'); + expect(html).toContain('dataset.reply'); + }); + + it('treats a malformed session cookie as unauthenticated, not 500', async () => { + const composition = createBenchTicketComposition({ + store: createMemoryStore(), + origin: ORIGIN, + emailCodeSecretBase64: TEST_SECRET, + mailDelivery: recordingMail(), + clock: fixedClock('2026-09-11T12:00:00.000Z'), + }); + const me = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/me`, { + headers: { cookie: `${SESSION_COOKIE}=%ZZ` }, + }), + composition, + ); + expect(me.status).toBe(401); + expect(await me.json()).toEqual({ error: 'unauthenticated' }); + }); + + it('refuses a malformed ticket id with 400, not 500', async () => { + const mail = recordingMail(); + const composition = createBenchTicketComposition({ + store: createMemoryStore(), + origin: ORIGIN, + emailCodeSecretBase64: TEST_SECRET, + mailDelivery: mail, + clock: fixedClock('2026-09-11T12:00:00.000Z'), + }); + const begin = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/auth/begin`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'member@bench.example', flow: 'create' }), + }), + composition, + ); + const started = (await begin.json()) as { codeHandle: string }; + const codeMatch = /Your Bench Ticket code is (\d{8})/.exec(mail.sent[0]?.subject ?? ''); + const finish = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/auth/finish`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + flow: 'create', + codeHandle: started.codeHandle, + code: codeMatch?.[1], + }), + }), + composition, + ); + const cookie = cookieFrom(finish); + const view = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/tickets/%ZZ`, { headers: { cookie } }), + composition, + ); + expect(view.status).toBe(400); + expect(await view.json()).toEqual({ error: 'invalid_ticket_id' }); + }); }); diff --git a/recipes/bench-ticket/handler.ts b/recipes/bench-ticket/handler.ts index 7514f9f..eddf200 100644 --- a/recipes/bench-ticket/handler.ts +++ b/recipes/bench-ticket/handler.ts @@ -90,14 +90,26 @@ const PAGE_HTML = ` document.getElementById('who').textContent = me.principalId; const listed = await api('/api/tickets'); const root = document.getElementById('tickets'); - root.innerHTML = ''; + root.replaceChildren(); for (const row of listed.tickets) { const el = document.createElement('div'); el.className = 'ticket'; - el.innerHTML = '#' + row.number + ' ' + row.subject + - ' ' + row.status + '' + - '
' + - '
'; + const title = document.createElement('strong'); + title.textContent = '#' + row.number; + const subject = document.createTextNode(' ' + row.subject + ' '); + const status = document.createElement('span'); + status.className = 'muted'; + status.textContent = String(row.status); + const replyWrap = document.createElement('div'); + const textarea = document.createElement('textarea'); + textarea.dataset.reply = String(row.id); + textarea.placeholder = 'Reply'; + const button = document.createElement('button'); + button.type = 'button'; + button.dataset.send = String(row.id); + button.textContent = 'Reply'; + replyWrap.append(textarea, button); + el.append(title, subject, status, replyWrap); root.appendChild(el); } root.onclick = async (event) => { @@ -185,6 +197,14 @@ function json( }); } +function decodeUriComponentSafe(value: string): string | null { + try { + return decodeURIComponent(value); + } catch { + return null; + } +} + function parseCookies(header: string | null): Record { const out: Record = {}; if (!header) return out; @@ -193,7 +213,10 @@ function parseCookies(header: string | null): Record { if (idx < 0) continue; const key = part.slice(0, idx).trim(); const value = part.slice(idx + 1).trim(); - if (key.length > 0) out[key] = decodeURIComponent(value); + if (key.length === 0) continue; + const decoded = decodeUriComponentSafe(value); + if (decoded === null) continue; + out[key] = decoded; } return out; } @@ -373,9 +396,11 @@ export async function handleBenchTicketRequest( if (method === 'GET' && ticketMatch) { const principalId = await currentPrincipal(request, composition); if (!principalId) return json(401, { error: 'unauthenticated' }); + const ticketId = decodeUriComponentSafe(ticketMatch[1] ?? ''); + if (ticketId === null) return json(400, { error: 'invalid_ticket_id' }); const view = await composition.support.readCustomerTicket( composition.customerAccess(principalId), - decodeURIComponent(ticketMatch[1] ?? ''), + ticketId, ); return json(200, view); } @@ -384,13 +409,15 @@ export async function handleBenchTicketRequest( if (method === 'POST' && replyMatch) { const principalId = await currentPrincipal(request, composition); if (!principalId) return json(401, { error: 'unauthenticated' }); + const ticketId = decodeUriComponentSafe(replyMatch[1] ?? ''); + if (ticketId === null) return json(400, { error: 'invalid_ticket_id' }); const body = await readJson(request); const replied = await composition.support.replyToCustomerTicket( composition.customerAccess(principalId), { commandId: mintId(), correlationId: mintId(), - ticketId: decodeURIComponent(replyMatch[1] ?? ''), + ticketId, messageId: mintId(), body: String(body.body ?? ''), }, diff --git a/recipes/bench-ticket/host.test.ts b/recipes/bench-ticket/host.test.ts new file mode 100644 index 0000000..3ba4966 --- /dev/null +++ b/recipes/bench-ticket/host.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest'; +import { joinIncomingHeader } from './host'; + +describe('Node incoming headers', () => { + it('joins Cookie arrays with "; "', () => { + expect(joinIncomingHeader('cookie', ['a=1', 'b=2'])).toBe('a=1; b=2'); + expect(joinIncomingHeader('Cookie', ['bench_ticket_session=abc', 'other=1'])).toBe( + 'bench_ticket_session=abc; other=1', + ); + }); + + it('joins other multi-value headers with ", "', () => { + expect(joinIncomingHeader('accept', ['text/html', 'application/json'])).toBe( + 'text/html, application/json', + ); + }); + + it('leaves a single header value unchanged', () => { + expect(joinIncomingHeader('cookie', 'a=1')).toBe('a=1'); + }); +}); diff --git a/recipes/bench-ticket/host.ts b/recipes/bench-ticket/host.ts index bdaf88e..9e8720b 100644 --- a/recipes/bench-ticket/host.ts +++ b/recipes/bench-ticket/host.ts @@ -67,6 +67,15 @@ export function createBenchTicketNodeHandler() { }; } +/** Cookie headers must join with `; `; other multi-value headers use `, `. */ +export function joinIncomingHeader( + name: string, + value: string | readonly string[], +): string { + if (typeof value === 'string') return value; + return name.toLowerCase() === 'cookie' ? value.join('; ') : value.join(', '); +} + async function requestFromNode( req: IncomingMessage, origin: string, @@ -75,8 +84,7 @@ async function requestFromNode( const headers = new Headers(); for (const [name, value] of Object.entries(req.headers)) { if (value === undefined) continue; - if (Array.isArray(value)) headers.set(name, value.join(', ')); - else headers.set(name, value); + headers.set(name, joinIncomingHeader(name, value)); } const method = req.method ?? 'GET'; if (method === 'GET' || method === 'HEAD') { From 7020b0e727c30933dc14846b27b4178ad93f1853 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 18:42:42 +0000 Subject: [PATCH 4/8] Map queue capacity to 503 and stop shipping HMAC as plaintext env. Map SupportDeskQueueCapacityError like the production host, reject a NaN Mailpit SMTP port before connect, and inject the Azure/AWS email-code secret through platform secret refs instead of plaintext container env. Co-authored-by: Fly Over Coder --- recipes/bench-ticket/handler.test.ts | 47 ++++++++++++++++++++++++++++ recipes/bench-ticket/handler.ts | 4 +++ recipes/bench-ticket/host.test.ts | 37 +++++++++++++++++++++- recipes/bench-ticket/host.ts | 10 +++++- recipes/bench-ticket/mail-smtp.ts | 3 ++ src/pages/runbooks/aws.md | 30 ++++++++++++------ src/pages/runbooks/azure.md | 8 +++-- 7 files changed, 126 insertions(+), 13 deletions(-) diff --git a/recipes/bench-ticket/handler.test.ts b/recipes/bench-ticket/handler.test.ts index d136917..f70fe36 100644 --- a/recipes/bench-ticket/handler.test.ts +++ b/recipes/bench-ticket/handler.test.ts @@ -1,5 +1,6 @@ import { fixedClock } from '@pegma/spine'; import { createMemoryStore } from '@pegma/storage-core'; +import { SupportDeskQueueCapacityError } from '@pegma/support-desk-application'; import { describe, expect, it } from 'vitest'; import { BENCH_TICKET, @@ -217,4 +218,50 @@ describe('Bench Ticket HTTP host', () => { expect(view.status).toBe(400); expect(await view.json()).toEqual({ error: 'invalid_ticket_id' }); }); + + it('maps SupportDeskQueueCapacityError to 503, not 500', async () => { + const mail = recordingMail(); + const composition = createBenchTicketComposition({ + store: createMemoryStore(), + origin: ORIGIN, + emailCodeSecretBase64: TEST_SECRET, + mailDelivery: mail, + clock: fixedClock('2026-09-11T12:00:00.000Z'), + }); + const begin = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/auth/begin`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'member@bench.example', flow: 'create' }), + }), + composition, + ); + const started = (await begin.json()) as { codeHandle: string }; + const codeMatch = /Your Bench Ticket code is (\d{8})/.exec(mail.sent[0]?.subject ?? ''); + const finish = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/auth/finish`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + flow: 'create', + codeHandle: started.codeHandle, + code: codeMatch?.[1], + }), + }), + composition, + ); + const cookie = cookieFrom(finish); + const support = composition.support as unknown as { + listCustomerTickets: () => Promise; + }; + support.listCustomerTickets = async () => { + throw new SupportDeskQueueCapacityError('physical_rows', 1); + }; + const listed = await handleBenchTicketRequest( + new Request(`${ORIGIN}/api/tickets`, { headers: { cookie } }), + composition, + ); + expect(listed.status).toBe(503); + expect(await listed.json()).toEqual({ error: 'queue_unavailable' }); + }); }); diff --git a/recipes/bench-ticket/handler.ts b/recipes/bench-ticket/handler.ts index eddf200..c32e714 100644 --- a/recipes/bench-ticket/handler.ts +++ b/recipes/bench-ticket/handler.ts @@ -8,6 +8,7 @@ import { SupportDeskConflictError, SupportDeskLimitError, SupportDeskNotFoundError, + SupportDeskQueueCapacityError, } from '@pegma/support-desk-application'; import type { PrincipalId } from '@pegma/spine'; import { @@ -266,6 +267,9 @@ function mapError(error: unknown): Response { if (error instanceof SupportDeskConflictError) { return json(409, { error: 'conflict' }); } + if (error instanceof SupportDeskQueueCapacityError) { + return json(503, { error: 'queue_unavailable' }); + } if (error instanceof SupportDeskLimitError) { return json(413, { error: 'limit_exceeded' }); } diff --git a/recipes/bench-ticket/host.test.ts b/recipes/bench-ticket/host.test.ts index 3ba4966..18733b4 100644 --- a/recipes/bench-ticket/host.test.ts +++ b/recipes/bench-ticket/host.test.ts @@ -1,5 +1,40 @@ import { describe, expect, it } from 'vitest'; -import { joinIncomingHeader } from './host'; +import { joinIncomingHeader, parseMailpitSmtpPort } from './host'; +import { createMailpitSmtpProvider } from './mail-smtp'; + +describe('Node incoming headers', () => { + it('joins Cookie arrays with "; "', () => { + expect(joinIncomingHeader('cookie', ['a=1', 'b=2'])).toBe('a=1; b=2'); + expect(joinIncomingHeader('Cookie', ['bench_ticket_session=abc', 'other=1'])).toBe( + 'bench_ticket_session=abc; other=1', + ); + }); + + it('joins other multi-value headers with ", "', () => { + expect(joinIncomingHeader('accept', ['text/html', 'application/json'])).toBe( + 'text/html, application/json', + ); + }); + + it('leaves a single header value unchanged', () => { + expect(joinIncomingHeader('cookie', 'a=1')).toBe('a=1'); + }); +}); + +describe('Mailpit SMTP port', () => { + it('defaults to 1025 and accepts a valid integer', () => { + expect(parseMailpitSmtpPort(undefined)).toBe(1025); + expect(parseMailpitSmtpPort('1025')).toBe(1025); + }); + + it('refuses NaN and out-of-range values before connect', () => { + expect(() => parseMailpitSmtpPort('notanumber')).toThrow(/MAILPIT_SMTP_PORT/); + expect(() => parseMailpitSmtpPort('0')).toThrow(/MAILPIT_SMTP_PORT/); + expect(() => createMailpitSmtpProvider({ host: '127.0.0.1', port: Number.NaN, from: 'x@y' })).toThrow( + /Mailpit SMTP port/, + ); + }); +}); describe('Node incoming headers', () => { it('joins Cookie arrays with "; "', () => { diff --git a/recipes/bench-ticket/host.ts b/recipes/bench-ticket/host.ts index 9e8720b..57ce231 100644 --- a/recipes/bench-ticket/host.ts +++ b/recipes/bench-ticket/host.ts @@ -28,6 +28,14 @@ function requiredEnv(name: string): string { return value; } +export function parseMailpitSmtpPort(raw: string | undefined): number { + const parsed = Number.parseInt(raw ?? '1025', 10); + if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) { + throw new Error('MAILPIT_SMTP_PORT must be an integer 1–65535'); + } + return parsed; +} + function mailDelivery() { const renderer = createBenchTicketMailRenderer(); const reconciliation = createCatcherReconciliation(); @@ -42,7 +50,7 @@ function mailDelivery() { return { provider: createMailpitSmtpProvider({ host: process.env.MAILPIT_SMTP_HOST ?? '127.0.0.1', - port: Number.parseInt(process.env.MAILPIT_SMTP_PORT ?? '1025', 10), + port: parseMailpitSmtpPort(process.env.MAILPIT_SMTP_PORT), from: process.env.BENCH_TICKET_EMAIL_FROM ?? 'bench-ticket@localhost', }), reconciliation, diff --git a/recipes/bench-ticket/mail-smtp.ts b/recipes/bench-ticket/mail-smtp.ts index fd142b0..230fb45 100644 --- a/recipes/bench-ticket/mail-smtp.ts +++ b/recipes/bench-ticket/mail-smtp.ts @@ -73,6 +73,9 @@ function smtpDialog( export function createMailpitSmtpProvider( options: MailpitSmtpOptions, ): MailProvider { + if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) { + throw new Error('Mailpit SMTP port must be an integer 1–65535'); + } return { async send(request) { const subject = headerSafe(request.mail.subject); diff --git a/src/pages/runbooks/aws.md b/src/pages/runbooks/aws.md index 94ba437..7b8de05 100644 --- a/src/pages/runbooks/aws.md +++ b/src/pages/runbooks/aws.md @@ -48,7 +48,7 @@ pnpm install --frozen-lockfile | DynamoDB table | `bench-ticket` (every Storage Core collection shares one table) | | S3 bucket | `bench-ticket-blobs-` (globally unique) | | App Runner / container service | `bench-ticket` | -| Email-code secret | `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | +| Email-code secret | Secrets Manager `bench-ticket/email-code-hmac`, injected as runtime secret `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | The adapter README’s table schema is `pk` (HASH) + `sk` (RANGE), on-demand billing. Mirror Azure: **one table for every collection**, not one table per collection. @@ -130,20 +130,27 @@ aws ecr get-login-password --region "$REGION" \ | docker login --username AWS --password-stdin "$ECR" docker build -f recipes/bench-ticket/Dockerfile -t "$ECR/bench-ticket:local" . docker push "$ECR/bench-ticket:local" + +aws secretsmanager create-secret \ + --name bench-ticket/email-code-hmac \ + --secret-string "$SECRET" \ + --region "$REGION" ``` Create an App Runner service (or ECS/Fargate) with: -| Env var | Value | +| Name | Value | | --- | --- | -| `PORT` | `8787` | -| `BENCH_TICKET_MAIL_CATCHER` | `console` | -| `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | `$SECRET` | -| `BENCH_TICKET_TABLE` | `bench-ticket` | -| `AWS_REGION` | `us-east-1` | -| `BENCH_TICKET_ORIGIN` | `https://` (set after first URL exists, then redeploy) | +| `PORT` | `8787` (plaintext env) | +| `BENCH_TICKET_MAIL_CATCHER` | `console` (plaintext env) | +| `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | **runtime secret** from Secrets Manager `bench-ticket/email-code-hmac` — not a plaintext env var | +| `BENCH_TICKET_TABLE` | `bench-ticket` (plaintext env) | +| `AWS_REGION` | `us-east-1` (plaintext env) | +| `BENCH_TICKET_ORIGIN` | `https://` (plaintext env; set after first URL exists, then redeploy) | + +The process still reads `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` from its environment at runtime. Inject that name from Secrets Manager / SSM (App Runner runtime environment secrets, or an ECS `secrets` entry). Do not put `$SECRET` in `RuntimeEnvironmentVariables` or a task-definition `environment` block — `DescribeService` and `describe-task-definition` return those values. -Give the task role DynamoDB access to table `bench-ticket` and `s3:GetObject`/`PutObject` on the blob bucket. Do not put AWS keys in the image. +Give the task role DynamoDB access to table `bench-ticket`, `s3:GetObject`/`PutObject` on the blob bucket, and `secretsmanager:GetSecretValue` on `bench-ticket/email-code-hmac`. Do not put AWS keys in the image. ## 6. Verify @@ -166,6 +173,7 @@ Follow logs with the platform’s tail (`aws logs tail … --follow` or App Runn | `ResourceNotFoundException` | `aws dynamodb describe-table --table-name bench-ticket`. Recreate using `pk` HASH + `sk` RANGE. | | Health 503 / storage fail | IAM: the task role needs DynamoDB on that table. `aws dynamodb scan --table-name bench-ticket --max-items 1`. | | Origin invalid / finish 400 | `BENCH_TICKET_ORIGIN` must be the public HTTPS origin with no path. | +| HMAC printed by `DescribeService` / task definition | Recreate it as a Secrets Manager runtime secret (`bench-ticket/email-code-hmac`). Do not put the value in plaintext env vars. | | No code in logs | Tail logs **before** begin. `BENCH_TICKET_MAIL_CATCHER=console`. | | Temptation to use Cognito | Stop. This demo is `@pegma/identity` email-code only. | @@ -175,6 +183,10 @@ Follow logs with the platform’s tail (`aws logs tail … --follow` or App Runn aws dynamodb delete-table --table-name bench-ticket --region us-east-1 aws s3 rb "s3://bench-ticket-blobs-${ACCOUNT}" --force aws ecr delete-repository --repository-name bench-ticket --force --region us-east-1 +aws secretsmanager delete-secret \ + --secret-id bench-ticket/email-code-hmac \ + --force-delete-without-recovery \ + --region us-east-1 # plus delete the App Runner / ECS service rm -f /tmp/bench-ticket.cookies ``` diff --git a/src/pages/runbooks/azure.md b/src/pages/runbooks/azure.md index a2c04fd..f6a3100 100644 --- a/src/pages/runbooks/azure.md +++ b/src/pages/runbooks/azure.md @@ -40,7 +40,7 @@ pnpm install --frozen-lockfile | Blob container | `bench-ticket-blobs` | | Container Apps env | `cae-bench-ticket` | | Container app | `ca-bench-ticket` | -| Email-code secret | `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | +| Email-code secret | Container App **secret** `email-code-hmac`, injected as `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | ## 3. Create Azure resources @@ -104,6 +104,8 @@ docker push "$IMAGE" az containerapp env create -g rg-bench-ticket -n cae-bench-ticket -l eastus # First create without origin, then set origin from the assigned FQDN. +# The HMAC is a Container Apps secret (`secretref:`), not a plaintext env +# var — `az containerapp show` must not print it. az containerapp create \ -g rg-bench-ticket \ -n ca-bench-ticket \ @@ -112,9 +114,10 @@ az containerapp create \ --ingress external \ --target-port 8787 \ --registry-server "${ACR}.azurecr.io" \ + --secrets "email-code-hmac=$SECRET" \ --env-vars \ BENCH_TICKET_MAIL_CATCHER=console \ - BENCH_TICKET_EMAIL_CODE_SECRET_BASE64="$SECRET" \ + BENCH_TICKET_EMAIL_CODE_SECRET_BASE64=secretref:email-code-hmac \ AZURE_STORAGE_ACCOUNT="$ACCOUNT" \ AZURE_STORAGE_ACCOUNT_KEY="$KEY" \ PORT=8787 @@ -151,6 +154,7 @@ Then the same begin / copy 8-digit code from logs / finish / file ticket / reply | `TableNotFound` | `az storage table create --name pegma --connection-string "$CONN"` | | Health 503 / storage fail | Confirm `AZURE_STORAGE_ACCOUNT` / `AZURE_STORAGE_ACCOUNT_KEY` on the container app: `az containerapp show -g rg-bench-ticket -n ca-bench-ticket`. | | Origin invalid / finish 400 | `BENCH_TICKET_ORIGIN` must be `https://` with no path. `az containerapp update … --set-env-vars BENCH_TICKET_ORIGIN=…` | +| HMAC printed by `az containerapp show` | Recreate it as `--secrets email-code-hmac=…` and `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64=secretref:email-code-hmac`. Do not put the value in `--env-vars`. | | No code in logs | `az containerapp logs show … --follow` **before** calling begin. `BENCH_TICKET_MAIL_CATCHER` must be `console`. | | Building image fails on `tsx` | Image must `pnpm install` **before** `NODE_ENV=production` (the checked-in Dockerfile already does). | From 2c6aa9c9a094f3402cf1cc21aef27a1b4dc08f88 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 18:47:50 +0000 Subject: [PATCH 5/8] Exercise the Bench Ticket Cloudflare Worker on the existing D1 test pool. Health and email-code begin now run through worker.ts against Miniflare D1, which also pins composition reuse until the email-code secret rotates. Co-authored-by: Fly Over Coder --- package.json | 4 +- recipes/bench-ticket/README.md | 2 +- .../bench-ticket/cloudflare/worker.d1.test.ts | 54 +++++++++++++++++++ recipes/bench-ticket/cloudflare/worker.ts | 4 +- recipes/tsconfig.json | 3 +- vitest.bench-ticket.config.ts | 23 ++++++++ 6 files changed, 84 insertions(+), 6 deletions(-) create mode 100644 recipes/bench-ticket/cloudflare/worker.d1.test.ts create mode 100644 vitest.bench-ticket.config.ts diff --git a/package.json b/package.json index b02b136..2a186c0 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,9 @@ "dev": "astro dev", "build": "astro build", "check": "astro check && tsc -p worker/tsconfig.json --noEmit && tsc -p recipes/tsconfig.json --noEmit", - "test": "vitest run --config vitest.config.ts && vitest run --config vitest.d1.config.ts", + "test": "vitest run --config vitest.config.ts && vitest run --config vitest.d1.config.ts && vitest run --config vitest.bench-ticket.config.ts", "test:node": "vitest run --config vitest.config.ts", - "test:d1": "vitest run --config vitest.d1.config.ts", + "test:d1": "vitest run --config vitest.d1.config.ts && vitest run --config vitest.bench-ticket.config.ts", "eval:assembly": "vitest run --config vitest.config.ts evals/assembly-eval.test.ts", "preview": "astro preview", "demo:bench-ticket": "tsx recipes/bench-ticket/host.ts", diff --git a/recipes/bench-ticket/README.md b/recipes/bench-ticket/README.md index fdf5ef5..b7a6c35 100644 --- a/recipes/bench-ticket/README.md +++ b/recipes/bench-ticket/README.md @@ -4,7 +4,7 @@ Synthetic makerspace helpdesk used by the public environment runbooks. - Composition: [`composition.ts`](./composition.ts) (CI-tested) - HTTP host: [`handler.ts`](./handler.ts) + Node [`host.ts`](./host.ts) -- Cloudflare Worker: [`cloudflare/`](./cloudflare/) +- Cloudflare Worker: [`cloudflare/`](./cloudflare/) (CI-tested with the existing `@cloudflare/vitest-pool-workers` D1 pool) - Local Docker: [`docker-compose.yml`](./docker-compose.yml) Follow the runbooks on the site, not this file: diff --git a/recipes/bench-ticket/cloudflare/worker.d1.test.ts b/recipes/bench-ticket/cloudflare/worker.d1.test.ts new file mode 100644 index 0000000..4bfe02f --- /dev/null +++ b/recipes/bench-ticket/cloudflare/worker.d1.test.ts @@ -0,0 +1,54 @@ +import { env } from 'cloudflare:workers'; +import { describe, expect, it } from 'vitest'; +import worker, { compositionFor, type BenchTicketEnv } from './worker'; + +declare global { + namespace Cloudflare { + interface Env { + BENCH_TICKET_DB: D1Database; + BENCH_TICKET_EMAIL_CODE_SECRET_BASE64: string; + BENCH_TICKET_ORIGIN: string; + } + } +} + +function benchEnv(): BenchTicketEnv { + return env as BenchTicketEnv; +} + +describe('Bench Ticket Cloudflare Worker', () => { + it('creates D1 schema on first health and reuses composition until the secret rotates', async () => { + const origin = env.BENCH_TICKET_ORIGIN; + const health = await worker.fetch(new Request(`${origin}/health`), benchEnv()); + expect(health.status).toBe(200); + const body = (await health.json()) as { ok: boolean; service: string }; + expect(body.ok).toBe(true); + expect(body.service).toBe('bench-ticket'); + + const first = compositionFor(benchEnv()); + expect(compositionFor(benchEnv())).toBe(first); + + const rotated = compositionFor({ + ...benchEnv(), + BENCH_TICKET_EMAIL_CODE_SECRET_BASE64: btoa( + String.fromCharCode(...new Uint8Array(32).fill(12)), + ), + }); + expect(rotated).not.toBe(first); + }); + + it('accepts email-code begin on the Worker entry', async () => { + const origin = env.BENCH_TICKET_ORIGIN; + const begin = await worker.fetch( + new Request(`${origin}/api/auth/begin`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'member@bench.example', flow: 'create' }), + }), + benchEnv(), + ); + expect(begin.status).toBe(200); + const started = (await begin.json()) as { codeHandle: string }; + expect(started.codeHandle.length).toBeGreaterThan(0); + }); +}); diff --git a/recipes/bench-ticket/cloudflare/worker.ts b/recipes/bench-ticket/cloudflare/worker.ts index 48e95fb..43a58d2 100644 --- a/recipes/bench-ticket/cloudflare/worker.ts +++ b/recipes/bench-ticket/cloudflare/worker.ts @@ -32,11 +32,11 @@ let cached: } | undefined; -function compositionCacheKey(env: BenchTicketEnv): string { +export function compositionCacheKey(env: BenchTicketEnv): string { return `${env.BENCH_TICKET_ORIGIN}\n${env.BENCH_TICKET_EMAIL_CODE_SECRET_BASE64}`; } -function compositionFor(env: BenchTicketEnv) { +export function compositionFor(env: BenchTicketEnv) { const key = compositionCacheKey(env); if (cached && cached.key === key) { return cached.composition; diff --git a/recipes/tsconfig.json b/recipes/tsconfig.json index d7c2677..3ebc016 100644 --- a/recipes/tsconfig.json +++ b/recipes/tsconfig.json @@ -11,5 +11,6 @@ "isolatedModules": true, "types": ["node"] }, - "include": ["./**/*.ts"] + "include": ["./**/*.ts"], + "exclude": ["**/*.d1.test.ts"] } diff --git a/vitest.bench-ticket.config.ts b/vitest.bench-ticket.config.ts new file mode 100644 index 0000000..f05809c --- /dev/null +++ b/vitest.bench-ticket.config.ts @@ -0,0 +1,23 @@ +import { cloudflareTest } from '@cloudflare/vitest-pool-workers'; +import { defineConfig } from 'vitest/config'; + +/** Same pool as `vitest.d1.config.ts`, pointed at the Bench Ticket Worker. */ +const TEST_SECRET = btoa(String.fromCharCode(...new Uint8Array(32).fill(11))); + +export default defineConfig({ + plugins: [ + cloudflareTest({ + wrangler: { configPath: './recipes/bench-ticket/cloudflare/wrangler.jsonc' }, + miniflare: { + bindings: { + BENCH_TICKET_EMAIL_CODE_SECRET_BASE64: TEST_SECRET, + BENCH_TICKET_ORIGIN: 'https://bench-ticket.example.workers.dev', + }, + }, + }), + ], + test: { + include: ['recipes/bench-ticket/cloudflare/**/*.d1.test.ts'], + testTimeout: 30_000, + }, +}); From 425d5dee01afa9d2bdae07d6d23575b0bf4b55a3 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 18:55:12 +0000 Subject: [PATCH 6/8] Drop the duplicate Node header tests and clarify Azure HMAC secretref. The SMTP-port commit copied the incoming-header describe block. Azure still injects the HMAC via --secrets plus secretref; GET returns the name, not the value. Co-authored-by: Fly Over Coder --- recipes/bench-ticket/host.test.ts | 19 ------------------- src/pages/runbooks/azure.md | 5 +++-- 2 files changed, 3 insertions(+), 21 deletions(-) diff --git a/recipes/bench-ticket/host.test.ts b/recipes/bench-ticket/host.test.ts index 18733b4..d5cf80e 100644 --- a/recipes/bench-ticket/host.test.ts +++ b/recipes/bench-ticket/host.test.ts @@ -35,22 +35,3 @@ describe('Mailpit SMTP port', () => { ); }); }); - -describe('Node incoming headers', () => { - it('joins Cookie arrays with "; "', () => { - expect(joinIncomingHeader('cookie', ['a=1', 'b=2'])).toBe('a=1; b=2'); - expect(joinIncomingHeader('Cookie', ['bench_ticket_session=abc', 'other=1'])).toBe( - 'bench_ticket_session=abc; other=1', - ); - }); - - it('joins other multi-value headers with ", "', () => { - expect(joinIncomingHeader('accept', ['text/html', 'application/json'])).toBe( - 'text/html, application/json', - ); - }); - - it('leaves a single header value unchanged', () => { - expect(joinIncomingHeader('cookie', 'a=1')).toBe('a=1'); - }); -}); diff --git a/src/pages/runbooks/azure.md b/src/pages/runbooks/azure.md index f6a3100..3a4e7ec 100644 --- a/src/pages/runbooks/azure.md +++ b/src/pages/runbooks/azure.md @@ -104,8 +104,9 @@ docker push "$IMAGE" az containerapp env create -g rg-bench-ticket -n cae-bench-ticket -l eastus # First create without origin, then set origin from the assigned FQDN. -# The HMAC is a Container Apps secret (`secretref:`), not a plaintext env -# var — `az containerapp show` must not print it. +# HMAC is a Container Apps secret, not a plaintext env var: +# `--secrets email-code-hmac=…` plus `secretref:email-code-hmac`. +# `az containerapp show` returns the secret *name* and `secretRef`, not the value. az containerapp create \ -g rg-bench-ticket \ -n ca-bench-ticket \ From 7137420436a90cdc9d1200de3b3fbc673ad070b1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 19:08:38 +0000 Subject: [PATCH 7/8] Name App Runner RuntimeEnvironmentSecrets in the AWS runbook. App Runner injects Secrets Manager via ImageConfiguration.RuntimeEnvironmentSecrets, not RuntimeEnvironmentVariables. Keep the HMAC out of plaintext env. Co-authored-by: Fly Over Coder --- src/pages/runbooks/aws.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pages/runbooks/aws.md b/src/pages/runbooks/aws.md index 7b8de05..7b9c856 100644 --- a/src/pages/runbooks/aws.md +++ b/src/pages/runbooks/aws.md @@ -48,7 +48,7 @@ pnpm install --frozen-lockfile | DynamoDB table | `bench-ticket` (every Storage Core collection shares one table) | | S3 bucket | `bench-ticket-blobs-` (globally unique) | | App Runner / container service | `bench-ticket` | -| Email-code secret | Secrets Manager `bench-ticket/email-code-hmac`, injected as runtime secret `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | +| Email-code secret | Secrets Manager `bench-ticket/email-code-hmac`, injected via App Runner `RuntimeEnvironmentSecrets` (or ECS `secrets`) as `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | The adapter README’s table schema is `pk` (HASH) + `sk` (RANGE), on-demand billing. Mirror Azure: **one table for every collection**, not one table per collection. @@ -143,14 +143,14 @@ Create an App Runner service (or ECS/Fargate) with: | --- | --- | | `PORT` | `8787` (plaintext env) | | `BENCH_TICKET_MAIL_CATCHER` | `console` (plaintext env) | -| `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | **runtime secret** from Secrets Manager `bench-ticket/email-code-hmac` — not a plaintext env var | +| `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | **`RuntimeEnvironmentSecrets`** from Secrets Manager `bench-ticket/email-code-hmac` (ARN as the map value) — not `RuntimeEnvironmentVariables` | | `BENCH_TICKET_TABLE` | `bench-ticket` (plaintext env) | | `AWS_REGION` | `us-east-1` (plaintext env) | | `BENCH_TICKET_ORIGIN` | `https://` (plaintext env; set after first URL exists, then redeploy) | -The process still reads `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` from its environment at runtime. Inject that name from Secrets Manager / SSM (App Runner runtime environment secrets, or an ECS `secrets` entry). Do not put `$SECRET` in `RuntimeEnvironmentVariables` or a task-definition `environment` block — `DescribeService` and `describe-task-definition` return those values. +The process still reads `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` from its environment at runtime. On App Runner, put the Secrets Manager ARN in `ImageConfiguration.RuntimeEnvironmentSecrets` (API field; CLI: nested under `--source-configuration` / `--cli-input-json`). That map is distinct from `RuntimeEnvironmentVariables`. On ECS/Fargate, use a task-definition `secrets` entry. Do not put `$SECRET` in `RuntimeEnvironmentVariables` or a task-definition `environment` block — `DescribeService` and `describe-task-definition` return those values. -Give the task role DynamoDB access to table `bench-ticket`, `s3:GetObject`/`PutObject` on the blob bucket, and `secretsmanager:GetSecretValue` on `bench-ticket/email-code-hmac`. Do not put AWS keys in the image. +Give the App Runner instance role (or ECS task role) DynamoDB access to table `bench-ticket`, `s3:GetObject`/`PutObject` on the blob bucket, and `secretsmanager:GetSecretValue` on `bench-ticket/email-code-hmac`. Do not put AWS keys in the image. ## 6. Verify @@ -173,7 +173,7 @@ Follow logs with the platform’s tail (`aws logs tail … --follow` or App Runn | `ResourceNotFoundException` | `aws dynamodb describe-table --table-name bench-ticket`. Recreate using `pk` HASH + `sk` RANGE. | | Health 503 / storage fail | IAM: the task role needs DynamoDB on that table. `aws dynamodb scan --table-name bench-ticket --max-items 1`. | | Origin invalid / finish 400 | `BENCH_TICKET_ORIGIN` must be the public HTTPS origin with no path. | -| HMAC printed by `DescribeService` / task definition | Recreate it as a Secrets Manager runtime secret (`bench-ticket/email-code-hmac`). Do not put the value in plaintext env vars. | +| HMAC printed by `DescribeService` / task definition | Recreate it as `RuntimeEnvironmentSecrets` (Secrets Manager ARN) or an ECS `secrets` entry. Do not put the value in `RuntimeEnvironmentVariables`. | | No code in logs | Tail logs **before** begin. `BENCH_TICKET_MAIL_CATCHER=console`. | | Temptation to use Cognito | Stop. This demo is `@pegma/identity` email-code only. | From 9c873602312eb1754712cfb186380173bbef6004 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 11 Sep 2026 19:13:17 +0000 Subject: [PATCH 8/8] Move the Azure storage account key onto secretref. Same Container Apps pattern as the email-code HMAC: --secrets storage-key plus AZURE_STORAGE_ACCOUNT_KEY=secretref:storage-key. az containerapp show then returns the name, not the key. Co-authored-by: Fly Over Coder --- src/pages/runbooks/azure.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/pages/runbooks/azure.md b/src/pages/runbooks/azure.md index 3a4e7ec..ff5b146 100644 --- a/src/pages/runbooks/azure.md +++ b/src/pages/runbooks/azure.md @@ -41,6 +41,7 @@ pnpm install --frozen-lockfile | Container Apps env | `cae-bench-ticket` | | Container app | `ca-bench-ticket` | | Email-code secret | Container App **secret** `email-code-hmac`, injected as `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64` | +| Storage account key | Container App **secret** `storage-key`, injected as `AZURE_STORAGE_ACCOUNT_KEY` | ## 3. Create Azure resources @@ -104,9 +105,9 @@ docker push "$IMAGE" az containerapp env create -g rg-bench-ticket -n cae-bench-ticket -l eastus # First create without origin, then set origin from the assigned FQDN. -# HMAC is a Container Apps secret, not a plaintext env var: -# `--secrets email-code-hmac=…` plus `secretref:email-code-hmac`. -# `az containerapp show` returns the secret *name* and `secretRef`, not the value. +# HMAC and the storage account key are Container Apps secrets, not plaintext env: +# `--secrets email-code-hmac=… storage-key=…` plus `secretref:`. +# `az containerapp show` returns the secret *name* and `secretRef`, not the values. az containerapp create \ -g rg-bench-ticket \ -n ca-bench-ticket \ @@ -115,12 +116,12 @@ az containerapp create \ --ingress external \ --target-port 8787 \ --registry-server "${ACR}.azurecr.io" \ - --secrets "email-code-hmac=$SECRET" \ + --secrets "email-code-hmac=$SECRET" "storage-key=$KEY" \ --env-vars \ BENCH_TICKET_MAIL_CATCHER=console \ BENCH_TICKET_EMAIL_CODE_SECRET_BASE64=secretref:email-code-hmac \ AZURE_STORAGE_ACCOUNT="$ACCOUNT" \ - AZURE_STORAGE_ACCOUNT_KEY="$KEY" \ + AZURE_STORAGE_ACCOUNT_KEY=secretref:storage-key \ PORT=8787 FQDN=$(az containerapp show -g rg-bench-ticket -n ca-bench-ticket --query properties.configuration.ingress.fqdn -o tsv) @@ -153,9 +154,9 @@ Then the same begin / copy 8-digit code from logs / finish / file ticket / reply | `az account show` fails | `az login` | | Storage account name taken | Add a longer suffix; Azure storage names are global and lowercase. | | `TableNotFound` | `az storage table create --name pegma --connection-string "$CONN"` | -| Health 503 / storage fail | Confirm `AZURE_STORAGE_ACCOUNT` / `AZURE_STORAGE_ACCOUNT_KEY` on the container app: `az containerapp show -g rg-bench-ticket -n ca-bench-ticket`. | +| Health 503 / storage fail | Confirm `AZURE_STORAGE_ACCOUNT` and that `AZURE_STORAGE_ACCOUNT_KEY` is `secretref:storage-key` (not the key value): `az containerapp show -g rg-bench-ticket -n ca-bench-ticket`. Re-list the key with `az storage account keys list` if you must recover it. | | Origin invalid / finish 400 | `BENCH_TICKET_ORIGIN` must be `https://` with no path. `az containerapp update … --set-env-vars BENCH_TICKET_ORIGIN=…` | -| HMAC printed by `az containerapp show` | Recreate it as `--secrets email-code-hmac=…` and `BENCH_TICKET_EMAIL_CODE_SECRET_BASE64=secretref:email-code-hmac`. Do not put the value in `--env-vars`. | +| HMAC or storage key printed by `az containerapp show` | Recreate them as `--secrets email-code-hmac=… storage-key=…` and `secretref:`. Do not put either value in `--env-vars`. | | No code in logs | `az containerapp logs show … --follow` **before** calling begin. `BENCH_TICKET_MAIL_CATCHER` must be `console`. | | Building image fails on `tsx` | Image must `pnpm install` **before** `NODE_ENV=production` (the checked-in Dockerfile already does). |