@openmobilehub/attestomcp-storefront 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Open Mobile Hub, a series of LF Projects, LLC
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @openmobilehub/attestomcp-storefront
2
+
3
+ **The agentic storefront core.** A runnable MCP shopping server — the cart → priced-cart →
4
+ order model + the nine shopping tools + the widget bundle — **catalog-injected** (bring your
5
+ own products, own-the-code). Pairs with
6
+ [`@openmobilehub/attestomcp-gate`](../attestomcp-gate) so you can **gate any consequential MCP tool
7
+ with any credential**: age, membership, a prescription, payment. **Payments is one application
8
+ of the same gate, not the point** — `minimumAge` on a product is all it takes to lock checkout.
9
+
10
+ > **Design preview / v0.1.** The pure pricing/order model (`@openmobilehub/attestomcp-storefront`)
11
+ > and the runnable MCP server (`@openmobilehub/attestomcp-storefront/server`) are real and tested.
12
+ > Some of the demo's widget polish is still being extracted from the reference server
13
+ > ([mcp-apps-shopping-demo](https://github.com/openmobilehub/mcp-apps-shopping-demo)).
14
+ > See the repo's `ROADMAP.md`.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @openmobilehub/attestomcp-storefront @openmobilehub/attestomcp-gate
20
+ ```
21
+
22
+ Apache-2.0, ESM. Two entry points: `.` (the pure pricing model, dependency-light) and
23
+ `./server` (the runnable MCP server, brings in `@modelcontextprotocol/sdk` + `express`).
24
+
25
+ ## Quickstart — a credential-gated storefront in ≤ 10 lines
26
+
27
+ `createStorefront()` stands up the real MCP server (nine tools, a widget resource, a checkout
28
+ page) over HTTP at `/mcp`. It publishes the ceremony seams on `store.app.locals.attestomcp`, so
29
+ `new AttestoMcp().mount(store.app)` wires the real `/attestomcp/*` ceremony rails with zero glue, and
30
+ `store.gate()` resolves your policy on every `checkout` call (copied from
31
+ [`examples/storefront.mjs`](https://github.com/openmobilehub/mcp-apps-shopping-demo/blob/main/examples/storefront.mjs) /
32
+ [`storefront-gate.test.ts`](https://github.com/openmobilehub/mcp-apps-shopping-demo/blob/main/storefront-gate.test.ts)):
33
+
34
+ ```ts
35
+ import { createStorefront } from "@openmobilehub/attestomcp-storefront/server";
36
+ import { AttestoMcp, age, membership, payment, required, optional } from "@openmobilehub/attestomcp-gate";
37
+
38
+ const store = createStorefront(); // the whole storefront — one line
39
+ const attestomcp = new AttestoMcp();
40
+ attestomcp.mount(store.app); // wires the real /attestomcp/* ceremony rails
41
+
42
+ store.gate((order) => // resolved on every checkout (payment settles LAST)
43
+ attestomcp.requirements(order, [
44
+ required(age.over(21).when((order) => order.lines.some((l) => l.minimumAge != null))),
45
+ optional(membership.discount(10)), // 10% off if a loyalty credential is presented
46
+ required(payment.in("usd")), // amount derived from the order; settles last
47
+ ]),
48
+ );
49
+
50
+ const { url } = await store.listen(3005); // → add http://localhost:3005/mcp to Claude / ChatGPT / Goose
51
+ ```
52
+
53
+ Browse → add the whiskey (21+) → checkout. The `checkout` tool returns the link **plus** a
54
+ `requires` manifest; the buyer proves age + (optionally) membership, then authorizes payment on
55
+ the `mount()`-served page; the widget polls and shows the discounted confirmation. Add the
56
+ headphones instead and the age gate drops — the `.when()` predicate receives the **order** and is
57
+ false. Without `store.gate(...)` the storefront is ungated: a plain checkout link, no `requires`.
58
+
59
+ > The product's `minimumAge` is the single field that ties the two packages together: `priceCart`
60
+ > re-derives it onto each priced line, so a storefront `Order` feeds `attestomcp.requirements()`
61
+ > directly — no mapping. The gate's amount is **re-derived server-side from this catalog**, never
62
+ > trusted from the order token (Security invariant 2).
63
+
64
+ ## The three execution contexts
65
+
66
+ `createStorefront()` is built around the split the gate enforces — conflating these is forbidden
67
+ ([spec §0](https://github.com/openmobilehub/mcp-apps-shopping-demo/blob/main/specs/001-attesto-sdk/spec.md)):
68
+
69
+ 1. **Tool — mints the link + reports requirements.** The `checkout` tool snapshots the cart into an
70
+ order, returns `{ orderId, checkoutUrl, requires }`, and runs **no ceremony** (no phone in the loop).
71
+ 2. **Page — runs the gates.** `GET /checkout?order=<id>` links to the `/attestomcp/*` ceremony routes
72
+ `attestomcp.mount(store.app)` serves; the buyer completes every gate there in one session.
73
+ 3. **Poll — reports completion.** The widget polls `GET /checkout/order-status?orderId=<id>`; once the
74
+ ceremony's shared `completeOrder` records the order (re-priced, age re-enforced, cart cleared), it
75
+ reflects the completed — discounted — total.
76
+
77
+ ## Pure pricing model (no server)
78
+
79
+ The `.` entry point is the pure, catalog-injected pricing core — useful standalone or to fork:
80
+
81
+ ```ts
82
+ import { priceCart, createOrder, requiredAgeForLines, SAMPLE_CATALOG } from "@openmobilehub/attestomcp-storefront";
83
+
84
+ const cart = priceCart([{ productId: "oak-whiskey", quantity: 1 }], SAMPLE_CATALOG);
85
+ cart.hasAgeRestricted; // true → wire @openmobilehub/attestomcp-gate on checkout
86
+ requiredAgeForLines(cart.lines, SAMPLE_CATALOG); // 21
87
+
88
+ const order = createOrder([{ productId: "oak-whiskey", quantity: 1 }], "ORD-1", SAMPLE_CATALOG);
89
+ order.total; // 124
90
+ ```
91
+
92
+ Pure functions — no globals — so the same code serves any storefront. Pass your own `Product[]` as
93
+ the catalog; unknown ids are collected (`unknownIds`), not thrown.
94
+
95
+ ## What's real in v0.1
96
+
97
+ - `createStorefront(opts)` → `{ app, catalog, gate, listen, mcpServer }` — the runnable MCP server
98
+ (nine tools, widget resource, checkout page) over HTTP, catalog-injected, gate-ready.
99
+ - `priceCart()` / `createOrder()` / `requiredAgeForLines()` / `getProduct()` / `getReviews()` — pure,
100
+ catalog-injected pricing & lookups.
101
+ - The `Product` / `Order` / `PricedCart` / `PricedCartLine` model + a runnable `SAMPLE_CATALOG`
102
+ (includes one 21+ item) so the package demos itself.
103
+ - Loyalty discount with a per-call percent override (`LOYALTY_DISCOUNT_PCT`, `PriceOpts`).
104
+ - Pluggable stores (cart / created-order / completed-order / verification) — default in-memory;
105
+ inject a shared store (e.g. Redis) for a multi-instance serverless deployment.
106
+
107
+ `createStorefront()` accepts `{ catalog, reviews, baseUrl, cartStore, orderStore, createdOrderStore,
108
+ verificationStore, signingKey, allowEphemeralKey, settle }`. The optional `settle` seam (e.g.
109
+ on-chain) **gates** completion: a configured-but-failed settle records nothing and leaves the cart
110
+ intact.
111
+
112
+ ## Honest status
113
+
114
+ The composed gate is **presence-only** in v0.1 (`trust_level: "presence-only-demo"`): the passkey rail
115
+ is real WebAuthn cryptography, but the age/membership and Digital-Credentials payment rails enforce
116
+ disclosure + binding, **not** mdoc issuer/device-signature trust — a flow demo, not a real safety
117
+ control. See [`@openmobilehub/attestomcp-gate`](../attestomcp-gate#honest-status) for the full breakdown.
118
+
119
+ Apache-2.0 · part of [Open Mobile Hub](https://openmobilehub.org) (Linux Foundation).
@@ -0,0 +1,2 @@
1
+ /** Product id → a generated, self-contained image (data URI). */
2
+ export declare const PRODUCT_IMAGES: Record<string, string>;
@@ -0,0 +1,23 @@
1
+ // Self-contained product images — generated here, no external image service.
2
+ // Each is a clean SVG tile: a category-tinted gradient + the product's emoji
3
+ // (instantly recognizable, renders crisply at any size), embedded as a data URI.
4
+ // The widget shows the product name beneath, so the tile is just the visual.
5
+ function tile(emoji, bg) {
6
+ const svg = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 300'>` +
7
+ `<defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'>` +
8
+ `<stop offset='0' stop-color='${bg[0]}'/><stop offset='1' stop-color='${bg[1]}'/>` +
9
+ `</linearGradient></defs>` +
10
+ `<rect width='400' height='300' fill='url(#g)'/>` +
11
+ `<text x='200' y='150' font-size='150' text-anchor='middle' dominant-baseline='central'>${emoji}</text>` +
12
+ `</svg>`;
13
+ return "data:image/svg+xml," + encodeURIComponent(svg);
14
+ }
15
+ /** Product id → a generated, self-contained image (data URI). */
16
+ export const PRODUCT_IMAGES = {
17
+ "aurora-headphones": tile("🎧", ["#7c3aed", "#a78bfa"]),
18
+ "oak-whiskey": tile("🥃", ["#b45309", "#f59e0b"]),
19
+ "drift-mouse": tile("🖱️", ["#0f766e", "#2dd4bf"]),
20
+ "celebration-champagne": tile("🍾", ["#be185d", "#f9a8d4"]),
21
+ "summit-backpack": tile("🎒", ["#1d4ed8", "#60a5fa"]),
22
+ "lumen-desk-lamp": tile("💡", ["#a16207", "#fde047"]),
23
+ };
@@ -0,0 +1,87 @@
1
+ /** Default loyalty discount, in percent. Override per-call via PriceOpts. */
2
+ export declare const LOYALTY_DISCOUNT_PCT = 10;
3
+ /** `_meta` keys the storefront tools use to embed the catalog / cart for the widget to read. */
4
+ export declare const CATALOG_META_KEY = "product-picker/catalog";
5
+ export declare const CART_META_KEY = "product-picker/cart";
6
+ /** A product review, surfaced by `get-product-reviews`. */
7
+ export interface Review {
8
+ author: string;
9
+ rating: number;
10
+ text: string;
11
+ }
12
+ export interface Product {
13
+ id: string;
14
+ name: string;
15
+ price: number;
16
+ currency: string;
17
+ image: string;
18
+ category: string;
19
+ description: string;
20
+ /** Minimum age to purchase (e.g. 21). Absent = no age restriction. */
21
+ minimumAge?: number;
22
+ }
23
+ export interface CartItemInput {
24
+ productId: string;
25
+ quantity: number;
26
+ }
27
+ export interface PricedCartLine {
28
+ id: string;
29
+ name: string;
30
+ unitPrice: number;
31
+ currency: string;
32
+ quantity: number;
33
+ lineTotal: number;
34
+ /**
35
+ * Per-product age threshold (e.g. 21), re-derived from the catalog onto the
36
+ * line. Lets a priced `Order` feed `@openmobilehub/attestomcp-gate`'s
37
+ * `requirements()` directly — no `toGateOrder` mapping needed.
38
+ */
39
+ minimumAge?: number;
40
+ /** Product category, carried through for custom `.when()` / `appliesTo` predicates. */
41
+ category?: string;
42
+ }
43
+ export interface PricedCart {
44
+ lines: PricedCartLine[];
45
+ itemCount: number;
46
+ subtotal: number;
47
+ discount: number;
48
+ total: number;
49
+ currency: string;
50
+ unknownIds: string[];
51
+ hasAgeRestricted: boolean;
52
+ ageVerified: boolean;
53
+ loyaltyApplied: boolean;
54
+ }
55
+ export interface Order {
56
+ id: string;
57
+ lines: PricedCartLine[];
58
+ itemCount: number;
59
+ subtotal: number;
60
+ discount: number;
61
+ total: number;
62
+ currency: string;
63
+ createdAt: string;
64
+ }
65
+ export interface PriceOpts {
66
+ ageVerified?: boolean;
67
+ loyaltyApplied?: boolean;
68
+ /** Loyalty discount percent (defaults to LOYALTY_DISCOUNT_PCT). */
69
+ loyaltyDiscountPct?: number;
70
+ }
71
+ /**
72
+ * Price a cart against an injected catalog. Unknown ids are collected, not
73
+ * thrown. Pure — no globals, so the same function serves any storefront.
74
+ */
75
+ export declare function priceCart(items: CartItemInput[], catalog: Product[], opts?: PriceOpts): PricedCart;
76
+ /** The strictest minimum age across the cart's products, or null if none. */
77
+ export declare function requiredAgeForLines(lines: {
78
+ id: string;
79
+ }[], catalog: Product[]): number | null;
80
+ /** Snapshot a priced cart into an immutable order. */
81
+ export declare function createOrder(items: CartItemInput[], id: string, catalog: Product[], opts?: PriceOpts): Order;
82
+ /** Look up a product by id in the injected catalog. */
83
+ export declare function getProduct(catalog: Product[], productId: string): Product | undefined;
84
+ /** Reviews for a product, from the injected reviews map (empty if none). */
85
+ export declare function getReviews(reviews: Record<string, Review[]> | undefined, productId: string): Review[];
86
+ /** A tiny runnable catalog (incl. one age-restricted item) so the package demos itself. */
87
+ export declare const SAMPLE_CATALOG: Product[];
package/dist/index.js ADDED
@@ -0,0 +1,151 @@
1
+ // @openmobilehub/attestomcp-storefront — the agentic storefront core (v0.1 slice).
2
+ //
3
+ // The cart → priced-cart → order model an MCP shopping app needs, **catalog-injected**
4
+ // (bring your own products). Own-the-code: fork it and edit your catalog. This slice
5
+ // is the pure pricing/order model; the MCP tools + widget bundle that render it are
6
+ // tracked in the roadmap.
7
+ import { PRODUCT_IMAGES } from "./generated-images.js";
8
+ /** Default loyalty discount, in percent. Override per-call via PriceOpts. */
9
+ export const LOYALTY_DISCOUNT_PCT = 10;
10
+ /** `_meta` keys the storefront tools use to embed the catalog / cart for the widget to read. */
11
+ export const CATALOG_META_KEY = "product-picker/catalog";
12
+ export const CART_META_KEY = "product-picker/cart";
13
+ function round2(n) {
14
+ return Math.round(n * 100) / 100;
15
+ }
16
+ /**
17
+ * Price a cart against an injected catalog. Unknown ids are collected, not
18
+ * thrown. Pure — no globals, so the same function serves any storefront.
19
+ */
20
+ export function priceCart(items, catalog, opts = {}) {
21
+ const byId = new Map(catalog.map((p) => [p.id, p]));
22
+ const lines = [];
23
+ const unknownIds = [];
24
+ let hasAgeRestricted = false;
25
+ for (const { productId, quantity } of items) {
26
+ const product = byId.get(productId);
27
+ if (!product) {
28
+ unknownIds.push(productId);
29
+ continue;
30
+ }
31
+ if (quantity <= 0)
32
+ continue;
33
+ if (product.minimumAge != null)
34
+ hasAgeRestricted = true;
35
+ lines.push({
36
+ id: product.id,
37
+ name: product.name,
38
+ unitPrice: product.price,
39
+ currency: product.currency,
40
+ quantity,
41
+ lineTotal: round2(product.price * quantity),
42
+ // Re-derived onto the line so a priced Order is gate-ready (inv #2).
43
+ ...(product.minimumAge != null ? { minimumAge: product.minimumAge } : {}),
44
+ category: product.category,
45
+ });
46
+ }
47
+ const itemCount = lines.reduce((sum, l) => sum + l.quantity, 0);
48
+ const subtotal = round2(lines.reduce((sum, l) => sum + l.lineTotal, 0));
49
+ const loyaltyApplied = !!opts.loyaltyApplied;
50
+ const pct = opts.loyaltyDiscountPct ?? LOYALTY_DISCOUNT_PCT;
51
+ const discount = loyaltyApplied ? round2(subtotal * (pct / 100)) : 0;
52
+ const total = round2(subtotal - discount);
53
+ const currency = lines[0]?.currency ?? "USD";
54
+ return {
55
+ lines,
56
+ itemCount,
57
+ subtotal,
58
+ discount,
59
+ total,
60
+ currency,
61
+ unknownIds,
62
+ hasAgeRestricted,
63
+ ageVerified: !!opts.ageVerified,
64
+ loyaltyApplied,
65
+ };
66
+ }
67
+ /** The strictest minimum age across the cart's products, or null if none. */
68
+ export function requiredAgeForLines(lines, catalog) {
69
+ const byId = new Map(catalog.map((p) => [p.id, p]));
70
+ let max = null;
71
+ for (const { id } of lines) {
72
+ const m = byId.get(id)?.minimumAge;
73
+ if (m != null && (max === null || m > max))
74
+ max = m;
75
+ }
76
+ return max;
77
+ }
78
+ /** Snapshot a priced cart into an immutable order. */
79
+ export function createOrder(items, id, catalog, opts = {}) {
80
+ const { lines, itemCount, subtotal, discount, total, currency } = priceCart(items, catalog, opts);
81
+ return { id, lines, itemCount, subtotal, discount, total, currency, createdAt: new Date().toISOString() };
82
+ }
83
+ /** Look up a product by id in the injected catalog. */
84
+ export function getProduct(catalog, productId) {
85
+ return catalog.find((p) => p.id === productId);
86
+ }
87
+ /** Reviews for a product, from the injected reviews map (empty if none). */
88
+ export function getReviews(reviews, productId) {
89
+ return reviews?.[productId] ?? [];
90
+ }
91
+ /** A tiny runnable catalog (incl. one age-restricted item) so the package demos itself. */
92
+ // Generated, self-contained product images (see generated-images.ts) — emoji tiles
93
+ // embedded as data URIs, so the catalog needs no external image service.
94
+ export const SAMPLE_CATALOG = [
95
+ {
96
+ id: "aurora-headphones",
97
+ name: "Aurora Wireless Headphones",
98
+ price: 199.0,
99
+ currency: "USD",
100
+ image: PRODUCT_IMAGES["aurora-headphones"],
101
+ category: "Audio",
102
+ description: "Over-ear ANC headphones with 40h battery life.",
103
+ },
104
+ {
105
+ id: "oak-whiskey",
106
+ name: "Oak Reserve Whiskey Collection",
107
+ price: 124.0,
108
+ currency: "USD",
109
+ image: PRODUCT_IMAGES["oak-whiskey"],
110
+ category: "Beverages",
111
+ description: "Trio of small-batch aged whiskeys. 21+ only.",
112
+ minimumAge: 21,
113
+ },
114
+ {
115
+ id: "drift-mouse",
116
+ name: "Drift Wireless Mouse",
117
+ price: 49.0,
118
+ currency: "USD",
119
+ image: PRODUCT_IMAGES["drift-mouse"],
120
+ category: "Electronics",
121
+ description: "Ergonomic silent-click wireless mouse, 6-month battery.",
122
+ },
123
+ {
124
+ id: "celebration-champagne",
125
+ name: "Celebration Champagne Duo",
126
+ price: 89.0,
127
+ currency: "USD",
128
+ image: PRODUCT_IMAGES["celebration-champagne"],
129
+ category: "Beverages",
130
+ description: "Brut champagne duo with two crystal flutes. 21+ only.",
131
+ minimumAge: 21,
132
+ },
133
+ {
134
+ id: "summit-backpack",
135
+ name: "Summit Trail Backpack",
136
+ price: 129.0,
137
+ currency: "USD",
138
+ image: PRODUCT_IMAGES["summit-backpack"],
139
+ category: "Outdoors",
140
+ description: "35L weatherproof hiking backpack with a stowaway rain cover.",
141
+ },
142
+ {
143
+ id: "lumen-desk-lamp",
144
+ name: "Lumen LED Desk Lamp",
145
+ price: 59.0,
146
+ currency: "USD",
147
+ image: PRODUCT_IMAGES["lumen-desk-lamp"],
148
+ category: "Home",
149
+ description: "Dimmable LED desk lamp with a USB-C charging base.",
150
+ },
151
+ ];
@@ -0,0 +1,86 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { Express, Request } from "express";
3
+ import type { Order, Product, Review } from "./index.js";
4
+ import type { CartStore, OrderStore } from "./state.js";
5
+ import { type CeremonyOrder, type VerificationStore } from "@openmobilehub/attestomcp-gate";
6
+ /** Given a priced order, return the `requires` manifest (or `undefined` = ungated). */
7
+ export type GateResolver = (order: Order) => unknown[] | undefined;
8
+ export interface StorefrontOptions {
9
+ /** Products to sell. Defaults to the package's `SAMPLE_CATALOG`. */
10
+ catalog?: Product[];
11
+ /** Reviews per product id, backing `get-product-reviews`. */
12
+ reviews?: Record<string, Review[]>;
13
+ /** Origin the checkout links resolve from. Default `http://localhost:<port>`. */
14
+ baseUrl?: string;
15
+ /** Cart store; default in-memory. */
16
+ cartStore?: CartStore;
17
+ /** Completed-order store (read by `get-order-status`); default in-memory. */
18
+ orderStore?: OrderStore<CompletedOrderRecord>;
19
+ /**
20
+ * Created-but-not-yet-completed orders (read by the checkout page + place-order),
21
+ * keyed by order id. Default in-memory. Inject a shared store (e.g. Redis) on a
22
+ * multi-instance serverless deployment, or the checkout page lands on a cold
23
+ * instance that never saw the order.
24
+ */
25
+ createdOrderStore?: OrderStore<Order>;
26
+ /**
27
+ * Per-order verification state the mounted ceremony writes (age proven / loyalty
28
+ * applied) and this server's `completion` seam reads back to re-price + enforce
29
+ * the age gate. Default in-memory; inject a shared store on a serverless
30
+ * deployment. Published on `app.locals.attestomcp` so `attestomcp.mount(store.app)`
31
+ * wires the rails against the SAME state (Security invariant 4).
32
+ */
33
+ verificationStore?: VerificationStore;
34
+ /**
35
+ * Stable HMAC key for the ceremony's challenge nonce (e.g. `process.env.GATE_SECRET`).
36
+ * Required so an options→verify hop survives an instance split on serverless. When
37
+ * absent, `allowEphemeralKey` defaults true so a single-process dev server / tests
38
+ * just run with a per-process key.
39
+ */
40
+ signingKey?: string;
41
+ /** Allow a per-process ephemeral signing key (default: true unless `signingKey` is set). */
42
+ allowEphemeralKey?: boolean;
43
+ /**
44
+ * Optional demo-mode settlement seam (e.g. on-chain). Throwing GATES completion:
45
+ * a configured-but-failed settle records nothing and leaves the cart intact.
46
+ */
47
+ settle?: (order: CeremonyOrder) => Promise<Record<string, unknown> & {
48
+ network: string;
49
+ txId: string;
50
+ status: string;
51
+ }>;
52
+ }
53
+ /**
54
+ * A completed-order record the widget poll + `get-order-status` read. The standalone
55
+ * demo `place-order` writes the lean shape (orderId/amount/currency/method/completedAt);
56
+ * the mounted ceremony's shared `completeOrder` writes the richer one (mandate id,
57
+ * gate outcomes, instrument, settlement) — both satisfy this superset so the poll
58
+ * reads either.
59
+ */
60
+ export interface CompletedOrderRecord {
61
+ orderId: string;
62
+ amount: number;
63
+ currency: string;
64
+ method: string;
65
+ completedAt: string;
66
+ mandateId?: string;
67
+ instrument?: unknown;
68
+ gates?: {
69
+ gate: string;
70
+ pass: boolean;
71
+ detail: string;
72
+ }[];
73
+ settlement?: unknown;
74
+ }
75
+ export interface Storefront {
76
+ app: Express;
77
+ catalog: Product[];
78
+ gate(resolve: GateResolver): void;
79
+ listen(port?: number): Promise<{
80
+ url: string;
81
+ port: number;
82
+ }>;
83
+ mcpServer(): McpServer;
84
+ }
85
+ export declare function originFromRequest(req: Request): string;
86
+ export declare function createStorefront(opts?: StorefrontOptions): Storefront;