@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.
- package/README.md +12 -14
- package/dist/bin.js +102 -102
- package/package.json +3 -6
- package/templates/golden-path/.dev.vars.example +0 -33
- package/templates/golden-path/.env.example +0 -10
- package/templates/golden-path/.github/workflows/ci.yml +0 -22
- package/templates/golden-path/AGENTS.md +0 -1
- package/templates/golden-path/CLAUDE.md +0 -187
- package/templates/golden-path/README.md +0 -118
- package/templates/golden-path/gitignore +0 -17
- package/templates/golden-path/index.html +0 -16
- package/templates/golden-path/migrations/0001_init.sql +0 -10
- package/templates/golden-path/overlay-mtime.mjs +0 -30
- package/templates/golden-path/package-lock.json +0 -4318
- package/templates/golden-path/package.json +0 -41
- package/templates/golden-path/scripts/assert-dev-compiled-out.mjs +0 -45
- package/templates/golden-path/shared/api.ts +0 -325
- package/templates/golden-path/src/auth.ts +0 -230
- package/templates/golden-path/src/call-service.ts +0 -147
- package/templates/golden-path/src/dataset-query.ts +0 -470
- package/templates/golden-path/src/dataset-schema.ts +0 -398
- package/templates/golden-path/src/db.ts +0 -32
- package/templates/golden-path/src/dev-call-service.ts +0 -392
- package/templates/golden-path/src/dev-personas.ts +0 -186
- package/templates/golden-path/src/dev-read-dataset.ts +0 -444
- package/templates/golden-path/src/dev-registry.ts +0 -294
- package/templates/golden-path/src/email.ts +0 -224
- package/templates/golden-path/src/entry-name.ts +0 -114
- package/templates/golden-path/src/env.ts +0 -38
- package/templates/golden-path/src/files.ts +0 -38
- package/templates/golden-path/src/identity-header.ts +0 -17
- package/templates/golden-path/src/index.ts +0 -276
- package/templates/golden-path/src/legal-identity.ts +0 -180
- package/templates/golden-path/src/levels.ts +0 -132
- package/templates/golden-path/src/notification-response.ts +0 -55
- package/templates/golden-path/src/notify.ts +0 -311
- package/templates/golden-path/src/payment.ts +0 -554
- package/templates/golden-path/src/read-dataset.ts +0 -490
- package/templates/golden-path/src/registry.ts +0 -128
- package/templates/golden-path/src/vite-env.d.ts +0 -27
- package/templates/golden-path/test/apply-migrations.ts +0 -4
- package/templates/golden-path/test/call-service.test.ts +0 -288
- package/templates/golden-path/test/dev-call-service.test.ts +0 -455
- package/templates/golden-path/test/dev-read-dataset.test.ts +0 -379
- package/templates/golden-path/test/dev-registry.test.ts +0 -404
- package/templates/golden-path/test/effective-sub.test.ts +0 -101
- package/templates/golden-path/test/email-offline.test.ts +0 -51
- package/templates/golden-path/test/email.test.ts +0 -117
- package/templates/golden-path/test/env.d.ts +0 -17
- package/templates/golden-path/test/fixtures/overlay/branch-list/entry.md +0 -85
- package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/audience.json +0 -3
- package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/named.json +0 -3
- package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/offices.json +0 -6
- package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/roster.json +0 -3
- package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/summary.json +0 -1
- package/templates/golden-path/test/fixtures/overlay/catalog/entry.md +0 -8
- package/templates/golden-path/test/fixtures/overlay/catalog/mocks/responses.json +0 -7
- package/templates/golden-path/test/fixtures/overlay/election/2027/score/entry.md +0 -11
- package/templates/golden-path/test/fixtures/overlay/election/2027/score/mocks/responses.json +0 -7
- package/templates/golden-path/test/fixtures/overlay/election/results/entry.md +0 -24
- package/templates/golden-path/test/fixtures/overlay/election/results/mocks/turnout.json +0 -1
- package/templates/golden-path/test/fixtures/overlay/orders/entry.md +0 -12
- package/templates/golden-path/test/fixtures/overlay/orders/mocks/responses.json +0 -36
- package/templates/golden-path/test/fixtures/overlay/platform/email/entry.md +0 -12
- package/templates/golden-path/test/fixtures/overlay/platform/email/mocks/responses.json +0 -11
- package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/entry.md +0 -8
- package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/mocks/responses.json +0 -13
- package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +0 -12
- package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +0 -71
- package/templates/golden-path/test/fixtures/overlay/platform/sms/entry.md +0 -10
- package/templates/golden-path/test/fixtures/overlay/platform/sms/mocks/responses.json +0 -7
- package/templates/golden-path/test/fixtures/overlay/score/entry.md +0 -10
- package/templates/golden-path/test/fixtures/overlay/score/mocks/responses.json +0 -7
- package/templates/golden-path/test/harness.ts +0 -153
- package/templates/golden-path/test/interaction.test.ts +0 -230
- package/templates/golden-path/test/legal-identity.test.ts +0 -323
- package/templates/golden-path/test/membership.test.ts +0 -105
- package/templates/golden-path/test/notification-response.test.ts +0 -79
- package/templates/golden-path/test/payment-app.test.ts +0 -210
- package/templates/golden-path/test/payment-offline.test.ts +0 -91
- package/templates/golden-path/test/payment.test.ts +0 -427
- package/templates/golden-path/test/payments-offline.ts +0 -33
- package/templates/golden-path/test/read-dataset.test.ts +0 -387
- package/templates/golden-path/test/service-call.test.ts +0 -166
- package/templates/golden-path/test/smoke.test.ts +0 -464
- package/templates/golden-path/tsconfig.json +0 -20
- package/templates/golden-path/tsconfig.worker.json +0 -21
- package/templates/golden-path/vite.config.ts +0 -12
- package/templates/golden-path/vitest.config.ts +0 -28
- package/templates/golden-path/web/App.tsx +0 -478
- package/templates/golden-path/web/app.css +0 -83
- package/templates/golden-path/web/main.tsx +0 -51
- package/templates/golden-path/web/pple.ts +0 -124
- package/templates/golden-path/web/vite-env.d.ts +0 -10
- package/templates/golden-path/wrangler.jsonc +0 -89
- package/templates/payment-bridge/.github/workflows/ci.yml +0 -21
- package/templates/payment-bridge/CLAUDE.md +0 -9
- package/templates/payment-bridge/README.md +0 -57
- package/templates/payment-bridge/docs/verify-webhook.md +0 -80
- package/templates/payment-bridge/docs/verify-webhook.ts +0 -29
- package/templates/payment-bridge/gitignore +0 -5
- package/templates/payment-bridge/package-lock.json +0 -4198
- package/templates/payment-bridge/package.json +0 -21
- package/templates/payment-bridge/src/bridge-key.ts +0 -18
- package/templates/payment-bridge/src/env.ts +0 -14
- package/templates/payment-bridge/src/index.ts +0 -39
- package/templates/payment-bridge/src/platform.ts +0 -49
- package/templates/payment-bridge/src/webhook.ts +0 -86
- package/templates/payment-bridge/test/docs.test.ts +0 -9
- package/templates/payment-bridge/test/fixtures/payments-responses.json +0 -71
- package/templates/payment-bridge/test/harness.ts +0 -78
- package/templates/payment-bridge/test/inbound.test.ts +0 -138
- package/templates/payment-bridge/test/webhook.test.ts +0 -174
- package/templates/payment-bridge/tsconfig.json +0 -22
- package/templates/payment-bridge/vitest.config.ts +0 -8
- package/templates/payment-bridge/wrangler.jsonc +0 -15
- package/templates/payment-bridge.version +0 -1
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
// R2 (object storage) upload example. R2 is your app's private bucket for
|
|
2
|
-
// files — images, PDFs, exports. Store the human-facing filename in custom
|
|
3
|
-
// metadata so listings can show it; the object key itself is a random id.
|
|
4
|
-
import type { UploadedFile } from "../shared/api";
|
|
5
|
-
|
|
6
|
-
function toUploaded(
|
|
7
|
-
key: string,
|
|
8
|
-
name: string,
|
|
9
|
-
size: number,
|
|
10
|
-
uploaded: Date,
|
|
11
|
-
): UploadedFile {
|
|
12
|
-
return { key, name, size, uploadedAt: uploaded.toISOString() };
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export async function putFile(
|
|
16
|
-
bucket: R2Bucket,
|
|
17
|
-
name: string,
|
|
18
|
-
body: ReadableStream | ArrayBuffer | string,
|
|
19
|
-
contentType?: string,
|
|
20
|
-
): Promise<UploadedFile> {
|
|
21
|
-
const key = crypto.randomUUID();
|
|
22
|
-
const obj = await bucket.put(key, body, {
|
|
23
|
-
httpMetadata: contentType ? { contentType } : undefined,
|
|
24
|
-
customMetadata: { name },
|
|
25
|
-
});
|
|
26
|
-
return toUploaded(obj.key, name, obj.size, obj.uploaded);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export async function listFiles(bucket: R2Bucket): Promise<UploadedFile[]> {
|
|
30
|
-
const listed = await bucket.list({ limit: 50, include: ["customMetadata"] });
|
|
31
|
-
return listed.objects.map((o) =>
|
|
32
|
-
toUploaded(o.key, o.customMetadata?.name ?? o.key, o.size, o.uploaded),
|
|
33
|
-
);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export function getFile(bucket: R2Bucket, key: string): Promise<R2ObjectBody | null> {
|
|
37
|
-
return bucket.get(key);
|
|
38
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// How a Provider test and the dev server build `x-pple-identity` (ADR-0024).
|
|
2
|
-
//
|
|
3
|
-
// Base64url (RFC 4648 §5, no padding) of the UTF-8 JSON `{ actor, effective }`.
|
|
4
|
-
// A Thai name is not a reliable raw header value. `serviceCall` decodes this
|
|
5
|
-
// exact encoding. The platform's copy is
|
|
6
|
-
// `workers/src/services/identity-header.ts`; a test keeps the two strings
|
|
7
|
-
// equal. One function, so the dev wrapper and `callRegistry` cannot drift.
|
|
8
|
-
|
|
9
|
-
import type { Identity } from "../shared/api";
|
|
10
|
-
|
|
11
|
-
/** Base64url of the Identity JSON. ASCII, so it survives an HTTP header. */
|
|
12
|
-
export function encodeIdentityHeader(identity: Identity): string {
|
|
13
|
-
const bytes = new TextEncoder().encode(JSON.stringify(identity));
|
|
14
|
-
let binary = "";
|
|
15
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
16
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
17
|
-
}
|
|
@@ -1,276 +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 "has_receipt":
|
|
201
|
-
case "mismatch":
|
|
202
|
-
case "not_your_payment":
|
|
203
|
-
case "not_payable":
|
|
204
|
-
return 409;
|
|
205
|
-
default:
|
|
206
|
-
// Not granted, still Draft, no Checkout Page, platform down: not the
|
|
207
|
-
// Payer's doing, and not something they can fix.
|
|
208
|
-
return 502;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* What to do when the platform tells the app about a Payment. This default
|
|
214
|
-
* only checks the event against the platform and stops: **it does not issue
|
|
215
|
-
* the legal Receipt.** Issuing is your decision, and a Receipt is never edited,
|
|
216
|
-
* only voided and replaced, so an app should not do it by habit. A paid Payment
|
|
217
|
-
* you neither issue nor reject within the party's deadline goes to the Finance
|
|
218
|
-
* Officer as Undecided. Pick one of the two patterns (the `pple-platform`
|
|
219
|
-
* Skill's payments reference has both in full):
|
|
220
|
-
*
|
|
221
|
-
* Issue at payment: there is nothing more to check (a donation). After the
|
|
222
|
-
* verify below, add:
|
|
223
|
-
*
|
|
224
|
-
* const issued = await issueReceipt(env, event.payment.id, fetchImpl);
|
|
225
|
-
* if (!issued.ok && issued.reason !== "not_paid") return tryAgain();
|
|
226
|
-
*
|
|
227
|
-
* Verify first: your app must check something (an order in stock, a
|
|
228
|
-
* membership that exists). Do the check, then `issueReceipt` when it passes
|
|
229
|
-
* or `rejectPayment(env, event.payment.id, fetchImpl)` when it does not.
|
|
230
|
-
*/
|
|
231
|
-
export function createPaymentHandler(overrides: AppOverrides = {}): PaymentHandler {
|
|
232
|
-
const fetchImpl = overrides.fetchImpl;
|
|
233
|
-
// Answer `2xx` and the platform stops; anything else, or a throw, is sent
|
|
234
|
-
// again every few minutes. Retry only what a retry can fix.
|
|
235
|
-
const tryAgain = () => new Response(null, { status: 503 });
|
|
236
|
-
return paymentHandler({
|
|
237
|
-
"payment.paid": async (event, env) => {
|
|
238
|
-
const verified = await verifyPaymentEvent(env, event, fetchImpl);
|
|
239
|
-
if (!verified.ok) return verified.reason === "mismatch" ? undefined : tryAgain();
|
|
240
|
-
if (verified.payment.state !== "paid") return;
|
|
241
|
-
// Decide here: issue at payment, or verify first (see above). Until you do, nothing is issued.
|
|
242
|
-
},
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
const api = createApp();
|
|
247
|
-
|
|
248
|
-
const registry: RegistryMap = {};
|
|
249
|
-
|
|
250
|
-
const appFetch: RegistryFetch = (request, env, ctx) => api.fetch(request, env, ctx);
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* The Worker entry. `registry` is where a Service handler or a Dataset's page
|
|
254
|
-
* functions live, keyed by the entry name. A Hono app plugs straight in
|
|
255
|
-
* (`registry: { "<name>": app }`). A Dataset is an object of page functions
|
|
256
|
-
* (`registry: { "<name>": { "<objectType>": ({ cursor }, env, ctx) => page } }`).
|
|
257
|
-
* The platform calls a Service at `/.pple/registry/<name>/…` and a Dataset at
|
|
258
|
-
* `/.pple/registry/<name>/<objectType>`. Read a Service caller with
|
|
259
|
-
* `serviceCall(request)` from `./registry`.
|
|
260
|
-
*
|
|
261
|
-
* Under `vite dev` the same path is emulated locally. `import.meta.env.DEV`
|
|
262
|
-
* is false in `vite build`, so that branch and `dev-registry.ts` are absent
|
|
263
|
-
* from the deployed Worker, the same way the Persona bypass is (ADR-0011).
|
|
264
|
-
*/
|
|
265
|
-
const worker: PpleWorker = {
|
|
266
|
-
fetch(request, env, ctx) {
|
|
267
|
-
if (import.meta.env.DEV) {
|
|
268
|
-
return devWorkerFetch({ fetch: appFetch, registry }, request, env, ctx);
|
|
269
|
-
}
|
|
270
|
-
return appFetch(request, env, ctx);
|
|
271
|
-
},
|
|
272
|
-
registry,
|
|
273
|
-
payment: createPaymentHandler(),
|
|
274
|
-
};
|
|
275
|
-
|
|
276
|
-
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
|
-
}
|