@openmoat/sdk 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Crocodile Labs and OpenMoat contributors
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/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @openmoat/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenMoat's policy decisions for your own agent product, in JavaScript: the engine
4
+ compiled to WebAssembly behind a typed API. Decide each tool call before your loop runs
5
+ it. No dependencies, no network, no telemetry: the module imports nothing from its host.
6
+
7
+ ```sh
8
+ npm install @openmoat/sdk
9
+ ```
10
+
11
+ ```js
12
+ import { load, Session } from "@openmoat/sdk";
13
+
14
+ const openmoat = await load();
15
+ const engine = openmoat.compile({
16
+ policy: openmoat.defaultPolicy,
17
+ context: { home: "/home/me", cwd: "/home/me/app", project: "/home/me/app" },
18
+ });
19
+ const session = new Session();
20
+
21
+ const d = engine.decide({ type: "shell", command: "cat ~/.ssh/id_rsa" }, { session });
22
+ if (d.verdict === "allow") {
23
+ run(d.action); // the frozen copy of exactly what was decided
24
+ session.record(engine, d.action);
25
+ }
26
+ ```
27
+
28
+ **The SDK decides; your code enforces.** A `deny` must not run; a `review` (and a `defer`,
29
+ if your product has no permission flow of its own) runs only after a person approves
30
+ that exact call. It is not a sandbox.
31
+
32
+ It decides every OpenMoat conformance fixture exactly as `openmoat guard` of the same
33
+ version. Full guide, actions, facts and sessions:
34
+ [docs/SDK.md](https://github.com/crocodile-labs/openmoat/blob/main/docs/SDK.md).
35
+ A complete agent loop: `examples/agent-loop.js`.
36
+
37
+ Build from a checkout with `scripts/ci/sdk-js.sh`, which writes `dist/openmoat.wasm` and
38
+ its SHA-256 and runs the tests.
Binary file
@@ -0,0 +1 @@
1
+ 74425a32559ceeff4fb6c1f46b21dfdbd0a148c8746fc6fb7b12c9cacb55af8d openmoat.wasm
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@openmoat/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.16.0",
4
+ "description": "OpenMoat's policy decisions for your own agent: decide each tool call before it runs. WebAssembly, no dependencies, no network.",
5
+ "license": "MIT OR Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/crocodile-labs/openmoat.git",
9
+ "directory": "sdk/js"
10
+ },
11
+ "homepage": "https://github.com/crocodile-labs/openmoat/blob/main/docs/SDK.md",
12
+ "keywords": ["ai-agents", "security", "policy", "mcp", "guardrails"],
13
+ "type": "module",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./src/index.d.ts",
17
+ "default": "./src/index.js"
18
+ },
19
+ "./openmoat.wasm": "./dist/openmoat.wasm"
20
+ },
21
+ "types": "./src/index.d.ts",
22
+ "files": [
23
+ "src/",
24
+ "dist/openmoat.wasm",
25
+ "dist/openmoat.wasm.sha256",
26
+ "LICENSE",
27
+ "LICENSE-APACHE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20"
31
+ },
32
+ "sideEffects": false,
33
+ "scripts": {
34
+ "test": "node --test \"test/*.test.js\""
35
+ }
36
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,102 @@
1
+ // Types of @openmoat/sdk (docs/SDK.md, ADR-046). The shapes are the JSON forms
2
+ // of the Rust crate openmoat-sdk; an unknown field is an error, never ignored.
3
+
4
+ /** `allow < defer < review < deny`.
5
+ * - `deny`: the call must not run; no approval can lift it.
6
+ * - `review` (called `ask` before 0.14.0, ADR-053): it runs only after a person approves this exact call.
7
+ * - `defer`: your own permission flow decides; OpenMoat neither objects nor vouches.
8
+ * - `allow`: it may run. */
9
+ export type Verdict = "allow" | "defer" | "review" | "deny";
10
+
11
+ /** Arguments of an MCP or unknown tool call that name files, hosts or commands,
12
+ * so the usual rules apply to them too. */
13
+ export interface Touches {
14
+ reads?: string[];
15
+ writes?: string[];
16
+ /** URLs or hosts. */
17
+ hosts?: string[];
18
+ commands?: string[];
19
+ }
20
+
21
+ /** One tool call, before it runs. Paths are absolute or relative to `context.cwd`. */
22
+ export type Action =
23
+ | { type: "shell"; command: string }
24
+ | { type: "foreign_shell"; shell: string; command: string }
25
+ | { type: "fs_read"; path: string }
26
+ | { type: "fs_write"; path: string }
27
+ | { type: "read_files"; paths: string[] }
28
+ | { type: "patch"; writes: string[] }
29
+ | { type: "net"; url: string }
30
+ | { type: "fetch"; url: string }
31
+ | { type: "web_search"; query: string }
32
+ /** `opens`: the one URL a call that only opens or reads a page names (a browser's
33
+ * `navigate`), decided like a fetch; a call that sends more names it in `hosts`. */
34
+ | ({ type: "mcp_tool"; name: string; opens?: string[]; unchecked?: string } & Touches)
35
+ | ({ type: "unknown_tool"; host: string; tool: string } & Touches)
36
+ | { type: "unchecked"; action: Action; reason: string };
37
+
38
+ /** Where the agent runs. Absolute, slash-separated paths. */
39
+ export interface Context {
40
+ home: string;
41
+ cwd: string;
42
+ /** The trusted project root, for `${project}`; never the home directory or a root. */
43
+ project?: string;
44
+ real_home?: string;
45
+ real_project?: string;
46
+ /** Default directory → where an environment variable moved it. */
47
+ moved_dirs?: Record<string, string>;
48
+ case_insensitive_paths?: boolean;
49
+ }
50
+
51
+ /** What the caller observed on its filesystem, for the checks that need it. */
52
+ export interface Facts {
53
+ /** Program name → absolute path it resolves to on the search path the call uses. */
54
+ programs?: Record<string, string>;
55
+ /** Program name → path recorded at setup; anywhere else is a deny. */
56
+ pinned?: Record<string, string>;
57
+ /** Symlink path → target. */
58
+ links?: Record<string, string>;
59
+ /** Files that exist, for glob operands. */
60
+ files?: string[];
61
+ }
62
+
63
+ export interface Decision {
64
+ readonly verdict: Verdict;
65
+ /** Rule ids that produced `verdict` (`secrets-paths`, `default.net`, `unparseable`). */
66
+ readonly rules: readonly string[];
67
+ readonly reasons: readonly string[];
68
+ /** `reasons` joined with "; ". */
69
+ readonly reason: string;
70
+ /** Weaker matches that did not decide. */
71
+ readonly context: readonly string[];
72
+ /** A frozen copy of exactly the action decided: run this one. */
73
+ readonly action: Readonly<Action>;
74
+ }
75
+
76
+ export class OpenMoatError extends Error {}
77
+
78
+ export class Session {
79
+ constructor(saved?: string);
80
+ record(engine: Engine, action: Action, facts?: Facts): void;
81
+ save(): string;
82
+ }
83
+
84
+ export class Engine {
85
+ decide(action: Action, options?: { facts?: Facts; session?: Session }): Decision;
86
+ paths(action: Action): string[];
87
+ free(): void;
88
+ [Symbol.dispose](): void;
89
+ }
90
+
91
+ export class OpenMoat {
92
+ readonly version: string;
93
+ readonly policySchemaVersion: number;
94
+ readonly defaultPolicy: string;
95
+ compile(options: {
96
+ policy: string;
97
+ context: Context;
98
+ repository?: { policy: string; trusted?: boolean };
99
+ }): Engine;
100
+ }
101
+
102
+ export function load(options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<OpenMoat>;
package/src/index.js ADDED
@@ -0,0 +1,251 @@
1
+ // OpenMoat's policy decisions for JavaScript: the Rust engine compiled to
2
+ // WebAssembly (crates/openmoat-wasm), behind a typed API. docs/SDK.md, ADR-046.
3
+ //
4
+ // Types are in index.d.ts.
5
+ //
6
+ // The module imports nothing, so it cannot reach a network, a clock or a file.
7
+ // This file reads the module from disk only when `load()` is given no bytes.
8
+ // No telemetry: nothing here sends anything anywhere.
9
+ //
10
+ // The SDK decides; enforcement is the caller's. A call it denies must not run,
11
+ // and a `review` must not run until a person approves that exact call.
12
+
13
+ /** The request protocol version this wrapper speaks (`ABI_VERSION` in Rust). */
14
+ const ABI = 1;
15
+
16
+ /** Characters JSON may hold raw but a YAML 1.2 stream may not (the module
17
+ * reads JSON with the core's YAML 1.2 reader); `JSON.stringify` already
18
+ * escapes C0 controls. Keep in step with `not_yaml_printable` in json.rs. */
19
+ const NOT_YAML_PRINTABLE = /[\u007f-\u009f￾￿]/g;
20
+
21
+ /** An input OpenMoat cannot use, or a module that can no longer answer.
22
+ * Whatever the cause, the call in hand has no decision: do not run it. */
23
+ export class OpenMoatError extends Error {
24
+ /** @param {string} message */
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = "OpenMoatError";
28
+ }
29
+ }
30
+
31
+ /** @param {unknown} value */
32
+ function deepFreeze(value) {
33
+ if (value && typeof value === "object") {
34
+ for (const inner of Object.values(value)) deepFreeze(inner);
35
+ Object.freeze(value);
36
+ }
37
+ return value;
38
+ }
39
+
40
+ /** One instance of the module, and the request/response exchange with it. */
41
+ class Module {
42
+ /** @param {WebAssembly.Instance} instance */
43
+ constructor(instance) {
44
+ const e = /** @type {any} */ (instance.exports);
45
+ /** @type {WebAssembly.Memory} */
46
+ this.memory = e.memory;
47
+ /** @type {(len: number) => number} */
48
+ this.input = e.openmoat_input;
49
+ /** @type {() => number} */
50
+ this.call = e.openmoat_call;
51
+ /** @type {() => number} */
52
+ this.output = e.openmoat_output;
53
+ /** @type {string | null} */
54
+ this.broken = null;
55
+ this.encoder = new TextEncoder();
56
+ this.decoder = new TextDecoder("utf-8", { fatal: true });
57
+ }
58
+
59
+ /**
60
+ * Send one request; the `ok` value of the answer.
61
+ * @param {object} request
62
+ * @returns {any}
63
+ */
64
+ request(request) {
65
+ if (this.broken) throw new OpenMoatError(this.broken);
66
+ const text = JSON.stringify(request).replace(
67
+ NOT_YAML_PRINTABLE,
68
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"),
69
+ );
70
+ const bytes = this.encoder.encode(text);
71
+ let answer;
72
+ try {
73
+ const at = this.input(bytes.length);
74
+ if (at === 0) throw new OpenMoatError("request too large");
75
+ // Views are taken after each call: the module's memory may have grown.
76
+ new Uint8Array(this.memory.buffer, at, bytes.length).set(bytes);
77
+ const len = this.call();
78
+ const out = new Uint8Array(this.memory.buffer, this.output(), len);
79
+ answer = JSON.parse(this.decoder.decode(out));
80
+ } catch (error) {
81
+ if (error instanceof OpenMoatError) throw error;
82
+ // A trap leaves the module's state unknown: it never decides again.
83
+ this.broken = `the OpenMoat module failed and was disabled: ${error}`;
84
+ throw new OpenMoatError(this.broken);
85
+ }
86
+ if (typeof answer.error === "string") throw new OpenMoatError(answer.error);
87
+ return answer.ok;
88
+ }
89
+ }
90
+
91
+ /** One agent session's history, as far as later decisions need it. Record each
92
+ * call after it ran; pass the session to `Engine.decide`. */
93
+ export class Session {
94
+ /** @param {string} [saved] what `save()` returned, to continue a session */
95
+ constructor(saved) {
96
+ if (saved !== undefined && typeof saved !== "string") {
97
+ throw new OpenMoatError("a saved session is the string save() returned");
98
+ }
99
+ /** @type {string | undefined} The module's opaque state; empty when fresh. */
100
+ this.state = saved || undefined;
101
+ }
102
+
103
+ /**
104
+ * Note that `action` ran, as `engine` decided it with `facts`. Record only
105
+ * calls that really ran.
106
+ * @param {Engine} engine
107
+ * @param {import("./index").Action} action
108
+ * @param {import("./index").Facts} [facts]
109
+ */
110
+ record(engine, action, facts) {
111
+ this.state = engine.module.request({
112
+ op: "record",
113
+ engine: engine.handle(),
114
+ action,
115
+ facts,
116
+ session: this.state,
117
+ }).session;
118
+ }
119
+
120
+ /** The session as opaque text, for `new Session(saved)` in another process. */
121
+ save() {
122
+ return this.state ?? "";
123
+ }
124
+ }
125
+
126
+ const released = new FinalizationRegistry(
127
+ /** @param {{module: Module, handle: number}} held */
128
+ ({ module, handle }) => {
129
+ if (!module.broken) module.request({ op: "release", engine: handle });
130
+ },
131
+ );
132
+
133
+ /** A policy compiled for one context. Keep it: compiling dominates the cost. */
134
+ export class Engine {
135
+ /**
136
+ * @param {Module} module
137
+ * @param {number} handle
138
+ */
139
+ constructor(module, handle) {
140
+ this.module = module;
141
+ /** @type {number | null} */
142
+ this.id = handle;
143
+ released.register(this, { module, handle }, this);
144
+ }
145
+
146
+ /** @returns {number} */
147
+ handle() {
148
+ if (this.id === null) throw new OpenMoatError("this engine was freed");
149
+ return this.id;
150
+ }
151
+
152
+ /**
153
+ * Decide `action`. The result carries `action`: a frozen copy of exactly
154
+ * what was decided. Run that, never a value rebuilt from it afterwards.
155
+ * @param {import("./index").Action} action
156
+ * @param {{facts?: import("./index").Facts, session?: Session}} [options]
157
+ * @returns {import("./index").Decision}
158
+ */
159
+ decide(action, options = {}) {
160
+ const decided = deepFreeze(JSON.parse(JSON.stringify(action)));
161
+ const d = this.module.request({
162
+ op: "decide",
163
+ engine: this.handle(),
164
+ action: decided,
165
+ facts: options.facts,
166
+ session: options.session?.state,
167
+ });
168
+ return deepFreeze({
169
+ verdict: d.verdict,
170
+ rules: d.rules,
171
+ reasons: d.reasons,
172
+ reason: d.reasons.join("; "),
173
+ context: d.context,
174
+ action: decided,
175
+ });
176
+ }
177
+
178
+ /**
179
+ * The absolute paths `action` reads or writes, to resolve and report as
180
+ * `facts.links` before deciding.
181
+ * @param {import("./index").Action} action
182
+ * @returns {string[]}
183
+ */
184
+ paths(action) {
185
+ return this.module.request({ op: "paths", engine: this.handle(), action }).paths;
186
+ }
187
+
188
+ /** Release the compiled policy now rather than when collected. */
189
+ free() {
190
+ if (this.id === null) return;
191
+ released.unregister(this);
192
+ const handle = this.id;
193
+ this.id = null;
194
+ if (!this.module.broken) this.module.request({ op: "release", engine: handle });
195
+ }
196
+
197
+ [Symbol.dispose]() {
198
+ this.free();
199
+ }
200
+ }
201
+
202
+ /** A loaded module: compile policies into engines. */
203
+ export class OpenMoat {
204
+ /** @param {Module} module */
205
+ constructor(module) {
206
+ this.module = module;
207
+ const info = module.request({ op: "info" });
208
+ if (info.abi !== ABI) {
209
+ throw new OpenMoatError(`module speaks protocol ${info.abi}; this wrapper speaks ${ABI}`);
210
+ }
211
+ /** The OpenMoat release the module was built from. */
212
+ this.version = /** @type {string} */ (info.version);
213
+ /** The policy schema version (`version:` in a policy) it reads. */
214
+ this.policySchemaVersion = /** @type {number} */ (info.policy_schema_version);
215
+ /** The shipped default policy, as YAML. */
216
+ this.defaultPolicy = /** @type {string} */ (module.request({ op: "default_policy" }).policy);
217
+ }
218
+
219
+ /**
220
+ * Compile `policy` (YAML text) for `context`, with a repository policy
221
+ * merged in when `repository` is given.
222
+ * @param {{policy: string, context: import("./index").Context,
223
+ * repository?: {policy: string, trusted?: boolean}}} options
224
+ * @returns {Engine}
225
+ */
226
+ compile({ policy, context, repository }) {
227
+ const { engine } = this.module.request({ op: "compile", policy, context, repository });
228
+ return new Engine(this.module, engine);
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Load the module. With no `wasm`, it is read from `dist/openmoat.wasm` beside
234
+ * this package (Node); in a browser or bundler, pass the bytes or a compiled
235
+ * `WebAssembly.Module`.
236
+ * @param {{wasm?: BufferSource | WebAssembly.Module}} [options]
237
+ * @returns {Promise<OpenMoat>}
238
+ */
239
+ export async function load(options = {}) {
240
+ let wasm = options.wasm;
241
+ if (wasm === undefined) {
242
+ const { readFile } = await import("node:fs/promises");
243
+ wasm = await readFile(new URL("../dist/openmoat.wasm", import.meta.url));
244
+ }
245
+ const compiled = wasm instanceof WebAssembly.Module ? wasm : await WebAssembly.compile(wasm);
246
+ if (WebAssembly.Module.imports(compiled).length !== 0) {
247
+ throw new OpenMoatError("not OpenMoat's module: it imports from its host");
248
+ }
249
+ const instance = await WebAssembly.instantiate(compiled, {});
250
+ return new OpenMoat(new Module(instance));
251
+ }