@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.
Files changed (61) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +67 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.js +88 -0
  5. package/dist/client/DaemonClient.d.ts +55 -0
  6. package/dist/client/DaemonClient.js +383 -0
  7. package/dist/client/connectToDaemon.d.ts +19 -0
  8. package/dist/client/connectToDaemon.js +131 -0
  9. package/dist/client/errors.d.ts +74 -0
  10. package/dist/client/errors.js +104 -0
  11. package/dist/client/identity.d.ts +3 -0
  12. package/dist/client/identity.js +7 -0
  13. package/dist/client/index.d.ts +6 -0
  14. package/dist/client/index.js +23 -0
  15. package/dist/client/socket.d.ts +9 -0
  16. package/dist/client/socket.js +101 -0
  17. package/dist/client/spawn.d.ts +7 -0
  18. package/dist/client/spawn.js +171 -0
  19. package/dist/index.d.ts +12 -0
  20. package/dist/index.js +29 -0
  21. package/dist/instanceRegistry.d.ts +130 -0
  22. package/dist/instanceRegistry.js +332 -0
  23. package/dist/lifecycle/endpoint.d.ts +19 -0
  24. package/dist/lifecycle/endpoint.js +124 -0
  25. package/dist/lifecycle/idle.d.ts +28 -0
  26. package/dist/lifecycle/idle.js +69 -0
  27. package/dist/lifecycle/index.d.ts +4 -0
  28. package/dist/lifecycle/index.js +21 -0
  29. package/dist/lifecycle/lock.d.ts +28 -0
  30. package/dist/lifecycle/lock.js +155 -0
  31. package/dist/lifecycle/shutdown.d.ts +39 -0
  32. package/dist/lifecycle/shutdown.js +115 -0
  33. package/dist/operatorConfig.d.ts +36 -0
  34. package/dist/operatorConfig.js +92 -0
  35. package/dist/security/channel.d.ts +113 -0
  36. package/dist/security/channel.js +448 -0
  37. package/dist/security/noise.d.ts +64 -0
  38. package/dist/security/noise.js +313 -0
  39. package/dist/security/ownership.d.ts +36 -0
  40. package/dist/security/ownership.js +86 -0
  41. package/dist/security/peerCredentials.d.ts +104 -0
  42. package/dist/security/peerCredentials.js +244 -0
  43. package/dist/server/Connection.d.ts +70 -0
  44. package/dist/server/Connection.js +412 -0
  45. package/dist/server/DaemonServer.d.ts +77 -0
  46. package/dist/server/DaemonServer.js +396 -0
  47. package/dist/server/createDaemon.d.ts +52 -0
  48. package/dist/server/createDaemon.js +165 -0
  49. package/dist/server/dispatch.d.ts +52 -0
  50. package/dist/server/dispatch.js +291 -0
  51. package/dist/server/framing.d.ts +63 -0
  52. package/dist/server/framing.js +196 -0
  53. package/dist/server/handshake.d.ts +22 -0
  54. package/dist/server/handshake.js +94 -0
  55. package/dist/server/protocolValidation.d.ts +47 -0
  56. package/dist/server/protocolValidation.js +366 -0
  57. package/dist/server/wireErrors.d.ts +5 -0
  58. package/dist/server/wireErrors.js +190 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +6 -0
  61. package/package.json +55 -4
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LockAcquisitionError = exports.LockContentionError = void 0;
4
+ exports.isPidAlive = isPidAlive;
5
+ exports.releaseDaemonLock = releaseDaemonLock;
6
+ exports.acquireDaemonLock = acquireDaemonLock;
7
+ const promises_1 = require("node:fs/promises");
8
+ const LOCK_FILE_MODE = 0o600;
9
+ const MAX_ACQUIRE_ATTEMPTS = 3;
10
+ class LockContentionError extends Error {
11
+ existingPid;
12
+ lockPath;
13
+ constructor(lockPath, existingPid, message) {
14
+ super(message ?? `Daemon lock at "${lockPath}" is held by running pid ${existingPid ?? 'unknown'}`);
15
+ this.name = 'LockContentionError';
16
+ this.existingPid = existingPid;
17
+ this.lockPath = lockPath;
18
+ }
19
+ }
20
+ exports.LockContentionError = LockContentionError;
21
+ class LockAcquisitionError extends Error {
22
+ constructor(message, options) {
23
+ super(message, options);
24
+ this.name = 'LockAcquisitionError';
25
+ }
26
+ }
27
+ exports.LockAcquisitionError = LockAcquisitionError;
28
+ function readErrorCode(error) {
29
+ if (typeof error !== 'object' || error === null || !('code' in error)) {
30
+ return undefined;
31
+ }
32
+ const code = error.code;
33
+ return typeof code === 'string' ? code : undefined;
34
+ }
35
+ function asLockRecord(value) {
36
+ if (typeof value !== 'object' || value === null) {
37
+ return undefined;
38
+ }
39
+ if (!('pid' in value) || !('startedAt' in value) || !('version' in value) || !('home' in value)) {
40
+ return undefined;
41
+ }
42
+ const { pid, startedAt, version, home } = value;
43
+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
44
+ return undefined;
45
+ }
46
+ if (typeof startedAt !== 'number' || !Number.isFinite(startedAt)) {
47
+ return undefined;
48
+ }
49
+ if (typeof version !== 'string' || typeof home !== 'string') {
50
+ return undefined;
51
+ }
52
+ return { pid, startedAt, version, home };
53
+ }
54
+ function isPidAlive(pid) {
55
+ if (!Number.isInteger(pid) || pid <= 0) {
56
+ return false;
57
+ }
58
+ try {
59
+ process.kill(pid, 0);
60
+ return true;
61
+ }
62
+ catch (error) {
63
+ return readErrorCode(error) === 'EPERM';
64
+ }
65
+ }
66
+ async function readLockRecord(lockPath) {
67
+ let content;
68
+ try {
69
+ content = await (0, promises_1.readFile)(lockPath, 'utf8');
70
+ }
71
+ catch (error) {
72
+ if (readErrorCode(error) === 'ENOENT') {
73
+ return undefined;
74
+ }
75
+ throw error;
76
+ }
77
+ let parsed;
78
+ try {
79
+ parsed = JSON.parse(content);
80
+ }
81
+ catch (error) {
82
+ throw new LockContentionError(lockPath, undefined, `Daemon lock at "${lockPath}" is unreadable`);
83
+ }
84
+ const record = asLockRecord(parsed);
85
+ if (record === undefined) {
86
+ throw new LockContentionError(lockPath, undefined, `Daemon lock at "${lockPath}" is malformed`);
87
+ }
88
+ return record;
89
+ }
90
+ async function releaseDaemonLock(endpoint) {
91
+ await (0, promises_1.unlink)(endpoint.lockPath).catch((error) => {
92
+ if (readErrorCode(error) !== 'ENOENT') {
93
+ throw error;
94
+ }
95
+ });
96
+ }
97
+ async function reclaimStaleLock(endpoint) {
98
+ await (0, promises_1.unlink)(endpoint.lockPath).catch((error) => {
99
+ if (readErrorCode(error) !== 'ENOENT') {
100
+ throw error;
101
+ }
102
+ });
103
+ if (!endpoint.isWindows) {
104
+ await (0, promises_1.unlink)(endpoint.socketPath).catch((error) => {
105
+ if (readErrorCode(error) !== 'ENOENT') {
106
+ throw error;
107
+ }
108
+ });
109
+ }
110
+ }
111
+ async function writeLockRecord(lockPath, record) {
112
+ const handle = await (0, promises_1.open)(lockPath, 'wx', LOCK_FILE_MODE);
113
+ try {
114
+ await handle.writeFile(JSON.stringify(record), 'utf8');
115
+ await handle.sync();
116
+ }
117
+ finally {
118
+ await handle.close();
119
+ }
120
+ }
121
+ async function acquireDaemonLock(endpoint, metadata) {
122
+ const record = {
123
+ pid: metadata.pid,
124
+ startedAt: Date.now(),
125
+ version: metadata.version,
126
+ home: endpoint.home,
127
+ };
128
+ for (let attempt = 1; attempt <= MAX_ACQUIRE_ATTEMPTS; attempt += 1) {
129
+ try {
130
+ await writeLockRecord(endpoint.lockPath, record);
131
+ }
132
+ catch (error) {
133
+ if (readErrorCode(error) !== 'EEXIST') {
134
+ throw new LockAcquisitionError(`Failed to create daemon lock at "${endpoint.lockPath}"`, { cause: error });
135
+ }
136
+ const existing = await readLockRecord(endpoint.lockPath);
137
+ if (existing === undefined) {
138
+ continue;
139
+ }
140
+ if (isPidAlive(existing.pid)) {
141
+ throw new LockContentionError(endpoint.lockPath, existing.pid);
142
+ }
143
+ await reclaimStaleLock(endpoint);
144
+ continue;
145
+ }
146
+ return {
147
+ endpoint,
148
+ lockPath: endpoint.lockPath,
149
+ record,
150
+ release: () => releaseDaemonLock(endpoint),
151
+ };
152
+ }
153
+ throw new LockAcquisitionError(`Failed to acquire daemon lock at "${endpoint.lockPath}" after ${MAX_ACQUIRE_ATTEMPTS} attempts`);
154
+ }
155
+ //# sourceMappingURL=lock.js.map
@@ -0,0 +1,39 @@
1
+ import type { KernelLifecycleState } from '@brud/kernel' with { 'resolution-mode': 'import' };
2
+ import type { DaemonActivitySnapshot } from '../server/DaemonServer.js';
3
+ import type { DaemonEndpoint } from './endpoint.js';
4
+ export declare const DEFAULT_DRAIN_TIMEOUT_MS = 10000;
5
+ export interface ShutdownServer {
6
+ readonly inFlightCount: number;
7
+ stopAccepting(): void;
8
+ closeConnections(): void;
9
+ onActivity(listener: (snapshot: DaemonActivitySnapshot) => void): () => void;
10
+ }
11
+ export interface ShutdownKernel {
12
+ readonly lifecycleState: KernelLifecycleState;
13
+ shutdown(): Promise<void>;
14
+ }
15
+ export interface GracefulShutdownCoordinatorOptions {
16
+ readonly server: ShutdownServer;
17
+ /** Single-kernel composition. Ignored when `disposeKernels` is provided. */
18
+ readonly kernel?: ShutdownKernel;
19
+ /** Multi-workspace disposer, run before the single-kernel fallback. */
20
+ readonly disposeKernels?: () => Promise<void>;
21
+ readonly endpoint: DaemonEndpoint;
22
+ readonly drainTimeoutMs?: number;
23
+ readonly beforeTeardown?: () => void;
24
+ }
25
+ export declare class GracefulShutdownCoordinator {
26
+ private readonly server;
27
+ private readonly kernel;
28
+ private readonly disposeKernels;
29
+ private readonly endpoint;
30
+ private readonly drainTimeoutMs;
31
+ private readonly beforeTeardown;
32
+ private shutdownPromise;
33
+ constructor(options: GracefulShutdownCoordinatorOptions);
34
+ get isShuttingDown(): boolean;
35
+ shutdown(): Promise<void>;
36
+ private runShutdown;
37
+ private drainInFlightRequests;
38
+ private cleanupArtifacts;
39
+ }
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GracefulShutdownCoordinator = exports.DEFAULT_DRAIN_TIMEOUT_MS = void 0;
4
+ const promises_1 = require("node:fs/promises");
5
+ exports.DEFAULT_DRAIN_TIMEOUT_MS = 10_000;
6
+ function readErrorCode(error) {
7
+ if (typeof error !== 'object' || error === null || !('code' in error)) {
8
+ return undefined;
9
+ }
10
+ const code = error.code;
11
+ return typeof code === 'string' ? code : undefined;
12
+ }
13
+ async function unlinkIfPresent(path) {
14
+ try {
15
+ await (0, promises_1.unlink)(path);
16
+ }
17
+ catch (error) {
18
+ if (readErrorCode(error) !== 'ENOENT') {
19
+ throw error;
20
+ }
21
+ }
22
+ }
23
+ class GracefulShutdownCoordinator {
24
+ server;
25
+ kernel;
26
+ disposeKernels;
27
+ endpoint;
28
+ drainTimeoutMs;
29
+ beforeTeardown;
30
+ shutdownPromise;
31
+ constructor(options) {
32
+ this.server = options.server;
33
+ this.kernel = options.kernel;
34
+ this.disposeKernels = options.disposeKernels;
35
+ this.endpoint = options.endpoint;
36
+ this.drainTimeoutMs = options.drainTimeoutMs ?? exports.DEFAULT_DRAIN_TIMEOUT_MS;
37
+ this.beforeTeardown = options.beforeTeardown;
38
+ }
39
+ get isShuttingDown() {
40
+ return this.shutdownPromise !== undefined;
41
+ }
42
+ shutdown() {
43
+ this.shutdownPromise ??= this.runShutdown();
44
+ return this.shutdownPromise;
45
+ }
46
+ async runShutdown() {
47
+ this.beforeTeardown?.();
48
+ let firstError;
49
+ try {
50
+ this.server.stopAccepting();
51
+ await this.drainInFlightRequests();
52
+ this.server.closeConnections();
53
+ if (this.disposeKernels !== undefined) {
54
+ await this.disposeKernels();
55
+ }
56
+ else if (this.kernel !== undefined && this.kernel.lifecycleState === 'RUNNING') {
57
+ await this.kernel.shutdown();
58
+ }
59
+ }
60
+ catch (error) {
61
+ firstError = error;
62
+ }
63
+ try {
64
+ await this.cleanupArtifacts();
65
+ }
66
+ catch (error) {
67
+ firstError ??= error;
68
+ }
69
+ if (firstError !== undefined) {
70
+ throw firstError;
71
+ }
72
+ }
73
+ async drainInFlightRequests() {
74
+ if (this.server.inFlightCount === 0) {
75
+ return;
76
+ }
77
+ await new Promise((resolve) => {
78
+ let unsubscribe;
79
+ let settled = false;
80
+ let timer;
81
+ const finish = () => {
82
+ if (settled) {
83
+ return;
84
+ }
85
+ settled = true;
86
+ if (timer !== undefined) {
87
+ clearTimeout(timer);
88
+ }
89
+ unsubscribe?.();
90
+ resolve();
91
+ };
92
+ timer = setTimeout(finish, this.drainTimeoutMs);
93
+ timer.unref();
94
+ unsubscribe = this.server.onActivity((snapshot) => {
95
+ if (snapshot.inFlightRequests === 0) {
96
+ finish();
97
+ }
98
+ });
99
+ if (this.server.inFlightCount === 0) {
100
+ finish();
101
+ }
102
+ });
103
+ }
104
+ async cleanupArtifacts() {
105
+ if (!this.endpoint.isWindows) {
106
+ await unlinkIfPresent(this.endpoint.socketPath);
107
+ }
108
+ await unlinkIfPresent(this.endpoint.tokenPath);
109
+ await unlinkIfPresent(this.endpoint.aiTokenPath);
110
+ await unlinkIfPresent(this.endpoint.lockPath);
111
+ await unlinkIfPresent(this.endpoint.metaPath);
112
+ }
113
+ }
114
+ exports.GracefulShutdownCoordinator = GracefulShutdownCoordinator;
115
+ //# sourceMappingURL=shutdown.js.map
@@ -0,0 +1,36 @@
1
+ import type { DaemonCallerTier } from '@brud/protocol';
2
+ /**
3
+ * Operator-owned daemon configuration, read once at start and frozen.
4
+ *
5
+ * The daemon knows no participant and no domain concept. Everything a kernel
6
+ * needs comes from here (the operator) or from the client, and the operator
7
+ * decides which startup fields a client may set.
8
+ */
9
+ export interface DaemonOperatorConfig {
10
+ /** Absolute path of the composition (`brud.config.json`) every kernel boots. */
11
+ readonly composition: string;
12
+ /** Startup options fixed by the operator; a client can never override them. */
13
+ readonly fixedOptions: Readonly<Record<string, unknown>>;
14
+ /** Startup field names a client may set in `kernel.boot`. */
15
+ readonly clientOptions: readonly string[];
16
+ /** Host-session capabilities per authenticated principal. */
17
+ readonly principals: Readonly<Record<DaemonCallerTier, readonly string[]>>;
18
+ /** Reuse a running kernel when a boot request carries identical options. */
19
+ readonly reuseIdenticalBoots: boolean;
20
+ }
21
+ /** Raised when the operator config file is missing or malformed. */
22
+ export declare class OperatorConfigError extends Error {
23
+ readonly code = "DAEMON_OPERATOR_CONFIG_INVALID";
24
+ constructor(message: string, options?: {
25
+ readonly cause?: unknown;
26
+ });
27
+ }
28
+ /** File name of the operator config inside the daemon home. */
29
+ export declare const OPERATOR_CONFIG_FILE = "daemon.json";
30
+ /**
31
+ * Parses an operator config value. Relative composition paths resolve against
32
+ * the config file's folder.
33
+ */
34
+ export declare function parseOperatorConfig(value: unknown, configPath: string): DaemonOperatorConfig;
35
+ /** Reads `<home>/daemon.json` (or an explicit path). */
36
+ export declare function loadOperatorConfig(home: string, explicitPath?: string): DaemonOperatorConfig;
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OPERATOR_CONFIG_FILE = exports.OperatorConfigError = void 0;
4
+ exports.parseOperatorConfig = parseOperatorConfig;
5
+ exports.loadOperatorConfig = loadOperatorConfig;
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ /** Raised when the operator config file is missing or malformed. */
9
+ class OperatorConfigError extends Error {
10
+ code = 'DAEMON_OPERATOR_CONFIG_INVALID';
11
+ constructor(message, options) {
12
+ super(message, options);
13
+ this.name = 'OperatorConfigError';
14
+ }
15
+ }
16
+ exports.OperatorConfigError = OperatorConfigError;
17
+ /** File name of the operator config inside the daemon home. */
18
+ exports.OPERATOR_CONFIG_FILE = 'daemon.json';
19
+ function isRecord(value) {
20
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
21
+ }
22
+ function stringList(value, field) {
23
+ if (value === undefined) {
24
+ return Object.freeze([]);
25
+ }
26
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === 'string')) {
27
+ throw new OperatorConfigError(`${field} must be an array of strings`);
28
+ }
29
+ return Object.freeze([...value]);
30
+ }
31
+ /**
32
+ * Parses an operator config value. Relative composition paths resolve against
33
+ * the config file's folder.
34
+ */
35
+ function parseOperatorConfig(value, configPath) {
36
+ if (!isRecord(value)) {
37
+ throw new OperatorConfigError(`${configPath} must contain a JSON object`);
38
+ }
39
+ const known = new Set(['composition', 'fixedOptions', 'clientOptions', 'principals', 'reuseIdenticalBoots']);
40
+ for (const key of Object.keys(value)) {
41
+ if (!known.has(key)) {
42
+ throw new OperatorConfigError(`${configPath}: unknown key "${key}"`);
43
+ }
44
+ }
45
+ if (typeof value.composition !== 'string' || value.composition.length === 0) {
46
+ throw new OperatorConfigError(`${configPath}: composition must be a path to a brud.config.json`);
47
+ }
48
+ if (value.fixedOptions !== undefined && !isRecord(value.fixedOptions)) {
49
+ throw new OperatorConfigError(`${configPath}: fixedOptions must be an object`);
50
+ }
51
+ const principals = value.principals === undefined ? {} : value.principals;
52
+ if (!isRecord(principals)) {
53
+ throw new OperatorConfigError(`${configPath}: principals must be an object`);
54
+ }
55
+ if (value.reuseIdenticalBoots !== undefined && typeof value.reuseIdenticalBoots !== 'boolean') {
56
+ throw new OperatorConfigError(`${configPath}: reuseIdenticalBoots must be a boolean`);
57
+ }
58
+ const composition = (0, node_path_1.isAbsolute)(value.composition)
59
+ ? value.composition
60
+ : (0, node_path_1.resolve)((0, node_path_1.dirname)(configPath), value.composition);
61
+ return Object.freeze({
62
+ composition,
63
+ fixedOptions: Object.freeze({ ...(value.fixedOptions ?? {}) }),
64
+ clientOptions: stringList(value.clientOptions, 'clientOptions'),
65
+ principals: Object.freeze({
66
+ ui: stringList(principals.ui, 'principals.ui'),
67
+ ai: stringList(principals.ai, 'principals.ai'),
68
+ }),
69
+ reuseIdenticalBoots: value.reuseIdenticalBoots ?? false,
70
+ });
71
+ }
72
+ /** Reads `<home>/daemon.json` (or an explicit path). */
73
+ function loadOperatorConfig(home, explicitPath) {
74
+ const configPath = explicitPath ?? (0, node_path_1.join)(home, exports.OPERATOR_CONFIG_FILE);
75
+ let raw;
76
+ try {
77
+ raw = (0, node_fs_1.readFileSync)(configPath, 'utf8');
78
+ }
79
+ catch (error) {
80
+ throw new OperatorConfigError(`Cannot read the daemon operator config at ${configPath}`, { cause: error });
81
+ }
82
+ try {
83
+ return parseOperatorConfig(JSON.parse(raw), configPath);
84
+ }
85
+ catch (error) {
86
+ if (error instanceof OperatorConfigError) {
87
+ throw error;
88
+ }
89
+ throw new OperatorConfigError(`${configPath} is not valid JSON`, { cause: error });
90
+ }
91
+ }
92
+ //# sourceMappingURL=operatorConfig.js.map
@@ -0,0 +1,113 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import type { Socket } from 'node:net';
3
+ import type { DaemonCallerTier, DaemonClientIdentity } from '@brud/protocol';
4
+ /** Hard ceiling for one Noise handshake message. */
5
+ export declare const MAX_HANDSHAKE_BYTES: number;
6
+ /** Hard ceiling for one encrypted transport record's plaintext. */
7
+ export declare const MAX_RECORD_PLAINTEXT_BYTES: number;
8
+ /** Default deadline for completing the Noise handshake. */
9
+ export declare const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10000;
10
+ /** Constant channel-binding prefix mixed into every Noise prologue. */
11
+ export declare const CHANNEL_PROLOGUE_PREFIX = "brud-daemon-channel-v1";
12
+ /** Binds a handshake to the endpoint both parties believe they are using. */
13
+ export declare function channelPrologue(socketPath: string): Buffer;
14
+ /**
15
+ * Record type, authenticated as the AEAD associated data.
16
+ *
17
+ * Direction separation comes from the two Noise cipher states; type
18
+ * separation comes from this byte. A record reflected with a different type
19
+ * fails authentication.
20
+ */
21
+ export declare const RECORD_REQUEST = 1;
22
+ export declare const RECORD_NOTIFICATION = 2;
23
+ export declare const RECORD_SUCCESS = 3;
24
+ export declare const RECORD_ERROR = 4;
25
+ export type RecordType = typeof RECORD_REQUEST | typeof RECORD_NOTIFICATION | typeof RECORD_SUCCESS | typeof RECORD_ERROR;
26
+ export interface SecureChannelHandshakeContext {
27
+ readonly principal: DaemonCallerTier;
28
+ readonly home: string;
29
+ readonly clientInfo?: DaemonClientIdentity;
30
+ readonly capabilities?: readonly string[];
31
+ }
32
+ export interface SecureChannelServerContext {
33
+ readonly name: string;
34
+ readonly version: string;
35
+ readonly pid: number;
36
+ }
37
+ export interface SecureChannelOptions {
38
+ readonly prologue: Buffer;
39
+ readonly handshakeTimeoutMs?: number;
40
+ readonly maxRecordBytes?: number;
41
+ }
42
+ export interface SecureChannelAcceptOptions extends SecureChannelOptions {
43
+ readonly psks: readonly {
44
+ readonly principal: DaemonCallerTier;
45
+ readonly psk: Buffer;
46
+ }[];
47
+ /** Validates the client-claimed workspace before the channel opens. */
48
+ readonly validateHome: (home: string) => void;
49
+ readonly server: SecureChannelServerContext;
50
+ }
51
+ export interface SecureChannelConnectOptions extends SecureChannelOptions {
52
+ readonly psk: Buffer;
53
+ readonly context: SecureChannelHandshakeContext;
54
+ }
55
+ export type SecureChannelMessageListener = (type: RecordType, text: string) => void;
56
+ /**
57
+ * Authenticated, AEAD-protected record channel over one local socket.
58
+ *
59
+ * The handshake is two Noise NNpsk0 messages; every message after it is a
60
+ * length-prefixed record whose type is bound into the AEAD associated data.
61
+ * Authentication failure, nonce reuse, a replayed record, or an invalid
62
+ * record shape destroys the connection: there is no fallback to plaintext.
63
+ */
64
+ export declare class SecureChannel {
65
+ private readonly socket;
66
+ private readonly options;
67
+ private readonly maxRecordBytes;
68
+ private sendState;
69
+ private receiveState;
70
+ private handshakeHash;
71
+ private buffer;
72
+ private phase;
73
+ private messageListener;
74
+ private closeListener;
75
+ private handshakeTimer;
76
+ private resolveHandshake;
77
+ private rejectHandshake;
78
+ private handshakeDone;
79
+ private handshakeResolved;
80
+ private constructor();
81
+ static connect(socket: Socket, options: SecureChannelConnectOptions): Promise<{
82
+ channel: SecureChannel;
83
+ server: SecureChannelServerContext;
84
+ }>;
85
+ static accept(socket: Socket, options: SecureChannelAcceptOptions): Promise<{
86
+ channel: SecureChannel;
87
+ context: SecureChannelHandshakeContext;
88
+ }>;
89
+ onMessage(listener: SecureChannelMessageListener): void;
90
+ onClose(listener: () => void): void;
91
+ get isClosed(): boolean;
92
+ get binding(): Buffer | undefined;
93
+ send(message: unknown): void;
94
+ /**
95
+ * Sends raw JSON text of a chosen type through the real encryption path.
96
+ *
97
+ * Test clients use this to inject malformed or hostile plaintext after the
98
+ * handshake; the daemon's post-decryption validation is still the real path.
99
+ */
100
+ sendRaw(text: string, type?: RecordType): void;
101
+ end(): void;
102
+ destroy(): void;
103
+ private sendTyped;
104
+ private beginHandshakeTimeout;
105
+ private installTransport;
106
+ private onData;
107
+ private maxBufferBytes;
108
+ private pump;
109
+ private deliverHandshakeMessage;
110
+ private writeRaw;
111
+ private fail;
112
+ private notifyClose;
113
+ }