@pplethai/cli 0.21.0 → 0.23.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 (117) hide show
  1. package/README.md +12 -14
  2. package/dist/bin.js +102 -102
  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 -187
  9. package/templates/golden-path/README.md +0 -118
  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 -224
  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 -276
  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/payment.ts +0 -554
  38. package/templates/golden-path/src/read-dataset.ts +0 -490
  39. package/templates/golden-path/src/registry.ts +0 -128
  40. package/templates/golden-path/src/vite-env.d.ts +0 -27
  41. package/templates/golden-path/test/apply-migrations.ts +0 -4
  42. package/templates/golden-path/test/call-service.test.ts +0 -288
  43. package/templates/golden-path/test/dev-call-service.test.ts +0 -455
  44. package/templates/golden-path/test/dev-read-dataset.test.ts +0 -379
  45. package/templates/golden-path/test/dev-registry.test.ts +0 -404
  46. package/templates/golden-path/test/effective-sub.test.ts +0 -101
  47. package/templates/golden-path/test/email-offline.test.ts +0 -51
  48. package/templates/golden-path/test/email.test.ts +0 -117
  49. package/templates/golden-path/test/env.d.ts +0 -17
  50. package/templates/golden-path/test/fixtures/overlay/branch-list/entry.md +0 -85
  51. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/audience.json +0 -3
  52. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/named.json +0 -3
  53. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/offices.json +0 -6
  54. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/roster.json +0 -3
  55. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/summary.json +0 -1
  56. package/templates/golden-path/test/fixtures/overlay/catalog/entry.md +0 -8
  57. package/templates/golden-path/test/fixtures/overlay/catalog/mocks/responses.json +0 -7
  58. package/templates/golden-path/test/fixtures/overlay/election/2027/score/entry.md +0 -11
  59. package/templates/golden-path/test/fixtures/overlay/election/2027/score/mocks/responses.json +0 -7
  60. package/templates/golden-path/test/fixtures/overlay/election/results/entry.md +0 -24
  61. package/templates/golden-path/test/fixtures/overlay/election/results/mocks/turnout.json +0 -1
  62. package/templates/golden-path/test/fixtures/overlay/orders/entry.md +0 -12
  63. package/templates/golden-path/test/fixtures/overlay/orders/mocks/responses.json +0 -36
  64. package/templates/golden-path/test/fixtures/overlay/platform/email/entry.md +0 -12
  65. package/templates/golden-path/test/fixtures/overlay/platform/email/mocks/responses.json +0 -11
  66. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/entry.md +0 -8
  67. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/mocks/responses.json +0 -13
  68. package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +0 -12
  69. package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +0 -71
  70. package/templates/golden-path/test/fixtures/overlay/platform/sms/entry.md +0 -10
  71. package/templates/golden-path/test/fixtures/overlay/platform/sms/mocks/responses.json +0 -7
  72. package/templates/golden-path/test/fixtures/overlay/score/entry.md +0 -10
  73. package/templates/golden-path/test/fixtures/overlay/score/mocks/responses.json +0 -7
  74. package/templates/golden-path/test/harness.ts +0 -153
  75. package/templates/golden-path/test/interaction.test.ts +0 -230
  76. package/templates/golden-path/test/legal-identity.test.ts +0 -323
  77. package/templates/golden-path/test/membership.test.ts +0 -105
  78. package/templates/golden-path/test/notification-response.test.ts +0 -79
  79. package/templates/golden-path/test/payment-app.test.ts +0 -210
  80. package/templates/golden-path/test/payment-offline.test.ts +0 -91
  81. package/templates/golden-path/test/payment.test.ts +0 -427
  82. package/templates/golden-path/test/payments-offline.ts +0 -33
  83. package/templates/golden-path/test/read-dataset.test.ts +0 -387
  84. package/templates/golden-path/test/service-call.test.ts +0 -166
  85. package/templates/golden-path/test/smoke.test.ts +0 -464
  86. package/templates/golden-path/tsconfig.json +0 -20
  87. package/templates/golden-path/tsconfig.worker.json +0 -21
  88. package/templates/golden-path/vite.config.ts +0 -12
  89. package/templates/golden-path/vitest.config.ts +0 -28
  90. package/templates/golden-path/web/App.tsx +0 -478
  91. package/templates/golden-path/web/app.css +0 -83
  92. package/templates/golden-path/web/main.tsx +0 -51
  93. package/templates/golden-path/web/pple.ts +0 -124
  94. package/templates/golden-path/web/vite-env.d.ts +0 -10
  95. package/templates/golden-path/wrangler.jsonc +0 -89
  96. package/templates/payment-bridge/.github/workflows/ci.yml +0 -21
  97. package/templates/payment-bridge/CLAUDE.md +0 -9
  98. package/templates/payment-bridge/README.md +0 -57
  99. package/templates/payment-bridge/docs/verify-webhook.md +0 -80
  100. package/templates/payment-bridge/docs/verify-webhook.ts +0 -29
  101. package/templates/payment-bridge/gitignore +0 -5
  102. package/templates/payment-bridge/package-lock.json +0 -4198
  103. package/templates/payment-bridge/package.json +0 -21
  104. package/templates/payment-bridge/src/bridge-key.ts +0 -18
  105. package/templates/payment-bridge/src/env.ts +0 -14
  106. package/templates/payment-bridge/src/index.ts +0 -39
  107. package/templates/payment-bridge/src/platform.ts +0 -49
  108. package/templates/payment-bridge/src/webhook.ts +0 -86
  109. package/templates/payment-bridge/test/docs.test.ts +0 -9
  110. package/templates/payment-bridge/test/fixtures/payments-responses.json +0 -71
  111. package/templates/payment-bridge/test/harness.ts +0 -78
  112. package/templates/payment-bridge/test/inbound.test.ts +0 -138
  113. package/templates/payment-bridge/test/webhook.test.ts +0 -174
  114. package/templates/payment-bridge/tsconfig.json +0 -22
  115. package/templates/payment-bridge/vitest.config.ts +0 -8
  116. package/templates/payment-bridge/wrangler.jsonc +0 -15
  117. package/templates/payment-bridge.version +0 -1
