@blamejs/blamejs-shop 0.1.13 → 0.1.15

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/CHANGELOG.md CHANGED
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.1.x
10
10
 
11
+ - v0.1.15 (2026-05-25) — **PayPal checkout orchestration.** Checkout can now run a PayPal order end to end, building on the adapter from the previous release. The orchestrator prices the cart, opens a PayPal order and persists the local order as pending, captures it after the buyer approves and advances the order to paid, and has a webhook backstop for captures completed or refunded out of band. Wired in when a PayPal app's credentials are present, and surfaced on the integrations status page. The storefront button and routes that drive this from the pay page come next; card / Stripe checkout is unchanged. **Added:** *checkout PayPal methods* — With a PayPal adapter wired (`paypal` dep), checkout gains three methods. `createPaypalOrder({ cart_id, ship_to, selected_shipping_id, customer, idempotency_key, return_url?, cancel_url? })` prices the cart, opens a PayPal Orders-v2 order, persists the local order in `pending` with the PayPal order id linked, and marks the cart converted. `capturePaypalOrder(paypalOrderId)` captures the approved order and advances the local order to `paid` (idempotent — a retry or a webhook that beat it won't double-transition). `handlePaypalEvent({ headers, rawBody })` is the asynchronous backstop: it verifies the event through PayPal, then maps `PAYMENT.CAPTURE.COMPLETED` → paid and `PAYMENT.CAPTURE.REFUNDED` → refunded, idempotent across re-deliveries. · *PayPal wired from configuration* — When `PAYPAL_CLIENT_ID` + `PAYPAL_SECRET` are set (with `PAYPAL_ENV` and `PAYPAL_WEBHOOK_ID`), the server builds the PayPal adapter and passes it to checkout; the integrations status page lists PayPal as action-needed once card checkout is also live. Off until configured; the existing checkout flow is untouched.
12
+
13
+ - v0.1.14 (2026-05-25) — **PayPal payment adapter (Orders v2).** `payment.create({ adapter: "paypal", … })` is a new native PayPal adapter alongside the Stripe one — a from-scratch Orders-v2 client over the framework's SSRF-gated HTTP client, with no PayPal SDK dependency. It exchanges an OAuth2 client-credentials token (cached until it nears expiry), creates and captures orders, fetches and refunds them, and verifies inbound webhooks through PayPal's verify-webhook-signature API. This ships the adapter only; wiring it into the checkout flow and a storefront button comes next. Card / Stripe checkout is unchanged. **Added:** *PayPal Orders-v2 adapter* — `payment.create({ adapter: "paypal", clientId, secret, sandbox?, webhookId?, apiBase? })` returns `{ createOrder, captureOrder, getOrder, refund, verifyWebhook }`. `createOrder({ amount_minor, currency, order_id?, return_url?, cancel_url? })` opens a CAPTURE-intent order (amounts converted to PayPal's decimal-string major units, including 0-decimal currencies); `captureOrder(id)` finalizes it; `refund({ capture_id, amount_minor?, currency? })` refunds full or partial; `getOrder(id)` reads status. Every call carries an OAuth2 bearer token exchanged once and cached until ~2 minutes before expiry, and a `PayPal-Request-Id` for idempotency (plus the shared idempotency cache when a `query` handle is wired). `verifyWebhook(headers, rawBody, { webhookId })` confirms an inbound event through PayPal's verify-webhook-signature API and returns `{ ok, event }`. Outbound HTTP goes through `b.httpClient` — no `paypal` npm dependency. Off until the operator supplies credentials; the Stripe adapter and existing checkout are unchanged.
14
+
11
15
  - v0.1.13 (2026-05-25) — **Internal: uniform framework access across the library.** An internal consistency refactor with no API or behavior change. Every library module now captures the framework once at the top — straight from the vendored tree (`var b = require("./vendor/blamejs");`) — and uses `b.*` uniformly, replacing a per-module lazy accessor and its scattered call sites. Capturing the framework directly (rather than via the composing entry point) also avoids a circular-load edge case on leaf-first imports. Two source files that embedded a raw NUL byte as a map-key separator now use the `\u0000` escape, so the whole library is plain text. New lint rules lock all of this in place. Public APIs, runtime behavior, and the published surface are unchanged. **Added:** *Lint detectors for accessor uniformity and source hygiene* — Three repository lint rules now prevent drift: one rejects the reintroduction of the per-module lazy framework accessor (capture the framework once at module top); one rejects requiring the composing entry point from a leaf module (require the vendored framework directly — entry-point requires from a leaf create a circular-load hazard); and one rejects raw C0 control bytes in source files (write `\u0000` and friends as escapes so files stay plain text — grep / diff / editors handle them correctly). **Changed:** *Framework handle captured once per module* — Library modules previously reached the vendored framework through a lazy `_b()` accessor invoked at every call site. They now capture it once at module top — `var b = require("./vendor/blamejs");`, the same object the entry point re-exports as `.framework` — and reference `b.*` directly, matching how the edge worker already accesses it. Capturing it directly from the vendored tree (instead of through the composing entry point) keeps leaf-first module imports working — requiring a single module no longer pulls the entry point's whole assembly mid-initialization. No public API or runtime behavior changes.
12
16
 
13
17
  - v0.1.12 (2026-05-25) — **Card payments now finalize the order — the Stripe webhook is handled end to end.** A confirmed Stripe payment now advances the order from pending to paid. The container now serves the `POST /api/webhooks/stripe` route the edge worker forwards to: it re-verifies the event signature over the exact raw bytes, maps the event to the order's FSM transition, and is idempotent across Stripe's re-deliveries. Previously the edge verified the webhook but nothing consumed it on the container, so a paid PaymentIntent (card, Apple Pay, or Google Pay) left the order stuck in pending — no fulfillment, no paid status. Operators running checkout should upgrade and confirm their Stripe webhook points at `/api/webhooks/stripe`. **Added:** *Raw-body capture for payment webhooks* — A small middleware preserves the exact request bytes for the webhook path before the JSON body-parser runs, so signature verification (which is computed over the raw body) is reliable. It is scoped to the webhook routes and leaves every other request untouched. **Fixed:** *Stripe webhook completes the order* — `POST /api/webhooks/stripe` is now handled on the container: the event signature is re-verified against `STRIPE_WEBHOOK_SECRET` over the raw request body (a tampered or unsigned event is rejected with 400), then `payment_intent.succeeded` / `.canceled` / `charge.refunded` drive the order FSM (`mark_paid` / `cancel` / `refund`). Re-deliveries are idempotent — an event for an order already in the target state is acknowledged with 200 and skipped. A delivery for an unknown PaymentIntent is acknowledged without effect. This closes the gap where a confirmed payment never moved the order out of `pending`.
package/lib/admin.js CHANGED
@@ -1785,6 +1785,8 @@ var INTEGRATIONS_CATALOG = [
1785
1785
  set: "GOOGLE_OAUTH_CLIENT_ID, GOOGLE_OAUTH_CLIENT_SECRET, SHOP_ORIGIN. Add <SHOP_ORIGIN>/account/auth/google/callback as a Google OAuth redirect URI." },
1786
1786
  { key: "apple_signin", name: "Sign in with Apple", enables: "A “Continue with Apple” button on the account login page.",
1787
1787
  set: "APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_CLIENT_ID (your Services ID), APPLE_PRIVATE_KEY (the .p8 key contents), SHOP_ORIGIN. Add <SHOP_ORIGIN>/account/auth/apple/callback as a Return URL on the Services ID. Requires an Apple Developer Program membership." },
1788
+ { key: "paypal", name: "PayPal checkout", enables: "Native PayPal create / capture via PayPal Orders v2 (distinct from PayPal-through-Stripe). The on-page button and webhook endpoint land in a follow-up release.",
1789
+ set: "PAYPAL_CLIENT_ID, PAYPAL_SECRET (a PayPal REST app), PAYPAL_WEBHOOK_ID, PAYPAL_ENV (sandbox|live). Card checkout (Stripe) must be live too." },
1788
1790
  ];
