@blamejs/blamejs-shop 0.0.122 → 0.0.123

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,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.0.x
10
10
 
11
+ - v0.0.123 (2026-05-24) — **Wishlist — save products to your account, with social-proof counts on the product page.** Signed-in customers can now save products to a wishlist from the product page. A "N shoppers saved this" count surfaces social proof, and saved items live on a new account page where they can be removed or reopened. The save control and count render identically on the edge and container paths; the toggle is idempotent (saving twice is a no-op, toggling again removes) and login-gated, since a wishlist is scoped to one customer. **Added:** *Save to wishlist on the product page* — The PDP renders a "Save to wishlist" control and, once any customer has saved it, a "N shoppers saved this" social-proof count. Both render server-side on the edge and container paths. The count is public; the save action requires sign-in. · *`/account/wishlist` — saved items* — A new account page lists the customer's saved products with a thumbnail, a link back to the product, and a Remove control. Entries whose product was archived render as "no longer available" rather than breaking the list (wishlist rows are orphan-tolerant by design). The account dashboard links to it. · *`POST /wishlist/toggle`* — Login-required endpoint that saves the product if it isn't saved and removes it if it is. Idempotent (`INSERT OR IGNORE`). Redirects back to the product by resolving its canonical slug from the product id, or to a safe same-origin `return_to` (the account page's Remove uses it) — a forged or off-site redirect target is rejected.
12
+
11
13
  - v0.0.122 (2026-05-24) — **Product reviews on the storefront — verified-buyer submission, operator moderation, and rich-snippet ratings.** The product page now shows customer reviews: an average rating, a per-star distribution, and the published review list, with `AggregateRating` structured data so star ratings can surface in search results. Submission is gated to signed-in customers who have actually purchased the product — the route confirms a completed order for that product before accepting a review, and re-checks on submit. Reviews land in a pending state; operators publish or reject them through new bearer-token admin endpoints. Display and structured data are identical whether the page is served at the edge or from the container. **Added:** *Reviews on the product page* — The PDP renders an average rating, a per-star distribution bar chart, and the published reviews (newest first, verified-buyer badge, date). Products with no reviews show an invite to be the first. Rendered server-side on both the edge and container paths. · *Verified-buyer review submission* — `GET /products/:slug/review` shows the review form to a signed-in customer who has purchased the product; everyone else is redirected to sign in or told only verified buyers can review. `POST /products/:slug/review` re-checks the purchase before accepting the review, so a direct POST can't bypass the gate. Submitted reviews start pending. · *Operator review moderation* — `GET /admin/reviews?status=pending` lists the moderation queue across all products; `GET /admin/reviews/:id` reads one; `POST /admin/reviews/:id/publish` and `POST /admin/reviews/:id/reject` move it. Bearer-token-gated like the rest of the admin API. Pending and rejected reviews never appear on the storefront. · *`AggregateRating` structured data* — The product page emits Schema.org `AggregateRating` (rating value + review count) nested in the existing `Product` JSON-LD when published reviews exist, so eligible products can show star ratings in search results. Omitted entirely at zero reviews to stay valid. The container render path now emits the full `Product` + `AggregateOffer` + `BreadcrumbList` JSON-LD that the edge already did. · *`order.hasPurchasedProduct(customerId, productId)`* — Existence check — true when the customer has an order line for any variant of the product in an order that reached `paid` or later (excludes `pending` and `cancelled`). Backs the review purchase gate. · *`reviews.listByStatus(status, opts)`* — Lists reviews across all products by status, newest first, with the same opaque tuple cursor as `listForProduct`. Backs the admin moderation queue.
12
14
 
13
15
  - v0.0.121 (2026-05-24) — **Codebase-patterns detector blocks SHA3 primitives in `worker/` — prevents the regression that broke newsletter signup.** v0.0.120 fixed the newsletter signup by routing the POST to the container instead of computing `b.crypto.namespaceHash` (SHA3-512) at the edge — Workers' `nodejs_compat` doesn't expose SHA3-family digests. New `worker-uses-sha3-primitive` codebase-patterns detector flags any `b.crypto.{sha3Hash, hmacSha3, namespaceHash, shake256, shake512, hkdfSha3}(...)` call under `worker/` so the next operator can't re-introduce the substrate-mismatch bug. Catalog grows 121 → 122. Detector targets the exact SHA3-family primitive names rather than a general regex match — Worker code that legitimately uses `b.crypto.toBase64Url`, `b.crypto.timingSafeEqual`, `b.crypto.generateBytes`, `b.crypto.hmacSha256` (the Stripe webhook augment), etc. is unaffected. **Added:** *`worker-uses-sha3-primitive` detector* — Flags `b.crypto.sha3Hash(...)`, `hmacSha3(...)`, `namespaceHash(...)`, `shake256(...)`, `shake512(...)`, and `hkdfSha3(...)` in any file under `worker/`. Catches the substrate-mismatch class that broke v0.0.92's edge newsletter handler (live for 28 versions before being routed back to the container in v0.0.120). When edge code needs a stable hash: route to the container OR use `b.crypto.hmacSha256` IFF both sides read with the same SHA-256 path. Never have one substrate write SHA3 and another read SHA-256 — silent divergence breaks cross-substrate lookups (e.g. unsubscribe-by-email_hash).
package/README.md CHANGED
@@ -64,6 +64,7 @@ Every primitive is composed on the vendored blamejs surface — no npm runtime d
64
64
  | **`lib/storefront.js`** | Server-rendered HTML — utility bar + sticky header + dark hero with code-preview card + primitives marquee + featured-product callout + collections grid + framework feature band + designed catalog grid + newsletter band + four-column footer. Designed surfaces also for PDP, cart, checkout, pay, order, account login / register / dashboard, search results, `/admin` API landing, 404. Image-bearing cards on the home + search grids pull from `catalog.media`. The default theme stylesheet is external (R2-served `themes/default/assets/css/main.css`) and CSP-compliant — operators override by uploading a replacement at the same key, by passing `opts.theme_css` to renderers, or by registering a named theme through the `theme` primitive. |
65
65
  | **`lib/customers.js`** | Customer accounts — passkey-only (WebAuthn). Email is stored hash-only (`b.crypto.namespaceHash` namespace `customer-email`); the raw address never lands in D1. Passkey credentials carry CBOR-encoded public keys, transport hints, and SHA3-512-fingerprinted attestation. Account routes (`/account/login`, `/account/register`, `/account`) ship as designed cards on the storefront. |
66
66
  | **`lib/reviews.js`** | Operator-moderated product ratings. Submission requires a signed-in customer **and** a verified purchase — `/products/:slug/review` confirms a completed order for the product (via `order.hasPurchasedProduct`) before accepting, re-checked on POST; reviews land `pending`. Author identity is hash-only (`b.crypto.namespaceHash`); the raw email is never stored. The PDP renders the average, per-star distribution, and published reviews with `AggregateRating` JSON-LD. `/admin/reviews` is the moderation queue (`listByStatus` → publish / reject). |
67
+ | **`lib/wishlist.js`** | Per-customer saved products. The PDP renders a login-gated "Save to wishlist" toggle and a "N shoppers saved this" social-proof count; `/account/wishlist` lists saved items (remove + reopen, orphan-tolerant when a product is archived). `POST /wishlist/toggle` is idempotent (`INSERT OR IGNORE`) and redirects to the canonical product slug or a safe same-origin `return_to`. UUID-shape-validated ids, `b.pagination` HMAC cursors. |
67
68
  | **`lib/subscriptions.js`** | Stripe-backed recurring billing — `subscription_plans` (interval / amount / trial) + `subscriptions` (mirrors Stripe's object byte-for-byte). `subscriptions.create` POSTs to Stripe via the payment dep, then persists the returned object locally. `handleStripeEvent` replays `customer.subscription.*` events into the local row so the shop has an authoritative view without round-tripping. |
68
69
  | **`lib/newsletter.js`** | Operator-collected email broadcast list — `signup({ email, source })` composes `b.guardEmail` for shape validation, `b.crypto.namespaceHash` for the dedup key, and `INSERT OR IGNORE` for idempotency. Storefront POST `/newsletter` route renders a designed thank-you card with separate copy for the `new` vs `dedup` branches. |
69
70
  | **`lib/admin.js`** | Bearer-token-gated CRUD over catalog + orders + refunds + bulk CSV import + subscription plans + review moderation. Token compared via `b.crypto.timingSafeEqual`. Errors as RFC 9457 problem documents via `b.problemDetails`. Audit emission on every mutation. |
@@ -82,6 +83,7 @@ Every primitive is composed on the vendored blamejs surface — no npm runtime d
82
83
  - `migrations-d1/0009_subscriptions.sql` — subscription_plans + subscriptions (Stripe-mirrored)
83
84
  - `migrations-d1/0010_newsletter_signups.sql` — email signups with hash-based dedup
84
85
  - `migrations-d1/0011_reviews.sql` — operator-moderated product reviews (hash-only author identity)
86
+ - `migrations-d1/0012_wishlist.sql` — per-customer saved products (unique customer + product + variant)
85
87
 
86
88
  ### Demo seed
87
89
 
package/SECURITY.md CHANGED
@@ -92,8 +92,8 @@ node -e "
92
92
 
93
93
  | Purpose | Algorithm | Fingerprint |
94
94
  |-----------------------------------|------------|---------------------------|
95
- | Maintainer commit/tag signing key | SSH-ED25519 | *(populate on first signed tag — see below)* |
96
- | Release-signing public key | ML-DSA-65 (FIPS 204) | `0d9d241e23c333201911afd6d6d0b0ba9a2feb4f60bf5fdd976bb33e0678f7ff0ec3db816c3cb2d9caf50c681caf8b04939ffe8cf4652eae9e6c90c988bfb87e` (SHA3-512 of `keys/release-pqc-pub.json#publicKey`) |
95
+ | Maintainer commit/tag signing key | SSH-ED25519 | `SHA256:5oF/XWhFpMde9TRfEX2GAHiApAq/MXOS4vti5zQbD7g` (cross-check against `https://github.com/<maintainer>.keys` — see below) |
96
+ | Release-signing public key | ML-DSA-65 (FIPS 204) | `d40e1e2b06a2509271cc3cf76bd34c63d2fbb093f42e1e1f6b349288900ec044509ca183b3d735cda003d80eb6cf5d80fd9181ad897889e1c1f701d61b7902c9` (SHA3-512 of `keys/release-pqc-pub.json#publicKey`) |
97
97
 
98
98
  To populate the maintainer SSH fingerprint:
99
99
  ```
package/lib/storefront.js CHANGED
@@ -676,6 +676,7 @@ var PRODUCT_PAGE =
676
676
  " </table>\n" +
677
677
  " </div>\n" +
678
678
  " </div>\n" +
679
+ " RAW_WISHLIST_PLACEHOLDER\n" +
679
680
  " </div>\n" +
680
681
  " </div>\n" +
681
682
  " RAW_REVIEWS_PLACEHOLDER\n" +
@@ -900,6 +901,93 @@ function _reviewMessagePage(opts, heading, message, cta) {
900
901
  });
901
902
  }
902
903
 
904
+ // Remove control for a wishlist entry — a form POST back through the
905
+ // toggle route with `return_to` so the customer lands back on the
906
+ // account page (not the product PDP the default toggle returns to).
907
+ function _wishlistRemoveForm(productId, esc) {
908
+ return "<form class=\"wishlist-item__remove\" method=\"post\" action=\"/wishlist/toggle\">" +
909
+ "<input type=\"hidden\" name=\"product_id\" value=\"" + esc(productId) + "\">" +
910
+ "<input type=\"hidden\" name=\"return_to\" value=\"/account/wishlist\">" +
911
+ "<button type=\"submit\" class=\"btn-ghost btn-ghost--sm\">Remove</button>" +
912
+ "</form>";
913
+ }
914
+
915
+ // Account "Saved items" page. `opts.items` is a resolved list:
916
+ // { product, hero_media } for live products, or { product: null,
917
+ // product_id } for entries whose product was archived/deleted (the
918
+ // wishlist row is orphan-tolerant by design — render "unavailable",
919
+ // never crash the listing).
920
+ function renderWishlist(opts) {
921
+ var esc = _b().template.escapeHtml;
922
+ var items = opts.items || [];
923
+ var prefix = opts.asset_prefix || "/assets/";
924
+ var rowsHtml = "";
925
+ for (var i = 0; i < items.length; i += 1) {
926
+ var it = items[i];
927
+ if (!it.product) {
928
+ rowsHtml +=
929
+ "<li class=\"wishlist-item wishlist-item--gone\">" +
930
+ "<span class=\"wishlist-item__title\">This item is no longer available.</span>" +
931
+ _wishlistRemoveForm(it.product_id, esc) +
932
+ "</li>";
933
+ continue;
934
+ }
935
+ var slug = esc(it.product.slug);
936
+ var thumb = it.hero_media
937
+ ? "<img src=\"" + esc(prefix + it.hero_media.r2_key) + "\" alt=\"" + esc(it.hero_media.alt_text || it.product.title) + "\" loading=\"lazy\">"
938
+ : "<span class=\"wishlist-item__mark\" aria-hidden=\"true\">" + esc((it.product.title || "?").trim().charAt(0).toUpperCase() || "?") + "</span>";
939
+ rowsHtml +=
940
+ "<li class=\"wishlist-item\">" +
941
+ "<a class=\"wishlist-item__media\" href=\"/products/" + slug + "\">" + thumb + "</a>" +
942
+ "<div class=\"wishlist-item__body\">" +
943
+ "<a class=\"wishlist-item__title\" href=\"/products/" + slug + "\">" + esc(it.product.title) + "</a>" +
944
+ "<a class=\"wishlist-item__view card-link\" href=\"/products/" + slug + "\">View product →</a>" +
945
+ "</div>" +
946
+ _wishlistRemoveForm(it.product.id, esc) +
947
+ "</li>";
948
+ }
949
+ var inner = rowsHtml
950
+ ? "<ul class=\"wishlist-list\">" + rowsHtml + "</ul>"
951
+ : "<p class=\"wishlist-empty\">You haven't saved anything yet. Browse the shop and tap <strong>Save to wishlist</strong> on products you want to keep an eye on.</p>";
952
+ var body =
953
+ "<section class=\"account-wishlist\">" +
954
+ "<nav class=\"breadcrumb\" aria-label=\"Breadcrumb\"><ol>" +
955
+ "<li><a href=\"/account\">Account</a></li>" +
956
+ "<li aria-current=\"page\">Saved items</li>" +
957
+ "</ol></nav>" +
958
+ "<h1 class=\"account-wishlist__title\">Saved items</h1>" +
959
+ inner +
960
+ "</section>";
961
+ return _wrap({
962
+ title: "Saved items",
963
+ shop_name: opts.shop_name || "blamejs.shop",
964
+ cart_count: opts.cart_count == null ? 0 : opts.cart_count,
965
+ theme_css: opts.theme_css,
966
+ body: body,
967
+ });
968
+ }
969
+
970
+ // Product-level "Save to wishlist" control + social-proof count.
971
+ // Byte-compatible with the edge renderer (`worker/render/product.js`)
972
+ // so both paths emit identical markup. Action-only label — the toggle
973
+ // route resolves add/remove server-side against the sealed session.
974
+ function _buildWishlist(productId, count) {
975
+ var esc = _b().template.escapeHtml;
976
+ var n = Number(count) || 0;
977
+ var countHtml = n > 0
978
+ ? "<span class=\"wishlist__count\">" + n + (n === 1 ? " shopper saved this" : " shoppers saved this") + "</span>"
979
+ : "";
980
+ return "<div class=\"wishlist\">" +
981
+ "<form class=\"wishlist__form\" method=\"post\" action=\"/wishlist/toggle\">" +
982
+ "<input type=\"hidden\" name=\"product_id\" value=\"" + esc(productId) + "\">" +
983
+ "<button type=\"submit\" class=\"btn-secondary wishlist__btn\">" +
984
+ "<span class=\"wishlist__heart\" aria-hidden=\"true\">♡</span> Save to wishlist" +
985
+ "</button>" +
986
+ "</form>" +
987
+ countHtml +
988
+ "</div>";
989
+ }
990
+
903
991
  // Schema.org JSON-LD block. JSON.stringify covers the standard escapes;
904
992
  // the `</` → `<\/` rewrite neutralises any literal `</script>` in a
905
993
  // value. Mirrors the edge renderer's `jsonLdScript`.
@@ -933,6 +1021,7 @@ function renderProduct(opts) {
933
1021
  // theme's `{{{ reviews_html }}}` raw slot. The bundled themes
934
1022
  // include the slot; a custom theme opts in by adding it.
935
1023
  reviews_html: _buildReviews(opts.review_summary, opts.reviews, opts.review_cta),
1024
+ wishlist_html: _buildWishlist(opts.product.id, opts.wishlist_count),
936
1025
  asset_css_main: opts.theme.assetUrl("css/main.css"),
937
1026
  });
938
1027
  }
@@ -942,6 +1031,7 @@ function renderProduct(opts) {
942
1031
  if (!rows) rows = "<tr><td colspan=\"4\" class=\"empty\">No variants available.</td></tr>";
943
1032
  var galleryHtml = _buildPdpGallery(opts.product, opts.media || [], opts.asset_prefix || "/assets/");
944
1033
  var reviewsHtml = _buildReviews(opts.review_summary, opts.reviews, opts.review_cta);
1034
+ var wishlistHtml = _buildWishlist(opts.product.id, opts.wishlist_count);
945
1035
  var body = _render(PRODUCT_PAGE, {
946
1036
  title: opts.product.title,
947
1037
  description: description,
@@ -949,6 +1039,7 @@ function renderProduct(opts) {
949
1039
  })
950
1040
  .replace("RAW_GALLERY_PLACEHOLDER", galleryHtml)
951
1041
  .replace("RAW_ROWS_PLACEHOLDER", rows)
1042
+ .replace("RAW_WISHLIST_PLACEHOLDER", wishlistHtml)
952
1043
  .replace("RAW_REVIEWS_PLACEHOLDER", reviewsHtml);
953
1044
  // Product-specific OpenGraph + Twitter Card values so shares
954
1045
  // unfurl as "Operator Tee — blamejs.shop" with the SVG hero, not
@@ -1795,7 +1886,10 @@ var ACCOUNT_DASH_PAGE =
1795
1886
  " <h1 class=\"section-head__title\">Hi, {{display_name}}</h1>\n" +
1796
1887
  " <p class=\"section-head__lede\">Your orders + account controls. Every order ships from origin with a Stripe-secured receipt.</p>\n" +
1797
1888
  " </div>\n" +
1798
- " <form method=\"post\" action=\"/account/logout\"><button type=\"submit\" class=\"btn-ghost\">Sign out</button></form>\n" +
1889
+ " <div class=\"account-dash__actions\">\n" +
1890
+ " <a class=\"btn-secondary\" href=\"/account/wishlist\">Saved items</a>\n" +
1891
+ " <form method=\"post\" action=\"/account/logout\"><button type=\"submit\" class=\"btn-ghost\">Sign out</button></form>\n" +
1892
+ " </div>\n" +
1799
1893
  " </header>\n" +
1800
1894
  " <dl class=\"account-dash__stats\">\n" +
1801
1895
  " <div><dt>Orders</dt><dd>{{order_count}}</dd></div>\n" +
@@ -2061,6 +2155,13 @@ function mount(router, deps) {
2061
2155
  reviewCta = "<a class=\"btn-secondary reviews__cta\" href=\"/products/" +
2062
2156
  _b().template.escapeHtml(product.slug) + "/review\">Write a review</a>";
2063
2157
  }
2158
+ // Wishlist social-proof count — degrades to 0 on a read failure
2159
+ // (e.g. table not yet migrated) rather than 500-ing the PDP.
2160
+ var wishlistCount = 0;
2161
+ if (deps.wishlist) {
2162
+ try { wishlistCount = await deps.wishlist.countForProduct(product.id); }
2163
+ catch (_e) { wishlistCount = 0; }
2164
+ }
2064
2165
  var html = renderProduct({
2065
2166
  product: product,
2066
2167
  variants: variants,
@@ -2069,6 +2170,7 @@ function mount(router, deps) {
2069
2170
  review_summary: reviewSummary,
2070
2171
  reviews: reviewRows,
2071
2172
  review_cta: reviewCta,
2173
+ wishlist_count: wishlistCount,
2072
2174
  shop_name: shopName,
2073
2175
  cart_count: cartCount,
2074
2176
  theme: theme,
@@ -2607,6 +2709,82 @@ function mount(router, deps) {
2607
2709
  return res.end ? res.end() : res.send("");
2608
2710
  });
2609
2711
 
2712
+ // Wishlist — saved products scoped to the logged-in customer.
2713
+ // Mounts when the wishlist primitive is wired.
2714
+ if (deps.wishlist) {
2715
+ // POST /wishlist/toggle — add the product if not saved, remove it
2716
+ // if already saved. Login required (the wishlist is per-customer).
2717
+ // Redirects to `return_to` when it's a safe same-origin path
2718
+ // (the account page's Remove uses it), otherwise back to the
2719
+ // product PDP (the canonical slug is resolved from product_id, so
2720
+ // a forged slug can't drive an open redirect).
2721
+ router.post("/wishlist/toggle", async function (req, res) {
2722
+ var auth;
2723
+ try { auth = _currentCustomer(req); }
2724
+ catch (e) {
2725
+ if (e && e.code === "vault/not-initialized") return _serviceUnavailable(res, "auth not configured");
2726
+ throw e;
2727
+ }
2728
+ if (!auth) {
2729
+ res.status(303); res.setHeader && res.setHeader("location", "/account/login");
2730
+ return res.end ? res.end() : res.send("");
2731
+ }
2732
+ var productId = (req.body || {}).product_id;
2733
+ try {
2734
+ var already = await deps.wishlist.isWishlisted({ customer_id: auth.customer_id, product_id: productId });
2735
+ if (already) await deps.wishlist.remove({ customer_id: auth.customer_id, product_id: productId });
2736
+ else await deps.wishlist.add({ customer_id: auth.customer_id, product_id: productId });
2737
+ } catch (e) {
2738
+ res.status(e instanceof TypeError ? 400 : 500);
2739
+ return res.end ? res.end((e && e.message) || "Error") : res.send((e && e.message) || "Error");
2740
+ }
2741
+ var rt = (req.body || {}).return_to;
2742
+ var dest;
2743
+ if (typeof rt === "string" && /^\/[^/]/.test(rt)) {
2744
+ dest = rt;
2745
+ } else {
2746
+ var product = null;
2747
+ try { product = await deps.catalog.products.get(productId); } catch (_e) { product = null; }
2748
+ dest = product ? ("/products/" + encodeURIComponent(product.slug)) : "/account/wishlist";
2749
+ }
2750
+ res.status(303); res.setHeader && res.setHeader("location", dest);
2751
+ return res.end ? res.end() : res.send("");
2752
+ });
2753
+
2754
+ // GET /account/wishlist — the customer's saved items. Each entry
2755
+ // resolves its product + hero image; an entry whose product was
2756
+ // archived renders as "unavailable" (the row is orphan-tolerant).
2757
+ router.get("/account/wishlist", async function (req, res) {
2758
+ var auth;
2759
+ try { auth = _currentCustomer(req); }
2760
+ catch (e) {
2761
+ if (e && e.code === "vault/not-initialized") return _serviceUnavailable(res, "auth not configured");
2762
+ throw e;
2763
+ }
2764
+ if (!auth) {
2765
+ res.status(303); res.setHeader && res.setHeader("location", "/account/login");
2766
+ return res.end ? res.end() : res.send("");
2767
+ }
2768
+ var page = await deps.wishlist.listForCustomer(auth.customer_id, { limit: 50 });
2769
+ var items = [];
2770
+ for (var i = 0; i < page.rows.length; i += 1) {
2771
+ var entry = page.rows[i];
2772
+ var product = null;
2773
+ try { product = await deps.catalog.products.get(entry.product_id); } catch (_e) { product = null; }
2774
+ if (!product) { items.push({ product: null, product_id: entry.product_id }); continue; }
2775
+ var media = await deps.catalog.media.listForProduct(product.id);
2776
+ items.push({ product: product, hero_media: media.length ? media[0] : null });
2777
+ }
2778
+ var cartCount = await _cartCountForReq(req);
2779
+ _send(res, 200, renderWishlist({
2780
+ items: items,
2781
+ shop_name: shopName,
2782
+ cart_count: cartCount,
2783
+ asset_prefix: deps.asset_prefix || "/assets/",
2784
+ }));
2785
+ });
2786
+ }
2787
+
2610
2788
  // Product reviews — submission requires a logged-in customer AND a
2611
2789
  // verified purchase of the product (the gate, not just a badge).
2612
2790
  // Only mounts when both the reviews primitive and an order handle
@@ -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.28",
7
- "tag": "v0.12.28",
6
+ "version": "0.12.29",
7
+ "tag": "v0.12.29",
8
8
  "license": "Apache-2.0",
9
9
  "author": "blamejs contributors",
10
10
  "source": "https://github.com/blamejs/blamejs",
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.12.x
10
10
 
11
+ - v0.12.29 (2026-05-24) — **`b.ai.dp` — float-safe differential privacy: snapping-mechanism Laplace + discrete Gaussian + Rényi-DP budgets.** Differential privacy adds calibrated noise so an aggregate is provably insensitive to any single record — but the guarantee is fragile: Mironov (2012) showed that a Laplace mechanism sampled with naive double-precision floats lets an attacker distinguish neighbouring datasets with > 35% probability from a single output, silently destroying the promise. `b.ai.dp` ships only mechanisms whose sampling is hardened against that attack class: Laplace via the snapping mechanism (clamp + CSPRNG sign + full-mantissa uniform + power-of-two-grid rounding) and the discrete Gaussian (Canonne–Kamath–Steinke 2020) via integer-exact rejection sampling built from Bernoulli(exp(−γ)) over exact rationals — no floating-point noise at all. All randomness comes from `b.crypto.generateBytes` (SHAKE256 over the OS CSPRNG), never `Math.random`. `b.ai.dp.budget({ scope, epsilon, delta })` tracks a privacy budget per scope and refuses a `consume` that would exceed it, accounting composition either by basic summation (default) or a Rényi-DP accountant (Mironov 2017) for a much tighter bound under repeated Gaussian releases. NIST SP 800-226 (2025) is the evaluation standard; Dwork & Roth is the canonical reference. The exponential and sparse-vector mechanisms are deferred-with-condition — their float-safe constructions (base-2 / permute-and-flip; snapped SVT) re-open on operator demand, since shipping them float-unsafe would defeat the module's purpose. **Added:** *`b.ai.dp.mechanism({ type, sensitivity, epsilon, ... })` — float-safe noise mechanisms* — `type: "laplace"` is the snapping mechanism (pure ε-DP, real-valued, requires a clamp `bound` the guarantee depends on); `type: "gaussian"` is the discrete Gaussian (integer-valued, (ε, δ)-DP, requires `delta`). The Gaussian uses the classic calibration σ = √(2 ln(1.25/δ))·Δ/ε, proven for ε ≤ 1 — larger ε is refused with a pointer to splitting the release under an rdp budget. Descriptors are validated + frozen at construction so a malformed parameter fails fast. · *`b.ai.dp.budget({ scope, epsilon, delta, accounting })` — per-scope privacy budget* — Returns `{ consume, remaining, spent, reset }`. `consume(mechanism, value)` adds the mechanism's noise, charges the accountant, and throws `aiDp/budget-exhausted` if the release would push the scope past its (ε, δ). `accounting: "basic"` (default) sums per-release ε and δ; `accounting: "rdp"` runs a Rényi-DP accountant across a grid of orders and converts to (ε, δ) at the scope's δ for a tight composition bound under repeated Gaussian releases (requires `delta > 0`). The scope budget is enforced on both ε and δ independently. **Security:** *`b.crypto.generateBytes` uniformity fix at 1-byte length* — Node's SHAKE256 XOF is non-uniform at `outputLength: 1` — the byte values 0x00 and 0xff never occur and the low bit skews to ~0.54. `b.crypto.generateBytes(1)` (and the underlying `random(1)`) now draws at least 2 bytes and slices, so a single-byte CSPRNG request is uniform. Surfaced by `b.ai.dp` per-byte noise sampling; any per-byte consumer of `generateBytes` inherits the fix. A regression test asserts 0x00 / 0xff occur and the low bit is balanced.
12
+
11
13
  - v0.12.28 (2026-05-24) — **`b.ai.capability` — model-capability registry + cheapest-satisfying-model router.** `b.ai.capability.create({ models })` turns a fleet of AI model descriptors into a routing decision: given a set of requirements (context window, input/output modalities, tool use, structured output, reasoning tier, citation support, prompt-caching size), it picks the cheapest model that satisfies all of them. NIST AI RMF (AI 100-1) MAP 2.x requires documenting each model's capabilities and limitations; the Model Cards convention (Mitchell et al., 2019) formalizes that descriptor — this primitive makes the descriptor actionable. Routing to the cheapest sufficient model is a front-line defense against over-provisioning spend and composes directly with `b.ai.quota`'s `cost-usd` dimension (the chosen descriptor's rate feeds the budget charge); refusing to route a request to a model that cannot satisfy it (missing modality, too-small context window, no tool use) catches a capability mismatch before the inference call burns tokens on a guaranteed-bad result. Cost ranking uses a supplied `costBasis` (`{ inputTokens, outputTokens }`) for real per-call spend, else the sum of the per-1k rates; ties break by model id so the choice is deterministic across calls and nodes. **Added:** *`b.ai.capability.create({ models })` — capability registry + router* — Returns `{ describe, list, register, satisfies, route }`. A descriptor carries `maxContextTokens`, `maxOutputTokens`, `modalitiesIn` / `modalitiesOut` (arrays), `toolUse`, `structuredOutput`, `fineTunable`, `reasoningTier` (`none` / `basic` / `standard` / `advanced`, ordered), `citationSupport`, `promptCachingMaxTokens`, and the cost rates `costPer1kInputTokens` / `costPer1kOutputTokens`. Descriptors are validated + frozen at registration so a typo (negative cost, unknown reasoning tier, non-array modality list) surfaces at config time rather than as a silent mis-route. `describe(modelId)` returns the frozen descriptor; `register(modelId, descriptor)` adds or replaces one at runtime. · *`route({ requirements, fallback?, costBasis? })` — cheapest-satisfying selection* — Collects every model whose descriptor satisfies all requirements, then returns the cheapest (`{ modelId, descriptor, estimatedCost, reason }`). Requirements: `minContextTokens`, `minOutputTokens`, `modalitiesIn` / `modalitiesOut` (model must support every listed modality), `toolUse`, `structuredOutput`, `fineTunable`, `minReasoningTier` (tier ordering — `standard` is met by `standard` or `advanced`), `citationSupport`, `minPromptCachingTokens`. When no model matches, `fallback` (a registered model id) is returned with `reason: "fallback"`, or the call refuses with `aiCapability/no-candidate` if no fallback was supplied. Routing decisions emit `ai/capability-routed` / `ai/capability-fallback` / `ai/capability-no-candidate` through the drop-silent audit chain. · *`satisfies(modelId, requirements)` — precise capability-mismatch reasons* — Returns `{ ok, failures }` where each failure names the `requirement`, the `need`, and what the model `have`s — so a caller surfaces a precise reason (e.g. `minReasoningTier need advanced have basic`) instead of a bare boolean. Use it to explain a routing miss or to gate a request against a specific model before calling it.
12
14
 
13
15
  - v0.12.27 (2026-05-24) — **`b.ai.quota` — per-tenant, per-model AI usage budgets with atomic consume-and-check.** `b.ai.quota.create(opts)` builds an enforcer that caps AI inference usage per `(tenant, model, dimension, period)` and defends OWASP LLM Top 10 2025 LLM10 (Unbounded Consumption) — the class that includes denial-of-wallet, where an attacker drives a high volume of pay-per-use inferences until the bill itself is the attack. Meter by `tokens`, `requests`, `cost-usd`, or `compute-hours` over a calendar-aligned UTC window (`second` through `month`). `consume(tenant, model, amount)` is a single atomic check-and-charge: under the default `hard` enforcement it reserves the amount only if it fits under the ceiling, otherwise it refuses without charging — the limit test and the charge are one indivisible operation, so there is no charge-then-refund window for a concurrent call to observe. The in-memory counter is per-process; multi-node deployments supply an `opts.store` adapter whose `reserve` (an atomic conditional test-and-charge — a Redis Lua script, a SQL `UPDATE ... WHERE used + :amt <= :limit RETURNING used`) and `add` are atomic on the shared backend to enforce one aggregate ceiling across the cluster without false denials under contention. Limit resolution is most-specific-first: `perTenantModel` over `perTenant` over `perModel` over the default `limit`; tenant and model identifiers are percent-encoded into the counter key so a hostile tenant name cannot collide with another tenant's budget. **Added:** *`b.ai.quota.create(opts)` — per-tenant AI usage-budget enforcer* — Returns `{ consume, check, snapshot, reset }` scoped to one `dimension` (`tokens` / `requests` / `cost-usd` / `compute-hours`) and one `period` (`second` / `minute` / `hour` / `day` / `week` (Monday-aligned) / `month` (1st-of-month), all UTC-aligned). `consume(tenant, model, amount, opts?)` returns `{ used, limit, remaining, allowed, exceeded, windowStart, resetsAt, ... }`. `check(tenant, model)` is the read-only snapshot. Spin up one enforcer per dimension you meter — a monthly `cost-usd` budget and a per-minute `tokens` burst cap coexist as two `create()` calls sharing one store. Defends OWASP LLM10:2025 Unbounded Consumption / denial-of-wallet; maps to NIST AI RMF (AI 100-1) MANAGE 2.x and EU AI Act Art. 15 (robustness / resource-exhaustion resilience). · *`hard` / `soft` / `warn` enforcement* — `hard` (default) refuses the over-budget call and throws `aiQuota/exceeded` without charging — the rejected reservation is refunded so the counter is untouched. `soft` admits the charge but reports `allowed: false` so the caller decides whether to honor it. `warn` admits and allows (advisory), flagging `exceeded: true`. A per-call `consume(..., { enforcement })` override lets one endpoint soften the mode for a trusted internal caller without a second enforcer. Every over-budget event emits `ai/quota-exceeded` through the drop-silent audit chain (`ai/quota-applied` on success), tagged with the active cluster node id for attribution. · *Cross-node aggregate budgets via `opts.store`* — The default counter is in-memory (per-process). Supply `opts.store` exposing atomic `reserve` / `add` / `get` / `reset` (a Redis Lua script, a shared SQL row) and the ceiling is enforced on the cluster-wide aggregate. `hard` mode goes through `reserve`, an atomic conditional test-and-charge that adds the amount only if it fits — so a concurrent over-budget call cannot transiently inflate the counter and falsely deny a smaller call that should fit. Per-tenant and per-model limit overrides (`perTenant` / `perModel` / `perTenantModel`) are validated at config time so a malformed cap surfaces at boot, not as a silent fall-through to the default.
@@ -182,6 +182,7 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
182
182
  - **Audit + segregation** — 21 CFR Part 11 §11.10(e) audit-content gate + §11.50(b) electronicSignature (`b.fda21cfr11`); PCI DSS 4.0 Req 10.4.1.1 daily-review automation (`b.auditDailyReview`); SOX §404 + SOC 2 CC1.3 segregation-of-duties via Postgres trigger DDL (`b.audit.bindActor`, `b.audit.assertSegregation`)
183
183
  - **Change control + WORM** — m-of-n approver DDL change-control with maintenance-window + ML-DSA-87 signed proposals (`b.ddlChangeControl`); row-level WORM triggers boot-asserted under `sec-17a-4` / `finra-4511` / `fda-21cfr11` (`b.db.declareWorm`); dual-control physical delete + crypto-erase + REINDEX in one transaction (`b.db.declareRequireDualControl`, `b.db.eraseHard`)
184
184
  - **Consumer-protection** — FTC click-to-cancel UX-parity attestation (`ftc-2024` / `ca-sb942` / `strict`) (`b.darkPatterns`)
185
+ - **Differential privacy** — float-safe DP for aggregate releases: snapping-mechanism Laplace (Mironov 2012) + discrete Gaussian (Canonne–Kamath–Steinke 2020), CSPRNG noise, per-scope ε/δ budgets with basic + Rényi-DP accounting; defends the floating-point distinguishing attack that breaks naive Laplace samplers (NIST SP 800-226) (`b.ai.dp`)
185
186
  - **Privacy / DSR** — GDPR Articles 15–22 / CCPA / CPRA / LGPD / PIPEDA data-subject-rights workflow (`b.dsr`); IAB TCF v2.3 consent-string parser + `disclosedVendors` validator (`b.iabTcf`); IAB MSPA / GPP universal-opt-out (USNAT / USCA / USVA / USCO / USCT / USUT) + GPC mirror (`b.iabMspa`); generic consent capture + withdrawal (`b.consent`)
186
187
  - **Incident reporters** — EU DORA Article 17 ICT-incident workflow per Commission Delegated Regulation 2024/1772 (`b.dora`); EU NIS2 (`b.nis2`); EU Cyber Resilience Act SBOM + secure-software-attestation (`b.cra`); SEC Form 8-K Item 1.05 cybersecurity-incident materiality-disclosure (`b.secCyber`); incident lifecycle coordinator (`b.incident`)
187
188
  - **Outbound DLP** — interceptor-installed on httpClient + mail + webhook with built-in detectors for PAN (Luhn), SSN, EIN, IBAN (mod-97), api-key shapes, PEM, SSH private keys, JWTs, AWS access keys, PHI composite; refuse / redact / audit-only verdicts under pci-dss / hipaa / fapi2 / soc2 / gdpr presets (`b.redact.installOutboundDlp`)
@@ -342,6 +342,7 @@ This is the minimum-viable security posture for a production deployment. The fra
342
342
  - [ ] For OAuth / OIDC RP callbacks: call `b.auth.oauth.parseCallback(query, opts?)` BEFORE consuming `code` — validates RFC 9207 AS Issuer Identifier (refuses iss-mismatch + OP `error=` redirects + state-mismatch CSRF). For FAPI 2.0 deployments add `b.fapi2.assertCallback(query)` (refuses missing iss; refuses bare-param under `fapi-2.0-message-signing` posture, requiring JARM `response`) and `b.fapi2.assertAuthzRequest(authzParams)` BEFORE issuing the redirect (refuses non-JAR authorization requests). For refresh-token flows, pass `seen({ jti, iss })` to `b.auth.oauth.refreshAccessToken` so reuse of an already-rotated token refuses BEFORE the HTTP exchange (RFC 9700 §4.13 / OAuth 2.1 §6.1)
343
343
  - [ ] For Model Context Protocol servers exposing tools to LLM agents: wire `b.mcp.toolResult.sanitize(result, { posture: "refuse" })` over EVERY tool output before returning it to the model — defends OWASP LLM07 (sensitive tool output / prompt-injection echo back into the agent loop), refuses dangerous-HTML + off-allowlist URLs. Wrap each tool's input handler with `b.mcp.validateToolInput(toolName, input, schema)` (JSON Schema 2020-12 subset — `type` / `properties` / `required` / `enum` / `const` / length + range caps) so an LLM-supplied argument shape that doesn't match refuses BEFORE the tool runs. Define each tool's required scopes via `b.mcp.capability.create(scopes)` and gate execution on `cap.satisfiedBy(grantedScopes)` (LLM08 least-privilege)
344
344
  - [ ] For AI inference endpoints (especially pay-per-use provider models): wire `b.ai.quota.create({ dimension, period, limit, enforcement: "hard" })` and call `quota.consume(tenant, model, amount)` BEFORE every inference — caps tokens / requests / cost-usd / compute-hours per tenant per window so one tenant cannot run up an unbounded bill (OWASP LLM10:2025 unbounded consumption / denial-of-wallet). For multi-node deployments supply an `opts.store` whose `reserve` (atomic conditional test-and-charge) + `add` are atomic on the shared backend (Redis Lua / a SQL `UPDATE ... WHERE used + :amt <= :limit`) so the ceiling is enforced on the cluster-wide aggregate, not per-process
345
+ - [ ] For endpoints returning aggregate statistics over personal data (counts / sums / means / histograms): add calibrated noise with `b.ai.dp` and gate spend with `b.ai.dp.budget({ scope, epsilon, delta })` — use `type: "laplace"` (snapping mechanism) or `type: "gaussian"` (discrete Gaussian), NEVER a hand-rolled `Math.random`-based noise generator: a naive double-precision Laplace sampler lets an attacker distinguish neighbouring datasets from a single output (Mironov 2012), silently breaking the guarantee. Track the per-scope ε/δ budget so repeated queries can't be averaged to cancel the noise
345
346
  - [ ] For data with a TTL (GDPR Art. 17, PCI 3.1, retention windows): declare retention rules via `b.retention.create({ db, audit }).declare({ name, table, ageField, ttlMs, action: "erase" })` and run on a `b.scheduler` cadence; honour legal-hold via `legalHoldField`
346
347
  - [ ] For write-once-read-many object archives (SEC 17a-4, FINRA, HIPAA-shaped retention): create the bucket with `b.objectStore.bucketOps.create(name, { objectLockEnabled: true })` (Object Lock can ONLY be flipped at create time), apply a default retention via `setObjectLockConfiguration(name, { mode: "COMPLIANCE", years })`, and pin individual objects with `setObjectRetention(name, key, { mode, retainUntil })` or `setObjectLegalHold(name, key, "ON")` — `COMPLIANCE` cannot be shortened or bypassed by anyone (including root); pick deliberately
347
348
  - [ ] At boot, before any outbound socket opens: call `b.network.bootFromEnv({ env: process.env, audit: b.audit })` so operator-supplied NTP / DNS / proxy / DPI-trust / TCP socket settings (`BLAMEJS_NTP_*`, `BLAMEJS_DNS_*`, `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`, `BLAMEJS_EXTRA_CA_CERTS`, `BLAMEJS_SOCKET_*`) apply uniformly
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 1,
3
- "frameworkVersion": "0.12.28",
4
- "createdAt": "2026-05-24T15:47:42.211Z",
3
+ "frameworkVersion": "0.12.29",
4
+ "createdAt": "2026-05-24T17:07:11.597Z",
5
5
  "exports": {
6
6
  "a2a": {
7
7
  "type": "object",
@@ -1548,6 +1548,31 @@
1548
1548
  }
1549
1549
  }
1550
1550
  },
1551
+ "dp": {
1552
+ "type": "object",
1553
+ "members": {
1554
+ "ACCOUNTINGS": {
1555
+ "type": "instance",
1556
+ "ctorName": "Array"
1557
+ },
1558
+ "AiDpError": {
1559
+ "type": "function",
1560
+ "arity": 4
1561
+ },
1562
+ "MECHANISMS": {
1563
+ "type": "instance",
1564
+ "ctorName": "Array"
1565
+ },
1566
+ "budget": {
1567
+ "type": "function",
1568
+ "arity": 1
1569
+ },
1570
+ "mechanism": {
1571
+ "type": "function",
1572
+ "arity": 1
1573
+ }
1574
+ }
1575
+ },
1551
1576
  "input": {
1552
1577
  "type": "object",
1553
1578
  "members": {
@@ -445,6 +445,7 @@ module.exports = {
445
445
  disclosure: require("./lib/ai-disclosure"),
446
446
  quota: require("./lib/ai-quota"),
447
447
  capability: require("./lib/ai-capability"),
448
+ dp: require("./lib/ai-dp"),
448
449
  },
449
450
  promisePool: require("./lib/promise-pool"),
450
451
  sdNotify: require("./lib/sd-notify"),
@@ -0,0 +1,539 @@
1
+ "use strict";
2
+ /**
3
+ * @module b.ai.dp
4
+ * @nav Compliance
5
+ * @title Differential privacy
6
+ *
7
+ * @intro
8
+ * Float-safe differential-privacy mechanisms with per-scope privacy
9
+ * budgeting. Differential privacy adds calibrated noise to an
10
+ * aggregate so the output is provably insensitive to any single
11
+ * record — but the guarantee is fragile: Mironov (2012) showed that
12
+ * a Laplace mechanism implemented with naive double-precision
13
+ * sampling lets an attacker distinguish neighbouring datasets with
14
+ * &gt; 35% probability from a <em>single</em> output, silently
15
+ * destroying the promise. This module ships only mechanisms whose
16
+ * sampling is hardened against that class of attack:
17
+ *
18
+ * - <strong>Laplace via the snapping mechanism</strong> (Mironov
19
+ * 2012): clamp to a bound, draw a CSPRNG sign + full-mantissa
20
+ * uniform, then round to a power-of-two grid — the rounding
21
+ * removes the exploitable low-order mantissa bits. Pure
22
+ * ε-differential privacy.
23
+ * - <strong>Discrete Gaussian</strong> (Canonne–Kamath–Steinke
24
+ * 2020): integer-exact rejection sampling built from
25
+ * Bernoulli(exp(−γ)) over exact rationals — no floating-point
26
+ * noise at all. (ε, δ)-differential privacy, integer-valued.
27
+ *
28
+ * All randomness comes from <code>b.crypto.generateBytes</code>
29
+ * (SHAKE256 over the OS CSPRNG), never <code>Math.random</code>.
30
+ *
31
+ * <code>b.ai.dp.budget({ scope, epsilon, delta })</code> tracks a
32
+ * privacy budget per scope (per-user / per-tenant / per-query-class)
33
+ * and refuses a <code>consume</code> that would exceed it.
34
+ * Composition is accounted two ways:
35
+ *
36
+ * - <code>"basic"</code> (default) — sum the per-release ε and δ.
37
+ * Always valid; conservative.
38
+ * - <code>"rdp"</code> — a Rényi DP accountant (Mironov 2017) tracks
39
+ * RDP across a grid of orders and converts to (ε, δ) at the
40
+ * scope's δ, giving a much tighter bound under repeated Gaussian
41
+ * releases. Requires <code>delta &gt; 0</code>.
42
+ *
43
+ * NIST SP 800-226 (2025) is the evaluation standard for these
44
+ * guarantees; Dwork &amp; Roth, "The Algorithmic Foundations of
45
+ * Differential Privacy", is the canonical reference.
46
+ *
47
+ * The exponential and sparse-vector mechanisms are
48
+ * deferred-with-condition: their float-safe constructions (the
49
+ * base-2 / permute-and-flip exponential mechanism, Ilvento 2019; a
50
+ * snapped sparse-vector) are a distinct effort, and shipping them
51
+ * float-<em>unsafe</em> would defeat the module's purpose. They
52
+ * re-open on operator demand with the named construction.
53
+ *
54
+ * @card
55
+ * Float-safe differential privacy — snapping-mechanism Laplace
56
+ * (Mironov 2012) + discrete Gaussian (CKS20), CSPRNG noise, per-
57
+ * scope ε/δ budgets with basic + Rényi-DP accounting.
58
+ */
59
+
60
+ var bCrypto = require("./crypto");
61
+ var validateOpts = require("./validate-opts");
62
+ var lazyRequire = require("./lazy-require");
63
+ var { defineClass } = require("./framework-error");
64
+
65
+ var AiDpError = defineClass("AiDpError", { alwaysPermanent: true });
66
+
67
+ var audit = lazyRequire(function () { return require("./audit"); });
68
+
69
+ var MECHANISMS = ["laplace", "gaussian"];
70
+ var ACCOUNTINGS = ["basic", "rdp"];
71
+
72
+ // Rational approximation precision for a real-valued σ² fed to the
73
+ // integer-exact discrete-Gaussian sampler. 2^32 keeps the deviation
74
+ // from the target σ² below 2^-32 — far under the noise scale — while
75
+ // keeping the BigInt denominators bounded.
76
+ var SIGMA2_RATIONAL_DEN = 4294967296; // allow:raw-byte-literal — 2^32 rational-approx denominator, not a byte size
77
+
78
+ // ---- Minimal exact rational (BigInt num / den, den > 0) ----
79
+
80
+ function _gcd(a, b) {
81
+ a = a < 0n ? -a : a;
82
+ b = b < 0n ? -b : b;
83
+ while (b) { var t = a % b; a = b; b = t; }
84
+ return a;
85
+ }
86
+ function _fr(num, den) {
87
+ if (den < 0n) { num = -num; den = -den; }
88
+ var g = _gcd(num, den) || 1n;
89
+ return { num: num / g, den: den / g };
90
+ }
91
+ function _frFromFloat(x, den) {
92
+ // den is a Number power-of-two-ish denominator; round(x*den)/den.
93
+ return _fr(BigInt(Math.round(x * den)), BigInt(den));
94
+ }
95
+ function _frMul(a, b) { return _fr(a.num * b.num, a.den * b.den); }
96
+ function _frSub(a, b) { return _fr(a.num * b.den - b.num * a.den, a.den * b.den); }
97
+ function _frLte(a, b) { return a.num * b.den <= b.num * a.den; } // a <= b
98
+ function _frGt(a, b) { return a.num * b.den > b.num * a.den; } // a > b
99
+
100
+ // ---- CSPRNG primitives (all noise routes through b.crypto) ----
101
+
102
+ // Uniform BigInt in [0, m) via rejection sampling on CSPRNG bytes —
103
+ // no modulo bias.
104
+ function _uniformBelow(m) {
105
+ if (m <= 0n) throw new AiDpError("aiDp/internal", "ai.dp: _uniformBelow needs m > 0");
106
+ if (m === 1n) return 0n;
107
+ var bits = m.toString(2).length;
108
+ var bytes = Math.ceil(bits / 8); // allow:raw-byte-literal — bits-per-byte divisor, not a size
109
+ var mask = (1n << BigInt(bits)) - 1n;
110
+ for (;;) {
111
+ var buf = bCrypto.generateBytes(bytes);
112
+ var x = 0n;
113
+ for (var i = 0; i < bytes; i++) x = (x << 8n) | BigInt(buf[i]);
114
+ x = x & mask;
115
+ if (x < m) return x;
116
+ }
117
+ }
118
+
119
+ // Uniform double in (0, 1] with full 53-bit mantissa entropy — the
120
+ // snapping mechanism's noise source. A 53-bit integer is drawn via
121
+ // the BigInt rejection sampler (accumulating 53 bits in a JS Number
122
+ // would overflow the 2^53 safe-integer range and skew the draw), then
123
+ // mapped (val + 1) / 2^53 → (0, 1].
124
+ var TWO_POW_53 = 9007199254740992; // allow:raw-byte-literal — 2^53 mantissa range, not a byte size
125
+ function _uniformOpen() {
126
+ var v = Number(_uniformBelow(9007199254740992n)); // [0, 2^53) exact
127
+ return (v + 1) / TWO_POW_53; // (0, 1]
128
+ }
129
+
130
+ function _randomSign() {
131
+ return (bCrypto.generateBytes(1)[0] & 1) === 1 ? 1 : -1;
132
+ }
133
+
134
+ // ---- Canonne–Kamath–Steinke 2020 integer-exact samplers ----
135
+ // Ported verbatim from the reference implementation
136
+ // (github.com/IBM/discrete-gaussian-differential-privacy). All
137
+ // arithmetic is exact (BigInt rationals); no floating-point noise.
138
+
139
+ function _bernoulli(p) { // p rational in [0,1]
140
+ return _uniformBelow(p.den) < p.num ? 1 : 0;
141
+ }
142
+ function _bernoulliExp1(x) { // x rational in [0,1]
143
+ var k = 1n;
144
+ for (;;) {
145
+ if (_bernoulli(_fr(x.num, x.den * k)) === 1) k = k + 1n;
146
+ else break;
147
+ }
148
+ return Number(k % 2n);
149
+ }
150
+ function _bernoulliExp(x) { // x rational >= 0
151
+ while (_frGt(x, _fr(1n, 1n))) {
152
+ if (_bernoulliExp1(_fr(1n, 1n)) === 1) x = _frSub(x, _fr(1n, 1n));
153
+ else return 0;
154
+ }
155
+ return _bernoulliExp1(x);
156
+ }
157
+ function _geometricExpSlow(x) { // x rational >= 0
158
+ var k = 0n;
159
+ for (;;) {
160
+ if (_bernoulliExp(x) === 1) k = k + 1n;
161
+ else return k;
162
+ }
163
+ }
164
+ function _geometricExpFast(x) { // x rational > 0; returns BigInt
165
+ if (x.num === 0n) return 0n;
166
+ var t = x.den;
167
+ var u;
168
+ for (;;) {
169
+ u = _uniformBelow(t);
170
+ if (_bernoulliExp(_fr(u, t)) === 1) break;
171
+ }
172
+ var v = _geometricExpSlow(_fr(1n, 1n));
173
+ var value = v * t + u;
174
+ return value / x.num; // integer division
175
+ }
176
+ function _sampleDLaplace(scaleNum, scaleDen) { // Lap_Z(scale); returns BigInt
177
+ var invScale = _fr(scaleDen, scaleNum); // 1 / scale
178
+ for (;;) {
179
+ var sign = _bernoulli(_fr(1n, 2n));
180
+ var magnitude = _geometricExpFast(invScale);
181
+ if (sign === 1 && magnitude === 0n) continue;
182
+ return magnitude * BigInt(1 - 2 * sign);
183
+ }
184
+ }
185
+ function _floorSqrtFrac(fr) { // floor(sqrt(rational)); returns BigInt
186
+ var num = fr.num, den = fr.den;
187
+ var a = 0n, b = 1n;
188
+ while (b * b * den <= num) b = 2n * b;
189
+ while (a + 1n < b) {
190
+ var c = (a + b) / 2n;
191
+ if (c * c * den <= num) a = c; else b = c;
192
+ }
193
+ return a;
194
+ }
195
+ function _sampleDGauss(sigma2) { // sigma2 rational > 0; returns BigInt
196
+ var t = _floorSqrtFrac(sigma2) + 1n;
197
+ var two_sigma2 = _fr(2n * sigma2.num, sigma2.den); // 2 * sigma2
198
+ var sigma2_over_t = _fr(sigma2.num, sigma2.den * t); // sigma2 / t
199
+ for (;;) {
200
+ var candidate = _sampleDLaplace(t, 1n);
201
+ var absC = candidate < 0n ? -candidate : candidate;
202
+ var diff = _frSub(_fr(absC, 1n), sigma2_over_t); // |candidate| - sigma2/t
203
+ // bias = diff^2 / (2 sigma2) — multiply diff^2 by the reciprocal of 2σ².
204
+ var diff2 = _fr(diff.num * diff.num, diff.den * diff.den);
205
+ var bias = _frMul(diff2, _fr(two_sigma2.den, two_sigma2.num));
206
+ if (_bernoulliExp(bias) === 1) return candidate;
207
+ }
208
+ }
209
+
210
+ // ---- Snapping-mechanism Laplace (Mironov 2012), float-safe ----
211
+
212
+ function _clamp(x, bound) {
213
+ if (x < -bound) return -bound;
214
+ if (x > bound) return bound;
215
+ return x;
216
+ }
217
+ function _snappingLaplace(value, scale, bound) {
218
+ // scale = sensitivity / epsilon (Laplace b). bound B clamps the
219
+ // input + output; the privacy guarantee depends on it. Lambda is
220
+ // the smallest power of two >= scale, so inner / Lambda and
221
+ // Lambda * round(...) are exact float ops — that is what removes
222
+ // the attackable low-order bits the naive sampler leaks.
223
+ var xc = _clamp(value, bound);
224
+ var S = _randomSign();
225
+ var U = _uniformOpen(); // (0, 1]
226
+ var lambdaPow = Math.pow(2, Math.ceil(Math.log2(scale)));
227
+ var inner = xc + S * scale * Math.log(U);
228
+ var rounded = lambdaPow * Math.round(inner / lambdaPow);
229
+ return _clamp(rounded, bound);
230
+ }
231
+
232
+ // ---- Rényi-DP costs (Mironov 2017) ----
233
+
234
+ var RDP_ORDERS = [1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5, 6, 8, 12, 16, 24, 32, 48, 64, 128, 256]; // allow:raw-byte-literal — Rényi DP orders (α), not byte sizes
235
+
236
+ // Gaussian mechanism with noise-to-sensitivity z = sigma / sensitivity:
237
+ // RDP(alpha) = alpha / (2 z^2).
238
+ function _rdpGaussian(alpha, sigma, sensitivity) {
239
+ var z = sigma / sensitivity;
240
+ return alpha / (2 * z * z);
241
+ }
242
+ // Laplace mechanism with pure-DP parameter eps0 (= sensitivity / scale):
243
+ // RDP(alpha) = (1/(alpha-1)) * ln( (alpha/(2alpha-1)) e^{(alpha-1)eps0}
244
+ // + ((alpha-1)/(2alpha-1)) e^{-alpha eps0} ).
245
+ function _rdpLaplace(alpha, eps0) {
246
+ var a = alpha;
247
+ var num1 = a / (2 * a - 1);
248
+ var num2 = (a - 1) / (2 * a - 1);
249
+ var term = num1 * Math.exp((a - 1) * eps0) + num2 * Math.exp(-a * eps0);
250
+ return Math.log(term) / (a - 1);
251
+ }
252
+ // Convert an RDP curve (rdp[order]) to (eps, delta): the standard
253
+ // RDP -> DP bound eps(delta) = min_alpha ( rdp(alpha) + ln(1/delta)/(alpha-1) ).
254
+ function _rdpToEpsilon(rdpByOrder, delta) {
255
+ var best = Infinity;
256
+ for (var i = 0; i < RDP_ORDERS.length; i++) {
257
+ var a = RDP_ORDERS[i];
258
+ var e = rdpByOrder[i] + Math.log(1 / delta) / (a - 1);
259
+ if (e < best) best = e;
260
+ }
261
+ return best;
262
+ }
263
+
264
+ // ---- mechanism descriptor ----
265
+
266
+ /**
267
+ * @primitive b.ai.dp.mechanism
268
+ * @signature b.ai.dp.mechanism(opts)
269
+ * @since 0.12.29
270
+ * @status stable
271
+ * @compliance gdpr, soc2
272
+ * @related b.ai.dp.budget, b.ai.quota.create
273
+ *
274
+ * Build a float-safe DP noise mechanism. <code>type: "laplace"</code>
275
+ * is the snapping mechanism (pure ε-DP, real-valued, needs a
276
+ * <code>bound</code>); <code>type: "gaussian"</code> is the discrete
277
+ * Gaussian (integer-valued, (ε, δ)-DP, needs <code>delta</code>).
278
+ * Pass the result to <code>budget.consume(mechanism, value)</code>.
279
+ *
280
+ * @opts
281
+ * {
282
+ * type: string, // "laplace" | "gaussian"
283
+ * sensitivity: number, // required, > 0 (L1 for laplace, L1/integer for gaussian)
284
+ * epsilon: number, // required, > 0 (per-release ε; ε ≤ 1 for the
285
+ * // classic Gaussian calibration)
286
+ * delta?: number, // gaussian only, required, 0 < δ < 1
287
+ * bound?: number, // laplace only, required, > 0 — clamp bound B
288
+ * }
289
+ *
290
+ * @example
291
+ * var lap = b.ai.dp.mechanism({ type: "laplace", sensitivity: 1, epsilon: 0.5, bound: 1000 });
292
+ * var gss = b.ai.dp.mechanism({ type: "gaussian", sensitivity: 1, epsilon: 0.5, delta: 1e-6 });
293
+ */
294
+ function mechanism(opts) {
295
+ validateOpts.requireObject(opts, "ai.dp.mechanism", AiDpError);
296
+ validateOpts(opts, ["type", "sensitivity", "epsilon", "delta", "bound"], "ai.dp.mechanism");
297
+
298
+ if (MECHANISMS.indexOf(opts.type) === -1) {
299
+ throw new AiDpError("aiDp/bad-mechanism",
300
+ "ai.dp.mechanism: type must be one of " + MECHANISMS.join(" / ") +
301
+ " (exponential / sparse-vector are deferred — their float-safe constructions " +
302
+ "re-open on demand)");
303
+ }
304
+ if (typeof opts.sensitivity !== "number" || !isFinite(opts.sensitivity) || opts.sensitivity <= 0) {
305
+ throw new AiDpError("aiDp/bad-sensitivity",
306
+ "ai.dp.mechanism: sensitivity must be a positive finite number");
307
+ }
308
+ if (typeof opts.epsilon !== "number" || !isFinite(opts.epsilon) || opts.epsilon <= 0) {
309
+ throw new AiDpError("aiDp/bad-epsilon",
310
+ "ai.dp.mechanism: epsilon must be a positive finite number");
311
+ }
312
+
313
+ if (opts.type === "laplace") {
314
+ if (typeof opts.bound !== "number" || !isFinite(opts.bound) || opts.bound <= 0) {
315
+ throw new AiDpError("aiDp/bad-bound",
316
+ "ai.dp.mechanism: laplace requires bound > 0 (the snapping clamp; the " +
317
+ "privacy guarantee depends on it)");
318
+ }
319
+ var scale = opts.sensitivity / opts.epsilon;
320
+ return Object.freeze({
321
+ type: "laplace", sensitivity: opts.sensitivity, epsilon: opts.epsilon,
322
+ delta: 0, scale: scale, bound: opts.bound,
323
+ });
324
+ }
325
+
326
+ // gaussian
327
+ if (typeof opts.delta !== "number" || !isFinite(opts.delta) || opts.delta <= 0 || opts.delta >= 1) {
328
+ throw new AiDpError("aiDp/bad-delta",
329
+ "ai.dp.mechanism: gaussian requires 0 < delta < 1");
330
+ }
331
+ if (opts.epsilon > 1) {
332
+ throw new AiDpError("aiDp/epsilon-too-large",
333
+ "ai.dp.mechanism: the classic Gaussian calibration is proven for epsilon <= 1; " +
334
+ "split into multiple releases under an rdp budget, or the analytic Gaussian " +
335
+ "mechanism (Balle-Wang 2018) re-opens this path on demand");
336
+ }
337
+ // Classic Gaussian calibration (Dwork & Roth Thm 3.22), valid for ε ≤ 1.
338
+ var sigma = Math.sqrt(2 * Math.log(1.25 / opts.delta)) * opts.sensitivity / opts.epsilon;
339
+ return Object.freeze({
340
+ type: "gaussian", sensitivity: opts.sensitivity, epsilon: opts.epsilon,
341
+ delta: opts.delta, sigma: sigma, sigma2: sigma * sigma,
342
+ });
343
+ }
344
+
345
+ // Apply a mechanism's noise to a numeric value (no accounting — the
346
+ // budget wraps this).
347
+ function _applyMechanism(m, value) {
348
+ if (typeof value !== "number" || !isFinite(value)) {
349
+ throw new AiDpError("aiDp/bad-value", "ai.dp: value must be a finite number");
350
+ }
351
+ if (m.type === "laplace") {
352
+ return _snappingLaplace(value, m.scale, m.bound);
353
+ }
354
+ // gaussian — discrete, integer noise added to the (rounded) value.
355
+ var sigma2Frac = _frFromFloat(m.sigma2, SIGMA2_RATIONAL_DEN);
356
+ var noise = _sampleDGauss(sigma2Frac);
357
+ return Math.round(value) + Number(noise);
358
+ }
359
+
360
+ function _mechRdp(m, orderIndex) {
361
+ var alpha = RDP_ORDERS[orderIndex];
362
+ if (m.type === "gaussian") return _rdpGaussian(alpha, m.sigma, m.sensitivity);
363
+ return _rdpLaplace(alpha, m.epsilon);
364
+ }
365
+
366
+ // ---- per-scope budget ----
367
+
368
+ /**
369
+ * @primitive b.ai.dp.budget
370
+ * @signature b.ai.dp.budget(opts)
371
+ * @since 0.12.29
372
+ * @status stable
373
+ * @compliance gdpr, soc2
374
+ * @related b.ai.dp.mechanism, b.ai.quota.create
375
+ *
376
+ * Track a differential-privacy budget for one scope (per-user /
377
+ * per-tenant / per-query-class) and refuse a release that would
378
+ * exceed it. Returns <code>{ consume, remaining, spent, reset }</code>.
379
+ * <code>consume(mechanism, value)</code> adds the mechanism's noise,
380
+ * charges the accountant, and throws <code>aiDp/budget-exhausted</code>
381
+ * if the release would push the scope past its (ε, δ). With
382
+ * <code>accounting: "rdp"</code> the charge is accounted via Rényi DP
383
+ * for a tight composition bound (requires <code>delta &gt; 0</code>);
384
+ * <code>"basic"</code> (default) sums per-release ε and δ.
385
+ *
386
+ * @opts
387
+ * {
388
+ * scope: string, // required, the budget scope id
389
+ * epsilon: number, // required, total ε budget (> 0)
390
+ * delta?: number, // total δ budget (>= 0; required > 0 for rdp / gaussian)
391
+ * accounting?: string, // "basic" (default) | "rdp"
392
+ * audit?: boolean, // default: true
393
+ * }
394
+ *
395
+ * @example
396
+ * var b1 = b.ai.dp.budget({ scope: "tenant-acme:daily", epsilon: 3, delta: 1e-6, accounting: "rdp" });
397
+ * var m = b.ai.dp.mechanism({ type: "gaussian", sensitivity: 1, epsilon: 0.5, delta: 1e-6 });
398
+ * var out = b1.consume(m, trueCount);
399
+ * // → { value: <noised>, cost: { epsilon: 0.5, delta: 1e-6 }, remaining: { epsilon, delta } }
400
+ */
401
+ function budget(opts) {
402
+ validateOpts.requireObject(opts, "ai.dp.budget", AiDpError);
403
+ validateOpts(opts, ["scope", "epsilon", "delta", "accounting", "audit"], "ai.dp.budget");
404
+
405
+ validateOpts.requireNonEmptyString(opts.scope,
406
+ "ai.dp.budget: scope", AiDpError, "aiDp/bad-scope");
407
+ if (typeof opts.epsilon !== "number" || !isFinite(opts.epsilon) || opts.epsilon <= 0) {
408
+ throw new AiDpError("aiDp/bad-epsilon", "ai.dp.budget: epsilon must be a positive finite number");
409
+ }
410
+ var totalEpsilon = opts.epsilon;
411
+ var totalDelta = (opts.delta == null) ? 0 : opts.delta;
412
+ if (typeof totalDelta !== "number" || !isFinite(totalDelta) || totalDelta < 0 || totalDelta >= 1) {
413
+ throw new AiDpError("aiDp/bad-delta", "ai.dp.budget: delta must be in [0, 1)");
414
+ }
415
+ var accounting = (opts.accounting == null) ? "basic" : opts.accounting;
416
+ if (ACCOUNTINGS.indexOf(accounting) === -1) {
417
+ throw new AiDpError("aiDp/bad-accounting",
418
+ "ai.dp.budget: accounting must be one of " + ACCOUNTINGS.join(" / "));
419
+ }
420
+ if (accounting === "rdp" && totalDelta <= 0) {
421
+ throw new AiDpError("aiDp/bad-accounting",
422
+ "ai.dp.budget: rdp accounting requires delta > 0 (the RDP→(ε,δ) conversion is " +
423
+ "undefined at delta = 0; use basic accounting for pure-ε budgets)");
424
+ }
425
+ var auditOn = opts.audit !== false;
426
+
427
+ var scope = opts.scope;
428
+ var spentEpsilon = 0; // basic accounting
429
+ var spentDelta = 0;
430
+ var rdp = RDP_ORDERS.map(function () { return 0; }); // rdp accounting
431
+
432
+ function _emitAudit(action, outcome, metadata) {
433
+ if (!auditOn) return;
434
+ try { audit().safeEmit({ action: action, outcome: outcome, metadata: metadata || {} }); }
435
+ catch (_e) { /* drop-silent */ }
436
+ }
437
+
438
+ function _currentEpsilon(rdpCurve) {
439
+ if (accounting === "basic") return spentEpsilon;
440
+ return _rdpToEpsilon(rdpCurve, totalDelta);
441
+ }
442
+
443
+ function remaining() {
444
+ if (accounting === "basic") {
445
+ return {
446
+ epsilon: Math.max(0, totalEpsilon - spentEpsilon),
447
+ delta: Math.max(0, totalDelta - spentDelta),
448
+ };
449
+ }
450
+ return { epsilon: Math.max(0, totalEpsilon - _rdpToEpsilon(rdp, totalDelta)), delta: totalDelta };
451
+ }
452
+
453
+ function spent() {
454
+ if (accounting === "basic") return { epsilon: spentEpsilon, delta: spentDelta };
455
+ return { epsilon: _rdpToEpsilon(rdp, totalDelta), delta: totalDelta };
456
+ }
457
+
458
+ function consume(m, value) {
459
+ if (!m || typeof m !== "object" || MECHANISMS.indexOf(m.type) === -1) {
460
+ throw new AiDpError("aiDp/bad-mechanism",
461
+ "ai.dp.budget.consume: first argument must be a b.ai.dp.mechanism");
462
+ }
463
+ if (m.type === "gaussian" && totalDelta <= 0) {
464
+ throw new AiDpError("aiDp/bad-delta",
465
+ "ai.dp.budget.consume: a gaussian mechanism needs a scope delta > 0");
466
+ }
467
+
468
+ // Prospective accounting: would this release fit under the budget?
469
+ var cost;
470
+ if (accounting === "basic") {
471
+ if (spentEpsilon + m.epsilon > totalEpsilon + 1e-12 ||
472
+ spentDelta + m.delta > totalDelta + 1e-12) {
473
+ _emitAudit("dp/budget-exhausted", "denied", {
474
+ scope: scope, accounting: accounting, mechanism: m.type,
475
+ requestEpsilon: m.epsilon, requestDelta: m.delta,
476
+ spentEpsilon: spentEpsilon, totalEpsilon: totalEpsilon,
477
+ });
478
+ throw new AiDpError("aiDp/budget-exhausted",
479
+ "ai.dp.budget.consume: scope '" + scope + "' would spend ε=" +
480
+ (spentEpsilon + m.epsilon) + "/" + totalEpsilon + ", δ=" +
481
+ (spentDelta + m.delta) + "/" + totalDelta + "; refused");
482
+ }
483
+ cost = { epsilon: m.epsilon, delta: m.delta };
484
+ } else {
485
+ var trial = rdp.map(function (r, i) { return r + _mechRdp(m, i); });
486
+ var trialEps = _rdpToEpsilon(trial, totalDelta);
487
+ if (trialEps > totalEpsilon + 1e-12) {
488
+ _emitAudit("dp/budget-exhausted", "denied", {
489
+ scope: scope, accounting: accounting, mechanism: m.type,
490
+ projectedEpsilon: trialEps, totalEpsilon: totalEpsilon,
491
+ });
492
+ throw new AiDpError("aiDp/budget-exhausted",
493
+ "ai.dp.budget.consume: scope '" + scope + "' would reach ε=" +
494
+ trialEps.toFixed(4) + " of " + totalEpsilon + " at δ=" + totalDelta + "; refused");
495
+ }
496
+ var before = _rdpToEpsilon(rdp, totalDelta);
497
+ cost = { epsilon: trialEps - before, delta: 0 };
498
+ }
499
+
500
+ // Charge, then sample. (Sampling never fails; charging first keeps
501
+ // the budget monotone even if a caller ignores the throw path.)
502
+ var noised = _applyMechanism(m, value);
503
+ if (accounting === "basic") {
504
+ spentEpsilon += m.epsilon;
505
+ spentDelta += m.delta;
506
+ } else {
507
+ rdp = rdp.map(function (r, i) { return r + _mechRdp(m, i); });
508
+ }
509
+
510
+ _emitAudit("dp/budget-consumed", "allowed", {
511
+ scope: scope, accounting: accounting, mechanism: m.type,
512
+ epsilon: m.epsilon, delta: m.delta,
513
+ });
514
+ return { value: noised, cost: cost, remaining: remaining() };
515
+ }
516
+
517
+ function reset() {
518
+ spentEpsilon = 0;
519
+ spentDelta = 0;
520
+ rdp = RDP_ORDERS.map(function () { return 0; });
521
+ }
522
+
523
+ return {
524
+ consume: consume,
525
+ remaining: remaining,
526
+ spent: spent,
527
+ reset: reset,
528
+ scope: scope,
529
+ accounting: accounting,
530
+ };
531
+ }
532
+
533
+ module.exports = {
534
+ mechanism: mechanism,
535
+ budget: budget,
536
+ MECHANISMS: MECHANISMS,
537
+ ACCOUNTINGS: ACCOUNTINGS,
538
+ AiDpError: AiDpError,
539
+ };
@@ -387,9 +387,16 @@ function random(byteLength) {
387
387
  // when callers requested more. SHAKE256 is also already the
388
388
  // framework's KDF / browser-side derivation primitive, so the same
389
389
  // hash family does double duty.
390
- return nodeCrypto.createHash("shake256", { outputLength: n })
391
- .update(nodeCrypto.randomBytes(n))
390
+ //
391
+ // Node's SHAKE256 XOF is non-uniform at outputLength 1 (the byte
392
+ // values 0x00 and 0xff never occur and the low bit skews to ~0.54);
393
+ // outputLength >= 2 is uniform. Draw at least 2 bytes and slice so a
394
+ // 1-byte request still returns a uniform byte.
395
+ var drawN = n < 2 ? 2 : n;
396
+ var out = nodeCrypto.createHash("shake256", { outputLength: drawN })
397
+ .update(nodeCrypto.randomBytes(drawN))
392
398
  .digest();
399
+ return drawN === n ? out : out.subarray(0, n);
393
400
  }
394
401
 
395
402
  /**
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.12.28",
3
+ "version": "0.12.29",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
@@ -0,0 +1,31 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.12.29",
4
+ "date": "2026-05-24",
5
+ "headline": "`b.ai.dp` — float-safe differential privacy: snapping-mechanism Laplace + discrete Gaussian + Rényi-DP budgets",
6
+ "summary": "Differential privacy adds calibrated noise so an aggregate is provably insensitive to any single record — but the guarantee is fragile: Mironov (2012) showed that a Laplace mechanism sampled with naive double-precision floats lets an attacker distinguish neighbouring datasets with > 35% probability from a single output, silently destroying the promise. `b.ai.dp` ships only mechanisms whose sampling is hardened against that attack class: Laplace via the snapping mechanism (clamp + CSPRNG sign + full-mantissa uniform + power-of-two-grid rounding) and the discrete Gaussian (Canonne–Kamath–Steinke 2020) via integer-exact rejection sampling built from Bernoulli(exp(−γ)) over exact rationals — no floating-point noise at all. All randomness comes from `b.crypto.generateBytes` (SHAKE256 over the OS CSPRNG), never `Math.random`. `b.ai.dp.budget({ scope, epsilon, delta })` tracks a privacy budget per scope and refuses a `consume` that would exceed it, accounting composition either by basic summation (default) or a Rényi-DP accountant (Mironov 2017) for a much tighter bound under repeated Gaussian releases. NIST SP 800-226 (2025) is the evaluation standard; Dwork & Roth is the canonical reference. The exponential and sparse-vector mechanisms are deferred-with-condition — their float-safe constructions (base-2 / permute-and-flip; snapped SVT) re-open on operator demand, since shipping them float-unsafe would defeat the module's purpose.",
7
+ "sections": [
8
+ {
9
+ "heading": "Added",
10
+ "items": [
11
+ {
12
+ "title": "`b.ai.dp.mechanism({ type, sensitivity, epsilon, ... })` — float-safe noise mechanisms",
13
+ "body": "`type: \"laplace\"` is the snapping mechanism (pure ε-DP, real-valued, requires a clamp `bound` the guarantee depends on); `type: \"gaussian\"` is the discrete Gaussian (integer-valued, (ε, δ)-DP, requires `delta`). The Gaussian uses the classic calibration σ = √(2 ln(1.25/δ))·Δ/ε, proven for ε ≤ 1 — larger ε is refused with a pointer to splitting the release under an rdp budget. Descriptors are validated + frozen at construction so a malformed parameter fails fast."
14
+ },
15
+ {
16
+ "title": "`b.ai.dp.budget({ scope, epsilon, delta, accounting })` — per-scope privacy budget",
17
+ "body": "Returns `{ consume, remaining, spent, reset }`. `consume(mechanism, value)` adds the mechanism's noise, charges the accountant, and throws `aiDp/budget-exhausted` if the release would push the scope past its (ε, δ). `accounting: \"basic\"` (default) sums per-release ε and δ; `accounting: \"rdp\"` runs a Rényi-DP accountant across a grid of orders and converts to (ε, δ) at the scope's δ for a tight composition bound under repeated Gaussian releases (requires `delta > 0`). The scope budget is enforced on both ε and δ independently."
18
+ }
19
+ ]
20
+ },
21
+ {
22
+ "heading": "Security",
23
+ "items": [
24
+ {
25
+ "title": "`b.crypto.generateBytes` uniformity fix at 1-byte length",
26
+ "body": "Node's SHAKE256 XOF is non-uniform at `outputLength: 1` — the byte values 0x00 and 0xff never occur and the low bit skews to ~0.54. `b.crypto.generateBytes(1)` (and the underlying `random(1)`) now draws at least 2 bytes and slices, so a single-byte CSPRNG request is uniform. Surfaced by `b.ai.dp` per-byte noise sampling; any per-byte consumer of `generateBytes` inherits the fix. A regression test asserts 0x00 / 0xff occur and the low bit is balanced."
27
+ }
28
+ ]
29
+ }
30
+ ]
31
+ }
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * Layer 0 — b.ai.dp float-safe differential privacy. Snapping-
4
+ * mechanism Laplace (Mironov 2012) + discrete Gaussian (CKS20) with
5
+ * CSPRNG noise; per-scope ε/δ budgets with basic + Rényi-DP
6
+ * accounting. Statistical checks validate the noise distributions;
7
+ * the budget tests validate composition + exhaustion.
8
+ */
9
+
10
+ var b = require("../../index");
11
+ var helpers = require("../helpers");
12
+ var check = helpers.check;
13
+
14
+ // A budget large enough that the statistical loops never exhaust it.
15
+ function _bigBudget() {
16
+ return b.ai.dp.budget({ scope: "stat", epsilon: 1e12, delta: 0.9, accounting: "basic", audit: false });
17
+ }
18
+ function _mean(xs) { var s = 0; for (var i = 0; i < xs.length; i++) s += xs[i]; return s / xs.length; }
19
+ function _variance(xs, mean) { var s = 0; for (var i = 0; i < xs.length; i++) s += (xs[i] - mean) * (xs[i] - mean); return s / xs.length; }
20
+
21
+ async function testMechanismValidation() {
22
+ var cases = [
23
+ [{ type: "exponential", sensitivity: 1, epsilon: 1 }, "aiDp/bad-mechanism"],
24
+ [{ type: "laplace", sensitivity: 0, epsilon: 1, bound: 10 }, "aiDp/bad-sensitivity"],
25
+ [{ type: "laplace", sensitivity: 1, epsilon: 0, bound: 10 }, "aiDp/bad-epsilon"],
26
+ [{ type: "laplace", sensitivity: 1, epsilon: 1 }, "aiDp/bad-bound"],
27
+ [{ type: "gaussian", sensitivity: 1, epsilon: 0.5 }, "aiDp/bad-delta"],
28
+ [{ type: "gaussian", sensitivity: 1, epsilon: 0.5, delta: 1 }, "aiDp/bad-delta"],
29
+ [{ type: "gaussian", sensitivity: 1, epsilon: 2, delta: 1e-6 }, "aiDp/epsilon-too-large"],
30
+ ];
31
+ var ok = true;
32
+ for (var i = 0; i < cases.length; i++) {
33
+ var caught = null;
34
+ try { b.ai.dp.mechanism(cases[i][0]); } catch (e) { caught = e; }
35
+ if (!caught || caught.code !== cases[i][1]) { ok = false; check("mechanism case " + i + " expected " + cases[i][1] + " got " + (caught && caught.code), false); }
36
+ }
37
+ check("mechanism: malformed configs throw the right codes", ok);
38
+ var lap = b.ai.dp.mechanism({ type: "laplace", sensitivity: 1, epsilon: 0.5, bound: 1000 });
39
+ check("mechanism: laplace scale = sensitivity/epsilon", lap.scale === 2 && lap.delta === 0);
40
+ var gss = b.ai.dp.mechanism({ type: "gaussian", sensitivity: 1, epsilon: 0.5, delta: 1e-6 });
41
+ check("mechanism: gaussian computes sigma", gss.sigma > 0 && gss.sigma2 > 0);
42
+ }
43
+
44
+ async function testSnappingLaplaceDistribution() {
45
+ var bud = _bigBudget();
46
+ var m = b.ai.dp.mechanism({ type: "laplace", sensitivity: 1, epsilon: 0.5, bound: 1e6 }); // scale 2 → Λ 2
47
+ var N = 40000, xs = [], onGrid = true;
48
+ for (var i = 0; i < N; i++) {
49
+ var v = bud.consume(m, 100).value;
50
+ xs.push(v);
51
+ if (v % 2 !== 0) onGrid = false; // snapping grid Λ = 2
52
+ }
53
+ check("laplace: every output lands on the power-of-two snapping grid", onGrid);
54
+ var mean = _mean(xs);
55
+ check("laplace: mean ≈ true value (100)", Math.abs(mean - 100) < 0.3);
56
+ var variance = _variance(xs, mean);
57
+ check("laplace: variance ≈ 2·scale² (8)", variance > 6.5 && variance < 9.5);
58
+ }
59
+
60
+ async function testLaplaceClamping() {
61
+ var bud = _bigBudget();
62
+ var m = b.ai.dp.mechanism({ type: "laplace", sensitivity: 1, epsilon: 1, bound: 10 });
63
+ var withinBound = true;
64
+ for (var i = 0; i < 5000; i++) {
65
+ var v = bud.consume(m, 1000000).value; // true value far outside the bound
66
+ if (v < -10 || v > 10) withinBound = false;
67
+ }
68
+ check("laplace: output is clamped to ±bound", withinBound);
69
+ }
70
+
71
+ async function testDiscreteGaussianDistribution() {
72
+ var bud = _bigBudget();
73
+ var m = b.ai.dp.mechanism({ type: "gaussian", sensitivity: 1, epsilon: 0.5, delta: 1e-6 });
74
+ var N = 40000, xs = [], allInt = true;
75
+ for (var i = 0; i < N; i++) {
76
+ var v = bud.consume(m, 0).value;
77
+ xs.push(v);
78
+ if (!Number.isInteger(v)) allInt = false;
79
+ }
80
+ check("gaussian: discrete — every output is an integer", allInt);
81
+ var mean = _mean(xs);
82
+ check("gaussian: mean ≈ 0", Math.abs(mean) < 0.5);
83
+ var variance = _variance(xs, mean);
84
+ // Discrete Gaussian variance ≈ σ² for σ not tiny.
85
+ check("gaussian: variance ≈ σ²", variance > m.sigma2 * 0.85 && variance < m.sigma2 * 1.15);
86
+ }
87
+
88
+ async function testBudgetBasicComposition() {
89
+ var bud = b.ai.dp.budget({ scope: "t", epsilon: 1.0, delta: 1e-5, accounting: "basic", audit: false });
90
+ var m = b.ai.dp.mechanism({ type: "laplace", sensitivity: 1, epsilon: 0.3, bound: 100 });
91
+ var r1 = bud.consume(m, 5);
92
+ check("budget: consume returns { value, cost, remaining }",
93
+ typeof r1.value === "number" && r1.cost.epsilon === 0.3 && Math.abs(r1.remaining.epsilon - 0.7) < 1e-9);
94
+ bud.consume(m, 5);
95
+ bud.consume(m, 5); // spent 0.9
96
+ var refused = null;
97
+ try { bud.consume(m, 5); } catch (e) { refused = e; } // 0.9 + 0.3 > 1.0
98
+ check("budget: basic composition refuses over-ε release", refused && refused.code === "aiDp/budget-exhausted");
99
+ check("budget: spent reflects three releases", Math.abs(bud.spent().epsilon - 0.9) < 1e-9);
100
+ bud.reset();
101
+ check("budget: reset clears spend", bud.spent().epsilon === 0);
102
+ }
103
+
104
+ async function testBudgetDeltaExhaustion() {
105
+ var bud = b.ai.dp.budget({ scope: "t", epsilon: 1e6, delta: 2.5e-6, accounting: "basic", audit: false });
106
+ var m = b.ai.dp.mechanism({ type: "gaussian", sensitivity: 1, epsilon: 0.1, delta: 1e-6 });
107
+ bud.consume(m, 0); bud.consume(m, 0); // δ spent 2e-6
108
+ var refused = null;
109
+ try { bud.consume(m, 0); } catch (e) { refused = e; } // 2e-6 + 1e-6 > 2.5e-6
110
+ check("budget: δ budget exhaustion refuses (not just ε)", refused && refused.code === "aiDp/budget-exhausted");
111
+ }
112
+
113
+ async function testRdpTighterThanBasic() {
114
+ function spend(acc) {
115
+ var bud = b.ai.dp.budget({ scope: "s", epsilon: 1e9, delta: 1e-3, accounting: acc, audit: false });
116
+ var m = b.ai.dp.mechanism({ type: "gaussian", sensitivity: 1, epsilon: 0.3, delta: 1e-6 });
117
+ for (var k = 0; k < 12; k++) bud.consume(m, 0);
118
+ return bud.spent().epsilon;
119
+ }
120
+ var basicEps = spend("basic");
121
+ var rdpEps = spend("rdp");
122
+ check("rdp: 12× Gaussian basic sums to 3.6", Math.abs(basicEps - 3.6) < 1e-9);
123
+ check("rdp: Rényi accounting is strictly tighter than basic", rdpEps < basicEps);
124
+ }
125
+
126
+ async function testBudgetValidation() {
127
+ var cases = [
128
+ [{ scope: "", epsilon: 1 }, "aiDp/bad-scope"],
129
+ [{ scope: "s", epsilon: 0 }, "aiDp/bad-epsilon"],
130
+ [{ scope: "s", epsilon: 1, delta: 1 }, "aiDp/bad-delta"],
131
+ [{ scope: "s", epsilon: 1, delta: -1 }, "aiDp/bad-delta"],
132
+ [{ scope: "s", epsilon: 1, accounting: "zcdp" }, "aiDp/bad-accounting"],
133
+ [{ scope: "s", epsilon: 1, delta: 0, accounting: "rdp" }, "aiDp/bad-accounting"],
134
+ ];
135
+ var ok = true;
136
+ for (var i = 0; i < cases.length; i++) {
137
+ var caught = null;
138
+ try { b.ai.dp.budget(cases[i][0]); } catch (e) { caught = e; }
139
+ if (!caught || caught.code !== cases[i][1]) { ok = false; check("budget case " + i + " expected " + cases[i][1] + " got " + (caught && caught.code), false); }
140
+ }
141
+ check("budget: malformed configs throw the right codes", ok);
142
+ // A gaussian mechanism needs a scope delta > 0.
143
+ var bud = b.ai.dp.budget({ scope: "s", epsilon: 1, accounting: "basic", audit: false });
144
+ var refused = null;
145
+ try { bud.consume(b.ai.dp.mechanism({ type: "gaussian", sensitivity: 1, epsilon: 0.5, delta: 1e-6 }), 0); } catch (e) { refused = e; }
146
+ check("budget: gaussian into a δ=0 scope refused", refused && refused.code === "aiDp/bad-delta");
147
+ }
148
+
149
+ async function run() {
150
+ await testMechanismValidation();
151
+ await testSnappingLaplaceDistribution();
152
+ await testLaplaceClamping();
153
+ await testDiscreteGaussianDistribution();
154
+ await testBudgetBasicComposition();
155
+ await testBudgetDeltaExhaustion();
156
+ await testRdpTighterThanBasic();
157
+ await testBudgetValidation();
158
+ }
159
+
160
+ module.exports = { run: run };
161
+
162
+ if (require.main === module) {
163
+ run().then(
164
+ function () { console.log("[ai-dp] OK — " + helpers.getChecks() + " checks passed"); },
165
+ function (e) { console.error("FAIL:", e && e.stack || e); process.exit(1); }
166
+ );
167
+ }
@@ -2200,10 +2200,11 @@ async function testNoDuplicateCodeBlocks() {
2200
2200
  files: [
2201
2201
  "lib/ai-quota.js:_emitAudit",
2202
2202
  "lib/ai-capability.js:_emitAudit",
2203
+ "lib/ai-dp.js:_emitAudit",
2203
2204
  "lib/cert.js:_emitAudit",
2204
2205
  "lib/mail-send-deliver.js:_auditEmit",
2205
2206
  ],
2206
- reason: "v0.12.27 + v0.12.28 — per-module drop-silent audit-emit helper (`try { audit().safeEmit({ action, outcome, metadata }); } catch (_e) {}`). Same family as the archive / http-client _emitAudit cluster (feedback_audit_safeEmit_per_module_emitAudit_shape): ai-quota.js emits ai/quota-applied + ai/quota-exceeded, ai-capability.js emits ai/capability-routed + ai/capability-no-candidate, cert.js emits certificate-lifecycle events, mail-send-deliver.js emits delivery events. Each carries a primitive-specific `action:` namespace + metadata fields; consolidating would force a shared audit import and lose the per-primitive namespace operators grep for in audit logs.",
2207
+ reason: "v0.12.27 + v0.12.28 + v0.12.29 — per-module drop-silent audit-emit helper (`try { audit().safeEmit({ action, outcome, metadata }); } catch (_e) {}`). Same family as the archive / http-client _emitAudit cluster (feedback_audit_safeEmit_per_module_emitAudit_shape): ai-quota.js emits ai/quota-applied + ai/quota-exceeded, ai-capability.js emits ai/capability-routed + ai/capability-no-candidate, ai-dp.js emits dp/budget-consumed + dp/budget-exhausted, cert.js emits certificate-lifecycle events, mail-send-deliver.js emits delivery events. Each carries a primitive-specific `action:` namespace + metadata fields; consolidating would force a shared audit import and lose the per-primitive namespace operators grep for in audit logs.",
2207
2208
  },
