@kedge/plugin-stripe 0.0.0-stage → 0.12.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Kedge Authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @kedge/plugin-stripe
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Part of [Kedge](https://www.npmjs.com/package/create-kedge), an open-source headless commerce backend on Cloudflare Workers and D1. Stripe payments: PaymentIntents for the Payment Element, refunds and disputes, behind core's payment port.
4
+
5
+ Add it to `kedge.config.ts` (`plugins: [stripe()]`), set `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` with `kedge secret put`, and register a webhook endpoint at `<your store>/hooks/payments/stripe`. Your store's `node_modules/@kedge/docs/reference/payments.md` has the rest.
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@kedge/plugin-stripe",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.12.1",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/chandeldivyam/Kedge.git",
8
+ "directory": "packages/plugin-stripe"
9
+ },
10
+ "engines": {
11
+ "node": ">=24"
12
+ },
13
+ "type": "module",
14
+ "description": "Stripe payments for Kedge: the Payment Element's PaymentIntents, refunds and disputes behind core's payment port (docs/proposals/p1.1-payments.md).",
15
+ "exports": {
16
+ ".": "./src/index.ts"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "dependencies": {
22
+ "@kedge/plugin-sdk": "0.12.1"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "24.19.2",
26
+ "@kedge/core": "0.12.1"
27
+ },
28
+ "scripts": {
29
+ "typecheck": "tsc --noEmit -p .",
30
+ "test": "vitest run"
31
+ }
6
32
  }
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ // @kedge/plugin-stripe: Stripe as a Kedge payment provider (p1.1-payments.md).
2
+ // Add it to kedge.config.ts and set STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET
3
+ // with `kedge secret`; core runs the payments, refunds and the settler.
4
+ import { definePaymentProvider, definePlugin } from "@kedge/plugin-sdk";
5
+ import { OVER_REFUND_CODES, PERMANENT_REFUND_FAILURES, stripeClient } from "./stripe";
6
+
7
+ export {
8
+ fromStripeAmount,
9
+ normalizeDispute,
10
+ normalizeIntentStatus,
11
+ PAYMENT_METHODS,
12
+ STRIPE_API_VERSION,
13
+ SWEPT_EVENTS,
14
+ stripeClient,
15
+ toStripeAmount,
16
+ verifyStripeSignature,
17
+ } from "./stripe";
18
+
19
+ export const stripeProvider = definePaymentProvider({
20
+ id: "stripe",
21
+ secrets: ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"],
22
+ // Stripe documents that a canceled PaymentIntent can't be charged again (§4).
23
+ closeIsFinal: true,
24
+ permanentRefundFailures: PERMANENT_REFUND_FAILURES,
25
+ overRefundCodes: OVER_REFUND_CODES,
26
+ connect: (secrets, transport) =>
27
+ stripeClient(
28
+ { secretKey: secrets.STRIPE_SECRET_KEY ?? "", webhookSecret: secrets.STRIPE_WEBHOOK_SECRET ?? null },
29
+ transport,
30
+ ),
31
+ });
32
+
33
+ export default definePlugin({
34
+ name: "stripe",
35
+ version: "1.0.0",
36
+ payments: stripeProvider,
37
+ });
package/src/stripe.ts ADDED
@@ -0,0 +1,601 @@
1
+ // Stripe behind core's payment port (docs/proposals/p1.1-payments.md §2, §11).
2
+ // Every request pins one API version, the one the sandbox gate tested, so a
3
+ // dashboard upgrade never changes what Kedge parses (codex r46). Kedge names
4
+ // the payment methods itself: from 2026-09-30.endive `payment_method_types`
5
+ // is refused and `allowed_payment_method_types` is the explicit list. Stripe's
6
+ // own words never reach the journal or a log: each failure is mapped to a
7
+ // declared code (docs/07 K12).
8
+ import {
9
+ type AccountRead,
10
+ type BudgetClass,
11
+ type ChargeRead,
12
+ type CredentialMode,
13
+ type DisputeRead,
14
+ type EffectOperation,
15
+ type EventRead,
16
+ type Hint,
17
+ KedgeError,
18
+ KedgeProviderError,
19
+ type Page,
20
+ type PaymentProviderClient,
21
+ type PaymentRead,
22
+ type PortDefinition,
23
+ type ProviderTransport,
24
+ paymentPortName,
25
+ type RefundRead,
26
+ } from "@kedge/plugin-sdk";
27
+
28
+ /** The API version every request sends (§5): a constant of this release. */
29
+ export const STRIPE_API_VERSION = "2026-09-30.endive";
30
+ const API = "https://api.stripe.com";
31
+
32
+ /** Card-like methods only, so nothing waits days in `processing` (D-076). */
33
+ export const PAYMENT_METHODS = ["card", "link"] as const;
34
+
35
+ // ---- amounts (§2, https://docs.stripe.com/currencies) ----
36
+
37
+ /** Sent as two-decimal values ending in 00 for backward compatibility. */
38
+ const HUNDRED_X = new Set(["ISK", "UGX"]);
39
+ /** Three-decimal currencies aren't offered here: refused, never rounded. */
40
+ const THREE_DECIMAL = new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
41
+ /** Stripe's minimum charge, in Kedge's minor units, for an account settling in that currency. */
42
+ const MINIMUMS: Readonly<Record<string, number>> = {
43
+ USD: 50,
44
+ AED: 200,
45
+ ARS: 50,
46
+ AUD: 50,
47
+ BRL: 50,
48
+ CAD: 50,
49
+ CHF: 50,
50
+ COP: 50,
51
+ CZK: 1500,
52
+ DKK: 250,
53
+ EUR: 50,
54
+ GBP: 30,
55
+ HKD: 400,
56
+ HUF: 17500,
57
+ IDR: 50,
58
+ ILS: 50,
59
+ INR: 50,
60
+ JPY: 50,
61
+ KRW: 50,
62
+ MXN: 1000,
63
+ MYR: 200,
64
+ NOK: 300,
65
+ NZD: 50,
66
+ PHP: 50,
67
+ PLN: 200,
68
+ RON: 200,
69
+ SEK: 300,
70
+ SGD: 50,
71
+ THB: 1000,
72
+ ZAR: 50,
73
+ };
74
+
75
+ export function toStripeAmount(amount: number, currency: string): number {
76
+ const c = currency.toUpperCase();
77
+ if (!Number.isSafeInteger(amount) || amount < 0 || THREE_DECIMAL.has(c))
78
+ throw new KedgeError("PAYMENT_AMOUNT_UNSUPPORTED", "Stripe can't take this amount in this currency", {
79
+ currency_code: c,
80
+ });
81
+ const out = HUNDRED_X.has(c) ? amount * 100 : amount;
82
+ // Card networks allow 12 digits at most.
83
+ if (out > 999_999_999_999)
84
+ throw new KedgeError("PAYMENT_AMOUNT_UNSUPPORTED", "Stripe can't take an amount this large", { currency_code: c });
85
+ return out;
86
+ }
87
+
88
+ export function fromStripeAmount(amount: number, currency: string): number {
89
+ const c = currency.toUpperCase();
90
+ if (!HUNDRED_X.has(c)) return amount;
91
+ // kedge-allow no-dynamic-throw: an amount and a currency code
92
+ if (amount % 100 !== 0) throw new Error(`Stripe sent a fractional ${c} amount`);
93
+ return amount / 100;
94
+ }
95
+
96
+ // ---- requests ----
97
+
98
+ /** Stripe's form encoding: nested keys in brackets, arrays as `key[]`. */
99
+ export function formEncode(body: Readonly<Record<string, unknown>>, prefix = ""): string[] {
100
+ const out: string[] = [];
101
+ for (const [k, v] of Object.entries(body)) {
102
+ if (v === undefined || v === null) continue;
103
+ const key = prefix ? `${prefix}[${k}]` : k;
104
+ if (Array.isArray(v))
105
+ for (const x of v) out.push(`${encodeURIComponent(`${key}[]`)}=${encodeURIComponent(String(x))}`);
106
+ else if (typeof v === "object") out.push(...formEncode(v as Record<string, unknown>, key));
107
+ else out.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`);
108
+ }
109
+ return out;
110
+ }
111
+
112
+ interface StripeError {
113
+ readonly type?: string;
114
+ readonly code?: string;
115
+ readonly param?: string;
116
+ }
117
+
118
+ /** A Stripe answer that isn't 2xx, by status and machine fields only. */
119
+ export class StripeHttpError extends Error {
120
+ constructor(
121
+ readonly status: number,
122
+ readonly error: StripeError,
123
+ ) {
124
+ super(`stripe_${status}`);
125
+ }
126
+ }
127
+
128
+ type Json = Record<string, unknown>;
129
+ const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
130
+ const num = (v: unknown): number => (typeof v === "number" ? v : 0);
131
+
132
+ export interface StripeSecrets {
133
+ readonly secretKey: string;
134
+ readonly webhookSecret: string | null;
135
+ }
136
+
137
+ // ---- normalization (§2, §6.2) ----
138
+
139
+ /** PaymentIntent statuses: a failed attempt goes back to requires_payment_method, not a close. */
140
+ export function normalizeIntentStatus(status: string): PaymentRead["status"] | null {
141
+ if (status === "succeeded") return "succeeded";
142
+ if (status === "canceled") return "canceled";
143
+ if (status === "processing") return "processing";
144
+ if (["requires_payment_method", "requires_confirmation", "requires_action", "requires_capture"].includes(status))
145
+ return "open";
146
+ return null;
147
+ }
148
+
149
+ /** Dispute statuses (§6.2): inquiries are `warning_*`; anything else unknown is `dispute_unexplained`. */
150
+ export function normalizeDispute(
151
+ status: string,
152
+ ): { kind: "inquiry" | "dispute"; open: boolean; outcome: string | null } | null {
153
+ if (status === "warning_needs_response" || status === "warning_under_review")
154
+ return { kind: "inquiry", open: true, outcome: null };
155
+ if (status === "warning_closed") return { kind: "inquiry", open: false, outcome: status };
156
+ if (["needs_response", "under_review", "appeal_needs_response", "appeal_under_review"].includes(status))
157
+ return { kind: "dispute", open: true, outcome: null };
158
+ if (["won", "lost", "prevented"].includes(status)) return { kind: "dispute", open: false, outcome: status };
159
+ return null;
160
+ }
161
+
162
+ export function chargeOf(c: Json): ChargeRead {
163
+ const currency = String(c.currency ?? "").toUpperCase();
164
+ return {
165
+ id: String(c.id),
166
+ amount: fromStripeAmount(num(c.amount), currency),
167
+ currency,
168
+ amountRefunded: fromStripeAmount(num(c.amount_refunded), currency),
169
+ disputed: c.disputed === true,
170
+ latestDisputeId: typeof c.dispute === "string" ? c.dispute : str((c.dispute as Json | null)?.id),
171
+ captured: c.captured === true && c.status === "succeeded",
172
+ providerTimes: { created: num(c.created) },
173
+ };
174
+ }
175
+
176
+ function refundOf(r: Json): RefundRead {
177
+ const currency = String(r.currency ?? "").toUpperCase();
178
+ const status = String(r.status);
179
+ const metadata = (r.metadata ?? {}) as Json;
180
+ return {
181
+ id: String(r.id),
182
+ chargeId: str(r.charge),
183
+ paymentRef: str(r.payment_intent),
184
+ amount: fromStripeAmount(num(r.amount), currency),
185
+ currency,
186
+ // `requires_action` is a refund waiting on the customer: pending to Kedge.
187
+ status: status === "requires_action" ? "pending" : (status as RefundRead["status"]),
188
+ kedgeRefundId: str(metadata.kedge_refund_id),
189
+ created: num(r.created),
190
+ failureReason: str(r.failure_reason),
191
+ };
192
+ }
193
+
194
+ function disputeOf(d: Json): DisputeRead {
195
+ const status = String(d.status);
196
+ const n = normalizeDispute(status);
197
+ const txns = Array.isArray(d.balance_transactions) ? (d.balance_transactions as Json[]) : [];
198
+ return {
199
+ id: String(d.id),
200
+ chargeId: String(d.charge),
201
+ status,
202
+ kind: n?.kind ?? null,
203
+ open: n?.open ?? false,
204
+ outcome: n?.outcome ?? null,
205
+ refundable: typeof d.is_charge_refundable === "boolean" ? d.is_charge_refundable : null,
206
+ // Each balance transaction's own amount is the movement's principal; its fee is apart (§6.2).
207
+ movements: txns.map((t) => {
208
+ const currency = String(t.currency ?? "").toUpperCase();
209
+ const amount = num(t.amount);
210
+ return {
211
+ id: String(t.id),
212
+ amount: fromStripeAmount(Math.abs(amount), currency),
213
+ currency,
214
+ direction: amount < 0 ? ("withdrawal" as const) : ("reinstatement" as const),
215
+ };
216
+ }),
217
+ };
218
+ }
219
+
220
+ /** The events the sweep turns into hints (§6.4): charges, refunds, disputes and the intent's ends. */
221
+ export const SWEPT_EVENTS = [
222
+ "payment_intent.succeeded",
223
+ "payment_intent.canceled",
224
+ "payment_intent.payment_failed",
225
+ "charge.refunded",
226
+ "charge.refund.updated",
227
+ "refund.created",
228
+ "refund.updated",
229
+ "refund.failed",
230
+ "charge.dispute.created",
231
+ "charge.dispute.updated",
232
+ "charge.dispute.closed",
233
+ "charge.dispute.funds_withdrawn",
234
+ "charge.dispute.funds_reinstated",
235
+ ] as const;
236
+
237
+ function eventOf(e: Json): EventRead {
238
+ const data = (e.data ?? {}) as Json;
239
+ const object = (data.object ?? {}) as Json;
240
+ const request = (e.request ?? {}) as Json;
241
+ return {
242
+ id: String(e.id),
243
+ type: String(e.type),
244
+ objectId: String(object.id),
245
+ created: num(e.created),
246
+ idempotencyKey: str(request.idempotency_key),
247
+ paymentRef: String(object.object) === "payment_intent" ? str(object.id) : str(object.payment_intent),
248
+ };
249
+ }
250
+
251
+ const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
252
+
253
+ /** Constant time over the full length, so a signature can't be learned a byte at a time. */
254
+ function timingSafeEqual(a: string, b: string): boolean {
255
+ if (a.length !== b.length) return false;
256
+ let diff = 0;
257
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
258
+ return diff === 0;
259
+ }
260
+
261
+ /**
262
+ * `Stripe-Signature` (§10): HMAC-SHA256 of `t.body` under the endpoint
263
+ * secret, any `v1` matching, within 5 minutes of `now`
264
+ * (https://docs.stripe.com/webhooks). A bad one is null: nothing is written.
265
+ */
266
+ export async function verifyStripeSignature(
267
+ body: string,
268
+ header: string | null,
269
+ secret: string,
270
+ now: number,
271
+ ): Promise<boolean> {
272
+ if (!header) return false;
273
+ const parts = header.split(",").map((p) => p.trim().split("=", 2) as [string, string]);
274
+ const t = Number(parts.find(([k]) => k === "t")?.[1]);
275
+ if (!Number.isSafeInteger(t) || Math.abs(now / 1000 - t) > 300) return false;
276
+ const key = await crypto.subtle.importKey(
277
+ "raw",
278
+ new TextEncoder().encode(secret),
279
+ { name: "HMAC", hash: "SHA-256" },
280
+ false,
281
+ ["sign"],
282
+ );
283
+ const expected = hex(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${t}.${body}`)));
284
+ return parts.filter(([k]) => k === "v1").some(([, v]) => timingSafeEqual(v ?? "", expected));
285
+ }
286
+
287
+ /** Refund codes that make a restitution staff's at once (§6.3): the card can't take money back. */
288
+ export const PERMANENT_REFUND_FAILURES = [
289
+ "expired_or_canceled_card",
290
+ "lost_or_stolen_card",
291
+ "charge_for_pending_refund_disputed",
292
+ ];
293
+ /** Refusals meaning "beyond what remains on the charge" (§6.3, §7.2). */
294
+ export const OVER_REFUND_CODES = ["over_refund"];
295
+
296
+ /** The client bound to its secrets and transport: one per request or settler turn. */
297
+ export function stripeClient(secrets: StripeSecrets, transport: ProviderTransport): PaymentProviderClient {
298
+ async function call(
299
+ method: "GET" | "POST",
300
+ path: string,
301
+ budget: BudgetClass,
302
+ o: { body?: Json; query?: Json; idempotencyKey?: string; signal?: AbortSignal | undefined } = {},
303
+ ): Promise<Json> {
304
+ const query = o.query ? `?${formEncode(o.query).join("&")}` : "";
305
+ const headers: Record<string, string> = {
306
+ authorization: `Bearer ${secrets.secretKey}`,
307
+ "stripe-version": STRIPE_API_VERSION,
308
+ };
309
+ if (o.idempotencyKey) headers["idempotency-key"] = o.idempotencyKey;
310
+ let body: string | undefined;
311
+ if (method === "POST") {
312
+ headers["content-type"] = "application/x-www-form-urlencoded";
313
+ body = formEncode(o.body ?? {}).join("&");
314
+ }
315
+ const res = await transport.fetch(
316
+ new Request(`${API}${path}${query}`, { method, headers, body }),
317
+ budget,
318
+ o.signal,
319
+ );
320
+ const json = (await res.json().catch(() => ({}))) as Json;
321
+ if (!res.ok) throw new StripeHttpError(res.status, (json.error ?? {}) as StripeError);
322
+ return json;
323
+ }
324
+
325
+ /**
326
+ * Maps a failed money or close call to what K12 needs (§7.2): a refusal
327
+ * Stripe answered is final (it saved that answer under the key), a rate
328
+ * limit was verifiably not executed, and anything else is a lost result.
329
+ */
330
+ const providerError = (e: unknown, finalCode: (err: StripeError) => string): never => {
331
+ if (e instanceof StripeHttpError) {
332
+ if (e.status === 429) throw new KedgeProviderError("rate_limited", { notExecuted: true });
333
+ if (e.status >= 400 && e.status < 500 && e.status !== 409)
334
+ throw new KedgeProviderError(finalCode(e.error), { final: true });
335
+ }
336
+ throw e;
337
+ };
338
+
339
+ /**
340
+ * The charge's latest dispute by identity (code r8). The sandbox's charge
341
+ * names it in `dispute` (2026-11-06), which the Charge reference doesn't
342
+ * document; when it's absent, the newest dispute by charge from the
343
+ * documented list (https://docs.stripe.com/api/disputes/list) names it, so a
344
+ * known older dispute can never explain a newer one's flag.
345
+ */
346
+ async function identified(c: ChargeRead, budget: BudgetClass, signal?: AbortSignal): Promise<ChargeRead> {
347
+ if (!c.disputed || c.latestDisputeId !== null) return c;
348
+ const list = await call("GET", "/v1/disputes", budget, { query: { charge: c.id, limit: 1 }, signal });
349
+ const first = Array.isArray(list.data) ? (list.data[0] as Json | undefined) : undefined;
350
+ return { ...c, latestDisputeId: str(first?.id) };
351
+ }
352
+
353
+ async function retrieve(ref: string, budget: BudgetClass, signal?: AbortSignal): Promise<PaymentRead> {
354
+ const pi = await call("GET", `/v1/payment_intents/${encodeURIComponent(ref)}`, budget, {
355
+ query: { expand: ["latest_charge"] },
356
+ signal,
357
+ });
358
+ const status = normalizeIntentStatus(String(pi.status));
359
+ // kedge-allow no-dynamic-throw: a provider status token
360
+ if (!status) throw new Error(`unknown PaymentIntent status ${String(pi.status)}`);
361
+ const charge =
362
+ pi.latest_charge && typeof pi.latest_charge === "object"
363
+ ? await identified(chargeOf(pi.latest_charge as Json), budget, signal)
364
+ : null;
365
+ const currency = String(pi.currency ?? "").toUpperCase();
366
+ return {
367
+ ref: String(pi.id),
368
+ status,
369
+ rawStatus: String(pi.status),
370
+ amount: fromStripeAmount(num(pi.amount), currency),
371
+ currency,
372
+ charge,
373
+ kedgePaymentId: str(((pi.metadata ?? {}) as Json).kedge_payment_id),
374
+ };
375
+ }
376
+
377
+ const initiate: EffectOperation = {
378
+ kind: "effect",
379
+ version: 1,
380
+ // Creating an unconfirmed intent moves no money; Stripe keeps the key 24 hours (§2).
381
+ category: "other",
382
+ resend: { policy: "window", delayMs: 3_600_000 },
383
+ erasure: "operational",
384
+ result: { intent_id: "id", status: "status" },
385
+ failures: ["initiation_refused"],
386
+ call: async (input, c) => {
387
+ try {
388
+ const pi = await call("POST", "/v1/payment_intents", "storefront", {
389
+ body: input as Json,
390
+ idempotencyKey: c.providerKey,
391
+ signal: c.signal,
392
+ });
393
+ return { intent_id: String(pi.id), status: String(pi.status) };
394
+ } catch (e) {
395
+ return providerError(e, () => "initiation_refused");
396
+ }
397
+ },
398
+ };
399
+
400
+ const close: EffectOperation = {
401
+ kind: "effect",
402
+ version: 1,
403
+ category: "other",
404
+ // "Ensure canceled" (§7.2): kept uncertain when lost; the next cancel goes under a new occurrence.
405
+ resend: { policy: "never" },
406
+ erasure: "operational",
407
+ result: { intent_id: "id", status: "status" },
408
+ failures: ["intent_succeeded", "close_refused"],
409
+ call: async (input, c) => {
410
+ const ref = String(input.intent_id);
411
+ try {
412
+ const pi = await call("POST", `/v1/payment_intents/${encodeURIComponent(ref)}/cancel`, "money", {
413
+ idempotencyKey: c.providerKey,
414
+ signal: c.signal,
415
+ });
416
+ return { intent_id: String(pi.id), status: String(pi.status) };
417
+ } catch (e) {
418
+ // Already canceled, or paid first: an authenticated read decides (codex r38, r43).
419
+ if (e instanceof StripeHttpError && e.error.code === "payment_intent_unexpected_state") {
420
+ const read = await retrieve(ref, "money", c.signal);
421
+ if (read.status === "canceled") return { intent_id: read.ref, status: "canceled" };
422
+ if (read.status === "succeeded" || read.status === "processing")
423
+ throw new KedgeProviderError("intent_succeeded", { final: true });
424
+ }
425
+ return providerError(e, () => "close_refused");
426
+ }
427
+ },
428
+ };
429
+
430
+ const refund: EffectOperation = {
431
+ kind: "effect",
432
+ version: 1,
433
+ category: "refund",
434
+ money: true,
435
+ resend: { policy: "never" },
436
+ erasure: "required",
437
+ result: { refund_id: "id", status: "status" },
438
+ failures: ["over_refund", "charge_disputed", "refund_refused", ...PERMANENT_REFUND_FAILURES],
439
+ call: async (input, c) => {
440
+ try {
441
+ const r = await call("POST", "/v1/refunds", "money", {
442
+ body: {
443
+ payment_intent: input.payment_intent,
444
+ amount: toStripeAmount(Number(input.amount), String(input.currency)),
445
+ metadata: { kedge_refund_id: input.kedge_refund_id },
446
+ },
447
+ idempotencyKey: c.providerKey,
448
+ signal: c.signal,
449
+ });
450
+ const read = refundOf(r);
451
+ return { refund_id: read.id, status: read.status };
452
+ } catch (e) {
453
+ return providerError(e, (err) => {
454
+ if (err.code === "charge_disputed") return "charge_disputed";
455
+ // Beyond what remains: Stripe names the param, not a code (sandbox, 2026-11-03).
456
+ if (
457
+ err.code === "charge_already_refunded" ||
458
+ (err.type === "invalid_request_error" && err.param === "amount")
459
+ )
460
+ return "over_refund";
461
+ return err.code && PERMANENT_REFUND_FAILURES.includes(err.code) ? err.code : "refund_refused";
462
+ });
463
+ }
464
+ },
465
+ };
466
+
467
+ let account: Promise<AccountRead> | null = null;
468
+ const accountRead = (signal?: AbortSignal) => {
469
+ account ??= call("GET", "/v1/account", "watch", { signal }).then((a) => ({
470
+ binding: String(a.id),
471
+ defaultCurrency: String(a.default_currency ?? "").toUpperCase(),
472
+ }));
473
+ return account;
474
+ };
475
+
476
+ const port: PortDefinition = {
477
+ name: paymentPortName("stripe"),
478
+ deliveryClass: "effect",
479
+ // Keys are enforced per account; Stripe may prune them after 24 hours (§2).
480
+ dedupe: { enforced: true, scope: "account", horizonMs: 86_400_000 },
481
+ binding: async () => ({
482
+ provider: "stripe",
483
+ account: (await accountRead()).binding,
484
+ installation: null,
485
+ scope: "default",
486
+ }),
487
+ credentialMode: () => credentialMode(),
488
+ operations: { initiate, close, refund },
489
+ };
490
+
491
+ async function credentialMode(): Promise<CredentialMode> {
492
+ const prefix = /^(sk|rk)_(test|live)_/.exec(secrets.secretKey)?.[2];
493
+ try {
494
+ // The balance read says `livemode` (§11); the account object has none.
495
+ const b = await call("GET", "/v1/balance", "watch");
496
+ const live = b.livemode === true;
497
+ if (!prefix || (prefix === "live") !== live) return "unknown";
498
+ return live ? "live" : "test";
499
+ } catch {
500
+ return "unknown";
501
+ }
502
+ }
503
+
504
+ const page = <T>(list: Json, map: (x: Json) => T): Page<T> => {
505
+ const items = (Array.isArray(list.data) ? (list.data as Json[]) : []).map(map);
506
+ const last = (list.data as Json[] | undefined)?.at(-1);
507
+ return { items, next: list.has_more === true && last ? String(last.id) : null };
508
+ };
509
+
510
+ return {
511
+ port,
512
+ toProvider: toStripeAmount,
513
+ fromProvider: fromStripeAmount,
514
+ minimum: (currency) => MINIMUMS[currency.toUpperCase()] ?? 1,
515
+ initiation: (input) => ({
516
+ amount: toStripeAmount(input.amount, input.currency),
517
+ currency: input.currency.toLowerCase(),
518
+ capture_method: "automatic",
519
+ allowed_payment_method_types: [...PAYMENT_METHODS],
520
+ metadata: { kedge_payment_id: input.paymentId, kedge_order_id: input.orderId },
521
+ }),
522
+ account: accountRead,
523
+ retrieve,
524
+ capability: async (ref, signal) => {
525
+ const pi = await call("GET", `/v1/payment_intents/${encodeURIComponent(ref)}`, "storefront", { signal });
526
+ return { kind: "stripe", client_secret: String(pi.client_secret) };
527
+ },
528
+ refunds: async (ref, cursor, signal) =>
529
+ page(
530
+ await call("GET", "/v1/refunds", "reconcile", {
531
+ query: { payment_intent: ref, limit: 25, starting_after: cursor ?? undefined },
532
+ signal,
533
+ }),
534
+ refundOf,
535
+ ),
536
+ disputes: async (chargeId, cursor, signal) =>
537
+ page(
538
+ await call("GET", "/v1/disputes", "reconcile", {
539
+ query: { charge: chargeId, limit: 25, starting_after: cursor ?? undefined },
540
+ signal,
541
+ }),
542
+ disputeOf,
543
+ ),
544
+ refund: async (id, signal) =>
545
+ refundOf(await call("GET", `/v1/refunds/${encodeURIComponent(id)}`, "reconcile", { signal })),
546
+ charge: async (id, signal) => {
547
+ const c = await call("GET", `/v1/charges/${encodeURIComponent(id)}`, "reconcile", { signal });
548
+ return { ...(await identified(chargeOf(c), "reconcile", signal)), paymentRef: str(c.payment_intent) };
549
+ },
550
+ events: async (cursor, signal, older) => {
551
+ if (older) {
552
+ // Newest first, paged back by `starting_after` (https://docs.stripe.com/api/events/list).
553
+ const list = await call("GET", "/v1/events", "reconcile", {
554
+ query: { limit: 100, type: older.type, starting_after: cursor ?? undefined },
555
+ signal,
556
+ });
557
+ return page(list, eventOf);
558
+ }
559
+ // The sweep's cursor is the newest event seen; Stripe lists newest first,
560
+ // so `ending_before` pages forward from it (§6.4).
561
+ const list = await call("GET", "/v1/events", "watch", {
562
+ query: { limit: 100, types: [...SWEPT_EVENTS], ending_before: cursor ?? undefined },
563
+ signal,
564
+ });
565
+ const items = (Array.isArray(list.data) ? (list.data as Json[]) : []).map(eventOf);
566
+ return { items, next: items[0]?.id ?? null };
567
+ },
568
+ event: async (id, signal) =>
569
+ eventOf(await call("GET", `/v1/events/${encodeURIComponent(id)}`, "reconcile", { signal })),
570
+ verifyWebhook: async (body, headers, now): Promise<Hint | null> => {
571
+ if (!secrets.webhookSecret) return null;
572
+ if (!(await verifyStripeSignature(body, headers.get("stripe-signature"), secrets.webhookSecret, now)))
573
+ return null;
574
+ let e: Json;
575
+ try {
576
+ e = JSON.parse(body) as Json;
577
+ } catch {
578
+ return null;
579
+ }
580
+ const object = (((e.data ?? {}) as Json).object ?? {}) as Json;
581
+ const paymentRef = String(object.object) === "payment_intent" ? str(object.id) : str(object.payment_intent);
582
+ return { id: String(e.id), type: String(e.type), objectRef: String(object.id), paymentRef };
583
+ },
584
+ credentialMode,
585
+ webhookStatus: async (url) => {
586
+ const list = await call("GET", "/v1/webhook_endpoints", "watch", { query: { limit: 100 } });
587
+ const endpoints = (Array.isArray(list.data) ? (list.data as Json[]) : []).filter(
588
+ (e) => e.url === url && e.status === "enabled",
589
+ );
590
+ const covers = (e: Json) => {
591
+ const events = Array.isArray(e.enabled_events) ? (e.enabled_events as string[]) : [];
592
+ return events.includes("*") || SWEPT_EVENTS.every((t) => events.includes(t));
593
+ };
594
+ return {
595
+ registered: endpoints.length > 0,
596
+ apiVersionMatches: endpoints.some((e) => e.api_version === STRIPE_API_VERSION),
597
+ eventsCovered: endpoints.some(covers),
598
+ };
599
+ },
600
+ };
601
+ }