@@ -1,41 +0,0 @@
1
- {
2
- "name": "pple-app",
3
- "private": true,
4
- "type": "module",
5
- "//": "Golden-path template for a PPLE Platform Builder App. Rename this to your app slug. Everything runs on Cloudflare: a Hono Worker (API), D1 (database), R2 (files); the UI is a React SPA built with the People's Party design system.",
6
- "scripts": {
7
- "predev": "wrangler d1 migrations apply DB --local",
8
- "dev": "vite dev",
9
- "build": "vite build && node scripts/assert-dev-compiled-out.mjs",
10
- "preview": "vite preview",
11
- "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.worker.json",
12
- "test": "vitest run",
13
- "test:watch": "vitest",
14
- "db:migrate:local": "wrangler d1 migrations apply DB --local",
15
- "deploy": "vite build && wrangler deploy"
16
- },
17
- "dependencies": {
18
- "@fontsource/ibm-plex-sans-thai-looped": "^5.3.0",
19
- "@pplethai/components": "^2.0.0",
20
- "@pplethai/pple-today-miniapp-sdk": "^0.1.4",
21
- "hono": "^4.12.30",
22
- "lucide-react": "^0.469.0",
23
- "react": "^19.2.0",
24
- "react-dom": "^19.2.0",
25
- "react-hook-form": "^7.81.0",
26
- "zod": "^4.4.0"
27
- },
28
- "devDependencies": {
29
- "@cloudflare/vite-plugin": "^1.45.1",
30
- "@cloudflare/vitest-pool-workers": "^0.18.6",
31
- "@cloudflare/workers-types": "^5.20260714.1",
32
- "@types/react": "^19.2.0",
33
- "@types/react-dom": "^19.2.0",
34
- "@vitejs/plugin-react": "^6.0.3",
35
- "typescript": "^5.8.0",
36
- "vite": "^8.1.5",
37
- "vitest": "^4.1.10",
38
- "wrangler": "^4.112.0",
39
- "yaml": "^2.9.1"
40
- }
41
- }
@@ -1,45 +0,0 @@
1
- // The deployed Worker is dist/<worker name>/index.js (the name in
2
- // wrangler.jsonc, which `pple init` sets to the app's slug), found the way the
3
- // deploy workflow finds it. Vite inlines
4
- // `import.meta.env.DEV` to false and drops the Persona bypass and the
5
- // offline registry wrapper (ADR-0011). Strings that exist only in those
6
- // modules must not survive. The client bundle is a different compile.
7
-
8
- import fs from "node:fs";
9
- import path from "node:path";
10
- import { fileURLToPath } from "node:url";
11
-
12
- const dist = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../dist");
13
- const bundle = (fs.existsSync(dist) ? fs.readdirSync(dist) : [])
14
- .filter((dir) => dir !== "client")
15
- .map((dir) => path.join(dist, dir, "index.js"))
16
- .find((file) => fs.existsSync(file));
17
-
18
- if (!bundle) {
19
- console.error(`production Worker bundle not found at ${dist}/*/index.js`);
20
- process.exit(1);
21
- }
22
-
23
- const source = fs.readFileSync(bundle, "utf8").replace(/\/\/# sourceMappingURL[\s\S]*$/, "");
24
-
25
- const forbidden = [
26
- ["dev-hq-staff", "Persona bypass"],
27
- ["Local Dev (HQ)", "Persona bypass"],
28
- ["บุคคลทดสอบ ออฟไลน์", "offline Legal Identity"],
29
- ["dev-consumer", "registry dev wrapper"],
30
- ["DEV_CONSUMER", "registry dev wrapper"],
31
- ["dev-provider", "registry dev wrapper"],
32
- ["registry handler missing", "registry dev wrapper"],
33
- ["x-pple-mock", "offline callService"],
34
- ["../.pple/registry", "offline callService overlay glob"],
35
- ["ไม่มีข้อมูลจำลอง", "offline callService no_mock"],
36
- ];
37
-
38
- const found = forbidden.filter(([needle]) => source.includes(needle));
39
- if (found.length > 0) {
40
- console.error(`production Worker still contains dev-only code (${bundle}):`);
41
- for (const [needle, why] of found) console.error(` ${JSON.stringify(needle)} (${why})`);
42
- process.exit(1);
43
- }
44
-
45
- console.log("production Worker has no dev-only registry or Persona code");
@@ -1,325 +0,0 @@
1
- // The API contract shared by the Worker (src/) and the React app (web/).
2
- // Defining request/response shapes once, as Zod schemas, means the server
3
- // validates exactly what the client promises to send — and both sides share
4
- // the inferred TypeScript types.
5
- import { z } from "zod";
6
-
7
- /**
8
- * The signed-in caller, as the Worker resolves it from the PPLE ID token
9
- * (src/auth.ts). Two faces:
10
- *
11
- * - `actor` — the real human clicking (`sub`, name, mobile, KYC Status,
12
- * party membership). Use for audit and display only.
13
- * - `effective` — what they may do, including `sub` of the person whose
14
- * authority is in effect. Gate every authorization decision on this,
15
- * never on `actor`. Under Delegation these are the supervisor's values and
16
- * `isDelegated` is true. See docs/adr/0012 and CONTEXT.md.
17
- */
18
- /**
19
- * KYC Status (CONTEXT.md). Whether PPLE ID knows a real person behind this
20
- * account. It carries no name and no citizen ID, and it belongs to the human,
21
- * so it sits on the actor — a delegate does not inherit a supervisor's status.
22
- * `verified` does not prove the account holder is the cardholder.
23
- */
24
- export const KycStatusSchema = z.object({
25
- status: z.enum(["none", "pending_review", "verified", "rejected"]),
26
- verified: z.boolean(),
27
- verifiedAt: z.string().nullable(),
28
- /** `membership` for an active member, `kyc` for a national-ID check, or null. */
29
- source: z.enum(["membership", "kyc"]).nullable(),
30
- });
31
- export type KycStatus = z.infer<typeof KycStatusSchema>;
32
-
33
- /**
34
- * Active party membership as the Identity carries it. `memberSince` is the
35
- * ISO date (`YYYY-MM-DD`) PPLE ID reports. The actor field is null when the
36
- * person is not an active member, or the lookup failed.
37
- */
38
- export const MembershipSchema = z.object({
39
- memberSince: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
40
- });
41
- export type Membership = z.infer<typeof MembershipSchema>;
42
-
43
- export const ActorSchema = z.object({
44
- sub: z.string(),
45
- name: z.string().nullable(),
46
- /** Thai mobile number, the join key across PPLE systems. May be null. */
47
- mobile: z.string().nullable(),
48
- /** Never copied onto `effective`. See KycStatusSchema. */
49
- kyc: KycStatusSchema,
50
- /**
51
- * The human's party membership. Never copied onto `effective`: a delegate
52
- * does not inherit a supervisor's membership. A lookup error is null.
53
- */
54
- membership: MembershipSchema.nullable(),
55
- });
56
- export type Actor = z.infer<typeof ActorSchema>;
57
-
58
- export const EffectiveSchema = z.object({
59
- /** True ⇒ the values below are borrowed from a supervisor (see Actor). */
60
- isDelegated: z.boolean(),
61
- /**
62
- * PPLE ID sub of the person whose authority is in effect. The actor's own
63
- * sub when nobody is delegating. Under Delegation, the supervisor's Zitadel
64
- * sub, or null when PPLE ID has none. Null matches no custom `subs`.
65
- */
66
- sub: z.string().min(1).nullable(),
67
- /** The Role in play now (one of `eligibleRoles`), e.g. "hq", "province". */
68
- activeRole: z.string(),
69
- eligibleRoles: z.array(z.string()),
70
- /** Geographic scope, or ["all"]. */
71
- provinces: z.array(z.string()),
72
- /** Capabilities, e.g. "platform:admin", "exco", "province_co". */
73
- extraRoles: z.array(z.string()),
74
- });
75
- export type Effective = z.infer<typeof EffectiveSchema>;
76
-
77
- export const IdentitySchema = z.object({
78
- actor: ActorSchema,
79
- effective: EffectiveSchema,
80
- });
81
- export type Identity = z.infer<typeof IdentitySchema>;
82
-
83
- /** What `GET /api/me` returns: the caller's Identity. */
84
- export const MeSchema = IdentitySchema;
85
- export type Me = Identity;
86
-
87
- /** A row in the example `notes` table (the D1 read/write demo). */
88
- export const NoteSchema = z.object({
89
- id: z.number(),
90
- body: z.string(),
91
- createdAt: z.string(),
92
- });
93
- export type Note = z.infer<typeof NoteSchema>;
94
-
95
- /** Body for creating a note. */
96
- export const CreateNoteSchema = z.object({
97
- body: z.string().trim().min(1).max(500),
98
- });
99
- export type CreateNote = z.infer<typeof CreateNoteSchema>;
100
-
101
- /**
102
- * Body for starting a donation (the payments demo). The amount is in satang
103
- * (100 satang is 1 baht) and must be a positive whole number. The platform
104
- * checks the party's own limits at checkout, not here.
105
- */
106
- export const CreateDonationSchema = z.object({
107
- amountSatang: z.number().int().positive().max(100_000_000),
108
- });
109
- export type CreateDonation = z.infer<typeof CreateDonationSchema>;
110
-
111
- /** An uploaded file's metadata (the R2 demo). */
112
- export const UploadedFileSchema = z.object({
113
- key: z.string(),
114
- name: z.string(),
115
- size: z.number(),
116
- uploadedAt: z.string(),
117
- });
118
- export type UploadedFile = z.infer<typeof UploadedFileSchema>;
119
-
120
- /**
121
- * One person a Direct Notification names: a PPLE ID `sub` **or** a mobile
122
- * number, exactly one per entry. Both are accepted because a Builder's source
123
- * of truth may be its own traffic (every request carries `actor.sub` and
124
- * `actor.mobile`) or a list it holds by number.
125
- *
126
- * Strict objects, so an entry naming both is rejected here rather than at the
127
- * platform. TypeScript alone cannot catch that one — `{ sub, phone }` is
128
- * assignable to the union — so this runtime check is the one that matters.
129
- */
130
- export const NotificationRecipientSchema = z.union([
131
- z.strictObject({ sub: z.string().trim().min(1) }),
132
- z.strictObject({ phone: z.string().trim().min(1) }),
133
- ]);
134
- export type NotificationRecipient = z.infer<typeof NotificationRecipientSchema>;
135
-
136
- /**
137
- * The platform's per-call cap. Over it is a refusal, never a silent
138
- * truncation, so chunk a long list deliberately rather than discovering half
139
- * your people were dropped.
140
- */
141
- export const MAX_DIRECT_RECIPIENTS = 200;
142
-
143
- /**
144
- * Who a send is for — **required**, and a discriminated union on purpose.
145
- *
146
- * - `all` — a **Broadcast Notification** (การแจ้งเตือนทุกคน) to everyone this
147
- * app can reach: its App Users ∩ its current publication-tier audience.
148
- * - `direct` — a **Direct Notification** (การแจ้งเตือนรายบุคคล) to the people
149
- * it names.
150
- *
151
- * Naming **narrows** that reachable set and never widens it: a named person
152
- * who has not opened this app receives nothing and comes back
153
- * `not_reachable`. The union is required because the dangerous bug here is
154
- * omission — a dropped field silently turning a message meant for one person
155
- * into a message to every App User. Leaving the audience out is a compile
156
- * error here and a refusal at the platform; it is never a broadcast.
157
- */
158
- export const NotificationAudienceSchema = z.discriminatedUnion("kind", [
159
- z.object({ kind: z.literal("all") }),
160
- z.object({
161
- kind: z.literal("direct"),
162
- recipients: z
163
- .array(NotificationRecipientSchema)
164
- .min(1)
165
- .max(MAX_DIRECT_RECIPIENTS),
166
- }),
167
- ]);
168
- export type NotificationAudience = z.infer<typeof NotificationAudienceSchema>;
169
-
170
- /**
171
- * The names an Action may take as its `icon`: PPLE Today's fixed allowlist.
172
- * Anything else is refused by PPLE Today, not here.
173
- */
174
- export type InteractionIconName =
175
- | "check"
176
- | "x"
177
- | "thumbs-up"
178
- | "thumbs-down"
179
- | "calendar-check"
180
- | "calendar-x"
181
- | "clock"
182
- | "send"
183
- | "heart"
184
- | "star"
185
- | "flag"
186
- | "user-check"
187
- | "user-x"
188
- | "help";
189
-
190
- export interface InteractionOption {
191
- id: string;
192
- label: string;
193
- }
194
-
195
- /** One input an Interactive Notification asks for, above its actions. */
196
- export type InteractionField =
197
- | {
198
- id: string;
199
- type: "text";
200
- label: string;
201
- description?: string;
202
- required?: boolean;
203
- placeholder?: string;
204
- multiline?: boolean;
205
- maxLength?: number;
206
- minLength?: number;
207
- }
208
- | {
209
- id: string;
210
- type: "radio";
211
- label: string;
212
- description?: string;
213
- required?: boolean;
214
- options: InteractionOption[];
215
- default?: string;
216
- }
217
- | {
218
- id: string;
219
- type: "checkbox";
220
- label: string;
221
- description?: string;
222
- required?: boolean;
223
- options: InteractionOption[];
224
- min?: number;
225
- max?: number;
226
- default?: string[];
227
- };
228
-
229
- /** A button that submits the answer. Every interaction has one to three. */
230
- export interface InteractionAction {
231
- id: string;
232
- label: string;
233
- icon?: InteractionIconName;
234
- style?: "primary" | "outline" | "destructive";
235
- /** Field ids this action needs filled, on top of fields marked `required`. */
236
- requires?: string[];
237
- confirm?: { title: string; message?: string };
238
- }
239
-
240
- /**
241
- * What an Interactive Notification asks its recipients. Passed to PPLE Today
242
- * exactly as written: PPLE Today owns the rules (id format, limits, expiry),
243
- * and a broken one comes back as `invalid_interaction` naming the failing
244
- * path. The type is here so an editor can help; it is not a validator.
245
- */
246
- export interface Interaction {
247
- /** Opaque to the platform; echoed back with the answer. At most 200 chars. */
248
- ref?: string;
249
- /** ISO date-time with `Z` or an offset, in the future, at most 30 days out. */
250
- expiresAt?: string;
251
- fields?: InteractionField[];
252
- actions: InteractionAction[];
253
- /** `false` keeps action buttons off the OS notification. Default `true`. */
254
- tray?: boolean;
255
- /**
256
- * Asks for a Live Activity on capable iPhones: the buttons stay on the Lock
257
- * Screen and in the Dynamic Island, with no long press. For urgent questions
258
- * only. Everyone else gets the ordinary notification, and every recipient
259
- * still has the question in PPLE Today. PPLE Today refuses it (as
260
- * `invalid_interaction`) unless `expiresAt` is set and at most 8 h ahead,
261
- * `tray` is not `false`, and the question shows buttons on the phone: no
262
- * `radio`, `checkbox` or `required` field, and not a lone `text` field with
263
- * one action (the reply box) unless that action has `confirm`.
264
- */
265
- liveActivity?: boolean;
266
- }
267
-
268
- /**
269
- * A notification to send. The privacy model in one line: this app can reach
270
- * the people who already use it — and now say which of them it means — and no
271
- * one else (see src/notify.ts and docs/integration/direct-notifications.md).
272
- *
273
- * Content is uniform across every recipient of a call; a personalized message
274
- * is one call per person.
275
- *
276
- * Optional `linkPath` is a path-only deep link into *this* app (must start
277
- * with `/`). The platform joins it to this app's known entry and rejects
278
- * absolute URLs / cross-app destinations. Free-form destinations that could
279
- * address another mini app are not accepted.
280
- */
281
- export const NotificationSchema = z.object({
282
- audience: NotificationAudienceSchema,
283
- title: z.string().trim().min(1).max(120),
284
- body: z.string().trim().min(1).max(500),
285
- linkPath: z
286
- .string()
287
- .trim()
288
- .regex(/^\/(?!\/).*/, "linkPath must be a path starting with a single /")
289
- .optional(),
290
- /**
291
- * Optional: makes retrying after a network timeout safe instead of
292
- * double-notifying everyone who already received it. Reusing a key with a
293
- * recipient list of a different length is a conflict, not a replay.
294
- */
295
- idempotencyKey: z.string().trim().min(1).optional(),
296
- /**
297
- * Makes this an Interactive Notification. Only checked to be an object here;
298
- * PPLE Today validates it and names the failing path.
299
- */
300
- interaction: z
301
- .custom<Interaction>((v) => typeof v === "object" && v !== null && !Array.isArray(v))
302
- .optional(),
303
- });
304
- export type Notification = z.infer<typeof NotificationSchema>;
305
-
306
- /**
307
- * What happened to one named recipient of a Direct Notification.
308
- *
309
- * `not_reachable` is **one collapsed reason**, deliberately: no PPLE ID
310
- * account at all, an account that has never opened this app, someone outside
311
- * this app's current tier audience, or someone opted out. Do not decompose it,
312
- * and do not show a Builder a guess about which applies — separating "not a
313
- * user of this app" from "no such person" would turn every Builder App into a
314
- * lookup service answering *"is this number a party workforce member?"* about
315
- * people who never consented to it. See docs/adr/0017.
316
- *
317
- * What it *is* good for: pruning. A stale entry costs quota on every send
318
- * until it is removed, because a send debits the reach it requested, not the
319
- * reach it achieved.
320
- */
321
- export const NotificationDeliverySchema = z.object({
322
- recipient: NotificationRecipientSchema,
323
- status: z.enum(["delivered", "not_reachable"]),
324
- });
325
- export type NotificationDelivery = z.infer<typeof NotificationDeliverySchema>;
@@ -1,230 +0,0 @@
1
- // PPLE ID authentication.
2
- //
3
- // PPLE Today launches your mini-app with an access token in the URL; the
4
- // frontend SDK captures it and sends it as a bearer token on every API call.
5
- // The Worker validates that token server-side against the PPLE ID userinfo
6
- // endpoint — the same seam the platform's own services use. There is no local
7
- // session or cookie: each request carries the token.
8
- //
9
- // The token resolves to an Identity with two faces (see shared/api.ts):
10
- // • actor — the real human clicking (audit/display only)
11
- // • effective — what they may do (gate authorization on this)
12
- // Under Delegation, effective.* are the supervisor's and effective.isDelegated
13
- // is true, while actor stays the delegate. effective.sub is the PPLE ID sub
14
- // of the person whose authority is in effect. See docs/adr/0012.
15
- import type { Identity } from "../shared/api";
16
- import { resolveDevPersona } from "./dev-personas";
17
-
18
- export type { Identity };
19
-
20
- export type AuthResult =
21
- | { ok: true; identity: Identity }
22
- | { ok: false; status: 401 | 502 };
23
-
24
- interface AuthEnv {
25
- SSO_BASE_URL: string;
26
- /**
27
- * Local development only: which mock persona to sign in as (see
28
- * src/dev-personas.ts). Unset means the default persona; "none" turns the
29
- * bypass off so you can exercise the real PPLE ID path locally.
30
- */
31
- DEV_PERSONA?: string;
32
- }
33
-
34
- /**
35
- * Resolve the caller's identity from a bearer token. Distinguishes an
36
- * invalid token (401) from PPLE ID being unreachable (502) so the client can
37
- * tell "sign in again" apart from "try again later".
38
- */
39
- export async function authenticate(
40
- env: AuthEnv,
41
- token: string,
42
- fetchImpl: typeof fetch = globalThis.fetch.bind(globalThis),
43
- ): Promise<AuthResult> {
44
- // Local development bypass. `import.meta.env.DEV` is true under `vite dev`
45
- // (and tests) and statically `false` in `vite build`, so this whole block is
46
- // dead-code-eliminated from the deployed Worker — the bypass cannot exist in
47
- // production (docs/adr/0011). No token, no `.dev.vars`, no PPLE Today needed;
48
- // set DEV_PERSONA="none" to fall through to the real path instead.
49
- if (import.meta.env.DEV && env.DEV_PERSONA !== "none") {
50
- return { ok: true, identity: resolveDevPersona(env.DEV_PERSONA) };
51
- }
52
-
53
- if (!token) return { ok: false, status: 401 };
54
-
55
- const res = await fetchImpl(`${env.SSO_BASE_URL}/oidc/v1/userinfo`, {
56
- headers: { authorization: `Bearer ${token}` },
57
- });
58
- if (res.status === 401 || res.status === 403) return { ok: false, status: 401 };
59
- if (!res.ok) return { ok: false, status: 502 };
60
-
61
- const body = (await res.json().catch(() => ({}))) as RawUserInfo;
62
- if (!body.sub) return { ok: false, status: 502 };
63
- return { ok: true, identity: toIdentity(body) };
64
- }
65
-
66
- // --- Parsing the PPLE ID userinfo response -------------------------------
67
- //
68
- // Organization members carry an `ad` block. Its `user` is the person whose
69
- // authority is in effect (a delegate is already resolved to their supervisor
70
- // here); `actualPpleUser` is the real human who logged in. Every level is
71
- // optional, so a missing or oddly-shaped payload yields empty values rather
72
- // than throwing. See pple-sso's lib/ad/legacy-context.ts for the full shape.
73
-
74
- interface RawPerson {
75
- id?: number;
76
- role?: string;
77
- mobile?: string;
78
- /**
79
- * The person's Zitadel user id, which is their PPLE ID sub. Read only for
80
- * the supervisor under Delegation. Never `sso_user_id`.
81
- */
82
- zitadel_user_id?: unknown;
83
- metadata?: { ad?: { extra_roles?: unknown; is_province_coordinator?: unknown } };
84
- }
85
-
86
- interface RawAd {
87
- user?: RawPerson;
88
- actualPpleUser?: RawPerson;
89
- activeRole?: string;
90
- eligibleRoles?: unknown;
91
- eligibleProvinces?: unknown;
92
- }
93
-
94
- interface RawKyc {
95
- status?: string;
96
- verified?: boolean;
97
- verifiedAt?: string | null;
98
- source?: string | null;
99
- }
100
-
101
- interface RawUserInfo {
102
- sub?: string;
103
- name?: string;
104
- /** KYC Status of the human who logged in. Absent until PPLE ID sends it. */
105
- kyc?: RawKyc;
106
- /**
107
- * Party membership of the logged-in human, beside `ad` and `kyc`.
108
- * PPLE ID sends an object or null. See membershipOf.
109
- */
110
- membership?: unknown;
111
- ad?: RawAd;
112
- }
113
-
114
- /** `YYYY-MM-DD`, the shape of userinfo `membership.memberSince`. */
115
- const MEMBER_SINCE = /^\d{4}-\d{2}-\d{2}$/;
116
-
117
- /**
118
- * Reduce userinfo `membership` to `{ memberSince }` or null.
119
- *
120
- * PPLE ID sends `{ type, memberSince, registeredAddress }` only while the
121
- * membership is legally active, looked up by the logged-in human's phone.
122
- * A lookup error arrives as null. The Identity keeps the date and drops the
123
- * address. A missing or odd value is null, so it cannot pass `member`.
124
- */
125
- function membershipOf(value: unknown): Identity["actor"]["membership"] {
126
- if (value === null || value === undefined || typeof value !== "object") return null;
127
- const memberSince = (value as { memberSince?: unknown }).memberSince;
128
- if (typeof memberSince !== "string" || !MEMBER_SINCE.test(memberSince)) return null;
129
- return { memberSince };
130
- }
131
-
132
- /** Zitadel user ids are decimal strings. Anything else is not a PPLE ID sub. */
133
- const ZITADEL_SUB = /^\d+$/;
134
-
135
- /**
136
- * `effective.sub` (ADR-0028, #266).
137
- *
138
- * Not delegated (`isDelegated` false): the Actor's `sub` from the token. It
139
- * is never read from `ad`. PPLE ID falls back silently to the logged-in row
140
- * when the supervisor row is missing, and that reads as not delegated.
141
- *
142
- * Delegated: `ad.user` is the supervisor only when the logged-in human's role
143
- * is `delegate`. The supervisor's sub is `ad.user.zitadel_user_id`.
144
- * `sso_user_id` is legacy (a Supabase UUID or null) and is never read. Any
145
- * other delegated shape, or a missing, null, or non-Zitadel id, is null. It
146
- * is never the Actor's sub, because `effective` is someone else's authority
147
- * here. Null matches no custom `subs`.
148
- */
149
- function effectiveSub(
150
- actorSub: string,
151
- isDelegated: boolean,
152
- user: RawPerson | undefined,
153
- actual: RawPerson | undefined,
154
- ): string | null {
155
- if (!isDelegated) return actorSub;
156
- if (actual?.role !== "delegate") return null;
157
- const zitadel = user?.zitadel_user_id;
158
- if (typeof zitadel !== "string" || !ZITADEL_SUB.test(zitadel)) return null;
159
- return zitadel;
160
- }
161
-
162
- function stringArray(value: unknown): string[] {
163
- return Array.isArray(value)
164
- ? value.filter((v): v is string => typeof v === "string")
165
- : [];
166
- }
167
-
168
- /** Extra-roles nested under a person's AD metadata, plus the synthetic
169
- * `province_co` a province coordinator carries. */
170
- function extraRolesOf(person: RawPerson | undefined): string[] {
171
- const ad = person?.metadata?.ad;
172
- const roles = stringArray(ad?.extra_roles);
173
- if (person?.role === "province" && ad?.is_province_coordinator === true) {
174
- roles.push("province_co");
175
- }
176
- return roles;
177
- }
178
-
179
- const KYC_STATUSES = ["none", "pending_review", "verified", "rejected"] as const;
180
- const KYC_SOURCES = ["membership", "kyc"] as const;
181
-
182
- /** A missing or odd `kyc` is "PPLE ID has not verified this person", not an error. */
183
- function kycOf(raw: RawKyc | undefined): Identity["actor"]["kyc"] {
184
- const status = KYC_STATUSES.find((s) => s === raw?.status) ?? "none";
185
- const source = KYC_SOURCES.find((s) => s === raw?.source) ?? null;
186
- return {
187
- status,
188
- verified: raw?.verified === true,
189
- verifiedAt: typeof raw?.verifiedAt === "string" ? raw.verifiedAt : null,
190
- source,
191
- };
192
- }
193
-
194
- function toIdentity(body: RawUserInfo): Identity {
195
- const ad = body.ad;
196
- const effectivePerson = ad?.user;
197
- // When nobody is delegating, `actualPpleUser` mirrors `user`.
198
- const actualPerson = ad?.actualPpleUser ?? effectivePerson;
199
- const isDelegated =
200
- effectivePerson?.id !== undefined &&
201
- actualPerson?.id !== undefined &&
202
- effectivePerson.id !== actualPerson.id;
203
- const activeRole = ad?.activeRole ?? effectivePerson?.role ?? "";
204
- const eligibleRoles = stringArray(ad?.eligibleRoles);
205
- // Top-level `sub` is the OIDC subject of the human who logged in.
206
- const actorSub = body.sub as string;
207
-
208
- return {
209
- actor: {
210
- sub: actorSub,
211
- name: body.name ?? null,
212
- mobile: actualPerson?.mobile ?? null,
213
- // The human's own KYC Status. A delegated session still reports the
214
- // actor's, never the supervisor's, and effective never carries it.
215
- kyc: kycOf(body.kyc),
216
- // The human's own membership, likewise. Top-level userinfo, not `ad.user`
217
- // (under Delegation `ad.user` is the supervisor).
218
- membership: membershipOf(body.membership),
219
- },
220
- effective: {
221
- isDelegated,
222
- sub: effectiveSub(actorSub, isDelegated, effectivePerson, ad?.actualPpleUser),
223
- activeRole,
224
- eligibleRoles:
225
- eligibleRoles.length > 0 ? eligibleRoles : activeRole ? [activeRole] : [],
226
- provinces: stringArray(ad?.eligibleProvinces),
227
- extraRoles: extraRolesOf(effectivePerson),
228
- },
229
- };
230
- }