@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.
Files changed (225) hide show
  1. package/AGENTS.md +75 -0
  2. package/CHANGELOG.md +1053 -0
  3. package/LICENSE +21 -0
  4. package/QUICKSTART.md +239 -0
  5. package/README.md +117 -2
  6. package/dist/adapters/express.d.ts +39 -0
  7. package/dist/adapters/express.js +106 -0
  8. package/dist/adapters/hono.d.ts +16 -0
  9. package/dist/adapters/hono.js +15 -0
  10. package/dist/adapters/next.d.ts +29 -0
  11. package/dist/adapters/next.js +38 -0
  12. package/dist/agent-card.d.ts +14 -0
  13. package/dist/agent-card.js +58 -0
  14. package/dist/agent-docs.d.ts +36 -0
  15. package/dist/agent-docs.js +78 -0
  16. package/dist/agent-hooks.d.ts +66 -0
  17. package/dist/agent-hooks.js +280 -0
  18. package/dist/agents.d.ts +24 -0
  19. package/dist/agents.js +120 -0
  20. package/dist/api-key.d.ts +6 -0
  21. package/dist/api-key.js +33 -0
  22. package/dist/cache.d.ts +46 -0
  23. package/dist/cache.js +86 -0
  24. package/dist/cart-tokens.d.ts +31 -0
  25. package/dist/cart-tokens.js +58 -0
  26. package/dist/cart-transfer.d.ts +95 -0
  27. package/dist/cart-transfer.js +387 -0
  28. package/dist/catalog-enrichment.d.ts +6 -0
  29. package/dist/catalog-enrichment.js +71 -0
  30. package/dist/catalog-reads.d.ts +126 -0
  31. package/dist/catalog-reads.js +104 -0
  32. package/dist/catalog.d.ts +78 -0
  33. package/dist/catalog.js +288 -0
  34. package/dist/charge-claims.d.ts +11 -0
  35. package/dist/charge-claims.js +47 -0
  36. package/dist/check.d.ts +44 -0
  37. package/dist/check.js +152 -0
  38. package/dist/checklist-manifest.d.ts +72 -0
  39. package/dist/checklist-manifest.js +341 -0
  40. package/dist/checkout.d.ts +222 -0
  41. package/dist/checkout.js +353 -0
  42. package/dist/cli.d.ts +2 -0
  43. package/dist/cli.js +727 -0
  44. package/dist/confirmation.d.ts +78 -0
  45. package/dist/confirmation.js +124 -0
  46. package/dist/context.d.ts +81 -0
  47. package/dist/context.js +10 -0
  48. package/dist/discovery.d.ts +151 -0
  49. package/dist/discovery.js +346 -0
  50. package/dist/doctor-cart-transfer.d.ts +33 -0
  51. package/dist/doctor-cart-transfer.js +186 -0
  52. package/dist/doctor-catalog.d.ts +8 -0
  53. package/dist/doctor-catalog.js +47 -0
  54. package/dist/doctor-evidence.d.ts +22 -0
  55. package/dist/doctor-evidence.js +57 -0
  56. package/dist/doctor-merchant.d.ts +48 -0
  57. package/dist/doctor-merchant.js +74 -0
  58. package/dist/doctor-source.d.ts +5 -0
  59. package/dist/doctor-source.js +142 -0
  60. package/dist/doctor-variants.d.ts +70 -0
  61. package/dist/doctor-variants.js +102 -0
  62. package/dist/doctor.d.ts +215 -0
  63. package/dist/doctor.js +1689 -0
  64. package/dist/events.d.ts +95 -0
  65. package/dist/events.js +200 -0
  66. package/dist/feed-mapping.d.ts +114 -0
  67. package/dist/feed-mapping.js +152 -0
  68. package/dist/feed-values.d.ts +13 -0
  69. package/dist/feed-values.js +40 -0
  70. package/dist/feeds.d.ts +104 -0
  71. package/dist/feeds.js +366 -0
  72. package/dist/identify.d.ts +102 -0
  73. package/dist/identify.js +124 -0
  74. package/dist/identity.d.ts +37 -0
  75. package/dist/identity.js +54 -0
  76. package/dist/index.d.ts +42 -0
  77. package/dist/index.js +41 -0
  78. package/dist/init.d.ts +157 -0
  79. package/dist/init.js +912 -0
  80. package/dist/kit-config.d.ts +19 -0
  81. package/dist/kit-config.js +43 -0
  82. package/dist/kit-environment.d.ts +20 -0
  83. package/dist/kit-environment.js +32 -0
  84. package/dist/kit-updates.d.ts +47 -0
  85. package/dist/kit-updates.js +77 -0
  86. package/dist/kit-version-project.d.ts +18 -0
  87. package/dist/kit-version-project.js +214 -0
  88. package/dist/kit-version.d.ts +37 -0
  89. package/dist/kit-version.js +162 -0
  90. package/dist/kit.d.ts +516 -0
  91. package/dist/kit.js +1309 -0
  92. package/dist/layers/pages.d.ts +3 -0
  93. package/dist/layers/pages.js +5 -0
  94. package/dist/layers/payments.d.ts +7 -0
  95. package/dist/layers/payments.js +9 -0
  96. package/dist/layers/products.d.ts +10 -0
  97. package/dist/layers/products.js +13 -0
  98. package/dist/live.d.ts +13 -0
  99. package/dist/live.js +52 -0
  100. package/dist/mcp.d.ts +270 -0
  101. package/dist/mcp.js +312 -0
  102. package/dist/next-steps.d.ts +101 -0
  103. package/dist/next-steps.js +257 -0
  104. package/dist/order-pending.d.ts +57 -0
  105. package/dist/order-pending.js +127 -0
  106. package/dist/orders.d.ts +12 -0
  107. package/dist/orders.js +21 -0
  108. package/dist/payments-init.d.ts +19 -0
  109. package/dist/payments-init.js +70 -0
  110. package/dist/payments-routes.d.ts +54 -0
  111. package/dist/payments-routes.js +123 -0
  112. package/dist/payments.d.ts +165 -0
  113. package/dist/payments.js +192 -0
  114. package/dist/pnpm-workspace.d.ts +58 -0
  115. package/dist/pnpm-workspace.js +250 -0
  116. package/dist/policies.d.ts +111 -0
  117. package/dist/policies.js +317 -0
  118. package/dist/preview-hosts.d.ts +64 -0
  119. package/dist/preview-hosts.js +175 -0
  120. package/dist/private-config.d.ts +169 -0
  121. package/dist/private-config.js +820 -0
  122. package/dist/progress.d.ts +54 -0
  123. package/dist/progress.js +153 -0
  124. package/dist/protocol-inputs.d.ts +22 -0
  125. package/dist/protocol-inputs.js +151 -0
  126. package/dist/public-origin.d.ts +50 -0
  127. package/dist/public-origin.js +180 -0
  128. package/dist/refusals.d.ts +86 -0
  129. package/dist/refusals.js +157 -0
  130. package/dist/relay.d.ts +107 -0
  131. package/dist/relay.js +655 -0
  132. package/dist/release-notes.d.ts +2 -0
  133. package/dist/release-notes.js +290 -0
  134. package/dist/relyon-cart-tokens.d.ts +101 -0
  135. package/dist/relyon-cart-tokens.js +521 -0
  136. package/dist/relyon.d.ts +141 -0
  137. package/dist/relyon.js +238 -0
  138. package/dist/robots.d.ts +27 -0
  139. package/dist/robots.js +127 -0
  140. package/dist/rules.d.ts +144 -0
  141. package/dist/rules.js +347 -0
  142. package/dist/sdk/generated/public-api.d.ts +4816 -0
  143. package/dist/sdk/generated/public-api.js +1 -0
  144. package/dist/sdk/index.d.ts +24 -0
  145. package/dist/sdk/index.js +34 -0
  146. package/dist/sdk/signatures.d.ts +17 -0
  147. package/dist/sdk/signatures.js +33 -0
  148. package/dist/setup.d.ts +37 -0
  149. package/dist/setup.js +94 -0
  150. package/dist/signatures.d.ts +112 -0
  151. package/dist/signatures.js +443 -0
  152. package/dist/state.d.ts +185 -0
  153. package/dist/state.js +96 -0
  154. package/dist/store-payments.d.ts +48 -0
  155. package/dist/store-payments.js +143 -0
  156. package/dist/structured-fields.d.ts +26 -0
  157. package/dist/structured-fields.js +200 -0
  158. package/dist/templates.d.ts +19 -0
  159. package/dist/templates.js +193 -0
  160. package/dist/test-checkout-command.d.ts +32 -0
  161. package/dist/test-checkout-command.js +161 -0
  162. package/dist/test-checkout.d.ts +88 -0
  163. package/dist/test-checkout.js +292 -0
  164. package/dist/types.d.ts +103 -0
  165. package/dist/types.js +18 -0
  166. package/dist/ucp-versions.d.ts +57 -0
  167. package/dist/ucp-versions.js +129 -0
  168. package/dist/util.d.ts +23 -0
  169. package/dist/util.js +68 -0
  170. package/dist/variants.d.ts +67 -0
  171. package/dist/variants.js +146 -0
  172. package/dist/version.d.ts +9 -0
  173. package/dist/version.js +10 -0
  174. package/dist/waiting.d.ts +43 -0
  175. package/dist/waiting.js +57 -0
  176. package/dist/webhook-command.d.ts +48 -0
  177. package/dist/webhook-command.js +367 -0
  178. package/dist/webhook-registration.d.ts +47 -0
  179. package/dist/webhook-registration.js +69 -0
  180. package/dist/webmcp-schema.d.ts +14 -0
  181. package/dist/webmcp-schema.js +140 -0
  182. package/dist/webmcp-script.d.ts +3 -0
  183. package/dist/webmcp-script.js +176 -0
  184. package/dist/webmcp-store.d.ts +102 -0
  185. package/dist/webmcp-store.js +116 -0
  186. package/dist/webmcp.d.ts +242 -0
  187. package/dist/webmcp.js +866 -0
  188. package/dist/wire-names.d.ts +85 -0
  189. package/dist/wire-names.js +109 -0
  190. package/package.json +118 -4
  191. package/release-notes.json +290 -0
  192. package/scripts/install-notice.cjs +7 -0
  193. package/skills/relyon-agents/SKILL.md +327 -0
  194. package/skills/relyon-catalog/SKILL.md +499 -0
  195. package/skills/relyon-catalog/references/example-store.md +218 -0
  196. package/skills/relyon-checkout/SKILL.md +603 -0
  197. package/skills/relyon-checkout/references/checkout-flow.md +257 -0
  198. package/skills/relyon-checkout/references/checkout-page.md +315 -0
  199. package/skills/relyon-go-live/SKILL.md +344 -0
  200. package/skills/relyon-orders/SKILL.md +191 -0
  201. package/skills/relyon-orders/references/webhook-receiver.md +113 -0
  202. package/skills/relyon-payments/SKILL.md +117 -0
  203. package/skills/relyon-setup/SKILL.md +1061 -0
  204. package/skills/relyon-setup/references/QUICKSTART.md +239 -0
  205. package/skills/relyon-setup/references/durable-state.md +209 -0
  206. package/skills/relyon-setup/references/express-server.md +388 -0
  207. package/skills/relyon-setup/references/next-app-router.md +251 -0
  208. package/templates/common/STORE-README.md +67 -0
  209. package/templates/common/gitignore +8 -0
  210. package/templates/common/scripts/check-pricing.ts +22 -0
  211. package/templates/common/scripts/serve.mjs +13 -0
  212. package/templates/common/server/catalog.ts +79 -0
  213. package/templates/common/server/checkout-flow.d.ts +34 -0
  214. package/templates/common/server/pages.ts +184 -0
  215. package/templates/common/server/storage.ts +114 -0
  216. package/templates/common/server/store.ts +67 -0
  217. package/templates/express/server/express.ts +20 -0
  218. package/templates/express/tsconfig.build.json +6 -0
  219. package/templates/express/tsconfig.json +9 -0
  220. package/templates/next/app/[[...path]]/route.ts +24 -0
  221. package/templates/next/next.config.mjs +19 -0
  222. package/templates/next/tsconfig.json +12 -0
  223. package/templates/payments/express.ts +39 -0
  224. package/templates/payments/next.ts +38 -0
  225. package/templates/payments/node.ts +39 -0
