@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
package/dist/rules.js ADDED
@@ -0,0 +1,347 @@
1
+ import { AGENT_RULES_OBJECT, AGENT_RULES_PATH, DOCTOR_CHALLENGE_OBJECT, WEBHOOK_ENDPOINTS_PATH } from "./wire-names.js";
2
+ import { verifyEventSignature } from "./sdk/signatures.js";
3
+ import { RelyonUnavailableError } from "./relyon.js";
4
+ import { createHmac } from "node:crypto";
5
+ import { isRecord, tryParseJson } from "./util.js";
6
+ import { describeError } from "./relyon-cart-tokens.js";
7
+ import { WEBHOOK_EVENTS, isWebhookEndpointFor, isWebhookEndpointListFor, newestActiveEndpoint, webhookRegistrationKey, webhookSecretShape, } from "./webhook-registration.js";
8
+ /** The response header carrying the doctor challenge acknowledgement. */
9
+ export const DOCTOR_ACKNOWLEDGEMENT_HEADER = "relyon-doctor-acknowledgement";
10
+ /**
11
+ * The contract's doctor acknowledgement: lowercase hex HMAC-SHA256, with the
12
+ * webhook endpoint's signing secret, of
13
+ * "relyon.doctor.ack.v1\n<id>\n<challenge>\n<created>" (no trailing newline).
14
+ */
15
+ export function doctorAcknowledgement(secret, id, challenge, created) {
16
+ return createHmac("sha256", secret).update(`relyon.doctor.ack.v1\n${id}\n${challenge}\n${created}`).digest("hex");
17
+ }
18
+ /** The contract's DoctorChallenge, exactly (no extra properties). */
19
+ function isDoctorChallenge(event) {
20
+ const keys = Object.keys(event).sort().join(",");
21
+ return keys === "challenge,created,id,livemode,object,type"
22
+ && typeof event.id === "string" && /^evt_doctor_[a-f0-9-]{36}$/.test(event.id)
23
+ && event.object === DOCTOR_CHALLENGE_OBJECT && event.type === "doctor.challenge"
24
+ && typeof event.livemode === "boolean"
25
+ && Number.isInteger(event.created) && event.created >= 0
26
+ && typeof event.challenge === "string" && /^[a-f0-9]{64}$/.test(event.challenge);
27
+ }
28
+ const DEFAULT_REFRESH_SECONDS = 60;
29
+ const AGENT_CHANNELS = new Set(["google", "chatgpt", "mcp", "agent"]);
30
+ /**
31
+ * Runtime secret resolution backs off after any failure: 60s, doubling per
32
+ * consecutive failure up to 15 minutes, reset on success. Deliveries during a
33
+ * cooldown never hit Relyon, so an unsigned-request flood cannot amplify into
34
+ * registration replays.
35
+ */
36
+ const SECRET_RETRY_BASE_MS = 60_000;
37
+ const SECRET_RETRY_MAX_MS = 15 * 60_000;
38
+ /**
39
+ * How long a doctor challenge waits on a cold secret recovery before it
40
+ * answers 503 and lets the shared recovery finish in the background for
41
+ * Relyon's retry (Brief 89c). Comfortably inside the doctor's per-attempt
42
+ * response budget, so the fast answer always beats the probe's abort.
43
+ */
44
+ export const CHALLENGE_SECRET_BUDGET_MS = 2_500;
45
+ /** Sentinel: the challenge's bounded wait elapsed while recovery continues. */
46
+ const CHALLENGE_SECRET_PENDING = Symbol("challenge-secret-pending");
47
+ /**
48
+ * The store's merged agent rules, read with `getAgentRules`, used for at most
49
+ * `refresh_seconds` (60 by default) and refreshed early by a signed
50
+ * `agent_rules.updated` webhook. When a refresh fails the last good copy is
51
+ * kept: blocks keep applying while Relyon is away.
52
+ */
53
+ export class AgentRulesCache {
54
+ gateway;
55
+ options;
56
+ now;
57
+ logger;
58
+ rules = null;
59
+ fetchedAt = 0;
60
+ inflight;
61
+ timer;
62
+ stopped = false;
63
+ lastAttemptAt = 0;
64
+ /** The secret recovered at runtime; undefined until one resolves. */
65
+ recoveredSecret;
66
+ recoveringSecret;
67
+ /** Consecutive resolution failures; drives the backoff. Reset on success. */
68
+ secretFailures = 0;
69
+ /** Resolution (and bad-signature re-resolution) is refused until this time. */
70
+ secretBlockedUntil = 0;
71
+ /** The last signature-mismatch warning, throttled to one per cooldown window. */
72
+ mismatchWarnedAt = 0;
73
+ constructor(gateway, options, now, logger) {
74
+ this.gateway = gateway;
75
+ this.options = options;
76
+ this.now = now;
77
+ this.logger = logger;
78
+ }
79
+ get current() {
80
+ return this.rules;
81
+ }
82
+ get refreshMs() {
83
+ return (this.rules?.refresh_seconds ?? DEFAULT_REFRESH_SECONDS) * 1000;
84
+ }
85
+ /**
86
+ * The rules to apply now. A copy older than `refresh_seconds` is still used
87
+ * while it refreshes in the background, so requests never wait on Relyon
88
+ * once the first copy is in. Before that, the first read waits for Relyon
89
+ * (bounded by the client timeout); while Relyon stays away, further reads
90
+ * retry at most every 5 seconds and get null (no edge rules; Relyon still
91
+ * applies its rules to every checkout step and payment).
92
+ */
93
+ async get() {
94
+ if (this.rules) {
95
+ if (this.now() - this.fetchedAt >= this.refreshMs)
96
+ void this.refresh();
97
+ return this.rules;
98
+ }
99
+ if (this.inflight)
100
+ return this.inflight;
101
+ if (this.lastAttemptAt && this.now() - this.lastAttemptAt < 5_000)
102
+ return null;
103
+ return this.refresh();
104
+ }
105
+ /** Reads the rules from Relyon now. Keeps (and returns) the last good copy when Relyon is unavailable. */
106
+ refresh() {
107
+ if (!this.inflight) {
108
+ this.inflight = this.load().finally(() => { this.inflight = undefined; });
109
+ }
110
+ return this.inflight;
111
+ }
112
+ async load() {
113
+ this.lastAttemptAt = this.now();
114
+ try {
115
+ const { data } = await this.gateway.call((client) => client.GET(AGENT_RULES_PATH), isAgentRules);
116
+ this.rules = data;
117
+ this.fetchedAt = this.now();
118
+ }
119
+ catch (error) {
120
+ if (!(error instanceof RelyonUnavailableError)) {
121
+ this.logger.warn("could not read agent rules", { error: describeError(error) });
122
+ }
123
+ }
124
+ this.schedule();
125
+ return this.rules;
126
+ }
127
+ schedule() {
128
+ if (this.stopped || this.options.backgroundRefresh === false)
129
+ return;
130
+ if (this.timer)
131
+ clearTimeout(this.timer);
132
+ this.timer = setTimeout(() => { void this.refresh(); }, this.refreshMs);
133
+ this.timer.unref?.();
134
+ }
135
+ stop() {
136
+ this.stopped = true;
137
+ if (this.timer)
138
+ clearTimeout(this.timer);
139
+ this.timer = undefined;
140
+ }
141
+ /**
142
+ * Handles a Relyon webhook delivery. A valid `agent_rules.updated` refreshes
143
+ * the rules now. Any other validly signed event type is acknowledged (200)
144
+ * and changes nothing; a bad or missing signature is ignored (400).
145
+ */
146
+ async handleWebhook(rawBody, signature) {
147
+ // An absent signature is "unsigned", not "wrong": refuse it without the
148
+ // mismatch warning and without any secret resolution. The doctor's route
149
+ // probe deliberately sends no signature, and an unsigned flood must stay
150
+ // cheap — no re-resolution attempt, no call to Relyon.
151
+ if (!signature)
152
+ return { status: 400 };
153
+ // Parse before any secret work: a doctor challenge is identified up front
154
+ // and takes the bounded path below — its answer is never queued behind a
155
+ // slow cold recovery past the point where Relyon's probe has given up.
156
+ const event = tryParseJson(rawBody);
157
+ const challenge = isRecord(event) && event.type === "doctor.challenge";
158
+ const verify = (secret) => verifyEventSignature({ rawBody, signature, secret, nowSeconds: Math.floor(this.now() / 1000) });
159
+ let secret;
160
+ if (this.options.webhookSecret)
161
+ secret = this.options.webhookSecret;
162
+ else if (challenge) {
163
+ const recovered = await this.recoverForChallenge();
164
+ // Recovery is still running in the background (its shared promise caches
165
+ // the secret when it lands). Answer fast — a retryable 503 instead of a
166
+ // hung request — so Relyon's retry lands on the warm cache.
167
+ if (recovered === CHALLENGE_SECRET_PENDING)
168
+ return { status: 503, error: "secret_warming" };
169
+ secret = recovered;
170
+ }
171
+ else
172
+ secret = await this.resolveWebhookSecret();
173
+ // A loaded secret whose signature doesn't match is a different problem
174
+ // from no secret at all: the secret was probably rotated out from under
175
+ // the running store (webhook --rotate), which the mismatch warning names.
176
+ const hadSecret = secret !== undefined;
177
+ let reResolved = false;
178
+ if (secret && !verify(secret) && this.recoveredSecret === secret && !this.options.webhookSecret) {
179
+ // The cached (recovered) secret may be stale after a rotation: re-resolve
180
+ // at most once per cooldown window, then re-verify this one delivery.
181
+ // The mismatch warning rides the same window: it fires only when this
182
+ // delivery actually attempted a re-resolution, so a bad-signature flood
183
+ // warns once per attempt, never per request.
184
+ reResolved = this.now() >= this.secretBlockedUntil && !this.recoveringSecret;
185
+ const fresh = await this.resolveWebhookSecret(true);
186
+ if (fresh && fresh !== secret && verify(fresh))
187
+ secret = fresh;
188
+ else
189
+ secret = undefined;
190
+ }
191
+ if (!secret || !verify(secret)) {
192
+ if (hadSecret)
193
+ this.warnSignatureMismatch(reResolved || this.options.webhookSecret !== undefined);
194
+ return { status: 400 };
195
+ }
196
+ if (!isRecord(event) || typeof event.type !== "string")
197
+ return { status: 400 };
198
+ if (event.type === "doctor.challenge") {
199
+ // Relyon's integration doctor: acknowledge the verified challenge, nothing else.
200
+ if (!isDoctorChallenge(event))
201
+ return { status: 400 };
202
+ return { status: 200, type: event.type, acknowledgement: doctorAcknowledgement(secret, event.id, event.challenge, event.created) };
203
+ }
204
+ if (event.type === "agent_rules.updated")
205
+ await this.refresh();
206
+ return { status: 200, type: event.type };
207
+ }
208
+ /**
209
+ * The challenge path's secret wait (Brief 89c). A doctor challenge must be
210
+ * answered fast: a configured or cached secret is used at once, an in-flight
211
+ * recovery is awaited only up to CHALLENGE_SECRET_BUDGET_MS, and a cold
212
+ * recovery is started and awaited under the same bound. When the bound
213
+ * elapses the caller answers 503 while the shared recovery promise keeps
214
+ * running and caches the secret, so Relyon's retry succeeds instead of this
215
+ * request hanging past the doctor's response budget.
216
+ */
217
+ async recoverForChallenge() {
218
+ const recovery = this.resolveWebhookSecret();
219
+ let timer;
220
+ try {
221
+ return await Promise.race([
222
+ recovery,
223
+ new Promise((resolve) => {
224
+ timer = setTimeout(() => resolve(CHALLENGE_SECRET_PENDING), CHALLENGE_SECRET_BUDGET_MS);
225
+ // The bound must never keep a process alive on its own.
226
+ if (typeof timer === "object" && timer !== null && typeof timer.unref === "function") {
227
+ timer.unref();
228
+ }
229
+ }),
230
+ ]);
231
+ }
232
+ finally {
233
+ if (timer !== undefined)
234
+ clearTimeout(timer);
235
+ }
236
+ }
237
+ /**
238
+ * Runtime recovery of the webhook signing secret, used only when no
239
+ * `webhookSecret` is configured: find the newest active endpoint for the
240
+ * receiver's own URL and replay its deterministic registration with the
241
+ * store's key. Works in Test and Live with identical semantics: an answer
242
+ * is accepted only when its livemode matches the kit's mode, it names that
243
+ * newest endpoint and it carries a shape-valid secret of the mode. No first
244
+ * endpoint is registered by this receiver. A 409 (a session-owned or legacy
245
+ * registration row, or a Live adoption refusal), an endpoint-id mismatch or
246
+ * a malformed answer fails closed: the webhook is refused as before, with
247
+ * guidance to run the webhook command. No active endpoint for the URL means
248
+ * nothing to replay, so no registration POST ever goes out from a request
249
+ * handler.
250
+ *
251
+ * Every failure starts a cooldown (60s, doubling per consecutive failure up
252
+ * to 15 minutes, reset on success) and warns once per cooldown window, so
253
+ * unsigned-request floods cannot amplify into Relyon calls. With `force`
254
+ * (a bad signature against the cached secret) the same cooldown bounds
255
+ * re-resolution, but a fresh attempt is allowed once the window elapsed —
256
+ * and a forced re-resolution returning the SAME secret the cache already
257
+ * holds counts as a failure (the suspected rotation has not happened), so
258
+ * the backoff doubles instead of resetting.
259
+ */
260
+ /**
261
+ * A secret was loaded (configured or recovered) but the delivery's signature
262
+ * doesn't match it: after `webhook --rotate` the running store still holds
263
+ * the old secret. `attempted` is true only when this delivery ran the
264
+ * bounded re-resolution (or the secret is operator-configured, which never
265
+ * re-resolves): the warning fires once per re-resolution attempt — never
266
+ * per request inside a cooldown window — and the secret's value is never
267
+ * logged.
268
+ */
269
+ warnSignatureMismatch(attempted) {
270
+ if (!attempted)
271
+ return;
272
+ if (this.now() - this.mismatchWarnedAt < SECRET_RETRY_BASE_MS)
273
+ return;
274
+ this.mismatchWarnedAt = this.now();
275
+ this.logger.warn("A Relyon webhook arrived but its signature didn't match the saved secret. The secret was probably changed (for example by webhook --rotate). Restart the store's server or reload RELYON_WEBHOOK_SECRET.");
276
+ }
277
+ async resolveWebhookSecret(force = false) {
278
+ if (!force && this.recoveredSecret)
279
+ return this.recoveredSecret;
280
+ const url = this.options.recoverSecretForUrl;
281
+ if (!url || this.gateway.waitingForSandboxKey)
282
+ return undefined;
283
+ if (this.now() < this.secretBlockedUntil)
284
+ return undefined; // cooldown; the window already warned
285
+ if (this.recoveringSecret)
286
+ return this.recoveringSecret;
287
+ this.recoveringSecret = (async () => {
288
+ const cached = this.recoveredSecret;
289
+ try {
290
+ const live = this.gateway.livemode;
291
+ const list = (await this.gateway.call((client) => client.GET(WEBHOOK_ENDPOINTS_PATH), isWebhookEndpointListFor(live))).data.data;
292
+ const newest = newestActiveEndpoint(list, url);
293
+ if (!newest)
294
+ throw new Error("no active endpoint for the receiver URL");
295
+ const { data } = await this.gateway.call((client) => client.POST(WEBHOOK_ENDPOINTS_PATH, {
296
+ params: { header: { "Idempotency-Key": webhookRegistrationKey(url) } },
297
+ body: { url, events: [...WEBHOOK_EVENTS] },
298
+ }), isWebhookEndpointFor(live));
299
+ // The answer is authorized recovery only for the listed current row
300
+ // (Live never answers an adoption with a secret, so this is a replay).
301
+ if (data.id !== newest.id)
302
+ throw new Error("the replay names a superseded endpoint");
303
+ if (typeof data.secret !== "string" || !webhookSecretShape(live).test(data.secret)) {
304
+ throw new Error("the answer carried no usable signing secret");
305
+ }
306
+ if (force && cached !== undefined && data.secret === cached) {
307
+ // The forced re-resolve answered the secret the cache already holds:
308
+ // the rotation the bad signature suggested has not happened, so this
309
+ // counts as a failure — the backoff doubles instead of resetting, or
310
+ // an unsigned-request flood would get one Relyon call per 60 seconds
311
+ // forever.
312
+ throw new Error("the re-resolved secret is the cached one");
313
+ }
314
+ this.recoveredSecret = data.secret;
315
+ this.secretFailures = 0;
316
+ // A success also opens a window: a bad signature against the cached
317
+ // secret may force one re-resolution per window, never more.
318
+ this.secretBlockedUntil = this.now() + SECRET_RETRY_BASE_MS;
319
+ return data.secret;
320
+ }
321
+ catch {
322
+ // One warning per cooldown window: an attempt only runs when no
323
+ // cooldown is active, and it starts the next window. The warning
324
+ // speaks only for "no secret can be found at all": when a cached
325
+ // secret exists (a forced re-resolution after a bad signature), the
326
+ // signature-mismatch warning names the real problem instead.
327
+ this.secretFailures += 1;
328
+ this.secretBlockedUntil = this.now()
329
+ + Math.min(SECRET_RETRY_BASE_MS * 2 ** (this.secretFailures - 1), SECRET_RETRY_MAX_MS);
330
+ if (cached === undefined) {
331
+ this.logger.warn(this.gateway.livemode
332
+ ? "A Relyon webhook arrived but the signing secret couldn't be resolved with the store's Live key. Run `npx @relyon/store-kit webhook` to register or verify the endpoint — the secret is resolved at runtime, nothing is saved to a file — or set RELYON_WEBHOOK_SECRET explicitly. (The secret is never logged.)"
333
+ : "A Relyon webhook arrived but the signing secret couldn't be resolved with the store's key. Run `npx @relyon/store-kit webhook` to register the endpoint and save the secret, or set RELYON_WEBHOOK_SECRET explicitly. (The secret is never logged.)");
334
+ }
335
+ return undefined;
336
+ }
337
+ })().finally(() => { this.recoveringSecret = undefined; });
338
+ return this.recoveringSecret;
339
+ }
340
+ }
341
+ export function isAgentRules(data) {
342
+ return isRecord(data) && data.object === AGENT_RULES_OBJECT && typeof data.version === "string"
343
+ && Number.isInteger(data.refresh_seconds) && data.refresh_seconds >= 1
344
+ && Array.isArray(data.blocked_agents) && data.blocked_agents.every(isRecord)
345
+ && typeof data.paused === "boolean"
346
+ && Array.isArray(data.paused_channels) && data.paused_channels.every((channel) => AGENT_CHANNELS.has(channel));
347
+ }