@zanii/broker 0.1.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,159 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work; and
103
+
104
+ (d) If the Work includes a "NOTICE" text file as part of its
105
+ distribution, then any Derivative Works that You distribute must
106
+ include a readable copy of the attribution notices contained
107
+ within such NOTICE file.
108
+
109
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
110
+ any Contribution intentionally submitted for inclusion in the Work
111
+ by You to the Licensor shall be under the terms and conditions of
112
+ this License, without any additional terms or conditions.
113
+
114
+ 6. Trademarks. This License does not grant permission to use the trade
115
+ names, trademarks, service marks, or product names of the Licensor,
116
+ except as required for reasonable and customary use in describing the
117
+ origin of the Work and reproducing the content of the NOTICE file.
118
+
119
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed
120
+ to in writing, Licensor provides the Work (and each Contributor
121
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
122
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
123
+ without limitation, any warranties or conditions of TITLE,
124
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
125
+
126
+ 8. Limitation of Liability. In no event and under no legal theory,
127
+ whether in tort (including negligence), contract, or otherwise,
128
+ unless required by applicable law (such as deliberate and grossly
129
+ negligent acts) or agreed to in writing, shall any Contributor be
130
+ liable to You for damages, including any direct, indirect, special,
131
+ incidental, or consequential damages of any character arising as a
132
+ result of this License or out of the use or inability to use the
133
+ Work.
134
+
135
+ 9. Accepting Warranty or Additional Liability. While redistributing
136
+ the Work or Derivative Works thereof, You may choose to offer,
137
+ and charge a fee for, acceptance of support, warranty, indemnity,
138
+ or other liability obligations and/or rights consistent with this
139
+ License. However, in accepting such obligations, You may act only
140
+ on Your own behalf and on Your sole responsibility, not on behalf
141
+ of any other Contributor, and only if You agree to indemnify,
142
+ defend, and hold each Contributor harmless for any liability
143
+ incurred by, or claims asserted against, such Contributor.
144
+
145
+ END OF TERMS AND CONDITIONS
146
+
147
+ Copyright 2026 Zanii
148
+
149
+ Licensed under the Apache License, Version 2.0 (the "License");
150
+ you may not use this file except in compliance with the License.
151
+ You may obtain a copy of the License at
152
+
153
+ http://www.apache.org/licenses/LICENSE-2.0
154
+
155
+ Unless required by applicable law or agreed to in writing, software
156
+ distributed under the License is distributed on an "AS IS" BASIS,
157
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
158
+ See the License for the specific language governing permissions and
159
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @zanii/broker
2
+
3
+ The credential broker that closes Zanii's stated custody hole. Every package's limits
4
+ section ends the same way: *"an agent still holding raw credentials can act off the
5
+ rails."* This replaces detection with one invariant:
6
+
7
+ > **The agent never holds the credential. The broker does — and it injects it ONLY
8
+ > into calls that produced a receipt first.**
9
+
10
+ ```sh
11
+ npm install @zanii/broker @zanii/core
12
+ ```
13
+
14
+ ```ts
15
+ import { createBroker } from '@zanii/broker';
16
+
17
+ const broker = createBroker({
18
+ credentials: {
19
+ openai: { inject: 'bearer', secret: process.env.OPENAI_KEY!, allow: ['https://api.openai.com/v1'] },
20
+ maps: { inject: 'query', name: 'key', secret: process.env.MAPS_KEY!, allow: ['https://maps.googleapis.com/'] },
21
+ },
22
+ // MUST reject unless the receipt is durably accepted — record + flush + check:
23
+ record: async (f) => {
24
+ await agent.record({ target: f.target, payload: f.payload });
25
+ const results = await agent.flush();
26
+ if (results.some((r) => !r.ok)) throw new Error('receipt not accepted');
27
+ },
28
+ gate: (req) => policy.evaluate(req).decision !== 'deny', // optional @zanii/policy hook
29
+ });
30
+
31
+ // the agent asks; it never sees the key:
32
+ const res = await broker.execute({
33
+ credential: 'openai', method: 'POST',
34
+ url: 'https://api.openai.com/v1/chat/completions', body: JSON.stringify(payload),
35
+ });
36
+ ```
37
+
38
+ Python: `from zanii.broker import create_broker` — same semantics.
39
+
40
+ ## Fail-closed by construction (none of this is configurable)
41
+
42
+ 1. **Allow-list first** — each credential is bound to explicit https origins + path
43
+ prefixes. Origins compare **exactly** (`api.openai.com.evil.com` cannot masquerade),
44
+ path prefixes respect segment boundaries (`/v1` allows `/v1/chat`, not `/v1abc`). A
45
+ prompt-injected agent cannot exfiltrate the key to an attacker-chosen URL.
46
+ 2. **Receipt BEFORE call** — `record` must succeed before the upstream is contacted.
47
+ Ledger unreachable = no call. Over-recording is safe; under-recording is the hole.
48
+ 3. **The secret never enters the receipt** — the payload is hashed from the request as
49
+ the agent submitted it, *before* injection.
50
+ 4. **Responses are scrubbed** — `set-cookie` (configurable) stripped before the agent
51
+ sees them.
52
+
53
+ ## The limit, stated up front
54
+
55
+ Isolation is only real when the broker runs in a **separate process/host** from the
56
+ agent (the `@zanii/gateway` deployment shape) — in-process, a compromised agent can
57
+ read the broker's memory. And receipt-or-nothing governs calls made *through* the
58
+ broker: it removes the agent's need to hold credentials; it cannot stop an operator
59
+ who hands the agent raw keys anyway. Adopt the broker AND delete the keys from the
60
+ agent's environment — the second half is yours.
@@ -0,0 +1,59 @@
1
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
2
+ export interface CredentialSpec {
3
+ /** How the secret is injected into the upstream request. */
4
+ inject: 'bearer' | 'header' | 'query';
5
+ /** Header or query-parameter name. Default for `bearer`: `Authorization`. */
6
+ name?: string;
7
+ /** The raw secret — held HERE, never by the agent. */
8
+ secret: string;
9
+ /**
10
+ * URLs this credential may be sent to: full origin + optional path prefix, e.g.
11
+ * `https://api.openai.com/v1`. Origins compare EXACTLY (no suffix tricks —
12
+ * `https://api.openai.com.evil.com` does not match). Required and non-empty:
13
+ * an unbounded credential is the vulnerability this package exists to remove.
14
+ */
15
+ allow: string[];
16
+ }
17
+ export interface BrokerRequest {
18
+ /** Which named credential to use. */
19
+ credential: string;
20
+ method: string;
21
+ url: string;
22
+ headers?: Record<string, string>;
23
+ body?: string;
24
+ }
25
+ export interface BrokerResponse {
26
+ status: number;
27
+ headers: Record<string, string>;
28
+ body: string;
29
+ /** What was recorded for this call (target + payload) — for the agent's own bookkeeping. */
30
+ recorded: {
31
+ target: string;
32
+ payload: Record<string, unknown>;
33
+ };
34
+ }
35
+ export interface BrokerOptions {
36
+ /** The secrets, by name. */
37
+ credentials: Record<string, CredentialSpec>;
38
+ /**
39
+ * Records the receipt and MUST reject/throw unless the receipt is durably accepted
40
+ * (record + flush + check the submit result — see README). If this throws, the
41
+ * upstream call DOES NOT HAPPEN. Fail-closed is the invariant, not an option.
42
+ */
43
+ record: (fields: {
44
+ target: string;
45
+ payload: Record<string, unknown>;
46
+ }) => Promise<unknown>;
47
+ /** Optional pre-flight gate (compose `@zanii/policy` here). false = refuse, nothing recorded. */
48
+ gate?: (req: BrokerRequest) => boolean | Promise<boolean>;
49
+ fetchImpl?: FetchLike;
50
+ /** Response headers stripped before the agent sees them. Default: `['set-cookie']`. */
51
+ stripResponseHeaders?: string[];
52
+ }
53
+ export interface Broker {
54
+ execute(req: BrokerRequest): Promise<BrokerResponse>;
55
+ /** The credential names this broker holds (never the secrets). */
56
+ list(): string[];
57
+ }
58
+ export declare function createBroker(opts: BrokerOptions): Broker;
59
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAoCA,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEjF,MAAM,WAAW,cAAc;IAC7B,4DAA4D;IAC5D,MAAM,EAAE,QAAQ,GAAG,QAAQ,GAAG,OAAO,CAAC;IACtC,6EAA6E;IAC7E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,sDAAsD;IACtD,MAAM,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,M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/dist/index.js ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * @zanii/broker — the credential broker: receipt-or-nothing credential use.
3
+ *
4
+ * Every Zanii package's limits section ends the same way: *"an agent still holding
5
+ * raw credentials can act off the rails."* This package closes that hole with one
6
+ * invariant instead of another detector:
7
+ *
8
+ * > **The agent never holds the credential. The broker does — and it injects it
9
+ * > ONLY into calls that produced a receipt first.**
10
+ *
11
+ * `execute()` is fail-closed by construction, and that is not configurable:
12
+ *
13
+ * 1. **Allow-list first** — each credential is bound to explicit URL origins (+ path
14
+ * prefixes). A request to any other host is refused before anything happens, so a
15
+ * prompt-injected agent cannot exfiltrate the key to an attacker-chosen URL.
16
+ * 2. **Receipt BEFORE call** — the injected `record` function must succeed (i.e. the
17
+ * receipt is durably accepted) before the upstream is contacted. Ledger down =
18
+ * no call. Over-recording (receipted but the call then failed) is safe;
19
+ * under-recording is the entire hole — so the order is record → call, always.
20
+ * 3. **The secret never enters the receipt** — the payload is hashed from the
21
+ * request *as the agent submitted it*, before injection; the credential cannot
22
+ * appear in any hash preimage, log line, or returned artifact.
23
+ * 4. **Responses are scrubbed** — `set-cookie` (and any configured headers) are
24
+ * stripped before the response reaches the agent.
25
+ *
26
+ * ## The limit, stated up front
27
+ *
28
+ * Isolation is only real when the broker runs in a **separate process/host** from
29
+ * the agent (the `@zanii/gateway` deployment shape) — in-process, a compromised
30
+ * agent can read the broker's memory. And receipt-or-nothing governs calls made
31
+ * *through the broker*: it removes the need for the agent to hold credentials, it
32
+ * cannot stop an operator who hands the agent raw keys anyway. Adopt the broker AND
33
+ * delete the keys from the agent's environment — the second half is yours.
34
+ */
35
+ import { hashPayload } from '@zanii/core';
36
+ function parseAllow(entries, credName) {
37
+ if (!entries?.length)
38
+ throw new Error(`credential '${credName}': allow list is required and non-empty — an unbounded credential is the vulnerability`);
39
+ return entries.map((e) => {
40
+ let u;
41
+ try {
42
+ u = new URL(e);
43
+ }
44
+ catch {
45
+ throw new Error(`credential '${credName}': allow entry '${e}' is not a valid URL`);
46
+ }
47
+ if (u.protocol !== 'https:')
48
+ throw new Error(`credential '${credName}': allow entry '${e}' must be https`);
49
+ return { origin: u.origin, pathPrefix: u.pathname };
50
+ });
51
+ }
52
+ function urlAllowed(url, rules) {
53
+ // Origin equality — never prefix-matching on the raw string, so
54
+ // https://api.openai.com.evil.com can NOT masquerade as https://api.openai.com.
55
+ // Path prefixes respect segment boundaries: /v1 allows /v1 and /v1/chat, not /v1abc.
56
+ return rules.some((r) => {
57
+ if (url.origin !== r.origin)
58
+ return false;
59
+ const p = r.pathPrefix;
60
+ return url.pathname === p || url.pathname.startsWith(p.endsWith('/') ? p : p + '/');
61
+ });
62
+ }
63
+ export function createBroker(opts) {
64
+ const rules = new Map();
65
+ for (const [name, spec] of Object.entries(opts.credentials)) {
66
+ if (!spec.secret)
67
+ throw new Error(`credential '${name}': secret is required`);
68
+ rules.set(name, parseAllow(spec.allow, name));
69
+ }
70
+ const fetchImpl = opts.fetchImpl ?? ((u, i) => fetch(u, i));
71
+ const strip = new Set((opts.stripResponseHeaders ?? ['set-cookie']).map((h) => h.toLowerCase()));
72
+ return {
73
+ list: () => Object.keys(opts.credentials),
74
+ async execute(req) {
75
+ const spec = opts.credentials[req.credential];
76
+ if (!spec)
77
+ throw new Error(`unknown credential '${req.credential}'`);
78
+ if (!req.method)
79
+ throw new Error('method is required');
80
+ let url;
81
+ try {
82
+ url = new URL(req.url);
83
+ }
84
+ catch {
85
+ throw new Error(`invalid url '${req.url}'`);
86
+ }
87
+ if (!urlAllowed(url, rules.get(req.credential))) {
88
+ throw new Error(`credential '${req.credential}' is not allowed for ${url.origin}${url.pathname} — refused before any receipt or call`);
89
+ }
90
+ if (opts.gate && !(await opts.gate(req))) {
91
+ throw new Error(`gate refused ${req.method} ${url.origin}${url.pathname}`);
92
+ }
93
+ // The receipt payload is the request AS THE AGENT SUBMITTED IT — hashed
94
+ // before injection, so the secret can never enter the preimage.
95
+ const recorded = {
96
+ target: `broker.${req.credential}.${req.method.toLowerCase()}`,
97
+ payload: {
98
+ method: req.method,
99
+ url: req.url,
100
+ body_hash: hashPayload(req.body ?? ''),
101
+ },
102
+ };
103
+ // Receipt-or-nothing: if this throws, the call below never happens.
104
+ await opts.record(recorded);
105
+ // Inject only now, after the hash and the successful record.
106
+ const headers = { ...(req.headers ?? {}) };
107
+ let finalUrl = url;
108
+ if (spec.inject === 'bearer') {
109
+ headers[spec.name ?? 'Authorization'] = `Bearer ${spec.secret}`;
110
+ }
111
+ else if (spec.inject === 'header') {
112
+ if (!spec.name)
113
+ throw new Error(`credential '${req.credential}': header injection needs a name`);
114
+ headers[spec.name] = spec.secret;
115
+ }
116
+ else {
117
+ if (!spec.name)
118
+ throw new Error(`credential '${req.credential}': query injection needs a name`);
119
+ finalUrl = new URL(url.toString());
120
+ finalUrl.searchParams.set(spec.name, spec.secret);
121
+ }
122
+ const res = await fetchImpl(finalUrl.toString(), {
123
+ method: req.method,
124
+ headers,
125
+ ...(req.body !== undefined ? { body: req.body } : {}),
126
+ });
127
+ const outHeaders = {};
128
+ res.headers.forEach((v, k) => {
129
+ if (!strip.has(k.toLowerCase()))
130
+ outHeaders[k] = v;
131
+ });
132
+ return { status: res.status, headers: outHeaders, body: await res.text(), recorded };
133
+ },
134
+ };
135
+ }
136
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AA0D1C,SAAS,UAAU,CAAC,OAAiB,EAAE,QAAgB;IACrD,IAAI,CAAC,OAAO,EAAE,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,eAAe,QAAQ,wFAAwF,CAAC,CAAC;IACvJ,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;QACvB,IAAI,CAAM,CAAC;QACX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jG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;YACnC,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,IAAI,CAAC,IAAI;oBAAE,MAAM,IAAI,KAAK,CAAC,eAAe,GAAG,CAAC,UAAU,iCAAiC,CAAC,CAAC;gBAChG,QAAQ,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACnC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;YACpD,CAAC;YAED,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE;gBAC/C,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,OAAO;gBACP,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACtD,CAAC,CAAC;YACH,MAAM,UAAU,GAA2B,EAAE,CAAC;YAC9C,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;gBAC3B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;oBAAE,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YACrD,CAAC,CAAC,CAAC;YACH,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,CAAC;QACvF,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@zanii/broker",
3
+ "version": "0.1.0",
4
+ "description": "The credential broker that closes Zanii's stated custody hole: the agent never holds raw API keys - the broker does, and it injects them ONLY into calls that produced a receipt first. Receipt-or-nothing, fail-closed (ledger unreachable = no call), credentials bound to URL origins so they cannot be exfiltrated to attacker-chosen hosts, secrets never in hash preimages or logged responses.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://ledger.zanii.agency",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^26.1.0",
30
+ "typescript": "^5.8.2",
31
+ "vitest": "^3.0.9"
32
+ },
33
+ "dependencies": {
34
+ "@zanii/core": "0.4.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.build.json",
38
+ "test": "vitest run",
39
+ "typecheck": "tsc --noEmit"
40
+ }
41
+ }
package/src/index.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * @zanii/broker — the credential broker: receipt-or-nothing credential use.
3
+ *
4
+ * Every Zanii package's limits section ends the same way: *"an agent still holding
5
+ * raw credentials can act off the rails."* This package closes that hole with one
6
+ * invariant instead of another detector:
7
+ *
8
+ * > **The agent never holds the credential. The broker does — and it injects it
9
+ * > ONLY into calls that produced a receipt first.**
10
+ *
11
+ * `execute()` is fail-closed by construction, and that is not configurable:
12
+ *
13
+ * 1. **Allow-list first** — each credential is bound to explicit URL origins (+ path
14
+ * prefixes). A request to any other host is refused before anything happens, so a
15
+ * prompt-injected agent cannot exfiltrate the key to an attacker-chosen URL.
16
+ * 2. **Receipt BEFORE call** — the injected `record` function must succeed (i.e. the
17
+ * receipt is durably accepted) before the upstream is contacted. Ledger down =
18
+ * no call. Over-recording (receipted but the call then failed) is safe;
19
+ * under-recording is the entire hole — so the order is record → call, always.
20
+ * 3. **The secret never enters the receipt** — the payload is hashed from the
21
+ * request *as the agent submitted it*, before injection; the credential cannot
22
+ * appear in any hash preimage, log line, or returned artifact.
23
+ * 4. **Responses are scrubbed** — `set-cookie` (and any configured headers) are
24
+ * stripped before the response reaches the agent.
25
+ *
26
+ * ## The limit, stated up front
27
+ *
28
+ * Isolation is only real when the broker runs in a **separate process/host** from
29
+ * the agent (the `@zanii/gateway` deployment shape) — in-process, a compromised
30
+ * agent can read the broker's memory. And receipt-or-nothing governs calls made
31
+ * *through the broker*: it removes the need for the agent to hold credentials, it
32
+ * cannot stop an operator who hands the agent raw keys anyway. Adopt the broker AND
33
+ * delete the keys from the agent's environment — the second half is yours.
34
+ */
35
+ import { hashPayload } from '@zanii/core';
36
+
37
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
38
+
39
+ export interface CredentialSpec {
40
+ /** How the secret is injected into the upstream request. */
41
+ inject: 'bearer' | 'header' | 'query';
42
+ /** Header or query-parameter name. Default for `bearer`: `Authorization`. */
43
+ name?: string;
44
+ /** The raw secret — held HERE, never by the agent. */
45
+ secret: string;
46
+ /**
47
+ * URLs this credential may be sent to: full origin + optional path prefix, e.g.
48
+ * `https://api.openai.com/v1`. Origins compare EXACTLY (no suffix tricks —
49
+ * `https://api.openai.com.evil.com` does not match). Required and non-empty:
50
+ * an unbounded credential is the vulnerability this package exists to remove.
51
+ */
52
+ allow: string[];
53
+ }
54
+
55
+ export interface BrokerRequest {
56
+ /** Which named credential to use. */
57
+ credential: string;
58
+ method: string;
59
+ url: string;
60
+ headers?: Record<string, string>;
61
+ body?: string;
62
+ }
63
+
64
+ export interface BrokerResponse {
65
+ status: number;
66
+ headers: Record<string, string>;
67
+ body: string;
68
+ /** What was recorded for this call (target + payload) — for the agent's own bookkeeping. */
69
+ recorded: { target: string; payload: Record<string, unknown> };
70
+ }
71
+
72
+ export interface BrokerOptions {
73
+ /** The secrets, by name. */
74
+ credentials: Record<string, CredentialSpec>;
75
+ /**
76
+ * Records the receipt and MUST reject/throw unless the receipt is durably accepted
77
+ * (record + flush + check the submit result — see README). If this throws, the
78
+ * upstream call DOES NOT HAPPEN. Fail-closed is the invariant, not an option.
79
+ */
80
+ record: (fields: { target: string; payload: Record<string, unknown> }) => Promise<unknown>;
81
+ /** Optional pre-flight gate (compose `@zanii/policy` here). false = refuse, nothing recorded. */
82
+ gate?: (req: BrokerRequest) => boolean | Promise<boolean>;
83
+ fetchImpl?: FetchLike;
84
+ /** Response headers stripped before the agent sees them. Default: `['set-cookie']`. */
85
+ stripResponseHeaders?: string[];
86
+ }
87
+
88
+ interface AllowRule {
89
+ origin: string;
90
+ pathPrefix: string;
91
+ }
92
+
93
+ function parseAllow(entries: string[], credName: string): AllowRule[] {
94
+ if (!entries?.length) throw new Error(`credential '${credName}': allow list is required and non-empty — an unbounded credential is the vulnerability`);
95
+ return entries.map((e) => {
96
+ let u: URL;
97
+ try {
98
+ u = new URL(e);
99
+ } catch {
100
+ throw new Error(`credential '${credName}': allow entry '${e}' is not a valid URL`);
101
+ }
102
+ if (u.protocol !== 'https:') throw new Error(`credential '${credName}': allow entry '${e}' must be https`);
103
+ return { origin: u.origin, pathPrefix: u.pathname };
104
+ });
105
+ }
106
+
107
+ function urlAllowed(url: URL, rules: AllowRule[]): boolean {
108
+ // Origin equality — never prefix-matching on the raw string, so
109
+ // https://api.openai.com.evil.com can NOT masquerade as https://api.openai.com.
110
+ // Path prefixes respect segment boundaries: /v1 allows /v1 and /v1/chat, not /v1abc.
111
+ return rules.some((r) => {
112
+ if (url.origin !== r.origin) return false;
113
+ const p = r.pathPrefix;
114
+ return url.pathname === p || url.pathname.startsWith(p.endsWith('/') ? p : p + '/');
115
+ });
116
+ }
117
+
118
+ export interface Broker {
119
+ execute(req: BrokerRequest): Promise<BrokerResponse>;
120
+ /** The credential names this broker holds (never the secrets). */
121
+ list(): string[];
122
+ }
123
+
124
+ export function createBroker(opts: BrokerOptions): Broker {
125
+ const rules = new Map<string, AllowRule[]>();
126
+ for (const [name, spec] of Object.entries(opts.credentials)) {
127
+ if (!spec.secret) throw new Error(`credential '${name}': secret is required`);
128
+ rules.set(name, parseAllow(spec.allow, name));
129
+ }
130
+ const fetchImpl = opts.fetchImpl ?? ((u: string, i?: RequestInit) => fetch(u, i));
131
+ const strip = new Set((opts.stripResponseHeaders ?? ['set-cookie']).map((h) => h.toLowerCase()));
132
+
133
+ return {
134
+ list: () => Object.keys(opts.credentials),
135
+
136
+ async execute(req: BrokerRequest): Promise<BrokerResponse> {
137
+ const spec = opts.credentials[req.credential];
138
+ if (!spec) throw new Error(`unknown credential '${req.credential}'`);
139
+ if (!req.method) throw new Error('method is required');
140
+
141
+ let url: URL;
142
+ try {
143
+ url = new URL(req.url);
144
+ } catch {
145
+ throw new Error(`invalid url '${req.url}'`);
146
+ }
147
+ if (!urlAllowed(url, rules.get(req.credential)!)) {
148
+ throw new Error(`credential '${req.credential}' is not allowed for ${url.origin}${url.pathname} — refused before any receipt or call`);
149
+ }
150
+ if (opts.gate && !(await opts.gate(req))) {
151
+ throw new Error(`gate refused ${req.method} ${url.origin}${url.pathname}`);
152
+ }
153
+
154
+ // The receipt payload is the request AS THE AGENT SUBMITTED IT — hashed
155
+ // before injection, so the secret can never enter the preimage.
156
+ const recorded = {
157
+ target: `broker.${req.credential}.${req.method.toLowerCase()}`,
158
+ payload: {
159
+ method: req.method,
160
+ url: req.url,
161
+ body_hash: hashPayload(req.body ?? ''),
162
+ },
163
+ };
164
+ // Receipt-or-nothing: if this throws, the call below never happens.
165
+ await opts.record(recorded);
166
+
167
+ // Inject only now, after the hash and the successful record.
168
+ const headers: Record<string, string> = { ...(req.headers ?? {}) };
169
+ let finalUrl = url;
170
+ if (spec.inject === 'bearer') {
171
+ headers[spec.name ?? 'Authorization'] = `Bearer ${spec.secret}`;
172
+ } else if (spec.inject === 'header') {
173
+ if (!spec.name) throw new Error(`credential '${req.credential}': header injection needs a name`);
174
+ headers[spec.name] = spec.secret;
175
+ } else {
176
+ if (!spec.name) throw new Error(`credential '${req.credential}': query injection needs a name`);
177
+ finalUrl = new URL(url.toString());
178
+ finalUrl.searchParams.set(spec.name, spec.secret);
179
+ }
180
+
181
+ const res = await fetchImpl(finalUrl.toString(), {
182
+ method: req.method,
183
+ headers,
184
+ ...(req.body !== undefined ? { body: req.body } : {}),
185
+ });
186
+ const outHeaders: Record<string, string> = {};
187
+ res.headers.forEach((v, k) => {
188
+ if (!strip.has(k.toLowerCase())) outHeaders[k] = v;
189
+ });
190
+ return { status: res.status, headers: outHeaders, body: await res.text(), recorded };
191
+ },
192
+ };
193
+ }