@openmobilehub/credentagent-storefront 0.2.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,186 @@
1
+ # @openmobilehub/credentagent-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/credentagent-gate`](../credentagent-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/credentagent-storefront`)
11
+ > and the runnable MCP server (`@openmobilehub/credentagent-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/credentagent-storefront @openmobilehub/credentagent-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.credentagent`, so
29
+ `new CredentAgent().mount(store.app)` wires the real `/credentagent/*` 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/credentagent-storefront/server";
36
+ import { CredentAgent, age, membership, payment, required, optional } from "@openmobilehub/credentagent-gate";
37
+
38
+ const store = createStorefront(); // the whole storefront — one line
39
+ const credentagent = new CredentAgent();
40
+ credentagent.mount(store.app); // wires the real /credentagent/* ceremony rails
41
+
42
+ store.gate((order) => // resolved on every checkout (payment settles LAST)
43
+ credentagent.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 `credentagent.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
+ ## Production persistence — one option, no adapters
65
+
66
+ `createStorefront()` defaults to **in-memory** stores — perfect for local dev and the quickstart
67
+ above. A real deployment runs on **multiple instances** (serverless / Vercel), where a cart added on
68
+ one instance is invisible to the checkout that lands on another, so production needs **shared
69
+ persistence**. Pass a `storage` provider and all four stores (cart, created-order, completed-order,
70
+ verification) are backed by it — no hand-written adapters:
71
+
72
+ ```ts
73
+ import { createStorefront } from "@openmobilehub/credentagent-storefront/server";
74
+ import { redisStorage } from "@openmobilehub/credentagent-storefront/redis";
75
+
76
+ const store = createStorefront({
77
+ storage: redisStorage({
78
+ url: process.env.KV_REST_API_URL!,
79
+ token: process.env.KV_REST_API_TOKEN!,
80
+ namespace: "my-shop", // isolates keys if multiple shops share one Redis
81
+ }),
82
+ });
83
+ ```
84
+
85
+ - **In-memory stays the zero-config default** — omit `storage` and nothing changes.
86
+ - **Escape hatch:** an explicit `cartStore` / `orderStore` / `createdOrderStore` / `verificationStore`
87
+ still wins over the provider for that slot (bring any custom backend).
88
+ - **Lean by default:** `@upstash/redis` is an **optional peer dependency**, loaded lazily only on the
89
+ `{ url, token }` path — in-memory users never install it.
90
+ - Order and verification state is **keyed per order id**, and the **cart is keyed per MCP session**
91
+ (`${namespace}:cart:${sessionId}`) — never process-global (Security invariant 4); the store persists
92
+ state only and is **not** a trust anchor.
93
+ - **Per-user carts need session affinity on serverless.** Each MCP session gets its own cart, but the
94
+ session/transport lives in per-instance memory — so a **multi-instance serverless** deployment needs
95
+ **sticky sessions** for a shopper's cart to follow them. (Orders & verification are keyed by order id
96
+ and are unaffected.)
97
+
98
+ ## Live catalog — one option, no loader
99
+
100
+ `createStorefront({ catalog })` takes a static `Product[]` by default — perfect for the quickstart.
101
+ A real merchant wants to edit products **without a redeploy**, i.e. a **dynamic catalog source**.
102
+ Pass `firestoreCatalog(...)` and the module owns the loader, the cache, and fail-closed loading — no
103
+ hand-written glue:
104
+
105
+ ```ts
106
+ import { createStorefront } from "@openmobilehub/credentagent-storefront/server";
107
+ import { firestoreCatalog } from "@openmobilehub/credentagent-storefront/firestore";
108
+
109
+ const store = createStorefront({
110
+ catalog: firestoreCatalog({
111
+ collection: "products", // Firestore collection of product docs
112
+ ttlMs: 300_000, // cache for 5 min, then refresh
113
+ // credential: { projectId, clientEmail, privateKey } // or rely on Application Default Credentials
114
+ }),
115
+ });
116
+ ```
117
+
118
+ - **Static array stays the zero-config default** — pass a `Product[]` (or omit `catalog`) and nothing
119
+ changes; no Firebase required.
120
+ - **Fails closed:** an empty/unreachable **cold** load **refuses** (the server returns 503) rather than
121
+ serving an empty catalog; a **refresh** blip serves the last-known-good catalog; a malformed /
122
+ negative-price doc **fails the load** (never silently drops a product).
123
+ - **Prices and age thresholds re-derive server-side** from the loaded catalog on every completion path
124
+ (Security invariant 2 — never trust the order token).
125
+ - **Lean by default:** `firebase-admin` is an **optional peer dependency**, loaded lazily only on the
126
+ credentials path — static-catalog users never install it.
127
+
128
+ ## The three execution contexts
129
+
130
+ `createStorefront()` is built around the split the gate enforces — conflating these is forbidden
131
+ ([spec §0](https://github.com/openmobilehub/mcp-apps-shopping-demo/blob/main/specs/001-attesto-sdk/spec.md)):
132
+
133
+ 1. **Tool — mints the link + reports requirements.** The `checkout` tool snapshots the cart into an
134
+ order, returns `{ orderId, checkoutUrl, requires }`, and runs **no ceremony** (no phone in the loop).
135
+ 2. **Page — runs the gates.** `GET /checkout?order=<id>` links to the `/credentagent/*` ceremony routes
136
+ `credentagent.mount(store.app)` serves; the buyer completes every gate there in one session.
137
+ 3. **Poll — reports completion.** The widget polls `GET /checkout/order-status?orderId=<id>`; once the
138
+ ceremony's shared `completeOrder` records the order (re-priced, age re-enforced, cart cleared), it
139
+ reflects the completed — discounted — total.
140
+
141
+ ## Pure pricing model (no server)
142
+
143
+ The `.` entry point is the pure, catalog-injected pricing core — useful standalone or to fork:
144
+
145
+ ```ts
146
+ import { priceCart, createOrder, requiredAgeForLines, SAMPLE_CATALOG } from "@openmobilehub/credentagent-storefront";
147
+
148
+ const cart = priceCart([{ productId: "oak-whiskey", quantity: 1 }], SAMPLE_CATALOG);
149
+ cart.hasAgeRestricted; // true → wire @openmobilehub/credentagent-gate on checkout
150
+ requiredAgeForLines(cart.lines, SAMPLE_CATALOG); // 21
151
+
152
+ const order = createOrder([{ productId: "oak-whiskey", quantity: 1 }], "ORD-1", SAMPLE_CATALOG);
153
+ order.total; // 124
154
+ ```
155
+
156
+ Pure functions — no globals — so the same code serves any storefront. Pass your own `Product[]` as
157
+ the catalog; unknown ids are collected (`unknownIds`), not thrown.
158
+
159
+ ## What's real in v0.1
160
+
161
+ - `createStorefront(opts)` → `{ app, catalog, gate, listen, mcpServer }` — the runnable MCP server
162
+ (nine tools, widget resource, checkout page) over HTTP, catalog-injected, gate-ready.
163
+ - `priceCart()` / `createOrder()` / `requiredAgeForLines()` / `getProduct()` / `getReviews()` — pure,
164
+ catalog-injected pricing & lookups.
165
+ - The `Product` / `Order` / `PricedCart` / `PricedCartLine` model + a runnable `SAMPLE_CATALOG`
166
+ (includes one 21+ item) so the package demos itself.
167
+ - Loyalty discount with a per-call percent override (`LOYALTY_DISCOUNT_PCT`, `PriceOpts`).
168
+ - Pluggable stores (cart / created-order / completed-order / verification) — default in-memory;
169
+ inject a shared store (e.g. Redis) for a multi-instance serverless deployment.
170
+ - Catalog is static by default or a **dynamic source** (`firestoreCatalog(...)` from `./firestore`) —
171
+ edit products with no redeploy; loaded + cached server-side, fail-closed.
172
+
173
+ `createStorefront()` accepts `{ catalog, reviews, baseUrl, cartStore, orderStore, createdOrderStore,
174
+ verificationStore, storage, signingKey, allowEphemeralKey, settle }`. `catalog` is a `Product[]` (static)
175
+ or a `CatalogSource` (dynamic, e.g. `firestoreCatalog(...)`). The optional `settle` seam (e.g.
176
+ on-chain) **gates** completion: a configured-but-failed settle records nothing and leaves the cart
177
+ intact.
178
+
179
+ ## Honest status
180
+
181
+ The composed gate is **presence-only** in v0.1 (`trust_level: "presence-only-demo"`): the passkey rail
182
+ is real WebAuthn cryptography, but the age/membership and Digital-Credentials payment rails enforce
183
+ disclosure + binding, **not** mdoc issuer/device-signature trust — a flow demo, not a real safety
184
+ control. See [`@openmobilehub/credentagent-gate`](../credentagent-gate#honest-status) for the full breakdown.
185
+
186
+ 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,110 @@
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/credentagent-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
+ /**
87
+ * A source of products for `createStorefront({ catalog })`. The static-array default is
88
+ * wrapped in `staticCatalog(...)`; a DYNAMIC source (e.g. `firestoreCatalog(...)` from
89
+ * `@openmobilehub/credentagent-storefront/firestore`) loads products server-side with a TTL
90
+ * cache so a merchant edits the catalog without a redeploy.
91
+ *
92
+ * Two methods so an async source can feed the gate's SYNCHRONOUS ceremony re-price:
93
+ * `load()` refreshes (fail-closed on a cold/empty load); `current()` returns the
94
+ * last-known-good snapshot the synchronous re-price paths read. The storefront awaits
95
+ * `load()` before every request, so `current()` is always warm inside a handler. Prices
96
+ * and age thresholds are always re-derived from this source server-side (Security
97
+ * invariant 2 — never trust the order token).
98
+ */
99
+ export interface CatalogSource {
100
+ /** Load the current catalog, TTL-cached. Rejects (fail-closed) on a cold/empty load. */
101
+ load(): Promise<Product[]>;
102
+ /** Last-known-good snapshot for the synchronous re-price paths. Throws if never loaded. */
103
+ current(): Product[];
104
+ }
105
+ /** Wrap a static product array as a {@link CatalogSource} — the zero-config default (never fails). */
106
+ export declare function staticCatalog(products: Product[]): CatalogSource;
107
+ /** True when `x` is a {@link CatalogSource} (has a `load` method) rather than a plain `Product[]`. */
108
+ export declare function isCatalogSource(x: Product[] | CatalogSource | undefined): x is CatalogSource;
109
+ /** A tiny runnable catalog (incl. one age-restricted item) so the package demos itself. */
110
+ export declare const SAMPLE_CATALOG: Product[];