@oked/hook-core 0.0.0-stage → 0.6.21
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 +201 -0
- package/README.md +36 -2
- package/dist/claude-hooks.d.ts +17 -0
- package/dist/claude-hooks.js +62 -0
- package/dist/decide.d.ts +46 -0
- package/dist/decide.js +152 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/log.d.ts +30 -0
- package/dist/log.js +39 -0
- package/dist/normalize.d.ts +39 -0
- package/dist/normalize.js +124 -0
- package/dist/pair.d.ts +29 -0
- package/dist/pair.js +210 -0
- package/dist/qr.d.ts +7 -0
- package/dist/qr.js +332 -0
- package/dist/receipts.d.ts +23 -0
- package/dist/receipts.js +52 -0
- package/dist/timeout.d.ts +12 -0
- package/dist/timeout.js +13 -0
- package/package.json +54 -4
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,37 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @oked/hook-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@oked/hook-core)
|
|
4
|
+
[](./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. Install a host package. This package has no `init` command.
|
|
9
|
+
|
|
10
|
+
Decisions are made in Telegram or on the [web dashboard](https://oked.ai/dashboard?ref=github-hook-core). The iPhone app is coming soon. Questions: [contact@oked.ai](mailto:contact@oked.ai).
|
|
11
|
+
|
|
12
|
+
## What `decide()` does
|
|
13
|
+
|
|
14
|
+
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.
|
|
15
|
+
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`.
|
|
16
|
+
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.
|
|
17
|
+
4. An approval counts only when the signed receipt verifies. The hook keeps a copy in `~/.oked/receipts.jsonl`.
|
|
18
|
+
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.
|
|
19
|
+
|
|
20
|
+
`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.
|
|
21
|
+
|
|
22
|
+
## Tool names
|
|
23
|
+
|
|
24
|
+
`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.
|
|
25
|
+
|
|
26
|
+
`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.
|
|
27
|
+
|
|
28
|
+
## Troubleshooting
|
|
29
|
+
|
|
30
|
+
- No API key: `decide()` returns the unpaired decision. It does not silently allow a risky call.
|
|
31
|
+
- Backend down: `high_stakes` denies. Lower sensitive tiers allow unless `OKED_STRICT_FAIL_CLOSED=1`.
|
|
32
|
+
- Receipt missing or invalid: the approval is denied. `OKED_REQUIRE_RECEIPT=0` is only for a backend that does not sign receipts.
|
|
33
|
+
- 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`.
|
|
34
|
+
|
|
35
|
+
## License
|
|
36
|
+
|
|
37
|
+
[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
|
+
}
|
package/dist/decide.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
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.21`. */
|
|
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
|
+
/**
|
|
36
|
+
* Classify one tool call and, when the tier needs a person, wait for the
|
|
37
|
+
* decision. Safe and warning calls return allow without a prompt, unless a
|
|
38
|
+
* cached user rule matches. Receipts are checked by the SDK before an approval
|
|
39
|
+
* counts. Explicit denials, auth failures, bad receipts, and unexpected errors
|
|
40
|
+
* deny. An unreachable backend follows `degradedDecision`.
|
|
41
|
+
*
|
|
42
|
+
* This function does not write host output. The caller maps `decision` onto
|
|
43
|
+
* the host's protocol. It does write the shared decision log and the local
|
|
44
|
+
* receipt copy, matching `@oked/claude-code`.
|
|
45
|
+
*/
|
|
46
|
+
export declare function decide(call: ToolCallInput, options: DecideOptions): Promise<GateDecision>;
|
package/dist/decide.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
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
|
+
function defaultInvalidKeyReason(status) {
|
|
5
|
+
return `OKed: invalid API key (HTTP ${status}). Run \`oked init\` to pair again, or \`oked uninstall\` to remove OKed.`;
|
|
6
|
+
}
|
|
7
|
+
function errorText(err) {
|
|
8
|
+
const info = errorInfo(err);
|
|
9
|
+
return `${info.name}: ${info.message}`;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Classify one tool call and, when the tier needs a person, wait for the
|
|
13
|
+
* decision. Safe and warning calls return allow without a prompt, unless a
|
|
14
|
+
* cached user rule matches. Receipts are checked by the SDK before an approval
|
|
15
|
+
* counts. Explicit denials, auth failures, bad receipts, and unexpected errors
|
|
16
|
+
* deny. An unreachable backend follows `degradedDecision`.
|
|
17
|
+
*
|
|
18
|
+
* This function does not write host output. The caller maps `decision` onto
|
|
19
|
+
* the host's protocol. It does write the shared decision log and the local
|
|
20
|
+
* receipt copy, matching `@oked/claude-code`.
|
|
21
|
+
*/
|
|
22
|
+
export async function decide(call, options) {
|
|
23
|
+
const log = options.log ??
|
|
24
|
+
((msg) => {
|
|
25
|
+
process.stderr.write(`[OKed] ${msg}\n`);
|
|
26
|
+
});
|
|
27
|
+
const unpaired = options.unpaired ?? "deny";
|
|
28
|
+
const finish = (decision, reason, ctx) => {
|
|
29
|
+
if (decision !== "allow" || ctx.degraded) {
|
|
30
|
+
logDecision({
|
|
31
|
+
decision,
|
|
32
|
+
reason: reason ?? "",
|
|
33
|
+
client: options.clientId,
|
|
34
|
+
...ctx,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return reason ? { decision, reason } : { decision };
|
|
38
|
+
};
|
|
39
|
+
const toolName = call.toolName;
|
|
40
|
+
const toolInput = call.toolInput;
|
|
41
|
+
const tier = classify(toolName, toolInput);
|
|
42
|
+
const client = new OKedClient({ client: options.clientId, source: options.source });
|
|
43
|
+
// Presence ping (throttled to once/day on disk, never throws). Fired before
|
|
44
|
+
// the safe/warning fast-path return so installs that only ever run safe
|
|
45
|
+
// actions still register for retention. Bounded by the 3s internal timeout,
|
|
46
|
+
// and only the once/day send actually waits.
|
|
47
|
+
if (client.apiKey)
|
|
48
|
+
await client.heartbeat();
|
|
49
|
+
let fields = describeFields(toolName, toolInput, { cwd: call.cwd }) ?? undefined;
|
|
50
|
+
// safe/warning normally short-circuit locally with no network call. But a
|
|
51
|
+
// user rule can escalate (or auto-decide) such an action, and rules live
|
|
52
|
+
// server-side. Consult the locally-cached rules: if one matches this action,
|
|
53
|
+
// route it to the backend so the rule is applied authoritatively. With no
|
|
54
|
+
// matching rule (the common case) we keep the cheap local fast-path.
|
|
55
|
+
if (tier === "safe" || tier === "warning") {
|
|
56
|
+
let ruleMatches = false;
|
|
57
|
+
if (client.apiKey) {
|
|
58
|
+
try {
|
|
59
|
+
const rules = await client.getRules();
|
|
60
|
+
if (rules.length > 0) {
|
|
61
|
+
const decision = applyRules({ tier, fields: fields ?? {} }, rules, { cwd: call.cwd ?? "" });
|
|
62
|
+
ruleMatches = Boolean(decision.appliedRuleId);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// Advisory: a failed rules lookup must never block the action.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (!ruleMatches) {
|
|
70
|
+
if (tier === "warning") {
|
|
71
|
+
const summary = (toolInput.file_path ?? toolInput.command ?? toolName);
|
|
72
|
+
process.stderr.write(`WARNING OKed: ${toolName} ${summary} - allowed (inside project)\n`);
|
|
73
|
+
}
|
|
74
|
+
return { decision: "allow" };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const ctx = { tool: toolName, tier };
|
|
78
|
+
if (!client.apiKey) {
|
|
79
|
+
log(options.unpairedLog);
|
|
80
|
+
return finish(unpaired, options.unpairedReason, ctx);
|
|
81
|
+
}
|
|
82
|
+
const prTitle = await lookupPrTitle(fields);
|
|
83
|
+
if (prTitle)
|
|
84
|
+
fields = describeFields(toolName, toolInput, { cwd: call.cwd, prTitle }) ?? undefined;
|
|
85
|
+
const description = describe(toolName, toolInput, { cwd: call.cwd, prTitle });
|
|
86
|
+
log(`${toolName}: "${description}" - ${tier}`);
|
|
87
|
+
log("Requesting approval... (check your phone)");
|
|
88
|
+
try {
|
|
89
|
+
const result = await client.approve({
|
|
90
|
+
action: toolName,
|
|
91
|
+
description,
|
|
92
|
+
tier,
|
|
93
|
+
fields,
|
|
94
|
+
tool_input: toolInput,
|
|
95
|
+
session_id: call.sessionId,
|
|
96
|
+
cwd: call.cwd,
|
|
97
|
+
});
|
|
98
|
+
if (result.receipt)
|
|
99
|
+
appendReceipt(result.receipt);
|
|
100
|
+
const receiptNote = result.receipt ? ` (receipt ${shortReceiptId(result.receipt.body.receipt_id)})` : "";
|
|
101
|
+
const decided = {
|
|
102
|
+
...ctx,
|
|
103
|
+
approval_id: result.approval_id,
|
|
104
|
+
receipt_id: result.receipt?.body.receipt_id ?? null,
|
|
105
|
+
};
|
|
106
|
+
if (result.approved) {
|
|
107
|
+
log(`Approved (${result.approval_id})${receiptNote}`);
|
|
108
|
+
return finish("allow", `Approved via OKed${receiptNote}`, decided);
|
|
109
|
+
}
|
|
110
|
+
if (result.decision === "timeout") {
|
|
111
|
+
log(`No decision in time (${result.approval_id})${receiptNote}`);
|
|
112
|
+
return finish("deny", `OKed: no decision within the approval window (timed out): ${description}`, decided);
|
|
113
|
+
}
|
|
114
|
+
log(`Denied (${result.approval_id})${receiptNote}`);
|
|
115
|
+
return finish("deny", `Denied via OKed: ${description}`, decided);
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
const failed = { ...ctx, error: errorInfo(err) };
|
|
119
|
+
if (err instanceof OKedReceiptError) {
|
|
120
|
+
log(`Approval receipt did not verify (${err.problems.join(", ")}) - action denied`);
|
|
121
|
+
return finish("deny", `OKed: the approval receipt did not verify (${err.problems.join(", ")}); action denied`, failed);
|
|
122
|
+
}
|
|
123
|
+
if (err instanceof OKedAuthError) {
|
|
124
|
+
log(`Invalid API key (HTTP ${err.status}) - action denied`);
|
|
125
|
+
const reason = (options.invalidKeyReason ?? defaultInvalidKeyReason)(err.status);
|
|
126
|
+
return finish("deny", reason, failed);
|
|
127
|
+
}
|
|
128
|
+
if (err instanceof OKedTooManyPendingError) {
|
|
129
|
+
log(`Too many pending approvals (HTTP 429) - action denied`);
|
|
130
|
+
return finish("deny", err.message, failed);
|
|
131
|
+
}
|
|
132
|
+
if (err instanceof OKedHttpError) {
|
|
133
|
+
log(`Backend error HTTP ${err.status} - action denied (fail-safe)`);
|
|
134
|
+
return finish("deny", `OKed: backend error HTTP ${err.status}${err.detail ? `: ${err.detail}` : ""} (fail-safe deny)`, failed);
|
|
135
|
+
}
|
|
136
|
+
if (err instanceof OKedBackendUnreachableError) {
|
|
137
|
+
const decision = degradedDecision(tier, {
|
|
138
|
+
strictFailClosed: client.strictFailClosed,
|
|
139
|
+
});
|
|
140
|
+
const cause = errorInfo(err).message;
|
|
141
|
+
if (decision === "allow") {
|
|
142
|
+
log(`Backend unreachable (${cause}) - allowed (degraded; ${tier}, non-high-stakes)`);
|
|
143
|
+
return finish("allow", `OKed backend unreachable (${cause}) - allowed (degraded; non-high-stakes)`, { ...failed, degraded: true });
|
|
144
|
+
}
|
|
145
|
+
const why = client.strictFailClosed ? "strict fail-closed" : "high-stakes";
|
|
146
|
+
log(`Backend unreachable (${cause}) - ${why} denied (fail-safe)`);
|
|
147
|
+
return finish("deny", `OKed backend unreachable (${cause}) - ${why} denied (fail-safe)`, failed);
|
|
148
|
+
}
|
|
149
|
+
log(`Unexpected error (${errorText(err)}) - action denied (fail-safe)`);
|
|
150
|
+
return finish("deny", `OKed: unexpected error (fail-safe): ${errorText(err)}`, failed);
|
|
151
|
+
}
|
|
152
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
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 { encodeQR, renderQR } from "./qr.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
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 { 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
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** First string value among `keys`, if any. */
|
|
2
|
+
export declare function stringField(input: Record<string, unknown>, keys: readonly string[]): string | undefined;
|
|
3
|
+
/**
|
|
4
|
+
* Copy host-specific argument names onto the fields `classify` and `describe`
|
|
5
|
+
* already read (`file_path`, `content`, `command`). The original keys stay.
|
|
6
|
+
*/
|
|
7
|
+
export declare function withNormalizedFields(input: Record<string, unknown>): Record<string, unknown>;
|
|
8
|
+
/** Turn a host tool-args value into an object. A raw string is a command. */
|
|
9
|
+
export declare function asToolInput(value: unknown): Record<string, unknown>;
|
|
10
|
+
/** Shell-safe single quotes. The result is classified, never executed. */
|
|
11
|
+
export declare function shQuote(value: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* A file delete, expressed as `rm` so the SDK's bash classifier can tell a
|
|
14
|
+
* temp file from a real one. No path stays an unknown tool (approval required).
|
|
15
|
+
*/
|
|
16
|
+
export declare function mapFileDelete(input: Record<string, unknown>): {
|
|
17
|
+
toolName: string;
|
|
18
|
+
toolInput: Record<string, unknown>;
|
|
19
|
+
};
|
|
20
|
+
interface PatchFiles {
|
|
21
|
+
writes: string[];
|
|
22
|
+
deletes: string[];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Paths named by a Codex-style apply_patch body or a unified diff.
|
|
26
|
+
* Used only to pick a tier. The patch is not applied here.
|
|
27
|
+
*/
|
|
28
|
+
export declare function extractPatchPaths(patch: string): PatchFiles;
|
|
29
|
+
/**
|
|
30
|
+
* Map a patch onto one SDK tool call whose tier matches the riskiest file.
|
|
31
|
+
* Deletes become `rm`. Writes and updates become `Write` (warning inside a
|
|
32
|
+
* project, review on a sensitive path). An unreadable patch is an unknown
|
|
33
|
+
* edit, which the classifier sends to approval.
|
|
34
|
+
*/
|
|
35
|
+
export declare function mapPatch(patch: string): {
|
|
36
|
+
toolName: string;
|
|
37
|
+
toolInput: Record<string, unknown>;
|
|
38
|
+
};
|
|
39
|
+
export {};
|