@dreamlake/dreamlake-cli 0.100.0 → 0.102.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/dist/api/access.d.ts +2 -0
- package/dist/api/access.js +2 -0
- package/dist/api/agent.d.ts +10 -0
- package/dist/api/agent.js +11 -0
- package/dist/api/host-moves.d.ts +54 -0
- package/dist/api/host-moves.js +66 -0
- package/dist/api/index.d.ts +12 -0
- package/dist/cli/artifact/index.d.ts +2 -0
- package/dist/cli/artifact/index.js +23 -3
- package/dist/cli/artifact/site.d.ts +16 -0
- package/dist/cli/artifact/site.js +125 -0
- package/dist/cli/artifact/siteFormat.d.ts +25 -0
- package/dist/cli/artifact/siteFormat.js +53 -0
- package/dist/cli/auth/materialized.d.ts +6 -0
- package/dist/cli/auth/materialized.js +2 -1
- package/dist/cli/compat/s3-backend.d.ts +26 -0
- package/dist/cli/compat/s3-backend.js +45 -0
- package/dist/cli/config.d.ts +2 -2
- package/dist/cli/config.js +13 -5
- package/dist/cli/help-examples.generated.js +3 -1
- package/dist/cli/hosts/api.js +1 -0
- package/dist/cli/hosts/index.js +7 -5
- package/dist/cli/hosts/inventory.d.ts +3 -0
- package/dist/cli/hosts/move.d.ts +39 -0
- package/dist/cli/hosts/move.js +77 -0
- package/dist/cli/hosts/ssh-transport.d.ts +27 -0
- package/dist/cli/hosts/ssh-transport.js +79 -0
- package/dist/cli/hosts/ssh.js +4 -4
- package/dist/cli/index.js +2 -0
- package/dist/cli/infra/index.js +2 -2
- package/dist/cli/jobs/index.js +1 -1
- package/dist/cli/namespace.d.ts +10 -0
- package/dist/cli/namespace.js +70 -0
- package/dist/cli/notes/index.js +31 -33
- package/dist/cli/version.d.ts +1 -1
- package/dist/cli/version.js +1 -1
- package/package.json +10 -9
|
@@ -13,6 +13,11 @@
|
|
|
13
13
|
// (POST .../upload-credentials) and are short-lived and prefix-scoped, so
|
|
14
14
|
// they never touch disk.
|
|
15
15
|
import { AwsClient } from "aws4fetch";
|
|
16
|
+
import { constants } from "node:fs";
|
|
17
|
+
import { open } from "node:fs/promises";
|
|
18
|
+
import { Readable } from "node:stream";
|
|
19
|
+
// S3's single PutObject ceiling; larger individual objects require multipart.
|
|
20
|
+
export const S3_SINGLE_PUT_MAX_BYTES = 5 * 1024 * 1024 * 1024;
|
|
16
21
|
/**
|
|
17
22
|
* S3 ETags come back quoted (`"abc123"`), but DreamDB hands them straight
|
|
18
23
|
* back as `ifMatch` unquoted. Comparing the two raw forms makes every
|
|
@@ -99,6 +104,46 @@ export class S3Backend {
|
|
|
99
104
|
}
|
|
100
105
|
return { status: "created", etag: unquote(res.headers.get("etag")) };
|
|
101
106
|
}
|
|
107
|
+
/** Stream a pre-hashed file, binding its expected bytes into the S3 signature/checksum. */
|
|
108
|
+
async putFile(key, file, opts = {}) {
|
|
109
|
+
if (!Number.isSafeInteger(file.size) || file.size < 0 || file.size > S3_SINGLE_PUT_MAX_BYTES ||
|
|
110
|
+
!/^[a-f0-9]{64}$/.test(file.sha256))
|
|
111
|
+
throw new Error('Invalid streaming S3 file');
|
|
112
|
+
const handle = await open(file.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
113
|
+
let source;
|
|
114
|
+
try {
|
|
115
|
+
const stat = await handle.stat();
|
|
116
|
+
if (!stat.isFile() || stat.size !== file.size || stat.dev !== file.dev || stat.ino !== file.ino ||
|
|
117
|
+
stat.mtimeMs !== file.mtimeMs || stat.ctimeMs !== file.ctimeMs)
|
|
118
|
+
throw new Error('Site file changed after hashing; retry the push');
|
|
119
|
+
const headers = {
|
|
120
|
+
'Content-Length': String(file.size),
|
|
121
|
+
'X-Amz-Content-Sha256': file.sha256,
|
|
122
|
+
'X-Amz-Checksum-Sha256': Buffer.from(file.sha256, 'hex').toString('base64'),
|
|
123
|
+
};
|
|
124
|
+
if (opts.ifNoneMatchStar)
|
|
125
|
+
headers['If-None-Match'] = '*';
|
|
126
|
+
source = file.size ? handle.createReadStream({ autoClose: false, highWaterMark: 256 * 1024 }) : undefined;
|
|
127
|
+
const request = await this.client.sign(this.url(key), {
|
|
128
|
+
method: 'PUT', headers,
|
|
129
|
+
body: source ? Readable.toWeb(source, {
|
|
130
|
+
strategy: { highWaterMark: 256 * 1024, size: chunk => chunk.byteLength },
|
|
131
|
+
}) : new Uint8Array(),
|
|
132
|
+
duplex: 'half',
|
|
133
|
+
});
|
|
134
|
+
// A consumed stream cannot be retried by aws4fetch; a failed push can safely reuse completed objects.
|
|
135
|
+
const res = await fetch(request);
|
|
136
|
+
if (res.status === 412 || res.status === 409)
|
|
137
|
+
return { status: opts.ifNoneMatchStar ? 'exists' : 'casFailed' };
|
|
138
|
+
if (!res.ok)
|
|
139
|
+
throw new Error(`PUT ${key} → ${res.status} ${await res.text().catch(() => '')}`.slice(0, 300));
|
|
140
|
+
return { status: 'created', etag: unquote(res.headers.get('etag')) };
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
source?.destroy();
|
|
144
|
+
await handle.close();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
102
147
|
/** Keys under `prefix`, relative to the dataset base (ListObjectsV2). */
|
|
103
148
|
async list(prefix) {
|
|
104
149
|
// The bucket root is one level above the dataset prefix in a path-style
|
package/dist/cli/config.d.ts
CHANGED
|
@@ -8,8 +8,8 @@ export declare function resolveToken(flag?: string, dir?: string): string | null
|
|
|
8
8
|
/** Decode a JWT payload without verifying the signature. Returns {} on failure. */
|
|
9
9
|
export declare function decodeJwtPayload(token: string): Record<string, unknown>;
|
|
10
10
|
/**
|
|
11
|
-
* Resolve the
|
|
12
|
-
* explicit
|
|
11
|
+
* Resolve a command's default namespace without changing the signed-in user's identity:
|
|
12
|
+
* explicit → selected CLI namespace → personal cache → GET /auth/me → JWT decode.
|
|
13
13
|
*
|
|
14
14
|
* The cache is only trusted when the effective (remote, token) is exactly
|
|
15
15
|
* the materialized pair — under a flag or env-var override it may describe
|
package/dist/cli/config.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { identityMode, loadMachineConfig } from "./auth/machine.js";
|
|
2
|
-
// Shared connection config —
|
|
3
|
-
//
|
|
3
|
+
// Shared connection config — token and remote match dreamlake-py.
|
|
4
|
+
// Namespace selection is CLI-local; SDK domain methods take explicit scopes:
|
|
4
5
|
//
|
|
5
6
|
// token: flag → DREAMLAKE_API_KEY → ~/.dreamlake/tokens.json → null
|
|
6
7
|
// remote: flag → DREAMLAKE_REMOTE → config.json remote_url → prod
|
|
7
|
-
// namespace: explicit
|
|
8
|
+
// namespace: explicit → selected CLI namespace → personal cache → GET /auth/me → JWT decode
|
|
8
9
|
//
|
|
9
10
|
// The multi-env cache (auth.yml) is deliberately absent here — it is a
|
|
10
11
|
// write-path convenience for `env use` and is never consulted to answer
|
|
@@ -56,8 +57,8 @@ export function decodeJwtPayload(token) {
|
|
|
56
57
|
}
|
|
57
58
|
}
|
|
58
59
|
/**
|
|
59
|
-
* Resolve the
|
|
60
|
-
* explicit
|
|
60
|
+
* Resolve a command's default namespace without changing the signed-in user's identity:
|
|
61
|
+
* explicit → selected CLI namespace → personal cache → GET /auth/me → JWT decode.
|
|
61
62
|
*
|
|
62
63
|
* The cache is only trusted when the effective (remote, token) is exactly
|
|
63
64
|
* the materialized pair — under a flag or env-var override it may describe
|
|
@@ -67,6 +68,13 @@ export async function resolveNamespace(explicit, opts) {
|
|
|
67
68
|
if (explicit)
|
|
68
69
|
return explicit;
|
|
69
70
|
const cfg = readConfig(opts.dir);
|
|
71
|
+
const selected = cfg.default_namespace;
|
|
72
|
+
if (selected && typeof selected === 'object' && selected.remote === stripTrailingSlash(opts.remote) &&
|
|
73
|
+
selected.tokenSha256 === createHash('sha256').update(opts.token).digest('hex')) {
|
|
74
|
+
if (typeof selected.namespace !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(selected.namespace))
|
|
75
|
+
throw new Error('Saved CLI namespace is invalid; run dreamlake su <namespace> again');
|
|
76
|
+
return selected.namespace;
|
|
77
|
+
}
|
|
70
78
|
if (cfg.namespace &&
|
|
71
79
|
cfg.remote_url &&
|
|
72
80
|
stripTrailingSlash(cfg.remote_url) === stripTrailingSlash(opts.remote) &&
|
|
@@ -4,7 +4,7 @@ export const helpExamples = {
|
|
|
4
4
|
"agents show": "dreamlake agents show my_repo.tri --namespace my-workspace",
|
|
5
5
|
"agents edit": "dreamlake agents edit my_repo.tri --namespace my-workspace\n# Browser form: follow the localhost URL printed by the command.\ndreamlake agents edit my_repo.tri --namespace my-workspace --web",
|
|
6
6
|
"telemetry": "dreamlake telemetry disable --quiet\ndreamlake telemetry status\ndreamlake telemetry enable --quiet",
|
|
7
|
-
"artifact push": "dreamlake artifact push ./dashboard.html --id q1-dashboard\n# Edit the file, then repeat the same command to upload only new chunks.\n\n# Compatibility with older self-hosted viewers:\ndreamlake artifact push ./dashboard.html --id q1-dashboard --full\n\n# Multiple self-contained HTML pages (requires an updated viewer):\ndreamlake artifact push ./report --entry index.html --id quarterly-report",
|
|
7
|
+
"artifact push": "dreamlake artifact push ./dashboard.html --id q1-dashboard\n# Edit the file, then repeat the same command to upload only new chunks.\n\n# Static build with on-demand assets (CLI 0.101.0+; requires site hosting):\ndreamlake artifact push ./dist/client --site --id simulation\n\n# Compatibility with older self-hosted viewers:\ndreamlake artifact push ./dashboard.html --id q1-dashboard --full\n\n# Multiple self-contained HTML pages (requires an updated viewer):\ndreamlake artifact push ./report --entry index.html --id quarterly-report",
|
|
8
8
|
"artifact meta set": "# At push time:\ndreamlake artifact push ./report.html --id q1-dashboard \\\n --description \"Revenue, churn and pipeline for the quarter\" \\\n --cover ./cover.png\n\n# Or after the fact, for an artifact that already exists:\ndreamlake artifact meta set q1-dashboard --description \"Revenue, churn and pipeline\"\ndreamlake artifact meta set q1-dashboard --cover ./cover.png\ndreamlake artifact meta show q1-dashboard\n\n# Back to the automatic description / the generated cover:\ndreamlake artifact meta set q1-dashboard --clear-description --clear-cover",
|
|
9
9
|
"artifact share": "# Find the dashboard you already uploaded; no new version is needed.\ndreamlake artifact list\nARTIFACT=\"q1-dashboard\" # Replace with the id from list.\ndreamlake artifact share get \"$ARTIFACT\"\n\n# Give signed-in recipients read access, then verify the returned link.\ndreamlake artifact share create \"$ARTIFACT\"\ndreamlake artifact share get \"$ARTIFACT\"\n\n# When link access is no longer needed, revoke it and verify.\ndreamlake artifact share revoke \"$ARTIFACT\"\ndreamlake artifact share get \"$ARTIFACT\"",
|
|
10
10
|
"artifact visibility": "ARTIFACT=\"q1-dashboard\" # Your existing artifact id.\ndreamlake artifact visibility \"$ARTIFACT\" public\ndreamlake artifact visibility \"$ARTIFACT\" private",
|
|
@@ -12,6 +12,7 @@ export const helpExamples = {
|
|
|
12
12
|
"runnable execute": "dreamlake runnable execute exec/acme/recipes.process@EXECUTION_DIGEST \\\n --queue cpu --inputs record.json --timeout-seconds 600 --json\ndreamlake runnable execute exec/acme/recipes.process@EXECUTION_DIGEST \\\n --queue cpu --inputs record.json --timeout-seconds 600 --attempt 2 --json",
|
|
13
13
|
"runnable execution-receipt": "dreamlake runnable execution-receipt exec/acme/recipes.process@EXECUTION_DIGEST \\\n --queue cpu --inputs record.json --timeout-seconds 600 --wait-seconds 30",
|
|
14
14
|
"hosts": "dreamlake hosts\ndreamlake hosts --all\ndreamlake hosts -h\ndreamlake hosts list -h",
|
|
15
|
+
"su": "dreamlake su fortyfive\ndreamlake hosts list\ndreamlake hosts list --namespace geyang\ndreamlake su geyang",
|
|
15
16
|
"nymph": "dreamlake nymph\ndreamlake nymph --json",
|
|
16
17
|
"nymph setup": "dreamlake nymph setup --name alice/computers/laptop --lakeshore-id CONNECTION_ID",
|
|
17
18
|
"nymph config": "dreamlake nymph config --name alice/computers/laptop",
|
|
@@ -53,6 +54,7 @@ export const helpExamples = {
|
|
|
53
54
|
"hosts exec": "dreamlake hosts exec geyang/dev/worker -- python3 -c 'print(\"hello\")'",
|
|
54
55
|
"hosts upgrade": "dreamlake hosts upgrade geyang/dev/worker --nymph-version 0.1.32 --dry-run\ndreamlake hosts upgrade geyang/dev/worker --nymph-version 0.1.32\ndreamlake hosts upgrade 'geyang/lab/*' --nymph-version 0.1.32 --concurrency 4 --max-failures 2\ndreamlake hosts upgrade --all --namespace geyang --nymph-version 0.1.32 --json",
|
|
55
56
|
"hosts rollback": "dreamlake hosts rollback geyang/dev/worker\ndreamlake hosts rollback geyang/dev/worker --upgrade-id 20261029-001 --json",
|
|
57
|
+
"hosts move": "dreamlake hosts move HOST_ID --namespace alice --to acme --dry-run --json",
|
|
56
58
|
"infra list": "dreamlake infra list --namespace fortyfive --project dreamlake-infra --json",
|
|
57
59
|
"infra status": "dreamlake infra status da8e49cf-1b37-446f-9494-9620faf3192d --json",
|
|
58
60
|
"infra connect": "dreamlake infra connect da8e49cf-1b37-446f-9494-9620faf3192d",
|
package/dist/cli/hosts/api.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { resolveRemote, resolveToken } from "../config.js";
|
|
2
2
|
const SAFE_POWER_CODES = new Set([
|
|
3
|
+
"host_move_blocked", "move_preview_conflict", "catalog_revision_conflict", "move_conflict", "move_busy", "enrollment_moved", "connection_access_denied",
|
|
3
4
|
"host_power_unsupported", "provider_binding_ambiguous", "enrollment_not_provider_bound",
|
|
4
5
|
"provider_binding_revoked", "enrollment_revoked", "active_work_present", "request_id_conflict",
|
|
5
6
|
"invalid_power_request", "invalid_request_id", "volume_disposition_required", "host_lifecycle_unavailable",
|
package/dist/cli/hosts/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { registerHostMoveCommand } from './move.js';
|
|
1
2
|
import { collectionList } from "../collection-list.js";
|
|
2
3
|
import { inspectHostCatalog, changeHostCatalog, formatHostCatalog } from "./catalog.js";
|
|
3
4
|
import { registerHostLifecycleCommands } from "./lifecycle.js";
|
|
@@ -133,7 +134,7 @@ export function registerHostsCommand(program) {
|
|
|
133
134
|
process.exitCode = await runHostsEnroll(opts);
|
|
134
135
|
});
|
|
135
136
|
collectionList(group, "list").description("list active (verified online) hosts across all groups and pages in one namespace")
|
|
136
|
-
.option("--namespace <namespace>", "namespace slug (default:
|
|
137
|
+
.option("--namespace <namespace>", "namespace slug (default: selected CLI namespace, otherwise personal)")
|
|
137
138
|
.option("--group <group>", "limit to one group")
|
|
138
139
|
.option("--archived <mode>", "catalog visibility: exclude (default), include, or only")
|
|
139
140
|
.option("--all", "include offline hosts and hosts with unknown connection state")
|
|
@@ -154,7 +155,7 @@ export function registerHostsCommand(program) {
|
|
|
154
155
|
});
|
|
155
156
|
group.command("enrollments").description("inspect enrollment identities and observed presence for one host; read-only")
|
|
156
157
|
.argument("<selector>", "host ID or namespace/group/host")
|
|
157
|
-
.option("--namespace <namespace>", "namespace for a host ID (default:
|
|
158
|
+
.option("--namespace <namespace>", "namespace for a host ID (default: selected CLI namespace, otherwise personal)")
|
|
158
159
|
.option("--json", "emit machine-readable enrollment details and observed presence freshness")
|
|
159
160
|
.action(async (selector, opts) => {
|
|
160
161
|
try {
|
|
@@ -174,7 +175,7 @@ export function registerHostsCommand(program) {
|
|
|
174
175
|
group.command("metrics").description("read timestamped CPU, RAM, and disk observations for one enrollment")
|
|
175
176
|
.argument("<selector>", "host ID or namespace/group/host")
|
|
176
177
|
.requiredOption("--enrollment <id>", "exact enrollment ID from hosts enrollments")
|
|
177
|
-
.option("--namespace <namespace>", "namespace for a host ID (default:
|
|
178
|
+
.option("--namespace <namespace>", "namespace for a host ID (default: selected CLI namespace, otherwise personal)")
|
|
178
179
|
.option("--resolution <seconds>", "history resolution: 10, 60, 900, or 3600 seconds", "60")
|
|
179
180
|
.option("--json", "emit latest sample, retained history, and freshness")
|
|
180
181
|
.action(async (selector, opts) => {
|
|
@@ -195,7 +196,7 @@ export function registerHostsCommand(program) {
|
|
|
195
196
|
.argument("<selector>", "host ID or namespace/group/host")
|
|
196
197
|
.requiredOption("--enrollment <id>", "exact enrollment ID from hosts enrollments")
|
|
197
198
|
.requiredOption("--action <action>", "ssh or tracked-run (ordinary uv-run/uvx)")
|
|
198
|
-
.option("--namespace <namespace>", "namespace for a host ID (default:
|
|
199
|
+
.option("--namespace <namespace>", "namespace for a host ID (default: selected CLI namespace, otherwise personal)")
|
|
199
200
|
.option("--json", "emit the backend readiness verdict and observation timestamps")
|
|
200
201
|
.action(async (selector, opts) => {
|
|
201
202
|
try {
|
|
@@ -255,7 +256,7 @@ export function registerHostsCommand(program) {
|
|
|
255
256
|
}
|
|
256
257
|
group.command("status").description("inspect a host's backend-reported connection and enrollments")
|
|
257
258
|
.argument("<selector>", "host ID, namespace/group/host or quoted namespace/group/*")
|
|
258
|
-
.option("--namespace <namespace>", "namespace for a host ID (default:
|
|
259
|
+
.option("--namespace <namespace>", "namespace for a host ID (default: selected CLI namespace, otherwise personal)")
|
|
259
260
|
.option("--page <number>", "group listing page (default 1)")
|
|
260
261
|
.option("--page-size <number>", "listing page size (default 100, maximum 100)")
|
|
261
262
|
.option("--json", "emit machine-readable output")
|
|
@@ -276,6 +277,7 @@ export function registerHostsCommand(program) {
|
|
|
276
277
|
}
|
|
277
278
|
});
|
|
278
279
|
registerHostSshCommands(group, program);
|
|
280
|
+
registerHostMoveCommand(group);
|
|
279
281
|
registerHostLifecycleCommands(group);
|
|
280
282
|
registerHostUpgradeCommands(group);
|
|
281
283
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type HostMoveRetainedSessions, type HostMoveRetainedRuns } from '../../api/host-moves.js';
|
|
2
|
+
import type { Command } from 'commander';
|
|
3
|
+
import { hostRequest } from './api.js';
|
|
4
|
+
export interface HostMovePreview {
|
|
5
|
+
apiVersion: 1;
|
|
6
|
+
hostId: string;
|
|
7
|
+
sourceNamespaceId: string;
|
|
8
|
+
destinationNamespaceId: string;
|
|
9
|
+
destinationNamespace: string;
|
|
10
|
+
name: string;
|
|
11
|
+
ownerUserId: string;
|
|
12
|
+
visibility: 'private';
|
|
13
|
+
revision: number;
|
|
14
|
+
previewHash: string;
|
|
15
|
+
blockers: string[];
|
|
16
|
+
executable: boolean;
|
|
17
|
+
sessions?: HostMoveRetainedSessions;
|
|
18
|
+
runs?: HostMoveRetainedRuns;
|
|
19
|
+
}
|
|
20
|
+
export interface HostMoveReceipt extends Omit<HostMovePreview, 'previewHash' | 'blockers' | 'executable'> {
|
|
21
|
+
operationId: string;
|
|
22
|
+
requestId: string;
|
|
23
|
+
recordedAt: string;
|
|
24
|
+
replayed: boolean;
|
|
25
|
+
}
|
|
26
|
+
type Options = {
|
|
27
|
+
namespace?: string;
|
|
28
|
+
to: string;
|
|
29
|
+
dryRun?: boolean;
|
|
30
|
+
confirm?: boolean;
|
|
31
|
+
requestId?: string;
|
|
32
|
+
expectedRevision?: string;
|
|
33
|
+
previewHash?: string;
|
|
34
|
+
json?: boolean;
|
|
35
|
+
};
|
|
36
|
+
export declare function previewHostMove(hostId: string, opts: Pick<Options, 'namespace' | 'to'>, request?: typeof hostRequest): Promise<HostMovePreview>;
|
|
37
|
+
export declare function applyHostMove(hostId: string, opts: Pick<Options, 'namespace' | 'to' | 'requestId' | 'expectedRevision' | 'previewHash'>, request?: typeof hostRequest): Promise<HostMoveReceipt>;
|
|
38
|
+
export declare function registerHostMoveCommand(group: Command): void;
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { validateHostMoveSessions, validateHostMoveRuns } from '../../api/host-moves.js';
|
|
2
|
+
import { hostApiPath, hostRequest } from './api.js';
|
|
3
|
+
import { resolveHostNamespace } from './inventory.js';
|
|
4
|
+
function input(hostId, to) {
|
|
5
|
+
if (!/^[a-f0-9]{24}$/.test(hostId) || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(to))
|
|
6
|
+
throw new Error('Use one exact lowercase Host ID and a destination namespace slug');
|
|
7
|
+
}
|
|
8
|
+
function common(value, hostId, to) {
|
|
9
|
+
if (!value || value.apiVersion !== 1 || value.hostId !== hostId || value.destinationNamespace !== to ||
|
|
10
|
+
typeof value.sourceNamespaceId !== 'string' || !value.sourceNamespaceId || typeof value.destinationNamespaceId !== 'string' || !value.destinationNamespaceId ||
|
|
11
|
+
value.sourceNamespaceId === value.destinationNamespaceId || typeof value.name !== 'string' || !value.name.startsWith(`${to}/`) ||
|
|
12
|
+
typeof value.ownerUserId !== 'string' || !value.ownerUserId || value.visibility !== 'private' || !Number.isSafeInteger(value.revision) || value.revision < 0 || value.revision > 2147483647)
|
|
13
|
+
throw new Error('Host API returned an invalid private move response');
|
|
14
|
+
validateHostMoveSessions(value.sessions);
|
|
15
|
+
validateHostMoveRuns(value.runs);
|
|
16
|
+
}
|
|
17
|
+
export async function previewHostMove(hostId, opts, request = hostRequest) {
|
|
18
|
+
input(hostId, opts.to);
|
|
19
|
+
const namespace = await resolveHostNamespace(opts.namespace);
|
|
20
|
+
const result = await request(`${hostApiPath(namespace)}/${hostId}/move/preview`, 'POST', { destinationNamespace: opts.to });
|
|
21
|
+
common(result, hostId, opts.to);
|
|
22
|
+
if (typeof result.previewHash !== 'string' || !/^[a-f0-9]{64}$/.test(result.previewHash) || !Array.isArray(result.blockers) ||
|
|
23
|
+
result.blockers.some((b) => typeof b !== 'string' || !/^[a-z_]+$/.test(b)) || result.executable !== (result.blockers.length === 0))
|
|
24
|
+
throw new Error('Host API returned an invalid move preview');
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
export async function applyHostMove(hostId, opts, request = hostRequest) {
|
|
28
|
+
input(hostId, opts.to);
|
|
29
|
+
if (typeof opts.requestId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(opts.requestId) ||
|
|
30
|
+
typeof opts.expectedRevision !== 'string' || !/^(0|[1-9][0-9]*)$/.test(opts.expectedRevision) || Number(opts.expectedRevision) >= 2147483647 ||
|
|
31
|
+
typeof opts.previewHash !== 'string' || !/^[a-f0-9]{64}$/.test(opts.previewHash))
|
|
32
|
+
throw new Error('Apply requires the reviewed --preview-hash, --expected-revision, and a stable --request-id');
|
|
33
|
+
const namespace = await resolveHostNamespace(opts.namespace);
|
|
34
|
+
// Submit exactly once. After uncertainty retry these exact inputs, never refresh the plan implicitly.
|
|
35
|
+
const result = await request(`${hostApiPath(namespace)}/${hostId}/move`, 'POST', { destinationNamespace: opts.to,
|
|
36
|
+
requestId: opts.requestId, expectedRevision: Number(opts.expectedRevision), previewHash: opts.previewHash });
|
|
37
|
+
common(result, hostId, opts.to);
|
|
38
|
+
if (result.requestId !== opts.requestId || typeof result.operationId !== 'string' || !/^[a-f0-9]{64}$/.test(result.operationId) ||
|
|
39
|
+
result.revision !== Number(opts.expectedRevision) + 1 || typeof result.replayed !== 'boolean' ||
|
|
40
|
+
typeof result.recordedAt !== 'string' || !Number.isFinite(Date.parse(result.recordedAt)))
|
|
41
|
+
throw new Error('Host API returned an invalid move receipt');
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
export function registerHostMoveCommand(group) {
|
|
45
|
+
group.command('move').description('preview or apply an owner-private Host namespace move without re-enrolling')
|
|
46
|
+
.argument('<host-id>', 'exact lowercase Host ID').requiredOption('--to <namespace>', 'destination namespace slug')
|
|
47
|
+
.option('--namespace <namespace>', 'source namespace slug').option('--dry-run', 'read a server preview; do not move')
|
|
48
|
+
.option('--confirm', 'apply the exact reviewed preview').option('--request-id <id>', 'stable mutation request ID')
|
|
49
|
+
.option('--expected-revision <revision>', 'revision from the reviewed preview').option('--preview-hash <hash>', 'hash from the reviewed preview')
|
|
50
|
+
.option('--json', 'emit structured preview or receipt').action(async (hostId, opts) => {
|
|
51
|
+
try {
|
|
52
|
+
if (Boolean(opts.dryRun) === Boolean(opts.confirm))
|
|
53
|
+
throw new Error('Choose --dry-run to review or --confirm with the exact reviewed inputs');
|
|
54
|
+
if (opts.dryRun && (opts.requestId !== undefined || opts.expectedRevision !== undefined || opts.previewHash !== undefined))
|
|
55
|
+
throw new Error('Mutation inputs belong with --confirm');
|
|
56
|
+
const result = opts.dryRun ? await previewHostMove(hostId, opts) : await applyHostMove(hostId, opts);
|
|
57
|
+
if (opts.json)
|
|
58
|
+
console.log(JSON.stringify(result, null, 2));
|
|
59
|
+
else
|
|
60
|
+
console.log([`Host: ${result.name}`, 'Access: Private — only you', `Revision: ${result.revision}`,
|
|
61
|
+
...(result.sessions ? [`Saved sessions: ${result.sessions.count} retained at their original addresses; private to you`, `Session access changes: ${result.sessions.accessChanges.public} public and ${result.sessions.accessChanges.shared} shared become private`] : []),
|
|
62
|
+
...(result.runs ? [`Runs retained: ${result.runs.count} (${result.runs.terminal} terminal, ${result.runs.active} active acknowledged); original namespace and execution identity unchanged`] : []),
|
|
63
|
+
...('previewHash' in result ? [`Preview hash: ${result.previewHash}`, result.executable ? 'Ready to move. Apply with --confirm and these reviewed inputs.' : `Blocked: ${result.blockers.join(', ')}`]
|
|
64
|
+
: [`Operation ID: ${result.operationId}`, `Request ID: ${result.requestId}`, result.replayed ? 'Stored original receipt; inspect the host for its current location.' : 'Move committed.'])].join('\n'));
|
|
65
|
+
if ('executable' in result && !result.executable)
|
|
66
|
+
process.exitCode = 1;
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
const message = error instanceof Error ? error.message : 'Host move failed';
|
|
70
|
+
if (opts.json)
|
|
71
|
+
console.log(JSON.stringify({ status: 'error', error: message }));
|
|
72
|
+
else
|
|
73
|
+
console.error(message);
|
|
74
|
+
process.exitCode = 1;
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Socket } from 'node:net';
|
|
2
|
+
import { Duplex } from 'node:stream';
|
|
3
|
+
import type WebSocket from 'ws';
|
|
4
|
+
/**
|
|
5
|
+
* Feed ws bounded raw chunks through the public Duplex contract. Pausing a
|
|
6
|
+
* WebSocket cannot stop frames already decoded from one large Bun TCP chunk.
|
|
7
|
+
* This adapter leaves the raw socket in pull mode and admits at most 16 KiB
|
|
8
|
+
* per read, so the decoder returns control before another full relay frame.
|
|
9
|
+
*/
|
|
10
|
+
export declare class SshIngress extends Duplex {
|
|
11
|
+
private socket;
|
|
12
|
+
private pulling;
|
|
13
|
+
private connected;
|
|
14
|
+
private pendingWrite?;
|
|
15
|
+
constructor(socket: Socket, secure?: boolean);
|
|
16
|
+
get connecting(): boolean;
|
|
17
|
+
get encrypted(): boolean | undefined;
|
|
18
|
+
setTimeout(ms: number, callback?: () => void): this;
|
|
19
|
+
setNoDelay(value?: boolean): this;
|
|
20
|
+
setKeepAlive(value?: boolean, delay?: number): this;
|
|
21
|
+
private pull;
|
|
22
|
+
_read(): void;
|
|
23
|
+
_write(bytes: Buffer, encoding: BufferEncoding, done: (error?: Error | null) => void): void;
|
|
24
|
+
_final(done: () => void): void;
|
|
25
|
+
_destroy(error: Error | null, done: (error?: Error | null) => void): void;
|
|
26
|
+
}
|
|
27
|
+
export declare function sshSocket(url: string, ticket?: string): WebSocket;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { connect as netConnect, isIP } from 'node:net';
|
|
2
|
+
import { connect as tlsConnect } from 'node:tls';
|
|
3
|
+
import { Duplex } from 'node:stream';
|
|
4
|
+
// A package alias keeps Bun from substituting its built-in ws shim.
|
|
5
|
+
import PackageWebSocket from 'ws-transport';
|
|
6
|
+
/**
|
|
7
|
+
* Feed ws bounded raw chunks through the public Duplex contract. Pausing a
|
|
8
|
+
* WebSocket cannot stop frames already decoded from one large Bun TCP chunk.
|
|
9
|
+
* This adapter leaves the raw socket in pull mode and admits at most 16 KiB
|
|
10
|
+
* per read, so the decoder returns control before another full relay frame.
|
|
11
|
+
*/
|
|
12
|
+
export class SshIngress extends Duplex {
|
|
13
|
+
socket;
|
|
14
|
+
pulling = false;
|
|
15
|
+
connected = false;
|
|
16
|
+
pendingWrite;
|
|
17
|
+
constructor(socket, secure = false) {
|
|
18
|
+
super({ highWaterMark: 16384 });
|
|
19
|
+
this.socket = socket;
|
|
20
|
+
socket.on('readable', () => this.pull());
|
|
21
|
+
socket.on('end', () => this.push(null));
|
|
22
|
+
socket.on('error', error => this.destroy(error));
|
|
23
|
+
socket.on('close', () => this.destroy());
|
|
24
|
+
socket.on('timeout', () => this.emit('timeout'));
|
|
25
|
+
socket.on('connect', () => this.emit('connect'));
|
|
26
|
+
socket.once(secure ? 'secureConnect' : 'connect', () => {
|
|
27
|
+
this.connected = true;
|
|
28
|
+
const pending = this.pendingWrite;
|
|
29
|
+
this.pendingWrite = undefined;
|
|
30
|
+
if (pending)
|
|
31
|
+
socket.write(pending.bytes, pending.encoding, pending.done);
|
|
32
|
+
if (secure)
|
|
33
|
+
this.emit('secureConnect');
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
get connecting() { return this.socket.connecting; }
|
|
37
|
+
get encrypted() { return this.socket.encrypted; }
|
|
38
|
+
setTimeout(ms, callback) { this.socket.setTimeout(ms, callback); return this; }
|
|
39
|
+
setNoDelay(value) { this.socket.setNoDelay(value); return this; }
|
|
40
|
+
setKeepAlive(value, delay) { this.socket.setKeepAlive(value, delay); return this; }
|
|
41
|
+
pull() {
|
|
42
|
+
if (!this.pulling || this.destroyed)
|
|
43
|
+
return;
|
|
44
|
+
const bytes = this.socket.read(Math.min(16384, this.socket.readableLength || 16384));
|
|
45
|
+
if (bytes && !this.push(bytes))
|
|
46
|
+
this.pulling = false;
|
|
47
|
+
}
|
|
48
|
+
_read() { this.pulling = true; this.pull(); }
|
|
49
|
+
_write(bytes, encoding, done) {
|
|
50
|
+
// Bun's TLS socket rejects writes during asynchronous DNS/handshake. Keep
|
|
51
|
+
// just the stream's current write until the authenticated connection exists.
|
|
52
|
+
if (!this.connected)
|
|
53
|
+
this.pendingWrite = { bytes, encoding, done };
|
|
54
|
+
else
|
|
55
|
+
this.socket.write(bytes, encoding, done);
|
|
56
|
+
}
|
|
57
|
+
_final(done) { this.socket.end(done); }
|
|
58
|
+
_destroy(error, done) {
|
|
59
|
+
const pending = this.pendingWrite;
|
|
60
|
+
this.pendingWrite = undefined;
|
|
61
|
+
this.socket.destroy();
|
|
62
|
+
pending?.done(error ?? new Error('SSH socket closed before connection'));
|
|
63
|
+
done(error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export function sshSocket(url, ticket) {
|
|
67
|
+
const secure = new URL(url).protocol === 'wss:';
|
|
68
|
+
return new PackageWebSocket(url, ticket ? 'nymph-ssh.v1' : [], {
|
|
69
|
+
...(ticket ? { headers: { Authorization: `Bearer ${ticket}` } } : {}),
|
|
70
|
+
perMessageDeflate: false, maxPayload: 65537, handshakeTimeout: 10000, followRedirects: false,
|
|
71
|
+
// ws documents a Duplex socket; its type declaration narrows this to net.Socket.
|
|
72
|
+
createConnection: ((options) => {
|
|
73
|
+
const opts = { ...options, path: secure ? undefined : options.socketPath };
|
|
74
|
+
if (secure && !opts.servername && opts.servername !== '')
|
|
75
|
+
opts.servername = isIP(opts.host ?? '') ? '' : opts.host;
|
|
76
|
+
return new SshIngress(secure ? tlsConnect(opts) : netConnect(opts), secure);
|
|
77
|
+
}),
|
|
78
|
+
});
|
|
79
|
+
}
|
package/dist/cli/hosts/ssh.js
CHANGED
|
@@ -7,7 +7,7 @@ import { createServer } from 'node:net';
|
|
|
7
7
|
import { Duplex } from 'node:stream';
|
|
8
8
|
import { promisify } from 'node:util';
|
|
9
9
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
|
-
import
|
|
10
|
+
import { sshSocket } from './ssh-transport.js';
|
|
11
11
|
import { select } from '@inquirer/prompts';
|
|
12
12
|
import { HostApiError, hostApiPath, hostRequest } from './api.js';
|
|
13
13
|
import { hostStatus } from './enroll.js';
|
|
@@ -25,8 +25,7 @@ export const defaultSshIO = {
|
|
|
25
25
|
request: hostRequest, fetch: (...args) => fetch(...args), terminal: () => Boolean(process.stderr.isTTY),
|
|
26
26
|
interactive: () => Boolean(process.stdin.isTTY && process.stderr.isTTY),
|
|
27
27
|
pick: (inventory, selector, command) => pickHost(inventory, selector, command, { input: process.stdin, output: process.stderr, color: !process.env.NO_COLOR }),
|
|
28
|
-
socket:
|
|
29
|
-
perMessageDeflate: false, maxPayload: 65537, handshakeTimeout: 10000, followRedirects: false }),
|
|
28
|
+
socket: sshSocket,
|
|
30
29
|
spawn: args => spawn('ssh', args, { stdio: 'inherit' }),
|
|
31
30
|
};
|
|
32
31
|
/** Only a selector that named no host earns suggestions; auth, namespace and transport errors pass through unchanged. */
|
|
@@ -132,7 +131,8 @@ export class SshRelay extends Duplex {
|
|
|
132
131
|
this.push(null);
|
|
133
132
|
return;
|
|
134
133
|
}
|
|
135
|
-
|
|
134
|
+
// The stream retains payload only; already-decoded frames may follow pause.
|
|
135
|
+
if (b[0] !== 0 || b.length < 2 || this.readableLength + b.length - 1 > 262144)
|
|
136
136
|
return this.destroy(new Error('Invalid SSH relay frame'));
|
|
137
137
|
if (!this.push(b.subarray(1)))
|
|
138
138
|
ws.pause();
|
package/dist/cli/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { registerNamespaceCommand } from "./namespace.js";
|
|
1
2
|
import { registerNymphCommand } from "./nymph/index.js";
|
|
2
3
|
import { collectionList } from "./collection-list.js";
|
|
3
4
|
import { configureTelemetryCommand, deliverTelemetry, installTelemetryOptOut, registerTelemetryCommand, startCommandTelemetry } from './telemetry.js';
|
|
@@ -114,6 +115,7 @@ async function main(argv) {
|
|
|
114
115
|
process.env.DREAMLAKE_IDENTITY = mode;
|
|
115
116
|
}
|
|
116
117
|
});
|
|
118
|
+
registerNamespaceCommand(program);
|
|
117
119
|
registerMachineCommand(program);
|
|
118
120
|
registerTelemetryCommand(program);
|
|
119
121
|
program.hook("preAction", (_program, action) => configureTelemetryCommand(action));
|
package/dist/cli/infra/index.js
CHANGED
|
@@ -19,10 +19,10 @@ export function registerInfraCommand(program) {
|
|
|
19
19
|
const cmd = (name === "list" ? collectionList(infra) : infra.command(name === "create" ? "create <name>" : `${name} <stack-id>`))
|
|
20
20
|
.option("--remote <url>", "API remote").option("--token <token>", "API credential (never printed)").option("--json", "JSON output");
|
|
21
21
|
if (name === "list")
|
|
22
|
-
cmd.requiredOption("--project <slug>", "owner/access project").option("--namespace <slug>", "default:
|
|
22
|
+
cmd.requiredOption("--project <slug>", "owner/access project").option("--namespace <slug>", "default: selected CLI namespace, otherwise personal");
|
|
23
23
|
if (name === "create")
|
|
24
24
|
cmd.requiredOption("--project <slug>", "owner project")
|
|
25
|
-
.option("--namespace <slug>", "default:
|
|
25
|
+
.option("--namespace <slug>", "default: selected CLI namespace, otherwise personal")
|
|
26
26
|
.requiredOption("--environment <label>", "Terraform environment")
|
|
27
27
|
.requiredOption("--repository <url>", "HTTPS repository URL")
|
|
28
28
|
.requiredOption("--directory <path>", "relative Terraform root (empty string allowed)")
|
package/dist/cli/jobs/index.js
CHANGED
|
@@ -44,7 +44,7 @@ function hostId(value) {
|
|
|
44
44
|
return value;
|
|
45
45
|
}
|
|
46
46
|
function common(command) {
|
|
47
|
-
return command.option("--namespace <slug>", "namespace (default:
|
|
47
|
+
return command.option("--namespace <slug>", "namespace (default: selected CLI namespace, otherwise personal)").option("--json", "output the full API JSON receipt");
|
|
48
48
|
}
|
|
49
49
|
function printReceipt(result, json) {
|
|
50
50
|
console.log(json ? JSON.stringify(result) : `${jobText(result.job)}${result.alreadyRegistered ? "\nAlready registered." : ""}`);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Command } from 'commander';
|
|
2
|
+
export declare function selectNamespace(value: string, options?: {
|
|
3
|
+
dir?: string;
|
|
4
|
+
fetch?: typeof fetch;
|
|
5
|
+
}): Promise<{
|
|
6
|
+
namespace: string;
|
|
7
|
+
personalNamespace: string;
|
|
8
|
+
remote: string;
|
|
9
|
+
}>;
|
|
10
|
+
export declare function registerNamespaceCommand(program: Command): void;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Persistent CLI scope; it never replaces a login, an identity or the GUI workspace. */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readConfig, readToken, updateConfig } from './auth/materialized.js';
|
|
4
|
+
import { resolveRemote, resolveToken } from './config.js';
|
|
5
|
+
const slug = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
6
|
+
const normalizeRemote = (remote) => remote.replace(/\/+$/, '');
|
|
7
|
+
export async function selectNamespace(value, options = {}) {
|
|
8
|
+
const namespace = value.replace(/^@/, '');
|
|
9
|
+
if (!slug.test(namespace))
|
|
10
|
+
throw new Error('Use dreamlake su <namespace> with an exact namespace name');
|
|
11
|
+
const remote = resolveRemote(undefined, options.dir), token = resolveToken(undefined, options.dir);
|
|
12
|
+
if (!token)
|
|
13
|
+
throw new Error('Log in to DreamLake before selecting a namespace');
|
|
14
|
+
const materialized = () => readToken(options.dir) === token && normalizeRemote(readConfig(options.dir).remote_url ?? '') === remote;
|
|
15
|
+
if (!materialized())
|
|
16
|
+
throw new Error('Select a saved login with dreamlake auth env use before persisting a namespace; explicit connection overrides are not saved');
|
|
17
|
+
const request = options.fetch ?? fetch;
|
|
18
|
+
const get = async (path, json) => {
|
|
19
|
+
let response;
|
|
20
|
+
try {
|
|
21
|
+
response = await request(remote + path, { method: json === undefined ? 'GET' : 'POST',
|
|
22
|
+
headers: { Authorization: `Bearer ${token}`, ...(json === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
|
23
|
+
...(json === undefined ? {} : { body: JSON.stringify(json) }), redirect: 'error', signal: AbortSignal.timeout(10000) });
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new Error('Could not verify namespace access; the saved selection was not changed');
|
|
27
|
+
}
|
|
28
|
+
if (!response.ok)
|
|
29
|
+
throw new Error(`Could not verify namespace access (HTTP ${response.status}); the saved selection was not changed`);
|
|
30
|
+
try {
|
|
31
|
+
return await response.json();
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new Error('Invalid namespace access response; the saved selection was not changed');
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const me = await get('/auth/me');
|
|
38
|
+
if (!me || typeof me.namespace?.slug !== 'string' || !slug.test(me.namespace.slug))
|
|
39
|
+
throw new Error('Could not verify the signed-in personal namespace');
|
|
40
|
+
if (namespace !== me.namespace.slug) {
|
|
41
|
+
const memberships = await get('/graphql', { query: 'query { myOrganizations { slug } }', variables: {} });
|
|
42
|
+
if (!memberships || typeof memberships !== 'object' || memberships.errors?.length || !Array.isArray(memberships.data?.myOrganizations))
|
|
43
|
+
throw new Error('Could not verify organization memberships; the saved selection was not changed');
|
|
44
|
+
if (!memberships.data.myOrganizations.some(org => org?.slug === namespace))
|
|
45
|
+
throw new Error(`You do not have namespace membership in '${namespace}'; the saved selection was not changed`);
|
|
46
|
+
}
|
|
47
|
+
// Recheck after I/O. The stored digest also prevents another process's login switch from reusing this selection.
|
|
48
|
+
if (!materialized())
|
|
49
|
+
throw new Error('The login changed while checking namespace access; retry against the intended login');
|
|
50
|
+
updateConfig({ default_namespace: { namespace, remote, tokenSha256: createHash('sha256').update(token).digest('hex') } }, options.dir);
|
|
51
|
+
return { namespace, personalNamespace: me.namespace.slug, remote };
|
|
52
|
+
}
|
|
53
|
+
export function registerNamespaceCommand(program) {
|
|
54
|
+
program.command('su').description('persist the default namespace for CLI commands under the current login')
|
|
55
|
+
.argument('<namespace>', 'personal or organization namespace name; no special personal alias')
|
|
56
|
+
.option('--json', 'emit the selected namespace and unchanged personal identity')
|
|
57
|
+
.action(async (namespace, options) => {
|
|
58
|
+
try {
|
|
59
|
+
const selected = await selectNamespace(namespace);
|
|
60
|
+
if (options.json)
|
|
61
|
+
console.log(JSON.stringify(selected, null, 2));
|
|
62
|
+
else
|
|
63
|
+
console.log(`Default namespace: ${selected.namespace}\nSigned-in personal namespace: ${selected.personalNamespace}`);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
console.error(error instanceof Error ? error.message : 'Namespace selection failed');
|
|
67
|
+
process.exitCode = 1;
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|