@relyon/kit 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +75 -0
- package/CHANGELOG.md +1053 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +239 -0
- package/README.md +117 -2
- package/dist/adapters/express.d.ts +39 -0
- package/dist/adapters/express.js +106 -0
- package/dist/adapters/hono.d.ts +16 -0
- package/dist/adapters/hono.js +15 -0
- package/dist/adapters/next.d.ts +29 -0
- package/dist/adapters/next.js +38 -0
- package/dist/agent-card.d.ts +14 -0
- package/dist/agent-card.js +58 -0
- package/dist/agent-docs.d.ts +36 -0
- package/dist/agent-docs.js +78 -0
- package/dist/agent-hooks.d.ts +66 -0
- package/dist/agent-hooks.js +280 -0
- package/dist/agents.d.ts +24 -0
- package/dist/agents.js +120 -0
- package/dist/api-key.d.ts +6 -0
- package/dist/api-key.js +33 -0
- package/dist/cache.d.ts +46 -0
- package/dist/cache.js +86 -0
- package/dist/cart-tokens.d.ts +31 -0
- package/dist/cart-tokens.js +58 -0
- package/dist/cart-transfer.d.ts +95 -0
- package/dist/cart-transfer.js +387 -0
- package/dist/catalog-enrichment.d.ts +6 -0
- package/dist/catalog-enrichment.js +71 -0
- package/dist/catalog-reads.d.ts +126 -0
- package/dist/catalog-reads.js +104 -0
- package/dist/catalog.d.ts +78 -0
- package/dist/catalog.js +288 -0
- package/dist/charge-claims.d.ts +11 -0
- package/dist/charge-claims.js +47 -0
- package/dist/check.d.ts +44 -0
- package/dist/check.js +152 -0
- package/dist/checklist-manifest.d.ts +72 -0
- package/dist/checklist-manifest.js +341 -0
- package/dist/checkout.d.ts +222 -0
- package/dist/checkout.js +353 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +727 -0
- package/dist/confirmation.d.ts +78 -0
- package/dist/confirmation.js +124 -0
- package/dist/context.d.ts +81 -0
- package/dist/context.js +10 -0
- package/dist/discovery.d.ts +151 -0
- package/dist/discovery.js +346 -0
- package/dist/doctor-cart-transfer.d.ts +33 -0
- package/dist/doctor-cart-transfer.js +186 -0
- package/dist/doctor-catalog.d.ts +8 -0
- package/dist/doctor-catalog.js +47 -0
- package/dist/doctor-evidence.d.ts +22 -0
- package/dist/doctor-evidence.js +57 -0
- package/dist/doctor-merchant.d.ts +48 -0
- package/dist/doctor-merchant.js +74 -0
- package/dist/doctor-source.d.ts +5 -0
- package/dist/doctor-source.js +142 -0
- package/dist/doctor-variants.d.ts +70 -0
- package/dist/doctor-variants.js +102 -0
- package/dist/doctor.d.ts +215 -0
- package/dist/doctor.js +1689 -0
- package/dist/events.d.ts +95 -0
- package/dist/events.js +200 -0
- package/dist/feed-mapping.d.ts +114 -0
- package/dist/feed-mapping.js +152 -0
- package/dist/feed-values.d.ts +13 -0
- package/dist/feed-values.js +40 -0
- package/dist/feeds.d.ts +104 -0
- package/dist/feeds.js +366 -0
- package/dist/identify.d.ts +102 -0
- package/dist/identify.js +124 -0
- package/dist/identity.d.ts +37 -0
- package/dist/identity.js +54 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +41 -0
- package/dist/init.d.ts +157 -0
- package/dist/init.js +912 -0
- package/dist/kit-config.d.ts +19 -0
- package/dist/kit-config.js +43 -0
- package/dist/kit-environment.d.ts +20 -0
- package/dist/kit-environment.js +32 -0
- package/dist/kit-updates.d.ts +47 -0
- package/dist/kit-updates.js +77 -0
- package/dist/kit-version-project.d.ts +18 -0
- package/dist/kit-version-project.js +214 -0
- package/dist/kit-version.d.ts +37 -0
- package/dist/kit-version.js +162 -0
- package/dist/kit.d.ts +516 -0
- package/dist/kit.js +1309 -0
- package/dist/layers/pages.d.ts +3 -0
- package/dist/layers/pages.js +5 -0
- package/dist/layers/payments.d.ts +7 -0
- package/dist/layers/payments.js +9 -0
- package/dist/layers/products.d.ts +10 -0
- package/dist/layers/products.js +13 -0
- package/dist/live.d.ts +13 -0
- package/dist/live.js +52 -0
- package/dist/mcp.d.ts +270 -0
- package/dist/mcp.js +312 -0
- package/dist/next-steps.d.ts +101 -0
- package/dist/next-steps.js +257 -0
- package/dist/order-pending.d.ts +57 -0
- package/dist/order-pending.js +127 -0
- package/dist/orders.d.ts +12 -0
- package/dist/orders.js +21 -0
- package/dist/payments-init.d.ts +19 -0
- package/dist/payments-init.js +70 -0
- package/dist/payments-routes.d.ts +54 -0
- package/dist/payments-routes.js +123 -0
- package/dist/payments.d.ts +165 -0
- package/dist/payments.js +192 -0
- package/dist/pnpm-workspace.d.ts +58 -0
- package/dist/pnpm-workspace.js +250 -0
- package/dist/policies.d.ts +111 -0
- package/dist/policies.js +317 -0
- package/dist/preview-hosts.d.ts +64 -0
- package/dist/preview-hosts.js +175 -0
- package/dist/private-config.d.ts +169 -0
- package/dist/private-config.js +820 -0
- package/dist/progress.d.ts +54 -0
- package/dist/progress.js +153 -0
- package/dist/protocol-inputs.d.ts +22 -0
- package/dist/protocol-inputs.js +151 -0
- package/dist/public-origin.d.ts +50 -0
- package/dist/public-origin.js +180 -0
- package/dist/refusals.d.ts +86 -0
- package/dist/refusals.js +157 -0
- package/dist/relay.d.ts +107 -0
- package/dist/relay.js +655 -0
- package/dist/release-notes.d.ts +2 -0
- package/dist/release-notes.js +290 -0
- package/dist/relyon-cart-tokens.d.ts +101 -0
- package/dist/relyon-cart-tokens.js +521 -0
- package/dist/relyon.d.ts +141 -0
- package/dist/relyon.js +238 -0
- package/dist/robots.d.ts +27 -0
- package/dist/robots.js +127 -0
- package/dist/rules.d.ts +144 -0
- package/dist/rules.js +347 -0
- package/dist/sdk/generated/public-api.d.ts +4816 -0
- package/dist/sdk/generated/public-api.js +1 -0
- package/dist/sdk/index.d.ts +24 -0
- package/dist/sdk/index.js +34 -0
- package/dist/sdk/signatures.d.ts +17 -0
- package/dist/sdk/signatures.js +33 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.js +94 -0
- package/dist/signatures.d.ts +112 -0
- package/dist/signatures.js +443 -0
- package/dist/state.d.ts +185 -0
- package/dist/state.js +96 -0
- package/dist/store-payments.d.ts +48 -0
- package/dist/store-payments.js +143 -0
- package/dist/structured-fields.d.ts +26 -0
- package/dist/structured-fields.js +200 -0
- package/dist/templates.d.ts +19 -0
- package/dist/templates.js +193 -0
- package/dist/test-checkout-command.d.ts +32 -0
- package/dist/test-checkout-command.js +161 -0
- package/dist/test-checkout.d.ts +88 -0
- package/dist/test-checkout.js +292 -0
- package/dist/types.d.ts +103 -0
- package/dist/types.js +18 -0
- package/dist/ucp-versions.d.ts +57 -0
- package/dist/ucp-versions.js +129 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.js +68 -0
- package/dist/variants.d.ts +67 -0
- package/dist/variants.js +146 -0
- package/dist/version.d.ts +9 -0
- package/dist/version.js +10 -0
- package/dist/waiting.d.ts +43 -0
- package/dist/waiting.js +57 -0
- package/dist/webhook-command.d.ts +48 -0
- package/dist/webhook-command.js +367 -0
- package/dist/webhook-registration.d.ts +47 -0
- package/dist/webhook-registration.js +69 -0
- package/dist/webmcp-schema.d.ts +14 -0
- package/dist/webmcp-schema.js +140 -0
- package/dist/webmcp-script.d.ts +3 -0
- package/dist/webmcp-script.js +176 -0
- package/dist/webmcp-store.d.ts +102 -0
- package/dist/webmcp-store.js +116 -0
- package/dist/webmcp.d.ts +242 -0
- package/dist/webmcp.js +866 -0
- package/dist/wire-names.d.ts +85 -0
- package/dist/wire-names.js +109 -0
- package/package.json +118 -4
- package/release-notes.json +290 -0
- package/scripts/install-notice.cjs +7 -0
- package/skills/relyon-agents/SKILL.md +327 -0
- package/skills/relyon-catalog/SKILL.md +499 -0
- package/skills/relyon-catalog/references/example-store.md +218 -0
- package/skills/relyon-checkout/SKILL.md +603 -0
- package/skills/relyon-checkout/references/checkout-flow.md +257 -0
- package/skills/relyon-checkout/references/checkout-page.md +315 -0
- package/skills/relyon-go-live/SKILL.md +344 -0
- package/skills/relyon-orders/SKILL.md +191 -0
- package/skills/relyon-orders/references/webhook-receiver.md +113 -0
- package/skills/relyon-payments/SKILL.md +117 -0
- package/skills/relyon-setup/SKILL.md +1061 -0
- package/skills/relyon-setup/references/QUICKSTART.md +239 -0
- package/skills/relyon-setup/references/durable-state.md +209 -0
- package/skills/relyon-setup/references/express-server.md +388 -0
- package/skills/relyon-setup/references/next-app-router.md +251 -0
- package/templates/common/STORE-README.md +67 -0
- package/templates/common/gitignore +8 -0
- package/templates/common/scripts/check-pricing.ts +22 -0
- package/templates/common/scripts/serve.mjs +13 -0
- package/templates/common/server/catalog.ts +79 -0
- package/templates/common/server/checkout-flow.d.ts +34 -0
- package/templates/common/server/pages.ts +184 -0
- package/templates/common/server/storage.ts +114 -0
- package/templates/common/server/store.ts +67 -0
- package/templates/express/server/express.ts +20 -0
- package/templates/express/tsconfig.build.json +6 -0
- package/templates/express/tsconfig.json +9 -0
- package/templates/next/app/[[...path]]/route.ts +24 -0
- package/templates/next/next.config.mjs +19 -0
- package/templates/next/tsconfig.json +12 -0
- package/templates/payments/express.ts +39 -0
- package/templates/payments/next.ts +38 -0
- package/templates/payments/node.ts +39 -0
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import { WEBHOOK_ENDPOINTS_PATH } from "./wire-names.js";
|
|
2
|
+
import { usableApiKey, usableTestKey } from "./api-key.js";
|
|
3
|
+
import { DEFAULT_RELYON_BASE_URL, redactSecrets, terminalSafe } from "./doctor.js";
|
|
4
|
+
import { nonPublicStoreHost } from "./live.js";
|
|
5
|
+
import { isRotatingPreviewHost } from "./preview-hosts.js";
|
|
6
|
+
import { loadTestConfig, readEnvValue, writeEnvValue } from "./private-config.js";
|
|
7
|
+
import { OFFICIAL_RELYON_ORIGIN } from "./progress.js";
|
|
8
|
+
import { RelyonGateway, RelyonProblemError, RelyonUnavailableError } from "./relyon.js";
|
|
9
|
+
import { WEBHOOK_ENDPOINT_ID_SHAPE, WEBHOOK_EVENTS, isWebhookEndpointFor, isWebhookEndpointListFor, newestActiveEndpoint, webhookRegistrationKey, webhookRotationKey, webhookSecretShape, } from "./webhook-registration.js";
|
|
10
|
+
export { webhookRegistrationKey, webhookRotationKey, WEBHOOK_EVENTS } from "./webhook-registration.js";
|
|
11
|
+
// `npx @relyon/store-kit webhook`: registers the store's webhook endpoint
|
|
12
|
+
// (<origin>/relyon/webhooks) with Relyon, idempotently. An environment API key
|
|
13
|
+
// means no file is written: receivers resolve the secret at runtime.
|
|
14
|
+
// A local file API key keeps the local-dev secret in gitignored .env (0600).
|
|
15
|
+
// Test and Live both work; the secret is never
|
|
16
|
+
// printed. Exit codes: 0 registered (or already registered), 1 the
|
|
17
|
+
// registration or the .env write failed, 2 refused to run (usage, a Live run
|
|
18
|
+
// without the Live key in RELYON_API_KEY, a non-https URL, a preview host, or
|
|
19
|
+
// no Test key).
|
|
20
|
+
//
|
|
21
|
+
// Live mode (RELYON_LIVE=true or a Live key in RELYON_API_KEY) runs on the
|
|
22
|
+
// host's environment key only — never a saved key file, and no file is
|
|
23
|
+
// written — and only for a public https origin on the store's own domain:
|
|
24
|
+
// loopback, IP literals, single-label names and development preview domains
|
|
25
|
+
// are refused by the same Live origin rules as the rest of the kit.
|
|
26
|
+
//
|
|
27
|
+
// One endpoint per URL: when an active endpoint for the URL already exists
|
|
28
|
+
// (the dashboard panel's, an older registration's), the deterministic
|
|
29
|
+
// registration adopts it in Test — Relyon returns that endpoint with its
|
|
30
|
+
// current secret and never inserts a duplicate. In Live an adoption is never
|
|
31
|
+
// answered with a secret: the run is refused with guidance to rotate. A Live
|
|
32
|
+
// rotation is owner-only — it rotates an endpoint this key registered through
|
|
33
|
+
// the kit (or one whose registering key was revoked); a dashboard-created
|
|
34
|
+
// endpoint can't be taken over (an admin deletes it or changes its URL in the
|
|
35
|
+
// dashboard first), and an endpoint owned by another Live key refuses until
|
|
36
|
+
// that key is revoked. `--rotate` rotates an owned endpoint
|
|
37
|
+
// in place (new secret, same `we_` id), so rotation never creates a second
|
|
38
|
+
// endpoint either.
|
|
39
|
+
//
|
|
40
|
+
// Reconciliation: the saved secret alone proves nothing — an in-place
|
|
41
|
+
// rotation elsewhere keeps the endpoint id but replaces the secret — so a run
|
|
42
|
+
// always replays the registration key and compares: Relyon's replay answers
|
|
43
|
+
// the endpoint's CURRENT secret, and .env is updated when it diverged. A
|
|
44
|
+
// normal run never rotates: a replay Relyon refuses (409) or an answer naming
|
|
45
|
+
// anything but the newest active endpoint exits 1 with guidance to rerun with
|
|
46
|
+
// --rotate, and never saves a superseded secret.
|
|
47
|
+
//
|
|
48
|
+
// `--rotate` is the only rotation trigger. Its rotation key mixes the URL
|
|
49
|
+
// with fresh randomness on every run, so every run rotates — a retry of an
|
|
50
|
+
// interrupted rotation rotates again instead of replaying, which is the
|
|
51
|
+
// honest behavior: the fresh secret may never have been saved. If Relyon's
|
|
52
|
+
// answer ever comes back marked as a replay, the command reports that the
|
|
53
|
+
// current secret was recovered — it never claims the previous secret stopped
|
|
54
|
+
// verifying when nothing was rotated.
|
|
55
|
+
//
|
|
56
|
+
// Replay: Relyon keeps a registration's deterministic Idempotency-Key without
|
|
57
|
+
// expiry in both modes, and the replay's answer is rebuilt from the endpoint
|
|
58
|
+
// row, so recovery keeps working after an older Live record's 24-hour window
|
|
59
|
+
// expired. A replay answers the principal that registered; a replacement Test
|
|
60
|
+
// key in the same store recovers the secret too (the row transfers to it),
|
|
61
|
+
// and in Test a registration row the key may not replay as-is (a session's, a
|
|
62
|
+
// legacy row, or one whose endpoint was superseded or deleted) is re-pointed
|
|
63
|
+
// at the newest active endpoint and answered as an adoption with its current
|
|
64
|
+
// secret. Live replays stay strictly single-principal. Anything Relyon
|
|
65
|
+
// returns is validated before it is saved (secret shape, endpoint id shape,
|
|
66
|
+
// livemode matching the run's mode); a malformed answer fails with a generic
|
|
67
|
+
// error and writes nothing.
|
|
68
|
+
export const WEBHOOK_COMMAND = "npx @relyon/store-kit webhook";
|
|
69
|
+
export const DEFAULT_WEBHOOK_PATH = "/relyon/webhooks";
|
|
70
|
+
export const WEBHOOK_NO_KEY_LIVE = "webhook in Live mode needs the store's Live key (rly_live_…) set as RELYON_API_KEY in the host's environment settings — never a file, and never pasted into a command. (A Test key, a missing key, or a saved key file can't run Live.)";
|
|
71
|
+
export const WEBHOOK_NO_KEY = "webhook needs the store's Test key (rly_test_…): run `npx @relyon/store-kit init` first (it saves the key privately). Never paste the key into a command.";
|
|
72
|
+
/** Init's line when registration couldn't run: deferred, never a failure. */
|
|
73
|
+
export const WEBHOOK_DEFERRED_LINE = `Webhook registration is deferred: after publish, run \`${WEBHOOK_COMMAND}\` to register the store's webhook endpoint. With an environment API key nothing is saved; local file-key development saves the signing secret privately.`;
|
|
74
|
+
export const WEBHOOK_RUNTIME_LINE = "Webhook registered. The signing secret is resolved at runtime from RELYON_API_KEY; nothing was saved to a file.";
|
|
75
|
+
/** Live rotation warning: rotating replaces the signing secret everywhere the old one is used. */
|
|
76
|
+
export const WEBHOOK_ROTATE_LIVE_WARNING = "Warning: rotating issues a new signing secret; anything else using the endpoint's old secret will stop verifying.";
|
|
77
|
+
/** The validation failure line: generic, echoing none of Relyon's values. */
|
|
78
|
+
const malformedAnswer = (live) => `Relyon's answer didn't match the expected shape for a ${live ? "Live" : "Test"} webhook registration, so nothing was written. Rerun \`${WEBHOOK_COMMAND}\`; if it repeats, contact Relyon support.`;
|
|
79
|
+
/** Runs the command. Never throws; every line is terminal-safe and redacted, and never holds the secret. */
|
|
80
|
+
export async function runWebhookCommand(options) {
|
|
81
|
+
const envKey = usableApiKey(options.envKey);
|
|
82
|
+
const key = envKey ?? (options.live ? undefined : options.savedKey);
|
|
83
|
+
const secrets = [options.envKey, options.savedKey, key];
|
|
84
|
+
const finish = (exitCode, lines) => ({ exitCode, lines: lines.map((line) => redactSecrets(terminalSafe(line), secrets)) });
|
|
85
|
+
// Live mode: RELYON_LIVE=true or a Live key. A Live run uses the host's
|
|
86
|
+
// environment key only — a saved key file is never a Live credential.
|
|
87
|
+
const live = options.live === true || (key !== undefined && usableTestKey(key) === undefined && key.startsWith("rly_live_"));
|
|
88
|
+
if (live && !(envKey !== undefined && envKey.startsWith("rly_live_")))
|
|
89
|
+
return finish(2, [WEBHOOK_NO_KEY_LIVE]);
|
|
90
|
+
const apiKey = live ? envKey : usableTestKey(key);
|
|
91
|
+
if (!apiKey)
|
|
92
|
+
return finish(2, [WEBHOOK_NO_KEY]);
|
|
93
|
+
let store;
|
|
94
|
+
try {
|
|
95
|
+
store = new URL(options.storeUrl);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return finish(2, ["--url needs the store's origin, such as https://shop.example.com."]);
|
|
99
|
+
}
|
|
100
|
+
if ((store.protocol !== "https:" && store.protocol !== "http:") || store.username || store.password) {
|
|
101
|
+
return finish(2, ["--url needs an http(s) origin without credentials."]);
|
|
102
|
+
}
|
|
103
|
+
const webhookPath = options.webhookPath ?? DEFAULT_WEBHOOK_PATH;
|
|
104
|
+
if (!webhookPath.startsWith("/") || webhookPath.startsWith("//"))
|
|
105
|
+
return finish(2, ["--webhook-path needs a path on the store's origin, such as /relyon/webhooks."]);
|
|
106
|
+
const endpointUrl = `${store.origin}${webhookPath}`;
|
|
107
|
+
if (store.protocol !== "https:") {
|
|
108
|
+
return finish(2, [`Relyon registers https webhook endpoints only, and ${store.origin} is not https. Publish the store, set STORE_PUBLIC_URL (or --url) to its public origin, then run \`${WEBHOOK_COMMAND}\`.`]);
|
|
109
|
+
}
|
|
110
|
+
if (isRotatingPreviewHost(store.hostname)) {
|
|
111
|
+
return finish(2, [`${store.origin} is a preview or loopback address that rotates away, so Relyon can't keep delivering webhooks to it. Publish the store, set STORE_PUBLIC_URL (or --url) to its public origin, then run \`${WEBHOOK_COMMAND}\`.`]);
|
|
112
|
+
}
|
|
113
|
+
if (live) {
|
|
114
|
+
// The Live origin rules: the store's own public https hostname only —
|
|
115
|
+
// never a loopback, an IP literal, a single-label name or a development
|
|
116
|
+
// preview domain.
|
|
117
|
+
const refusedHost = nonPublicStoreHost(store.hostname);
|
|
118
|
+
if (refusedHost) {
|
|
119
|
+
return finish(2, [`Live mode refuses the store hostname ${JSON.stringify(store.hostname)}: ${refusedHost}. Publish the store on its own public domain, set STORE_PUBLIC_URL (or --url) to that origin, then run \`${WEBHOOK_COMMAND}\`.`]);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const baseUrl = options.baseUrl ?? DEFAULT_RELYON_BASE_URL;
|
|
123
|
+
// A saved key goes only to Relyon's official https API unless explicitly allowed (the doctor's L1 rule).
|
|
124
|
+
if (!envKey && !options.allowSavedKeyToBaseUrl) {
|
|
125
|
+
let baseOrigin = "";
|
|
126
|
+
try {
|
|
127
|
+
baseOrigin = new URL(baseUrl).origin;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
baseOrigin = "";
|
|
131
|
+
}
|
|
132
|
+
if (baseOrigin !== OFFICIAL_RELYON_ORIGIN) {
|
|
133
|
+
return finish(2, [`The saved Test key was not sent: the Relyon base URL is not ${DEFAULT_RELYON_BASE_URL}. Rerun with --allow-saved-key-to-base-url only if you trust that address, or put the key in RELYON_API_KEY.`]);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const gateway = new RelyonGateway({
|
|
137
|
+
baseUrl, apiKey, live,
|
|
138
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
139
|
+
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
|
140
|
+
});
|
|
141
|
+
const isWebhookEndpoint = isWebhookEndpointFor(live);
|
|
142
|
+
const post = (idempotencyKey) => gateway.call((client) => client.POST(WEBHOOK_ENDPOINTS_PATH, {
|
|
143
|
+
params: { header: { "Idempotency-Key": idempotencyKey } },
|
|
144
|
+
body: { url: endpointUrl, events: [...WEBHOOK_EVENTS] },
|
|
145
|
+
}), isWebhookEndpoint);
|
|
146
|
+
const failure = (what, error) => error instanceof RelyonProblemError ? `${what}: Relyon refused (${error.status} ${error.code}): ${error.message}`
|
|
147
|
+
: error instanceof RelyonUnavailableError ? `${what}: ${error.message} Try again, then rerun \`${WEBHOOK_COMMAND}\`.`
|
|
148
|
+
: `${what}: an unexpected error (${error?.message ?? String(error)}).`;
|
|
149
|
+
let list;
|
|
150
|
+
try {
|
|
151
|
+
list = (await gateway.call((client) => client.GET(WEBHOOK_ENDPOINTS_PATH), isWebhookEndpointListFor(live))).data.data;
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
return finish(1, [failure("The webhook endpoint list couldn't be read", error)]);
|
|
155
|
+
}
|
|
156
|
+
// The doctor verifies against the newest active registration for the URL.
|
|
157
|
+
const newest = newestActiveEndpoint(list, endpointUrl);
|
|
158
|
+
const project = options.project ?? process.cwd();
|
|
159
|
+
const env = options.env ?? process.env;
|
|
160
|
+
const envPath = pathJoin(project, ".env");
|
|
161
|
+
/** Saves a secret and the endpoint it belongs to; reports where; never prints it. Validates both first. */
|
|
162
|
+
const save = async (secret, endpointId) => {
|
|
163
|
+
secrets.push(secret);
|
|
164
|
+
if (!webhookSecretShape(live).test(secret) || !WEBHOOK_ENDPOINT_ID_SHAPE.test(endpointId)) {
|
|
165
|
+
return { outcome: { status: "refused", reason: "the registration answer was malformed" }, lines: [malformedAnswer(live)] };
|
|
166
|
+
}
|
|
167
|
+
if (envKey) {
|
|
168
|
+
const overrides = [env.RELYON_WEBHOOK_SECRET?.trim(), await readEnvValue(project, "RELYON_WEBHOOK_SECRET")].filter(Boolean);
|
|
169
|
+
secrets.push(...overrides);
|
|
170
|
+
const mismatch = overrides.some(value => value !== secret);
|
|
171
|
+
return {
|
|
172
|
+
outcome: options.rotate && mismatch ? { status: "refused", reason: "RELYON_WEBHOOK_SECRET overrides the rotated secret" } : { status: "unchanged" },
|
|
173
|
+
lines: [
|
|
174
|
+
...(options.rotate
|
|
175
|
+
? ["The endpoint's current signing secret is available for runtime recovery with RELYON_API_KEY; no file was written."]
|
|
176
|
+
: [WEBHOOK_RUNTIME_LINE]),
|
|
177
|
+
...(overrides.length ? [
|
|
178
|
+
mismatch
|
|
179
|
+
? "RELYON_WEBHOOK_SECRET is set in the environment or .env and overrides runtime recovery. Unset RELYON_WEBHOOK_SECRET, or update it in host settings to the current signing secret; restart the store. Its value is never printed."
|
|
180
|
+
: "RELYON_WEBHOOK_SECRET matches the current signing secret. Update it in host settings or unset it before future rotations; restart the store.",
|
|
181
|
+
] : []),
|
|
182
|
+
],
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const outcome = await writeEnvValue(project, "RELYON_WEBHOOK_SECRET", secret, env)
|
|
186
|
+
.catch(() => ({ status: "refused", reason: ".env couldn't be written" }));
|
|
187
|
+
if (outcome.status === "refused") {
|
|
188
|
+
return {
|
|
189
|
+
outcome,
|
|
190
|
+
lines: [`RELYON_WEBHOOK_SECRET couldn't be saved: ${outcome.reason}. The secret is never printed; fix that and rerun \`${WEBHOOK_COMMAND}\` to recover it by replay, or rerun with --rotate for a fresh one.`],
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// Record which endpoint the secret belongs to, so a later run never replays a
|
|
194
|
+
// different endpoint's registration over it.
|
|
195
|
+
const idOutcome = await writeEnvValue(project, "RELYON_WEBHOOK_ENDPOINT_ID", endpointId, env)
|
|
196
|
+
.catch(() => ({ status: "refused", reason: ".env couldn't be written" }));
|
|
197
|
+
return {
|
|
198
|
+
outcome,
|
|
199
|
+
lines: [
|
|
200
|
+
outcome.status === "written"
|
|
201
|
+
? `RELYON_WEBHOOK_SECRET saved to ${envPath} (0600, git-ignored, never printed).`
|
|
202
|
+
: `RELYON_WEBHOOK_SECRET was already saved in ${envPath}.`,
|
|
203
|
+
...(idOutcome.status === "refused" ? [`The webhook endpoint id couldn't be recorded in .env: ${idOutcome.reason}.`] : []),
|
|
204
|
+
],
|
|
205
|
+
};
|
|
206
|
+
};
|
|
207
|
+
/** In-place rotation: the endpoint id never changes, so the secret it returns always belongs to the current endpoint. */
|
|
208
|
+
const rotate = async () => {
|
|
209
|
+
if (!envKey) {
|
|
210
|
+
const checked = await writeEnvValue(project, "RELYON_WEBHOOK_SECRET", "preflight", env, true)
|
|
211
|
+
.catch(() => ({ status: "refused", reason: ".env couldn't be checked" }));
|
|
212
|
+
if (checked.status === "refused")
|
|
213
|
+
return finish(1, [`Nothing was rotated: RELYON_WEBHOOK_SECRET storage refused: ${checked.reason}. Fix storage and rerun with --rotate.`]);
|
|
214
|
+
}
|
|
215
|
+
// A Live rotation replaces the secret wherever it is used, so the warning
|
|
216
|
+
// leads the output; the Live environment-key requirement stays the
|
|
217
|
+
// confirmation. Test output is unchanged.
|
|
218
|
+
const warning = live ? [WEBHOOK_ROTATE_LIVE_WARNING] : [];
|
|
219
|
+
let rotated;
|
|
220
|
+
let replayed = false;
|
|
221
|
+
try {
|
|
222
|
+
const answer = await post(webhookRotationKey(endpointUrl));
|
|
223
|
+
rotated = answer.data;
|
|
224
|
+
replayed = answer.response.headers.get("idempotent-replayed") === "true";
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
if (error instanceof RelyonProblemError && error.status === 409) {
|
|
228
|
+
if (error.code === "webhook_endpoint_not_kit_managed") {
|
|
229
|
+
return finish(1, [...warning, `The webhook endpoint for ${endpointUrl} was registered outside the kit (for example in the Relyon dashboard), so this key can't rotate it. An admin must delete the endpoint in the dashboard or change its URL, then rerun \`${WEBHOOK_COMMAND}\`. Nothing was saved.`]);
|
|
230
|
+
}
|
|
231
|
+
if (error.code === "webhook_endpoint_owned_by_other_key") {
|
|
232
|
+
return finish(1, [...warning, `The webhook endpoint for ${endpointUrl} is managed by a different API key, so this key can't rotate it. Revoke that key first (or ask an admin), then rerun \`${WEBHOOK_COMMAND} --rotate\`. Nothing was saved.`]);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return finish(1, [...warning, failure(`The signing secret of the webhook endpoint for ${endpointUrl} couldn't be rotated`, error)]);
|
|
236
|
+
}
|
|
237
|
+
if (typeof rotated.secret !== "string") {
|
|
238
|
+
return finish(1, [...warning, `The webhook endpoint for ${endpointUrl} answered without a signing secret, so nothing was saved. Rerun \`${WEBHOOK_COMMAND}\` to recover it by replay.`]);
|
|
239
|
+
}
|
|
240
|
+
const saved = await save(rotated.secret, rotated.id);
|
|
241
|
+
// Honesty: only a fresh rotation answer means the previous secret stopped
|
|
242
|
+
// verifying. A replayed answer means nothing was rotated — the returned
|
|
243
|
+
// secret was already the current one — so say that instead.
|
|
244
|
+
const first = replayed
|
|
245
|
+
? `The webhook endpoint's current signing secret for ${endpointUrl} was recovered${envKey ? " for runtime resolution" : " and saved"} (nothing was rotated).`
|
|
246
|
+
: `Rotated the webhook endpoint's signing secret for ${endpointUrl} in place (same endpoint, fresh secret; the previous secret no longer verifies).`;
|
|
247
|
+
if (envKey)
|
|
248
|
+
return finish(saved.outcome.status === "refused" ? 1 : 0, [...warning, first, ...saved.lines]);
|
|
249
|
+
if (saved.outcome.status === "refused")
|
|
250
|
+
return finish(1, [...warning, first, ...saved.lines]);
|
|
251
|
+
return finish(0, [...warning, first, ...saved.lines, `Restart the store's server so it reads the secret, then run \`npx @relyon/store-kit doctor\`.`]);
|
|
252
|
+
};
|
|
253
|
+
if (newest && options.rotate)
|
|
254
|
+
return rotate();
|
|
255
|
+
if (newest) {
|
|
256
|
+
const [savedSecret, savedEndpointId] = envKey ? [undefined, undefined] : await Promise.all([
|
|
257
|
+
readEnvValue(project, "RELYON_WEBHOOK_SECRET").catch(() => undefined),
|
|
258
|
+
readEnvValue(project, "RELYON_WEBHOOK_ENDPOINT_ID").catch(() => undefined),
|
|
259
|
+
]);
|
|
260
|
+
if (savedSecret)
|
|
261
|
+
secrets.push(savedSecret);
|
|
262
|
+
// Relyon keeps a Test registration's Idempotency-Key without expiry, so the
|
|
263
|
+
// deterministic registration replays to recover the one-time secret — and
|
|
264
|
+
// when the active endpoint came from the panel or an older registration,
|
|
265
|
+
// the same POST adopts it (a fresh answer naming that same endpoint). The
|
|
266
|
+
// answer carries the endpoint's CURRENT secret, so this replay doubles as
|
|
267
|
+
// reconciliation: an in-place rotation elsewhere keeps the endpoint id but
|
|
268
|
+
// replaces the secret, which a saved id match alone cannot rule out.
|
|
269
|
+
try {
|
|
270
|
+
const { data, response } = await post(webhookRegistrationKey(endpointUrl));
|
|
271
|
+
const replayed = response.headers.get("idempotent-replayed") === "true";
|
|
272
|
+
if (data.id === newest.id && typeof data.secret === "string") {
|
|
273
|
+
if (envKey) {
|
|
274
|
+
const verified = await save(data.secret, data.id);
|
|
275
|
+
return finish(verified.outcome.status === "refused" ? 1 : 0, verified.lines);
|
|
276
|
+
}
|
|
277
|
+
// Provably current already: the replayed secret is the saved one.
|
|
278
|
+
if (savedSecret === data.secret && savedEndpointId === newest.id) {
|
|
279
|
+
return finish(0, [
|
|
280
|
+
`The webhook endpoint is already registered for ${endpointUrl} and its signing secret is already saved in ${envPath}.`,
|
|
281
|
+
`The secret is never shown again. Rerun with --rotate only if the saved secret was lost.`,
|
|
282
|
+
]);
|
|
283
|
+
}
|
|
284
|
+
const saved = await save(data.secret, data.id);
|
|
285
|
+
const first = savedSecret && savedEndpointId === newest.id
|
|
286
|
+
? `The webhook endpoint's signing secret for ${endpointUrl} had been rotated elsewhere; the current secret was recovered and saved.`
|
|
287
|
+
: replayed
|
|
288
|
+
? `The webhook endpoint is already registered for ${endpointUrl}; its registration replayed and the signing secret was recovered.`
|
|
289
|
+
: `The webhook endpoint is already registered for ${endpointUrl}; the kit adopted the existing endpoint and saved its current signing secret.`;
|
|
290
|
+
if (saved.outcome.status === "refused")
|
|
291
|
+
return finish(1, [`The webhook endpoint is already registered for ${endpointUrl}.`, ...saved.lines]);
|
|
292
|
+
return finish(0, [first, ...saved.lines]);
|
|
293
|
+
}
|
|
294
|
+
// A normal run never rotates: an answer naming anything but the newest
|
|
295
|
+
// active endpoint (or no usable secret) cannot be matched to the
|
|
296
|
+
// endpoint the doctor probes, and a superseded secret is never saved.
|
|
297
|
+
// Rotation is the honest recovery, and it is always explicit.
|
|
298
|
+
return finish(1, [
|
|
299
|
+
`The webhook endpoint for ${endpointUrl} is registered, but Relyon's answer didn't name the store's current endpoint with a usable signing secret, so nothing was saved. Run \`${WEBHOOK_COMMAND} --rotate\` to rotate the current endpoint's signing secret in place${envKey ? "; it will be resolved at runtime without a file" : " and save the fresh one"}.`,
|
|
300
|
+
]);
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
// A 409 means the registration row couldn't be replayed or re-pointed
|
|
304
|
+
// with this key (a Relyon without the re-point): the endpoint already
|
|
305
|
+
// exists, so the choices are reusing it or rotating it — never creating
|
|
306
|
+
// anything new.
|
|
307
|
+
if (error instanceof RelyonProblemError && error.status === 409) {
|
|
308
|
+
return finish(1, [
|
|
309
|
+
`An endpoint already exists for this store: the webhook endpoint for ${endpointUrl} is registered, but its registration couldn't be replayed with this key (Relyon refused: 409 ${error.code}), so nothing was saved. To reuse it, rerun \`${WEBHOOK_COMMAND}\` with the key that registered it — the replay recovers the current signing secret. To replace it, run \`${WEBHOOK_COMMAND} --rotate\` to rotate the endpoint's signing secret in place${envKey ? "; it will be resolved at runtime without a file" : " and save the fresh one"}.${live ? " Rotation takes over only an endpoint this key registered through the kit; an endpoint created in the Relyon dashboard can't be taken over — an admin must delete it there or change its URL, then rerun the command." : ""}`,
|
|
310
|
+
...(live ? [WEBHOOK_ROTATE_LIVE_WARNING] : []),
|
|
311
|
+
]);
|
|
312
|
+
}
|
|
313
|
+
return finish(1, [failure(`The webhook endpoint is already registered for ${endpointUrl}, but its registration couldn't be replayed`, error)]);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
// No active endpoint for this URL (also with --rotate: nothing to rotate):
|
|
317
|
+
// register it. The deterministic key makes a retried registration replay
|
|
318
|
+
// instead of duplicating.
|
|
319
|
+
let created;
|
|
320
|
+
try {
|
|
321
|
+
created = (await post(webhookRegistrationKey(endpointUrl))).data;
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
if (error instanceof RelyonProblemError && error.status === 409 && error.code === "webhook_endpoint_disabled") {
|
|
325
|
+
return finish(1, [`The webhook endpoint for ${endpointUrl} is disabled. Re-enable or delete it in the Relyon dashboard, then rerun \`${WEBHOOK_COMMAND}\`. Nothing was saved.`]);
|
|
326
|
+
}
|
|
327
|
+
return finish(1, [failure(`The webhook endpoint for ${endpointUrl} couldn't be registered`, error)]);
|
|
328
|
+
}
|
|
329
|
+
if (typeof created.secret !== "string") {
|
|
330
|
+
return finish(1, [`The webhook endpoint for ${endpointUrl} registered, but Relyon's answer carried no signing secret. Rerun \`${WEBHOOK_COMMAND}\` to recover it by replay.`]);
|
|
331
|
+
}
|
|
332
|
+
const saved = await save(created.secret, created.id);
|
|
333
|
+
if (envKey)
|
|
334
|
+
return finish(saved.outcome.status === "refused" ? 1 : 0, saved.lines);
|
|
335
|
+
const first = `Webhook endpoint registered for ${endpointUrl} (events: ${WEBHOOK_EVENTS.join(", ")}).`;
|
|
336
|
+
if (saved.outcome.status === "refused")
|
|
337
|
+
return finish(1, [first, ...saved.lines]);
|
|
338
|
+
return finish(0, [first, ...saved.lines, `Restart the store's server so it reads the secret, then run \`npx @relyon/store-kit doctor\`.`]);
|
|
339
|
+
}
|
|
340
|
+
/** path.join without importing node:path into a module that otherwise never touches the fs. */
|
|
341
|
+
function pathJoin(dir, file) {
|
|
342
|
+
return `${dir.replace(/[\\/]+$/, "")}/${file}`;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Init's best-effort registration when STORE_PUBLIC_URL is known: one outcome
|
|
346
|
+
* line (runtime resolution, local-dev saving, or the deferral). Never throws, never
|
|
347
|
+
* carries the secret, and never changes init's exit code.
|
|
348
|
+
*/
|
|
349
|
+
export async function initWebhookRegistration(options) {
|
|
350
|
+
try {
|
|
351
|
+
const env = options.env ?? process.env;
|
|
352
|
+
const saved = await loadTestConfig({ project: options.project, env }).catch(() => ({}));
|
|
353
|
+
const result = await runWebhookCommand({
|
|
354
|
+
storeUrl: options.storeUrl, project: options.project, env,
|
|
355
|
+
envKey: env.RELYON_API_KEY, savedKey: saved.apiKey,
|
|
356
|
+
live: env.RELYON_LIVE?.trim().toLowerCase() === "true",
|
|
357
|
+
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
|
358
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
359
|
+
});
|
|
360
|
+
if (result.exitCode !== 0)
|
|
361
|
+
return WEBHOOK_DEFERRED_LINE;
|
|
362
|
+
return result.lines.slice(0, 2).join(" ");
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
return WEBHOOK_DEFERRED_LINE;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** The only event the kit acts on; the doctor challenge is answered regardless of the subscription. */
|
|
2
|
+
export declare const WEBHOOK_EVENTS: readonly ["agent_rules.updated"];
|
|
3
|
+
/** The deterministic Idempotency-Key of a URL's original registration, so a retry replays instead of duplicating. */
|
|
4
|
+
export declare function webhookRegistrationKey(endpointUrl: string): string;
|
|
5
|
+
/**
|
|
6
|
+
* The Idempotency-Key of one `--rotate` run: Relyon rotates the newest active
|
|
7
|
+
* endpoint for the URL in place (new secret, same `we_` id), so `--rotate`
|
|
8
|
+
* never creates a second endpoint. The key mixes the URL with fresh
|
|
9
|
+
* randomness on every run, so every run rotates — a retry of an interrupted
|
|
10
|
+
* rotation rotates again instead of replaying, which is the honest behavior:
|
|
11
|
+
* the fresh secret may never have reached the store's `.env`. The server
|
|
12
|
+
* recognizes the key family by shape (`sk-whe-rot-` + 40 hex), not by value.
|
|
13
|
+
*/
|
|
14
|
+
export declare function webhookRotationKey(endpointUrl: string): string;
|
|
15
|
+
/** A Test webhook signing secret as Relyon issues it (`rly_whsec_test_` + hex). */
|
|
16
|
+
export declare const WEBHOOK_SECRET_SHAPE: RegExp;
|
|
17
|
+
/** A webhook signing secret as Relyon issues it for the mode (`rly_whsec_test_…` or `rly_whsec_live_…`). Test and Live never mix. */
|
|
18
|
+
export declare function webhookSecretShape(live: boolean): RegExp;
|
|
19
|
+
/** A contract webhook endpoint id (`we_…`). */
|
|
20
|
+
export declare const WEBHOOK_ENDPOINT_ID_SHAPE: RegExp;
|
|
21
|
+
export interface V1WebhookEndpoint {
|
|
22
|
+
id: string;
|
|
23
|
+
url: string;
|
|
24
|
+
status: "enabled" | "disabled";
|
|
25
|
+
created: number;
|
|
26
|
+
secret?: string;
|
|
27
|
+
}
|
|
28
|
+
/** The contract's WebhookEndpoint for the given mode: the kit never accepts a row from the other mode. */
|
|
29
|
+
export declare function isWebhookEndpointFor(live: boolean): (data: unknown) => data is V1WebhookEndpoint;
|
|
30
|
+
/** The contract's WebhookEndpoint list for the given mode. */
|
|
31
|
+
export declare function isWebhookEndpointListFor(live: boolean): (data: unknown) => data is {
|
|
32
|
+
object: "list";
|
|
33
|
+
data: V1WebhookEndpoint[];
|
|
34
|
+
};
|
|
35
|
+
/** The contract's WebhookEndpoint, Test mode only: the kit never accepts a Live row here. */
|
|
36
|
+
export declare function isTestWebhookEndpoint(data: unknown): data is V1WebhookEndpoint;
|
|
37
|
+
export declare function isTestWebhookEndpointList(data: unknown): data is {
|
|
38
|
+
object: "list";
|
|
39
|
+
data: V1WebhookEndpoint[];
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The endpoint the doctor verifies against: the newest active registration
|
|
43
|
+
* for a URL. Mirrors the server's list order (created desc, then the
|
|
44
|
+
* registration-ordered `we_` id desc) so a rotation within one created
|
|
45
|
+
* second still picks the successor, never the superseded registration.
|
|
46
|
+
*/
|
|
47
|
+
export declare function newestActiveEndpoint(endpoints: readonly V1WebhookEndpoint[], url: string): V1WebhookEndpoint | undefined;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { LIST_OBJECT, WEBHOOK_ENDPOINT_OBJECT } from "./wire-names.js";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { isRecord, sha256 } from "./util.js";
|
|
4
|
+
// Shared by the `webhook` command and the kit's webhook receiver: the
|
|
5
|
+
// deterministic registration key, the event list, and the shape every answer
|
|
6
|
+
// from /v1/webhook_endpoints must pass before the kit trusts, saves or uses
|
|
7
|
+
// any of its values. A response outside this shape is treated as Relyon being
|
|
8
|
+
// unreachable — generic error, nothing written, no value echoed.
|
|
9
|
+
/** The only event the kit acts on; the doctor challenge is answered regardless of the subscription. */
|
|
10
|
+
export const WEBHOOK_EVENTS = ["agent_rules.updated"];
|
|
11
|
+
/** The deterministic Idempotency-Key of a URL's original registration, so a retry replays instead of duplicating. */
|
|
12
|
+
export function webhookRegistrationKey(endpointUrl) {
|
|
13
|
+
return `sk-whe-${sha256(endpointUrl).slice(0, 40)}`;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The Idempotency-Key of one `--rotate` run: Relyon rotates the newest active
|
|
17
|
+
* endpoint for the URL in place (new secret, same `we_` id), so `--rotate`
|
|
18
|
+
* never creates a second endpoint. The key mixes the URL with fresh
|
|
19
|
+
* randomness on every run, so every run rotates — a retry of an interrupted
|
|
20
|
+
* rotation rotates again instead of replaying, which is the honest behavior:
|
|
21
|
+
* the fresh secret may never have reached the store's `.env`. The server
|
|
22
|
+
* recognizes the key family by shape (`sk-whe-rot-` + 40 hex), not by value.
|
|
23
|
+
*/
|
|
24
|
+
export function webhookRotationKey(endpointUrl) {
|
|
25
|
+
return `sk-whe-rot-${sha256(`${endpointUrl}\n${randomBytes(16).toString("hex")}`).slice(0, 40)}`;
|
|
26
|
+
}
|
|
27
|
+
/** A Test webhook signing secret as Relyon issues it (`rly_whsec_test_` + hex). */
|
|
28
|
+
export const WEBHOOK_SECRET_SHAPE = /^rly_whsec_test_[A-Za-z0-9]{32,128}$/;
|
|
29
|
+
/** A webhook signing secret as Relyon issues it for the mode (`rly_whsec_test_…` or `rly_whsec_live_…`). Test and Live never mix. */
|
|
30
|
+
export function webhookSecretShape(live) {
|
|
31
|
+
return live ? /^rly_whsec_live_[A-Za-z0-9]{32,128}$/ : WEBHOOK_SECRET_SHAPE;
|
|
32
|
+
}
|
|
33
|
+
/** A contract webhook endpoint id (`we_…`). */
|
|
34
|
+
export const WEBHOOK_ENDPOINT_ID_SHAPE = /^we_[A-Za-z0-9_]{1,64}$/;
|
|
35
|
+
/** The contract's WebhookEndpoint for the given mode: the kit never accepts a row from the other mode. */
|
|
36
|
+
export function isWebhookEndpointFor(live) {
|
|
37
|
+
return (data) => isRecord(data) && data.object === WEBHOOK_ENDPOINT_OBJECT && data.livemode === live
|
|
38
|
+
&& typeof data.id === "string" && WEBHOOK_ENDPOINT_ID_SHAPE.test(data.id)
|
|
39
|
+
&& typeof data.url === "string"
|
|
40
|
+
&& (data.status === "enabled" || data.status === "disabled") && typeof data.created === "number";
|
|
41
|
+
}
|
|
42
|
+
/** The contract's WebhookEndpoint list for the given mode. */
|
|
43
|
+
export function isWebhookEndpointListFor(live) {
|
|
44
|
+
const item = isWebhookEndpointFor(live);
|
|
45
|
+
return (data) => isRecord(data) && data.object === LIST_OBJECT && Array.isArray(data.data) && data.data.every(item);
|
|
46
|
+
}
|
|
47
|
+
/** The contract's WebhookEndpoint, Test mode only: the kit never accepts a Live row here. */
|
|
48
|
+
export function isTestWebhookEndpoint(data) {
|
|
49
|
+
return isWebhookEndpointFor(false)(data);
|
|
50
|
+
}
|
|
51
|
+
export function isTestWebhookEndpointList(data) {
|
|
52
|
+
return isWebhookEndpointListFor(false)(data);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The endpoint the doctor verifies against: the newest active registration
|
|
56
|
+
* for a URL. Mirrors the server's list order (created desc, then the
|
|
57
|
+
* registration-ordered `we_` id desc) so a rotation within one created
|
|
58
|
+
* second still picks the successor, never the superseded registration.
|
|
59
|
+
*/
|
|
60
|
+
export function newestActiveEndpoint(endpoints, url) {
|
|
61
|
+
let newest;
|
|
62
|
+
for (const endpoint of endpoints) {
|
|
63
|
+
if (endpoint.url !== url || endpoint.status !== "enabled")
|
|
64
|
+
continue;
|
|
65
|
+
if (!newest || endpoint.created > newest.created || (endpoint.created === newest.created && endpoint.id > newest.id))
|
|
66
|
+
newest = endpoint;
|
|
67
|
+
}
|
|
68
|
+
return newest;
|
|
69
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
type JsonSchema = Record<string, unknown>;
|
|
2
|
+
export declare const GET_CHECKOUT_SCHEMA: JsonSchema;
|
|
3
|
+
export declare const UPDATE_CHECKOUT_SCHEMA: JsonSchema;
|
|
4
|
+
/** complete_checkout takes nothing: approval happens in the page, the card in the card fields. */
|
|
5
|
+
export declare const COMPLETE_CHECKOUT_SCHEMA: JsonSchema;
|
|
6
|
+
/** A small JSON Schema check (type, enum, properties, required, additionalProperties, items, bounds). null when valid. */
|
|
7
|
+
export declare function validateToolInput(schema: Record<string, unknown>, value: unknown, path?: string): string | null;
|
|
8
|
+
/**
|
|
9
|
+
* True when a value carries card data: a card-shaped key anywhere (number,
|
|
10
|
+
* pan, cvc, expiry...) or a 13-19 digit run (spaces and dashes allowed).
|
|
11
|
+
* Card data goes into the card fields only, never into a tool.
|
|
12
|
+
*/
|
|
13
|
+
export declare function containsCardData(value: unknown, depth?: number): boolean;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// WebMCP tool input schemas and the two checks both sides run: the browser
|
|
2
|
+
// script before it sends anything, and the kit's endpoints on arrival.
|
|
3
|
+
// `validateToolInput` and `containsCardData` are copied into the browser
|
|
4
|
+
// script with Function.prototype.toString, so they stay self-contained (no
|
|
5
|
+
// imports, no outer references).
|
|
6
|
+
const text = (maxLength) => ({ type: "string", maxLength });
|
|
7
|
+
export const GET_CHECKOUT_SCHEMA = { type: "object", properties: {}, additionalProperties: false };
|
|
8
|
+
export const UPDATE_CHECKOUT_SCHEMA = {
|
|
9
|
+
type: "object",
|
|
10
|
+
additionalProperties: false,
|
|
11
|
+
properties: {
|
|
12
|
+
line_items: {
|
|
13
|
+
type: "array", maxItems: 50,
|
|
14
|
+
items: {
|
|
15
|
+
type: "object", additionalProperties: false, required: ["item", "quantity"],
|
|
16
|
+
properties: {
|
|
17
|
+
item: { type: "object", additionalProperties: false, required: ["id"], properties: { id: text(200) } },
|
|
18
|
+
quantity: { type: "integer", minimum: 1, maximum: 999 },
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
buyer: {
|
|
23
|
+
type: "object", additionalProperties: false,
|
|
24
|
+
properties: { first_name: text(100), last_name: text(100), email: text(254) },
|
|
25
|
+
},
|
|
26
|
+
fulfillment: {
|
|
27
|
+
type: "object", additionalProperties: false,
|
|
28
|
+
properties: {
|
|
29
|
+
methods: {
|
|
30
|
+
type: "array", maxItems: 1,
|
|
31
|
+
items: {
|
|
32
|
+
type: "object", additionalProperties: false,
|
|
33
|
+
properties: {
|
|
34
|
+
type: { enum: ["shipping"] },
|
|
35
|
+
destinations: {
|
|
36
|
+
type: "array", maxItems: 1,
|
|
37
|
+
items: {
|
|
38
|
+
type: "object", additionalProperties: false,
|
|
39
|
+
properties: {
|
|
40
|
+
name: text(200), street_address: text(200), extended_address: text(200), address_locality: text(100),
|
|
41
|
+
address_region: text(100), postal_code: text(20), address_country: text(2),
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
groups: {
|
|
46
|
+
type: "array", maxItems: 1,
|
|
47
|
+
items: { type: "object", additionalProperties: false, properties: { selected_option_id: text(100) } },
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
discounts: { type: "object", additionalProperties: false, properties: { codes: { type: "array", maxItems: 10, items: text(64) } } },
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
/** complete_checkout takes nothing: approval happens in the page, the card in the card fields. */
|
|
58
|
+
export const COMPLETE_CHECKOUT_SCHEMA = { type: "object", properties: {}, additionalProperties: false };
|
|
59
|
+
/** A small JSON Schema check (type, enum, properties, required, additionalProperties, items, bounds). null when valid. */
|
|
60
|
+
export function validateToolInput(schema, value, path = "input") {
|
|
61
|
+
if (Array.isArray(schema.enum) && !schema.enum.includes(value))
|
|
62
|
+
return `${path} must be one of ${schema.enum.join(", ")}`;
|
|
63
|
+
const type = schema.type;
|
|
64
|
+
if (type === "object") {
|
|
65
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
66
|
+
return `${path} must be an object`;
|
|
67
|
+
const props = (schema.properties || {});
|
|
68
|
+
const record = value;
|
|
69
|
+
for (const key of (schema.required || []))
|
|
70
|
+
if (!(key in record))
|
|
71
|
+
return `${path}.${key} is required`;
|
|
72
|
+
for (const key of Object.keys(record)) {
|
|
73
|
+
if (!Object.prototype.hasOwnProperty.call(props, key)) {
|
|
74
|
+
if (schema.additionalProperties === false)
|
|
75
|
+
return `${path}.${key} is not accepted`;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const error = validateToolInput(props[key], record[key], `${path}.${key}`);
|
|
79
|
+
if (error)
|
|
80
|
+
return error;
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
if (type === "array") {
|
|
85
|
+
if (!Array.isArray(value))
|
|
86
|
+
return `${path} must be an array`;
|
|
87
|
+
if (typeof schema.maxItems === "number" && value.length > schema.maxItems)
|
|
88
|
+
return `${path} has too many items`;
|
|
89
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
90
|
+
const error = validateToolInput((schema.items || {}), value[i], `${path}[${i}]`);
|
|
91
|
+
if (error)
|
|
92
|
+
return error;
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
if (type === "string") {
|
|
97
|
+
if (typeof value !== "string")
|
|
98
|
+
return `${path} must be a string`;
|
|
99
|
+
if (typeof schema.maxLength === "number" && value.length > schema.maxLength)
|
|
100
|
+
return `${path} is too long`;
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
if (type === "integer" || type === "number") {
|
|
104
|
+
if (typeof value !== "number" || !Number.isFinite(value) || (type === "integer" && !Number.isInteger(value)))
|
|
105
|
+
return `${path} must be a ${type}`;
|
|
106
|
+
if (typeof schema.minimum === "number" && value < schema.minimum)
|
|
107
|
+
return `${path} is too small`;
|
|
108
|
+
if (typeof schema.maximum === "number" && value > schema.maximum)
|
|
109
|
+
return `${path} is too large`;
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
if (type === "boolean" && typeof value !== "boolean")
|
|
113
|
+
return `${path} must be a boolean`;
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* True when a value carries card data: a card-shaped key anywhere (number,
|
|
118
|
+
* pan, cvc, expiry...) or a 13-19 digit run (spaces and dashes allowed).
|
|
119
|
+
* Card data goes into the card fields only, never into a tool.
|
|
120
|
+
*/
|
|
121
|
+
export function containsCardData(value, depth = 0) {
|
|
122
|
+
if (depth > 12)
|
|
123
|
+
return true;
|
|
124
|
+
if (typeof value === "string")
|
|
125
|
+
return /(?:\d[ -]?){12,18}\d/.test(value);
|
|
126
|
+
if (typeof value === "number")
|
|
127
|
+
return Number.isInteger(value) && Math.abs(value) >= 1e12;
|
|
128
|
+
if (Array.isArray(value))
|
|
129
|
+
return value.some((item) => containsCardData(item, depth + 1));
|
|
130
|
+
if (typeof value === "object" && value !== null) {
|
|
131
|
+
for (const [key, item] of Object.entries(value)) {
|
|
132
|
+
if (/(^|[^a-z])(card|pan|cvc|cvv|cvn|csc|cid|security_?code|exp|expiry|expiration|exp_?month|exp_?year|cardholder|account_?number)([^a-z]|$)/i.test(key)
|
|
133
|
+
|| /^(number|cardnumber|cardNumber|primary_account_number)$/i.test(key))
|
|
134
|
+
return true;
|
|
135
|
+
if (containsCardData(item, depth + 1))
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return false;
|
|
140
|
+
}
|