@ddtcorex/dsh-maestro-core 0.10.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 +21 -0
- package/README.md +209 -0
- package/cordis.patch.yml +43 -0
- package/lib/bin.d.ts +2 -0
- package/lib/bin.js +3 -0
- package/lib/boot-guard.d.ts +33 -0
- package/lib/boot-guard.js +68 -0
- package/lib/boot-lock.d.ts +56 -0
- package/lib/boot-lock.js +155 -0
- package/lib/cli.d.ts +31 -0
- package/lib/cli.js +336 -0
- package/lib/client.js +2901 -0
- package/lib/config/index.d.ts +34 -0
- package/lib/config/index.js +62 -0
- package/lib/config/service.d.ts +18 -0
- package/lib/config/service.js +28 -0
- package/lib/config.d.ts +1 -0
- package/lib/config.js +19 -0
- package/lib/daemon-freshness.d.ts +48 -0
- package/lib/daemon-freshness.js +122 -0
- package/lib/debug-agent.d.ts +17 -0
- package/lib/debug-agent.js +144 -0
- package/lib/dsh-session.d.ts +26 -0
- package/lib/dsh-session.js +45 -0
- package/lib/guard/config.d.ts +82 -0
- package/lib/guard/config.js +211 -0
- package/lib/guard/decide.d.ts +30 -0
- package/lib/guard/decide.js +38 -0
- package/lib/guard/full-scan-tool.d.ts +6 -0
- package/lib/guard/full-scan-tool.js +65 -0
- package/lib/guard/index.d.ts +85 -0
- package/lib/guard/index.js +254 -0
- package/lib/guard/journal.d.ts +146 -0
- package/lib/guard/journal.js +398 -0
- package/lib/guard/migrate.d.ts +15 -0
- package/lib/guard/migrate.js +42 -0
- package/lib/guard/parse.d.ts +193 -0
- package/lib/guard/parse.js +1103 -0
- package/lib/guard/paths.d.ts +104 -0
- package/lib/guard/paths.js +254 -0
- package/lib/guard/permission-policy.d.ts +10 -0
- package/lib/guard/permission-policy.js +21 -0
- package/lib/guard/redact.d.ts +25 -0
- package/lib/guard/redact.js +52 -0
- package/lib/guard/rules.d.ts +65 -0
- package/lib/guard/rules.js +832 -0
- package/lib/guard/status-tool.d.ts +54 -0
- package/lib/guard/status-tool.js +195 -0
- package/lib/guard/tiers.d.ts +2 -0
- package/lib/guard/tiers.js +1 -0
- package/lib/guard/validators.d.ts +4 -0
- package/lib/guard/validators.js +45 -0
- package/lib/health-poller.d.ts +90 -0
- package/lib/health-poller.js +430 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +7 -0
- package/lib/intents.d.ts +32 -0
- package/lib/intents.js +49 -0
- package/lib/notifier.d.ts +12 -0
- package/lib/notifier.js +62 -0
- package/lib/paths.d.ts +13 -0
- package/lib/paths.js +70 -0
- package/lib/plugin.d.ts +250 -0
- package/lib/plugin.js +1126 -0
- package/lib/preset.d.ts +73 -0
- package/lib/preset.js +158 -0
- package/lib/report.d.ts +11 -0
- package/lib/report.js +58 -0
- package/lib/restart-exec.d.ts +35 -0
- package/lib/restart-exec.js +60 -0
- package/lib/restart-guards.d.ts +39 -0
- package/lib/restart-guards.js +150 -0
- package/lib/restart-tool.d.ts +124 -0
- package/lib/restart-tool.js +539 -0
- package/lib/restart-web.d.ts +26 -0
- package/lib/restart-web.js +58 -0
- package/lib/resume-log.d.ts +24 -0
- package/lib/resume-log.js +18 -0
- package/lib/resume-tools.d.ts +131 -0
- package/lib/resume-tools.js +337 -0
- package/lib/resume.d.ts +33 -0
- package/lib/resume.js +221 -0
- package/lib/scan.d.ts +20 -0
- package/lib/scan.js +71 -0
- package/lib/self-kill-guard.d.ts +81 -0
- package/lib/self-kill-guard.js +208 -0
- package/lib/session-health.d.ts +89 -0
- package/lib/session-health.js +274 -0
- package/lib/session-log-file.d.ts +22 -0
- package/lib/session-log-file.js +74 -0
- package/lib/skill-provider.d.ts +6 -0
- package/lib/skill-provider.js +73 -0
- package/lib/snapshot.d.ts +59 -0
- package/lib/snapshot.js +358 -0
- package/lib/source.d.ts +19 -0
- package/lib/source.js +19 -0
- package/lib/store/index.d.ts +42 -0
- package/lib/store/index.js +340 -0
- package/lib/store/legacy.d.ts +17 -0
- package/lib/store/legacy.js +85 -0
- package/lib/supervisor.d.ts +119 -0
- package/lib/supervisor.js +741 -0
- package/lib/sync/backup-config.d.ts +55 -0
- package/lib/sync/backup-config.js +119 -0
- package/lib/sync/backup-service.d.ts +110 -0
- package/lib/sync/backup-service.js +440 -0
- package/lib/sync/bidirectional.d.ts +39 -0
- package/lib/sync/bidirectional.js +25 -0
- package/lib/sync/cli.d.ts +38 -0
- package/lib/sync/cli.js +536 -0
- package/lib/sync/config.d.ts +77 -0
- package/lib/sync/config.js +90 -0
- package/lib/sync/fingerprint.d.ts +29 -0
- package/lib/sync/fingerprint.js +65 -0
- package/lib/sync/hashing.d.ts +9 -0
- package/lib/sync/hashing.js +47 -0
- package/lib/sync/index.d.ts +6 -0
- package/lib/sync/index.js +634 -0
- package/lib/sync/machine-id.d.ts +29 -0
- package/lib/sync/machine-id.js +66 -0
- package/lib/sync/merge.d.ts +33 -0
- package/lib/sync/merge.js +88 -0
- package/lib/sync/peer-host.d.ts +22 -0
- package/lib/sync/peer-host.js +62 -0
- package/lib/sync/process-runner.d.ts +31 -0
- package/lib/sync/process-runner.js +161 -0
- package/lib/sync/remote-agent.d.ts +42 -0
- package/lib/sync/remote-agent.js +217 -0
- package/lib/sync/remote-cache.d.ts +18 -0
- package/lib/sync/remote-cache.js +60 -0
- package/lib/sync/remote-manifest.d.ts +8 -0
- package/lib/sync/remote-manifest.js +64 -0
- package/lib/sync/s3-object-store.d.ts +38 -0
- package/lib/sync/s3-object-store.js +126 -0
- package/lib/sync/session-merge.d.ts +18 -0
- package/lib/sync/session-merge.js +191 -0
- package/lib/sync/session-plan.d.ts +29 -0
- package/lib/sync/session-plan.js +213 -0
- package/lib/sync/sigv4.d.ts +20 -0
- package/lib/sync/sigv4.js +57 -0
- package/lib/sync/snapshot.d.ts +21 -0
- package/lib/sync/snapshot.js +176 -0
- package/lib/sync/ssh-mux.d.ts +12 -0
- package/lib/sync/ssh-mux.js +48 -0
- package/lib/sync/sync-plan.d.ts +24 -0
- package/lib/sync/sync-plan.js +366 -0
- package/lib/sync/sync-service.d.ts +177 -0
- package/lib/sync/sync-service.js +819 -0
- package/lib/sync/sync-types.d.ts +87 -0
- package/lib/sync/sync-types.js +1 -0
- package/lib/sync/transport.d.ts +75 -0
- package/lib/sync/transport.js +200 -0
- package/lib/sync/tunnel-restore.d.ts +77 -0
- package/lib/sync/tunnel-restore.js +142 -0
- package/lib/sync/validation.d.ts +10 -0
- package/lib/sync/validation.js +83 -0
- package/lib/tool-view.d.ts +62 -0
- package/lib/tool-view.js +70 -0
- package/lib/types/client/auto-reload.d.ts +8 -0
- package/lib/types/client/auto-reload.d.ts.map +1 -0
- package/lib/types/client/config/MaestroSettings.d.ts +25 -0
- package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
- package/lib/types/client/config/components/BrandMark.d.ts +50 -0
- package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
- package/lib/types/client/config/guard-view.d.ts +83 -0
- package/lib/types/client/config/guard-view.d.ts.map +1 -0
- package/lib/types/client/config/index.d.ts +20 -0
- package/lib/types/client/config/index.d.ts.map +1 -0
- package/lib/types/client/config/maestro-mark.d.ts +29 -0
- package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
- package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
- package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +16 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/SyncPanel.d.ts +12 -0
- package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
- package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
- package/lib/types/client/sync/index.d.ts +10 -0
- package/lib/types/client/sync/index.d.ts.map +1 -0
- package/lib/types/client/sync/ui.d.ts +79 -0
- package/lib/types/client/sync/ui.d.ts.map +1 -0
- package/lib/types/client/sync/use-backup.d.ts +50 -0
- package/lib/types/client/sync/use-backup.d.ts.map +1 -0
- package/lib/types/client/sync/use-sync.d.ts +88 -0
- package/lib/types/client/sync/use-sync.d.ts.map +1 -0
- package/package.json +89 -0
- package/skills/dsh-safe-restart/SKILL.md +206 -0
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
- package/src/client/auto-reload.ts +104 -0
- package/src/client/config/MaestroSettings.tsx +892 -0
- package/src/client/config/components/BrandMark.tsx +94 -0
- package/src/client/config/guard-view.ts +187 -0
- package/src/client/config/index.tsx +109 -0
- package/src/client/config/maestro-mark.ts +37 -0
- package/src/client/config/settings-nav-icon.ts +68 -0
- package/src/client/index.tsx +33 -0
- package/src/client/sync/R2SyncPanel.tsx +260 -0
- package/src/client/sync/SyncPanel.tsx +422 -0
- package/src/client/sync/confirm-dialog.tsx +202 -0
- package/src/client/sync/index.tsx +336 -0
- package/src/client/sync/ui.tsx +313 -0
- package/src/client/sync/use-backup.ts +207 -0
- package/src/client/sync/use-sync.ts +502 -0
- package/src/host/bin.ts +3 -0
- package/src/host/boot-guard.ts +76 -0
- package/src/host/boot-lock.ts +155 -0
- package/src/host/cli.ts +288 -0
- package/src/host/config/index.ts +78 -0
- package/src/host/config/service.ts +40 -0
- package/src/host/config.ts +18 -0
- package/src/host/daemon-freshness.ts +143 -0
- package/src/host/debug-agent.ts +145 -0
- package/src/host/dsh-session.ts +56 -0
- package/src/host/dsh-skill.d.ts +44 -0
- package/src/host/guard/augment.d.ts +33 -0
- package/src/host/guard/config.ts +244 -0
- package/src/host/guard/decide.ts +40 -0
- package/src/host/guard/full-scan-tool.ts +61 -0
- package/src/host/guard/index.ts +281 -0
- package/src/host/guard/journal.ts +440 -0
- package/src/host/guard/migrate.ts +41 -0
- package/src/host/guard/parse.ts +1150 -0
- package/src/host/guard/paths.ts +239 -0
- package/src/host/guard/permission-policy.ts +15 -0
- package/src/host/guard/redact.ts +64 -0
- package/src/host/guard/rules.ts +891 -0
- package/src/host/guard/status-tool.ts +229 -0
- package/src/host/guard/tiers.ts +2 -0
- package/src/host/guard/validators.ts +29 -0
- package/src/host/health-poller.ts +446 -0
- package/src/host/index.ts +7 -0
- package/src/host/intents.ts +67 -0
- package/src/host/notifier.ts +71 -0
- package/src/host/paths.ts +70 -0
- package/src/host/plugin.ts +1097 -0
- package/src/host/preset.ts +170 -0
- package/src/host/report.ts +71 -0
- package/src/host/restart-exec.ts +81 -0
- package/src/host/restart-guards.ts +150 -0
- package/src/host/restart-tool.ts +483 -0
- package/src/host/restart-web.ts +72 -0
- package/src/host/resume-log.ts +39 -0
- package/src/host/resume-tools.ts +385 -0
- package/src/host/resume.ts +204 -0
- package/src/host/scan.ts +61 -0
- package/src/host/self-kill-guard.ts +216 -0
- package/src/host/session-health.ts +236 -0
- package/src/host/session-log-file.ts +77 -0
- package/src/host/skill-provider.ts +69 -0
- package/src/host/snapshot.ts +337 -0
- package/src/host/source.ts +19 -0
- package/src/host/store/index.ts +348 -0
- package/src/host/store/legacy.ts +96 -0
- package/src/host/supervisor.ts +720 -0
- package/src/host/sync/backup-config.ts +159 -0
- package/src/host/sync/backup-service.ts +453 -0
- package/src/host/sync/bidirectional.ts +66 -0
- package/src/host/sync/cli.ts +539 -0
- package/src/host/sync/config.ts +119 -0
- package/src/host/sync/fingerprint.ts +83 -0
- package/src/host/sync/hashing.ts +58 -0
- package/src/host/sync/index.ts +737 -0
- package/src/host/sync/machine-id.ts +81 -0
- package/src/host/sync/merge.ts +102 -0
- package/src/host/sync/peer-host.ts +65 -0
- package/src/host/sync/process-runner.ts +177 -0
- package/src/host/sync/remote-agent.ts +213 -0
- package/src/host/sync/remote-cache.ts +68 -0
- package/src/host/sync/remote-manifest.ts +70 -0
- package/src/host/sync/s3-object-store.ts +144 -0
- package/src/host/sync/session-merge.ts +220 -0
- package/src/host/sync/session-plan.ts +237 -0
- package/src/host/sync/sigv4.ts +81 -0
- package/src/host/sync/snapshot.ts +162 -0
- package/src/host/sync/ssh-mux.ts +56 -0
- package/src/host/sync/sync-plan.ts +366 -0
- package/src/host/sync/sync-service.ts +855 -0
- package/src/host/sync/sync-types.ts +102 -0
- package/src/host/sync/transport.ts +261 -0
- package/src/host/sync/tunnel-restore.ts +160 -0
- package/src/host/sync/validation.ts +91 -0
- package/src/host/tool-view.ts +98 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Binary-safe session planning for DSH Zstd artifacts.
|
|
3
|
+
* Bytes remain bytes: .jsonl.zstd is staged and merged only through validated Zstd artifact API.
|
|
4
|
+
* Session handling is Buffer/path-only and preserves DSH standalone checksummed Zstd header frame.
|
|
5
|
+
*/
|
|
6
|
+
import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib';
|
|
7
|
+
|
|
8
|
+
const ZSTD_MAGIC = 0xFD2FB528;
|
|
9
|
+
const ZSTD_CHECKSUM_OPTIONS = {
|
|
10
|
+
params: { [constants.ZSTD_c_checksumFlag]: 1 },
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export interface SessionIdentity {
|
|
14
|
+
/** decompressed header line Buffer (UTF-8 without trailing newline) */
|
|
15
|
+
header: Buffer;
|
|
16
|
+
sessionId: string;
|
|
17
|
+
cwd: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface ZstdFrameRange {
|
|
21
|
+
start: number;
|
|
22
|
+
end: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Locate complete Zstd frames, throwing on corrupt/truncated structure. Never converts Zstd bytes to string. */
|
|
26
|
+
function scanZstdFrames(source: Buffer): ZstdFrameRange[] {
|
|
27
|
+
const frames: ZstdFrameRange[] = [];
|
|
28
|
+
let offset = 0;
|
|
29
|
+
|
|
30
|
+
while (offset < source.length) {
|
|
31
|
+
const start = offset;
|
|
32
|
+
if (source.length - offset < 4 || source.readUInt32LE(offset) !== ZSTD_MAGIC) {
|
|
33
|
+
throw new Error('corrupt Zstandard session artifact');
|
|
34
|
+
}
|
|
35
|
+
if (source.length - offset < 5) {
|
|
36
|
+
throw new Error('incomplete Zstandard frame header');
|
|
37
|
+
}
|
|
38
|
+
offset += 4;
|
|
39
|
+
const descriptor = source.readUInt8(offset++);
|
|
40
|
+
if ((descriptor & 0x18) !== 0) throw new Error('corrupt Zstandard frame descriptor');
|
|
41
|
+
|
|
42
|
+
const contentSizeFlag = descriptor >>> 6;
|
|
43
|
+
const singleSegment = (descriptor & 0x20) !== 0;
|
|
44
|
+
const dictionaryFlag = descriptor & 0x03;
|
|
45
|
+
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
|
|
46
|
+
const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
|
|
47
|
+
const frameHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
|
|
48
|
+
if (source.length - offset < frameHeaderBytes) throw new Error('incomplete Zstandard frame header');
|
|
49
|
+
offset += frameHeaderBytes;
|
|
50
|
+
|
|
51
|
+
for (;;) {
|
|
52
|
+
if (source.length - offset < 3) throw new Error('incomplete Zstandard frame block');
|
|
53
|
+
const blockHeader = source.readUIntLE(offset, 3);
|
|
54
|
+
offset += 3;
|
|
55
|
+
const lastBlock = (blockHeader & 1) !== 0;
|
|
56
|
+
const blockType = (blockHeader >>> 1) & 0x03;
|
|
57
|
+
const blockSize = blockHeader >>> 3;
|
|
58
|
+
if (blockType === 3) throw new Error('corrupt Zstandard frame block');
|
|
59
|
+
const payloadBytes = blockType === 1 ? 1 : blockSize;
|
|
60
|
+
if (source.length - offset < payloadBytes) throw new Error('incomplete Zstandard frame payload');
|
|
61
|
+
offset += payloadBytes;
|
|
62
|
+
if (lastBlock) break;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if ((descriptor & 0x04) !== 0) {
|
|
66
|
+
if (source.length - offset < 4) throw new Error('incomplete Zstandard frame checksum');
|
|
67
|
+
offset += 4;
|
|
68
|
+
}
|
|
69
|
+
frames.push({ start, end: offset });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return frames;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function parseHeaderLine(headerBytes: Buffer, label: string): { line: string; record: Record<string, unknown> } {
|
|
76
|
+
if (headerBytes.length === 0 || headerBytes[headerBytes.length - 1] !== 0x0A) {
|
|
77
|
+
throw new Error(`${label} session artifact has no standalone header frame`);
|
|
78
|
+
}
|
|
79
|
+
if (headerBytes.indexOf(0x0A) !== headerBytes.length - 1) {
|
|
80
|
+
throw new Error(`${label} session artifact header frame not standalone`);
|
|
81
|
+
}
|
|
82
|
+
const line = headerBytes.subarray(0, -1).toString('utf8');
|
|
83
|
+
let value: unknown;
|
|
84
|
+
try {
|
|
85
|
+
value = JSON.parse(line);
|
|
86
|
+
} catch {
|
|
87
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
88
|
+
}
|
|
89
|
+
const record = value as Record<string, unknown> | null;
|
|
90
|
+
const hasValidInteger = (field: string) => {
|
|
91
|
+
const v = (record as any)?.[field];
|
|
92
|
+
return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && !Object.is(v, -0);
|
|
93
|
+
};
|
|
94
|
+
if (
|
|
95
|
+
record === null ||
|
|
96
|
+
typeof record !== 'object' ||
|
|
97
|
+
(record as any).type !== 'session' ||
|
|
98
|
+
typeof (record as any).version !== 'number' ||
|
|
99
|
+
typeof (record as any).id !== 'string' ||
|
|
100
|
+
!hasValidInteger('createdAt') ||
|
|
101
|
+
!hasValidInteger('delegationDepth') ||
|
|
102
|
+
((record as any).origin !== undefined && (record as any).origin !== 'subagent') ||
|
|
103
|
+
((record as any).agentPreset !== undefined && typeof (record as any).agentPreset !== 'string')
|
|
104
|
+
) {
|
|
105
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
106
|
+
}
|
|
107
|
+
if ((record as any).cwd !== undefined && typeof (record as any).cwd !== 'string') {
|
|
108
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
109
|
+
}
|
|
110
|
+
return { line, record: record as Record<string, unknown> };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Validates Zstd header frame and extracts identity.
|
|
115
|
+
* - Validates Zstd magic and frame structure via checksum-aware decompression.
|
|
116
|
+
* - Decompresses only the first frame (standalone header) and validates JSONL header.
|
|
117
|
+
* - Never converts raw Zstd bytes to UTF-8 string.
|
|
118
|
+
*/
|
|
119
|
+
export function parseSessionIdentity(buffer: Buffer): SessionIdentity {
|
|
120
|
+
if (!Buffer.isBuffer(buffer)) throw new Error('session buffer must be Buffer');
|
|
121
|
+
if (buffer.length === 0) throw new Error('empty session buffer');
|
|
122
|
+
if (buffer.length < 4) throw new Error('corrupt Zstandard session artifact');
|
|
123
|
+
if (buffer.readUInt32LE(0) !== ZSTD_MAGIC) throw new Error('corrupt Zstandard session artifact');
|
|
124
|
+
|
|
125
|
+
const frames = scanZstdFrames(buffer);
|
|
126
|
+
if (frames.length === 0) throw new Error('session artifact has no Zstandard frames');
|
|
127
|
+
|
|
128
|
+
let headerBytes: Buffer;
|
|
129
|
+
try {
|
|
130
|
+
headerBytes = zstdDecompressSync(buffer.subarray(frames[0]!.start, frames[0]!.end));
|
|
131
|
+
} catch (e: any) {
|
|
132
|
+
throw new Error(`invalid Zstd header frame: ${e?.message ?? String(e)}`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const { line, record } = parseHeaderLine(headerBytes, 'session');
|
|
136
|
+
|
|
137
|
+
const sessionId = String((record as any).id);
|
|
138
|
+
const cwd = typeof (record as any).cwd === 'string' ? String((record as any).cwd) : '';
|
|
139
|
+
const header = Buffer.from(line, 'utf8');
|
|
140
|
+
return { header, sessionId, cwd };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Compare header identity, not just path.
|
|
145
|
+
* Returns true if both buffers represent the same session (same id, cwd, and header line).
|
|
146
|
+
*/
|
|
147
|
+
export function isSameSession(a: Buffer, b: Buffer): boolean {
|
|
148
|
+
try {
|
|
149
|
+
const idA = parseSessionIdentity(a);
|
|
150
|
+
const idB = parseSessionIdentity(b);
|
|
151
|
+
return idA.sessionId === idB.sessionId && idA.cwd === idB.cwd && idA.header.equals(idB.header);
|
|
152
|
+
} catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function mergePlaintextLines(localText: string, remoteText: string): { merged: string; added: number } {
|
|
158
|
+
const localLines = String(localText ?? '')
|
|
159
|
+
.split('\n')
|
|
160
|
+
.filter((line) => line.length > 0);
|
|
161
|
+
const remoteLines = String(remoteText ?? '')
|
|
162
|
+
.split('\n')
|
|
163
|
+
.filter((line) => line.length > 0);
|
|
164
|
+
|
|
165
|
+
const seen = new Set<string>(localLines);
|
|
166
|
+
const mergedArr = [...localLines];
|
|
167
|
+
let added = 0;
|
|
168
|
+
|
|
169
|
+
for (const line of remoteLines) {
|
|
170
|
+
if (!seen.has(line)) {
|
|
171
|
+
seen.add(line);
|
|
172
|
+
mergedArr.push(line);
|
|
173
|
+
added++;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const merged = mergedArr.length > 0 ? mergedArr.join('\n') + '\n' : '';
|
|
178
|
+
return { merged, added };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Merge two valid session buffers via binary path and return merged Buffer with added count.
|
|
183
|
+
* - Validates both buffers via validated Zstd artifact API (checksum, header frame).
|
|
184
|
+
* - Preserves DSH standalone checksummed Zstd header frame (first frame is header alone).
|
|
185
|
+
* - Never converts Zstd bytes to UTF-8 string; only decompressed plaintext is stringified for line union.
|
|
186
|
+
* - Throws if headers differ (conflict) or either buffer is invalid/truncated.
|
|
187
|
+
*/
|
|
188
|
+
export function mergeSessionBuffers(local: Buffer, remote: Buffer): { merged: Buffer; added: number } {
|
|
189
|
+
const localId = parseSessionIdentity(local);
|
|
190
|
+
const remoteId = parseSessionIdentity(remote);
|
|
191
|
+
|
|
192
|
+
if (localId.sessionId !== remoteId.sessionId || localId.cwd !== remoteId.cwd || !localId.header.equals(remoteId.header)) {
|
|
193
|
+
throw new Error('cannot merge session buffers with different headers');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const localFrames = scanZstdFrames(local);
|
|
197
|
+
const remoteFrames = scanZstdFrames(remote);
|
|
198
|
+
|
|
199
|
+
const localPlainBufs: Buffer[] = [];
|
|
200
|
+
for (const f of localFrames) {
|
|
201
|
+
try {
|
|
202
|
+
localPlainBufs.push(zstdDecompressSync(local.subarray(f.start, f.end)));
|
|
203
|
+
} catch (e: any) {
|
|
204
|
+
throw new Error(`local session decompress failed: ${e?.message ?? String(e)}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const remotePlainBufs: Buffer[] = [];
|
|
208
|
+
for (const f of remoteFrames) {
|
|
209
|
+
try {
|
|
210
|
+
remotePlainBufs.push(zstdDecompressSync(remote.subarray(f.start, f.end)));
|
|
211
|
+
} catch (e: any) {
|
|
212
|
+
throw new Error(`remote session decompress failed: ${e?.message ?? String(e)}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const localText = Buffer.concat(localPlainBufs).toString('utf8');
|
|
217
|
+
const remoteText = Buffer.concat(remotePlainBufs).toString('utf8');
|
|
218
|
+
|
|
219
|
+
const { merged, added } = mergePlaintextLines(localText, remoteText);
|
|
220
|
+
|
|
221
|
+
if (added === 0) {
|
|
222
|
+
return { merged: local, added: 0 };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const headerLine = localId.header.toString('utf8');
|
|
226
|
+
if (!merged.startsWith(headerLine + '\n')) {
|
|
227
|
+
throw new Error('merged session artifact lost its header');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const body = merged.slice(headerLine.length + 1);
|
|
231
|
+
const frames: Buffer[] = [zstdCompressSync(headerLine + '\n', ZSTD_CHECKSUM_OPTIONS as any)];
|
|
232
|
+
if (body.length > 0) {
|
|
233
|
+
frames.push(zstdCompressSync(body, ZSTD_CHECKSUM_OPTIONS as any));
|
|
234
|
+
}
|
|
235
|
+
const mergedBuf = Buffer.concat(frames);
|
|
236
|
+
return { merged: mergedBuf, added };
|
|
237
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// src/host/sigv4.ts — AWS Signature Version 4 (S3 service) with zero deps.
|
|
2
|
+
//
|
|
3
|
+
// Computes the canonical request, the string-to-sign, and the signing key
|
|
4
|
+
// chain exactly per the AWS docs; the pinned known-answer test keeps it honest.
|
|
5
|
+
// ETag is a CAS/version token, never a content checksum — our content
|
|
6
|
+
// integrity lives in SHA-256 (blob keys + manifest metadata).
|
|
7
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
8
|
+
|
|
9
|
+
export function sha256Hex(data: string | Buffer): string {
|
|
10
|
+
return createHash('sha256').update(data).digest('hex');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function hmac(key: Buffer, data: string): Buffer {
|
|
14
|
+
return createHmac('sha256', key).update(data).digest();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function isoDate(d: Date): string {
|
|
18
|
+
return d.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z'); // YYYYMMDDTHHMMSSZ
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function scopeDate(d: Date): string {
|
|
22
|
+
return isoDate(d).slice(0, 8);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface SignRequestOpts {
|
|
26
|
+
method: string;
|
|
27
|
+
host: string;
|
|
28
|
+
path: string;
|
|
29
|
+
query?: string;
|
|
30
|
+
headers: Record<string, string>;
|
|
31
|
+
bodySha256: string;
|
|
32
|
+
region: string;
|
|
33
|
+
service: string;
|
|
34
|
+
accessKeyId: string;
|
|
35
|
+
secretAccessKey: string;
|
|
36
|
+
now: Date;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface SignedRequest {
|
|
40
|
+
authorization: string;
|
|
41
|
+
amzDate: string;
|
|
42
|
+
xAmzContentSha256: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function signRequest(opts: SignRequestOpts): SignedRequest {
|
|
46
|
+
const amzDate = isoDate(opts.now);
|
|
47
|
+
const date = scopeDate(opts.now);
|
|
48
|
+
const raw: Record<string, string> = {
|
|
49
|
+
host: opts.host,
|
|
50
|
+
'x-amz-content-sha256': opts.bodySha256,
|
|
51
|
+
'x-amz-date': amzDate,
|
|
52
|
+
...opts.headers,
|
|
53
|
+
};
|
|
54
|
+
// Signed headers are lower-cased; look up through a normalized map so mixed
|
|
55
|
+
// case (e.g. 'Content-Length') never hits an undefined value.
|
|
56
|
+
const headers: Record<string, string> = {};
|
|
57
|
+
for (const [k, v] of Object.entries(raw)) headers[k.toLowerCase()] = v;
|
|
58
|
+
const signedKeys = Object.keys(headers).sort();
|
|
59
|
+
const canonicalHeaders = signedKeys.map((k) => `${k}:${headers[k]!.trim().replace(/\s+/g, ' ')}\n`).join('');
|
|
60
|
+
const canonicalQuery = (opts.query ?? '').split('&').filter(Boolean).sort().join('&');
|
|
61
|
+
const canonicalRequest = [
|
|
62
|
+
opts.method.toUpperCase(),
|
|
63
|
+
opts.path,
|
|
64
|
+
canonicalQuery,
|
|
65
|
+
canonicalHeaders,
|
|
66
|
+
signedKeys.join(';'),
|
|
67
|
+
opts.bodySha256,
|
|
68
|
+
].join('\n');
|
|
69
|
+
const scope = `${date}/${opts.region}/${opts.service}/aws4_request`;
|
|
70
|
+
const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonicalRequest)].join('\n');
|
|
71
|
+
const kDate = hmac(Buffer.from(`AWS4${opts.secretAccessKey}`, 'utf8'), date);
|
|
72
|
+
const kRegion = hmac(kDate, opts.region);
|
|
73
|
+
const kService = hmac(kRegion, opts.service);
|
|
74
|
+
const kSigning = hmac(kService, 'aws4_request');
|
|
75
|
+
const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex');
|
|
76
|
+
return {
|
|
77
|
+
authorization: `AWS4-HMAC-SHA256 Credential=${opts.accessKeyId}/${scope}, SignedHeaders=${signedKeys.join(';')}, Signature=${signature}`,
|
|
78
|
+
amzDate,
|
|
79
|
+
xAmzContentSha256: opts.bodySha256,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { normalizeEligiblePath } from './validation.js';
|
|
4
|
+
import type { FileSnapshot } from './sync-types.js';
|
|
5
|
+
|
|
6
|
+
export function hashBuffer(buf: Buffer): string {
|
|
7
|
+
return createHash('sha256').update(buf).digest('hex');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function kindForPath(p: string): FileSnapshot['kind'] {
|
|
11
|
+
const normalized = p; // caller should have validated; we still dispatch by suffix
|
|
12
|
+
if (normalized.endsWith('.zstd')) return 'session';
|
|
13
|
+
if (normalized.endsWith('.jsonl')) return 'jsonl';
|
|
14
|
+
return 'memory';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function snapshotFile(validatedPath: string, content: Buffer): FileSnapshot {
|
|
18
|
+
const normalized = normalizeEligiblePath(validatedPath);
|
|
19
|
+
const sha256 = hashBuffer(content);
|
|
20
|
+
const kind = kindForPath(normalized);
|
|
21
|
+
return { path: normalized, sha256, size: content.length, kind };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Collect snapshots for all eligible files under root using the provided fs.
|
|
26
|
+
* - Walks recursively via fs.readdirSync/statSync/readFileSync when available.
|
|
27
|
+
* - Validates each discovered relative path via normalizeEligiblePath.
|
|
28
|
+
* - Hashes file bytes with SHA-256 and records kind.
|
|
29
|
+
* Returns sorted snapshots by path for determinism.
|
|
30
|
+
*/
|
|
31
|
+
export function collectSnapshots(root: string, fs: any): FileSnapshot[] {
|
|
32
|
+
const result: FileSnapshot[] = [];
|
|
33
|
+
if (!root || typeof root !== 'string') return result;
|
|
34
|
+
const fsMod = fs ?? {};
|
|
35
|
+
// Check root exists
|
|
36
|
+
try {
|
|
37
|
+
if (fsMod.existsSync && !fsMod.existsSync(root)) return [];
|
|
38
|
+
} catch {
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const walk = (dir: string, base: string) => {
|
|
43
|
+
let entries: any[] = [];
|
|
44
|
+
try {
|
|
45
|
+
if (typeof fsMod.readdirSync !== 'function') return;
|
|
46
|
+
const raw = fsMod.readdirSync(dir, { withFileTypes: true } as any);
|
|
47
|
+
if (!raw || raw.length === 0) return;
|
|
48
|
+
// handle string[] mode (no withFileTypes)
|
|
49
|
+
if (typeof raw[0] === 'string') {
|
|
50
|
+
for (const name of raw as unknown as string[]) {
|
|
51
|
+
const full = path.join(dir, name);
|
|
52
|
+
let st: any = null;
|
|
53
|
+
try {
|
|
54
|
+
st = fsMod.statSync ? fsMod.statSync(full) : null;
|
|
55
|
+
} catch {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const isDir = st && typeof st.isDirectory === 'function' ? st.isDirectory() : false;
|
|
59
|
+
if (isDir) walk(full, path.join(base, name));
|
|
60
|
+
else {
|
|
61
|
+
const relPosix = path.join(base, name).split(path.sep).join('/');
|
|
62
|
+
try {
|
|
63
|
+
normalizeEligiblePath(relPosix);
|
|
64
|
+
} catch {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
let buf: Buffer;
|
|
69
|
+
if (typeof fsMod.readFileSync === 'function') {
|
|
70
|
+
const data = fsMod.readFileSync(full);
|
|
71
|
+
buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
|
|
72
|
+
} else {
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
result.push(snapshotFile(relPosix, buf));
|
|
76
|
+
} catch {
|
|
77
|
+
// skip unreadable
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
for (const ent of raw as any[]) {
|
|
84
|
+
const name = ent.name ?? String(ent);
|
|
85
|
+
const full = path.join(dir, name);
|
|
86
|
+
const isDir = typeof ent.isDirectory === 'function' ? ent.isDirectory() : false;
|
|
87
|
+
if (isDir) {
|
|
88
|
+
walk(full, path.join(base, name));
|
|
89
|
+
} else {
|
|
90
|
+
const relPosix = path.join(base, name).split(path.sep).join('/');
|
|
91
|
+
try {
|
|
92
|
+
normalizeEligiblePath(relPosix);
|
|
93
|
+
} catch {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
let buf: Buffer;
|
|
98
|
+
if (typeof fsMod.readFileSync === 'function') {
|
|
99
|
+
const data = fsMod.readFileSync(full);
|
|
100
|
+
buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
|
|
101
|
+
} else continue;
|
|
102
|
+
result.push(snapshotFile(relPosix, buf));
|
|
103
|
+
} catch {
|
|
104
|
+
// skip
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
// walk errors are ignored
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
walk(root, '');
|
|
114
|
+
// Deterministic sort
|
|
115
|
+
result.sort((a, b) => a.path.localeCompare(b.path));
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Snapshot a specific list of validated eligible paths under root.
|
|
121
|
+
* Useful for hashing staged remote files where we already know the manifest.
|
|
122
|
+
*/
|
|
123
|
+
export function snapshotPaths(root: string, paths: string[], fs: any): FileSnapshot[] {
|
|
124
|
+
const fsMod = fs ?? {};
|
|
125
|
+
const out: FileSnapshot[] = [];
|
|
126
|
+
for (const p of paths) {
|
|
127
|
+
let normalized: string;
|
|
128
|
+
try {
|
|
129
|
+
normalized = normalizeEligiblePath(p);
|
|
130
|
+
} catch {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const full = path.join(root, normalized);
|
|
134
|
+
try {
|
|
135
|
+
if (fsMod.existsSync && !fsMod.existsSync(full)) continue;
|
|
136
|
+
if (typeof fsMod.readFileSync !== 'function') continue;
|
|
137
|
+
const data = fsMod.readFileSync(full);
|
|
138
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');
|
|
139
|
+
out.push(snapshotFile(normalized, buf));
|
|
140
|
+
} catch {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
out.sort((a, b) => a.path.localeCompare(b.path));
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Snapshot from an in-memory map of path -> Buffer (useful for testing staged remote).
|
|
150
|
+
*/
|
|
151
|
+
export function snapshotFromMap(contents: Map<string, Buffer>): FileSnapshot[] {
|
|
152
|
+
const out: FileSnapshot[] = [];
|
|
153
|
+
for (const [p, buf] of contents.entries()) {
|
|
154
|
+
try {
|
|
155
|
+
out.push(snapshotFile(p, buf));
|
|
156
|
+
} catch {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
out.sort((a, b) => a.path.localeCompare(b.path));
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// src/host/ssh-mux.ts — per-operation SSH ControlMaster multiplexing.
|
|
2
|
+
//
|
|
3
|
+
// One backgrounded master (`ssh -S <socket> -o ControlMaster=yes -f -N`) owns
|
|
4
|
+
// the connection; every subsequent spawn in the operation passes `-S <socket>`
|
|
5
|
+
// (ssh slaves) or `rsync -e "ssh -S <socket>"` (single validated argv) so a
|
|
6
|
+
// multi-spawn flow pays one handshake. The socket lives in a private 0700 dir
|
|
7
|
+
// and is torn down with `-O exit`; a dead master degrades to a fresh handshake.
|
|
8
|
+
import * as fs from 'node:fs';
|
|
9
|
+
import * as path from 'node:path';
|
|
10
|
+
import { randomBytes } from 'node:crypto';
|
|
11
|
+
import type { ProcessRunner } from './process-runner.js';
|
|
12
|
+
|
|
13
|
+
export interface SshMux {
|
|
14
|
+
socketPath: string;
|
|
15
|
+
sshArgs: string[];
|
|
16
|
+
rsyncRsh: string;
|
|
17
|
+
dispose(): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function sanitizeHost(host: string): string {
|
|
21
|
+
return host.replace(/[^A-Za-z0-9._-]/g, '_');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function openSshMux(opts: { host: string; baseDir: string; runner: ProcessRunner }): Promise<SshMux> {
|
|
25
|
+
const dir = path.join(opts.baseDir, `${sanitizeHost(opts.host)}-${Math.random().toString(16).slice(2, 6)}`);
|
|
26
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
27
|
+
const socketPath = path.join(dir, 'ssh.sock');
|
|
28
|
+
const connectOpts = ['-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes'];
|
|
29
|
+
// -f backgrounds the master after auth and the process exits 0, so runner.run
|
|
30
|
+
// does not hang on a connection that is meant to stay alive.
|
|
31
|
+
const masterArgs = ['-S', socketPath, '-o', 'ControlMaster=yes', '-o', 'ControlPersist=60', ...connectOpts, opts.host, '-f', '-N'];
|
|
32
|
+
const res = await opts.runner.run('ssh', masterArgs, { timeoutMs: 8000 });
|
|
33
|
+
if (res.exitCode !== 0) {
|
|
34
|
+
try {
|
|
35
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
36
|
+
} catch {}
|
|
37
|
+
throw Object.assign(new Error(`ssh mux master failed: ${res.stderr.toString()}`), {
|
|
38
|
+
phase: 'snapshot',
|
|
39
|
+
code: 'MUX_FAILED',
|
|
40
|
+
detail: res.stderr.toString() || `exit ${res.exitCode}`,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
socketPath,
|
|
45
|
+
sshArgs: ['-S', socketPath],
|
|
46
|
+
rsyncRsh: `ssh -S ${socketPath}`,
|
|
47
|
+
dispose: async () => {
|
|
48
|
+
try {
|
|
49
|
+
await opts.runner.run('ssh', ['-S', socketPath, '-O', 'exit', opts.host], { timeoutMs: 5000 });
|
|
50
|
+
} catch {}
|
|
51
|
+
try {
|
|
52
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
53
|
+
} catch {}
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|