@intentrax/sdk 1.6.0 → 1.8.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 (62) hide show
  1. package/README.md +56 -3
  2. package/cli/intentrax.mjs +57 -1
  3. package/index.js +4 -2
  4. package/index.ts +4 -2
  5. package/mcp/README.md +138 -0
  6. package/mcp/canonical.d.ts +12 -0
  7. package/mcp/canonical.mjs +70 -0
  8. package/mcp/cli.d.ts +16 -0
  9. package/mcp/cli.mjs +214 -0
  10. package/mcp/client.d.ts +131 -0
  11. package/mcp/client.mjs +955 -0
  12. package/mcp/commands.d.ts +113 -0
  13. package/mcp/commands.mjs +575 -0
  14. package/mcp/index.d.ts +12 -0
  15. package/mcp/index.mjs +12 -0
  16. package/mcp/proxy.d.ts +47 -0
  17. package/mcp/proxy.mjs +434 -0
  18. package/mcp/receipt-meta.d.ts +59 -0
  19. package/mcp/receipt-meta.mjs +178 -0
  20. package/mcp/tool-manifest.d.ts +74 -0
  21. package/mcp/tool-manifest.mjs +154 -0
  22. package/package.json +19 -1
  23. package/readback/README.md +352 -0
  24. package/readback/bridge.mjs +71 -0
  25. package/readback/cli.mjs +150 -0
  26. package/readback/confirm.mjs +404 -0
  27. package/readback/index.mjs +12 -0
  28. package/readback/recipe-worker.mjs +33 -0
  29. package/readback/recipes/_shared.mjs +126 -0
  30. package/readback/recipes/email-delivery.mjs +136 -0
  31. package/readback/recipes/github-issue.mjs +88 -0
  32. package/readback/recipes/http-json.mjs +109 -0
  33. package/readback/recipes/sql-row.mjs +96 -0
  34. package/readback/recipes/stripe-refund.mjs +73 -0
  35. package/readback/redact.mjs +68 -0
  36. package/sandbox/README.md +255 -0
  37. package/sandbox/authority.mjs +66 -0
  38. package/sandbox/bundle.mjs +93 -0
  39. package/sandbox/canonical.mjs +64 -0
  40. package/sandbox/check-runner.mjs +50 -0
  41. package/sandbox/check-worker.mjs +30 -0
  42. package/sandbox/cli.mjs +376 -0
  43. package/sandbox/effect-verifier.mjs +242 -0
  44. package/sandbox/effects.mjs +80 -0
  45. package/sandbox/envelope.mjs +174 -0
  46. package/sandbox/examples/read-only-check.example.mjs +32 -0
  47. package/sandbox/external-decision.mjs +364 -0
  48. package/sandbox/keys.mjs +179 -0
  49. package/sandbox/model.mjs +170 -0
  50. package/sandbox/run.mjs +324 -0
  51. package/sandbox/time.mjs +18 -0
  52. package/sandbox/verifier.mjs +503 -0
  53. package/scan/README.md +211 -0
  54. package/scan/classify.mjs +276 -0
  55. package/scan/cli.mjs +102 -0
  56. package/scan/configs.mjs +261 -0
  57. package/scan/credentials.mjs +121 -0
  58. package/scan/extract.mjs +323 -0
  59. package/scan/gates.mjs +94 -0
  60. package/scan/report.mjs +58 -0
  61. package/scan/scan.mjs +571 -0
  62. package/scan/text.mjs +186 -0
