@oked/hook-core 0.0.0-stage → 0.6.23

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @oked/hook-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/@oked/hook-core.svg)](https://www.npmjs.com/package/@oked/hook-core)
4
+ [![License: Apache-2.0](https://img.shields.io/npm/l/@oked/hook-core.svg)](./LICENSE)
5
+
6
+ Shared gate for OKed coding-agent hooks. It is the part of [`@oked/claude-code`](../claude-code) that does not depend on Claude Code: classify the tool call, build the approval request, wait for a person, check the signed receipt, and fail closed.
7
+
8
+ Host packages read the host's payload, map tool names, call `decide()`, and write the host's own allow or deny output. `@oked/claude-code` does this with unchanged behavior. `@oked/codex`, `@oked/cursor`, and `@oked/copilot` do it for those hosts.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install @oked/hook-core
14
+ ```
15
+
16
+ This package has no `init` command. Install a host package (`@oked/claude-code`, `@oked/codex`, `@oked/cursor`, or `@oked/copilot`) unless you are building a hook.
17
+
18
+ Decisions are made in Telegram or on the [web dashboard](https://oked.ai/dashboard). The iPhone app is coming soon. Questions: [contact@oked.ai](mailto:contact@oked.ai).
19
+
20
+ ## What `decide()` does
21
+
22
+ 1. Classify the call with `@oked/sdk`. `safe` returns allow, with no notification. `warning` returns allow and writes a terminal line. A cached user rule that matches either tier sends the call to the backend instead. For `source: "claude-code"`, an opaque runner (`cargo test`, `npm test`, a script file, `npx`) is `review` unless Claude Code's Bash sandbox is on with `allowUnsandboxedCommands: false`. Other sources leave those commands `safe`.
23
+ 2. With no API key, return the host's unpaired decision. Claude Code asks the host's own prompt. A host that cannot enforce `ask` should deny, and the reason should say `Pair first`.
24
+ 3. For `review` and `high_stakes`, send the approval and wait. The SDK waits 630 seconds (`DEFAULT_APPROVAL_TIMEOUT_MS`), which is 30 seconds past the backend's 10 minute window.
25
+ 4. An approval counts only when the signed receipt verifies. The hook keeps a copy in `~/.oked/receipts.jsonl`.
26
+ 5. An explicit denial, a bad key, a bad receipt, HTTP 429, and any unexpected error deny. If the backend is unreachable, `high_stakes` denies and lower tiers allow, unless `OKED_STRICT_FAIL_CLOSED` is set. A backend `decision` of `timeout` denies.
27
+
28
+ `HOOK_TIMEOUT_SECONDS` is 690. A host that can set a hook timeout must set it at least that high, so the SDK's deny is written before the host kills the process. A killed hook prints nothing, and most hosts then let the tool call continue. Cursor can also set `failClosed` so a killed hook denies. Codex and Copilot fail open on timeout, and their installers still set 690 so the SDK finishes first when the host honors it.
29
+
30
+ ## Tool names
31
+
32
+ `classify()` knows Claude Code names (`Bash`, `Write`, `Edit`, `mcp__server__tool`). Host packages map their own names onto those before calling `decide()`. Unknown names stay unknown, and the classifier treats an unknown tool as `review` (approval required). `mapPatch()` and `mapFileDelete()` turn patches and deletes into the same effect classes the bash classifier already uses.
33
+
34
+ `findClaudeOkedHooks()` reports an existing `oked-hook` entry in Claude settings. A host that also loads those files uses it so one action is not asked twice.
35
+
36
+ ## Troubleshooting
37
+
38
+ - No API key: `decide()` returns the unpaired decision. It does not silently allow a risky call.
39
+ - Backend down: `high_stakes` denies. Lower sensitive tiers allow unless `OKED_STRICT_FAIL_CLOSED=1`.
40
+ - Receipt missing or invalid: the approval is denied. `OKED_REQUIRE_RECEIPT=0` is only for a backend that does not sign receipts.
41
+ - Hook killed before it prints: the host's own timeout is below 690, or the host failed open. Raise the host timeout. On Cursor, set `failClosed`.
42
+
43
+ ## License
44
+
45
+ [Apache-2.0](./LICENSE)
@@ -0,0 +1,17 @@
1
+ export type ClaudeHookScope = "user" | "project" | "project-local";
2
+ export interface ClaudeHookHit {
3
+ scope: ClaudeHookScope;
4
+ path: string;
5
+ }
6
+ /** User-level Claude Code settings. `CLAUDE_CONFIG_DIR` moves the directory. */
7
+ export declare function claudeUserSettingsPath(): string;
8
+ /** True when a Claude settings object has an `oked-hook` PreToolUse command. */
9
+ export declare function settingsHasOkedHook(settings: unknown): boolean;
10
+ /**
11
+ * Claude settings files that already install `@oked/claude-code`.
12
+ * Cursor reads the user file and both project files. Copilot's CLI and VS
13
+ * Code read the two project files. Pass `includeUser: false` for Copilot.
14
+ */
15
+ export declare function findClaudeOkedHooks(cwd: string, opts?: {
16
+ includeUser?: boolean;
17
+ }): ClaudeHookHit[];
@@ -0,0 +1,62 @@
1
+ import { existsSync, readFileSync } from "fs";
2
+ import { homedir } from "os";
3
+ import { join } from "path";
4
+ /** User-level Claude Code settings. `CLAUDE_CONFIG_DIR` moves the directory. */
5
+ export function claudeUserSettingsPath() {
6
+ return join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "settings.json");
7
+ }
8
+ function commandIsOkedHook(command) {
9
+ if (typeof command !== "string")
10
+ return false;
11
+ const trimmed = command.trim();
12
+ return (trimmed === "oked-hook" ||
13
+ trimmed.endsWith("/oked-hook") ||
14
+ trimmed.endsWith("\\oked-hook"));
15
+ }
16
+ /** True when a Claude settings object has an `oked-hook` PreToolUse command. */
17
+ export function settingsHasOkedHook(settings) {
18
+ if (!settings || typeof settings !== "object")
19
+ return false;
20
+ const pre = settings.hooks?.PreToolUse;
21
+ if (!Array.isArray(pre))
22
+ return false;
23
+ for (const entry of pre) {
24
+ if (!entry || typeof entry !== "object")
25
+ continue;
26
+ const list = entry.hooks;
27
+ if (!Array.isArray(list))
28
+ continue;
29
+ if (list.some((hook) => hook && typeof hook === "object" && commandIsOkedHook(hook.command))) {
30
+ return true;
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+ /**
36
+ * Claude settings files that already install `@oked/claude-code`.
37
+ * Cursor reads the user file and both project files. Copilot's CLI and VS
38
+ * Code read the two project files. Pass `includeUser: false` for Copilot.
39
+ */
40
+ export function findClaudeOkedHooks(cwd, opts) {
41
+ const candidates = [
42
+ { scope: "project-local", path: join(cwd, ".claude", "settings.local.json") },
43
+ { scope: "project", path: join(cwd, ".claude", "settings.json") },
44
+ ];
45
+ if (opts?.includeUser !== false) {
46
+ candidates.push({ scope: "user", path: claudeUserSettingsPath() });
47
+ }
48
+ const hits = [];
49
+ for (const candidate of candidates) {
50
+ if (!existsSync(candidate.path))
51
+ continue;
52
+ try {
53
+ const parsed = JSON.parse(readFileSync(candidate.path, "utf-8"));
54
+ if (settingsHasOkedHook(parsed))
55
+ hits.push(candidate);
56
+ }
57
+ catch {
58
+ // A file that does not parse is not a hook we can see.
59
+ }
60
+ }
61
+ return hits;
62
+ }
@@ -0,0 +1,54 @@
1
+ export interface ToolCallInput {
2
+ toolName: string;
3
+ toolInput: Record<string, unknown>;
4
+ cwd?: string;
5
+ sessionId?: string;
6
+ }
7
+ export type PermissionDecision = "allow" | "deny" | "ask";
8
+ export interface GateDecision {
9
+ decision: PermissionDecision;
10
+ /** Omitted when the host should continue with no reason text. */
11
+ reason?: string;
12
+ }
13
+ export interface DecideOptions {
14
+ /** Recorded on receipts and in the decision log, e.g. `@oked/claude-code@0.6.22`. */
15
+ clientId: string;
16
+ /** Receipt subject source, e.g. `claude-code`. */
17
+ source: string;
18
+ /**
19
+ * What to do when this device has no API key.
20
+ * Claude Code uses `ask` so the host's own prompt can decide.
21
+ * Hosts that treat `ask` as allow, or that ignore it, must use `deny`.
22
+ */
23
+ unpaired?: "ask" | "deny";
24
+ /** Reason returned to the host when unpaired. */
25
+ unpairedReason: string;
26
+ /** stderr line, without the `[OKed]` prefix, when unpaired. */
27
+ unpairedLog: string;
28
+ /**
29
+ * Sentence for an invalid API key. The default matches `@oked/claude-code`.
30
+ * Other hosts pass a sentence that names their own init command.
31
+ */
32
+ invalidKeyReason?: (status: number) => string;
33
+ log?: (msg: string) => void;
34
+ /**
35
+ * When set, overrides Claude Code sandbox detection.
36
+ * `false`: an opaque code runner (test runner, script file, npx) is `review`.
37
+ * `true`: those commands stay `safe`.
38
+ * Omitted: `source: "claude-code"` reads sandbox settings. Other hosts omit
39
+ * it and keep the previous behaviour.
40
+ */
41
+ sandboxEnforced?: boolean;
42
+ }
43
+ /**
44
+ * Classify one tool call and, when the tier needs a person, wait for the
45
+ * decision. Safe and warning calls return allow without a prompt, unless a
46
+ * cached user rule matches. Receipts are checked by the SDK before an approval
47
+ * counts. Explicit denials, auth failures, bad receipts, and unexpected errors
48
+ * deny. An unreachable backend follows `degradedDecision`.
49
+ *
50
+ * This function does not write host output. The caller maps `decision` onto
51
+ * the host's protocol. It does write the shared decision log and the local
52
+ * receipt copy, matching `@oked/claude-code`.
53
+ */
54
+ export declare function decide(call: ToolCallInput, options: DecideOptions): Promise<GateDecision>;
package/dist/decide.js ADDED
@@ -0,0 +1,167 @@
1
+ import { OKedClient, classify, describe, describeFields, lookupPrTitle, applyRules, degradedDecision, OKedAuthError, OKedBackendUnreachableError, OKedHttpError, OKedReceiptError, OKedTooManyPendingError, shortReceiptId, } from "@oked/sdk";
2
+ import { appendReceipt } from "./receipts.js";
3
+ import { errorInfo, logDecision } from "./log.js";
4
+ import { claudeSandboxEnforced } from "./sandbox.js";
5
+ function defaultInvalidKeyReason(status) {
6
+ return `OKed: invalid API key (HTTP ${status}). Run \`oked init\` to pair again, or \`oked uninstall\` to remove OKed.`;
7
+ }
8
+ function errorText(err) {
9
+ const info = errorInfo(err);
10
+ return `${info.name}: ${info.message}`;
11
+ }
12
+ function commandOf(toolInput) {
13
+ const command = toolInput.command ?? toolInput.cmd;
14
+ return typeof command === "string" ? command : undefined;
15
+ }
16
+ /**
17
+ * Classify one tool call and, when the tier needs a person, wait for the
18
+ * decision. Safe and warning calls return allow without a prompt, unless a
19
+ * cached user rule matches. Receipts are checked by the SDK before an approval
20
+ * counts. Explicit denials, auth failures, bad receipts, and unexpected errors
21
+ * deny. An unreachable backend follows `degradedDecision`.
22
+ *
23
+ * This function does not write host output. The caller maps `decision` onto
24
+ * the host's protocol. It does write the shared decision log and the local
25
+ * receipt copy, matching `@oked/claude-code`.
26
+ */
27
+ export async function decide(call, options) {
28
+ const log = options.log ??
29
+ ((msg) => {
30
+ process.stderr.write(`[OKed] ${msg}\n`);
31
+ });
32
+ const unpaired = options.unpaired ?? "deny";
33
+ const finish = (decision, reason, ctx) => {
34
+ if (decision !== "allow" || ctx.degraded) {
35
+ logDecision({
36
+ decision,
37
+ reason: reason ?? "",
38
+ client: options.clientId,
39
+ ...ctx,
40
+ });
41
+ }
42
+ return reason ? { decision, reason } : { decision };
43
+ };
44
+ const toolName = call.toolName;
45
+ const toolInput = call.toolInput;
46
+ const command = commandOf(toolInput);
47
+ const sandboxEnforced = options.sandboxEnforced !== undefined
48
+ ? options.sandboxEnforced
49
+ : options.source === "claude-code"
50
+ ? claudeSandboxEnforced(call.cwd ?? process.cwd(), command)
51
+ : undefined;
52
+ const tier = classify(toolName, toolInput, sandboxEnforced === undefined ? undefined : { sandboxEnforced });
53
+ const describeCtx = {
54
+ cwd: call.cwd,
55
+ ...(sandboxEnforced === false ? { sandboxEnforced: false } : {}),
56
+ };
57
+ const client = new OKedClient({ client: options.clientId, source: options.source });
58
+ // Presence ping (throttled to once/day on disk, never throws). Fired before
59
+ // the safe/warning fast-path return so installs that only ever run safe
60
+ // actions still register for retention. Bounded by the 3s internal timeout,
61
+ // and only the once/day send actually waits.
62
+ if (client.apiKey)
63
+ await client.heartbeat();
64
+ let fields = describeFields(toolName, toolInput, describeCtx) ?? undefined;
65
+ // safe/warning normally short-circuit locally with no network call. But a
66
+ // user rule can escalate (or auto-decide) such an action, and rules live
67
+ // server-side. Consult the locally-cached rules: if one matches this action,
68
+ // route it to the backend so the rule is applied authoritatively. With no
69
+ // matching rule (the common case) we keep the cheap local fast-path.
70
+ if (tier === "safe" || tier === "warning") {
71
+ let ruleMatches = false;
72
+ if (client.apiKey) {
73
+ try {
74
+ const rules = await client.getRules();
75
+ if (rules.length > 0) {
76
+ const decision = applyRules({ tier, fields: fields ?? {} }, rules, { cwd: call.cwd ?? "" });
77
+ ruleMatches = Boolean(decision.appliedRuleId);
78
+ }
79
+ }
80
+ catch {
81
+ // Advisory: a failed rules lookup must never block the action.
82
+ }
83
+ }
84
+ if (!ruleMatches) {
85
+ if (tier === "warning") {
86
+ const summary = (toolInput.file_path ?? toolInput.command ?? toolName);
87
+ process.stderr.write(`WARNING OKed: ${toolName} ${summary} - allowed (inside project)\n`);
88
+ }
89
+ return { decision: "allow" };
90
+ }
91
+ }
92
+ const ctx = { tool: toolName, tier };
93
+ if (!client.apiKey) {
94
+ log(options.unpairedLog);
95
+ return finish(unpaired, options.unpairedReason, ctx);
96
+ }
97
+ const prTitle = await lookupPrTitle(fields);
98
+ if (prTitle)
99
+ fields = describeFields(toolName, toolInput, { ...describeCtx, prTitle }) ?? undefined;
100
+ const description = describe(toolName, toolInput, { ...describeCtx, 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: call.sessionId,
111
+ cwd: call.cwd,
112
+ });
113
+ if (result.receipt)
114
+ appendReceipt(result.receipt);
115
+ const receiptNote = result.receipt ? ` (receipt ${shortReceiptId(result.receipt.body.receipt_id)})` : "";
116
+ const decided = {
117
+ ...ctx,
118
+ approval_id: result.approval_id,
119
+ receipt_id: result.receipt?.body.receipt_id ?? null,
120
+ };
121
+ if (result.approved) {
122
+ log(`Approved (${result.approval_id})${receiptNote}`);
123
+ return finish("allow", `Approved via OKed${receiptNote}`, decided);
124
+ }
125
+ if (result.decision === "timeout") {
126
+ log(`No decision in time (${result.approval_id})${receiptNote}`);
127
+ return finish("deny", `OKed: no decision within the approval window (timed out): ${description}`, decided);
128
+ }
129
+ log(`Denied (${result.approval_id})${receiptNote}`);
130
+ return finish("deny", `Denied via OKed: ${description}`, decided);
131
+ }
132
+ catch (err) {
133
+ const failed = { ...ctx, error: errorInfo(err) };
134
+ if (err instanceof OKedReceiptError) {
135
+ log(`Approval receipt did not verify (${err.problems.join(", ")}) - action denied`);
136
+ return finish("deny", `OKed: the approval receipt did not verify (${err.problems.join(", ")}); action denied`, failed);
137
+ }
138
+ if (err instanceof OKedAuthError) {
139
+ log(`Invalid API key (HTTP ${err.status}) - action denied`);
140
+ const reason = (options.invalidKeyReason ?? defaultInvalidKeyReason)(err.status);
141
+ return finish("deny", reason, failed);
142
+ }
143
+ if (err instanceof OKedTooManyPendingError) {
144
+ log(`Too many pending approvals (HTTP 429) - action denied`);
145
+ return finish("deny", err.message, failed);
146
+ }
147
+ if (err instanceof OKedHttpError) {
148
+ log(`Backend error HTTP ${err.status} - action denied (fail-safe)`);
149
+ return finish("deny", `OKed: backend error HTTP ${err.status}${err.detail ? `: ${err.detail}` : ""} (fail-safe deny)`, failed);
150
+ }
151
+ if (err instanceof OKedBackendUnreachableError) {
152
+ const decision = degradedDecision(tier, {
153
+ strictFailClosed: client.strictFailClosed,
154
+ });
155
+ const cause = errorInfo(err).message;
156
+ if (decision === "allow") {
157
+ log(`Backend unreachable (${cause}) - allowed (degraded; ${tier}, non-high-stakes)`);
158
+ return finish("allow", `OKed backend unreachable (${cause}) - allowed (degraded; non-high-stakes)`, { ...failed, degraded: true });
159
+ }
160
+ const why = client.strictFailClosed ? "strict fail-closed" : "high-stakes";
161
+ log(`Backend unreachable (${cause}) - ${why} denied (fail-safe)`);
162
+ return finish("deny", `OKed backend unreachable (${cause}) - ${why} denied (fail-safe)`, failed);
163
+ }
164
+ log(`Unexpected error (${errorText(err)}) - action denied (fail-safe)`);
165
+ return finish("deny", `OKed: unexpected error (fail-safe): ${errorText(err)}`, failed);
166
+ }
167
+ }
@@ -0,0 +1,9 @@
1
+ export { decide, type ToolCallInput, type DecideOptions, type GateDecision, type PermissionDecision } from "./decide.js";
2
+ export { HOOK_TIMEOUT_SECONDS } from "./timeout.js";
3
+ export { logDecision, errorInfo, OKED_HOOK_LOG, type DecisionLogEntry, type ErrorInfo, } from "./log.js";
4
+ export { appendReceipt, verifyReceiptsFile, OKED_RECEIPTS_LOG, type LocalVerifyReport, } from "./receipts.js";
5
+ export { findClaudeOkedHooks, settingsHasOkedHook, claudeUserSettingsPath, type ClaudeHookHit, type ClaudeHookScope, } from "./claude-hooks.js";
6
+ export { stringField, withNormalizedFields, asToolInput, shQuote, mapFileDelete, extractPatchPaths, mapPatch, } from "./normalize.js";
7
+ export { pairDevice, writeOkedConfig, maskKey, type PairOptions } from "./pair.js";
8
+ export { claudeSandboxEnforced, readClaudeSandbox, exclusionCoversCommand, SANDBOX_INIT_HINT, type ClaudeSandboxView, } from "./sandbox.js";
9
+ export { encodeQR, renderQR } from "./qr.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { decide } from "./decide.js";
2
+ export { HOOK_TIMEOUT_SECONDS } from "./timeout.js";
3
+ export { logDecision, errorInfo, OKED_HOOK_LOG, } from "./log.js";
4
+ export { appendReceipt, verifyReceiptsFile, OKED_RECEIPTS_LOG, } from "./receipts.js";
5
+ export { findClaudeOkedHooks, settingsHasOkedHook, claudeUserSettingsPath, } from "./claude-hooks.js";
6
+ export { stringField, withNormalizedFields, asToolInput, shQuote, mapFileDelete, extractPatchPaths, mapPatch, } from "./normalize.js";
7
+ export { pairDevice, writeOkedConfig, maskKey } from "./pair.js";
8
+ export { claudeSandboxEnforced, readClaudeSandbox, exclusionCoversCommand, SANDBOX_INIT_HINT, } from "./sandbox.js";
9
+ export { encodeQR, renderQR } from "./qr.js";
package/dist/log.d.ts ADDED
@@ -0,0 +1,30 @@
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/log.js ADDED
@@ -0,0 +1,39 @@
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
+ }