hallpass-client 0.4.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,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 ADDED
@@ -0,0 +1,52 @@
1
+ # hallpass-client
2
+
3
+ The Node.js and TypeScript client for [hallpass](https://github.com/roee-hersh/hallpass): before
4
+ your AI agent acts for a user, ask the system that owns the resource whether that user may do it.
5
+
6
+ ```sh
7
+ npm install https://github.com/roee-hersh/hallpass/releases/download/v0.4.0/hallpass-client-node.tgz
8
+ ```
9
+
10
+ Every [release](https://github.com/roee-hersh/hallpass/releases) carries the package. Pin a version
11
+ as above rather than using `latest/download`: npm records the tarball's checksum in
12
+ `package-lock.json`, so a URL whose content changes with each release would fail `npm ci` later.
13
+ The package name is `hallpass-client`, so imports read `from "hallpass-client"`.
14
+
15
+ It needs a running hallpass service. The client has no dependencies; it uses Node's built-in `fetch`
16
+ (Node 18.17 or later). It ships as an ES module with type declarations.
17
+
18
+ ```ts
19
+ import { AsyncLocalStorage } from "node:async_hooks";
20
+ import { Hallpass, guarded } from "hallpass-client";
21
+
22
+ const hp = new Hallpass(); // HALLPASS_URL and HALLPASS_API_KEY from the environment
23
+ const currentUser = new AsyncLocalStorage<string>();
24
+
25
+ const deleteIssue = guarded(hp, "jira-main", "DELETE_ISSUES", "issue:{key}", { user: currentUser, fresh: true })(
26
+ async ({ key }: { key: string }) => {
27
+ await jira.deleteIssue(key); // the agent's own credential, only after hallpass said allow
28
+ return `deleted ${key}`;
29
+ },
30
+ );
31
+
32
+ // per request or session, from your auth:
33
+ await currentUser.run(req.user.email, () => generateText({ model, tools, prompt }));
34
+ ```
35
+
36
+ - **The model never picks the user.** It comes from `user`: a string, a zero-argument function,
37
+ or an `AsyncLocalStorage` your application enters. A `user` key in the tool's arguments is ignored.
38
+ - **It fails closed.** `deny`, `unknown` and hallpass being unreachable all reject with
39
+ `PermissionDenied` before the body runs. Pass `deny` to return a message to the model instead.
40
+ - **One package covers every framework.** The wrapped function takes one object of arguments,
41
+ which is what the Vercel AI SDK, the MCP SDK and most agent frameworks pass to a tool.
42
+
43
+ Without a wrapper:
44
+
45
+ ```ts
46
+ const d = await hp.check("dana@example.com", "jira-main", "DELETE_ISSUES", "issue:PAY-123");
47
+ d.decision, d.reason; // "deny", "denied: ..."
48
+ await hp.require(...); // rejects with PermissionDenied unless allow
49
+ ```
50
+
51
+ Framework examples: [examples/agent-ts](https://github.com/roee-hersh/hallpass/tree/main/examples/agent-ts).
52
+ The guide: [docs/agents.md](https://github.com/roee-hersh/hallpass/blob/main/docs/agents.md).
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The hallpass client for agents. Node's built-in fetch, no dependencies.
3
+ *
4
+ * The one rule an agent has to follow: perform an action on behalf of a user
5
+ * only when hallpass answered `allow`. `deny` and `unknown` both mean "do not
6
+ * act", and so does any failure to reach hallpass at all.
7
+ *
8
+ * const hp = new Hallpass(); // HALLPASS_URL and HALLPASS_API_KEY from the environment
9
+ * await hp.require("dana@example.com", "jira-main", "DELETE_ISSUES", "issue:PAY-123");
10
+ * await jira.deleteIssue("PAY-123"); // only reached when the answer was allow
11
+ *
12
+ * Or, for a tool an agent framework exposes to a model, `guarded`:
13
+ *
14
+ * const currentUser = new AsyncLocalStorage<string>();
15
+ *
16
+ * const deleteIssue = guarded(hp, "jira-main", "DELETE_ISSUES", "issue:{key}", { user: currentUser })(
17
+ * async ({ key }: { key: string }) => {
18
+ * await jira.deleteIssue(key);
19
+ * return `deleted ${key}`;
20
+ * },
21
+ * );
22
+ *
23
+ * The user comes from the application, never from the tool's arguments.
24
+ *
25
+ * Install it from a hallpass release (see sdk/node/README.md). This is the TypeScript
26
+ * counterpart of the Python package (sdk/python) and follows the same
27
+ * contract; the tests in examples/agent-ts/hallpass_client.test.ts spell it
28
+ * out.
29
+ */
30
+ import { AsyncLocalStorage } from "node:async_hooks";
31
+ export declare const ALLOW = "allow";
32
+ export declare const DENY = "deny";
33
+ export declare const UNKNOWN = "unknown";
34
+ export type DecisionValue = typeof ALLOW | typeof DENY | typeof UNKNOWN;
35
+ /**
36
+ * One answer from `POST /check`.
37
+ *
38
+ * `decision` is `allow`, `deny` or `unknown`. `reason` is `"<code>: <text>"`
39
+ * as hallpass sent it, or `"client_error: ..."` when the request never
40
+ * produced a usable answer. `status` is the HTTP status, 0 when no response
41
+ * arrived.
42
+ */
43
+ export declare class Decision {
44
+ readonly decision: DecisionValue;
45
+ readonly reason: string;
46
+ readonly status: number;
47
+ constructor(decision: DecisionValue, reason: string, status?: number);
48
+ /** True only for a positive `allow`. `unknown` is not allowed. */
49
+ get allowed(): boolean;
50
+ /** The machine-readable code in front of the colon, e.g. `user_not_found`. */
51
+ get code(): string;
52
+ }
53
+ /** Thrown by `Hallpass.require` when the answer was not `allow`. */
54
+ export declare class PermissionDenied extends Error {
55
+ readonly decision: Decision;
56
+ readonly user: string;
57
+ readonly connection: string;
58
+ readonly action: string;
59
+ readonly resource: string;
60
+ constructor(decision: Decision, user: string, connection: string, action: string, resource: string);
61
+ }
62
+ export interface HallpassOptions {
63
+ /** Defaults to `$HALLPASS_URL` or `http://localhost:8080`. */
64
+ url?: string;
65
+ /** Defaults to `$HALLPASS_API_KEY`. */
66
+ apiKey?: string;
67
+ /** Total budget for one check, connection and body included. Default 10 s. */
68
+ timeoutMs?: number;
69
+ }
70
+ /**
71
+ * Client for one hallpass service.
72
+ *
73
+ * The URL must be `https://`; plain `http://` is accepted only for
74
+ * `localhost` or a loopback address, the same rule hallpass applies to its
75
+ * own upstream URLs, because the API key travels in a header. hallpass
76
+ * itself waits up to the connection's `timeout` (8 s by default) for the
77
+ * upstream system, so keep `timeoutMs` a little above that.
78
+ *
79
+ * Redirects are not followed. A redirect would re-send the API key to
80
+ * whatever host the `Location` header names, and its answer would not be
81
+ * hallpass's, so a 3xx becomes an `unknown` decision like any other
82
+ * unusable response.
83
+ */
84
+ export declare class Hallpass {
85
+ #private;
86
+ readonly url: string;
87
+ readonly timeoutMs: number;
88
+ constructor(options?: HallpassOptions);
89
+ /**
90
+ * Ask hallpass. Never rejects on transport: every failure becomes an
91
+ * `unknown` decision. The fifth argument is the user's groups, or an
92
+ * options object: `{ groups, fresh }`. Groups left out or null are
93
+ * omitted from the request.
94
+ *
95
+ * `fresh: true` asks for an answer straight from the upstream system,
96
+ * skipping hallpass's caches. Use it for destructive actions. It narrows
97
+ * the window between the check and the action to the time between the
98
+ * two; it does not close it.
99
+ */
100
+ check(user: string, connection: string, action: string, resource: string, options?: readonly string[] | null | CheckOptions): Promise<Decision>;
101
+ /** True only when hallpass said `allow`. */
102
+ allowed(user: string, connection: string, action: string, resource: string, options?: readonly string[] | null | CheckOptions): Promise<boolean>;
103
+ /** Resolve to the decision when it is `allow`; reject with `PermissionDenied` otherwise. */
104
+ require(user: string, connection: string, action: string, resource: string, options?: readonly string[] | null | CheckOptions): Promise<Decision>;
105
+ }
106
+ /** Options of `check`, `allowed` and `require`. */
107
+ export interface CheckOptions {
108
+ /** The user's groups; left out or null, none are sent. */
109
+ groups?: readonly string[] | null;
110
+ /** Skip hallpass's caches and ask the upstream system now. */
111
+ fresh?: boolean;
112
+ }
113
+ /**
114
+ * Where the acting user (or their groups) comes from: a fixed value, a
115
+ * zero-argument function, or an `AsyncLocalStorage` the application enters
116
+ * for the current session or request. Resolved on every call.
117
+ */
118
+ export type Source<T> = T | (() => T | undefined) | AsyncLocalStorage<T>;
119
+ export type UserSource = Source<string>;
120
+ export type GroupsSource = Source<readonly string[]>;
121
+ /**
122
+ * Resolve a user or groups source now.
123
+ *
124
+ * An `AsyncLocalStorage` with nothing set for this session throws an error
125
+ * saying so, rather than handing an `undefined` to a framework.
126
+ */
127
+ export declare function current<T>(source: Source<T>, what?: string): T;
128
+ export interface GuardedOptions<D = never> {
129
+ /** Where the acting user comes from. Never the tool's arguments. */
130
+ user: UserSource;
131
+ /** The user's groups, from the same kinds of source. Must yield an array. */
132
+ groups?: GroupsSource;
133
+ /**
134
+ * Called with the `PermissionDenied` instead of throwing it; its return
135
+ * value is returned to the caller. For frameworks that hide a thrown
136
+ * error's text from the model.
137
+ */
138
+ deny?: (e: PermissionDenied) => D | Promise<D>;
139
+ /**
140
+ * Make every check skip hallpass's caches and ask the upstream system
141
+ * now. Use it for delete, merge and scale-type actions.
142
+ */
143
+ fresh?: boolean;
144
+ }
145
+ /** The shape every agent framework hands a tool: one object of arguments, then whatever else it passes. */
146
+ export type Args = Record<string, unknown>;
147
+ /**
148
+ * Wrap a function so it runs only after hallpass allowed it.
149
+ *
150
+ * The user the check is for comes from `options.user`: a string, a
151
+ * zero-argument function, or an `AsyncLocalStorage` the application enters
152
+ * for the current session. It is never read from the call's arguments, so a
153
+ * framework's tool definition can take the wrapped function directly and
154
+ * the model cannot pick who it acts as; a `user` key in the arguments is
155
+ * ignored, never honoured. `groups` works the same way and must yield an
156
+ * array.
157
+ *
158
+ * `resource` is a template over the call's arguments, e.g. `"issue:{key}"`.
159
+ * A call whose arguments cannot fill it makes no request and runs nothing.
160
+ * The wrapped function is called with the same arguments it was given, so
161
+ * an agent framework's extra parameters (tool call id, abort signal, ...)
162
+ * pass through.
163
+ *
164
+ * Any answer other than `allow` rejects with `PermissionDenied` before the
165
+ * body runs. With `options.deny` given, its return value is returned instead.
166
+ */
167
+ export declare function guarded<D = never>(hp: Hallpass, connection: string, action: string, resource: string, options: GuardedOptions<D>): <A extends Args, Rest extends unknown[], R>(fn: (args: A, ...rest: Rest) => R | Promise<R>) => (args: A, ...rest: Rest) => Promise<R | D>;
package/dist/index.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * The hallpass client for agents. Node's built-in fetch, no dependencies.
3
+ *
4
+ * The one rule an agent has to follow: perform an action on behalf of a user
5
+ * only when hallpass answered `allow`. `deny` and `unknown` both mean "do not
6
+ * act", and so does any failure to reach hallpass at all.
7
+ *
8
+ * const hp = new Hallpass(); // HALLPASS_URL and HALLPASS_API_KEY from the environment
9
+ * await hp.require("dana@example.com", "jira-main", "DELETE_ISSUES", "issue:PAY-123");
10
+ * await jira.deleteIssue("PAY-123"); // only reached when the answer was allow
11
+ *
12
+ * Or, for a tool an agent framework exposes to a model, `guarded`:
13
+ *
14
+ * const currentUser = new AsyncLocalStorage<string>();
15
+ *
16
+ * const deleteIssue = guarded(hp, "jira-main", "DELETE_ISSUES", "issue:{key}", { user: currentUser })(
17
+ * async ({ key }: { key: string }) => {
18
+ * await jira.deleteIssue(key);
19
+ * return `deleted ${key}`;
20
+ * },
21
+ * );
22
+ *
23
+ * The user comes from the application, never from the tool's arguments.
24
+ *
25
+ * Install it from a hallpass release (see sdk/node/README.md). This is the TypeScript
26
+ * counterpart of the Python package (sdk/python) and follows the same
27
+ * contract; the tests in examples/agent-ts/hallpass_client.test.ts spell it
28
+ * out.
29
+ */
30
+ import { AsyncLocalStorage } from "node:async_hooks";
31
+ import { isIPv4, isIPv6 } from "node:net";
32
+ export const ALLOW = "allow";
33
+ export const DENY = "deny";
34
+ export const UNKNOWN = "unknown";
35
+ /**
36
+ * One answer from `POST /check`.
37
+ *
38
+ * `decision` is `allow`, `deny` or `unknown`. `reason` is `"<code>: <text>"`
39
+ * as hallpass sent it, or `"client_error: ..."` when the request never
40
+ * produced a usable answer. `status` is the HTTP status, 0 when no response
41
+ * arrived.
42
+ */
43
+ export class Decision {
44
+ decision;
45
+ reason;
46
+ status;
47
+ constructor(decision, reason, status = 200) {
48
+ this.decision = decision;
49
+ this.reason = reason;
50
+ this.status = status;
51
+ Object.freeze(this);
52
+ }
53
+ /** True only for a positive `allow`. `unknown` is not allowed. */
54
+ get allowed() {
55
+ return this.decision === ALLOW;
56
+ }
57
+ /** The machine-readable code in front of the colon, e.g. `user_not_found`. */
58
+ get code() {
59
+ return (this.reason.split(":", 1)[0] ?? "").trim();
60
+ }
61
+ }
62
+ /** Thrown by `Hallpass.require` when the answer was not `allow`. */
63
+ export class PermissionDenied extends Error {
64
+ decision;
65
+ user;
66
+ connection;
67
+ action;
68
+ resource;
69
+ constructor(decision, user, connection, action, resource) {
70
+ super(`${user} may not ${action} on ${resource} in ${connection}: ${decision.decision} (${decision.reason})`);
71
+ this.name = "PermissionDenied";
72
+ this.decision = decision;
73
+ this.user = user;
74
+ this.connection = connection;
75
+ this.action = action;
76
+ this.resource = resource;
77
+ }
78
+ }
79
+ /**
80
+ * Client for one hallpass service.
81
+ *
82
+ * The URL must be `https://`; plain `http://` is accepted only for
83
+ * `localhost` or a loopback address, the same rule hallpass applies to its
84
+ * own upstream URLs, because the API key travels in a header. hallpass
85
+ * itself waits up to the connection's `timeout` (8 s by default) for the
86
+ * upstream system, so keep `timeoutMs` a little above that.
87
+ *
88
+ * Redirects are not followed. A redirect would re-send the API key to
89
+ * whatever host the `Location` header names, and its answer would not be
90
+ * hallpass's, so a 3xx becomes an `unknown` decision like any other
91
+ * unusable response.
92
+ */
93
+ export class Hallpass {
94
+ url;
95
+ timeoutMs;
96
+ #apiKey;
97
+ constructor(options = {}) {
98
+ this.url = validateUrl(options.url || process.env.HALLPASS_URL || "http://localhost:8080");
99
+ this.#apiKey = options.apiKey ?? process.env.HALLPASS_API_KEY ?? "";
100
+ if (!this.#apiKey) {
101
+ throw new Error("hallpass API key missing: pass apiKey or set HALLPASS_API_KEY");
102
+ }
103
+ this.timeoutMs = options.timeoutMs ?? 10_000;
104
+ }
105
+ /**
106
+ * Ask hallpass. Never rejects on transport: every failure becomes an
107
+ * `unknown` decision. The fifth argument is the user's groups, or an
108
+ * options object: `{ groups, fresh }`. Groups left out or null are
109
+ * omitted from the request.
110
+ *
111
+ * `fresh: true` asks for an answer straight from the upstream system,
112
+ * skipping hallpass's caches. Use it for destructive actions. It narrows
113
+ * the window between the check and the action to the time between the
114
+ * two; it does not close it.
115
+ */
116
+ async check(user, connection, action, resource, options) {
117
+ const { groups, fresh } = checkOptions(options);
118
+ const body = { user, connection, action, resource };
119
+ if (groups != null) {
120
+ body.groups = groupList(groups);
121
+ }
122
+ if (fresh) {
123
+ body.fresh = true;
124
+ }
125
+ let response;
126
+ let raw;
127
+ try {
128
+ response = await fetch(this.url + "/check", {
129
+ method: "POST",
130
+ headers: {
131
+ Authorization: "Bearer " + this.#apiKey,
132
+ "Content-Type": "application/json",
133
+ Accept: "application/json",
134
+ },
135
+ body: JSON.stringify(body),
136
+ redirect: "manual",
137
+ signal: AbortSignal.timeout(this.timeoutMs),
138
+ });
139
+ // 400 and 401 still carry a decision body; anything else is unusable
140
+ // and parse() says so. A body cut short or a malformed response
141
+ // rejects here and lands in the catch below.
142
+ raw = await response.text();
143
+ }
144
+ catch (e) {
145
+ return new Decision(UNKNOWN, `client_error: hallpass unreachable: ${describe(e)}`, 0);
146
+ }
147
+ return parse(response.status, raw);
148
+ }
149
+ /** True only when hallpass said `allow`. */
150
+ async allowed(user, connection, action, resource, options) {
151
+ return (await this.check(user, connection, action, resource, options)).allowed;
152
+ }
153
+ /** Resolve to the decision when it is `allow`; reject with `PermissionDenied` otherwise. */
154
+ async require(user, connection, action, resource, options) {
155
+ const d = await this.check(user, connection, action, resource, options);
156
+ if (!d.allowed) {
157
+ throw new PermissionDenied(d, user, connection, action, resource);
158
+ }
159
+ return d;
160
+ }
161
+ }
162
+ /** The rule hallpass applies to its own upstream URLs (ValidateHTTPSURL). */
163
+ function validateUrl(url) {
164
+ if (/[\s?#]/.test(url)) {
165
+ throw new Error(`hallpass url ${JSON.stringify(url)} must not contain whitespace, '?' or '#'`);
166
+ }
167
+ let u;
168
+ try {
169
+ u = new URL(url);
170
+ }
171
+ catch {
172
+ throw new Error(`hallpass url ${JSON.stringify(url)} must start with https:// (http:// only for localhost)`);
173
+ }
174
+ if (u.username || u.password) {
175
+ throw new Error(`hallpass url ${JSON.stringify(url)} must not contain userinfo`);
176
+ }
177
+ if (u.protocol === "https:" && u.hostname) {
178
+ return url.replace(/\/+$/, "");
179
+ }
180
+ if (u.protocol === "http:" && isLoopback(u.hostname)) {
181
+ return url.replace(/\/+$/, "");
182
+ }
183
+ throw new Error(`hallpass url ${JSON.stringify(url)} must start with https:// (http:// only for localhost)`);
184
+ }
185
+ /** localhost, 127.0.0.0/8, ::1, and 127.0.0.0/8 mapped into IPv6, as Go's net.IP.IsLoopback. */
186
+ function isLoopback(hostname) {
187
+ if (hostname === "localhost") {
188
+ return true;
189
+ }
190
+ const host = hostname.replace(/^\[|\]$/g, ""); // URL keeps the brackets around an IPv6 literal
191
+ if (isIPv4(host)) {
192
+ return host.startsWith("127.");
193
+ }
194
+ if (!isIPv6(host)) {
195
+ return false;
196
+ }
197
+ if (host === "::1") {
198
+ return true;
199
+ }
200
+ // URL normalizes ::ffff:127.0.0.1 to ::ffff:7f00:1; the first hex group holds the top two octets.
201
+ const mapped = /^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/i.exec(host);
202
+ return mapped !== null && parseInt(mapped[1], 16) >> 8 === 127;
203
+ }
204
+ function checkOptions(o) {
205
+ if (o == null) {
206
+ return { groups: null, fresh: false };
207
+ }
208
+ if (Array.isArray(o)) {
209
+ return { groups: o, fresh: false };
210
+ }
211
+ if (typeof o === "boolean") {
212
+ throw new TypeError("the fifth argument is the groups array or { groups, fresh }; pass { fresh: true } for a fresh check");
213
+ }
214
+ if (typeof o !== "object" || Symbol.iterator in o) {
215
+ // A Set or another iterable of groups is not an array of them.
216
+ throw new TypeError("groups must be an array of strings");
217
+ }
218
+ for (const key of Object.keys(o)) {
219
+ if (key !== "groups" && key !== "fresh") {
220
+ throw new TypeError(`unknown check option ${JSON.stringify(key)}; the options are groups and fresh`);
221
+ }
222
+ }
223
+ const opts = o;
224
+ if (opts.fresh !== undefined && typeof opts.fresh !== "boolean") {
225
+ throw new TypeError("fresh must be a boolean");
226
+ }
227
+ return { groups: opts.groups ?? null, fresh: opts.fresh === true };
228
+ }
229
+ function groupList(groups) {
230
+ if (typeof groups === "string" || !Array.isArray(groups) || !groups.every((g) => typeof g === "string")) {
231
+ throw new TypeError("groups must be an array of strings");
232
+ }
233
+ return [...groups];
234
+ }
235
+ function describe(e) {
236
+ if (!(e instanceof Error)) {
237
+ return String(e);
238
+ }
239
+ // fetch reports "fetch failed" and keeps the socket error in cause.
240
+ const cause = e.cause instanceof Error ? `: ${e.cause.message}` : "";
241
+ return e.message + cause;
242
+ }
243
+ function parse(status, raw) {
244
+ let data;
245
+ try {
246
+ data = JSON.parse(raw);
247
+ }
248
+ catch {
249
+ return new Decision(UNKNOWN, `client_error: unexpected response (HTTP ${status})`, status);
250
+ }
251
+ if (typeof data !== "object" || data === null || !("decision" in data)) {
252
+ return new Decision(UNKNOWN, `client_error: unexpected response (HTTP ${status})`, status);
253
+ }
254
+ const { decision, reason } = data;
255
+ if (decision !== ALLOW && decision !== DENY && decision !== UNKNOWN) {
256
+ return new Decision(UNKNOWN, `client_error: unexpected decision ${JSON.stringify(decision)}`, status);
257
+ }
258
+ if (decision === ALLOW && status !== 200) {
259
+ // hallpass never allows with a non-200 status; do not trust a proxy that does.
260
+ return new Decision(UNKNOWN, `client_error: allow with HTTP ${status}`, status);
261
+ }
262
+ return new Decision(decision, reason === undefined ? "" : String(reason), status);
263
+ }
264
+ /**
265
+ * Resolve a user or groups source now.
266
+ *
267
+ * An `AsyncLocalStorage` with nothing set for this session throws an error
268
+ * saying so, rather than handing an `undefined` to a framework.
269
+ */
270
+ export function current(source, what = "user") {
271
+ let value;
272
+ if (source instanceof AsyncLocalStorage) {
273
+ value = source.getStore();
274
+ if (value === undefined) {
275
+ throw new Error(`no ${what} set for this session: the AsyncLocalStorage has no store here`);
276
+ }
277
+ return value;
278
+ }
279
+ if (typeof source === "function") {
280
+ value = source();
281
+ if (value === undefined) {
282
+ throw new Error(`no ${what} set for this session: the ${what} function returned undefined`);
283
+ }
284
+ return value;
285
+ }
286
+ return source;
287
+ }
288
+ /**
289
+ * Wrap a function so it runs only after hallpass allowed it.
290
+ *
291
+ * The user the check is for comes from `options.user`: a string, a
292
+ * zero-argument function, or an `AsyncLocalStorage` the application enters
293
+ * for the current session. It is never read from the call's arguments, so a
294
+ * framework's tool definition can take the wrapped function directly and
295
+ * the model cannot pick who it acts as; a `user` key in the arguments is
296
+ * ignored, never honoured. `groups` works the same way and must yield an
297
+ * array.
298
+ *
299
+ * `resource` is a template over the call's arguments, e.g. `"issue:{key}"`.
300
+ * A call whose arguments cannot fill it makes no request and runs nothing.
301
+ * The wrapped function is called with the same arguments it was given, so
302
+ * an agent framework's extra parameters (tool call id, abort signal, ...)
303
+ * pass through.
304
+ *
305
+ * Any answer other than `allow` rejects with `PermissionDenied` before the
306
+ * body runs. With `options.deny` given, its return value is returned instead.
307
+ */
308
+ export function guarded(hp, connection, action, resource, options) {
309
+ const { user, groups, deny, fresh = false } = options;
310
+ return (fn) => {
311
+ const name = fn.name || "the guarded function";
312
+ const inner = async (args, ...rest) => {
313
+ if (typeof args !== "object" || args === null || Array.isArray(args)) {
314
+ throw new TypeError(`${name} takes one object of arguments`);
315
+ }
316
+ // Everything below happens before any request, so a bad call is an
317
+ // error to the caller, never a check on one resource and an action on
318
+ // another.
319
+ const target = fill(resource, args);
320
+ const who = current(user, "user");
321
+ if (typeof who !== "string" || who === "") {
322
+ throw new Error("guarded: user must be a non-empty string");
323
+ }
324
+ const grp = groups === undefined ? undefined : current(groups, "groups");
325
+ try {
326
+ await hp.require(who, connection, action, target, { groups: grp, fresh });
327
+ }
328
+ catch (e) {
329
+ if (e instanceof PermissionDenied && deny !== undefined) {
330
+ return deny(e);
331
+ }
332
+ throw e;
333
+ }
334
+ return fn(args, ...rest);
335
+ };
336
+ Object.defineProperty(inner, "name", { value: fn.name });
337
+ return inner;
338
+ };
339
+ }
340
+ /** `"thing:{thing_id}"` over `{thing_id: "1"}` gives `"thing:1"`. */
341
+ function fill(template, args) {
342
+ return template.replace(/\{([^{}]*)\}/g, (_, key) => {
343
+ const v = args[key];
344
+ if (typeof v === "string") {
345
+ return v;
346
+ }
347
+ if (typeof v === "number" || typeof v === "boolean") {
348
+ return String(v);
349
+ }
350
+ throw new Error(`guarded: resource ${JSON.stringify(template)} needs a string argument ${JSON.stringify(key)}`);
351
+ });
352
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "hallpass-client",
3
+ "version": "0.4.0",
4
+ "description": "Check with hallpass whether a user may do something before your AI agent does it for them.",
5
+ "keywords": [
6
+ "ai-agents",
7
+ "authorization",
8
+ "permissions",
9
+ "llm",
10
+ "tools",
11
+ "mcp"
12
+ ],
13
+ "homepage": "https://github.com/roee-hersh/hallpass/tree/main/sdk/node",
14
+ "bugs": "https://github.com/roee-hersh/hallpass/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/roee-hersh/hallpass.git",
18
+ "directory": "sdk/node"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "main": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "sideEffects": false,
36
+ "engines": {
37
+ "node": ">=18.17"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.json",
41
+ "test": "npm run build && node --test test/package.test.mjs",
42
+ "prepack": "npm run build"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^22.20.4",
46
+ "typescript": "^5.9.3"
47
+ }
48
+ }