@@ -0,0 +1,136 @@
1
+ // Read-back recipe: email delivery status by provider message id.
2
+ //
3
+ // A generic provider-status adapter with two built-in adapters. Field names
4
+ // below were checked against the providers' public API reference pages on
5
+ // 2026-11-19:
6
+ //
7
+ // Postmark — "Outbound message details"
8
+ // https://postmarkapp.com/developer/api/messages-api
9
+ // GET https://api.postmarkapp.com/messages/outbound/{messageid}/details
10
+ // headers: Accept: application/json, X-Postmark-Server-Token: <server token>
11
+ // response: MessageID, Status ("Sent" | "Processed" | "Queued"),
12
+ // MessageEvents[] with Type in Delivered | Bounced | Transient |
13
+ // Opened | LinkClicked | SubscriptionChanged.
14
+ // Scope: Postmark has no read-only server token. The endpoint needs a
15
+ // Server API token, which can also SEND mail. This recipe only issues GET,
16
+ // but keep that token away from the agent whose claims you are checking.
17
+ //
18
+ // SendGrid (Twilio) — Email Activity "Filter messages by message ID"
19
+ // https://www.twilio.com/docs/sendgrid/api-reference/email-activity/filter-messages-by-message-id
20
+ // GET https://api.sendgrid.com/v3/messages/{msg_id}
21
+ // headers: Authorization: Bearer <api key>
22
+ // response: msg_id, to_email, status ("processed" | "delivered" |
23
+ // "not_delivered"), events[] with event_name in bounced | opened |
24
+ // clicked | processed | dropped | delivered | deferred | ...
25
+ // Scope: a restricted API key with Email Activity access only. The Email
26
+ // Activity API needs the paid "additional email activity history" add-on,
27
+ // and generates no data for regional (EU) subusers.
28
+ // ASSUMPTION: SendGrid's getting-started guide also mentions a "processing"
29
+ // status value that the response schema does not list; this adapter treats
30
+ // any value other than delivered / not_delivered as in flight only if it is
31
+ // "processed" or "processing", and leaves `delivery` out otherwise.
32
+ //
33
+ // Normalized observation (only fields that could be derived are present):
34
+ // { message_id, provider_status, delivery }
35
+ // delivery: "delivered" | "bounced" | "not_delivered" | "in_flight"
36
+ // `in_flight` is this recipe's default PENDING value. When delivery cannot be
37
+ // derived, `delivery` is left out, so confirmThenReport says UNKNOWN rather
38
+ // than guessing.
39
+ //
40
+ // Multi-recipient Postmark messages: any Bounced event makes the message
41
+ // "bounced" (a partial failure is not a delivery); "delivered" needs at least
42
+ // one Delivered event and no Bounced event.
43
+
44
+ import { defineRecipe, getJson, requireString, resolveFetch } from "./_shared.mjs";
45
+
46
+ export const EMAIL_DELIVERY_PENDING = Object.freeze({ delivery: Object.freeze(["in_flight"]) });
47
+
48
+ const MESSAGE_ID = /^[A-Za-z0-9._<>@+=-]+$/;
49
+
50
+ function postmarkNormalize(body) {
51
+ const out = {};
52
+ if (!body || typeof body !== "object") return out;
53
+ if (typeof body.MessageID === "string") out.message_id = body.MessageID;
54
+ if (typeof body.Status === "string") out.provider_status = body.Status;
55
+ const types = Array.isArray(body.MessageEvents) ? body.MessageEvents.map((e) => e && e.Type) : [];
56
+ if (types.includes("Bounced")) out.delivery = "bounced";
57
+ else if (types.includes("Delivered")) out.delivery = "delivered";
58
+ else if (["Queued", "Processed", "Sent"].includes(body.Status)) out.delivery = "in_flight";
59
+ return out;
60
+ }
61
+
62
+ function sendgridNormalize(body) {
63
+ const out = {};
64
+ if (!body || typeof body !== "object") return out;
65
+ if (typeof body.msg_id === "string") out.message_id = body.msg_id;
66
+ if (typeof body.status === "string") out.provider_status = body.status;
67
+ const names = Array.isArray(body.events) ? body.events.map((e) => e && e.event_name) : [];
68
+ if (body.status === "delivered") out.delivery = "delivered";
69
+ else if (body.status === "not_delivered") out.delivery = names.includes("bounced") ? "bounced" : "not_delivered";
70
+ else if (body.status === "processed" || body.status === "processing") out.delivery = "in_flight";
71
+ return out;
72
+ }
73
+
74
+ export const EMAIL_ADAPTERS = Object.freeze({
75
+ postmark: Object.freeze({
76
+ source: "Postmark",
77
+ apiBase: "https://api.postmarkapp.com",
78
+ path: (id) => "/messages/outbound/" + encodeURIComponent(id) + "/details",
79
+ headers: (token) => ({ accept: "application/json", "x-postmark-server-token": token }),
80
+ normalize: postmarkNormalize,
81
+ }),
82
+ sendgrid: Object.freeze({
83
+ source: "SendGrid",
84
+ apiBase: "https://api.sendgrid.com",
85
+ path: (id) => "/v3/messages/" + encodeURIComponent(id),
86
+ headers: (token) => ({ accept: "application/json", authorization: "Bearer " + token }),
87
+ normalize: sendgridNormalize,
88
+ }),
89
+ });
90
+
91
+ /**
92
+ * @param {object} opts
93
+ * @param {"postmark"|"sendgrid"} [opts.provider] built-in adapter name
94
+ * @param {object} [opts.adapter] custom adapter: { source, apiBase, path(id), headers(token), normalize(json) }
95
+ * @param {string} opts.token provider credential (see scopes above)
96
+ * @param {string} opts.messageId provider message id
97
+ * @param {string} [opts.apiBase] override the adapter's base URL
98
+ * @param {Function} [opts.fetch]
99
+ */
100
+ export function emailDelivery(opts = {}) {
101
+ const { provider, adapter: custom, token, messageId, apiBase, fetch: fetchImpl } = opts;
102
+ if ((provider === undefined) === (custom === undefined)) throw new TypeError("pass exactly one of provider or adapter");
103
+ let adapter;
104
+ if (provider !== undefined) {
105
+ if (!Object.prototype.hasOwnProperty.call(EMAIL_ADAPTERS, provider)) {
106
+ throw new TypeError("provider must be one of: " + Object.keys(EMAIL_ADAPTERS).join(", "));
107
+ }
108
+ adapter = EMAIL_ADAPTERS[provider];
109
+ } else {
110
+ adapter = custom;
111
+ for (const k of ["path", "headers", "normalize"]) {
112
+ if (!adapter || typeof adapter[k] !== "function") throw new TypeError("adapter." + k + " must be a function");
113
+ }
114
+ requireString("adapter.source", adapter.source);
115
+ requireString("adapter.apiBase", adapter.apiBase);
116
+ }
117
+ requireString("token", token, { max: 10000 });
118
+ requireString("messageId", messageId, { pattern: MESSAGE_ID, max: 500 });
119
+ const f = resolveFetch(fetchImpl);
120
+ const url = String(apiBase || adapter.apiBase).replace(/\/+$/, "") + adapter.path(messageId);
121
+ const headers = adapter.headers(token);
122
+
123
+ return defineRecipe({
124
+ href: import.meta.url,
125
+ exportName: "emailDelivery",
126
+ options: opts,
127
+ secrets: [token],
128
+ resource: "email " + messageId,
129
+ source: adapter.source,
130
+ pending: EMAIL_DELIVERY_PENDING,
131
+ read: async ({ signal }) => {
132
+ const { body } = await getJson({ fetchImpl: f, url, headers, signal, source: adapter.source });
133
+ return adapter.normalize(body);
134
+ },
135
+ });
136
+ }
@@ -0,0 +1,88 @@
1
+ // Read-back recipe: GitHub issue or pull request state.
2
+ //
3
+ // Minimum scope: a fine-grained personal access token (or GitHub App token)
4
+ // limited to the one repository, with "Issues: Read-only" (for kind "issue")
5
+ // or "Pull requests: Read-only" (for kind "pull"); GitHub adds
6
+ // "Metadata: Read-only" automatically. Public repositories need no token
7
+ // (unauthenticated requests have a low rate limit).
8
+ //
9
+ // const check = githubIssue({ owner: "acme", repo: "app", number: 42, token: process.env.GH_ISSUES_READ });
10
+ // const check = githubIssue({ owner: "acme", repo: "app", number: 7, kind: "pull", octokit });
11
+ //
12
+ // kind "issue": GET /repos/{owner}/{repo}/issues/{number}
13
+ // -> { number, state ("open" | "closed"), state_reason, is_pull_request }
14
+ // kind "pull": GET /repos/{owner}/{repo}/pulls/{number}
15
+ // -> { number, state ("open" | "closed"), merged, draft }
16
+ // (GitHub's issues endpoint also returns pull requests; `is_pull_request`
17
+ // says which.)
18
+
19
+ import { checkNotFoundAs, defineRecipe, getJson, pick, requireString, resolveFetch } from "./_shared.mjs";
20
+
21
+ const NAME = /^[A-Za-z0-9_.-]+$/;
22
+
23
+ /**
24
+ * @param {object} opts
25
+ * @param {string} opts.owner
26
+ * @param {string} opts.repo
27
+ * @param {number} opts.number
28
+ * @param {"issue"|"pull"} [opts.kind] default "issue"
29
+ * @param {string} [opts.token] fine-grained read-only token
30
+ * @param {object} [opts.octokit] an Octokit client (only rest.issues.get / rest.pulls.get are called)
31
+ * @param {string} [opts.apiBase] default https://api.github.com (GitHub Enterprise: https://HOST/api/v3)
32
+ * @param {object} [opts.notFoundAs]
33
+ * @param {Function} [opts.fetch]
34
+ */
35
+ export function githubIssue(opts = {}) {
36
+ const { owner, repo, number, kind = "issue", token, octokit, apiBase = "https://api.github.com", notFoundAs, fetch: fetchImpl } = opts;
37
+ requireString("owner", owner, { pattern: NAME, max: 100 });
38
+ requireString("repo", repo, { pattern: NAME, max: 100 });
39
+ if (!Number.isSafeInteger(number) || number < 1) throw new TypeError("number must be a positive integer");
40
+ if (kind !== "issue" && kind !== "pull") throw new TypeError('kind must be "issue" or "pull"');
41
+ if (token !== undefined && octokit !== undefined) throw new TypeError("pass token or octokit, not both");
42
+ if (token !== undefined) requireString("token", token, { max: 1000 });
43
+ checkNotFoundAs(notFoundAs);
44
+
45
+ const shape = (data) => {
46
+ if (kind === "pull") return pick(data, ["number", "state", "merged", "draft"]);
47
+ const out = pick(data, ["number", "state", "state_reason"]);
48
+ if (data && typeof data === "object") out.is_pull_request = Object.prototype.hasOwnProperty.call(data, "pull_request");
49
+ return out;
50
+ };
51
+
52
+ let read;
53
+ if (octokit !== undefined) {
54
+ const api = octokit && octokit.rest ? octokit.rest : octokit;
55
+ const fn = kind === "pull" ? api && api.pulls && api.pulls.get : api && api.issues && api.issues.get;
56
+ if (typeof fn !== "function") throw new TypeError("octokit must expose rest." + (kind === "pull" ? "pulls" : "issues") + ".get");
57
+ read = async ({ signal }) => {
58
+ const params = kind === "pull" ? { owner, repo, pull_number: number } : { owner, repo, issue_number: number };
59
+ const res = await fn.call(kind === "pull" ? api.pulls : api.issues, { ...params, request: signal ? { signal } : undefined });
60
+ return shape(res && res.data !== undefined ? res.data : res);
61
+ };
62
+ } else {
63
+ const f = resolveFetch(fetchImpl);
64
+ const url = String(apiBase).replace(/\/+$/, "") + "/repos/" + owner + "/" + repo + (kind === "pull" ? "/pulls/" : "/issues/") + number;
65
+ const headers = {
66
+ accept: "application/vnd.github+json",
67
+ "x-github-api-version": "2022-11-28",
68
+ "user-agent": "intentrax-readback",
69
+ };
70
+ if (token) headers.authorization = "Bearer " + token;
71
+ read = async ({ signal }) => {
72
+ const { notFound, body } = await getJson({ fetchImpl: f, url, headers, signal, source: "GitHub", allowNotFound: notFoundAs !== undefined });
73
+ if (notFound) return structuredClone(notFoundAs);
74
+ return shape(body);
75
+ };
76
+ }
77
+
78
+ return defineRecipe({
79
+ href: import.meta.url,
80
+ exportName: "githubIssue",
81
+ options: opts,
82
+ secrets: token ? [token] : [],
83
+ resource: (kind === "pull" ? "pull request " : "issue ") + owner + "/" + repo + "#" + number,
84
+ source: "GitHub",
85
+ pending: null,
86
+ read,
87
+ });
88
+ }
@@ -0,0 +1,109 @@
1
+ // Read-back recipe: generic HTTP GET of a JSON document, plus field selection.
2
+ //
3
+ // Minimum scope: whatever read-only credential the API offers for this one
4
+ // resource (a read-scoped API key, a viewer role token), or none for a public
5
+ // endpoint. The recipe only ever sends GET with no body and refuses redirects.
6
+ //
7
+ // const check = httpJson({
8
+ // url: "https://api.example.com/v1/tickets/T-1",
9
+ // token: process.env.EXAMPLE_READONLY_TOKEN, // sent as `Authorization: Bearer …`
10
+ // select: { status: "data.status", owner: "data.assignee.login" },
11
+ // });
12
+ //
13
+ // `select` maps output field names to dot paths (`a.b[0].c` and `a.b.0.c`
14
+ // both work). A path the response does not contain is left OUT of the result
15
+ // (never null), so confirmThenReport reports it as a missing field. Without
16
+ // `select` the whole top-level JSON object is returned.
17
+
18
+ import { checkNotFoundAs, defineRecipe, getJson, requireString, resolveFetch } from "./_shared.mjs";
19
+ import { displayUrl } from "../redact.mjs";
20
+
21
+ const CREDENTIAL_HEADER = /auth|token|key|secret|cookie|session/i;
22
+
23
+ /** Resolve a dot path; returns { found, value }. */
24
+ export function selectPath(root, path) {
25
+ const parts = String(path).replace(/\[(\d+)\]/g, ".$1").split(".").filter((p) => p.length > 0);
26
+ let cur = root;
27
+ for (const p of parts) {
28
+ if (cur === null || typeof cur !== "object" || !Object.prototype.hasOwnProperty.call(cur, p)) {
29
+ return { found: false, value: undefined };
30
+ }
31
+ cur = cur[p];
32
+ }
33
+ return cur === undefined ? { found: false, value: undefined } : { found: true, value: cur };
34
+ }
35
+
36
+ function normalizeSelect(select) {
37
+ if (select === undefined || select === null) return null;
38
+ if (Array.isArray(select)) {
39
+ if (select.length === 0) throw new TypeError("select must not be empty");
40
+ return Object.fromEntries(select.map((p) => [requireString("select path", p), p]));
41
+ }
42
+ if (typeof select === "object") {
43
+ const entries = Object.entries(select);
44
+ if (entries.length === 0) throw new TypeError("select must not be empty");
45
+ for (const [k, p] of entries) {
46
+ requireString("select field name", k);
47
+ requireString("select path for " + k, p);
48
+ }
49
+ return { ...select };
50
+ }
51
+ throw new TypeError("select must be an array of paths or an object of { field: path }");
52
+ }
53
+
54
+ /**
55
+ * @param {object} opts
56
+ * @param {string} opts.url http(s) URL to GET
57
+ * @param {string} [opts.token] read-only bearer token
58
+ * @param {Record<string,string>} [opts.headers] extra headers (credential-looking values are redacted from messages)
59
+ * @param {string[]|Record<string,string>} [opts.select]
60
+ * @param {object} [opts.notFoundAs] returned as the observation on HTTP 404 (e.g. `{ exists: false }`)
61
+ * @param {string} [opts.resource] label for messages (default `GET <origin><path>`)
62
+ * @param {string} [opts.source] name of the system read (default: the URL host)
63
+ * @param {Record<string,unknown[]>} [opts.pending] field values that mean "not settled yet"
64
+ * @param {Function} [opts.fetch] injected fetch (runs the check in-process)
65
+ */
66
+ export function httpJson(opts = {}) {
67
+ const { url, token, headers = {}, select, notFoundAs, resource, source, pending, fetch: fetchImpl } = opts;
68
+ requireString("url", url, { max: 4000 });
69
+ const parsed = new URL(url);
70
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new TypeError("url must be http(s)");
71
+ if (token !== undefined) requireString("token", token, { max: 10000 });
72
+ if (headers === null || typeof headers !== "object" || Array.isArray(headers)) throw new TypeError("headers must be an object");
73
+ const fields = normalizeSelect(select);
74
+ checkNotFoundAs(notFoundAs);
75
+ const f = resolveFetch(fetchImpl);
76
+
77
+ const secrets = [];
78
+ if (token) secrets.push(token);
79
+ for (const [k, v] of Object.entries(headers)) if (CREDENTIAL_HEADER.test(k) && typeof v === "string") secrets.push(v);
80
+ if (parsed.password) secrets.push(decodeURIComponent(parsed.password));
81
+
82
+ const sendHeaders = { accept: "application/json", ...headers };
83
+ if (token) sendHeaders.authorization = "Bearer " + token;
84
+ const src = source || parsed.host;
85
+
86
+ return defineRecipe({
87
+ href: import.meta.url,
88
+ exportName: "httpJson",
89
+ options: opts,
90
+ secrets,
91
+ resource: resource || "GET " + displayUrl(url),
92
+ source: src,
93
+ pending,
94
+ read: async ({ signal }) => {
95
+ const { notFound, body } = await getJson({ fetchImpl: f, url, headers: sendHeaders, signal, source: src, allowNotFound: notFoundAs !== undefined });
96
+ if (notFound) return structuredClone(notFoundAs);
97
+ if (fields === null) {
98
+ if (body === null || typeof body !== "object" || Array.isArray(body)) throw new Error(src + " returned JSON that is not an object; pass `select`");
99
+ return body;
100
+ }
101
+ const out = {};
102
+ for (const [name, path] of Object.entries(fields)) {
103
+ const { found, value } = selectPath(body, path);
104
+ if (found) out[name] = value;
105
+ }
106
+ return out;
107
+ },
108
+ });
109
+ }
@@ -0,0 +1,96 @@
1
+ // Read-back recipe: one database row, through a query function you pass.
2
+ //
3
+ // Minimum scope: a database role with SELECT on the tables the query reads
4
+ // and nothing else (for example Postgres `GRANT SELECT ON orders TO readback;`
5
+ // on a role with no INSERT/UPDATE/DELETE), ideally on a read replica, with
6
+ // `default_transaction_read_only = on` for that role.
7
+ //
8
+ // const check = sqlRow({
9
+ // query: (sql, params) => readonlyPool.query(sql, params), // pg: returns { rows }
10
+ // sql: "SELECT status, amount_cents FROM refunds WHERE id = $1",
11
+ // params: ["rf_2291"],
12
+ // resource: "refund rf_2291",
13
+ // });
14
+ //
15
+ // `query(sql, params, { signal })` may return an array of rows or an object
16
+ // with a `rows` array (node-postgres, mysql2's [rows] is NOT accepted: pass
17
+ // `(sql, p) => pool.query(sql, p).then(([rows]) => rows)`). Exactly one row
18
+ // must match; zero rows is an error (UNKNOWN) unless you pass `notFoundAs`,
19
+ // and more than one row is always an error.
20
+ //
21
+ // The SQL text is checked lexically: it must be a single SELECT (or WITH …
22
+ // SELECT) statement without data-modifying keywords or row locks. That check
23
+ // is a tripwire for mistakes, NOT a security boundary — the read-only role is
24
+ // what actually keeps the check from writing.
25
+
26
+ import { checkNotFoundAs, defineRecipe, requireString } from "./_shared.mjs";
27
+
28
+ // Keywords that cannot appear in a plain read. (Postgres allows INSERT /
29
+ // UPDATE / DELETE / MERGE inside WITH; SELECT … INTO creates a table; FOR
30
+ // UPDATE takes locks.) Functions with side effects (nextval, pg_notify, your
31
+ // own) cannot be caught lexically: the read-only role is the real guard.
32
+ const WRITE_KEYWORDS = /\b(insert|update|delete|merge|upsert|truncate|drop|alter|create|grant|revoke|copy|call|exec|execute|lock|into|set|nextval|setval|pg_notify|dblink_exec)\b/i;
33
+
34
+ function stripLiteralsAndComments(sql) {
35
+ return sql
36
+ .replace(/--[^\n]*/g, " ")
37
+ .replace(/\/\*[\s\S]*?\*\//g, " ")
38
+ .replace(/'(?:[^']|'')*'/g, "''")
39
+ .replace(/"(?:[^"]|"")*"/g, '""')
40
+ .replace(/`[^`]*`/g, "``");
41
+ }
42
+
43
+ /** Throws TypeError unless `sql` looks like one read-only SELECT statement. */
44
+ export function assertReadOnlySql(sql) {
45
+ requireString("sql", sql, { max: 20000 });
46
+ const bare = stripLiteralsAndComments(sql).trim().replace(/;\s*$/, "");
47
+ if (bare.includes(";")) throw new TypeError("sql must be a single statement");
48
+ if (!/^(select|with)\b/i.test(bare)) throw new TypeError("sql must start with SELECT or WITH");
49
+ const hit = bare.match(WRITE_KEYWORDS);
50
+ if (hit) throw new TypeError("sql contains a non-read keyword: " + hit[1].toUpperCase());
51
+ if (/\bfor\s+(no\s+key\s+)?(share|key\s+share)\b/i.test(bare)) throw new TypeError("sql must not take row locks");
52
+ return sql;
53
+ }
54
+
55
+ /**
56
+ * @param {object} opts
57
+ * @param {(sql: string, params: unknown[], ctx: { signal?: AbortSignal }) => Promise<unknown>} opts.query
58
+ * @param {string} opts.sql
59
+ * @param {unknown[]} [opts.params]
60
+ * @param {string} [opts.resource]
61
+ * @param {string} [opts.source] default "database"
62
+ * @param {object} [opts.notFoundAs] observation when no row matches
63
+ * @param {Record<string,unknown[]>} [opts.pending]
64
+ */
65
+ export function sqlRow(opts = {}) {
66
+ const { query, sql, params = [], resource, source = "database", notFoundAs, pending } = opts;
67
+ if (typeof query !== "function") throw new TypeError("query must be a function (sql, params) => rows");
68
+ assertReadOnlySql(sql);
69
+ if (!Array.isArray(params)) throw new TypeError("params must be an array");
70
+ checkNotFoundAs(notFoundAs);
71
+
72
+ return defineRecipe({
73
+ href: import.meta.url,
74
+ exportName: "sqlRow",
75
+ options: opts, // holds a function, so this check always runs in-process
76
+ secrets: [],
77
+ resource: resource || "row",
78
+ source,
79
+ pending,
80
+ read: async ({ signal }) => {
81
+ const result = await query(sql, params.slice(), { signal });
82
+ const rows = Array.isArray(result) ? result : result && Array.isArray(result.rows) ? result.rows : null;
83
+ if (rows === null) throw new Error("query returned neither an array of rows nor { rows: [...] }");
84
+ if (rows.length === 0) {
85
+ if (notFoundAs !== undefined) return structuredClone(notFoundAs);
86
+ throw new Error("no row matched");
87
+ }
88
+ if (rows.length > 1) throw new Error("query matched " + rows.length + " rows; expected exactly one");
89
+ const row = rows[0];
90
+ if (row === null || typeof row !== "object" || Array.isArray(row)) throw new Error("row is not an object of columns");
91
+ const out = {};
92
+ for (const [k, v] of Object.entries(row)) if (v !== undefined) out[k] = v;
93
+ return out;
94
+ },
95
+ });
96
+ }
@@ -0,0 +1,73 @@
1
+ // Read-back recipe: Stripe refund status by id.
2
+ //
3
+ // Minimum scope: a Stripe RESTRICTED key (rk_live_… / rk_test_…) with
4
+ // "Refunds: Read" and nothing else. A full secret key (sk_live_…) can move
5
+ // money, so it is refused unless the caller passes `allowFullSecretKey: true`;
6
+ // sk_test_ keys are accepted for local testing.
7
+ //
8
+ // const check = stripeRefund({ apiKey: process.env.STRIPE_REFUNDS_READ_KEY, refundId: "re_123" });
9
+ // // or, with a client you already have (only `refunds.retrieve` is called):
10
+ // const check = stripeRefund({ stripe, refundId: "re_123" });
11
+ //
12
+ // Reads GET https://api.stripe.com/v1/refunds/{id} and returns the fields
13
+ // Stripe returned among: id, status, amount, currency, failure_reason.
14
+ // Stripe documents refund `status` as one of pending, requires_action,
15
+ // succeeded, failed, canceled; `pending` and `requires_action` are not final,
16
+ // so they are this recipe's default PENDING values.
17
+
18
+ import { checkNotFoundAs, defineRecipe, getJson, pick, requireString, resolveFetch } from "./_shared.mjs";
19
+
20
+ export const STRIPE_REFUND_FIELDS = Object.freeze(["id", "status", "amount", "currency", "failure_reason"]);
21
+ export const STRIPE_REFUND_PENDING = Object.freeze({ status: Object.freeze(["pending", "requires_action"]) });
22
+
23
+ const ID = /^[A-Za-z0-9_]+$/;
24
+
25
+ /**
26
+ * @param {object} opts
27
+ * @param {string} opts.refundId
28
+ * @param {string} [opts.apiKey] restricted key with Refunds: Read
29
+ * @param {object} [opts.stripe] a Stripe client (only refunds.retrieve is used)
30
+ * @param {boolean} [opts.allowFullSecretKey] accept an sk_live_ key (not recommended)
31
+ * @param {string} [opts.apiBase] default https://api.stripe.com
32
+ * @param {object} [opts.notFoundAs] observation to return on HTTP 404
33
+ * @param {Function} [opts.fetch]
34
+ */
35
+ export function stripeRefund(opts = {}) {
36
+ const { refundId, apiKey, stripe, allowFullSecretKey = false, apiBase = "https://api.stripe.com", notFoundAs, fetch: fetchImpl } = opts;
37
+ requireString("refundId", refundId, { pattern: ID, max: 255 });
38
+ if ((apiKey === undefined) === (stripe === undefined)) throw new TypeError("pass exactly one of apiKey or stripe");
39
+ checkNotFoundAs(notFoundAs);
40
+ if (apiKey !== undefined) {
41
+ requireString("apiKey", apiKey, { max: 1000 });
42
+ if (/^sk_live_/.test(apiKey) && !allowFullSecretKey) {
43
+ throw new TypeError("refusing a full secret key (sk_live_); use a restricted key (rk_live_) with only Refunds: Read, or pass allowFullSecretKey: true");
44
+ }
45
+ } else if (!stripe || !stripe.refunds || typeof stripe.refunds.retrieve !== "function") {
46
+ throw new TypeError("stripe client must expose refunds.retrieve");
47
+ }
48
+
49
+ let read;
50
+ if (stripe) {
51
+ read = async () => pick(await stripe.refunds.retrieve(refundId), STRIPE_REFUND_FIELDS);
52
+ } else {
53
+ const f = resolveFetch(fetchImpl);
54
+ const url = String(apiBase).replace(/\/+$/, "") + "/v1/refunds/" + encodeURIComponent(refundId);
55
+ const headers = { accept: "application/json", authorization: "Bearer " + apiKey };
56
+ read = async ({ signal }) => {
57
+ const { notFound, body } = await getJson({ fetchImpl: f, url, headers, signal, source: "Stripe", allowNotFound: notFoundAs !== undefined });
58
+ if (notFound) return structuredClone(notFoundAs);
59
+ return pick(body, STRIPE_REFUND_FIELDS);
60
+ };
61
+ }
62
+
63
+ return defineRecipe({
64
+ href: import.meta.url,
65
+ exportName: "stripeRefund",
66
+ options: opts,
67
+ secrets: apiKey ? [apiKey] : [],
68
+ resource: "refund " + refundId,
69
+ source: "Stripe",
70
+ pending: STRIPE_REFUND_PENDING,
71
+ read,
72
+ });
73
+ }
@@ -0,0 +1,68 @@
1
+ // Credential redaction for read-back messages.
2
+ //
3
+ // Every string that confirmThenReport puts in `firstLine` or `detail` (check
4
+ // error messages in particular) passes through redact(). Two layers:
5
+ //
6
+ // 1. exact secrets: values the caller or a recipe declared (an API key, a
7
+ // token). Each occurrence is replaced, whatever its shape.
8
+ // 2. shape patterns: common credential formats that may leak through an
9
+ // error message even when nobody declared them (Bearer headers, Stripe
10
+ // / GitHub / SendGrid keys, URL userinfo, credential query parameters).
11
+ //
12
+ // Redaction is a backstop, not a licence to put secrets in messages: recipes
13
+ // build their own error messages from status codes and never include headers.
14
+
15
+ export const REDACTED = "[REDACTED]";
16
+
17
+ const PATTERNS = [
18
+ // Authorization header values.
19
+ /\b(Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi,
20
+ // Stripe secret, restricted and publishable keys.
21
+ /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{8,}/g,
22
+ // GitHub tokens (classic, fine-grained, app, OAuth, refresh).
23
+ /\bgh[pousr]_[A-Za-z0-9]{16,}/g,
24
+ /\bgithub_pat_[A-Za-z0-9_]{16,}/g,
25
+ // SendGrid API keys.
26
+ /\bSG\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
27
+ // Postmark-style server tokens are UUIDs; only redact them next to a
28
+ // credential-looking label so message ids (also UUIDs) stay readable.
29
+ /\b(X-Postmark-(?:Server|Account)-Token["':=\s]+)[0-9a-f-]{36}/gi,
30
+ ];
31
+
32
+ // URL userinfo (scheme://user:password@host) and credential query parameters.
33
+ const USERINFO = /(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi;
34
+ const QUERY_SECRET = /([?&](?:access_token|token|api_key|apikey|key|secret|password|signature|sig)=)[^&#\s"']+/gi;
35
+
36
+ /**
37
+ * Replace declared secrets and credential-shaped substrings in `text`.
38
+ * @param {unknown} text
39
+ * @param {Iterable<string>} [secrets]
40
+ * @returns {string}
41
+ */
42
+ export function redact(text, secrets = []) {
43
+ let out = String(text);
44
+ const exact = [...secrets]
45
+ .filter((s) => typeof s === "string" && s.length >= 4)
46
+ // Longest first, so a secret that contains another is removed whole.
47
+ .sort((a, b) => b.length - a.length);
48
+ for (const s of exact) out = out.split(s).join(REDACTED);
49
+ for (const re of PATTERNS) {
50
+ out = out.replace(re, (match, label) =>
51
+ typeof label === "string" && /^X-Postmark/i.test(label) ? label + REDACTED
52
+ : typeof label === "string" && /^(bearer|basic|token)$/i.test(label) ? label + " " + REDACTED
53
+ : REDACTED);
54
+ }
55
+ out = out.replace(USERINFO, "$1" + REDACTED + "@");
56
+ out = out.replace(QUERY_SECRET, "$1" + REDACTED);
57
+ return out;
58
+ }
59
+
60
+ /** A URL for messages: origin + path only, never userinfo, query or fragment. */
61
+ export function displayUrl(url) {
62
+ try {
63
+ const u = new URL(url);
64
+ return u.origin + u.pathname;
65
+ } catch {
66
+ return "<invalid url>";
67
+ }
68
+ }