@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,282 +0,0 @@
1
- // The Worker: your app's API. Hono routes everything under /api/*; the React
2
- // SPA is served for every other path (see wrangler.jsonc). Keep route
3
- // handlers thin — the real work lives in the helpers (auth, db, files, notify)
4
- // so each concern is easy to find and test.
5
- import { Hono } from "hono";
6
- import type { ContentfulStatusCode } from "hono/utils/http-status";
7
- import type { Identity } from "../shared/api";
8
- import { CreateDonationSchema, CreateNoteSchema, NotificationSchema } from "../shared/api";
9
- import { authenticate } from "./auth";
10
- import { addNote, listNotes } from "./db";
11
- import type { Env } from "./env";
12
- import { devWorkerFetch } from "./dev-registry";
13
- import { getFile, listFiles, putFile } from "./files";
14
- import { closeInteraction, sendNotification } from "./notify";
15
- import {
16
- createCheckoutPass,
17
- createPayment,
18
- getPayment,
19
- paymentHandler,
20
- verifyPaymentEvent,
21
- type PaymentHandler,
22
- type PaymentReason,
23
- } from "./payment";
24
- import type { PpleWorker, RegistryFetch, RegistryMap } from "./registry";
25
-
26
- /** Test seam: real fetch by default, an injected fake in tests. */
27
- export interface AppOverrides {
28
- fetchImpl?: typeof fetch;
29
- }
30
-
31
- type AppContext = {
32
- Bindings: Env;
33
- Variables: { identity: Identity };
34
- };
35
-
36
- export function createApp(overrides: AppOverrides = {}) {
37
- const fetchImpl = overrides.fetchImpl ?? globalThis.fetch.bind(globalThis);
38
-
39
- const app = new Hono<AppContext>().basePath("/api");
40
-
41
- // Liveness check — no auth, so uptime monitors and CI smoke tests can hit it.
42
- app.get("/health", (c) => c.json({ ok: true }));
43
-
44
- // Everything below requires a valid PPLE ID token. authenticate() owns the
45
- // whole decision — including the local dev-persona bypass — so a missing
46
- // token is just one of the ways it can say 401.
47
- app.use("*", async (c, next) => {
48
- const token = (c.req.header("authorization") ?? "")
49
- .replace(/^Bearer\s+/i, "")
50
- .trim();
51
- const result = await authenticate(c.env, token, fetchImpl);
52
- if (!result.ok) {
53
- return c.json(
54
- { error: result.status === 401 ? "not_authenticated" : "sso_unavailable" },
55
- result.status,
56
- );
57
- }
58
- c.set("identity", result.identity);
59
- await next();
60
- });
61
-
62
- // The signed-in caller. `actor` is who is clicking; `effective` is what they
63
- // may do — gate authorization on `effective`, never on `actor`.
64
- app.get("/me", (c) => c.json(c.get("identity")));
65
-
66
- // --- D1 demo: a shared notes list ---
67
- app.get("/notes", async (c) => c.json({ notes: await listNotes(c.env.DB) }));
68
-
69
- app.post("/notes", async (c) => {
70
- const parsed = CreateNoteSchema.safeParse(
71
- await c.req.json().catch(() => null),
72
- );
73
- if (!parsed.success) return c.json({ error: "invalid_body" }, 400);
74
- return c.json(await addNote(c.env.DB, parsed.data.body), 201);
75
- });
76
-
77
- // --- R2 demo: file upload/list/download ---
78
- app.get("/files", async (c) => c.json({ files: await listFiles(c.env.FILES) }));
79
-
80
- app.post("/files", async (c) => {
81
- const form = await c.req.formData().catch(() => null);
82
- const file = form?.get("file");
83
- if (!(file instanceof File)) return c.json({ error: "no_file" }, 400);
84
- const uploaded = await putFile(
85
- c.env.FILES,
86
- file.name,
87
- file.stream(),
88
- file.type,
89
- );
90
- return c.json(uploaded, 201);
91
- });
92
-
93
- app.get("/files/:key", async (c) => {
94
- const obj = await getFile(c.env.FILES, c.req.param("key"));
95
- if (!obj) return c.json({ error: "not_found" }, 404);
96
- const headers = new Headers();
97
- obj.writeHttpMetadata(headers);
98
- headers.set("etag", obj.httpEtag);
99
- return new Response(obj.body, { headers });
100
- });
101
-
102
- // --- Notification demo: Broadcast and Direct sends ---
103
- // The audience is required by the schema, so a send that forgets to state it
104
- // is refused here and never reaches the platform as a broadcast.
105
- app.post("/notify", async (c) => {
106
- const parsed = NotificationSchema.safeParse(
107
- await c.req.json().catch(() => null),
108
- );
109
- if (!parsed.success) return c.json({ error: "invalid_body" }, 400);
110
- const result = await sendNotification(c.env, parsed.data, fetchImpl);
111
- if (!result.ok) {
112
- return c.json(
113
- {
114
- error: result.error,
115
- ...(result.message ? { message: result.message } : {}),
116
- ...(result.quota ? { quota: result.quota } : {}),
117
- },
118
- result.status as ContentfulStatusCode,
119
- );
120
- }
121
- // A Direct send answers for each recipient it named; a Broadcast names no
122
- // one, so there is nothing to enumerate.
123
- const notificationId = result.notificationId ? { notificationId: result.notificationId } : {};
124
- return c.json(
125
- result.audience === "direct"
126
- ? { ok: true, results: result.results, ...notificationId }
127
- : { ok: true, ...notificationId },
128
- );
129
- });
130
-
131
- // Close an Interactive Notification early, by the id its send returned.
132
- app.post("/notify/:notificationId/close", async (c) => {
133
- const result = await closeInteraction(c.env, c.req.param("notificationId"), fetchImpl);
134
- if (!result.ok) {
135
- return c.json({ error: result.error }, result.status as ContentfulStatusCode);
136
- }
137
- return c.json({ ok: true, ...(result.closedAt ? { closedAt: result.closedAt } : {}) });
138
- });
139
-
140
- // --- Payments demo: take a donation through the platform's Checkout Page ---
141
- // Replace this with your own. The Payer must be KYC-verified, or the
142
- // Checkout Page turns them away, so the app says so first. The Payer pays on
143
- // the platform's page: you send them to `checkoutUrl` and never see card
144
- // data or a full citizen ID. The outcome arrives at `payment` on the
145
- // default export (below). Needs the Use Grant of `platform/payments`.
146
- app.post("/payments", async (c) => {
147
- if (!c.get("identity").actor.kyc.verified) return c.json({ error: "kyc_required" }, 403);
148
- const parsed = CreateDonationSchema.safeParse(await c.req.json().catch(() => null));
149
- if (!parsed.success) return c.json({ error: "invalid_body" }, 400);
150
- const created = await createPayment(
151
- c.env,
152
- {
153
- kind: "donation",
154
- amountSatang: parsed.data.amountSatang,
155
- description: "บริจาคสนับสนุนพรรค",
156
- // Your own id for this payment: it comes back on every event. Use the
157
- // id of your own order or record here.
158
- reference: crypto.randomUUID(),
159
- returnUrl: new URL("/", c.req.url).toString(),
160
- },
161
- fetchImpl,
162
- );
163
- if (!created.ok) return c.json({ error: created.reason }, paymentStatus(created.reason));
164
- return c.json({ id: created.id, checkoutUrl: created.checkoutUrl }, 201);
165
- });
166
-
167
- // The Payer taps to pay: mint a Checkout Pass with their own token (ADR-0043).
168
- // The page posts `pass` to `checkoutUrl` as a form, from this app's own
169
- // address (`goToCheckout` in web/pple.ts), and they open the Checkout Page
170
- // already signed in, with no PPLE ID screen. Ask now, not when you create the
171
- // Payment: a pass lasts a few minutes and works once, and each call mints a
172
- // fresh one. Without a token
173
- // (or on `user_token_invalid`) fall back to the `checkoutUrl` the create call
174
- // answered: the Payer then signs in on the Checkout Page.
175
- app.post("/payments/:id/checkout", async (c) => {
176
- const token = (c.req.header("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
177
- const pass = await createCheckoutPass(c.env, c.req.param("id"), token, fetchImpl);
178
- if (!pass.ok) return c.json({ error: pass.reason }, paymentStatus(pass.reason));
179
- return c.json({ checkoutUrl: pass.checkoutUrl, pass: pass.pass }, 201);
180
- });
181
-
182
- app.get("/payments/:id", async (c) => {
183
- const read = await getPayment(c.env, c.req.param("id"), fetchImpl);
184
- if (!read.ok) return c.json({ error: read.reason }, paymentStatus(read.reason));
185
- return c.json({ payment: read.payment });
186
- });
187
-
188
- return app;
189
- }
190
-
191
- function paymentStatus(reason: PaymentReason): ContentfulStatusCode {
192
- switch (reason) {
193
- case "not_found":
194
- return 404;
195
- case "invalid_payment":
196
- return 400;
197
- case "user_token_invalid":
198
- return 401;
199
- case "not_paid":
200
- case "not_late":
201
- case "has_receipt":
202
- case "mismatch":
203
- case "not_your_payment":
204
- case "not_payable":
205
- return 409;
206
- default:
207
- // Not granted, still Draft, no Checkout Page, platform down: not the
208
- // Payer's doing, and not something they can fix.
209
- return 502;
210
- }
211
- }
212
-
213
- /**
214
- * What to do when the platform tells the app about a Payment. This default
215
- * only checks the event against the platform and stops: **it does not issue
216
- * the legal Receipt.** Issuing is your decision, and a Receipt is never edited,
217
- * only voided and replaced, so an app should not do it by habit. A paid Payment
218
- * you neither issue nor reject within the party's deadline goes to the Finance
219
- * Officer as Undecided. Pick one of the two patterns (the `pple-platform`
220
- * Skill's payments reference has both in full):
221
- *
222
- * Issue at payment: there is nothing more to check (a donation). After the
223
- * verify below, add:
224
- *
225
- * const issued = await issueReceipt(env, event.payment.id, fetchImpl);
226
- * if (!issued.ok && issued.reason !== "not_paid") return tryAgain();
227
- *
228
- * Verify first: your app must check something (an order in stock, a
229
- * membership that exists). Do the check, then `issueReceipt` when it passes
230
- * or `rejectPayment(env, event.payment.id, fetchImpl)` when it does not.
231
- *
232
- * Holding something while the Payer pays? Give `createPayment` an `expiresAt`,
233
- * release your hold on your own timer, add a `"payment.expired"` function here,
234
- * and a `"payment.late"` one: money confirmed after `expiresAt` waits for you to
235
- * `acceptPayment` it (you can still serve it) or `rejectPayment` it (you cannot).
236
- */
237
- export function createPaymentHandler(overrides: AppOverrides = {}): PaymentHandler {
238
- const fetchImpl = overrides.fetchImpl;
239
- // Answer `2xx` and the platform stops; anything else, or a throw, is sent
240
- // again every few minutes. Retry only what a retry can fix.
241
- const tryAgain = () => new Response(null, { status: 503 });
242
- return paymentHandler({
243
- "payment.paid": async (event, env) => {
244
- const verified = await verifyPaymentEvent(env, event, fetchImpl);
245
- if (!verified.ok) return verified.reason === "mismatch" ? undefined : tryAgain();
246
- if (verified.payment.state !== "paid") return;
247
- // Decide here: issue at payment, or verify first (see above). Until you do, nothing is issued.
248
- },
249
- });
250
- }
251
-
252
- const api = createApp();
253
-
254
- const registry: RegistryMap = {};
255
-
256
- const appFetch: RegistryFetch = (request, env, ctx) => api.fetch(request, env, ctx);
257
-
258
- /**
259
- * The Worker entry. `registry` is where a Service handler or a Dataset's page
260
- * functions live, keyed by the entry name. A Hono app plugs straight in
261
- * (`registry: { "<name>": app }`). A Dataset is an object of page functions
262
- * (`registry: { "<name>": { "<objectType>": ({ cursor }, env, ctx) => page } }`).
263
- * The platform calls a Service at `/.pple/registry/<name>/…` and a Dataset at
264
- * `/.pple/registry/<name>/<objectType>`. Read a Service caller with
265
- * `serviceCall(request)` from `./registry`.
266
- *
267
- * Under `vite dev` the same path is emulated locally. `import.meta.env.DEV`
268
- * is false in `vite build`, so that branch and `dev-registry.ts` are absent
269
- * from the deployed Worker, the same way the Persona bypass is (ADR-0011).
270
- */
271
- const worker: PpleWorker = {
272
- fetch(request, env, ctx) {
273
- if (import.meta.env.DEV) {
274
- return devWorkerFetch({ fetch: appFetch, registry }, request, env, ctx);
275
- }
276
- return appFetch(request, env, ctx);
277
- },
278
- registry,
279
- payment: createPaymentHandler(),
280
- };
281
-
282
- export default worker;
@@ -1,180 +0,0 @@
1
- // Legal Identity (CONTEXT.md). A Builder App reads a person's name and
2
- // citizen ID from the Private Platform Service `platform/legal-identity`,
3
- // only under a Use Grant of that entry, only at the moment it needs them.
4
- // This module fetches that record. It does not store it.
5
- //
6
- // Offline (`npm run dev` with a Persona) the answer is a fixed fake. Member
7
- // Personas have no citizen ID, matching production. The one ID this module
8
- // invents fails the Thai checksum, so it can never be mistaken for a real one.
9
-
10
- import type { KycStatus } from "../shared/api";
11
- import { callService, platformError, type PlatformErrorCode } from "./call-service";
12
- import { resolveDevPersona } from "./dev-personas";
13
-
14
- export interface LegalIdentity {
15
- source: "membership" | "kyc";
16
- name: string;
17
- /** Null for a member who never did a national-ID check. */
18
- idCardNumber: string | null;
19
- }
20
-
21
- export type LegalIdentityReason =
22
- | "not_configured"
23
- | "invalid_app_key"
24
- | "not_granted"
25
- | "needs_beta"
26
- | "not_verified"
27
- | "user_token_invalid"
28
- | "upstream_unavailable";
29
-
30
- export type LegalIdentityResult =
31
- | { ok: true; legalIdentity: LegalIdentity }
32
- | { ok: false; reason: LegalIdentityReason };
33
-
34
- interface LegalIdentityEnv {
35
- PPLE_SERVICES_URL?: string;
36
- PPLE_APP_KEY?: string;
37
- /** Which Persona is signed in. `"none"` uses the real Platform Service. */
38
- DEV_PERSONA?: string;
39
- }
40
-
41
- /** The only name the offline path returns. */
42
- export const OFFLINE_LEGAL_NAME = "บุคคลทดสอบ ออฟไลน์";
43
-
44
- /**
45
- * 13 digits that fail the Thai national-ID checksum (expected check digit 8).
46
- * The offline path uses this and nothing that would pass.
47
- */
48
- export const OFFLINE_INVALID_ID = "1100000000000";
49
-
50
- /** What this Service itself answers, with no `x-pple-error` header. */
51
- const PROVIDER_REASONS = ["not_verified", "user_token_invalid", "upstream_unavailable"] as const;
52
-
53
- type ProviderReason = (typeof PROVIDER_REASONS)[number];
54
-
55
- /** True when `id` is 13 digits and its check digit matches. */
56
- export function thaiIdChecksumValid(id: string): boolean {
57
- if (!/^\d{13}$/.test(id)) return false;
58
- let sum = 0;
59
- for (let i = 0; i < 12; i++) sum += Number(id[i]) * (13 - i);
60
- return (11 - (sum % 11)) % 10 === Number(id[12]);
61
- }
62
-
63
- /**
64
- * The caller's Legal Identity, or why it isn't available.
65
- *
66
- * Offline (`npm run dev` with a Persona) this never calls out. Otherwise it
67
- * wraps `callService(env, "platform/legal-identity", "", { method: "POST" },
68
- * { userToken })`. `not_configured` means PPLE_SERVICES_URL or PPLE_APP_KEY
69
- * is missing. `needs_beta` means the Use Grant is held and the app is still
70
- * Draft. `not_listed`, `identity_unavailable`, `provider_unavailable` and
71
- * `provider_timeout` are `upstream_unavailable`.
72
- */
73
- export async function getLegalIdentity(
74
- env: LegalIdentityEnv,
75
- token: string,
76
- fetchImpl?: typeof fetch,
77
- ): Promise<LegalIdentityResult> {
78
- // Same seam as authenticate: a Persona stands in for PPLE ID, and the
79
- // block is dead-code-eliminated from the production build (ADR-0011).
80
- if (import.meta.env.DEV && env.DEV_PERSONA !== "none") {
81
- return offlineLegalIdentity(env.DEV_PERSONA);
82
- }
83
-
84
- if (!env.PPLE_SERVICES_URL || !env.PPLE_APP_KEY) {
85
- return { ok: false, reason: "not_configured" };
86
- }
87
-
88
- let res: Response;
89
- try {
90
- res = await callService(
91
- env,
92
- "platform/legal-identity",
93
- "",
94
- { method: "POST" },
95
- { userToken: token, ...(fetchImpl ? { fetchImpl } : {}) },
96
- );
97
- } catch {
98
- return { ok: false, reason: "upstream_unavailable" };
99
- }
100
-
101
- // A platform refusal carries `x-pple-error`. This Service's own answers
102
- // do not, so a body `error` is trusted only when the header is absent.
103
- if (res.headers.get("x-pple-error")) {
104
- return { ok: false, reason: platformReason(platformError(res)) };
105
- }
106
-
107
- const body = (await res.json().catch(() => ({}))) as {
108
- error?: string;
109
- source?: string;
110
- name?: string;
111
- idCardNumber?: string | null;
112
- };
113
- const provider = providerReason(body.error);
114
- if (provider) return { ok: false, reason: provider };
115
- if (!res.ok) return { ok: false, reason: "upstream_unavailable" };
116
-
117
- if (typeof body.name !== "string" || body.name === "") {
118
- return { ok: false, reason: "upstream_unavailable" };
119
- }
120
- const source = body.source === "membership" || body.source === "kyc" ? body.source : null;
121
- if (!source) return { ok: false, reason: "upstream_unavailable" };
122
- const idCardNumber = typeof body.idCardNumber === "string" ? body.idCardNumber : null;
123
- return { ok: true, legalIdentity: { source, name: body.name, idCardNumber } };
124
- }
125
-
126
- function platformReason(code: PlatformErrorCode | null): LegalIdentityReason {
127
- switch (code) {
128
- case "invalid_app_key":
129
- case "not_granted":
130
- case "needs_beta":
131
- case "user_token_invalid":
132
- return code;
133
- default:
134
- return "upstream_unavailable";
135
- }
136
- }
137
-
138
- function providerReason(error: string | undefined): ProviderReason | null {
139
- return PROVIDER_REASONS.find((reason) => reason === error) ?? null;
140
- }
141
-
142
- function offlineLegalIdentity(personaName: string | undefined): LegalIdentityResult {
143
- const persona = resolveDevPersona(personaName);
144
- const kyc: KycStatus = persona.actor.kyc;
145
- if (!kyc.verified || (kyc.source !== "membership" && kyc.source !== "kyc")) {
146
- return { ok: false, reason: "not_verified" };
147
- }
148
- // Members have a name and no citizen ID until they do KYC. Anyone else gets
149
- // the one invalid ID, and a checksum that accidentally passed is dropped.
150
- let idCardNumber = kyc.source === "membership" ? null : OFFLINE_INVALID_ID;
151
- if (idCardNumber && thaiIdChecksumValid(idCardNumber)) idCardNumber = null;
152
- return {
153
- ok: true,
154
- legalIdentity: { source: kyc.source, name: OFFLINE_LEGAL_NAME, idCardNumber },
155
- };
156
- }
157
-
158
- /**
159
- * Where a "start KYC" button sends the person. Locally that is straight back
160
- * to `returnTo` with `?kyc=cancelled` — there is no PPLE ID to open. In
161
- * production it is `{ssoBaseUrl}/kyc`, which is the shape pple-today owns
162
- * (PPLEThai/pple-today#500).
163
- */
164
- export function kycStartUrl(input: {
165
- ssoBaseUrl: string;
166
- clientId: string;
167
- returnTo: string;
168
- dev?: boolean;
169
- }): string {
170
- const dev = input.dev ?? import.meta.env.DEV;
171
- if (dev) {
172
- const back = new URL(input.returnTo);
173
- back.searchParams.set("kyc", "cancelled");
174
- return back.toString();
175
- }
176
- const url = new URL("/kyc", input.ssoBaseUrl);
177
- url.searchParams.set("client_id", input.clientId);
178
- url.searchParams.set("return_to", input.returnTo);
179
- return url.toString();
180
- }
@@ -1,132 +0,0 @@
1
- // Whether an Identity passes a Dataset Access Level (ADR-0028).
2
- //
3
- // A copy of workers/src/shared/registry/levels.ts. This file is copied into
4
- // a Builder App, which cannot import the platform package. Offline reads
5
- // (#270) use this copy so a Persona sees the same refusals as production.
6
- // cli/test/registry-levels.test.ts keeps the two in step.
7
-
8
- export type AccessLevel =
9
- | "public"
10
- | "member"
11
- | "internal"
12
- | {
13
- roles?: readonly string[];
14
- subs?: readonly string[] | "swept";
15
- };
16
-
17
- /** The Identity facts a level reads. Other Identity fields are ignored. */
18
- export interface LevelIdentity {
19
- actor: {
20
- sub: string;
21
- /** Non-null only while PPLE ID reports an active party membership. */
22
- membership: { memberSince: string } | null;
23
- };
24
- effective: {
25
- isDelegated: boolean;
26
- /**
27
- * PPLE ID sub of the person whose authority is in effect.
28
- * The Actor's own sub when nobody is delegating. Under Delegation, the
29
- * supervisor's Zitadel sub, or null when that id is missing. Null matches
30
- * no custom `subs`.
31
- */
32
- sub: string | null;
33
- activeRole: string;
34
- extraRoles: readonly string[];
35
- };
36
- }
37
-
38
- export interface PassesLevelOptions {
39
- /**
40
- * The snapshot's subs when the level says `subs: "swept"`.
41
- * The caller passes the list (#267, #269). This function never loads it.
42
- * Absent means empty, so swept subs admit nobody until a sweep has landed.
43
- */
44
- sweptSubs?: readonly string[];
45
- }
46
-
47
- /**
48
- * Live visibility stores `pple-ad:` plus the bare Active Role or Extra Role,
49
- * the vocabulary `GET /role-options` returns. A custom level uses that
50
- * same vocabulary, matched by exact string against that prefixed union.
51
- * Eligible Roles are not part of the union.
52
- */
53
- const ROLE_PREFIX = "pple-ad:";
54
-
55
- function bareRole(role: string): string {
56
- return role.startsWith(ROLE_PREFIX) ? role.slice(ROLE_PREFIX.length) : role;
57
- }
58
-
59
- function viewerRoles(identity: LevelIdentity): Set<string> {
60
- const roles = new Set<string>();
61
- const add = (role: unknown) => {
62
- if (typeof role !== "string" || role === "") return;
63
- roles.add(`${ROLE_PREFIX}${bareRole(role)}`);
64
- };
65
- add(identity.effective.activeRole);
66
- const extras = identity.effective.extraRoles;
67
- if (Array.isArray(extras)) {
68
- for (const extra of extras) add(extra);
69
- }
70
- return roles;
71
- }
72
-
73
- function passesInternal(identity: LevelIdentity): boolean {
74
- return typeof identity.effective.activeRole === "string" && identity.effective.activeRole !== "";
75
- }
76
-
77
- function passesMember(identity: LevelIdentity): boolean {
78
- // A delegate is read with the supervisor's authority at every level.
79
- // A null membership (the lookup failed, or there is none) does not pass on its own.
80
- if (identity.effective.isDelegated === true) return true;
81
- if (identity.actor.membership !== null && identity.actor.membership !== undefined) return true;
82
- return passesInternal(identity);
83
- }
84
-
85
- /**
86
- * Custom `subs` match the Actor's `sub`. Under Delegation they also match
87
- * `effective.sub`, the supervisor's PPLE ID sub.
88
- *
89
- * A null or empty Effective sub matches nothing: a supervisor without a
90
- * Zitadel id does not pass a level that names them. A session that is not
91
- * delegated matches the Actor only, even if `effective.sub` says someone else.
92
- */
93
- function subsAdmit(identity: LevelIdentity, subs: readonly string[]): boolean {
94
- if (typeof identity.actor.sub === "string" && identity.actor.sub !== "" && subs.includes(identity.actor.sub)) {
95
- return true;
96
- }
97
- if (identity.effective.isDelegated !== true) return false;
98
- const supervisor = identity.effective.sub;
99
- if (typeof supervisor !== "string" || supervisor === "") return false;
100
- return subs.includes(supervisor);
101
- }
102
-
103
- function subsMatch(
104
- identity: LevelIdentity,
105
- subs: unknown,
106
- sweptSubs: readonly string[] | undefined,
107
- ): boolean {
108
- const list = subs === "swept" ? sweptSubs : subs;
109
- if (!Array.isArray(list)) return false;
110
- const names = list.filter((item): item is string => typeof item === "string");
111
- return subsAdmit(identity, names);
112
- }
113
-
114
- function rolesMatch(identity: LevelIdentity, roles: unknown): boolean {
115
- if (!Array.isArray(roles)) return false;
116
- const viewer = viewerRoles(identity);
117
- return roles.some((role) => typeof role === "string" && viewer.has(role));
118
- }
119
-
120
- export function passesLevel(
121
- identity: LevelIdentity | null,
122
- level: AccessLevel,
123
- options?: PassesLevelOptions,
124
- ): boolean {
125
- if (level === "public") return true;
126
- if (identity === null || identity === undefined) return false;
127
- if (level === "member") return passesMember(identity);
128
- if (level === "internal") return passesInternal(identity);
129
- if (typeof level !== "object") return false;
130
- if (rolesMatch(identity, level.roles)) return true;
131
- return subsMatch(identity, level.subs, options?.sweptSubs);
132
- }
@@ -1,55 +0,0 @@
1
- // A Notification Response: one recipient's answer to an Interactive Notification
2
- // your app sent (docs/adr/0035). today-v2 delivers it through the platform to
3
- // `notificationResponse(event, env, ctx)` on the Worker default export, beside
4
- // `fetch` and `registry`. Define it on `worker` in `src/index.ts`.
5
- //
6
- // What your handler does is the status today-v2 retries on:
7
- //
8
- // - not defined: the platform answers 404, and answers keep coming for about
9
- // a day and a half, so there is time to ship one
10
- // - returns nothing: 204, delivered
11
- // - returns a `Response`: that status. Return `410` to say "stop sending me
12
- // these", which ends delivery for good
13
- // - throws: 500, and today-v2 tries again
14
- //
15
- // Delivery is at-least-once and unordered. Dedupe on `event.id`. If only the
16
- // first answer should count ("first approver wins"), decide it yourself by
17
- // `respondedAt`, then `id`. An answer can arrive after you closed the
18
- // interaction.
19
- //
20
- // The platform answers when the handler returns. It does not wait for work
21
- // handed to `ctx.waitUntil`, so do the slow part there, after the answer is
22
- // acknowledged. today-v2 gives up on a call after about 10 s.
23
- //
24
- // The handler gets the parsed event only: no request, no headers. The
25
- // responder is a PPLE ID `sub` and nothing else. If you need more about that
26
- // person, call a Service you have been granted.
27
-
28
- import type { Env } from "./env";
29
-
30
- export interface NotificationResponseEvent {
31
- type: "notification.response";
32
- /** The response's own id. The same on every retry, so dedupe on it. */
33
- id: string;
34
- /** The notification that was answered. `notify()` returned it when you sent. */
35
- notificationId: string;
36
- /** Your own id for the question, as you sent it. Absent if you sent none. */
37
- ref?: string;
38
- app: { slug: string };
39
- /** Who answered: their PPLE ID `sub`. */
40
- responder: { sub: string };
41
- /** The action the recipient chose. */
42
- action: string;
43
- /** The form fields they filled in, by field id. A tick-list is an array. */
44
- values?: Record<string, string | string[]>;
45
- /** ISO 8601 time they answered. */
46
- respondedAt: string;
47
- /** Which delivery attempt this is, from 1. */
48
- attempt: number;
49
- }
50
-
51
- export type NotificationResponseHandler = (
52
- event: NotificationResponseEvent,
53
- env: Env,
54
- ctx: ExecutionContext,
55
- ) => void | Response | Promise<void | Response>;