@@ -0,0 +1,443 @@
1
+ import { createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
2
+ import { StructuredFieldError, isInnerList, isToken, parseDictionary, parseItem, serializeInnerList, serializeParameters, } from "./structured-fields.js";
3
+ /**
4
+ * Web Bot Auth directory origins the kit trusts by default, and the agent each
5
+ * one names. Only OpenAI's published ChatGPT agent directory is listed; confirm
6
+ * it against OpenAI's documentation before relying on it in Live.
7
+ */
8
+ export const DEFAULT_WEB_BOT_AUTH_DIRECTORIES = Object.freeze({
9
+ "https://chatgpt.com": "chatgpt",
10
+ });
11
+ export const WEB_BOT_AUTH_DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
12
+ export const WEB_BOT_AUTH_TAG = "web-bot-auth";
13
+ export const NETWORK_TAGS = ["agent-browser-auth", "agent-payer-auth"];
14
+ /** One process's nonces, bounded. When full of live nonces it refuses new ones rather than forgetting a live one. */
15
+ export class MemoryNonceStore {
16
+ maxEntries;
17
+ entries = new Map();
18
+ constructor(maxEntries = 50_000) {
19
+ this.maxEntries = maxEntries;
20
+ }
21
+ claim(scope, nonce, expiresAtMs, nowMs) {
22
+ const key = `${scope}\u0000${nonce}`;
23
+ const existing = this.entries.get(key);
24
+ if (existing !== undefined && existing > nowMs)
25
+ return false;
26
+ if (existing === undefined && this.entries.size >= this.maxEntries) {
27
+ for (const [k, until] of this.entries)
28
+ if (until <= nowMs)
29
+ this.entries.delete(k);
30
+ if (this.entries.size >= this.maxEntries)
31
+ return false;
32
+ }
33
+ this.entries.set(key, expiresAtMs);
34
+ return true;
35
+ }
36
+ }
37
+ /** RFC 7638 thumbprint of an Ed25519 key: the Web Bot Auth keyid. */
38
+ export function ed25519Thumbprint(x) {
39
+ return createHash("sha256").update(JSON.stringify({ crv: "Ed25519", kty: "OKP", x })).digest("base64url");
40
+ }
41
+ /** Keeps only Ed25519 public signing keys, indexed by kid and by thumbprint. Throws when it's not a JWKS. */
42
+ export function parseEd25519Jwks(document) {
43
+ if (!document || typeof document !== "object" || !Array.isArray(document.keys)) {
44
+ throw new Error("not a JWKS document");
45
+ }
46
+ const keys = new Map();
47
+ for (const raw of document.keys) {
48
+ if (!raw || typeof raw !== "object")
49
+ continue;
50
+ const jwk = raw;
51
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string" || jwk.d !== undefined)
52
+ continue;
53
+ if (jwk.use !== undefined && jwk.use !== "sig")
54
+ continue;
55
+ if (Buffer.from(jwk.x, "base64url").length !== 32)
56
+ continue;
57
+ let publicKey;
58
+ try {
59
+ publicKey = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: jwk.x }, format: "jwk" });
60
+ }
61
+ catch {
62
+ continue;
63
+ }
64
+ const thumbprint = ed25519Thumbprint(jwk.x);
65
+ for (const id of new Set([typeof jwk.kid === "string" && jwk.kid ? jwk.kid : thumbprint, thumbprint])) {
66
+ if (id.length <= 200 && !keys.has(id))
67
+ keys.set(id, { keyId: id, publicKey });
68
+ }
69
+ }
70
+ return keys;
71
+ }
72
+ /** One key directory: TTL cache, one shared fetch, rate-limited refreshes, no redirects, size and time caps. */
73
+ class KeyDirectory {
74
+ url;
75
+ o;
76
+ now;
77
+ keys = null;
78
+ fetchedAt = 0;
79
+ lastAttempt = null;
80
+ inflight = null;
81
+ fetches = 0;
82
+ constructor(url, o, now) {
83
+ this.url = url;
84
+ this.o = o;
85
+ this.now = now;
86
+ }
87
+ fresh() { return this.keys !== null && this.now() - this.fetchedAt < this.o.directoryTtlMs; }
88
+ async find(keyId) {
89
+ if (this.fresh()) {
90
+ const key = this.keys.get(keyId);
91
+ if (key)
92
+ return { status: "found", key };
93
+ }
94
+ const may = this.inflight !== null || this.lastAttempt === null || this.now() - this.lastAttempt >= this.o.directoryRefreshIntervalMs;
95
+ if (may)
96
+ await this.refresh();
97
+ if (!this.fresh())
98
+ return { status: "unavailable" };
99
+ const key = this.keys.get(keyId);
100
+ return key ? { status: "found", key } : { status: "unknown" };
101
+ }
102
+ refresh() {
103
+ if (!this.inflight) {
104
+ this.lastAttempt = this.now();
105
+ this.fetches += 1;
106
+ this.inflight = this.load().finally(() => { this.inflight = null; });
107
+ }
108
+ return this.inflight;
109
+ }
110
+ async load() {
111
+ const controller = new AbortController();
112
+ let timer;
113
+ const timeout = new Promise((_, reject) => {
114
+ timer = setTimeout(() => { controller.abort(); reject(new Error("directory timed out")); }, this.o.directoryTimeoutMs);
115
+ });
116
+ try {
117
+ const response = await Promise.race([this.o.fetch(this.url, {
118
+ method: "GET",
119
+ headers: { accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json" },
120
+ redirect: "error",
121
+ signal: controller.signal,
122
+ }), timeout]);
123
+ if (response.status !== 200)
124
+ throw new Error(`HTTP ${response.status}`);
125
+ if (Number(response.headers.get("content-length") ?? "0") > this.o.maxDirectoryBytes)
126
+ throw new Error("directory too large");
127
+ const body = await Promise.race([readCapped(response, this.o.maxDirectoryBytes), timeout]);
128
+ this.keys = parseEd25519Jwks(JSON.parse(body));
129
+ this.fetchedAt = this.now();
130
+ }
131
+ catch {
132
+ // Keep what's cached; lookups report unavailable once it's stale.
133
+ }
134
+ finally {
135
+ clearTimeout(timer);
136
+ }
137
+ }
138
+ }
139
+ async function readCapped(response, max) {
140
+ if (!response.body)
141
+ return "";
142
+ const reader = response.body.getReader();
143
+ const chunks = [];
144
+ let total = 0;
145
+ for (;;) {
146
+ const { done, value } = await reader.read();
147
+ if (done)
148
+ break;
149
+ total += value.byteLength;
150
+ if (total > max) {
151
+ await reader.cancel().catch(() => undefined);
152
+ throw new Error("directory too large");
153
+ }
154
+ chunks.push(value);
155
+ }
156
+ return Buffer.concat(chunks).toString("utf8");
157
+ }
158
+ const DERIVED = new Set(["@method", "@authority", "@path", "@query", "@target-uri", "@scheme", "@request-target"]);
159
+ function componentValue(target, name, params) {
160
+ if (params.size > 0)
161
+ throw new SignatureError("unsupported_component", `parameters on ${name}`);
162
+ if (name !== name.toLowerCase())
163
+ throw new SignatureError("malformed", `component ${name} is not lower case`);
164
+ if (name.startsWith("@")) {
165
+ if (!DERIVED.has(name))
166
+ throw new SignatureError("unsupported_component", name);
167
+ const path = target.path || "/";
168
+ const query = target.query === null ? "" : `?${target.query}`;
169
+ switch (name) {
170
+ case "@method": return target.method.toUpperCase();
171
+ case "@authority": return target.authority;
172
+ case "@path": return path;
173
+ case "@query": return `?${target.query ?? ""}`;
174
+ case "@scheme": return "https";
175
+ case "@request-target": return `${path}${query}`;
176
+ default: return `https://${target.authority}${path}${query}`;
177
+ }
178
+ }
179
+ const value = target.headers.get(name);
180
+ if (value === null)
181
+ throw new SignatureError("missing_component", `header ${name} is not present`);
182
+ return value.trim();
183
+ }
184
+ class SignatureError extends Error {
185
+ reason;
186
+ constructor(reason, detail) {
187
+ super(detail);
188
+ this.reason = reason;
189
+ }
190
+ }
191
+ function signatureBase(target, list) {
192
+ const lines = [];
193
+ const seen = new Set();
194
+ for (const item of list.items) {
195
+ if (typeof item.value !== "string")
196
+ throw new SignatureError("malformed", "a covered component is not a string");
197
+ const id = `"${item.value}"${serializeParameters(item.params)}`;
198
+ if (seen.has(id))
199
+ throw new SignatureError("malformed", `${id} is covered twice`);
200
+ seen.add(id);
201
+ if (item.value === "@signature-params")
202
+ throw new SignatureError("malformed", "@signature-params is covered");
203
+ const value = componentValue(target, item.value, item.params);
204
+ if (/[\r\n]/.test(value))
205
+ throw new SignatureError("malformed", "a component has a newline");
206
+ lines.push(`${id}: ${value}`);
207
+ }
208
+ lines.push(`"@signature-params": ${serializeInnerList(list)}`);
209
+ return lines.join("\n");
210
+ }
211
+ const str = (value) => (typeof value === "string" ? value : undefined);
212
+ const int = (value) => (typeof value === "number" && Number.isInteger(value) ? value : undefined);
213
+ /** The directory URL a Signature-Agent value names for a signature label, or null. */
214
+ export function signatureAgentUrl(header, label) {
215
+ if (!header)
216
+ return null;
217
+ let value;
218
+ try {
219
+ const dict = parseDictionary(header);
220
+ const member = dict.get(label);
221
+ if (member && !isInnerList(member))
222
+ value = str(member.value);
223
+ }
224
+ catch {
225
+ // Not a dictionary: try a single string item below.
226
+ }
227
+ if (value === undefined) {
228
+ try {
229
+ value = str(parseItem(header).value);
230
+ }
231
+ catch {
232
+ value = /^https:\/\/[^\s",;]+$/i.test(header.trim()) ? header.trim() : undefined;
233
+ }
234
+ }
235
+ return value ?? null;
236
+ }
237
+ /** The store kit's local verifier. One per kit; directories and nonces are cached in memory. */
238
+ export class AgentSignatureVerifier {
239
+ now;
240
+ o;
241
+ allowlist;
242
+ networks;
243
+ directories = new Map();
244
+ nonces;
245
+ constructor(options = {}, now = Date.now) {
246
+ this.now = now;
247
+ this.o = {
248
+ maxSignatureAgeMs: options.maxSignatureAgeMs ?? 8 * 60_000,
249
+ clockSkewMs: options.clockSkewMs ?? 30_000,
250
+ directoryTtlMs: options.directoryTtlMs ?? 10 * 60_000,
251
+ directoryRefreshIntervalMs: options.directoryRefreshIntervalMs ?? 60_000,
252
+ directoryTimeoutMs: options.directoryTimeoutMs ?? 3_000,
253
+ maxDirectoryBytes: options.maxDirectoryBytes ?? 64 * 1024,
254
+ fetch: options.fetch ?? ((url, init) => fetch(url, init)),
255
+ };
256
+ this.allowlist = new Map();
257
+ for (const [origin, name] of Object.entries(options.webBotAuth ?? DEFAULT_WEB_BOT_AUTH_DIRECTORIES)) {
258
+ this.allowlist.set(httpsOrigin(origin), name);
259
+ }
260
+ this.networks = Object.entries(options.networks ?? {}).flatMap(([network, config]) => {
261
+ if (!config)
262
+ return [];
263
+ httpsOrigin(config.directoryUrl);
264
+ return [{ network: network, tags: config.tags ?? [...NETWORK_TAGS], directory: new KeyDirectory(config.directoryUrl, this.o, this.now) }];
265
+ });
266
+ this.nonces = options.nonces ?? new MemoryNonceStore();
267
+ }
268
+ /** The allowlisted Web Bot Auth origins and the agent each names. */
269
+ get webBotAuthDirectories() {
270
+ return Object.fromEntries(this.allowlist);
271
+ }
272
+ /**
273
+ * Verifies the request's agent signature against each candidate `@authority`
274
+ * (the store's public hostnames). Never throws.
275
+ */
276
+ async verify(request, authorities) {
277
+ const input = request.headers.get("signature-input");
278
+ const signature = request.headers.get("signature");
279
+ if (!input || !signature)
280
+ return { status: "unverified", reason: "no_signature" };
281
+ let inputs;
282
+ let signatures;
283
+ try {
284
+ inputs = parseDictionary(input);
285
+ signatures = parseDictionary(signature);
286
+ }
287
+ catch (error) {
288
+ return { status: "unverified", reason: "malformed", detail: error instanceof StructuredFieldError ? error.message : "unparseable" };
289
+ }
290
+ const url = new URL(request.url);
291
+ let first = null;
292
+ for (const [label, member] of inputs) {
293
+ if (!isInnerList(member)) {
294
+ first ??= { status: "unverified", reason: "malformed", detail: `${label} is not an inner list` };
295
+ continue;
296
+ }
297
+ const tag = str(member.params.get("tag"));
298
+ const known = tag === WEB_BOT_AUTH_TAG || (tag !== undefined && NETWORK_TAGS.includes(tag));
299
+ if (!known) {
300
+ first ??= { status: "unverified", reason: "unsupported_tag" };
301
+ continue;
302
+ }
303
+ const sig = signatures.get(label);
304
+ if (!sig || isInnerList(sig) || !(sig.value instanceof Uint8Array)) {
305
+ first ??= { status: "unverified", reason: "malformed", detail: `no signature for ${label}` };
306
+ continue;
307
+ }
308
+ const verdict = await this.verifyOne(request, url, label, member, sig.value, tag, authorities);
309
+ if (verdict.status === "verified")
310
+ return verdict;
311
+ first ??= verdict;
312
+ }
313
+ return first ?? { status: "unverified", reason: "unsupported_tag" };
314
+ }
315
+ async verifyOne(request, url, label, list, signature, tag, authorities) {
316
+ const method = tag === WEB_BOT_AUTH_TAG ? "web_bot_auth" : undefined;
317
+ const fail = (reason, detail, m = method) => ({ status: "unverified", reason, ...(m ? { method: m } : {}), ...(detail ? { detail } : {}) });
318
+ const alg = list.params.get("alg");
319
+ if (alg !== undefined && !(str(alg) === "ed25519" || (isToken(alg) && alg.token === "ed25519")))
320
+ return fail("unsupported_algorithm");
321
+ const keyId = str(list.params.get("keyid"));
322
+ const created = int(list.params.get("created"));
323
+ const expires = int(list.params.get("expires"));
324
+ const nonce = list.params.get("nonce");
325
+ if (!keyId || created === undefined || expires === undefined)
326
+ return fail("missing_params", "keyid, created and expires are required");
327
+ if (nonce !== undefined && typeof nonce !== "string")
328
+ return fail("missing_params", "nonce must be a string");
329
+ const now = this.now();
330
+ if (created * 1000 > now + this.o.clockSkewMs)
331
+ return fail("not_yet_valid");
332
+ if (expires * 1000 <= now)
333
+ return fail("expired");
334
+ if (now - created * 1000 > this.o.maxSignatureAgeMs)
335
+ return fail("too_old");
336
+ if (expires <= created || (expires - created) * 1000 > this.o.maxSignatureAgeMs)
337
+ return fail("window_too_long");
338
+ const covered = new Set(list.items.map((item) => item.value).filter((v) => typeof v === "string"));
339
+ let candidates;
340
+ if (method === "web_bot_auth") {
341
+ const agentUrl = signatureAgentUrl(request.headers.get("signature-agent"), label);
342
+ if (!agentUrl)
343
+ return fail("missing_component", "Signature-Agent is required for web-bot-auth");
344
+ let parsed;
345
+ try {
346
+ parsed = new URL(agentUrl);
347
+ }
348
+ catch {
349
+ return fail("malformed", "Signature-Agent is not a URL");
350
+ }
351
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password)
352
+ return fail("not_allowlisted", "Signature-Agent must be https");
353
+ const name = this.allowlist.get(parsed.origin);
354
+ if (!name)
355
+ return fail("not_allowlisted", parsed.origin);
356
+ if (!covered.has("@authority") || !covered.has("signature-agent"))
357
+ return fail("missing_component", "@authority and signature-agent must be covered");
358
+ const directoryUrl = parsed.pathname === "/" || parsed.pathname === "" ? `${parsed.origin}${WEB_BOT_AUTH_DIRECTORY_PATH}` : `${parsed.origin}${parsed.pathname}`;
359
+ candidates = [{ method, name, directory: this.directory(directoryUrl) }];
360
+ }
361
+ else {
362
+ candidates = this.networks.filter((n) => n.tags.includes(tag)).map((n) => ({ method: n.network, name: "other_known", directory: n.directory }));
363
+ if (candidates.length === 0)
364
+ return fail("not_allowlisted", "no card-network directory is configured");
365
+ if (!covered.has("@authority") || !covered.has("@path"))
366
+ return fail("missing_component", "@authority and @path must be covered", candidates[0].method);
367
+ if (nonce === undefined)
368
+ return fail("missing_params", "nonce is required", candidates[0].method);
369
+ }
370
+ let found = null;
371
+ let lookupFailure = null;
372
+ for (const candidate of candidates) {
373
+ const lookup = await candidate.directory.find(keyId);
374
+ if (lookup.status === "found") {
375
+ found = { ...candidate, key: lookup.key };
376
+ break;
377
+ }
378
+ lookupFailure ??= fail(lookup.status === "unknown" ? "unknown_key" : "directory_unavailable", undefined, candidate.method);
379
+ }
380
+ if (!found)
381
+ return lookupFailure;
382
+ let matched = null;
383
+ for (const authority of new Set(authorities.map((a) => a.toLowerCase()))) {
384
+ let base;
385
+ try {
386
+ base = signatureBase({ method: request.method, authority, path: url.pathname, query: url.search ? url.search.slice(1) : null, headers: request.headers }, list);
387
+ }
388
+ catch (error) {
389
+ if (error instanceof SignatureError)
390
+ return fail(error.reason, error.message, found.method);
391
+ return fail("malformed", undefined, found.method);
392
+ }
393
+ if (signature.length === 64 && safeVerify(base, signature, found.key.publicKey)) {
394
+ matched = authority;
395
+ break;
396
+ }
397
+ }
398
+ if (!matched)
399
+ return fail("bad_signature", undefined, found.method);
400
+ if (nonce !== undefined) {
401
+ const claimed = await this.nonces.claim(`${found.directory.url}|${keyId}`, nonce, expires * 1000 + this.o.clockSkewMs, now);
402
+ if (!claimed)
403
+ return fail("replayed", undefined, found.method);
404
+ }
405
+ return {
406
+ status: "verified", method: found.method, name: found.name, keyId, directory: found.directory.url, label, tag,
407
+ authority: matched, created, expires,
408
+ };
409
+ }
410
+ directory(url) {
411
+ let directory = this.directories.get(url);
412
+ if (!directory) {
413
+ directory = new KeyDirectory(url, this.o, this.now);
414
+ this.directories.set(url, directory);
415
+ while (this.directories.size > 100)
416
+ this.directories.delete(this.directories.keys().next().value);
417
+ }
418
+ return directory;
419
+ }
420
+ /** How often each directory was fetched (diagnostics and tests). */
421
+ directoryFetches() {
422
+ const out = {};
423
+ for (const [url, directory] of this.directories)
424
+ out[url] = directory.fetches;
425
+ for (const { directory } of this.networks)
426
+ out[directory.url] = directory.fetches;
427
+ return out;
428
+ }
429
+ }
430
+ function safeVerify(base, signature, key) {
431
+ try {
432
+ return cryptoVerify(null, Buffer.from(base, "utf8"), key, signature);
433
+ }
434
+ catch {
435
+ return false;
436
+ }
437
+ }
438
+ function httpsOrigin(value) {
439
+ const url = new URL(value);
440
+ if (url.protocol !== "https:" || url.username || url.password)
441
+ throw new TypeError(`Agent key directories must be https URLs without credentials: ${value}`);
442
+ return url.origin;
443
+ }
@@ -0,0 +1,185 @@
1
+ import type { AgentProtocol, CartInputs } from "./types.js";
2
+ /** What the kit remembers about one agent checkout between steps. */
3
+ export interface CheckoutRecord {
4
+ protocol: AgentProtocol;
5
+ /** The protocol's own checkout ID (the one in the agent's URLs). */
6
+ sessionId: string;
7
+ /** Relyon's ID for the agent checkout; pass it to `createPayment`. */
8
+ agentCheckoutId: string | null;
9
+ /** The cart inputs the kit last relayed for this checkout. */
10
+ inputs: CartInputs;
11
+ /**
12
+ * Cart fields Relyon locked on the last priced step and expects back on
13
+ * `complete` (today's server returns `cart.merchant_reference` and
14
+ * `cart.expires_at`; the contract's Cart has neither). Echoed only when present.
15
+ */
16
+ locked: Record<string, unknown> | null;
17
+ /**
18
+ * Set while this checkout is order pending: its payment succeeded and the
19
+ * store's order isn't created yet. The checkout's reads answer
20
+ * `complete_in_progress` until the order exists. A custom store must save
21
+ * and return it unchanged; absent (or null) means not order pending.
22
+ */
23
+ orderPending?: CheckoutOrderPending | null;
24
+ /**
25
+ * The `relyon_cart` token of the latest hand-off link Relyon issued for this
26
+ * checkout in a relayed answer (`continue_url`, a message, MCP tool content).
27
+ * `kit.landing` accepts a Relyon-issued token only when it is exactly this
28
+ * one, and only once (see `CheckoutStateStore.claimHandoffToken`). A custom
29
+ * store must save and return it unchanged; absent (or null) means no Relyon
30
+ * link was seen, so Relyon's links for it land unattributed.
31
+ */
32
+ handoffToken?: string | null;
33
+ /**
34
+ * When the kit first saw `handoffToken` (ms, the kit's clock); kept while
35
+ * the token stays the same. A Test link whose expiry (on Relyon's sandbox
36
+ * clock) is already past lands only within a fixed window after this time.
37
+ * A custom store must save and return it unchanged.
38
+ */
39
+ handoffTokenAt?: number | null;
40
+ updatedAt: number;
41
+ }
42
+ /** The succeeded payment an order-pending checkout is waiting on (see `CheckoutRecord.orderPending`). */
43
+ export interface CheckoutOrderPending {
44
+ /** The payment ID the order claim is keyed on. */
45
+ paymentId: string;
46
+ /** When the kit first saw the order pending (the kit's clock, ms). */
47
+ since: number;
48
+ /**
49
+ * Set when a payment on the store's own checkout page (`payAndConfirm` with
50
+ * this agent checkout, a hand-off cart) paid it: the agent's `complete` is
51
+ * then answered by the kit and never relayed, so Relyon can't charge again.
52
+ */
53
+ handoff?: boolean;
54
+ }
55
+ /**
56
+ * What the store's own pay endpoint (`payAndConfirm`) remembers about a
57
+ * payment, by its Idempotency-Key (one per order reference and attempt):
58
+ * - `charging`: sent to Relyon (after the agent-rules gate allowed it), no
59
+ * final outcome recorded yet: it may have been charged;
60
+ * - `declined`: Relyon declined it: nothing was charged;
61
+ * - `order_pending`: it succeeded and the store's order isn't created
62
+ * (written before `createOrder` runs);
63
+ * - `order_created`: it succeeded and `payAndConfirm` confirmed the order.
64
+ */
65
+ export interface StorePaymentRecord {
66
+ state: "charging" | "declined" | "order_pending" | "order_created";
67
+ /** Relyon's payment ID; null while `charging`. */
68
+ paymentId: string | null;
69
+ /** The kit's clock (ms). */
70
+ updatedAt: number;
71
+ /** The order reference and attempt that paid; set on the records an order reference or a hand-off cart shares. */
72
+ orderReference?: string;
73
+ attempt?: number;
74
+ }
75
+ /** What the kit passes to `claimOrder`: who is claiming, the kit's clock, and how long an unfinished claim holds. */
76
+ export interface OrderClaimOptions {
77
+ /** Unique to this attempt. `releaseOrder` gives the claim back only while it is still this one. */
78
+ claimId: string;
79
+ /** The kit's clock (ms). */
80
+ now: number;
81
+ /** How long a claim that wasn't marked created (`completeOrder`) holds before another caller may take it over. */
82
+ leaseMs: number;
83
+ }
84
+ /**
85
+ * Where an order claim stands. `created`: `completeOrder` was called, so the
86
+ * order exists. `creating`: another caller holds a claim whose lease hasn't
87
+ * passed. null: no claim (never claimed, released, or its lease passed).
88
+ */
89
+ export type OrderClaimStatus = "created" | "creating" | null;
90
+ /** What the kit passes to `claimHandoffToken`: the kit's clock and when the token expires (both ms). */
91
+ export interface HandoffTokenClaimOptions {
92
+ now: number;
93
+ /** After this the token is refused as expired anyway, so the claim may be forgotten. */
94
+ expiresAt: number;
95
+ }
96
+ /** What the kit passes to `setHandoffToken`: the record the write is conditional on, and the kit's clock (ms). */
97
+ export interface HandoffTokenSetOptions {
98
+ /** The record's `handoffToken` when the read began (null: none). */
99
+ expectedToken: string | null;
100
+ /** The record's `inputs` when the read began. */
101
+ expectedInputs: CartInputs;
102
+ /** The new `updatedAt`, and the new `handoffTokenAt`. */
103
+ now: number;
104
+ }
105
+ /**
106
+ * Per-checkout memory, plus the claim that makes `createOrder` run once per
107
+ * payment. The default keeps everything in memory; a store running more than
108
+ * one server process plugs in a shared store with an atomic claim.
109
+ */
110
+ export interface CheckoutStateStore {
111
+ get(protocol: AgentProtocol, sessionId: string): Promise<CheckoutRecord | null> | CheckoutRecord | null;
112
+ byAgentCheckoutId(agentCheckoutId: string): Promise<CheckoutRecord | null> | CheckoutRecord | null;
113
+ put(record: CheckoutRecord): Promise<void> | void;
114
+ /**
115
+ * Atomically claims order creation for a payment. true: this caller creates
116
+ * the order. It succeeds when the payment has no claim, or its claim was
117
+ * never marked created and is older than `options.leaseMs` (the server that
118
+ * held it may have died mid-creation). It never succeeds once the claim is
119
+ * marked created.
120
+ */
121
+ claimOrder(paymentId: string, options?: OrderClaimOptions): Promise<boolean> | boolean;
122
+ /** Gives the claim back after `createOrder` failed, so a replay can try again. Only while `claimId` still holds it. */
123
+ releaseOrder(paymentId: string, claimId?: string): Promise<void> | void;
124
+ /**
125
+ * Marks the claim done: `createOrder` returned, so the order exists. A
126
+ * claim marked done never expires and is never given back. Without it
127
+ * (a store written before it existed) a claim can't be told apart from
128
+ * one still being created, so a WebMCP checkout stays order pending.
129
+ */
130
+ completeOrder?(paymentId: string, claimId?: string): Promise<void> | void;
131
+ /** Where the payment's order claim stands (see `OrderClaimStatus`). */
132
+ orderClaimStatus?(paymentId: string, now: number): Promise<OrderClaimStatus> | OrderClaimStatus;
133
+ /**
134
+ * Optional (implement both or neither): what `payAndConfirm` charged, by
135
+ * the payment's Idempotency-Key. A retry of an order reference whose
136
+ * payment succeeded with the order pending must never hear "nothing was
137
+ * charged", even when the agent rules now refuse it on another server: the
138
+ * kit answers the same 202 order pending instead. "Nothing was charged" is
139
+ * said only after a recorded decline; a missing record is charge-neutral.
140
+ * Without these the kit remembers in this process only, and on other
141
+ * servers its rule refusals in `payAndConfirm` are charge-neutral.
142
+ */
143
+ getStorePayment?(idempotencyKey: string): Promise<StorePaymentRecord | null> | StorePaymentRecord | null;
144
+ putStorePayment?(idempotencyKey: string, record: StorePaymentRecord): Promise<void> | void;
145
+ /**
146
+ * Optional: atomically claims the single attributed landing of a Relyon
147
+ * hand-off token, by its SHA-256 digest (the token itself is never passed).
148
+ * true exactly once per digest until `options.expiresAt`; every later or
149
+ * simultaneous call answers false. Without it each server process lets a
150
+ * token land once, so a store running more than one process should
151
+ * implement it (a unique insert in a shared table is enough).
152
+ */
153
+ claimHandoffToken?(tokenDigest: string, options: HandoffTokenClaimOptions): Promise<boolean> | boolean;
154
+ /**
155
+ * Optional: one atomic compare-and-set that records the hand-off link token
156
+ * a read (or cancel) answer carried. It sets `handoffToken`,
157
+ * `handoffTokenAt` and `updatedAt` (all from `options.now` for the times),
158
+ * keeping every other field, only while the record's
159
+ * `handoffToken` and `inputs` (compared as canonical JSON) still equal the
160
+ * expected ones; true when it wrote. An update saved meanwhile makes it
161
+ * write nothing. Without it the kit records links only from creates and
162
+ * updates, and a newer link seen on a read lands unattributed.
163
+ */
164
+ setHandoffToken?(protocol: AgentProtocol, sessionId: string, token: string, options: HandoffTokenSetOptions): Promise<boolean> | boolean;
165
+ }
166
+ export declare class MemoryCheckoutStateStore implements CheckoutStateStore {
167
+ private readonly maxRecords;
168
+ private readonly records;
169
+ private readonly byAgent;
170
+ private readonly claims;
171
+ private readonly storePayments;
172
+ private readonly handoffClaims;
173
+ constructor(maxRecords?: number);
174
+ get(protocol: AgentProtocol, sessionId: string): CheckoutRecord | null;
175
+ byAgentCheckoutId(agentCheckoutId: string): CheckoutRecord | null;
176
+ put(record: CheckoutRecord): void;
177
+ claimOrder(paymentId: string, options?: OrderClaimOptions): boolean;
178
+ releaseOrder(paymentId: string, claimId?: string): void;
179
+ completeOrder(paymentId: string): void;
180
+ orderClaimStatus(paymentId: string, now: number): OrderClaimStatus;
181
+ getStorePayment(idempotencyKey: string): StorePaymentRecord | null;
182
+ putStorePayment(idempotencyKey: string, record: StorePaymentRecord): void;
183
+ setHandoffToken(protocol: AgentProtocol, sessionId: string, token: string, options: HandoffTokenSetOptions): boolean;
184
+ claimHandoffToken(tokenDigest: string, options: HandoffTokenClaimOptions): boolean;
185
+ }