2208
2209
  {
2209
2210
  mode: "family-subset",
@@ -2219,11 +2220,22 @@ async function testNoDuplicateCodeBlocks() {
2219
2220
  mode: "family-subset",
2220
2221
  files: [
2221
2222
  "lib/ai-capability.js:create",
2223
+ "lib/ai-dp.js:budget",
2222
2224
  "lib/cert.js:create",
2223
2225
  "lib/mail-send-deliver.js:create",
2224
2226
  "lib/auth/sd-jwt-vc-holder.js:create",
2225
2227
  ],
2226
- reason: "v0.12.28 — factory-primitive opts-validation prelude (`validateOpts.requireObject + validateOpts(allowedKeys) + per-field typed-error throws + closure-captured return`). ai-capability.create validates a model-descriptor registry + builds a router closure; cert.create / mail-send-deliver.create / sd-jwt-vc-holder.create each validate a distinct spec's opts (X.509 cert issuance / RFC 5321 SMTP send / SD-JWT-VC holder store). Each throws a primitive-specific typed error (AiCapabilityError / CertError / MailSendError / SdJwtVcError); the shingle is the create()-factory validation idiom, not behaviour. Same family as the v0.10.16 factory-primitive validateOpts cluster.",
2228
+ reason: "v0.12.28 + v0.12.29 — factory-primitive opts-validation prelude (`validateOpts.requireObject + validateOpts(allowedKeys) + per-field typed-error throws + closure-captured return`). ai-capability.create validates a model-descriptor registry + builds a router closure; ai-dp.budget validates a per-scope ε/δ budget + builds an accountant closure; cert.create / mail-send-deliver.create / sd-jwt-vc-holder.create each validate a distinct spec's opts (X.509 cert issuance / RFC 5321 SMTP send / SD-JWT-VC holder store). Each throws a primitive-specific typed error (AiCapabilityError / AiDpError / CertError / MailSendError / SdJwtVcError); the shingle is the create()-factory validation idiom, not behaviour. Same family as the v0.10.16 factory-primitive validateOpts cluster.",
2229
+ },
2230
+ {
2231
+ mode: "family-subset",
2232
+ files: [
2233
+ "lib/ai-dp.js:mechanism",
2234
+ "lib/dora.js:_validateReportInput",
2235
+ "lib/config.js:loadDbBacked",
2236
+ "lib/guard-snapshot-envelope.js:validate",
2237
+ ],
2238
+ reason: "v0.12.29 — input-shape validation prelude (`validateOpts(allowedKeys) + chained typeof / range guards + typed-error throw`). ai-dp.mechanism validates a DP mechanism descriptor (type / sensitivity / epsilon / delta / bound); dora._validateReportInput validates a DORA Art. 17 incident report; config.loadDbBacked validates DB-backed config opts; guard-snapshot-envelope.validate validates a sealed snapshot envelope. Each enforces a distinct spec's field set with a primitive-specific typed error; the shingle is the validateOpts-then-guard idiom, not behaviour.",
2227
2239
  },
2228
2240
  {
2229
2241
  mode: "family-subset",
@@ -62,10 +62,31 @@ function testInputValidation() {
62
62
  check("max < min throws RangeError", threw);
63
63
  }
64
64
 
65
+ function testGenerateBytesUniformity() {
66
+ // Regression: Node's SHAKE256 XOF is non-uniform at outputLength 1
67
+ // (byte values 0x00 / 0xff never occur, low bit skews to ~0.54).
68
+ // b.crypto.random draws >= 2 bytes and slices so a 1-byte request
69
+ // is still uniform — without this, every per-byte CSPRNG consumer
70
+ // (e.g. b.ai.dp noise sampling) would inherit the bias.
71
+ var N = 60000;
72
+ var sawZero = false, sawMax = false, lowBitOnes = 0;
73
+ for (var i = 0; i < N; i += 1) {
74
+ var byte = b.crypto.generateBytes(1)[0];
75
+ if (byte === 0) sawZero = true;
76
+ if (byte === 255) sawMax = true; // allow:raw-byte-literal — 0xff byte value, not a size
77
+ lowBitOnes += (byte & 1);
78
+ }
79
+ check("generateBytes(1) can emit 0x00", sawZero);
80
+ check("generateBytes(1) can emit 0xff", sawMax);
81
+ var lowBitFrac = lowBitOnes / N;
82
+ check("generateBytes(1) low bit is balanced (~0.5)", lowBitFrac > 0.47 && lowBitFrac < 0.53);
83
+ }
84
+
65
85
  function run() {
66
86
  testRangeContract();
67
87
  testDispersion();
68
88
  testInputValidation();
89
+ testGenerateBytesUniformity();
69
90
  }
70
91
 
71
92
  if (require.main === module) run();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/blamejs-shop",
3
- "version": "0.0.122",
3
+ "version": "0.0.123",
4
4
  "description": "Open-source framework built on blamejs. Vendored stack, zero npm runtime deps, PQC-first crypto, security-on by default.",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {