@adhdev/session-host-core 1.0.82-rc.36 → 1.0.82-rc.38
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/dist/index.d.mts +90 -94
- package/dist/index.d.ts +90 -94
- package/dist/index.js +114 -131
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +107 -126
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/cleanup-expected.ts +114 -0
- package/src/control-plane.ts +58 -0
- package/src/index.ts +12 -2
- package/src/types.ts +40 -8
- package/src/operator-recovery.ts +0 -134
package/package.json
CHANGED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/** Shared cleanup expected-assignment / host-boot helpers (daemon + host). */
|
|
2
|
+
import type { SessionCleanupExpectedAssignment, SessionHostRecord } from './types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Prefix on delete_session_if_expected refusals after runtime.stop was requested.
|
|
6
|
+
* Client durable fences must not abort on these — the writer may already be dying.
|
|
7
|
+
* Before-action refusals keep the bare CLEANUP_HOST_REFUSAL_CODES (abort-safe proof).
|
|
8
|
+
*/
|
|
9
|
+
export const CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX = 'cleanup_after_stop_side_effect:';
|
|
10
|
+
|
|
11
|
+
export function tagCleanupAfterStopSideEffect(code: string): string {
|
|
12
|
+
return `${CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX}${code}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function stripCleanupAfterStopSideEffect(raw: string): { afterStop: boolean; code: string } {
|
|
16
|
+
if (raw.startsWith(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX)) {
|
|
17
|
+
return { afterStop: true, code: raw.slice(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX.length) };
|
|
18
|
+
}
|
|
19
|
+
return { afterStop: false, code: raw };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function hostBootIdFromStartedAt(hostStartedAt: number): string {
|
|
23
|
+
return `hs:${hostStartedAt}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function resolveHostBootId(opts: { upgradeBootId?: string | null; hostStartedAt: number }): string | null {
|
|
27
|
+
if (typeof opts.upgradeBootId === 'string' && opts.upgradeBootId) return opts.upgradeBootId;
|
|
28
|
+
if (!Number.isFinite(opts.hostStartedAt) || opts.hostStartedAt <= 0) return null;
|
|
29
|
+
return hostBootIdFromStartedAt(opts.hostStartedAt);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function refuseCleanupExpectedIdentity(
|
|
33
|
+
record: SessionHostRecord | null | undefined,
|
|
34
|
+
expected: SessionCleanupExpectedAssignment,
|
|
35
|
+
currentHostBootId: string | null,
|
|
36
|
+
): string | null {
|
|
37
|
+
if (!expected || expected.sessionId !== (record?.sessionId ?? '')
|
|
38
|
+
|| typeof expected.hostBootId !== 'string' || !expected.hostBootId
|
|
39
|
+
|| typeof expected.runtimeKey !== 'string' || !expected.runtimeKey
|
|
40
|
+
|| !Number.isSafeInteger(expected.startedAt) || expected.startedAt <= 0) {
|
|
41
|
+
return 'cleanup_expected_malformed';
|
|
42
|
+
}
|
|
43
|
+
if (!currentHostBootId) return 'cleanup_host_boot_unknown';
|
|
44
|
+
if (expected.hostBootId !== currentHostBootId) return 'cleanup_host_boot_mismatch';
|
|
45
|
+
if (!record) return 'cleanup_session_not_running';
|
|
46
|
+
if (record.runtimeKey !== expected.runtimeKey || record.startedAt !== expected.startedAt) {
|
|
47
|
+
return 'cleanup_native_incarnation_mismatch';
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function refuseCleanupExpectedAssignment(
|
|
53
|
+
record: SessionHostRecord,
|
|
54
|
+
expected: SessionCleanupExpectedAssignment,
|
|
55
|
+
opts: { allowClearedBound?: boolean } = {},
|
|
56
|
+
): string | null {
|
|
57
|
+
const active = record.meta?.meshActiveAssignment as Record<string, unknown> | undefined;
|
|
58
|
+
// taskId null is the unbound intent; attempt/generation/nonce may still be present as
|
|
59
|
+
// sticky fence fields on an idle worker and must not be treated as a live assignment.
|
|
60
|
+
if (expected.taskId === null) {
|
|
61
|
+
if (active && typeof active.taskId === 'string' && active.taskId) return 'cleanup_expected_unbound_now_bound';
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
if (!active || typeof active.taskId !== 'string' || !active.taskId) {
|
|
65
|
+
// After a proven stop the assignment may clear on the same incarnation — allow delete.
|
|
66
|
+
return opts.allowClearedBound ? null : 'cleanup_expected_bound_now_unbound';
|
|
67
|
+
}
|
|
68
|
+
if (active.taskId !== expected.taskId || active.attemptId !== expected.attemptId
|
|
69
|
+
|| active.generation !== expected.generation || active.dispatchNonce !== expected.dispatchNonce) {
|
|
70
|
+
return 'cleanup_assignment_mismatch';
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Sanitized refusal codes only — never echo assignment contents. */
|
|
76
|
+
export function refuseCleanupExpectedStop(
|
|
77
|
+
record: SessionHostRecord | null | undefined,
|
|
78
|
+
expected: SessionCleanupExpectedAssignment,
|
|
79
|
+
currentHostBootId: string | null,
|
|
80
|
+
hasRuntime: boolean,
|
|
81
|
+
): string | null {
|
|
82
|
+
const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
|
|
83
|
+
if (identity) return identity;
|
|
84
|
+
if (!record || record.termination || !hasRuntime || record.lifecycle !== 'running') {
|
|
85
|
+
return 'cleanup_session_not_running';
|
|
86
|
+
}
|
|
87
|
+
return refuseCleanupExpectedAssignment(record, expected);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Delete CAS: same identity/assignment proof as stop. A replaced incarnation or a
|
|
92
|
+
* newly bound writer must survive — never delete a record that no longer matches
|
|
93
|
+
* the captured expected tuple. `force` is required to stop a still-live runtime
|
|
94
|
+
* before deleting that exact incarnation.
|
|
95
|
+
*/
|
|
96
|
+
export function refuseCleanupExpectedDelete(
|
|
97
|
+
record: SessionHostRecord | null | undefined,
|
|
98
|
+
expected: SessionCleanupExpectedAssignment,
|
|
99
|
+
currentHostBootId: string | null,
|
|
100
|
+
hasRuntime: boolean,
|
|
101
|
+
force: boolean,
|
|
102
|
+
): string | null {
|
|
103
|
+
// Missing record after a proven stop is handled by the caller as idempotent delete.
|
|
104
|
+
if (!record) return 'cleanup_session_not_running';
|
|
105
|
+
const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
|
|
106
|
+
if (identity) return identity;
|
|
107
|
+
if (hasRuntime) {
|
|
108
|
+
if (!force) return 'cleanup_session_still_running';
|
|
109
|
+
if (record.termination || record.lifecycle !== 'running') return 'cleanup_session_not_running';
|
|
110
|
+
return refuseCleanupExpectedAssignment(record, expected);
|
|
111
|
+
}
|
|
112
|
+
// Stopped/failed record: protect unbound→bound and reassignment on the same incarnation.
|
|
113
|
+
return refuseCleanupExpectedAssignment(record, expected, { allowClearedBound: true });
|
|
114
|
+
}
|
package/src/control-plane.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { resolveHostBootId } from './cleanup-expected.js';
|
|
1
2
|
import type {
|
|
2
3
|
AcquireWritePayload,
|
|
3
4
|
GetHostDiagnosticsPayload,
|
|
4
5
|
GetSnapshotPayload,
|
|
5
6
|
PruneDuplicateSessionsPayload,
|
|
6
7
|
ReleaseWritePayload,
|
|
8
|
+
SessionCleanupExpectedAssignment,
|
|
7
9
|
SessionHostDiagnostics,
|
|
8
10
|
SessionHostPruneDuplicatesResult,
|
|
9
11
|
SessionHostRecord,
|
|
@@ -28,9 +30,24 @@ export interface SessionHostSnapshot {
|
|
|
28
30
|
*/
|
|
29
31
|
export interface SessionHostControlPlane {
|
|
30
32
|
getDiagnostics(payload?: GetHostDiagnosticsPayload): Promise<SessionHostDiagnostics>;
|
|
33
|
+
/**
|
|
34
|
+
* Authoritative host boot identity for idle inventory / cleanup expected CAS.
|
|
35
|
+
* Prefers diagnostics.hostBootId (host SoT), else proves upgrade lease bootId
|
|
36
|
+
* via get_upgrade_lease, else hs:<hostStartedAt> for non-upgrade / old hosts.
|
|
37
|
+
* Ambiguous upgrade-lease failures fail closed (null) — never invent a UUID.
|
|
38
|
+
*/
|
|
39
|
+
resolveHostBootId(): Promise<string | null>;
|
|
31
40
|
listSessions(): Promise<SessionHostRecord[]>;
|
|
32
41
|
stopSession(sessionId: string): Promise<SessionHostRecord | null>;
|
|
42
|
+
/** Host CAS stop: refuses without mutating when expected assignment/boot/incarnation drift. */
|
|
43
|
+
stopSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment): Promise<SessionHostRecord | null>;
|
|
33
44
|
deleteSession(sessionId: string, opts?: { force?: boolean }): Promise<SessionHostRecord | null>;
|
|
45
|
+
/** Host CAS delete: refuses without mutating when expected assignment/boot/incarnation drift. */
|
|
46
|
+
deleteSessionIfExpected(
|
|
47
|
+
sessionId: string,
|
|
48
|
+
expected: SessionCleanupExpectedAssignment,
|
|
49
|
+
opts?: { force?: boolean },
|
|
50
|
+
): Promise<{ sessionId: string; deleted: boolean; alreadyAbsent?: boolean } | null>;
|
|
34
51
|
resumeSession(sessionId: string): Promise<SessionHostRecord | null>;
|
|
35
52
|
restartSession(sessionId: string): Promise<SessionHostRecord | null>;
|
|
36
53
|
sendSignal(sessionId: string, signal: string): Promise<SessionHostRecord | null>;
|
|
@@ -76,15 +93,56 @@ export function createSessionHostControlPlane(
|
|
|
76
93
|
getDiagnostics(payload: GetHostDiagnosticsPayload = {}): Promise<SessionHostDiagnostics> {
|
|
77
94
|
return transport.request<SessionHostDiagnostics>('get_host_diagnostics', payload as Record<string, unknown>);
|
|
78
95
|
},
|
|
96
|
+
async resolveHostBootId(): Promise<string | null> {
|
|
97
|
+
let diagnostics: SessionHostDiagnostics;
|
|
98
|
+
try {
|
|
99
|
+
diagnostics = await transport.request<SessionHostDiagnostics>('get_host_diagnostics', {});
|
|
100
|
+
} catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
if (typeof diagnostics.hostBootId === 'string' && diagnostics.hostBootId) {
|
|
104
|
+
return diagnostics.hostBootId;
|
|
105
|
+
}
|
|
106
|
+
// Host omitted hostBootId (older binary). Prove upgrade lease or fall back to hs:.
|
|
107
|
+
try {
|
|
108
|
+
const proof = await transport.request<{ bootId?: string }>('get_upgrade_lease', {});
|
|
109
|
+
return resolveHostBootId({
|
|
110
|
+
upgradeBootId: typeof proof?.bootId === 'string' ? proof.bootId : null,
|
|
111
|
+
hostStartedAt: diagnostics.hostStartedAt,
|
|
112
|
+
});
|
|
113
|
+
} catch (error) {
|
|
114
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
115
|
+
if (
|
|
116
|
+
msg.includes('native_host_upgrade_binding_unavailable')
|
|
117
|
+
|| /unsupported|unknown request/i.test(msg)
|
|
118
|
+
) {
|
|
119
|
+
return resolveHostBootId({ hostStartedAt: diagnostics.hostStartedAt });
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
},
|
|
79
124
|
listSessions(): Promise<SessionHostRecord[]> {
|
|
80
125
|
return transport.request<SessionHostRecord[]>('list_sessions', {});
|
|
81
126
|
},
|
|
82
127
|
stopSession(sessionId: string): Promise<SessionHostRecord | null> {
|
|
83
128
|
return transport.request<SessionHostRecord | null>('stop_session', { sessionId });
|
|
84
129
|
},
|
|
130
|
+
stopSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment): Promise<SessionHostRecord | null> {
|
|
131
|
+
return transport.request<SessionHostRecord | null>('stop_session_if_expected', { sessionId, expected });
|
|
132
|
+
},
|
|
85
133
|
deleteSession(sessionId: string, opts: { force?: boolean } = {}): Promise<SessionHostRecord | null> {
|
|
86
134
|
return transport.request<SessionHostRecord | null>('delete_session', { sessionId, force: opts.force === true });
|
|
87
135
|
},
|
|
136
|
+
deleteSessionIfExpected(
|
|
137
|
+
sessionId: string,
|
|
138
|
+
expected: SessionCleanupExpectedAssignment,
|
|
139
|
+
opts: { force?: boolean } = {},
|
|
140
|
+
): Promise<{ sessionId: string; deleted: boolean; alreadyAbsent?: boolean } | null> {
|
|
141
|
+
return transport.request<{ sessionId: string; deleted: boolean; alreadyAbsent?: boolean } | null>(
|
|
142
|
+
'delete_session_if_expected',
|
|
143
|
+
{ sessionId, expected, force: opts.force === true },
|
|
144
|
+
);
|
|
145
|
+
},
|
|
88
146
|
resumeSession(sessionId: string): Promise<SessionHostRecord | null> {
|
|
89
147
|
return transport.request<SessionHostRecord | null>('resume_session', { sessionId });
|
|
90
148
|
},
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
export { OPERATOR_RECOVERY_TARGET, recoveryTargetBytes, RecoveryOwnerAdmission, assertRecoveryLaunchIdentity, isRecoveryEndpoint } from './operator-recovery.js';
|
|
2
|
-
export type { RecoveryOwnerOperation, RecoveryOwnerGrant, RecoveryOwnerChallenge, RecoveryOwnerEnrollment, RecoveryHostBinding, RecoveryPhysicalProof } from './operator-recovery.js';
|
|
3
1
|
export type {
|
|
4
2
|
MeshWriterAssignment,
|
|
5
3
|
MeshWriterStopTarget,
|
|
@@ -52,9 +50,21 @@ export type {
|
|
|
52
50
|
SessionHostWireEnvelope,
|
|
53
51
|
SessionWriteOwner,
|
|
54
52
|
StopSessionPayload,
|
|
53
|
+
SessionCleanupExpectedAssignment,
|
|
54
|
+
StopSessionIfExpectedPayload,
|
|
55
|
+
DeleteSessionIfExpectedPayload,
|
|
55
56
|
} from './types.js';
|
|
56
57
|
|
|
57
58
|
export { SESSION_HOST_SUPPORTED_REQUEST_TYPES } from './types.js';
|
|
59
|
+
export {
|
|
60
|
+
CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
|
|
61
|
+
tagCleanupAfterStopSideEffect,
|
|
62
|
+
stripCleanupAfterStopSideEffect,
|
|
63
|
+
hostBootIdFromStartedAt,
|
|
64
|
+
resolveHostBootId,
|
|
65
|
+
refuseCleanupExpectedStop,
|
|
66
|
+
refuseCleanupExpectedDelete,
|
|
67
|
+
} from './cleanup-expected.js';
|
|
58
68
|
export { classifyTermination } from './termination.js';
|
|
59
69
|
export { CLI_CHILD_NICE_INCREMENT, CLI_CHILD_NICE_ENV, CLI_CHILD_SCHEDULING_ENV, createCliChildPriorityPolicy, niceLaunch, spawnCliChild, type NiceLaunch } from './cli-child-priority.js';
|
|
60
70
|
export { hiddenSpawn as hiddenSpawnProcess } from './process/hidden-spawn.js';
|
package/src/types.ts
CHANGED
|
@@ -195,6 +195,26 @@ export interface ResizeSessionPayload {
|
|
|
195
195
|
export interface StopSessionPayload {
|
|
196
196
|
sessionId: string;
|
|
197
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* Expected logical + physical identity for a cleanup stop. Captured before any
|
|
200
|
+
* async host RPC and re-checked inside the host stop critical section.
|
|
201
|
+
* All of taskId/attemptId/generation/dispatchNonce null means expected unbound
|
|
202
|
+
* (no meshActiveAssignment) so a later claim cannot be stopped by stale cleanup.
|
|
203
|
+
*/
|
|
204
|
+
export interface SessionCleanupExpectedAssignment {
|
|
205
|
+
sessionId: string;
|
|
206
|
+
hostBootId: string;
|
|
207
|
+
runtimeKey: string;
|
|
208
|
+
startedAt: number;
|
|
209
|
+
taskId: string | null;
|
|
210
|
+
attemptId: string | null;
|
|
211
|
+
generation: number | null;
|
|
212
|
+
dispatchNonce: number | null;
|
|
213
|
+
}
|
|
214
|
+
export interface StopSessionIfExpectedPayload {
|
|
215
|
+
sessionId: string;
|
|
216
|
+
expected: SessionCleanupExpectedAssignment;
|
|
217
|
+
}
|
|
198
218
|
export interface MeshWriterAssignment {
|
|
199
219
|
meshId: string; nodeId: string; taskId: string; attemptId: string;
|
|
200
220
|
generation: number; dispatchNonce: number; ownerDaemonId: string;
|
|
@@ -210,6 +230,13 @@ export interface DeleteSessionPayload {
|
|
|
210
230
|
/** Stop a live runtime before deleting the persisted record. */
|
|
211
231
|
force?: boolean;
|
|
212
232
|
}
|
|
233
|
+
/** Expected identity for record deletion; old hosts must refuse this distinct kind. */
|
|
234
|
+
export interface DeleteSessionIfExpectedPayload {
|
|
235
|
+
sessionId: string;
|
|
236
|
+
expected: SessionCleanupExpectedAssignment;
|
|
237
|
+
/** Stop the matching live runtime before deleting that exact incarnation. */
|
|
238
|
+
force?: boolean;
|
|
239
|
+
}
|
|
213
240
|
|
|
214
241
|
export interface ResumeSessionPayload {
|
|
215
242
|
sessionId: string;
|
|
@@ -347,6 +374,13 @@ export interface SessionHostDiagnostics {
|
|
|
347
374
|
* must treat `undefined` as "unknown", never as a match.
|
|
348
375
|
*/
|
|
349
376
|
hostEntryPath?: string;
|
|
377
|
+
/**
|
|
378
|
+
* Authoritative host boot identity used by cleanup expected-assignment CAS.
|
|
379
|
+
* Same value `stop_session_if_expected` refuses against: upgrade-lease bootId
|
|
380
|
+
* when the host was launched with a native upgrade binding, otherwise `hs:<hostStartedAt>`.
|
|
381
|
+
* Optional so older hosts omit it; callers must not invent an upgrade UUID.
|
|
382
|
+
*/
|
|
383
|
+
hostBootId?: string;
|
|
350
384
|
runtimeCount: number;
|
|
351
385
|
supportedRequestTypes?: SessionHostRequestType[];
|
|
352
386
|
sessions?: SessionHostRecord[];
|
|
@@ -366,10 +400,6 @@ export interface HostUpgradeLeasePayload {
|
|
|
366
400
|
}
|
|
367
401
|
|
|
368
402
|
export type SessionHostRequest =
|
|
369
|
-
| { type: 'prepare_operator_recovery_fence_v1'; payload?: {} }
|
|
370
|
-
| { type: 'install_operator_recovery_fence_v1'; payload: { message: string; signature: string } }
|
|
371
|
-
| { type: 'attest_operator_recovery_v1'; payload: { nonce: string; fenceDigest: string } }
|
|
372
|
-
| { type: 'get_operator_recovery_coverage_v1'; payload: { nonce: string } }
|
|
373
403
|
| { type: 'get_upgrade_lease'; payload?: {} }
|
|
374
404
|
| { type: 'acquire_upgrade_lease'; payload: HostUpgradeLeasePayload }
|
|
375
405
|
| { type: 'release_upgrade_lease'; payload: HostUpgradeLeasePayload }
|
|
@@ -382,8 +412,12 @@ export type SessionHostRequest =
|
|
|
382
412
|
| { type: 'get_input_state'; payload: GetInputStatePayload }
|
|
383
413
|
| { type: 'resize_session'; payload: ResizeSessionPayload }
|
|
384
414
|
| { type: 'stop_session'; payload: StopSessionPayload }
|
|
415
|
+
/** Distinct kind: old hosts must refuse instead of stopping by session id alone. */
|
|
416
|
+
| { type: 'stop_session_if_expected'; payload: StopSessionIfExpectedPayload }
|
|
385
417
|
| { type: 'stop_mesh_writer'; payload: StopMeshWriterPayload }
|
|
386
418
|
| { type: 'delete_session'; payload: DeleteSessionPayload }
|
|
419
|
+
/** Distinct kind: old hosts must refuse instead of deleting by session id alone. */
|
|
420
|
+
| { type: 'delete_session_if_expected'; payload: DeleteSessionIfExpectedPayload }
|
|
387
421
|
| { type: 'resume_session'; payload: ResumeSessionPayload }
|
|
388
422
|
| { type: 'acquire_write'; payload: AcquireWritePayload }
|
|
389
423
|
| { type: 'release_write'; payload: ReleaseWritePayload }
|
|
@@ -403,10 +437,6 @@ export type SessionHostRequest =
|
|
|
403
437
|
export type SessionHostRequestType = SessionHostRequest['type'];
|
|
404
438
|
|
|
405
439
|
export const SESSION_HOST_SUPPORTED_REQUEST_TYPES: readonly SessionHostRequestType[] = [
|
|
406
|
-
'prepare_operator_recovery_fence_v1',
|
|
407
|
-
'install_operator_recovery_fence_v1',
|
|
408
|
-
'attest_operator_recovery_v1',
|
|
409
|
-
'get_operator_recovery_coverage_v1',
|
|
410
440
|
'get_upgrade_lease',
|
|
411
441
|
'acquire_upgrade_lease',
|
|
412
442
|
'release_upgrade_lease',
|
|
@@ -420,8 +450,10 @@ export const SESSION_HOST_SUPPORTED_REQUEST_TYPES: readonly SessionHostRequestTy
|
|
|
420
450
|
'get_input_state',
|
|
421
451
|
'resize_session',
|
|
422
452
|
'stop_session',
|
|
453
|
+
'stop_session_if_expected',
|
|
423
454
|
'stop_mesh_writer',
|
|
424
455
|
'delete_session',
|
|
456
|
+
'delete_session_if_expected',
|
|
425
457
|
'resume_session',
|
|
426
458
|
'acquire_write',
|
|
427
459
|
'release_write',
|
package/src/operator-recovery.ts
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
import { createPublicKey, randomBytes, verify, type KeyObject } from 'node:crypto';
|
|
2
|
-
import { isAbsolute, basename } from 'node:path';
|
|
3
|
-
import { performance } from 'node:perf_hooks';
|
|
4
|
-
|
|
5
|
-
/** This association is owner asserted, never a historical native receipt. */
|
|
6
|
-
export const OPERATOR_RECOVERY_TARGET = Object.freeze({
|
|
7
|
-
association: 'operator_asserted' as const,
|
|
8
|
-
taskId: 'a1cdf3c0-f029-4d17-a8e9-db64e0a55501',
|
|
9
|
-
meshId: 'mesh_271444af883843e9b36c67155b87b22f',
|
|
10
|
-
attemptId: 'mesh_queue:mesh_271444af883843e9b36c67155b87b22f:a1cdf3c0-f029-4d17-a8e9-db64e0a55501:0',
|
|
11
|
-
generation: 0, dispatchNonce: 1,
|
|
12
|
-
deliveryId: 'dlv-7e259b34-b049-47ee-a466-2ca9c12bcff4',
|
|
13
|
-
ownerDaemonId: 'daemon_mach_4462a75330c548be9c2e74dd9f7f6ffb',
|
|
14
|
-
nodeId: 'node_d82de0cef9b042b6948986609e32142f',
|
|
15
|
-
workerDaemonId: 'daemon_mach_6733c865d60f432dbeb119a6875ee303',
|
|
16
|
-
sessionId: 'de321185-4ebc-40aa-8c6e-b4919e87fae3',
|
|
17
|
-
providerSessionId: '60806c79-7d77-4614-9fa6-e628533478ba',
|
|
18
|
-
namespace: '6a2ef3162182',
|
|
19
|
-
});
|
|
20
|
-
export const recoveryTargetBytes = JSON.stringify(OPERATOR_RECOVERY_TARGET);
|
|
21
|
-
/** Shared final admission guard for saved IDs, new aliases and provider argv.
|
|
22
|
-
* This is a permanent exact-target denial, independent of journal availability. */
|
|
23
|
-
export function assertRecoveryLaunchIdentity(value: unknown): void {
|
|
24
|
-
if (!value || typeof value !== 'object') return;
|
|
25
|
-
const identities = new Set(['sessionId', 'runtimeId', 'runtimeSessionId', 'providerSessionId',
|
|
26
|
-
'presetSessionKey', 'resumeSessionId', 'key']);
|
|
27
|
-
const nested = new Set(['options', 'meta', 'settings', 'settingsOverride', 'restartBinding', 'sessionBinding', 'launchCommand']);
|
|
28
|
-
for (const [key, field] of Object.entries(value)) {
|
|
29
|
-
if (identities.has(key) || ['args', 'cliArgs', 'cliArgsWithBrain'].includes(key)) {
|
|
30
|
-
const bytes = JSON.stringify(field)?.toLowerCase();
|
|
31
|
-
if (bytes?.includes(OPERATOR_RECOVERY_TARGET.sessionId) || bytes?.includes(OPERATOR_RECOVERY_TARGET.providerSessionId)) {
|
|
32
|
-
throw new Error('operator_recovery_fenced');
|
|
33
|
-
}
|
|
34
|
-
} else if (nested.has(key)) assertRecoveryLaunchIdentity(field);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
export type RecoveryOwnerOperation = 'anchor_recover' | 'fence_install' | 'witness_enroll';
|
|
38
|
-
export interface RecoveryOwnerGrant { readonly purpose: 'operator_recovery_v1'; readonly operation: RecoveryOwnerOperation }
|
|
39
|
-
export function isRecoveryEndpoint(endpoint: string): boolean {
|
|
40
|
-
return isAbsolute(endpoint) && basename(endpoint) === `adhdev-preview-session-host-${OPERATOR_RECOVERY_TARGET.namespace}.sock`;
|
|
41
|
-
}
|
|
42
|
-
export interface RecoveryOwnerChallenge { readonly message: string }
|
|
43
|
-
export interface RecoveryOwnerEnrollment {
|
|
44
|
-
/** Trusted boot dependency, provisioned outside delegated worker authority.
|
|
45
|
-
* Do not load this from daemon config, IPC arguments or an MCP credential. */
|
|
46
|
-
publicKey: string;
|
|
47
|
-
enrollmentId: string;
|
|
48
|
-
coordinatorBootId: string;
|
|
49
|
-
authEpoch: string;
|
|
50
|
-
verifyCurrent: () => boolean;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/** Signature possession authenticates the separately enrolled owner signer.
|
|
54
|
-
* This verifier does not enroll keys or assert user presence on their behalf. */
|
|
55
|
-
export class RecoveryOwnerAdmission {
|
|
56
|
-
private readonly key: KeyObject;
|
|
57
|
-
private readonly enrollment: Readonly<RecoveryOwnerEnrollment>;
|
|
58
|
-
private readonly pending = new Map<string, { deadline: number; operation: RecoveryOwnerOperation }>();
|
|
59
|
-
private readonly grants = new WeakMap<object, { deadline: number; operation: RecoveryOwnerOperation }>();
|
|
60
|
-
private lastNow = -Infinity;
|
|
61
|
-
constructor(enrollment: RecoveryOwnerEnrollment, private readonly clock = () => performance.now()) {
|
|
62
|
-
this.enrollment = Object.freeze({ ...enrollment });
|
|
63
|
-
if (!enrollment.enrollmentId || !enrollment.coordinatorBootId || !enrollment.authEpoch ||
|
|
64
|
-
typeof enrollment.verifyCurrent !== 'function') throw new Error('recovery_owner_enrollment_required');
|
|
65
|
-
this.key = createPublicKey(enrollment.publicKey);
|
|
66
|
-
if (this.key.asymmetricKeyType !== 'ed25519') throw new Error('recovery_owner_key_type');
|
|
67
|
-
}
|
|
68
|
-
private now(): number {
|
|
69
|
-
const n = this.clock();
|
|
70
|
-
if (!Number.isFinite(n) || n < this.lastNow || this.enrollment.verifyCurrent() !== true) {
|
|
71
|
-
this.pending.clear();
|
|
72
|
-
this.lastNow = Infinity; // A revocation or clock rollback cannot be undone.
|
|
73
|
-
throw new Error('recovery_owner_revoked');
|
|
74
|
-
}
|
|
75
|
-
this.lastNow = n;
|
|
76
|
-
return n;
|
|
77
|
-
}
|
|
78
|
-
challenge(operation: RecoveryOwnerOperation = 'anchor_recover'): RecoveryOwnerChallenge {
|
|
79
|
-
if (!['anchor_recover', 'fence_install', 'witness_enroll'].includes(operation)) throw new Error('recovery_owner_operation_rejected');
|
|
80
|
-
const now = this.now();
|
|
81
|
-
for (const [message, entry] of this.pending) if (entry.deadline <= now) this.pending.delete(message);
|
|
82
|
-
if (this.pending.size >= 16) throw new Error('recovery_owner_challenge_limit');
|
|
83
|
-
const message = JSON.stringify(['operator_recovery_v1', operation, recoveryTargetBytes,
|
|
84
|
-
this.enrollment.enrollmentId, this.enrollment.coordinatorBootId, this.enrollment.authEpoch,
|
|
85
|
-
randomBytes(32).toString('hex')]);
|
|
86
|
-
this.pending.set(message, { deadline: now + 30_000, operation });
|
|
87
|
-
return Object.freeze({ message });
|
|
88
|
-
}
|
|
89
|
-
authorize(message: string, signature: string): RecoveryOwnerGrant {
|
|
90
|
-
const now = this.now();
|
|
91
|
-
const entry = this.pending.get(message);
|
|
92
|
-
this.pending.delete(message); // Every verification attempt burns the challenge.
|
|
93
|
-
if (!entry || now >= entry.deadline || !/^[a-f0-9]{128}$/.test(signature) ||
|
|
94
|
-
!verify(null, Buffer.from(message), this.key, Buffer.from(signature, 'hex'))) {
|
|
95
|
-
throw new Error('recovery_owner_signature_rejected');
|
|
96
|
-
}
|
|
97
|
-
const grant = Object.freeze({ purpose: 'operator_recovery_v1' as const, operation: entry.operation });
|
|
98
|
-
this.grants.set(grant, entry);
|
|
99
|
-
return grant;
|
|
100
|
-
}
|
|
101
|
-
assertGrant(grant: unknown): asserts grant is RecoveryOwnerGrant {
|
|
102
|
-
const now = this.now();
|
|
103
|
-
const entry = typeof grant === 'object' && grant !== null ? this.grants.get(grant) : undefined;
|
|
104
|
-
if (!entry || now >= entry.deadline) throw new Error('recovery_owner_grant_rejected');
|
|
105
|
-
}
|
|
106
|
-
/** Burn synchronously before any work or await. The private continuation
|
|
107
|
-
* rechecks the ORIGINAL deadline and revocation; it cannot mint a new grant. */
|
|
108
|
-
reserve(grant: unknown, operation: RecoveryOwnerOperation): () => void {
|
|
109
|
-
this.assertGrant(grant);
|
|
110
|
-
const entry = this.grants.get(grant as object)!;
|
|
111
|
-
this.grants.delete(grant as object);
|
|
112
|
-
if (entry.operation !== operation) throw new Error('recovery_owner_operation_rejected');
|
|
113
|
-
return () => {
|
|
114
|
-
if (this.now() >= entry.deadline) throw new Error('recovery_owner_grant_rejected');
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
consume(grant: unknown): void {
|
|
118
|
-
this.assertGrant(grant);
|
|
119
|
-
this.grants.delete(grant as object);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export interface RecoveryHostBinding {
|
|
124
|
-
namespace: string; endpoint: string; hostBootId: string; workerDaemonId: string;
|
|
125
|
-
}
|
|
126
|
-
export interface RecoveryPhysicalProof extends RecoveryHostBinding {
|
|
127
|
-
protocol: 1;
|
|
128
|
-
verdict: 'ABSENT' | 'LIVE' | 'UNKNOWN';
|
|
129
|
-
reason: string;
|
|
130
|
-
nonce: string;
|
|
131
|
-
fenceDigest: string;
|
|
132
|
-
sessionId: string;
|
|
133
|
-
providerSessionId: string;
|
|
134
|
-
}
|