@intentrax/sdk 1.7.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.
- package/README.md +17 -2
- package/cli/intentrax.mjs +45 -1
- package/mcp/README.md +138 -0
- package/mcp/canonical.d.ts +12 -0
- package/mcp/canonical.mjs +70 -0
- package/mcp/cli.d.ts +16 -0
- package/mcp/cli.mjs +214 -0
- package/mcp/client.d.ts +131 -0
- package/mcp/client.mjs +955 -0
- package/mcp/commands.d.ts +113 -0
- package/mcp/commands.mjs +575 -0
- package/mcp/index.d.ts +12 -0
- package/mcp/index.mjs +12 -0
- package/mcp/proxy.d.ts +47 -0
- package/mcp/proxy.mjs +434 -0
- package/mcp/receipt-meta.d.ts +59 -0
- package/mcp/receipt-meta.mjs +178 -0
- package/mcp/tool-manifest.d.ts +74 -0
- package/mcp/tool-manifest.mjs +154 -0
- package/package.json +16 -1
- package/readback/README.md +352 -0
- package/readback/bridge.mjs +71 -0
- package/readback/cli.mjs +150 -0
- package/readback/confirm.mjs +404 -0
- package/readback/index.mjs +12 -0
- package/readback/recipe-worker.mjs +33 -0
- package/readback/recipes/_shared.mjs +126 -0
- package/readback/recipes/email-delivery.mjs +136 -0
- package/readback/recipes/github-issue.mjs +88 -0
- package/readback/recipes/http-json.mjs +109 -0
- package/readback/recipes/sql-row.mjs +96 -0
- package/readback/recipes/stripe-refund.mjs +73 -0
- package/readback/redact.mjs +68 -0
- package/scan/README.md +211 -0
- package/scan/classify.mjs +276 -0
- package/scan/cli.mjs +102 -0
- package/scan/configs.mjs +261 -0
- package/scan/credentials.mjs +121 -0
- package/scan/extract.mjs +323 -0
- package/scan/gates.mjs +94 -0
- package/scan/report.mjs +58 -0
- package/scan/scan.mjs +571 -0
- package/scan/text.mjs +186 -0
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
# Read-back: confirm, then report (preview)
|
|
2
|
+
|
|
3
|
+
> **Self-reported, not an attestation.** Every result here comes from a check
|
|
4
|
+
> that *you* configured, run on *your* machine, with *your* credential. It is
|
|
5
|
+
> labelled `SELF_REPORTED`, carries `trust_bearing: false`, and is not an
|
|
6
|
+
> Intentrax attestation. It catches mistakes in your own pipeline. It does not
|
|
7
|
+
> prove anything to a third party.
|
|
8
|
+
|
|
9
|
+
The most common agent failure is not a wrong decision. It is a false report
|
|
10
|
+
of success: the agent says "refund processed", "email sent" or "issue closed",
|
|
11
|
+
and it did not happen. Read-back catches that before the success message goes
|
|
12
|
+
anywhere. It reads the system of record with a read-only check, compares the
|
|
13
|
+
fields that matter, and leads with the catch:
|
|
14
|
+
|
|
15
|
+
```text
|
|
16
|
+
CAUGHT refund rf_2291: agent reported "processed", provider shows "failed"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
It runs locally, needs no Intentrax account, and makes no network call except
|
|
20
|
+
the read you configure.
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
import { confirmThenReport, stripeRefund } from "@intentrax/sdk/readback"; // @intentrax/sdk 1.8.0 and later
|
|
26
|
+
|
|
27
|
+
const result = await confirmThenReport({
|
|
28
|
+
claimed: { status: agentResult.status }, // what the agent says happened
|
|
29
|
+
expected: { status: "succeeded" }, // what the system must show
|
|
30
|
+
check: stripeRefund({ apiKey: process.env.STRIPE_REFUNDS_READ_KEY, refundId: "re_123" }),
|
|
31
|
+
retries: 3, // extra reads while the state is not final (default 2)
|
|
32
|
+
intervalMs: 2000, // wait between reads (default 1000)
|
|
33
|
+
timeoutMs: 10000, // limit per read (default 10000)
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
console.log(result.firstLine);
|
|
37
|
+
if (result.status !== "CONFIRMED") {
|
|
38
|
+
// Do NOT tell the user it worked. Escalate, retry the action, or say so.
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`confirmThenReport` returns `{ status, firstLine, detail }`:
|
|
43
|
+
|
|
44
|
+
| `status` | Meaning | `firstLine` begins |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `CONFIRMED` | The read matches every expected field. | `CONFIRMED` |
|
|
47
|
+
| `CONTRADICTED` | The read shows a different, final value. | `CAUGHT` |
|
|
48
|
+
| `PENDING` | Still in a not-final state (for example `pending`) after all retries. | `PENDING` |
|
|
49
|
+
| `UNKNOWN` | The check threw, timed out, returned a non-object, or a field is missing. | `UNKNOWN` |
|
|
50
|
+
|
|
51
|
+
Only `CONFIRMED` is ever worded as success. The other lines end with
|
|
52
|
+
"not confirmed" or are a `CAUGHT` line.
|
|
53
|
+
|
|
54
|
+
**`expected`** takes one of two forms:
|
|
55
|
+
|
|
56
|
+
- an **array of field names**, such as `["status", "amount"]`. Each named
|
|
57
|
+
field must equal the agent's `claimed` value. Use this form when the agent
|
|
58
|
+
and the system use the same vocabulary.
|
|
59
|
+
- an **object of required values**, such as `{ status: "succeeded" }`. Use
|
|
60
|
+
this form when the vocabularies differ. Here the agent says "processed" and
|
|
61
|
+
Stripe says "succeeded". `claimed` is optional and only appears in the
|
|
62
|
+
message.
|
|
63
|
+
|
|
64
|
+
**Missing is not null.** A field that the read did not return makes the
|
|
65
|
+
result `UNKNOWN`. It is never treated as `null`. A `null` that the system did
|
|
66
|
+
return is a value and is compared like any other value. This is the same rule
|
|
67
|
+
as `intentrax sandbox --check`. No type coercion is applied: `500` does not
|
|
68
|
+
equal `"500"`.
|
|
69
|
+
|
|
70
|
+
**Eventual consistency.** `pending` maps each field to the values that mean
|
|
71
|
+
"not final yet", for example `{ status: ["pending", "requires_action"] }`.
|
|
72
|
+
While the read shows one of those values, read-back reads again, up to
|
|
73
|
+
`retries` more times. It ends with `PENDING` if the value never settles.
|
|
74
|
+
Recipes supply sensible defaults. By default a final mismatch is reported at
|
|
75
|
+
once. Pass `retryOnMismatch: true` to re-read a mismatch as well, for systems
|
|
76
|
+
that lag without an explicit pending state.
|
|
77
|
+
|
|
78
|
+
**`detail`** holds:
|
|
79
|
+
|
|
80
|
+
- `provenance: "SELF_REPORTED"`, `trust_bearing: false` and a `note`;
|
|
81
|
+
- the `resource` and `source` labels;
|
|
82
|
+
- the `isolation` used;
|
|
83
|
+
- for each compared field: `expected`, `claimed` and `observed` (or
|
|
84
|
+
`observed_missing`), plus `matches`;
|
|
85
|
+
- every attempt, with its outcome, elapsed time and reason.
|
|
86
|
+
|
|
87
|
+
Fields that were not compared are not copied into `detail`.
|
|
88
|
+
|
|
89
|
+
Other options:
|
|
90
|
+
|
|
91
|
+
- `resource` and `source` label the message, for example `"refund re_123"`
|
|
92
|
+
and `"Stripe"`. Recipes set both.
|
|
93
|
+
- `actor` names who made the claim (default `"agent"`).
|
|
94
|
+
- `secrets` lists extra strings to redact.
|
|
95
|
+
- `isolation` sets where the check runs (see below).
|
|
96
|
+
|
|
97
|
+
Caller mistakes throw a `TypeError` before any read. Examples are an empty
|
|
98
|
+
`expected` or a field missing from `claimed`.
|
|
99
|
+
|
|
100
|
+
### Isolation
|
|
101
|
+
|
|
102
|
+
The approach is the same as the sandbox's `--check`. A check runs in a worker
|
|
103
|
+
thread. That worker is terminated when the check answers or when `timeoutMs`
|
|
104
|
+
passes, so a hung socket or timer cannot keep your process alive.
|
|
105
|
+
|
|
106
|
+
| Check | Where it runs |
|
|
107
|
+
| --- | --- |
|
|
108
|
+
| A recipe built from plain data (credential string, ids, base URL) | worker thread, automatically |
|
|
109
|
+
| `{ module: "./my-check.mjs", probe?: {...} }` | worker thread, using the sandbox's own runner. The module's default export is called with the probe (default `{ resource, fields }`) |
|
|
110
|
+
| Any other function (a closure over your client, a recipe given `fetch` / `stripe` / `octokit` / `query`) | **in-process**, bounded by the same timeout and given an `AbortSignal` |
|
|
111
|
+
|
|
112
|
+
A function cannot be moved to another thread, so the last row cannot be
|
|
113
|
+
isolated. `detail.isolation` says which mode was used. If you pass
|
|
114
|
+
`isolation: "worker"`, a check that cannot move to a worker throws instead
|
|
115
|
+
of silently running in-process.
|
|
116
|
+
|
|
117
|
+
### Credentials
|
|
118
|
+
|
|
119
|
+
- Use the narrowest read-only credential you can. Each recipe below lists
|
|
120
|
+
the minimum scope it needs.
|
|
121
|
+
- Keep that credential away from the agent whose claims you are checking. A
|
|
122
|
+
check the agent can edit is not a check.
|
|
123
|
+
- Recipes never log. Their error messages are built from status codes,
|
|
124
|
+
never from headers.
|
|
125
|
+
- Every string in `firstLine` and `detail` is redacted twice:
|
|
126
|
+
- first, every exact secret the recipe declared or you passed in `secrets`
|
|
127
|
+
is removed;
|
|
128
|
+
- then common credential shapes are removed: `Bearer …`, `sk_`/`rk_` keys,
|
|
129
|
+
`ghp_`/`github_pat_` tokens, `SG.` keys, URL userinfo, and `token=`-style
|
|
130
|
+
query parameters.
|
|
131
|
+
- URLs in messages show the origin and path only.
|
|
132
|
+
|
|
133
|
+
## Recipes
|
|
134
|
+
|
|
135
|
+
Each recipe is a factory. It takes a read-only credential, or a client you
|
|
136
|
+
already built, and returns a `check`. Recipes **never write**:
|
|
137
|
+
|
|
138
|
+
- HTTP recipes send `GET` with no body and refuse redirects, so a credential
|
|
139
|
+
is never replayed to another URL.
|
|
140
|
+
- Client recipes call only one read method.
|
|
141
|
+
|
|
142
|
+
A field the system did not return is left out of the result, never set to
|
|
143
|
+
`null`.
|
|
144
|
+
|
|
145
|
+
### `httpJson`: any JSON GET endpoint
|
|
146
|
+
|
|
147
|
+
**Minimum scope:** whatever read-only credential the API offers for that
|
|
148
|
+
resource, or none for a public endpoint.
|
|
149
|
+
|
|
150
|
+
```js
|
|
151
|
+
const check = httpJson({
|
|
152
|
+
url: "https://api.example.com/v1/tickets/T-1",
|
|
153
|
+
token: process.env.TICKETS_READ_TOKEN, // Authorization: Bearer …
|
|
154
|
+
select: { status: "data.status", owner: "data.assignee.login" }, // dot paths; a[0].b works
|
|
155
|
+
notFoundAs: { exists: false }, // optional: what a 404 means
|
|
156
|
+
});
|
|
157
|
+
await confirmThenReport({ claimed: { status: "closed" }, expected: ["status"], check });
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### `stripeRefund`: refund status by id
|
|
161
|
+
|
|
162
|
+
**Minimum scope:** a restricted key (`rk_…`) with **Refunds: Read** only.
|
|
163
|
+
|
|
164
|
+
A full `sk_live_` key can move money, so the recipe refuses one unless you
|
|
165
|
+
pass `allowFullSecretKey: true`.
|
|
166
|
+
|
|
167
|
+
```js
|
|
168
|
+
const check = stripeRefund({ apiKey: process.env.STRIPE_REFUNDS_READ_KEY, refundId: "re_123" });
|
|
169
|
+
// or with your client (only stripe.refunds.retrieve is called):
|
|
170
|
+
const check = stripeRefund({ stripe, refundId: "re_123" });
|
|
171
|
+
await confirmThenReport({ claimed: { status: "processed" }, expected: { status: "succeeded" }, check });
|
|
172
|
+
// -> CAUGHT refund re_123: agent reported "processed", Stripe shows "failed"
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
- **Reads:** `GET /v1/refunds/{id}`.
|
|
176
|
+
- **Returns:** `id`, `status`, `amount`, `currency` and `failure_reason`.
|
|
177
|
+
- **Default pending values:** `status` ∈ {`pending`, `requires_action`}.
|
|
178
|
+
Stripe's final refund statuses are `succeeded`, `failed` and `canceled`.
|
|
179
|
+
|
|
180
|
+
### `emailDelivery`: provider message status (Postmark, SendGrid, or your own adapter)
|
|
181
|
+
|
|
182
|
+
The recipe normalizes each provider's answer to
|
|
183
|
+
`{ message_id, provider_status, delivery }`. `delivery` is one of
|
|
184
|
+
`delivered`, `bounced`, `not_delivered` or `in_flight`. `in_flight` is the
|
|
185
|
+
default pending value. If the delivery state cannot be derived, `delivery` is
|
|
186
|
+
left out, and the result is `UNKNOWN`.
|
|
187
|
+
|
|
188
|
+
```js
|
|
189
|
+
const check = emailDelivery({ provider: "postmark", token: process.env.POSTMARK_SERVER_TOKEN, messageId });
|
|
190
|
+
const check = emailDelivery({ provider: "sendgrid", token: process.env.SENDGRID_ACTIVITY_KEY, messageId });
|
|
191
|
+
await confirmThenReport({ claimed: { delivery: "delivered" }, expected: ["delivery"], check, retries: 5, intervalMs: 5000 });
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
The field names were checked against the providers' public API reference
|
|
195
|
+
pages on 2026-11-19.
|
|
196
|
+
|
|
197
|
+
**Postmark** ([Messages API, "Outbound message details"](https://postmarkapp.com/developer/api/messages-api)):
|
|
198
|
+
|
|
199
|
+
- **Endpoint:** `GET /messages/outbound/{messageid}/details`, with the
|
|
200
|
+
headers `Accept: application/json` and `X-Postmark-Server-Token`.
|
|
201
|
+
- **`Status`:** one of `Sent`, `Processed` or `Queued`.
|
|
202
|
+
- **`MessageEvents[].Type`:** one of `Delivered`, `Bounced`, `Transient`,
|
|
203
|
+
`Opened`, `LinkClicked` or `SubscriptionChanged`.
|
|
204
|
+
- **Mapping to `delivery`:**
|
|
205
|
+
- any `Bounced` event gives `bounced`, so a partial failure on a
|
|
206
|
+
multi-recipient message is not a delivery;
|
|
207
|
+
- otherwise a `Delivered` event gives `delivered`;
|
|
208
|
+
- otherwise the message is `in_flight`.
|
|
209
|
+
- **Minimum scope: there is no read-only Postmark server token.** This
|
|
210
|
+
endpoint requires a Server API token, and that token can also send mail.
|
|
211
|
+
The recipe only reads, but keep that token out of the agent's reach.
|
|
212
|
+
|
|
213
|
+
**SendGrid** ([Email Activity, "Filter messages by message ID"](https://www.twilio.com/docs/sendgrid/api-reference/email-activity/filter-messages-by-message-id)):
|
|
214
|
+
|
|
215
|
+
- **Endpoint:** `GET /v3/messages/{msg_id}`, with the header
|
|
216
|
+
`Authorization: Bearer`.
|
|
217
|
+
- **`status`:** one of `processed`, `delivered` or `not_delivered`.
|
|
218
|
+
- **`events[].event_name`:** includes `bounced`, `dropped`, `deferred` and
|
|
219
|
+
`delivered`.
|
|
220
|
+
- **Mapping to `delivery`:**
|
|
221
|
+
- `not_delivered` with a `bounced` event gives `bounced`;
|
|
222
|
+
- `processed` gives `in_flight`.
|
|
223
|
+
- **Minimum scope:** a restricted API key with **Email Activity** access only.
|
|
224
|
+
The docs do not name a scope string, so the recipe does not assert one.
|
|
225
|
+
- The API needs SendGrid's paid "additional email activity history" add-on.
|
|
226
|
+
- It returns no data for regional (EU) subusers.
|
|
227
|
+
- **Assumption:** SendGrid's getting-started guide also mentions a
|
|
228
|
+
`processing` status that the response schema does not list. The recipe
|
|
229
|
+
treats `processing` like `processed`.
|
|
230
|
+
|
|
231
|
+
**Your own provider:** pass
|
|
232
|
+
`adapter: { source, apiBase, path(id), headers(token), normalize(json) }`.
|
|
233
|
+
|
|
234
|
+
### `githubIssue`: issue or pull request state
|
|
235
|
+
|
|
236
|
+
**Minimum scope:** a fine-grained token limited to the one repository:
|
|
237
|
+
|
|
238
|
+
- **Issues: Read-only** for `kind: "issue"`;
|
|
239
|
+
- **Pull requests: Read-only** for `kind: "pull"`.
|
|
240
|
+
|
|
241
|
+
GitHub adds **Metadata: Read-only** itself. Public repositories need no token.
|
|
242
|
+
|
|
243
|
+
```js
|
|
244
|
+
const check = githubIssue({ owner: "acme", repo: "app", number: 42, token: process.env.GH_ISSUES_READ });
|
|
245
|
+
await confirmThenReport({ claimed: { state: "closed" }, expected: ["state"], check });
|
|
246
|
+
|
|
247
|
+
const pr = githubIssue({ owner: "acme", repo: "app", number: 7, kind: "pull", octokit }); // only rest.pulls.get
|
|
248
|
+
await confirmThenReport({ expected: { merged: true }, check: pr });
|
|
249
|
+
// -> CAUGHT pull request acme/app#7: expected true, GitHub shows false
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
- `kind: "issue"` returns `{ number, state, state_reason, is_pull_request }`.
|
|
253
|
+
- `kind: "pull"` returns `{ number, state, merged, draft }`.
|
|
254
|
+
|
|
255
|
+
### `sqlRow`: one database row through your query function
|
|
256
|
+
|
|
257
|
+
**Minimum scope:** a database role with `SELECT` on the tables the query
|
|
258
|
+
reads and nothing else. Use a read replica if you can, and set
|
|
259
|
+
`default_transaction_read_only = on` for that role.
|
|
260
|
+
|
|
261
|
+
```js
|
|
262
|
+
const check = sqlRow({
|
|
263
|
+
query: (sql, params) => readonlyPool.query(sql, params), // returns rows[] or { rows }
|
|
264
|
+
sql: "SELECT status, amount_cents FROM refunds WHERE id = $1",
|
|
265
|
+
params: ["rf_2291"],
|
|
266
|
+
resource: "refund rf_2291",
|
|
267
|
+
});
|
|
268
|
+
await confirmThenReport({ claimed: { status: "refunded" }, expected: ["status"], check });
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
The query must match exactly one row.
|
|
272
|
+
|
|
273
|
+
- **No row** gives `UNKNOWN`, unless you pass `notFoundAs`.
|
|
274
|
+
- **More than one row** is always `UNKNOWN`.
|
|
275
|
+
|
|
276
|
+
The SQL is checked lexically before it runs. It must be a single `SELECT` or
|
|
277
|
+
`WITH … SELECT` statement, with no `INSERT`/`UPDATE`/`DELETE`/`MERGE`,
|
|
278
|
+
`SELECT … INTO`, row locks or `nextval`. This check catches mistakes. **It is
|
|
279
|
+
not a security boundary.** The read-only role is what actually stops the
|
|
280
|
+
check from writing.
|
|
281
|
+
|
|
282
|
+
## Bridge to `intentrax sandbox --check`
|
|
283
|
+
|
|
284
|
+
`toSandboxCheck(check, expected)` wraps a recipe, or any read-only function,
|
|
285
|
+
in the module shape that the sandbox's `--check` loads:
|
|
286
|
+
|
|
287
|
+
```js
|
|
288
|
+
// refund-check.mjs
|
|
289
|
+
import { toSandboxCheck, stripeRefund } from "@intentrax/sdk/readback";
|
|
290
|
+
const m = toSandboxCheck(
|
|
291
|
+
stripeRefund({ apiKey: process.env.STRIPE_REFUNDS_READ_KEY, refundId: process.env.REFUND_ID }),
|
|
292
|
+
{ status: "succeeded" },
|
|
293
|
+
);
|
|
294
|
+
export const expected = m.expected;
|
|
295
|
+
export const resource = m.resource;
|
|
296
|
+
export default m.check;
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
```bash
|
|
300
|
+
intentrax sandbox --check ./refund-check.mjs # exit 12 CONFLICTING_EVIDENCE on a contradiction
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
On a contradiction, the sandbox exits 12 and also writes a **local,
|
|
304
|
+
non-trust-bearing bundle**:
|
|
305
|
+
|
|
306
|
+
- it is signed with ephemeral keys generated on your machine;
|
|
307
|
+
- its read is `SELF_REPORTED`;
|
|
308
|
+
- no production verifier, hosted verify or Verification Mark accepts it.
|
|
309
|
+
|
|
310
|
+
The wrapped check passes only the fields named in `expected`. The bundle
|
|
311
|
+
stores the raw read, so it holds no more of the provider's response than the
|
|
312
|
+
comparison needs. The bridge's `label` field says the same thing in one
|
|
313
|
+
sentence.
|
|
314
|
+
|
|
315
|
+
## Honest limits
|
|
316
|
+
|
|
317
|
+
- **You wrote the check.** Read-back shows that your configured read
|
|
318
|
+
disagrees with the agent's report. It cannot show that the read itself is
|
|
319
|
+
right, complete or unaltered. That is why it is `SELF_REPORTED` and not an
|
|
320
|
+
attestation.
|
|
321
|
+
- **A wrong check gives a wrong answer.** A check can point at the wrong
|
|
322
|
+
account or use a stale replica. It can also compare a field that does not
|
|
323
|
+
mean what you think it means. Coverage is only the fields you named.
|
|
324
|
+
- **Read-only is a convention, enforced as far as a library can enforce it.**
|
|
325
|
+
The recipes only issue reads. Your own function or `query` can do anything,
|
|
326
|
+
and an in-process check cannot be sandboxed. Least-privilege credentials
|
|
327
|
+
are the real control.
|
|
328
|
+
- **Point-in-time.** `CONFIRMED` means the state matched when it was read. It
|
|
329
|
+
does not mean the state will stay that way.
|
|
330
|
+
- **Provider semantics vary.** "Delivered" means the receiving server
|
|
331
|
+
accepted the mail, not that a person read it. A Stripe refund can still
|
|
332
|
+
fail after it shows `succeeded`.
|
|
333
|
+
|
|
334
|
+
## Status
|
|
335
|
+
|
|
336
|
+
Preview, shipped in `@intentrax/sdk` 1.8.0 as the `@intentrax/sdk/readback`
|
|
337
|
+
subpath export (not re-exported from the package root) and as a CLI command:
|
|
338
|
+
|
|
339
|
+
```bash
|
|
340
|
+
npx @intentrax/sdk readback --check ./read-refund.mjs --expected '{"status":"succeeded"}' --claimed '{"status":"processed"}'
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
The `--check` module's default export runs in a worker thread with
|
|
344
|
+
`{ resource, fields }` and returns the object it read. Exit codes, aligned with
|
|
345
|
+
the sandbox: `0` CONFIRMED, `12` CONTRADICTED (the line starts with `CAUGHT`),
|
|
346
|
+
`10` PENDING, `11` UNKNOWN, `64` usage. `--json` prints the full result.
|
|
347
|
+
`npx @intentrax/sdk readback --help` lists every option. To run the tests from
|
|
348
|
+
a checkout:
|
|
349
|
+
|
|
350
|
+
```bash
|
|
351
|
+
node --test "sdk/typescript/readback/test/*.test.mjs"
|
|
352
|
+
```
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// toSandboxCheck: turn a read-back check (a recipe or your own function)
|
|
2
|
+
// into the module shape `intentrax sandbox --check` loads.
|
|
3
|
+
//
|
|
4
|
+
// // my-refund-check.mjs
|
|
5
|
+
// import { toSandboxCheck, stripeRefund } from "<sdk>/readback/index.mjs";
|
|
6
|
+
// const m = toSandboxCheck(
|
|
7
|
+
// stripeRefund({ apiKey: process.env.STRIPE_REFUNDS_READ_KEY, refundId: process.env.REFUND_ID }),
|
|
8
|
+
// { status: "succeeded" },
|
|
9
|
+
// );
|
|
10
|
+
// export const expected = m.expected;
|
|
11
|
+
// export const resource = m.resource;
|
|
12
|
+
// export default m.check;
|
|
13
|
+
//
|
|
14
|
+
// $ intentrax sandbox --check ./my-refund-check.mjs
|
|
15
|
+
//
|
|
16
|
+
// The sandbox then runs the check in its worker, compares the read with
|
|
17
|
+
// `expected`, and on a contradiction exits 12 (CONFLICTING_EVIDENCE) and
|
|
18
|
+
// writes a LOCAL bundle. That bundle is NON-TRUST-BEARING: it is signed with
|
|
19
|
+
// ephemeral keys generated on your machine, the read is SELF_REPORTED (you
|
|
20
|
+
// wrote or configured the check), and no production verifier accepts it.
|
|
21
|
+
//
|
|
22
|
+
// The wrapped check returns only the fields named in `expected` (fields the
|
|
23
|
+
// read lacks are left out, never null), so the bundle — which stores the raw
|
|
24
|
+
// read — holds no more of the provider's response than the comparison needs.
|
|
25
|
+
|
|
26
|
+
import { isCanonicalizable } from "../sandbox/canonical.mjs";
|
|
27
|
+
|
|
28
|
+
export const SANDBOX_BRIDGE_LABEL =
|
|
29
|
+
"LOCAL, NON-TRUST-BEARING: a sandbox bundle from this check is signed with ephemeral local keys and its read is " +
|
|
30
|
+
"SELF_REPORTED (you configured the check). It is not an Intentrax attestation and no production verifier accepts it.";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {Function} recipeCheck a read-back recipe check, or any async read-only function
|
|
34
|
+
* @param {object} expected { field: value } the action should have produced (JSON, integers only)
|
|
35
|
+
* @param {{ resource?: string }} [opts]
|
|
36
|
+
* @returns {{ expected: object, resource: string, check: Function, label: string, trust_bearing: false, provenance: "SELF_REPORTED" }}
|
|
37
|
+
*/
|
|
38
|
+
export function toSandboxCheck(recipeCheck, expected, opts = {}) {
|
|
39
|
+
if (typeof recipeCheck !== "function") throw new TypeError("recipeCheck must be a function");
|
|
40
|
+
if (expected === null || typeof expected !== "object" || Array.isArray(expected) || Object.keys(expected).length === 0
|
|
41
|
+
|| !isCanonicalizable(expected)) {
|
|
42
|
+
throw new TypeError("expected must be a non-empty plain object of JSON values (integers only), as sandbox --check requires");
|
|
43
|
+
}
|
|
44
|
+
const resource = opts.resource !== undefined ? opts.resource : typeof recipeCheck.resource === "string" ? recipeCheck.resource : "readback";
|
|
45
|
+
if (typeof resource !== "string" || resource.length === 0 || resource.length > 200 || resource.endsWith("*")) {
|
|
46
|
+
throw new TypeError("resource must be a non-empty string (max 200 chars, no trailing *)");
|
|
47
|
+
}
|
|
48
|
+
const fields = Object.keys(expected);
|
|
49
|
+
const frozenExpected = JSON.parse(JSON.stringify(expected));
|
|
50
|
+
|
|
51
|
+
async function check(probe) {
|
|
52
|
+
const observed = await recipeCheck({ ...(probe && typeof probe === "object" ? probe : {}) });
|
|
53
|
+
// Not an object: hand it through, so the sandbox reports it as unusable
|
|
54
|
+
// (INSUFFICIENT_EVIDENCE) instead of this bridge inventing fields.
|
|
55
|
+
if (observed === null || typeof observed !== "object" || Array.isArray(observed)) return observed;
|
|
56
|
+
const out = {};
|
|
57
|
+
for (const f of fields) {
|
|
58
|
+
if (Object.prototype.hasOwnProperty.call(observed, f) && observed[f] !== undefined) out[f] = observed[f];
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return Object.freeze({
|
|
64
|
+
expected: frozenExpected,
|
|
65
|
+
resource,
|
|
66
|
+
check,
|
|
67
|
+
label: SANDBOX_BRIDGE_LABEL,
|
|
68
|
+
trust_bearing: false,
|
|
69
|
+
provenance: "SELF_REPORTED",
|
|
70
|
+
});
|
|
71
|
+
}
|
package/readback/cli.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// `intentrax readback`: read the outcome back before reporting success, from
|
|
2
|
+
// the command line. A thin front end for confirmThenReport with a { module }
|
|
3
|
+
// check, which always runs in a worker thread (same runner as
|
|
4
|
+
// `intentrax sandbox --check`).
|
|
5
|
+
//
|
|
6
|
+
// Exit codes (aligned with the sandbox): 0 CONFIRMED, 10 PENDING,
|
|
7
|
+
// 11 UNKNOWN, 12 CONTRADICTED (CAUGHT), 64 usage.
|
|
8
|
+
//
|
|
9
|
+
// Every result is SELF_REPORTED: the check is code you configured. It is not
|
|
10
|
+
// an Intentrax attestation.
|
|
11
|
+
|
|
12
|
+
import { isAbsolute, resolve } from "node:path";
|
|
13
|
+
import { pathToFileURL } from "node:url";
|
|
14
|
+
import { confirmThenReport, STATUS } from "./confirm.mjs";
|
|
15
|
+
|
|
16
|
+
export const EXIT_CODES = Object.freeze({
|
|
17
|
+
[STATUS.CONFIRMED]: 0,
|
|
18
|
+
[STATUS.PENDING]: 10,
|
|
19
|
+
[STATUS.UNKNOWN]: 11,
|
|
20
|
+
[STATUS.CONTRADICTED]: 12,
|
|
21
|
+
});
|
|
22
|
+
export const USAGE_EXIT_CODE = 64;
|
|
23
|
+
|
|
24
|
+
class UsageError extends Error {}
|
|
25
|
+
|
|
26
|
+
const VALUE_FLAGS = new Map([
|
|
27
|
+
["--check", "check"],
|
|
28
|
+
["--expected", "expected"],
|
|
29
|
+
["--claimed", "claimed"],
|
|
30
|
+
["--pending", "pending"],
|
|
31
|
+
["--retries", "retries"],
|
|
32
|
+
["--interval-ms", "intervalMs"],
|
|
33
|
+
["--timeout-ms", "timeoutMs"],
|
|
34
|
+
["--resource", "resource"],
|
|
35
|
+
["--source", "source"],
|
|
36
|
+
["--actor", "actor"],
|
|
37
|
+
]);
|
|
38
|
+
const BOOL_FLAGS = new Map([
|
|
39
|
+
["--retry-on-mismatch", "retryOnMismatch"],
|
|
40
|
+
["--json", "json"],
|
|
41
|
+
["--help", "help"],
|
|
42
|
+
["-h", "help"],
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
export function usage(invokedAs = "intentrax readback") {
|
|
46
|
+
return `Usage:
|
|
47
|
+
${invokedAs} --check <read-only-check.mjs> --expected <json> [--claimed <json>]
|
|
48
|
+
[--pending <json>] [--retries N] [--interval-ms N] [--timeout-ms N]
|
|
49
|
+
[--retry-on-mismatch] [--resource <label>] [--source <label>] [--actor <who>] [--json]
|
|
50
|
+
|
|
51
|
+
Reads the system of record with your read-only check and compares the fields
|
|
52
|
+
that matter, before anyone reports success. The check module's default export
|
|
53
|
+
is called (in a worker thread) with { resource, fields } and returns an object.
|
|
54
|
+
|
|
55
|
+
--expected '["status"]' compare these fields with --claimed
|
|
56
|
+
--expected '{"status":"succeeded"}' require these values
|
|
57
|
+
--claimed '{"status":"processed"}' what the agent reported
|
|
58
|
+
--pending '{"status":["pending"]}' values that mean "not final yet" (re-read)
|
|
59
|
+
|
|
60
|
+
Exit codes:
|
|
61
|
+
0 CONFIRMED the read matches
|
|
62
|
+
12 CONTRADICTED the read differs (first line starts with CAUGHT)
|
|
63
|
+
10 PENDING still not final after the retries
|
|
64
|
+
11 UNKNOWN the check failed, timed out, or a field is missing
|
|
65
|
+
64 usage
|
|
66
|
+
|
|
67
|
+
Self-reported: the check is code you configured. Not an Intentrax attestation.`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function parseJson(flag, text) {
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(text);
|
|
73
|
+
} catch {
|
|
74
|
+
throw new UsageError(`${flag} must be valid JSON`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function parseInt10(flag, text) {
|
|
79
|
+
if (!/^\d+$/.test(text)) throw new UsageError(`${flag} must be a non-negative integer`);
|
|
80
|
+
return Number(text);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function parseReadbackArgs(argv, cwd = process.cwd()) {
|
|
84
|
+
const raw = {};
|
|
85
|
+
for (let i = 0; i < argv.length; i++) {
|
|
86
|
+
const arg = argv[i];
|
|
87
|
+
const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
|
|
88
|
+
const flag = eq > 0 ? arg.slice(0, eq) : arg;
|
|
89
|
+
const inline = eq > 0 ? arg.slice(eq + 1) : undefined;
|
|
90
|
+
if (BOOL_FLAGS.has(flag)) {
|
|
91
|
+
if (inline !== undefined) throw new UsageError(`${flag} takes no value`);
|
|
92
|
+
raw[BOOL_FLAGS.get(flag)] = true;
|
|
93
|
+
} else if (VALUE_FLAGS.has(flag)) {
|
|
94
|
+
const key = VALUE_FLAGS.get(flag);
|
|
95
|
+
if (Object.hasOwn(raw, key)) throw new UsageError(`${flag} given twice`);
|
|
96
|
+
let value = inline;
|
|
97
|
+
if (value === undefined) {
|
|
98
|
+
value = argv[i + 1];
|
|
99
|
+
if (value === undefined) throw new UsageError(`${flag} requires a value`);
|
|
100
|
+
i += 1;
|
|
101
|
+
}
|
|
102
|
+
raw[key] = value;
|
|
103
|
+
} else {
|
|
104
|
+
throw new UsageError(arg.startsWith("-") ? `unknown option ${arg}` : `unexpected argument ${JSON.stringify(arg)}`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (raw.help) return { help: true };
|
|
108
|
+
if (raw.check === undefined) throw new UsageError("--check <read-only-check.mjs> is required");
|
|
109
|
+
if (raw.expected === undefined) throw new UsageError("--expected is required");
|
|
110
|
+
const modulePath = /^file:/i.test(raw.check) ? raw.check : pathToFileURL(isAbsolute(raw.check) ? raw.check : resolve(cwd, raw.check)).href;
|
|
111
|
+
const input = { check: { module: modulePath }, expected: parseJson("--expected", raw.expected) };
|
|
112
|
+
if (raw.claimed !== undefined) input.claimed = parseJson("--claimed", raw.claimed);
|
|
113
|
+
if (raw.pending !== undefined) input.pending = parseJson("--pending", raw.pending);
|
|
114
|
+
for (const key of ["retries", "intervalMs", "timeoutMs"]) {
|
|
115
|
+
if (raw[key] !== undefined) input[key] = parseInt10("--" + key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()), raw[key]);
|
|
116
|
+
}
|
|
117
|
+
for (const key of ["resource", "source", "actor"]) if (raw[key] !== undefined) input[key] = raw[key];
|
|
118
|
+
if (raw.retryOnMismatch) input.retryOnMismatch = true;
|
|
119
|
+
return { input, json: Boolean(raw.json) };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Run `intentrax readback ...`. Resolves to the exit code. io: { out, err, cwd, invokedAs }. */
|
|
123
|
+
export async function readbackMain(argv = [], io = {}) {
|
|
124
|
+
const out = io.out ?? ((text) => process.stdout.write(text));
|
|
125
|
+
const err = io.err ?? ((text) => process.stderr.write(text));
|
|
126
|
+
const invokedAs = io.invokedAs ?? "intentrax readback";
|
|
127
|
+
let parsed;
|
|
128
|
+
try {
|
|
129
|
+
parsed = parseReadbackArgs(argv, io.cwd ?? process.cwd());
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (!(error instanceof UsageError)) throw error;
|
|
132
|
+
err(`intentrax readback: ${error.message}\n\n${usage(invokedAs)}\n`);
|
|
133
|
+
return USAGE_EXIT_CODE;
|
|
134
|
+
}
|
|
135
|
+
if (parsed.help) {
|
|
136
|
+
out(usage(invokedAs) + "\n");
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
let result;
|
|
140
|
+
try {
|
|
141
|
+
result = await confirmThenReport(parsed.input);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
// confirmThenReport throws TypeError for caller mistakes, before any read.
|
|
144
|
+
if (!(error instanceof TypeError)) throw error;
|
|
145
|
+
err(`intentrax readback: ${error.message}\n\n${usage(invokedAs)}\n`);
|
|
146
|
+
return USAGE_EXIT_CODE;
|
|
147
|
+
}
|
|
148
|
+
out((parsed.json ? JSON.stringify(result, null, 2) : result.firstLine + "\n" + result.detail.note) + "\n");
|
|
149
|
+
return EXIT_CODES[result.status] ?? EXIT_CODES[STATUS.UNKNOWN];
|
|
150
|
+
}
|