@zanii/chain-bridge 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,53 @@
1
+ # @zanii/chain-bridge
2
+
3
+ **One keypair, two products.** The Zanii L1 (`blockchain.zanii.agency`) and the Zanii
4
+ transparency ledger both use Ed25519 — a chain wallet's public key *is* a ledger
5
+ `did:key`, and the chain address derives from the same bytes:
6
+ `bech32("zan", blake3(pubkey)[:20])`. This bridge turns that fact into a verifiable
7
+ claim: **the agent paying you on-chain is provably the agent whose entire action
8
+ history you can audit on the ledger.**
9
+
10
+ ```sh
11
+ npm install @zanii/chain-bridge @zanii/core @zanii/a2a-directory
12
+ ```
13
+
14
+ ```ts
15
+ import { chainAddressFromDid, verifyChainAgentBinding, resolveChainAgent } from '@zanii/chain-bridge';
16
+
17
+ // the chain's agent registry stores metadata like {"did":"did:key:z6Mk…"} — on its
18
+ // own that's just a string anyone can paste. The binding check closes it:
19
+ const check = verifyChainAgentBinding(entry); // entry from GET /agents
20
+ check.ok; // the claimed DID's key derives EXACTLY the registered zan1… address —
21
+ // the wallet key IS the ledger identity, not a name-drop
22
+ check.did; // the verified ledger identity (null unless ok)
23
+
24
+ // end to end: find on chain → verify binding → pull ledger reputation
25
+ const r = await resolveChainAgent('payments-router'); // or a zan1… address
26
+ r.binding.ok && r.ledger; // { receipts, distinct_counterparties, revoked, … }
27
+ // a failed binding NEVER reaches the ledger — no reputation for a name-dropper
28
+
29
+ // utilities for provisioning one identity across both products:
30
+ chainAddressFromDid(agent.did); // the wallet this ledger agent controls
31
+ ```
32
+
33
+ Python (`pip install "zanii[chain]"` — blake3):
34
+ `from zanii.chain_bridge import verify_chain_agent_binding, resolve_chain_agent, ...`
35
+ — identical derivation, locked by a live-captured vector asserted in both languages.
36
+
37
+ ## Why the binding is strong
38
+
39
+ The registration tx on the chain is **signed by the wallet key**. So when the claimed
40
+ DID's public key derives exactly the registered address, the registrant *is* the DID's
41
+ key holder — one Ed25519 keypair provably controls both the money (session keys,
42
+ streams, transfers on the L1) and the accountability record (receipts, delegation,
43
+ reputation on the ledger). Compose with `@zanii/x402`'s `zaniiChainTxFetcher` to
44
+ verify the payment itself, and `@zanii/kya` to screen before transacting.
45
+
46
+ ## The limit, stated up front
47
+
48
+ The binding proves **key identity — nothing more.** Everything else in the registry
49
+ metadata (role, capabilities) is self-asserted; a chain agent *name* is
50
+ first-come-first-served, not a trademark; and the ledger summary returned here is the
51
+ server's aggregate — full offline acceptance still means following `audit_bundle`
52
+ with `verifyAuditBundle` (`resolveAndVerify`). Read-only: this package never holds
53
+ keys or funds.
@@ -0,0 +1,55 @@
1
+ import { type AgentTrust } from '@zanii/a2a-directory';
2
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
3
+ export declare const CHAIN_HRP = "zan";
4
+ export declare const DEFAULT_CHAIN_RPC = "https://blockchain.zanii.agency";
5
+ /** An entry from the chain's `GET /agents` registry. */
6
+ export interface ChainAgentEntry {
7
+ /** bech32 `zan1…` — the registrant's wallet (the key that signed the registration tx). */
8
+ address: string;
9
+ name: string;
10
+ /** JSON string; convention: `{"did": "did:key:z6Mk…", ...}`. */
11
+ metadata: string;
12
+ since_ms?: number;
13
+ }
14
+ /** Derive a Zanii L1 address from an Ed25519 public key: `bech32("zan", blake3(pub)[:20])`. */
15
+ export declare function chainAddressFromPublicKey(publicKey: Uint8Array): string;
16
+ /** Derive the chain address a ledger DID's key controls. Null if the DID doesn't decode. */
17
+ export declare function chainAddressFromDid(did: string): string | null;
18
+ /** The ledger DID a chain wallet's public key IS (`@zanii/core` `didFromPublicKey`, re-exported for the pairing). */
19
+ export declare function didFromChainPublicKey(publicKey: Uint8Array): string;
20
+ export interface BindingCheck {
21
+ ok: boolean;
22
+ reasons: string[];
23
+ /** The verified DID — the registered wallet's key IS this ledger identity. Null unless ok. */
24
+ did: string | null;
25
+ /** The registry address the DID was verified against. */
26
+ address: string | null;
27
+ }
28
+ /**
29
+ * Does this registry entry's claimed DID actually control the registered wallet?
30
+ * Pure and offline. `ok` means: metadata parses, a `did` is present, it decodes to an
31
+ * Ed25519 key, and that key derives EXACTLY the entry's `zan1…` address. A DID that
32
+ * merely name-drops someone else's identity fails here.
33
+ */
34
+ export declare function verifyChainAgentBinding(entry: ChainAgentEntry | undefined): BindingCheck;
35
+ export interface ResolvedChainAgent {
36
+ /** The registry entry as found on chain. */
37
+ chain: ChainAgentEntry;
38
+ /** The key-identity verdict — trust nothing below unless this is ok. */
39
+ binding: BindingCheck;
40
+ /** The ledger's reputation aggregate for the verified DID. Null when the binding failed or the agent has no ledger history. */
41
+ ledger: AgentTrust | null;
42
+ }
43
+ /**
44
+ * Find an agent on the chain (by exact `name` or `zan1…` address), verify its
45
+ * key-identity binding, and — only when the binding holds — pull its ledger
46
+ * reputation. Paginates `GET /agents` (500/page, capped) so a busy registry still
47
+ * resolves. Returns null when no entry matches.
48
+ */
49
+ export declare function resolveChainAgent(nameOrAddress: string, opts?: {
50
+ chainRpc?: string;
51
+ ledgerServer?: string;
52
+ fetchImpl?: FetchLike;
53
+ maxPages?: number;
54
+ }): Promise<ResolvedChainAgent | null>;
55
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA+BA,OAAO,EAAgB,KAAK,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAGrE,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,C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AC,SAAS,CAAC,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAChG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAuBpC"}
package/dist/index.js ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @zanii/chain-bridge — one keypair, two products.
3
+ *
4
+ * The Zanii L1 (blockchain.zanii.agency) and the Zanii transparency ledger both use
5
+ * Ed25519. A chain wallet's public key *is* a ledger `did:key`, and the chain address
6
+ * is derived from the same bytes: `bech32("zan", blake3(pubkey)[:20])`. This bridge
7
+ * turns that fact into a verifiable claim:
8
+ *
9
+ * - The chain's agent registry stores a self-asserted `metadata` blob whose
10
+ * convention is `{"did": "did:key:z6Mk…"}`. On its own that DID is **just a
11
+ * string** — anyone can paste anyone's DID into their metadata.
12
+ * - `verifyChainAgentBinding` closes it: decode the claimed DID to its Ed25519 key,
13
+ * derive the chain address from that key, and require it to EQUAL the registered
14
+ * wallet address. Since the registration tx was signed by that wallet, a match
15
+ * proves the registrant **controls the DID's key** — the wallet key IS the ledger
16
+ * identity key, not a name-drop.
17
+ * - `resolveChainAgent` finishes the loop: find the agent on chain, verify the
18
+ * binding, then pull its ledger reputation — "the agent paying you on-chain is
19
+ * provably the agent whose entire action history you can audit on the ledger."
20
+ *
21
+ * ## The limit, stated up front
22
+ *
23
+ * The binding proves **key identity** — nothing more. Everything else in the
24
+ * registry metadata (role, capabilities, version) is self-asserted; a chain agent
25
+ * *name* is first-come-first-served, not a trademark; and the ledger summary
26
+ * returned here is the server's aggregate — for full offline acceptance, follow
27
+ * `audit_bundle` with `verifyAuditBundle` (`@zanii/a2a-directory` `resolveAndVerify`).
28
+ * Chain reads are injected and read-only; this package never holds keys or funds.
29
+ */
30
+ import { blake3 } from '@noble/hashes/blake3';
31
+ import { bech32 } from '@scure/base';
32
+ import { resolveAgent } from '@zanii/a2a-directory';
33
+ import { didFromPublicKey, publicKeyFromDid } from '@zanii/core';
34
+ export const CHAIN_HRP = 'zan';
35
+ export const DEFAULT_CHAIN_RPC = 'https://blockchain.zanii.agency';
36
+ /** Derive a Zanii L1 address from an Ed25519 public key: `bech32("zan", blake3(pub)[:20])`. */
37
+ export function chainAddressFromPublicKey(publicKey) {
38
+ return bech32.encode(CHAIN_HRP, bech32.toWords(blake3(publicKey).slice(0, 20)));
39
+ }
40
+ /** Derive the chain address a ledger DID's key controls. Null if the DID doesn't decode. */
41
+ export function chainAddressFromDid(did) {
42
+ const pub = publicKeyFromDid(did);
43
+ return pub ? chainAddressFromPublicKey(pub) : null;
44
+ }
45
+ /** The ledger DID a chain wallet's public key IS (`@zanii/core` `didFromPublicKey`, re-exported for the pairing). */
46
+ export function didFromChainPublicKey(publicKey) {
47
+ return didFromPublicKey(publicKey);
48
+ }
49
+ /**
50
+ * Does this registry entry's claimed DID actually control the registered wallet?
51
+ * Pure and offline. `ok` means: metadata parses, a `did` is present, it decodes to an
52
+ * Ed25519 key, and that key derives EXACTLY the entry's `zan1…` address. A DID that
53
+ * merely name-drops someone else's identity fails here.
54
+ */
55
+ export function verifyChainAgentBinding(entry) {
56
+ const reasons = [];
57
+ const e = entry ?? {};
58
+ if (typeof e.address !== 'string' || !e.address.startsWith(CHAIN_HRP + '1')) {
59
+ return { ok: false, reasons: ['entry has no zan1… address'], did: null, address: null };
60
+ }
61
+ let meta;
62
+ try {
63
+ meta = JSON.parse(e.metadata);
64
+ }
65
+ catch {
66
+ return { ok: false, reasons: ['metadata is not valid JSON'], did: null, address: null };
67
+ }
68
+ const did = meta?.did;
69
+ if (typeof did !== 'string' || !did.startsWith('did:key:')) {
70
+ return { ok: false, reasons: ['metadata claims no did:key — the entry is a name, not an identity'], did: null, address: null };
71
+ }
72
+ const derived = chainAddressFromDid(did);
73
+ if (!derived)
74
+ reasons.push('claimed did does not decode to an Ed25519 key');
75
+ else if (derived !== e.address) {
76
+ reasons.push(`claimed DID derives to ${derived}, but the entry is registered by ${e.address} — a name-dropped identity, not a controlled one`);
77
+ }
78
+ const ok = reasons.length === 0;
79
+ return { ok, reasons, did: ok ? did : null, address: ok ? e.address : null };
80
+ }
81
+ /**
82
+ * Find an agent on the chain (by exact `name` or `zan1…` address), verify its
83
+ * key-identity binding, and — only when the binding holds — pull its ledger
84
+ * reputation. Paginates `GET /agents` (500/page, capped) so a busy registry still
85
+ * resolves. Returns null when no entry matches.
86
+ */
87
+ export async function resolveChainAgent(nameOrAddress, opts = {}) {
88
+ const fetchImpl = opts.fetchImpl ?? ((u, i) => fetch(u, i));
89
+ const rpc = (opts.chainRpc ?? DEFAULT_CHAIN_RPC).replace(/\/$/, '');
90
+ const byAddress = nameOrAddress.startsWith(CHAIN_HRP + '1');
91
+ const maxPages = opts.maxPages ?? 10;
92
+ let entry;
93
+ for (let page = 0; page < maxPages && !entry; page++) {
94
+ const res = await fetchImpl(`${rpc}/agents?limit=500&offset=${page * 500}`);
95
+ if (!res.ok)
96
+ throw new Error(`chain /agents: HTTP ${res.status}`);
97
+ const batch = (await res.json());
98
+ if (!Array.isArray(batch) || batch.length === 0)
99
+ break;
100
+ entry = batch.find((a) => (byAddress ? a.address === nameOrAddress : a.name === nameOrAddress));
101
+ if (batch.length < 500)
102
+ break;
103
+ }
104
+ if (!entry)
105
+ return null;
106
+ const binding = verifyChainAgentBinding(entry);
107
+ let ledger = null;
108
+ if (binding.ok && binding.did) {
109
+ ledger = await resolveAgent(binding.did, { server: opts.ledgerServer, fetchImpl });
110
+ }
111
+ return { chain: entry, binding, ledger };
112
+ }
113
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,YAAY,EAAmB,MAAM,sBAAsB,CAAC;AACrE,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sB,IAAI,CAAC;IACrC,IAAI,OAAO,CAAC,EAAE,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;QAC9B,MAAM,GAAG,MAAM,YAAY,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,EAAE,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC"}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@zanii/chain-bridge",
3
+ "version": "0.1.0",
4
+ "description": "One keypair, two products: bridge the Zanii L1 (blockchain.zanii.agency) to the Zanii transparency ledger. A chain wallet's Ed25519 pubkey IS a ledger did:key, so the bridge PROVES a registered chain agent's claimed DID controls its wallet (address = bech32 zan + blake3(pubkey)[:20]) and resolves it to its verified ledger history - the agent paying you on-chain is provably the agent whose actions you can audit.",
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
+ "@noble/hashes": "^1.7.1",
35
+ "@scure/base": "^1.2.1",
36
+ "@zanii/core": "0.4.0",
37
+ "@zanii/a2a-directory": "0.1.0"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.build.json",
41
+ "test": "vitest run",
42
+ "typecheck": "tsc --noEmit"
43
+ }
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * @zanii/chain-bridge — one keypair, two products.
3
+ *
4
+ * The Zanii L1 (blockchain.zanii.agency) and the Zanii transparency ledger both use
5
+ * Ed25519. A chain wallet's public key *is* a ledger `did:key`, and the chain address
6
+ * is derived from the same bytes: `bech32("zan", blake3(pubkey)[:20])`. This bridge
7
+ * turns that fact into a verifiable claim:
8
+ *
9
+ * - The chain's agent registry stores a self-asserted `metadata` blob whose
10
+ * convention is `{"did": "did:key:z6Mk…"}`. On its own that DID is **just a
11
+ * string** — anyone can paste anyone's DID into their metadata.
12
+ * - `verifyChainAgentBinding` closes it: decode the claimed DID to its Ed25519 key,
13
+ * derive the chain address from that key, and require it to EQUAL the registered
14
+ * wallet address. Since the registration tx was signed by that wallet, a match
15
+ * proves the registrant **controls the DID's key** — the wallet key IS the ledger
16
+ * identity key, not a name-drop.
17
+ * - `resolveChainAgent` finishes the loop: find the agent on chain, verify the
18
+ * binding, then pull its ledger reputation — "the agent paying you on-chain is
19
+ * provably the agent whose entire action history you can audit on the ledger."
20
+ *
21
+ * ## The limit, stated up front
22
+ *
23
+ * The binding proves **key identity** — nothing more. Everything else in the
24
+ * registry metadata (role, capabilities, version) is self-asserted; a chain agent
25
+ * *name* is first-come-first-served, not a trademark; and the ledger summary
26
+ * returned here is the server's aggregate — for full offline acceptance, follow
27
+ * `audit_bundle` with `verifyAuditBundle` (`@zanii/a2a-directory` `resolveAndVerify`).
28
+ * Chain reads are injected and read-only; this package never holds keys or funds.
29
+ */
30
+ import { blake3 } from '@noble/hashes/blake3';
31
+ import { bech32 } from '@scure/base';
32
+ import { resolveAgent, type AgentTrust } from '@zanii/a2a-directory';
33
+ import { didFromPublicKey, publicKeyFromDid } from '@zanii/core';
34
+
35
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
36
+
37
+ export const CHAIN_HRP = 'zan';
38
+ export const DEFAULT_CHAIN_RPC = 'https://blockchain.zanii.agency';
39
+
40
+ /** An entry from the chain's `GET /agents` registry. */
41
+ export interface ChainAgentEntry {
42
+ /** bech32 `zan1…` — the registrant's wallet (the key that signed the registration tx). */
43
+ address: string;
44
+ name: string;
45
+ /** JSON string; convention: `{"did": "did:key:z6Mk…", ...}`. */
46
+ metadata: string;
47
+ since_ms?: number;
48
+ }
49
+
50
+ /** Derive a Zanii L1 address from an Ed25519 public key: `bech32("zan", blake3(pub)[:20])`. */
51
+ export function chainAddressFromPublicKey(publicKey: Uint8Array): string {
52
+ return bech32.encode(CHAIN_HRP, bech32.toWords(blake3(publicKey).slice(0, 20)));
53
+ }
54
+
55
+ /** Derive the chain address a ledger DID's key controls. Null if the DID doesn't decode. */
56
+ export function chainAddressFromDid(did: string): string | null {
57
+ const pub = publicKeyFromDid(did);
58
+ return pub ? chainAddressFromPublicKey(pub) : null;
59
+ }
60
+
61
+ /** The ledger DID a chain wallet's public key IS (`@zanii/core` `didFromPublicKey`, re-exported for the pairing). */
62
+ export function didFromChainPublicKey(publicKey: Uint8Array): string {
63
+ return didFromPublicKey(publicKey);
64
+ }
65
+
66
+ export interface BindingCheck {
67
+ ok: boolean;
68
+ reasons: string[];
69
+ /** The verified DID — the registered wallet's key IS this ledger identity. Null unless ok. */
70
+ did: string | null;
71
+ /** The registry address the DID was verified against. */
72
+ address: string | null;
73
+ }
74
+
75
+ /**
76
+ * Does this registry entry's claimed DID actually control the registered wallet?
77
+ * Pure and offline. `ok` means: metadata parses, a `did` is present, it decodes to an
78
+ * Ed25519 key, and that key derives EXACTLY the entry's `zan1…` address. A DID that
79
+ * merely name-drops someone else's identity fails here.
80
+ */
81
+ export function verifyChainAgentBinding(entry: ChainAgentEntry | undefined): BindingCheck {
82
+ const reasons: string[] = [];
83
+ const e = entry ?? ({} as ChainAgentEntry);
84
+ if (typeof e.address !== 'string' || !e.address.startsWith(CHAIN_HRP + '1')) {
85
+ return { ok: false, reasons: ['entry has no zan1… address'], did: null, address: null };
86
+ }
87
+ let meta: Record<string, unknown>;
88
+ try {
89
+ meta = JSON.parse(e.metadata) as Record<string, unknown>;
90
+ } catch {
91
+ return { ok: false, reasons: ['metadata is not valid JSON'], did: null, address: null };
92
+ }
93
+ const did = meta?.did;
94
+ if (typeof did !== 'string' || !did.startsWith('did:key:')) {
95
+ return { ok: false, reasons: ['metadata claims no did:key — the entry is a name, not an identity'], did: null, address: null };
96
+ }
97
+ const derived = chainAddressFromDid(did);
98
+ if (!derived) reasons.push('claimed did does not decode to an Ed25519 key');
99
+ else if (derived !== e.address) {
100
+ reasons.push(`claimed DID derives to ${derived}, but the entry is registered by ${e.address} — a name-dropped identity, not a controlled one`);
101
+ }
102
+ const ok = reasons.length === 0;
103
+ return { ok, reasons, did: ok ? did : null, address: ok ? e.address : null };
104
+ }
105
+
106
+ export interface ResolvedChainAgent {
107
+ /** The registry entry as found on chain. */
108
+ chain: ChainAgentEntry;
109
+ /** The key-identity verdict — trust nothing below unless this is ok. */
110
+ binding: BindingCheck;
111
+ /** The ledger's reputation aggregate for the verified DID. Null when the binding failed or the agent has no ledger history. */
112
+ ledger: AgentTrust | null;
113
+ }
114
+
115
+ /**
116
+ * Find an agent on the chain (by exact `name` or `zan1…` address), verify its
117
+ * key-identity binding, and — only when the binding holds — pull its ledger
118
+ * reputation. Paginates `GET /agents` (500/page, capped) so a busy registry still
119
+ * resolves. Returns null when no entry matches.
120
+ */
121
+ export async function resolveChainAgent(
122
+ nameOrAddress: string,
123
+ opts: { chainRpc?: string; ledgerServer?: string; fetchImpl?: FetchLike; maxPages?: number } = {},
124
+ ): Promise<ResolvedChainAgent | null> {
125
+ const fetchImpl = opts.fetchImpl ?? ((u: string, i?: RequestInit) => fetch(u, i));
126
+ const rpc = (opts.chainRpc ?? DEFAULT_CHAIN_RPC).replace(/\/$/, '');
127
+ const byAddress = nameOrAddress.startsWith(CHAIN_HRP + '1');
128
+ const maxPages = opts.maxPages ?? 10;
129
+
130
+ let entry: ChainAgentEntry | undefined;
131
+ for (let page = 0; page < maxPages && !entry; page++) {
132
+ const res = await fetchImpl(`${rpc}/agents?limit=500&offset=${page * 500}`);
133
+ if (!res.ok) throw new Error(`chain /agents: HTTP ${res.status}`);
134
+ const batch = (await res.json()) as ChainAgentEntry[];
135
+ if (!Array.isArray(batch) || batch.length === 0) break;
136
+ entry = batch.find((a) => (byAddress ? a.address === nameOrAddress : a.name === nameOrAddress));
137
+ if (batch.length < 500) break;
138
+ }
139
+ if (!entry) return null;
140
+
141
+ const binding = verifyChainAgentBinding(entry);
142
+ let ledger: AgentTrust | null = null;
143
+ if (binding.ok && binding.did) {
144
+ ledger = await resolveAgent(binding.did, { server: opts.ledgerServer, fetchImpl });
145
+ }
146
+ return { chain: entry, binding, ledger };
147
+ }