@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/doctor.js ADDED
@@ -0,0 +1,1689 @@
1
+ import { forKitPackage } from "./identity.js";
2
+ import { DOCTOR_OBJECT, DOCTOR_PATH, KIT_DIAGNOSTIC_STATUS_HEADER, KIT_MANIFEST_VERSION_HEADER, KIT_VERSION_DIAGNOSTIC_HEADER, PROJECT_SPACE_HOSTNAME_HEADER, PROJECT_SPACE_POLICIES_PATH, WEBHOOK_ENDPOINTS_PATH } from "./wire-names.js";
3
+ import { readKitConfig } from "./kit-config.js";
4
+ import { createHmac, randomBytes, randomUUID } from "node:crypto";
5
+ import { gunzipSync } from "node:zlib";
6
+ import { placeholderApiKey, usableApiKey } from "./api-key.js";
7
+ import { GATED_KIT_WARNING, findGatedKitMounts } from "./doctor-source.js";
8
+ import { isWaitingBody } from "./waiting.js";
9
+ import { AI_DISCOVERY_CRAWLERS } from "./robots.js";
10
+ import { STORE_FEED_PATHS } from "./feeds.js";
11
+ import { nonPublicStoreHost } from "./live.js";
12
+ import { RelyonGateway, RelyonProblemError, RelyonUnavailableError, liveModeFor } from "./relyon.js";
13
+ import { isRecord } from "./util.js";
14
+ import { liveSigningKey } from "./relyon-cart-tokens.js";
15
+ import { KIT_VERSION } from "./version.js";
16
+ import { GO_LIVE_STEPS, TEST_ON_PREVIEW, TEST_PREVIEW_HEADER, isLoopbackHostname } from "./preview-hosts.js";
17
+ import { findDomain, readStorePolicies } from "./setup.js";
18
+ import { AGENT_CHECKOUT_OFF, AGENT_DOMAIN_STEP, DO_NOT_INVENT, FINAL_MESSAGE_TODOS, MERCHANT_QUESTIONS, OWNER_TO_FILL_IN, domainPendingOnlyFailure, pendingPolicyFields, policyOnlyFailure, transientCatalogFailure } from "./doctor-merchant.js";
19
+ import { cartTransferCheck } from "./doctor-cart-transfer.js";
20
+ import { catalogReadiness, RETURN_WINDOW_PENDING } from "./doctor-catalog.js";
21
+ import { CHECKOUT_MARKER_FIX, checkoutMarker, readMcpProducts, variantsCheck } from "./doctor-variants.js";
22
+ import { CHECKLIST_MANIFEST_VERSION, checkIdForItem } from "./checklist-manifest.js";
23
+ import { diagnoseKitVersion, legacyNewerKitVersion } from "./kit-version.js";
24
+ import { KIT_OUTCOMES_HEADER, kitOutcomeMetadata } from "./doctor-evidence.js";
25
+ import { KIT_VERSION_HEADER, encodeKitVersionSnapshot } from "./kit-updates.js";
26
+ import { DOCTOR_ACKNOWLEDGEMENT_HEADER, doctorAcknowledgement } from "./rules.js";
27
+ import { WEBHOOK_EVENTS, WEBHOOK_SECRET_SHAPE, isTestWebhookEndpoint, isTestWebhookEndpointList, newestActiveEndpoint, webhookRegistrationKey, } from "./webhook-registration.js";
28
+ /** The checkout page path doctor checks unless told otherwise (the kit's default `paths.checkout`). */
29
+ export const DEFAULT_CHECKOUT_PATH = "/checkout";
30
+ /** Doctor's item for the human checkout page; NOT DONE until it answers 200. */
31
+ export const CHECKOUT_PAGE_ITEM = "checkout page";
32
+ export const CART_PAGE_ITEM = "cart page";
33
+ /** The cart-page item for a layer-2 app (relyon/kit.json says "products"). */
34
+ export const CART_PAGE_NOT_REQUIRED = "Not required for this app: init recorded layer 2 (products and agents) in relyon/kit.json, and a /cart page is required only when the kit builds the shopping pages (layer 3).";
35
+ export const CART_PAGE_FIX = "Serve a real /cart page that answers 200, lists the cart's lines and links to checkout (a drawer alone is not enough), then re-run npx @relyon/store-kit doctor.";
36
+ /** Doctor's item for the sampled product pages; NOT DONE until each answers 200. */
37
+ export const PRODUCT_PAGES_ITEM = "product pages";
38
+ /** Doctor's item for products with options (NOT DONE as a warning for agents when variants aren't listed). */
39
+ export const VARIANTS_ITEM = "product variants";
40
+ /** The checklist row telling agents (and the dashboard) that checkout needs an agent credential. */
41
+ export const AI_AGENT_CHECKOUT_ITEM = "AI-agent checkout";
42
+ /** At most this many product pages are fetched per run. */
43
+ export const PRODUCT_PAGE_SAMPLE = 3;
44
+ /** A spread sample of product page URLs: the first, the middle and the last. */
45
+ export function sampleProductPages(urls) {
46
+ const unique = [...new Set(urls)];
47
+ if (unique.length <= PRODUCT_PAGE_SAMPLE)
48
+ return unique;
49
+ return [...new Set([unique[0], unique[Math.floor(unique.length / 2)], unique[unique.length - 1]])];
50
+ }
51
+ /** Policy pages in Live: https only (Test also accepts http on loopback addresses). */
52
+ export const LIVE_POLICY_HTTPS = "Live mode requires https policy URLs on the store's published domain; plain http on localhost, 127.0.0.1 or [::1] is accepted in Test only.";
53
+ /** A kit route answered by the app's own page or another non-kit body. */
54
+ export const CATCH_ALL_FIX = "Your server's catch-all route answers this path. Mount storeKitMiddleware before the catch-all.";
55
+ /** A random unknown path answered 200. */
56
+ export const UNKNOWN_PATH_FIX = "Your server answers 200 for unknown paths, so agents can't tell what is missing. Return 404 for unknown non-page paths.";
57
+ const WAITING_DETAIL = "The kit answers waiting_for_sandbox_key: checkout waits for a Test sandbox key. Run npx @relyon/store-kit init (it sets one up privately), then restart the server.";
58
+ /** The profile parses, but without a key nothing shows it is Relyon's profile for this domain rather than a hand-written file. */
59
+ const KEYLESS_PROFILE = "The profile looks right, but without RELYON_API_KEY the doctor can't tell it from a hand-written static file: Relyon's doctor, which confirms the store's domain, is skipped. Set RELYON_API_KEY (npx @relyon/store-kit init sets up a Test key), then rerun doctor.";
60
+ /** The command a failed run ends with. */
61
+ export const RERUN_DOCTOR = "npx @relyon/store-kit doctor";
62
+ const WAITING_WITH_KEY = "The store's server is waiting for a sandbox key, but this run has one. Give the server the same RELYON_API_KEY (init saves it in .env or the private Relyon folder) and restart it.";
63
+ export const DEFAULT_RELYON_BASE_URL = "https://core.getrelyon.com/api";
64
+ const USER_AGENT = `Relyon-Doctor/${KIT_VERSION} (store-kit doctor; not an identified shopper)`;
65
+ /** The most the doctor reads from one response, and the most a gzip feed may expand to. */
66
+ export const DOCTOR_MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
67
+ class ResponseTooLarge extends Error {
68
+ }
69
+ /**
70
+ * A probe's connection was refused or reset: the store may still be starting.
71
+ * Carries the same message an ordinary fetch failure would; the class only
72
+ * marks the cause so the probe layer can retry it inside the startup window.
73
+ */
74
+ class StartupError extends Error {
75
+ }
76
+ /** A store that never became ready inside the startup window: the plain verdict, with no route-order blame. */
77
+ export const STORE_STARTING = "The store is still starting or unreachable. Wait a moment and re-run the doctor.";
78
+ /** A tunnel or proxy's own error page (ngrok, a Cloudflare tunnel, a gateway's proxy page), not the store. */
79
+ const TUNNEL_ERROR_PAGE = /err_ngrok|error 1033|cloudflare[^\n]{0,120}tunnel|tunnel[^\n]{0,80}(?:offline|not (?:found|available|running))|<title>[^<]{0,120}(?:bad gateway|proxy error|service unavailable)/i;
80
+ /** Reads a body up to `limit` bytes; larger bodies are refused, never buffered whole. */
81
+ async function readLimited(response, limit) {
82
+ const declared = Number(response.headers.get("content-length"));
83
+ if (Number.isFinite(declared) && declared > limit) {
84
+ await response.body?.cancel().catch(() => { });
85
+ throw new ResponseTooLarge();
86
+ }
87
+ if (!response.body)
88
+ return new Uint8Array();
89
+ const reader = response.body.getReader();
90
+ const chunks = [];
91
+ let total = 0;
92
+ for (;;) {
93
+ const { done, value } = await reader.read();
94
+ if (done)
95
+ break;
96
+ total += value.byteLength;
97
+ if (total > limit) {
98
+ await reader.cancel().catch(() => { });
99
+ throw new ResponseTooLarge();
100
+ }
101
+ chunks.push(value);
102
+ }
103
+ const bytes = new Uint8Array(total);
104
+ let offset = 0;
105
+ for (const chunk of chunks) {
106
+ bytes.set(chunk, offset);
107
+ offset += chunk.byteLength;
108
+ }
109
+ return bytes;
110
+ }
111
+ const MCP_PROTOCOL_VERSION = "2025-06-18";
112
+ /** One catalog-URL message: store-owned callbacks serve URLs without a sync; without them the sitemap reads the synced index. */
113
+ /** Where to look when a feed lists fewer products than the store shows agents. */
114
+ export const FEED_RULES = "Feeds list only agent-visible products with feed.exactPrice and feed.condition; a product with options lists each variant in feed.variants. See the feeds section (\"Source-backed discovery and feeds\") of .agents/skills/relyon-catalog/SKILL.md, and log feeds.onDiagnostic in createStoreKit: it names each omitted product and why.";
115
+ const FEED_EMPTY = `A valid feed with no products yet. ${FEED_RULES}`;
116
+ /** A product page URL compared without its fragment. */
117
+ const pageKey = (value) => {
118
+ if (typeof value !== "string")
119
+ return "";
120
+ try {
121
+ const url = new URL(value);
122
+ url.hash = "";
123
+ return url.href;
124
+ }
125
+ catch {
126
+ return value;
127
+ }
128
+ };
129
+ export const CATALOG_URL_FIX = "Give each agent-visible product a url on the store's own domain in its catalog.source callbacks "
130
+ + "(store-owned catalog callbacks need no sync). Without catalog.source, the sitemap reads Relyon's index, which kit.syncCatalog fills.";
131
+ /** The Relyon doctor checks of the older Relyon-priced flow, which don't apply to a store-first app. */
132
+ const LEGACY_CHECKS = new Set(["pricing", "checkout"]);
133
+ /** The public doctor checks with a manifest id (`relyon-doctor-<check>`). */
134
+ const KNOWN_REMOTE_CHECKS = new Set(["keys", "webhook", "catalog", "pricing", "checkout"]);
135
+ /** Store-first findings the server reports under those checks: real blockers, which always FAIL. */
136
+ const STORE_FIRST_BLOCKER = /Observed blocker|Unverified|Fixture only|Required condition:/;
137
+ /** The kit routes that, all passing in this run, positively show a store-first app on a verified domain. */
138
+ const STORE_FIRST_EVIDENCE = ["/.well-known/ucp", "relyon-verification", "llms.txt", "/mcp initialize"];
139
+ const SECRET_PATTERN = /\brly_whsec_(?:test|live)_[A-Za-z0-9_-]+|\b(?:rly|rk|sk|pk)_(?:test|live)_[A-Za-z0-9_-]+|\bwhsec_[A-Za-z0-9_-]+/g;
140
+ /** Removes the given secrets and anything shaped like a Relyon key or webhook secret. */
141
+ export function redactSecrets(text, secrets = []) {
142
+ let out = text;
143
+ for (const secret of secrets)
144
+ if (secret && secret.length >= 6)
145
+ out = out.split(secret).join("[redacted]");
146
+ return out.replace(SECRET_PATTERN, "[redacted]");
147
+ }
148
+ /**
149
+ * Makes server-controlled text safe to print on a terminal: C0 and C1 control
150
+ * characters (escape sequences, carriage returns, line breaks) and Unicode
151
+ * bidirectional overrides become "?", so a remote answer can't rewrite or
152
+ * reorder what the doctor prints.
153
+ */
154
+ export function terminalSafe(text) {
155
+ return text.replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "?");
156
+ }
157
+ /**
158
+ * A path segment the doctor may print as it is: a short word such as "api",
159
+ * "v1", "doctor" or "sign-in" once percent-decoding is undone. Anything else
160
+ * (long, encoded, digit-heavy or key-shaped) could be a token and is hidden.
161
+ */
162
+ function plainSegment(segment) {
163
+ let decoded;
164
+ try {
165
+ decoded = decodeURIComponent(segment);
166
+ }
167
+ catch {
168
+ return false;
169
+ }
170
+ return decoded === segment && /^[A-Za-z_][A-Za-z0-9._-]{0,23}$/.test(decoded)
171
+ && !/^(?:rly|pk|sk|rk|rc)_/i.test(decoded) && (decoded.match(/[0-9]/g)?.length ?? 0) < 6;
172
+ }
173
+ /**
174
+ * A URL as the doctor prints it: scheme, host and path only. Credentials, the
175
+ * query string and the fragment are dropped (they may carry a token), every
176
+ * path segment that isn't a short plain word is shown as "…" (a sign-in page's
177
+ * path can carry a session or reset token, possibly percent-encoded), and
178
+ * anything shaped like a Relyon key is redacted.
179
+ */
180
+ export function printableUrl(value, base) {
181
+ let url;
182
+ try {
183
+ url = base !== undefined ? new URL(value, base) : new URL(value);
184
+ }
185
+ catch {
186
+ return "(not a valid URL)";
187
+ }
188
+ if (url.protocol !== "https:" && url.protocol !== "http:")
189
+ return `(a ${terminalSafe(url.protocol.slice(0, 20))} URL)`;
190
+ const dropped = url.search || url.hash || url.username || url.password ? " (query removed)" : "";
191
+ const segments = url.pathname.split("/");
192
+ const hidden = segments.some((segment) => segment !== "" && !plainSegment(segment));
193
+ const path = segments.slice(0, 20).map((segment) => segment === "" || plainSegment(segment) ? segment : "…").join("/")
194
+ + (segments.length > 20 ? "/…" : "");
195
+ const shown = `${url.origin}${path}`;
196
+ const note = dropped && hidden ? " (query and parts of the path hidden)" : hidden ? " (parts of the path hidden)" : dropped;
197
+ return `${terminalSafe(redactSecrets(shown.length > 300 ? `${shown.slice(0, 300)}…` : shown))}${note}`;
198
+ }
199
+ /**
200
+ * Where a redirect points, as the doctor prints it: only its origin. The
201
+ * Location comes from whatever answered (a sign-in or protection page), and
202
+ * its path can carry a short session or reset token that no heuristic can
203
+ * tell from a word, so no part of the path is printed.
204
+ */
205
+ export function printableOrigin(value, base) {
206
+ let url;
207
+ try {
208
+ url = base !== undefined ? new URL(value, base) : new URL(value);
209
+ }
210
+ catch {
211
+ return "(not a valid URL)";
212
+ }
213
+ if (url.protocol !== "https:" && url.protocol !== "http:")
214
+ return `(a ${terminalSafe(url.protocol.slice(0, 20))} URL)`;
215
+ const more = url.pathname !== "/" || url.search || url.hash || url.username || url.password ? " (path not shown)" : "";
216
+ return `${terminalSafe(redactSecrets(url.origin.slice(0, 300)))}${more}`;
217
+ }
218
+ /**
219
+ * Relyon's store-first `check_unavailable` text repeats every legacy probe and
220
+ * evidence rule; the kit shows only the required conditions (at most 3) and a
221
+ * short fix, so the step stays a few lines.
222
+ */
223
+ export function shortCheckUnavailable(failure) {
224
+ const clip = (text, max) => text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
225
+ const conditions = [...failure.explanation.matchAll(/Required condition: (.*?)(?= Required evidence:|$)/g)]
226
+ .map((match) => match[1].trim()).filter(Boolean);
227
+ const unique = [...new Set(conditions)];
228
+ const needs = unique.length
229
+ ? `Relyon could not confirm: ${unique.slice(0, 3).map((condition) => clip(condition, 160)).join(" ")}${unique.length > 3 ? ` (+${unique.length - 3} more)` : ""}`
230
+ : clip(failure.explanation, 300);
231
+ const fixes = [...new Set(failure.fix.split(/(?<=\.)\s+/).map((sentence) => sentence.trim()).filter(Boolean))];
232
+ return `${failure.code}: ${needs} Fix: ${clip(fixes.slice(0, 2).join(" "), 300)}`;
233
+ }
234
+ /** One line per item: `PASS name detail`. */
235
+ export function formatStoreDoctor(result, secrets = [], options = {}) {
236
+ const width = Math.max(...result.items.map((item) => item.name.length), 4);
237
+ // "PENDING merchant" is only for items carrying owner to-dos; an agent-actionable
238
+ // pending item (run a kit command after publish) prints plain "PENDING".
239
+ const label = (item) => item.status === "PENDING" && item.merchantTodo?.length ? "PENDING merchant" : item.status;
240
+ const lines = result.items.map((item) => `${label(item).padEnd(16)} ${terminalSafe(item.name).padEnd(width)} ${terminalSafe(item.detail)}`);
241
+ const count = (name) => result.items.filter((item) => label(item) === name).length;
242
+ const counts = ["PASS", "FAIL", "PENDING merchant", "PENDING", "N/A", "UNVERIFIED"].map((name) => `${count(name)} ${name}`);
243
+ const warnings = result.items.filter((item) => item.status === "WARN").length;
244
+ if (warnings)
245
+ counts.splice(2, 0, `${warnings} WARN`);
246
+ const notDone = result.items.filter((item) => item.status === "NOT DONE").length;
247
+ if (notDone)
248
+ counts.splice(1, 0, `${notDone} NOT DONE`);
249
+ // While a required step is missing, the footer never reads as finished: no
250
+ // "No failures", no zero counts.
251
+ const unfinished = options.verdict === "not_done" || notDone > 0;
252
+ if (result.ok && unfinished)
253
+ lines.push("", `NOT DONE yet (see the steps above): ${counts.filter((count) => !count.startsWith("0 ")).join(", ")}.`);
254
+ else if (result.ok)
255
+ lines.push("", `No failures: ${counts.join(", ")}.`);
256
+ // The CLI prints its own verdict and "Do this next" list above the items: one summary, not two.
257
+ else if (options.nextSteps === false)
258
+ lines.push("", `Failures found: ${counts.join(", ")}.`);
259
+ else {
260
+ // Failures read as direct next steps, in the order the doctor found them.
261
+ const failed = result.items.filter((item) => item.status === "FAIL");
262
+ lines.push("", `NOT DONE: ${failed.length} of ${result.items.length} checks failed.`, "Next:", ...failed.map((item, index) => ` ${index + 1}. ${terminalSafe(item.name)}: ${terminalSafe(item.detail)}`), ` Then rerun doctor: ${RERUN_DOCTOR}`, `Failures found: ${counts.join(", ")}.`);
263
+ }
264
+ const todos = [...new Set(result.items.flatMap(item => item.merchantTodo ?? []))];
265
+ if (todos.length)
266
+ lines.push("", "Merchant to-do (owner to fill in):", ...todos.map(question => `- ${terminalSafe(question)}`), AGENT_CHECKOUT_OFF, DO_NOT_INVENT, FINAL_MESSAGE_TODOS);
267
+ return forKitPackage(redactSecrets(lines.join("\n"), secrets) + "\n");
268
+ }
269
+ function storeOrigin(value) {
270
+ let url;
271
+ try {
272
+ url = new URL(value);
273
+ }
274
+ catch {
275
+ throw new TypeError("STORE_PUBLIC_URL is not a valid URL.");
276
+ }
277
+ if (url.protocol !== "https:" && url.protocol !== "http:")
278
+ throw new TypeError("STORE_PUBLIC_URL must be an http(s) URL.");
279
+ if (url.username || url.password || url.search || url.hash || (url.pathname !== "/" && url.pathname !== "")) {
280
+ throw new TypeError("STORE_PUBLIC_URL must be the store's origin only, such as https://shop.example.com (no path, query or credentials).");
281
+ }
282
+ return url;
283
+ }
284
+ const sameOrigin = (value, origin) => {
285
+ try {
286
+ const url = new URL(value, origin);
287
+ return url.origin === origin && !url.username && !url.password;
288
+ }
289
+ catch {
290
+ return false;
291
+ }
292
+ };
293
+ const links = (text) => [...text.matchAll(/https?:\/\/[^\s<>"')\]]+/g)].map((match) => match[0]);
294
+ /** The usable ES256 P-256 signing keys a UCP profile publishes (what Live hand-off verification uses). */
295
+ function liveSigningKeys(profile) {
296
+ if (!isRecord(profile) || !Array.isArray(profile.keys))
297
+ return [];
298
+ return profile.keys.filter((key) => isRecord(key) && typeof key.kid === "string" && liveSigningKey([key], key.kid) !== null);
299
+ }
300
+ /** Thrown when Relyon answered with a redirect or a web page instead of data. */
301
+ class RelyonWebPage extends Error {
302
+ constructor() { super("Relyon answered with a web page instead of data."); }
303
+ }
304
+ /** True for an HTML answer: an HTML content type, or (without a JSON type) a body that opens with "<". */
305
+ async function looksLikeWebPage(response) {
306
+ const type = (response.headers.get("content-type") ?? "").toLowerCase();
307
+ if (type.includes("json"))
308
+ return false;
309
+ if (type.includes("text/html") || type.includes("xhtml"))
310
+ return true;
311
+ if (!response.body)
312
+ return false;
313
+ try {
314
+ const reader = response.clone().body.getReader();
315
+ const { value } = await reader.read();
316
+ // Not awaited: cancelling one branch of a cloned body can wait on the other.
317
+ void reader.cancel().catch(() => { });
318
+ return /^(?:\ufeff)?\s*</.test(new TextDecoder().decode((value ?? new Uint8Array()).slice(0, 512)));
319
+ }
320
+ catch {
321
+ return false;
322
+ }
323
+ }
324
+ /** The first system error code on a fetch failure (Node wraps it in `cause`, happy eyeballs in `errors`). */
325
+ function errorCode(error, depth = 0) {
326
+ if (depth > 5 || typeof error !== "object" || error === null)
327
+ return undefined;
328
+ const { code, cause, errors } = error;
329
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]{1,40}$/.test(code))
330
+ return code;
331
+ if (Array.isArray(errors))
332
+ for (const inner of errors) {
333
+ const found = errorCode(inner, depth + 1);
334
+ if (found)
335
+ return found;
336
+ }
337
+ return errorCode(cause, depth + 1);
338
+ }
339
+ const DNS_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_NONAME", "EAI_FAIL", "EAI_NODATA"]);
340
+ const BLOCKED_CODES = new Set(["ENETUNREACH", "EHOSTUNREACH", "ENETDOWN", "EHOSTDOWN", "EACCES", "EPERM", "ECONNRESET", "EPIPE"]);
341
+ const TLS_CODE = /^(?:CERT_|UNABLE_TO_|SELF_SIGNED_|DEPTH_ZERO_|ERR_TLS_|ERR_SSL_)/;
342
+ /** The doctor's one line for "Relyon could not be asked", by what went wrong. Never advice to change or redeploy the store. */
343
+ function relyonUnavailable(error, seen, timeoutMs) {
344
+ const tried = seen.url ? printableUrl(seen.url) : "Relyon's API";
345
+ if (seen.webPage) {
346
+ const status = seen.status ?? 0;
347
+ const what = status >= 300 && status < 400
348
+ ? `HTTP ${status}, a redirect to ${seen.webPage.location ? printableOrigin(seen.webPage.location, seen.url) : "(no Location given)"}`
349
+ : `HTTP ${status}, an HTML page`;
350
+ return `Relyon's server answered with a web page instead of data (${what}) when the doctor asked ${tried}. `
351
+ + "Relyon's API may be behind access protection or temporarily unavailable. "
352
+ + "This was not caused by your store or its network, and nothing on the store needs to change. "
353
+ + `Try again later. If it keeps happening, check that the Relyon base URL (RELYON_BASE_URL or --base-url) is ${DEFAULT_RELYON_BASE_URL}, then contact Relyon support.`;
354
+ }
355
+ if (error.kind === "server_error") {
356
+ return `Relyon's server had an error (HTTP ${error.status ?? seen.status ?? "5xx"}) at ${tried}. Relyon is temporarily unavailable; this isn't caused by your store. Try again in a few minutes.`;
357
+ }
358
+ if (error.kind === "timeout") {
359
+ return `Relyon did not answer within ${timeoutMs} ms at ${tried}. Relyon may be slow, or the network between this machine and Relyon is dropping the connection. Try again.`;
360
+ }
361
+ const code = errorCode(seen.error);
362
+ if (code && DNS_CODES.has(code)) {
363
+ return `This machine could not look up the name of Relyon's server (a DNS failure, ${code}) for ${tried}. Check this machine's internet connection and DNS, and the Relyon base URL (RELYON_BASE_URL or --base-url).`;
364
+ }
365
+ if (code === "ECONNREFUSED") {
366
+ return `The connection to ${tried} was refused (ECONNREFUSED): nothing accepted it at that address. Check the Relyon base URL (RELYON_BASE_URL or --base-url) and try again.`;
367
+ }
368
+ if (code && (BLOCKED_CODES.has(code) || TLS_CODE.test(code))) {
369
+ return `The network blocked or interrupted the connection to ${tried} (${code}). This machine may not be allowed to reach the internet, or a firewall or proxy stops it. Run the doctor from a machine with outbound HTTPS access.`;
370
+ }
371
+ if (error.kind === "malformed") {
372
+ return `Relyon's answer at ${tried}${seen.status ? ` (HTTP ${seen.status})` : ""} wasn't the data the doctor expects: ${terminalSafe(error.message)} Try again later.`;
373
+ }
374
+ const reason = seen.error instanceof Error ? seen.error.message : error.message;
375
+ return `Relyon could not be reached at ${tried}${code ? ` (${code})` : ""}: ${terminalSafe(redactSecrets(String(reason))).slice(0, 300)}`;
376
+ }
377
+ /** Runs every check and returns the items; `ok` is false only when an item FAILs. */
378
+ export async function runStoreDoctor(options) {
379
+ const kitVersion = await diagnoseKitVersion({ projectDir: options.projectDir, ...options.kitVersionOptions });
380
+ let kitVersionDelivery = "unavailable";
381
+ const items = [];
382
+ // Every check carries its stable checklist-manifest id (checklist-manifest.ts);
383
+ // Relyon and the dashboard match stored run outcomes by it, never by wording.
384
+ const add = (name, status, detail) => {
385
+ const checkId = checkIdForItem(name);
386
+ items.push(checkId ? { name, status, detail, checkId } : { name, status, detail });
387
+ };
388
+ const merchant = (name, questions) => {
389
+ const checkId = checkIdForItem(name);
390
+ items.push({
391
+ name, status: live || options.strict ? "FAIL" : "PENDING",
392
+ detail: `${OWNER_TO_FILL_IN} ${questions.join(" ")} ${AGENT_CHECKOUT_OFF} ${DO_NOT_INVENT}`, merchantTodo: questions,
393
+ ...(checkId ? { checkId } : {}),
394
+ });
395
+ };
396
+ const newerKitVersion = legacyNewerKitVersion(kitVersion);
397
+ const done = () => ({
398
+ items, ok: !items.some((item) => item.status === "FAIL"), kitVersion, kitVersionDelivery,
399
+ ...(newerKitVersion ? { newerKitVersion } : {}),
400
+ });
401
+ const fetchImpl = options.fetch ?? ((request, init) => fetch(request, init));
402
+ const timeoutMs = options.timeoutMs ?? 10_000;
403
+ // 1. Configuration.
404
+ let origin;
405
+ let live = false;
406
+ let keyUsable = false;
407
+ /** Test with no Relyon domain on this address yet (any preview or development address). */
408
+ let preview = false;
409
+ let loopback = false;
410
+ /** The webhook route's path (the kit's paths.webhook). */
411
+ const webhookPath = options.webhookPath ?? "/relyon/webhooks";
412
+ /** The webhook route item once its unsigned-refusal probe passes; the signed-challenge proof then upgrades or fails it. */
413
+ let webhookRouteItem;
414
+ // An empty, placeholder or malformed key counts as no key.
415
+ const apiKey = usableApiKey(options.apiKey);
416
+ try {
417
+ const url = storeOrigin(options.storeUrl);
418
+ origin = url.origin;
419
+ loopback = isLoopbackHostname(url.hostname);
420
+ if (apiKey) {
421
+ live = liveModeFor({ apiKey, ...(options.live !== undefined ? { live: options.live } : {}) });
422
+ keyUsable = true;
423
+ }
424
+ else if (options.live) {
425
+ throw new TypeError("--live needs the store's Live secret key in RELYON_API_KEY.");
426
+ }
427
+ if (live) {
428
+ if (url.protocol !== "https:")
429
+ throw new TypeError("Live mode needs an https STORE_PUBLIC_URL.");
430
+ const reason = nonPublicStoreHost(url.hostname);
431
+ if (reason)
432
+ throw new TypeError(`Live mode refuses the store hostname "${url.hostname}": ${reason}.`);
433
+ }
434
+ add("store URL", "PASS", `${origin} (${live ? "Live" : "Test"} mode)`);
435
+ }
436
+ catch (error) {
437
+ add("store URL", "FAIL", error.message);
438
+ return done();
439
+ }
440
+ if (placeholderApiKey(options.apiKey))
441
+ add("Relyon key", "UNVERIFIED", "RELYON_API_KEY is a placeholder or malformed value, not a Relyon key, so it counts as no key: Relyon's doctor is skipped. Run npx @relyon/store-kit init to set up a Test key.");
442
+ else if (!apiKey && options.savedKeyWithheld)
443
+ add("Relyon key", "UNVERIFIED", `The saved Test key was not sent: the Relyon base URL is not ${DEFAULT_RELYON_BASE_URL}, so Relyon's doctor is skipped. Rerun with --allow-saved-key-to-base-url only if you trust that address.`);
444
+ else if (!apiKey)
445
+ add("Relyon key", "UNVERIFIED", "RELYON_API_KEY is not set: Relyon's doctor is skipped.");
446
+ else
447
+ add("Relyon key", "PASS", live ? "Live secret key with the explicit Live opt-in." : "Test secret key.");
448
+ const html = (result) => /<(?:html|script|body)\b/i.test(result.text) || result.type.includes("text/html");
449
+ const jsonOf = (result) => { try {
450
+ return JSON.parse(result.text);
451
+ }
452
+ catch {
453
+ return undefined;
454
+ } };
455
+ /**
456
+ * The kit's own waiting answer: exactly 503 with its waiting body. The only
457
+ * answer the doctor accepts as "pending" on the discovery paths; any other
458
+ * status or body there (a plain or JSON 404, a 500, a catch-all 200) is not
459
+ * the kit and FAILs, with or without a key.
460
+ */
461
+ const waiting = (result) => !(result instanceof Error) && result.status === 503 && isWaitingBody(jsonOf(result));
462
+ /** A Cloudflare challenge page (a private-preview wall), never a startup signal. */
463
+ const challengePage = (result) => result.cfMitigated === "challenge"
464
+ || ((result.status === 403 || result.status === 429 || result.status === 503)
465
+ && /cdn-cgi\/challenge-platform|cf-chl-|<title>\s*just a moment/i.test(result.text));
466
+ /**
467
+ * An answer that looks like a store still starting: the connection was
468
+ * refused or reset, a gateway answered 502/503/504 (never the kit's own
469
+ * waiting body), a tunnel or proxy served its own error page, or the answer
470
+ * is empty or HTML on a path where the kit or a discovery file never serves
471
+ * HTML. A Cloudflare challenge is a private-preview wall, not a startup.
472
+ */
473
+ const startupAnswer = (result) => {
474
+ if (result instanceof Error)
475
+ return result instanceof StartupError;
476
+ if (waiting(result) || challengePage(result))
477
+ return false;
478
+ if (result.status >= 502 && result.status <= 504)
479
+ return true;
480
+ if (TUNNEL_ERROR_PAGE.test(result.text.slice(0, 8192)))
481
+ return true;
482
+ if (result.status === 200 && result.bytes.length === 0)
483
+ return true;
484
+ return html(result);
485
+ };
486
+ const get = async (path, init = {}) => {
487
+ const controller = new AbortController();
488
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
489
+ // Every request stays on the store's origin: a path is resolved against
490
+ // it and refused unless the result is still that exact origin (a "//host"
491
+ // path would otherwise name another host).
492
+ let target;
493
+ try {
494
+ target = new URL(path, origin);
495
+ }
496
+ catch {
497
+ clearTimeout(timer);
498
+ return new Error("not a URL on the store's origin");
499
+ }
500
+ if (!path.startsWith("/") || path.startsWith("//") || target.origin !== origin) {
501
+ clearTimeout(timer);
502
+ return new Error(`refused: ${JSON.stringify(path)} is not a path on ${origin}`);
503
+ }
504
+ try {
505
+ const request = new Request(target, {
506
+ method: init.method ?? "GET", redirect: "manual",
507
+ headers: { "user-agent": USER_AGENT, ...init.headers },
508
+ ...(init.body !== undefined ? { body: init.body } : {}),
509
+ signal: controller.signal,
510
+ });
511
+ const response = await fetchImpl(request, { signal: controller.signal });
512
+ const bytes = await readLimited(response, DOCTOR_MAX_RESPONSE_BYTES);
513
+ return { status: response.status, type: response.headers.get("content-type") ?? "", text: new TextDecoder().decode(bytes), bytes, location: response.headers.get("location"), cfMitigated: response.headers.get("cf-mitigated"), testPreview: response.headers.get(TEST_PREVIEW_HEADER) === "no-domain", acknowledgement: response.headers.get(DOCTOR_ACKNOWLEDGEMENT_HEADER) };
514
+ }
515
+ catch (error) {
516
+ if (error instanceof ResponseTooLarge)
517
+ return new Error(`the response is larger than ${DOCTOR_MAX_RESPONSE_BYTES} bytes`);
518
+ const message = controller.signal.aborted ? `no answer within ${timeoutMs} ms` : `could not connect (${error?.message ?? String(error)})`;
519
+ const code = controller.signal.aborted ? undefined : errorCode(error);
520
+ return code === "ECONNREFUSED" || code === "ECONNRESET" ? new StartupError(message) : new Error(message);
521
+ }
522
+ finally {
523
+ clearTimeout(timer);
524
+ }
525
+ };
526
+ // A store right after it was started answers connection refusals, gateway
527
+ // 502/503/504s, tunnel error pages or empty/HTML shells before its routes
528
+ // are up. Probes that expect a kit or discovery answer retry such answers
529
+ // inside one shared window (~12 s over a few attempts) before judging, so a
530
+ // slow start never reads as a catch-all misconfiguration. Page probes (the
531
+ // checkout and product pages, where HTML is correct) use `get` directly.
532
+ const startupGraceMs = options.startupGraceMs ?? 12_000;
533
+ const startupRetryMs = options.startupRetryMs ?? 1_500;
534
+ const startupDeadline = Date.now() + startupGraceMs;
535
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
536
+ const probe = async (path, init = {}) => {
537
+ for (;;) {
538
+ const result = await get(path, init);
539
+ if (!startupAnswer(result) || Date.now() >= startupDeadline) {
540
+ // Past the window a persistent non-kit 502/503/504 or tunnel/proxy
541
+ // error page still means "starting or unreachable"; an empty or HTML
542
+ // answer is judged as it is (a real catch-all looks identical).
543
+ if (!(result instanceof Error) && !waiting(result) && !challengePage(result)
544
+ && ((result.status >= 502 && result.status <= 504) || TUNNEL_ERROR_PAGE.test(result.text.slice(0, 8192))))
545
+ return { ...result, stillStarting: true };
546
+ return result;
547
+ }
548
+ await sleep(Math.min(startupRetryMs, Math.max(1, startupDeadline - Date.now())));
549
+ }
550
+ };
551
+ /** The still-starting verdict: a store that isn't up yet, never route-order blame. */
552
+ const starting = (result) => result instanceof StartupError || (!(result instanceof Error) && result.stillStarting === true);
553
+ /**
554
+ * A private preview, not the store: an unauthenticated visitor gets a
555
+ * redirect to an external sign-in page, or the deployment answers with a
556
+ * Cloudflare challenge. Every probe then fails with generic redirect or
557
+ * catch-all FAILs that name nothing fixable, so the shared branches name
558
+ * the wall instead. Redirect targets stay origin-only.
559
+ */
560
+ const privatePreview = (result, path) => {
561
+ if (result instanceof Error)
562
+ return undefined;
563
+ if (result.status >= 300 && result.status < 400 && result.location) {
564
+ let target;
565
+ try {
566
+ target = new URL(result.location, origin);
567
+ }
568
+ catch {
569
+ return undefined;
570
+ }
571
+ if (target.origin !== origin && /^\/(?:login|signin|sign-in)(?:\/|$)/i.test(target.pathname))
572
+ return `${path} redirects (${result.status}) to a sign-in page (${printableOrigin(result.location, origin)}): the preview is private, publish or use the public URL.`;
573
+ return undefined;
574
+ }
575
+ // A Cloudflare challenge counts only on a challenge status or Cloudflare's
576
+ // own header; a 200 whose body merely mentions the challenge platform (an
577
+ // app shell bundling the script, say) falls through to the normal checks.
578
+ const challenge = result.cfMitigated === "challenge"
579
+ || ((result.status === 403 || result.status === 429 || result.status === 503)
580
+ && /cdn-cgi\/challenge-platform|cf-chl-|<title>\s*just a moment/i.test(result.text));
581
+ if (challenge)
582
+ return `${path} answers a Cloudflare challenge (${result.status}): the preview is private, publish or use the public URL.`;
583
+ return undefined;
584
+ };
585
+ /** The catch-all verdict, naming a private-preview wall instead when the answer is one. */
586
+ const catchAll = (result, path) => starting(result) ? STORE_STARTING : privatePreview(result, path) ?? CATCH_ALL_FIX;
587
+ /** The common failures: still starting, unreachable, redirected, or not 200. Returns null when the response is a 200. */
588
+ const problem = (result, path) => {
589
+ if (starting(result))
590
+ return STORE_STARTING;
591
+ if (result instanceof Error)
592
+ return `${path}: ${result.message}.`;
593
+ const wall = privatePreview(result, path);
594
+ if (wall)
595
+ return wall;
596
+ if (result.status >= 300 && result.status < 400)
597
+ return `${path} redirects (${result.status}${result.location ? ` to ${result.location}` : ""}); agents and Relyon don't follow redirects. Serve it on the store's own origin.`;
598
+ if (result.status !== 200)
599
+ return `${path} answered ${result.status}${result.status === 404 ? ": not served. Mount the kit's routes on the store's server" : ""}.`;
600
+ return null;
601
+ };
602
+ // 2. The UCP business profile. Without a key the kit answers only its 503
603
+ // waiting status here; a server that has a key (even when this doctor run
604
+ // has none) answers its profile, which is checked in full below.
605
+ /** The served profile, for the cart-transfer row (set only when it is a UCP profile). */
606
+ let servedProfile;
607
+ {
608
+ const result = await probe("/.well-known/ucp");
609
+ const failed = problem(result, "/.well-known/ucp");
610
+ const profileJson = (fetched) => { const value = jsonOf(fetched); return isRecord(value) && isRecord(value.ucp); };
611
+ if (!(result instanceof Error) && (html(result) || (result.status === 200 && !profileJson(result))))
612
+ add("/.well-known/ucp", "FAIL", catchAll(result, "/.well-known/ucp"));
613
+ else if (waiting(result))
614
+ add("/.well-known/ucp", apiKey ? "FAIL" : "UNVERIFIED", apiKey ? WAITING_WITH_KEY : WAITING_DETAIL);
615
+ else if (failed)
616
+ add("/.well-known/ucp", "FAIL", failed);
617
+ else {
618
+ const fetched = result;
619
+ let profile;
620
+ try {
621
+ profile = JSON.parse(fetched.text);
622
+ }
623
+ catch {
624
+ profile = undefined;
625
+ }
626
+ const ucp = isRecord(profile) && isRecord(profile.ucp) ? profile.ucp : undefined;
627
+ if (ucp)
628
+ servedProfile = profile;
629
+ const services = ucp && isRecord(ucp.services) && Array.isArray(ucp.services["dev.ucp.shopping"]) ? ucp.services["dev.ucp.shopping"] : [];
630
+ const checkout = ucp && isRecord(ucp.capabilities) && Array.isArray(ucp.capabilities["dev.ucp.shopping.checkout"]) ? ucp.capabilities["dev.ucp.shopping.checkout"] : [];
631
+ const endpoints = services.filter(isRecord).map((service) => String(service.endpoint ?? ""));
632
+ if (!ucp || typeof ucp.version !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(ucp.version))
633
+ add("/.well-known/ucp", "FAIL", "Not a UCP profile (no ucp.version). Serve the kit's /.well-known/ucp, not the app's fallback page.");
634
+ else if (!services.length || !checkout.length)
635
+ add("/.well-known/ucp", "FAIL", "The profile advertises no shopping service or checkout capability. Check the store's domain is verified in Relyon.");
636
+ else if (endpoints.some((endpoint) => !sameOrigin(endpoint, origin)))
637
+ add("/.well-known/ucp", "FAIL", `A shopping endpoint is not on ${origin}: ${endpoints.filter((endpoint) => !sameOrigin(endpoint, origin)).join(", ")}.`);
638
+ else if (!endpoints.some((endpoint) => new URL(endpoint, origin).pathname === "/ucp"))
639
+ add("/.well-known/ucp", "FAIL", "No REST shopping endpoint at the store's /ucp.");
640
+ else if (live && !liveSigningKeys(profile).length)
641
+ add("/.well-known/ucp", "FAIL", "The Live profile advertises checkout but publishes no ES256 signing key, so Live hand-off links can't be verified and land unattributed. Relyon advertises Live checkout, with its keys, only for a store approved for Live; serve the kit's /.well-known/ucp and check the store's Live approval.");
642
+ else if (!apiKey)
643
+ add("/.well-known/ucp", "UNVERIFIED", KEYLESS_PROFILE);
644
+ else
645
+ add("/.well-known/ucp", "PASS", `UCP ${ucp.version}; shopping endpoints on the store's own origin.${live ? ` Live checkout with ${liveSigningKeys(profile).length} published signing key${liveSigningKeys(profile).length === 1 ? "" : "s"}.` : ""}`);
646
+ }
647
+ }
648
+ // The store's agent-visible products from its own MCP search_products (read once, on first use).
649
+ let mcpProductsRead;
650
+ const mcpProducts = () => (mcpProductsRead ??= readMcpProducts(probe));
651
+ // 2b. UCP cart transfer (additive row; see doctor-cart-transfer.ts). Its API
652
+ // calls (cart creation, the well-known profile) retry startup-looking
653
+ // answers; the continue_url landing is a page, where HTML is correct, so it
654
+ // fetches directly.
655
+ if (servedProfile !== undefined) {
656
+ const probeApi = (path, init = {}) => init.method === "POST" || path.startsWith("/.well-known/") ? probe(path, init) : get(path, init);
657
+ const row = await cartTransferCheck(probeApi, origin, servedProfile, live, { products: mcpProducts, callerKey: options.cartTransferKey });
658
+ add("cart transfer", row.status, row.detail);
659
+ }
660
+ else {
661
+ // The profile check above already reported why; this row only says the
662
+ // transfer itself could not be tried. Never a fabricated pass.
663
+ add("cart transfer", "UNVERIFIED", "The UCP profile could not be read, so a cart transfer could not be tried.");
664
+ }
665
+ // 3. The domain verification file.
666
+ {
667
+ const hostname = new URL(origin).hostname;
668
+ const verifyNext = `Run kit.verifyDomain(${JSON.stringify(hostname)}), then rerun ${RERUN_DOCTOR}.`;
669
+ let domain;
670
+ let lookupError;
671
+ if (apiKey && !loopback) {
672
+ try {
673
+ domain = await findDomain(new RelyonGateway({
674
+ baseUrl: options.baseUrl ?? DEFAULT_RELYON_BASE_URL, apiKey,
675
+ ...(live ? { live: true } : {}), timeoutMs, fetch: fetchImpl,
676
+ }), hostname);
677
+ }
678
+ catch (error) {
679
+ lookupError = error;
680
+ }
681
+ }
682
+ const result = await probe("/.well-known/relyon-verification");
683
+ const failed = problem(result, "/.well-known/relyon-verification");
684
+ const verificationValue = (fetched) => /^relyon-domain-verification=\S+$/.test(fetched.text.trim());
685
+ if (!(result instanceof Error) && (html(result) || (result.status === 200 && !verificationValue(result))))
686
+ add("relyon-verification", "FAIL", catchAll(result, "/.well-known/relyon-verification"));
687
+ else if (waiting(result))
688
+ add("relyon-verification", apiKey ? "FAIL" : "UNVERIFIED", apiKey ? WAITING_WITH_KEY : "Pending sandbox key and domain verification; continue building.");
689
+ else if (failed && !(!live && !domain && !(result instanceof Error) && result.status === 404 && result.testPreview)) {
690
+ add("relyon-verification", "FAIL", failed);
691
+ }
692
+ else if (lookupError) {
693
+ const reason = lookupError instanceof RelyonProblemError
694
+ ? `HTTP ${lookupError.status} ${lookupError.code}: ${lookupError.message}`
695
+ : lookupError instanceof Error ? lookupError.message : String(lookupError);
696
+ add("relyon-verification", "UNVERIFIED", `Relyon's domain lookup failed: ${terminalSafe(redactSecrets(reason, [apiKey]))}. Resolve this API/authentication/scope/network problem and rerun ${RERUN_DOCTOR}; a served file does not prove ownership.`);
697
+ }
698
+ else if (!live && !domain && !(result instanceof Error) && result.status === 404 && result.testPreview) {
699
+ // Test on an address with no Relyon domain yet. Loopback stays N/A (it
700
+ // can never be a verified domain). On a public address this is the
701
+ // agent's own step: add and verify the domain with the kit.
702
+ preview = true;
703
+ if (loopback) {
704
+ add("relyon-verification", "N/A", `${TEST_ON_PREVIEW}: a loopback address has no Relyon domain to verify. Test agent checkout still requires complete merchant-confirmed policies and all server gates. Live still needs a published, verified domain. ${GO_LIVE_STEPS}`);
705
+ }
706
+ else {
707
+ // An agent-actionable pending step, promoted to FAIL under --strict
708
+ // like the other pending items.
709
+ add("relyon-verification", options.strict ? "FAIL" : "PENDING", `${TEST_ON_PREVIEW}: this public Test address has no Relyon domain yet. Call kit.ensureDomain() (or add it in the Relyon dashboard), serve its verification value, then ${verifyNext} Test agent checkout still requires complete policies and all server gates. Live still needs the verified domain. ${GO_LIVE_STEPS} ${AGENT_DOMAIN_STEP(hostname)}`);
710
+ }
711
+ }
712
+ else if (failed) {
713
+ // Without a key the kit answers only its 503 waiting status here, so any
714
+ // other failure means the kit isn't serving this path.
715
+ add("relyon-verification", "FAIL", apiKey && result.status === 404
716
+ ? "No Relyon domain matches this host. Add it with kit.ensureDomain() (or the dashboard), then verify it."
717
+ : failed);
718
+ }
719
+ else if (loopback && !live)
720
+ add("relyon-verification", "N/A", "Loopback has no public domain to verify; the served file is not ownership evidence. Live needs a published, verified domain.");
721
+ else if (!apiKey)
722
+ add("relyon-verification", "UNVERIFIED", "The file is served, but RELYON_API_KEY is needed to read Relyon's domain status; a file alone does not prove ownership.");
723
+ else if (!domain)
724
+ add("relyon-verification", live || options.strict ? "FAIL" : "PENDING", `Relyon has no matching domain for ${hostname}. Call kit.ensureDomain(${JSON.stringify(hostname)}), then ${verifyNext} ${AGENT_DOMAIN_STEP(hostname)}`);
725
+ else if (!(result instanceof Error) && result.text.trim() !== domain.verification.record_value)
726
+ add("relyon-verification", "FAIL", `The served verification value does not match Relyon's value for ${hostname}. Serve the matching value from kit.ensureDomain(${JSON.stringify(hostname)}). ${verifyNext}`);
727
+ else if (domain.status === "pending")
728
+ add("relyon-verification", live || options.strict ? "FAIL" : "PENDING", `Relyon reports ${hostname} pending; serving the file alone does not verify ownership. ${verifyNext} ${AGENT_DOMAIN_STEP(hostname)}`);
729
+ else if (domain.status === "failed")
730
+ add("relyon-verification", "FAIL", `Relyon reports ${hostname} failed (${domain.failure_reason ?? "verification failed"}). Check the matching verification file. ${verifyNext}`);
731
+ else
732
+ add("relyon-verification", "PASS", `Relyon reports ${hostname} verified and the file serves its matching verification value.`);
733
+ }
734
+ // 4. llms.txt.
735
+ let advertised = [];
736
+ /** The product sitemap's URLs, for the missing-from-feeds warning. */
737
+ let sitemapUrls = [];
738
+ let sitemapPath = "/sitemap-products.xml";
739
+ {
740
+ const result = await probe("/llms.txt");
741
+ const failed = problem(result, "/llms.txt");
742
+ if (!(result instanceof Error) && html(result))
743
+ add("llms.txt", "FAIL", catchAll(result, "/llms.txt"));
744
+ else if (failed)
745
+ add("llms.txt", "FAIL", failed);
746
+ else {
747
+ const fetched = result;
748
+ advertised = links(fetched.text);
749
+ const own = (path) => advertised.some((link) => sameOrigin(link, origin) && new URL(link).pathname === path);
750
+ const sitemaps = advertised.filter((link) => sameOrigin(link, origin) && /sitemap[^/]*\.xml$/.test(new URL(link).pathname));
751
+ if (sitemaps.length === 1)
752
+ sitemapPath = new URL(sitemaps[0]).pathname;
753
+ if (html(fetched) || !/^#\s+\S/m.test(fetched.text))
754
+ add("llms.txt", "FAIL", CATCH_ALL_FIX);
755
+ else if (!own("/.well-known/ucp") || !own("/mcp") || sitemaps.length !== 1)
756
+ add("llms.txt", "FAIL", `It must link ${origin}/.well-known/ucp, ${origin}/mcp and one product sitemap on the store's origin.`);
757
+ else
758
+ add("llms.txt", "PASS", "Links the UCP profile, MCP server and product sitemap on the store's origin.");
759
+ }
760
+ }
761
+ // 5. Product sitemap.
762
+ /** The sitemap answered with a body the doctor could read (for the product-pages row). */
763
+ let sitemapRead = false;
764
+ {
765
+ const result = await probe(sitemapPath);
766
+ const failed = problem(result, sitemapPath);
767
+ if (!(result instanceof Error) && (html(result) || (result.status === 200 && !/<urlset\b/.test(result.text))))
768
+ add("product sitemap", "FAIL", catchAll(result, sitemapPath));
769
+ else if (failed)
770
+ add("product sitemap", "FAIL", failed);
771
+ else {
772
+ sitemapRead = true;
773
+ const fetched = result;
774
+ const locations = [...fetched.text.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/g)].map((match) => match[1]);
775
+ sitemapUrls = locations.map((location) => location.replace(/&amp;/g, "&"));
776
+ if (!/<urlset\b/.test(fetched.text))
777
+ add("product sitemap", "FAIL", `${sitemapPath} is not an XML sitemap.`);
778
+ else if (!locations.length)
779
+ add("product sitemap", "FAIL", `${sitemapPath} lists no product URLs. ${CATALOG_URL_FIX}`);
780
+ else if (locations.some((location) => !sameOrigin(location.replace(/&amp;/g, "&"), origin)))
781
+ add("product sitemap", "FAIL", `Some product URLs are not on ${origin}. ${CATALOG_URL_FIX}`);
782
+ else
783
+ add("product sitemap", "PASS", `${locations.length} product URL${locations.length === 1 ? "" : "s"} on the store's origin.`);
784
+ }
785
+ }
786
+ let cartPageBody;
787
+ // 5b. Pages for human shoppers: the checkout page and a sample of the
788
+ // product pages. DONE needs each to answer 200 on the store's origin
789
+ // (same-origin redirects are followed, at most 3); otherwise the item is
790
+ // NOT DONE with the exact step.
791
+ {
792
+ /** The final answer for `path`, following same-origin redirects; an Error names an off-origin hop. */
793
+ const reach = async (path) => {
794
+ let current = path;
795
+ for (let hop = 0;; hop++) {
796
+ const result = await get(current);
797
+ if (result instanceof Error || result.status < 300 || result.status >= 400 || !result.location || hop === 3)
798
+ return { result, path: current };
799
+ let next;
800
+ try {
801
+ next = new URL(result.location, `${origin}${current}`);
802
+ }
803
+ catch {
804
+ return { result: new Error(`redirects to ${JSON.stringify(result.location.slice(0, 200))}, which is not a URL`), path: current };
805
+ }
806
+ if (!sameOrigin(next.href, origin))
807
+ return { result: new Error(`redirects off the store's origin (to ${printableOrigin(next.href)})`), path: current };
808
+ current = `${next.pathname}${next.search}`;
809
+ }
810
+ };
811
+ const pageProblem = (reached, page) => {
812
+ const { result, path } = reached;
813
+ if (starting(result))
814
+ return STORE_STARTING;
815
+ if (result instanceof Error)
816
+ return `${page}: ${result.message}.`;
817
+ if (result.status >= 300 && result.status < 400)
818
+ return `${page} keeps redirecting (${result.status} at ${path}).`;
819
+ if (result.status !== 200)
820
+ return `${page} answered ${result.status}${path !== page ? ` (at ${path})` : ""}.`;
821
+ return null;
822
+ };
823
+ const checkoutPath = options.checkoutPath ?? DEFAULT_CHECKOUT_PATH;
824
+ const layer = options.layer ?? (options.projectDir ? (await readKitConfig(options.projectDir))?.layer : undefined);
825
+ if (layer === "products" || layer === "payments") {
826
+ add(CART_PAGE_ITEM, "N/A", CART_PAGE_NOT_REQUIRED);
827
+ }
828
+ else {
829
+ const reached = await reach("/cart");
830
+ const result = reached.result;
831
+ const failed = pageProblem(reached, "/cart");
832
+ const wall = privatePreview(result, "/cart");
833
+ if (starting(result) || wall || (!(result instanceof Error) && (result.status === 401 || result.status === 403))) {
834
+ add(CART_PAGE_ITEM, "UNVERIFIED", `${wall ?? failed ?? STORE_STARTING} ${CART_PAGE_FIX}`);
835
+ }
836
+ else if (failed || reached.path.split("?")[0] !== "/cart" || !html(result)) {
837
+ add(CART_PAGE_ITEM, "NOT DONE", `${failed ?? "/cart does not serve its own HTML page."} ${CART_PAGE_FIX}`);
838
+ }
839
+ else {
840
+ cartPageBody = result.text.trim();
841
+ const checkoutLink = [...cartPageBody.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)].some(match => {
842
+ try {
843
+ const url = new URL(match[1] ?? match[2] ?? match[3], `${origin}/cart`);
844
+ return sameOrigin(url.href, origin) && url.pathname === checkoutPath;
845
+ }
846
+ catch {
847
+ return false;
848
+ }
849
+ });
850
+ add(CART_PAGE_ITEM, checkoutLink ? "PASS" : "WARN", checkoutLink
851
+ ? "/cart answers 200 with a checkout link on the store's origin."
852
+ : `/cart answers 200 but has no checkout link. ${CART_PAGE_FIX}`);
853
+ }
854
+ }
855
+ {
856
+ const reached = await reach(checkoutPath);
857
+ const failed = pageProblem(reached, checkoutPath);
858
+ const landed = reached.path.split("?")[0];
859
+ const marker = failed ? null : checkoutMarker(reached.result.text);
860
+ if (failed) {
861
+ add(CHECKOUT_PAGE_ITEM, "NOT DONE", `${failed} Shoppers who aren't agents need a working checkout page: serve the store's own checkout page at ${origin}${checkoutPath} with a 200 `
862
+ + `(the kit hands shoppers off there; paths.checkout in createStoreKit), or rerun doctor with --checkout-path <path> if it lives elsewhere.`);
863
+ }
864
+ else if (marker && marker.items === null && !marker.cardFields) {
865
+ // A 200 alone isn't a checkout page: a redirect home or a placeholder no longer passes.
866
+ const where = landed === checkoutPath ? `${checkoutPath} answers 200` : `${checkoutPath} redirects to ${printableUrl(`${origin}${reached.path}`)}${landed === "/" ? " (the home page)" : ""}, which answers 200`;
867
+ add(CHECKOUT_PAGE_ITEM, "NOT DONE", `${where} but shows no checkout marker, so it isn't a checkout page yet. Serve the store's checkout page at ${origin}${checkoutPath} and ${CHECKOUT_MARKER_FIX}`);
868
+ }
869
+ else {
870
+ add(CHECKOUT_PAGE_ITEM, "PASS", `${origin}${checkoutPath} answers 200 on the store's origin${landed !== checkoutPath ? ` (at ${printableUrl(`${origin}${reached.path}`)})` : ""} and shows the checkout marker${marker?.items !== null && marker?.items !== undefined ? ` (${marker.items} ${marker.items === 1 ? "item" : "items"} in the cart)` : " (card fields)"}.`);
871
+ }
872
+ }
873
+ const pages = sampleProductPages(sitemapUrls.filter((url) => sameOrigin(url, origin)));
874
+ if (pages.length) {
875
+ const failures = [];
876
+ for (const page of pages) {
877
+ const url = new URL(page);
878
+ const failed = pageProblem(await reach(`${url.pathname}${url.search}`), url.href);
879
+ if (failed)
880
+ failures.push(failed);
881
+ }
882
+ if (failures.length) {
883
+ add(PRODUCT_PAGES_ITEM, "NOT DONE", `${failures.length} of ${pages.length} sampled product page${pages.length === 1 ? "" : "s"} from the product sitemap failed: ${failures.slice(0, 3).join(" ")} `
884
+ + "Serve each agent-visible product's page at its url with a 200 on the store's origin (or fix the product's url), so shoppers and agents can open it.");
885
+ }
886
+ else
887
+ add(PRODUCT_PAGES_ITEM, "PASS", `${pages.length} sampled product page${pages.length === 1 ? " from the product sitemap answers" : "s from the product sitemap answer"} 200 on the store's origin.`);
888
+ }
889
+ else if (!sitemapRead) {
890
+ // The sitemap row above already FAILed; this row says only that the
891
+ // pages could not be sampled, never a fabricated pass.
892
+ add(PRODUCT_PAGES_ITEM, "UNVERIFIED", "The product sitemap could not be read, so no product pages could be sampled.");
893
+ }
894
+ else {
895
+ add(PRODUCT_PAGES_ITEM, "N/A", "The product sitemap lists no product pages on the store's origin to sample.");
896
+ }
897
+ }
898
+ // 6. Selected feeds.
899
+ {
900
+ const formats = Object.keys(STORE_FEED_PATHS);
901
+ const advertisedFormats = formats.filter((format) => advertised.some((link) => sameOrigin(link, origin) && new URL(link).pathname === STORE_FEED_PATHS[format]));
902
+ const selected = options.feeds ?? advertisedFormats;
903
+ if (!selected.length)
904
+ add("product feeds", "N/A", "No feeds are selected (feeds is an opt-in kit option).");
905
+ // Every manifest feed check gets an explicit verdict, selected or not.
906
+ for (const format of formats) {
907
+ if (!selected.includes(format))
908
+ add(`feed ${STORE_FEED_PATHS[format]}`, "N/A", "Not selected (feeds.formats is an opt-in kit option).");
909
+ }
910
+ /** Product page URLs each readable feed lists. */
911
+ const listed = new Map();
912
+ for (const format of selected) {
913
+ const path = STORE_FEED_PATHS[format];
914
+ const name = `feed ${path}`;
915
+ if (!advertisedFormats.includes(format)) {
916
+ add(name, "FAIL", `Selected but not advertised in llms.txt. Add "${format}" to the kit's feeds.formats.`);
917
+ continue;
918
+ }
919
+ const result = await probe(path);
920
+ const failed = problem(result, path);
921
+ if (!(result instanceof Error) && html(result)) {
922
+ add(name, "FAIL", catchAll(result, path));
923
+ continue;
924
+ }
925
+ if (failed) {
926
+ add(name, "FAIL", failed);
927
+ continue;
928
+ }
929
+ const fetched = result;
930
+ let body = fetched.text;
931
+ if (format === "openaiGzip") {
932
+ try {
933
+ body = new TextDecoder().decode(gunzipSync(fetched.bytes, { maxOutputLength: DOCTOR_MAX_RESPONSE_BYTES }));
934
+ }
935
+ catch (error) {
936
+ add(name, "FAIL", error?.code === "ERR_BUFFER_TOO_LARGE" ? `Expands beyond ${DOCTOR_MAX_RESPONSE_BYTES} bytes.` : "Not gzip data.");
937
+ continue;
938
+ }
939
+ }
940
+ if (format === "openai" || format === "openaiGzip") {
941
+ const lines = body.split("\n").filter((line) => line.trim());
942
+ let rows;
943
+ try {
944
+ rows = lines.map((line) => JSON.parse(line));
945
+ }
946
+ catch {
947
+ add(name, "FAIL", CATCH_ALL_FIX);
948
+ continue;
949
+ }
950
+ if (rows.some((row) => !isRecord(row) || typeof row.item_id !== "string" || typeof row.url !== "string" || !sameOrigin(row.url, origin)))
951
+ add(name, "FAIL", "Some rows lack item_id, or link off the store's origin.");
952
+ else if (!rows.length)
953
+ add(name, "UNVERIFIED", FEED_EMPTY);
954
+ else
955
+ add(name, "PASS", `${rows.length} product${rows.length === 1 ? "" : "s"}.`);
956
+ if (rows.every(isRecord))
957
+ listed.set(path, new Set(rows.map((row) => pageKey(row.url))));
958
+ }
959
+ else {
960
+ const items = [...body.matchAll(/<item\b[^>]*>([\s\S]*?)<\/item>/g)].map((match) => match[1]);
961
+ if (!/<rss\b/.test(body))
962
+ add(name, "FAIL", CATCH_ALL_FIX);
963
+ else if (items.some((item) => !/<g:id>[^<]+<\/g:id>/.test(item) || ![...item.matchAll(/<g:link>([^<]+)<\/g:link>/g)].some((link) => sameOrigin(link[1].replace(/&amp;/g, "&"), origin))))
964
+ add(name, "FAIL", "Some items lack g:id, or link off the store's origin.");
965
+ else if (!items.length)
966
+ add(name, "UNVERIFIED", FEED_EMPTY);
967
+ else
968
+ add(name, "PASS", `${items.length} product${items.length === 1 ? "" : "s"}.`);
969
+ if (/<rss\b/.test(body))
970
+ listed.set(path, new Set(items.flatMap((item) => [...item.matchAll(/<g:link>([^<]+)<\/g:link>/g)].map((link) => pageKey(link[1].replace(/&amp;/g, "&"))))));
971
+ }
972
+ }
973
+ // The aggregate manifest check: one explicit "product feeds" verdict
974
+ // whenever feeds are selected (the no-feeds case already emitted N/A).
975
+ // A selected feed's failure already fails the run; this row mirrors it so
976
+ // the manifest id is never silent.
977
+ if (selected.length) {
978
+ const feedItems = items.filter((item) => item.name.startsWith("feed "));
979
+ const failedFeeds = feedItems.filter((item) => item.status === "FAIL");
980
+ const unverifiedFeeds = feedItems.filter((item) => item.status === "UNVERIFIED");
981
+ if (failedFeeds.length)
982
+ add("product feeds", "FAIL", `${failedFeeds.length} selected feed${failedFeeds.length === 1 ? "" : "s"} failed (${failedFeeds.map((item) => item.name).join(", ")}).`);
983
+ else if (unverifiedFeeds.length)
984
+ add("product feeds", "UNVERIFIED", `Not every selected feed could be verified (${unverifiedFeeds.map((item) => item.name).join(", ")}).`);
985
+ else
986
+ add("product feeds", "PASS", `${selected.length} selected feed${selected.length === 1 ? "" : "s"} serve the store's products.`);
987
+ }
988
+ // 6b. Agent-visible products (the product sitemap) missing from a selected feed: a warning, never a failure.
989
+ const gaps = [...listed].map(([path, pages]) => ({ path, missing: sitemapUrls.filter((url) => !pages.has(pageKey(url))) }))
990
+ .filter((gap) => gap.missing.length);
991
+ if (gaps.length) {
992
+ const missing = [...new Set(gaps.flatMap((gap) => gap.missing))];
993
+ add("products missing from feeds", "WARN", `${missing.length} product page${missing.length === 1 ? "" : "s"} in the product sitemap ${missing.length === 1 ? "is" : "are"} not in ${gaps.map((gap) => gap.path).join(", ")} (${missing.slice(0, 3).join(", ")}${missing.length > 3 ? ", …" : ""}). ${FEED_RULES}`);
994
+ }
995
+ else if (!selected.length) {
996
+ add("products missing from feeds", "N/A", "No feeds are selected, so there is nothing to compare the sitemap against.");
997
+ }
998
+ else if (!listed.size) {
999
+ add("products missing from feeds", "UNVERIFIED", "No selected feed could be read, so feed completeness could not be checked.");
1000
+ }
1001
+ else if (!sitemapUrls.length) {
1002
+ add("products missing from feeds", "UNVERIFIED", "No product sitemap could be read to compare the feeds against.");
1003
+ }
1004
+ else {
1005
+ add("products missing from feeds", "PASS", "Every product page in the product sitemap is listed in the selected feeds.");
1006
+ }
1007
+ }
1008
+ // 7. MCP initialize.
1009
+ let mcpCheckoutTools;
1010
+ {
1011
+ const result = await probe("/mcp", {
1012
+ method: "POST",
1013
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
1014
+ body: JSON.stringify({ jsonrpc: "2.0", id: "doctor-initialize", method: "initialize", params: { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "relyon-store-kit-doctor", version: KIT_VERSION } } }),
1015
+ });
1016
+ const failed = problem(result, "/mcp");
1017
+ if (!(result instanceof Error) && html(result))
1018
+ add("/mcp initialize", "FAIL", catchAll(result, "/mcp"));
1019
+ else if (failed)
1020
+ add("/mcp initialize", "FAIL", failed);
1021
+ else {
1022
+ const fetched = result;
1023
+ let message;
1024
+ try {
1025
+ message = fetched.type.includes("text/event-stream")
1026
+ ? JSON.parse(fetched.text.split("\n").find((line) => line.startsWith("data: "))?.slice(6) ?? "null")
1027
+ : JSON.parse(fetched.text);
1028
+ }
1029
+ catch {
1030
+ message = undefined;
1031
+ }
1032
+ const resultField = isRecord(message) && isRecord(message.result) ? message.result : undefined;
1033
+ if (!resultField || typeof resultField.protocolVersion !== "string" || !isRecord(resultField.serverInfo) || typeof resultField.serverInfo.name !== "string") {
1034
+ add("/mcp initialize", "FAIL", isRecord(message) && message.jsonrpc === "2.0"
1035
+ ? "No MCP initialize result (protocolVersion and serverInfo). Mount the kit's /mcp."
1036
+ : CATCH_ALL_FIX);
1037
+ }
1038
+ else {
1039
+ add("/mcp initialize", "PASS", `MCP ${resultField.protocolVersion}, server "${resultField.serverInfo.name}".${isRecord(resultField._meta) && resultField._meta["relyon/status"] === "waiting_for_sandbox_key" ? " Checkout waits for a sandbox key (browse tools only)." : ""}`);
1040
+ // AI-agent checkout: agents can buy only with the store's agent
1041
+ // credential; make the requirement (and where a merchant issues one)
1042
+ // visible next to the checkout tools.
1043
+ mcpCheckoutTools = isRecord(resultField._meta) && resultField._meta["relyon/status"] === "waiting_for_sandbox_key" ? "waiting" : "offered";
1044
+ }
1045
+ }
1046
+ }
1047
+ // 7a. Agent credential guidance: checkout works for agents holding the
1048
+ // store's agent credential (agt_…), which the merchant issues in the Relyon
1049
+ // dashboard. The kit's tool descriptions, agent card and llms.txt say so.
1050
+ if (mcpCheckoutTools === "offered") {
1051
+ add(AI_AGENT_CHECKOUT_ITEM, "PASS", "Agent checkout tools are offered; agents check out with the store's agent credential (agt_…), issued by the merchant in the Relyon dashboard under AI agents → Credentials.");
1052
+ }
1053
+ else if (mcpCheckoutTools === "waiting") {
1054
+ add(AI_AGENT_CHECKOUT_ITEM, "NOT DONE", "Checkout is still being set up (waiting for a sandbox key); once offered, agents check out with the store's agent credential (agt_…) from the Relyon dashboard under AI agents → Credentials.");
1055
+ }
1056
+ // 7a. Products with options: each lists its variants for agents (a warning when not).
1057
+ {
1058
+ const row = variantsCheck(await mcpProducts());
1059
+ add(VARIANTS_ITEM, row.status, row.detail);
1060
+ }
1061
+ // 7b. The checkout routes. Discovery files alone are not a store agents can
1062
+ // buy from: each checkout route must be answered by the kit itself. The
1063
+ // probes are harmless: an unknown checkout endpoint (the kit refuses it
1064
+ // locally, without asking Relyon) and an unsigned webhook (refused).
1065
+ {
1066
+ const probeName = `__relyon_doctor_${randomBytes(6).toString("hex")}`;
1067
+ const acpLink = advertised.map((link) => { try {
1068
+ return new URL(link);
1069
+ }
1070
+ catch {
1071
+ return undefined;
1072
+ } })
1073
+ .find((url) => url !== undefined && url.origin === origin && url.pathname.endsWith("/checkout_sessions"));
1074
+ const acpPath = acpLink ? acpLink.pathname.slice(0, -"/checkout_sessions".length) || "/acp" : "/acp";
1075
+ /** The shared verdict: the kit's waiting answer, the kit's own answer, or the app's. */
1076
+ const route = (name, path, result, kitAnswer, passDetail, notServed) => {
1077
+ if (waiting(result)) {
1078
+ add(name, apiKey ? "FAIL" : "UNVERIFIED", apiKey ? WAITING_WITH_KEY : WAITING_DETAIL);
1079
+ return;
1080
+ }
1081
+ if (result instanceof Error) {
1082
+ add(name, "FAIL", problem(result, path));
1083
+ return;
1084
+ }
1085
+ if (kitAnswer(result)) {
1086
+ add(name, "PASS", passDetail);
1087
+ return;
1088
+ }
1089
+ if (result.status >= 300 && result.status < 400) {
1090
+ add(name, "FAIL", problem(result, path));
1091
+ return;
1092
+ }
1093
+ const wall = privatePreview(result, path);
1094
+ if (wall) {
1095
+ add(name, "FAIL", wall);
1096
+ return;
1097
+ }
1098
+ if (html(result) || result.status === 200) {
1099
+ add(name, "FAIL", catchAll(result, path));
1100
+ return;
1101
+ }
1102
+ if (starting(result)) {
1103
+ add(name, "FAIL", STORE_STARTING);
1104
+ return;
1105
+ }
1106
+ add(name, "FAIL", result.status === 404 ? notServed : `${path} answered ${result.status}, which is not the kit's answer. ${CATCH_ALL_FIX}`);
1107
+ };
1108
+ const mount = (what, path) => `${path} is not served by the kit, so ${what}. Mount storeKitMiddleware (every kit route, not only the discovery files) before the app's own routes.`;
1109
+ {
1110
+ const path = `/ucp/${probeName}`;
1111
+ const result = await probe(path);
1112
+ route("/ucp checkout", "/ucp", result, (fetched) => {
1113
+ const body = jsonOf(fetched);
1114
+ return fetched.status === 404 && isRecord(body) && body.code === "not_found" && typeof body.content === "string";
1115
+ }, "The kit answers UCP checkout at /ucp.", mount("agents can't check out over UCP", "/ucp"));
1116
+ }
1117
+ {
1118
+ const result = await probe(`${acpPath}/${probeName}`);
1119
+ route("/acp checkout", acpPath, result, (fetched) => {
1120
+ const body = jsonOf(fetched);
1121
+ return fetched.status === 404 && isRecord(body) && body.code === "not_found" && typeof body.type === "string" && typeof body.message === "string";
1122
+ }, `The kit answers ACP checkout at ${acpPath}.`, mount("agents can't check out over ACP", acpPath));
1123
+ }
1124
+ {
1125
+ const result = await probe(webhookPath, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
1126
+ route("webhook route", webhookPath, result, (fetched) => {
1127
+ const body = jsonOf(fetched);
1128
+ return fetched.status === 400 && isRecord(body) && body.error === "invalid_signature";
1129
+ }, `The kit answers ${webhookPath} and refuses an unsigned event.`, `${mount("Relyon can't deliver order and rule events to the store", webhookPath)} If the kit's paths.webhook is set to another path, pass that path with --webhook-path.`);
1130
+ // The route is proven; the signing-secret proof runs once a key exists
1131
+ // (below, after the gateway). A configured secret alone also proves it.
1132
+ const added = items[items.length - 1];
1133
+ if (added?.name === "webhook route" && added.status === "PASS")
1134
+ webhookRouteItem = added;
1135
+ }
1136
+ {
1137
+ const path = "/.well-known/agent-card.json";
1138
+ const result = await probe(path);
1139
+ const advertisedCard = advertised.some((link) => sameOrigin(link, origin) && new URL(link).pathname === path);
1140
+ if (!advertisedCard && !(result instanceof Error) && result.status === 404 && !html(result)) {
1141
+ add("agent card", "N/A", "Not served and not advertised in llms.txt (the kit's agentCard option is off).");
1142
+ }
1143
+ else {
1144
+ route("agent card", path, result, (fetched) => {
1145
+ const body = jsonOf(fetched);
1146
+ return fetched.status === 200 && isRecord(body) && typeof body.protocolVersion === "string" && typeof body.name === "string"
1147
+ && typeof body.url === "string" && sameOrigin(body.url, origin);
1148
+ }, "The kit serves the agent card on the store's origin.", mount("agents can't read the agent card that llms.txt advertises", path));
1149
+ }
1150
+ }
1151
+ }
1152
+ // 8. robots.txt.
1153
+ {
1154
+ const result = await probe("/robots.txt");
1155
+ if (result instanceof Error)
1156
+ add("robots.txt", "FAIL", starting(result) ? STORE_STARTING : `/robots.txt: ${result.message}.`);
1157
+ else if (starting(result))
1158
+ add("robots.txt", "FAIL", STORE_STARTING);
1159
+ else if (result.status >= 400 && result.status < 500)
1160
+ add("robots.txt", "PASS", `None (${result.status}): every crawler may read the store.`);
1161
+ else if (result.status !== 200)
1162
+ add("robots.txt", "FAIL", `/robots.txt answered ${result.status}; crawlers treat that as "keep out".`);
1163
+ else if (html(result))
1164
+ add("robots.txt", "FAIL", catchAll(result, "/robots.txt"));
1165
+ else {
1166
+ const blocked = blockedCrawlers(result.text, ["/", "/llms.txt", sitemapPath, "/.well-known/ucp", "/mcp"]);
1167
+ if (blocked.length)
1168
+ add("robots.txt", "FAIL", `Keeps ${blocked.join(", ")} out of discovery paths. See mergeAiRobots in the kit README.`);
1169
+ else
1170
+ add("robots.txt", "PASS", "AI search and shopping crawlers may read the discovery paths.");
1171
+ }
1172
+ }
1173
+ // 8b. A random unknown path must not answer 200.
1174
+ {
1175
+ const path = `/__relyon_doctor_${randomBytes(8).toString("hex")}`;
1176
+ const result = await probe(path);
1177
+ if (!(result instanceof Error) && result.status === 200 && cartPageBody !== undefined && result.text.trim() === cartPageBody) {
1178
+ const cart = items.find(item => item.name === CART_PAGE_ITEM);
1179
+ if (cart) {
1180
+ cart.status = "NOT DONE";
1181
+ cart.detail = `/cart is the same catch-all page served for an unknown path. ${CART_PAGE_FIX}`;
1182
+ }
1183
+ }
1184
+ if (!(result instanceof Error) && result.status === 200)
1185
+ add("unknown paths", "FAIL", UNKNOWN_PATH_FIX);
1186
+ else if (starting(result))
1187
+ add("unknown paths", "UNVERIFIED", STORE_STARTING);
1188
+ else if (result instanceof Error)
1189
+ add("unknown paths", "UNVERIFIED", `A random unknown path could not be fetched: ${result.message}.`);
1190
+ else
1191
+ add("unknown paths", "PASS", `A random unknown path answers ${result.status}, not 200.`);
1192
+ }
1193
+ // 8c. Best-effort source check: the kit mounted only when RELYON_API_KEY is set.
1194
+ if (options.projectDir) {
1195
+ const gated = await findGatedKitMounts(options.projectDir).catch(() => null);
1196
+ if (gated === null)
1197
+ add("kit mount", "WARN", `The source check could not read the project folder. Make sure the kit is created and mounted unconditionally, not only when RELYON_API_KEY is set. ${GATED_KIT_WARNING}`);
1198
+ else if (gated.length)
1199
+ add("kit mount", "WARN", `${gated.slice(0, 5).join(", ")} creates or mounts the kit only when RELYON_API_KEY is set. ${GATED_KIT_WARNING}`);
1200
+ else
1201
+ add("kit mount", "PASS", "No source file creates or mounts the kit only when RELYON_API_KEY is set.");
1202
+ }
1203
+ else {
1204
+ add("kit mount", "N/A", "Not checked: the doctor ran without the store's project folder (the CLI passes the current folder).");
1205
+ }
1206
+ // 9. Relyon's integration doctor.
1207
+ // Finish local and progress evidence before sending the one remote diagnostic.
1208
+ let progress;
1209
+ let remoteDoctor;
1210
+ let webhookProofDone = false;
1211
+ /**
1212
+ * The signing-secret half of the webhook route proof: a signed, harmless
1213
+ * doctor.challenge the running store must accept and acknowledge with that
1214
+ * same secret. Preferred secret: Relyon's current one for this URL,
1215
+ * recovered in Test through the receiver's own deterministic registration
1216
+ * replay (an existing contract operation; no active endpoint for the URL
1217
+ * means no POST ever goes out, so the doctor never creates one). Fallback:
1218
+ * the operator-configured secret (RELYON_WEBHOOK_SECRET or the saved Test
1219
+ * configuration). A refusal or a wrong acknowledgement FAILs the route item
1220
+ * and names RELYON_WEBHOOK_SECRET; the value is never printed. When no
1221
+ * secret can be resolved the route-scope PASS stands and says what it checked.
1222
+ */
1223
+ const proveWebhookSecret = async (gateway) => {
1224
+ if (webhookProofDone)
1225
+ return;
1226
+ const item = webhookRouteItem;
1227
+ if (!item)
1228
+ return; // the route probe did not pass; that item already reports why
1229
+ const url = `${origin}${webhookPath}`;
1230
+ let secret;
1231
+ let recovered = false;
1232
+ let recoveryRefused = false;
1233
+ if (gateway && !live) {
1234
+ try {
1235
+ const list = (await gateway.call((client) => client.GET(WEBHOOK_ENDPOINTS_PATH), isTestWebhookEndpointList)).data.data;
1236
+ const newest = newestActiveEndpoint(list, url);
1237
+ if (newest) {
1238
+ const { data } = await gateway.call((client) => client.POST(WEBHOOK_ENDPOINTS_PATH, {
1239
+ params: { header: { "Idempotency-Key": webhookRegistrationKey(url) } },
1240
+ body: { url, events: [...WEBHOOK_EVENTS] },
1241
+ }), isTestWebhookEndpoint);
1242
+ // As in the receiver's recovery: replay or adoption only counts when
1243
+ // it names the listed newest endpoint and carries a usable secret.
1244
+ if (data.id === newest.id && typeof data.secret === "string" && WEBHOOK_SECRET_SHAPE.test(data.secret)) {
1245
+ secret = data.secret;
1246
+ recovered = true;
1247
+ }
1248
+ else
1249
+ recoveryRefused = true;
1250
+ }
1251
+ }
1252
+ catch (error) {
1253
+ // A definitive problem answer (such as the 409 of a session-owned or
1254
+ // legacy registration row) means runtime recovery cannot work; an
1255
+ // unavailable Relyon is transient and leaves the secret unresolved.
1256
+ if (error instanceof RelyonProblemError && error.status === 409)
1257
+ recoveryRefused = true;
1258
+ }
1259
+ }
1260
+ secret ??= options.webhookSecret || undefined;
1261
+ if (!secret) {
1262
+ webhookProofDone = true;
1263
+ if (recoveryRefused) {
1264
+ item.status = "FAIL";
1265
+ item.detail = `The kit answers ${webhookPath}, but the store cannot resolve the webhook signing secret at runtime: Relyon refused the registration replay for this URL. Set RELYON_WEBHOOK_SECRET in the store's environment (or its saved private configuration) to the endpoint's current signing secret, or re-run npx @relyon/store-kit webhook and restart the store. The secret's value is never printed.`;
1266
+ }
1267
+ else {
1268
+ // The route probe passed, but without a resolved secret no signed
1269
+ // challenge goes out — the manifest's completion check did not run, so
1270
+ // this is an honest UNVERIFIED, never an unproven PASS.
1271
+ item.status = "UNVERIFIED";
1272
+ item.detail = `The kit answers ${webhookPath} and refuses an unsigned event, but this run could not resolve the webhook signing secret, so the signed challenge that proves the running store accepts it was not sent. Set RELYON_WEBHOOK_SECRET in the store's environment (or its saved private configuration) to the endpoint's current signing secret, or run \`npx @relyon/store-kit webhook\` and restart the store. The secret's value is never printed.`;
1273
+ }
1274
+ return;
1275
+ }
1276
+ webhookProofDone = true;
1277
+ const created = Math.floor(Date.now() / 1000);
1278
+ const event = { id: `evt_doctor_${randomUUID()}`, object: "doctor_challenge", type: "doctor.challenge", livemode: live, created, challenge: randomBytes(32).toString("hex") };
1279
+ const raw = JSON.stringify(event);
1280
+ const signature = `t=${created},v1=${createHmac("sha256", secret).update(`${created}.${raw}`).digest("hex")}`;
1281
+ const answer = await probe(webhookPath, { method: "POST", headers: { "content-type": "application/json", "relyon-signature": signature }, body: raw });
1282
+ if (answer instanceof Error) {
1283
+ item.status = "UNVERIFIED";
1284
+ item.detail = `The signed webhook challenge could not be delivered: ${answer.message}.`;
1285
+ return;
1286
+ }
1287
+ if (answer.status === 200 && answer.acknowledgement === doctorAcknowledgement(secret, event.id, event.challenge, created)) {
1288
+ item.detail = `The kit answers ${webhookPath}, refuses an unsigned event, and accepted the doctor's correctly signed challenge: the running store resolves the webhook signing secret${recovered ? " (recovered from Relyon, the receiver's own runtime path)" : ""}.`;
1289
+ return;
1290
+ }
1291
+ item.status = "FAIL";
1292
+ item.detail = answer.status === 400
1293
+ ? `The running store refused a correctly signed doctor challenge (invalid_signature): the webhook signing secret it resolves is not Relyon's current one for this endpoint. Fix RELYON_WEBHOOK_SECRET in the store's environment or saved private configuration (a saved value goes stale when the endpoint is re-registered), or re-run npx @relyon/store-kit webhook and restart the store. The secret's value is never printed.`
1294
+ : `The running store answered the signed doctor challenge with ${answer.status} and ${answer.acknowledgement ? "a wrong" : "no"} acknowledgement, so it does not prove the webhook signing secret. Check RELYON_WEBHOOK_SECRET in the store's environment or saved private configuration, or re-run npx @relyon/store-kit webhook. The secret's value is never printed.`;
1295
+ };
1296
+ // Without a usable key no gateway exists; a configured secret still proves the route.
1297
+ if (!keyUsable)
1298
+ await proveWebhookSecret();
1299
+ // One explicit verdict per server check too: without a usable key none of
1300
+ // Relyon's checks can be observed, so each is UNVERIFIED, never absent.
1301
+ if (!apiKey) {
1302
+ add("Relyon doctor", "UNVERIFIED", "Skipped: set RELYON_API_KEY to the store's secret key.");
1303
+ for (const check of KNOWN_REMOTE_CHECKS)
1304
+ add(`Relyon doctor: ${check}`, "UNVERIFIED", "Skipped: set RELYON_API_KEY to the store's secret key.");
1305
+ }
1306
+ else if (!keyUsable) {
1307
+ add("Relyon doctor", "UNVERIFIED", "Skipped: the key can't be used as configured.");
1308
+ for (const check of KNOWN_REMOTE_CHECKS)
1309
+ add(`Relyon doctor: ${check}`, "UNVERIFIED", "Skipped: the key can't be used as configured.");
1310
+ }
1311
+ else {
1312
+ // The doctor sees Relyon's answer as sent: a redirect is never followed,
1313
+ // and a web page (a sign-in or access-protection page, a proxy's error
1314
+ // page) is told apart from an outage of the store's own network.
1315
+ const seen = {};
1316
+ const relyonFetch = async (request, init) => {
1317
+ seen.url = request.url;
1318
+ // Version metadata as headers (never query/body, which the route
1319
+ // rejects): Relyon records the kit and manifest versions on the run.
1320
+ const versioned = new Headers(request.headers);
1321
+ versioned.set(KIT_VERSION_DIAGNOSTIC_HEADER, KIT_VERSION);
1322
+ versioned.set(KIT_MANIFEST_VERSION_HEADER, String(CHECKLIST_MANIFEST_VERSION));
1323
+ if (new URL(request.url).pathname.endsWith(DOCTOR_PATH)) {
1324
+ versioned.set(PROJECT_SPACE_HOSTNAME_HEADER, new URL(origin).hostname);
1325
+ const evidence = kitOutcomeMetadata(items);
1326
+ if (evidence)
1327
+ versioned.set(KIT_OUTCOMES_HEADER, evidence);
1328
+ // Encode only the already-computed diagnostic. No second lookup or status computation.
1329
+ // Invalid/oversized local evidence is represented by a rejected marker, never a guess.
1330
+ versioned.set(KIT_VERSION_HEADER, encodeKitVersionSnapshot(kitVersion) ?? "unavailable");
1331
+ }
1332
+ let response;
1333
+ try {
1334
+ response = await fetchImpl(new Request(request, { redirect: "manual", headers: versioned }), init);
1335
+ }
1336
+ catch (error) {
1337
+ seen.error = error;
1338
+ throw error;
1339
+ }
1340
+ seen.status = response.status;
1341
+ if (new URL(request.url).pathname.endsWith(DOCTOR_PATH) && response.ok) {
1342
+ const ack = response.headers.get(KIT_DIAGNOSTIC_STATUS_HEADER);
1343
+ kitVersionDelivery = ack === "accepted" ? "accepted" : ack === "rejected" ? "rejected" : "unavailable";
1344
+ }
1345
+ const redirected = (response.status >= 300 && response.status < 400) || response.type === "opaqueredirect";
1346
+ if (redirected || (response.status < 500 && await looksLikeWebPage(response))) {
1347
+ seen.webPage = { location: redirected ? response.headers.get("location") : null };
1348
+ throw new RelyonWebPage();
1349
+ }
1350
+ return response;
1351
+ };
1352
+ const gateway = new RelyonGateway({
1353
+ baseUrl: options.baseUrl ?? DEFAULT_RELYON_BASE_URL, apiKey,
1354
+ ...(live ? { live: true } : {}), timeoutMs, fetch: relyonFetch,
1355
+ // Brief 87b: the doctor's other calls (webhook proof, policy read) name
1356
+ // the project space too (and its ID from RELYON_PROJECT_SPACE).
1357
+ storeHostname: new URL(origin).hostname,
1358
+ });
1359
+ // The webhook signing-secret proof (signed challenge) once a key can
1360
+ // recover the registered secret; before the remote call so the evidence
1361
+ // header reflects the final verdict.
1362
+ await proveWebhookSecret(gateway);
1363
+ // One scoped read corroborates policy completeness; it can never erase
1364
+ // other blockers in a combined Relyon failure.
1365
+ let policies;
1366
+ let policyReadError;
1367
+ try {
1368
+ policies = await readStorePolicies(gateway);
1369
+ }
1370
+ catch (error) {
1371
+ policyReadError = error;
1372
+ }
1373
+ for (const key of Object.keys(seen))
1374
+ delete seen[key];
1375
+ remoteDoctor = async () => {
1376
+ try {
1377
+ let { data, response } = await gateway.call((client) => client.GET(DOCTOR_PATH), isDoctorResult);
1378
+ // A transient catalog check_unavailable (the adapter's plain "could not
1379
+ // complete", no observed blockers folded in) is retried briefly before
1380
+ // it is judged: a recovering dependency answers cleanly on a re-read.
1381
+ for (let attempt = 0; attempt < 2 && data.status !== "pass" && data.failures.some(transientCatalogFailure); attempt += 1) {
1382
+ await sleep(Math.min(startupRetryMs, 1_500));
1383
+ ({ data, response } = await gateway.call((client) => client.GET(DOCTOR_PATH), isDoctorResult));
1384
+ }
1385
+ // A newer kit Relyon knows about, named in response metadata. Absent or
1386
+ // unparseable metadata means no notice — never a failure of the run.
1387
+ if (data.livemode !== live) {
1388
+ add("Relyon doctor", "FAIL", `Relyon answered for ${data.livemode ? "Live" : "Test"} but this run is ${live ? "Live" : "Test"}.`);
1389
+ // One explicit verdict per server check too: the wrong-mode answer
1390
+ // proves none of them.
1391
+ for (const check of KNOWN_REMOTE_CHECKS) {
1392
+ add(`Relyon doctor: ${check}`, "UNVERIFIED", `Relyon answered for ${data.livemode ? "Live" : "Test"}, not this run's mode.`);
1393
+ }
1394
+ }
1395
+ else {
1396
+ let catalog;
1397
+ let catalogError;
1398
+ try {
1399
+ catalog = await catalogReadiness(gateway, policies);
1400
+ }
1401
+ catch (error) {
1402
+ catalogError = error;
1403
+ }
1404
+ const catalogAgent = catalogError
1405
+ ? [`Catalog readiness could not be read: ${redactSecrets(String(catalogError.message))}. Re-run the doctor after resolving this read failure.`]
1406
+ : catalog?.agent ?? [];
1407
+ const catalogOwner = catalog?.owner ?? [];
1408
+ // A store-first app prices its own carts and checks out on its own domain, so the older
1409
+ // Relyon-priced pricing and checkout probes don't apply to it — on a passing answer just
1410
+ // as on a failing one (Core stores the same not_applicable), in Test and in Live. That is
1411
+ // N/A only when this run positively observed the store-first routes (a UCP profile is
1412
+ // served only for a verified domain); missing evidence is never enough, and a store-first
1413
+ // blocker the server reports under those checks still FAILs.
1414
+ // On a preview address the verification file is N/A (no domain yet; Test only — Live
1415
+ // refuses preview hosts, so `preview` can never be set on a Live run).
1416
+ const storeFirst = STORE_FIRST_EVIDENCE.every((name) => items.some((item) => item.name === name
1417
+ && (item.status === "PASS" || (preview && name === "relyon-verification" && (item.status === "N/A" || item.status === "PENDING")))));
1418
+ const failed = new Set();
1419
+ const transientUnverified = new Set();
1420
+ if (data.status !== "pass") {
1421
+ for (const failure of data.failures) {
1422
+ const name = `Relyon doctor: ${failure.check}`;
1423
+ if (failure.check === "catalog" && catalogAgent.length) {
1424
+ failed.add("catalog");
1425
+ add(name, "FAIL", [...catalogAgent, ...catalogOwner,
1426
+ failure.code === "check_unavailable" ? shortCheckUnavailable(failure) : `${failure.code}: ${failure.explanation} Fix: ${failure.fix}`].join(" "));
1427
+ }
1428
+ else if (!live && policyOnlyFailure(failure, policies)) {
1429
+ merchant(name, pendingPolicyFields(policies, false).map(field => MERCHANT_QUESTIONS[field]));
1430
+ if (policies?.missing.some(field => field === "returns" || field === "returns.policy_url"))
1431
+ items.at(-1).detail = `${RETURN_WINDOW_PENDING}. ${items.at(-1).detail}`;
1432
+ }
1433
+ else if (!live && (preview || loopback) && failure.check === "webhook" && failure.code === "webhook_missing") {
1434
+ // Agent-actionable, not an owner question: the agent registers the endpoint
1435
+ // itself with `npx @relyon/store-kit webhook` once the store is published.
1436
+ add(name, options.strict ? "FAIL" : "PENDING", `${failure.code}: ${failure.explanation} Fix: run \`npx @relyon/store-kit webhook\` after publish (it registers ${origin}${options.webhookPath ?? "/relyon/webhooks"}; with an environment API key the signing secret is resolved at runtime and no file is written; only a local file key saves RELYON_WEBHOOK_SECRET to gitignored .env, 0600, never printed); re-run it if the store's URL changes.`);
1437
+ }
1438
+ else if (live && failure.check === "webhook") {
1439
+ // The Live webhook check passes only when the challenge was
1440
+ // acknowledged — the endpoint exists AND the receiver resolved the
1441
+ // signing secret. Anything else fails with the kit's own fix.
1442
+ add(name, "FAIL", `${failure.code}: ${failure.explanation} Fix: run \`npx @relyon/store-kit webhook\` with the store's Live key set as RELYON_API_KEY in the host's environment settings (it registers or verifies ${origin}${options.webhookPath ?? "/relyon/webhooks"}; the signing secret is resolved at runtime and no file is written). If the endpoint already exists but its secret can't be resolved, run \`npx @relyon/store-kit webhook --rotate\` to rotate it in place.`);
1443
+ }
1444
+ else if (!live && domainPendingOnlyFailure(failure)) {
1445
+ // The server's whole catalog projection is the pending domain:
1446
+ // pending like the domain row itself, with the verifyDomain step,
1447
+ // never a FAIL carrying fixes for surfaces that were never probed.
1448
+ add(name, options.strict ? "FAIL" : "PENDING", `${failure.code}: domain verification is the only missing catalog condition. ${failure.fix} ${AGENT_DOMAIN_STEP(new URL(origin).hostname)}`);
1449
+ }
1450
+ else if (storeFirst && LEGACY_CHECKS.has(failure.check) && !STORE_FIRST_BLOCKER.test(failure.explanation)) {
1451
+ add(name, "N/A", `${failure.code}: the older Relyon-priced ${failure.check} check doesn't apply to a store-first app; this run saw the kit's UCP profile, verification file, llms.txt and MCP on the store's domain.`);
1452
+ }
1453
+ else if (transientCatalogFailure(failure)) {
1454
+ // Still unanswered after the brief retries above: an unverified
1455
+ // pending state, never a FAIL against the store.
1456
+ transientUnverified.add(failure.check);
1457
+ add(name, "UNVERIFIED", `${failure.code}: Relyon could not complete its catalog check; unverified, try again in a minute, then re-run the doctor.`);
1458
+ }
1459
+ else {
1460
+ failed.add(failure.check);
1461
+ add(name, "FAIL", failure.code === "check_unavailable" ? shortCheckUnavailable(failure)
1462
+ : `${failure.code}: ${failure.explanation} Fix: ${failure.fix}`);
1463
+ }
1464
+ }
1465
+ }
1466
+ // Every known server check gets its own explicit outcome: PASS when
1467
+ // Relyon reported it without a failure, the store-first N/A for the
1468
+ // legacy probes, and an honest UNVERIFIED when Relyon's answer never
1469
+ // mentioned it. Never silence.
1470
+ const reported = new Set(data.failures.map((failure) => failure.check));
1471
+ for (const check of KNOWN_REMOTE_CHECKS) {
1472
+ if (reported.has(check))
1473
+ continue;
1474
+ const name = `Relyon doctor: ${check}`;
1475
+ if (check === "catalog" && catalogAgent.length) {
1476
+ failed.add(check);
1477
+ add(name, "FAIL", [...catalogAgent, ...catalogOwner].join(" "));
1478
+ }
1479
+ else if (check === "catalog" && catalogOwner.length) {
1480
+ merchant(name, [MERCHANT_QUESTIONS.returns]);
1481
+ items.at(-1).detail = `${catalogOwner.join(" ")}. ${items.at(-1).detail}`;
1482
+ }
1483
+ else if (storeFirst && LEGACY_CHECKS.has(check))
1484
+ add(name, "N/A", `The older Relyon-priced ${check} check doesn't apply to a store-first app; this run saw the kit's UCP profile, verification file, llms.txt and MCP on the store's domain.`);
1485
+ else if (data.checks.includes(check))
1486
+ add(name, "PASS", `Relyon's ${check} check passes.`);
1487
+ else
1488
+ add(name, "UNVERIFIED", `Relyon's answer did not include the ${check} check, so this run could not confirm it.`);
1489
+ }
1490
+ // The overall row is explicit on every answered run: FAIL when any
1491
+ // check still failed after the merchant/agent downgrades, UNVERIFIED
1492
+ // when a transient check never answered, else PASS.
1493
+ const passing = data.checks.filter((check) => !reported.has(check));
1494
+ if (failed.size)
1495
+ add("Relyon doctor", "FAIL", `Relyon's checks report failures: ${[...failed].join(", ")}.`);
1496
+ else if (data.status === "pass")
1497
+ add("Relyon doctor", "PASS", `Relyon's checks pass: ${data.checks.join(", ")}.`);
1498
+ else if (transientUnverified.size)
1499
+ add("Relyon doctor", "UNVERIFIED", `Relyon could not complete its ${[...transientUnverified].join(", ")} check; unverified, try again in a minute, then re-run the doctor.`);
1500
+ else
1501
+ add("Relyon doctor", "PASS", `Relyon's checks pass: ${passing.join(", ")}.`);
1502
+ }
1503
+ }
1504
+ catch (error) {
1505
+ // One explicit verdict per server check on an unanswered run too: a
1506
+ // refusal or an outage proves none of them.
1507
+ if (error instanceof RelyonProblemError) {
1508
+ add("Relyon doctor", "FAIL", `Relyon refused (${error.status} ${error.code})${error.param ? ` on field ${error.param}` : ""}: ${error.message}`);
1509
+ for (const check of KNOWN_REMOTE_CHECKS)
1510
+ add(`Relyon doctor: ${check}`, "UNVERIFIED", `Relyon refused the doctor read (${error.status} ${error.code}), so this check could not be confirmed.`);
1511
+ }
1512
+ else if (error instanceof RelyonUnavailableError) {
1513
+ add("Relyon doctor", "UNVERIFIED", relyonUnavailable(error, seen, timeoutMs));
1514
+ for (const check of KNOWN_REMOTE_CHECKS)
1515
+ add(`Relyon doctor: ${check}`, "UNVERIFIED", "Relyon's doctor could not be read, so this check could not be confirmed.");
1516
+ }
1517
+ else
1518
+ throw error;
1519
+ }
1520
+ };
1521
+ // 10. The store policies agent checkout needs, named field by field.
1522
+ try {
1523
+ if (policyReadError)
1524
+ throw policyReadError;
1525
+ if (!policies)
1526
+ throw new TypeError("Store policies read returned no result.");
1527
+ if (policies.livemode !== live)
1528
+ add("store policies", "FAIL", "Relyon's store policies do not match this run's Test/Live mode.");
1529
+ else if (policies.complete && policies.missing.length === 0)
1530
+ add("store policies", "PASS", "Returns (with its policy page) and a support contact are set in Relyon.");
1531
+ else if (!live && pendingPolicyFields(policies, false).length) {
1532
+ merchant("store policies", pendingPolicyFields(policies, false).map(field => MERCHANT_QUESTIONS[field]));
1533
+ }
1534
+ else {
1535
+ add("store policies", "FAIL", `Agent checkout is refused until these store-policy fields are set: ${policies.missing.join(", ")}. `
1536
+ + policies.missing.map((field) => `${field}: ${STORE_POLICY_FIELD_FIXES[field] ?? `set it in PUT ${PROJECT_SPACE_POLICIES_PATH}.`}`).join(" ")
1537
+ + " The kit's syncStorePolicies() shows the exact replacement to confirm with the merchant first; it never assumes free returns or a return cost."
1538
+ + (live ? ` ${LIVE_POLICY_HTTPS}` : ""));
1539
+ }
1540
+ }
1541
+ catch (error) {
1542
+ if (error instanceof RelyonProblemError)
1543
+ add("store policies", "UNVERIFIED", `Relyon refused the store-policies read (${error.status} ${error.code}).`);
1544
+ else if (error instanceof RelyonUnavailableError || error instanceof RelyonWebPage)
1545
+ add("store policies", "UNVERIFIED", "Relyon's store policies could not be read.");
1546
+ else
1547
+ throw error;
1548
+ }
1549
+ // 10b. The policy pages Relyon holds that point at the store itself
1550
+ // (or loopback) must exist, in Test and in Live; a missing page is an
1551
+ // owner to-do.
1552
+ if (policies && policies.livemode === live) {
1553
+ const missing = await missingPolicyPages(policies, origin, get, fetchImpl, timeoutMs);
1554
+ if (missing.length)
1555
+ merchant(POLICY_PAGES_ITEM, missing);
1556
+ else
1557
+ add(POLICY_PAGES_ITEM, "PASS", "Every policy page the store's policies link to answers on the store.");
1558
+ }
1559
+ }
1560
+ if (!items.some((item) => item.name === POLICY_PAGES_ITEM)) {
1561
+ // The policies could not be read (no key, refusal, outage), in Test or
1562
+ // Live: the pages could not be checked either. Never a fabricated pass.
1563
+ add(POLICY_PAGES_ITEM, "UNVERIFIED", "The store policies could not be read, so the policy pages could not be checked.");
1564
+ }
1565
+ const domainVerified = items.some(item => item.name === "relyon-verification" && item.status === "PASS");
1566
+ if (live)
1567
+ add("Live readiness", domainVerified ? "PASS" : "UNVERIFIED", domainVerified
1568
+ ? "The store runs with a Live key on the domain Relyon reports verified."
1569
+ : "The store uses a Live key, but this run has not confirmed its domain verification. Resolve the domain-verification item and rerun doctor.");
1570
+ else if (preview)
1571
+ add("Live readiness", "N/A", `${TEST_ON_PREVIEW}. Live still needs a published, verified domain. ${GO_LIVE_STEPS}`);
1572
+ else
1573
+ add("Live readiness", "PENDING", `${domainVerified ? "The store runs in Test on its verified domain." : "The store runs in Test; this run has not confirmed a verified public domain."} Live itself is an owner and Relyon-staff step, not an agent step: complete the go-live steps in the Relyon dashboard (Relyon staff approve Live).`);
1574
+ if (options.beforeRelyonDoctor) {
1575
+ progress = await options.beforeRelyonDoctor(live);
1576
+ items.push(progress);
1577
+ }
1578
+ if (remoteDoctor) {
1579
+ // Preserve the printed item order: remote doctor, policies, Live, confirmation.
1580
+ const localEnd = items.length;
1581
+ await remoteDoctor();
1582
+ const remoteItems = items.splice(localEnd);
1583
+ const policiesIndex = items.findIndex(item => item.name === "store policies");
1584
+ items.splice(policiesIndex < 0 ? localEnd - (progress ? 1 : 0) : policiesIndex, 0, ...remoteItems);
1585
+ }
1586
+ return done();
1587
+ }
1588
+ /** Doctor's item for policy links whose pages don't exist (an owner to-do in Test). */
1589
+ export const POLICY_PAGES_ITEM = "policy pages";
1590
+ /**
1591
+ * The policy links Relyon holds that point at the store's origin or a
1592
+ * loopback address and don't open (a 4xx/5xx answer or no answer), one owner
1593
+ * question each. Links on other hosts aren't fetched.
1594
+ */
1595
+ async function missingPolicyPages(policies, origin, get, fetchImpl, timeoutMs) {
1596
+ const links = [
1597
+ ["returns policy", policies.returns?.policy_url], ["support contact page", policies.support?.url],
1598
+ ["shipping policy", policies.shipping_policy_url], ["privacy policy", policies.privacy_policy_url], ["terms", policies.terms_url],
1599
+ ];
1600
+ const questions = [];
1601
+ for (const [label, value] of links) {
1602
+ if (typeof value !== "string")
1603
+ continue;
1604
+ let url;
1605
+ try {
1606
+ url = new URL(value);
1607
+ }
1608
+ catch {
1609
+ continue;
1610
+ }
1611
+ if (url.protocol !== "http:" && url.protocol !== "https:")
1612
+ continue;
1613
+ let status = null;
1614
+ if (url.origin === origin) {
1615
+ const result = await get(`${url.pathname}${url.search}`);
1616
+ status = result instanceof Error ? null : result.status;
1617
+ }
1618
+ else if (isLoopbackHostname(url.hostname)) {
1619
+ const controller = new AbortController();
1620
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1621
+ try {
1622
+ const response = await fetchImpl(new Request(url, { redirect: "manual", headers: { "user-agent": USER_AGENT }, signal: controller.signal }), { signal: controller.signal });
1623
+ await response.body?.cancel().catch(() => undefined);
1624
+ status = response.status;
1625
+ }
1626
+ catch {
1627
+ status = null;
1628
+ }
1629
+ finally {
1630
+ clearTimeout(timer);
1631
+ }
1632
+ }
1633
+ else
1634
+ continue;
1635
+ if (status !== null && status < 400)
1636
+ continue;
1637
+ questions.push(`The ${label} link ${printableUrl(url.href)} ${status === null ? "does not open" : `answers ${status}`}: which published page does the owner confirm? Publish it (the owner writes its text) or point the policy at the store's real page.`);
1638
+ }
1639
+ return questions;
1640
+ }
1641
+ /** The exact fix for each missing project-space policy field, by its PUT policies path. */
1642
+ export const STORE_POLICY_FIELD_FIXES = {
1643
+ returns: "ask the merchant for the return window (days) and what a return costs the shopper (free, buyer_pays, or fixed with an amount), set policies.returns.windowDays in the kit and pass the cost to syncStorePolicies({ returns: { cost } }).",
1644
+ "returns.policy_url": "publish the store's returns page and set policies.returns.policyUrl to its https:// address on the store's public domain.",
1645
+ support: "set policies.contactUrl to the store's https:// contact page, or ask the merchant for a support email and pass it to syncStorePolicies({ support: { email } }).",
1646
+ };
1647
+ function isDoctorResult(data) {
1648
+ return isRecord(data) && data.object === DOCTOR_OBJECT && typeof data.livemode === "boolean"
1649
+ && (data.status === "pass" || data.status === "fail") && Array.isArray(data.checks) && data.checks.every((check) => typeof check === "string")
1650
+ && Array.isArray(data.failures) && data.failures.every((failure) => isRecord(failure)
1651
+ && typeof failure.check === "string" && typeof failure.code === "string" && typeof failure.explanation === "string" && typeof failure.fix === "string");
1652
+ }
1653
+ /** The AI discovery crawlers a robots.txt keeps out of any of `paths` (most specific group; longest match wins, Allow on ties). */
1654
+ export function blockedCrawlers(text, paths) {
1655
+ const groups = [];
1656
+ let group;
1657
+ let hasRules = false;
1658
+ for (const line of text.split(/\r?\n/)) {
1659
+ const match = /^\s*(user-agent|allow|disallow)\s*:\s*([^#]*)/i.exec(line);
1660
+ if (!match)
1661
+ continue;
1662
+ if (match[1].toLowerCase() === "user-agent") {
1663
+ if (!group || hasRules) {
1664
+ group = { agents: [], rules: [] };
1665
+ groups.push(group);
1666
+ hasRules = false;
1667
+ }
1668
+ group.agents.push(match[2].trim().toLowerCase());
1669
+ }
1670
+ else if (group) {
1671
+ hasRules = true;
1672
+ const path = match[2].trim();
1673
+ if (path)
1674
+ group.rules.push({ allow: match[1].toLowerCase() === "allow", path });
1675
+ }
1676
+ }
1677
+ return AI_DISCOVERY_CRAWLERS.filter((agent) => {
1678
+ const exact = groups.filter((g) => g.agents.includes(agent.toLowerCase()));
1679
+ const rules = (exact.length ? exact : groups.filter((g) => g.agents.includes("*"))).flatMap((g) => g.rules);
1680
+ return paths.some((path) => {
1681
+ const matches = rules.filter((rule) => {
1682
+ const anchored = rule.path.endsWith("$");
1683
+ const pattern = rule.path.replace(/\$$/, "").split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
1684
+ return new RegExp(`^${pattern}${anchored ? "$" : ""}`).test(path);
1685
+ }).sort((a, b) => b.path.replace(/[*$]/g, "").length - a.path.replace(/[*$]/g, "").length || Number(b.allow) - Number(a.allow));
1686
+ return matches.length > 0 && !matches[0].allow;
1687
+ });
1688
+ });
1689
+ }