@ddtcorex/dsh-maestro-core 0.15.1 → 0.16.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/README.md +7 -7
- package/assets/icon.svg +4 -0
- package/cordis.patch.yml +0 -12
- package/lib/client.js +3 -1744
- package/lib/health-poller.js +1 -1
- package/lib/self-kill-guard.d.ts +25 -8
- package/lib/self-kill-guard.js +81 -27
- package/lib/types/client/config/components/BrandMark.d.ts +3 -3
- package/lib/types/client/index.d.ts.map +1 -1
- package/locale/en.json +6 -0
- package/package.json +9 -5
- package/src/client/config/components/BrandMark.tsx +3 -3
- package/src/client/index.tsx +0 -2
- package/src/host/health-poller.ts +1 -1
- package/src/host/self-kill-guard.ts +84 -26
- package/lib/sync/backup-config.d.ts +0 -55
- package/lib/sync/backup-config.js +0 -119
- package/lib/sync/backup-service.d.ts +0 -123
- package/lib/sync/backup-service.js +0 -486
- package/lib/sync/bidirectional.d.ts +0 -39
- package/lib/sync/bidirectional.js +0 -25
- package/lib/sync/cli.d.ts +0 -38
- package/lib/sync/cli.js +0 -528
- package/lib/sync/config.d.ts +0 -59
- package/lib/sync/config.js +0 -72
- package/lib/sync/fingerprint.d.ts +0 -29
- package/lib/sync/fingerprint.js +0 -65
- package/lib/sync/hashing.d.ts +0 -22
- package/lib/sync/hashing.js +0 -77
- package/lib/sync/index.d.ts +0 -6
- package/lib/sync/index.js +0 -619
- package/lib/sync/machine-id.d.ts +0 -29
- package/lib/sync/machine-id.js +0 -66
- package/lib/sync/merge.d.ts +0 -31
- package/lib/sync/merge.js +0 -86
- package/lib/sync/peer-host.d.ts +0 -22
- package/lib/sync/peer-host.js +0 -62
- package/lib/sync/process-runner.d.ts +0 -31
- package/lib/sync/process-runner.js +0 -161
- package/lib/sync/remote-agent.d.ts +0 -41
- package/lib/sync/remote-agent.js +0 -216
- package/lib/sync/remote-cache.d.ts +0 -18
- package/lib/sync/remote-cache.js +0 -60
- package/lib/sync/remote-manifest.d.ts +0 -20
- package/lib/sync/remote-manifest.js +0 -86
- package/lib/sync/s3-object-store.d.ts +0 -38
- package/lib/sync/s3-object-store.js +0 -126
- package/lib/sync/session-plan.d.ts +0 -29
- package/lib/sync/session-plan.js +0 -213
- package/lib/sync/sigv4.d.ts +0 -20
- package/lib/sync/sigv4.js +0 -57
- package/lib/sync/snapshot.d.ts +0 -16
- package/lib/sync/snapshot.js +0 -143
- package/lib/sync/ssh-mux.d.ts +0 -12
- package/lib/sync/ssh-mux.js +0 -48
- package/lib/sync/store-root.d.ts +0 -44
- package/lib/sync/store-root.js +0 -67
- package/lib/sync/sync-plan.d.ts +0 -24
- package/lib/sync/sync-plan.js +0 -366
- package/lib/sync/sync-service.d.ts +0 -183
- package/lib/sync/sync-service.js +0 -926
- package/lib/sync/sync-types.d.ts +0 -87
- package/lib/sync/sync-types.js +0 -1
- package/lib/sync/transport.d.ts +0 -75
- package/lib/sync/transport.js +0 -196
- package/lib/sync/tunnel-restore.d.ts +0 -77
- package/lib/sync/tunnel-restore.js +0 -142
- package/lib/sync/validation.d.ts +0 -12
- package/lib/sync/validation.js +0 -96
- package/lib/types/client/sync/R2SyncPanel.d.ts +0 -6
- package/lib/types/client/sync/R2SyncPanel.d.ts.map +0 -1
- package/lib/types/client/sync/SyncPanel.d.ts +0 -12
- package/lib/types/client/sync/SyncPanel.d.ts.map +0 -1
- package/lib/types/client/sync/confirm-dialog.d.ts +0 -43
- package/lib/types/client/sync/confirm-dialog.d.ts.map +0 -1
- package/lib/types/client/sync/index.d.ts +0 -10
- package/lib/types/client/sync/index.d.ts.map +0 -1
- package/lib/types/client/sync/ui.d.ts +0 -75
- package/lib/types/client/sync/ui.d.ts.map +0 -1
- package/lib/types/client/sync/use-backup.d.ts +0 -50
- package/lib/types/client/sync/use-backup.d.ts.map +0 -1
- package/lib/types/client/sync/use-sync.d.ts +0 -88
- package/lib/types/client/sync/use-sync.d.ts.map +0 -1
- package/src/client/sync/R2SyncPanel.tsx +0 -260
- package/src/client/sync/SyncPanel.tsx +0 -422
- package/src/client/sync/confirm-dialog.tsx +0 -202
- package/src/client/sync/index.tsx +0 -286
- package/src/client/sync/ui.tsx +0 -297
- package/src/client/sync/use-backup.ts +0 -207
- package/src/client/sync/use-sync.ts +0 -502
- package/src/host/sync/backup-config.ts +0 -158
- package/src/host/sync/backup-service.ts +0 -506
- package/src/host/sync/bidirectional.ts +0 -66
- package/src/host/sync/cli.ts +0 -530
- package/src/host/sync/config.ts +0 -96
- package/src/host/sync/fingerprint.ts +0 -83
- package/src/host/sync/hashing.ts +0 -91
- package/src/host/sync/index.ts +0 -697
- package/src/host/sync/machine-id.ts +0 -81
- package/src/host/sync/merge.ts +0 -99
- package/src/host/sync/peer-host.ts +0 -65
- package/src/host/sync/process-runner.ts +0 -177
- package/src/host/sync/remote-agent.ts +0 -212
- package/src/host/sync/remote-cache.ts +0 -68
- package/src/host/sync/remote-manifest.ts +0 -91
- package/src/host/sync/s3-object-store.ts +0 -144
- package/src/host/sync/session-plan.ts +0 -237
- package/src/host/sync/sigv4.ts +0 -81
- package/src/host/sync/snapshot.ts +0 -132
- package/src/host/sync/ssh-mux.ts +0 -55
- package/src/host/sync/store-root.ts +0 -83
- package/src/host/sync/sync-plan.ts +0 -366
- package/src/host/sync/sync-service.ts +0 -960
- package/src/host/sync/sync-types.ts +0 -102
- package/src/host/sync/transport.ts +0 -256
- package/src/host/sync/tunnel-restore.ts +0 -160
- package/src/host/sync/validation.ts +0 -104
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
export type SyncDirection = 'pull' | 'push';
|
|
2
|
-
|
|
3
|
-
export type SyncPhase = 'validate' | 'snapshot' | 'stage' | 'plan' | 'publish' | 'cleanup';
|
|
4
|
-
|
|
5
|
-
export interface RemoteTarget {
|
|
6
|
-
host: string;
|
|
7
|
-
dshRoot: string;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export interface SyncRequest {
|
|
11
|
-
direction: SyncDirection;
|
|
12
|
-
dryRun: boolean;
|
|
13
|
-
localRoot: string;
|
|
14
|
-
remote: RemoteTarget;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export interface SyncFailure {
|
|
18
|
-
phase: SyncPhase;
|
|
19
|
-
code: string;
|
|
20
|
-
detail: string;
|
|
21
|
-
path?: string;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export interface SyncSummary {
|
|
25
|
-
copied: number;
|
|
26
|
-
merged: number;
|
|
27
|
-
skipped: number;
|
|
28
|
-
conflicts: number;
|
|
29
|
-
added: number;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export interface FileSnapshot {
|
|
33
|
-
path: string;
|
|
34
|
-
sha256: string;
|
|
35
|
-
size: number;
|
|
36
|
-
kind: 'memory' | 'jsonl' | 'session';
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export interface PlannedAction {
|
|
40
|
-
path: string;
|
|
41
|
-
action: 'copy' | 'merge' | 'skip' | 'conflict';
|
|
42
|
-
target: 'local' | 'remote';
|
|
43
|
-
added: number;
|
|
44
|
-
reason: string;
|
|
45
|
-
expectedTargetSha256?: string;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export interface SyncPlan {
|
|
49
|
-
revision: string;
|
|
50
|
-
actions: PlannedAction[];
|
|
51
|
-
summary: SyncSummary;
|
|
52
|
-
/** present when sessions were counted by checksum instead of staged */
|
|
53
|
-
sessionCounts?: SessionCounts;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** Session-only preview counts (computed from path+checksum, no content staged). */
|
|
57
|
-
export interface SessionCounts {
|
|
58
|
-
/** files that only exist on the incoming side (will be copied) */
|
|
59
|
-
added: number;
|
|
60
|
-
/** files present on both sides with different checksums (will be merged) */
|
|
61
|
-
updated: number;
|
|
62
|
-
/** files that exist locally but the remote has dropped (pull keeps them; counted only) */
|
|
63
|
-
deleted: number;
|
|
64
|
-
/** files byte-identical on both sides (skipped) */
|
|
65
|
-
identical: number;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export interface SyncPreview extends SyncPlan {
|
|
69
|
-
previewId: string;
|
|
70
|
-
expiresAt: string;
|
|
71
|
-
/** present when sessions were counted by checksum instead of staged */
|
|
72
|
-
sessionCounts?: SessionCounts;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** Per-file progress tick for async preview. */
|
|
76
|
-
export interface SyncProgress {
|
|
77
|
-
phase: 'listing' | 'hashing' | 'staging' | 'planning';
|
|
78
|
-
current: number;
|
|
79
|
-
total: number;
|
|
80
|
-
file?: string;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** Job state exposed by RPC while a preview runs in the background. */
|
|
84
|
-
export interface PreviewJobState {
|
|
85
|
-
status: 'running' | 'done' | 'error' | 'cancelled';
|
|
86
|
-
progress: SyncProgress;
|
|
87
|
-
preview?: SyncPreview;
|
|
88
|
-
error?: string;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export interface PreviewRequest {
|
|
92
|
-
direction: SyncDirection;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
export interface ApplyRequest {
|
|
96
|
-
previewId: string;
|
|
97
|
-
direction: SyncDirection;
|
|
98
|
-
confirm: true;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Inventory scope: 'memory' covers maestro-memory only, 'all' adds sessions/. */
|
|
102
|
-
export type SyncScope = 'memory' | 'all';
|
|
@@ -1,256 +0,0 @@
|
|
|
1
|
-
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
|
2
|
-
import { tmpdir } from 'node:os';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import type { RemoteTarget, SyncFailure, SyncPhase } from './sync-types.js';
|
|
5
|
-
import type { ProcessRunner } from './process-runner.js';
|
|
6
|
-
import { validateRemoteTarget } from './validation.js';
|
|
7
|
-
import { REMOTE_AGENT_REL, remoteAgentSource, verifyRemoteAgentSource } from './remote-agent.js';
|
|
8
|
-
import { buildRemoteManifestScript, parseRemoteManifest, type RemoteManifestEntry } from './remote-manifest.js';
|
|
9
|
-
import { buildWarmCacheScript } from './remote-cache.js';
|
|
10
|
-
import type { SshMux } from './ssh-mux.js';
|
|
11
|
-
|
|
12
|
-
export interface SyncTransport {
|
|
13
|
-
/** Resolve the remote user's $HOME as raw bytes (preflight, never shell ~ expansion). */
|
|
14
|
-
remoteHome(target: { host: string }): Promise<string>;
|
|
15
|
-
/** Rsync one batched --files-from stage of validated relative paths into `destination`. */
|
|
16
|
-
stage(target: RemoteTarget, paths: readonly string[], destination: string): Promise<void>;
|
|
17
|
-
/**
|
|
18
|
-
* One-pass remote inventory: a single ssh runs the fixed NUL-framed manifest
|
|
19
|
-
* script and returns validated eligible entries (path/sha256/size/mtimeSec)
|
|
20
|
-
* — replaces find + rsync -rcn compare + session hashes for inventory.
|
|
21
|
-
*/
|
|
22
|
-
manifest(target: RemoteTarget): Promise<RemoteManifestEntry[]>;
|
|
23
|
-
/**
|
|
24
|
-
* Refresh the remote fingerprint cache (<root>/.maestro-sync/fp.tsv, atomic
|
|
25
|
-
* tmp+rename). NEVER called from preview — only from the push-apply path
|
|
26
|
-
* (which already writes the remote) or an explicit warm command.
|
|
27
|
-
*/
|
|
28
|
-
warmCache(target: RemoteTarget): Promise<void>;
|
|
29
|
-
/** Upload materialized bytes for one operation into the remote private stage dir. */
|
|
30
|
-
upload(target: RemoteTarget, source: string, paths: readonly string[], operationId: string): Promise<void>;
|
|
31
|
-
/** Install the fixed remote CAS helper under `<root>/.maestro-sync/bin`. */
|
|
32
|
-
ensureAgent(target: RemoteTarget): Promise<void>;
|
|
33
|
-
/** Run the fixed remote helper with `operationId`; the JSONL manifest is the only input. */
|
|
34
|
-
commit(target: RemoteTarget, operationId: string, manifest: Buffer): Promise<void>;
|
|
35
|
-
/** Read `<root>/machine-id` via the fixed helper; null when missing/unreadable (lenient unknown). */
|
|
36
|
-
readMachineId(target: RemoteTarget): Promise<string | null>;
|
|
37
|
-
/**
|
|
38
|
-
* Rewrite only `domains.tunnel` in the remote settings from the named
|
|
39
|
-
* profile via the fixed helper. No settings bytes cross the wire.
|
|
40
|
-
* Caller runs `ensureAgent` first. Returns changed flag + new settings sha.
|
|
41
|
-
*/
|
|
42
|
-
patchRemoteTunnel(target: RemoteTarget, profile: string): Promise<{ changed: boolean; sha256: string }>;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function failure(phase: SyncPhase, code: string, detail: string, path?: string): SyncFailure {
|
|
46
|
-
return { phase, code, detail, path };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export class SshRsyncTransport implements SyncTransport {
|
|
50
|
-
private mux: SshMux | null = null;
|
|
51
|
-
|
|
52
|
-
constructor(private readonly runner: ProcessRunner) {}
|
|
53
|
-
|
|
54
|
-
/** Attach an SSH ControlMaster for this operation (preview/apply wrapper). */
|
|
55
|
-
setMux(mux: SshMux | null): void {
|
|
56
|
-
this.mux = mux;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
private sshArgs(host: string): string[] {
|
|
60
|
-
return this.mux ? [...this.mux.sshArgs, host] : [host];
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
private rsyncSSHArgs(): string[] {
|
|
64
|
-
return this.mux ? ['-e', this.mux.rsyncRsh] : [];
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async remoteHome(target: { host: string }): Promise<string> {
|
|
68
|
-
if (!target || typeof target.host !== 'string' || target.host.length === 0) {
|
|
69
|
-
throw Object.assign(new Error('remoteHome requires a non-empty host'), failure('validate', 'INVALID_HOST', 'remoteHome requires a non-empty host'));
|
|
70
|
-
}
|
|
71
|
-
// Preflight: `printf %s '$HOME'` over ssh returns the remote home as bytes.
|
|
72
|
-
// SSH-over-Cloudflare handshakes flake transiently (bad-handshake races),
|
|
73
|
-
// so one retry on spawn/timeout throw; exit-code and content failures are
|
|
74
|
-
// deterministic and fail fast. Still throws after the retry is exhausted.
|
|
75
|
-
let lastErr: unknown = null;
|
|
76
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
77
|
-
let result;
|
|
78
|
-
try {
|
|
79
|
-
result = await this.runner.run('ssh', [...this.sshArgs(target.host), 'printf', '%s', '$HOME'], { timeoutMs: 8000 });
|
|
80
|
-
} catch (e) {
|
|
81
|
-
lastErr = e;
|
|
82
|
-
continue;
|
|
83
|
-
}
|
|
84
|
-
if (result.exitCode !== 0) {
|
|
85
|
-
throw Object.assign(new Error(`remoteHome failed: ${result.stderr.toString()}`), failure('validate', 'REMOTE_HOME_FAILED', result.stderr.toString()));
|
|
86
|
-
}
|
|
87
|
-
const home = result.stdout.toString('utf-8').trim();
|
|
88
|
-
if (!home || !home.startsWith('/')) {
|
|
89
|
-
throw Object.assign(new Error(`invalid remote home: ${JSON.stringify(home)}`), failure('validate', 'INVALID_REMOTE_HOME', String(home)));
|
|
90
|
-
}
|
|
91
|
-
return home;
|
|
92
|
-
}
|
|
93
|
-
throw lastErr instanceof Error ? lastErr : new Error(`remoteHome failed after retry: ${String(lastErr)}`);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
async stage(target: RemoteTarget, paths: readonly string[], destination: string): Promise<void> {
|
|
97
|
-
const validated = validateRemoteTarget(target);
|
|
98
|
-
if (paths.length === 0) return;
|
|
99
|
-
const tmp = await mkdtemp(join(tmpdir(), 'maestro-stage-'));
|
|
100
|
-
try {
|
|
101
|
-
const listFile = join(tmp, 'files.txt');
|
|
102
|
-
await writeFile(listFile, paths.join('\n') + '\n', 'utf-8');
|
|
103
|
-
const result = await this.runner.run(
|
|
104
|
-
'rsync',
|
|
105
|
-
[...this.rsyncSSHArgs(), '-az', '--files-from=' + listFile, `${validated.host}:${validated.dshRoot}/`, destination + '/'],
|
|
106
|
-
// SSH transfers of hundreds of small session files need more than 2 min
|
|
107
|
-
// on real links (3.5s latency × N round-trips); 5 min keeps preview/apply
|
|
108
|
-
// usable while still failing closed when the link is actually down.
|
|
109
|
-
{ timeoutMs: 300000 },
|
|
110
|
-
);
|
|
111
|
-
if (result.exitCode !== 0) {
|
|
112
|
-
throw Object.assign(new Error(`stage failed: ${result.stderr.toString()}`), failure('stage', 'STAGE_FAILED', result.stderr.toString()));
|
|
113
|
-
}
|
|
114
|
-
} finally {
|
|
115
|
-
await rm(tmp, { recursive: true, force: true }).catch(() => {});
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
async manifest(target: RemoteTarget): Promise<RemoteManifestEntry[]> {
|
|
120
|
-
const validated = validateRemoteTarget(target);
|
|
121
|
-
// One ssh runs the fixed NUL-framed manifest script (find + sha256sum +
|
|
122
|
-
// stat in a single pass); every returned path is validated by the parser
|
|
123
|
-
// before it can enter a plan. This replaces list + compare + hashes for
|
|
124
|
-
// inventory: one remote byte pass, one spawn.
|
|
125
|
-
const result = await this.runner.run('ssh', [...this.sshArgs(validated.host), buildRemoteManifestScript(validated.dshRoot)], { timeoutMs: 300000 });
|
|
126
|
-
if (result.exitCode !== 0) {
|
|
127
|
-
throw Object.assign(new Error(`manifest failed: ${result.stderr.toString()}`), failure('snapshot', 'MANIFEST_FAILED', result.stderr.toString()));
|
|
128
|
-
}
|
|
129
|
-
return parseRemoteManifest(result.stdout);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
async warmCache(target: RemoteTarget): Promise<void> {
|
|
133
|
-
const validated = validateRemoteTarget(target);
|
|
134
|
-
// Refreshes <root>/.maestro-sync/fp.tsv atomically on the remote. Only the
|
|
135
|
-
// push-apply path (post-commit) or an explicit warm command calls this —
|
|
136
|
-
// preview must stay strictly read-only.
|
|
137
|
-
const result = await this.runner.run('ssh', [...this.sshArgs(validated.host), buildWarmCacheScript(validated.dshRoot)], { timeoutMs: 300000 });
|
|
138
|
-
if (result.exitCode !== 0) {
|
|
139
|
-
throw Object.assign(new Error(`warmCache failed: ${result.stderr.toString()}`), failure('snapshot', 'WARM_FAILED', result.stderr.toString()));
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
async upload(target: RemoteTarget, source: string, paths: readonly string[], operationId: string): Promise<void> {
|
|
144
|
-
const validated = validateRemoteTarget(target);
|
|
145
|
-
if (paths.length === 0) return;
|
|
146
|
-
const remoteStage = `${validated.dshRoot}/.maestro-sync/stage/${operationId}`;
|
|
147
|
-
const mkdirResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), 'mkdir', '-p', remoteStage], { timeoutMs: 8000 });
|
|
148
|
-
if (mkdirResult.exitCode !== 0) {
|
|
149
|
-
throw Object.assign(new Error(`mkdir failed: ${mkdirResult.stderr.toString()}`), failure('publish', 'UPLOAD_FAILED', mkdirResult.stderr.toString()));
|
|
150
|
-
}
|
|
151
|
-
const tmp = await mkdtemp(join(tmpdir(), 'maestro-upload-'));
|
|
152
|
-
try {
|
|
153
|
-
const listFile = join(tmp, 'files.txt');
|
|
154
|
-
await writeFile(listFile, paths.join('\n') + '\n', 'utf-8');
|
|
155
|
-
const result = await this.runner.run(
|
|
156
|
-
'rsync',
|
|
157
|
-
[...this.rsyncSSHArgs(), '-az', '--files-from=' + listFile, source + '/', `${validated.host}:${remoteStage}/`],
|
|
158
|
-
{ timeoutMs: 300000 },
|
|
159
|
-
);
|
|
160
|
-
if (result.exitCode !== 0) {
|
|
161
|
-
throw Object.assign(new Error(`upload failed: ${result.stderr.toString()}`), failure('publish', 'UPLOAD_FAILED', result.stderr.toString()));
|
|
162
|
-
}
|
|
163
|
-
} finally {
|
|
164
|
-
await rm(tmp, { recursive: true, force: true }).catch(() => {});
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
async ensureAgent(target: RemoteTarget): Promise<void> {
|
|
169
|
-
const validated = validateRemoteTarget(target);
|
|
170
|
-
const agentPath = `${validated.dshRoot}/${REMOTE_AGENT_REL}`;
|
|
171
|
-
const agentDir = `${validated.dshRoot}/.maestro-sync/bin`;
|
|
172
|
-
const source = verifyRemoteAgentSource(remoteAgentSource());
|
|
173
|
-
// mkdir -p the private bin dir, then stream the fixed helper via stdin (argv-only).
|
|
174
|
-
const mkdirResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), 'mkdir', '-p', agentDir], { timeoutMs: 8000 });
|
|
175
|
-
if (mkdirResult.exitCode !== 0) {
|
|
176
|
-
throw Object.assign(new Error(`ensureAgent mkdir failed: ${mkdirResult.stderr.toString()}`), failure('publish', 'AGENT_INSTALL_FAILED', mkdirResult.stderr.toString()));
|
|
177
|
-
}
|
|
178
|
-
const installResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), `cat > ${agentPath}`], { input: Buffer.from(source, 'utf-8'), timeoutMs: 8000 });
|
|
179
|
-
if (installResult.exitCode !== 0) {
|
|
180
|
-
throw Object.assign(new Error(`ensureAgent install failed: ${installResult.stderr.toString()}`), failure('publish', 'AGENT_INSTALL_FAILED', installResult.stderr.toString()));
|
|
181
|
-
}
|
|
182
|
-
const chmodResult = await this.runner.run('ssh', [...this.sshArgs(validated.host), 'chmod', '700', agentPath], { timeoutMs: 8000 });
|
|
183
|
-
if (chmodResult.exitCode !== 0) {
|
|
184
|
-
throw Object.assign(new Error(`ensureAgent chmod failed: ${chmodResult.stderr.toString()}`), failure('publish', 'AGENT_INSTALL_FAILED', chmodResult.stderr.toString()));
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
async commit(target: RemoteTarget, operationId: string, manifest: Buffer): Promise<void> {
|
|
189
|
-
const validated = validateRemoteTarget(target);
|
|
190
|
-
// Fixed protocol command: the helper path is a validated constant under the
|
|
191
|
-
// validated root; operationId is a locally generated hex id. The manifest on
|
|
192
|
-
// stdin is the only carrier of discovered paths.
|
|
193
|
-
const result = await this.runner.run(
|
|
194
|
-
'ssh',
|
|
195
|
-
[validated.host, `${validated.dshRoot}/${REMOTE_AGENT_REL}`, operationId],
|
|
196
|
-
{ input: manifest, timeoutMs: 15000 },
|
|
197
|
-
);
|
|
198
|
-
if (result.exitCode !== 0) {
|
|
199
|
-
const stderr = result.stderr.toString('utf-8');
|
|
200
|
-
const code = stderr.includes('CONCURRENT_MODIFICATION') ? 'CONCURRENT_MODIFICATION' : 'COMMIT_FAILED';
|
|
201
|
-
throw Object.assign(new Error(`commit failed: ${stderr || `exit ${result.exitCode}`}`), failure('publish', code, stderr || `exit ${result.exitCode}`));
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/**
|
|
206
|
-
* Read-only identity probe. The deployed helper answers `machine-id` too,
|
|
207
|
-
* but only a MUTATING sync installs it (`ensureAgent`), and this probe runs
|
|
208
|
-
* before any mutation — so depending on it made the id unreadable (null) on
|
|
209
|
-
* a machine that had never synced, which is exactly when the direction has
|
|
210
|
-
* to be resolved. Read `<dshRoot>/machine-id` directly first (validated
|
|
211
|
-
* absolute path, argv-only ssh), then fall back to the helper, whose
|
|
212
|
-
* self-resolved root is authoritative when the deployed copy disagrees.
|
|
213
|
-
*/
|
|
214
|
-
async readMachineId(target: RemoteTarget): Promise<string | null> {
|
|
215
|
-
const validated = validateRemoteTarget(target);
|
|
216
|
-
const direct = await this.readIdOverSsh(validated.host, ['cat', `${validated.dshRoot}/machine-id`]);
|
|
217
|
-
if (direct !== null) return direct;
|
|
218
|
-
return await this.readIdOverSsh(validated.host, [`${validated.dshRoot}/${REMOTE_AGENT_REL}`, 'machine-id']);
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
private async readIdOverSsh(host: string, argv: string[]): Promise<string | null> {
|
|
222
|
-
try {
|
|
223
|
-
const result = await this.runner.run('ssh', [host, ...argv], { timeoutMs: 8000 });
|
|
224
|
-
if (result.exitCode !== 0) return null;
|
|
225
|
-
const id = result.stdout.toString('utf-8').trim();
|
|
226
|
-
return id.length > 0 ? id : null;
|
|
227
|
-
} catch {
|
|
228
|
-
return null;
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
async patchRemoteTunnel(target: RemoteTarget, profile: string): Promise<{ changed: boolean; sha256: string }> {
|
|
233
|
-
const validated = validateRemoteTarget(target);
|
|
234
|
-
// Fixed protocol command: profile is a validated name, never a path.
|
|
235
|
-
// Caller runs ensureAgent first (same contract as commit).
|
|
236
|
-
const result = await this.runner.run(
|
|
237
|
-
'ssh',
|
|
238
|
-
[validated.host, `${validated.dshRoot}/${REMOTE_AGENT_REL}`, 'tunnel-patch', profile],
|
|
239
|
-
{ timeoutMs: 15000 },
|
|
240
|
-
);
|
|
241
|
-
const line = result.stdout.toString('utf-8').trim();
|
|
242
|
-
const m = /^(PATCHED|UNCHANGED) ([0-9a-f]{64})$/.exec(line);
|
|
243
|
-
if (result.exitCode !== 0 || !m) {
|
|
244
|
-
const stderr = result.stderr.toString('utf-8');
|
|
245
|
-
throw Object.assign(
|
|
246
|
-
new Error(`tunnel patch failed: ${stderr || line || `exit ${result.exitCode}`}`),
|
|
247
|
-
failure('publish', 'TUNNEL_PATCH_FAILED', stderr || line || `exit ${result.exitCode}`),
|
|
248
|
-
);
|
|
249
|
-
}
|
|
250
|
-
return { changed: m[1] === 'PATCHED', sha256: m[2]! };
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
export function createTransport(runner: ProcessRunner): SyncTransport {
|
|
255
|
-
return new SshRsyncTransport(runner);
|
|
256
|
-
}
|
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
import * as fs from 'node:fs';
|
|
2
|
-
import * as path from 'node:path';
|
|
3
|
-
import * as os from 'node:os';
|
|
4
|
-
import type { SyncTransport } from './transport.js';
|
|
5
|
-
import type { RemoteTarget } from './sync-types.js';
|
|
6
|
-
|
|
7
|
-
export type LocalRestoreResult = { ok: true; profile: string } | { ok: false; code: 'NO_PROFILE' | 'INVALID_PROFILE' };
|
|
8
|
-
export type RemoteRestoreResult =
|
|
9
|
-
| { ok: true; profile: string; changed: boolean; sha256: string }
|
|
10
|
-
| { ok: false; code: 'BAD_PROFILE' };
|
|
11
|
-
|
|
12
|
-
/** Everything a caller needs to DESCRIBE (not perform) a local restore. */
|
|
13
|
-
export type LocalTunnelProfile =
|
|
14
|
-
| {
|
|
15
|
-
ok: true
|
|
16
|
-
profile: string
|
|
17
|
-
/** the named-tunnel OBJECT read from the profile, already shape-checked */
|
|
18
|
-
tunnel: Record<string, unknown>
|
|
19
|
-
cloudflaredSrc: string
|
|
20
|
-
cloudflaredDst: string
|
|
21
|
-
settingsPath: string
|
|
22
|
-
}
|
|
23
|
-
| { ok: false; code: 'NO_PROFILE' | 'INVALID_PROFILE' };
|
|
24
|
-
|
|
25
|
-
/** Profile names are single path segments; mirrors the remote-agent allowlist. */
|
|
26
|
-
export function isSafeProfileName(name: string): boolean {
|
|
27
|
-
if (!name || name.startsWith('.') || name.includes('..') || name.includes('/')) return false;
|
|
28
|
-
return /^[A-Za-z0-9._-]+$/.test(name);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* The tunnel domain is a named-tunnel OBJECT (mode/hostname/...), never a
|
|
33
|
-
* bare string. A string write clobbered the object shape on 2026-09-09 and
|
|
34
|
-
* took a machine's tunnel down (HTTP 530) — so a non-object profile value
|
|
35
|
-
* fails closed here before anything is written.
|
|
36
|
-
*/
|
|
37
|
-
export function isValidTunnelDomain(v: unknown): v is Record<string, unknown> {
|
|
38
|
-
if (!v || typeof v !== 'object' || Array.isArray(v)) return false;
|
|
39
|
-
const t = v as Record<string, unknown>;
|
|
40
|
-
return typeof t.mode === 'string' && t.mode.length > 0 && typeof t.hostname === 'string' && t.hostname.length > 0;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Local tunnel profile restore: re-patches the moved shared store
|
|
45
|
-
* (<dsh>/dsh-maestro-config/settings.json via config-lib) domains.tunnel
|
|
46
|
-
* from this machine's own profile dir. Never throws; profiles may not
|
|
47
|
-
* exist on CI.
|
|
48
|
-
*/
|
|
49
|
-
/**
|
|
50
|
-
* Read-only resolution of this machine's tunnel profile: which profile would
|
|
51
|
-
* be restored, and the named-tunnel object it carries. Performs no write, so a
|
|
52
|
-
* read-only preview can show the operator exactly what a restore would change
|
|
53
|
-
* before anything touches the shared store. Never throws.
|
|
54
|
-
*/
|
|
55
|
-
export function readLocalTunnelProfile(opts?: { dshHome?: string; profileName?: string }): LocalTunnelProfile {
|
|
56
|
-
try {
|
|
57
|
-
const dshHome = opts?.dshHome ?? process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
|
|
58
|
-
const profilesRoot = path.join(dshHome, 'dsh-maestro-remote', 'tunnel-profiles');
|
|
59
|
-
if (!fs.existsSync(profilesRoot)) return { ok: false, code: 'NO_PROFILE' };
|
|
60
|
-
let profiles: string[] = [];
|
|
61
|
-
try {
|
|
62
|
-
profiles = fs.readdirSync(profilesRoot).filter((n) => {
|
|
63
|
-
try {
|
|
64
|
-
return fs.statSync(path.join(profilesRoot, n)).isDirectory();
|
|
65
|
-
} catch {
|
|
66
|
-
return false;
|
|
67
|
-
}
|
|
68
|
-
});
|
|
69
|
-
} catch {
|
|
70
|
-
return { ok: false, code: 'NO_PROFILE' };
|
|
71
|
-
}
|
|
72
|
-
if (profiles.length === 0) return { ok: false, code: 'NO_PROFILE' };
|
|
73
|
-
|
|
74
|
-
const envProfile = process.env.LOCAL_TUNNEL_PROFILE || process.env.TUNNEL_PROFILE;
|
|
75
|
-
const wanted = opts?.profileName ?? (envProfile && profiles.includes(envProfile) ? envProfile : undefined);
|
|
76
|
-
const profileName = wanted ?? profiles[0];
|
|
77
|
-
if (!profileName) return { ok: false, code: 'NO_PROFILE' };
|
|
78
|
-
|
|
79
|
-
const profileDir = path.join(profilesRoot, profileName);
|
|
80
|
-
const tunnelSettingsPath = path.join(profileDir, 'settings-tunnel.json');
|
|
81
|
-
const cloudflaredSrc = path.join(profileDir, 'cloudflared-config.yml');
|
|
82
|
-
const cloudflaredDst = path.join(dshHome, 'dsh-maestro-remote', 'cloudflared-config.yml');
|
|
83
|
-
const settingsPath = path.join(dshHome, 'dsh-maestro-config', 'settings.json');
|
|
84
|
-
|
|
85
|
-
// Gate only on the profile source: the store file itself may be absent
|
|
86
|
-
// (config-lib recreates it); a missing store must not skip the restore.
|
|
87
|
-
if (!fs.existsSync(tunnelSettingsPath)) return { ok: false, code: 'NO_PROFILE' };
|
|
88
|
-
|
|
89
|
-
const tunnelJson = JSON.parse(fs.readFileSync(tunnelSettingsPath, 'utf-8'));
|
|
90
|
-
const tunnelDomain = tunnelJson?.domains?.tunnel;
|
|
91
|
-
if (!isValidTunnelDomain(tunnelDomain)) return { ok: false, code: 'INVALID_PROFILE' };
|
|
92
|
-
return { ok: true, profile: profileName, tunnel: tunnelDomain, cloudflaredSrc, cloudflaredDst, settingsPath };
|
|
93
|
-
} catch {
|
|
94
|
-
return { ok: false, code: 'NO_PROFILE' };
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Local tunnel profile restore: re-patches the moved shared store
|
|
100
|
-
* (<dsh>/dsh-maestro-config/settings.json via config-lib) domains.tunnel
|
|
101
|
-
* from this machine's own profile dir. Never throws; profiles may not
|
|
102
|
-
* exist on CI.
|
|
103
|
-
*
|
|
104
|
-
* The mutation itself lives here; the decision to run it belongs to the
|
|
105
|
-
* caller's preview/confirm contract (see the `tunnelRestorePreview` /
|
|
106
|
-
* `tunnelRestore` RPC pair in `index.ts`) — this function is never called
|
|
107
|
-
* from a bare click.
|
|
108
|
-
*/
|
|
109
|
-
export async function restoreLocalTunnel(opts?: { dshHome?: string; profileName?: string }): Promise<LocalRestoreResult> {
|
|
110
|
-
const found = readLocalTunnelProfile(opts);
|
|
111
|
-
if (!found.ok) return { ok: false, code: found.code };
|
|
112
|
-
const { profile, tunnel, cloudflaredSrc, cloudflaredDst, settingsPath } = found;
|
|
113
|
-
|
|
114
|
-
try {
|
|
115
|
-
if (fs.existsSync(cloudflaredSrc) && fs.existsSync(path.dirname(cloudflaredDst))) {
|
|
116
|
-
fs.copyFileSync(cloudflaredSrc, cloudflaredDst);
|
|
117
|
-
try {
|
|
118
|
-
fs.chmodSync(cloudflaredDst, 0o600);
|
|
119
|
-
} catch {}
|
|
120
|
-
}
|
|
121
|
-
} catch {}
|
|
122
|
-
|
|
123
|
-
try {
|
|
124
|
-
try {
|
|
125
|
-
const cfgLib: any = await import('../store/index.js');
|
|
126
|
-
if (typeof cfgLib.set === 'function') {
|
|
127
|
-
await cfgLib.set('tunnel', tunnel);
|
|
128
|
-
return { ok: true, profile };
|
|
129
|
-
}
|
|
130
|
-
} catch {}
|
|
131
|
-
const raw = fs.readFileSync(settingsPath, 'utf-8');
|
|
132
|
-
const doc = JSON.parse(raw);
|
|
133
|
-
doc.domains = doc.domains || {};
|
|
134
|
-
doc.domains.tunnel = tunnel;
|
|
135
|
-
const tmp = settingsPath + '.tmp.' + Math.random().toString(16).slice(2, 6);
|
|
136
|
-
fs.writeFileSync(tmp, JSON.stringify(doc, null, 2) + '\n', 'utf-8');
|
|
137
|
-
fs.renameSync(tmp, settingsPath);
|
|
138
|
-
try {
|
|
139
|
-
fs.chmodSync(settingsPath, 0o600);
|
|
140
|
-
} catch {}
|
|
141
|
-
return { ok: true, profile };
|
|
142
|
-
} catch {
|
|
143
|
-
return { ok: false, code: 'NO_PROFILE' };
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* Remote tunnel restore via the fixed agent op: the profile is read on the
|
|
149
|
-
* remote itself and only `domains.tunnel` is rewritten. No settings bytes
|
|
150
|
-
* cross the wire. Transport errors propagate (fail closed, typed failure).
|
|
151
|
-
*/
|
|
152
|
-
export async function restoreRemoteTunnel(
|
|
153
|
-
transport: Pick<SyncTransport, 'patchRemoteTunnel'>,
|
|
154
|
-
target: RemoteTarget,
|
|
155
|
-
profileName: string,
|
|
156
|
-
): Promise<RemoteRestoreResult> {
|
|
157
|
-
if (!isSafeProfileName(profileName)) return { ok: false, code: 'BAD_PROFILE' };
|
|
158
|
-
const out = await transport.patchRemoteTunnel(target, profileName);
|
|
159
|
-
return { ok: true, profile: profileName, changed: out.changed, sha256: out.sha256 };
|
|
160
|
-
}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import type { RemoteTarget } from './sync-types.js';
|
|
2
|
-
|
|
3
|
-
export const HOST_RE = /^(?!-)[A-Za-z0-9._@:-]+$/;
|
|
4
|
-
export const ABSOLUTE_RE = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/;
|
|
5
|
-
// `migrated-v5.json` is the store-move marker: a peer that carries it has moved its
|
|
6
|
-
// store out of the DSH home. Sync needs to see it to refuse a half-upgraded pair instead
|
|
7
|
-
// of publishing into a directory the peer no longer reads.
|
|
8
|
-
export const ELIGIBLE_RE =
|
|
9
|
-
/^(?:maestro-memory\/(?!.*\.bak\.)[A-Za-z0-9._\/-]+\.md|maestro-memory\/SUGGESTIONS\.jsonl|maestro-memory\/\.maestro-memory\/migrated-v5\.json|sessions\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+\/session\.jsonl\.zstd|sessions\/[A-Za-z0-9._\/-]+\.jsonl\.zstd)$/;
|
|
10
|
-
|
|
11
|
-
/** True when a wire path is eligible, without throwing at the caller. */
|
|
12
|
-
export function isEligiblePath(value: string): boolean {
|
|
13
|
-
try {
|
|
14
|
-
normalizeEligiblePath(value);
|
|
15
|
-
return true;
|
|
16
|
-
} catch {
|
|
17
|
-
return false;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// Backwards-compatible aliases required by spec
|
|
22
|
-
export const HOST = HOST_RE;
|
|
23
|
-
export const ABSOLUTE = ABSOLUTE_RE;
|
|
24
|
-
export const ELIGIBLE = ELIGIBLE_RE;
|
|
25
|
-
|
|
26
|
-
function containsControlChars(s: string): boolean {
|
|
27
|
-
// Reject NUL, newline, carriage return, and other C0 controls
|
|
28
|
-
for (let i = 0; i < s.length; i++) {
|
|
29
|
-
const code = s.charCodeAt(i);
|
|
30
|
-
if (code <= 0x1f || code === 0x7f) return true;
|
|
31
|
-
}
|
|
32
|
-
return false;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function containsWhitespace(s: string): boolean {
|
|
36
|
-
return /\s/.test(s);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function containsShellMeta(s: string): boolean {
|
|
40
|
-
// Shell metachars that must not appear in host/path even if regex would catch some
|
|
41
|
-
// Keep validation explicit and fail-closed
|
|
42
|
-
return /[;`$|&><*?'"\\(){}!]/.test(s);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export function validateHost(host: string): string {
|
|
46
|
-
if (typeof host !== 'string' || host.length === 0) throw new Error('host must be a non-empty string');
|
|
47
|
-
if (containsControlChars(host) || host.includes('\u0000')) throw new Error(`invalid host: contains control characters`);
|
|
48
|
-
if (!HOST_RE.test(host)) throw new Error(`invalid host: ${JSON.stringify(host)} does not match ${HOST_RE}`);
|
|
49
|
-
if (containsWhitespace(host) || containsShellMeta(host) || host.includes('=')) {
|
|
50
|
-
throw new Error(`invalid host: ${JSON.stringify(host)} contains illegal characters`);
|
|
51
|
-
}
|
|
52
|
-
return host;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export function validateRemoteTarget(value: RemoteTarget): RemoteTarget {
|
|
56
|
-
if (!value || typeof value.host !== 'string' || typeof value.dshRoot !== 'string') {
|
|
57
|
-
throw new Error('RemoteTarget must have string host and dshRoot');
|
|
58
|
-
}
|
|
59
|
-
const { host, dshRoot } = value;
|
|
60
|
-
validateHost(host);
|
|
61
|
-
|
|
62
|
-
if (!ABSOLUTE_RE.test(dshRoot)) {
|
|
63
|
-
throw new Error(`invalid dshRoot: ${JSON.stringify(dshRoot)} does not match ${ABSOLUTE_RE}`);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Additional fail-closed checks: reject traversal, ~, //, trailing slash already covered
|
|
67
|
-
if (dshRoot.includes('~')) {
|
|
68
|
-
throw new Error(`invalid dshRoot: must be absolute without ~ expansion: ${JSON.stringify(dshRoot)}`);
|
|
69
|
-
}
|
|
70
|
-
if (dshRoot.includes('..')) {
|
|
71
|
-
throw new Error(`invalid dshRoot: must not contain traversal: ${JSON.stringify(dshRoot)}`);
|
|
72
|
-
}
|
|
73
|
-
if (containsWhitespace(dshRoot) || containsShellMeta(dshRoot)) {
|
|
74
|
-
throw new Error(`invalid dshRoot: contains whitespace or shell metacharacters`);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
return { host, dshRoot };
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export function normalizeEligiblePath(value: string): string {
|
|
81
|
-
if (typeof value !== 'string') {
|
|
82
|
-
throw new Error('path must be a string');
|
|
83
|
-
}
|
|
84
|
-
if (value.length === 0) throw new Error('path must not be empty');
|
|
85
|
-
if (containsControlChars(value) || value.includes('\u0000')) {
|
|
86
|
-
throw new Error(`ineligible path: contains control characters: ${JSON.stringify(value)}`);
|
|
87
|
-
}
|
|
88
|
-
if (value.includes('..')) {
|
|
89
|
-
// traversal not allowed at all; eligible paths are strictly under maestro-memory/ or sessions/
|
|
90
|
-
// The ELIGIBLE regex would reject it anyway, but be explicit
|
|
91
|
-
throw new Error(`ineligible path: traversal: ${JSON.stringify(value)}`);
|
|
92
|
-
}
|
|
93
|
-
if (value.startsWith('/') || value.startsWith('./') || value.startsWith('../')) {
|
|
94
|
-
throw new Error(`ineligible path: must be relative eligible path: ${JSON.stringify(value)}`);
|
|
95
|
-
}
|
|
96
|
-
if (!ELIGIBLE_RE.test(value)) {
|
|
97
|
-
throw new Error(`ineligible path: ${JSON.stringify(value)} does not match ${ELIGIBLE_RE}`);
|
|
98
|
-
}
|
|
99
|
-
// Extra sanity: already checked NUL, but also forbid backslash (Windows sep) and absolute
|
|
100
|
-
if (value.includes('\\')) {
|
|
101
|
-
throw new Error(`ineligible path: must use POSIX separators: ${JSON.stringify(value)}`);
|
|
102
|
-
}
|
|
103
|
-
return value;
|
|
104
|
-
}
|