@relyon/kit 0.0.0-stage → 1.0.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/AGENTS.md +75 -0
- package/CHANGELOG.md +1053 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +239 -0
- package/README.md +117 -2
- package/dist/adapters/express.d.ts +39 -0
- package/dist/adapters/express.js +106 -0
- package/dist/adapters/hono.d.ts +16 -0
- package/dist/adapters/hono.js +15 -0
- package/dist/adapters/next.d.ts +29 -0
- package/dist/adapters/next.js +38 -0
- package/dist/agent-card.d.ts +14 -0
- package/dist/agent-card.js +58 -0
- package/dist/agent-docs.d.ts +36 -0
- package/dist/agent-docs.js +78 -0
- package/dist/agent-hooks.d.ts +66 -0
- package/dist/agent-hooks.js +280 -0
- package/dist/agents.d.ts +24 -0
- package/dist/agents.js +120 -0
- package/dist/api-key.d.ts +6 -0
- package/dist/api-key.js +33 -0
- package/dist/cache.d.ts +46 -0
- package/dist/cache.js +86 -0
- package/dist/cart-tokens.d.ts +31 -0
- package/dist/cart-tokens.js +58 -0
- package/dist/cart-transfer.d.ts +95 -0
- package/dist/cart-transfer.js +387 -0
- package/dist/catalog-enrichment.d.ts +6 -0
- package/dist/catalog-enrichment.js +71 -0
- package/dist/catalog-reads.d.ts +126 -0
- package/dist/catalog-reads.js +104 -0
- package/dist/catalog.d.ts +78 -0
- package/dist/catalog.js +288 -0
- package/dist/charge-claims.d.ts +11 -0
- package/dist/charge-claims.js +47 -0
- package/dist/check.d.ts +44 -0
- package/dist/check.js +152 -0
- package/dist/checklist-manifest.d.ts +72 -0
- package/dist/checklist-manifest.js +341 -0
- package/dist/checkout.d.ts +222 -0
- package/dist/checkout.js +353 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +727 -0
- package/dist/confirmation.d.ts +78 -0
- package/dist/confirmation.js +124 -0
- package/dist/context.d.ts +81 -0
- package/dist/context.js +10 -0
- package/dist/discovery.d.ts +151 -0
- package/dist/discovery.js +346 -0
- package/dist/doctor-cart-transfer.d.ts +33 -0
- package/dist/doctor-cart-transfer.js +186 -0
- package/dist/doctor-catalog.d.ts +8 -0
- package/dist/doctor-catalog.js +47 -0
- package/dist/doctor-evidence.d.ts +22 -0
- package/dist/doctor-evidence.js +57 -0
- package/dist/doctor-merchant.d.ts +48 -0
- package/dist/doctor-merchant.js +74 -0
- package/dist/doctor-source.d.ts +5 -0
- package/dist/doctor-source.js +142 -0
- package/dist/doctor-variants.d.ts +70 -0
- package/dist/doctor-variants.js +102 -0
- package/dist/doctor.d.ts +215 -0
- package/dist/doctor.js +1689 -0
- package/dist/events.d.ts +95 -0
- package/dist/events.js +200 -0
- package/dist/feed-mapping.d.ts +114 -0
- package/dist/feed-mapping.js +152 -0
- package/dist/feed-values.d.ts +13 -0
- package/dist/feed-values.js +40 -0
- package/dist/feeds.d.ts +104 -0
- package/dist/feeds.js +366 -0
- package/dist/identify.d.ts +102 -0
- package/dist/identify.js +124 -0
- package/dist/identity.d.ts +37 -0
- package/dist/identity.js +54 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +41 -0
- package/dist/init.d.ts +157 -0
- package/dist/init.js +912 -0
- package/dist/kit-config.d.ts +19 -0
- package/dist/kit-config.js +43 -0
- package/dist/kit-environment.d.ts +20 -0
- package/dist/kit-environment.js +32 -0
- package/dist/kit-updates.d.ts +47 -0
- package/dist/kit-updates.js +77 -0
- package/dist/kit-version-project.d.ts +18 -0
- package/dist/kit-version-project.js +214 -0
- package/dist/kit-version.d.ts +37 -0
- package/dist/kit-version.js +162 -0
- package/dist/kit.d.ts +516 -0
- package/dist/kit.js +1309 -0
- package/dist/layers/pages.d.ts +3 -0
- package/dist/layers/pages.js +5 -0
- package/dist/layers/payments.d.ts +7 -0
- package/dist/layers/payments.js +9 -0
- package/dist/layers/products.d.ts +10 -0
- package/dist/layers/products.js +13 -0
- package/dist/live.d.ts +13 -0
- package/dist/live.js +52 -0
- package/dist/mcp.d.ts +270 -0
- package/dist/mcp.js +312 -0
- package/dist/next-steps.d.ts +101 -0
- package/dist/next-steps.js +257 -0
- package/dist/order-pending.d.ts +57 -0
- package/dist/order-pending.js +127 -0
- package/dist/orders.d.ts +12 -0
- package/dist/orders.js +21 -0
- package/dist/payments-init.d.ts +19 -0
- package/dist/payments-init.js +70 -0
- package/dist/payments-routes.d.ts +54 -0
- package/dist/payments-routes.js +123 -0
- package/dist/payments.d.ts +165 -0
- package/dist/payments.js +192 -0
- package/dist/pnpm-workspace.d.ts +58 -0
- package/dist/pnpm-workspace.js +250 -0
- package/dist/policies.d.ts +111 -0
- package/dist/policies.js +317 -0
- package/dist/preview-hosts.d.ts +64 -0
- package/dist/preview-hosts.js +175 -0
- package/dist/private-config.d.ts +169 -0
- package/dist/private-config.js +820 -0
- package/dist/progress.d.ts +54 -0
- package/dist/progress.js +153 -0
- package/dist/protocol-inputs.d.ts +22 -0
- package/dist/protocol-inputs.js +151 -0
- package/dist/public-origin.d.ts +50 -0
- package/dist/public-origin.js +180 -0
- package/dist/refusals.d.ts +86 -0
- package/dist/refusals.js +157 -0
- package/dist/relay.d.ts +107 -0
- package/dist/relay.js +655 -0
- package/dist/release-notes.d.ts +2 -0
- package/dist/release-notes.js +290 -0
- package/dist/relyon-cart-tokens.d.ts +101 -0
- package/dist/relyon-cart-tokens.js +521 -0
- package/dist/relyon.d.ts +141 -0
- package/dist/relyon.js +238 -0
- package/dist/robots.d.ts +27 -0
- package/dist/robots.js +127 -0
- package/dist/rules.d.ts +144 -0
- package/dist/rules.js +347 -0
- package/dist/sdk/generated/public-api.d.ts +4816 -0
- package/dist/sdk/generated/public-api.js +1 -0
- package/dist/sdk/index.d.ts +24 -0
- package/dist/sdk/index.js +34 -0
- package/dist/sdk/signatures.d.ts +17 -0
- package/dist/sdk/signatures.js +33 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.js +94 -0
- package/dist/signatures.d.ts +112 -0
- package/dist/signatures.js +443 -0
- package/dist/state.d.ts +185 -0
- package/dist/state.js +96 -0
- package/dist/store-payments.d.ts +48 -0
- package/dist/store-payments.js +143 -0
- package/dist/structured-fields.d.ts +26 -0
- package/dist/structured-fields.js +200 -0
- package/dist/templates.d.ts +19 -0
- package/dist/templates.js +193 -0
- package/dist/test-checkout-command.d.ts +32 -0
- package/dist/test-checkout-command.js +161 -0
- package/dist/test-checkout.d.ts +88 -0
- package/dist/test-checkout.js +292 -0
- package/dist/types.d.ts +103 -0
- package/dist/types.js +18 -0
- package/dist/ucp-versions.d.ts +57 -0
- package/dist/ucp-versions.js +129 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.js +68 -0
- package/dist/variants.d.ts +67 -0
- package/dist/variants.js +146 -0
- package/dist/version.d.ts +9 -0
- package/dist/version.js +10 -0
- package/dist/waiting.d.ts +43 -0
- package/dist/waiting.js +57 -0
- package/dist/webhook-command.d.ts +48 -0
- package/dist/webhook-command.js +367 -0
- package/dist/webhook-registration.d.ts +47 -0
- package/dist/webhook-registration.js +69 -0
- package/dist/webmcp-schema.d.ts +14 -0
- package/dist/webmcp-schema.js +140 -0
- package/dist/webmcp-script.d.ts +3 -0
- package/dist/webmcp-script.js +176 -0
- package/dist/webmcp-store.d.ts +102 -0
- package/dist/webmcp-store.js +116 -0
- package/dist/webmcp.d.ts +242 -0
- package/dist/webmcp.js +866 -0
- package/dist/wire-names.d.ts +85 -0
- package/dist/wire-names.js +109 -0
- package/package.json +118 -4
- package/release-notes.json +290 -0
- package/scripts/install-notice.cjs +7 -0
- package/skills/relyon-agents/SKILL.md +327 -0
- package/skills/relyon-catalog/SKILL.md +499 -0
- package/skills/relyon-catalog/references/example-store.md +218 -0
- package/skills/relyon-checkout/SKILL.md +603 -0
- package/skills/relyon-checkout/references/checkout-flow.md +257 -0
- package/skills/relyon-checkout/references/checkout-page.md +315 -0
- package/skills/relyon-go-live/SKILL.md +344 -0
- package/skills/relyon-orders/SKILL.md +191 -0
- package/skills/relyon-orders/references/webhook-receiver.md +113 -0
- package/skills/relyon-payments/SKILL.md +117 -0
- package/skills/relyon-setup/SKILL.md +1061 -0
- package/skills/relyon-setup/references/QUICKSTART.md +239 -0
- package/skills/relyon-setup/references/durable-state.md +209 -0
- package/skills/relyon-setup/references/express-server.md +388 -0
- package/skills/relyon-setup/references/next-app-router.md +251 -0
- package/templates/common/STORE-README.md +67 -0
- package/templates/common/gitignore +8 -0
- package/templates/common/scripts/check-pricing.ts +22 -0
- package/templates/common/scripts/serve.mjs +13 -0
- package/templates/common/server/catalog.ts +79 -0
- package/templates/common/server/checkout-flow.d.ts +34 -0
- package/templates/common/server/pages.ts +184 -0
- package/templates/common/server/storage.ts +114 -0
- package/templates/common/server/store.ts +67 -0
- package/templates/express/server/express.ts +20 -0
- package/templates/express/tsconfig.build.json +6 -0
- package/templates/express/tsconfig.json +9 -0
- package/templates/next/app/[[...path]]/route.ts +24 -0
- package/templates/next/next.config.mjs +19 -0
- package/templates/next/tsconfig.json +12 -0
- package/templates/payments/express.ts +39 -0
- package/templates/payments/next.ts +38 -0
- package/templates/payments/node.ts +39 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Pinned Test store
|
|
2
|
+
|
|
3
|
+
Use Node 22.13 or newer (tested with Node 24). No scaffolder or framework upgrade
|
|
4
|
+
is needed. `npm run check:pricing`, `npm run typecheck`, `npm run build`, then
|
|
5
|
+
`HOST=0.0.0.0 PORT=3000 npm run dev`. Set STORE_PUBLIC_URL for your own preview
|
|
6
|
+
origin and STORE_HOSTNAMES if needed. Run `npm run doctor -- --url <origin>`.
|
|
7
|
+
|
|
8
|
+
Read relyon/QUICKSTART.md first; open a skill only when a numbered step names its section.
|
|
9
|
+
Its absence is an integration blocker, not permission to invent its text. Use
|
|
10
|
+
your own /llms.txt and the copied Relyon reference skills meanwhile.
|
|
11
|
+
|
|
12
|
+
Domain verification is an agent step, not the owner's: run `kit.ensureDomain()`
|
|
13
|
+
and serve its verification value, then `kit.verifyDomain(domain.hostname)`
|
|
14
|
+
yourself, then re-run the doctor. Only a custom domain the owner has not
|
|
15
|
+
bought yet goes to the owner.
|
|
16
|
+
|
|
17
|
+
## Merchant data
|
|
18
|
+
|
|
19
|
+
`--store` prose is preserved as merchant data, never executed or guessed into
|
|
20
|
+
inventory. To supply deterministic facts, it may instead contain JSON:
|
|
21
|
+
|
|
22
|
+
{"name":"My store","products":[{"id":"mug","title":"Mug","amount":1500}],"shipping":{"amount":500,"freeOver":7500}}
|
|
23
|
+
|
|
24
|
+
Amounts are integer USD cents; free shipping applies above freeOver. A product
|
|
25
|
+
with options (size, color) lists them as variants on one product, each with its
|
|
26
|
+
own feed ID, options and price; the store prices the chosen variant:
|
|
27
|
+
|
|
28
|
+
{"id":"tee","title":"Tee","variants":[{"id":"tee-s-black","options":{"size":"S","color":"black"},"amount":2500},
|
|
29
|
+
{"id":"tee-2xl-white","options":{"size":"2XL","color":"white"},"amount":3000}]}
|
|
30
|
+
|
|
31
|
+
Only name, products (id/title/amount/variants), and shipping (amount/freeOver) are accepted
|
|
32
|
+
as catalog facts. Without these, catalog.json is a clearly labelled Test fixture.
|
|
33
|
+
Unknown shipping uses labelled Test-fixture zero shipping, not a merchant promise.
|
|
34
|
+
Tax, returns, support, privacy and terms remain pending merchant confirmation.
|
|
35
|
+
Replace fixtures and confirm policies before any real use; Live is refused.
|
|
36
|
+
Supplied prices/titles alone do not attest stock, condition, brand or images.
|
|
37
|
+
Such merchant items stay non-purchasable by agents and out of feeds until you
|
|
38
|
+
explicitly add those verified facts in server/store.ts; no inventory is guessed.
|
|
39
|
+
|
|
40
|
+
## Server-only Test setup
|
|
41
|
+
|
|
42
|
+
Init never creates sandboxes: open https://core.getrelyon.com/get-sandbox-key
|
|
43
|
+
(signed in) for a Test key, then run `npx @relyon/store-kit init
|
|
44
|
+
--key-from-stdin`. The key is saved in an owner-only private folder outside the
|
|
45
|
+
app and every git tree, and init sets RELYON_API_KEY in .env (0600,
|
|
46
|
+
gitignored). Example env files leave it blank (`RELYON_API_KEY=`); init fills
|
|
47
|
+
it. Never paste keys into chat or read the private key file. Server
|
|
48
|
+
configuration uses the public kit server-config loader.
|
|
49
|
+
Without a key the store builds and browses; checkout visibly waits for a sandbox
|
|
50
|
+
key. Mock Test card fields never ask for real card data.
|
|
51
|
+
|
|
52
|
+
## Durable local storage
|
|
53
|
+
|
|
54
|
+
STORE_DATA_DIR defaults to .store, outside public assets and ignored by git.
|
|
55
|
+
SQLite WAL, synchronous FULL and atomic conditional writes preserve carts,
|
|
56
|
+
checkout attempts, kit state, event queue, catalog and orders over restarts.
|
|
57
|
+
Keep this directory on a persistent local volume shared by all workers on one
|
|
58
|
+
host. Ephemeral/serverless disks and replicas on separate hosts are unsupported:
|
|
59
|
+
use a shared transactional database before moving there. Do not expose this
|
|
60
|
+
directory through static hosting or put it inside public/.
|
|
61
|
+
|
|
62
|
+
The exact tokenized payment request and stable order reference are saved before
|
|
63
|
+
sending. Retries/restarts replay that request with the same idempotency key;
|
|
64
|
+
no raw card data is accepted or stored. A successful payment has one uniquely
|
|
65
|
+
associated order. Unknown outcomes keep Pay disabled; known charges with unsaved
|
|
66
|
+
orders stay order pending. Confirmation replays the saved attempt. Never delete
|
|
67
|
+
pending records to unblock checkout or start another payment for them.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { priceCart, catalog } from "../server/catalog.js";
|
|
3
|
+
const context = { protocol: "web", operation: "landing", shippingOptionId: null, agentCheckoutId: null } as const;
|
|
4
|
+
for (const product of catalog.products) {
|
|
5
|
+
// A product with options is priced as one of its variants; the store owns each variant's price.
|
|
6
|
+
const choices = product.variants?.length ? product.variants.map(v => ({ options: v.options, amount: v.amount })) : [{ options: undefined, amount: product.amount }];
|
|
7
|
+
for (const choice of choices) {
|
|
8
|
+
const cart = await priceCart([{ product_id: product.id, quantity: 2, ...(choice.options ? { options: choice.options } : {}) }], null, [], context);
|
|
9
|
+
assert.equal(cart.totals.subtotal, choice.amount * 2);
|
|
10
|
+
assert.equal(cart.totals.total, cart.totals.subtotal + cart.totals.shipping + cart.totals.tax - cart.totals.discount);
|
|
11
|
+
}
|
|
12
|
+
if (product.variants?.length) {
|
|
13
|
+
// An option the product doesn't offer is refused with the product and the option named.
|
|
14
|
+
const [name] = Object.keys(product.variants[0]!.options);
|
|
15
|
+
assert.throws(() => priceCart([{ product_id: product.id, quantity: 1, options: { ...product.variants![0]!.options, [name!]: "not-an-option" } }], null, [], context),
|
|
16
|
+
(error: Error) => error.message.includes(product.id) && error.message.includes(name!));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const first = catalog.products[0]!;
|
|
20
|
+
assert.throws(() => priceCart([{ product_id: "not-a-product", quantity: 1 }], null, [], context));
|
|
21
|
+
assert.throws(() => priceCart([{ product_id: first.id, quantity: -1, ...(first.variants?.length ? { options: first.variants[0]!.options } : {}) }], null, [], context));
|
|
22
|
+
console.log("Pricing passed: server-owned amounts and variant prices, unknown products, bad options and invalid quantities.");
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
const require = createRequire(import.meta.url);
|
|
4
|
+
const [framework, mode] = process.argv.slice(2);
|
|
5
|
+
const host = process.env.HOST || "0.0.0.0";
|
|
6
|
+
const port = process.env.PORT || "3000";
|
|
7
|
+
if (!/^\d+$/.test(port) || +port < 1 || +port > 65535) throw Error("PORT must be 1–65535.");
|
|
8
|
+
const args = framework === "next"
|
|
9
|
+
? [require.resolve("next/dist/bin/next"), mode, "--hostname", host, "--port", port]
|
|
10
|
+
: mode === "dev" ? ["--import", "tsx", "server/express.ts"] : ["dist/server/express.js"];
|
|
11
|
+
const child = spawn(process.execPath, args, { stdio: "inherit", env: { ...process.env, HOST: host, PORT: port } });
|
|
12
|
+
for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => child.kill(signal));
|
|
13
|
+
child.on("exit", code => { process.exitCode = code ?? 1; });
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import data from "../catalog.json" with { type: "json" };
|
|
2
|
+
import { StoreRefusal, type Cart, type PriceCart, type StoreProduct } from "@relyon/store-kit";
|
|
3
|
+
|
|
4
|
+
/** One choice of a product with options: its feed ID, its options (such as size and color) and its price in USD cents. */
|
|
5
|
+
export interface CatalogVariant { id: string; options: Record<string, string>; amount: number }
|
|
6
|
+
export interface CatalogProduct {
|
|
7
|
+
id: string; title: string; amount: number; currency: string; variants?: CatalogVariant[];
|
|
8
|
+
// Merchant facts, never guessed. The labelled Test mug demonstrates both.
|
|
9
|
+
category?: string; attributes?: StoreProduct["attributes"];
|
|
10
|
+
}
|
|
11
|
+
export interface Catalog {
|
|
12
|
+
name: string; fixture: boolean; products: CatalogProduct[];
|
|
13
|
+
shipping: { amount: number; freeOver?: number; fixture: boolean };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const catalog = data as unknown as Catalog;
|
|
17
|
+
|
|
18
|
+
/** The option names and their values a product's variants use, in first-seen order. */
|
|
19
|
+
export function optionValues(product: CatalogProduct): Record<string, string[]> {
|
|
20
|
+
const names: Record<string, string[]> = {};
|
|
21
|
+
for (const variant of product.variants ?? []) {
|
|
22
|
+
for (const [name, value] of Object.entries(variant.options)) {
|
|
23
|
+
const values = names[name] ??= [];
|
|
24
|
+
if (!values.includes(value)) values.push(value);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return names;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The variant a line's options choose, or a StoreRefusal naming the product and the bad option. */
|
|
31
|
+
function chosenVariant(product: CatalogProduct, options: Record<string, unknown> | undefined): CatalogVariant | null {
|
|
32
|
+
const given = { ...(options ?? {}) };
|
|
33
|
+
const keys = Object.keys(given);
|
|
34
|
+
if (!product.variants?.length) {
|
|
35
|
+
if (keys.length) throw new StoreRefusal("invalid_option", `Product "${product.id}" has no options; remove option "${keys[0]}".`);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
const names = optionValues(product);
|
|
39
|
+
for (const name of Object.keys(names)) {
|
|
40
|
+
if (!(name in given)) {
|
|
41
|
+
// An option with exactly one value never has to be named: it defaults.
|
|
42
|
+
// A multi-value option still refuses with its choices listed.
|
|
43
|
+
if (names[name]!.length === 1) given[name] = names[name]![0]!;
|
|
44
|
+
else throw new StoreRefusal("invalid_option", `Product "${product.id}" needs option "${name}" (one of: ${names[name]!.join(", ")}).`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
for (const [name, value] of Object.entries(given)) {
|
|
48
|
+
if (!names[name]) throw new StoreRefusal("invalid_option", `Product "${product.id}" has no option "${name}" (its options: ${Object.keys(names).join(", ")}).`);
|
|
49
|
+
if (typeof value !== "string" || !names[name]!.includes(value)) {
|
|
50
|
+
throw new StoreRefusal("invalid_option", `Product "${product.id}" has no ${name} ${JSON.stringify(value)} (one of: ${names[name]!.join(", ")}).`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const variant = product.variants.find(v => Object.keys(names).every(name => v.options[name] === given[name]));
|
|
54
|
+
if (!variant) throw new StoreRefusal("invalid_option", `Product "${product.id}" has no variant with options ${JSON.stringify(given)}.`);
|
|
55
|
+
return variant;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const priceCart: PriceCart = (lines, address, coupons) => {
|
|
59
|
+
if (!lines.length || lines.length > 100) throw new StoreRefusal("empty_cart", "Choose 1–100 items.");
|
|
60
|
+
if (coupons.length) throw new StoreRefusal("coupon_not_supported", "No confirmed coupon rules.");
|
|
61
|
+
if (address && address.country?.toUpperCase() !== "US") throw new StoreRefusal("shipping_unavailable", "Only US Test shipping is configured.");
|
|
62
|
+
const priced = lines.map((line, i) => {
|
|
63
|
+
const product = catalog.products.find(p => p.id === line.product_id);
|
|
64
|
+
if (!product) throw new StoreRefusal("invalid_line", `No product "${String(line.product_id).slice(0, 80)}" in this store.`);
|
|
65
|
+
if (!Number.isSafeInteger(line.quantity) || line.quantity < 1 || line.quantity > 100) {
|
|
66
|
+
throw new StoreRefusal("invalid_line", `Choose a quantity from 1 to 100 for product "${product.id}".`);
|
|
67
|
+
}
|
|
68
|
+
// The store prices the chosen variant; the kit never does.
|
|
69
|
+
const variant = chosenVariant(product, line.options);
|
|
70
|
+
const unit = variant ? variant.amount : product.amount;
|
|
71
|
+
const title = variant ? `${product.title} (${Object.values(variant.options).join(", ")})` : product.title;
|
|
72
|
+
return { id: `line_${i}`, merchant_product_id: product.id, title, quantity: line.quantity,
|
|
73
|
+
unit_amount: unit, amount: unit * line.quantity, ...(variant ? { options: { ...variant.options } } : {}) };
|
|
74
|
+
});
|
|
75
|
+
const subtotal = priced.reduce((n, p) => n + p.amount, 0);
|
|
76
|
+
const shipping = typeof catalog.shipping.freeOver === "number" && subtotal > catalog.shipping.freeOver ? 0 : catalog.shipping.amount;
|
|
77
|
+
if (subtotal + shipping > 2_147_483_647) throw new StoreRefusal("cart_too_large", "Reduce the cart before Test checkout.");
|
|
78
|
+
return { currency: "usd", lines: priced, totals: { currency: "usd", subtotal, discount: 0, shipping, tax: 0, total: subtotal + shipping } } as Cart;
|
|
79
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Types for the public reference example copied into checkout-flow.js by init.
|
|
2
|
+
import type { StoreKit, Cart, CartInputs, CardFields, PriceCart, PaymentChannel, RequestInfo } from "@relyon/store-kit";
|
|
3
|
+
export interface CheckoutView {
|
|
4
|
+
httpStatus: number;
|
|
5
|
+
body: {
|
|
6
|
+
state: "open" | "pending" | "paid" | "closed" | "not_found";
|
|
7
|
+
order_reference: string | null;
|
|
8
|
+
message: string;
|
|
9
|
+
order?: string | null;
|
|
10
|
+
error?: string;
|
|
11
|
+
payment_succeeded?: boolean;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export interface CheckoutRows {
|
|
15
|
+
get(ref: string): any;
|
|
16
|
+
insert(ref: string, record: any): Promise<void>;
|
|
17
|
+
update(ref: string, expected: string, record: any): Promise<{ updated: boolean; row: any }>;
|
|
18
|
+
confirming(): Promise<string[]>;
|
|
19
|
+
}
|
|
20
|
+
export function createCheckoutFlow(kit: StoreKit, options: {
|
|
21
|
+
priceCart: PriceCart;
|
|
22
|
+
checkouts: CheckoutRows;
|
|
23
|
+
findOrder?: (paymentId: string) => any;
|
|
24
|
+
}): {
|
|
25
|
+
price(inputs: CartInputs): Promise<Cart>;
|
|
26
|
+
open(input: { inputs: CartInputs; cart?: Cart | null; previous?: string | null; startNew?: boolean;
|
|
27
|
+
channel?: PaymentChannel; agentCheckoutId?: string | null }): Promise<{
|
|
28
|
+
orderReference: string; cart?: Cart; fields?: CardFields; view?: CheckoutView;
|
|
29
|
+
}>;
|
|
30
|
+
pay(input: { orderReference: string; paymentMethod: Record<string, unknown>; request?: Request; info?: RequestInfo }): Promise<CheckoutView>;
|
|
31
|
+
confirm(ref: string | null): Promise<CheckoutView>;
|
|
32
|
+
status(ref: string | null): Promise<CheckoutView>;
|
|
33
|
+
reconcile(options?: { minAgeMs?: number }): Promise<void>;
|
|
34
|
+
};
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { StoreRefusal, cartItemCount } from "@relyon/store-kit";
|
|
5
|
+
import { catalog, priceCart } from "./catalog.js";
|
|
6
|
+
import type { Store } from "./store.js";
|
|
7
|
+
|
|
8
|
+
export const escape = (value: unknown) => String(value ?? "").replace(/[&<>"']/g, c =>
|
|
9
|
+
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);
|
|
10
|
+
const money = (amount: number) => `$${(amount / 100).toFixed(2)}`;
|
|
11
|
+
function cookie(request: Request, name: string) {
|
|
12
|
+
const value = request.headers.get("cookie")?.split(";").map(p => p.trim()).find(p => p.startsWith(`${name}=`))?.slice(name.length + 1);
|
|
13
|
+
return value && /^[a-zA-Z0-9_-]{1,160}$/.test(value) ? value : null;
|
|
14
|
+
}
|
|
15
|
+
const cookieHeader = (request: Request, name: string, value: string) =>
|
|
16
|
+
`${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000${new URL(request.url).protocol === "https:" ? "; Secure" : ""}`;
|
|
17
|
+
const response = (html: string, status = 200, headers: Record<string, string> = {}) =>
|
|
18
|
+
new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", ...headers } });
|
|
19
|
+
const redirect = (to: string, headers: Record<string, string> = {}) => new Response(null, { status: 303, headers: { location: to, ...headers } });
|
|
20
|
+
const json = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
21
|
+
async function bodyText(request: Request) {
|
|
22
|
+
const reader = request.body?.getReader();
|
|
23
|
+
if (!reader) return "";
|
|
24
|
+
let size = 0, text = "";
|
|
25
|
+
const decoder = new TextDecoder();
|
|
26
|
+
for (;;) {
|
|
27
|
+
const part = await reader.read();
|
|
28
|
+
if (part.done) return text + decoder.decode();
|
|
29
|
+
size += part.value.byteLength;
|
|
30
|
+
if (size > 65536) { await reader.cancel(); throw new StoreRefusal("body_too_large", "Request too large.", 413); }
|
|
31
|
+
text += decoder.decode(part.value, { stream: true });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function storePage(store: Store, request: Request): Promise<Response> {
|
|
36
|
+
const { kit, storage, flow } = store;
|
|
37
|
+
const url = new URL(request.url), pathname = url.pathname;
|
|
38
|
+
const layout = (title: string, body: string) => `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
|
39
|
+
<meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)} — ${escape(catalog.name)}</title>
|
|
40
|
+
<meta name="description" content="Test storefront. Merchant policies pending.">${kit.renderDiscoveryLinks(request)}
|
|
41
|
+
<style>body{font:18px system-ui;max-width:850px;margin:40px auto;padding:0 20px;line-height:1.6}a{color:#184c91}button{padding:10px 20px;cursor:pointer}nav,footer{margin:24px 0}li{margin:18px 0}.notice{background:#fff3cd;padding:16px}input{max-width:80px;padding:8px}</style></head><body>
|
|
42
|
+
<nav><a href="/">${escape(catalog.name)}</a> · <a href="/cart">Cart</a></nav>
|
|
43
|
+
<p class="notice">Test only. ${catalog.fixture ? "Labelled Test fixture catalog, not merchant inventory. " : ""}Merchant policies and tax handling pending.</p>
|
|
44
|
+
${body}<footer>${["shipping", "returns", "support", "privacy", "terms"].map(p => `<a href="/${p}">${p}</a>`).join(" · ")}</footer></body></html>`;
|
|
45
|
+
// Fixed public filenames only: no user-supplied paths can expose server files.
|
|
46
|
+
if (pathname === "/checkout.js" && request.method === "GET") {
|
|
47
|
+
return new Response(await readFile(path.resolve("public/checkout.js"), "utf8"),
|
|
48
|
+
{ headers: { "content-type": "application/javascript", "cache-control": "no-store" } });
|
|
49
|
+
}
|
|
50
|
+
if (pathname === "/test-product.svg") return new Response('<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400"><rect width="400" height="400" fill="#eef2f5"/><text x="65" y="200" font-size="32">Test product</text></svg>', { headers: { "content-type": "image/svg+xml" } });
|
|
51
|
+
const cartId = cookie(request, "store_cart");
|
|
52
|
+
let inputs = cartId ? storage.get("cart", cartId) : null;
|
|
53
|
+
const previous = cookie(request, "store_checkout");
|
|
54
|
+
if (request.method === "POST") {
|
|
55
|
+
// Reject cross-origin mutations, including requests whose Origin is "null".
|
|
56
|
+
if (request.headers.get("origin") !== url.origin && request.headers.get("origin") !== process.env.STORE_PUBLIC_URL) return json({ error: "same_origin_required" }, 403);
|
|
57
|
+
if (pathname === "/cart") {
|
|
58
|
+
// A pending payment owns the cart until it is resolved.
|
|
59
|
+
if (previous && storage.checkouts.get(previous)?.state === "confirming") return redirect("/checkout/status");
|
|
60
|
+
const form = new URLSearchParams(await bodyText(request));
|
|
61
|
+
const id = String(form.get("product") ?? ""), quantity = Number(form.get("quantity") ?? 1);
|
|
62
|
+
// A product with options: the chosen variant's options go on the line (the store prices them).
|
|
63
|
+
const variant = catalog.products.find(p => p.id === id)?.variants?.find(v => v.id === form.get("variant"));
|
|
64
|
+
const line = { product_id: id, quantity, ...(variant ? { options: variant.options } : {}) };
|
|
65
|
+
const candidate = { lines: [line], address: null, coupons: [], shipping_option_id: null };
|
|
66
|
+
await priceCart(candidate.lines, null, [], {} as any);
|
|
67
|
+
const key = cartId ?? `cart_${randomUUID()}`;
|
|
68
|
+
const same = (p: any) => p.product_id === id && JSON.stringify(p.options ?? {}) === JSON.stringify(line.options ?? {});
|
|
69
|
+
inputs = { ...candidate, lines: [...(inputs?.lines ?? []).filter((p: any) => !same(p)), ...candidate.lines] };
|
|
70
|
+
storage.put("cart", key, inputs);
|
|
71
|
+
return redirect("/cart", { "set-cookie": cookieHeader(request, "store_cart", key) });
|
|
72
|
+
}
|
|
73
|
+
if (pathname === "/checkout/pay" || pathname === "/checkout/confirm") {
|
|
74
|
+
const body = JSON.parse(await bodyText(request)) as any;
|
|
75
|
+
// The random reference alone is not sufficient: require this shopper's HttpOnly cookie.
|
|
76
|
+
if (!previous || body.orderReference !== previous) return json({ error: "checkout_not_found" }, 404);
|
|
77
|
+
if (pathname.endsWith("/pay")) {
|
|
78
|
+
if (storage.checkouts.get(previous)?.state !== "open") {
|
|
79
|
+
const result = await flow.confirm(previous);
|
|
80
|
+
return json(result.body, result.httpStatus);
|
|
81
|
+
}
|
|
82
|
+
const pm = body.paymentMethod;
|
|
83
|
+
// Only opaque tokenized instruments (or the kit's Test mock); never accept card data.
|
|
84
|
+
// wallet_token is a Google Pay token from <relyon-card-fields>; it is passed to
|
|
85
|
+
// Relyon untouched (never scanned for card data — it is encrypted).
|
|
86
|
+
const hostedCard = pm && typeof pm === "object" && !Array.isArray(pm)
|
|
87
|
+
&& pm.type === "hosted_card"
|
|
88
|
+
&& !Object.keys(pm).some(k => !["type", "payment_session", "encrypted_data", "key_id"].includes(k))
|
|
89
|
+
&& /^ps_[a-zA-Z0-9_-]{1,150}$/.test(pm.payment_session)
|
|
90
|
+
&& typeof pm.encrypted_data === "string" && !!pm.encrypted_data && pm.encrypted_data.length <= 16384
|
|
91
|
+
&& !/^[\d -]{13,}$/.test(pm.encrypted_data)
|
|
92
|
+
&& typeof pm.key_id === "string" && /^[a-zA-Z0-9_-]{1,200}$/.test(pm.key_id);
|
|
93
|
+
const wallet = pm && typeof pm === "object" && !Array.isArray(pm)
|
|
94
|
+
&& pm.type === "wallet_token"
|
|
95
|
+
&& !Object.keys(pm).some(k => !["type", "wallet_token"].includes(k))
|
|
96
|
+
&& pm.wallet_token && typeof pm.wallet_token === "object" && !Array.isArray(pm.wallet_token)
|
|
97
|
+
&& typeof pm.wallet_token.data === "string" && !!pm.wallet_token.data && pm.wallet_token.data.length <= 16384
|
|
98
|
+
&& typeof pm.wallet_token.keyId === "string" && !!pm.wallet_token.keyId
|
|
99
|
+
&& (pm.wallet_token.cardSecurity === undefined
|
|
100
|
+
|| (pm.wallet_token.cardSecurity && typeof pm.wallet_token.cardSecurity === "object"
|
|
101
|
+
&& !Object.keys(pm.wallet_token.cardSecurity).some(k => !["dsrpCryptogram", "cavv"].includes(k))));
|
|
102
|
+
if (!hostedCard && !wallet) {
|
|
103
|
+
return json({ state: "open", message: "Use the Relyon Test card fields." }, 400);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const result = pathname.endsWith("/pay") ? await flow.pay({ orderReference: previous, paymentMethod: body.paymentMethod, request }) : await flow.confirm(previous);
|
|
107
|
+
return json(result.body, result.httpStatus);
|
|
108
|
+
}
|
|
109
|
+
return json({ error: "not_found" }, 404);
|
|
110
|
+
}
|
|
111
|
+
if (request.method !== "GET" && request.method !== "HEAD") return json({ error: "method_not_allowed" }, 405);
|
|
112
|
+
if (pathname === "/") {
|
|
113
|
+
kit.recordCrawlerVisit(request, 200);
|
|
114
|
+
return response(layout("Catalog", `<h1>${escape(catalog.name)}</h1>${kit.renderProductListJsonLd(store.products, request)}
|
|
115
|
+
<ul>${catalog.products.map(p => `<li><a href="/products/${escape(p.id)}">${escape(p.title)}</a> — ${p.variants?.length ? `from ${money(Math.min(...p.variants.map(v => v.amount)))}` : money(p.amount)}</li>`).join("")}</ul>`));
|
|
116
|
+
}
|
|
117
|
+
if (pathname.startsWith("/products/")) {
|
|
118
|
+
const p = catalog.products.find(p => pathname === `/products/${p.id}`);
|
|
119
|
+
if (!p) return response(layout("Not found", "<h1>Product not found</h1>"), 404);
|
|
120
|
+
const product = store.products.find(item => item.merchant_product_id === p.id)!;
|
|
121
|
+
const choose = p.variants?.length
|
|
122
|
+
? `<label>Option <select name="variant" required>${p.variants.map(v => `<option value="${escape(v.id)}">${escape(Object.entries(v.options).map(([k, value]) => `${k}: ${value}`).join(", "))} — ${money(v.amount)}</option>`).join("")}</select></label> `
|
|
123
|
+
: "";
|
|
124
|
+
const price = p.variants?.length ? `From ${money(Math.min(...p.variants.map(v => v.amount)))}` : money(p.amount);
|
|
125
|
+
return response(layout(p.title, `${kit.renderProductJsonLd(product, request)}<h1>${escape(p.title)}</h1><p>${price}</p>
|
|
126
|
+
<img src="/test-product.svg" alt="Test product placeholder" width="160" height="160">
|
|
127
|
+
<form action="/cart" method="post"><input type="hidden" name="product" value="${escape(p.id)}">${choose}<label>Quantity <input name="quantity" type="number" min="1" max="100" value="1" required></label> <button>Add to cart</button></form>`));
|
|
128
|
+
}
|
|
129
|
+
if (["/shipping", "/returns", "/support", "/privacy", "/terms"].includes(pathname)) {
|
|
130
|
+
const shipping = pathname === "/shipping" ? `<p>${catalog.shipping.fixture ? "Test fixture shipping only" : "Supplied US shipping"}: ${money(catalog.shipping.amount)}${"freeOver" in catalog.shipping ? `; free above ${money(Number(catalog.shipping.freeOver))}` : ""}.</p>` : "";
|
|
131
|
+
return response(layout(pathname.slice(1), `<h1>${escape(pathname.slice(1))}</h1>${shipping}<p>Pending merchant confirmation. No final merchant policy is published here.</p>`));
|
|
132
|
+
}
|
|
133
|
+
if (pathname === "/cart") {
|
|
134
|
+
if (!inputs) return response(layout("Cart", '<h1>Cart</h1><p>Your cart is empty. <a href="/">Browse products</a></p>'));
|
|
135
|
+
const cart = await flow.price(inputs);
|
|
136
|
+
return response(layout("Cart", `<h1>Cart</h1><ul>${cart.lines.map((p: any) => `<li>${escape(p.title)} × ${p.quantity}: ${money(p.amount)}</li>`).join("")}</ul>
|
|
137
|
+
<p>Shipping ${money(cart.totals.shipping)} · Total ${money(cart.totals.total)}</p><a href="/checkout">Checkout</a>`));
|
|
138
|
+
}
|
|
139
|
+
const statusPage = async () => {
|
|
140
|
+
const view = await flow.status(previous);
|
|
141
|
+
const b = view.body;
|
|
142
|
+
return response(layout("Order status", `<h1>Order status</h1><div id="checkout-status" data-order-reference="${escape(previous)}"
|
|
143
|
+
data-state="${escape(b.state)}" data-payment-succeeded="${b.payment_succeeded === true}">
|
|
144
|
+
<p id="status" role="status">${escape(b.message)}</p></div>
|
|
145
|
+
${b.state === "closed" ? '<a href="/checkout?new=1">Start a new checkout</a>' : ""}
|
|
146
|
+
<script type="module" src="/checkout.js"></script>`));
|
|
147
|
+
};
|
|
148
|
+
if (pathname === "/checkout/status") return statusPage();
|
|
149
|
+
if (pathname === "/orders/thanks") {
|
|
150
|
+
const row = previous ? storage.checkouts.get(previous) : null;
|
|
151
|
+
if (row?.state !== "paid") return redirect("/checkout/status");
|
|
152
|
+
return response(layout("Order saved", `<h1>Test order saved</h1><p>${escape(row.order)}</p>`));
|
|
153
|
+
}
|
|
154
|
+
if (pathname === "/checkout") {
|
|
155
|
+
const prior = previous ? storage.checkouts.get(previous) : null;
|
|
156
|
+
if (prior?.state === "confirming" || (prior?.state === "paid" && url.searchParams.get("new") !== "1")) return statusPage();
|
|
157
|
+
if (kit.checkoutStatus !== "ready") return response(layout("Checkout", "<h1>Checkout</h1><p>waiting for sandbox key</p><p>Never enter real card data in Test.</p>"), 503);
|
|
158
|
+
// Hand-off inputs and attribution come only from the public kit landing verifier.
|
|
159
|
+
const landing = await kit.landing(request);
|
|
160
|
+
if (landing.alreadyPaid) return response(layout("Order status", `<h1>Order status</h1><p role="status">${landing.alreadyPaid.orderPending
|
|
161
|
+
? "Your payment went through. Your order is still being placed" : "This order may already have been paid. Check the order status before paying again."}</p>`), 202);
|
|
162
|
+
// A UCP cart transfer link lands unattributed with its items (inputs) pre-filled.
|
|
163
|
+
if ((landing.attributed || landing.inputs) && landing.refusal) return response(layout("Checkout", `<p role="alert">${escape(landing.refusal.message)}</p>`), 409);
|
|
164
|
+
if (landing.inputs) inputs = landing.inputs;
|
|
165
|
+
// The checkout marker (data-relyon-cart-items, the cart's item count) is on the page empty or filled.
|
|
166
|
+
if (!inputs) return response(layout("Checkout", '<h1>Checkout</h1><div id="checkout" data-relyon-cart-items="0"><p>Your cart is empty. <a href="/">Browse products</a></p></div>'));
|
|
167
|
+
const opened: any = await flow.open({ inputs, previous, startNew: url.searchParams.get("new") === "1",
|
|
168
|
+
...(landing.attributed ? { cart: landing.cart, channel: landing.channel, agentCheckoutId: landing.agentCheckoutId } : {}) });
|
|
169
|
+
if (opened.view) return statusPage();
|
|
170
|
+
return response(layout("Checkout", `<h1>Test checkout</h1><p>Never enter real card data in Test. Total ${money(opened.cart.totals.total)}</p>
|
|
171
|
+
<div id="checkout" data-order-reference="${escape(opened.orderReference)}" data-state="open" data-relyon-cart-items="${cartItemCount(inputs)}">
|
|
172
|
+
<form id="pay" data-order-reference="${escape(opened.orderReference)}" data-new-checkout="/checkout?new=1">
|
|
173
|
+
<script>document.addEventListener("relyon-ready",event=>{event.target.dataset.relyonReady="true"},true)</script>
|
|
174
|
+
${opened.fields.html}<p id="status" role="status"></p><button type="submit" disabled>Pay Test total</button></form></div>
|
|
175
|
+
<script type="module" src="/checkout.js"></script>`), 200, { "set-cookie": cookieHeader(request, "store_checkout", opened.orderReference) });
|
|
176
|
+
}
|
|
177
|
+
return response(layout("Not found", "<h1>Not found</h1>"), 404);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function pageError(error: unknown): Response {
|
|
181
|
+
return json({ error: error instanceof StoreRefusal ? error.code : "store_unavailable",
|
|
182
|
+
message: error instanceof StoreRefusal ? error.message : "Test store request unavailable; check server configuration." },
|
|
183
|
+
error instanceof StoreRefusal ? error.status : 503);
|
|
184
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Server only. A persistent local SQLite volume is required; never put it in public/.
|
|
2
|
+
import { DatabaseSync } from "node:sqlite";
|
|
3
|
+
import { mkdirSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import type { CheckoutStateStore, CheckoutRecord, StorePaymentRecord, AgentEventStore } from "@relyon/store-kit";
|
|
7
|
+
|
|
8
|
+
export function openStorage(directory = process.env.STORE_DATA_DIR ?? path.resolve(".store")) {
|
|
9
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
10
|
+
const db = new DatabaseSync(path.join(directory, "test-store.sqlite"));
|
|
11
|
+
db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=10000;
|
|
12
|
+
CREATE TABLE IF NOT EXISTS records (kind TEXT NOT NULL, id TEXT NOT NULL, state TEXT, value TEXT NOT NULL, PRIMARY KEY(kind,id));
|
|
13
|
+
CREATE TABLE IF NOT EXISTS claims (id TEXT PRIMARY KEY, owner TEXT, expires INTEGER, done INTEGER NOT NULL DEFAULT 0);
|
|
14
|
+
CREATE TABLE IF NOT EXISTS orders (payment TEXT PRIMARY KEY, reference TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS events (seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, value TEXT NOT NULL);`);
|
|
16
|
+
const get = (kind: string, id: string): any => {
|
|
17
|
+
const row = db.prepare("SELECT value FROM records WHERE kind=? AND id=?").get(kind, id);
|
|
18
|
+
return row ? JSON.parse(String(row.value)) : null;
|
|
19
|
+
};
|
|
20
|
+
const put = (kind: string, id: string, value: any) => {
|
|
21
|
+
db.prepare("INSERT INTO records VALUES (?,?,?,?) ON CONFLICT(kind,id) DO UPDATE SET state=excluded.state,value=excluded.value")
|
|
22
|
+
.run(kind, id, value.state ?? null, JSON.stringify(value));
|
|
23
|
+
};
|
|
24
|
+
const state: CheckoutStateStore = {
|
|
25
|
+
get: (protocol, id) => get("kit", `${protocol}:${id}`),
|
|
26
|
+
put: record => put("kit", `${record.protocol}:${record.sessionId}`, record),
|
|
27
|
+
byAgentCheckoutId(id) {
|
|
28
|
+
const row = db.prepare("SELECT value FROM records WHERE kind='kit' AND json_extract(value,'$.agentCheckoutId')=? ORDER BY json_extract(value,'$.updatedAt') DESC LIMIT 1").get(id);
|
|
29
|
+
return row ? JSON.parse(String(row.value)) as CheckoutRecord : null;
|
|
30
|
+
},
|
|
31
|
+
claimOrder(id, options) {
|
|
32
|
+
const o = options ?? { claimId: "", now: Date.now(), leaseMs: 120000 };
|
|
33
|
+
return db.prepare(`INSERT INTO claims VALUES (?,?,?,0) ON CONFLICT(id) DO UPDATE SET owner=excluded.owner,expires=excluded.expires
|
|
34
|
+
WHERE claims.done=0 AND claims.expires<=?`).run(id, o.claimId, o.now + o.leaseMs, o.now).changes === 1;
|
|
35
|
+
},
|
|
36
|
+
completeOrder(id, owner) { db.prepare("UPDATE claims SET done=1,expires=NULL WHERE id=? AND owner=?").run(id, owner ?? ""); },
|
|
37
|
+
releaseOrder(id, owner) { db.prepare("DELETE FROM claims WHERE id=? AND owner=? AND done=0").run(id, owner ?? ""); },
|
|
38
|
+
orderClaimStatus(id, now) {
|
|
39
|
+
const row = db.prepare("SELECT done,expires FROM claims WHERE id=?").get(id);
|
|
40
|
+
return row?.done ? "created" : row && Number(row.expires) > now ? "creating" : null;
|
|
41
|
+
},
|
|
42
|
+
getStorePayment: id => get("payment", id) as StorePaymentRecord | null,
|
|
43
|
+
putStorePayment(id, record) {
|
|
44
|
+
// A stale writer can never erase durable evidence of a charge.
|
|
45
|
+
db.prepare(`INSERT INTO records VALUES ('payment',?,?,?) ON CONFLICT(kind,id) DO UPDATE SET state=excluded.state,value=excluded.value
|
|
46
|
+
WHERE CASE excluded.state WHEN 'order_created' THEN 4 WHEN 'order_pending' THEN 3 WHEN 'declined' THEN 2 ELSE 1 END
|
|
47
|
+
>= CASE records.state WHEN 'order_created' THEN 4 WHEN 'order_pending' THEN 3 WHEN 'declined' THEN 2 ELSE 1 END`)
|
|
48
|
+
.run(id, record.state, JSON.stringify(record));
|
|
49
|
+
},
|
|
50
|
+
claimHandoffToken(id, options) {
|
|
51
|
+
return db.prepare("INSERT INTO claims VALUES (?,NULL,?,1) ON CONFLICT(id) DO UPDATE SET expires=excluded.expires WHERE claims.expires<=?")
|
|
52
|
+
.run(`handoff:${id}`, options.expiresAt, options.now).changes === 1;
|
|
53
|
+
},
|
|
54
|
+
setHandoffToken(protocol, id, token, options) {
|
|
55
|
+
const key = `${protocol}:${id}`;
|
|
56
|
+
db.exec("BEGIN IMMEDIATE");
|
|
57
|
+
try {
|
|
58
|
+
const current = get("kit", key);
|
|
59
|
+
const canonical = (value: any): string => JSON.stringify(value, (_key, v) =>
|
|
60
|
+
v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map(k => [k, v[k]])) : v);
|
|
61
|
+
const matches = current && (current.handoffToken ?? null) === options.expectedToken
|
|
62
|
+
&& canonical(current.inputs) === canonical(options.expectedInputs);
|
|
63
|
+
if (matches) put("kit", key, { ...current, handoffToken: token, handoffTokenAt: options.now, updatedAt: options.now });
|
|
64
|
+
db.exec("COMMIT");
|
|
65
|
+
return !!matches;
|
|
66
|
+
} catch (error) { db.exec("ROLLBACK"); throw error; }
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
const events: AgentEventStore = {
|
|
70
|
+
append(event) { db.prepare("INSERT OR IGNORE INTO events(id,value) VALUES (?,?)").run(event.id, JSON.stringify(event)); },
|
|
71
|
+
peek(limit) { return db.prepare("SELECT value FROM events ORDER BY seq LIMIT ?").all(limit).map(r => JSON.parse(String(r.value))); },
|
|
72
|
+
remove(ids) { const del = db.prepare("DELETE FROM events WHERE id=?"); for (const id of ids) del.run(id); },
|
|
73
|
+
size() { return Number(db.prepare("SELECT count(*) AS n FROM events").get()!.n); },
|
|
74
|
+
};
|
|
75
|
+
const checkouts = {
|
|
76
|
+
get: (id: string) => get("checkout", id),
|
|
77
|
+
async insert(id: string, value: any) {
|
|
78
|
+
db.prepare("INSERT INTO records VALUES ('checkout',?,?,?)").run(id, value.state, JSON.stringify(value));
|
|
79
|
+
},
|
|
80
|
+
async update(id: string, expected: string, value: any) {
|
|
81
|
+
db.exec("BEGIN IMMEDIATE");
|
|
82
|
+
try {
|
|
83
|
+
const current = get("checkout", id);
|
|
84
|
+
if (current?.state !== expected) { db.exec("COMMIT"); return { updated: false, row: current }; }
|
|
85
|
+
// Parallel replies must never erase evidence that the payment succeeded,
|
|
86
|
+
// nor close a paid-but-unsaved checkout as though it charged nothing.
|
|
87
|
+
const next = current.paid && value.state === "closed" ? current : {
|
|
88
|
+
...value, ...(current.paid ? { paid: true, paymentId: current.paymentId } : {}),
|
|
89
|
+
};
|
|
90
|
+
const changed = db.prepare("UPDATE records SET state=?,value=? WHERE kind='checkout' AND id=? AND state=?")
|
|
91
|
+
.run(next.state, JSON.stringify(next), id, expected).changes === 1;
|
|
92
|
+
const row = get("checkout", id);
|
|
93
|
+
db.exec("COMMIT");
|
|
94
|
+
return { updated: changed, row };
|
|
95
|
+
} catch (error) { db.exec("ROLLBACK"); throw error; }
|
|
96
|
+
},
|
|
97
|
+
async confirming() { return db.prepare("SELECT id FROM records WHERE kind='checkout' AND state='confirming'").all().map(r => String(r.id)); },
|
|
98
|
+
};
|
|
99
|
+
const findOrder = (payment: string): any => {
|
|
100
|
+
const row = db.prepare("SELECT value FROM orders WHERE payment=?").get(payment);
|
|
101
|
+
return row ? JSON.parse(String(row.value)) : null;
|
|
102
|
+
};
|
|
103
|
+
// Store an independent cart-token key, stable over restarts and shared by workers.
|
|
104
|
+
db.prepare("INSERT OR IGNORE INTO records VALUES ('config','cart-secret',NULL,?)").run(JSON.stringify(randomBytes(32).toString("hex")));
|
|
105
|
+
return { db, get, put, state, events, checkouts, findOrder, cartSecret: get("config", "cart-secret") as string,
|
|
106
|
+
createOrder(cart: any, payment: any) {
|
|
107
|
+
const id = `order_${createHash("sha256").update(payment.id).digest("hex").slice(0, 24)}`;
|
|
108
|
+
const order = { id, paymentId: payment.id, total: cart.totals.total };
|
|
109
|
+
db.prepare("INSERT INTO orders VALUES (?,?,?) ON CONFLICT(payment) DO NOTHING")
|
|
110
|
+
.run(payment.id, typeof payment.order_reference === "string" ? payment.order_reference : id, JSON.stringify(order));
|
|
111
|
+
return findOrder(payment.id);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Never import this module into a browser component.
|
|
2
|
+
import { createStoreKit, type StoreCatalogProduct } from "@relyon/store-kit";
|
|
3
|
+
import { loadTestConfig } from "@relyon/store-kit/server-config";
|
|
4
|
+
import { catalog, optionValues, priceCart } from "./catalog.js";
|
|
5
|
+
import { openStorage } from "./storage.js";
|
|
6
|
+
import { createCheckoutFlow } from "./checkout-flow.js";
|
|
7
|
+
|
|
8
|
+
export async function createStore() {
|
|
9
|
+
const config = await loadTestConfig({ project: process.cwd() });
|
|
10
|
+
// Live needs the double opt-in: a rly_live_… key AND RELYON_LIVE=true (relyon.live). Test stays the default.
|
|
11
|
+
const liveRequested = process.env.RELYON_LIVE?.trim().toLowerCase() === "true";
|
|
12
|
+
const expectedPrefix = liveRequested ? "rly_live_" : "rly_test_";
|
|
13
|
+
if (config.apiKey && !config.apiKey.startsWith(expectedPrefix)) {
|
|
14
|
+
throw Error(liveRequested ? "RELYON_LIVE=true needs a Live secret key (rly_live_…)." : "This template accepts Test keys only.");
|
|
15
|
+
}
|
|
16
|
+
const storage = openStorage();
|
|
17
|
+
const hostnames = (process.env.STORE_HOSTNAMES ?? (process.env.STORE_PUBLIC_URL ? new URL(process.env.STORE_PUBLIC_URL).hostname : "localhost"))
|
|
18
|
+
.split(",").map(s => s.trim()).filter(Boolean);
|
|
19
|
+
const products: StoreCatalogProduct[] = catalog.products.map(p => ({
|
|
20
|
+
merchant_product_id: p.id, title: p.title, description: catalog.fixture ? "Clearly labelled Test fixture; not merchant inventory." : p.title,
|
|
21
|
+
url: `/products/${encodeURIComponent(p.id)}`,
|
|
22
|
+
from_price: { amount: p.amount, currency: "USD" },
|
|
23
|
+
...(p.category !== undefined ? { category: p.category } : {}),
|
|
24
|
+
...(p.attributes !== undefined ? { attributes: p.attributes } : {}),
|
|
25
|
+
agent: { visible: true, purchasable: catalog.fixture },
|
|
26
|
+
// Fixture attestations are not facts about merchant-supplied inventory.
|
|
27
|
+
...(catalog.fixture ? { images: ["/test-product.svg"], availability: "in_stock" as const,
|
|
28
|
+
brand: "Test fixture goods", mpn: p.id } : {}),
|
|
29
|
+
feed: { exactPrice: { amount: p.amount, currency: "USD" },
|
|
30
|
+
...(catalog.fixture ? { condition: "new" as const, ownBrand: true } : {}),
|
|
31
|
+
// A product with options lists each variant (feed ID, options, price); agents buy one of them.
|
|
32
|
+
...(p.variants?.length ? { variants: p.variants.map(v => ({ id: v.id, options: v.options, exactPrice: { amount: v.amount, currency: "USD" } })) } : {}) },
|
|
33
|
+
...(p.variants?.length ? { configurable: true, options: optionValues(p),
|
|
34
|
+
from_price: { amount: Math.min(...p.variants.map(v => v.amount)), currency: "USD" } } : {}),
|
|
35
|
+
} as StoreCatalogProduct));
|
|
36
|
+
const source = {
|
|
37
|
+
listProducts: ({ limit, cursor, query }: { limit: number; cursor?: string; query?: string }) => {
|
|
38
|
+
const start = Number(cursor ?? 0);
|
|
39
|
+
const list = products.filter(p => !query || p.title.toLowerCase().includes(query.toLowerCase()));
|
|
40
|
+
return { products: list.slice(start, start + limit), nextCursor: start + limit < list.length ? String(start + limit) : null };
|
|
41
|
+
},
|
|
42
|
+
getProduct: (id: string) => products.find(p => p.merchant_product_id === id) ?? null,
|
|
43
|
+
};
|
|
44
|
+
const kit = createStoreKit({
|
|
45
|
+
relyon: { apiKey: config.apiKey, baseUrl: process.env.RELYON_BASE_URL ?? "https://core.getrelyon.com/api", waitingForSandboxKey: !liveRequested,
|
|
46
|
+
...(liveRequested ? { live: true } : {}) },
|
|
47
|
+
store: { name: catalog.name, description: "Test storefront. Merchant policies pending.", hostnames,
|
|
48
|
+
...(process.env.STORE_PUBLIC_URL ? { publicUrl: process.env.STORE_PUBLIC_URL } : {}) },
|
|
49
|
+
priceCart, createOrder: storage.createOrder, findOrderByPaymentId: storage.findOrder,
|
|
50
|
+
state: storage.state, events: { store: storage.events },
|
|
51
|
+
cartTokens: { secret: storage.cartSecret },
|
|
52
|
+
catalog: { initial: products, source, persistence: {
|
|
53
|
+
load: () => storage.get("catalog", "current"), save: value => storage.put("catalog", "current", value),
|
|
54
|
+
} },
|
|
55
|
+
feeds: { formats: ["openai", "google", "microsoft"] },
|
|
56
|
+
// robots.txt is served by default (AI search and shopping crawlers allowed); robots: false opts out.
|
|
57
|
+
rules: { webhookSecret: config.webhookSecret },
|
|
58
|
+
logger: { warn: message => console.warn(message), error: message => console.error(message) },
|
|
59
|
+
});
|
|
60
|
+
await kit.start();
|
|
61
|
+
const flow = createCheckoutFlow(kit, { priceCart, checkouts: storage.checkouts, findOrder: storage.findOrder });
|
|
62
|
+
const timer = setInterval(() => { void flow.reconcile().catch(() => console.error("Test checkout reconciliation pending.")); }, 60000);
|
|
63
|
+
timer.unref();
|
|
64
|
+
return { kit, storage, flow, products, source,
|
|
65
|
+
async stop() { clearInterval(timer); await kit.stop(); storage.db.close(); } };
|
|
66
|
+
}
|
|
67
|
+
export type Store = Awaited<ReturnType<typeof createStore>>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import { storeKitMiddleware, writeResponse } from "@relyon/store-kit/express";
|
|
3
|
+
import { createStore } from "./store.js";
|
|
4
|
+
import { storePage, pageError } from "./pages.js";
|
|
5
|
+
const store = await createStore();
|
|
6
|
+
const app = express();
|
|
7
|
+
app.disable("x-powered-by");
|
|
8
|
+
app.use(storeKitMiddleware(store.kit)); // Raw protocol bodies, before all parsers.
|
|
9
|
+
app.use(express.raw({ type: () => true, limit: "64kb" }));
|
|
10
|
+
app.use(async (req, res) => {
|
|
11
|
+
try {
|
|
12
|
+
const origin = `${req.protocol}://${req.headers.host}`;
|
|
13
|
+
const request = new Request(new URL(req.originalUrl, origin), { method: req.method,
|
|
14
|
+
headers: req.headers as HeadersInit,
|
|
15
|
+
...(!["GET", "HEAD"].includes(req.method) && req.body?.length ? { body: req.body } : {}) });
|
|
16
|
+
await writeResponse(res, await storePage(store, request));
|
|
17
|
+
} catch (error) { await writeResponse(res, pageError(error)); }
|
|
18
|
+
});
|
|
19
|
+
const server = app.listen(Number(process.env.PORT ?? 3000), process.env.HOST ?? "0.0.0.0", () => console.log("Test store ready."));
|
|
20
|
+
for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => server.close(() => { void store.stop().finally(() => process.exit()); }));
|