@pplethai/cli 0.19.0 → 0.20.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pplethai/cli",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -118,7 +118,11 @@ Where the token comes from:
118
118
  membership fee (`term`) through the Private Platform
119
119
  Service `platform/payments` (Use Grant needed; Beta or Live). `src/payment.ts`
120
120
  has `createPayment` (send the Payer to its `checkoutUrl`; never build a card
121
- form), `getPayment`, `issueReceipt`, `rejectPayment`, `verifyPaymentEvent`
121
+ form), `createCheckoutPass` (when the Payer is signed in and taps to pay, send
122
+ them with `goToCheckout(paymentId)` from `web/pple.ts`, which posts the pass as
123
+ a form from your page (never a link), so they skip signing in again; ask at
124
+ the tap, not at create time; `not_your_payment` is a `409`: the Payment is
125
+ someone else's; `POST /api/payments/:id/checkout` does it), `getPayment`, `issueReceipt`, `rejectPayment`, `verifyPaymentEvent`
122
126
  and `paymentHandler`. The outcome arrives at `payment` on the default export
123
127
  (`createPaymentHandler` in `src/index.ts` is the starting point): it verifies
124
128
  the event and **does not issue a Receipt**: you choose, issue at payment or
@@ -101,7 +101,13 @@ you, so a freshly created app is ready to `npm run dev` straight away.)
101
101
 
102
102
  - **Take a payment:** `createPayment` in `src/payment.ts` asks the platform's
103
103
  `platform/payments` Service for a Payment; send the Payer to the
104
- `checkoutUrl` it returns (never build a card form). The outcome arrives at
104
+ `checkoutUrl` it returns (never build a card form). When the Payer is signed
105
+ in, `createCheckoutPass` (`POST /api/payments/:id/checkout`) gives a
106
+ `checkoutUrl` and a one-use `pass` that skip signing in again: ask for it when
107
+ they tap to pay, post the pass as a form from your page (`goToCheckout` in
108
+ `web/pple.ts`, never a link),
109
+ and treat `not_your_payment` (`409`) as "this Payment is someone else's". The
110
+ outcome arrives at
105
111
  `payment` on the default export, where `verifyPaymentEvent` checks it and
106
112
  your code decides: `issueReceipt` or `rejectPayment`. The starter handler only
107
113
  verifies and does not issue a Receipt for you. You only ever see a masked
@@ -13,6 +13,7 @@ import { devWorkerFetch } from "./dev-registry";
13
13
  import { getFile, listFiles, putFile } from "./files";
14
14
  import { closeInteraction, sendNotification } from "./notify";