1789
1791
 
1790
1792
  function renderAdminIntegrations(opts) {
package/lib/checkout.js CHANGED
@@ -73,6 +73,15 @@ var STRIPE_EVENT_MAP = Object.freeze({
73
73
  // Subscription webhook event types route to the subscriptions
74
74
  // primitive (if wired via deps.subscriptions) instead of the order
75
75
  // FSM. The one-time-order path stays unchanged.
76
+ // PayPal webhook event types → order FSM event. The create/capture flow
77
+ // marks the order paid directly; these are the asynchronous backstop.
78
+ var PAYPAL_EVENT_MAP = Object.freeze({
79
+ "PAYMENT.CAPTURE.COMPLETED": "mark_paid",
80
+ "PAYMENT.CAPTURE.DENIED": null, // no state change — operator decides
81
+ "PAYMENT.CAPTURE.REFUNDED": "refund",
82
+ "CHECKOUT.ORDER.APPROVED": null, // approved but not captured yet
83
+ });
84
+
76
85
  var STRIPE_SUB_EVENT_TYPES = Object.freeze({
77
86
  "customer.subscription.created": true,
78
87
  "customer.subscription.updated": true,
@@ -90,6 +99,7 @@ function create(deps) {
90
99
  var tax = deps.tax;
91
100
  var shipping = deps.shipping;
92
101
  var payment = deps.payment;
102
+ var paypal = deps.paypal || null; // PayPal adapter — checkout-via-PayPal disabled when absent
93
103
  var order = deps.order;
94
104
  var subscriptions = deps.subscriptions || null;
95
105
  // Optional — when wired, the buyer email is hashed (via the same
@@ -313,6 +323,128 @@ function create(deps) {
313
323
  }
314
324
  return { handled: true, event_type: eventType, order: updated };
315
325
  },
326
+
327
+ // ---- PayPal (Orders v2) ----------------------------------------------
328
+ //
329
+ // PayPal's flow is create → buyer-approve → capture, not a Stripe-style
330
+ // PaymentIntent + webhook. `createPaypalOrder` prices the cart, opens a
331
+ // PayPal order, and persists the local order in `pending` with the PayPal
332
+ // order id linked. `capturePaypalOrder` (called after the buyer approves)
333
+ // captures and advances the order to `paid`. `handlePaypalEvent` is the
334
+ // async backstop. All three require the `paypal` adapter to be wired.
335
+
336
+ createPaypalOrder: async function (input) {
337
+ if (!paypal) throw new TypeError("checkout.createPaypalOrder: paypal adapter not wired");
338
+ if (!input || typeof input !== "object") throw new TypeError("checkout.createPaypalOrder: input required");
339
+ if (!input.customer || typeof input.customer !== "object") throw new TypeError("checkout.createPaypalOrder: customer required");
340
+ var email = _email(input.customer.customer_email || input.customer.email);
341
+ if (!input.selected_shipping_id) throw new TypeError("checkout.createPaypalOrder: selected_shipping_id required");
342
+ var idempotencyKey = input.idempotency_key;
343
+ if (typeof idempotencyKey !== "string" || idempotencyKey.length < 8) {
344
+ throw new TypeError("checkout.createPaypalOrder: idempotency_key (≥8 chars) required");
345
+ }
346
+ var quote = await _buildQuote(input);
347
+ if (quote.totals.grand_total_minor <= 0) {
348
+ throw new TypeError("checkout.createPaypalOrder: grand_total_minor must be > 0");
349
+ }
350
+ var ppOrder = await paypal.createOrder({
351
+ amount_minor: quote.totals.grand_total_minor,
352
+ currency: quote.currency.toUpperCase(),
353
+ order_id: quote.cart_id,
354
+ return_url: input.return_url || undefined,
355
+ cancel_url: input.cancel_url || undefined,
356
+ }, idempotencyKey);
357
+ var cartRow = await cart.get(quote.cart_id);
358
+ var createdOrder = await order.createFromCart({
359
+ cart_id: quote.cart_id,
360
+ session_id: cartRow.session_id,
361
+ customer_id: cartRow.customer_id || null,
362
+ currency: quote.currency,
363
+ subtotal_minor: quote.totals.subtotal_minor,
364
+ discount_minor: quote.totals.discount_minor,
365
+ tax_minor: quote.totals.tax_minor,
366
+ shipping_minor: quote.totals.shipping_minor,
367
+ grand_total_minor: quote.totals.grand_total_minor,
368
+ payment_intent_id: ppOrder.id, // the PayPal order id (opaque); links the webhook + capture
369
+ ship_to: input.ship_to,
370
+ customer_email_hash: customers ? customers.hashEmail(email) : null,
371
+ lines: quote.lines.map(function (l) {
372
+ return { variant_id: l.variant_id, sku: l.sku, qty: l.qty, unit_amount_minor: l.unit_amount_minor, unit_currency: l.unit_currency };
373
+ }),
374
+ });
375
+ await cart.setStatus(quote.cart_id, "converted");
376
+ return { order: createdOrder, paypal_order_id: ppOrder.id, status: ppOrder.status };
377
+ },
378
+
379
+ // Capture an approved PayPal order, then advance the local order to paid.
380
+ // Idempotent: if the order already left `pending` (a webhook or a retry
381
+ // beat us), the capture result is returned without a second transition.
382
+ capturePaypalOrder: async function (paypalOrderId) {
383
+ if (!paypal) throw new TypeError("checkout.capturePaypalOrder: paypal adapter not wired");
384
+ if (typeof paypalOrderId !== "string" || !paypalOrderId.length) {
385
+ throw new TypeError("checkout.capturePaypalOrder: paypalOrderId required");
386
+ }
387
+ var o = await order.byPaymentIntent(paypalOrderId);
388
+ if (!o) return { handled: false, reason: "order-not-found", paypal_order_id: paypalOrderId };
389
+ // Guard on LOCAL status before calling PayPal: if a prior capture or a
390
+ // webhook already advanced the order, a second remote capture would be
391
+ // rejected by PayPal (orders capture once) — turning an idempotent retry
392
+ // into an exception. Treat already-advanced as a success no-op.
393
+ if (o.status !== "pending") {
394
+ return { handled: true, order: o, skipped: "already-advanced", paypal_order_id: paypalOrderId };
395
+ }
396
+ var cap = await paypal.captureOrder(paypalOrderId);
397
+ var captureId = null;
398
+ try { captureId = cap.purchase_units[0].payments.captures[0].id; } catch (_e) { captureId = null; }
399
+ var completed = cap && (cap.status === "COMPLETED" ||
400
+ (captureId && cap.purchase_units[0].payments.captures[0].status === "COMPLETED"));
401
+ if (completed && o.status === "pending") {
402
+ await order.transition(o.id, "mark_paid", {
403
+ reason: "paypal:capture",
404
+ metadata: { paypal_order_id: paypalOrderId, paypal_capture_id: captureId },
405
+ });
406
+ }
407
+ return { handled: !!completed, order: await order.get(o.id), capture_id: captureId, capture: cap };
408
+ },
409
+
410
+ // Verify a PayPal webhook (server-to-server, via the adapter) and apply
411
+ // the matching order transition. The capture flow above is primary; this
412
+ // catches captures completed/refunded out of band. { handled, ... }.
413
+ handlePaypalEvent: async function (input) {
414
+ if (!paypal) throw new TypeError("checkout.handlePaypalEvent: paypal adapter not wired");
415
+ if (!input || typeof input !== "object") throw new TypeError("checkout.handlePaypalEvent: input required");
416
+ if (typeof input.rawBody !== "string") throw new TypeError("checkout.handlePaypalEvent: rawBody (string) required");
417
+ var v = await paypal.verifyWebhook(input.headers || {}, input.rawBody, { webhookId: input.webhookId });
418
+ if (!v.ok) {
419
+ var err = new Error("checkout: paypal webhook verification failed — " + v.reason);
420
+ err.code = "WEBHOOK_INVALID";
421
+ err.reason = v.reason;
422
+ throw err;
423
+ }
424
+ var event = v.event || {};
425
+ var eventType = event.event_type;
426
+ if (!eventType || !Object.prototype.hasOwnProperty.call(PAYPAL_EVENT_MAP, eventType)) {
427
+ return { handled: false, event_type: eventType || null };
428
+ }
429
+ var fsmEvent = PAYPAL_EVENT_MAP[eventType];
430
+ if (!fsmEvent) return { handled: false, event_type: eventType, reason: "no-state-change" };
431
+ // The PayPal order id lives in the capture resource's related ids.
432
+ var ppOrderId = null;
433
+ try { ppOrderId = event.resource.supplementary_data.related_ids.order_id; } catch (_e) { ppOrderId = null; }
434
+ if (!ppOrderId) return { handled: false, event_type: eventType, reason: "no-order-id" };
435
+ var o = await order.byPaymentIntent(ppOrderId);
436
+ if (!o) return { handled: false, event_type: eventType, reason: "order-not-found" };
437
+ var alreadyAdvanced = (
438
+ (fsmEvent === "mark_paid" && o.status !== "pending") ||
439
+ (fsmEvent === "refund" && o.status === "refunded")
440
+ );
441
+ if (alreadyAdvanced) return { handled: true, event_type: eventType, order: o, skipped: "already-advanced" };
442
+ var updated = await order.transition(o.id, fsmEvent, {
443
+ reason: "paypal:" + eventType,
444
+ metadata: { paypal_event_id: event.id, paypal_order_id: ppOrderId },
445
+ });
446
+ return { handled: true, event_type: eventType, order: updated };
447
+ },
316
448
  };
317
449
  }
318
450
 
@@ -320,4 +452,5 @@ module.exports = {
320
452
  create: create,
321
453
  STRIPE_EVENT_MAP: STRIPE_EVENT_MAP,
322
454
  STRIPE_SUB_EVENT_TYPES: STRIPE_SUB_EVENT_TYPES,
455
+ PAYPAL_EVENT_MAP: PAYPAL_EVENT_MAP,
323
456
  };
package/lib/payment.js CHANGED
@@ -43,6 +43,10 @@ var IDEMPOTENT_OPERATIONS = {
43
43
  "subscription.create": true,
44
44
  "subscription.update": true,
45
45
  "subscription.cancel": true,
46
+ // PayPal adapter mutating operations (Orders v2).
47
+ "paypal_order.create": true,
48
+ "paypal_capture.create": true,
49
+ "paypal_refund.create": true,
46
50
  };
47
51
 
48
52
  // ---- validation -----------------------------------------------------------
@@ -502,17 +506,261 @@ function stripe(opts) {
502
506
  };
503
507
  }
504
508
 
505
- function create(opts) {
509
+ // ---- PayPal adapter -------------------------------------------------------
510
+ //
511
+ // PayPal Orders v2 over `b.httpClient`. Two structural differences from the
512
+ // Stripe adapter: (1) every call needs an OAuth2 client-credentials access
513
+ // token, exchanged up front and cached until it nears expiry; (2) webhook
514
+ // verification is a server-to-server call to PayPal's own
515
+ // verify-webhook-signature API — PayPal has no offline-HMAC shape like
516
+ // Stripe's. Outbound goes through `b.httpClient` (SSRF-gated, retried); the
517
+ // shared `_runIdempotent` cache applies when `query` is wired.
518
+ var PAYPAL_API_BASE_LIVE = "https://api-m.paypal.com";
519
+ var PAYPAL_API_BASE_SANDBOX = "https://api-m.sandbox.paypal.com";
520
+ var PAYPAL_HTTP_TIMEOUT_MS = 15000;
521
+ var PAYPAL_TOKEN_SKEW_MS = C.TIME.minutes(2); // refresh this far before expiry
522
+
523
+ // PayPal rejects decimal places for these currencies; everything else is
524
+ // 2-decimal. Amounts cross the wire as decimal strings in MAJOR units.
525
+ var PAYPAL_ZERO_DECIMAL = { HUF: true, JPY: true, TWD: true };
526
+
527
+ function _paypalApiBase(opts) {
528
+ if (opts.apiBase) return opts.apiBase.replace(/\/$/, "");
529
+ return opts.sandbox ? PAYPAL_API_BASE_SANDBOX : PAYPAL_API_BASE_LIVE;
530
+ }
531
+
532
+ function _minorToDecimalString(minor, currency) {
533
+ var dec = PAYPAL_ZERO_DECIMAL[currency] ? 0 : 2;
534
+ var neg = minor < 0;
535
+ var s = String(Math.abs(minor));
536
+ if (dec === 0) return (neg ? "-" : "") + s;
537
+ while (s.length <= dec) s = "0" + s;
538
+ return (neg ? "-" : "") + s.slice(0, s.length - dec) + "." + s.slice(s.length - dec);
539
+ }
540
+
541
+ function _headerCI(headers, name) {
542
+ if (!headers) return undefined;
543
+ if (headers[name] != null) return headers[name];
544
+ var lower = name.toLowerCase();
545
+ for (var k in headers) {
546
+ if (Object.prototype.hasOwnProperty.call(headers, k) && k.toLowerCase() === lower) return headers[k];
547
+ }
548
+ return undefined;
549
+ }
550
+
551
+ async function _paypalToken(opts, state) {
552
+ var now = state.now();
553
+ if (state.token && now < state.tokenExpiresAt) return state.token;
554
+ var httpClient = opts.httpClient || b.httpClient;
555
+ var basic = Buffer.from(opts.clientId + ":" + opts.secret).toString("base64");
556
+ var res = await httpClient.request({
557
+ method: "POST",
558
+ url: _paypalApiBase(opts) + "/v1/oauth2/token",
559
+ headers: {
560
+ "authorization": "Basic " + basic,
561
+ "accept": "application/json",
562
+ "content-type": "application/x-www-form-urlencoded",
563
+ "user-agent": "blamejs-shop (zero-dep)",
564
+ },
565
+ body: "grant_type=client_credentials",
566
+ timeoutMs: opts.timeoutMs || PAYPAL_HTTP_TIMEOUT_MS,
567
+ });
568
+ var text = res.body && res.body.toString ? res.body.toString("utf8") : "";
569
+ var json; try { json = text.length ? JSON.parse(text) : {}; } catch (_e) { json = {}; }
570
+ if (res.statusCode < 200 || res.statusCode >= 300 || !json.access_token) {
571
+ var err = new Error("paypal: OAuth2 token exchange failed → HTTP " + res.statusCode +
572
+ (json && json.error_description ? " — " + json.error_description : ""));
573
+ err.code = "PAYPAL_AUTH_" + res.statusCode;
574
+ err.statusCode = res.statusCode;
575
+ throw err;
576
+ }
577
+ state.token = json.access_token;
578
+ var ttlMs = (typeof json.expires_in === "number" ? json.expires_in : 0) * 1000; // allow:raw-time-literal — PayPal expires_in is a runtime seconds value; *1000 → ms
579
+ state.tokenExpiresAt = now + Math.max(0, ttlMs - PAYPAL_TOKEN_SKEW_MS);
580
+ return state.token;
581
+ }
582
+
583
+ async function _paypalCall(opts, state, method, path, bodyObj, requestId) {
584
+ var token = await _paypalToken(opts, state);
585
+ var headers = {
586
+ "authorization": "Bearer " + token,
587
+ "accept": "application/json",
588
+ "content-type": "application/json",
589
+ "user-agent": "blamejs-shop (zero-dep)",
590
+ };
591
+ if (requestId) headers["paypal-request-id"] = requestId;
592
+ var body = bodyObj != null ? JSON.stringify(bodyObj) : undefined;
593
+ if (body) headers["content-length"] = Buffer.byteLength(body, "utf8");
594
+ var httpClient = opts.httpClient || b.httpClient;
595
+ var res = await httpClient.request({
596
+ method: method,
597
+ url: _paypalApiBase(opts) + path,
598
+ headers: headers,
599
+ body: body,
600
+ timeoutMs: opts.timeoutMs || PAYPAL_HTTP_TIMEOUT_MS,
601
+ });
602
+ var text = res.body && res.body.toString ? res.body.toString("utf8") : "";
603
+ var json; try { json = text.length ? JSON.parse(text) : {}; } catch (_e) { json = { _raw: text }; }
604
+ if (res.statusCode < 200 || res.statusCode >= 300) {
605
+ var detail = json && (json.message || (json.details && json.details[0] && json.details[0].description)) || "";
606
+ var err = new Error("paypal: " + method + " " + path + " → HTTP " + res.statusCode + (detail ? " — " + detail : ""));
607
+ err.code = (json && json.name) || "PAYPAL_HTTP_" + res.statusCode;
608
+ err.statusCode = res.statusCode;
609
+ err.paypal = json || null;
610
+ throw err;
611
+ }
612
+ Object.defineProperty(json, "_paypalStatus", { value: res.statusCode, enumerable: false });
613
+ Object.defineProperty(json, "_paypalRawText", { value: text, enumerable: false });
614
+ return json;
615
+ }
616
+
617
+ function paypal(opts) {
506
618
  opts = opts || {};
507
- if (opts.adapter && opts.adapter !== "stripe") {
508
- throw new TypeError("payment.create: unknown adapter " + JSON.stringify(opts.adapter) + " — only 'stripe' is supported in v1");
619
+ _assertSecret(opts.clientId, "clientId");
620
+ _assertSecret(opts.secret, "secret");
621
+ if (opts.query != null && typeof opts.query !== "function") {
622
+ throw new TypeError("payment: query must be a function (sql, params) => Promise<{ rows }>");
623
+ }
624
+ if (opts.now != null && typeof opts.now !== "function") {
625
+ throw new TypeError("payment: now must be a function returning current epoch ms");
626
+ }
627
+ var state = {
628
+ query: opts.query || null,
629
+ now: typeof opts.now === "function" ? opts.now : function () { return Date.now(); },
630
+ token: null,
631
+ tokenExpiresAt: 0,
632
+ };
633
+
634
+ function _maybeIdempotent(operation, idempotencyKey, requestObj, doCall) {
635
+ if (!state.query || idempotencyKey == null) return doCall();
636
+ return _runIdempotent(state, operation, idempotencyKey, requestObj, doCall);
509
637
  }
510
- return stripe(opts);
638
+
639
+ function _amount(input, label) {
640
+ _positiveInt(input.amount_minor, "amount_minor");
641
+ if (typeof input.currency !== "string" || !/^[A-Z]{3}$/.test(input.currency)) {
642
+ throw new TypeError("payment." + label + ": currency must be a 3-letter uppercase ISO 4217 code");
643
+ }
644
+ return { currency_code: input.currency, value: _minorToDecimalString(input.amount_minor, input.currency) };
645
+ }
646
+
647
+ return {
648
+ name: "paypal",
649
+
650
+ // Create an Orders-v2 order (intent CAPTURE). The returned `id` is the
651
+ // PayPal order id the buyer approves; `captureOrder` finalizes it.
652
+ createOrder: function (input, idempotencyKey) {
653
+ if (!input || typeof input !== "object") throw new TypeError("payment.createOrder: input object required");
654
+ var bodyObj = {
655
+ intent: "CAPTURE",
656
+ purchase_units: [{
657
+ amount: _amount(input, "createOrder"),
658
+ custom_id: input.order_id || undefined,
659
+ invoice_id: input.invoice_id || undefined,
660
+ }],
661
+ };
662
+ if (input.return_url || input.cancel_url) {
663
+ bodyObj.payment_source = { paypal: { experience_context: {
664
+ return_url: input.return_url || undefined,
665
+ cancel_url: input.cancel_url || undefined,
666
+ } } };
667
+ }
668
+ var requestId = "order:" + (input.order_id || idempotencyKey || b.uuid.v7());
669
+ return _maybeIdempotent("paypal_order.create", idempotencyKey, { op: "createOrder", input: input }, function () {
670
+ return _paypalCall(opts, state, "POST", "/v2/checkout/orders", bodyObj, requestId);
671
+ });
672
+ },
673
+
674
+ // Capture an approved order. Returns the capture resource (the
675
+ // `purchase_units[0].payments.captures[0].id` is the capture id refunds
676
+ // reference).
677
+ captureOrder: function (orderId, idempotencyKey) {
678
+ if (typeof orderId !== "string" || !orderId.length) throw new TypeError("payment.captureOrder: orderId required");
679
+ var requestId = "capture:" + orderId + (idempotencyKey ? ":" + idempotencyKey : "");
680
+ return _maybeIdempotent("paypal_capture.create", idempotencyKey, { op: "captureOrder", orderId: orderId }, function () {
681
+ return _paypalCall(opts, state, "POST", "/v2/checkout/orders/" + encodeURIComponent(orderId) + "/capture", {}, requestId);
682
+ });
683
+ },
684
+
685
+ getOrder: function (orderId) {
686
+ if (typeof orderId !== "string" || !orderId.length) throw new TypeError("payment.getOrder: orderId required");
687
+ return _paypalCall(opts, state, "GET", "/v2/checkout/orders/" + encodeURIComponent(orderId), null, null);
688
+ },
689
+
690
+ // Refund a capture — full when no amount is given, partial with
691
+ // { amount_minor, currency }.
692
+ refund: function (input, idempotencyKey) {
693
+ if (!input || typeof input !== "object") throw new TypeError("payment.refund: input object required");
694
+ if (typeof input.capture_id !== "string" || !input.capture_id.length) {
695
+ throw new TypeError("payment.refund: capture_id required");
696
+ }
697
+ var bodyObj = {};
698
+ if (input.amount_minor != null) bodyObj.amount = _amount(input, "refund");
699
+ if (input.note_to_payer) bodyObj.note_to_payer = input.note_to_payer;
700
+ if (input.invoice_id) bodyObj.invoice_id = input.invoice_id;
701
+ // Multiple partial refunds on the SAME capture are legitimate + distinct,
702
+ // so the PayPal-Request-Id (PayPal's idempotency identity) must be unique
703
+ // per call by default — reusing `capture_id` alone would make PayPal
704
+ // replay the first refund instead of executing the next. A caller that
705
+ // wants a retry deduplicated passes an explicit idempotencyKey (or
706
+ // input.idempotency_suffix); otherwise a fresh uuid keeps each refund
707
+ // its own request. (createOrder / captureOrder stay stable on purpose —
708
+ // retrying those SHOULD be idempotent.)
709
+ var requestId = "refund:" + input.capture_id + ":" + (idempotencyKey || input.idempotency_suffix || b.uuid.v7());
710
+ return _maybeIdempotent("paypal_refund.create", idempotencyKey, { op: "refund", input: input }, function () {
711
+ return _paypalCall(opts, state, "POST",
712
+ "/v2/payments/captures/" + encodeURIComponent(input.capture_id) + "/refund", bodyObj, requestId);
713
+ });
714
+ },
715
+
716
+ // Verify an inbound webhook by calling PayPal's verify-webhook-signature
717
+ // API with the transmission headers + the configured webhook id + the
718
+ // event body. Returns { ok, event } on a SUCCESS verification status,
719
+ // { ok:false, reason } otherwise (drop-silent — never throws).
720
+ verifyWebhook: async function (headers, rawBody, vOpts) {
721
+ var webhookId = (vOpts && vOpts.webhookId) || opts.webhookId;
722
+ if (!webhookId) return { ok: false, reason: "no-webhook-id" };
723
+ var authAlgo = _headerCI(headers, "paypal-auth-algo");
724
+ var certUrl = _headerCI(headers, "paypal-cert-url");
725
+ var transmissionId = _headerCI(headers, "paypal-transmission-id");
726
+ var transmissionSig = _headerCI(headers, "paypal-transmission-sig");
727
+ var transmissionTime= _headerCI(headers, "paypal-transmission-time");
728
+ if (!authAlgo || !certUrl || !transmissionId || !transmissionSig || !transmissionTime) {
729
+ return { ok: false, reason: "missing-transmission-headers" };
730
+ }
731
+ var event;
732
+ try { event = typeof rawBody === "string" ? JSON.parse(rawBody) : rawBody; }
733
+ catch (_e) { return { ok: false, reason: "malformed-body" }; }
734
+ var verifyBody = {
735
+ auth_algo: authAlgo,
736
+ cert_url: certUrl,
737
+ transmission_id: transmissionId,
738
+ transmission_sig: transmissionSig,
739
+ transmission_time: transmissionTime,
740
+ webhook_id: webhookId,
741
+ webhook_event: event,
742
+ };
743
+ var res;
744
+ try { res = await _paypalCall(opts, state, "POST", "/v1/notifications/verify-webhook-signature", verifyBody, null); }
745
+ catch (e) { return { ok: false, reason: "verify-call-failed", error: e && e.message }; }
746
+ if (res && res.verification_status === "SUCCESS") return { ok: true, event: event };
747
+ return { ok: false, reason: "verification-status-" + ((res && res.verification_status) || "unknown") };
748
+ },
749
+ };
750
+ }
751
+
752
+ function create(opts) {
753
+ opts = opts || {};
754
+ var adapter = opts.adapter || "stripe";
755
+ if (adapter === "stripe") return stripe(opts);
756
+ if (adapter === "paypal") return paypal(opts);
757
+ throw new TypeError("payment.create: unknown adapter " + JSON.stringify(opts.adapter) + " — 'stripe' and 'paypal' are supported");
511
758
  }
512
759
 
513
760
  module.exports = {
514
761
  create: create,
515
762
  stripe: stripe,
763
+ paypal: paypal,
516
764
  STRIPE_WEBHOOK_TOLERANCE: STRIPE_WEBHOOK_TOLERANCE,
517
765
  IDEMPOTENCY_TTL_MS: IDEMPOTENCY_TTL_MS,
518
766
  // Exposed for tests + Worker to share form-encoding shape.
@@ -3,8 +3,8 @@
3
3
  "_about": "blamejs.shop vendors a single framework — blamejs — which itself bundles every server-side crypto/identity dependency. The transitive packages blamejs ships are surfaced in its own MANIFEST.json at lib/vendor/blamejs/lib/vendor/MANIFEST.json — Trivy / Grype rely on that nested data for CVE attribution.",
4
4
  "packages": {
5
5
  "blamejs": {
6
- "version": "0.12.53",
7
- "tag": "v0.12.53",
6
+ "version": "0.12.55",
7
+ "tag": "v0.12.55",
8
8
  "license": "Apache-2.0",
9
9
  "author": "blamejs contributors",
10
10
  "source": "https://github.com/blamejs/blamejs",
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.12.x
10
10
 
11
+ - v0.12.55 (2026-05-25) — **`b.structuredFields` — RFC 9651 Date and Display String types.** Brings the Structured Fields codec up to RFC 9651, which obsoletes RFC 8941 by adding two bare-item types. A Date (`@1659578233`) is an Integer number of seconds since the Unix epoch; a Display String (`%"f%c3%bc%c3%bc"`) is a Unicode string conveyed as percent-escaped UTF-8. parse returns them as distinct SfDate / SfDisplayString values, and serialize emits them canonically — a Date as `@` + integer, a Display String as `%"`-wrapped lowercase-percent-escaped UTF-8 that escapes only what RFC 9651 requires. Parsing is strict: a Date rejects a decimal / out-of-range value, and a Display String rejects uppercase escapes, raw non-ASCII, bad hex, and invalid UTF-8. Validated against the official httpwg structured-field-tests date and display-string vectors. **Added:** *RFC 9651 Date (`@…`) and Display String (`%"…"`) in `b.structuredFields`* — `parse` now reads the two RFC 9651 types: `@` + an Integer yields an `SfDate` (rejecting a decimal `@1.5`, an empty `@`, a sign-only `@-`, and out-of-range values), and `%"…"` yields an `SfDisplayString` (decoding lowercase `%XX` escapes as UTF-8, rejecting uppercase escapes, raw non-ASCII or control characters, malformed hex, and invalid UTF-8). `serialize` is the inverse — a Date as `@` + the integer, a Display String percent-escaping only non-printable / non-ASCII bytes plus `%` and `"`. The new `b.structuredFields.Date` and `b.structuredFields.DisplayString` wrappers construct these values. The module now tracks RFC 9651 (which obsoletes RFC 8941); the existing Item / List / Dictionary parsing is unchanged.
12
+
13
+ - v0.12.54 (2026-05-25) — **`b.structuredFields.parse` / `serialize` — full RFC 8941 Structured Fields codec.** The structured-fields module gains a complete RFC 8941 parser and serializer alongside its existing quote-aware helpers. b.structuredFields.parse reads an Item, List, or Dictionary into a typed value model — items are { value, params }, lists are arrays of items / inner lists, dictionaries are Maps — with Tokens and byte sequences returned as distinct SfToken / SfByteSequence instances. It enforces the grammar strictly: integer and decimal digit caps, printable-ASCII strings, canonical base64 byte sequences, valid token and key grammar, and no trailing characters. b.structuredFields.serialize is the exact inverse. This is the real parser the framework's Content-Digest, Client Hints, Web Push, and HTTP Message Signature surfaces can build on instead of open-coding each field. Validated against the official httpwg structured-field-tests conformance vectors. **Added:** *`b.structuredFields.parse(input, type, opts?)` / `serialize(value, type, opts?)` / `Token` / `ByteSequence`* — `parse` accepts `type` of `"item"`, `"list"`, or `"dictionary"` and returns the value model (items as `{ value, params }` with a `Map` of parameters; lists as arrays of items or inner lists; dictionaries as `Map`s). Bare items are JS numbers (Integer / Decimal), strings, booleans, `SfToken`, or `SfByteSequence`. Malformed input is rejected — out-of-range integers, over-long decimals, non-printable string bytes, non-canonical base64, invalid tokens / keys, and any trailing characters — and `opts.ErrorClass` yields a typed error. `serialize` is the inverse, rounding decimals to three fractional digits and refusing values outside the RFC's ranges or grammar. `b.structuredFields.Token` and `b.structuredFields.ByteSequence` wrap those bare-item types for serialization. The existing `splitTopLevel` / `refuseControlBytes` / `unquoteSfString` helpers are unchanged.
14
+
11
15
  - v0.12.53 (2026-05-25) — **`b.contentDigest` — HTTP Content-Digest / Repr-Digest fields (RFC 9530).** Emit and verify the Content-Digest / Repr-Digest HTTP fields so a recipient can detect a corrupted or tampered message body. b.contentDigest.create builds the RFC 8941 dictionary value (sha-256=:base64:, sha-512=:base64:) over a body; b.contentDigest.verify recomputes each modern digest over the body and compares it in constant time. Only SHA-256 and SHA-512 are computed — the legacy algorithms RFC 9530 §6 marks insecure (MD5, SHA-1, the unix checksums) are ignored on verify, and a field carrying no modern digest is refused, so an attacker cannot downgrade integrity to an MD5-only digest. Content-Digest is the integrity companion to HTTP Message Signatures (b.httpSig, RFC 9421): sign the digest rather than the whole body. Verified against the RFC 9530 Appendix D worked examples. **Added:** *`b.contentDigest.create(body, opts?)` / `b.contentDigest.verify(fieldValue, body, opts?)`* — `create` returns a Content-Digest / Repr-Digest field value over the body — SHA-256 by default, or any subset of `["sha-256","sha-512"]` via `opts.algorithms` — and refuses insecure or unknown algorithms. `verify` parses the field, recomputes each SHA-256 / SHA-512 entry over the body, and compares constant-time; it throws `content-digest/mismatch` on any mismatch, ignores legacy / unknown entries, throws `content-digest/no-modern-digest` if the field has no SHA-256 / SHA-512 entry at all, and honours `opts.required` to force specific algorithms to be present and match. Composes the framework's structured-field helpers and constant-time compare; Repr-Digest is the same machinery over the selected representation (RFC 9110).
12
16
 
13
17
  - v0.12.52 (2026-05-25) — **`b.privacyPass` — Privacy Pass origin-side token verification (RFC 9577 / 9578).** Anonymous, publicly verifiable authorization: an origin issues a WWW-Authenticate: PrivateToken challenge and verifies a presented token cryptographically, without learning who the client is and without a callback to the issuer. b.privacyPass implements the publicly verifiable token type 0x0002 (Blind RSA, 2048-bit): the token's authenticator is an RSA Blind Signature (RFC 9474) checked as RSASSA-PSS (SHA-384, 48-byte salt) over token_input = token_type ‖ nonce ‖ challenge_digest ‖ token_key_id, using only the issuer's public key. The token is bound to that key (token_key_id) and, optionally, to the challenge it answers, so a token minted for another origin is refused. Blind RSA is the algorithm Privacy Pass defines on the wire — like the DNSSEC / DANE verifiers it validates an external protocol's signatures rather than introducing classical crypto as a framework default. Verified against the RFC 9578 §8.2 test vector. **Added:** *`b.privacyPass.verifyToken(opts)` / `parseToken` / `buildChallenge`* — `buildChallenge` builds a TokenChallenge (RFC 9577 §2.1) and the matching `WWW-Authenticate: PrivateToken challenge=…, token-key=…` header an origin returns to request a token, scoped to an issuer (and optionally an origin and a 32-byte redemption context). `parseToken` splits a token into its fields (type / nonce / challenge_digest / token_key_id / authenticator). `verifyToken` verifies a type 0x0002 (Blind RSA) token: it confirms the token's `token_key_id` is the SHA-256 of the supplied issuer public key, optionally that its `challenge_digest` matches `opts.challenge`, and that the authenticator is a valid RSASSA-PSS signature over the token input. Refuses unknown / privately verifiable token types (the VOPRF type 0x0001 needs the issuer secret and is an issuer-side operation), key-id and challenge mismatches, and tampered authenticators. Marked experimental while the issuance protocols see deployment.
@@ -98,6 +98,7 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
98
98
  - **AAD-bound sealed columns** — AEAD tag tied to `(table, rowId, column, schemaVersion)`; copy-paste between rows or schema-version replay surfaces as refused decrypt (`b.vault.aad`)
99
99
  - **Signed webhooks + API encryption** — SLH-DSA-SHAKE-256f default; ML-DSA-65 opt-in; ECIES API encryption (`b.webhook`, `b.crypto`)
100
100
  - **HPKE / HTTP signatures** — RFC 9180 HPKE with ML-KEM-1024 + HKDF-SHA3-512 + ChaCha20-Poly1305 (`b.crypto.hpke`); RFC 9421 HTTP Message Signatures with derived components and ed25519 / ML-DSA-65 (`b.crypto.httpSig`); RFC 9530 Content-Digest / Repr-Digest body-integrity fields (SHA-256 / SHA-512, legacy algorithms refused — `b.contentDigest`) to sign the digest rather than the whole body
101
+ - **Structured Fields** — full RFC 9651 codec (`b.structuredFields.parse` / `serialize`): Items / Lists / Dictionaries, Inner Lists, Parameters, and every bare-item type (Integer / Decimal / String / Token / Byte Sequence / Boolean / Date / Display String) with strict grammar + range enforcement — the parser behind Content-Digest, Client Hints, and HTTP Message Signatures
101
102
  - **CMS codec** — RFC 5652 Cryptographic Message Syntax encoder + decoder with PQC signers (ML-DSA-65 / ML-DSA-87 / SLH-DSA-SHAKE-256f; RFC 9909 + 9881) and KEMRecipientInfo recipients (ML-KEM-1024; RFC 9629 + 9936); ChaCha20-Poly1305 content encryption (RFC 8103) so Efail-class malleability cannot apply (`b.cms`)
102
103
  - **Stream throttle** — shared token-bucket bandwidth limiter (RFC 2697 srTCM shape); N concurrent `node:stream` pipelines draw from one operator-configured `bytesPerSec` budget (`b.streamThrottle`)
103
104
  - **TLS-RPT receiver** — RFC 8460 inbound aggregate-report ingest; HTTPS POST handler + §4.4 schema parser with gzip-bomb / ratio-bomb / depth-bomb defenses (`b.mail.deploy.parseTlsRptReport` / `b.mail.deploy.tlsRptIngestHttp`)
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 1,
3
- "frameworkVersion": "0.12.53",
4
- "createdAt": "2026-05-25T17:13:42.241Z",
3
+ "frameworkVersion": "0.12.55",
4
+ "createdAt": "2026-05-25T19:45:48.985Z",
5
5
  "exports": {
6
6
  "a2a": {
7
7
  "type": "object",
@@ -48694,14 +48694,42 @@
48694
48694
  "structuredFields": {
48695
48695
  "type": "object",
48696
48696
  "members": {
48697
+ "ByteSequence": {
48698
+ "type": "function",
48699
+ "arity": 1
48700
+ },
48701
+ "Date": {
48702
+ "type": "function",
48703
+ "arity": 1
48704
+ },
48705
+ "Decimal": {
48706
+ "type": "function",
48707
+ "arity": 1
48708
+ },
48709
+ "DisplayString": {
48710
+ "type": "function",
48711
+ "arity": 1
48712
+ },
48713
+ "Token": {
48714
+ "type": "function",
48715
+ "arity": 1
48716
+ },
48697
48717
  "containsControlBytes": {
48698
48718
  "type": "function",
48699
48719
  "arity": 2
48700
48720
  },
48721
+ "parse": {
48722
+ "type": "function",
48723
+ "arity": 3
48724
+ },
48701
48725
  "refuseControlBytes": {
48702
48726
  "type": "function",
48703
48727
  "arity": 2
48704
48728
  },
48729
+ "serialize": {
48730
+ "type": "function",
48731
+ "arity": 3
48732
+ },
48705
48733
  "splitTopLevel": {
48706
48734
  "type": "function",
48707
48735
  "arity": 2