@oked/claude-code 0.6.20 → 0.6.22
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 +54 -33
- package/dist/cli.js +27 -209
- package/dist/hook-config.d.ts +3 -1
- package/dist/hook-config.js +3 -2
- package/dist/hook.js +29 -153
- package/dist/qr.d.ts +1 -7
- package/dist/qr.js +1 -332
- package/package.json +5 -4
- package/dist/hook-log.d.ts +0 -30
- package/dist/hook-log.js +0 -39
- package/dist/receipts.d.ts +0 -23
- package/dist/receipts.js +0 -52
package/README.md
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
# @oked/claude-code
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@oked/claude-code)
|
|
4
|
-
[](./LICENSE)
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
Claude Code hook. Sensitive actions wait for a person in Telegram or on the [web dashboard](https://oked.ai/dashboard) before Claude Code continues. The iPhone app is coming soon.
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
The gate itself is [`@oked/hook-core`](../hook-core) (`decide()`): classify, wait, check the signed receipt, fail closed. This package still reads Claude's stdin and writes Claude's `hookSpecificOutput`. Behavior is unchanged. An unpaired device returns `ask`. An allow is an explicit `permissionDecision`. `oked init` still writes the same hook entry, including the 690 second timeout.
|
|
9
|
+
|
|
10
|
+
Safe actions are allowed by the hook, with no notification. Warning actions are allowed and logged. OKed asks only for `review` and `high_stakes`.
|
|
9
11
|
|
|
10
12
|
## Install
|
|
11
13
|
|
|
@@ -14,66 +16,85 @@ npm install -g @oked/claude-code
|
|
|
14
16
|
oked init
|
|
15
17
|
```
|
|
16
18
|
|
|
17
|
-
`oked init` writes a `PreToolUse` hook
|
|
19
|
+
`oked init` writes a `PreToolUse` hook into the current project's `.claude/settings.json`, opens the device-pairing page in your browser, and stores the API key in `~/.oked/config.json`. Open a new Claude Code session in that project.
|
|
20
|
+
|
|
21
|
+
On a TTY, unless `NO_COLOR` is set, init also prints a QR code of the pairing link. The QR opens that link in the phone's browser.
|
|
22
|
+
|
|
23
|
+
The approval window is 10 minutes. The hook process is allowed 690 seconds, and the SDK client waits 630 seconds, so a timeout becomes a deny instead of Claude killing the hook first.
|
|
18
24
|
|
|
19
25
|
## Commands
|
|
20
26
|
|
|
21
27
|
| Command | What it does |
|
|
22
28
|
|---|---|
|
|
23
|
-
| `oked init` | Install or update the project hook and pair this device. It also updates an existing `oked-hook` entry in
|
|
24
|
-
| `oked init --key-only` |
|
|
25
|
-
| `oked init --no-browser` | Print the pairing link
|
|
26
|
-
| `oked
|
|
27
|
-
| `oked
|
|
28
|
-
| `oked
|
|
29
|
+
| `oked init` | Install or update the project hook and pair this device. It also updates an existing `oked-hook` entry in user settings (`~/.claude/settings.json`), for example to raise an old timeout. Run it again after you update the package. |
|
|
30
|
+
| `oked init --key-only` | Create or show the API key in `~/.oked/config.json`. It does not add or change a hook. Use it for tools that only need the key, such as the [OpenShell](https://github.com/oked-ai/oked-openshell) middleware. The paired client type is `sdk`. |
|
|
31
|
+
| `oked init --no-browser` | Print the pairing link. Do not open a browser, and do not touch the clipboard. Works with `--key-only`. |
|
|
32
|
+
| `oked init --yes` (or `-y`) | Skip the "press Enter to open the browser" prompt. For a non-interactive shell. |
|
|
33
|
+
| `oked status` | Show install state and ping `GET /health` on the backend. |
|
|
34
|
+
| `oked receipts verify [file]` | Check this machine's receipts (default `~/.oked/receipts.jsonl`): every signature, and the chain links between neighbouring receipts. |
|
|
35
|
+
| `oked uninstall` | Remove the project hook entry. Other hooks are kept. |
|
|
29
36
|
|
|
30
37
|
## What gets intercepted
|
|
31
38
|
|
|
32
|
-
The hook uses a four-tier classifier. Classification is
|
|
33
|
-
detects the *kind of effect* an action has rather than matching specific command
|
|
34
|
-
names, and **defaults to no prompt**. Only destructive, irreversible, or
|
|
35
|
-
outward-facing operations put a human in the loop.
|
|
39
|
+
The hook uses a four-tier classifier. Classification is effect-based: it detects the kind of effect, not a list of command names, and it defaults to no prompt. Only destructive, irreversible, or outward-facing operations ask a person.
|
|
36
40
|
|
|
37
41
|
| Tier | Behavior | Examples |
|
|
38
42
|
|---|---|---|
|
|
39
|
-
| `safe` |
|
|
40
|
-
| `warning` | Terminal log only, no
|
|
41
|
-
| `review` |
|
|
42
|
-
| `high_stakes` |
|
|
43
|
+
| `safe` | Allow, no notification | Reads and queries, a DB `SELECT`, and any Bash command with no detected side effect: `ls`, `grep`, `jq`, plain `curl` GET. Test runners and script files are included only when the Bash sandbox is containing child processes (see below). |
|
|
44
|
+
| `warning` | Terminal log only, no approval | A reversible local change (file create, `cp`, `mv`, a `/tmp` delete, local git `add`/`commit`, `npm install`, SQL `INSERT` or `CREATE`), plus a plain `git push` |
|
|
45
|
+
| `review` | Wait for approval | Sensitive-path writes (`~/.ssh`, shell rc, system dirs, OKed config), `sudo`, outward message or email sends, `curl` POST/PUT/PATCH with an inline body, other cloud CLI writes (`aws s3 cp` to a bucket, `kubectl apply`, `helm upgrade`, a preview deploy), MCP tools named `create_*`, `send_*`, or `update_*` |
|
|
46
|
+
| `high_stakes` | Wait for approval, with confirmation | Destructive or hard to undo: `rm` of non-temp data, `DROP TABLE` or `DELETE FROM`, a force push (`git push --force`, `-f`, or `--force-with-lease`), a remote branch delete (`git push --delete`, `-d`, or `git push origin :branch`), `reset --hard`, `branch -D`, `mkfs`, `dd` to a device, `shutdown`, `curl` DELETE, file upload, pay or send APIs, `ssh` / `scp`, `npm publish`, `kill`, cloud and cluster deletes (`aws s3 rm`, `kubectl delete`), `terraform apply` / `destroy`, production deploys (`vercel --prod`, `fly deploy`), Stripe CLI writes |
|
|
47
|
+
|
|
48
|
+
A Bash command that matches none of those effect categories defaults to `safe`. Cloud CLI reads (`aws s3 ls`, `kubectl get`, `terraform plan`), `--help`, and dry runs are `safe`. Running a command is not, by itself, a reason to interrupt you. Unknown tools that are not Bash default to `review`. MCP tools named `delete_*`, `drop_*`, or `remove_*` are `high_stakes`.
|
|
49
|
+
|
|
50
|
+
### Test runners and scripts
|
|
51
|
+
|
|
52
|
+
`cargo test`, `npm test`, `npm run <script>`, `pnpm` / `yarn` test and scripts, `pytest`, `go test`, `make <target>`, `./script.sh`, `bash script.sh`, `node scripts/x.mjs`, and `npx <tool>` run code the hook never sees. A child process can delete files without a second tool call. When the Bash sandbox is not containing those processes, OKed asks (`review`) before the runner. `ls`, `git status`, `git commit`, and `npm install` are unchanged. `node -e` and `python -c` stay `safe`, because the body is in the command string.
|
|
43
53
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
54
|
+
The sandbox contains them when `sandbox.enabled` is true and `allowUnsandboxedCommands` is false. Child processes are then limited to the working directory, and OKed allows the runner with no prompt. `oked init` prints this when that is not already set. Put it in `~/.claude/settings.json` or `.claude/settings.local.json`:
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{ "sandbox": { "enabled": true, "allowUnsandboxedCommands": false } }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The hook also reads the project `.claude/settings.json`. A `false` for `allowUnsandboxedCommands` in `~/.claude/settings.json` holds against a project `true`, matching Claude Code. `sandbox.filesystem.disabled: true` in user settings turns filesystem isolation off, so the runner still asks. An entry in `sandbox.excludedCommands` that covers the command runs outside the sandbox, so that command still asks. The approval card footnote repeats how to turn the prompts off.
|
|
47
61
|
|
|
48
62
|
## How it works
|
|
49
63
|
|
|
50
|
-
1. Claude Code
|
|
51
|
-
2. The hook classifies the action locally
|
|
52
|
-
3.
|
|
53
|
-
4. You
|
|
54
|
-
5. Approve or
|
|
64
|
+
1. Claude Code runs the `PreToolUse` hook (`oked-hook`) before the tool call. The hook is a separate process.
|
|
65
|
+
2. The hook classifies the action locally. `safe` and `warning` do not wait on the network, unless a cached user rule matches and the action has to be sent to the backend.
|
|
66
|
+
3. For `review` and `high_stakes`, it sends an approval request.
|
|
67
|
+
4. You decide in Telegram or on the web dashboard. Web push is optional.
|
|
68
|
+
5. Approve, and Claude continues. Deny or time out, and the tool call is denied.
|
|
69
|
+
|
|
70
|
+
If this device is not paired, the hook returns `ask`, so Claude Code's own permission prompt can decide.
|
|
55
71
|
|
|
56
72
|
## Environment
|
|
57
73
|
|
|
58
74
|
| Var | Required | Description |
|
|
59
75
|
|---|---|---|
|
|
60
|
-
| `OKED_API_KEY` | no, after pairing | Optional override. `oked init`
|
|
61
|
-
| `
|
|
62
|
-
| `
|
|
76
|
+
| `OKED_API_KEY` | no, after pairing | Optional override. `oked init` stores the paired key in `~/.oked/config.json`. |
|
|
77
|
+
| `OKED_STRICT_FAIL_CLOSED` | no | `1` or `true` denies every sensitive action when the backend is unreachable. |
|
|
78
|
+
| `OKED_REQUIRE_RECEIPT` | no | `0` allows an approval with no receipt. On by default since 0.6.0. |
|
|
79
|
+
| `OKED_HOOK_LOG` | no | Decision log path. Default `~/.oked/hook.log`. |
|
|
63
80
|
|
|
64
81
|
## Receipts
|
|
65
82
|
|
|
66
|
-
Every decision comes with a receipt signed by OKed (who decided, how they were verified, the exact command, when). The hook verifies it before allowing the action, shows its short id (`Approved via OKed (receipt rcpt_7Q2FABCD)`), and keeps
|
|
83
|
+
Every decision comes with a receipt signed by OKed (who decided, how they were verified, the exact command, when). The hook verifies it before allowing the action, shows its short id (`Approved via OKed (receipt rcpt_7Q2FABCD)`), and keeps a copy in `~/.oked/receipts.jsonl`. Check that file with `oked receipts verify`. Since 0.6.0 the hook denies an approval that has no valid receipt. Set `OKED_REQUIRE_RECEIPT=0` only for a backend that does not sign receipts.
|
|
84
|
+
|
|
85
|
+
You can also paste one receipt at [oked.ai/docs/#verify](https://oked.ai/docs#verify), or check an export with `npx @oked/verify`. See [docs/receipts.md](../../docs/receipts.md). Questions: [contact@oked.ai](mailto:contact@oked.ai).
|
|
67
86
|
|
|
68
87
|
## Degraded-mode behavior
|
|
69
88
|
|
|
70
|
-
Explicit denials, invalid API keys and
|
|
89
|
+
Explicit denials, invalid API keys, and receipts that do not verify deny the action. If the backend is unreachable, OKed denies `high_stakes` and, by default, allows lower tiers, so a short outage does not stop every workflow. Set `OKED_STRICT_FAIL_CLOSED=1` to deny every sensitive action during an outage.
|
|
90
|
+
|
|
91
|
+
The backend counts as unreachable when the connection fails, when it answers with HTTP 5xx, when the hosting platform answers in its place (for example Railway "Application not found"), or when the reply is not JSON. "Too many pending approvals" (HTTP 429) is not an outage: the hook denies the action and asks you to decide the waiting approvals first. Deny reasons include the error and its HTTP status.
|
|
71
92
|
|
|
72
|
-
|
|
93
|
+
If the hook cannot parse its stdin, it allows the call, so a bad payload does not crash Claude. Every other unexpected error denies.
|
|
73
94
|
|
|
74
95
|
## Decision log
|
|
75
96
|
|
|
76
|
-
The hook writes one JSON line to `~/.oked/hook.log` (mode 600) for each deny and ask, and for each degraded allow (`"degraded": true`: an action that ran without a person's decision because the backend was unreachable). Each line has the time, decision, tool, tier, reason, approval
|
|
97
|
+
The hook writes one JSON line to `~/.oked/hook.log` (mode 600) for each deny and ask, and for each degraded allow (`"degraded": true`: an action that ran without a person's decision because the backend was unreachable). Each line has the time, decision, tool, tier, reason, client, approval id, receipt id, and error (name, message, HTTP status). The log never holds the tool input or the command. Above 1 MB, the file moves to `hook.log.1`. Set `OKED_HOOK_LOG` to use another path.
|
|
77
98
|
|
|
78
99
|
## License
|
|
79
100
|
|
package/dist/cli.js
CHANGED
|
@@ -1,23 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { createInterface } from "readline";
|
|
7
|
-
import { OKedClient, loadOKedConfig, OKED_CONFIG_PATH } from "@oked/sdk";
|
|
2
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
|
|
3
|
+
import { join } from "path";
|
|
4
|
+
import { OKedClient, OKED_CONFIG_PATH } from "@oked/sdk";
|
|
5
|
+
import { claudeSandboxEnforced, maskKey, OKED_RECEIPTS_LOG, pairDevice, SANDBOX_INIT_HINT, verifyReceiptsFile, writeOkedConfig, } from "@oked/hook-core";
|
|
8
6
|
import { HOOK_CONFIG, hasOkedCommandHook, ensureMcpMatcher, ensureHookTimeout, upgradeSettingsFile, userSettingsPath, } from "./hook-config.js";
|
|
9
7
|
import { CLIENT_VERSION } from "./version.js";
|
|
10
|
-
import { OKED_RECEIPTS_LOG, verifyReceiptsFile } from "./receipts.js";
|
|
11
|
-
import { renderQR } from "./qr.js";
|
|
12
8
|
const DEFAULT_BACKEND_URL = process.env.OKED_BACKEND_URL || "https://api.oked.ai";
|
|
13
9
|
/** `oked init --key-only`: create or show the API key; add or change no hook. */
|
|
14
10
|
const KEY_ONLY = process.argv.includes("--key-only");
|
|
15
11
|
/** `oked init --no-browser`: print the pairing link; open no browser, use no clipboard. */
|
|
16
12
|
const NO_BROWSER = process.argv.includes("--no-browser");
|
|
17
|
-
/** The first 8 characters, never the whole key. */
|
|
18
|
-
function maskKey(key) {
|
|
19
|
-
return `${key.slice(0, 8)}...`;
|
|
20
|
-
}
|
|
21
13
|
function getSettingsPath() {
|
|
22
14
|
return join(process.cwd(), ".claude", "settings.json");
|
|
23
15
|
}
|
|
@@ -37,201 +29,13 @@ function writeSettings(path, settings) {
|
|
|
37
29
|
mkdirSync(dir, { recursive: true });
|
|
38
30
|
writeFileSync(path, JSON.stringify(settings, null, 2) + "\n");
|
|
39
31
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
if (
|
|
43
|
-
|
|
44
|
-
const existing = loadOKedConfig();
|
|
45
|
-
const payload = { ...existing, apiKey, backendUrl };
|
|
46
|
-
writeFileSync(OKED_CONFIG_PATH, JSON.stringify(payload, null, 2) + "\n");
|
|
47
|
-
try {
|
|
48
|
-
chmodSync(OKED_CONFIG_PATH, 0o600);
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
// Windows doesn't honor chmod; the file lives in the user profile anyway.
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
function openBrowser(url) {
|
|
55
|
-
const platform = process.platform;
|
|
56
|
-
let cmd;
|
|
57
|
-
let args;
|
|
58
|
-
if (platform === "darwin") {
|
|
59
|
-
cmd = "open";
|
|
60
|
-
args = [url];
|
|
61
|
-
}
|
|
62
|
-
else if (platform === "win32") {
|
|
63
|
-
cmd = "cmd";
|
|
64
|
-
args = ["/c", "start", "", url];
|
|
65
|
-
}
|
|
66
|
-
else {
|
|
67
|
-
cmd = "xdg-open";
|
|
68
|
-
args = [url];
|
|
69
|
-
}
|
|
70
|
-
try {
|
|
71
|
-
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
72
|
-
// The launcher may fail asynchronously (e.g. xdg-open missing). Swallow it
|
|
73
|
-
// so it can't crash the process; the URL is always printed as a fallback.
|
|
74
|
-
child.on("error", () => { });
|
|
75
|
-
child.unref();
|
|
76
|
-
return true;
|
|
77
|
-
}
|
|
78
|
-
catch {
|
|
79
|
-
// Best effort. The user has the URL on screen anyway.
|
|
80
|
-
return false;
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Best-effort copy to the OS clipboard. Resolves true only if a clipboard tool
|
|
85
|
-
* actually accepted the text, so the "(copied to clipboard)" line never lies on
|
|
86
|
-
* a headless box. Linux is tried via wl-copy (Wayland), then xclip, then xsel.
|
|
87
|
-
* The code is always printed, so a failure here is purely cosmetic.
|
|
88
|
-
*/
|
|
89
|
-
function copyToClipboard(text) {
|
|
90
|
-
const candidates = process.platform === "darwin"
|
|
91
|
-
? [{ cmd: "pbcopy", args: [] }]
|
|
92
|
-
: process.platform === "win32"
|
|
93
|
-
? [{ cmd: "clip", args: [] }]
|
|
94
|
-
: [
|
|
95
|
-
{ cmd: "wl-copy", args: [] },
|
|
96
|
-
{ cmd: "xclip", args: ["-selection", "clipboard"] },
|
|
97
|
-
{ cmd: "xsel", args: ["--clipboard", "--input"] },
|
|
98
|
-
];
|
|
99
|
-
const tryCopy = ({ cmd, args }) => new Promise((resolve) => {
|
|
100
|
-
let settled = false;
|
|
101
|
-
const done = (ok) => {
|
|
102
|
-
if (!settled) {
|
|
103
|
-
settled = true;
|
|
104
|
-
resolve(ok);
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
try {
|
|
108
|
-
const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "ignore"] });
|
|
109
|
-
child.on("error", () => done(false)); // tool missing / not spawnable
|
|
110
|
-
child.on("close", (code) => done(code === 0));
|
|
111
|
-
child.stdin?.on("error", () => { }); // ignore EPIPE if the tool died early
|
|
112
|
-
child.stdin?.end(text);
|
|
113
|
-
}
|
|
114
|
-
catch {
|
|
115
|
-
done(false);
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
// Try each candidate in order; stop at the first that succeeds.
|
|
119
|
-
return candidates.reduce((acc, cand) => acc.then((ok) => (ok ? true : tryCopy(cand))), Promise.resolve(false));
|
|
120
|
-
}
|
|
121
|
-
/** Wait for the user to press Enter. Resolves immediately if stdin is closed. */
|
|
122
|
-
/** Ask for Enter. cancel() takes the prompt away, for when pairing ends first. */
|
|
123
|
-
function waitForEnter(message) {
|
|
124
|
-
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
125
|
-
// The pairing poll keeps the process alive, so Ctrl+C must exit on purpose.
|
|
126
|
-
rl.on("SIGINT", () => {
|
|
127
|
-
process.stdout.write("\n");
|
|
128
|
-
process.exit(130);
|
|
129
|
-
});
|
|
130
|
-
const pressed = new Promise((resolve) => {
|
|
131
|
-
rl.question(message, () => {
|
|
132
|
-
rl.close();
|
|
133
|
-
resolve();
|
|
134
|
-
});
|
|
135
|
-
});
|
|
136
|
-
return {
|
|
137
|
-
pressed,
|
|
138
|
-
cancel: () => {
|
|
139
|
-
process.stdout.write("\n");
|
|
140
|
-
rl.close();
|
|
141
|
-
},
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
async function pair(clientType) {
|
|
145
|
-
const codeRes = await fetch(`${DEFAULT_BACKEND_URL}/api/v1/device/code`, {
|
|
146
|
-
method: "POST",
|
|
147
|
-
headers: { "Content-Type": "application/json" },
|
|
148
|
-
body: JSON.stringify({
|
|
149
|
-
client_type: clientType,
|
|
150
|
-
hostname: hostname(),
|
|
151
|
-
client_version: CLIENT_VERSION,
|
|
152
|
-
}),
|
|
153
|
-
});
|
|
154
|
-
if (!codeRes.ok) {
|
|
155
|
-
console.log(` Failed to start pairing: ${codeRes.status} ${await codeRes.text()}`);
|
|
156
|
-
return null;
|
|
157
|
-
}
|
|
158
|
-
const code = (await codeRes.json());
|
|
159
|
-
console.log("");
|
|
160
|
-
console.log(" Pair this device with your OKed account.");
|
|
161
|
-
console.log("");
|
|
162
|
-
console.log(" Your pairing code:");
|
|
163
|
-
console.log(` ${code.user_code}`);
|
|
164
|
-
if (!NO_BROWSER && (await copyToClipboard(code.user_code))) {
|
|
165
|
-
console.log(" (copied to clipboard)");
|
|
166
|
-
}
|
|
167
|
-
console.log("");
|
|
168
|
-
// The QR code holds the pairing link: the OKed app pairs from it, and the
|
|
169
|
-
// Camera app opens it in the browser. Only in a terminal that shows colors.
|
|
170
|
-
if (process.stdout.isTTY && !process.env.NO_COLOR) {
|
|
171
|
-
console.log(" Or scan this with your iPhone:");
|
|
172
|
-
console.log("");
|
|
173
|
-
console.log(renderQR(code.verification_uri_complete));
|
|
174
|
-
console.log("");
|
|
175
|
-
}
|
|
176
|
-
// Poll from now on, so a scan from the phone pairs before anyone presses Enter.
|
|
177
|
-
const paired = pollForKey(code);
|
|
178
|
-
// Let the user read the code and initiate the browser launch themselves, so
|
|
179
|
-
// the popup isn't a surprise. Skip the prompt when non-interactive (no TTY,
|
|
180
|
-
// or `--yes`/`-y`) so CI and scripted installs still work.
|
|
181
|
-
const interactive = Boolean(process.stdin.isTTY) &&
|
|
182
|
-
!process.argv.includes("--yes") &&
|
|
183
|
-
!process.argv.includes("-y");
|
|
184
|
-
if (interactive && !NO_BROWSER) {
|
|
185
|
-
const enter = waitForEnter(" Press Enter to open your browser (Ctrl+C to cancel)... ");
|
|
186
|
-
const first = await Promise.race([enter.pressed.then(() => "enter"), paired.then(() => "paired")]);
|
|
187
|
-
if (first === "paired") {
|
|
188
|
-
enter.cancel();
|
|
189
|
-
return paired;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
const opened = NO_BROWSER ? false : openBrowser(code.verification_uri_complete);
|
|
193
|
-
console.log("");
|
|
194
|
-
if (opened) {
|
|
195
|
-
console.log(" Opened your browser to:");
|
|
196
|
-
}
|
|
197
|
-
else if (NO_BROWSER) {
|
|
198
|
-
console.log(" Open this link:");
|
|
199
|
-
}
|
|
200
|
-
else {
|
|
201
|
-
console.log(" Couldn't open your browser automatically. Open this link:");
|
|
202
|
-
}
|
|
203
|
-
console.log(` ${code.verification_uri_complete}`);
|
|
204
|
-
console.log("");
|
|
205
|
-
console.log(` (Or visit ${code.verification_uri} and enter the code above,`);
|
|
206
|
-
console.log(" or enter it in the OKed app on your iPhone.)");
|
|
32
|
+
/** Suggest the Bash sandbox when it is not already containing child processes. */
|
|
33
|
+
function printSandboxHint() {
|
|
34
|
+
if (claudeSandboxEnforced(process.cwd()))
|
|
35
|
+
return;
|
|
207
36
|
console.log("");
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
}
|
|
211
|
-
/** Poll until the code is confirmed (the API key), or it expires (null). */
|
|
212
|
-
async function pollForKey(code) {
|
|
213
|
-
const deadline = Date.now() + code.expires_in * 1000;
|
|
214
|
-
const intervalMs = Math.max(1, code.interval) * 1000;
|
|
215
|
-
while (Date.now() < deadline) {
|
|
216
|
-
await new Promise((r) => setTimeout(r, intervalMs));
|
|
217
|
-
const pollRes = await fetch(`${DEFAULT_BACKEND_URL}/api/v1/device/poll`, {
|
|
218
|
-
method: "POST",
|
|
219
|
-
headers: { "Content-Type": "application/json" },
|
|
220
|
-
body: JSON.stringify({ device_code: code.device_code }),
|
|
221
|
-
});
|
|
222
|
-
if (pollRes.status === 410) {
|
|
223
|
-
console.log(" Pairing code expired. Run `oked init` again.");
|
|
224
|
-
return null;
|
|
225
|
-
}
|
|
226
|
-
if (!pollRes.ok)
|
|
227
|
-
continue;
|
|
228
|
-
const body = (await pollRes.json());
|
|
229
|
-
if (body.status === "approved" && body.api_key) {
|
|
230
|
-
return body.api_key;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
console.log(" Pairing timed out. Run `oked init` again.");
|
|
234
|
-
return null;
|
|
37
|
+
for (const line of SANDBOX_INIT_HINT.split("\n"))
|
|
38
|
+
console.log(` ${line}`);
|
|
235
39
|
}
|
|
236
40
|
/**
|
|
237
41
|
* `oked init --key-only`: pair this device (or show the existing key) and save
|
|
@@ -251,7 +55,12 @@ async function initKeyOnly() {
|
|
|
251
55
|
console.log(` Backend: ${existing.backendUrl} (${ok ? "connected" : "not reachable"})`);
|
|
252
56
|
return;
|
|
253
57
|
}
|
|
254
|
-
const apiKey = await
|
|
58
|
+
const apiKey = await pairDevice({
|
|
59
|
+
backendUrl: DEFAULT_BACKEND_URL,
|
|
60
|
+
clientType: "sdk",
|
|
61
|
+
clientVersion: CLIENT_VERSION,
|
|
62
|
+
noBrowser: NO_BROWSER,
|
|
63
|
+
});
|
|
255
64
|
if (!apiKey)
|
|
256
65
|
return;
|
|
257
66
|
writeOkedConfig(apiKey, DEFAULT_BACKEND_URL);
|
|
@@ -325,18 +134,27 @@ async function init() {
|
|
|
325
134
|
console.log(` Backend: ${existingClient.backendUrl} (${ok ? "connected" : "not reachable"})`);
|
|
326
135
|
console.log("");
|
|
327
136
|
console.log("Every Claude Code session in this project is now protected.");
|
|
137
|
+
printSandboxHint();
|
|
328
138
|
return;
|
|
329
139
|
}
|
|
330
140
|
// Pair this device.
|
|
331
|
-
const apiKey = await
|
|
332
|
-
|
|
141
|
+
const apiKey = await pairDevice({
|
|
142
|
+
backendUrl: DEFAULT_BACKEND_URL,
|
|
143
|
+
clientType: "claude-code",
|
|
144
|
+
clientVersion: CLIENT_VERSION,
|
|
145
|
+
noBrowser: NO_BROWSER,
|
|
146
|
+
});
|
|
147
|
+
if (!apiKey) {
|
|
148
|
+
printSandboxHint();
|
|
333
149
|
return;
|
|
150
|
+
}
|
|
334
151
|
writeOkedConfig(apiKey, DEFAULT_BACKEND_URL);
|
|
335
152
|
console.log("");
|
|
336
153
|
console.log(` Paired ✓ Key saved to ${OKED_CONFIG_PATH}`);
|
|
337
154
|
console.log("");
|
|
338
155
|
console.log("Every Claude Code session in this project is now protected.");
|
|
339
156
|
console.log("Open a new Claude Code session to activate the hook.");
|
|
157
|
+
printSandboxHint();
|
|
340
158
|
}
|
|
341
159
|
async function status() {
|
|
342
160
|
const settingsPath = getSettingsPath();
|
package/dist/hook-config.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { HOOK_TIMEOUT_SECONDS } from "@oked/hook-core";
|
|
1
2
|
export declare const MCP_TOOL_MATCHER = "mcp__.*";
|
|
2
3
|
export declare const DEFAULT_TOOL_MATCHER = "Bash|Write|Edit|Agent|mcp__.*";
|
|
3
4
|
/**
|
|
@@ -12,8 +13,9 @@ export declare const DEFAULT_TOOL_MATCHER = "Bash|Write|Edit|Agent|mcp__.*";
|
|
|
12
13
|
*
|
|
13
14
|
* Claude Code imposes no ceiling of its own: the field is validated as any
|
|
14
15
|
* positive number of seconds, and defaults to 600 when absent.
|
|
16
|
+
* The number itself lives in `@oked/hook-core` so every host uses the same 690.
|
|
15
17
|
*/
|
|
16
|
-
export
|
|
18
|
+
export { HOOK_TIMEOUT_SECONDS };
|
|
17
19
|
export declare const HOOK_CONFIG: {
|
|
18
20
|
matcher: string;
|
|
19
21
|
hooks: {
|
package/dist/hook-config.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
10
10
|
import { homedir } from "os";
|
|
11
11
|
import { join } from "path";
|
|
12
|
-
import {
|
|
12
|
+
import { HOOK_TIMEOUT_SECONDS } from "@oked/hook-core";
|
|
13
13
|
export const MCP_TOOL_MATCHER = "mcp__.*";
|
|
14
14
|
export const DEFAULT_TOOL_MATCHER = `Bash|Write|Edit|Agent|${MCP_TOOL_MATCHER}`;
|
|
15
15
|
/**
|
|
@@ -24,8 +24,9 @@ export const DEFAULT_TOOL_MATCHER = `Bash|Write|Edit|Agent|${MCP_TOOL_MATCHER}`;
|
|
|
24
24
|
*
|
|
25
25
|
* Claude Code imposes no ceiling of its own: the field is validated as any
|
|
26
26
|
* positive number of seconds, and defaults to 600 when absent.
|
|
27
|
+
* The number itself lives in `@oked/hook-core` so every host uses the same 690.
|
|
27
28
|
*/
|
|
28
|
-
export
|
|
29
|
+
export { HOOK_TIMEOUT_SECONDS };
|
|
29
30
|
export const HOOK_CONFIG = {
|
|
30
31
|
matcher: DEFAULT_TOOL_MATCHER,
|
|
31
32
|
hooks: [
|
package/dist/hook.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { decide, errorInfo, logDecision } from "@oked/hook-core";
|
|
3
3
|
import { CLIENT_ID } from "./version.js";
|
|
4
|
-
import { appendReceipt } from "./receipts.js";
|
|
5
|
-
import { logDecision, errorInfo } from "./hook-log.js";
|
|
6
4
|
function makeOutput(decision, reason) {
|
|
7
5
|
return {
|
|
8
6
|
hookSpecificOutput: {
|
|
@@ -12,22 +10,9 @@ function makeOutput(decision, reason) {
|
|
|
12
10
|
},
|
|
13
11
|
};
|
|
14
12
|
}
|
|
15
|
-
function log(msg) {
|
|
16
|
-
process.stderr.write(`[OKed] ${msg}\n`);
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* Writes the hook output. Every deny and ask, and every degraded allow, also
|
|
20
|
-
* goes to ~/.oked/hook.log.
|
|
21
|
-
*/
|
|
22
|
-
function respond(decision, reason, ctx) {
|
|
23
|
-
process.stdout.write(JSON.stringify(makeOutput(decision, reason)));
|
|
24
|
-
if (decision !== "allow" || ctx.degraded)
|
|
25
|
-
logDecision({ decision, reason: reason ?? "", client: CLIENT_ID, ...ctx });
|
|
26
|
-
}
|
|
27
|
-
/** "Name: message", one line, short. For deny reasons. */
|
|
28
13
|
function errorText(err) {
|
|
29
|
-
const
|
|
30
|
-
return `${
|
|
14
|
+
const info = errorInfo(err);
|
|
15
|
+
return `${info.name}: ${info.message}`;
|
|
31
16
|
}
|
|
32
17
|
async function main() {
|
|
33
18
|
// Read hook input from stdin
|
|
@@ -44,143 +29,34 @@ async function main() {
|
|
|
44
29
|
process.stdout.write(JSON.stringify(makeOutput("allow")));
|
|
45
30
|
return;
|
|
46
31
|
}
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
if (tier === "safe" || tier === "warning") {
|
|
64
|
-
let ruleMatches = false;
|
|
65
|
-
if (client.apiKey) {
|
|
66
|
-
try {
|
|
67
|
-
const rules = await client.getRules();
|
|
68
|
-
if (rules.length > 0) {
|
|
69
|
-
const decision = applyRules({ tier, fields: fields ?? {} }, rules, { cwd: input.cwd });
|
|
70
|
-
ruleMatches = Boolean(decision.appliedRuleId);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
catch {
|
|
74
|
-
// Advisory: a failed rules lookup must never block the action.
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
if (!ruleMatches) {
|
|
78
|
-
if (tier === "warning") {
|
|
79
|
-
const summary = (toolInput.file_path ?? toolInput.command ?? toolName);
|
|
80
|
-
process.stderr.write(`WARNING OKed: ${toolName} ${summary} - allowed (inside project)\n`);
|
|
81
|
-
}
|
|
82
|
-
process.stdout.write(JSON.stringify(makeOutput("allow")));
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
// A rule matched a normally-silent action — fall through to the backend,
|
|
86
|
-
// which applies the rule authoritatively (escalate / auto-decide + audit).
|
|
87
|
-
}
|
|
88
|
-
const ctx = { tool: toolName, tier };
|
|
89
|
-
// Check if API key is configured
|
|
90
|
-
if (!client.apiKey) {
|
|
91
|
-
log("not paired - run `oked init` to pair this device. Falling back to Claude's built-in prompt.");
|
|
92
|
-
respond("ask", "OKed: this device is not paired. Run `oked init`.", ctx);
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
|
-
// A PR card names the PR. Ask GitHub for the title when the command does not say it.
|
|
96
|
-
const prTitle = await lookupPrTitle(fields);
|
|
97
|
-
if (prTitle)
|
|
98
|
-
fields = describeFields(toolName, toolInput, { cwd: input.cwd, prTitle }) ?? undefined;
|
|
99
|
-
// Generate human-readable description
|
|
100
|
-
const description = describe(toolName, toolInput, { cwd: input.cwd, prTitle });
|
|
101
|
-
log(`${toolName}: "${description}" - ${tier}`);
|
|
102
|
-
log("Requesting approval... (check your phone)");
|
|
103
|
-
try {
|
|
104
|
-
const result = await client.approve({
|
|
105
|
-
action: toolName,
|
|
106
|
-
description,
|
|
107
|
-
tier,
|
|
108
|
-
fields,
|
|
109
|
-
tool_input: toolInput,
|
|
110
|
-
session_id: input.session_id,
|
|
111
|
-
cwd: input.cwd,
|
|
112
|
-
});
|
|
113
|
-
// Keep our own copy of every verified receipt (approve, deny or timeout).
|
|
114
|
-
if (result.receipt)
|
|
115
|
-
appendReceipt(result.receipt);
|
|
116
|
-
const receiptNote = result.receipt ? ` (receipt ${shortReceiptId(result.receipt.body.receipt_id)})` : "";
|
|
117
|
-
const decided = {
|
|
118
|
-
...ctx,
|
|
119
|
-
approval_id: result.approval_id,
|
|
120
|
-
receipt_id: result.receipt?.body.receipt_id ?? null,
|
|
121
|
-
};
|
|
122
|
-
if (result.approved) {
|
|
123
|
-
log(`Approved (${result.approval_id})${receiptNote}`);
|
|
124
|
-
respond("allow", `Approved via OKed${receiptNote}`, decided);
|
|
125
|
-
}
|
|
126
|
-
else if (result.decision === "timeout") {
|
|
127
|
-
log(`No decision in time (${result.approval_id})${receiptNote}`);
|
|
128
|
-
respond("deny", `OKed: no decision within the approval window (timed out): ${description}`, decided);
|
|
129
|
-
}
|
|
130
|
-
else {
|
|
131
|
-
log(`Denied (${result.approval_id})${receiptNote}`);
|
|
132
|
-
respond("deny", `Denied via OKed: ${description}`, decided);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
catch (err) {
|
|
136
|
-
const failed = { ...ctx, error: errorInfo(err) };
|
|
137
|
-
if (err instanceof OKedReceiptError) {
|
|
138
|
-
// A decision we cannot prove is not a decision - always deny.
|
|
139
|
-
log(`Approval receipt did not verify (${err.problems.join(", ")}) - action denied`);
|
|
140
|
-
respond("deny", `OKed: the approval receipt did not verify (${err.problems.join(", ")}); action denied`, failed);
|
|
141
|
-
}
|
|
142
|
-
else if (err instanceof OKedAuthError) {
|
|
143
|
-
// Auth misconfig is not an outage - always deny. A deleted account ends
|
|
144
|
-
// here too, so name the way out as well as the way back.
|
|
145
|
-
log(`Invalid API key (HTTP ${err.status}) - action denied`);
|
|
146
|
-
respond("deny", `OKed: invalid API key (HTTP ${err.status}). Run \`oked init\` to pair again, or \`oked uninstall\` to remove OKed.`, failed);
|
|
147
|
-
}
|
|
148
|
-
else if (err instanceof OKedTooManyPendingError) {
|
|
149
|
-
// Not an outage: the backend works, and too many approvals wait.
|
|
150
|
-
log(`Too many pending approvals (HTTP 429) - action denied`);
|
|
151
|
-
respond("deny", err.message, failed);
|
|
152
|
-
}
|
|
153
|
-
else if (err instanceof OKedHttpError) {
|
|
154
|
-
log(`Backend error HTTP ${err.status} - action denied (fail-safe)`);
|
|
155
|
-
respond("deny", `OKed: backend error HTTP ${err.status}${err.detail ? `: ${err.detail}` : ""} (fail-safe deny)`, failed);
|
|
156
|
-
}
|
|
157
|
-
else if (err instanceof OKedBackendUnreachableError) {
|
|
158
|
-
const decision = degradedDecision(tier, {
|
|
159
|
-
strictFailClosed: client.strictFailClosed,
|
|
160
|
-
});
|
|
161
|
-
const cause = errorInfo(err).message;
|
|
162
|
-
if (decision === "allow") {
|
|
163
|
-
log(`Backend unreachable (${cause}) - allowed (degraded; ${tier}, non-high-stakes)`);
|
|
164
|
-
respond("allow", `OKed backend unreachable (${cause}) - allowed (degraded; non-high-stakes)`, { ...failed, degraded: true });
|
|
165
|
-
}
|
|
166
|
-
else {
|
|
167
|
-
const why = client.strictFailClosed
|
|
168
|
-
? "strict fail-closed"
|
|
169
|
-
: "high-stakes";
|
|
170
|
-
log(`Backend unreachable (${cause}) - ${why} denied (fail-safe)`);
|
|
171
|
-
respond("deny", `OKed backend unreachable (${cause}) - ${why} denied (fail-safe)`, failed);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
else {
|
|
175
|
-
// Unknown error - fail safe deny, with the real cause.
|
|
176
|
-
log(`Unexpected error (${errorText(err)}) - action denied (fail-safe)`);
|
|
177
|
-
respond("deny", `OKed: unexpected error (fail-safe): ${errorText(err)}`, failed);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
32
|
+
const decision = await decide({
|
|
33
|
+
toolName: input.tool_name,
|
|
34
|
+
// Pass tool_input through. Replacing a missing value with {} makes Bash
|
|
35
|
+
// and Write look safe, and the hook would allow them. 0.6.21 did not
|
|
36
|
+
// coerce it: classify threw, and the fail-safe handler denied.
|
|
37
|
+
toolInput: input.tool_input,
|
|
38
|
+
cwd: input.cwd,
|
|
39
|
+
sessionId: input.session_id,
|
|
40
|
+
}, {
|
|
41
|
+
clientId: CLIENT_ID,
|
|
42
|
+
source: "claude-code",
|
|
43
|
+
unpaired: "ask",
|
|
44
|
+
unpairedReason: "OKed: this device is not paired. Run `oked init`.",
|
|
45
|
+
unpairedLog: "not paired - run `oked init` to pair this device. Falling back to Claude's built-in prompt.",
|
|
46
|
+
});
|
|
47
|
+
process.stdout.write(JSON.stringify(makeOutput(decision.decision, decision.reason)));
|
|
180
48
|
}
|
|
181
49
|
main().catch((err) => {
|
|
182
50
|
process.stderr.write(`[OKed] Fatal: ${err}\n`);
|
|
183
|
-
|
|
184
|
-
|
|
51
|
+
const reason = `OKed: internal error (fail-safe): ${errorText(err)}`;
|
|
52
|
+
process.stdout.write(JSON.stringify(makeOutput("deny", reason)));
|
|
53
|
+
logDecision({
|
|
54
|
+
decision: "deny",
|
|
55
|
+
reason,
|
|
56
|
+
tool: "unknown",
|
|
57
|
+
tier: null,
|
|
58
|
+
client: CLIENT_ID,
|
|
59
|
+
error: errorInfo(err),
|
|
60
|
+
});
|
|
185
61
|
process.exit(0); // exit 0 so Claude reads our JSON, not a crash
|
|
186
62
|
});
|
package/dist/qr.d.ts
CHANGED
|
@@ -1,7 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export declare function encodeQR(text: string): boolean[][];
|
|
3
|
-
/**
|
|
4
|
-
* The QR code as terminal text, two modules per character with half blocks,
|
|
5
|
-
* in black on white with ANSI colors, so it scans on dark and light themes.
|
|
6
|
-
*/
|
|
7
|
-
export declare function renderQR(text: string, indent?: string): string;
|
|
1
|
+
export { encodeQR, renderQR } from "@oked/hook-core";
|
package/dist/qr.js
CHANGED
|
@@ -1,332 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// OKed iPhone app can scan it. Byte mode, error correction level M, versions
|
|
3
|
-
// 1 to 10 (up to 213 bytes): enough for a URL. It follows ISO/IEC 18004 and
|
|
4
|
-
// Project Nayuki's reference design. It is here, not a dependency, so the hook
|
|
5
|
-
// package keeps a single dependency.
|
|
6
|
-
const ECC_PER_BLOCK = [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26];
|
|
7
|
-
const NUM_BLOCKS = [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5];
|
|
8
|
-
const MAX_VERSION = 10;
|
|
9
|
-
const FORMAT_ECC_M = 0;
|
|
10
|
-
/** The QR modules for text: rows of booleans, true is dark. No quiet zone. */
|
|
11
|
-
export function encodeQR(text) {
|
|
12
|
-
const bytes = [...Buffer.from(text, "utf8")];
|
|
13
|
-
let version = 1;
|
|
14
|
-
for (; version <= MAX_VERSION; version++) {
|
|
15
|
-
if (4 + charCountBits(version) + bytes.length * 8 <= dataCodewords(version) * 8)
|
|
16
|
-
break;
|
|
17
|
-
}
|
|
18
|
-
if (version > MAX_VERSION)
|
|
19
|
-
throw new Error("Text too long for a QR code");
|
|
20
|
-
// The data bits: mode, length, bytes, terminator, then pad bytes.
|
|
21
|
-
const capacity = dataCodewords(version) * 8;
|
|
22
|
-
const bits = [];
|
|
23
|
-
const append = (value, length) => {
|
|
24
|
-
for (let i = length - 1; i >= 0; i--)
|
|
25
|
-
bits.push((value >>> i) & 1);
|
|
26
|
-
};
|
|
27
|
-
append(0b0100, 4);
|
|
28
|
-
append(bytes.length, charCountBits(version));
|
|
29
|
-
for (const b of bytes)
|
|
30
|
-
append(b, 8);
|
|
31
|
-
append(0, Math.min(4, capacity - bits.length));
|
|
32
|
-
append(0, (8 - (bits.length % 8)) % 8);
|
|
33
|
-
for (let pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11)
|
|
34
|
-
append(pad, 8);
|
|
35
|
-
const data = [];
|
|
36
|
-
for (let i = 0; i < bits.length; i += 8)
|
|
37
|
-
data.push(parseInt(bits.slice(i, i + 8).join(""), 2));
|
|
38
|
-
const qr = new Matrix(version);
|
|
39
|
-
qr.drawFunctionPatterns();
|
|
40
|
-
qr.drawCodewords(addEccAndInterleave(data, version));
|
|
41
|
-
let best = [];
|
|
42
|
-
let bestPenalty = Infinity;
|
|
43
|
-
for (let mask = 0; mask < 8; mask++) {
|
|
44
|
-
const masked = qr.withMask(mask);
|
|
45
|
-
const penalty = penaltyScore(masked);
|
|
46
|
-
if (penalty < bestPenalty) {
|
|
47
|
-
best = masked;
|
|
48
|
-
bestPenalty = penalty;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return best;
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* The QR code as terminal text, two modules per character with half blocks,
|
|
55
|
-
* in black on white with ANSI colors, so it scans on dark and light themes.
|
|
56
|
-
*/
|
|
57
|
-
export function renderQR(text, indent = " ") {
|
|
58
|
-
const modules = encodeQR(text);
|
|
59
|
-
const quiet = 2;
|
|
60
|
-
const size = modules.length + quiet * 2;
|
|
61
|
-
const dark = (x, y) => x >= quiet && y >= quiet && x < size - quiet && y < size - quiet && modules[y - quiet][x - quiet];
|
|
62
|
-
const lines = [];
|
|
63
|
-
for (let y = 0; y < size; y += 2) {
|
|
64
|
-
let line = "";
|
|
65
|
-
for (let x = 0; x < size; x++) {
|
|
66
|
-
const top = dark(x, y);
|
|
67
|
-
const bottom = y + 1 < size && dark(x, y + 1);
|
|
68
|
-
line += top && bottom ? "█" : top ? "▀" : bottom ? "▄" : " ";
|
|
69
|
-
}
|
|
70
|
-
lines.push(`${indent}\x1b[30;107m${line}\x1b[0m`);
|
|
71
|
-
}
|
|
72
|
-
return lines.join("\n");
|
|
73
|
-
}
|
|
74
|
-
function charCountBits(version) {
|
|
75
|
-
return version <= 9 ? 8 : 16;
|
|
76
|
-
}
|
|
77
|
-
function rawDataModules(version) {
|
|
78
|
-
let result = (16 * version + 128) * version + 64;
|
|
79
|
-
if (version >= 2) {
|
|
80
|
-
const numAlign = Math.floor(version / 7) + 2;
|
|
81
|
-
result -= (25 * numAlign - 10) * numAlign - 55;
|
|
82
|
-
if (version >= 7)
|
|
83
|
-
result -= 36;
|
|
84
|
-
}
|
|
85
|
-
return result;
|
|
86
|
-
}
|
|
87
|
-
function dataCodewords(version) {
|
|
88
|
-
return Math.floor(rawDataModules(version) / 8) - ECC_PER_BLOCK[version] * NUM_BLOCKS[version];
|
|
89
|
-
}
|
|
90
|
-
function addEccAndInterleave(data, version) {
|
|
91
|
-
const numBlocks = NUM_BLOCKS[version];
|
|
92
|
-
const eccLen = ECC_PER_BLOCK[version];
|
|
93
|
-
const rawCodewords = Math.floor(rawDataModules(version) / 8);
|
|
94
|
-
const numShortBlocks = numBlocks - (rawCodewords % numBlocks);
|
|
95
|
-
const shortBlockLen = Math.floor(rawCodewords / numBlocks);
|
|
96
|
-
const divisor = reedSolomonDivisor(eccLen);
|
|
97
|
-
const blocks = [];
|
|
98
|
-
for (let i = 0, k = 0; i < numBlocks; i++) {
|
|
99
|
-
const dat = data.slice(k, k + shortBlockLen - eccLen + (i < numShortBlocks ? 0 : 1));
|
|
100
|
-
k += dat.length;
|
|
101
|
-
const ecc = reedSolomonRemainder(dat, divisor);
|
|
102
|
-
if (i < numShortBlocks)
|
|
103
|
-
dat.push(0);
|
|
104
|
-
blocks.push(dat.concat(ecc));
|
|
105
|
-
}
|
|
106
|
-
const result = [];
|
|
107
|
-
for (let i = 0; i < blocks[0].length; i++) {
|
|
108
|
-
blocks.forEach((block, j) => {
|
|
109
|
-
// Skip the padding byte of the short blocks.
|
|
110
|
-
if (i !== shortBlockLen - eccLen || j >= numShortBlocks)
|
|
111
|
-
result.push(block[i]);
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
return result;
|
|
115
|
-
}
|
|
116
|
-
function gfMultiply(x, y) {
|
|
117
|
-
let z = 0;
|
|
118
|
-
for (let i = 7; i >= 0; i--) {
|
|
119
|
-
z = (z << 1) ^ ((z >>> 7) * 0x11d);
|
|
120
|
-
z ^= ((y >>> i) & 1) * x;
|
|
121
|
-
}
|
|
122
|
-
return z;
|
|
123
|
-
}
|
|
124
|
-
function reedSolomonDivisor(degree) {
|
|
125
|
-
const result = new Array(degree).fill(0);
|
|
126
|
-
result[degree - 1] = 1;
|
|
127
|
-
let root = 1;
|
|
128
|
-
for (let i = 0; i < degree; i++) {
|
|
129
|
-
for (let j = 0; j < result.length; j++) {
|
|
130
|
-
result[j] = gfMultiply(result[j], root);
|
|
131
|
-
if (j + 1 < result.length)
|
|
132
|
-
result[j] ^= result[j + 1];
|
|
133
|
-
}
|
|
134
|
-
root = gfMultiply(root, 0x02);
|
|
135
|
-
}
|
|
136
|
-
return result;
|
|
137
|
-
}
|
|
138
|
-
function reedSolomonRemainder(data, divisor) {
|
|
139
|
-
const result = divisor.map(() => 0);
|
|
140
|
-
for (const b of data) {
|
|
141
|
-
const factor = b ^ result.shift();
|
|
142
|
-
result.push(0);
|
|
143
|
-
divisor.forEach((coef, i) => (result[i] ^= gfMultiply(coef, factor)));
|
|
144
|
-
}
|
|
145
|
-
return result;
|
|
146
|
-
}
|
|
147
|
-
class Matrix {
|
|
148
|
-
version;
|
|
149
|
-
size;
|
|
150
|
-
modules;
|
|
151
|
-
isFunction;
|
|
152
|
-
constructor(version) {
|
|
153
|
-
this.version = version;
|
|
154
|
-
this.size = version * 4 + 17;
|
|
155
|
-
this.modules = Array.from({ length: this.size }, () => new Array(this.size).fill(false));
|
|
156
|
-
this.isFunction = Array.from({ length: this.size }, () => new Array(this.size).fill(false));
|
|
157
|
-
}
|
|
158
|
-
set(x, y, dark) {
|
|
159
|
-
this.modules[y][x] = dark;
|
|
160
|
-
this.isFunction[y][x] = true;
|
|
161
|
-
}
|
|
162
|
-
drawFunctionPatterns() {
|
|
163
|
-
const size = this.size;
|
|
164
|
-
for (let i = 0; i < size; i++) {
|
|
165
|
-
this.set(6, i, i % 2 === 0);
|
|
166
|
-
this.set(i, 6, i % 2 === 0);
|
|
167
|
-
}
|
|
168
|
-
this.drawFinder(3, 3);
|
|
169
|
-
this.drawFinder(size - 4, 3);
|
|
170
|
-
this.drawFinder(3, size - 4);
|
|
171
|
-
const positions = this.alignmentPositions();
|
|
172
|
-
const last = positions.length - 1;
|
|
173
|
-
positions.forEach((x, i) => positions.forEach((y, j) => {
|
|
174
|
-
if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0))
|
|
175
|
-
return;
|
|
176
|
-
for (let dy = -2; dy <= 2; dy++) {
|
|
177
|
-
for (let dx = -2; dx <= 2; dx++)
|
|
178
|
-
this.set(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
|
|
179
|
-
}
|
|
180
|
-
}));
|
|
181
|
-
// Reserve the format areas now; withMask() writes the real bits.
|
|
182
|
-
this.drawFormatBits(0, this.modules);
|
|
183
|
-
if (this.version >= 7) {
|
|
184
|
-
let rem = this.version;
|
|
185
|
-
for (let i = 0; i < 12; i++)
|
|
186
|
-
rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
|
|
187
|
-
const bits = (this.version << 12) | rem;
|
|
188
|
-
for (let i = 0; i < 18; i++) {
|
|
189
|
-
const dark = ((bits >>> i) & 1) !== 0;
|
|
190
|
-
const a = size - 11 + (i % 3);
|
|
191
|
-
const b = Math.floor(i / 3);
|
|
192
|
-
this.set(a, b, dark);
|
|
193
|
-
this.set(b, a, dark);
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
drawFinder(cx, cy) {
|
|
198
|
-
for (let dy = -4; dy <= 4; dy++) {
|
|
199
|
-
for (let dx = -4; dx <= 4; dx++) {
|
|
200
|
-
const x = cx + dx;
|
|
201
|
-
const y = cy + dy;
|
|
202
|
-
const dist = Math.max(Math.abs(dx), Math.abs(dy));
|
|
203
|
-
if (x >= 0 && x < this.size && y >= 0 && y < this.size)
|
|
204
|
-
this.set(x, y, dist !== 2 && dist !== 4);
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
alignmentPositions() {
|
|
209
|
-
if (this.version === 1)
|
|
210
|
-
return [];
|
|
211
|
-
const numAlign = Math.floor(this.version / 7) + 2;
|
|
212
|
-
const step = Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
|
|
213
|
-
const result = [6];
|
|
214
|
-
for (let pos = this.size - 7; result.length < numAlign; pos -= step)
|
|
215
|
-
result.splice(1, 0, pos);
|
|
216
|
-
return result;
|
|
217
|
-
}
|
|
218
|
-
drawFormatBits(mask, target) {
|
|
219
|
-
const data = (FORMAT_ECC_M << 3) | mask;
|
|
220
|
-
let rem = data;
|
|
221
|
-
for (let i = 0; i < 10; i++)
|
|
222
|
-
rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
|
|
223
|
-
const bits = ((data << 10) | rem) ^ 0x5412;
|
|
224
|
-
const bit = (i) => ((bits >>> i) & 1) !== 0;
|
|
225
|
-
const put = (x, y, dark) => {
|
|
226
|
-
target[y][x] = dark;
|
|
227
|
-
this.isFunction[y][x] = true;
|
|
228
|
-
};
|
|
229
|
-
const size = this.size;
|
|
230
|
-
for (let i = 0; i <= 5; i++)
|
|
231
|
-
put(8, i, bit(i));
|
|
232
|
-
put(8, 7, bit(6));
|
|
233
|
-
put(8, 8, bit(7));
|
|
234
|
-
put(7, 8, bit(8));
|
|
235
|
-
for (let i = 9; i < 15; i++)
|
|
236
|
-
put(14 - i, 8, bit(i));
|
|
237
|
-
for (let i = 0; i < 8; i++)
|
|
238
|
-
put(size - 1 - i, 8, bit(i));
|
|
239
|
-
for (let i = 8; i < 15; i++)
|
|
240
|
-
put(8, size - 15 + i, bit(i));
|
|
241
|
-
put(8, size - 8, true);
|
|
242
|
-
}
|
|
243
|
-
drawCodewords(codewords) {
|
|
244
|
-
const size = this.size;
|
|
245
|
-
let i = 0;
|
|
246
|
-
for (let right = size - 1; right >= 1; right -= 2) {
|
|
247
|
-
if (right === 6)
|
|
248
|
-
right = 5;
|
|
249
|
-
for (let vert = 0; vert < size; vert++) {
|
|
250
|
-
for (let j = 0; j < 2; j++) {
|
|
251
|
-
const x = right - j;
|
|
252
|
-
const upward = ((right + 1) & 2) === 0;
|
|
253
|
-
const y = upward ? size - 1 - vert : vert;
|
|
254
|
-
if (!this.isFunction[y][x] && i < codewords.length * 8) {
|
|
255
|
-
this.modules[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) !== 0;
|
|
256
|
-
i++;
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
/** A copy with the data masked and the format bits for that mask. */
|
|
263
|
-
withMask(mask) {
|
|
264
|
-
const out = this.modules.map((row) => row.slice());
|
|
265
|
-
for (let y = 0; y < this.size; y++) {
|
|
266
|
-
for (let x = 0; x < this.size; x++) {
|
|
267
|
-
if (!this.isFunction[y][x] && maskBit(mask, x, y))
|
|
268
|
-
out[y][x] = !out[y][x];
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
this.drawFormatBits(mask, out);
|
|
272
|
-
return out;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
function maskBit(mask, x, y) {
|
|
276
|
-
switch (mask) {
|
|
277
|
-
case 0: return (x + y) % 2 === 0;
|
|
278
|
-
case 1: return y % 2 === 0;
|
|
279
|
-
case 2: return x % 3 === 0;
|
|
280
|
-
case 3: return (x + y) % 3 === 0;
|
|
281
|
-
case 4: return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
|
|
282
|
-
case 5: return ((x * y) % 2) + ((x * y) % 3) === 0;
|
|
283
|
-
case 6: return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
|
|
284
|
-
default: return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
/** The standard mask penalty: runs, 2x2 blocks, finder-like patterns, balance. */
|
|
288
|
-
function penaltyScore(m) {
|
|
289
|
-
const size = m.length;
|
|
290
|
-
let score = 0;
|
|
291
|
-
const lines = [];
|
|
292
|
-
for (let i = 0; i < size; i++) {
|
|
293
|
-
lines.push(m[i]);
|
|
294
|
-
lines.push(m.map((row) => row[i]));
|
|
295
|
-
}
|
|
296
|
-
const finderLike = [
|
|
297
|
-
[true, false, true, true, true, false, true, false, false, false, false],
|
|
298
|
-
[false, false, false, false, true, false, true, true, true, false, true],
|
|
299
|
-
];
|
|
300
|
-
for (const line of lines) {
|
|
301
|
-
let run = 1;
|
|
302
|
-
for (let i = 1; i <= size; i++) {
|
|
303
|
-
if (i < size && line[i] === line[i - 1]) {
|
|
304
|
-
run++;
|
|
305
|
-
}
|
|
306
|
-
else {
|
|
307
|
-
if (run >= 5)
|
|
308
|
-
score += run - 2;
|
|
309
|
-
run = 1;
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
for (let i = 0; i + 11 <= size; i++) {
|
|
313
|
-
for (const pattern of finderLike) {
|
|
314
|
-
if (pattern.every((v, k) => line[i + k] === v))
|
|
315
|
-
score += 40;
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
let darkCount = 0;
|
|
320
|
-
for (let y = 0; y < size; y++) {
|
|
321
|
-
for (let x = 0; x < size; x++) {
|
|
322
|
-
if (m[y][x])
|
|
323
|
-
darkCount++;
|
|
324
|
-
if (x + 1 < size && y + 1 < size && m[y][x] === m[y][x + 1] && m[y][x] === m[y + 1][x] && m[y][x] === m[y + 1][x + 1]) {
|
|
325
|
-
score += 3;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
const total = size * size;
|
|
330
|
-
score += Math.floor(Math.abs(darkCount * 20 - total * 10) / total) * 10;
|
|
331
|
-
return score;
|
|
332
|
-
}
|
|
1
|
+
export { encodeQR, renderQR } from "@oked/hook-core";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oked/claude-code",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.22",
|
|
4
4
|
"description": "OKed for Claude Code - zero-code human approval for sensitive actions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"oked-hook": "./bin/oked-hook.js"
|
|
9
9
|
},
|
|
10
10
|
"scripts": {
|
|
11
|
-
"prebuild": "npm run build --workspace=@oked/
|
|
11
|
+
"prebuild": "npm run build --workspace=@oked/hook-core",
|
|
12
12
|
"build": "tsc",
|
|
13
13
|
"test": "npm run build && node src/smoke.test.mjs && node src/hook.test.mjs && node src/cli.test.mjs",
|
|
14
14
|
"prepublishOnly": "npm run build"
|
|
@@ -44,9 +44,10 @@
|
|
|
44
44
|
"access": "public"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@oked/
|
|
47
|
+
"@oked/hook-core": "0.6.22",
|
|
48
|
+
"@oked/sdk": "0.6.22"
|
|
48
49
|
},
|
|
49
50
|
"devDependencies": {
|
|
50
|
-
"typescript": "^
|
|
51
|
+
"typescript": "^7.0.2"
|
|
51
52
|
}
|
|
52
53
|
}
|
package/dist/hook-log.d.ts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* One JSON line per hook decision that is not a normal allow: every deny and
|
|
3
|
-
* ask, and every degraded allow (an action that ran without a person's
|
|
4
|
-
* decision because the backend was unreachable). A person can see later why
|
|
5
|
-
* an action was blocked, or which actions ran during an outage. It never holds
|
|
6
|
-
* the tool input or the description: a command line can contain a secret.
|
|
7
|
-
*/
|
|
8
|
-
export declare const OKED_HOOK_LOG: string;
|
|
9
|
-
export interface ErrorInfo {
|
|
10
|
-
name: string;
|
|
11
|
-
message: string;
|
|
12
|
-
status?: number;
|
|
13
|
-
}
|
|
14
|
-
export interface DecisionLogEntry {
|
|
15
|
-
ts: string;
|
|
16
|
-
decision: "deny" | "ask" | "allow";
|
|
17
|
-
/** True for an allow without a person's decision, during a backend outage. */
|
|
18
|
-
degraded?: boolean;
|
|
19
|
-
reason: string;
|
|
20
|
-
tool: string;
|
|
21
|
-
tier: string | null;
|
|
22
|
-
client: string;
|
|
23
|
-
approval_id?: string | null;
|
|
24
|
-
receipt_id?: string | null;
|
|
25
|
-
error?: ErrorInfo;
|
|
26
|
-
}
|
|
27
|
-
/** Name, one-line message (at most 300 characters) and HTTP status, if any. */
|
|
28
|
-
export declare function errorInfo(err: unknown): ErrorInfo;
|
|
29
|
-
/** Appends one entry. Best-effort: a log problem never changes the decision. */
|
|
30
|
-
export declare function logDecision(entry: Omit<DecisionLogEntry, "ts">, path?: string): void;
|
package/dist/hook-log.js
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
|
|
2
|
-
import { homedir } from "os";
|
|
3
|
-
import { dirname, join } from "path";
|
|
4
|
-
/**
|
|
5
|
-
* One JSON line per hook decision that is not a normal allow: every deny and
|
|
6
|
-
* ask, and every degraded allow (an action that ran without a person's
|
|
7
|
-
* decision because the backend was unreachable). A person can see later why
|
|
8
|
-
* an action was blocked, or which actions ran during an outage. It never holds
|
|
9
|
-
* the tool input or the description: a command line can contain a secret.
|
|
10
|
-
*/
|
|
11
|
-
export const OKED_HOOK_LOG = join(homedir(), ".oked", "hook.log");
|
|
12
|
-
/** Above this size, hook.log moves to hook.log.1 and a new file starts. */
|
|
13
|
-
const MAX_BYTES = 1_000_000;
|
|
14
|
-
/** Name, one-line message (at most 300 characters) and HTTP status, if any. */
|
|
15
|
-
export function errorInfo(err) {
|
|
16
|
-
const e = err;
|
|
17
|
-
const name = typeof e?.name === "string" ? e.name : typeof err;
|
|
18
|
-
const raw = typeof e?.message === "string" ? e.message : String(err);
|
|
19
|
-
const line = raw.replace(/\s+/g, " ").trim();
|
|
20
|
-
const message = line.length > 300 ? line.slice(0, 297) + "..." : line;
|
|
21
|
-
return typeof e?.status === "number" ? { name, message, status: e.status } : { name, message };
|
|
22
|
-
}
|
|
23
|
-
/** Appends one entry. Best-effort: a log problem never changes the decision. */
|
|
24
|
-
export function logDecision(entry, path = process.env.OKED_HOOK_LOG || OKED_HOOK_LOG) {
|
|
25
|
-
try {
|
|
26
|
-
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
27
|
-
try {
|
|
28
|
-
if (statSync(path).size > MAX_BYTES)
|
|
29
|
-
renameSync(path, `${path}.1`);
|
|
30
|
-
}
|
|
31
|
-
catch {
|
|
32
|
-
// No file yet.
|
|
33
|
-
}
|
|
34
|
-
appendFileSync(path, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + "\n", { mode: 0o600 });
|
|
35
|
-
}
|
|
36
|
-
catch {
|
|
37
|
-
// The decision itself is already written to stdout.
|
|
38
|
-
}
|
|
39
|
-
}
|
package/dist/receipts.d.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { verifyChain, type SignedReceipt } from "@oked/sdk";
|
|
2
|
-
/** The customer's own copy of every receipt this machine received. */
|
|
3
|
-
export declare const OKED_RECEIPTS_LOG: string;
|
|
4
|
-
/** Append one verified receipt. Best-effort: never blocks or breaks the agent. */
|
|
5
|
-
export declare function appendReceipt(receipt: SignedReceipt, path?: string): void;
|
|
6
|
-
export interface LocalVerifyReport {
|
|
7
|
-
total: number;
|
|
8
|
-
valid: number;
|
|
9
|
-
invalid: {
|
|
10
|
-
line: number;
|
|
11
|
-
receipt_id: string | null;
|
|
12
|
-
problems: string[];
|
|
13
|
-
}[];
|
|
14
|
-
unparsable: number[];
|
|
15
|
-
chains: ReturnType<typeof verifyChain>;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Verify a receipts file: every signature against OKed's published keys, and
|
|
19
|
-
* chain links between receipts that are adjacent. Gaps in seq are expected in a
|
|
20
|
-
* local copy (other devices and agents share the operator's chain); a broken
|
|
21
|
-
* link between adjacent receipts is not.
|
|
22
|
-
*/
|
|
23
|
-
export declare function verifyReceiptsFile(path?: string): Promise<LocalVerifyReport>;
|
package/dist/receipts.js
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { appendFileSync, mkdirSync, readFileSync } from "fs";
|
|
2
|
-
import { homedir } from "os";
|
|
3
|
-
import { dirname, join } from "path";
|
|
4
|
-
import { keysFor, loadOKedConfig, verifyChain, verifyReceipt, OKED_RECEIPT_KEYS_URL, } from "@oked/sdk";
|
|
5
|
-
/** The customer's own copy of every receipt this machine received. */
|
|
6
|
-
export const OKED_RECEIPTS_LOG = join(homedir(), ".oked", "receipts.jsonl");
|
|
7
|
-
/** Append one verified receipt. Best-effort: never blocks or breaks the agent. */
|
|
8
|
-
export function appendReceipt(receipt, path = OKED_RECEIPTS_LOG) {
|
|
9
|
-
try {
|
|
10
|
-
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
11
|
-
appendFileSync(path, JSON.stringify(receipt) + "\n", { mode: 0o600 });
|
|
12
|
-
}
|
|
13
|
-
catch {
|
|
14
|
-
// The receipt is still stored by OKed; the local copy is a convenience.
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Verify a receipts file: every signature against OKed's published keys, and
|
|
19
|
-
* chain links between receipts that are adjacent. Gaps in seq are expected in a
|
|
20
|
-
* local copy (other devices and agents share the operator's chain); a broken
|
|
21
|
-
* link between adjacent receipts is not.
|
|
22
|
-
*/
|
|
23
|
-
export async function verifyReceiptsFile(path = OKED_RECEIPTS_LOG) {
|
|
24
|
-
const keysUrl = process.env.OKED_RECEIPT_KEYS_URL || loadOKedConfig().receiptKeysUrl || OKED_RECEIPT_KEYS_URL;
|
|
25
|
-
const lines = readFileSync(path, "utf-8").split("\n");
|
|
26
|
-
const receipts = [];
|
|
27
|
-
const report = { total: 0, valid: 0, invalid: [], unparsable: [], chains: [] };
|
|
28
|
-
for (let i = 0; i < lines.length; i++) {
|
|
29
|
-
const text = lines[i].trim();
|
|
30
|
-
if (!text)
|
|
31
|
-
continue;
|
|
32
|
-
report.total++;
|
|
33
|
-
let receipt;
|
|
34
|
-
try {
|
|
35
|
-
receipt = JSON.parse(text);
|
|
36
|
-
}
|
|
37
|
-
catch {
|
|
38
|
-
report.unparsable.push(i + 1);
|
|
39
|
-
continue;
|
|
40
|
-
}
|
|
41
|
-
const check = verifyReceipt(receipt, { keys: await keysFor(String(receipt?.kid ?? ""), { keysUrl }) });
|
|
42
|
-
if (check.ok) {
|
|
43
|
-
report.valid++;
|
|
44
|
-
receipts.push(receipt);
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
report.invalid.push({ line: i + 1, receipt_id: receipt?.body?.receipt_id ?? null, problems: check.problems });
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
report.chains = verifyChain(receipts);
|
|
51
|
-
return report;
|
|
52
|
-
}
|