@clawkeepers/gatekeeper-kit 0.1.0-beta.1

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 ControlStackAI
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/NOTICE ADDED
@@ -0,0 +1,206 @@
1
+ OpenClaw OS
2
+ Copyright (c) 2026 ControlStackAI
3
+ Original project contributions are licensed under the MIT License; see LICENSE.
4
+ Third-party and adapted material retains its applicable license terms.
5
+
6
+ OpenClaw (https://github.com/openclaw/openclaw) provides the separately installed,
7
+ unmodified agent runtime, Gateway and public plugin interfaces. Its pinned
8
+ v2026.9.2 license is MIT, copyright (c) 2026 OpenClaw Foundation; its own
9
+ THIRD_PARTY_NOTICES.md applies to incorporated upstream dependencies.
10
+
11
+ Cloudflare OS (https://github.com/cloudflare/cloudflare-os), by Cloudflare and
12
+ its contributors, provides architectural foundations and adapted material:
13
+ capability introductions, gatekeepers, approval/simulation contracts, observers,
14
+ and kernel review/authoring guidance. OpenClaw OS contributors modified these
15
+ contracts and documents for a self-hosted, single-process, tool-calling plugin
16
+ runtime. Cloudflare OS Starter (https://github.com/cloudflare/cloudflare-os-starter)
17
+ informed wrapper-owned customization and the upgrade discipline.
18
+
19
+ Cloudflare OS and Cloudflare OS Starter are Apache-2.0 licensed. Their retained
20
+ material is not relicensed by the project's MIT license. The applicable Apache
21
+ License 2.0 text is reproduced below. The original source distribution includes
22
+ further provenance in docs/acknowledgments.md. Other dependencies retain their
23
+ respective licenses and notices, including generated THIRD-PARTY-NOTICES for
24
+ bundled dependencies.
25
+
26
+ This is an independent project, not an upstream-endorsed product. No affiliation,
27
+ endorsement or rights to upstream trademarks are implied.
28
+
29
+ --- Apache License 2.0: retained Cloudflare material ---
30
+
31
+ Apache License
32
+ Version 2.0, January 2004
33
+ http://www.apache.org/licenses/
34
+
35
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
36
+
37
+ 1. Definitions.
38
+
39
+ "License" shall mean the terms and conditions for use, reproduction,
40
+ and distribution as defined by Sections 1 through 9 of this document.
41
+
42
+ "Licensor" shall mean the copyright owner or entity authorized by
43
+ the copyright owner that is granting the License.
44
+
45
+ "Legal Entity" shall mean the union of the acting entity and all
46
+ other entities that control, are controlled by, or are under common
47
+ control with that entity. For the purposes of this definition,
48
+ "control" means (i) the power, direct or indirect, to cause the
49
+ direction or management of such entity, whether by contract or
50
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
51
+ outstanding shares, or (iii) beneficial ownership of such entity.
52
+
53
+ "You" (or "Your") shall mean an individual or Legal Entity
54
+ exercising permissions granted by this License.
55
+
56
+ "Source" form shall mean the preferred form for making modifications,
57
+ including but not limited to software source code, documentation
58
+ source, and configuration files.
59
+
60
+ "Object" form shall mean any form resulting from mechanical
61
+ transformation or translation of a Source form, including but
62
+ not limited to compiled object code, generated documentation,
63
+ and conversions to other media types.
64
+
65
+ "Work" shall mean the work of authorship, whether in Source or
66
+ Object form, made available under the License, as indicated by a
67
+ copyright notice that is included in or attached to the work
68
+ (an example is provided in the Appendix below).
69
+
70
+ "Derivative Works" shall mean any work, whether in Source or Object
71
+ form, that is based on (or derived from) the Work and for which the
72
+ editorial revisions, annotations, elaborations, or other modifications
73
+ represent, as a whole, an original work of authorship. For the purposes
74
+ of this License, Derivative Works shall not include works that remain
75
+ separable from, or merely link (or bind by name) to the interfaces of,
76
+ the Work and Derivative Works thereof.
77
+
78
+ "Contribution" shall mean any work of authorship, including
79
+ the original version of the Work and any modifications or additions
80
+ to that Work or Derivative Works thereof, that is intentionally
81
+ submitted to Licensor for inclusion in the Work by the copyright owner
82
+ or by an individual or Legal Entity authorized to submit on behalf of
83
+ the copyright owner. For the purposes of this definition, "submitted"
84
+ means any form of electronic, verbal, or written communication sent
85
+ to the Licensor or its representatives, including but not limited to
86
+ communication on electronic mailing lists, source code control systems,
87
+ and issue tracking systems that are managed by, or on behalf of, the
88
+ Licensor for the purpose of discussing and improving the Work, but
89
+ excluding communication that is conspicuously marked or otherwise
90
+ designated in writing by the copyright owner as "Not a Contribution."
91
+
92
+ "Contributor" shall mean Licensor and any individual or Legal Entity
93
+ on behalf of whom a Contribution has been received by Licensor and
94
+ subsequently incorporated within the Work.
95
+
96
+ 2. Grant of Copyright License. Subject to the terms and conditions of
97
+ this License, each Contributor hereby grants to You a perpetual,
98
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
99
+ copyright license to reproduce, prepare Derivative Works of,
100
+ publicly display, publicly perform, sublicense, and distribute the
101
+ Work and such Derivative Works in Source or Object form.
102
+
103
+ 3. Grant of Patent License. Subject to the terms and conditions of
104
+ this License, each Contributor hereby grants to You a perpetual,
105
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
106
+ (except as stated in this section) patent license to make, have made,
107
+ use, offer to sell, sell, import, and otherwise transfer the Work,
108
+ where such license applies only to those patent claims licensable
109
+ by such Contributor that are necessarily infringed by their
110
+ Contribution(s) alone or by combination of their Contribution(s)
111
+ with the Work to which such Contribution(s) was submitted. If You
112
+ institute patent litigation against any entity (including a
113
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
114
+ or a Contribution incorporated within the Work constitutes direct
115
+ or contributory patent infringement, then any patent licenses
116
+ granted to You under this License for that Work shall terminate
117
+ as of the date such litigation is filed.
118
+
119
+ 4. Redistribution. You may reproduce and distribute copies of the
120
+ Work or Derivative Works thereof in any medium, with or without
121
+ modifications, and in Source or Object form, provided that You
122
+ meet the following conditions:
123
+
124
+ (a) You must give any other recipients of the Work or
125
+ Derivative Works a copy of this License; and
126
+
127
+ (b) You must cause any modified files to carry prominent notices
128
+ stating that You changed the files; and
129
+
130
+ (c) You must retain, in the Source form of any Derivative Works
131
+ that You distribute, all copyright, patent, trademark, and
132
+ attribution notices from the Source form of the Work,
133
+ excluding those notices that do not pertain to any part of
134
+ the Derivative Works; and
135
+
136
+ (d) If the Work includes a "NOTICE" text file as part of its
137
+ distribution, then any Derivative Works that You distribute must
138
+ include a readable copy of the attribution notices contained
139
+ within such NOTICE file, excluding those notices that do not
140
+ pertain to any part of the Derivative Works, in at least one
141
+ of the following places: within a NOTICE text file distributed
142
+ as part of the Derivative Works; within the Source form or
143
+ documentation, if provided along with the Derivative Works; or,
144
+ within a display generated by the Derivative Works, if and
145
+ wherever such third-party notices normally appear. The contents
146
+ of the NOTICE file are for informational purposes only and
147
+ do not modify the License. You may add Your own attribution
148
+ notices within Derivative Works that You distribute, alongside
149
+ or as an addendum to the NOTICE text from the Work, provided
150
+ that such additional attribution notices cannot be construed
151
+ as modifying the License.
152
+
153
+ You may add Your own copyright statement to Your modifications and
154
+ may provide additional or different license terms and conditions
155
+ for use, reproduction, or distribution of Your modifications, or
156
+ for any such Derivative Works as a whole, provided Your use,
157
+ reproduction, and distribution of the Work otherwise complies with
158
+ the conditions stated in this License.
159
+
160
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
161
+ any Contribution intentionally submitted for inclusion in the Work
162
+ by You to the Licensor shall be under the terms and conditions of
163
+ this License, without any additional terms or conditions.
164
+ Notwithstanding the above, nothing herein shall supersede or modify
165
+ the terms of any separate license agreement you may have executed
166
+ with Licensor regarding such Contributions.
167
+
168
+ 6. Trademarks. This License does not grant permission to use the trade
169
+ names, trademarks, service marks, or product names of the Licensor,
170
+ except as required for reasonable and customary use in describing the
171
+ origin of the Work and reproducing the content of the NOTICE file.
172
+
173
+ 7. Disclaimer of Warranty. Unless required by applicable law or
174
+ agreed to in writing, Licensor provides the Work (and each
175
+ Contributor provides its Contributions) on an "AS IS" BASIS,
176
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
177
+ implied, including, without limitation, any warranties or conditions
178
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
179
+ PARTICULAR PURPOSE. You are solely responsible for determining the
180
+ appropriateness of using or redistributing the Work and assume any
181
+ risks associated with Your exercise of permissions under this License.
182
+
183
+ 8. Limitation of Liability. In no event and under no legal theory,
184
+ whether in tort (including negligence), contract, or otherwise,
185
+ unless required by applicable law (such as deliberate and grossly
186
+ negligent acts) or agreed to in writing, shall any Contributor be
187
+ liable to You for damages, including any direct, indirect, special,
188
+ incidental, or consequential damages of any character arising as a
189
+ result of this License or out of the use or inability to use the
190
+ Work (including but not limited to damages for loss of goodwill,
191
+ work stoppage, computer failure or malfunction, or any and all
192
+ other commercial damages or losses), even if such Contributor
193
+ has been advised of the possibility of such damages.
194
+
195
+ 9. Accepting Warranty or Additional Liability. While redistributing
196
+ the Work or Derivative Works thereof, You may choose to offer,
197
+ and charge a fee for, acceptance of support, warranty, indemnity,
198
+ or other liability obligations and/or rights consistent with this
199
+ License. However, in accepting such obligations, You may act only
200
+ on Your own behalf and on Your sole responsibility, not on behalf
201
+ of any other Contributor, and only if You agree to indemnify,
202
+ defend, and hold each Contributor harmless for any liability
203
+ incurred by, or claims asserted against, such Contributor by reason
204
+ of your accepting any such warranty or additional liability.
205
+
206
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,10 @@
1
+ # @clawkeepers/gatekeeper-kit
2
+
3
+ Security-critical helpers for gatekeeper authors. Start with [SKELETON.md](SKELETON.md).
4
+
5
+ Includes the validated lifecycle builder, two-stage OAuth nonces, encrypted account storage with refresh coalescing,
6
+ persistent simulation stores, action sequencing, a resource-session base class, fixed-message error sanitization, and
7
+ an offline test queue. Kernel authorization and tool registration remain exclusively the kernel's responsibility.
8
+
9
+ Phase 2 acceptance is library-only: `scripts/vm/test.sh phase-2`. No Gateway, external API, or production state is used.
10
+ See the skeleton's ordering/recovery section for single-writer ownership, uncertain-action handling and sync approval binding.
@@ -0,0 +1,238 @@
1
+ import * as openclaw_plugin_sdk_plugin_entry from 'openclaw/plugin-sdk/plugin-entry';
2
+ import * as _clawkeepers_shared from '@clawkeepers/shared';
3
+ import { SupportedResource, GatekeeperToolDef, ActionDescription, GatekeeperVendor, Gatekeeper, ApprovalQueue, GatekeeperSession, ObserverVerifier, ObservationDescription, SessionCallContext } from '@clawkeepers/shared';
4
+
5
+ /** Gatekeeper declaration: metadata is separate from instance-bound implementations. */
6
+ interface GatekeeperDefinition {
7
+ vendor: string;
8
+ apiVersion: 1;
9
+ id: `gatekeeper-${string}`;
10
+ name: string;
11
+ description: string;
12
+ resources: SupportedResource[];
13
+ tools: GatekeeperToolDef[];
14
+ /** Pure descriptions are mandatory for all declared action tools; instance implementations are checked again on calls. */
15
+ actions?: Record<string, {
16
+ describe(params: Record<string, unknown>): ActionDescription | Promise<ActionDescription>;
17
+ }>;
18
+ createVendor(ctx: VendorContext): GatekeeperVendor;
19
+ }
20
+ /** Lifecycle-owned vendor configuration. No OpenClaw registration API is handed to a driver. */
21
+ interface VendorContext {
22
+ pluginConfig: Record<string, unknown>;
23
+ stateDir: string;
24
+ logger: {
25
+ debug(message: string): void;
26
+ info(message: string): void;
27
+ warn(message: string): void;
28
+ error(message: string): void;
29
+ };
30
+ }
31
+ /** Cell/root identity the kernel must compare to its trusted catalog before using a live driver. */
32
+ interface GatekeeperRuntimeIdentity {
33
+ pluginId: string;
34
+ vendor: string;
35
+ apiVersion: 1;
36
+ stateDir: string;
37
+ root: string;
38
+ }
39
+ /** Lifecycle slot. Its vendor and every retained account/resource/session fail closed after revocation. */
40
+ interface GatekeeperRuntime extends GatekeeperRuntimeIdentity {
41
+ getVendor(): GatekeeperVendor;
42
+ revoke(): void;
43
+ }
44
+ /** Access transport only: the kernel still validates enablement/catalog identity and uses resolveGrant(). */
45
+ declare function gatekeeperRuntimeSlot(pluginId: string): {
46
+ setRuntime: (next: GatekeeperRuntime) => void;
47
+ clearRuntime: () => void;
48
+ tryGetRuntime: () => GatekeeperRuntime | null;
49
+ getRuntime: () => GatekeeperRuntime;
50
+ };
51
+ /** Validate before loading a vendor; never registers tools or starts services in discovery modes. */
52
+ declare function defineGatekeeper(def: GatekeeperDefinition): Omit<{
53
+ id: string;
54
+ name: string;
55
+ description: string;
56
+ kind?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["kind"];
57
+ configSchema?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginConfigSchema | (() => openclaw_plugin_sdk_plugin_entry.OpenClawPluginConfigSchema);
58
+ reload?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["reload"];
59
+ nodeHostCommands?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["nodeHostCommands"];
60
+ securityAuditCollectors?: openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["securityAuditCollectors"];
61
+ register: NonNullable<openclaw_plugin_sdk_plugin_entry.OpenClawPluginDefinition["register"]>;
62
+ }, "configSchema"> & {
63
+ configSchema: openclaw_plugin_sdk_plugin_entry.OpenClawPluginConfigSchema;
64
+ };
65
+
66
+ /** One pending local effect, identified by the action's durable per-instance id. */
67
+ interface OverlayEntry {
68
+ actionId: number;
69
+ kind: string;
70
+ payload: unknown;
71
+ }
72
+ /** Overlay-at-read effects. File-backed instances survive restart; one cell process owns each file. */
73
+ declare class OverlayStore {
74
+ private readonly path?;
75
+ private state;
76
+ constructor(path?: string | undefined);
77
+ private load;
78
+ private save;
79
+ /** Allocate a negative simulated identifier without colliding with remote positive ids. */
80
+ nextTempId(): number;
81
+ /** Add exactly one effect per queued action; duplicate IDs are rejected. */
82
+ add(entry: OverlayEntry): void;
83
+ /** Retire a rejected or applied action. Missing ids are harmless. */
84
+ remove(actionId: number): void;
85
+ /** Return detached pending entries in action-id order. */
86
+ list(): OverlayEntry[];
87
+ /** Merge pending effects without allowing reducers to mutate the authoritative read or stored entries. */
88
+ applyTo<T>(value: T, mergers: Record<string, (value: T, entry: OverlayEntry) => T>): T;
89
+ }
90
+
91
+ /** Side-effect-free description, local simulation, and explicit remote application. */
92
+ interface ActionImpl<P = Record<string, unknown>> {
93
+ describe(params: P): ActionDescription | Promise<ActionDescription>;
94
+ simulate?(params: P, overlay: OverlayStore, actionId: number): unknown | Promise<unknown>;
95
+ apply(params: P, actionId: number): Promise<{
96
+ remoteId?: string;
97
+ value?: unknown;
98
+ } | void>;
99
+ revert?(record: {
100
+ actionId: number;
101
+ remoteId?: string;
102
+ params: P;
103
+ }): Promise<void>;
104
+ }
105
+ /** Observations describe before reading; the kit owns authorization and never hands them a write queue. */
106
+ interface ObservationImpl<P = Record<string, unknown>> {
107
+ describe(params: P): _clawkeepers_shared.ObservationDescription | Promise<_clawkeepers_shared.ObservationDescription>;
108
+ read(params: P): Promise<unknown>;
109
+ }
110
+ /** Base resource driver. Only the kernel may create its sessions through resolveGrant(). */
111
+ declare abstract class KitGatekeeper<State = unknown> implements Gatekeeper {
112
+ private readonly journalPath?;
113
+ abstract resource: SupportedResource;
114
+ observations: Record<string, ObservationImpl>;
115
+ actions: Record<string, ActionImpl>;
116
+ protected abstract overlay: OverlayStore;
117
+ private records;
118
+ private readonly sequence;
119
+ constructor(journalPath?: string | undefined);
120
+ private save;
121
+ private record;
122
+ private assertSettled;
123
+ private recoverOverlay;
124
+ private impl;
125
+ describe(): Promise<{
126
+ resource: SupportedResource;
127
+ title: string;
128
+ suggestedName: string;
129
+ }>;
130
+ getAutoApprovableActions(): Promise<never[]>;
131
+ /** Bind a kernel queue; dry passes never read vendors, reserve ids, submit actions or modify overlays. */
132
+ startSession(queue: ApprovalQueue): Promise<GatekeeperSession>;
133
+ private applyRecorded;
134
+ /** Apply once after the kernel's operator decision. Ambiguous remote failures are never blindly retried. */
135
+ applyAction(actionId: number): Promise<void>;
136
+ /** Remove a pending effect. An ambiguous submission/application requires operator reconciliation instead. */
137
+ rejectAction(actionId: number): Promise<void>;
138
+ /** Revert once using only the recorded remote identifier and original parameters. */
139
+ revertAction(actionId: number): Promise<void>;
140
+ /** v1 defaults to private-only; granting observers is never inferred from resource metadata. */
141
+ addObserver(_id: string, _verifier: ObserverVerifier): Promise<void>;
142
+ removeObserver(_id: string): Promise<void>;
143
+ }
144
+
145
+ /** Two-stage, operator-bound OAuth nonces. Advancing never extends the original lifetime. */
146
+ declare class OAuthNonceMachine {
147
+ private readonly ttlMs;
148
+ private readonly now;
149
+ private pending;
150
+ constructor(ttlMs?: number, now?: () => number);
151
+ /** Issue the first nonce for a local operator-initiated authorization flow. */
152
+ issue(operatorId: string): string;
153
+ /** Consume stage one and mint a distinct callback nonce for stage two. */
154
+ advance(nonce: string): string | null;
155
+ /** Rotate stage one while returning its trusted binding to the authorization router. */
156
+ advanceBound(nonce: string): {
157
+ nonce: string;
158
+ operatorId: string;
159
+ } | null;
160
+ /** Consume only a stage-two callback, exactly once. Invalid, expired and replayed values deny. */
161
+ consume(nonce: string): string | null;
162
+ private take;
163
+ /** Remove expired records without accepting them. */
164
+ sweep(): void;
165
+ }
166
+
167
+ /** AES-256-GCM account storage. Ciphertext is bound to both canonical store and exact operator identity. */
168
+ declare class TokenStore {
169
+ private readonly key;
170
+ private readonly dir;
171
+ private refreshes;
172
+ private generations;
173
+ constructor(dir: string, cellKey: Buffer);
174
+ private path;
175
+ private aad;
176
+ /** Encrypt and atomically replace one account record; plaintext is never written. */
177
+ put(operatorId: string, value: unknown): void;
178
+ /** Return null only for an absent account. Tampering, wrong keys and corrupt envelopes fail closed. */
179
+ get<T = unknown>(operatorId: string): T | null;
180
+ /** Delete an account and invalidate any in-flight refresh so it cannot restore revoked credentials. */
181
+ remove(operatorId: string): void;
182
+ /** Share one refresh per account. A concurrent put/remove makes its stale result fail closed. */
183
+ refresh<T>(operatorId: string, operation: () => Promise<T>): Promise<T>;
184
+ }
185
+
186
+ /** Mutate-the-cache simulation with an authoritative base retained for rejection and refresh replay. */
187
+ declare class CacheMutationStore<T> {
188
+ private readonly reducers;
189
+ private readonly path?;
190
+ private state;
191
+ private view;
192
+ constructor(base: T, reducers: Record<string, (value: T, entry: OverlayEntry) => T>, path?: string | undefined);
193
+ private replay;
194
+ private save;
195
+ /** Return a detached view containing all pending effects. */
196
+ read(): T;
197
+ /** Apply one new effect to the cached view after its action was queued. */
198
+ add(entry: OverlayEntry): void;
199
+ /** Reject one action and rebuild the view from the authoritative base. */
200
+ remove(actionId: number): void;
201
+ /** Refresh authoritative data and replay all pending actions in order. */
202
+ refresh(base: T): void;
203
+ /** Retire an applied effect together with the refreshed authoritative data. */
204
+ commit(actionId: number, base: T): void;
205
+ }
206
+
207
+ /** Per-instance monotonic action ids and single-flight lifecycle scheduling; file ownership is one cell process. */
208
+ declare class ActionSequencer {
209
+ private readonly path?;
210
+ private nextId;
211
+ private tail;
212
+ constructor(path?: string | undefined, minimum?: number);
213
+ private load;
214
+ /** Reserve an id durably before it can be submitted to the kernel queue. */
215
+ next(): number;
216
+ /** Serialize operations and remain usable after a rejected operation. */
217
+ run<T>(operation: () => Promise<T>): Promise<T>;
218
+ }
219
+
220
+ /** Emit only a fixed message and a structured numeric HTTP status; never vendor error strings or bodies. */
221
+ declare function sanitizeError(error: unknown): string;
222
+
223
+ /** Offline unit-test queue; never use it as a production authority or conformance substitute. */
224
+ declare class TestApprovalQueue implements ApprovalQueue {
225
+ readonly observations: ObservationDescription[];
226
+ readonly actions: Array<{
227
+ id: number;
228
+ description: ActionDescription;
229
+ }>;
230
+ denyObservations: boolean;
231
+ denyActions: boolean;
232
+ authorizeObservation(description: ObservationDescription): Promise<void>;
233
+ submitAction(id: number, description: ActionDescription): Promise<void>;
234
+ /** Construct a deterministic unit-test call context. */
235
+ context(toolCallId?: string): SessionCallContext;
236
+ }
237
+
238
+ export { type ActionImpl, ActionSequencer, CacheMutationStore, type GatekeeperDefinition, type GatekeeperRuntime, type GatekeeperRuntimeIdentity, KitGatekeeper, OAuthNonceMachine, type ObservationImpl, type OverlayEntry, OverlayStore, TestApprovalQueue, TokenStore, type VendorContext, defineGatekeeper, gatekeeperRuntimeSlot, sanitizeError };
package/dist/index.js ADDED
@@ -0,0 +1,686 @@
1
+ // src/define-gatekeeper.ts
2
+ import { realpathSync } from "fs";
3
+ import { Value } from "typebox/value";
4
+ import { GatekeeperToolDefSchema, SupportedResourceSchema } from "@clawkeepers/shared";
5
+ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
6
+ import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
7
+ var forbidden = /approv|oauth|cache|queue|simulat/i;
8
+ function gatekeeperRuntimeSlot(pluginId) {
9
+ if (!/^gatekeeper-[a-z][a-z0-9_]*$/.test(pluginId)) throw new Error("Invalid gatekeeper id.");
10
+ return createPluginRuntimeStore({ pluginId, errorMessage: "Gatekeeper unavailable." });
11
+ }
12
+ function defineGatekeeper(def) {
13
+ if (!/^[a-z][a-z0-9_]*$/.test(def.vendor) || def.id !== `gatekeeper-${def.vendor}` || def.apiVersion !== 1) throw new Error("Invalid gatekeeper identity.");
14
+ const resources = /* @__PURE__ */ new Map();
15
+ for (const resource of def.resources) {
16
+ if (!Value.Check(SupportedResourceSchema, resource) || resources.has(resource.type)) throw new Error("Invalid or duplicate resource.");
17
+ resources.set(resource.type, resource);
18
+ }
19
+ const names = /* @__PURE__ */ new Set();
20
+ for (const tool of def.tools) {
21
+ if (forbidden.test(tool.description)) throw new Error("Tool description leaks internals.");
22
+ if (!Value.Check(GatekeeperToolDefSchema, JSON.parse(JSON.stringify(tool))) || !tool.name.startsWith(`gk_${def.vendor}_`) || names.has(tool.name)) throw new Error("Invalid or duplicate tool name/metadata.");
23
+ const parameters = tool.parameters;
24
+ const properties = parameters.properties;
25
+ const required = parameters.required;
26
+ if (parameters.type !== "object" || !properties || !Object.hasOwn(properties, "grant") || properties.grant?.type !== "string" || !Array.isArray(required) || !required.includes("grant")) throw new Error("Tool requires a string grant parameter.");
27
+ if (!resources.get(tool.resourceType)?.tools.includes(tool.name)) throw new Error("Tool resource mapping mismatch.");
28
+ if (tool.kind === "action" && (!def.actions || !Object.hasOwn(def.actions, tool.name) || typeof def.actions[tool.name]?.describe !== "function")) throw new Error("Action tool requires describe().");
29
+ names.add(tool.name);
30
+ }
31
+ for (const resource of resources.values()) for (const name2 of resource.tools) {
32
+ if (!def.tools.some((tool) => tool.name === name2 && tool.resourceType === resource.type)) throw new Error("Resource tool mapping mismatch.");
33
+ }
34
+ for (const name2 of Object.keys(def.actions ?? {})) if (!def.tools.some((tool) => tool.name === name2 && tool.kind === "action")) throw new Error("Undeclared action implementation.");
35
+ const { id, vendor, apiVersion, name, description, createVendor } = def;
36
+ return definePluginEntry({ id, name, description, register(api) {
37
+ if (api.id !== id) throw new Error("Plugin identity mismatch.");
38
+ if (api.registrationMode !== "full") return;
39
+ const slot = gatekeeperRuntimeSlot(id);
40
+ let owned;
41
+ api.registerService({ id: `${id}-driver`, start(ctx) {
42
+ if (!api.rootDir) throw new Error("Plugin root unavailable.");
43
+ const root = realpathSync(api.rootDir), stateDir = realpathSync(ctx.stateDir);
44
+ const instance = createVendor({ pluginConfig: structuredClone(api.pluginConfig ?? {}), stateDir, logger: { debug: (message) => ctx.logger.debug?.(message), info: (message) => ctx.logger.info(message), warn: (message) => ctx.logger.warn(message), error: (message) => ctx.logger.error(message) } });
45
+ if (instance.vendor !== vendor || instance.apiVersion !== apiVersion) throw new Error("Vendor identity mismatch.");
46
+ let active = true;
47
+ const guard = () => {
48
+ if (!active || slot.tryGetRuntime() !== owned) throw new Error("Gatekeeper unavailable.");
49
+ };
50
+ const wrapped = revocable(instance, guard);
51
+ const runtime = {
52
+ pluginId: id,
53
+ vendor,
54
+ apiVersion,
55
+ root,
56
+ stateDir,
57
+ getVendor() {
58
+ guard();
59
+ return wrapped;
60
+ },
61
+ revoke() {
62
+ active = false;
63
+ }
64
+ };
65
+ slot.tryGetRuntime()?.revoke();
66
+ owned = runtime;
67
+ slot.setRuntime(runtime);
68
+ }, stop() {
69
+ owned?.revoke();
70
+ if (owned && slot.tryGetRuntime() === owned) slot.clearRuntime();
71
+ owned = void 0;
72
+ } });
73
+ } });
74
+ }
75
+ function revocable(root, guard) {
76
+ const cache = /* @__PURE__ */ new WeakMap();
77
+ function wrap(value) {
78
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
79
+ const existing = cache.get(value);
80
+ if (existing) return existing;
81
+ const proxy = new Proxy(value, {
82
+ get(target, key) {
83
+ guard();
84
+ const member = Reflect.get(target, key, target);
85
+ if (typeof member !== "function") return wrap(member);
86
+ return (...args) => {
87
+ guard();
88
+ const result2 = Reflect.apply(member, target, args);
89
+ if (result2 instanceof Promise) return result2.then((resolved) => {
90
+ guard();
91
+ return wrap(resolved);
92
+ });
93
+ guard();
94
+ return wrap(result2);
95
+ };
96
+ }
97
+ });
98
+ cache.set(value, proxy);
99
+ return proxy;
100
+ }
101
+ return wrap(root);
102
+ }
103
+
104
+ // src/kit-gatekeeper.ts
105
+ import { isDeepStrictEqual } from "util";
106
+ import { Value as Value2 } from "typebox/value";
107
+ import { ActionDescriptionSchema, ObservationDescriptionSchema } from "@clawkeepers/shared";
108
+
109
+ // src/atomic-json.ts
110
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
111
+ import { dirname, join } from "path";
112
+ import { randomBytes } from "crypto";
113
+ function writeJsonAtomic(path, value) {
114
+ const dir = dirname(path);
115
+ mkdirSync(dir, { recursive: true, mode: 448 });
116
+ const temp = join(dir, `.clawos-${randomBytes(16).toString("hex")}.tmp`);
117
+ let fd;
118
+ try {
119
+ fd = openSync(temp, "wx", 384);
120
+ writeFileSync(fd, JSON.stringify(value), "utf8");
121
+ fsyncSync(fd);
122
+ closeSync(fd);
123
+ fd = void 0;
124
+ renameSync(temp, path);
125
+ const directory = openSync(dir, "r");
126
+ try {
127
+ fsyncSync(directory);
128
+ } finally {
129
+ closeSync(directory);
130
+ }
131
+ } finally {
132
+ if (fd !== void 0) closeSync(fd);
133
+ try {
134
+ unlinkSync(temp);
135
+ } catch (error) {
136
+ if (error.code !== "ENOENT") throw error;
137
+ }
138
+ }
139
+ }
140
+ function readJson(path) {
141
+ try {
142
+ return JSON.parse(readFileSync(path, "utf8"));
143
+ } catch (error) {
144
+ if (error.code === "ENOENT") return void 0;
145
+ throw new Error("Invalid persisted state.");
146
+ }
147
+ }
148
+
149
+ // src/overlay-store.ts
150
+ function validEntries(value) {
151
+ return Array.isArray(value) && value.every((e) => e && Number.isSafeInteger(e.actionId) && e.actionId > 0 && typeof e.kind === "string" && e.kind.length > 0 && "payload" in e) && new Set(value.map((e) => e.actionId)).size === value.length;
152
+ }
153
+ var OverlayStore = class {
154
+ constructor(path) {
155
+ this.path = path;
156
+ this.load();
157
+ }
158
+ state = { version: 1, tempId: -1, entries: [] };
159
+ load() {
160
+ if (!this.path) return;
161
+ const raw = readJson(this.path);
162
+ if (raw === void 0) return;
163
+ const value = raw;
164
+ if (value.version !== 1 || !Number.isSafeInteger(value.tempId) || value.tempId >= 0 || !validEntries(value.entries)) throw new Error("Invalid overlay state.");
165
+ this.state = value;
166
+ }
167
+ save(next) {
168
+ if (this.path) writeJsonAtomic(this.path, next);
169
+ this.state = next;
170
+ }
171
+ /** Allocate a negative simulated identifier without colliding with remote positive ids. */
172
+ nextTempId() {
173
+ this.load();
174
+ if (this.state.tempId <= Number.MIN_SAFE_INTEGER) throw new Error("Temporary id space exhausted.");
175
+ const id = this.state.tempId;
176
+ this.save({ ...this.state, tempId: id - 1 });
177
+ return id;
178
+ }
179
+ /** Add exactly one effect per queued action; duplicate IDs are rejected. */
180
+ add(entry) {
181
+ this.load();
182
+ const entries = [...this.state.entries, structuredClone(entry)].sort((a, b) => a.actionId - b.actionId);
183
+ if (!validEntries(entries)) throw new Error("Invalid or duplicate overlay action.");
184
+ this.save({ ...this.state, entries });
185
+ }
186
+ /** Retire a rejected or applied action. Missing ids are harmless. */
187
+ remove(actionId) {
188
+ this.load();
189
+ this.save({ ...this.state, entries: this.state.entries.filter((e) => e.actionId !== actionId) });
190
+ }
191
+ /** Return detached pending entries in action-id order. */
192
+ list() {
193
+ this.load();
194
+ return structuredClone(this.state.entries);
195
+ }
196
+ /** Merge pending effects without allowing reducers to mutate the authoritative read or stored entries. */
197
+ applyTo(value, mergers) {
198
+ return this.list().reduce((result2, entry) => {
199
+ const merge = Object.hasOwn(mergers, entry.kind) ? mergers[entry.kind] : void 0;
200
+ if (!merge) throw new Error("Unknown simulation action kind.");
201
+ return merge(result2, entry);
202
+ }, structuredClone(value));
203
+ }
204
+ };
205
+
206
+ // src/action-sequencer.ts
207
+ var ActionSequencer = class {
208
+ constructor(path, minimum = 1) {
209
+ this.path = path;
210
+ if (!Number.isSafeInteger(minimum) || minimum < 1) throw new Error("Invalid action sequence minimum.");
211
+ this.nextId = minimum;
212
+ this.load();
213
+ }
214
+ nextId = 1;
215
+ tail = Promise.resolve();
216
+ load() {
217
+ if (!this.path) return;
218
+ const raw = readJson(this.path);
219
+ if (raw === void 0) return;
220
+ const state = raw;
221
+ if (state.version !== 1 || !Number.isSafeInteger(state.next) || state.next < 1) throw new Error("Invalid action sequence.");
222
+ this.nextId = Math.max(this.nextId, state.next);
223
+ }
224
+ /** Reserve an id durably before it can be submitted to the kernel queue. */
225
+ next() {
226
+ this.load();
227
+ if (this.nextId >= Number.MAX_SAFE_INTEGER) throw new Error("Action id space exhausted.");
228
+ const id = this.nextId;
229
+ if (this.path) writeJsonAtomic(this.path, { version: 1, next: id + 1 });
230
+ this.nextId = id + 1;
231
+ return id;
232
+ }
233
+ /** Serialize operations and remain usable after a rejected operation. */
234
+ run(operation) {
235
+ const result2 = this.tail.then(operation);
236
+ this.tail = result2.then(() => {
237
+ }, () => {
238
+ });
239
+ return result2;
240
+ }
241
+ };
242
+
243
+ // src/sanitize.ts
244
+ function sanitizeError(error) {
245
+ let status;
246
+ try {
247
+ if (error !== null && typeof error === "object" && "status" in error) status = error.status;
248
+ } catch {
249
+ }
250
+ return typeof status === "number" && Number.isInteger(status) && status >= 400 && status <= 599 ? `The operation failed. (status ${status})` : "The operation failed.";
251
+ }
252
+
253
+ // src/kit-gatekeeper.ts
254
+ var KitGatekeeper = class {
255
+ constructor(journalPath) {
256
+ this.journalPath = journalPath;
257
+ if (journalPath) {
258
+ const raw = readJson(journalPath);
259
+ if (raw !== void 0) {
260
+ const value = raw;
261
+ if (value.version !== 1 || !Array.isArray(value.records)) throw new Error("Invalid action journal.");
262
+ for (const record of value.records) {
263
+ if (!Number.isSafeInteger(record.id) || record.id < 1 || this.records.has(record.id) || typeof record.tool !== "string" || !record.params || typeof record.params !== "object" || !Value2.Check(ActionDescriptionSchema, record.description) || !["submitting", "pending", "applying", "applied", "rejected", "reverting", "reverted", "uncertain"].includes(record.status)) throw new Error("Invalid action journal.");
264
+ this.records.set(record.id, record);
265
+ }
266
+ }
267
+ }
268
+ this.sequence = new ActionSequencer(journalPath ? `${journalPath}.sequence` : void 0, [...this.records.keys()].reduce((max, id) => Math.max(max, id), 0) + 1);
269
+ }
270
+ observations = {};
271
+ actions = {};
272
+ records = /* @__PURE__ */ new Map();
273
+ sequence;
274
+ save(record) {
275
+ const records = new Map(this.records);
276
+ records.set(record.id, structuredClone(record));
277
+ if (this.journalPath) writeJsonAtomic(this.journalPath, { version: 1, records: [...records.values()] });
278
+ this.records = records;
279
+ }
280
+ record(id) {
281
+ const record = this.records.get(id);
282
+ if (!record) throw new Error("Unknown action.");
283
+ return structuredClone(record);
284
+ }
285
+ assertSettled() {
286
+ if ([...this.records.values()].some((record) => ["submitting", "applying", "reverting", "uncertain"].includes(record.status))) throw new Error("Action outcome requires reconciliation.");
287
+ }
288
+ async recoverOverlay() {
289
+ this.assertSettled();
290
+ for (const entry of this.overlay.list()) {
291
+ if (this.records.get(entry.actionId)?.status !== "pending") this.overlay.remove(entry.actionId);
292
+ }
293
+ for (const record of this.records.values()) {
294
+ if (record.status === "pending" && !record.description.awaitDecision && !this.overlay.list().some((entry) => entry.actionId === record.id)) {
295
+ const impl = this.impl(record.tool);
296
+ if (!impl.simulate) throw new Error("Simulation implementation missing.");
297
+ await impl.simulate(structuredClone(record.params), this.overlay, record.id);
298
+ }
299
+ }
300
+ }
301
+ impl(tool) {
302
+ const impl = Object.hasOwn(this.actions, tool) ? this.actions[tool] : void 0;
303
+ if (!impl || typeof impl.describe !== "function" || typeof impl.apply !== "function") throw new Error("Action implementation missing.");
304
+ return impl;
305
+ }
306
+ async describe() {
307
+ return { resource: this.resource, title: this.resource.title, suggestedName: this.resource.type.toUpperCase() };
308
+ }
309
+ async getAutoApprovableActions() {
310
+ return [];
311
+ }
312
+ /** Bind a kernel queue; dry passes never read vendors, reserve ids, submit actions or modify overlays. */
313
+ async startSession(queue) {
314
+ await this.sequence.run(() => this.recoverOverlay());
315
+ let closed = false;
316
+ const live = () => {
317
+ if (closed) throw new Error("Session closed.");
318
+ this.assertSettled();
319
+ };
320
+ return {
321
+ close: async () => {
322
+ closed = true;
323
+ },
324
+ call: async (tool, input, ctx) => {
325
+ try {
326
+ live();
327
+ this.assertSettled();
328
+ if (ctx.queue !== queue || !ctx.agentId || !ctx.sessionKey || (ctx.observers?.length ?? 0) > 0) throw new Error("Session authority unavailable.");
329
+ const params = structuredClone(input);
330
+ if (!this.resource.tools.includes(tool)) throw new Error("Tool outside resource.");
331
+ const observation = Object.hasOwn(this.observations, tool) ? this.observations[tool] : void 0;
332
+ if (observation) {
333
+ const description2 = await observation.describe(structuredClone(params));
334
+ if (!Value2.Check(ObservationDescriptionSchema, description2)) throw new Error("Invalid observation description.");
335
+ live();
336
+ if (ctx.dryRun) return { kind: "observation", description: description2 };
337
+ await queue.authorizeObservation(description2);
338
+ live();
339
+ const value = await observation.read(params);
340
+ live();
341
+ return result(value);
342
+ }
343
+ const impl = this.impl(tool), description = await impl.describe(structuredClone(params));
344
+ if (!Value2.Check(ActionDescriptionSchema, description) || description.implementsRevert && !impl.revert) throw new Error("Invalid action description.");
345
+ if (!description.awaitDecision && !impl.simulate) throw new Error("Action simulation missing.");
346
+ live();
347
+ if (ctx.dryRun) return { kind: "action", description };
348
+ if (description.awaitDecision && !approved(tool, params, ctx)) throw new Error("Action approval missing.");
349
+ return await this.sequence.run(async () => {
350
+ live();
351
+ this.assertSettled();
352
+ const callKey = ctx.toolCallId ? JSON.stringify([ctx.agentId, ctx.sessionKey, ctx.toolCallId]) : void 0;
353
+ if (callKey && [...this.records.values()].some((record2) => record2.callKey === callKey)) throw new Error("Action call already submitted.");
354
+ const id = this.sequence.next();
355
+ const record = { id, tool, params, description, status: "submitting", ...callKey ? { callKey } : {} };
356
+ this.save(record);
357
+ try {
358
+ await queue.submitAction(id, description);
359
+ } catch {
360
+ this.save({ ...record, status: "uncertain" });
361
+ throw new Error("Action submission failed.");
362
+ }
363
+ this.save({ ...record, status: "pending" });
364
+ try {
365
+ live();
366
+ if (description.awaitDecision) {
367
+ const value2 = await this.applyRecorded(id);
368
+ live();
369
+ return result(value2);
370
+ }
371
+ const value = await impl.simulate(structuredClone(params), this.overlay, id);
372
+ live();
373
+ if (!this.overlay.list().some((entry) => entry.actionId === id)) throw new Error("Simulation effect missing.");
374
+ return result(value);
375
+ } catch {
376
+ this.overlay.remove(id);
377
+ const current = this.record(id);
378
+ if (current.status === "pending") this.save({ ...current, status: "uncertain" });
379
+ throw new Error("Action did not complete.");
380
+ }
381
+ });
382
+ } catch (error) {
383
+ throw new Error(sanitizeError(error));
384
+ }
385
+ }
386
+ };
387
+ }
388
+ async applyRecorded(id) {
389
+ const record = this.record(id);
390
+ if (record.status === "applied") {
391
+ this.overlay.remove(id);
392
+ return void 0;
393
+ }
394
+ if (record.status !== "pending") throw new Error("Action is not pending.");
395
+ if ([...this.records.values()].some((other) => other.id < id && !["applied", "rejected", "reverted"].includes(other.status))) throw new Error("Earlier action must be decided first.");
396
+ this.save({ ...record, status: "applying" });
397
+ let applied;
398
+ try {
399
+ applied = await this.impl(record.tool).apply(structuredClone(record.params), id);
400
+ } catch {
401
+ this.save({ ...record, status: "uncertain" });
402
+ throw new Error("Application outcome uncertain.");
403
+ }
404
+ this.save({ ...record, status: "applied", ...applied?.remoteId ? { remoteId: applied.remoteId } : {} });
405
+ this.overlay.remove(id);
406
+ return applied?.value;
407
+ }
408
+ /** Apply once after the kernel's operator decision. Ambiguous remote failures are never blindly retried. */
409
+ async applyAction(actionId) {
410
+ try {
411
+ await this.sequence.run(async () => {
412
+ await this.applyRecorded(actionId);
413
+ });
414
+ } catch (error) {
415
+ throw new Error(sanitizeError(error));
416
+ }
417
+ }
418
+ /** Remove a pending effect. An ambiguous submission/application requires operator reconciliation instead. */
419
+ async rejectAction(actionId) {
420
+ await this.sequence.run(async () => {
421
+ const record = this.record(actionId);
422
+ if (record.status === "rejected") {
423
+ this.overlay.remove(actionId);
424
+ return;
425
+ }
426
+ if (record.status !== "pending") throw new Error("Action is not pending.");
427
+ this.save({ ...record, status: "rejected" });
428
+ this.overlay.remove(actionId);
429
+ });
430
+ }
431
+ /** Revert once using only the recorded remote identifier and original parameters. */
432
+ async revertAction(actionId) {
433
+ try {
434
+ await this.sequence.run(async () => {
435
+ const record = this.record(actionId);
436
+ if (record.status === "reverted") return;
437
+ const impl = this.impl(record.tool);
438
+ if (record.status !== "applied" || !record.description.implementsRevert || !impl.revert) throw new Error("Action cannot be reverted.");
439
+ this.save({ ...record, status: "reverting" });
440
+ try {
441
+ await impl.revert({ actionId, params: structuredClone(record.params), ...record.remoteId ? { remoteId: record.remoteId } : {} });
442
+ } catch {
443
+ this.save({ ...record, status: "uncertain" });
444
+ throw new Error("Revert outcome uncertain.");
445
+ }
446
+ this.save({ ...record, status: "reverted" });
447
+ });
448
+ } catch (error) {
449
+ throw new Error(sanitizeError(error));
450
+ }
451
+ }
452
+ /** v1 defaults to private-only; granting observers is never inferred from resource metadata. */
453
+ async addObserver(_id, _verifier) {
454
+ throw new Error("Shared access is unavailable.");
455
+ }
456
+ async removeObserver(_id) {
457
+ }
458
+ };
459
+ function result(value) {
460
+ const encoded = JSON.stringify(value ?? { ok: true });
461
+ if (encoded === void 0) throw new Error("Invalid tool result.");
462
+ return { content: [{ type: "text", text: encoded }], details: JSON.parse(encoded) };
463
+ }
464
+ function approved(tool, params, ctx) {
465
+ const approval = ctx.actionApproval;
466
+ return !!ctx.toolCallId && approval?.toolCallId === ctx.toolCallId && approval.tool === tool && isDeepStrictEqual(approval.params, params);
467
+ }
468
+
469
+ // src/oauth-nonce.ts
470
+ import { randomBytes as randomBytes2, timingSafeEqual } from "crypto";
471
+ var OAuthNonceMachine = class {
472
+ constructor(ttlMs = 10 * 6e4, now = Date.now) {
473
+ this.ttlMs = ttlMs;
474
+ this.now = now;
475
+ }
476
+ pending = /* @__PURE__ */ new Map();
477
+ /** Issue the first nonce for a local operator-initiated authorization flow. */
478
+ issue(operatorId) {
479
+ if (!operatorId) throw new Error("Operator required.");
480
+ this.sweep();
481
+ const nonce = randomBytes2(24).toString("base64url");
482
+ this.pending.set(nonce, { operatorId, expiresAt: this.now() + this.ttlMs, stage: 1 });
483
+ return nonce;
484
+ }
485
+ /** Consume stage one and mint a distinct callback nonce for stage two. */
486
+ advance(nonce) {
487
+ return this.advanceBound(nonce)?.nonce ?? null;
488
+ }
489
+ /** Rotate stage one while returning its trusted binding to the authorization router. */
490
+ advanceBound(nonce) {
491
+ const record = this.take(nonce, 1);
492
+ if (!record) return null;
493
+ const next = randomBytes2(24).toString("base64url");
494
+ this.pending.set(next, { ...record, stage: 2 });
495
+ return { nonce: next, operatorId: record.operatorId };
496
+ }
497
+ /** Consume only a stage-two callback, exactly once. Invalid, expired and replayed values deny. */
498
+ consume(nonce) {
499
+ return this.take(nonce, 2)?.operatorId ?? null;
500
+ }
501
+ take(nonce, stage) {
502
+ if (!/^[A-Za-z0-9_-]{32}$/.test(nonce)) return null;
503
+ for (const [key, record] of this.pending) {
504
+ if (timingSafeEqual(Buffer.from(key), Buffer.from(nonce))) {
505
+ this.pending.delete(key);
506
+ return record.stage === stage && record.expiresAt > this.now() ? record : null;
507
+ }
508
+ }
509
+ return null;
510
+ }
511
+ /** Remove expired records without accepting them. */
512
+ sweep() {
513
+ for (const [key, record] of this.pending) if (record.expiresAt <= this.now()) this.pending.delete(key);
514
+ }
515
+ };
516
+
517
+ // src/token-store.ts
518
+ import { createCipheriv, createDecipheriv, createHash, randomBytes as randomBytes3 } from "crypto";
519
+ import { chmodSync, mkdirSync as mkdirSync2, realpathSync as realpathSync2, unlinkSync as unlinkSync2 } from "fs";
520
+ import { join as join2 } from "path";
521
+ var TokenStore = class {
522
+ key;
523
+ dir;
524
+ refreshes = /* @__PURE__ */ new Map();
525
+ generations = /* @__PURE__ */ new Map();
526
+ constructor(dir, cellKey) {
527
+ if (cellKey.length !== 32) throw new Error("A 32-byte cell key is required.");
528
+ mkdirSync2(dir, { recursive: true, mode: 448 });
529
+ chmodSync(dir, 448);
530
+ this.dir = realpathSync2(dir);
531
+ this.key = Buffer.from(cellKey);
532
+ }
533
+ path(id) {
534
+ if (!id) throw new Error("Operator required.");
535
+ return join2(this.dir, `${createHash("sha256").update(id).digest("hex")}.json`);
536
+ }
537
+ aad(id) {
538
+ return Buffer.from(JSON.stringify(["clawos-token-v1", this.dir, id]));
539
+ }
540
+ /** Encrypt and atomically replace one account record; plaintext is never written. */
541
+ put(operatorId, value) {
542
+ const path = this.path(operatorId);
543
+ const plaintext = JSON.stringify(value);
544
+ if (plaintext === void 0) throw new Error("Token record must be JSON.");
545
+ const iv = randomBytes3(12), cipher = createCipheriv("aes-256-gcm", this.key, iv);
546
+ cipher.setAAD(this.aad(operatorId));
547
+ const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
548
+ writeJsonAtomic(path, { v: 1, iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), ct: ct.toString("base64") });
549
+ this.generations.set(operatorId, (this.generations.get(operatorId) ?? 0) + 1);
550
+ }
551
+ /** Return null only for an absent account. Tampering, wrong keys and corrupt envelopes fail closed. */
552
+ get(operatorId) {
553
+ const path = this.path(operatorId);
554
+ try {
555
+ const data = readJson(path);
556
+ if (data === void 0) return null;
557
+ const j = data;
558
+ if (j.v !== 1 || typeof j.iv !== "string" || typeof j.tag !== "string" || typeof j.ct !== "string") throw new Error();
559
+ const iv = Buffer.from(j.iv, "base64"), tag = Buffer.from(j.tag, "base64");
560
+ if (iv.length !== 12 || tag.length !== 16) throw new Error();
561
+ const decipher = createDecipheriv("aes-256-gcm", this.key, iv);
562
+ decipher.setAAD(this.aad(operatorId));
563
+ decipher.setAuthTag(tag);
564
+ return JSON.parse(Buffer.concat([decipher.update(Buffer.from(j.ct, "base64")), decipher.final()]).toString("utf8"));
565
+ } catch {
566
+ throw new Error("Credential record could not be decrypted.");
567
+ }
568
+ }
569
+ /** Delete an account and invalidate any in-flight refresh so it cannot restore revoked credentials. */
570
+ remove(operatorId) {
571
+ const path = this.path(operatorId);
572
+ try {
573
+ unlinkSync2(path);
574
+ } catch (error) {
575
+ if (error.code !== "ENOENT") throw new Error("Credential removal failed.");
576
+ }
577
+ this.generations.set(operatorId, (this.generations.get(operatorId) ?? 0) + 1);
578
+ }
579
+ /** Share one refresh per account. A concurrent put/remove makes its stale result fail closed. */
580
+ refresh(operatorId, operation) {
581
+ this.path(operatorId);
582
+ const existing = this.refreshes.get(operatorId);
583
+ if (existing) return existing;
584
+ const generation = this.generations.get(operatorId) ?? 0;
585
+ const pending = Promise.resolve().then(operation).then((value) => {
586
+ if ((this.generations.get(operatorId) ?? 0) !== generation) throw new Error("Credential refresh superseded.");
587
+ this.put(operatorId, value);
588
+ return value;
589
+ }).catch(() => {
590
+ throw new Error("Credential refresh failed.");
591
+ });
592
+ this.refreshes.set(operatorId, pending);
593
+ void pending.finally(() => {
594
+ if (this.refreshes.get(operatorId) === pending) this.refreshes.delete(operatorId);
595
+ }).catch(() => {
596
+ });
597
+ return pending;
598
+ }
599
+ };
600
+
601
+ // src/cache-mutation-store.ts
602
+ var CacheMutationStore = class {
603
+ constructor(base, reducers, path) {
604
+ this.reducers = reducers;
605
+ this.path = path;
606
+ this.state = { version: 1, base: structuredClone(base), pending: [] };
607
+ if (path) {
608
+ const raw = readJson(path);
609
+ if (raw !== void 0) {
610
+ if (raw.version !== 1 || !validEntries(raw.pending) || !("base" in raw)) throw new Error("Invalid cache state.");
611
+ this.state = raw;
612
+ }
613
+ }
614
+ this.view = this.replay(this.state);
615
+ }
616
+ state;
617
+ view;
618
+ replay(state) {
619
+ return structuredClone(state.pending).reduce((value, entry) => {
620
+ const reduce = Object.hasOwn(this.reducers, entry.kind) ? this.reducers[entry.kind] : void 0;
621
+ if (!reduce) throw new Error("Unknown simulation action kind.");
622
+ return reduce(value, entry);
623
+ }, structuredClone(state.base));
624
+ }
625
+ save(next) {
626
+ const view = this.replay(next);
627
+ if (this.path) writeJsonAtomic(this.path, next);
628
+ this.state = next;
629
+ this.view = view;
630
+ }
631
+ /** Return a detached view containing all pending effects. */
632
+ read() {
633
+ return structuredClone(this.view);
634
+ }
635
+ /** Apply one new effect to the cached view after its action was queued. */
636
+ add(entry) {
637
+ const pending = [...this.state.pending, structuredClone(entry)].sort((a, b) => a.actionId - b.actionId);
638
+ if (!validEntries(pending)) throw new Error("Invalid or duplicate cache action.");
639
+ this.save({ ...this.state, pending });
640
+ }
641
+ /** Reject one action and rebuild the view from the authoritative base. */
642
+ remove(actionId) {
643
+ this.save({ ...this.state, pending: this.state.pending.filter((e) => e.actionId !== actionId) });
644
+ }
645
+ /** Refresh authoritative data and replay all pending actions in order. */
646
+ refresh(base) {
647
+ this.save({ ...this.state, base: structuredClone(base) });
648
+ }
649
+ /** Retire an applied effect together with the refreshed authoritative data. */
650
+ commit(actionId, base) {
651
+ this.save({ version: 1, base: structuredClone(base), pending: this.state.pending.filter((e) => e.actionId !== actionId) });
652
+ }
653
+ };
654
+
655
+ // src/testing.ts
656
+ var TestApprovalQueue = class {
657
+ observations = [];
658
+ actions = [];
659
+ denyObservations = false;
660
+ denyActions = false;
661
+ async authorizeObservation(description) {
662
+ if (this.denyObservations) throw new Error("Observation denied.");
663
+ this.observations.push(structuredClone(description));
664
+ }
665
+ async submitAction(id, description) {
666
+ if (this.denyActions) throw new Error("Action denied.");
667
+ if (this.actions.some((action) => action.id === id)) throw new Error("Duplicate action.");
668
+ this.actions.push({ id, description: structuredClone(description) });
669
+ }
670
+ /** Construct a deterministic unit-test call context. */
671
+ context(toolCallId = "test-call") {
672
+ return { agentId: "test-agent", sessionKey: "test-session", toolCallId, queue: this };
673
+ }
674
+ };
675
+ export {
676
+ ActionSequencer,
677
+ CacheMutationStore,
678
+ KitGatekeeper,
679
+ OAuthNonceMachine,
680
+ OverlayStore,
681
+ TestApprovalQueue,
682
+ TokenStore,
683
+ defineGatekeeper,
684
+ gatekeeperRuntimeSlot,
685
+ sanitizeError
686
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@clawkeepers/gatekeeper-kit",
3
+ "version": "0.1.0-beta.1",
4
+ "description": "Builder and security-critical helpers for OpenClaw OS gatekeepers.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "LICENSE",
11
+ "NOTICE",
12
+ "README.md"
13
+ ],
14
+ "dependencies": {
15
+ "typebox": "1.1.39",
16
+ "@clawkeepers/shared": "0.1.0-beta.1"
17
+ },
18
+ "devDependencies": {
19
+ "tsup": "8.5.0",
20
+ "typescript": "5.9.2",
21
+ "vitest": "3.2.4",
22
+ "@types/node": "22.18.0"
23
+ },
24
+ "peerDependencies": {
25
+ "openclaw": ">=2026.9.2 <2026.11.0"
26
+ },
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/clawkeeper/openclaw-os.git",
31
+ "directory": "packages/gatekeeper-kit"
32
+ },
33
+ "private": false,
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "exports": {
38
+ ".": {
39
+ "types": "./dist/index.d.ts",
40
+ "import": "./dist/index.js"
41
+ }
42
+ },
43
+ "engines": {
44
+ "node": ">=22.22.3"
45
+ },
46
+ "scripts": {
47
+ "build": "tsup src/index.ts --format esm --dts --clean",
48
+ "test": "vitest run",
49
+ "typecheck": "tsc -p tsconfig.json --noEmit"
50
+ }
51
+ }