@pplethai/cli 0.18.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/dist/bin.js +2 -2
- package/package.json +1 -1
- package/templates/golden-path/CLAUDE.md +10 -1
- package/templates/golden-path/README.md +7 -1
- package/templates/golden-path/src/email.ts +224 -0
- package/templates/golden-path/src/index.ts +20 -0
- package/templates/golden-path/src/payment.ts +63 -2
- package/templates/golden-path/test/email.test.ts +117 -0
- package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +2 -2
- package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +9 -0
- package/templates/golden-path/test/payment-app.test.ts +45 -0
- package/templates/golden-path/test/payment-offline.test.ts +25 -1
- package/templates/golden-path/test/payment.test.ts +89 -0
- package/templates/golden-path/test/payments-offline.ts +2 -0
- package/templates/golden-path/web/pple.ts +26 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// Email: the party's layout, safe HTML building, and sending through
|
|
2
|
+
// `platform/email` (needs its Use Grant and at least Beta).
|
|
3
|
+
//
|
|
4
|
+
// import { html, partyEmail, sendEmail } from "./email";
|
|
5
|
+
//
|
|
6
|
+
// const email = partyEmail({
|
|
7
|
+
// heading: "ยืนยันการลงทะเบียน",
|
|
8
|
+
// content: html`<p>สวัสดีคุณ ${name}</p><p>คุณลงทะเบียนงาน ${event} แล้ว</p>`,
|
|
9
|
+
// text: `สวัสดีคุณ ${name}\nคุณลงทะเบียนงาน ${event} แล้ว`,
|
|
10
|
+
// button: { label: "ดูรายละเอียด", url: "https://my-app.ppleth.ai/events/1" },
|
|
11
|
+
// });
|
|
12
|
+
// await sendEmail(env, { to: address, subject: "ยืนยันการลงทะเบียน", ...email });
|
|
13
|
+
//
|
|
14
|
+
// ESCAPE WHAT PEOPLE TYPED. A value put into HTML with a plain template string
|
|
15
|
+
// (`<p>${name}</p>`) becomes HTML: a name containing `<a href=…>` puts a link
|
|
16
|
+
// in an email sent under the party's name. The platform removes scripts and
|
|
17
|
+
// the like, but not links or images: only your code can tell your markup from
|
|
18
|
+
// your users' text. Build HTML with the `html` tag below, which escapes every
|
|
19
|
+
// value it is given; `raw()` is the deliberate way to insert markup you wrote.
|
|
20
|
+
//
|
|
21
|
+
// The layout is hand-written table HTML with inline styles, which is what mail
|
|
22
|
+
// apps (Gmail, Outlook, Apple Mail) render alike. Keep `content` simple:
|
|
23
|
+
// paragraphs, links, lists, `<b>`. The logo is a PNG the platform serves.
|
|
24
|
+
|
|
25
|
+
import { callService, type CallServiceEnv } from "./call-service";
|
|
26
|
+
|
|
27
|
+
/** HTML that is safe to put in an email as it is: built by `html`, or vouched for with `raw`. */
|
|
28
|
+
export class SafeHtml {
|
|
29
|
+
constructor(readonly value: string) {}
|
|
30
|
+
toString(): string {
|
|
31
|
+
return this.value;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Text in, the same text as HTML out: `&`, `<`, `>`, `"` and `'` become entities. */
|
|
36
|
+
export function escapeHtml(text: string): string {
|
|
37
|
+
return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Markup you wrote yourself, inserted as it is. Never pass it anything a user typed. */
|
|
41
|
+
export function raw(trusted: string): SafeHtml {
|
|
42
|
+
return new SafeHtml(trusted);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type HtmlValue = SafeHtml | string | number | boolean | null | undefined | readonly HtmlValue[];
|
|
46
|
+
|
|
47
|
+
function render(value: HtmlValue): string {
|
|
48
|
+
if (value instanceof SafeHtml) return value.value;
|
|
49
|
+
if (Array.isArray(value)) return value.map(render).join("");
|
|
50
|
+
if (value === null || value === undefined || value === false) return "";
|
|
51
|
+
return escapeHtml(String(value));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A tagged template that escapes every inserted value. Nest it freely: an
|
|
56
|
+
* inserted `html` result (or a list of them) goes in as markup, not escaped twice.
|
|
57
|
+
*
|
|
58
|
+
* html`<p>สวัสดี ${user.name}</p>` // name is escaped
|
|
59
|
+
* html`<ul>${items.map((i) => html`<li>${i}</li>`)}</ul>`
|
|
60
|
+
*/
|
|
61
|
+
export function html(strings: TemplateStringsArray, ...values: HtmlValue[]): SafeHtml {
|
|
62
|
+
let out = strings[0] ?? "";
|
|
63
|
+
values.forEach((value, i) => {
|
|
64
|
+
out += render(value) + (strings[i + 1] ?? "");
|
|
65
|
+
});
|
|
66
|
+
return new SafeHtml(out);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A link a reader may follow: `https:` or `mailto:` only, or this throws. */
|
|
70
|
+
export function safeUrl(url: string): string {
|
|
71
|
+
let parsed: URL;
|
|
72
|
+
try {
|
|
73
|
+
parsed = new URL(url);
|
|
74
|
+
} catch {
|
|
75
|
+
throw new Error(`not a URL: ${url}`);
|
|
76
|
+
}
|
|
77
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "mailto:") {
|
|
78
|
+
throw new Error(`email links must be https: or mailto:, not ${parsed.protocol}`);
|
|
79
|
+
}
|
|
80
|
+
return parsed.toString();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The party's contact details, printed in every email's footer. */
|
|
84
|
+
export const PARTY = {
|
|
85
|
+
name: "พรรคประชาชน",
|
|
86
|
+
logoUrl: "https://services.ppleth.ai/email-assets/logo.png",
|
|
87
|
+
logoAlt: "ภาพโลโก้พรรคประชาชน",
|
|
88
|
+
phone: "02-038-5100",
|
|
89
|
+
phoneHref: "tel:+6620385100",
|
|
90
|
+
hours: "จันทร์-ศุกร์ 10:00-18:00 น.",
|
|
91
|
+
email: "office@peoplespartythailand.org",
|
|
92
|
+
line: "@peoplesth",
|
|
93
|
+
lineUrl: "https://line.me/R/ti/p/@peoplesth",
|
|
94
|
+
address: ["พรรคประชาชน สำนักงานใหญ่", "เลขที่ 167 ชั้น 4 ซอย รามคำแหง 42", "แขวงหัวหมาก เขตบางกะปิ", "กรุงเทพมหานคร 10240"],
|
|
95
|
+
} as const;
|
|
96
|
+
|
|
97
|
+
const NAVY = "#0b3a66";
|
|
98
|
+
const ORANGE = "#ff6413";
|
|
99
|
+
const INK = "#1f2937";
|
|
100
|
+
const FONT = "'IBM Plex Sans Thai Looped','Noto Sans Thai','Leelawadee UI',Tahoma,sans-serif";
|
|
101
|
+
|
|
102
|
+
export interface PartyEmailInput {
|
|
103
|
+
/** The big line at the top of the message. */
|
|
104
|
+
heading: string;
|
|
105
|
+
/** The message, built with `html`. */
|
|
106
|
+
content: SafeHtml;
|
|
107
|
+
/** The same message as plain text, for mail apps that show no HTML. */
|
|
108
|
+
text: string;
|
|
109
|
+
/** One call to action. Its URL must be `https:` or `mailto:`. */
|
|
110
|
+
button?: { label: string; url: string };
|
|
111
|
+
/** The grey line mail apps show beside the subject. Defaults to none. */
|
|
112
|
+
preheader?: string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Dark mode. Mail apps treat it three ways, and the layout is built for all:
|
|
116
|
+
// - Apple Mail, iOS Mail, Outlook for Mac honour `prefers-color-scheme`: the
|
|
117
|
+
// <style> block below swaps the light card for a dark one.
|
|
118
|
+
// - Gmail's apps ignore it and invert colours themselves: a navy block turns
|
|
119
|
+
// light blue and white text turns dark. They leave a `background-image`
|
|
120
|
+
// alone, so the navy header and the orange button are painted twice
|
|
121
|
+
// (`bg()`). Text colours are still inverted, so nothing relies on white text
|
|
122
|
+
// on a dark block: the header carries only the logo (an image, never
|
|
123
|
+
// inverted), and the footer is light with dark text, which Gmail inverts
|
|
124
|
+
// the way it inverts the body.
|
|
125
|
+
// - Clients that do neither show the light layout as it is.
|
|
126
|
+
const DARK_CSS = `
|
|
127
|
+
:root { color-scheme: light dark; supported-color-schemes: light dark; }
|
|
128
|
+
a[x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; }
|
|
129
|
+
@media (prefers-color-scheme: dark) {
|
|
130
|
+
.pe-page { background: #0f141a !important; }
|
|
131
|
+
.pe-card { background: #1a2129 !important; }
|
|
132
|
+
.pe-ink, .pe-ink p, .pe-ink td, .pe-ink li { color: #e6e9ee !important; }
|
|
133
|
+
.pe-heading { color: #ffb48a !important; }
|
|
134
|
+
.pe-ink td { border-color: #2c3540 !important; }
|
|
135
|
+
.pe-foot { background: #11171e !important; border-color: #2c3540 !important; }
|
|
136
|
+
.pe-foot-title { color: #ffb48a !important; }
|
|
137
|
+
.pe-foot-label { color: #8b96a5 !important; }
|
|
138
|
+
.pe-foot-text, .pe-foot-text a { color: #d5dbe3 !important; }
|
|
139
|
+
}`;
|
|
140
|
+
|
|
141
|
+
/** A solid block Gmail's dark mode leaves alone: the colour twice, once as an image. */
|
|
142
|
+
const bg = (color: string) => raw(`background-color:${color};background-image:linear-gradient(${color},${color})`);
|
|
143
|
+
|
|
144
|
+
/** The party layout around your message: `{ html, body }` for `sendEmail`. */
|
|
145
|
+
export function partyEmail(input: PartyEmailInput): { html: string; body: string } {
|
|
146
|
+
const button = input.button
|
|
147
|
+
? html`<table role="presentation" cellpadding="0" cellspacing="0" style="margin:24px 0 8px"><tr><td style="border-radius:8px;${bg(ORANGE)}">
|
|
148
|
+
<a href="${safeUrl(input.button.url)}" style="display:inline-block;padding:12px 24px;font-family:${raw(FONT)};font-size:16px;font-weight:bold;color:#ffffff;text-decoration:none;border-radius:8px">${input.button.label}</a>
|
|
149
|
+
</td></tr></table>`
|
|
150
|
+
: "";
|
|
151
|
+
|
|
152
|
+
const contactRow = (label: string, value: SafeHtml) =>
|
|
153
|
+
html`<tr><td class="pe-foot-label" style="padding:4px 12px 4px 0;font-size:14px;color:#6b7280;white-space:nowrap;vertical-align:top">${label}</td><td class="pe-foot-text" style="padding:4px 0;font-size:15px;color:${INK}">${value}</td></tr>`;
|
|
154
|
+
const link = (href: string, text: string) => html`<a href="${href}" style="color:${INK};text-decoration:none">${text}</a>`;
|
|
155
|
+
// A deliberate, styled link: left bare, Gmail and iOS underline the address in blue themselves.
|
|
156
|
+
const mapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(PARTY.address.join(" "))}`;
|
|
157
|
+
|
|
158
|
+
const page = html`<!doctype html>
|
|
159
|
+
<html lang="th"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
160
|
+
<meta name="color-scheme" content="light dark"><meta name="supported-color-schemes" content="light dark">
|
|
161
|
+
<meta name="format-detection" content="telephone=no,address=no,email=no,date=no">
|
|
162
|
+
<title>${input.heading}</title><style>${raw(DARK_CSS)}</style></head>
|
|
163
|
+
<body class="body pe-page" style="margin:0;padding:0;background:#eef1f5">
|
|
164
|
+
${input.preheader ? html`<div style="display:none;max-height:0;overflow:hidden;opacity:0">${input.preheader}</div>` : ""}
|
|
165
|
+
<table role="presentation" class="pe-page" width="100%" cellpadding="0" cellspacing="0" style="background:#eef1f5"><tr><td align="center" style="padding:24px 12px">
|
|
166
|
+
<table role="presentation" class="pe-card" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;background:#ffffff;border-radius:12px;overflow:hidden;font-family:${raw(FONT)}">
|
|
167
|
+
<tr><td style="${bg(NAVY)};padding:24px 32px"><img src="${PARTY.logoUrl}" width="176" height="50" alt="${PARTY.logoAlt}" style="display:block;border:0;color:#ffffff;font-size:20px;font-weight:bold"></td></tr>
|
|
168
|
+
<tr><td class="pe-ink" style="padding:32px 32px 24px;color:${INK};font-size:16px;line-height:1.7">
|
|
169
|
+
<h1 class="pe-heading" style="margin:0 0 16px;font-size:24px;line-height:1.4;color:${NAVY}">${input.heading}</h1>
|
|
170
|
+
${input.content}
|
|
171
|
+
${button}
|
|
172
|
+
</td></tr>
|
|
173
|
+
<tr><td class="pe-foot" style="background:#f3f5f8;border-top:1px solid #e3e7ed;padding:28px 32px">
|
|
174
|
+
<div class="pe-foot-title" style="margin:0 0 12px;font-size:20px;font-weight:bold;color:${NAVY}">ติดต่อเรา</div>
|
|
175
|
+
<table role="presentation" cellpadding="0" cellspacing="0">
|
|
176
|
+
${contactRow("โทร", html`${link(PARTY.phoneHref, PARTY.phone)} (${PARTY.hours})`)}
|
|
177
|
+
${contactRow("อีเมล", link(`mailto:${PARTY.email}`, PARTY.email))}
|
|
178
|
+
${contactRow("LINE", link(PARTY.lineUrl, PARTY.line))}
|
|
179
|
+
</table>
|
|
180
|
+
<div class="pe-foot-text" style="margin:16px 0 0;font-size:14px;line-height:1.6;color:#4b5563"><a href="${mapsUrl}" style="color:#4b5563;text-decoration:none">${PARTY.address.map((line, i) => html`${i ? raw("<br>") : ""}${line}`)}</a></div>
|
|
181
|
+
</td></tr>
|
|
182
|
+
</table>
|
|
183
|
+
</td></tr></table>
|
|
184
|
+
</body></html>`;
|
|
185
|
+
|
|
186
|
+
const body = [
|
|
187
|
+
input.heading,
|
|
188
|
+
"",
|
|
189
|
+
input.text,
|
|
190
|
+
...(input.button ? ["", `${input.button.label}: ${safeUrl(input.button.url)}`] : []),
|
|
191
|
+
"",
|
|
192
|
+
"—",
|
|
193
|
+
`ติดต่อ${PARTY.name}`,
|
|
194
|
+
`โทร ${PARTY.phone} (${PARTY.hours})`,
|
|
195
|
+
`อีเมล ${PARTY.email}`,
|
|
196
|
+
`LINE ${PARTY.line}`,
|
|
197
|
+
...PARTY.address,
|
|
198
|
+
].join("\n");
|
|
199
|
+
|
|
200
|
+
return { html: page.value, body };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface SendEmailResult {
|
|
204
|
+
status: number;
|
|
205
|
+
/** Set when the platform refused before the Service ran (`not_granted`, `needs_beta`, …). */
|
|
206
|
+
platformError: string | null;
|
|
207
|
+
body: unknown;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** POST /platform/email. Pass `html`, `body` (plain text), or both. See `pple registry show platform/email`. */
|
|
211
|
+
export async function sendEmail(
|
|
212
|
+
env: CallServiceEnv,
|
|
213
|
+
message: { to: string | string[]; subject: string; html?: string; body?: string },
|
|
214
|
+
fetchImpl?: typeof fetch,
|
|
215
|
+
): Promise<SendEmailResult> {
|
|
216
|
+
const res = await callService(
|
|
217
|
+
env,
|
|
218
|
+
"platform/email",
|
|
219
|
+
"",
|
|
220
|
+
{ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(message) },
|
|
221
|
+
fetchImpl ? { fetchImpl } : {},
|
|
222
|
+
);
|
|
223
|
+
return { status: res.status, platformError: res.headers.get("x-pple-error"), body: await res.json().catch(() => null) };
|
|
224
|
+
}
|
|
@@ -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,
|
|
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
|
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// src/email.ts: the `html` tag escapes what people typed, the party layout
|
|
2
|
+
// carries the footer and a plain-text part, and sendEmail posts to
|
|
3
|
+
// platform/email.
|
|
4
|
+
|
|
5
|
+
import { describe, expect, it } from "vitest";
|
|
6
|
+
import { escapeHtml, html, partyEmail, raw, safeUrl, sendEmail } from "../src/email";
|
|
7
|
+
|
|
8
|
+
describe("html", () => {
|
|
9
|
+
it("escapes every inserted value, so a user's text cannot become markup", () => {
|
|
10
|
+
const name = `<a href="https://evil.example">ยืนยันบัญชี</a> & 'x'`;
|
|
11
|
+
expect(html`<p>สวัสดี ${name}</p>`.value).toBe(
|
|
12
|
+
"<p>สวัสดี <a href="https://evil.example">ยืนยันบัญชี</a> & 'x'</p>",
|
|
13
|
+
);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it("nests html results and lists without escaping them twice, and drops empty values", () => {
|
|
17
|
+
const items = ["ก < ข", "ค"];
|
|
18
|
+
expect(html`<ul>${items.map((i) => html`<li>${i}</li>`)}</ul>${null}${undefined}${false}`.value).toBe(
|
|
19
|
+
"<ul><li>ก < ข</li><li>ค</li></ul>",
|
|
20
|
+
);
|
|
21
|
+
expect(html`${raw("<br>")}${42}`.value).toBe("<br>42");
|
|
22
|
+
expect(escapeHtml(`"&"`)).toBe(""&"");
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe("safeUrl", () => {
|
|
27
|
+
it("allows https and mailto links, and refuses the rest", () => {
|
|
28
|
+
expect(safeUrl("https://example.com/a?b=1")).toBe("https://example.com/a?b=1");
|
|
29
|
+
expect(safeUrl("mailto:office@example.com")).toBe("mailto:office@example.com");
|
|
30
|
+
for (const bad of ["javascript:alert(1)", "http://example.com", "data:text/html,x", "/relative"]) {
|
|
31
|
+
expect(() => safeUrl(bad), bad).toThrow();
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe("partyEmail", () => {
|
|
37
|
+
const email = partyEmail({
|
|
38
|
+
heading: "ยืนยันการลงทะเบียน <ทดสอบ>",
|
|
39
|
+
content: html`<p>สวัสดีคุณ ${"สมหญิง <b>"}</p>`,
|
|
40
|
+
text: "สวัสดีคุณ สมหญิง <b>",
|
|
41
|
+
button: { label: "ดูรายละเอียด", url: "https://my-app.ppleth.ai/events/1?a=1&b=2" },
|
|
42
|
+
preheader: "งานวันอาทิตย์",
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("wraps the message in the party layout: logo, contact footer and address, and nothing under it", () => {
|
|
46
|
+
expect(email.html).toContain('src="https://services.ppleth.ai/email-assets/logo.png"');
|
|
47
|
+
expect(email.html).toContain("ติดต่อเรา");
|
|
48
|
+
expect(email.html).toContain("02-038-5100");
|
|
49
|
+
expect(email.html).toContain("mailto:office@peoplespartythailand.org");
|
|
50
|
+
expect(email.html).toContain("@peoplesth");
|
|
51
|
+
expect(email.html).toContain("กรุงเทพมหานคร 10240");
|
|
52
|
+
expect(email.html).not.toContain("คุณได้รับอีเมลนี้");
|
|
53
|
+
expect(email.html).not.toContain("ไม่รับการตอบกลับ");
|
|
54
|
+
expect(email.html).toContain("งานวันอาทิตย์");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("survives dark mode: navy and orange painted as images too, a light footer, and a dark stylesheet", () => {
|
|
58
|
+
// Gmail's apps invert colours but not background images.
|
|
59
|
+
expect(email.html).toContain("background-image:linear-gradient(#0b3a66,#0b3a66)");
|
|
60
|
+
expect(email.html).toContain("background-image:linear-gradient(#ff6413,#ff6413)");
|
|
61
|
+
// No white text on a dark block: Gmail turns it dark. The footer is light.
|
|
62
|
+
expect(email.html).toMatch(/class="pe-foot" style="background:#f3f5f8/);
|
|
63
|
+
expect(email.html).not.toContain("mix-blend-mode");
|
|
64
|
+
// Mail apps that honour prefers-color-scheme get a real dark version.
|
|
65
|
+
expect(email.html).toContain('<meta name="color-scheme" content="light dark">');
|
|
66
|
+
expect(email.html).toContain("@media (prefers-color-scheme: dark)");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("describes the logo for readers who see no images, and links the address on purpose", () => {
|
|
70
|
+
expect(email.html).toContain('alt="ภาพโลโก้พรรคประชาชน"');
|
|
71
|
+
expect(email.html).toContain('<meta name="format-detection" content="telephone=no,address=no,email=no,date=no">');
|
|
72
|
+
expect(email.html).toContain("https://www.google.com/maps/search/?api=1&query=");
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("escapes the heading, the content's values and the button, and keeps the link's query intact", () => {
|
|
76
|
+
expect(email.html).toContain("ยืนยันการลงทะเบียน <ทดสอบ>");
|
|
77
|
+
expect(email.html).toContain("สมหญิง <b>");
|
|
78
|
+
expect(email.html).not.toContain("<ทดสอบ>");
|
|
79
|
+
expect(email.html).toContain('href="https://my-app.ppleth.ai/events/1?a=1&b=2"');
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("refuses a button link a reader should not follow", () => {
|
|
83
|
+
expect(() =>
|
|
84
|
+
partyEmail({ heading: "x", content: html`x`, text: "x", button: { label: "x", url: "javascript:alert(1)" } }),
|
|
85
|
+
).toThrow();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("carries a plain-text part with the message, the link and the contact details", () => {
|
|
89
|
+
expect(email.body).toContain("ยืนยันการลงทะเบียน <ทดสอบ>");
|
|
90
|
+
expect(email.body).toContain("สวัสดีคุณ สมหญิง <b>");
|
|
91
|
+
expect(email.body).toContain("ดูรายละเอียด: https://my-app.ppleth.ai/events/1?a=1&b=2");
|
|
92
|
+
expect(email.body).toContain("โทร 02-038-5100");
|
|
93
|
+
expect(email.body).toContain("กรุงเทพมหานคร 10240");
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe("sendEmail", () => {
|
|
98
|
+
it("posts the message to platform/email with the App Key, and reports the answer", async () => {
|
|
99
|
+
let seen: { url: string; auth: string | null; json: unknown } | undefined;
|
|
100
|
+
const fetchImpl: typeof fetch = async (input, init) => {
|
|
101
|
+
const req = new Request(input as RequestInfo, init);
|
|
102
|
+
seen = { url: req.url, auth: req.headers.get("authorization"), json: await req.json() };
|
|
103
|
+
return Response.json({ sent: [{ to: "somying@example.com", messageId: "m-1" }], rejected: [] });
|
|
104
|
+
};
|
|
105
|
+
const result = await sendEmail(
|
|
106
|
+
{ PPLE_SERVICES_URL: "https://services.test", PPLE_APP_KEY: "k", DEV_PERSONA: "none" },
|
|
107
|
+
{ to: "somying@example.com", subject: "ยืนยัน", html: "<p>x</p>", body: "x" },
|
|
108
|
+
fetchImpl,
|
|
109
|
+
);
|
|
110
|
+
expect(seen).toEqual({
|
|
111
|
+
url: "https://services.test/platform/email",
|
|
112
|
+
auth: "Bearer k",
|
|
113
|
+
json: { to: "somying@example.com", subject: "ยืนยัน", html: "<p>x</p>", body: "x" },
|
|
114
|
+
});
|
|
115
|
+
expect(result).toEqual({ status: 200, platformError: null, body: { sent: [{ to: "somying@example.com", messageId: "m-1" }], rejected: [] } });
|
|
116
|
+
});
|
|
117
|
+
});
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
kind: service
|
|
3
3
|
visibility: private
|
|
4
|
-
userToken:
|
|
5
|
-
description:
|
|
4
|
+
userToken: optional
|
|
5
|
+
description: รับเงินบริจาค ค่าสินค้า/บริการ ค่าจัดกิจกรรมระดมทุน และค่าบำรุงพรรคผ่านหน้าชำระเงินของแพลตฟอร์ม
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# Payments
|
|
@@ -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
|
});
|