@oked/claude-code 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OKed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # @oked/claude-code
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@oked/claude-code.svg)](https://www.npmjs.com/package/@oked/claude-code)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](./LICENSE)
5
+
6
+ Zero-code integration for Claude Code. Installs a `PreToolUse` hook that routes sensitive actions (destructive Bash commands, payment MCP tools, etc.) through the OKed backend and waits for a human decision before Claude Code proceeds.
7
+
8
+ Non-dangerous actions are left to Claude's normal permission flow - OKed only intervenes when it matters.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install -g @oked/claude-code
14
+ oked init
15
+ ```
16
+
17
+ `oked init` writes a `PreToolUse` hook entry into the current project's `.claude/settings.json`, opens OKed's device-pairing flow in your browser, and stores the paired API key in `~/.oked/config.json`. Open a new Claude Code session in that project to activate the hook.
18
+
19
+ ## Commands
20
+
21
+ | Command | What it does |
22
+ |---|---|
23
+ | `oked init` | Install or update the project hook and pair this device. |
24
+ | `oked status` | Show install state and ping the backend. |
25
+ | `oked uninstall` | Remove the project hook entry (other hooks are preserved). |
26
+
27
+ ## What gets intercepted
28
+
29
+ The hook uses a four-tier classifier:
30
+
31
+ | Tier | Behavior | Examples |
32
+ |---|---|---|
33
+ | `safe` | Auto-allow, no notification | `Read`, `Glob`, read-only Bash (`ls`, `git status`, plain `curl` GET) |
34
+ | `warning` | Terminal log only, no push | `Write` / `Edit` / `NotebookEdit` on a file inside the project |
35
+ | `review` | Push notification, tap to approve | `Write` / `Edit` on a file outside the project, MCP `create_*` / `send_*` / `update_*` |
36
+ | `high_stakes` | Push notification with confirmation | `rm -rf`, `git push --force`, `DROP TABLE`, `delete_*` MCP tools |
37
+
38
+ Everything not matched by the classifier defaults to `review`.
39
+
40
+ ## How it works
41
+
42
+ 1. Claude Code fires the `PreToolUse` hook before every tool call.
43
+ 2. The hook classifies the action locally (no network call for safe actions).
44
+ 3. If it's high-stakes, it sends an approval request to the OKed backend.
45
+ 4. You get a notification (Telegram, web push, or dashboard).
46
+ 5. Approve or deny - Claude waits for your decision.
47
+
48
+ ## Environment
49
+
50
+ | Var | Required | Description |
51
+ |---|---|---|
52
+ | `OKED_API_KEY` | no, after pairing | Optional override. `oked init` normally stores the paired key in `~/.oked/config.json`. |
53
+ | `OKED_BACKEND_URL` | no | Override the hosted backend URL. |
54
+ | `OKED_STRICT_FAIL_CLOSED` | no | Set to `1` or `true` to deny every sensitive action when the backend is unreachable. |
55
+
56
+ ## Degraded-mode behavior
57
+
58
+ Explicit denials and invalid API keys deny the action. If the backend is unreachable, OKed denies `high_stakes` actions and, by default, allows lower tiers so a temporary outage does not stop every Claude Code workflow. If no API key is configured, the hook returns `ask` so Claude Code's native permission flow can handle the decision. Set `OKED_STRICT_FAIL_CLOSED=1` to deny every sensitive action during backend outages.
59
+
60
+ ## License
61
+
62
+ [MIT](./LICENSE)
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/hook.js";
package/bin/oked.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/cli.js";
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,250 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from "fs";
3
+ import { hostname } from "os";
4
+ import { join, dirname } from "path";
5
+ import { spawn } from "child_process";
6
+ import { OKedClient, loadOKedConfig, OKED_CONFIG_PATH } from "@oked/sdk";
7
+ const MCP_TOOL_MATCHER = "mcp__.*";
8
+ const DEFAULT_TOOL_MATCHER = `Bash|Write|Edit|Agent|${MCP_TOOL_MATCHER}`;
9
+ const HOOK_CONFIG = {
10
+ matcher: DEFAULT_TOOL_MATCHER,
11
+ hooks: [
12
+ {
13
+ type: "command",
14
+ command: "oked-hook",
15
+ timeout: 300,
16
+ },
17
+ ],
18
+ };
19
+ const DEFAULT_BACKEND_URL = process.env.OKED_BACKEND_URL || "https://api.oked.ai";
20
+ const CLIENT_VERSION = "0.1.0";
21
+ function getSettingsPath() {
22
+ return join(process.cwd(), ".claude", "settings.json");
23
+ }
24
+ function readSettings(path) {
25
+ if (!existsSync(path))
26
+ return {};
27
+ try {
28
+ return JSON.parse(readFileSync(path, "utf-8"));
29
+ }
30
+ catch {
31
+ return {};
32
+ }
33
+ }
34
+ function writeSettings(path, settings) {
35
+ const dir = join(process.cwd(), ".claude");
36
+ if (!existsSync(dir))
37
+ mkdirSync(dir, { recursive: true });
38
+ writeFileSync(path, JSON.stringify(settings, null, 2) + "\n");
39
+ }
40
+ function writeOkedConfig(apiKey, backendUrl) {
41
+ const dir = dirname(OKED_CONFIG_PATH);
42
+ if (!existsSync(dir))
43
+ mkdirSync(dir, { recursive: true });
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 hasOkedCommandHook(entry) {
55
+ return Boolean(entry.hooks?.some((h) => typeof h === "object" &&
56
+ h !== null &&
57
+ h.command === "oked-hook"));
58
+ }
59
+ function ensureMcpMatcher(matcher) {
60
+ if (!matcher)
61
+ return matcher;
62
+ const parts = matcher.split("|").map((part) => part.trim());
63
+ if (parts.some((part) => part === MCP_TOOL_MATCHER || part.startsWith("mcp__"))) {
64
+ return matcher;
65
+ }
66
+ return `${matcher}|${MCP_TOOL_MATCHER}`;
67
+ }
68
+ function openBrowser(url) {
69
+ const platform = process.platform;
70
+ let cmd;
71
+ let args;
72
+ if (platform === "darwin") {
73
+ cmd = "open";
74
+ args = [url];
75
+ }
76
+ else if (platform === "win32") {
77
+ cmd = "cmd";
78
+ args = ["/c", "start", "", url];
79
+ }
80
+ else {
81
+ cmd = "xdg-open";
82
+ args = [url];
83
+ }
84
+ try {
85
+ spawn(cmd, args, { detached: true, stdio: "ignore" }).unref();
86
+ }
87
+ catch {
88
+ // Best effort. The user has the URL on screen anyway.
89
+ }
90
+ }
91
+ async function pair(clientType) {
92
+ const codeRes = await fetch(`${DEFAULT_BACKEND_URL}/api/v1/device/code`, {
93
+ method: "POST",
94
+ headers: { "Content-Type": "application/json" },
95
+ body: JSON.stringify({
96
+ client_type: clientType,
97
+ hostname: hostname(),
98
+ client_version: CLIENT_VERSION,
99
+ }),
100
+ });
101
+ if (!codeRes.ok) {
102
+ console.log(` Failed to start pairing: ${codeRes.status} ${await codeRes.text()}`);
103
+ return null;
104
+ }
105
+ const code = (await codeRes.json());
106
+ console.log("");
107
+ console.log(" To pair this device, open:");
108
+ console.log(` ${code.verification_uri_complete}`);
109
+ console.log("");
110
+ console.log(" Or visit " + code.verification_uri + " and enter the code:");
111
+ console.log(` ${code.user_code}`);
112
+ console.log("");
113
+ console.log(" Waiting for confirmation in your browser...");
114
+ openBrowser(code.verification_uri_complete);
115
+ const deadline = Date.now() + code.expires_in * 1000;
116
+ const intervalMs = Math.max(1, code.interval) * 1000;
117
+ while (Date.now() < deadline) {
118
+ await new Promise((r) => setTimeout(r, intervalMs));
119
+ const pollRes = await fetch(`${DEFAULT_BACKEND_URL}/api/v1/device/poll`, {
120
+ method: "POST",
121
+ headers: { "Content-Type": "application/json" },
122
+ body: JSON.stringify({ device_code: code.device_code }),
123
+ });
124
+ if (pollRes.status === 410) {
125
+ console.log(" Pairing code expired. Run `oked init` again.");
126
+ return null;
127
+ }
128
+ if (!pollRes.ok)
129
+ continue;
130
+ const body = (await pollRes.json());
131
+ if (body.status === "approved" && body.api_key) {
132
+ return body.api_key;
133
+ }
134
+ }
135
+ console.log(" Pairing timed out. Run `oked init` again.");
136
+ return null;
137
+ }
138
+ async function init() {
139
+ const settingsPath = getSettingsPath();
140
+ const settings = readSettings(settingsPath);
141
+ // Merge OKed hook into existing hooks
142
+ const hooks = (settings.hooks || {});
143
+ const preToolUse = (hooks.PreToolUse || []);
144
+ // Check if OKed hook already exists and upgrade older matchers to cover MCP
145
+ // tools (`mcp__<server>__<tool>`) as regular PreToolUse events.
146
+ let updatedOkedMatcher = false;
147
+ const hasOked = preToolUse.some((entry) => {
148
+ if (!hasOkedCommandHook(entry))
149
+ return false;
150
+ const nextMatcher = ensureMcpMatcher(entry.matcher);
151
+ if (nextMatcher !== entry.matcher) {
152
+ entry.matcher = nextMatcher;
153
+ updatedOkedMatcher = true;
154
+ }
155
+ return true;
156
+ });
157
+ if (!hasOked) {
158
+ preToolUse.push(HOOK_CONFIG);
159
+ hooks.PreToolUse = preToolUse;
160
+ settings.hooks = hooks;
161
+ writeSettings(settingsPath, settings);
162
+ console.log("OKed hook installed.");
163
+ console.log(` Config: ${settingsPath}`);
164
+ }
165
+ else if (updatedOkedMatcher) {
166
+ hooks.PreToolUse = preToolUse;
167
+ settings.hooks = hooks;
168
+ writeSettings(settingsPath, settings);
169
+ console.log("OKed hook updated.");
170
+ console.log(` Config: ${settingsPath}`);
171
+ }
172
+ else {
173
+ console.log("OKed hook already configured.");
174
+ console.log(` Config: ${settingsPath}`);
175
+ }
176
+ // Already paired? Just ping and exit.
177
+ const existingClient = new OKedClient();
178
+ if (existingClient.apiKey) {
179
+ const ok = await existingClient.ping();
180
+ console.log("");
181
+ console.log(` API key: ${existingClient.apiKey.slice(0, 8)}... (already paired)`);
182
+ console.log(` Backend: ${existingClient.backendUrl} (${ok ? "connected" : "not reachable"})`);
183
+ console.log("");
184
+ console.log("Every Claude Code session in this project is now protected.");
185
+ return;
186
+ }
187
+ // Pair this device.
188
+ const apiKey = await pair("claude-code");
189
+ if (!apiKey)
190
+ return;
191
+ writeOkedConfig(apiKey, DEFAULT_BACKEND_URL);
192
+ console.log("");
193
+ console.log(` Paired. Key saved to ${OKED_CONFIG_PATH}`);
194
+ console.log("");
195
+ console.log("Every Claude Code session in this project is now protected.");
196
+ }
197
+ async function status() {
198
+ const settingsPath = getSettingsPath();
199
+ const settings = readSettings(settingsPath);
200
+ const hooks = (settings.hooks || {});
201
+ const preToolUse = (hooks.PreToolUse || []);
202
+ const hasOked = preToolUse.some(hasOkedCommandHook);
203
+ const client = new OKedClient();
204
+ console.log(`OKed status:`);
205
+ console.log(` Hook: ${hasOked ? "installed" : "not installed"}`);
206
+ console.log(` Project config: ${existsSync(settingsPath) ? settingsPath : "not found"}`);
207
+ console.log(` API key: ${client.apiKey ? client.apiKey.slice(0, 8) + "..." : "not paired"}`);
208
+ console.log(` User config: ${existsSync(OKED_CONFIG_PATH) ? OKED_CONFIG_PATH : "not found"}`);
209
+ if (client.apiKey) {
210
+ const ok = await client.ping();
211
+ console.log(` Backend: ${client.backendUrl} (${ok ? "connected" : "not reachable"})`);
212
+ }
213
+ }
214
+ function uninstall() {
215
+ const settingsPath = getSettingsPath();
216
+ const settings = readSettings(settingsPath);
217
+ const hooks = (settings.hooks || {});
218
+ const preToolUse = (hooks.PreToolUse || []);
219
+ // Remove OKed hook entries
220
+ hooks.PreToolUse = preToolUse.filter((entry) => !hasOkedCommandHook(entry));
221
+ if (hooks.PreToolUse.length === 0) {
222
+ delete hooks.PreToolUse;
223
+ }
224
+ if (Object.keys(hooks).length === 0) {
225
+ delete settings.hooks;
226
+ }
227
+ writeSettings(settingsPath, settings);
228
+ console.log("OKed hooks removed from this project.");
229
+ }
230
+ // CLI entry point
231
+ const command = process.argv[2];
232
+ switch (command) {
233
+ case "init":
234
+ init().catch(console.error);
235
+ break;
236
+ case "status":
237
+ status().catch(console.error);
238
+ break;
239
+ case "uninstall":
240
+ uninstall();
241
+ break;
242
+ default:
243
+ console.log("Usage: oked <command>");
244
+ console.log("");
245
+ console.log("Commands:");
246
+ console.log(" init Install OKed hooks in current project and pair this device");
247
+ console.log(" status Show current config and connection status");
248
+ console.log(" uninstall Remove OKed hooks from current project");
249
+ break;
250
+ }
package/dist/hook.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/hook.js ADDED
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ import { OKedClient, classify, describe, describeFields, applyRules, degradedDecision, OKedAuthError, OKedBackendUnreachableError, } from "@oked/sdk";
3
+ function makeOutput(decision, reason) {
4
+ return {
5
+ hookSpecificOutput: {
6
+ hookEventName: "PreToolUse",
7
+ permissionDecision: decision,
8
+ ...(reason && { permissionDecisionReason: reason }),
9
+ },
10
+ };
11
+ }
12
+ function log(msg) {
13
+ process.stderr.write(`[OKed] ${msg}\n`);
14
+ }
15
+ async function main() {
16
+ // Read hook input from stdin
17
+ let rawInput = "";
18
+ for await (const chunk of process.stdin) {
19
+ rawInput += chunk;
20
+ }
21
+ let input;
22
+ try {
23
+ input = JSON.parse(rawInput);
24
+ }
25
+ catch {
26
+ // Can't parse input - don't break Claude, let it through
27
+ process.stdout.write(JSON.stringify(makeOutput("allow")));
28
+ return;
29
+ }
30
+ const { tool_name: toolName, tool_input: toolInput } = input;
31
+ // Classify risk
32
+ const tier = classify(toolName, toolInput);
33
+ const client = new OKedClient();
34
+ // Presence ping (throttled to once/day on disk, never throws). Fired before
35
+ // the safe/warning fast-path return so installs that only ever run safe
36
+ // actions still register for retention. Bounded by the 3s internal timeout,
37
+ // and only the once/day send actually waits.
38
+ if (client.apiKey)
39
+ await client.heartbeat();
40
+ const fields = describeFields(toolName, toolInput) ?? undefined;
41
+ // safe/warning normally short-circuit locally with no network call. But a
42
+ // user rule can escalate (or auto-decide) such an action, and rules live
43
+ // server-side. Consult the locally-cached rules: if one matches this action,
44
+ // route it to the backend so the rule is applied authoritatively. With no
45
+ // matching rule (the common case) we keep the cheap local fast-path.
46
+ if (tier === "safe" || tier === "warning") {
47
+ let ruleMatches = false;
48
+ if (client.apiKey) {
49
+ try {
50
+ const rules = await client.getRules();
51
+ if (rules.length > 0) {
52
+ const decision = applyRules({ tier, fields: fields ?? {} }, rules, { cwd: input.cwd });
53
+ ruleMatches = Boolean(decision.appliedRuleId);
54
+ }
55
+ }
56
+ catch {
57
+ // Advisory: a failed rules lookup must never block the action.
58
+ }
59
+ }
60
+ if (!ruleMatches) {
61
+ if (tier === "warning") {
62
+ const summary = (toolInput.file_path ?? toolInput.command ?? toolName);
63
+ process.stderr.write(`WARNING OKed: ${toolName} ${summary} - allowed (inside project)\n`);
64
+ }
65
+ process.stdout.write(JSON.stringify(makeOutput("allow")));
66
+ return;
67
+ }
68
+ // A rule matched a normally-silent action — fall through to the backend,
69
+ // which applies the rule authoritatively (escalate / auto-decide + audit).
70
+ }
71
+ // Check if API key is configured
72
+ if (!client.apiKey) {
73
+ log("not paired - run `oked init` to pair this device. Falling back to Claude's built-in prompt.");
74
+ process.stdout.write(JSON.stringify(makeOutput("ask")));
75
+ return;
76
+ }
77
+ // Generate human-readable description
78
+ const description = describe(toolName, toolInput);
79
+ log(`${toolName}: "${description}" - ${tier}`);
80
+ log("Requesting approval... (check your phone)");
81
+ try {
82
+ const result = await client.approve({
83
+ action: toolName,
84
+ description,
85
+ tier,
86
+ fields,
87
+ tool_input: toolInput,
88
+ session_id: input.session_id,
89
+ cwd: input.cwd,
90
+ });
91
+ if (result.approved) {
92
+ log(`Approved (${result.approval_id})`);
93
+ process.stdout.write(JSON.stringify(makeOutput("allow", `Approved via OKed`)));
94
+ }
95
+ else {
96
+ log(`Denied (${result.approval_id})`);
97
+ process.stdout.write(JSON.stringify(makeOutput("deny", `Denied via OKed: ${description}`)));
98
+ }
99
+ }
100
+ catch (err) {
101
+ if (err instanceof OKedAuthError) {
102
+ // Auth misconfig is not an outage - always deny.
103
+ log(`Invalid API key - action denied`);
104
+ process.stdout.write(JSON.stringify(makeOutput("deny", "OKed: invalid API key")));
105
+ }
106
+ else if (err instanceof OKedBackendUnreachableError) {
107
+ const decision = degradedDecision(tier, {
108
+ strictFailClosed: client.strictFailClosed,
109
+ });
110
+ if (decision === "allow") {
111
+ log(`Backend unreachable - allowed (degraded; ${tier}, non-high-stakes)`);
112
+ process.stdout.write(JSON.stringify(makeOutput("allow", "OKed backend unreachable - allowed (degraded; non-high-stakes)")));
113
+ }
114
+ else {
115
+ const why = client.strictFailClosed
116
+ ? "strict fail-closed"
117
+ : "high-stakes";
118
+ log(`Backend unreachable - ${why} denied (fail-safe)`);
119
+ process.stdout.write(JSON.stringify(makeOutput("deny", `OKed backend unreachable - ${why} denied (fail-safe)`)));
120
+ }
121
+ }
122
+ else {
123
+ // Unknown error - fail safe deny.
124
+ log(`Unexpected error - action denied (fail-safe)`);
125
+ process.stdout.write(JSON.stringify(makeOutput("deny", "OKed: unexpected error (fail-safe)")));
126
+ }
127
+ }
128
+ }
129
+ main().catch((err) => {
130
+ process.stderr.write(`[OKed] Fatal: ${err}\n`);
131
+ // Fail-safe: deny
132
+ process.stdout.write(JSON.stringify(makeOutput("deny", "OKed: internal error (fail-safe)")));
133
+ process.exit(0); // exit 0 so Claude reads our JSON, not a crash
134
+ });
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@oked/claude-code",
3
+ "version": "0.1.0",
4
+ "description": "OKed for Claude Code - zero-code human approval for sensitive actions",
5
+ "type": "module",
6
+ "bin": {
7
+ "oked": "./bin/oked.js",
8
+ "oked-hook": "./bin/oked-hook.js"
9
+ },
10
+ "scripts": {
11
+ "prebuild": "npm run build --workspace=@oked/sdk",
12
+ "build": "tsc",
13
+ "prepublishOnly": "npm run build"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "bin",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "keywords": [
22
+ "claude-code",
23
+ "claude",
24
+ "approval",
25
+ "hook",
26
+ "agents",
27
+ "oked"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/oked-ai/oked-sdk.git",
32
+ "directory": "packages/claude-code"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/oked-ai/oked-sdk/issues"
36
+ },
37
+ "homepage": "https://github.com/oked-ai/oked-sdk#readme",
38
+ "license": "MIT",
39
+ "engines": {
40
+ "node": ">=18"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@oked/sdk": "0.1.0"
47
+ },
48
+ "devDependencies": {
49
+ "typescript": "^5.6.0"
50
+ }
51
+ }