@activeledger/activep2p 0.0.0-stage → 5.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 +20 -0
- package/README.md +38 -2
- package/es/client.d.ts +15 -0
- package/es/client.d.ts.map +1 -0
- package/es/client.js +20 -0
- package/es/client.js.map +1 -0
- package/es/connection.d.ts +31 -0
- package/es/connection.d.ts.map +1 -0
- package/es/connection.js +152 -0
- package/es/connection.js.map +1 -0
- package/es/frame.d.ts +22 -0
- package/es/frame.d.ts.map +1 -0
- package/es/frame.js +93 -0
- package/es/frame.js.map +1 -0
- package/es/handshake.d.ts +25 -0
- package/es/handshake.d.ts.map +1 -0
- package/es/handshake.js +174 -0
- package/es/handshake.js.map +1 -0
- package/es/index.d.ts +6 -0
- package/es/index.d.ts.map +1 -0
- package/es/index.js +5 -0
- package/es/index.js.map +1 -0
- package/es/server.d.ts +30 -0
- package/es/server.d.ts.map +1 -0
- package/es/server.js +102 -0
- package/es/server.js.map +1 -0
- package/lib/client.d.ts +15 -0
- package/lib/client.d.ts.map +1 -0
- package/lib/client.js +57 -0
- package/lib/client.js.map +1 -0
- package/lib/connection.d.ts +31 -0
- package/lib/connection.d.ts.map +1 -0
- package/lib/connection.js +156 -0
- package/lib/connection.js.map +1 -0
- package/lib/frame.d.ts +22 -0
- package/lib/frame.d.ts.map +1 -0
- package/lib/frame.js +135 -0
- package/lib/frame.js.map +1 -0
- package/lib/handshake.d.ts +25 -0
- package/lib/handshake.d.ts.map +1 -0
- package/lib/handshake.js +210 -0
- package/lib/handshake.js.map +1 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +13 -0
- package/lib/index.js.map +1 -0
- package/lib/server.d.ts +30 -0
- package/lib/server.d.ts.map +1 -0
- package/lib/server.js +140 -0
- package/lib/server.js.map +1 -0
- package/package.json +53 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
MIT License (MIT)
|
|
2
|
+
Copyright (c) 2018 Activeledger
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,39 @@
|
|
|
1
|
-
|
|
1
|
+
<img src="https://raw.githubusercontent.com/activeledger/activeledger/master/docs/assets/Asset-23.png" alt="Activeledger" width="300"/>
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# Activep2p
|
|
4
|
+
|
|
5
|
+
Authenticated, encrypted peer to peer transport for Activeledger.
|
|
6
|
+
|
|
7
|
+
- Handshake: ephemeral X25519 on each side, both sides sign the transcript with
|
|
8
|
+
their long-term identity key (any `ActiveCrypto.KeyPair` type), session keys
|
|
9
|
+
derived with HKDF-SHA256.
|
|
10
|
+
- Frames: 4 byte big-endian length prefix, ChaCha20-Poly1305 with a key per
|
|
11
|
+
direction and an implicit, increasing nonce counter. A replayed, reordered,
|
|
12
|
+
tampered or oversize frame drops the connection.
|
|
13
|
+
- Messages: msgpack via `ActiveClone`, request/response with ids and timeouts,
|
|
14
|
+
and push in both directions over named channels.
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { P2PServer, P2PClient } from "@activeledger/activep2p";
|
|
18
|
+
|
|
19
|
+
const server = await P2PServer.listen({
|
|
20
|
+
port: 5262,
|
|
21
|
+
identity: { type: "secp256k1", publicKey, privateKey },
|
|
22
|
+
isKnownPeer: (key, type) => registry.has(key),
|
|
23
|
+
});
|
|
24
|
+
server.handle("umid", async (payload, connection) => lookup(payload));
|
|
25
|
+
|
|
26
|
+
const peer = await P2PClient.connect({
|
|
27
|
+
host: "127.0.0.1",
|
|
28
|
+
port: 5262,
|
|
29
|
+
identity,
|
|
30
|
+
expectedPeerKey: supernodeKey,
|
|
31
|
+
});
|
|
32
|
+
const answer = await peer.request("umid", { umid }, 5000);
|
|
33
|
+
peer.push("feed", item);
|
|
34
|
+
peer.close();
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Which keys are acceptable is the caller's decision (`isKnownPeer`), as is any
|
|
38
|
+
rate limiting or banning; a connection exposes `peerKey`, `drop(reason)` and
|
|
39
|
+
`close`/`error` events for that.
|
package/es/client.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { P2PIdentity, KnownPeerCheck } from "./handshake";
|
|
2
|
+
import { P2PConnection } from "./connection";
|
|
3
|
+
export interface P2PClientOptions {
|
|
4
|
+
host: string;
|
|
5
|
+
port: number;
|
|
6
|
+
identity: P2PIdentity;
|
|
7
|
+
expectedPeerKey?: string;
|
|
8
|
+
isKnownPeer?: KnownPeerCheck;
|
|
9
|
+
maxFrameBytes?: number;
|
|
10
|
+
handshakeTimeoutMs?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare class P2PClient {
|
|
13
|
+
static connect(options: P2PClientOptions): Promise<P2PConnection>;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAa,WAAW,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,WAAW,CAAC;IAEtB,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB,WAAW,CAAC,EAAE,cAAc,CAAC;IAE7B,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAQD,qBAAa,SAAS;IASpB,OAAoB,OAAO,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,aAAa,CAAC,CAmB7E;CACF"}
|
package/es/client.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import * as net from "net";
|
|
2
|
+
import { DEFAULT_MAX_FRAME_BYTES } from "./frame";
|
|
3
|
+
import { handshake } from "./handshake";
|
|
4
|
+
import { P2PConnection } from "./connection";
|
|
5
|
+
export class P2PClient {
|
|
6
|
+
static async connect(options) {
|
|
7
|
+
if (!options.expectedPeerKey && !options.isKnownPeer) {
|
|
8
|
+
throw new Error("P2PClient.connect needs expectedPeerKey or isKnownPeer to authenticate the server");
|
|
9
|
+
}
|
|
10
|
+
const socket = net.connect({ host: options.host, port: options.port });
|
|
11
|
+
const session = await handshake(socket, "client", {
|
|
12
|
+
identity: options.identity,
|
|
13
|
+
expectedPeerKey: options.expectedPeerKey,
|
|
14
|
+
isKnownPeer: options.isKnownPeer,
|
|
15
|
+
timeoutMs: options.handshakeTimeoutMs ?? 5000,
|
|
16
|
+
});
|
|
17
|
+
return new P2PConnection(socket, session, options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=client.js.map
|
package/es/client.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,SAAS,EAA+B,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAsB7C,MAAM,OAAO,SAAS;IASb,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,OAAyB;QAEnD,IAAI,CAAC,OAAO,CAAC,eAAe,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;YACrD,MAAM,IAAI,KAAK,CACb,mFAAmF,CACpF,CAAC;QACJ,CAAC;QACD,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;QACvE,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,MAAM,EAAE,QAAQ,EAAE;YAChD,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,eAAe,EAAE,OAAO,CAAC,eAAe;YACxC,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,SAAS,EAAE,OAAO,CAAC,kBAAkB,IAAI,IAAI;SAC9C,CAAC,CAAC;QACH,OAAO,IAAI,aAAa,CACtB,MAAM,EACN,OAAO,EACP,OAAO,CAAC,aAAa,IAAI,uBAAuB,CACjD,CAAC;IACJ,CAAC;CACF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import { Socket } from "net";
|
|
3
|
+
import { Session } from "./handshake";
|
|
4
|
+
export type ChannelHandler = (payload: any, connection: P2PConnection) => any;
|
|
5
|
+
export declare class P2PConnection extends EventEmitter {
|
|
6
|
+
private socket;
|
|
7
|
+
private session;
|
|
8
|
+
private maxFrameBytes;
|
|
9
|
+
private fallbackHandlers?;
|
|
10
|
+
readonly peerKey: string;
|
|
11
|
+
readonly peerKeyType: string;
|
|
12
|
+
closeReason?: string;
|
|
13
|
+
closed: boolean;
|
|
14
|
+
private handlers;
|
|
15
|
+
private pending;
|
|
16
|
+
private nextId;
|
|
17
|
+
private sendCounter;
|
|
18
|
+
private receiveCounter;
|
|
19
|
+
constructor(socket: Socket, session: Session, maxFrameBytes: number, fallbackHandlers?: Map<string, ChannelHandler> | undefined);
|
|
20
|
+
handle(channel: string, handler: ChannelHandler): this;
|
|
21
|
+
request<T = any>(channel: string, payload: any, timeoutMs?: number): Promise<T>;
|
|
22
|
+
push(channel: string, payload: any): Promise<void>;
|
|
23
|
+
close(): void;
|
|
24
|
+
drop(reason: string): void;
|
|
25
|
+
private send;
|
|
26
|
+
private receive;
|
|
27
|
+
private dispatch;
|
|
28
|
+
private raise;
|
|
29
|
+
private closedDown;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=connection.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAE7B,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAMtC,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,aAAa,KAAK,GAAG,CAAC;AAwB9E,qBAAa,aAAc,SAAQ,YAAY;IAyB3C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,gBAAgB,CAAC;IAxB3B,SAAgB,OAAO,EAAE,MAAM,CAAC;IAKhC,SAAgB,WAAW,EAAE,MAAM,CAAC;IAK7B,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,MAAM,UAAS;IAEtB,OAAO,CAAC,QAAQ,CAAqC;IACrD,OAAO,CAAC,OAAO,CAA8B;IAC7C,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,cAAc,CAAS;IAE/B,YACU,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,EAChB,aAAa,EAAE,MAAM,EACrB,gBAAgB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,YAAA,EAoBvD;IASM,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CAG5D;IAWY,OAAO,CAAC,CAAC,GAAG,GAAG,EAC1B,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,GAAG,EACZ,SAAS,GAAE,MAAc,GACxB,OAAO,CAAC,CAAC,CAAC,CAiBZ;IASY,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAE9D;IAKM,KAAK,IAAI,IAAI,CAInB;IAQM,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAKhC;IAED,OAAO,CAAC,IAAI;IASZ,OAAO,CAAC,OAAO;IAUf,OAAO,CAAC,QAAQ;IAsChB,OAAO,CAAC,KAAK;IAIb,OAAO,CAAC,UAAU;CAWnB"}
|
package/es/connection.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import { writeFrame, encode, decode, seal, open, TAG_BYTES } from "./frame";
|
|
3
|
+
const REQUEST = 0;
|
|
4
|
+
const RESPONSE = 1;
|
|
5
|
+
const PUSH = 2;
|
|
6
|
+
export class P2PConnection extends EventEmitter {
|
|
7
|
+
socket;
|
|
8
|
+
session;
|
|
9
|
+
maxFrameBytes;
|
|
10
|
+
fallbackHandlers;
|
|
11
|
+
peerKey;
|
|
12
|
+
peerKeyType;
|
|
13
|
+
closeReason;
|
|
14
|
+
closed = false;
|
|
15
|
+
handlers = new Map();
|
|
16
|
+
pending = new Map();
|
|
17
|
+
nextId = 1;
|
|
18
|
+
sendCounter;
|
|
19
|
+
receiveCounter;
|
|
20
|
+
constructor(socket, session, maxFrameBytes, fallbackHandlers) {
|
|
21
|
+
super();
|
|
22
|
+
this.socket = socket;
|
|
23
|
+
this.session = session;
|
|
24
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
25
|
+
this.fallbackHandlers = fallbackHandlers;
|
|
26
|
+
this.peerKey = session.peerKey;
|
|
27
|
+
this.peerKeyType = session.peerKeyType;
|
|
28
|
+
this.sendCounter = session.sendCounter;
|
|
29
|
+
this.receiveCounter = session.receiveCounter;
|
|
30
|
+
socket.on("close", () => this.closedDown());
|
|
31
|
+
socket.on("error", (error) => {
|
|
32
|
+
this.closeReason ??= error.message;
|
|
33
|
+
this.raise(error);
|
|
34
|
+
});
|
|
35
|
+
const { reader } = session;
|
|
36
|
+
reader.maxFrameBytes = maxFrameBytes;
|
|
37
|
+
reader.onFrame = (frame) => this.receive(frame);
|
|
38
|
+
reader.onError = (reason) => this.drop(reason);
|
|
39
|
+
reader.resume();
|
|
40
|
+
socket.resume();
|
|
41
|
+
}
|
|
42
|
+
handle(channel, handler) {
|
|
43
|
+
this.handlers.set(channel, handler);
|
|
44
|
+
return this;
|
|
45
|
+
}
|
|
46
|
+
async request(channel, payload, timeoutMs = 30000) {
|
|
47
|
+
const id = this.nextId++;
|
|
48
|
+
const body = await encode({ t: REQUEST, c: channel, i: id, d: payload });
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const timer = setTimeout(() => {
|
|
51
|
+
this.pending.delete(id);
|
|
52
|
+
reject(new Error(`request ${id} on ${channel} timed out`));
|
|
53
|
+
}, timeoutMs);
|
|
54
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
55
|
+
try {
|
|
56
|
+
this.send(body);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
this.pending.delete(id);
|
|
61
|
+
reject(error);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
async push(channel, payload) {
|
|
66
|
+
this.send(await encode({ t: PUSH, c: channel, d: payload }));
|
|
67
|
+
}
|
|
68
|
+
close() {
|
|
69
|
+
if (this.closed)
|
|
70
|
+
return;
|
|
71
|
+
this.closeReason ??= "closed";
|
|
72
|
+
this.socket.destroySoon();
|
|
73
|
+
}
|
|
74
|
+
drop(reason) {
|
|
75
|
+
if (this.closed)
|
|
76
|
+
return;
|
|
77
|
+
this.closeReason ??= reason;
|
|
78
|
+
this.session.reader.pause();
|
|
79
|
+
this.socket.destroy();
|
|
80
|
+
}
|
|
81
|
+
send(plaintext) {
|
|
82
|
+
if (this.closed)
|
|
83
|
+
throw new Error("connection is closed");
|
|
84
|
+
const size = plaintext.length + TAG_BYTES;
|
|
85
|
+
if (size > this.maxFrameBytes) {
|
|
86
|
+
throw new Error(`frame of ${size} bytes exceeds ${this.maxFrameBytes}`);
|
|
87
|
+
}
|
|
88
|
+
writeFrame(this.socket, seal(this.session.sendKey, this.sendCounter++, plaintext));
|
|
89
|
+
}
|
|
90
|
+
receive(frame) {
|
|
91
|
+
const plaintext = open(this.session.receiveKey, this.receiveCounter, frame);
|
|
92
|
+
if (!plaintext)
|
|
93
|
+
return this.drop("invalid frame");
|
|
94
|
+
this.receiveCounter++;
|
|
95
|
+
decode(plaintext).then((message) => this.dispatch(message), () => this.drop("invalid message"));
|
|
96
|
+
}
|
|
97
|
+
dispatch(message) {
|
|
98
|
+
if (this.closed)
|
|
99
|
+
return;
|
|
100
|
+
const { t, c, i, d, e } = message;
|
|
101
|
+
if (t === RESPONSE && typeof i === "number") {
|
|
102
|
+
const pending = this.pending.get(i);
|
|
103
|
+
if (!pending)
|
|
104
|
+
return;
|
|
105
|
+
this.pending.delete(i);
|
|
106
|
+
clearTimeout(pending.timer);
|
|
107
|
+
return typeof e === "string" ? pending.reject(new Error(e)) : pending.resolve(d);
|
|
108
|
+
}
|
|
109
|
+
if (typeof c !== "string")
|
|
110
|
+
return this.drop("invalid message");
|
|
111
|
+
const handler = this.handlers.get(c) ?? this.fallbackHandlers?.get(c);
|
|
112
|
+
if (t === PUSH) {
|
|
113
|
+
if (handler) {
|
|
114
|
+
Promise.resolve()
|
|
115
|
+
.then(() => handler(d, this))
|
|
116
|
+
.catch((error) => this.raise(error));
|
|
117
|
+
}
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (t === REQUEST && typeof i === "number") {
|
|
121
|
+
Promise.resolve()
|
|
122
|
+
.then(() => {
|
|
123
|
+
if (!handler)
|
|
124
|
+
throw new Error(`no handler for channel ${c}`);
|
|
125
|
+
return handler(d, this);
|
|
126
|
+
})
|
|
127
|
+
.then((result) => ({ t: RESPONSE, i, d: result }), (error) => ({ t: RESPONSE, i, e: error?.message ?? String(error) }))
|
|
128
|
+
.then(encode)
|
|
129
|
+
.then((body) => !this.closed && this.send(body))
|
|
130
|
+
.catch((error) => this.raise(error));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
this.drop("invalid message");
|
|
134
|
+
}
|
|
135
|
+
raise(error) {
|
|
136
|
+
if (this.listenerCount("error"))
|
|
137
|
+
this.emit("error", error);
|
|
138
|
+
}
|
|
139
|
+
closedDown() {
|
|
140
|
+
if (this.closed)
|
|
141
|
+
return;
|
|
142
|
+
this.closed = true;
|
|
143
|
+
this.session.reader.pause();
|
|
144
|
+
for (const pending of this.pending.values()) {
|
|
145
|
+
clearTimeout(pending.timer);
|
|
146
|
+
pending.reject(new Error(`connection closed: ${this.closeReason ?? "remote"}`));
|
|
147
|
+
}
|
|
148
|
+
this.pending.clear();
|
|
149
|
+
this.emit("close", this.closeReason);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.js","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAS5E,MAAM,OAAO,GAAG,CAAC,CAAC;AAClB,MAAM,QAAQ,GAAG,CAAC,CAAC;AACnB,MAAM,IAAI,GAAG,CAAC,CAAC;AAoBf,MAAM,OAAO,aAAc,SAAQ,YAAY;IAyBnC,MAAM;IACN,OAAO;IACP,aAAa;IACb,gBAAgB;IAxBV,OAAO,CAAS;IAKhB,WAAW,CAAS;IAK7B,WAAW,CAAU;IAErB,MAAM,GAAG,KAAK,CAAC;IAEd,QAAQ,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC7C,OAAO,GAAG,IAAI,GAAG,EAAmB,CAAC;IACrC,MAAM,GAAG,CAAC,CAAC;IACX,WAAW,CAAS;IACpB,cAAc,CAAS;IAE/B,YACU,MAAc,EACd,OAAgB,EAChB,aAAqB,EACrB,gBAA8C;QAEtD,KAAK,EAAE,CAAC;sBALA,MAAM;uBACN,OAAO;6BACP,aAAa;gCACb,gBAAgB;QAGxB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;QAE7C,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,E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net";
|
|
2
|
+
export declare const DEFAULT_MAX_FRAME_BYTES: number;
|
|
3
|
+
export declare const TAG_BYTES = 16;
|
|
4
|
+
export declare class FrameReader {
|
|
5
|
+
maxFrameBytes: number;
|
|
6
|
+
onFrame: (frame: Buffer) => void;
|
|
7
|
+
onError: (reason: string) => void;
|
|
8
|
+
private chunks;
|
|
9
|
+
private buffered;
|
|
10
|
+
private paused;
|
|
11
|
+
constructor(maxFrameBytes: number, onFrame: (frame: Buffer) => void, onError: (reason: string) => void);
|
|
12
|
+
push(chunk: Buffer): void;
|
|
13
|
+
pause(): void;
|
|
14
|
+
resume(): void;
|
|
15
|
+
private drain;
|
|
16
|
+
}
|
|
17
|
+
export declare function writeFrame(socket: Socket, body: Buffer): void;
|
|
18
|
+
export declare function seal(key: Buffer, counter: bigint, plaintext: Buffer): Buffer;
|
|
19
|
+
export declare function open(key: Buffer, counter: bigint, body: Buffer): Buffer | null;
|
|
20
|
+
export declare function encode(message: any): Promise<Buffer>;
|
|
21
|
+
export declare function decode(buffer: Buffer): Promise<any>;
|
|
22
|
+
//# sourceMappingURL=frame.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"frame.d.ts","sourceRoot":"","sources":["../src/frame.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAM7B,eAAO,MAAM,uBAAuB,QAAkB,CAAC;AAKvD,eAAO,MAAM,SAAS,KAAK,CAAC;AAa5B,qBAAa,WAAW;IAMb,aAAa,EAAE,MAAM;IACrB,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI;IAChC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI;IAP1C,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,MAAM,CAAS;IAEvB,YACS,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EAChC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,EACtC;IAEG,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAI/B;IAEM,KAAK,IAAI,IAAI,CAEnB;IAEM,MAAM,IAAI,IAAI,CAGpB;IAED,OAAO,CAAC,KAAK;CAiBd;AASD,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAI7D;AAaD,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAK5E;AAMD,wBAAgB,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAc9E;AAMD,wBAAgB,MAAM,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAEpD;AAOD,wBAAsB,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CASzD"}
|
package/es/frame.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import * as crypto from "crypto";
|
|
2
|
+
import { ActiveClone, ActiveFrame } from "@activeledger/activeutilities";
|
|
3
|
+
export const DEFAULT_MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
4
|
+
export const TAG_BYTES = 16;
|
|
5
|
+
export class FrameReader {
|
|
6
|
+
maxFrameBytes;
|
|
7
|
+
onFrame;
|
|
8
|
+
onError;
|
|
9
|
+
chunks = [];
|
|
10
|
+
buffered = 0;
|
|
11
|
+
paused = false;
|
|
12
|
+
constructor(maxFrameBytes, onFrame, onError) {
|
|
13
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
14
|
+
this.onFrame = onFrame;
|
|
15
|
+
this.onError = onError;
|
|
16
|
+
}
|
|
17
|
+
push(chunk) {
|
|
18
|
+
this.chunks.push(chunk);
|
|
19
|
+
this.buffered += chunk.length;
|
|
20
|
+
this.drain();
|
|
21
|
+
}
|
|
22
|
+
pause() {
|
|
23
|
+
this.paused = true;
|
|
24
|
+
}
|
|
25
|
+
resume() {
|
|
26
|
+
this.paused = false;
|
|
27
|
+
this.drain();
|
|
28
|
+
}
|
|
29
|
+
drain() {
|
|
30
|
+
while (!this.paused && this.buffered >= 4) {
|
|
31
|
+
const head = this.chunks[0].length >= 4 ? this.chunks[0] : Buffer.concat(this.chunks);
|
|
32
|
+
const length = head.readUInt32BE(0);
|
|
33
|
+
if (length > this.maxFrameBytes) {
|
|
34
|
+
this.paused = true;
|
|
35
|
+
this.onError(`frame of ${length} bytes exceeds ${this.maxFrameBytes}`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const frame = ActiveFrame.read(this.chunks, this.buffered);
|
|
39
|
+
if (!frame)
|
|
40
|
+
return;
|
|
41
|
+
this.chunks = frame.remaining.length ? [frame.remaining] : [];
|
|
42
|
+
this.buffered = frame.remaining.length;
|
|
43
|
+
this.onFrame(frame.item);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function writeFrame(socket, body) {
|
|
48
|
+
const header = Buffer.allocUnsafe(4);
|
|
49
|
+
header.writeUInt32BE(body.length, 0);
|
|
50
|
+
socket.write(Buffer.concat([header, body]));
|
|
51
|
+
}
|
|
52
|
+
function nonce(counter) {
|
|
53
|
+
const iv = Buffer.alloc(12);
|
|
54
|
+
iv.writeBigUInt64BE(counter, 4);
|
|
55
|
+
return iv;
|
|
56
|
+
}
|
|
57
|
+
export function seal(key, counter, plaintext) {
|
|
58
|
+
const cipher = crypto.createCipheriv("chacha20-poly1305", key, nonce(counter), {
|
|
59
|
+
authTagLength: TAG_BYTES,
|
|
60
|
+
});
|
|
61
|
+
return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
|
|
62
|
+
}
|
|
63
|
+
export function open(key, counter, body) {
|
|
64
|
+
if (body.length < TAG_BYTES)
|
|
65
|
+
return null;
|
|
66
|
+
try {
|
|
67
|
+
const decipher = crypto.createDecipheriv("chacha20-poly1305", key, nonce(counter), {
|
|
68
|
+
authTagLength: TAG_BYTES,
|
|
69
|
+
});
|
|
70
|
+
decipher.setAuthTag(body.subarray(body.length - TAG_BYTES));
|
|
71
|
+
return Buffer.concat([
|
|
72
|
+
decipher.update(body.subarray(0, body.length - TAG_BYTES)),
|
|
73
|
+
decipher.final(),
|
|
74
|
+
]);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export function encode(message) {
|
|
81
|
+
return ActiveClone.serialize(message, { enableCompression: false });
|
|
82
|
+
}
|
|
83
|
+
export async function decode(buffer) {
|
|
84
|
+
if (buffer.length < 2 || buffer[0] !== 0x00) {
|
|
85
|
+
throw new Error("unsupported message encoding");
|
|
86
|
+
}
|
|
87
|
+
const message = await ActiveClone.deserialize(buffer);
|
|
88
|
+
if (!message || typeof message !== "object") {
|
|
89
|
+
throw new Error("message is not an object");
|
|
90
|
+
}
|
|
91
|
+
return message;
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=frame.js.map
|
package/es/frame.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"frame.js","sourceRoot":"","sources":["../src/frame.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAEjC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAKzE,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAKvD,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAa5B,MAAM,OAAO,WAAW;IAMb,aAAa;IACb,OAAO;IACP,OAAO;IAPR,MAAM,GAAa,EAAE,CAAC;IACtB,QAAQ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} from "net";
|
|
2
|
+
import { FrameReader } from "./frame";
|
|
3
|
+
export interface P2PIdentity {
|
|
4
|
+
type: string;
|
|
5
|
+
publicKey: string;
|
|
6
|
+
privateKey: string;
|
|
7
|
+
}
|
|
8
|
+
export type KnownPeerCheck = (publicKey: string, type: string) => boolean | Promise<boolean>;
|
|
9
|
+
export interface HandshakeOptions {
|
|
10
|
+
identity: P2PIdentity;
|
|
11
|
+
timeoutMs: number;
|
|
12
|
+
isKnownPeer?: KnownPeerCheck;
|
|
13
|
+
expectedPeerKey?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface Session {
|
|
16
|
+
reader: FrameReader;
|
|
17
|
+
peerKey: string;
|
|
18
|
+
peerKeyType: string;
|
|
19
|
+
sendKey: Buffer;
|
|
20
|
+
receiveKey: Buffer;
|
|
21
|
+
sendCounter: bigint;
|
|
22
|
+
receiveCounter: bigint;
|
|
23
|
+
}
|
|
24
|
+
export declare function handshake(socket: Socket, role: "client" | "server", options: HandshakeOptions): Promise<Session>;
|
|
25
|
+
//# sourceMappingURL=handshake.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handshake.d.ts","sourceRoot":"","sources":["../src/handshake.ts"],"names":[],"mappings":"AA4CA,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAE7B,OAAO,EAAE,WAAW,EAA0C,MAAM,SAAS,CAAC;AAiB9E,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;CACpB;AAKD,MAAM,MAAM,cAAc,GAAG,CAC3B,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,KACT,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAEhC,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,WAAW,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,cAAc,CAAC;IAC7B,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,OAAO;IACtB,MAAM,EAAE,WAAW,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;CACxB;AAoFD,wBAAgB,SAAS,CACvB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,QAAQ,GAAG,QAAQ,EACzB,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,OAAO,CAAC,CAyDlB"}
|
package/es/handshake.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import * as crypto from "crypto";
|
|
2
|
+
import { ActiveCrypto } from "@activeledger/activecrypto";
|
|
3
|
+
import { FrameReader, writeFrame, encode, decode, seal, open } from "./frame";
|
|
4
|
+
const PROTOCOL = "activep2p/1";
|
|
5
|
+
const VERSION = 1;
|
|
6
|
+
const HANDSHAKE_MAX_BYTES = 64 * 1024;
|
|
7
|
+
function transcript(...parts) {
|
|
8
|
+
const hash = crypto.createHash("sha256");
|
|
9
|
+
for (const part of parts) {
|
|
10
|
+
const bytes = Buffer.isBuffer(part) ? part : Buffer.from(part, "utf8");
|
|
11
|
+
const length = Buffer.allocUnsafe(4);
|
|
12
|
+
length.writeUInt32BE(bytes.length, 0);
|
|
13
|
+
hash.update(length).update(bytes);
|
|
14
|
+
}
|
|
15
|
+
return hash.digest();
|
|
16
|
+
}
|
|
17
|
+
function ephemeral() {
|
|
18
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync("x25519");
|
|
19
|
+
return {
|
|
20
|
+
privateKey,
|
|
21
|
+
raw: Buffer.from(publicKey.export({ format: "jwk" }).x, "base64url"),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function sharedSecret(privateKey, peer) {
|
|
25
|
+
const publicKey = crypto.createPublicKey({
|
|
26
|
+
key: { kty: "OKP", crv: "X25519", x: peer.toString("base64url") },
|
|
27
|
+
format: "jwk",
|
|
28
|
+
});
|
|
29
|
+
return crypto.diffieHellman({ privateKey, publicKey });
|
|
30
|
+
}
|
|
31
|
+
function sessionKeys(shared, th2) {
|
|
32
|
+
const derive = (info) => Buffer.from(crypto.hkdfSync("sha256", shared, th2, `${PROTOCOL} ${info}`, 32));
|
|
33
|
+
return { c2s: derive("c2s"), s2c: derive("s2c") };
|
|
34
|
+
}
|
|
35
|
+
function sign(identity, role, hash) {
|
|
36
|
+
return new ActiveCrypto.KeyPair(identity.type, identity.privateKey).sign(`${PROTOCOL} ${role} ${hash.toString("hex")}`);
|
|
37
|
+
}
|
|
38
|
+
function verify(type, key, role, hash, sig) {
|
|
39
|
+
try {
|
|
40
|
+
return new ActiveCrypto.KeyPair(type, key).verify(`${PROTOCOL} ${role} ${hash.toString("hex")}`, sig);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function bytes(value, length, name) {
|
|
47
|
+
if (!(value instanceof Uint8Array) || value.length !== length) {
|
|
48
|
+
throw new Error(`invalid ${name}`);
|
|
49
|
+
}
|
|
50
|
+
return Buffer.from(value);
|
|
51
|
+
}
|
|
52
|
+
function strings(message, ...fields) {
|
|
53
|
+
for (const field of fields) {
|
|
54
|
+
if (typeof message[field] !== "string" || !message[field]) {
|
|
55
|
+
throw new Error(`invalid handshake field ${field}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export function handshake(socket, role, options) {
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
let done = false;
|
|
62
|
+
let waiting;
|
|
63
|
+
const finish = () => {
|
|
64
|
+
done = true;
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
socket.off("close", onClose);
|
|
67
|
+
socket.off("error", onError);
|
|
68
|
+
};
|
|
69
|
+
const fail = (reason) => {
|
|
70
|
+
if (done)
|
|
71
|
+
return;
|
|
72
|
+
finish();
|
|
73
|
+
reader.pause();
|
|
74
|
+
socket.destroy();
|
|
75
|
+
reject(new Error(reason));
|
|
76
|
+
};
|
|
77
|
+
const onClose = () => fail("connection closed during handshake");
|
|
78
|
+
const onError = (error) => fail(error.message);
|
|
79
|
+
const timer = setTimeout(() => fail("handshake timed out"), options.timeoutMs);
|
|
80
|
+
const reader = new FrameReader(HANDSHAKE_MAX_BYTES, (frame) => {
|
|
81
|
+
reader.pause();
|
|
82
|
+
socket.pause();
|
|
83
|
+
const deliver = waiting;
|
|
84
|
+
waiting = undefined;
|
|
85
|
+
deliver ? deliver(frame) : fail("unexpected handshake frame");
|
|
86
|
+
}, fail);
|
|
87
|
+
const next = () => new Promise((got) => {
|
|
88
|
+
waiting = got;
|
|
89
|
+
reader.resume();
|
|
90
|
+
socket.resume();
|
|
91
|
+
});
|
|
92
|
+
const send = async (message) => writeFrame(socket, await encode(message));
|
|
93
|
+
socket.on("data", (chunk) => reader.push(chunk));
|
|
94
|
+
socket.once("close", onClose);
|
|
95
|
+
socket.on("error", onError);
|
|
96
|
+
const run = role === "client" ? client : server;
|
|
97
|
+
run(options, next, send, (body) => writeFrame(socket, body)).then((session) => {
|
|
98
|
+
if (done)
|
|
99
|
+
return;
|
|
100
|
+
finish();
|
|
101
|
+
resolve({ ...session, reader });
|
|
102
|
+
}, (error) => fail(error.message));
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
async function client(options, next, send) {
|
|
106
|
+
const { identity } = options;
|
|
107
|
+
const eph = ephemeral();
|
|
108
|
+
await send({ v: VERSION, eph: eph.raw });
|
|
109
|
+
const reply = await decode(await next());
|
|
110
|
+
if (reply.v !== VERSION)
|
|
111
|
+
throw new Error("unsupported protocol version");
|
|
112
|
+
strings(reply, "type", "key", "sig");
|
|
113
|
+
const serverEph = bytes(reply.eph, 32, "ephemeral key");
|
|
114
|
+
if (options.expectedPeerKey && reply.key !== options.expectedPeerKey) {
|
|
115
|
+
throw new Error("peer key does not match expected key");
|
|
116
|
+
}
|
|
117
|
+
const th = transcript(PROTOCOL, eph.raw, serverEph, reply.type, reply.key);
|
|
118
|
+
if (!verify(reply.type, reply.key, "server", th, reply.sig)) {
|
|
119
|
+
throw new Error("invalid peer signature");
|
|
120
|
+
}
|
|
121
|
+
if (options.isKnownPeer && !(await options.isKnownPeer(reply.key, reply.type))) {
|
|
122
|
+
throw new Error("unknown peer");
|
|
123
|
+
}
|
|
124
|
+
const th2 = transcript(th, identity.type, identity.publicKey);
|
|
125
|
+
const keys = sessionKeys(sharedSecret(eph.privateKey, serverEph), th2);
|
|
126
|
+
await send({ type: identity.type, key: identity.publicKey, sig: sign(identity, "client", th2) });
|
|
127
|
+
const ready = open(keys.s2c, 0n, await next());
|
|
128
|
+
if (!ready || ready.toString() !== PROTOCOL)
|
|
129
|
+
throw new Error("invalid ready frame");
|
|
130
|
+
return {
|
|
131
|
+
peerKey: reply.key,
|
|
132
|
+
peerKeyType: reply.type,
|
|
133
|
+
sendKey: keys.c2s,
|
|
134
|
+
receiveKey: keys.s2c,
|
|
135
|
+
sendCounter: 0n,
|
|
136
|
+
receiveCounter: 1n,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
async function server(options, next, send, raw) {
|
|
140
|
+
const { identity } = options;
|
|
141
|
+
const hello = await decode(await next());
|
|
142
|
+
if (hello.v !== VERSION)
|
|
143
|
+
throw new Error("unsupported protocol version");
|
|
144
|
+
const clientEph = bytes(hello.eph, 32, "ephemeral key");
|
|
145
|
+
const eph = ephemeral();
|
|
146
|
+
const th = transcript(PROTOCOL, clientEph, eph.raw, identity.type, identity.publicKey);
|
|
147
|
+
await send({
|
|
148
|
+
v: VERSION,
|
|
149
|
+
eph: eph.raw,
|
|
150
|
+
type: identity.type,
|
|
151
|
+
key: identity.publicKey,
|
|
152
|
+
sig: sign(identity, "server", th),
|
|
153
|
+
});
|
|
154
|
+
const auth = await decode(await next());
|
|
155
|
+
strings(auth, "type", "key", "sig");
|
|
156
|
+
const th2 = transcript(th, auth.type, auth.key);
|
|
157
|
+
if (!verify(auth.type, auth.key, "client", th2, auth.sig)) {
|
|
158
|
+
throw new Error("invalid peer signature");
|
|
159
|
+
}
|
|
160
|
+
if (options.isKnownPeer && !(await options.isKnownPeer(auth.key, auth.type))) {
|
|
161
|
+
throw new Error("unknown peer");
|
|
162
|
+
}
|
|
163
|
+
const keys = sessionKeys(sharedSecret(eph.privateKey, clientEph), th2);
|
|
164
|
+
raw(seal(keys.s2c, 0n, Buffer.from(PROTOCOL)));
|
|
165
|
+
return {
|
|
166
|
+
peerKey: auth.key,
|
|
167
|
+
peerKeyType: auth.type,
|
|
168
|
+
sendKey: keys.s2c,
|
|
169
|
+
receiveKey: keys.c2s,
|
|
170
|
+
sendCounter: 1n,
|
|
171
|
+
receiveCounter: 0n,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
//# sourceMappingURL=handshake.js.map
|