@pplethai/cli 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +12 -14
  2. package/dist/bin.js +109 -109
  3. package/package.json +3 -6
  4. package/templates/golden-path/.dev.vars.example +0 -33
  5. package/templates/golden-path/.env.example +0 -10
  6. package/templates/golden-path/.github/workflows/ci.yml +0 -22
  7. package/templates/golden-path/AGENTS.md +0 -1
  8. package/templates/golden-path/CLAUDE.md +0 -191
  9. package/templates/golden-path/README.md +0 -121
  10. package/templates/golden-path/gitignore +0 -17
  11. package/templates/golden-path/index.html +0 -16
  12. package/templates/golden-path/migrations/0001_init.sql +0 -10
  13. package/templates/golden-path/overlay-mtime.mjs +0 -30
  14. package/templates/golden-path/package-lock.json +0 -4318
  15. package/templates/golden-path/package.json +0 -41
  16. package/templates/golden-path/scripts/assert-dev-compiled-out.mjs +0 -45
  17. package/templates/golden-path/shared/api.ts +0 -325
  18. package/templates/golden-path/src/auth.ts +0 -230
  19. package/templates/golden-path/src/call-service.ts +0 -147
  20. package/templates/golden-path/src/dataset-query.ts +0 -470
  21. package/templates/golden-path/src/dataset-schema.ts +0 -398
  22. package/templates/golden-path/src/db.ts +0 -32
  23. package/templates/golden-path/src/dev-call-service.ts +0 -392
  24. package/templates/golden-path/src/dev-personas.ts +0 -186
  25. package/templates/golden-path/src/dev-read-dataset.ts +0 -444
  26. package/templates/golden-path/src/dev-registry.ts +0 -294
  27. package/templates/golden-path/src/email.ts +0 -49
  28. package/templates/golden-path/src/entry-name.ts +0 -114
  29. package/templates/golden-path/src/env.ts +0 -38
  30. package/templates/golden-path/src/files.ts +0 -38
  31. package/templates/golden-path/src/identity-header.ts +0 -17
  32. package/templates/golden-path/src/index.ts +0 -282
  33. package/templates/golden-path/src/legal-identity.ts +0 -180
  34. package/templates/golden-path/src/levels.ts +0 -132
  35. package/templates/golden-path/src/notification-response.ts +0 -55
  36. package/templates/golden-path/src/notify.ts +0 -311
  37. package/templates/golden-path/src/party-email.ts +0 -183
  38. package/templates/golden-path/src/payment.ts +0 -676
  39. package/templates/golden-path/src/read-dataset.ts +0 -490
  40. package/templates/golden-path/src/registry.ts +0 -128
  41. package/templates/golden-path/src/vite-env.d.ts +0 -27
  42. package/templates/golden-path/test/apply-migrations.ts +0 -4
  43. package/templates/golden-path/test/call-service.test.ts +0 -288
  44. package/templates/golden-path/test/dev-call-service.test.ts +0 -455
  45. package/templates/golden-path/test/dev-read-dataset.test.ts +0 -379
  46. package/templates/golden-path/test/dev-registry.test.ts +0 -404
  47. package/templates/golden-path/test/effective-sub.test.ts +0 -101
  48. package/templates/golden-path/test/email-offline.test.ts +0 -51
  49. package/templates/golden-path/test/email.test.ts +0 -117
  50. package/templates/golden-path/test/env.d.ts +0 -17
  51. package/templates/golden-path/test/fixtures/overlay/branch-list/entry.md +0 -85
  52. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/audience.json +0 -3
  53. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/named.json +0 -3
  54. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/offices.json +0 -6
  55. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/roster.json +0 -3
  56. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/summary.json +0 -1
  57. package/templates/golden-path/test/fixtures/overlay/catalog/entry.md +0 -8
  58. package/templates/golden-path/test/fixtures/overlay/catalog/mocks/responses.json +0 -7
  59. package/templates/golden-path/test/fixtures/overlay/election/2027/score/entry.md +0 -11
  60. package/templates/golden-path/test/fixtures/overlay/election/2027/score/mocks/responses.json +0 -7
  61. package/templates/golden-path/test/fixtures/overlay/election/results/entry.md +0 -24
  62. package/templates/golden-path/test/fixtures/overlay/election/results/mocks/turnout.json +0 -1
  63. package/templates/golden-path/test/fixtures/overlay/orders/entry.md +0 -12
  64. package/templates/golden-path/test/fixtures/overlay/orders/mocks/responses.json +0 -36
  65. package/templates/golden-path/test/fixtures/overlay/platform/email/entry.md +0 -12
  66. package/templates/golden-path/test/fixtures/overlay/platform/email/mocks/responses.json +0 -11
  67. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/entry.md +0 -8
  68. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/mocks/responses.json +0 -13
  69. package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +0 -12
  70. package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +0 -98
  71. package/templates/golden-path/test/fixtures/overlay/platform/sms/entry.md +0 -10
  72. package/templates/golden-path/test/fixtures/overlay/platform/sms/mocks/responses.json +0 -7
  73. package/templates/golden-path/test/fixtures/overlay/score/entry.md +0 -10
  74. package/templates/golden-path/test/fixtures/overlay/score/mocks/responses.json +0 -7
  75. package/templates/golden-path/test/harness.ts +0 -153
  76. package/templates/golden-path/test/interaction.test.ts +0 -230
  77. package/templates/golden-path/test/legal-identity.test.ts +0 -323
  78. package/templates/golden-path/test/membership.test.ts +0 -105
  79. package/templates/golden-path/test/notification-response.test.ts +0 -79
  80. package/templates/golden-path/test/payment-app.test.ts +0 -211
  81. package/templates/golden-path/test/payment-offline.test.ts +0 -91
  82. package/templates/golden-path/test/payment.test.ts +0 -518
  83. package/templates/golden-path/test/payments-offline.ts +0 -33
  84. package/templates/golden-path/test/read-dataset.test.ts +0 -387
  85. package/templates/golden-path/test/service-call.test.ts +0 -166
  86. package/templates/golden-path/test/smoke.test.ts +0 -464
  87. package/templates/golden-path/tsconfig.json +0 -20
  88. package/templates/golden-path/tsconfig.worker.json +0 -21
  89. package/templates/golden-path/vite.config.ts +0 -12
  90. package/templates/golden-path/vitest.config.ts +0 -28
  91. package/templates/golden-path/web/App.tsx +0 -478
  92. package/templates/golden-path/web/app.css +0 -83
  93. package/templates/golden-path/web/main.tsx +0 -51
  94. package/templates/golden-path/web/pple.ts +0 -124
  95. package/templates/golden-path/web/vite-env.d.ts +0 -10
  96. package/templates/golden-path/wrangler.jsonc +0 -89
  97. package/templates/payment-bridge/.github/workflows/ci.yml +0 -21
  98. package/templates/payment-bridge/CLAUDE.md +0 -9
  99. package/templates/payment-bridge/README.md +0 -57
  100. package/templates/payment-bridge/docs/verify-webhook.md +0 -80
  101. package/templates/payment-bridge/docs/verify-webhook.ts +0 -29
  102. package/templates/payment-bridge/gitignore +0 -5
  103. package/templates/payment-bridge/package-lock.json +0 -4198
  104. package/templates/payment-bridge/package.json +0 -21
  105. package/templates/payment-bridge/src/bridge-key.ts +0 -18
  106. package/templates/payment-bridge/src/env.ts +0 -14
  107. package/templates/payment-bridge/src/index.ts +0 -39
  108. package/templates/payment-bridge/src/platform.ts +0 -49
  109. package/templates/payment-bridge/src/webhook.ts +0 -86
  110. package/templates/payment-bridge/test/docs.test.ts +0 -9
  111. package/templates/payment-bridge/test/fixtures/payments-responses.json +0 -98
  112. package/templates/payment-bridge/test/harness.ts +0 -78
  113. package/templates/payment-bridge/test/inbound.test.ts +0 -138
  114. package/templates/payment-bridge/test/webhook.test.ts +0 -174
  115. package/templates/payment-bridge/tsconfig.json +0 -22
  116. package/templates/payment-bridge/vitest.config.ts +0 -8
  117. package/templates/payment-bridge/wrangler.jsonc +0 -15
  118. package/templates/payment-bridge.version +0 -1
