@arcblock/did-noise 0.0.0-stage → 1.30.25
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 +13 -0
- package/esm/chacha20poly1305.d.mts +18 -0
- package/esm/chacha20poly1305.mjs +152 -0
- package/esm/chain-node-mesh.d.mts +79 -0
- package/esm/chain-node-mesh.mjs +187 -0
- package/esm/http-transport.d.mts +72 -0
- package/esm/http-transport.mjs +216 -0
- package/esm/index.d.mts +6 -0
- package/esm/index.mjs +7 -0
- package/esm/mesh-tunnel.d.mts +165 -0
- package/esm/mesh-tunnel.mjs +350 -0
- package/esm/noise-session.d.mts +157 -0
- package/esm/noise-session.mjs +491 -0
- package/lib/_vendor/@noble/curves/LICENSE +21 -0
- package/lib/_vendor/@noble/curves/abstract/curve.cjs +338 -0
- package/lib/_vendor/@noble/curves/abstract/edwards.cjs +542 -0
- package/lib/_vendor/@noble/curves/abstract/hash-to-curve.cjs +72 -0
- package/lib/_vendor/@noble/curves/abstract/modular.cjs +557 -0
- package/lib/_vendor/@noble/curves/abstract/montgomery.cjs +149 -0
- package/lib/_vendor/@noble/curves/ed25519.cjs +302 -0
- package/lib/_vendor/@noble/curves/utils.cjs +436 -0
- package/lib/_vendor/@noble/hashes/LICENSE +21 -0
- package/lib/_vendor/@noble/hashes/_blake.cjs +300 -0
- package/lib/_vendor/@noble/hashes/_md.cjs +194 -0
- package/lib/_vendor/@noble/hashes/_u64.cjs +60 -0
- package/lib/_vendor/@noble/hashes/blake2.cjs +291 -0
- package/lib/_vendor/@noble/hashes/hkdf.cjs +104 -0
- package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
- package/lib/_vendor/@noble/hashes/sha2.cjs +417 -0
- package/lib/_vendor/@noble/hashes/utils.cjs +422 -0
- package/lib/chacha20poly1305.cjs +153 -0
- package/lib/chacha20poly1305.d.cts +18 -0
- package/lib/chain-node-mesh.cjs +189 -0
- package/lib/chain-node-mesh.d.cts +79 -0
- package/lib/http-transport.cjs +219 -0
- package/lib/http-transport.d.cts +72 -0
- package/lib/index.cjs +31 -0
- package/lib/index.d.cts +6 -0
- package/lib/mesh-tunnel.cjs +354 -0
- package/lib/mesh-tunnel.d.cts +165 -0
- package/lib/noise-session.cjs +503 -0
- package/lib/noise-session.d.cts +157 -0
- package/package.json +80 -4
- package/README.md +0 -3
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
const require_ed25519 = require('./_vendor/@noble/curves/ed25519.cjs');
|
|
2
|
+
const require_http_transport = require('./http-transport.cjs');
|
|
3
|
+
const require_noise_session = require('./noise-session.cjs');
|
|
4
|
+
const require_mesh_tunnel = require('./mesh-tunnel.cjs');
|
|
5
|
+
|
|
6
|
+
//#region src/chain-node-mesh.ts
|
|
7
|
+
/**
|
|
8
|
+
* ChainNodeDarknet — Zero-Exposure Internal Mesh for Blockchain Nodes
|
|
9
|
+
* (Sequencer <-> Witness / Replica / Gateway)
|
|
10
|
+
*
|
|
11
|
+
* Implements Milestone M3 of Issue #1018 (planning/36 & planning/47):
|
|
12
|
+
* - Sequencer, Witness, Replica, and Gateway nodes communicate exclusively over
|
|
13
|
+
* `Noise_IK` (`@arcblock/did-noise`) encrypted channels inside an isolated `chain-darknet:<chainId>` mesh.
|
|
14
|
+
* - Unauthorized connection attempts are silently dropped in 1-RTT (`NoiseStealthDropError`).
|
|
15
|
+
* - Sequencer collects Ed25519 co-signatures from Witness nodes and replicates commitments
|
|
16
|
+
* to Replicas/Gateways over standard `NoiseHttpBridge` routes (`/internal/witness/sign`, `/internal/replica/sync`).
|
|
17
|
+
*/
|
|
18
|
+
const encoder = new TextEncoder();
|
|
19
|
+
function canonicalizeCommitment(c) {
|
|
20
|
+
return encoder.encode(`${c.chainId}:${c.height}:${c.stateRoot}:${c.txRoot}:${c.timestamp}:${c.sequencerDid}`);
|
|
21
|
+
}
|
|
22
|
+
function verifyWitnessAttestation(commitment, attestation) {
|
|
23
|
+
if (attestation.chainId !== commitment.chainId || attestation.height !== commitment.height || attestation.stateRoot !== commitment.stateRoot || attestation.txRoot !== commitment.txRoot) return false;
|
|
24
|
+
const msg = canonicalizeCommitment(commitment);
|
|
25
|
+
const sig = require_noise_session.fromHex(attestation.signatureHex);
|
|
26
|
+
const pub = require_noise_session.fromHex(attestation.witnessPubkeyHex);
|
|
27
|
+
return require_ed25519.ed25519.verify(sig, msg, pub);
|
|
28
|
+
}
|
|
29
|
+
var ChainNodeDarknet = class {
|
|
30
|
+
constructor(options) {
|
|
31
|
+
this.bridges = /* @__PURE__ */ new Map();
|
|
32
|
+
this.syncedCommitments = [];
|
|
33
|
+
this.chainId = options.chainId;
|
|
34
|
+
this.role = options.role;
|
|
35
|
+
this.identity = options.identity;
|
|
36
|
+
this.meshId = `chain-darknet:${options.chainId}`;
|
|
37
|
+
this.authorizedSequencers = new Set(options.authorizedSequencerDids ?? []);
|
|
38
|
+
this.onCommitmentSynced = options.onCommitmentSynced;
|
|
39
|
+
this.validateCommitmentForWitness = options.validateCommitmentForWitness;
|
|
40
|
+
this.router = new require_mesh_tunnel.MultiMeshRouter(options.identity);
|
|
41
|
+
this.router.joinMesh({
|
|
42
|
+
meshId: this.meshId,
|
|
43
|
+
allowedPeers: options.authorizedPeers,
|
|
44
|
+
label: `Chain Darknet (${options.chainId})`
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
getSyncedCommitments() {
|
|
48
|
+
return [...this.syncedCommitments];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Establish a bidirectional encrypted Noise_IK channel + HTTP bridge with a remote `ChainNodeDarknet`
|
|
52
|
+
* (or custom packet transport).
|
|
53
|
+
*/
|
|
54
|
+
connectToNode(targetNode) {
|
|
55
|
+
const { handshakeMsg, channel: localChannel } = this.router.initiateHandshake(this.meshId, targetNode.identity.pubkeyHex);
|
|
56
|
+
const { responseMsg, channel: remoteChannel } = targetNode.router.respondHandshake(handshakeMsg);
|
|
57
|
+
localChannel.completeHandshake(responseMsg);
|
|
58
|
+
const refs = {};
|
|
59
|
+
const remoteBridge = new require_http_transport.NoiseHttpBridge(remoteChannel, {
|
|
60
|
+
sendEncrypted: (ct) => refs.localBridge?.receiveEncrypted(ct),
|
|
61
|
+
handler: targetNode.handleInternalRequest.bind(targetNode)
|
|
62
|
+
});
|
|
63
|
+
const localBridge = new require_http_transport.NoiseHttpBridge(localChannel, {
|
|
64
|
+
sendEncrypted: (ct) => remoteBridge.receiveEncrypted(ct),
|
|
65
|
+
handler: this.handleInternalRequest.bind(this)
|
|
66
|
+
});
|
|
67
|
+
refs.localBridge = localBridge;
|
|
68
|
+
refs.remoteBridge = remoteBridge;
|
|
69
|
+
const remoteDid = targetNode.identity.did ?? targetNode.identity.pubkeyHex;
|
|
70
|
+
const localDid = this.identity.did ?? this.identity.pubkeyHex;
|
|
71
|
+
this.bridges.set(remoteDid, localBridge);
|
|
72
|
+
this.bridges.set(targetNode.identity.pubkeyHex, localBridge);
|
|
73
|
+
targetNode.bridges.set(localDid, remoteBridge);
|
|
74
|
+
targetNode.bridges.set(this.identity.pubkeyHex, remoteBridge);
|
|
75
|
+
return {
|
|
76
|
+
localChannel,
|
|
77
|
+
remoteChannel
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Sequencer calls a Witness node over the darknet tunnel to obtain an Ed25519 attestation.
|
|
82
|
+
*/
|
|
83
|
+
async requestWitnessSignature(witnessDidOrPubkey, commitment) {
|
|
84
|
+
const bridge = this.bridges.get(witnessDidOrPubkey);
|
|
85
|
+
if (!bridge) throw new Error(`No active darknet bridge to witness "${witnessDidOrPubkey}"`);
|
|
86
|
+
const res = await bridge.fetch("http://witness.internal/internal/witness/sign", {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: { "content-type": "application/json" },
|
|
89
|
+
body: JSON.stringify(commitment)
|
|
90
|
+
});
|
|
91
|
+
if (!res.ok) {
|
|
92
|
+
const errText = await res.text();
|
|
93
|
+
throw new Error(`Witness rejected commitment (${res.status}): ${errText}`);
|
|
94
|
+
}
|
|
95
|
+
const attestation = await res.json();
|
|
96
|
+
if (!verifyWitnessAttestation(commitment, attestation)) throw new Error(`Invalid Ed25519 signature returned by witness ${attestation.witnessDid}`);
|
|
97
|
+
return attestation;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Sequencer replicates a commitment to a Replica or Gateway node over the darknet tunnel.
|
|
101
|
+
*/
|
|
102
|
+
async replicateToNode(replicaDidOrPubkey, commitment) {
|
|
103
|
+
const bridge = this.bridges.get(replicaDidOrPubkey);
|
|
104
|
+
if (!bridge) throw new Error(`No active darknet bridge to replica "${replicaDidOrPubkey}"`);
|
|
105
|
+
const res = await bridge.fetch("http://replica.internal/internal/replica/sync", {
|
|
106
|
+
method: "POST",
|
|
107
|
+
headers: { "content-type": "application/json" },
|
|
108
|
+
body: JSON.stringify(commitment)
|
|
109
|
+
});
|
|
110
|
+
if (!res.ok) {
|
|
111
|
+
const errText = await res.text();
|
|
112
|
+
throw new Error(`Replica sync failed (${res.status}): ${errText}`);
|
|
113
|
+
}
|
|
114
|
+
return await res.json();
|
|
115
|
+
}
|
|
116
|
+
async handleInternalRequest(req, ctx) {
|
|
117
|
+
const url = new URL(req.url);
|
|
118
|
+
if (this.authorizedSequencers.size > 0 && !this.authorizedSequencers.has(ctx.remoteDid) && !this.authorizedSequencers.has(ctx.remotePubkeyHex)) return new Response(JSON.stringify({ error: `Sender ${ctx.remoteDid} is not an authorized sequencer` }), {
|
|
119
|
+
status: 403,
|
|
120
|
+
headers: { "content-type": "application/json" }
|
|
121
|
+
});
|
|
122
|
+
if (req.method === "POST" && url.pathname === "/internal/witness/sign") {
|
|
123
|
+
if (this.role !== "witness") return new Response(JSON.stringify({ error: "Node is not a witness" }), {
|
|
124
|
+
status: 400,
|
|
125
|
+
headers: { "content-type": "application/json" }
|
|
126
|
+
});
|
|
127
|
+
const commitment = await req.json();
|
|
128
|
+
if (commitment.chainId !== this.chainId) return new Response(JSON.stringify({ error: "Chain ID mismatch" }), {
|
|
129
|
+
status: 400,
|
|
130
|
+
headers: { "content-type": "application/json" }
|
|
131
|
+
});
|
|
132
|
+
if (this.validateCommitmentForWitness) {
|
|
133
|
+
if (!await this.validateCommitmentForWitness(commitment, ctx)) return new Response(JSON.stringify({ error: "Commitment rejected by witness policy" }), {
|
|
134
|
+
status: 422,
|
|
135
|
+
headers: { "content-type": "application/json" }
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
const msg = canonicalizeCommitment(commitment);
|
|
139
|
+
const seed = this.identity.secretKey.subarray(0, 32);
|
|
140
|
+
const sig = require_ed25519.ed25519.sign(msg, seed);
|
|
141
|
+
const attestation = {
|
|
142
|
+
chainId: this.chainId,
|
|
143
|
+
height: commitment.height,
|
|
144
|
+
stateRoot: commitment.stateRoot,
|
|
145
|
+
txRoot: commitment.txRoot,
|
|
146
|
+
witnessDid: this.identity.did ?? "",
|
|
147
|
+
witnessPubkeyHex: this.identity.pubkeyHex,
|
|
148
|
+
signatureHex: require_noise_session.toHex(sig)
|
|
149
|
+
};
|
|
150
|
+
return new Response(JSON.stringify(attestation), {
|
|
151
|
+
status: 200,
|
|
152
|
+
headers: { "content-type": "application/json" }
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (req.method === "POST" && url.pathname === "/internal/replica/sync") {
|
|
156
|
+
const commitment = await req.json();
|
|
157
|
+
if (commitment.chainId !== this.chainId) return new Response(JSON.stringify({ error: "Chain ID mismatch" }), {
|
|
158
|
+
status: 400,
|
|
159
|
+
headers: { "content-type": "application/json" }
|
|
160
|
+
});
|
|
161
|
+
this.syncedCommitments.push(commitment);
|
|
162
|
+
if (this.onCommitmentSynced) await this.onCommitmentSynced(commitment, ctx);
|
|
163
|
+
const ack = {
|
|
164
|
+
ok: true,
|
|
165
|
+
replicaDid: this.identity.did ?? "",
|
|
166
|
+
ackedHeight: commitment.height,
|
|
167
|
+
stateRoot: commitment.stateRoot
|
|
168
|
+
};
|
|
169
|
+
return new Response(JSON.stringify(ack), {
|
|
170
|
+
status: 200,
|
|
171
|
+
headers: { "content-type": "application/json" }
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
return new Response(JSON.stringify({ error: "Not Found" }), {
|
|
175
|
+
status: 404,
|
|
176
|
+
headers: { "content-type": "application/json" }
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
close() {
|
|
180
|
+
for (const bridge of this.bridges.values()) bridge.close();
|
|
181
|
+
this.bridges.clear();
|
|
182
|
+
this.router.leaveMesh(this.meshId);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
//#endregion
|
|
187
|
+
exports.ChainNodeDarknet = ChainNodeDarknet;
|
|
188
|
+
exports.canonicalizeCommitment = canonicalizeCommitment;
|
|
189
|
+
exports.verifyWitnessAttestation = verifyWitnessAttestation;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { NoiseIdentity } from "./noise-session.cjs";
|
|
2
|
+
import { EncryptedChannel, MultiMeshRouter } from "./mesh-tunnel.cjs";
|
|
3
|
+
import { NoisePeerContext } from "./http-transport.cjs";
|
|
4
|
+
|
|
5
|
+
//#region src/chain-node-mesh.d.ts
|
|
6
|
+
|
|
7
|
+
type ChainNodeRole = 'sequencer' | 'witness' | 'replica' | 'gateway';
|
|
8
|
+
interface ChainCommitmentPayload {
|
|
9
|
+
chainId: string;
|
|
10
|
+
height: number;
|
|
11
|
+
stateRoot: string;
|
|
12
|
+
txRoot: string;
|
|
13
|
+
timestamp: number;
|
|
14
|
+
sequencerDid: string;
|
|
15
|
+
}
|
|
16
|
+
interface ChainWitnessAttestation {
|
|
17
|
+
chainId: string;
|
|
18
|
+
height: number;
|
|
19
|
+
stateRoot: string;
|
|
20
|
+
txRoot: string;
|
|
21
|
+
witnessDid: string;
|
|
22
|
+
witnessPubkeyHex: string;
|
|
23
|
+
signatureHex: string;
|
|
24
|
+
}
|
|
25
|
+
interface ChainReplicaSyncAck {
|
|
26
|
+
ok: boolean;
|
|
27
|
+
replicaDid: string;
|
|
28
|
+
ackedHeight: number;
|
|
29
|
+
stateRoot: string;
|
|
30
|
+
}
|
|
31
|
+
interface ChainNodeDarknetOptions {
|
|
32
|
+
chainId: string;
|
|
33
|
+
role: ChainNodeRole;
|
|
34
|
+
identity: NoiseIdentity;
|
|
35
|
+
/** Authorized Sequencer DIDs allowed to push commitments / request witness signatures */
|
|
36
|
+
authorizedSequencerDids?: Iterable<string>;
|
|
37
|
+
/** All authorized peer DIDs or pubkeyHexes allowed into this chain's internal darknet */
|
|
38
|
+
authorizedPeers: Iterable<string>;
|
|
39
|
+
/** Optional hook invoked on Replica/Gateway when a verified commitment arrives */
|
|
40
|
+
onCommitmentSynced?: (commitment: ChainCommitmentPayload, peer: NoisePeerContext) => void | Promise<void>;
|
|
41
|
+
/** Optional policy hook invoked on Witness before signing a commitment */
|
|
42
|
+
validateCommitmentForWitness?: (commitment: ChainCommitmentPayload, peer: NoisePeerContext) => boolean | Promise<boolean>;
|
|
43
|
+
}
|
|
44
|
+
declare function canonicalizeCommitment(c: ChainCommitmentPayload): Uint8Array;
|
|
45
|
+
declare function verifyWitnessAttestation(commitment: ChainCommitmentPayload, attestation: ChainWitnessAttestation): boolean;
|
|
46
|
+
declare class ChainNodeDarknet {
|
|
47
|
+
readonly chainId: string;
|
|
48
|
+
readonly role: ChainNodeRole;
|
|
49
|
+
readonly identity: NoiseIdentity;
|
|
50
|
+
readonly meshId: string;
|
|
51
|
+
readonly router: MultiMeshRouter;
|
|
52
|
+
private readonly authorizedSequencers;
|
|
53
|
+
private readonly bridges;
|
|
54
|
+
private readonly onCommitmentSynced?;
|
|
55
|
+
private readonly validateCommitmentForWitness?;
|
|
56
|
+
private readonly syncedCommitments;
|
|
57
|
+
constructor(options: ChainNodeDarknetOptions);
|
|
58
|
+
getSyncedCommitments(): ChainCommitmentPayload[];
|
|
59
|
+
/**
|
|
60
|
+
* Establish a bidirectional encrypted Noise_IK channel + HTTP bridge with a remote `ChainNodeDarknet`
|
|
61
|
+
* (or custom packet transport).
|
|
62
|
+
*/
|
|
63
|
+
connectToNode(targetNode: ChainNodeDarknet): {
|
|
64
|
+
localChannel: EncryptedChannel;
|
|
65
|
+
remoteChannel: EncryptedChannel;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Sequencer calls a Witness node over the darknet tunnel to obtain an Ed25519 attestation.
|
|
69
|
+
*/
|
|
70
|
+
requestWitnessSignature(witnessDidOrPubkey: string, commitment: ChainCommitmentPayload): Promise<ChainWitnessAttestation>;
|
|
71
|
+
/**
|
|
72
|
+
* Sequencer replicates a commitment to a Replica or Gateway node over the darknet tunnel.
|
|
73
|
+
*/
|
|
74
|
+
replicateToNode(replicaDidOrPubkey: string, commitment: ChainCommitmentPayload): Promise<ChainReplicaSyncAck>;
|
|
75
|
+
private handleInternalRequest;
|
|
76
|
+
close(): void;
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
export { ChainCommitmentPayload, ChainNodeDarknet, ChainNodeDarknetOptions, ChainNodeRole, ChainReplicaSyncAck, ChainWitnessAttestation, canonicalizeCommitment, verifyWitnessAttestation };
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/http-transport.ts
|
|
3
|
+
function headersToRecord(headers) {
|
|
4
|
+
const out = {};
|
|
5
|
+
headers.forEach((value, key) => {
|
|
6
|
+
out[key] = value;
|
|
7
|
+
});
|
|
8
|
+
return out;
|
|
9
|
+
}
|
|
10
|
+
let reqSeq = 0;
|
|
11
|
+
function nextRequestId() {
|
|
12
|
+
reqSeq = (reqSeq + 1) % 2147483647;
|
|
13
|
+
return `nreq-${Date.now().toString(36)}-${reqSeq.toString(36)}`;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Multiplexes standard Web `Request` / `Response` pairs over a single `EncryptedChannel`.
|
|
17
|
+
*/
|
|
18
|
+
var NoiseHttpBridge = class {
|
|
19
|
+
constructor(channel, options) {
|
|
20
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
21
|
+
this.channel = channel;
|
|
22
|
+
this.sendEncrypted = options.sendEncrypted;
|
|
23
|
+
this.timeoutMs = options.timeoutMs ?? 15e3;
|
|
24
|
+
this.handler = options.handler;
|
|
25
|
+
this.unsubMessage = this.channel.onMessage((jsonText) => {
|
|
26
|
+
this.onDecryptedMessage(jsonText);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
setHandler(handler) {
|
|
30
|
+
this.handler = handler;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Feed an incoming encrypted frame from the network into the bridge.
|
|
34
|
+
*/
|
|
35
|
+
receiveEncrypted(ciphertext) {
|
|
36
|
+
this.channel.handleEncrypted(ciphertext);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Standard Web `fetch` implementation bound to this encrypted channel.
|
|
40
|
+
*/
|
|
41
|
+
async fetch(input, init) {
|
|
42
|
+
if (!this.channel.isReady()) throw new Error("NoiseHttpBridge: EncryptedChannel is not ready");
|
|
43
|
+
const req = input instanceof Request ? input : new Request(input.toString(), init);
|
|
44
|
+
const id = nextRequestId();
|
|
45
|
+
const arrayBuf = req.body ? await req.arrayBuffer() : null;
|
|
46
|
+
const bodyBase64 = arrayBuf && arrayBuf.byteLength > 0 ? Buffer.from(arrayBuf).toString("base64") : void 0;
|
|
47
|
+
const envelope = {
|
|
48
|
+
kind: "noise-http-req",
|
|
49
|
+
id,
|
|
50
|
+
method: req.method,
|
|
51
|
+
url: req.url,
|
|
52
|
+
headers: headersToRecord(req.headers),
|
|
53
|
+
...bodyBase64 !== void 0 ? { bodyBase64 } : {}
|
|
54
|
+
};
|
|
55
|
+
const encrypted = this.channel.encryptMessage(JSON.stringify(envelope));
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
const timer = setTimeout(() => {
|
|
58
|
+
this.pending.delete(id);
|
|
59
|
+
reject(/* @__PURE__ */ new Error(`Noise HTTP request timed out after ${this.timeoutMs}ms: ${req.url}`));
|
|
60
|
+
}, this.timeoutMs);
|
|
61
|
+
this.pending.set(id, {
|
|
62
|
+
resolve,
|
|
63
|
+
reject,
|
|
64
|
+
timer
|
|
65
|
+
});
|
|
66
|
+
Promise.resolve(this.sendEncrypted(encrypted)).catch((err) => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
this.pending.delete(id);
|
|
69
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
async onDecryptedMessage(jsonText) {
|
|
74
|
+
let parsed;
|
|
75
|
+
try {
|
|
76
|
+
parsed = JSON.parse(jsonText);
|
|
77
|
+
} catch {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (parsed.kind === "noise-http-res") {
|
|
81
|
+
const entry = this.pending.get(parsed.id);
|
|
82
|
+
if (!entry) return;
|
|
83
|
+
clearTimeout(entry.timer);
|
|
84
|
+
this.pending.delete(parsed.id);
|
|
85
|
+
if (parsed.error) {
|
|
86
|
+
entry.reject(new Error(parsed.error));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const body = parsed.bodyBase64 ? Buffer.from(parsed.bodyBase64, "base64") : null;
|
|
90
|
+
const response = new Response(body, {
|
|
91
|
+
status: parsed.status,
|
|
92
|
+
statusText: parsed.statusText,
|
|
93
|
+
headers: parsed.headers
|
|
94
|
+
});
|
|
95
|
+
entry.resolve(response);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (parsed.kind === "noise-http-req") {
|
|
99
|
+
if (!this.handler) {
|
|
100
|
+
const errEnvelope = {
|
|
101
|
+
kind: "noise-http-res",
|
|
102
|
+
id: parsed.id,
|
|
103
|
+
status: 501,
|
|
104
|
+
statusText: "Not Implemented",
|
|
105
|
+
headers: { "content-type": "application/json" },
|
|
106
|
+
bodyBase64: Buffer.from(JSON.stringify({ error: "No handler registered" })).toString("base64")
|
|
107
|
+
};
|
|
108
|
+
const ct = this.channel.encryptMessage(JSON.stringify(errEnvelope));
|
|
109
|
+
await this.sendEncrypted(ct);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const reqBody = parsed.bodyBase64 ? Buffer.from(parsed.bodyBase64, "base64") : void 0;
|
|
114
|
+
const headers = new Headers(parsed.headers);
|
|
115
|
+
if (this.channel.remoteDid) headers.set("x-noise-peer-did", this.channel.remoteDid);
|
|
116
|
+
if (this.channel.remotePubkeyHex) headers.set("x-noise-peer-pubkey", this.channel.remotePubkeyHex);
|
|
117
|
+
if (this.channel.meshId) headers.set("x-noise-mesh-id", this.channel.meshId);
|
|
118
|
+
const request = new Request(parsed.url, {
|
|
119
|
+
method: parsed.method,
|
|
120
|
+
headers,
|
|
121
|
+
body: parsed.method === "GET" || parsed.method === "HEAD" ? void 0 : reqBody
|
|
122
|
+
});
|
|
123
|
+
const context = {
|
|
124
|
+
remoteDid: this.channel.remoteDid ?? "",
|
|
125
|
+
remotePubkeyHex: this.channel.remotePubkeyHex ?? "",
|
|
126
|
+
...this.channel.meshId !== void 0 ? { meshId: this.channel.meshId } : {},
|
|
127
|
+
claims: this.channel.remoteClaims
|
|
128
|
+
};
|
|
129
|
+
const response = await this.handler(request, context);
|
|
130
|
+
const resBuf = response.body ? await response.arrayBuffer() : null;
|
|
131
|
+
const resBase64 = resBuf && resBuf.byteLength > 0 ? Buffer.from(resBuf).toString("base64") : void 0;
|
|
132
|
+
const resEnvelope = {
|
|
133
|
+
kind: "noise-http-res",
|
|
134
|
+
id: parsed.id,
|
|
135
|
+
status: response.status,
|
|
136
|
+
statusText: response.statusText,
|
|
137
|
+
headers: headersToRecord(response.headers),
|
|
138
|
+
...resBase64 !== void 0 ? { bodyBase64: resBase64 } : {}
|
|
139
|
+
};
|
|
140
|
+
const ct = this.channel.encryptMessage(JSON.stringify(resEnvelope));
|
|
141
|
+
await this.sendEncrypted(ct);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
const resEnvelope = {
|
|
144
|
+
kind: "noise-http-res",
|
|
145
|
+
id: parsed.id,
|
|
146
|
+
status: 500,
|
|
147
|
+
statusText: "Internal Server Error",
|
|
148
|
+
headers: {},
|
|
149
|
+
error: err instanceof Error ? err.message : String(err)
|
|
150
|
+
};
|
|
151
|
+
const ct = this.channel.encryptMessage(JSON.stringify(resEnvelope));
|
|
152
|
+
await this.sendEncrypted(ct);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
close() {
|
|
157
|
+
this.unsubMessage();
|
|
158
|
+
for (const [id, entry] of this.pending.entries()) {
|
|
159
|
+
clearTimeout(entry.timer);
|
|
160
|
+
entry.reject(/* @__PURE__ */ new Error("NoiseHttpBridge closed"));
|
|
161
|
+
this.pending.delete(id);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
/**
|
|
166
|
+
* Convenience helper to create a standard `(input, init) => Promise<Response>` fetch function
|
|
167
|
+
* bound to a `NoiseHttpBridge`.
|
|
168
|
+
*/
|
|
169
|
+
function createNoiseFetch(bridge) {
|
|
170
|
+
return bridge.fetch.bind(bridge);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Normalize URLs containing `did:abt:<address>.<meshId>.arc` in the authority position
|
|
174
|
+
* so standard `URL` / `Request` parsers do not treat `:abt:` as a port number.
|
|
175
|
+
*/
|
|
176
|
+
function normalizeNoiseUrl(rawUrl) {
|
|
177
|
+
const match = rawUrl.match(/^(https?:\/\/)([^/?#]+)(.*)$/i);
|
|
178
|
+
if (!match) return {
|
|
179
|
+
normalizedUrl: rawUrl,
|
|
180
|
+
rawHost: new URL(rawUrl).hostname
|
|
181
|
+
};
|
|
182
|
+
const [, scheme, authority, rest] = match;
|
|
183
|
+
if (authority.startsWith("did:abt:")) return {
|
|
184
|
+
normalizedUrl: `${scheme}${authority.slice(8)}${rest}`,
|
|
185
|
+
rawHost: authority
|
|
186
|
+
};
|
|
187
|
+
return {
|
|
188
|
+
normalizedUrl: rawUrl,
|
|
189
|
+
rawHost: new URL(rawUrl).hostname
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Create a Multi-VLAN aware `fetch` function that routes requests by virtual IP (`http://10.x.y.z/...`)
|
|
194
|
+
* or explicit mesh URL (`http://<peerDid>.<meshId>.arc/...`) across a `MultiMeshRouter`.
|
|
195
|
+
*/
|
|
196
|
+
function createMultiMeshFetch(router, getBridgeForChannel) {
|
|
197
|
+
return async (input, init) => {
|
|
198
|
+
const { normalizedUrl, rawHost } = normalizeNoiseUrl(input instanceof Request ? input.url : input.toString());
|
|
199
|
+
if (rawHost.endsWith(".arc")) {
|
|
200
|
+
const parts = rawHost.slice(0, -4).split(".");
|
|
201
|
+
if (parts.length >= 2) {
|
|
202
|
+
const meshId = parts[parts.length - 1];
|
|
203
|
+
const peerId = parts.slice(0, -1).join(".");
|
|
204
|
+
const channel = router.getChannel(meshId, peerId);
|
|
205
|
+
if (!channel) throw new Error(`No active channel for peer "${peerId}" in virtual mesh "${meshId}"`);
|
|
206
|
+
const targetInput = input instanceof Request ? new Request(normalizedUrl, input) : normalizedUrl;
|
|
207
|
+
return getBridgeForChannel(channel, meshId).fetch(targetInput, init);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const resolved = router.resolveChannelByVirtualIp(rawHost);
|
|
211
|
+
if (resolved) return getBridgeForChannel(resolved.channel, resolved.meshId).fetch(input, init);
|
|
212
|
+
throw new Error(`Unable to route host "${rawHost}" in any mounted virtual mesh`);
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
//#endregion
|
|
217
|
+
exports.NoiseHttpBridge = NoiseHttpBridge;
|
|
218
|
+
exports.createMultiMeshFetch = createMultiMeshFetch;
|
|
219
|
+
exports.createNoiseFetch = createNoiseFetch;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { NoiseHandshakeClaims } from "./noise-session.cjs";
|
|
2
|
+
import { EncryptedChannel, MultiMeshRouter } from "./mesh-tunnel.cjs";
|
|
3
|
+
|
|
4
|
+
//#region src/http-transport.d.ts
|
|
5
|
+
|
|
6
|
+
interface NoiseHttpRequestEnvelope {
|
|
7
|
+
kind: 'noise-http-req';
|
|
8
|
+
id: string;
|
|
9
|
+
method: string;
|
|
10
|
+
url: string;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
bodyBase64?: string;
|
|
13
|
+
}
|
|
14
|
+
interface NoiseHttpResponseEnvelope {
|
|
15
|
+
kind: 'noise-http-res';
|
|
16
|
+
id: string;
|
|
17
|
+
status: number;
|
|
18
|
+
statusText: string;
|
|
19
|
+
headers: Record<string, string>;
|
|
20
|
+
bodyBase64?: string;
|
|
21
|
+
error?: string;
|
|
22
|
+
}
|
|
23
|
+
interface NoisePeerContext {
|
|
24
|
+
remoteDid: string;
|
|
25
|
+
remotePubkeyHex: string;
|
|
26
|
+
meshId?: string;
|
|
27
|
+
claims: NoiseHandshakeClaims | null;
|
|
28
|
+
}
|
|
29
|
+
type NoiseHttpHandler = (request: Request, context: NoisePeerContext) => Promise<Response> | Response;
|
|
30
|
+
interface NoiseHttpBridgeOptions {
|
|
31
|
+
/** Default request timeout in milliseconds (default: 15_000) */
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/** Optional server-side HTTP handler for incoming requests on this channel */
|
|
34
|
+
handler?: NoiseHttpHandler;
|
|
35
|
+
/** Callback to transmit encrypted bytes to the remote peer */
|
|
36
|
+
sendEncrypted: (ciphertext: Uint8Array) => void | Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Multiplexes standard Web `Request` / `Response` pairs over a single `EncryptedChannel`.
|
|
40
|
+
*/
|
|
41
|
+
declare class NoiseHttpBridge {
|
|
42
|
+
private readonly channel;
|
|
43
|
+
private readonly sendEncrypted;
|
|
44
|
+
private readonly timeoutMs;
|
|
45
|
+
private handler?;
|
|
46
|
+
private readonly pending;
|
|
47
|
+
private readonly unsubMessage;
|
|
48
|
+
constructor(channel: EncryptedChannel, options: NoiseHttpBridgeOptions);
|
|
49
|
+
setHandler(handler: NoiseHttpHandler): void;
|
|
50
|
+
/**
|
|
51
|
+
* Feed an incoming encrypted frame from the network into the bridge.
|
|
52
|
+
*/
|
|
53
|
+
receiveEncrypted(ciphertext: Uint8Array): void;
|
|
54
|
+
/**
|
|
55
|
+
* Standard Web `fetch` implementation bound to this encrypted channel.
|
|
56
|
+
*/
|
|
57
|
+
fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
58
|
+
private onDecryptedMessage;
|
|
59
|
+
close(): void;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Convenience helper to create a standard `(input, init) => Promise<Response>` fetch function
|
|
63
|
+
* bound to a `NoiseHttpBridge`.
|
|
64
|
+
*/
|
|
65
|
+
declare function createNoiseFetch(bridge: NoiseHttpBridge): (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
66
|
+
/**
|
|
67
|
+
* Create a Multi-VLAN aware `fetch` function that routes requests by virtual IP (`http://10.x.y.z/...`)
|
|
68
|
+
* or explicit mesh URL (`http://<peerDid>.<meshId>.arc/...`) across a `MultiMeshRouter`.
|
|
69
|
+
*/
|
|
70
|
+
declare function createMultiMeshFetch(router: MultiMeshRouter, getBridgeForChannel: (channel: EncryptedChannel, meshId: string) => NoiseHttpBridge): (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
71
|
+
//#endregion
|
|
72
|
+
export { NoiseHttpBridge, NoiseHttpBridgeOptions, NoiseHttpHandler, NoiseHttpRequestEnvelope, NoiseHttpResponseEnvelope, NoisePeerContext, createMultiMeshFetch, createNoiseFetch };
|
package/lib/index.cjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const require_chacha20poly1305 = require('./chacha20poly1305.cjs');
|
|
2
|
+
const require_http_transport = require('./http-transport.cjs');
|
|
3
|
+
const require_noise_session = require('./noise-session.cjs');
|
|
4
|
+
const require_mesh_tunnel = require('./mesh-tunnel.cjs');
|
|
5
|
+
const require_chain_node_mesh = require('./chain-node-mesh.cjs');
|
|
6
|
+
|
|
7
|
+
exports.ChainNodeDarknet = require_chain_node_mesh.ChainNodeDarknet;
|
|
8
|
+
exports.EncryptedChannel = require_mesh_tunnel.EncryptedChannel;
|
|
9
|
+
exports.KEY_SIZE = require_noise_session.KEY_SIZE;
|
|
10
|
+
exports.MeshTunnel = require_mesh_tunnel.MeshTunnel;
|
|
11
|
+
exports.MultiMeshRouter = require_mesh_tunnel.MultiMeshRouter;
|
|
12
|
+
exports.NONCE_SIZE = require_noise_session.NONCE_SIZE;
|
|
13
|
+
exports.NoiseHttpBridge = require_http_transport.NoiseHttpBridge;
|
|
14
|
+
exports.NoiseReplayError = require_noise_session.NoiseReplayError;
|
|
15
|
+
exports.NoiseSession = require_noise_session.NoiseSession;
|
|
16
|
+
exports.NoiseStealthDropError = require_noise_session.NoiseStealthDropError;
|
|
17
|
+
exports.ReplayWindow = require_noise_session.ReplayWindow;
|
|
18
|
+
exports.TAG_SIZE = require_noise_session.TAG_SIZE;
|
|
19
|
+
exports.canonicalizeCommitment = require_chain_node_mesh.canonicalizeCommitment;
|
|
20
|
+
exports.chacha20poly1305 = require_chacha20poly1305.chacha20poly1305;
|
|
21
|
+
exports.computeMeshAddress = require_mesh_tunnel.computeMeshAddress;
|
|
22
|
+
exports.createMultiMeshFetch = require_http_transport.createMultiMeshFetch;
|
|
23
|
+
exports.createNoiseFetch = require_http_transport.createNoiseFetch;
|
|
24
|
+
exports.createNoiseIdentity = require_noise_session.createNoiseIdentity;
|
|
25
|
+
exports.deriveMeshSubnet = require_mesh_tunnel.deriveMeshSubnet;
|
|
26
|
+
exports.didFromPublicKey = require_noise_session.didFromPublicKey;
|
|
27
|
+
exports.edToX25519Priv = require_noise_session.edToX25519Priv;
|
|
28
|
+
exports.edToX25519Pub = require_noise_session.edToX25519Pub;
|
|
29
|
+
exports.fromHex = require_noise_session.fromHex;
|
|
30
|
+
exports.toHex = require_noise_session.toHex;
|
|
31
|
+
exports.verifyWitnessAttestation = require_chain_node_mesh.verifyWitnessAttestation;
|
package/lib/index.d.cts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { ChaCha20Poly1305Cipher, chacha20poly1305 } from "./chacha20poly1305.cjs";
|
|
2
|
+
import { KEY_SIZE, NONCE_SIZE, NoiseAdmissionPolicy, NoiseHandshakeClaims, NoiseIdentity, NoiseInitiatorOptions, NoiseReplayError, NoiseResponderOptions, NoiseSession, NoiseStealthDropError, ReplayWindow, TAG_SIZE, createNoiseIdentity, didFromPublicKey, edToX25519Priv, edToX25519Pub, fromHex, toHex } from "./noise-session.cjs";
|
|
3
|
+
import { EncryptedChannel, MeshTunnel, MultiMeshRouter, VirtualMeshConfig, VirtualMeshNetworkInfo, computeMeshAddress, deriveMeshSubnet } from "./mesh-tunnel.cjs";
|
|
4
|
+
import { NoiseHttpBridge, NoiseHttpBridgeOptions, NoiseHttpHandler, NoiseHttpRequestEnvelope, NoiseHttpResponseEnvelope, NoisePeerContext, createMultiMeshFetch, createNoiseFetch } from "./http-transport.cjs";
|
|
5
|
+
import { ChainCommitmentPayload, ChainNodeDarknet, ChainNodeDarknetOptions, ChainNodeRole, ChainReplicaSyncAck, ChainWitnessAttestation, canonicalizeCommitment, verifyWitnessAttestation } from "./chain-node-mesh.cjs";
|
|
6
|
+
export { type ChaCha20Poly1305Cipher, type ChainCommitmentPayload, ChainNodeDarknet, type ChainNodeDarknetOptions, type ChainNodeRole, type ChainReplicaSyncAck, type ChainWitnessAttestation, EncryptedChannel, KEY_SIZE, MeshTunnel, MultiMeshRouter, NONCE_SIZE, type NoiseAdmissionPolicy, type NoiseHandshakeClaims, NoiseHttpBridge, type NoiseHttpBridgeOptions, type NoiseHttpHandler, type NoiseHttpRequestEnvelope, type NoiseHttpResponseEnvelope, type NoiseIdentity, type NoiseInitiatorOptions, type NoisePeerContext, NoiseReplayError, type NoiseResponderOptions, NoiseSession, NoiseStealthDropError, ReplayWindow, TAG_SIZE, type VirtualMeshConfig, type VirtualMeshNetworkInfo, canonicalizeCommitment, chacha20poly1305, computeMeshAddress, createMultiMeshFetch, createNoiseFetch, createNoiseIdentity, deriveMeshSubnet, didFromPublicKey, edToX25519Priv, edToX25519Pub, fromHex, toHex, verifyWitnessAttestation };
|