@zanii/gateway 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 +159 -0
- package/README.md +45 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +26 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +60 -0
- package/dist/index.js.map +1 -0
- package/package.json +46 -0
- package/src/cli.ts +29 -0
- package/src/index.ts +81 -0
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,45 @@
|
|
|
1
|
+
# @zanii/gateway
|
|
2
|
+
|
|
3
|
+
A transparent HTTP proxy that records a signed Zanii receipt for **every API call
|
|
4
|
+
an agent makes** — no changes to the agent's code. Point its HTTP client at the
|
|
5
|
+
gateway; the gateway forwards to the real upstream and receipts each call as
|
|
6
|
+
`http.<method>.<path>`.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @zanii/gateway @zanii/sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## As a `fetch` handler (edge / serverless)
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { createZaniiHandler } from '@zanii/gateway';
|
|
16
|
+
import { ZaniiAgent } from '@zanii/sdk';
|
|
17
|
+
|
|
18
|
+
const agent = new ZaniiAgent({ /* did, key, delegation … */ });
|
|
19
|
+
const handler = createZaniiHandler({ upstream: 'https://api.stripe.com', agent });
|
|
20
|
+
|
|
21
|
+
// Cloudflare Workers / Vercel edge:
|
|
22
|
+
export default { fetch: handler };
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Each forwarded request is recorded before the response is returned. Works in any
|
|
26
|
+
`fetch`-based runtime (Node 18+, Workers, Vercel edge).
|
|
27
|
+
|
|
28
|
+
## As a CLI
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
zanii-gateway --upstream https://api.stripe.com --port 4800 --identity identity.json
|
|
32
|
+
# now point the agent at http://localhost:4800 instead of api.stripe.com
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`identity.json` is `{ "agent": { "did": "…", "privateKey": "<hex>" }, "delegation": [ … ] }`.
|
|
36
|
+
Server URL comes from `ZANII_SERVER` (default `https://ledger.zanii.agency`),
|
|
37
|
+
API key from `ZANII_API_KEY`.
|
|
38
|
+
|
|
39
|
+
## Changelog
|
|
40
|
+
|
|
41
|
+
- **0.1.0** — initial release: `createZaniiHandler` (fetch), `createZaniiGateway` (Node), `zanii-gateway` CLI.
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
Apache-2.0.
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import { ZaniiAgent } from '@zanii/sdk';
|
|
5
|
+
import { createZaniiGateway } from './index.js';
|
|
6
|
+
const arg = (n) => {
|
|
7
|
+
const i = process.argv.indexOf(`--${n}`);
|
|
8
|
+
return i >= 0 ? process.argv[i + 1] : undefined;
|
|
9
|
+
};
|
|
10
|
+
const upstream = arg('upstream');
|
|
11
|
+
if (!upstream) {
|
|
12
|
+
console.error('usage: zanii-gateway --upstream <url> [--port 4800] [--identity identity.json] [--prefix http]');
|
|
13
|
+
process.exit(2);
|
|
14
|
+
}
|
|
15
|
+
const port = Number(arg('port') ?? '4800');
|
|
16
|
+
const identity = JSON.parse(readFileSync(arg('identity') ?? './identity.json', 'utf8'));
|
|
17
|
+
const agent = new ZaniiAgent({
|
|
18
|
+
serverUrl: process.env.ZANII_SERVER ?? 'https://ledger.zanii.agency',
|
|
19
|
+
agentDid: identity.agent.did,
|
|
20
|
+
agentPrivateKey: Uint8Array.from(Buffer.from(identity.agent.privateKey, 'hex')),
|
|
21
|
+
delegation: identity.delegation,
|
|
22
|
+
apiKey: process.env.ZANII_API_KEY,
|
|
23
|
+
});
|
|
24
|
+
const gw = createZaniiGateway({ upstream, agent, prefix: arg('prefix') });
|
|
25
|
+
createServer(gw).listen(port, () => console.error(`zanii-gateway: ${upstream} → :${port} (receipting for ${String(identity.agent.did).slice(0, 24)}…)`));
|
|
26
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEhD,MAAM,GAAG,GAAG,CAAC,CAAS,EAAsB,EAAE;IAC5C,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClD,CAAC,CAAC;AAEF,MAAM,QAAQ,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC;AACjC,IAAI,CAAC,QAAQ,EAAE,CAAC;IACd,OAAO,CAAC,KAAK,CAAC,gGAAgG,CAAC,CAAC;IAChH,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AACD,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,CAAC;AAC3C,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,iBAAiB,EAAE,MAAM,CAAC,CAAC,CAAC;AACxF,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC;IAC3B,SAAS,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,6BAA6B;IACpE,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG;IAC5B,eAAe,EAAE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IAC/E,UAAU,EAAE,QAAQ,CAAC,UAAU;IAC/B,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,aAAa;CAClC,CAAC,CAAC;AACH,MAAM,EAAE,GAAG,kBAAkB,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AAC1E,YAAY,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,CACjC,OAAO,CAAC,KAAK,CAAC,kBAAkB,QAAQ,OAAO,IAAI,oBAAoB,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CACpH,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/gateway — receipt every HTTP API call an agent makes, with zero code
|
|
3
|
+
* changes. Point the agent's HTTP client at the gateway; it forwards to the real
|
|
4
|
+
* upstream and records a signed receipt (`<prefix>.<method>.<path>`) for each call.
|
|
5
|
+
*
|
|
6
|
+
* The core is a `fetch`-style handler (edge/serverless-compatible). A Node
|
|
7
|
+
* `http` server wrapper + the `zanii-gateway` CLI build on it.
|
|
8
|
+
*/
|
|
9
|
+
import type { ZaniiAgent } from '@zanii/sdk';
|
|
10
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
11
|
+
export interface GatewayOptions {
|
|
12
|
+
/** The real upstream base URL requests are forwarded to. */
|
|
13
|
+
upstream: string;
|
|
14
|
+
agent: ZaniiAgent;
|
|
15
|
+
/** Receipt target prefix (default `http`). */
|
|
16
|
+
prefix?: string;
|
|
17
|
+
/** Forwarding fetch (default global fetch). */
|
|
18
|
+
fetchImpl?: FetchLike;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Returns a `(request: Request) => Promise<Response>` handler. Works in any
|
|
22
|
+
* fetch-based runtime (Node 18+, Vercel/Cloudflare edge). Each forwarded call is
|
|
23
|
+
* recorded — status + method + path on success, error on failure.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createZaniiHandler(opts: GatewayOptions): (request: Request) => Promise<Response>;
|
|
26
|
+
/**
|
|
27
|
+
* Node `http` server request listener wrapping the handler — for `http.createServer`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createZaniiGateway(opts: GatewayOptions): (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>;
|
|
30
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,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,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,UAAU,CAAC;IAClB,8CAA8C;IAC9C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,SAAS,CAAC,EAAE,SAAS,CAAC;CACvB;AAOD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,cAAc,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAuBhG;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,cAAc,IAEvC,KAAK,OAAO,WAAW,EAAE,eAAe,EAAE,KAAK,OAAO,WAAW,EAAE,cAAc,KAAG,OAAO,CAAC,IAAI,CAAC,CAkBhH"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
function targetFor(prefix, method, pathname) {
|
|
2
|
+
const path = pathname.replace(/[^a-z0-9]+/gi, '.').replace(/^\.|\.$/g, '') || 'root';
|
|
3
|
+
return `${prefix}.${method.toLowerCase()}.${path}`;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Returns a `(request: Request) => Promise<Response>` handler. Works in any
|
|
7
|
+
* fetch-based runtime (Node 18+, Vercel/Cloudflare edge). Each forwarded call is
|
|
8
|
+
* recorded — status + method + path on success, error on failure.
|
|
9
|
+
*/
|
|
10
|
+
export function createZaniiHandler(opts) {
|
|
11
|
+
const upstream = opts.upstream.replace(/\/$/, '');
|
|
12
|
+
const prefix = opts.prefix ?? 'http';
|
|
13
|
+
const fetchImpl = opts.fetchImpl ?? ((u, i) => fetch(u, i));
|
|
14
|
+
return async (request) => {
|
|
15
|
+
const url = new URL(request.url);
|
|
16
|
+
const target = targetFor(prefix, request.method, url.pathname);
|
|
17
|
+
const method = request.method.toUpperCase();
|
|
18
|
+
const body = method === 'GET' || method === 'HEAD' ? undefined : await request.text();
|
|
19
|
+
const headers = {};
|
|
20
|
+
request.headers.forEach((v, k) => { if (k.toLowerCase() !== 'host')
|
|
21
|
+
headers[k] = v; });
|
|
22
|
+
try {
|
|
23
|
+
const res = await fetchImpl(`${upstream}${url.pathname}${url.search}`, { method, headers, body });
|
|
24
|
+
const buf = await res.arrayBuffer();
|
|
25
|
+
await opts.agent.record({ target, payload: { method, path: url.pathname, status: res.status } });
|
|
26
|
+
return new Response(buf, { status: res.status, headers: res.headers });
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
await opts.agent.record({ target, payload: { method, path: url.pathname, error: String(err) } });
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Node `http` server request listener wrapping the handler — for `http.createServer`.
|
|
36
|
+
*/
|
|
37
|
+
export function createZaniiGateway(opts) {
|
|
38
|
+
const handler = createZaniiHandler(opts);
|
|
39
|
+
return async (req, res) => {
|
|
40
|
+
const chunks = [];
|
|
41
|
+
for await (const c of req)
|
|
42
|
+
chunks.push(c);
|
|
43
|
+
const request = new Request(`http://gateway${req.url ?? '/'}`, {
|
|
44
|
+
method: req.method,
|
|
45
|
+
headers: req.headers,
|
|
46
|
+
body: chunks.length ? Buffer.concat(chunks) : undefined,
|
|
47
|
+
});
|
|
48
|
+
try {
|
|
49
|
+
const response = await handler(request);
|
|
50
|
+
res.statusCode = response.status;
|
|
51
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
52
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
res.statusCode = 502;
|
|
56
|
+
res.end(JSON.stringify({ error: `gateway upstream failed: ${String(err)}` }));
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"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CAAC,CAAC;QACpD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,iBAAiB,GAAG,CAAC,GAAG,IAAI,GAAG,EAAE,EAAE;YAC7D,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,OAAO,EAAE,GAAG,CAAC,OAAiC;YAC9C,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS;SACxD,CAAC,CAAC;QACH,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;YACxC,GAAG,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC;YACjC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YACxD,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;QACrD,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;YACrB,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,4BAA4B,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAChF,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zanii/gateway",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Drop-in proxy that receipts every HTTP API call an agent makes - zero code changes. Edge-compatible (fetch handler) plus a Node server and CLI.",
|
|
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
|
+
"bin": {
|
|
17
|
+
"zanii-gateway": "./dist/cli.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"src",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=18"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "^26.1.0",
|
|
33
|
+
"typescript": "^5.8.2",
|
|
34
|
+
"vitest": "^3.0.9",
|
|
35
|
+
"@zanii/sdk": "0.2.1",
|
|
36
|
+
"@zanii/testing": "0.1.0"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@zanii/sdk": "0.2.1"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc -p tsconfig.build.json",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"typecheck": "tsc --noEmit"
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import { ZaniiAgent } from '@zanii/sdk';
|
|
5
|
+
import { createZaniiGateway } from './index.js';
|
|
6
|
+
|
|
7
|
+
const arg = (n: string): string | undefined => {
|
|
8
|
+
const i = process.argv.indexOf(`--${n}`);
|
|
9
|
+
return i >= 0 ? process.argv[i + 1] : undefined;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const upstream = arg('upstream');
|
|
13
|
+
if (!upstream) {
|
|
14
|
+
console.error('usage: zanii-gateway --upstream <url> [--port 4800] [--identity identity.json] [--prefix http]');
|
|
15
|
+
process.exit(2);
|
|
16
|
+
}
|
|
17
|
+
const port = Number(arg('port') ?? '4800');
|
|
18
|
+
const identity = JSON.parse(readFileSync(arg('identity') ?? './identity.json', 'utf8'));
|
|
19
|
+
const agent = new ZaniiAgent({
|
|
20
|
+
serverUrl: process.env.ZANII_SERVER ?? 'https://ledger.zanii.agency',
|
|
21
|
+
agentDid: identity.agent.did,
|
|
22
|
+
agentPrivateKey: Uint8Array.from(Buffer.from(identity.agent.privateKey, 'hex')),
|
|
23
|
+
delegation: identity.delegation,
|
|
24
|
+
apiKey: process.env.ZANII_API_KEY,
|
|
25
|
+
});
|
|
26
|
+
const gw = createZaniiGateway({ upstream, agent, prefix: arg('prefix') });
|
|
27
|
+
createServer(gw).listen(port, () =>
|
|
28
|
+
console.error(`zanii-gateway: ${upstream} → :${port} (receipting for ${String(identity.agent.did).slice(0, 24)}…)`),
|
|
29
|
+
);
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zanii/gateway — receipt every HTTP API call an agent makes, with zero code
|
|
3
|
+
* changes. Point the agent's HTTP client at the gateway; it forwards to the real
|
|
4
|
+
* upstream and records a signed receipt (`<prefix>.<method>.<path>`) for each call.
|
|
5
|
+
*
|
|
6
|
+
* The core is a `fetch`-style handler (edge/serverless-compatible). A Node
|
|
7
|
+
* `http` server wrapper + the `zanii-gateway` CLI build on it.
|
|
8
|
+
*/
|
|
9
|
+
import type { ZaniiAgent } from '@zanii/sdk';
|
|
10
|
+
|
|
11
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
12
|
+
|
|
13
|
+
export interface GatewayOptions {
|
|
14
|
+
/** The real upstream base URL requests are forwarded to. */
|
|
15
|
+
upstream: string;
|
|
16
|
+
agent: ZaniiAgent;
|
|
17
|
+
/** Receipt target prefix (default `http`). */
|
|
18
|
+
prefix?: string;
|
|
19
|
+
/** Forwarding fetch (default global fetch). */
|
|
20
|
+
fetchImpl?: FetchLike;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function targetFor(prefix: string, method: string, pathname: string): string {
|
|
24
|
+
const path = pathname.replace(/[^a-z0-9]+/gi, '.').replace(/^\.|\.$/g, '') || 'root';
|
|
25
|
+
return `${prefix}.${method.toLowerCase()}.${path}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Returns a `(request: Request) => Promise<Response>` handler. Works in any
|
|
30
|
+
* fetch-based runtime (Node 18+, Vercel/Cloudflare edge). Each forwarded call is
|
|
31
|
+
* recorded — status + method + path on success, error on failure.
|
|
32
|
+
*/
|
|
33
|
+
export function createZaniiHandler(opts: GatewayOptions): (request: Request) => Promise<Response> {
|
|
34
|
+
const upstream = opts.upstream.replace(/\/$/, '');
|
|
35
|
+
const prefix = opts.prefix ?? 'http';
|
|
36
|
+
const fetchImpl = opts.fetchImpl ?? ((u, i) => fetch(u, i));
|
|
37
|
+
|
|
38
|
+
return async (request: Request): Promise<Response> => {
|
|
39
|
+
const url = new URL(request.url);
|
|
40
|
+
const target = targetFor(prefix, request.method, url.pathname);
|
|
41
|
+
const method = request.method.toUpperCase();
|
|
42
|
+
const body = method === 'GET' || method === 'HEAD' ? undefined : await request.text();
|
|
43
|
+
const headers: Record<string, string> = {};
|
|
44
|
+
request.headers.forEach((v, k) => { if (k.toLowerCase() !== 'host') headers[k] = v; });
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
const res = await fetchImpl(`${upstream}${url.pathname}${url.search}`, { method, headers, body });
|
|
48
|
+
const buf = await res.arrayBuffer();
|
|
49
|
+
await opts.agent.record({ target, payload: { method, path: url.pathname, status: res.status } });
|
|
50
|
+
return new Response(buf, { status: res.status, headers: res.headers });
|
|
51
|
+
} catch (err) {
|
|
52
|
+
await opts.agent.record({ target, payload: { method, path: url.pathname, error: String(err) } });
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Node `http` server request listener wrapping the handler — for `http.createServer`.
|
|
60
|
+
*/
|
|
61
|
+
export function createZaniiGateway(opts: GatewayOptions) {
|
|
62
|
+
const handler = createZaniiHandler(opts);
|
|
63
|
+
return async (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse): Promise<void> => {
|
|
64
|
+
const chunks: Buffer[] = [];
|
|
65
|
+
for await (const c of req) chunks.push(c as Buffer);
|
|
66
|
+
const request = new Request(`http://gateway${req.url ?? '/'}`, {
|
|
67
|
+
method: req.method,
|
|
68
|
+
headers: req.headers as Record<string, string>,
|
|
69
|
+
body: chunks.length ? Buffer.concat(chunks) : undefined,
|
|
70
|
+
});
|
|
71
|
+
try {
|
|
72
|
+
const response = await handler(request);
|
|
73
|
+
res.statusCode = response.status;
|
|
74
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
75
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
76
|
+
} catch (err) {
|
|
77
|
+
res.statusCode = 502;
|
|
78
|
+
res.end(JSON.stringify({ error: `gateway upstream failed: ${String(err)}` }));
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|