@@ -1,124 +0,0 @@
1
- // The single place the app talks to PPLE Today and to its own API.
2
- //
3
- // Three ways the app can start:
4
- // 1. Local dev (`vite dev`) — no login. The Worker signs you in as a mock
5
- // persona (DEV_PERSONA); we just attach a placeholder bearer it ignores.
6
- // 2. Inside PPLE Today — the SDK captures the access token from the launch
7
- // URL; we attach it to every API call.
8
- // 3. A plain browser — the same SDK runs the PPLE ID OIDC sign-in (redirect
9
- // / callback) and hands back an access token.
10
- import { PPLEMiniApp } from "@pplethai/pple-today-miniapp-sdk";
11
-
12
- // Provisioned per app and baked into this bundle at build time by the
13
- // platform deploy workflow's env (VITE_OAUTH_URL / VITE_OAUTH_CLIENT_ID).
14
- // Needed for the SDK in both PPLE Today and the browser (browser login uses
15
- // the OIDC redirect flow). Empty here means the build var was missing —
16
- // bootstrap() below turns that into a legible error.
17
- const OAUTH_URL = import.meta.env.VITE_OAUTH_URL ?? "";
18
- const OAUTH_CLIENT_ID = import.meta.env.VITE_OAUTH_CLIENT_ID ?? "";
19
- // Must match a redirect URI on the app's PPLE ID OAuth client. Provisioning
20
- // registers the mini-app URL; defaulting to this origin keeps them aligned.
21
- const OAUTH_REDIRECT_URI =
22
- import.meta.env.VITE_OAUTH_REDIRECT_URI ?? window.location.origin;
23
-
24
- // In local dev the Worker ignores the token entirely (it signs you in as a
25
- // mock persona), but api() still needs a non-null bearer to attach.
26
- const DEV_PLACEHOLDER_TOKEN = "dev";
27
-
28
- export type Bootstrap =
29
- | { kind: "signed-in" }
30
- | { kind: "error"; message: string };
31
-
32
- let token: string | null = null;
33
- let sdk: PPLEMiniApp | null = null;
34
-
35
- /** Establish the session. Call once at startup, before rendering the app. */
36
- export async function bootstrap(): Promise<Bootstrap> {
37
- try {
38
- if (import.meta.env.DEV) {
39
- token = DEV_PLACEHOLDER_TOKEN;
40
- return { kind: "signed-in" };
41
- }
42
-
43
- // The OAuth config is baked in at build time by the platform deploy
44
- // workflow (VITE_OAUTH_URL / VITE_OAUTH_CLIENT_ID). If it's missing the
45
- // SDK throws a bare "No authority or metadataUrl configured on settings"
46
- // from oidc-client-ts — turn that into something a Builder can act on
47
- // instead of a stack trace they can't read (issue #115).
48
- if (!OAUTH_URL || !OAUTH_CLIENT_ID) {
49
- return {
50
- kind: "error",
51
- message:
52
- "แอปตั้งค่าไม่ถูกต้อง: การตั้งค่าเข้าสู่ระบบ PPLE ID ไม่ได้ถูกตั้งตอนสร้างแอป โปรดดีพลอยใหม่จากแพลตฟอร์ม",
53
- };
54
- }
55
-
56
- sdk = new PPLEMiniApp({
57
- oauthUrl: OAUTH_URL,
58
- oauthClientId: OAUTH_CLIENT_ID,
59
- oauthRedirectUri: OAUTH_REDIRECT_URI,
60
- });
61
- await sdk.init();
62
- token = await sdk.getAccessToken();
63
- return { kind: "signed-in" };
64
- } catch (e) {
65
- return { kind: "error", message: e instanceof Error ? e.message : String(e) };
66
- }
67
- }
68
-
69
- /** Drop the session and return to the start (re-triggers PPLE ID login). */
70
- export async function logout(): Promise<void> {
71
- token = null;
72
- if (sdk) {
73
- await sdk.logout();
74
- sdk = null;
75
- }
76
- window.location.href = "/";
77
- }
78
-
79
- /**
80
- * Call your Worker API with the bearer token attached. Paths are relative
81
- * ("/api/notes"), since the SPA and the Worker share one origin.
82
- */
83
- export async function api(path: string, init: RequestInit = {}): Promise<Response> {
84
- if (!token) throw new Error("not signed in — call bootstrap() first");
85
- const headers = new Headers(init.headers);
86
- headers.set("authorization", `Bearer ${token}`);
87
- return fetch(path, { ...init, headers });
88
- }
89
-
90
- /** Small helper: call the API and parse JSON, throwing on a non-2xx status. */
91
- export async function apiJson<T>(path: string, init: RequestInit = {}): Promise<T> {
92
- const res = await api(path, init);
93
- if (!res.ok) {
94
- const body = (await res.json().catch(() => ({}))) as { error?: string };
95
- throw new Error(body.error ?? `request failed (${res.status})`);
96
- }
97
- return res.json() as Promise<T>;
98
- }
99
-
100
- /**
101
- * The Payer taps "pay": send them to the Checkout Page already signed in
102
- * (a Checkout Pass, ADR-0043). Asks your Worker's `POST /api/payments/:id/checkout`
103
- * for a fresh pass and posts it to the Checkout Page as a form, from this page,
104
- * which is the only way the platform redeems one. On a refusal it answers the
105
- * reason instead: on `user_token_invalid` send the Payer to the `checkoutUrl`
106
- * `createPayment` answered (they sign in there); `not_your_payment` and
107
- * `not_payable` are in the Skill's payments reference.
108
- */
109
- export async function goToCheckout(paymentId: string): Promise<{ error: string }> {
110
- const res = await api(`/api/payments/${encodeURIComponent(paymentId)}/checkout`, { method: "POST" });
111
- const body = (await res.json().catch(() => ({}))) as { checkoutUrl?: string; pass?: string; error?: string };
112
- if (res.status !== 201 || !body.checkoutUrl || !body.pass) return { error: body.error ?? `request failed (${res.status})` };
113
- const form = document.createElement("form");
114
- form.method = "POST";
115
- form.action = body.checkoutUrl;
116
- const field = document.createElement("input");
117
- field.type = "hidden";
118
- field.name = "pass";
119
- field.value = body.pass;
120
- form.append(field);
121
- document.body.append(form);
122
- form.submit();
123
- return new Promise(() => {}); // the page is leaving
124
- }
@@ -1,10 +0,0 @@
1
- /// <reference types="vite/client" />
2
-
3
- // Build-time OIDC config for the mini-app SDK (PPLE Today + browser login).
4
- // These are public values (a client id and public OAuth URLs), safe to ship
5
- // in the bundle. The platform injects them at deploy time; see .env.example.
6
- interface ImportMetaEnv {
7
- readonly VITE_OAUTH_URL?: string;
8
- readonly VITE_OAUTH_CLIENT_ID?: string;
9
- readonly VITE_OAUTH_REDIRECT_URI?: string;
10
- }
@@ -1,89 +0,0 @@
1
- // Your Builder App's Cloudflare configuration. The platform provisions the
2
- // real D1/R2 resources and injects secrets at deploy time; the values below
3
- // work for local development out of the box.
4
- //
5
- // Everything here is meant to be read top-to-bottom: one Worker serves the
6
- // API under /api/* and the React SPA for everything else.
7
- {
8
- "name": "pple-app",
9
- "main": "src/index.ts",
10
- "compatibility_date": "2026-06-01",
11
-
12
- // Workers Logs: `console.log` and uncaught exceptions are retained, so a
13
- // 500 in production can be read back instead of guessed at.
14
- //
15
- // This setting governs local development only. Your deployed app does not
16
- // ship this file — the platform uploads the Worker through the Cloudflare
17
- // API and sets observability itself (workers/src/provisioner/tenant-worker.ts),
18
- // so logging is on in production whether or not this line survives.
19
- "observability": { "enabled": true, "head_sampling_rate": 1 },
20
-
21
- // The React SPA (built to dist/client by Vite) is served for any request
22
- // that isn't worker-first. "/api/*" is the app's API; "/.pple/*" is reserved
23
- // for the platform (the deploy probe and scheduled jobs) — don't add routes
24
- // under it. "single-page-application" makes every
25
- // other path return index.html so client-side routing works.
26
- "assets": {
27
- "not_found_handling": "single-page-application",
28
- "run_worker_first": ["/api/*", "/.pple/*"]
29
- },
30
-
31
- // Your app's private SQLite database (D1). Migrations live in ./migrations
32
- // and are applied with `npm run db:migrate:local` / `:remote`.
33
- "d1_databases": [
34
- {
35
- "binding": "DB",
36
- "database_name": "pple-app",
37
- "database_id": "00000000-0000-0000-0000-000000000000",
38
- "migrations_dir": "migrations"
39
- }
40
- ],
41
-
42
- // Your app's private file storage (R2).
43
- "r2_buckets": [
44
- {
45
- "binding": "FILES",
46
- "bucket_name": "pple-app"
47
- }
48
- ],
49
-
50
- // Scheduled jobs (Cron Schedules, "งานตั้งเวลา"). Declare when the app runs
51
- // its own code, in UTC (Bangkok is UTC+7: 08:00 in Bangkok is "0 1 * * *"),
52
- // and export `scheduled()` beside `fetch` in src/index.ts. The platform fires
53
- // them, not Cloudflare, so only standard five-field cron works (lists,
54
- // ranges, steps, JAN-DEC months, and weekdays as NAMES only — MON-FRI, never
55
- // digits, which count differently from Cloudflare's docs), at most 3 schedules per app and
56
- // no closer than 5 minutes. Delivery is at-most-once: no catch-up and no
57
- // retry, so write jobs that are safe to repeat. Deploying is the only way to
58
- // change this list; `pple cron` shows, pauses and runs them. Uncomment to use:
59
- //
60
- // "triggers": { "crons": ["0 1 * * *"] },
61
-
62
- // Durable Objects. Export the class from src/index.ts (the Worker's main
63
- // module). Local `npm run dev` emulates it with no extra setup: this binding
64
- // and the migration are enough, and nothing is provisioned in the cloud.
65
- // A deployed app receives the binding only while it holds Durable Object
66
- // access — ask a Platform Admin in an App Note (บันทึก). New classes are
67
- // SQLite (`new_sqlite_classes` only). Uncomment both blocks together:
68
- //
69
- // "durable_objects": {
70
- // "bindings": [{ "name": "COUNTER", "class_name": "Counter" }]
71
- // },
72
- // "migrations": [
73
- // { "tag": "v1", "new_sqlite_classes": ["Counter"] }
74
- // ],
75
-
76
- "vars": {
77
- // PPLE ID (identity). The Worker validates bearer tokens against this.
78
- "SSO_BASE_URL": "https://id.peoplesparty.or.th",
79
- // Audience-bound notification endpoint (see src/notify.ts): the base that
80
- // `${NOTIFY_API_BASE}/notifications` is posted to. The platform sets the
81
- // real value; empty locally so notify is a no-op unless you wire it up in
82
- // .dev.vars.
83
- "NOTIFY_API_BASE": ""
84
- }
85
-
86
- // Secrets (never checked in): set with `wrangler secret put <NAME>`.
87
- // NOTIFY_API_KEY — your app's audience-bound notification key (platform-provisioned)
88
- // DEV_AUTH — local dev only; set in .dev.vars, never in production
89
- }
@@ -1,21 +0,0 @@
1
- # CI for a Payment Bridge. Runs on every push and pull request: type-checks the
2
- # Worker, runs its tests in the Workers runtime, and builds the deployable bundle.
3
- name: CI
4
-
5
- on:
6
- push:
7
- pull_request:
8
-
9
- jobs:
10
- check:
11
- runs-on: ubuntu-latest
12
- steps:
13
- - uses: actions/checkout@v4
14
- - uses: actions/setup-node@v4
15
- with:
16
- node-version: 22
17
- cache: npm
18
- - run: npm ci
19
- - run: npm run typecheck
20
- - run: npm test
21
- - run: npm run build
@@ -1,9 +0,0 @@
1
- # Payment Bridge
2
-
3
- Made and kept by the platform (docs/adr/0045). Deploy it unchanged; do not add
4
- routes, pages, storage, logging or retries. A Bridge whose code drifts from the
5
- template is flagged in its Code Review. Read README.md first.
6
-
7
- Two things must stay true of any change: the Bridge never sends its App Key
8
- anywhere but `platform/payments`, and it never logs a request body, an event or
9
- a key.
@@ -1,57 +0,0 @@
1
- # Payment Bridge
2
-
3
- A Builder App that lets one system outside the platform (an **External System**)
4
- take Payments exactly as a Builder App does (docs/adr/0045). **Deploy it
5
- unchanged.** It has no pages, no database, no files and no queue. A Bridge whose
6
- code drifts from this template is flagged in its Code Review.
7
-
8
- ```
9
- External System ──/api/* + Bridge Key──▶ Bridge ──+ App Key──▶ platform/payments
10
- External System ◀── signed webhook ─────── Bridge ◀── payment(event) ── platform
11
- ```
12
-
13
- ## Inbound: `/api/*`
14
-
15
- Call the Bridge with `Authorization: Bearer <Bridge Key>`. The Bridge makes the
16
- same call on `platform/payments` with its App Key, and hands the platform's answer
17
- back as it came (status, body and `x-pple-error` included). What it carries on:
18
- the method, everything after `/api` and the query, the body, `content-type`,
19
- `accept`, and the Payer's PPLE ID token. So the platform's payments docs apply
20
- to you word for word, with one difference: send the token as `pple-user-token`,
21
- not `x-pple-user-token` (the platform strips every `x-pple-*` header before it
22
- reaches the Bridge, and the Bridge renames it on the way out).
23
- `POST /api` is `POST platform/payments`, and `POST /api/<id>/checkout-pass` with
24
- the Payer's PPLE ID token in `pple-user-token` is a Checkout Pass.
25
-
26
- A missing or wrong Bridge Key is a `401`. A platform that cannot be reached is a
27
- `502`. Every other path is a `404`.
28
-
29
- ## Outbound: the webhook
30
-
31
- When the platform has an outcome for one of your Payments, it calls the Bridge's
32
- `payment(event)`. The Bridge `POST`s that event, unchanged, to `WEBHOOK_URL` at
33
- once, and answers the platform with your status: any `2xx` is delivered; anything
34
- else, an error or no answer within seven seconds is not, and the platform sends
35
- the event again with the same id. The Bridge keeps nothing between attempts.
36
-
37
- Each webhook is signed. See [docs/verify-webhook.md](docs/verify-webhook.md) for
38
- what to check on your side.
39
-
40
- ## Config
41
-
42
- Set in the platform (App Environment), never in this repo:
43
-
44
- | Key | Kind | |
45
- | --- | --- | --- |
46
- | `BRIDGE_KEY` | secret | What your External System calls `/api/*` with. |
47
- | `WEBHOOK_SECRET` | secret | Signs every webhook. Not the Bridge Key. |
48
- | `WEBHOOK_URL` | variable | Where events are `POST`ed. An `https` address. With none, every event is answered `503` and the platform sends it again later. |
49
-
50
- The App Key and the services address are bound by the platform; the Bridge never
51
- puts the App Key on anything it sends out and never logs a body.
52
-
53
- ## Develop
54
-
55
- `npm run typecheck`, `npm test`, `npm run build`. There is no offline mode:
56
- test against your deployed Bridge at Beta, on the Gateway's sandbox (a Draft Bridge's calls are refused
57
- with `needs_beta`).
@@ -1,80 +0,0 @@
1
- # Checking a webhook from your Payment Bridge
2
-
3
- Every payment event reaches your webhook address as a `POST` with the event as
4
- JSON, exactly as the platform's payments docs describe it, and three headers:
5
-
6
- | Header | What it is |
7
- | --- | --- |
8
- | `x-pple-webhook-id` | The event's id, a copy of `id` in the body. The same on every attempt to tell you the same event: use it to dedupe. |
9
- | `x-pple-webhook-timestamp` | When this attempt was sent, in Unix seconds. A new value on every attempt. |
10
- | `x-pple-webhook-signature` | `v1=` and the hex of `HMAC-SHA256(secret, timestamp + "." + body)`. |
11
-
12
- `body` is the raw request body, byte for byte: read it as text before you parse
13
- it. `secret` is the **signing secret** you were given with your Bridge (its
14
- `WEBHOOK_SECRET`). It is not your Bridge Key, and it never leaves you and your
15
- Bridge.
16
-
17
- Check, in this order, before you trust the event:
18
-
19
- 1. The signature matches (constant-time compare).
20
- 2. The timestamp is within five minutes of now, so a copy captured earlier
21
- cannot be played back to you.
22
- 3. Take the event id from the **body** (`id`), not the header: only the body is
23
- signed. If you already handled it, answer `200` and do nothing else.
24
-
25
- Then answer. Any `2xx` tells the platform you have the event. Anything else, or
26
- no answer within about seven seconds, tells it you do not, and it sends the
27
- event again every few minutes with the same id.
28
-
29
- ```ts
30
- // How an External System checks a webhook from its Payment Bridge. Plain Web
31
- // Crypto, so it runs unchanged in Node 20+, Deno, Bun and Cloudflare Workers.
32
-
33
- /** Headers the Bridge sets: `x-pple-webhook-timestamp` and `x-pple-webhook-signature`. */
34
- export async function verifyWebhook(input: {
35
- /** The signing secret you were given with the Bridge (its `WEBHOOK_SECRET`). */
36
- secret: string;
37
- /** The request body exactly as received: the raw text, not parsed and re-written JSON. */
38
- body: string;
39
- /** The `x-pple-webhook-timestamp` header, in Unix seconds. */
40
- timestamp: string;
41
- /** The `x-pple-webhook-signature` header, `v1=<hex>`. */
42
- signature: string;
43
- /** Refuse a timestamp further than this from now. Every attempt is signed afresh. */
44
- toleranceSeconds?: number;
45
- /** Unix seconds. Tests only. */
46
- now?: number;
47
- }): Promise<boolean> {
48
- const { secret, body, timestamp, signature, toleranceSeconds = 300 } = input;
49
- const now = input.now ?? Math.floor(Date.now() / 1000);
50
- if (!/^\d+$/.test(timestamp) || Math.abs(now - Number(timestamp)) > toleranceSeconds) return false;
51
- const given = /^v1=([0-9a-f]{64})$/.exec(signature)?.[1];
52
- if (!given) return false;
53
-
54
- const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
55
- const bytes = Uint8Array.from(given.match(/../g)!, (pair) => parseInt(pair, 16));
56
- // `verify` compares in constant time.
57
- return crypto.subtle.verify("HMAC", key, bytes, new TextEncoder().encode(`${timestamp}.${body}`));
58
- }
59
- ```
60
-
61
- Use it in your handler:
62
-
63
- ```ts
64
- const body = await request.text();
65
- const ok = await verifyWebhook({
66
- secret: process.env.PPLE_WEBHOOK_SECRET!,
67
- body,
68
- timestamp: request.headers.get("x-pple-webhook-timestamp") ?? "",
69
- signature: request.headers.get("x-pple-webhook-signature") ?? "",
70
- });
71
- if (!ok) return new Response(null, { status: 401 });
72
- const event = JSON.parse(body);
73
- ```
74
-
75
- ## Why the signing secret is its own
76
-
77
- The Bridge Key lets someone *call* the platform through your Bridge. The
78
- signing secret lets someone *pretend to be* your Bridge. They are kept apart
79
- so that a leak or a rotation of one does not touch the other, and the Owner
80
- can change either on its own.
@@ -1,29 +0,0 @@
1
- // How an External System checks a webhook from its Payment Bridge. Plain Web
2
- // Crypto, so it runs unchanged in Node 20+, Deno, Bun and Cloudflare Workers.
3
-
4
- /** Headers the Bridge sets: `x-pple-webhook-timestamp` and `x-pple-webhook-signature`. */
5
- export async function verifyWebhook(input: {
6
- /** The signing secret you were given with the Bridge (its `WEBHOOK_SECRET`). */
7
- secret: string;
8
- /** The request body exactly as received: the raw text, not parsed and re-written JSON. */
9
- body: string;
10
- /** The `x-pple-webhook-timestamp` header, in Unix seconds. */
11
- timestamp: string;
12
- /** The `x-pple-webhook-signature` header, `v1=<hex>`. */
13
- signature: string;
14
- /** Refuse a timestamp further than this from now. Every attempt is signed afresh. */
15
- toleranceSeconds?: number;
16
- /** Unix seconds. Tests only. */
17
- now?: number;
18
- }): Promise<boolean> {
19
- const { secret, body, timestamp, signature, toleranceSeconds = 300 } = input;
20
- const now = input.now ?? Math.floor(Date.now() / 1000);
21
- if (!/^\d+$/.test(timestamp) || Math.abs(now - Number(timestamp)) > toleranceSeconds) return false;
22
- const given = /^v1=([0-9a-f]{64})$/.exec(signature)?.[1];
23
- if (!given) return false;
24
-
25
- const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
26
- const bytes = Uint8Array.from(given.match(/../g)!, (pair) => parseInt(pair, 16));
27
- // `verify` compares in constant time.
28
- return crypto.subtle.verify("HMAC", key, bytes, new TextEncoder().encode(`${timestamp}.${body}`));
29
- }
@@ -1,5 +0,0 @@
1
- node_modules/
2
- dist/
3
- .wrangler/
4
- .dev.vars
5
- *.log