@brud/daemon 0.0.0-stage → 0.0.1
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 +201 -0
- package/README.md +67 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +88 -0
- package/dist/client/DaemonClient.d.ts +55 -0
- package/dist/client/DaemonClient.js +383 -0
- package/dist/client/connectToDaemon.d.ts +19 -0
- package/dist/client/connectToDaemon.js +131 -0
- package/dist/client/errors.d.ts +74 -0
- package/dist/client/errors.js +104 -0
- package/dist/client/identity.d.ts +3 -0
- package/dist/client/identity.js +7 -0
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.js +23 -0
- package/dist/client/socket.d.ts +9 -0
- package/dist/client/socket.js +101 -0
- package/dist/client/spawn.d.ts +7 -0
- package/dist/client/spawn.js +171 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +29 -0
- package/dist/instanceRegistry.d.ts +130 -0
- package/dist/instanceRegistry.js +332 -0
- package/dist/lifecycle/endpoint.d.ts +19 -0
- package/dist/lifecycle/endpoint.js +124 -0
- package/dist/lifecycle/idle.d.ts +28 -0
- package/dist/lifecycle/idle.js +69 -0
- package/dist/lifecycle/index.d.ts +4 -0
- package/dist/lifecycle/index.js +21 -0
- package/dist/lifecycle/lock.d.ts +28 -0
- package/dist/lifecycle/lock.js +155 -0
- package/dist/lifecycle/shutdown.d.ts +39 -0
- package/dist/lifecycle/shutdown.js +115 -0
- package/dist/operatorConfig.d.ts +36 -0
- package/dist/operatorConfig.js +92 -0
- package/dist/security/channel.d.ts +113 -0
- package/dist/security/channel.js +448 -0
- package/dist/security/noise.d.ts +64 -0
- package/dist/security/noise.js +313 -0
- package/dist/security/ownership.d.ts +36 -0
- package/dist/security/ownership.js +86 -0
- package/dist/security/peerCredentials.d.ts +104 -0
- package/dist/security/peerCredentials.js +244 -0
- package/dist/server/Connection.d.ts +70 -0
- package/dist/server/Connection.js +412 -0
- package/dist/server/DaemonServer.d.ts +77 -0
- package/dist/server/DaemonServer.js +396 -0
- package/dist/server/createDaemon.d.ts +52 -0
- package/dist/server/createDaemon.js +165 -0
- package/dist/server/dispatch.d.ts +52 -0
- package/dist/server/dispatch.js +291 -0
- package/dist/server/framing.d.ts +63 -0
- package/dist/server/framing.js +196 -0
- package/dist/server/handshake.d.ts +22 -0
- package/dist/server/handshake.js +94 -0
- package/dist/server/protocolValidation.d.ts +47 -0
- package/dist/server/protocolValidation.js +366 -0
- package/dist/server/wireErrors.d.ts +5 -0
- package/dist/server/wireErrors.js +190 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +6 -0
- package/package.json +55 -4
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NoiseHandshake = exports.NOISE_PROTOCOL_NAME = void 0;
|
|
4
|
+
exports.derivePsk = derivePsk;
|
|
5
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
|
+
/**
|
|
7
|
+
* Noise Protocol Framework revision 34, pattern NNpsk0, instantiated with
|
|
8
|
+
* X25519 / ChaCha20-Poly1305 / SHA-256.
|
|
9
|
+
*
|
|
10
|
+
* The pattern is:
|
|
11
|
+
*
|
|
12
|
+
* -> psk, e
|
|
13
|
+
* <- e, ee
|
|
14
|
+
*
|
|
15
|
+
* The pre-shared key is the daemon's 256-bit token. Both endpoints prove
|
|
16
|
+
* possession of it; the ephemeral X25519 exchange gives each session fresh
|
|
17
|
+
* key material and forward secrecy. The handshake hash is available as a
|
|
18
|
+
* channel binding after `split()`.
|
|
19
|
+
*/
|
|
20
|
+
exports.NOISE_PROTOCOL_NAME = 'Noise_NNpsk0_25519_ChaChaPoly_SHA256';
|
|
21
|
+
const HASHLEN = 32;
|
|
22
|
+
const DHLEN = 32;
|
|
23
|
+
const TAGLEN = 16;
|
|
24
|
+
const MAX_NONCE = (1n << 64n) - 1n;
|
|
25
|
+
const PROTOCOL_NAME = Buffer.from(exports.NOISE_PROTOCOL_NAME, 'ascii');
|
|
26
|
+
const X25519_SPKI_PREFIX = Buffer.from('302a300506032b656e032100', 'hex');
|
|
27
|
+
/**
|
|
28
|
+
* Derives the fixed-size Noise PSK from the on-disk token.
|
|
29
|
+
*
|
|
30
|
+
* Token files stay human-readable 256-bit hex strings; Noise requires exactly
|
|
31
|
+
* 32 key bytes, so the secret is hashed once on both ends.
|
|
32
|
+
*/
|
|
33
|
+
function derivePsk(secret) {
|
|
34
|
+
return (0, node_crypto_1.createHash)('sha256').update(secret, 'utf8').digest();
|
|
35
|
+
}
|
|
36
|
+
function hash(data) {
|
|
37
|
+
return (0, node_crypto_1.createHash)('sha256').update(data).digest();
|
|
38
|
+
}
|
|
39
|
+
function hmac(key, data) {
|
|
40
|
+
return (0, node_crypto_1.createHmac)('sha256', key).update(data).digest();
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Noise's HKDF, which is HKDF-SHA256 with the chaining key as salt and an
|
|
44
|
+
* empty info string. Outputs are always HASHLEN bytes each.
|
|
45
|
+
*/
|
|
46
|
+
function hkdf(chainingKey, inputKeyMaterial, outputs) {
|
|
47
|
+
const tempKey = hmac(chainingKey, inputKeyMaterial);
|
|
48
|
+
const output1 = hmac(tempKey, Buffer.from([0x01]));
|
|
49
|
+
const output2 = hmac(tempKey, Buffer.concat([output1, Buffer.from([0x02])]));
|
|
50
|
+
if (outputs === 2) {
|
|
51
|
+
return [output1, output2];
|
|
52
|
+
}
|
|
53
|
+
const output3 = hmac(tempKey, Buffer.concat([output2, Buffer.from([0x03])]));
|
|
54
|
+
return [output1, output2, output3];
|
|
55
|
+
}
|
|
56
|
+
function nonceBytes(nonce) {
|
|
57
|
+
const bytes = Buffer.alloc(12);
|
|
58
|
+
bytes.writeBigUInt64LE(nonce, 4);
|
|
59
|
+
return bytes;
|
|
60
|
+
}
|
|
61
|
+
function encryptAead(key, nonce, associatedData, plaintext) {
|
|
62
|
+
const cipher = (0, node_crypto_1.createCipheriv)('chacha20-poly1305', key, nonceBytes(nonce), {
|
|
63
|
+
authTagLength: TAGLEN,
|
|
64
|
+
});
|
|
65
|
+
cipher.setAAD(associatedData, { plaintextLength: plaintext.length });
|
|
66
|
+
return Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
|
|
67
|
+
}
|
|
68
|
+
function decryptAead(key, nonce, associatedData, ciphertext) {
|
|
69
|
+
if (ciphertext.length < TAGLEN) {
|
|
70
|
+
throw new Error('Noise ciphertext is shorter than the authentication tag');
|
|
71
|
+
}
|
|
72
|
+
const body = ciphertext.subarray(0, ciphertext.length - TAGLEN);
|
|
73
|
+
const tag = ciphertext.subarray(ciphertext.length - TAGLEN);
|
|
74
|
+
const decipher = (0, node_crypto_1.createDecipheriv)('chacha20-poly1305', key, nonceBytes(nonce), {
|
|
75
|
+
authTagLength: TAGLEN,
|
|
76
|
+
});
|
|
77
|
+
decipher.setAAD(associatedData, { plaintextLength: body.length });
|
|
78
|
+
decipher.setAuthTag(tag);
|
|
79
|
+
return Buffer.concat([decipher.update(body), decipher.final()]);
|
|
80
|
+
}
|
|
81
|
+
function rawPublicKey(key) {
|
|
82
|
+
return key.export({ type: 'spki', format: 'der' }).subarray(-DHLEN);
|
|
83
|
+
}
|
|
84
|
+
function publicKeyFromRaw(raw) {
|
|
85
|
+
if (raw.length !== DHLEN) {
|
|
86
|
+
throw new Error(`Expected a ${DHLEN}-byte X25519 public key`);
|
|
87
|
+
}
|
|
88
|
+
return (0, node_crypto_1.createPublicKey)({
|
|
89
|
+
key: Buffer.concat([X25519_SPKI_PREFIX, raw]),
|
|
90
|
+
format: 'der',
|
|
91
|
+
type: 'spki',
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
function diffieHellmanRaw(privateKey, remotePublic) {
|
|
95
|
+
return (0, node_crypto_1.diffieHellman)({
|
|
96
|
+
privateKey,
|
|
97
|
+
publicKey: publicKeyFromRaw(remotePublic),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function generateKeyPair() {
|
|
101
|
+
const pair = (0, node_crypto_1.generateKeyPairSync)('x25519');
|
|
102
|
+
return {
|
|
103
|
+
publicKey: rawPublicKey(pair.publicKey),
|
|
104
|
+
privateKey: pair.privateKey,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
class CipherState {
|
|
108
|
+
key;
|
|
109
|
+
counter = 0n;
|
|
110
|
+
constructor(key) {
|
|
111
|
+
this.key = key;
|
|
112
|
+
}
|
|
113
|
+
get nonce() {
|
|
114
|
+
return this.counter;
|
|
115
|
+
}
|
|
116
|
+
encrypt(ad, plaintext) {
|
|
117
|
+
if (this.key === undefined) {
|
|
118
|
+
return plaintext;
|
|
119
|
+
}
|
|
120
|
+
if (this.counter >= MAX_NONCE) {
|
|
121
|
+
throw new Error('Noise nonce exhausted');
|
|
122
|
+
}
|
|
123
|
+
const ciphertext = encryptAead(this.key, this.counter, ad, plaintext);
|
|
124
|
+
this.counter += 1n;
|
|
125
|
+
return ciphertext;
|
|
126
|
+
}
|
|
127
|
+
decrypt(ad, ciphertext) {
|
|
128
|
+
if (this.key === undefined) {
|
|
129
|
+
return ciphertext;
|
|
130
|
+
}
|
|
131
|
+
if (this.counter >= MAX_NONCE) {
|
|
132
|
+
throw new Error('Noise nonce exhausted');
|
|
133
|
+
}
|
|
134
|
+
const plaintext = decryptAead(this.key, this.counter, ad, ciphertext);
|
|
135
|
+
this.counter += 1n;
|
|
136
|
+
return plaintext;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
class SymmetricState {
|
|
140
|
+
chainingKey;
|
|
141
|
+
handshakeHash;
|
|
142
|
+
cipher = new CipherState(undefined);
|
|
143
|
+
constructor(protocolName) {
|
|
144
|
+
this.handshakeHash = protocolName.length <= HASHLEN
|
|
145
|
+
? Buffer.concat([protocolName, Buffer.alloc(HASHLEN - protocolName.length)])
|
|
146
|
+
: hash(protocolName);
|
|
147
|
+
this.chainingKey = Buffer.from(this.handshakeHash);
|
|
148
|
+
}
|
|
149
|
+
mixHash(data) {
|
|
150
|
+
this.handshakeHash = hash(Buffer.concat([this.handshakeHash, data]));
|
|
151
|
+
}
|
|
152
|
+
mixKey(inputKeyMaterial) {
|
|
153
|
+
const [chainingKey, tempKey] = hkdf(this.chainingKey, inputKeyMaterial, 2);
|
|
154
|
+
this.chainingKey = chainingKey;
|
|
155
|
+
this.cipher = new CipherState(tempKey);
|
|
156
|
+
}
|
|
157
|
+
mixKeyAndHash(inputKeyMaterial) {
|
|
158
|
+
const [chainingKey, tempHash, tempKey] = hkdf(this.chainingKey, inputKeyMaterial, 3);
|
|
159
|
+
this.chainingKey = chainingKey;
|
|
160
|
+
this.mixHash(tempHash);
|
|
161
|
+
this.cipher = new CipherState(tempKey);
|
|
162
|
+
}
|
|
163
|
+
encryptAndHash(plaintext) {
|
|
164
|
+
const ciphertext = this.cipher.encrypt(this.handshakeHash, plaintext);
|
|
165
|
+
this.mixHash(ciphertext);
|
|
166
|
+
return ciphertext;
|
|
167
|
+
}
|
|
168
|
+
decryptAndHash(ciphertext) {
|
|
169
|
+
const plaintext = this.cipher.decrypt(this.handshakeHash, ciphertext);
|
|
170
|
+
this.mixHash(ciphertext);
|
|
171
|
+
return plaintext;
|
|
172
|
+
}
|
|
173
|
+
split() {
|
|
174
|
+
const [first, second] = hkdf(this.chainingKey, Buffer.alloc(0), 2);
|
|
175
|
+
return {
|
|
176
|
+
send: new CipherState(first),
|
|
177
|
+
receive: new CipherState(second),
|
|
178
|
+
handshakeHash: Buffer.from(this.handshakeHash),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
get hash() {
|
|
182
|
+
return this.handshakeHash;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* One side of an NNpsk0 handshake.
|
|
187
|
+
*
|
|
188
|
+
* Usage is strictly alternating: the initiator writes message 1 and reads
|
|
189
|
+
* message 2; the responder reads message 1 and writes message 2. A call in the
|
|
190
|
+
* wrong order, a malformed payload, or a failed AEAD tag throws and the caller
|
|
191
|
+
* must abandon the connection.
|
|
192
|
+
*/
|
|
193
|
+
class NoiseHandshake {
|
|
194
|
+
role;
|
|
195
|
+
psk;
|
|
196
|
+
symmetric;
|
|
197
|
+
ephemeral;
|
|
198
|
+
remoteEphemeral;
|
|
199
|
+
messageIndex = 0;
|
|
200
|
+
splitResult;
|
|
201
|
+
constructor(options) {
|
|
202
|
+
if (options.psk.length !== 32) {
|
|
203
|
+
throw new Error('Noise PSK must be exactly 32 bytes');
|
|
204
|
+
}
|
|
205
|
+
this.role = options.role;
|
|
206
|
+
this.psk = Buffer.from(options.psk);
|
|
207
|
+
this.symmetric = new SymmetricState(PROTOCOL_NAME);
|
|
208
|
+
this.symmetric.mixHash(options.prologue ?? Buffer.alloc(0));
|
|
209
|
+
}
|
|
210
|
+
writeMessage(payload = Buffer.alloc(0)) {
|
|
211
|
+
const expectedRole = this.messageIndex === 0 ? 'initiator' : 'responder';
|
|
212
|
+
if (this.role !== expectedRole) {
|
|
213
|
+
throw new Error(`Noise ${this.role} cannot write handshake message ${this.messageIndex + 1}`);
|
|
214
|
+
}
|
|
215
|
+
if (this.splitResult !== undefined) {
|
|
216
|
+
throw new Error('Noise handshake is already complete');
|
|
217
|
+
}
|
|
218
|
+
if (this.messageIndex === 0) {
|
|
219
|
+
this.symmetric.mixKeyAndHash(this.psk);
|
|
220
|
+
const ephemeral = this.generateEphemeral();
|
|
221
|
+
const output = [ephemeral.publicKey];
|
|
222
|
+
this.symmetric.mixHash(ephemeral.publicKey);
|
|
223
|
+
this.symmetric.mixKey(ephemeral.publicKey);
|
|
224
|
+
output.push(this.symmetric.encryptAndHash(payload));
|
|
225
|
+
this.messageIndex = 1;
|
|
226
|
+
return Buffer.concat(output);
|
|
227
|
+
}
|
|
228
|
+
const ephemeral = this.generateEphemeral();
|
|
229
|
+
const output = [ephemeral.publicKey];
|
|
230
|
+
this.symmetric.mixHash(ephemeral.publicKey);
|
|
231
|
+
this.symmetric.mixKey(ephemeral.publicKey);
|
|
232
|
+
this.symmetric.mixKey(this.diffieHellman(ephemeral, this.requireRemoteEphemeral()));
|
|
233
|
+
output.push(this.symmetric.encryptAndHash(payload));
|
|
234
|
+
this.messageIndex = 2;
|
|
235
|
+
this.splitResult = this.symmetric.split();
|
|
236
|
+
return Buffer.concat(output);
|
|
237
|
+
}
|
|
238
|
+
readMessage(message) {
|
|
239
|
+
const expectedRole = this.messageIndex === 0 ? 'responder' : 'initiator';
|
|
240
|
+
if (this.role !== expectedRole) {
|
|
241
|
+
throw new Error(`Noise ${this.role} cannot read handshake message ${this.messageIndex + 1}`);
|
|
242
|
+
}
|
|
243
|
+
if (this.splitResult !== undefined) {
|
|
244
|
+
throw new Error('Noise handshake is already complete');
|
|
245
|
+
}
|
|
246
|
+
if (message.length < DHLEN + TAGLEN) {
|
|
247
|
+
throw new Error('Noise handshake message is too short');
|
|
248
|
+
}
|
|
249
|
+
if (this.messageIndex === 0) {
|
|
250
|
+
// The first NNpsk0 message pattern is `psk, e`; the responder processes
|
|
251
|
+
// the same tokens as the sender.
|
|
252
|
+
this.symmetric.mixKeyAndHash(this.psk);
|
|
253
|
+
}
|
|
254
|
+
const remoteEphemeral = Buffer.from(message.subarray(0, DHLEN));
|
|
255
|
+
const payload = message.subarray(DHLEN);
|
|
256
|
+
this.symmetric.mixHash(remoteEphemeral);
|
|
257
|
+
this.symmetric.mixKey(remoteEphemeral);
|
|
258
|
+
this.remoteEphemeral = remoteEphemeral;
|
|
259
|
+
if (this.messageIndex === 0) {
|
|
260
|
+
const plaintext = this.symmetric.decryptAndHash(payload);
|
|
261
|
+
this.messageIndex = 1;
|
|
262
|
+
return plaintext;
|
|
263
|
+
}
|
|
264
|
+
this.symmetric.mixKey(this.diffieHellman(this.requireEphemeral(), remoteEphemeral));
|
|
265
|
+
const plaintext = this.symmetric.decryptAndHash(payload);
|
|
266
|
+
this.messageIndex = 2;
|
|
267
|
+
this.splitResult = this.symmetric.split();
|
|
268
|
+
return plaintext;
|
|
269
|
+
}
|
|
270
|
+
split() {
|
|
271
|
+
if (this.splitResult === undefined) {
|
|
272
|
+
throw new Error('Noise handshake has not completed');
|
|
273
|
+
}
|
|
274
|
+
return this.role === 'initiator'
|
|
275
|
+
? {
|
|
276
|
+
send: this.splitResult.send,
|
|
277
|
+
receive: this.splitResult.receive,
|
|
278
|
+
handshakeHash: this.splitResult.handshakeHash,
|
|
279
|
+
}
|
|
280
|
+
: {
|
|
281
|
+
send: this.splitResult.receive,
|
|
282
|
+
receive: this.splitResult.send,
|
|
283
|
+
handshakeHash: this.splitResult.handshakeHash,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
get handshakeHash() {
|
|
287
|
+
return this.symmetric.hash;
|
|
288
|
+
}
|
|
289
|
+
generateEphemeral() {
|
|
290
|
+
if (this.ephemeral !== undefined) {
|
|
291
|
+
throw new Error('Noise ephemeral key was already generated');
|
|
292
|
+
}
|
|
293
|
+
this.ephemeral = generateKeyPair();
|
|
294
|
+
return this.ephemeral;
|
|
295
|
+
}
|
|
296
|
+
requireEphemeral() {
|
|
297
|
+
if (this.ephemeral === undefined) {
|
|
298
|
+
throw new Error('Noise ephemeral key is missing');
|
|
299
|
+
}
|
|
300
|
+
return this.ephemeral;
|
|
301
|
+
}
|
|
302
|
+
requireRemoteEphemeral() {
|
|
303
|
+
if (this.remoteEphemeral === undefined) {
|
|
304
|
+
throw new Error('Noise remote ephemeral key is missing');
|
|
305
|
+
}
|
|
306
|
+
return this.remoteEphemeral;
|
|
307
|
+
}
|
|
308
|
+
diffieHellman(local, remote) {
|
|
309
|
+
return diffieHellmanRaw(local.privateKey, remote);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
exports.NoiseHandshake = NoiseHandshake;
|
|
313
|
+
//# sourceMappingURL=noise.js.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result of verifying a local endpoint against the current process identity.
|
|
3
|
+
*
|
|
4
|
+
* `unsupported` means the platform does not expose the metadata needed to
|
|
5
|
+
* verify the endpoint from Node. It is reported, never treated as success.
|
|
6
|
+
*/
|
|
7
|
+
export type EndpointOwnership = {
|
|
8
|
+
readonly status: 'verified';
|
|
9
|
+
readonly uid: number;
|
|
10
|
+
readonly mode: number;
|
|
11
|
+
} | {
|
|
12
|
+
readonly status: 'unsupported';
|
|
13
|
+
readonly platform: NodeJS.Platform;
|
|
14
|
+
readonly reason: string;
|
|
15
|
+
};
|
|
16
|
+
export declare class EndpointOwnershipError extends Error {
|
|
17
|
+
readonly endpointPath: string;
|
|
18
|
+
constructor(endpointPath: string, message: string);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Verifies that the endpoint file is owned by this process's user and is not
|
|
22
|
+
* reachable by other users.
|
|
23
|
+
*
|
|
24
|
+
* On POSIX this is the operating-system ownership half of D-01: a socket that
|
|
25
|
+
* only the owning user can open is the strongest peer-identity control Node
|
|
26
|
+
* can enforce without a native `SO_PEERCRED` binding. Windows named pipes do
|
|
27
|
+
* not expose their security descriptor through `node:fs`, so the function
|
|
28
|
+
* reports `unsupported` instead of pretending to verify.
|
|
29
|
+
*/
|
|
30
|
+
export declare function verifyEndpointOwnership(endpointPath: string): Promise<EndpointOwnership>;
|
|
31
|
+
/**
|
|
32
|
+
* Forces the endpoint to owner-only access and verifies the result.
|
|
33
|
+
*
|
|
34
|
+
* Called by the daemon after bind, before any connection is accepted.
|
|
35
|
+
*/
|
|
36
|
+
export declare function enforceEndpointOwnership(endpointPath: string): Promise<EndpointOwnership>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EndpointOwnershipError = void 0;
|
|
4
|
+
exports.verifyEndpointOwnership = verifyEndpointOwnership;
|
|
5
|
+
exports.enforceEndpointOwnership = enforceEndpointOwnership;
|
|
6
|
+
const promises_1 = require("node:fs/promises");
|
|
7
|
+
class EndpointOwnershipError extends Error {
|
|
8
|
+
endpointPath;
|
|
9
|
+
constructor(endpointPath, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'EndpointOwnershipError';
|
|
12
|
+
this.endpointPath = endpointPath;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
exports.EndpointOwnershipError = EndpointOwnershipError;
|
|
16
|
+
function currentUid() {
|
|
17
|
+
return typeof process.getuid === 'function' ? process.getuid() : undefined;
|
|
18
|
+
}
|
|
19
|
+
function describeMode(mode) {
|
|
20
|
+
return (mode & 0o777).toString(8).padStart(3, '0');
|
|
21
|
+
}
|
|
22
|
+
async function inspect(path) {
|
|
23
|
+
try {
|
|
24
|
+
return await (0, promises_1.lstat)(path);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
throw new EndpointOwnershipError(path, `Cannot inspect daemon endpoint "${path}": ${error instanceof Error ? error.message : String(error)}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Verifies that the endpoint file is owned by this process's user and is not
|
|
32
|
+
* reachable by other users.
|
|
33
|
+
*
|
|
34
|
+
* On POSIX this is the operating-system ownership half of D-01: a socket that
|
|
35
|
+
* only the owning user can open is the strongest peer-identity control Node
|
|
36
|
+
* can enforce without a native `SO_PEERCRED` binding. Windows named pipes do
|
|
37
|
+
* not expose their security descriptor through `node:fs`, so the function
|
|
38
|
+
* reports `unsupported` instead of pretending to verify.
|
|
39
|
+
*/
|
|
40
|
+
async function verifyEndpointOwnership(endpointPath) {
|
|
41
|
+
if (process.platform === 'win32') {
|
|
42
|
+
return {
|
|
43
|
+
status: 'unsupported',
|
|
44
|
+
platform: process.platform,
|
|
45
|
+
reason: 'Windows named pipes do not expose ownership or mode through node:fs',
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const info = await inspect(endpointPath);
|
|
49
|
+
const uid = currentUid();
|
|
50
|
+
if (uid === undefined) {
|
|
51
|
+
return {
|
|
52
|
+
status: 'unsupported',
|
|
53
|
+
platform: process.platform,
|
|
54
|
+
reason: 'The platform does not expose process.getuid()',
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
if (info.uid !== uid) {
|
|
58
|
+
throw new EndpointOwnershipError(endpointPath, `Daemon endpoint "${endpointPath}" is owned by uid ${info.uid}, expected ${uid}`);
|
|
59
|
+
}
|
|
60
|
+
if ((info.mode & 0o077) !== 0) {
|
|
61
|
+
throw new EndpointOwnershipError(endpointPath, `Daemon endpoint "${endpointPath}" has insecure mode ${describeMode(info.mode)}`);
|
|
62
|
+
}
|
|
63
|
+
return { status: 'verified', uid, mode: info.mode & 0o777 };
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Forces the endpoint to owner-only access and verifies the result.
|
|
67
|
+
*
|
|
68
|
+
* Called by the daemon after bind, before any connection is accepted.
|
|
69
|
+
*/
|
|
70
|
+
async function enforceEndpointOwnership(endpointPath) {
|
|
71
|
+
if (process.platform === 'win32') {
|
|
72
|
+
return {
|
|
73
|
+
status: 'unsupported',
|
|
74
|
+
platform: process.platform,
|
|
75
|
+
reason: 'Windows named pipes do not expose ownership or mode through node:fs',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
await (0, promises_1.chmod)(endpointPath, 0o600);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
throw new EndpointOwnershipError(endpointPath, `Cannot set owner-only mode on daemon endpoint "${endpointPath}": ${error instanceof Error ? error.message : String(error)}`);
|
|
83
|
+
}
|
|
84
|
+
return await verifyEndpointOwnership(endpointPath);
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=ownership.js.map
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Socket } from 'node:net';
|
|
2
|
+
/** Identity the operating system reports for the other end of a local socket. */
|
|
3
|
+
export interface PeerCredentials {
|
|
4
|
+
readonly pid: number;
|
|
5
|
+
readonly uid: number;
|
|
6
|
+
readonly gid: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Identity the Windows named-pipe transport reports for the connecting process.
|
|
10
|
+
*
|
|
11
|
+
* `user` is the process token's user SID and `birth` is its creation time in
|
|
12
|
+
* 100 ns units since 1601 (the same decimal FILETIME string the helper returns
|
|
13
|
+
* from `processStartTime`). All three values are read through one process
|
|
14
|
+
* handle, so they describe the same process even after PID reuse.
|
|
15
|
+
*/
|
|
16
|
+
export interface WindowsPeerIdentity {
|
|
17
|
+
readonly pid: number;
|
|
18
|
+
readonly user: string;
|
|
19
|
+
readonly birth: string;
|
|
20
|
+
}
|
|
21
|
+
/** A connection the Windows helper authenticated; `fd` is a libuv descriptor. */
|
|
22
|
+
export interface PipePeer extends WindowsPeerIdentity {
|
|
23
|
+
readonly fd: number;
|
|
24
|
+
}
|
|
25
|
+
/** A connection the Windows helper dropped unread because identity was unavailable. */
|
|
26
|
+
export interface PipeRefused {
|
|
27
|
+
readonly refused: string;
|
|
28
|
+
readonly pid: number;
|
|
29
|
+
}
|
|
30
|
+
/** Windows named-pipe listener created by the prebuilt helper. */
|
|
31
|
+
export interface PipeListener {
|
|
32
|
+
accept(): Promise<PipePeer | PipeRefused>;
|
|
33
|
+
close(): void;
|
|
34
|
+
}
|
|
35
|
+
/** The process the daemon was spawned by, captured once before the first accept. */
|
|
36
|
+
export interface ExpectedPeer {
|
|
37
|
+
readonly pid: number;
|
|
38
|
+
/** POSIX effective uid. Absent on Windows, where `userSid` is used instead. */
|
|
39
|
+
readonly uid?: number;
|
|
40
|
+
/** Windows token user SID. Absent on POSIX. */
|
|
41
|
+
readonly userSid?: string;
|
|
42
|
+
readonly startTime: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Minimal shape of the prebuilt helper package.
|
|
46
|
+
*
|
|
47
|
+
* The package is ESM-only, so it is loaded with a dynamic import from this
|
|
48
|
+
* CommonJS package. The Windows-only primitives are optional here and are
|
|
49
|
+
* required by the Windows code path; the POSIX path uses the first two.
|
|
50
|
+
*/
|
|
51
|
+
interface PeerCredentialHost {
|
|
52
|
+
readonly localPeerCredentials: (socket: Socket) => PeerCredentials;
|
|
53
|
+
readonly processStartTime: (pid: number) => string | undefined;
|
|
54
|
+
readonly windowsUserSid?: () => string;
|
|
55
|
+
readonly listenPipe?: (name: string) => PipeListener;
|
|
56
|
+
readonly connectPipe?: (name: string, timeoutMs: number) => Promise<PipePeer>;
|
|
57
|
+
}
|
|
58
|
+
export declare class PeerCredentialError extends Error {
|
|
59
|
+
readonly reason: string;
|
|
60
|
+
constructor(reason: string);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Loads the prebuilt peer-credential helper.
|
|
64
|
+
*
|
|
65
|
+
* `@cotal-ai/seat` is the package used for both platforms: its shipped
|
|
66
|
+
* `peercred.node` reads `SO_PEERCRED` on Linux and `LOCAL_PEERCRED` plus
|
|
67
|
+
* `LOCAL_PEERPID` on macOS. The package never compiles at install time.
|
|
68
|
+
*/
|
|
69
|
+
export declare function loadPeerCredentialHost(): Promise<PeerCredentialHost>;
|
|
70
|
+
/**
|
|
71
|
+
* Reads a process start time in a form that can be compared across processes.
|
|
72
|
+
*
|
|
73
|
+
* Linux reads `/proc` (boot id plus the kernel start tick); macOS and Windows
|
|
74
|
+
* ask the prebuilt helper for the kernel process creation time. Every value
|
|
75
|
+
* survives a numeric PID reuse.
|
|
76
|
+
*/
|
|
77
|
+
export declare function readProcessStartTime(host: PeerCredentialHost, pid: number): string;
|
|
78
|
+
/** Captures the expected peer before the daemon accepts any connection. */
|
|
79
|
+
export declare function captureExpectedPeer(host: PeerCredentialHost, pid: number): ExpectedPeer;
|
|
80
|
+
/**
|
|
81
|
+
* Verifies the connected process against the host that spawned the daemon.
|
|
82
|
+
*
|
|
83
|
+
* The check runs on the accepted socket, before the Noise handshake or any
|
|
84
|
+
* dispatch work. A failure is final: the caller must close the connection.
|
|
85
|
+
*/
|
|
86
|
+
export declare function verifyPeerCredentials(socket: Socket, expected: ExpectedPeer, host: PeerCredentialHost): PeerCredentials;
|
|
87
|
+
/**
|
|
88
|
+
* Distinguishes an authenticated Windows pipe client from one the helper dropped.
|
|
89
|
+
*
|
|
90
|
+
* The helper only returns `fd` for a connection whose process identity it read;
|
|
91
|
+
* a `refused` result was already closed unread and must never be admitted.
|
|
92
|
+
*/
|
|
93
|
+
export declare function isPipePeer(value: PipePeer | PipeRefused): value is PipePeer;
|
|
94
|
+
/**
|
|
95
|
+
* Verifies the Windows named-pipe client against the host that spawned the daemon.
|
|
96
|
+
*
|
|
97
|
+
* The helper reports the connecting process's PID, token user SID, and creation
|
|
98
|
+
* time from one process handle at accept. The check is process-level: another
|
|
99
|
+
* process of the same user has the same SID but a different PID (and usually a
|
|
100
|
+
* different creation time), so it is refused before the Noise handshake or any
|
|
101
|
+
* dispatch work.
|
|
102
|
+
*/
|
|
103
|
+
export declare function verifyWindowsPeer(peer: WindowsPeerIdentity, expected: ExpectedPeer): WindowsPeerIdentity;
|
|
104
|
+
export {};
|