@pplethai/cli 0.20.0 → 0.21.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.
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "pple-app",
3
+ "private": true,
4
+ "type": "module",
5
+ "//": "Payment Bridge template (ADR-0045). Made and kept by the platform: deploy it unchanged. Rename this to your app slug. A pure relay on Cloudflare Workers: no pages, no database, no files.",
6
+ "scripts": {
7
+ "typecheck": "tsc -p tsconfig.json",
8
+ "test": "vitest run",
9
+ "test:watch": "vitest",
10
+ "build": "wrangler deploy --dry-run --outdir dist/pple-app",
11
+ "deploy": "npm run build && wrangler deploy"
12
+ },
13
+ "devDependencies": {
14
+ "@cloudflare/vitest-pool-workers": "^0.18.6",
15
+ "@cloudflare/workers-types": "^5.20260714.1",
16
+ "typescript": "^5.8.0",
17
+ "vite": "^8.1.5",
18
+ "vitest": "^4.1.10",
19
+ "wrangler": "^4.112.0"
20
+ }
21
+ }
@@ -0,0 +1,18 @@
1
+ // The Bridge Key check. The caller sends `Authorization: Bearer <Bridge Key>`.
2
+ // Both sides are hashed first so the comparison runs over two equal-length
3
+ // digests whatever the caller sent, and does not stop at the first difference.
4
+
5
+ const encoder = new TextEncoder();
6
+
7
+ async function digest(text: string): Promise<Uint8Array> {
8
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(text)));
9
+ }
10
+
11
+ /** True when `authorization` carries exactly the configured Bridge Key. An unset or empty key matches nothing. */
12
+ export async function bridgeKeyMatches(authorization: string | null, configured: string | undefined): Promise<boolean> {
13
+ const presented = /^Bearer ([^\s]+)$/i.exec(authorization ?? "")?.[1] ?? "";
14
+ const [a, b] = await Promise.all([digest(presented), digest(configured ?? "")]);
15
+ let difference = 0;
16
+ for (let i = 0; i < a.length; i++) difference |= a[i]! ^ b[i]!;
17
+ return difference === 0 && presented !== "" && (configured ?? "") !== "";
18
+ }
@@ -0,0 +1,14 @@
1
+ // Everything the Bridge reads from its environment. The platform binds the App
2
+ // Key and the services address; the rest is the Bridge's Config.
3
+ export interface Env {
4
+ /** Secret. The key the External System calls `/api/*` with. Not the App Key. */
5
+ BRIDGE_KEY?: string;
6
+ /** Secret. Signs every webhook. Separate from the Bridge Key (see docs/verify-webhook.md). */
7
+ WEBHOOK_SECRET?: string;
8
+ /** Where every payment event is POSTed. An https address. */
9
+ WEBHOOK_URL?: string;
10
+
11
+ /** Platform-bound. `platform/payments` is reached with it and it never leaves. */
12
+ PPLE_APP_KEY?: string;
13
+ PPLE_SERVICES_URL?: string;
14
+ }
@@ -0,0 +1,39 @@
1
+ // The Payment Bridge (ADR-0045): a pure relay between one External System and
2
+ // `platform/payments`. No pages, no storage, no queue. Deploy it unchanged.
3
+ import { bridgeKeyMatches } from "./bridge-key";
4
+ import type { Env } from "./env";
5
+ import { passThrough } from "./platform";
6
+ import { WEBHOOK_TIMEOUT_MS, relayEvent } from "./webhook";
7
+
8
+ export interface BridgeOptions {
9
+ /** Test seam: the fetch used to reach the platform and the webhook. Production omits it. */
10
+ fetchImpl?: typeof fetch;
11
+ /** Test seam: the clock, in milliseconds. */
12
+ now?: () => number;
13
+ /** Test seam: how long the External System has to answer. */
14
+ webhookTimeoutMs?: number;
15
+ }
16
+
17
+ export function createBridge(options: BridgeOptions = {}) {
18
+ const fetchImpl = options.fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
19
+ const now = options.now ?? (() => Date.now());
20
+ const timeoutMs = options.webhookTimeoutMs ?? WEBHOOK_TIMEOUT_MS;
21
+ return {
22
+ /** The platform calls this when a Payment's outcome is known (ADR-0037). */
23
+ async payment(event: object, env: Env, _ctx: ExecutionContext): Promise<Response> {
24
+ return relayEvent(event, env, { fetchImpl, now, timeoutMs });
25
+ },
26
+ async fetch(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
27
+ const { pathname } = new URL(request.url);
28
+ if (pathname === "/api" || pathname.startsWith("/api/")) {
29
+ if (!(await bridgeKeyMatches(request.headers.get("authorization"), env.BRIDGE_KEY))) {
30
+ return Response.json({ error: "invalid_bridge_key" }, { status: 401 });
31
+ }
32
+ return passThrough(request, env, fetchImpl);
33
+ }
34
+ return new Response(null, { status: 404 });
35
+ },
36
+ };
37
+ }
38
+
39
+ export default createBridge();
@@ -0,0 +1,49 @@
1
+ // The inbound half: one call from the External System, made again on
2
+ // `platform/payments` with the App Key, and the platform's answer handed back
3
+ // as it came. Nothing here reads the body, the token or the answer; it never
4
+ // logs, and it never puts the Bridge Key on the platform call.
5
+ import type { Env } from "./env";
6
+
7
+ /** The only request headers that go on to the platform, besides the App Key. */
8
+ const FORWARDED = ["content-type", "accept"] as const;
9
+
10
+ /**
11
+ * The Payer's PPLE ID token arrives as `pple-user-token` and goes on as
12
+ * `x-pple-user-token`. The deploy wrapper strips every `x-pple-*` header from
13
+ * public traffic (ADR-0024), so the platform's own name would never reach here.
14
+ */
15
+ export const INBOUND_USER_TOKEN_HEADER = "pple-user-token";
16
+ const PLATFORM_USER_TOKEN_HEADER = "x-pple-user-token";
17
+
18
+ /** `/api` + tail → `platform/payments` + tail, query and all. */
19
+ export async function passThrough(request: Request, env: Env, fetchImpl: typeof fetch): Promise<Response> {
20
+ if (!env.PPLE_SERVICES_URL || !env.PPLE_APP_KEY) {
21
+ return Response.json({ error: "bridge_not_bound" }, { status: 502 });
22
+ }
23
+ const url = new URL(request.url);
24
+ const tail = url.pathname.slice("/api".length);
25
+ const target = `${env.PPLE_SERVICES_URL.replace(/\/+$/, "")}/platform/payments${tail === "/" ? "" : tail}${url.search}`;
26
+
27
+ const headers = new Headers();
28
+ for (const name of FORWARDED) {
29
+ const value = request.headers.get(name);
30
+ if (value !== null) headers.set(name, value);
31
+ }
32
+ const userToken = request.headers.get(INBOUND_USER_TOKEN_HEADER);
33
+ if (userToken !== null) headers.set(PLATFORM_USER_TOKEN_HEADER, userToken);
34
+ headers.set("authorization", `Bearer ${env.PPLE_APP_KEY}`);
35
+
36
+ const hasBody = request.method !== "GET" && request.method !== "HEAD";
37
+ let answer: Response;
38
+ try {
39
+ answer = await fetchImpl(target, {
40
+ method: request.method,
41
+ headers,
42
+ redirect: "manual",
43
+ ...(hasBody ? { body: await request.arrayBuffer() } : {}),
44
+ });
45
+ } catch {
46
+ return Response.json({ error: "platform_unreachable" }, { status: 502 });
47
+ }
48
+ return new Response(answer.body, { status: answer.status, statusText: answer.statusText, headers: answer.headers });
49
+ }
@@ -0,0 +1,86 @@
1
+ // The outbound half: the platform tells the Bridge about a Payment, the Bridge
2
+ // tells the External System, straight away, and answers the platform with what
3
+ // the External System answered. No queue, no storage, no retry of its own: the
4
+ // platform's retries and its "gave up telling the app" signal are the External
5
+ // System's too (ADR-0045). Nothing here logs.
6
+ import type { Env } from "./env";
7
+
8
+ /** The platform gives an app 9 s (APP_CALLBACK_TIMEOUT_MS); this leaves it the rest to hear back. */
9
+ export const WEBHOOK_TIMEOUT_MS = 7_000;
10
+
11
+ export const WEBHOOK_ID_HEADER = "x-pple-webhook-id";
12
+ export const WEBHOOK_TIMESTAMP_HEADER = "x-pple-webhook-timestamp";
13
+ export const WEBHOOK_SIGNATURE_HEADER = "x-pple-webhook-signature";
14
+
15
+ export interface RelayDeps {
16
+ fetchImpl: typeof fetch;
17
+ /** Milliseconds since the epoch. */
18
+ now: () => number;
19
+ timeoutMs: number;
20
+ }
21
+
22
+ const encoder = new TextEncoder();
23
+
24
+ /** `v1=` + hex HMAC-SHA256 over `<timestamp>.<body>`. */
25
+ async function sign(secret: string, timestamp: string, body: string): Promise<string> {
26
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
27
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${body}`)));
28
+ return `v1=${Array.from(mac, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
29
+ }
30
+
31
+ /** The webhook address, only if it is a usable https URL. */
32
+ function webhookUrl(raw: string | undefined): string | null {
33
+ if (!raw) return null;
34
+ try {
35
+ return new URL(raw).protocol === "https:" ? raw : null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ const refused = (status: number) => new Response(null, { status });
42
+
43
+ /** A 2xx is delivered. Anything else, the External System's own status, or 502 when it gave none. */
44
+ export async function relayEvent(event: { id?: unknown }, env: Env, deps: RelayDeps): Promise<Response> {
45
+ const url = webhookUrl(env.WEBHOOK_URL);
46
+ if (!url || !env.WEBHOOK_SECRET) return refused(503);
47
+ if (typeof event.id !== "string" || event.id === "") return refused(400);
48
+
49
+ // The body the platform sent, as it was: parsed and written again, which keeps every field.
50
+ const body = JSON.stringify(event);
51
+ const timestamp = String(Math.floor(deps.now() / 1000));
52
+ const controller = new AbortController();
53
+ let timer: ReturnType<typeof setTimeout> | undefined;
54
+ const timedOut = new Promise<never>((_, reject) => {
55
+ timer = setTimeout(() => {
56
+ controller.abort();
57
+ reject(new Error("timeout"));
58
+ }, deps.timeoutMs);
59
+ });
60
+
61
+ try {
62
+ const answer = await Promise.race([
63
+ deps.fetchImpl(url, {
64
+ method: "POST",
65
+ redirect: "manual",
66
+ signal: controller.signal,
67
+ headers: {
68
+ "content-type": "application/json",
69
+ [WEBHOOK_ID_HEADER]: event.id,
70
+ [WEBHOOK_TIMESTAMP_HEADER]: timestamp,
71
+ [WEBHOOK_SIGNATURE_HEADER]: await sign(env.WEBHOOK_SECRET, timestamp, body),
72
+ },
73
+ body,
74
+ }),
75
+ timedOut,
76
+ ]);
77
+ // A body is never read, kept or passed on: only the status.
78
+ answer.body?.cancel().catch(() => {});
79
+ const { status } = answer;
80
+ return refused(status >= 200 && status <= 599 ? status : 502);
81
+ } catch {
82
+ return refused(504);
83
+ } finally {
84
+ if (timer !== undefined) clearTimeout(timer);
85
+ }
86
+ }
@@ -0,0 +1,9 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import source from "../docs/verify-webhook.ts?raw";
3
+ import page from "../docs/verify-webhook.md?raw";
4
+
5
+ describe("docs/verify-webhook.md", () => {
6
+ it("shows the check that is tested, not a copy that has drifted", () => {
7
+ expect(page).toContain(source.trimEnd());
8
+ });
9
+ });
@@ -0,0 +1,71 @@
1
+ [
2
+ {
3
+ "method": "POST",
4
+ "path": "/",
5
+ "status": 201,
6
+ "body": {
7
+ "id": "pay_offline-mock",
8
+ "checkoutUrl": "https://pay.example.invalid/pay_offline-mock",
9
+ "state": "created"
10
+ }
11
+ },
12
+ {
13
+ "method": "POST",
14
+ "path": "/pay_offline-mock/checkout-pass",
15
+ "status": 201,
16
+ "body": {
17
+ "checkoutUrl": "https://pay.example.invalid/pay_offline-mock",
18
+ "pass": "offline-mock-pass"
19
+ }
20
+ },
21
+ {
22
+ "method": "GET",
23
+ "path": "/pay_offline-mock",
24
+ "status": 200,
25
+ "body": {
26
+ "id": "pay_offline-mock",
27
+ "kind": "donation",
28
+ "amountSatang": 50000,
29
+ "description": "รายการทดสอบ",
30
+ "reference": "offline-mock",
31
+ "state": "paid",
32
+ "mode": "test",
33
+ "payer": { "name": "บุคคลทดสอบ หนึ่ง", "maskedCitizenId": "x-xxxx-xxxxx-xx-0" },
34
+ "voucher": { "number": "TEST-PV-000001", "nameTh": "หลักฐานการรับชำระเงิน (ไม่ใช่ใบเสร็จรับเงิน)", "isReceipt": false },
35
+ "receipt": null,
36
+ "paidAt": "2026-01-01T00:00:00.000Z",
37
+ "refusal": null,
38
+ "undecided": false,
39
+ "refund": null
40
+ }
41
+ },
42
+ {
43
+ "method": "POST",
44
+ "path": "/pay_offline-mock/receipt",
45
+ "status": 201,
46
+ "body": {
47
+ "receipt": { "id": "rcp_offline-mock", "number": "TEST-2569-000001", "isTest": true, "issuedAt": "2026-01-01T00:00:00.000Z", "replaces": null }
48
+ }
49
+ },
50
+ {
51
+ "method": "POST",
52
+ "path": "/pay_offline-mock/reject",
53
+ "status": 200,
54
+ "body": {
55
+ "id": "pay_offline-mock",
56
+ "kind": "donation",
57
+ "amountSatang": 50000,
58
+ "description": "รายการทดสอบ",
59
+ "reference": "offline-mock",
60
+ "state": "refunded",
61
+ "mode": "test",
62
+ "payer": { "name": "บุคคลทดสอบ หนึ่ง", "maskedCitizenId": "x-xxxx-xxxxx-xx-0" },
63
+ "voucher": { "number": "TEST-PV-000001", "nameTh": "หลักฐานการรับชำระเงิน (ไม่ใช่ใบเสร็จรับเงิน)", "isReceipt": false },
64
+ "receipt": null,
65
+ "paidAt": "2026-01-01T00:00:00.000Z",
66
+ "refusal": null,
67
+ "undecided": false,
68
+ "refund": { "status": "refunded" }
69
+ }
70
+ }
71
+ ]
@@ -0,0 +1,78 @@
1
+ import mocks from "./fixtures/payments-responses.json";
2
+ import type { Env } from "../src/env";
3
+
4
+ export const BRIDGE_KEY = "bk_test_0123456789";
5
+ export const WEBHOOK_SECRET = "whsec_test_abcdef";
6
+ export const APP_KEY = "app-key-do-not-leak";
7
+ export const SERVICES = "https://services.test";
8
+ export const WEBHOOK_URL = "https://external.test/hooks/pple";
9
+
10
+ /** A Bridge as the platform deploys it: Config set, App Key and services URL bound. */
11
+ export function testEnv(overrides: Partial<Env> = {}): Env {
12
+ return {
13
+ BRIDGE_KEY,
14
+ WEBHOOK_SECRET,
15
+ WEBHOOK_URL,
16
+ PPLE_APP_KEY: APP_KEY,
17
+ PPLE_SERVICES_URL: SERVICES,
18
+ ...overrides,
19
+ };
20
+ }
21
+
22
+ export function testExecutionContext(): ExecutionContext {
23
+ return { waitUntil() {}, passThroughOnException() {}, props: {}, exports: {} } as unknown as ExecutionContext;
24
+ }
25
+
26
+ export const asBridge = (key: string = BRIDGE_KEY): HeadersInit => ({ authorization: `Bearer ${key}` });
27
+
28
+ /** What a fake fetch saw. */
29
+ export interface Seen {
30
+ url: string;
31
+ method: string;
32
+ headers: Headers;
33
+ body: string;
34
+ }
35
+
36
+ /** A fetch that records each request and answers with `answer`. */
37
+ export function recordingFetch(answer: (seen: Seen) => Response | Promise<Response>) {
38
+ const calls: Seen[] = [];
39
+ const fetchImpl: typeof fetch = async (input, init) => {
40
+ const request = new Request(input as RequestInfo, init);
41
+ const seen: Seen = {
42
+ url: request.url,
43
+ method: request.method,
44
+ headers: request.headers,
45
+ body: await request.text(),
46
+ };
47
+ calls.push(seen);
48
+ return answer(seen);
49
+ };
50
+ return { calls, fetchImpl };
51
+ }
52
+
53
+ interface Mock {
54
+ method: string;
55
+ path: string;
56
+ status: number;
57
+ body: unknown;
58
+ headers?: Record<string, string>;
59
+ }
60
+
61
+
62
+ /** The `platform/payments` mocks (the registry's own, `test/fixtures/payments-responses.json`) as a fake platform. */
63
+ export const PAYMENT_MOCKS = mocks as Mock[];
64
+
65
+ /**
66
+ * Answers `{PPLE_SERVICES_URL}/platform/payments/…` from the mocks, and checks
67
+ * the call is the one the platform wants: the App Key as its bearer.
68
+ */
69
+ export function mockPlatform(request: { url: string; method: string; headers: Headers }): Response {
70
+ if (request.headers.get("authorization") !== `Bearer ${APP_KEY}`) {
71
+ return Response.json({ error: "invalid_app_key" }, { status: 401, headers: { "x-pple-error": "invalid_app_key" } });
72
+ }
73
+ const url = new URL(request.url);
74
+ const tail = url.pathname.slice("/platform/payments".length) || "/";
75
+ const hit = PAYMENT_MOCKS.find((m) => m.method === request.method && m.path === tail);
76
+ if (!hit) return Response.json({ error: "not_found" }, { status: 404 });
77
+ return Response.json(hit.body, { status: hit.status, headers: hit.headers ?? {} });
78
+ }
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createBridge } from "../src/index";
3
+ import { APP_KEY, BRIDGE_KEY, PAYMENT_MOCKS, SERVICES, asBridge, mockPlatform, recordingFetch, testEnv, testExecutionContext } from "./harness";
4
+
5
+ const ctx = testExecutionContext();
6
+
7
+ describe("the Bridge Key", () => {
8
+ it("refuses a call with no key, a wrong key, or an unset Bridge Key with a 401 and calls no one", async () => {
9
+ const platform = recordingFetch(() => new Response("{}"));
10
+ const bridge = createBridge({ fetchImpl: platform.fetchImpl });
11
+ const call = (headers: HeadersInit, env = testEnv()) =>
12
+ bridge.fetch(new Request("https://bridge.test/api/pay_1", { headers }), env, ctx);
13
+
14
+ expect((await call({})).status).toBe(401);
15
+ expect((await call(asBridge("bk_wrong"))).status).toBe(401);
16
+ expect((await call(asBridge(BRIDGE_KEY.slice(0, -1)))).status).toBe(401);
17
+ expect((await call({ authorization: BRIDGE_KEY })).status).toBe(401);
18
+ // An empty or missing configured key must never match an empty presented one.
19
+ expect((await call({ authorization: "Bearer " }, testEnv({ BRIDGE_KEY: "" }))).status).toBe(401);
20
+ expect((await call({}, testEnv({ BRIDGE_KEY: undefined }))).status).toBe(401);
21
+ expect(platform.calls).toEqual([]);
22
+ });
23
+ });
24
+
25
+ describe("passing calls through to platform/payments", () => {
26
+ // The same call made straight at the platform, as a Builder App would.
27
+ async function direct(path: string, init: RequestInit): Promise<Response> {
28
+ const platform = recordingFetch(mockPlatform);
29
+ const headers = new Headers(init.headers);
30
+ headers.set("authorization", `Bearer ${APP_KEY}`);
31
+ return platform.fetchImpl(`${SERVICES}/platform/payments${path}`, { ...init, headers });
32
+ }
33
+
34
+ async function same(a: Response, b: Response) {
35
+ expect(b.status).toBe(a.status);
36
+ expect([...b.headers].sort()).toEqual([...a.headers].sort());
37
+ expect(await b.text()).toBe(await a.text());
38
+ }
39
+
40
+ it.each(PAYMENT_MOCKS.map((m) => [`${m.method} ${m.path}`, m] as const))(
41
+ "answers %s exactly as the platform does",
42
+ async (_name, mock) => {
43
+ const platform = recordingFetch(mockPlatform);
44
+ const bridge = createBridge({ fetchImpl: platform.fetchImpl });
45
+ const init = { method: mock.method, ...(mock.method === "POST" ? { body: "{}" } : {}) };
46
+
47
+ const viaBridge = await bridge.fetch(
48
+ new Request(`https://bridge.test/api${mock.path === "/" ? "" : mock.path}`, { ...init, headers: asBridge() }),
49
+ testEnv(),
50
+ ctx,
51
+ );
52
+ await same(await direct(mock.path === "/" ? "" : mock.path, init), viaBridge);
53
+ },
54
+ );
55
+
56
+ it("sends the platform the method, path tail, query, body and user token as they came, under the App Key", async () => {
57
+ const platform = recordingFetch(() => Response.json({ ok: true }));
58
+ const bridge = createBridge({ fetchImpl: platform.fetchImpl });
59
+ const body = '{"amountSatang":50000, "kind":"donation"}';
60
+ await bridge.fetch(
61
+ new Request("https://bridge.test/api/pay_1/checkout-pass?x=1&y=%2F", {
62
+ method: "POST",
63
+ body,
64
+ headers: { ...asBridge(), "content-type": "application/json", "pple-user-token": "payer-token" },
65
+ }),
66
+ testEnv(),
67
+ ctx,
68
+ );
69
+ const [seen] = platform.calls;
70
+ expect(platform.calls).toHaveLength(1);
71
+ expect(seen?.url).toBe(`${SERVICES}/platform/payments/pay_1/checkout-pass?x=1&y=%2F`);
72
+ expect(seen?.method).toBe("POST");
73
+ expect(seen?.body).toBe(body);
74
+ expect(seen?.headers.get("content-type")).toBe("application/json");
75
+ expect(seen?.headers.get("x-pple-user-token")).toBe("payer-token");
76
+ expect(seen?.headers.get("authorization")).toBe(`Bearer ${APP_KEY}`);
77
+ });
78
+
79
+ it("ignores an x-pple-user-token from the caller: the wrapper strips that name, so only pple-user-token counts", async () => {
80
+ const platform = recordingFetch(() => Response.json({}));
81
+ const bridge = createBridge({ fetchImpl: platform.fetchImpl });
82
+ await bridge.fetch(new Request("https://bridge.test/api", { headers: { ...asBridge(), "x-pple-user-token": "t" } }), testEnv(), ctx);
83
+ expect(platform.calls[0]?.headers.has("x-pple-user-token")).toBe(false);
84
+ });
85
+
86
+ it("sends no user token when the caller sent none, and never the Bridge Key", async () => {
87
+ const platform = recordingFetch(() => Response.json({}));
88
+ const bridge = createBridge({ fetchImpl: platform.fetchImpl });
89
+ await bridge.fetch(new Request("https://bridge.test/api", { headers: asBridge() }), testEnv(), ctx);
90
+ const [seen] = platform.calls;
91
+ expect(seen?.url).toBe(`${SERVICES}/platform/payments`);
92
+ expect(seen?.headers.has("x-pple-user-token")).toBe(false);
93
+ expect([...(seen?.headers ?? [])].join(" ")).not.toContain(BRIDGE_KEY);
94
+ });
95
+
96
+ it("returns the platform's refusal, x-pple-error and body included, whatever the status", async () => {
97
+ for (const [status, code] of [[403, "not_granted"], [401, "invalid_app_key"], [503, "provider_unavailable"], [410, "renamed"]] as const) {
98
+ const platform = recordingFetch(
99
+ () => new Response(`{"error":"${code}","detail":"ไทย"}`, { status, headers: { "x-pple-error": code, "content-type": "application/json" } }),
100
+ );
101
+ const bridge = createBridge({ fetchImpl: platform.fetchImpl });
102
+ const res = await bridge.fetch(new Request("https://bridge.test/api/pay_1", { headers: asBridge() }), testEnv(), ctx);
103
+ expect(res.status).toBe(status);
104
+ expect(res.headers.get("x-pple-error")).toBe(code);
105
+ expect(await res.text()).toBe(`{"error":"${code}","detail":"ไทย"}`);
106
+ }
107
+ });
108
+
109
+ it("answers 502 when the platform cannot be reached or the Bridge is not bound to it", async () => {
110
+ const down = createBridge({ fetchImpl: async () => { throw new TypeError("network"); } });
111
+ const get = (b: ReturnType<typeof createBridge>, env = testEnv()) =>
112
+ b.fetch(new Request("https://bridge.test/api/pay_1", { headers: asBridge() }), env, ctx);
113
+ expect((await get(down)).status).toBe(502);
114
+ const unbound = createBridge({ fetchImpl: async () => Response.json({}) });
115
+ expect((await get(unbound, testEnv({ PPLE_APP_KEY: undefined }))).status).toBe(502);
116
+ expect((await get(unbound, testEnv({ PPLE_SERVICES_URL: undefined }))).status).toBe(502);
117
+ });
118
+
119
+ it("never lets a dot-segment path reach the platform under the App Key", async () => {
120
+ const platform = recordingFetch(() => Response.json({}));
121
+ const bridge = createBridge({ fetchImpl: platform.fetchImpl });
122
+ for (const tail of ["/%2e%2e/sms", "/%2E%2E/sms", "/../sms", "/pay_1/../../sms"]) {
123
+ const res = await bridge.fetch(new Request(`https://bridge.test/api${tail}`, { headers: asBridge() }), testEnv(), ctx);
124
+ expect(res.status, tail).toBe(404);
125
+ }
126
+ expect(platform.calls).toEqual([]);
127
+ });
128
+ });
129
+
130
+ describe("everything else", () => {
131
+ it("is a 404, with no pages", async () => {
132
+ const bridge = createBridge({ fetchImpl: async () => Response.json({}) });
133
+ for (const path of ["/", "/index.html", "/apiary", "/api-docs", "/.pple/registry/x", "/health"]) {
134
+ const res = await bridge.fetch(new Request(`https://bridge.test${path}`, { headers: asBridge() }), testEnv(), ctx);
135
+ expect(res.status, path).toBe(404);
136
+ }
137
+ });
138
+ });