@oked/sdk 0.4.0 → 0.6.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 +11 -3
- package/dist/config.d.ts +5 -0
- package/dist/config.js +5 -0
- package/dist/describe.d.ts +7 -2
- package/dist/describe.js +142 -9
- package/dist/errors.d.ts +15 -2
- package/dist/errors.js +19 -2
- package/dist/index.d.ts +10 -3
- package/dist/index.js +83 -7
- package/dist/receipt-keys.d.ts +12 -0
- package/dist/receipt-keys.js +19 -0
- package/dist/receipt.d.ts +38 -0
- package/dist/receipt.js +106 -0
- package/dist/types.d.ts +31 -2
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -44,8 +44,13 @@ Pass to `new OKedClient(config)`:
|
|
|
44
44
|
|---|---|---|---|
|
|
45
45
|
| `apiKey` | `string` | `OKED_API_KEY` env | Your OKed API key. Required. |
|
|
46
46
|
| `backendUrl` | `string` | `https://api.oked.ai` | Override the OKed backend URL. |
|
|
47
|
-
| `timeout` | `number` | `
|
|
47
|
+
| `timeout` | `number` | `630000` | Per-approval timeout in ms (10.5 minutes, just above the backend's 10 minute expiry, so the backend's `timeout` answer arrives first). If you raise it, raise the harness hook timeout to match: it must stay above this value so the fail-safe deny is written before the hook process is killed. |
|
|
48
48
|
| `strictFailClosed` | `boolean` | `false` | When true, backend outages deny every tier. When false, outages deny only `high_stakes` and allow lower tiers. |
|
|
49
|
+
| `requireReceipt` | `boolean` | `true` | Deny an approval that arrives without a signed receipt. A receipt that is present but invalid always denies. Set `false` (env `OKED_REQUIRE_RECEIPT=0`) only for a backend that does not sign receipts. |
|
|
50
|
+
| `receiptKeysUrl` | `string` | `https://api.oked.ai/.well-known/oked-receipt-keys.json` | Where to fetch a receipt key the SDK has not seen. Independent of `backendUrl`; https only, except loopback. |
|
|
51
|
+
| `receiptKeys` | `ReceiptKey[]` | | Verify with exactly these keys and never fetch (self-hosted backends, tests). |
|
|
52
|
+
| `client` | `string` | | Your integration's name and version, e.g. `my-agent@1.2.0`. Recorded in receipts. |
|
|
53
|
+
| `source` | `string` | `"sdk"` | Where requests come from. Part of each receipt's subject. |
|
|
49
54
|
|
|
50
55
|
## API
|
|
51
56
|
|
|
@@ -69,8 +74,9 @@ Response fields:
|
|
|
69
74
|
| Field | Type | Description |
|
|
70
75
|
|---|---|---|
|
|
71
76
|
| `approved` | `boolean` | `true` only when the user approved. |
|
|
72
|
-
| `approval_id` | `string` | Opaque id for logs / audit. |
|
|
77
|
+
| `approval_id` | `string \| null` | Opaque id for logs / audit. |
|
|
73
78
|
| `decision` | `"approved" \| "denied" \| "timeout"` | Exact outcome. |
|
|
79
|
+
| `receipt` | `SignedReceipt` | The signed receipt for this decision, already verified: OKed's signature, this request, this decision, and the exact action you sent. See [docs/receipts.md](../../docs/receipts.md). |
|
|
74
80
|
|
|
75
81
|
### `ping()`
|
|
76
82
|
|
|
@@ -90,10 +96,12 @@ Full type definitions ship with the package (`dist/index.d.ts`).
|
|
|
90
96
|
| `OKED_API_KEY` | yes, unless passed in code | Your OKed API key. |
|
|
91
97
|
| `OKED_BACKEND_URL` | no | Override the hosted backend URL. |
|
|
92
98
|
| `OKED_STRICT_FAIL_CLOSED` | no | Set to `1` or `true` to deny every sensitive action when the backend is unreachable. |
|
|
99
|
+
| `OKED_REQUIRE_RECEIPT` | no | Set to `0` to allow an approval that has no receipt (a backend that does not sign receipts). On by default. |
|
|
100
|
+
| `OKED_RECEIPT_KEYS_URL` | no | Where to fetch receipt keys (default OKed's published set). |
|
|
93
101
|
|
|
94
102
|
## Degraded-mode behavior
|
|
95
103
|
|
|
96
|
-
Explicit user denials return `{ approved: false }` and should always be treated as final. Invalid API keys throw `OKedAuthError` and should deny. If the backend is unreachable, `OKedBackendUnreachableError` lets integrations apply degraded mode: `high_stakes` denies, while lower tiers may proceed unless `strictFailClosed` is enabled. Unexpected errors should be treated as deny.
|
|
104
|
+
Explicit user denials return `{ approved: false }` and should always be treated as final. Invalid API keys throw `OKedAuthError` and should deny. A receipt that does not verify, or an approval with no receipt, throws `OKedReceiptError` and should deny. A request the backend accepted but nobody answered in time returns `decision: "timeout"`, never an outage. If the backend is unreachable, `OKedBackendUnreachableError` lets integrations apply degraded mode: `high_stakes` denies, while lower tiers may proceed unless `strictFailClosed` is enabled. Unexpected errors should be treated as deny.
|
|
97
105
|
|
|
98
106
|
## Development
|
|
99
107
|
|
package/dist/config.d.ts
CHANGED
|
@@ -6,10 +6,15 @@ export interface PersistedConfig {
|
|
|
6
6
|
rulesCacheTtlSeconds?: number;
|
|
7
7
|
/** Min interval (seconds) between heartbeats. See OKedConfig.heartbeatIntervalMs. */
|
|
8
8
|
heartbeatIntervalSeconds?: number;
|
|
9
|
+
/** Deny an approval that arrives without a receipt (default true). See OKedConfig.requireReceipt. */
|
|
10
|
+
requireReceipt?: boolean;
|
|
11
|
+
/** Where to fetch receipt keys. See OKedConfig.receiptKeysUrl. */
|
|
12
|
+
receiptKeysUrl?: string;
|
|
9
13
|
}
|
|
10
14
|
export declare const OKED_CONFIG_PATH: string;
|
|
11
15
|
export declare const OKED_RULES_CACHE_PATH: string;
|
|
12
16
|
export declare const OKED_HEARTBEAT_PATH: string;
|
|
17
|
+
export declare const OKED_RECEIPT_KEYS_PATH: string;
|
|
13
18
|
/**
|
|
14
19
|
* Read ~/.oked/config.json if present. Returns {} on any error (missing file,
|
|
15
20
|
* malformed JSON, no home dir). Callers should treat this as a best-effort
|
package/dist/config.js
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from "path";
|
|
|
4
4
|
export const OKED_CONFIG_PATH = join(homedir(), ".oked", "config.json");
|
|
5
5
|
export const OKED_RULES_CACHE_PATH = join(homedir(), ".oked", "rules-cache.json");
|
|
6
6
|
export const OKED_HEARTBEAT_PATH = join(homedir(), ".oked", "heartbeat.json");
|
|
7
|
+
export const OKED_RECEIPT_KEYS_PATH = join(homedir(), ".oked", "receipt-keys.json");
|
|
7
8
|
/**
|
|
8
9
|
* Read ~/.oked/config.json if present. Returns {} on any error (missing file,
|
|
9
10
|
* malformed JSON, no home dir). Callers should treat this as a best-effort
|
|
@@ -28,6 +29,10 @@ export function loadOKedConfig() {
|
|
|
28
29
|
if (typeof parsed.heartbeatIntervalSeconds === "number" && parsed.heartbeatIntervalSeconds >= 0) {
|
|
29
30
|
out.heartbeatIntervalSeconds = parsed.heartbeatIntervalSeconds;
|
|
30
31
|
}
|
|
32
|
+
if (typeof parsed.requireReceipt === "boolean")
|
|
33
|
+
out.requireReceipt = parsed.requireReceipt;
|
|
34
|
+
if (typeof parsed.receiptKeysUrl === "string" && parsed.receiptKeysUrl)
|
|
35
|
+
out.receiptKeysUrl = parsed.receiptKeysUrl;
|
|
31
36
|
return out;
|
|
32
37
|
}
|
|
33
38
|
catch {
|
package/dist/describe.d.ts
CHANGED
|
@@ -17,7 +17,12 @@ export interface Rendered {
|
|
|
17
17
|
footnote?: string;
|
|
18
18
|
kind: OperationKind;
|
|
19
19
|
}
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
/** Optional caller context. `cwd` lets describers read local files (e.g. the
|
|
21
|
+
* package.json behind `npm publish`) to show what an action will touch. */
|
|
22
|
+
export interface DescribeContext {
|
|
23
|
+
cwd?: string;
|
|
24
|
+
}
|
|
25
|
+
export declare function describe(toolName: string, toolInput: Record<string, unknown>, ctx?: DescribeContext): string;
|
|
26
|
+
export declare function describeFields(toolName: string, toolInput: Record<string, unknown>, ctx?: DescribeContext): Record<string, string> | null;
|
|
22
27
|
export declare const SQL_KEYWORDS_RE: RegExp;
|
|
23
28
|
export declare function findSqlInCommand(cmd: string): string | null;
|
package/dist/describe.js
CHANGED
|
@@ -7,13 +7,15 @@
|
|
|
7
7
|
* from the `fields` payload. `describe()` returns just the title for
|
|
8
8
|
* backwards-compatible single-line consumers (audit logs, SMS).
|
|
9
9
|
*/
|
|
10
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
11
|
+
import { basename, isAbsolute, join, resolve } from "node:path";
|
|
10
12
|
import { extractShellWriteOps } from "./classify.js";
|
|
11
13
|
const BODY_PREVIEW_MAX = 200;
|
|
12
14
|
const COMMAND_INLINE_MAX = 50;
|
|
13
15
|
const DIFF_HUNK_MAX_LINES = 10;
|
|
14
|
-
export function describe(toolName, toolInput) {
|
|
16
|
+
export function describe(toolName, toolInput, ctx = {}) {
|
|
15
17
|
// Single-line consumers (audit logs, SMS) get title + target inlined.
|
|
16
|
-
const r = summarize(toolName, toolInput);
|
|
18
|
+
const r = summarize(toolName, toolInput, ctx);
|
|
17
19
|
if (r.target) {
|
|
18
20
|
// Reorder phrasing for "Delete X recursively" / "Force push branch to remote"
|
|
19
21
|
if (r.title === "Delete file recursively")
|
|
@@ -28,8 +30,8 @@ export function describe(toolName, toolInput) {
|
|
|
28
30
|
}
|
|
29
31
|
return r.title;
|
|
30
32
|
}
|
|
31
|
-
export function describeFields(toolName, toolInput) {
|
|
32
|
-
const r = summarize(toolName, toolInput);
|
|
33
|
+
export function describeFields(toolName, toolInput, ctx = {}) {
|
|
34
|
+
const r = summarize(toolName, toolInput, ctx);
|
|
33
35
|
const out = { Title: r.title, Kind: r.kind };
|
|
34
36
|
if (r.target)
|
|
35
37
|
out.Target = r.target;
|
|
@@ -46,11 +48,11 @@ export function describeFields(toolName, toolInput) {
|
|
|
46
48
|
// ───────────────────────────────────────────────────────────────────────
|
|
47
49
|
// Top-level dispatch
|
|
48
50
|
// ───────────────────────────────────────────────────────────────────────
|
|
49
|
-
function summarize(toolName, toolInput) {
|
|
51
|
+
function summarize(toolName, toolInput, ctx) {
|
|
50
52
|
const fileSizeBytes = typeof toolInput._file_size_bytes === "number" ? toolInput._file_size_bytes : undefined;
|
|
51
53
|
switch (toolName) {
|
|
52
54
|
case "Bash":
|
|
53
|
-
return summarizeBash(toolInput.command || "", fileSizeBytes);
|
|
55
|
+
return summarizeBash(toolInput.command || "", fileSizeBytes, ctx.cwd);
|
|
54
56
|
case "Write":
|
|
55
57
|
return summarizeWrite(toolInput);
|
|
56
58
|
case "Edit":
|
|
@@ -135,7 +137,7 @@ function extractCurlPayload(cmd) {
|
|
|
135
137
|
const v = m[1] ?? m[2] ?? m[3];
|
|
136
138
|
return v ? v : undefined;
|
|
137
139
|
}
|
|
138
|
-
function summarizeBash(command, sizeBytes) {
|
|
140
|
+
function summarizeBash(command, sizeBytes, cwd) {
|
|
139
141
|
const cmd = (command || "").trim();
|
|
140
142
|
if (!cmd)
|
|
141
143
|
return { title: "Run empty command", kind: "unknown_bash" };
|
|
@@ -154,6 +156,11 @@ function summarizeBash(command, sizeBytes) {
|
|
|
154
156
|
const mutatingCurl = summarizeMutatingCurl(cmd);
|
|
155
157
|
if (mutatingCurl)
|
|
156
158
|
return mutatingCurl;
|
|
159
|
+
// npm publish is irreversible (a version can never be re-published), so it
|
|
160
|
+
// headlines even inside a compound `cd pkg && npm run build && npm publish`.
|
|
161
|
+
const npmPublish = summarizeNpmPublish(cmd, cwd);
|
|
162
|
+
if (npmPublish)
|
|
163
|
+
return npmPublish;
|
|
157
164
|
const shellWrite = summarizeShellWrite(cmd);
|
|
158
165
|
if (shellWrite)
|
|
159
166
|
return shellWrite;
|
|
@@ -290,8 +297,6 @@ function summarizeBash(command, sizeBytes) {
|
|
|
290
297
|
return { title: "Install npm dependencies", kind: "npm_install" };
|
|
291
298
|
if (/\bnpm\s+test\b/.test(cmd))
|
|
292
299
|
return { title: "Run npm tests", kind: "npm_test" };
|
|
293
|
-
if (/\bnpm\s+publish\b/.test(cmd))
|
|
294
|
-
return { title: "Publish package to npm", kind: "npm_publish" };
|
|
295
300
|
if (/\bnpm\s+unpublish\b/.test(cmd))
|
|
296
301
|
return { title: "Unpublish package from npm", kind: "npm_unpublish" };
|
|
297
302
|
if (/\bnpx\s+.*\s+deploy\b/.test(cmd))
|
|
@@ -311,6 +316,134 @@ function summarizeBash(command, sizeBytes) {
|
|
|
311
316
|
return { title: "Run command", body: truncateBody(cmd), kind: "unknown_bash" };
|
|
312
317
|
return { title: cmd, kind: "unknown_bash" };
|
|
313
318
|
}
|
|
319
|
+
/**
|
|
320
|
+
* `npm publish` → which package and version, dist-tag, access, registry.
|
|
321
|
+
* Name/version come from the package.json the publish will read: the cwd,
|
|
322
|
+
* adjusted by a preceding `cd`, a `--workspace`, or a folder argument.
|
|
323
|
+
*/
|
|
324
|
+
function summarizeNpmPublish(cmd, cwd) {
|
|
325
|
+
const m = cmd.match(/(?:^|[\n;&|(]|\$\()\s*(?:\w+=\S+\s+)*(?:sudo\s+)?npm\s+publish\b([^\n;&|)]*)/);
|
|
326
|
+
if (!m)
|
|
327
|
+
return null;
|
|
328
|
+
const tokens = m[1].trim().split(/\s+/).filter(Boolean).map(stripQuotes);
|
|
329
|
+
const flags = {};
|
|
330
|
+
const workspaces = [];
|
|
331
|
+
let positional;
|
|
332
|
+
const VALUE_FLAGS = new Set(["--tag", "--access", "--registry", "--otp", "--workspace", "-w"]);
|
|
333
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
334
|
+
const t = tokens[i];
|
|
335
|
+
if (t.startsWith("-")) {
|
|
336
|
+
const eq = t.indexOf("=");
|
|
337
|
+
const name = eq > 0 ? t.slice(0, eq) : t;
|
|
338
|
+
let value = eq > 0 ? t.slice(eq + 1) : true;
|
|
339
|
+
if (value === true && VALUE_FLAGS.has(name) && i + 1 < tokens.length)
|
|
340
|
+
value = tokens[++i];
|
|
341
|
+
if ((name === "--workspace" || name === "-w") && typeof value === "string")
|
|
342
|
+
workspaces.push(value);
|
|
343
|
+
else
|
|
344
|
+
flags[name] = value;
|
|
345
|
+
}
|
|
346
|
+
else if (positional === undefined) {
|
|
347
|
+
positional = t;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
// Directory the publish runs in: cwd, then the last `cd X` before it.
|
|
351
|
+
let baseDir = cwd;
|
|
352
|
+
const before = cmd.slice(0, m.index ?? 0);
|
|
353
|
+
const cds = [...before.matchAll(/(?:^|[\n;&|(])\s*cd\s+("[^"]+"|'[^']+'|\S+)/g)];
|
|
354
|
+
if (cds.length) {
|
|
355
|
+
const dir = stripQuotes(cds[cds.length - 1][1]);
|
|
356
|
+
baseDir = isAbsolute(dir) ? dir : baseDir ? resolve(baseDir, dir) : undefined;
|
|
357
|
+
}
|
|
358
|
+
const allWorkspaces = flags["--workspaces"] === true || flags["-ws"] === true;
|
|
359
|
+
let pkgDirs = [];
|
|
360
|
+
let tarball;
|
|
361
|
+
if (positional && /\.(tgz|tar\.gz)$/.test(positional))
|
|
362
|
+
tarball = positional;
|
|
363
|
+
else if (allWorkspaces)
|
|
364
|
+
pkgDirs = baseDir ? listWorkspaceDirs(baseDir) : [];
|
|
365
|
+
else if (workspaces.length)
|
|
366
|
+
pkgDirs = workspaces.map((w) => (baseDir ? resolve(baseDir, w) : w));
|
|
367
|
+
else if (positional)
|
|
368
|
+
pkgDirs = [baseDir ? resolve(baseDir, positional) : positional];
|
|
369
|
+
else if (baseDir)
|
|
370
|
+
pkgDirs = [baseDir];
|
|
371
|
+
const labels = pkgDirs.map((d) => readPackageLabel(d) ?? shortenPath(d));
|
|
372
|
+
const isPrivate = pkgDirs.some((d) => readPackageJson(d)?.private === true);
|
|
373
|
+
let target;
|
|
374
|
+
if (tarball)
|
|
375
|
+
target = basename(tarball);
|
|
376
|
+
else if (labels.length)
|
|
377
|
+
target = labels.join("\n");
|
|
378
|
+
else if (allWorkspaces)
|
|
379
|
+
target = "all workspaces";
|
|
380
|
+
else if (workspaces.length)
|
|
381
|
+
target = workspaces.join("\n");
|
|
382
|
+
const details = [];
|
|
383
|
+
details.push(`tag ${typeof flags["--tag"] === "string" ? flags["--tag"] : "latest"}`);
|
|
384
|
+
if (typeof flags["--access"] === "string")
|
|
385
|
+
details.push(`${flags["--access"]} access`);
|
|
386
|
+
if (typeof flags["--registry"] === "string")
|
|
387
|
+
details.push(`registry ${extractHost(flags["--registry"])}`);
|
|
388
|
+
if (flags["--provenance"] === true)
|
|
389
|
+
details.push("with provenance");
|
|
390
|
+
const dryRun = flags["--dry-run"] === true;
|
|
391
|
+
const count = tarball ? 1 : Math.max(labels.length, 1);
|
|
392
|
+
const title = count > 1 ? `Publish ${count} packages to npm` : "Publish package to npm";
|
|
393
|
+
// Never echo a one-time password onto the approval card.
|
|
394
|
+
const shown = cmd.replace(/(--otp(?:=|\s+))\S+/g, "$1***");
|
|
395
|
+
return {
|
|
396
|
+
title: dryRun ? `${title} (dry run)` : title,
|
|
397
|
+
target,
|
|
398
|
+
subline: details.join(" · "),
|
|
399
|
+
body: shown.trim() === "npm publish" ? undefined : truncateBody(shown),
|
|
400
|
+
footnote: isPrivate ? "package.json is marked private, npm will refuse to publish it" : undefined,
|
|
401
|
+
kind: "npm_publish",
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
function readPackageJson(dir) {
|
|
405
|
+
try {
|
|
406
|
+
return JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
407
|
+
}
|
|
408
|
+
catch {
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
function readPackageLabel(dir) {
|
|
413
|
+
const pkg = readPackageJson(dir);
|
|
414
|
+
if (!pkg || typeof pkg.name !== "string")
|
|
415
|
+
return null;
|
|
416
|
+
return typeof pkg.version === "string" ? `${pkg.name}@${pkg.version}` : pkg.name;
|
|
417
|
+
}
|
|
418
|
+
/** Expand the root package.json `workspaces` (plain dirs and `dir/*` globs). */
|
|
419
|
+
function listWorkspaceDirs(root) {
|
|
420
|
+
const pkg = readPackageJson(root);
|
|
421
|
+
const ws = Array.isArray(pkg?.workspaces)
|
|
422
|
+
? pkg.workspaces
|
|
423
|
+
: pkg?.workspaces?.packages;
|
|
424
|
+
if (!Array.isArray(ws))
|
|
425
|
+
return [];
|
|
426
|
+
const dirs = [];
|
|
427
|
+
for (const pattern of ws) {
|
|
428
|
+
if (typeof pattern !== "string")
|
|
429
|
+
continue;
|
|
430
|
+
if (pattern.endsWith("/*")) {
|
|
431
|
+
const parent = resolve(root, pattern.slice(0, -2));
|
|
432
|
+
try {
|
|
433
|
+
for (const e of readdirSync(parent, { withFileTypes: true })) {
|
|
434
|
+
if (e.isDirectory() && existsSync(join(parent, e.name, "package.json")))
|
|
435
|
+
dirs.push(join(parent, e.name));
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
catch { /* missing dir */ }
|
|
439
|
+
}
|
|
440
|
+
else if (!pattern.includes("*")) {
|
|
441
|
+
dirs.push(resolve(root, pattern));
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
// npm skips private workspaces under --workspaces.
|
|
445
|
+
return dirs.filter((d) => readPackageJson(d)?.private !== true);
|
|
446
|
+
}
|
|
314
447
|
function summarizeShellWrite(cmd) {
|
|
315
448
|
const ops = extractShellWriteOps(cmd);
|
|
316
449
|
if (!ops.length)
|
package/dist/errors.d.ts
CHANGED
|
@@ -4,8 +4,16 @@
|
|
|
4
4
|
*
|
|
5
5
|
* - OKedAuthError -> bad/missing API key. Always deny. Never an
|
|
6
6
|
* outage, so degraded-mode does NOT apply.
|
|
7
|
-
* - OKedBackendUnreachableError -> connect failure
|
|
8
|
-
*
|
|
7
|
+
* - OKedBackendUnreachableError -> connect failure or 5xx. This is the
|
|
8
|
+
* outage case degradedDecision() handles. A
|
|
9
|
+
* request the backend accepted and then held
|
|
10
|
+
* past a timer is NOT an outage: approve()
|
|
11
|
+
* returns { decision: "timeout" } for it.
|
|
12
|
+
*
|
|
13
|
+
* - OKedReceiptError -> the decision came with a receipt that does not
|
|
14
|
+
* verify (or with none, when requireReceipt is
|
|
15
|
+
* on). Always deny: a decision we cannot prove
|
|
16
|
+
* is not a decision. Never an outage.
|
|
9
17
|
*
|
|
10
18
|
* An explicit user *deny* is NOT an error: approve() returns normally with
|
|
11
19
|
* { approved: false, decision: "denied" } and must always be honored.
|
|
@@ -18,3 +26,8 @@ export declare class OKedBackendUnreachableError extends Error {
|
|
|
18
26
|
readonly cause?: unknown;
|
|
19
27
|
constructor(message: string, cause?: unknown);
|
|
20
28
|
}
|
|
29
|
+
export declare class OKedReceiptError extends Error {
|
|
30
|
+
/** e.g. ["bad_signature"], ["subject_mismatch"], ["missing"] */
|
|
31
|
+
readonly problems: string[];
|
|
32
|
+
constructor(reason: string, problems: string[]);
|
|
33
|
+
}
|
package/dist/errors.js
CHANGED
|
@@ -4,8 +4,16 @@
|
|
|
4
4
|
*
|
|
5
5
|
* - OKedAuthError -> bad/missing API key. Always deny. Never an
|
|
6
6
|
* outage, so degraded-mode does NOT apply.
|
|
7
|
-
* - OKedBackendUnreachableError -> connect failure
|
|
8
|
-
*
|
|
7
|
+
* - OKedBackendUnreachableError -> connect failure or 5xx. This is the
|
|
8
|
+
* outage case degradedDecision() handles. A
|
|
9
|
+
* request the backend accepted and then held
|
|
10
|
+
* past a timer is NOT an outage: approve()
|
|
11
|
+
* returns { decision: "timeout" } for it.
|
|
12
|
+
*
|
|
13
|
+
* - OKedReceiptError -> the decision came with a receipt that does not
|
|
14
|
+
* verify (or with none, when requireReceipt is
|
|
15
|
+
* on). Always deny: a decision we cannot prove
|
|
16
|
+
* is not a decision. Never an outage.
|
|
9
17
|
*
|
|
10
18
|
* An explicit user *deny* is NOT an error: approve() returns normally with
|
|
11
19
|
* { approved: false, decision: "denied" } and must always be honored.
|
|
@@ -26,3 +34,12 @@ export class OKedBackendUnreachableError extends Error {
|
|
|
26
34
|
this.cause = cause;
|
|
27
35
|
}
|
|
28
36
|
}
|
|
37
|
+
export class OKedReceiptError extends Error {
|
|
38
|
+
/** e.g. ["bad_signature"], ["subject_mismatch"], ["missing"] */
|
|
39
|
+
problems;
|
|
40
|
+
constructor(reason, problems) {
|
|
41
|
+
super(`OKed receipt not valid: ${reason}`);
|
|
42
|
+
this.name = "OKedReceiptError";
|
|
43
|
+
this.problems = problems;
|
|
44
|
+
}
|
|
45
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -8,11 +8,15 @@ import type { Rule } from "./rules.js";
|
|
|
8
8
|
* kills the hook process must set their own limit ABOVE this one, so our
|
|
9
9
|
* fail-safe deny is written before the harness pulls the plug. See
|
|
10
10
|
* HOOK_TIMEOUT_SECONDS in @oked/claude-code.
|
|
11
|
+
*
|
|
12
|
+
* 30s above the backend's own 10 minute expiry, so the backend's "timeout"
|
|
13
|
+
* answer normally arrives before our abort fires (backend < SDK < harness).
|
|
11
14
|
*/
|
|
12
|
-
export declare const DEFAULT_APPROVAL_TIMEOUT_MS =
|
|
15
|
+
export declare const DEFAULT_APPROVAL_TIMEOUT_MS = 630000;
|
|
13
16
|
export declare class OKedClient {
|
|
14
17
|
private config;
|
|
15
18
|
constructor(config?: Partial<OKedConfig>);
|
|
19
|
+
get requireReceipt(): boolean;
|
|
16
20
|
get strictFailClosed(): boolean;
|
|
17
21
|
get apiKey(): string;
|
|
18
22
|
get backendUrl(): string;
|
|
@@ -37,7 +41,10 @@ export declare class OKedClient {
|
|
|
37
41
|
*/
|
|
38
42
|
heartbeat(): Promise<void>;
|
|
39
43
|
}
|
|
40
|
-
export { OKedAuthError, OKedBackendUnreachableError } from "./errors.js";
|
|
44
|
+
export { OKedAuthError, OKedBackendUnreachableError, OKedReceiptError } from "./errors.js";
|
|
45
|
+
export { checkReceipt, keysFor, keysUrlAllowed, OKED_RECEIPT_KEYS_URL } from "./receipt.js";
|
|
46
|
+
export { PINNED_RECEIPT_KEYS } from "./receipt-keys.js";
|
|
47
|
+
export { verifyReceipt, verifyChain, shortReceiptId, type SignedReceipt, type ReceiptBody, type ReceiptKey, } from "@oked/receipt-core";
|
|
41
48
|
export { TIER_ORDER, degradedDecision } from "./degraded.js";
|
|
42
49
|
export { classify } from "./classify.js";
|
|
43
50
|
export { describe, describeFields } from "./describe.js";
|
|
@@ -46,6 +53,6 @@ export type { Rule, RuleMatch, RuleAction, RuleDecision, FieldOp, } from "./rule
|
|
|
46
53
|
export type { Rendered } from "./describe.js";
|
|
47
54
|
export { CLASSIFIER_VERSION } from "./kinds.js";
|
|
48
55
|
export type { OperationKind } from "./kinds.js";
|
|
49
|
-
export { loadOKedConfig, OKED_CONFIG_PATH } from "./config.js";
|
|
56
|
+
export { loadOKedConfig, OKED_CONFIG_PATH, OKED_RECEIPT_KEYS_PATH } from "./config.js";
|
|
50
57
|
export type { PersistedConfig } from "./config.js";
|
|
51
58
|
export type { RiskTier, ApprovalRequest, ApprovalResponse, OKedConfig, HookInput, HookOutput, } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,8 @@ import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
|
|
2
2
|
import { dirname } from "path";
|
|
3
3
|
import { loadOKedConfig, OKED_RULES_CACHE_PATH, OKED_HEARTBEAT_PATH } from "./config.js";
|
|
4
4
|
import { OKedAuthError, OKedBackendUnreachableError } from "./errors.js";
|
|
5
|
+
import { randomUUID } from "crypto";
|
|
6
|
+
import { checkReceipt, OKED_RECEIPT_KEYS_URL } from "./receipt.js";
|
|
5
7
|
import { hostname } from "os";
|
|
6
8
|
/**
|
|
7
9
|
* How long we wait for a human decision before giving up on the request.
|
|
@@ -11,8 +13,11 @@ import { hostname } from "os";
|
|
|
11
13
|
* kills the hook process must set their own limit ABOVE this one, so our
|
|
12
14
|
* fail-safe deny is written before the harness pulls the plug. See
|
|
13
15
|
* HOOK_TIMEOUT_SECONDS in @oked/claude-code.
|
|
16
|
+
*
|
|
17
|
+
* 30s above the backend's own 10 minute expiry, so the backend's "timeout"
|
|
18
|
+
* answer normally arrives before our abort fires (backend < SDK < harness).
|
|
14
19
|
*/
|
|
15
|
-
export const DEFAULT_APPROVAL_TIMEOUT_MS =
|
|
20
|
+
export const DEFAULT_APPROVAL_TIMEOUT_MS = 630_000;
|
|
16
21
|
function envStrictFailClosed() {
|
|
17
22
|
const raw = process.env.OKED_STRICT_FAIL_CLOSED;
|
|
18
23
|
if (raw === undefined)
|
|
@@ -26,6 +31,12 @@ function envRulesCacheTtlMs() {
|
|
|
26
31
|
const n = Number(raw);
|
|
27
32
|
return Number.isFinite(n) && n >= 0 ? n * 1000 : undefined;
|
|
28
33
|
}
|
|
34
|
+
function envRequireReceipt() {
|
|
35
|
+
const raw = process.env.OKED_REQUIRE_RECEIPT;
|
|
36
|
+
if (raw === undefined)
|
|
37
|
+
return undefined;
|
|
38
|
+
return raw === "1" || raw.toLowerCase() === "true";
|
|
39
|
+
}
|
|
29
40
|
function envHeartbeatIntervalMs() {
|
|
30
41
|
const raw = process.env.OKED_HEARTBEAT_INTERVAL; // seconds
|
|
31
42
|
if (raw === undefined)
|
|
@@ -106,8 +117,22 @@ export class OKedClient {
|
|
|
106
117
|
? persisted.heartbeatIntervalSeconds * 1000
|
|
107
118
|
: undefined) ??
|
|
108
119
|
86_400_000,
|
|
120
|
+
// On by default from 0.6.0: an approval only counts with a valid receipt.
|
|
121
|
+
// OKED_REQUIRE_RECEIPT=0 (or requireReceipt: false) for a backend that
|
|
122
|
+
// does not sign receipts yet, e.g. an older self-hosted one.
|
|
123
|
+
requireReceipt: config?.requireReceipt ?? envRequireReceipt() ?? persisted.requireReceipt ?? true,
|
|
124
|
+
receiptKeysUrl: config?.receiptKeysUrl ||
|
|
125
|
+
process.env.OKED_RECEIPT_KEYS_URL ||
|
|
126
|
+
persisted.receiptKeysUrl ||
|
|
127
|
+
OKED_RECEIPT_KEYS_URL,
|
|
128
|
+
receiptKeys: config?.receiptKeys,
|
|
129
|
+
client: config?.client,
|
|
130
|
+
source: config?.source,
|
|
109
131
|
};
|
|
110
132
|
}
|
|
133
|
+
get requireReceipt() {
|
|
134
|
+
return this.config.requireReceipt;
|
|
135
|
+
}
|
|
111
136
|
get strictFailClosed() {
|
|
112
137
|
return this.config.strictFailClosed;
|
|
113
138
|
}
|
|
@@ -119,6 +144,10 @@ export class OKedClient {
|
|
|
119
144
|
}
|
|
120
145
|
async approve(request) {
|
|
121
146
|
const signal = AbortSignal.timeout(this.config.timeout);
|
|
147
|
+
// A fresh nonce per request goes into the receipt's subject, so a receipt
|
|
148
|
+
// for an earlier, identical action can never be replayed for this one.
|
|
149
|
+
const nonce = randomUUID();
|
|
150
|
+
const source = this.config.source || "sdk";
|
|
122
151
|
const doFetch = () => fetch(`${this.config.backendUrl}/api/v1/approve`, {
|
|
123
152
|
method: "POST",
|
|
124
153
|
headers: {
|
|
@@ -130,10 +159,13 @@ export class OKedClient {
|
|
|
130
159
|
description: request.description,
|
|
131
160
|
tier: request.tier,
|
|
132
161
|
fields: request.fields,
|
|
162
|
+
nonce,
|
|
163
|
+
client: this.config.client,
|
|
133
164
|
metadata: {
|
|
134
165
|
tool_input: request.tool_input,
|
|
135
166
|
session_id: request.session_id,
|
|
136
167
|
cwd: request.cwd,
|
|
168
|
+
source: this.config.source,
|
|
137
169
|
},
|
|
138
170
|
}),
|
|
139
171
|
signal,
|
|
@@ -154,9 +186,13 @@ export class OKedClient {
|
|
|
154
186
|
}
|
|
155
187
|
}
|
|
156
188
|
catch (err) {
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
//
|
|
189
|
+
// The backend accepted the request and then held it past a timer: no
|
|
190
|
+
// human decided in time. That is a timeout (deny), not an outage, so it
|
|
191
|
+
// must never fall through to degraded-mode allow.
|
|
192
|
+
if (isHeldRequestTimeout(err))
|
|
193
|
+
return HELD_TIMEOUT;
|
|
194
|
+
// Connect failure: we never reached the backend -> treat as an outage
|
|
195
|
+
// so degraded-mode can apply.
|
|
160
196
|
throw new OKedBackendUnreachableError(err instanceof Error ? `OKed backend unreachable: ${err.message}` : "OKed backend unreachable", err);
|
|
161
197
|
}
|
|
162
198
|
if (!res.ok) {
|
|
@@ -164,16 +200,37 @@ export class OKedClient {
|
|
|
164
200
|
if (res.status === 401 || res.status === 403) {
|
|
165
201
|
throw new OKedAuthError(`OKed backend error ${res.status}: ${body}`, res.status);
|
|
166
202
|
}
|
|
203
|
+
// A gateway that gave up waiting on a held long-poll: same as above.
|
|
204
|
+
if (res.status === 504)
|
|
205
|
+
return HELD_TIMEOUT;
|
|
167
206
|
if (res.status >= 500) {
|
|
168
207
|
throw new OKedBackendUnreachableError(`OKed backend error ${res.status}: ${body}`);
|
|
169
208
|
}
|
|
170
209
|
throw new Error(`OKed backend error ${res.status}: ${body}`);
|
|
171
210
|
}
|
|
172
|
-
|
|
211
|
+
let result;
|
|
212
|
+
try {
|
|
213
|
+
// The backend sends headers at once and streams whitespace heartbeats
|
|
214
|
+
// while it waits, so the wait for a human happens here, in the body.
|
|
215
|
+
result = (await res.json());
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
if (isHeldRequestTimeout(err))
|
|
219
|
+
return HELD_TIMEOUT;
|
|
220
|
+
throw err;
|
|
221
|
+
}
|
|
222
|
+
// Nobody acts on a decision we cannot prove: an invalid receipt throws
|
|
223
|
+
// OKedReceiptError (every integration denies), and so does an approval
|
|
224
|
+
// with no receipt while requireReceipt is on (the default).
|
|
225
|
+
const receipt = await checkReceipt(result, { action: request.action, description: request.description, toolInput: request.tool_input, source, nonce }, {
|
|
226
|
+
required: this.config.requireReceipt,
|
|
227
|
+
trust: { keys: this.config.receiptKeys, keysUrl: this.config.receiptKeysUrl },
|
|
228
|
+
});
|
|
173
229
|
return {
|
|
174
230
|
approved: result.decision === "approved",
|
|
175
231
|
approval_id: result.approval_id,
|
|
176
232
|
decision: result.decision,
|
|
233
|
+
...(receipt ? { receipt } : {}),
|
|
177
234
|
};
|
|
178
235
|
}
|
|
179
236
|
/**
|
|
@@ -257,6 +314,22 @@ export class OKedClient {
|
|
|
257
314
|
}
|
|
258
315
|
}
|
|
259
316
|
}
|
|
317
|
+
const HELD_TIMEOUT = { approved: false, approval_id: null, decision: "timeout" };
|
|
318
|
+
/**
|
|
319
|
+
* True when a request reached the backend and then sat past a timer: our own
|
|
320
|
+
* abort (TimeoutError), or undici's 300s headers/body timeouts, which fire
|
|
321
|
+
* regardless of the abort signal on a silent long-poll.
|
|
322
|
+
*/
|
|
323
|
+
function isHeldRequestTimeout(err) {
|
|
324
|
+
if (!err || typeof err !== "object")
|
|
325
|
+
return false;
|
|
326
|
+
// AbortSignal.timeout() rejects with a DOMException, which is not an Error
|
|
327
|
+
// instance on every Node version, so match on the name alone.
|
|
328
|
+
if (err.name === "TimeoutError")
|
|
329
|
+
return true;
|
|
330
|
+
const code = err.cause?.code ?? err.code;
|
|
331
|
+
return code === "UND_ERR_HEADERS_TIMEOUT" || code === "UND_ERR_BODY_TIMEOUT";
|
|
332
|
+
}
|
|
260
333
|
function isRetriableConnectError(err) {
|
|
261
334
|
if (!(err instanceof Error))
|
|
262
335
|
return false;
|
|
@@ -269,10 +342,13 @@ function isRetriableConnectError(err) {
|
|
|
269
342
|
code === "ETIMEDOUT" ||
|
|
270
343
|
code === "UND_ERR_CONNECT_TIMEOUT");
|
|
271
344
|
}
|
|
272
|
-
export { OKedAuthError, OKedBackendUnreachableError } from "./errors.js";
|
|
345
|
+
export { OKedAuthError, OKedBackendUnreachableError, OKedReceiptError } from "./errors.js";
|
|
346
|
+
export { checkReceipt, keysFor, keysUrlAllowed, OKED_RECEIPT_KEYS_URL } from "./receipt.js";
|
|
347
|
+
export { PINNED_RECEIPT_KEYS } from "./receipt-keys.js";
|
|
348
|
+
export { verifyReceipt, verifyChain, shortReceiptId, } from "@oked/receipt-core";
|
|
273
349
|
export { TIER_ORDER, degradedDecision } from "./degraded.js";
|
|
274
350
|
export { classify } from "./classify.js";
|
|
275
351
|
export { describe, describeFields } from "./describe.js";
|
|
276
352
|
export { applyRules } from "./rules.js";
|
|
277
353
|
export { CLASSIFIER_VERSION } from "./kinds.js";
|
|
278
|
-
export { loadOKedConfig, OKED_CONFIG_PATH } from "./config.js";
|
|
354
|
+
export { loadOKedConfig, OKED_CONFIG_PATH, OKED_RECEIPT_KEYS_PATH } from "./config.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ReceiptKey } from "@oked/receipt-core";
|
|
2
|
+
/**
|
|
3
|
+
* OKed's production receipt keys, shipped with the SDK so the first receipt
|
|
4
|
+
* verifies without a network call and a lookalike backend cannot supply its
|
|
5
|
+
* own key. Keys not listed here are fetched from the fixed published URL
|
|
6
|
+
* (OKED_RECEIPT_KEYS_URL), never from the configurable backend URL.
|
|
7
|
+
*
|
|
8
|
+
* On rotation, add the new key here and give the old one its not_after (the
|
|
9
|
+
* same value the backend publishes), so a retired key stops verifying new
|
|
10
|
+
* receipts here too.
|
|
11
|
+
*/
|
|
12
|
+
export declare const PINNED_RECEIPT_KEYS: ReceiptKey[];
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OKed's production receipt keys, shipped with the SDK so the first receipt
|
|
3
|
+
* verifies without a network call and a lookalike backend cannot supply its
|
|
4
|
+
* own key. Keys not listed here are fetched from the fixed published URL
|
|
5
|
+
* (OKED_RECEIPT_KEYS_URL), never from the configurable backend URL.
|
|
6
|
+
*
|
|
7
|
+
* On rotation, add the new key here and give the old one its not_after (the
|
|
8
|
+
* same value the backend publishes), so a retired key stops verifying new
|
|
9
|
+
* receipts here too.
|
|
10
|
+
*/
|
|
11
|
+
export const PINNED_RECEIPT_KEYS = [
|
|
12
|
+
{
|
|
13
|
+
kid: "oked-2026-10",
|
|
14
|
+
alg: "Ed25519",
|
|
15
|
+
public_key: "C0YsmbAi0NLBz4eEDTwpusXlBMOzh30LXWkd-9dEiAw",
|
|
16
|
+
not_before: "2026-10-01T00:00:00.000Z",
|
|
17
|
+
not_after: null,
|
|
18
|
+
},
|
|
19
|
+
];
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { OKED_RECEIPT_KEYS_URL, type ReceiptKey, type SignedReceipt } from "@oked/receipt-core";
|
|
2
|
+
export interface ReceiptTrust {
|
|
3
|
+
/** Use exactly these keys and never fetch (tests, self-hosted backends). */
|
|
4
|
+
keys?: ReceiptKey[];
|
|
5
|
+
/** Where to fetch a key not seen before. https only, except loopback for local dev. */
|
|
6
|
+
keysUrl: string;
|
|
7
|
+
}
|
|
8
|
+
export interface SentRequest {
|
|
9
|
+
action: string;
|
|
10
|
+
description: unknown;
|
|
11
|
+
toolInput: unknown;
|
|
12
|
+
source: string;
|
|
13
|
+
nonce: string;
|
|
14
|
+
}
|
|
15
|
+
/** A key not seen before is accepted only over TLS (or from this machine, for local dev). */
|
|
16
|
+
export declare function keysUrlAllowed(url: string): boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Keys to verify `kid` with: pinned production keys and keys cached on disk,
|
|
19
|
+
* fetching the published set (from the fixed OKed URL, never from the
|
|
20
|
+
* configurable backend URL) only when the kid is unknown.
|
|
21
|
+
*/
|
|
22
|
+
export declare function keysFor(kid: string, trust: ReceiptTrust): Promise<ReceiptKey[]>;
|
|
23
|
+
/**
|
|
24
|
+
* Check the receipt that came with a decision before anyone acts on it: a
|
|
25
|
+
* valid signature by a published OKed key, for this request id, this
|
|
26
|
+
* decision, and the exact action and nonce we sent. Throws OKedReceiptError
|
|
27
|
+
* on any mismatch. A missing receipt throws only for an approval, when
|
|
28
|
+
* `required`: a deny or timeout without one is a deny anyway.
|
|
29
|
+
*/
|
|
30
|
+
export declare function checkReceipt(result: {
|
|
31
|
+
approval_id: string | null;
|
|
32
|
+
decision: string;
|
|
33
|
+
receipt?: unknown;
|
|
34
|
+
}, sent: SentRequest, opts: {
|
|
35
|
+
required: boolean;
|
|
36
|
+
trust: ReceiptTrust;
|
|
37
|
+
}): Promise<SignedReceipt | undefined>;
|
|
38
|
+
export { OKED_RECEIPT_KEYS_URL };
|
package/dist/receipt.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
2
|
+
import { dirname } from "path";
|
|
3
|
+
import { OKED_RECEIPT_KEYS_URL, jsonValue, responseDecision, verifyReceipt, } from "@oked/receipt-core";
|
|
4
|
+
import { OKedReceiptError } from "./errors.js";
|
|
5
|
+
import { OKED_RECEIPT_KEYS_PATH } from "./config.js";
|
|
6
|
+
import { PINNED_RECEIPT_KEYS } from "./receipt-keys.js";
|
|
7
|
+
function readCachedKeys() {
|
|
8
|
+
try {
|
|
9
|
+
const parsed = JSON.parse(readFileSync(OKED_RECEIPT_KEYS_PATH, "utf-8"));
|
|
10
|
+
return Array.isArray(parsed?.keys) ? parsed.keys : [];
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return [];
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function writeCachedKeys(keys) {
|
|
17
|
+
try {
|
|
18
|
+
mkdirSync(dirname(OKED_RECEIPT_KEYS_PATH), { recursive: true });
|
|
19
|
+
writeFileSync(OKED_RECEIPT_KEYS_PATH, JSON.stringify({ keys }));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// Best-effort; we fetch again next time.
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** A key not seen before is accepted only over TLS (or from this machine, for local dev). */
|
|
26
|
+
export function keysUrlAllowed(url) {
|
|
27
|
+
try {
|
|
28
|
+
const u = new URL(url);
|
|
29
|
+
if (u.protocol === "https:")
|
|
30
|
+
return true;
|
|
31
|
+
return u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function fetchKeys(url) {
|
|
38
|
+
if (!keysUrlAllowed(url))
|
|
39
|
+
return [];
|
|
40
|
+
try {
|
|
41
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
|
|
42
|
+
if (!res.ok)
|
|
43
|
+
return [];
|
|
44
|
+
const body = (await res.json());
|
|
45
|
+
return Array.isArray(body.keys) ? body.keys : [];
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Keys to verify `kid` with: pinned production keys and keys cached on disk,
|
|
53
|
+
* fetching the published set (from the fixed OKed URL, never from the
|
|
54
|
+
* configurable backend URL) only when the kid is unknown.
|
|
55
|
+
*/
|
|
56
|
+
export async function keysFor(kid, trust) {
|
|
57
|
+
if (trust.keys)
|
|
58
|
+
return trust.keys;
|
|
59
|
+
const known = [...PINNED_RECEIPT_KEYS, ...readCachedKeys()];
|
|
60
|
+
if (known.some((k) => k.kid === kid))
|
|
61
|
+
return known;
|
|
62
|
+
const fetched = await fetchKeys(trust.keysUrl);
|
|
63
|
+
if (fetched.length > 0)
|
|
64
|
+
writeCachedKeys(fetched);
|
|
65
|
+
return [...PINNED_RECEIPT_KEYS, ...fetched];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Check the receipt that came with a decision before anyone acts on it: a
|
|
69
|
+
* valid signature by a published OKed key, for this request id, this
|
|
70
|
+
* decision, and the exact action and nonce we sent. Throws OKedReceiptError
|
|
71
|
+
* on any mismatch. A missing receipt throws only for an approval, when
|
|
72
|
+
* `required`: a deny or timeout without one is a deny anyway.
|
|
73
|
+
*/
|
|
74
|
+
export async function checkReceipt(result, sent, opts) {
|
|
75
|
+
if (result.receipt === undefined || result.receipt === null) {
|
|
76
|
+
if (opts.required && result.decision === "approved")
|
|
77
|
+
throw new OKedReceiptError("missing", ["missing"]);
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
const receipt = result.receipt;
|
|
81
|
+
const kid = typeof receipt?.kid === "string" ? receipt.kid : "";
|
|
82
|
+
const body = receipt?.body;
|
|
83
|
+
if (!body || typeof body !== "object")
|
|
84
|
+
throw new OKedReceiptError("malformed", ["malformed"]);
|
|
85
|
+
const subject = {
|
|
86
|
+
type: "tool_call",
|
|
87
|
+
operator_id: body.operator_id ?? null,
|
|
88
|
+
request_id: result.approval_id ?? "",
|
|
89
|
+
source: sent.source,
|
|
90
|
+
action: sent.action,
|
|
91
|
+
description: jsonValue(sent.description),
|
|
92
|
+
tool_input: jsonValue(sent.toolInput),
|
|
93
|
+
client_nonce: sent.nonce,
|
|
94
|
+
};
|
|
95
|
+
const check = verifyReceipt(receipt, { keys: await keysFor(kid, opts.trust), subject });
|
|
96
|
+
const problems = [...check.problems];
|
|
97
|
+
if (body.request_id !== result.approval_id)
|
|
98
|
+
problems.push("request_mismatch");
|
|
99
|
+
if (typeof body.decision !== "string" || responseDecision(body.decision) !== result.decision) {
|
|
100
|
+
problems.push("decision_mismatch");
|
|
101
|
+
}
|
|
102
|
+
if (problems.length > 0)
|
|
103
|
+
throw new OKedReceiptError(problems.join(", "), problems);
|
|
104
|
+
return receipt;
|
|
105
|
+
}
|
|
106
|
+
export { OKED_RECEIPT_KEYS_URL };
|
package/dist/types.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ReceiptKey, SignedReceipt } from "@oked/receipt-core";
|
|
1
2
|
export type RiskTier = "safe" | "warning" | "review" | "high_stakes";
|
|
2
3
|
export interface ApprovalRequest {
|
|
3
4
|
action: string;
|
|
@@ -10,14 +11,22 @@ export interface ApprovalRequest {
|
|
|
10
11
|
}
|
|
11
12
|
export interface ApprovalResponse {
|
|
12
13
|
approved: boolean;
|
|
13
|
-
|
|
14
|
+
/** null when no request row exists (e.g. a request that timed out client-side). */
|
|
15
|
+
approval_id: string | null;
|
|
14
16
|
decision: "approved" | "denied" | "timeout";
|
|
17
|
+
/**
|
|
18
|
+
* The signed receipt for this decision, already verified: OKed's signature,
|
|
19
|
+
* this request, this decision, and the exact action and nonce sent. Absent
|
|
20
|
+
* for a deny or timeout that came without one (e.g. a client-side timeout),
|
|
21
|
+
* or when requireReceipt is off and the backend sent none.
|
|
22
|
+
*/
|
|
23
|
+
receipt?: SignedReceipt;
|
|
15
24
|
}
|
|
16
25
|
export interface OKedConfig {
|
|
17
26
|
apiKey: string;
|
|
18
27
|
backendUrl: string;
|
|
19
28
|
/**
|
|
20
|
-
* How long to wait for a human decision, in ms. Default
|
|
29
|
+
* How long to wait for a human decision, in ms. Default 630_000 (10.5 min);
|
|
21
30
|
* see DEFAULT_APPROVAL_TIMEOUT_MS.
|
|
22
31
|
*
|
|
23
32
|
* Three timers nest around one approval: the backend's own expiry (which
|
|
@@ -51,6 +60,26 @@ export interface OKedConfig {
|
|
|
51
60
|
* Default 86_400_000 (once per day).
|
|
52
61
|
*/
|
|
53
62
|
heartbeatIntervalMs: number;
|
|
63
|
+
/**
|
|
64
|
+
* Deny an approval that arrives without a receipt. A receipt that is present
|
|
65
|
+
* but does not verify always denies, whatever this says. Default true (since
|
|
66
|
+
* 0.6.0); set false, or env OKED_REQUIRE_RECEIPT=0, only for a backend that
|
|
67
|
+
* does not sign receipts.
|
|
68
|
+
*/
|
|
69
|
+
requireReceipt: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Where to fetch receipt keys the SDK has not seen. Default OKed's published
|
|
72
|
+
* set (https://api.oked.ai/.well-known/oked-receipt-keys.json), independent
|
|
73
|
+
* of backendUrl. https only, except loopback for local dev. Env
|
|
74
|
+
* OKED_RECEIPT_KEYS_URL.
|
|
75
|
+
*/
|
|
76
|
+
receiptKeysUrl: string;
|
|
77
|
+
/** Verify with exactly these keys and never fetch (tests, self-hosted backends). */
|
|
78
|
+
receiptKeys?: ReceiptKey[];
|
|
79
|
+
/** The integration asking, e.g. "@oked/claude-code@0.5.0". Recorded in receipts. */
|
|
80
|
+
client?: string;
|
|
81
|
+
/** Where the request comes from, e.g. "claude-code". Part of the receipt's subject. Default "sdk". */
|
|
82
|
+
source?: string;
|
|
54
83
|
}
|
|
55
84
|
export interface HookInput {
|
|
56
85
|
session_id: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oked/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "OKed SDK - human approval layer for AI agents",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
}
|
|
13
13
|
},
|
|
14
14
|
"scripts": {
|
|
15
|
+
"prebuild": "npm run build --workspace=@oked/receipt-core",
|
|
15
16
|
"build": "tsc",
|
|
16
17
|
"dev": "tsc --watch",
|
|
17
18
|
"test": "tsx --test test/*.test.ts",
|
|
@@ -43,6 +44,9 @@
|
|
|
43
44
|
"publishConfig": {
|
|
44
45
|
"access": "public"
|
|
45
46
|
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@oked/receipt-core": "0.6.0"
|
|
49
|
+
},
|
|
46
50
|
"devDependencies": {
|
|
47
51
|
"@types/node": "^22.13.10",
|
|
48
52
|
"tsx": "^4.22.0",
|