@oked/sdk 0.3.6 → 0.5.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/classify.d.ts +8 -0
- package/dist/classify.js +134 -4
- package/dist/config.d.ts +5 -0
- package/dist/config.js +5 -0
- package/dist/describe.d.ts +7 -2
- package/dist/describe.js +238 -10
- package/dist/errors.d.ts +15 -2
- package/dist/errors.js +19 -2
- package/dist/index.d.ts +19 -2
- package/dist/index.js +90 -7
- package/dist/kinds.d.ts +1 -1
- package/dist/receipt-keys.d.ts +12 -0
- package/dist/receipt-keys.js +19 -0
- package/dist/receipt.d.ts +37 -0
- package/dist/receipt.js +105 -0
- package/dist/types.d.ts +40 -1
- 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` | `false` (`true` from 0.6.0) | Deny any decision that arrives without a valid signed receipt. A receipt that is present but invalid always denies. Env `OKED_REQUIRE_RECEIPT=1`. |
|
|
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 `1` or `true` to deny any decision without a valid signed receipt. |
|
|
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 a missing one with `requireReceipt`) 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/classify.d.ts
CHANGED
|
@@ -19,4 +19,12 @@ export interface ShellWriteOp {
|
|
|
19
19
|
*/
|
|
20
20
|
export declare function stripHeredocBodies(command: string): string;
|
|
21
21
|
export declare function stripInlineScriptBodies(command: string): string;
|
|
22
|
+
/**
|
|
23
|
+
* Blank the interior of quoted curl request bodies, keeping the quotes and the
|
|
24
|
+
* flag so the per-stage curl rules still see a POST. A JSON payload that
|
|
25
|
+
* mentions `git push --force` or `rm -rf` is data, and must not trip the
|
|
26
|
+
* full-command high-stakes scan. Only applies inside a curl stage (from `curl`
|
|
27
|
+
* to the next unquoted `;`, `|`, `&` or newline).
|
|
28
|
+
*/
|
|
29
|
+
export declare function stripCurlDataBodies(command: string): string;
|
|
22
30
|
export declare function extractShellWriteOps(command: string): ShellWriteOp[];
|
package/dist/classify.js
CHANGED
|
@@ -338,7 +338,7 @@ export function classify(toolName, toolInput) {
|
|
|
338
338
|
}
|
|
339
339
|
// MCP tools: mcp__<server>__<tool>
|
|
340
340
|
if (toolName.startsWith("mcp__")) {
|
|
341
|
-
return classifyMcpTool(toolName);
|
|
341
|
+
return classifyMcpTool(toolName, toolInput);
|
|
342
342
|
}
|
|
343
343
|
// Shell-exec-style tools from other agents (Codex CLI's `exec`, OpenClaw,
|
|
344
344
|
// generic `run`/`run_command`/`shell`). Detect by signature: a string
|
|
@@ -744,11 +744,12 @@ function classifyBashCommand(command, ephemeralVars = new Set()) {
|
|
|
744
744
|
// SHELL-pattern scan, so a shell token embedded as code/data in
|
|
745
745
|
// an interpreter body (`rm`, `curl -d`, a `>` redirect — e.g. a
|
|
746
746
|
// reddit post fed to `node -e '…samples…'`) does not trip a
|
|
747
|
-
// destructive/outward rule.
|
|
747
|
+
// destructive/outward rule. Quoted curl request bodies (`-d
|
|
748
|
+
// '{"command":"git push --force"}'`) are blanked the same way. (SQL keywords in that data can still
|
|
748
749
|
// surface via `intact` — that is the accepted shell-only-opacity
|
|
749
750
|
// trade-off; see classifyStageShellEffects.)
|
|
750
751
|
const intact = stripHeredocBodies(command).trim();
|
|
751
|
-
const stripped = stripInlineScriptBodies(intact).trim();
|
|
752
|
+
const stripped = stripCurlDataBodies(stripInlineScriptBodies(intact)).trim();
|
|
752
753
|
// High-stakes scan on the FULL (body-stripped) command, before any splitting.
|
|
753
754
|
// These patterns use \b and several intentionally span an operator (e.g.
|
|
754
755
|
// `curl … | bash`, `wget … | sh` — download-and-execute), so they have to be
|
|
@@ -998,6 +999,60 @@ export function stripInlineScriptBodies(command) {
|
|
|
998
999
|
out += command.slice(last);
|
|
999
1000
|
return out;
|
|
1000
1001
|
}
|
|
1002
|
+
// curl request-body flags whose quoted value is payload sent to a server,
|
|
1003
|
+
// never run locally.
|
|
1004
|
+
const CURL_DATA_FLAG_RE = /^(?:-d|--data(?:-raw|-binary|-urlencode|-ascii)?|--json|-F|--form)(?:\s+|=)(['"])/;
|
|
1005
|
+
/**
|
|
1006
|
+
* Blank the interior of quoted curl request bodies, keeping the quotes and the
|
|
1007
|
+
* flag so the per-stage curl rules still see a POST. A JSON payload that
|
|
1008
|
+
* mentions `git push --force` or `rm -rf` is data, and must not trip the
|
|
1009
|
+
* full-command high-stakes scan. Only applies inside a curl stage (from `curl`
|
|
1010
|
+
* to the next unquoted `;`, `|`, `&` or newline).
|
|
1011
|
+
*/
|
|
1012
|
+
export function stripCurlDataBodies(command) {
|
|
1013
|
+
let out = "";
|
|
1014
|
+
let inCurl = false;
|
|
1015
|
+
let i = 0;
|
|
1016
|
+
while (i < command.length) {
|
|
1017
|
+
const ch = command[i];
|
|
1018
|
+
if (ch === "'" || ch === '"') {
|
|
1019
|
+
// Copy a quoted span verbatim (it isn't a body we're blanking).
|
|
1020
|
+
let j = i + 1;
|
|
1021
|
+
while (j < command.length && command[j] !== ch) {
|
|
1022
|
+
if (ch === '"' && command[j] === "\\")
|
|
1023
|
+
j++;
|
|
1024
|
+
j++;
|
|
1025
|
+
}
|
|
1026
|
+
out += command.slice(i, j + 1);
|
|
1027
|
+
i = j + 1;
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
if (/[;|&\n]/.test(ch))
|
|
1031
|
+
inCurl = false;
|
|
1032
|
+
else if (!inCurl && /^curl\b/.test(command.slice(i)) && (i === 0 || /[\s(;|&]/.test(command[i - 1]))) {
|
|
1033
|
+
inCurl = true;
|
|
1034
|
+
}
|
|
1035
|
+
else if (inCurl && /\s/.test(ch)) {
|
|
1036
|
+
const m = command.slice(i + 1).match(CURL_DATA_FLAG_RE);
|
|
1037
|
+
if (m) {
|
|
1038
|
+
const quote = m[1];
|
|
1039
|
+
const bodyStart = i + 1 + m[0].length;
|
|
1040
|
+
let j = bodyStart;
|
|
1041
|
+
while (j < command.length && command[j] !== quote) {
|
|
1042
|
+
if (quote === '"' && command[j] === "\\")
|
|
1043
|
+
j++;
|
|
1044
|
+
j++;
|
|
1045
|
+
}
|
|
1046
|
+
out += command.slice(i, bodyStart) + quote;
|
|
1047
|
+
i = j + 1;
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
out += ch;
|
|
1052
|
+
i++;
|
|
1053
|
+
}
|
|
1054
|
+
return out;
|
|
1055
|
+
}
|
|
1001
1056
|
/** Find output redirects (`>`, `>>`, `&>`, `2>`, …) outside quoted strings.
|
|
1002
1057
|
* The target token may itself be quoted. Skips `2>&1`-style FD dups, bare
|
|
1003
1058
|
* digits, and /dev/null. Heredoc `<<` is ignored (only `>` is a write). */
|
|
@@ -1159,9 +1214,84 @@ function splitArgs(s) {
|
|
|
1159
1214
|
out.push(cur);
|
|
1160
1215
|
return out;
|
|
1161
1216
|
}
|
|
1162
|
-
|
|
1217
|
+
// Browser MCP servers: the desktop app's built-in browser pane (also reached
|
|
1218
|
+
// as mcp__remote-devices__Claude_Browser__* from cloud sessions) and the
|
|
1219
|
+
// Claude in Chrome extension. Their tool names don't follow the verb-prefix
|
|
1220
|
+
// convention below, so they get an explicit table keyed on the tool name.
|
|
1221
|
+
const BROWSER_MCP_SERVERS = new Set(["Claude_Browser", "claude-in-chrome"]);
|
|
1222
|
+
// Browser tools that only look at, open, or arrange pages (no clicks, typing,
|
|
1223
|
+
// form fills, script execution, or uploads). Navigation is a read, like
|
|
1224
|
+
// WebSearch. Anything not listed here falls through to `review`.
|
|
1225
|
+
const SAFE_BROWSER_TOOLS = new Set([
|
|
1226
|
+
"navigate",
|
|
1227
|
+
"find",
|
|
1228
|
+
"read_page",
|
|
1229
|
+
"get_page_text",
|
|
1230
|
+
"read_console_messages",
|
|
1231
|
+
"read_network_requests",
|
|
1232
|
+
"tabs_context",
|
|
1233
|
+
"tabs_context_mcp",
|
|
1234
|
+
"tabs_create",
|
|
1235
|
+
"tabs_create_mcp",
|
|
1236
|
+
"tabs_select",
|
|
1237
|
+
"tabs_close",
|
|
1238
|
+
"tabs_close_mcp",
|
|
1239
|
+
"resize_window",
|
|
1240
|
+
"preview_list",
|
|
1241
|
+
"preview_logs",
|
|
1242
|
+
"preview_stop",
|
|
1243
|
+
"gif_creator",
|
|
1244
|
+
"shortcuts_list",
|
|
1245
|
+
"list_connected_browsers",
|
|
1246
|
+
"select_browser",
|
|
1247
|
+
"switch_browser",
|
|
1248
|
+
]);
|
|
1249
|
+
// `computer` actions that only observe or move the viewport.
|
|
1250
|
+
const SAFE_COMPUTER_ACTIONS = new Set(["screenshot", "zoom", "scroll", "scroll_to", "hover", "wait"]);
|
|
1251
|
+
// Page interactions (clicks, typing, form fills, in-page JS). In the desktop
|
|
1252
|
+
// app's built-in browser pane these act in an isolated browser, mostly against
|
|
1253
|
+
// the user's own dev servers, so they're logged (`warning`) rather than
|
|
1254
|
+
// prompted: a prompt per click is pure approval fatigue. In Claude in Chrome
|
|
1255
|
+
// they act inside the user's real logged-in sessions (mail, banking, …), so
|
|
1256
|
+
// they stay `review`.
|
|
1257
|
+
const BROWSER_INTERACTION_TOOLS = new Set(["computer", "form_input", "javascript_tool"]);
|
|
1258
|
+
function classifyBrowserTool(tool, toolInput, server) {
|
|
1259
|
+
if (SAFE_BROWSER_TOOLS.has(tool))
|
|
1260
|
+
return "safe";
|
|
1261
|
+
// preview_start with `url` just opens a tab. With `name` it launches the
|
|
1262
|
+
// dev-server command from .claude/launch.json, which is arbitrary command
|
|
1263
|
+
// execution, so it stays `review`.
|
|
1264
|
+
if (tool === "preview_start") {
|
|
1265
|
+
return typeof toolInput.url === "string" && toolInput.name === undefined ? "safe" : "review";
|
|
1266
|
+
}
|
|
1267
|
+
if (tool === "computer" && SAFE_COMPUTER_ACTIONS.has(toolInput.action))
|
|
1268
|
+
return "safe";
|
|
1269
|
+
if (BROWSER_INTERACTION_TOOLS.has(tool)) {
|
|
1270
|
+
return server === "claude-in-chrome" ? "review" : "warning";
|
|
1271
|
+
}
|
|
1272
|
+
// A batch is as risky as its riskiest step.
|
|
1273
|
+
if (tool === "browser_batch") {
|
|
1274
|
+
const actions = toolInput.actions;
|
|
1275
|
+
if (!Array.isArray(actions) || actions.length === 0)
|
|
1276
|
+
return "review";
|
|
1277
|
+
let tier = "safe";
|
|
1278
|
+
for (const a of actions) {
|
|
1279
|
+
const name = a?.name;
|
|
1280
|
+
const input = a?.input;
|
|
1281
|
+
if (typeof name !== "string" || name === "browser_batch")
|
|
1282
|
+
return "review";
|
|
1283
|
+
tier = maxTier(tier, classifyBrowserTool(name, (input && typeof input === "object" ? input : {}), server));
|
|
1284
|
+
}
|
|
1285
|
+
return tier;
|
|
1286
|
+
}
|
|
1287
|
+
return "review";
|
|
1288
|
+
}
|
|
1289
|
+
function classifyMcpTool(toolName, toolInput = {}) {
|
|
1163
1290
|
const parts = toolName.split("__");
|
|
1164
1291
|
const tool = parts[parts.length - 1] || "";
|
|
1292
|
+
const browserServer = parts.slice(1, -1).find((p) => BROWSER_MCP_SERVERS.has(p));
|
|
1293
|
+
if (browserServer)
|
|
1294
|
+
return classifyBrowserTool(tool, toolInput, browserServer);
|
|
1165
1295
|
// Read-only retrieval verbs.
|
|
1166
1296
|
if (tool.startsWith("list_") || tool.startsWith("get_") || tool.startsWith("search_") ||
|
|
1167
1297
|
tool.startsWith("read_") || tool.startsWith("fetch_") || tool.startsWith("query_") ||
|
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 any decision that arrives without a valid receipt. 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":
|
|
@@ -102,13 +104,40 @@ function summarizeMutatingCurl(cmd) {
|
|
|
102
104
|
const url = cmd.match(/https?:\/\/[^\s'"]+/)?.[0] || "";
|
|
103
105
|
const host = url ? extractHost(url) : "URL";
|
|
104
106
|
const kind = method === "DELETE" ? "http_delete" : method === "PUT" ? "http_put" : "http_post";
|
|
107
|
+
// The endpoint path and the payload say what the request does; the raw
|
|
108
|
+
// command's head is often just setup (`SP=/long/scratch/path; (curl …`) and
|
|
109
|
+
// eats the whole preview before reaching either.
|
|
110
|
+
const endpoint = url ? extractPath(url) : undefined;
|
|
111
|
+
const payload = extractCurlPayload(cmd);
|
|
105
112
|
return {
|
|
106
113
|
title: `${method} request to ${host}`,
|
|
107
|
-
|
|
114
|
+
target: endpoint,
|
|
115
|
+
body: payload !== undefined
|
|
116
|
+
? truncateBody(payload)
|
|
117
|
+
: cmd.length > COMMAND_INLINE_MAX ? truncateBody(cmd) : undefined,
|
|
108
118
|
kind,
|
|
109
119
|
};
|
|
110
120
|
}
|
|
111
|
-
|
|
121
|
+
/** Path (+ query) of a URL, or undefined for a bare origin. */
|
|
122
|
+
function extractPath(url) {
|
|
123
|
+
try {
|
|
124
|
+
const u = new URL(url);
|
|
125
|
+
const p = u.pathname + u.search;
|
|
126
|
+
return p && p !== "/" ? truncate(p, 80) : undefined;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** The value of the first curl request-body flag (-d, --data*, --json, -F, --form). */
|
|
133
|
+
function extractCurlPayload(cmd) {
|
|
134
|
+
const m = cmd.match(/\s(?:-d|--data(?:-raw|-binary|-urlencode|-ascii)?|--json|-F|--form)(?:\s+|=)(?:'([^']*)'|"((?:[^"\\]|\\.)*)"|([^\s'"|;&]+))/);
|
|
135
|
+
if (!m)
|
|
136
|
+
return undefined;
|
|
137
|
+
const v = m[1] ?? m[2] ?? m[3];
|
|
138
|
+
return v ? v : undefined;
|
|
139
|
+
}
|
|
140
|
+
function summarizeBash(command, sizeBytes, cwd) {
|
|
112
141
|
const cmd = (command || "").trim();
|
|
113
142
|
if (!cmd)
|
|
114
143
|
return { title: "Run empty command", kind: "unknown_bash" };
|
|
@@ -127,6 +156,11 @@ function summarizeBash(command, sizeBytes) {
|
|
|
127
156
|
const mutatingCurl = summarizeMutatingCurl(cmd);
|
|
128
157
|
if (mutatingCurl)
|
|
129
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;
|
|
130
164
|
const shellWrite = summarizeShellWrite(cmd);
|
|
131
165
|
if (shellWrite)
|
|
132
166
|
return shellWrite;
|
|
@@ -263,8 +297,6 @@ function summarizeBash(command, sizeBytes) {
|
|
|
263
297
|
return { title: "Install npm dependencies", kind: "npm_install" };
|
|
264
298
|
if (/\bnpm\s+test\b/.test(cmd))
|
|
265
299
|
return { title: "Run npm tests", kind: "npm_test" };
|
|
266
|
-
if (/\bnpm\s+publish\b/.test(cmd))
|
|
267
|
-
return { title: "Publish package to npm", kind: "npm_publish" };
|
|
268
300
|
if (/\bnpm\s+unpublish\b/.test(cmd))
|
|
269
301
|
return { title: "Unpublish package from npm", kind: "npm_unpublish" };
|
|
270
302
|
if (/\bnpx\s+.*\s+deploy\b/.test(cmd))
|
|
@@ -284,6 +316,134 @@ function summarizeBash(command, sizeBytes) {
|
|
|
284
316
|
return { title: "Run command", body: truncateBody(cmd), kind: "unknown_bash" };
|
|
285
317
|
return { title: cmd, kind: "unknown_bash" };
|
|
286
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
|
+
}
|
|
287
447
|
function summarizeShellWrite(cmd) {
|
|
288
448
|
const ops = extractShellWriteOps(cmd);
|
|
289
449
|
if (!ops.length)
|
|
@@ -629,10 +789,78 @@ function summarizeAgent(input) {
|
|
|
629
789
|
const short = truncate(prompt, 80);
|
|
630
790
|
return { title: "Launch sub-agent", body: short, kind: "agent_launch" };
|
|
631
791
|
}
|
|
792
|
+
/**
|
|
793
|
+
* Built-in browser pane / Claude in Chrome. The tool names (`computer`,
|
|
794
|
+
* `javascript_tool`, …) say nothing on their own, so lead with what the step
|
|
795
|
+
* does and use the agent's own `action_summary` as the target when present.
|
|
796
|
+
*/
|
|
797
|
+
function summarizeBrowser(tool, input, server) {
|
|
798
|
+
const where = server === "claude-in-chrome" ? "in Chrome" : "in browser";
|
|
799
|
+
const str = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
|
|
800
|
+
const summary = str(input.action_summary);
|
|
801
|
+
switch (tool) {
|
|
802
|
+
case "navigate": {
|
|
803
|
+
const url = str(input.url);
|
|
804
|
+
return { title: `Open page ${where}`, target: url ? truncate(url, 80) : undefined, kind: "browser_navigate" };
|
|
805
|
+
}
|
|
806
|
+
case "preview_start": {
|
|
807
|
+
const url = str(input.url);
|
|
808
|
+
if (url)
|
|
809
|
+
return { title: `Open page ${where}`, target: truncate(url, 80), kind: "browser_navigate" };
|
|
810
|
+
const name = str(input.name);
|
|
811
|
+
return {
|
|
812
|
+
title: name ? `Start dev server "${truncate(name, 40)}"` : "Start dev server",
|
|
813
|
+
footnote: "Runs the command configured in .claude/launch.json",
|
|
814
|
+
kind: "browser_dev_server",
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
case "computer": {
|
|
818
|
+
const action = str(input.action) || "action";
|
|
819
|
+
const text = str(input.text);
|
|
820
|
+
return {
|
|
821
|
+
title: `${action.replace(/_/g, " ")} ${where}`.replace(/^./, (c) => c.toUpperCase()),
|
|
822
|
+
target: summary,
|
|
823
|
+
body: text ? truncateBody(text) : undefined,
|
|
824
|
+
kind: "browser_interact",
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
case "form_input": {
|
|
828
|
+
const value = input.value;
|
|
829
|
+
return {
|
|
830
|
+
title: `Fill form field ${where}`,
|
|
831
|
+
target: summary,
|
|
832
|
+
body: value !== undefined ? truncateBody(String(value)) : undefined,
|
|
833
|
+
kind: "browser_interact",
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
case "javascript_tool": {
|
|
837
|
+
const code = str(input.text);
|
|
838
|
+
return { title: `Run JavaScript ${where}`, body: code ? truncateBody(code) : undefined, kind: "browser_script" };
|
|
839
|
+
}
|
|
840
|
+
case "browser_batch": {
|
|
841
|
+
const actions = Array.isArray(input.actions) ? input.actions : [];
|
|
842
|
+
const steps = actions.map((a) => {
|
|
843
|
+
const name = str(a?.name) || "step";
|
|
844
|
+
const inp = (a?.input ?? {});
|
|
845
|
+
const r = summarizeBrowser(name, inp, server);
|
|
846
|
+
return r.target ? `${r.title}: ${r.target}` : r.title;
|
|
847
|
+
});
|
|
848
|
+
return {
|
|
849
|
+
title: `Run ${actions.length} browser step${actions.length === 1 ? "" : "s"}`,
|
|
850
|
+
body: steps.length ? truncateBody(steps.join("\n")) : undefined,
|
|
851
|
+
kind: "browser_interact",
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return { title: `${tool.replace(/_/g, " ")} ${where}`.replace(/^./, (c) => c.toUpperCase()), target: summary, kind: "unknown_tool" };
|
|
856
|
+
}
|
|
632
857
|
function summarizeMcp(toolName, input) {
|
|
633
858
|
const parts = toolName.split("__");
|
|
634
859
|
const server = parts[1] || "unknown";
|
|
635
860
|
const tool = parts[2] || "";
|
|
861
|
+
const browser = parts.slice(1, -1).find((p) => p === "Claude_Browser" || p === "claude-in-chrome");
|
|
862
|
+
if (browser)
|
|
863
|
+
return summarizeBrowser(parts[parts.length - 1] || "", input, browser);
|
|
636
864
|
if (tool === "send_email")
|
|
637
865
|
return summarizeEmail(input);
|
|
638
866
|
if (tool === "send_message")
|
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
|
@@ -1,8 +1,22 @@
|
|
|
1
1
|
import type { ApprovalRequest, ApprovalResponse, OKedConfig } from "./types.js";
|
|
2
2
|
import type { Rule } from "./rules.js";
|
|
3
|
+
/**
|
|
4
|
+
* How long we wait for a human decision before giving up on the request.
|
|
5
|
+
*
|
|
6
|
+
* Sized for a human who has to be woken up (an oncall paged at 3am), not for a
|
|
7
|
+
* developer watching the terminal. Integrations that run under a harness which
|
|
8
|
+
* kills the hook process must set their own limit ABOVE this one, so our
|
|
9
|
+
* fail-safe deny is written before the harness pulls the plug. See
|
|
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).
|
|
14
|
+
*/
|
|
15
|
+
export declare const DEFAULT_APPROVAL_TIMEOUT_MS = 630000;
|
|
3
16
|
export declare class OKedClient {
|
|
4
17
|
private config;
|
|
5
18
|
constructor(config?: Partial<OKedConfig>);
|
|
19
|
+
get requireReceipt(): boolean;
|
|
6
20
|
get strictFailClosed(): boolean;
|
|
7
21
|
get apiKey(): string;
|
|
8
22
|
get backendUrl(): string;
|
|
@@ -27,7 +41,10 @@ export declare class OKedClient {
|
|
|
27
41
|
*/
|
|
28
42
|
heartbeat(): Promise<void>;
|
|
29
43
|
}
|
|
30
|
-
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";
|
|
31
48
|
export { TIER_ORDER, degradedDecision } from "./degraded.js";
|
|
32
49
|
export { classify } from "./classify.js";
|
|
33
50
|
export { describe, describeFields } from "./describe.js";
|
|
@@ -36,6 +53,6 @@ export type { Rule, RuleMatch, RuleAction, RuleDecision, FieldOp, } from "./rule
|
|
|
36
53
|
export type { Rendered } from "./describe.js";
|
|
37
54
|
export { CLASSIFIER_VERSION } from "./kinds.js";
|
|
38
55
|
export type { OperationKind } from "./kinds.js";
|
|
39
|
-
export { loadOKedConfig, OKED_CONFIG_PATH } from "./config.js";
|
|
56
|
+
export { loadOKedConfig, OKED_CONFIG_PATH, OKED_RECEIPT_KEYS_PATH } from "./config.js";
|
|
40
57
|
export type { PersistedConfig } from "./config.js";
|
|
41
58
|
export type { RiskTier, ApprovalRequest, ApprovalResponse, OKedConfig, HookInput, HookOutput, } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,22 @@ 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";
|
|
8
|
+
/**
|
|
9
|
+
* How long we wait for a human decision before giving up on the request.
|
|
10
|
+
*
|
|
11
|
+
* Sized for a human who has to be woken up (an oncall paged at 3am), not for a
|
|
12
|
+
* developer watching the terminal. Integrations that run under a harness which
|
|
13
|
+
* kills the hook process must set their own limit ABOVE this one, so our
|
|
14
|
+
* fail-safe deny is written before the harness pulls the plug. See
|
|
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).
|
|
19
|
+
*/
|
|
20
|
+
export const DEFAULT_APPROVAL_TIMEOUT_MS = 630_000;
|
|
6
21
|
function envStrictFailClosed() {
|
|
7
22
|
const raw = process.env.OKED_STRICT_FAIL_CLOSED;
|
|
8
23
|
if (raw === undefined)
|
|
@@ -16,6 +31,12 @@ function envRulesCacheTtlMs() {
|
|
|
16
31
|
const n = Number(raw);
|
|
17
32
|
return Number.isFinite(n) && n >= 0 ? n * 1000 : undefined;
|
|
18
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
|
+
}
|
|
19
40
|
function envHeartbeatIntervalMs() {
|
|
20
41
|
const raw = process.env.OKED_HEARTBEAT_INTERVAL; // seconds
|
|
21
42
|
if (raw === undefined)
|
|
@@ -78,7 +99,7 @@ export class OKedClient {
|
|
|
78
99
|
process.env.OKED_BACKEND_URL ||
|
|
79
100
|
persisted.backendUrl ||
|
|
80
101
|
"https://api.oked.ai",
|
|
81
|
-
timeout: config?.timeout ||
|
|
102
|
+
timeout: config?.timeout || DEFAULT_APPROVAL_TIMEOUT_MS,
|
|
82
103
|
// Precedence: constructor > env > ~/.oked/config.json > default false.
|
|
83
104
|
strictFailClosed: config?.strictFailClosed ??
|
|
84
105
|
envStrictFailClosed() ??
|
|
@@ -96,8 +117,19 @@ export class OKedClient {
|
|
|
96
117
|
? persisted.heartbeatIntervalSeconds * 1000
|
|
97
118
|
: undefined) ??
|
|
98
119
|
86_400_000,
|
|
120
|
+
requireReceipt: config?.requireReceipt ?? envRequireReceipt() ?? persisted.requireReceipt ?? false,
|
|
121
|
+
receiptKeysUrl: config?.receiptKeysUrl ||
|
|
122
|
+
process.env.OKED_RECEIPT_KEYS_URL ||
|
|
123
|
+
persisted.receiptKeysUrl ||
|
|
124
|
+
OKED_RECEIPT_KEYS_URL,
|
|
125
|
+
receiptKeys: config?.receiptKeys,
|
|
126
|
+
client: config?.client,
|
|
127
|
+
source: config?.source,
|
|
99
128
|
};
|
|
100
129
|
}
|
|
130
|
+
get requireReceipt() {
|
|
131
|
+
return this.config.requireReceipt;
|
|
132
|
+
}
|
|
101
133
|
get strictFailClosed() {
|
|
102
134
|
return this.config.strictFailClosed;
|
|
103
135
|
}
|
|
@@ -109,6 +141,10 @@ export class OKedClient {
|
|
|
109
141
|
}
|
|
110
142
|
async approve(request) {
|
|
111
143
|
const signal = AbortSignal.timeout(this.config.timeout);
|
|
144
|
+
// A fresh nonce per request goes into the receipt's subject, so a receipt
|
|
145
|
+
// for an earlier, identical action can never be replayed for this one.
|
|
146
|
+
const nonce = randomUUID();
|
|
147
|
+
const source = this.config.source || "sdk";
|
|
112
148
|
const doFetch = () => fetch(`${this.config.backendUrl}/api/v1/approve`, {
|
|
113
149
|
method: "POST",
|
|
114
150
|
headers: {
|
|
@@ -120,10 +156,13 @@ export class OKedClient {
|
|
|
120
156
|
description: request.description,
|
|
121
157
|
tier: request.tier,
|
|
122
158
|
fields: request.fields,
|
|
159
|
+
nonce,
|
|
160
|
+
client: this.config.client,
|
|
123
161
|
metadata: {
|
|
124
162
|
tool_input: request.tool_input,
|
|
125
163
|
session_id: request.session_id,
|
|
126
164
|
cwd: request.cwd,
|
|
165
|
+
source: this.config.source,
|
|
127
166
|
},
|
|
128
167
|
}),
|
|
129
168
|
signal,
|
|
@@ -144,9 +183,13 @@ export class OKedClient {
|
|
|
144
183
|
}
|
|
145
184
|
}
|
|
146
185
|
catch (err) {
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
186
|
+
// The backend accepted the request and then held it past a timer: no
|
|
187
|
+
// human decided in time. That is a timeout (deny), not an outage, so it
|
|
188
|
+
// must never fall through to degraded-mode allow.
|
|
189
|
+
if (isHeldRequestTimeout(err))
|
|
190
|
+
return HELD_TIMEOUT;
|
|
191
|
+
// Connect failure: we never reached the backend -> treat as an outage
|
|
192
|
+
// so degraded-mode can apply.
|
|
150
193
|
throw new OKedBackendUnreachableError(err instanceof Error ? `OKed backend unreachable: ${err.message}` : "OKed backend unreachable", err);
|
|
151
194
|
}
|
|
152
195
|
if (!res.ok) {
|
|
@@ -154,16 +197,37 @@ export class OKedClient {
|
|
|
154
197
|
if (res.status === 401 || res.status === 403) {
|
|
155
198
|
throw new OKedAuthError(`OKed backend error ${res.status}: ${body}`, res.status);
|
|
156
199
|
}
|
|
200
|
+
// A gateway that gave up waiting on a held long-poll: same as above.
|
|
201
|
+
if (res.status === 504)
|
|
202
|
+
return HELD_TIMEOUT;
|
|
157
203
|
if (res.status >= 500) {
|
|
158
204
|
throw new OKedBackendUnreachableError(`OKed backend error ${res.status}: ${body}`);
|
|
159
205
|
}
|
|
160
206
|
throw new Error(`OKed backend error ${res.status}: ${body}`);
|
|
161
207
|
}
|
|
162
|
-
|
|
208
|
+
let result;
|
|
209
|
+
try {
|
|
210
|
+
// The backend sends headers at once and streams whitespace heartbeats
|
|
211
|
+
// while it waits, so the wait for a human happens here, in the body.
|
|
212
|
+
result = (await res.json());
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
if (isHeldRequestTimeout(err))
|
|
216
|
+
return HELD_TIMEOUT;
|
|
217
|
+
throw err;
|
|
218
|
+
}
|
|
219
|
+
// Nobody acts on a decision we cannot prove: an invalid receipt throws
|
|
220
|
+
// OKedReceiptError (every integration denies), and so does a missing one
|
|
221
|
+
// when requireReceipt is on.
|
|
222
|
+
const receipt = await checkReceipt(result, { action: request.action, description: request.description, toolInput: request.tool_input, source, nonce }, {
|
|
223
|
+
required: this.config.requireReceipt,
|
|
224
|
+
trust: { keys: this.config.receiptKeys, keysUrl: this.config.receiptKeysUrl },
|
|
225
|
+
});
|
|
163
226
|
return {
|
|
164
227
|
approved: result.decision === "approved",
|
|
165
228
|
approval_id: result.approval_id,
|
|
166
229
|
decision: result.decision,
|
|
230
|
+
...(receipt ? { receipt } : {}),
|
|
167
231
|
};
|
|
168
232
|
}
|
|
169
233
|
/**
|
|
@@ -247,6 +311,22 @@ export class OKedClient {
|
|
|
247
311
|
}
|
|
248
312
|
}
|
|
249
313
|
}
|
|
314
|
+
const HELD_TIMEOUT = { approved: false, approval_id: null, decision: "timeout" };
|
|
315
|
+
/**
|
|
316
|
+
* True when a request reached the backend and then sat past a timer: our own
|
|
317
|
+
* abort (TimeoutError), or undici's 300s headers/body timeouts, which fire
|
|
318
|
+
* regardless of the abort signal on a silent long-poll.
|
|
319
|
+
*/
|
|
320
|
+
function isHeldRequestTimeout(err) {
|
|
321
|
+
if (!err || typeof err !== "object")
|
|
322
|
+
return false;
|
|
323
|
+
// AbortSignal.timeout() rejects with a DOMException, which is not an Error
|
|
324
|
+
// instance on every Node version, so match on the name alone.
|
|
325
|
+
if (err.name === "TimeoutError")
|
|
326
|
+
return true;
|
|
327
|
+
const code = err.cause?.code ?? err.code;
|
|
328
|
+
return code === "UND_ERR_HEADERS_TIMEOUT" || code === "UND_ERR_BODY_TIMEOUT";
|
|
329
|
+
}
|
|
250
330
|
function isRetriableConnectError(err) {
|
|
251
331
|
if (!(err instanceof Error))
|
|
252
332
|
return false;
|
|
@@ -259,10 +339,13 @@ function isRetriableConnectError(err) {
|
|
|
259
339
|
code === "ETIMEDOUT" ||
|
|
260
340
|
code === "UND_ERR_CONNECT_TIMEOUT");
|
|
261
341
|
}
|
|
262
|
-
export { OKedAuthError, OKedBackendUnreachableError } from "./errors.js";
|
|
342
|
+
export { OKedAuthError, OKedBackendUnreachableError, OKedReceiptError } from "./errors.js";
|
|
343
|
+
export { checkReceipt, keysFor, keysUrlAllowed, OKED_RECEIPT_KEYS_URL } from "./receipt.js";
|
|
344
|
+
export { PINNED_RECEIPT_KEYS } from "./receipt-keys.js";
|
|
345
|
+
export { verifyReceipt, verifyChain, shortReceiptId, } from "@oked/receipt-core";
|
|
263
346
|
export { TIER_ORDER, degradedDecision } from "./degraded.js";
|
|
264
347
|
export { classify } from "./classify.js";
|
|
265
348
|
export { describe, describeFields } from "./describe.js";
|
|
266
349
|
export { applyRules } from "./rules.js";
|
|
267
350
|
export { CLASSIFIER_VERSION } from "./kinds.js";
|
|
268
|
-
export { loadOKedConfig, OKED_CONFIG_PATH } from "./config.js";
|
|
351
|
+
export { loadOKedConfig, OKED_CONFIG_PATH, OKED_RECEIPT_KEYS_PATH } from "./config.js";
|
package/dist/kinds.d.ts
CHANGED
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
* classifier that produced them.
|
|
8
8
|
*/
|
|
9
9
|
export declare const CLASSIFIER_VERSION = "v2";
|
|
10
|
-
export type OperationKind = "file_create" | "file_append" | "file_edit" | "file_touch" | "file_copy" | "file_move" | "file_delete" | "sql_drop" | "sql_truncate" | "sql_alter" | "sql_create" | "sql_delete_rows" | "sql_delete_all_rows" | "sql_update_rows" | "sql_update_every_row" | "sql_insert" | "sql_query" | "git_push" | "git_force_push" | "git_reset_hard" | "git_clean" | "git_checkout" | "git_restore" | "git_commit" | "git_pr_create" | "ssh_remote" | "http_get" | "http_post" | "http_put" | "http_delete" | "http_pipe_to_shell" | "docker_up" | "docker_down" | "docker_rm" | "docker_rmi" | "docker_prune" | "npm_install" | "npm_run" | "npm_test" | "npm_publish" | "npm_unpublish" | "npx_deploy" | "kill_process" | "sudo" | "chmod_777" | "email_send" | "email_delete" | "email_purge" | "payment_charge" | "payment_create" | "chat_message" | "mcp_delete" | "mcp_update" | "mcp_create" | "mcp_post" | "mcp_publish" | "mcp_send" | "mcp_submit_form" | "mcp_fill" | "mcp_submit" | "mcp_query" | "agent_launch" | "shell_pipeline" | "unknown_bash" | "unknown_tool";
|
|
10
|
+
export type OperationKind = "file_create" | "file_append" | "file_edit" | "file_touch" | "file_copy" | "file_move" | "file_delete" | "sql_drop" | "sql_truncate" | "sql_alter" | "sql_create" | "sql_delete_rows" | "sql_delete_all_rows" | "sql_update_rows" | "sql_update_every_row" | "sql_insert" | "sql_query" | "git_push" | "git_force_push" | "git_reset_hard" | "git_clean" | "git_checkout" | "git_restore" | "git_commit" | "git_pr_create" | "ssh_remote" | "http_get" | "http_post" | "http_put" | "http_delete" | "http_pipe_to_shell" | "docker_up" | "docker_down" | "docker_rm" | "docker_rmi" | "docker_prune" | "npm_install" | "npm_run" | "npm_test" | "npm_publish" | "npm_unpublish" | "npx_deploy" | "kill_process" | "sudo" | "chmod_777" | "email_send" | "email_delete" | "email_purge" | "payment_charge" | "payment_create" | "chat_message" | "mcp_delete" | "mcp_update" | "mcp_create" | "mcp_post" | "mcp_publish" | "mcp_send" | "mcp_submit_form" | "mcp_fill" | "mcp_submit" | "mcp_query" | "browser_navigate" | "browser_interact" | "browser_script" | "browser_dev_server" | "agent_launch" | "shell_pipeline" | "unknown_bash" | "unknown_tool";
|
|
@@ -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,37 @@
|
|
|
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 when `required`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function checkReceipt(result: {
|
|
30
|
+
approval_id: string | null;
|
|
31
|
+
decision: string;
|
|
32
|
+
receipt?: unknown;
|
|
33
|
+
}, sent: SentRequest, opts: {
|
|
34
|
+
required: boolean;
|
|
35
|
+
trust: ReceiptTrust;
|
|
36
|
+
}): Promise<SignedReceipt | undefined>;
|
|
37
|
+
export { OKED_RECEIPT_KEYS_URL };
|
package/dist/receipt.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
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 when `required`.
|
|
72
|
+
*/
|
|
73
|
+
export async function checkReceipt(result, sent, opts) {
|
|
74
|
+
if (result.receipt === undefined || result.receipt === null) {
|
|
75
|
+
if (opts.required)
|
|
76
|
+
throw new OKedReceiptError("missing", ["missing"]);
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
const receipt = result.receipt;
|
|
80
|
+
const kid = typeof receipt?.kid === "string" ? receipt.kid : "";
|
|
81
|
+
const body = receipt?.body;
|
|
82
|
+
if (!body || typeof body !== "object")
|
|
83
|
+
throw new OKedReceiptError("malformed", ["malformed"]);
|
|
84
|
+
const subject = {
|
|
85
|
+
type: "tool_call",
|
|
86
|
+
operator_id: body.operator_id ?? null,
|
|
87
|
+
request_id: result.approval_id ?? "",
|
|
88
|
+
source: sent.source,
|
|
89
|
+
action: sent.action,
|
|
90
|
+
description: jsonValue(sent.description),
|
|
91
|
+
tool_input: jsonValue(sent.toolInput),
|
|
92
|
+
client_nonce: sent.nonce,
|
|
93
|
+
};
|
|
94
|
+
const check = verifyReceipt(receipt, { keys: await keysFor(kid, opts.trust), subject });
|
|
95
|
+
const problems = [...check.problems];
|
|
96
|
+
if (body.request_id !== result.approval_id)
|
|
97
|
+
problems.push("request_mismatch");
|
|
98
|
+
if (typeof body.decision !== "string" || responseDecision(body.decision) !== result.decision) {
|
|
99
|
+
problems.push("decision_mismatch");
|
|
100
|
+
}
|
|
101
|
+
if (problems.length > 0)
|
|
102
|
+
throw new OKedReceiptError(problems.join(", "), problems);
|
|
103
|
+
return receipt;
|
|
104
|
+
}
|
|
105
|
+
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,12 +11,31 @@ 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
|
+
* only when the backend sent none and requireReceipt is off, or when the
|
|
21
|
+
* request timed out on our side.
|
|
22
|
+
*/
|
|
23
|
+
receipt?: SignedReceipt;
|
|
15
24
|
}
|
|
16
25
|
export interface OKedConfig {
|
|
17
26
|
apiKey: string;
|
|
18
27
|
backendUrl: string;
|
|
28
|
+
/**
|
|
29
|
+
* How long to wait for a human decision, in ms. Default 630_000 (10.5 min);
|
|
30
|
+
* see DEFAULT_APPROVAL_TIMEOUT_MS.
|
|
31
|
+
*
|
|
32
|
+
* Three timers nest around one approval: the backend's own expiry (which
|
|
33
|
+
* returns `decision: "timeout"`), this client-side abort, and - under a
|
|
34
|
+
* harness that kills the hook process - the harness limit. They must stay
|
|
35
|
+
* ordered backend < this < harness. Raise this and the harness limit has to
|
|
36
|
+
* move with it, or the process is killed before the fail-safe deny is
|
|
37
|
+
* written and the gate falls open instead of denying.
|
|
38
|
+
*/
|
|
19
39
|
timeout: number;
|
|
20
40
|
/**
|
|
21
41
|
* When true, an unreachable backend hard-denies every sensitive action
|
|
@@ -40,6 +60,25 @@ export interface OKedConfig {
|
|
|
40
60
|
* Default 86_400_000 (once per day).
|
|
41
61
|
*/
|
|
42
62
|
heartbeatIntervalMs: number;
|
|
63
|
+
/**
|
|
64
|
+
* Deny any decision that arrives without a valid receipt. A receipt that is
|
|
65
|
+
* present but does not verify always denies, whatever this says. Default
|
|
66
|
+
* false in 0.5.0, true from 0.6.0. Env OKED_REQUIRE_RECEIPT=1.
|
|
67
|
+
*/
|
|
68
|
+
requireReceipt: boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Where to fetch receipt keys the SDK has not seen. Default OKed's published
|
|
71
|
+
* set (https://api.oked.ai/.well-known/oked-receipt-keys.json), independent
|
|
72
|
+
* of backendUrl. https only, except loopback for local dev. Env
|
|
73
|
+
* OKED_RECEIPT_KEYS_URL.
|
|
74
|
+
*/
|
|
75
|
+
receiptKeysUrl: string;
|
|
76
|
+
/** Verify with exactly these keys and never fetch (tests, self-hosted backends). */
|
|
77
|
+
receiptKeys?: ReceiptKey[];
|
|
78
|
+
/** The integration asking, e.g. "@oked/claude-code@0.5.0". Recorded in receipts. */
|
|
79
|
+
client?: string;
|
|
80
|
+
/** Where the request comes from, e.g. "claude-code". Part of the receipt's subject. Default "sdk". */
|
|
81
|
+
source?: string;
|
|
43
82
|
}
|
|
44
83
|
export interface HookInput {
|
|
45
84
|
session_id: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oked/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.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.5.0"
|
|
49
|
+
},
|
|
46
50
|
"devDependencies": {
|
|
47
51
|
"@types/node": "^22.13.10",
|
|
48
52
|
"tsx": "^4.22.0",
|