15
15
  import {
16
+ createCheckoutPass,
16
17
  createPayment,
17
18
  getPayment,
18
19
  paymentHandler,
@@ -163,6 +164,21 @@ export function createApp(overrides: AppOverrides = {}) {
163
164
  return c.json({ id: created.id, checkoutUrl: created.checkoutUrl }, 201);
164
165
  });
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
+
166
182
  app.get("/payments/:id", async (c) => {
167
183
  const read = await getPayment(c.env, c.req.param("id"), fetchImpl);
168
184
  if (!read.ok) return c.json({ error: read.reason }, paymentStatus(read.reason));
@@ -178,9 +194,13 @@ function paymentStatus(reason: PaymentReason): ContentfulStatusCode {
178
194
  return 404;
179
195
  case "invalid_payment":
180
196
  return 400;
197
+ case "user_token_invalid":
198
+ return 401;
181
199
  case "not_paid":
182
200
  case "has_receipt":
183
201
  case "mismatch":
202
+ case "not_your_payment":
203
+ case "not_payable":
184
204
  return 409;
185
205
  default:
186
206
  // Not granted, still Draft, no Checkout Page, platform down: not the
@@ -1,6 +1,6 @@
1
1
  // Payments (docs/adr/0037). The helpers below wrap the Private Platform Service
2
2
  // `platform/payments`: `createPayment`, `getPayment`, `issueReceipt`,
3
- // `rejectPayment`, `verifyPaymentEvent` and `paymentHandler`. Each answers
3
+ // `rejectPayment`, `createCheckoutPass`, `verifyPaymentEvent` and `paymentHandler`. Each answers
4
4
  // `{ ok: true, … }` or `{ ok: false, reason }`. Offline (`npm run dev` with a
5
5
  // Persona) they answer from the entry's mocks. The rest of this comment is the
6
6
  // outcome the platform sends you.
@@ -144,6 +144,9 @@ export type PaymentReason =
144
144
  | "not_paid"
145
145
  | "has_receipt"
146
146
  | "mismatch"
147
+ | "user_token_invalid"
148
+ | "not_your_payment"
149
+ | "not_payable"
147
150
  | "checkout_unavailable"
148
151
  | "upstream_unavailable";
149
152
 
@@ -250,6 +253,49 @@ export async function rejectPayment(
250
253
  return { ok: true, payment: answer.body as unknown as PaymentRecord };
251
254
  }
252
255
 
256
+ /**
257
+ * Ask the platform for a **Checkout Pass**: the Checkout Page's address and a
258
+ * one-use `pass`. Your page posts `pass` to `checkoutUrl` as a form (the web's
259
+ * `goToCheckout` does), and the Payer opens the Checkout Page already signed in
260
+ * as themselves, with no PPLE ID screen (ADR-0043). Only a form posted from
261
+ * your app's own address redeems it: never put the pass in a link. Prefer it to the bare
262
+ * `checkoutUrl` of `createPayment` whenever the Payer is signed in.
263
+ *
264
+ * Call it when the Payer taps to pay, not when you create the Payment: a pass
265
+ * lasts a few minutes and works once, and each call mints a fresh one. Pass the
266
+ * Payer's own PPLE ID token (the one your app checked on this request). The
267
+ * platform checks it itself and ties the Payment to that Payer.
268
+ *
269
+ * - `user_token_invalid`: no token, or the platform refused it. Fall back to
270
+ * `createPayment`'s `checkoutUrl`: the Payer signs in on the Checkout Page.
271
+ * - `not_your_payment` (`409`): the Payment already belongs to another Payer.
272
+ * Do not retry: create a new Payment for this Payer, or tell them it is not theirs.
273
+ * - `not_payable`: the Payment is already paid or cancelled. Read it with
274
+ * `getPayment` and show its state.
275
+ * - `not_found`: no such Payment of yours.
276
+ */
277
+ export async function createCheckoutPass(
278
+ env: PaymentsEnv,
279
+ id: string,
280
+ userToken: string,
281
+ fetchImpl?: typeof fetch,
282
+ ): Promise<PaymentResult<{ checkoutUrl: string; pass: string }>> {
283
+ // Offline a Persona signs the Payer in and there is no token to send.
284
+ const offline = import.meta.env.DEV && env.DEV_PERSONA !== "none";
285
+ if (!offline && userToken.trim() === "") return refused("user_token_invalid");
286
+ const answer = await callPayments(
287
+ env,
288
+ `/${encodeURIComponent(id)}/checkout-pass`,
289
+ fetchImpl,
290
+ { method: "POST" },
291
+ { userToken, passRefusals: true },
292
+ );
293
+ if (!answer.ok) return answer;
294
+ const { checkoutUrl, pass } = answer.body;
295
+ if (typeof checkoutUrl !== "string" || typeof pass !== "string") return refused("upstream_unavailable");
296
+ return { ok: true, checkoutUrl, pass };
297
+ }
298
+
253
299
  /** The states a Payment can be in once the platform has sent an event of that type, and any time after. */
254
300
  const STATES_AFTER: Record<string, readonly PaymentRecord["state"][]> = {
255
301
  "payment.paid": ["paid", "rejected", "refunding", "refunded"],
@@ -330,6 +376,7 @@ function platformReason(code: PlatformErrorCode | null): PaymentReason {
330
376
  case "invalid_app_key":
331
377
  case "not_granted":
332
378
  case "needs_beta":
379
+ case "user_token_invalid":
333
380
  return code;
334
381
  default:
335
382
  return "upstream_unavailable";
@@ -344,6 +391,12 @@ async function callPayments(
344
391
  path: string,
345
392
  fetchImpl: typeof fetch | undefined,
346
393
  init: RequestInit,
394
+ call: {
395
+ /** The Payer's PPLE ID token. Only the Checkout Pass call sends one. */
396
+ userToken?: string;
397
+ /** The Checkout Pass route's own refusals: `user_token_invalid`, `payment_tied_to_another_payer` and `payment_ended`. */
398
+ passRefusals?: boolean;
399
+ } = {},
347
400
  ): Promise<Answer> {
348
401
  // Offline (`npm run dev` with a Persona) `callService` answers from the mocks
349
402
  // and needs no bindings.
@@ -352,7 +405,10 @@ async function callPayments(
352
405
 
353
406
  let res: Response;
354
407
  try {
355
- res = await callService(env, "platform/payments", path, init, fetchImpl ? { fetchImpl } : {});
408
+ res = await callService(env, "platform/payments", path, init, {
409
+ ...(fetchImpl ? { fetchImpl } : {}),
410
+ ...(call.userToken !== undefined ? { userToken: call.userToken } : {}),
411
+ });
356
412
  } catch {
357
413
  return refused("upstream_unavailable");
358
414
  }
@@ -365,6 +421,11 @@ async function callPayments(
365
421
  const error = typeof body.error === "string" ? body.error : undefined;
366
422
  const reason = SERVICE_REASONS.find((r) => r === error);
367
423
  if (reason) return refused(reason, typeof body.field === "string" ? body.field : undefined);
424
+ if (call.passRefusals && !res.ok) {
425
+ if (error === "user_token_invalid") return refused("user_token_invalid");
426
+ if (error === "payment_tied_to_another_payer") return refused("not_your_payment");
427
+ if (error === "payment_ended") return refused("not_payable");
428
+ }
368
429
  if (!res.ok) return refused("upstream_unavailable");
369
430
  return { ok: true, status: res.status, body };
370
431
  }
@@ -9,6 +9,15 @@
9
9
  "state": "created"
10
10
  }
11
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
+ },
12
21
  {
13
22
  "method": "GET",
14
23
  "path": "/pay_offline-mock",
@@ -67,6 +67,51 @@ describe("a fresh template app, offline", () => {
67
67
  },
68
68
  );
69
69
 
70
+ it.each(["hq-staff", "member", "kyc-verified-nonmember", "delegate"])(
71
+ "sends %s to checkout with a Checkout Pass when they tap to pay (ADR-0043)",
72
+ async (persona) => {
73
+ const h = makeHarness({ services: offlinePayments(persona) }, { ...SERVICES, DEV_PERSONA: persona });
74
+
75
+ // The Payer taps to pay: the app mints a pass now, not at create time.
76
+ const res = await h.request("/api/payments/pay_offline-mock/checkout", { method: "POST" });
77
+
78
+ expect(res.status).toBe(201);
79
+ expect(await res.json()).toEqual({ checkoutUrl: "https://pay.example.invalid/pay_offline-mock", pass: "offline-mock-pass" });
80
+ expect(h.calls.services.map((c) => `${c.method} ${c.path}`)).toEqual([
81
+ "POST /platform/payments/pay_offline-mock/checkout-pass",
82
+ ]);
83
+ },
84
+ );
85
+
86
+ it("sends the Payer's own token with the pass call, and no other call carries it", async () => {
87
+ const tokens: Record<string, string | null> = {};
88
+ const h = makeHarness(
89
+ {
90
+ services: (req) => {
91
+ tokens[new URL(req.url).pathname] = req.headers.get("x-pple-user-token");
92
+ return Response.json({ checkoutUrl: "https://pay.example.test/pay_1", pass: "p" }, { status: 201 });
93
+ },
94
+ },
95
+ { ...SERVICES, DEV_PERSONA: "member" },
96
+ );
97
+ const res = await h.request("/api/payments/pay_1/checkout", { method: "POST" }, "payer-token");
98
+
99
+ expect(res.status).toBe(201);
100
+ expect(tokens).toEqual({ "/platform/payments/pay_1/checkout-pass": "payer-token" });
101
+ });
102
+
103
+ it("tells the Payer when the Payment belongs to someone else (409)", async () => {
104
+ const h = makeHarness(
105
+ { services: () => Response.json({ error: "payment_tied_to_another_payer" }, { status: 409 }) },
106
+ { ...SERVICES, DEV_PERSONA: "member" },
107
+ );
108
+
109
+ const res = await h.request("/api/payments/pay_1/checkout", { method: "POST" });
110
+
111
+ expect(res.status).toBe(409);
112
+ expect(await res.json()).toEqual({ error: "not_your_payment" });
113
+ });
114
+
70
115
  // The Checkout Page turns an unverified Payer away, so the app says so first.
71
116
  // The mocks cannot: the Service never sees who is signed in.
72
117
  it.each(["unverified", "kyc-pending"])("does not start a payment for %s: they must verify first", async (persona) => {
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { describe, expect, it } from "vitest";
10
10
  import { DEV_PERSONAS } from "../src/dev-personas";
11
- import { createPayment, getPayment, issueReceipt, rejectPayment } from "../src/payment";
11
+ import { createCheckoutPass, createPayment, getPayment, issueReceipt, rejectPayment } from "../src/payment";
12
12
  import { offlinePayments } from "./payments-offline";
13
13
 
14
14
  /** `callService` as `npm run dev` runs it for this Persona. */
@@ -64,4 +64,28 @@ describe("offline payments", () => {
64
64
  payment: { state: "refunded", refund: { status: "refunded" } },
65
65
  });
66
66
  });
67
+
68
+ // A signed-in Payer's app mints a pass the Checkout Page would redeem
69
+ // (ADR-0043). Offline there is no Checkout Page: the mock answers the address.
70
+ it.each([...personas, "intern"])("%s: a Checkout Pass is minted and answers an address to go to", async (persona) => {
71
+ const fetchImpl = offlineAs(persona);
72
+
73
+ const pass = await createCheckoutPass(env, "pay_offline-mock", "payer-token", fetchImpl);
74
+
75
+ expect(pass).toEqual({ ok: true, checkoutUrl: expect.stringMatching(/^https:\/\/.+\/pay_offline-mock$/), pass: "offline-mock-pass" });
76
+ });
77
+
78
+ it("mints a pass with no token while a Persona is signed in, as `npm run dev` does", async () => {
79
+ // `npm run dev` signs the Payer in as the Persona and sends no PPLE ID token,
80
+ // so a blank token is fine offline and refused against the real platform.
81
+ const fetchImpl = offlineAs("member");
82
+
83
+ expect(await createCheckoutPass({ ...env, DEV_PERSONA: "member" }, "pay_offline-mock", "", fetchImpl)).toMatchObject({
84
+ ok: true,
85
+ });
86
+ expect(await createCheckoutPass(env, "pay_offline-mock", "", fetchImpl)).toEqual({
87
+ ok: false,
88
+ reason: "user_token_invalid",
89
+ });
90
+ });
67
91
  });
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { describe, expect, it } from "vitest";
8
8
  import {
9
+ createCheckoutPass,
9
10
  createPayment,
10
11
  getPayment,
11
12
  issueReceipt,
@@ -79,6 +80,94 @@ const PAID: PaymentRecord = {
79
80
 
80
81
  const RECEIPT = { id: "rcp_1", number: "TEST-2569-000001", isTest: true, issuedAt: "2026-11-15T09:01:00.000Z", replaces: null };
81
82
 
83
+ describe("createCheckoutPass", () => {
84
+ it("asks for a pass with the Payer's token, and answers the address to send them to", async () => {
85
+ let seen: { token: string | null; auth: string | null; body: string } | undefined;
86
+ const h = makeHarness(
87
+ {
88
+ services: async (req) => {
89
+ seen = {
90
+ token: req.headers.get("x-pple-user-token"),
91
+ auth: req.headers.get("authorization"),
92
+ body: await req.text(),
93
+ };
94
+ return Response.json({ checkoutUrl: "https://pay.example.test/pay_1", pass: "abc" }, { status: 201 });
95
+ },
96
+ },
97
+ SERVICES,
98
+ );
99
+
100
+ const result = await createCheckoutPass(h.testEnv, "pay_1", "payer-token", h.fetchImpl);
101
+
102
+ expect(result).toEqual({ ok: true, checkoutUrl: "https://pay.example.test/pay_1", pass: "abc" });
103
+ expect(h.calls.services).toEqual([
104
+ expect.objectContaining({ path: "/platform/payments/pay_1/checkout-pass", method: "POST" }),
105
+ ]);
106
+ // The user token travels as the Payer's own; the App Key still names the app.
107
+ expect(seen).toEqual({ token: "payer-token", auth: "Bearer app-key", body: "" });
108
+ });
109
+
110
+ it("sends no token with any other call", async () => {
111
+ let token: string | null = "unset";
112
+ const h = makeHarness(
113
+ {
114
+ services: (req) => {
115
+ token = req.headers.get("x-pple-user-token");
116
+ return Response.json({}, { status: 404 });
117
+ },
118
+ },
119
+ SERVICES,
120
+ );
121
+
122
+ await getPayment(h.testEnv, "pay_1", h.fetchImpl);
123
+
124
+ expect(token).toBeNull();
125
+ });
126
+
127
+ const refusals: [string, Response, string][] = [
128
+ ["a token the platform refuses", serviceRefusal("user_token_invalid", 401), "user_token_invalid"],
129
+ ["the Service's own token refusal", Response.json({ error: "user_token_invalid" }, { status: 401 }), "user_token_invalid"],
130
+ [
131
+ "a Payment that belongs to another Payer",
132
+ Response.json({ error: "payment_tied_to_another_payer" }, { status: 409 }),
133
+ "not_your_payment",
134
+ ],
135
+ ["a Payment that is paid, refused or cancelled", Response.json({ error: "payment_ended" }, { status: 409 }), "not_payable"],
136
+ ["a bare 409", new Response(null, { status: 409 }), "upstream_unavailable"],
137
+ ["a Payment that is not there", Response.json({ error: "not_found" }, { status: 404 }), "not_found"],
138
+ ["no Use Grant", serviceRefusal("not_granted", 403), "not_granted"],
139
+ ["a Service that answers nonsense", new Response("oops", { status: 500 }), "upstream_unavailable"],
140
+ ["a 201 with no address", Response.json({}, { status: 201 }), "upstream_unavailable"],
141
+ ["a 201 with no pass", Response.json({ checkoutUrl: "https://pay.example.test/pay_1" }, { status: 201 }), "upstream_unavailable"],
142
+ ];
143
+
144
+ it.each(refusals)("names %s", async (_name, answer, reason) => {
145
+ const h = makeHarness({ services: () => answer.clone() }, SERVICES);
146
+
147
+ expect(await createCheckoutPass(h.testEnv, "pay_1", "payer-token", h.fetchImpl)).toEqual({ ok: false, reason });
148
+ });
149
+
150
+ it("does not call the platform without a token", async () => {
151
+ const h = makeHarness({}, SERVICES);
152
+
153
+ expect(await createCheckoutPass(h.testEnv, "pay_1", " ", h.fetchImpl)).toEqual({
154
+ ok: false,
155
+ reason: "user_token_invalid",
156
+ });
157
+ expect(h.calls.services).toEqual([]);
158
+ });
159
+
160
+ it("says not_configured, and calls nothing, when the platform bindings are missing", async () => {
161
+ const h = makeHarness({}, { PPLE_SERVICES_URL: undefined, PPLE_APP_KEY: undefined, DEV_PERSONA: "none" });
162
+
163
+ expect(await createCheckoutPass(h.testEnv, "pay_1", "payer-token", h.fetchImpl)).toEqual({
164
+ ok: false,
165
+ reason: "not_configured",
166
+ });
167
+ expect(h.calls.services).toEqual([]);
168
+ });
169
+ });
170
+
82
171
  describe("every helper names why the platform said no", () => {
83
172
  const cases: [string, Response, string, string?][] = [
84
173
  ["the gate refusing the App Key", serviceRefusal("invalid_app_key", 401), "invalid_app_key"],
@@ -25,6 +25,8 @@ export function offlinePayments(persona: string): (req: Request) => Response {
25
25
  path: url.pathname.slice(prefix.length),
26
26
  method: req.method,
27
27
  persona,
28
+ // As `callService` offline does: the Payer's token, when one is sent.
29
+ ...(req.headers.get("x-pple-user-token") ? { userToken: req.headers.get("x-pple-user-token")! } : {}),
28
30
  overlayRoot: "overlay/",
29
31
  });
30
32
  };
@@ -96,3 +96,29 @@ export async function apiJson<T>(path: string, init: RequestInit = {}): Promise<
96
96
  }
97
97
  return res.json() as Promise<T>;
98
98
  }
99
+
100
+ /**
101
+ * The Payer taps "pay": send them to the Checkout Page already signed in
102
+ * (a Checkout Pass, ADR-0043). Asks your Worker's `POST /api/payments/:id/checkout`
103
+ * for a fresh pass and posts it to the Checkout Page as a form, from this page,
104
+ * which is the only way the platform redeems one. On a refusal it answers the
105
+ * reason instead: on `user_token_invalid` send the Payer to the `checkoutUrl`
106
+ * `createPayment` answered (they sign in there); `not_your_payment` and
107
+ * `not_payable` are in the Skill's payments reference.
108
+ */
109
+ export async function goToCheckout(paymentId: string): Promise<{ error: string }> {
110
+ const res = await api(`/api/payments/${encodeURIComponent(paymentId)}/checkout`, { method: "POST" });
111
+ const body = (await res.json().catch(() => ({}))) as { checkoutUrl?: string; pass?: string; error?: string };
112
+ if (res.status !== 201 || !body.checkoutUrl || !body.pass) return { error: body.error ?? `request failed (${res.status})` };
113
+ const form = document.createElement("form");
114
+ form.method = "POST";
115
+ form.action = body.checkoutUrl;
116
+ const field = document.createElement("input");
117
+ field.type = "hidden";
118
+ field.name = "pass";
119
+ field.value = body.pass;
120
+ form.append(field);
121
+ document.body.append(form);
122
+ form.submit();
123
+ return new Promise(() => {}); // the page is leaving
124
+ }