@supersdk/supercli 0.3.0-staging.30 → 0.3.0-staging.35

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.
@@ -0,0 +1,849 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.NON_ROOT_REMEDIATION = exports.defaultDeployDeps = void 0;
37
+ exports.parseEnvAssignment = parseEnvAssignment;
38
+ exports.dockerUnavailableMessage = dockerUnavailableMessage;
39
+ exports.isNonRootRejection = isNonRootRejection;
40
+ exports.extractLogLines = extractLogLines;
41
+ exports.runDeploy = runDeploy;
42
+ exports.registerDeployCommand = registerDeployCommand;
43
+ // `supercli deploy` — one command from a Dockerfile to a running, addressable
44
+ // container service (CA-F260810034335 · AC-2 / AC-5 / AC-9 / AC-16 / AC-17).
45
+ //
46
+ // The shape is a deliberate copy of publishSite.ts, because that command is this
47
+ // repo's settled answer to "what does an agent-callable CLI command look like":
48
+ //
49
+ // local validation → path existence → auth (env token wins) → org
50
+ // → dry-run returns here (validate only, no image pushed, nothing written)
51
+ // → build + push (skippable with a digest-pinned --image)
52
+ // → create the service with an idempotency key
53
+ // → poll/report readiness; on failure, pull the last N startup log lines
54
+ //
55
+ // Everything the user sees goes through ResultPrinter, so `--output json` emits
56
+ // exactly one envelope line on stdout while docker's build output — which is
57
+ // long, noisy, and produced by a program we do not control — is confined to
58
+ // stderr (see docker/dockerCli.ts).
59
+ const crypto = __importStar(require("node:crypto"));
60
+ const fs = __importStar(require("node:fs"));
61
+ const path = __importStar(require("node:path"));
62
+ const consoleClient_1 = require("../api/consoleClient");
63
+ const tokenAuth_1 = require("../auth/tokenAuth");
64
+ const environments_1 = require("../config/environments");
65
+ const dockerCli_1 = require("../docker/dockerCli");
66
+ const registry_1 = require("../docker/registry");
67
+ const resultPrinter_1 = require("../output/resultPrinter");
68
+ const orgResolve_1 = require("../publish/orgResolve");
69
+ const runClient_1 = require("../publish/runClient");
70
+ const accountStore_1 = require("../store/accountStore");
71
+ const credentialStore_1 = require("../store/credentialStore");
72
+ const log_1 = require("../util/log");
73
+ const prompt_1 = require("../util/prompt");
74
+ const shell_1 = require("../util/shell");
75
+ function resolveBackend(account) {
76
+ return (0, credentialStore_1.backendForAccount)(account.backend, {
77
+ passphraseProvider: account.backend === 'encrypted-file'
78
+ ? () => (0, prompt_1.promptHiddenSync)(`Encryption passphrase for ${account.email ?? account.accountKey}: `)
79
+ : undefined,
80
+ });
81
+ }
82
+ exports.defaultDeployDeps = {
83
+ getCurrentAccount: accountStore_1.getCurrentAccount,
84
+ getStoredToken: (account) => resolveBackend(account).get(account.accountKey)?.token ?? null,
85
+ markNeedsLogin: accountStore_1.markAccountNeedsLogin,
86
+ fetchWhoami: (apiOrigin, token) => new consoleClient_1.ConsoleClient(apiOrigin).whoami(token),
87
+ createRunClient: (apiOrigin) => new runClient_1.RunClient(apiOrigin),
88
+ docker: dockerCli_1.defaultDockerFacade,
89
+ statPath: (target) => {
90
+ try {
91
+ const stat = fs.statSync(target);
92
+ if (stat.isDirectory())
93
+ return 'dir';
94
+ if (stat.isFile())
95
+ return 'file';
96
+ return 'other';
97
+ }
98
+ catch {
99
+ return 'missing';
100
+ }
101
+ },
102
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
103
+ pollAttempts: 40,
104
+ pollIntervalMs: 3_000,
105
+ };
106
+ // ---------------------------------------------------------------------------
107
+ // local validation helpers
108
+ // ---------------------------------------------------------------------------
109
+ /** Mirrors `validate_run_slug` (CA): the container and static-site name pools are the same one. */
110
+ const SLUG_PATTERN = /^[a-z0-9]{1,32}$/;
111
+ const RESERVED_SLUGS = new Set(['stg', 'site']);
112
+ const SPID_PATTERN = /^[a-z0-9]{8}$/;
113
+ const ENV_PATTERN = /^[a-z0-9]{1,10}$/;
114
+ /** Mirrors `validate_env_key` (CA). */
115
+ const ENV_KEY_PATTERN = /^[A-Z_][A-Z0-9_]{0,127}$/;
116
+ const SPEC_LIMITS = {
117
+ port: { min: 1, max: 65_535, def: 8080 },
118
+ cpu: { min: 1, max: 4_000, def: undefined },
119
+ memory: { min: 1, max: 8_192, def: undefined },
120
+ maxScale: { min: 1, max: 10, def: undefined },
121
+ };
122
+ /** Digest of the not-yet-built image, used ONLY to let a dry-run reach the server's validator. */
123
+ const PLACEHOLDER_DIGEST = `sha256:${'0'.repeat(64)}`;
124
+ function trimFlag(value) {
125
+ const trimmed = value?.trim();
126
+ return trimmed ? trimmed : undefined;
127
+ }
128
+ function parseIntFlag(raw, flag, limits) {
129
+ const trimmed = trimFlag(raw);
130
+ if (trimmed === undefined)
131
+ return { ok: true, value: undefined };
132
+ if (!/^[0-9]+$/.test(trimmed))
133
+ return { ok: false, message: `invalid ${flag}: must be a whole number` };
134
+ const value = Number(trimmed);
135
+ if (value < limits.min || value > limits.max) {
136
+ return { ok: false, message: `invalid ${flag}: must be in ${limits.min}..${limits.max}` };
137
+ }
138
+ return { ok: true, value };
139
+ }
140
+ /**
141
+ * `--env-var KEY=VALUE` (inline value allowed) and `--secret KEY` (name ONLY).
142
+ *
143
+ * 🔴 `--secret` deliberately REFUSES `KEY=VALUE`. Anything on argv is readable by
144
+ * every other process on the machine (`ps`, and each process's `cmdline` entry
145
+ * under procfs) and is written verbatim into shell history and CI job logs —
146
+ * which is why this CLI has no `--token` flag either, an invariant that
147
+ * `test/unit/util/log.test.ts` (TC-27) enforces across the whole command
148
+ * surface. So a secret rides in the environment and the command line carries
149
+ * only its NAME. Nothing about the non-interactive story is lost: a CI runner
150
+ * already holds its secrets as environment variables.
151
+ */
152
+ function parseEnvAssignment(entry, flag, opts = { allowInlineValue: true }) {
153
+ const separator = entry.indexOf('=');
154
+ const key = (separator === -1 ? entry : entry.slice(0, separator)).trim();
155
+ if (!ENV_KEY_PATTERN.test(key)) {
156
+ // 🔴 Only the key is ever echoed — never the value (CR-4 discipline, CLI half).
157
+ return { ok: false, message: `invalid ${flag} name "${key}": must match ^[A-Z_][A-Z0-9_]{0,127}$` };
158
+ }
159
+ if (separator !== -1 && !opts.allowInlineValue) {
160
+ return {
161
+ ok: false,
162
+ message: `${flag} takes a NAME, not a value: write \`${flag} ${key}\` and export ${key} in the environment first. ` +
163
+ 'a value written on the command line is visible to every process on this machine and is recorded in shell ' +
164
+ 'history and CI logs (use --env-var for values that are not secret)',
165
+ };
166
+ }
167
+ if (separator === -1) {
168
+ const fromEnv = process.env[key];
169
+ if (fromEnv === undefined) {
170
+ const inlineHint = opts.allowInlineValue ? `pass ${flag} ${key}=<value>, or ` : '';
171
+ return { ok: false, message: `${flag} ${key} has no value: ${inlineHint}export ${key} in the environment first` };
172
+ }
173
+ return { ok: true, key, value: fromEnv };
174
+ }
175
+ return { ok: true, key, value: entry.slice(separator + 1) };
176
+ }
177
+ function collectEnvVars(opts) {
178
+ const vars = [];
179
+ const seen = new Set();
180
+ const groups = [
181
+ { entries: opts.envVar ?? [], flag: '--env-var', secret: false },
182
+ { entries: opts.secret ?? [], flag: '--secret', secret: true },
183
+ ];
184
+ for (const group of groups) {
185
+ for (const entry of group.entries) {
186
+ const parsed = parseEnvAssignment(entry, group.flag, { allowInlineValue: !group.secret });
187
+ if (!parsed.ok)
188
+ return parsed;
189
+ if (seen.has(parsed.key)) {
190
+ return { ok: false, message: `duplicate environment variable ${parsed.key}: declare each key once` };
191
+ }
192
+ seen.add(parsed.key);
193
+ vars.push({ key: parsed.key, value: parsed.value, is_secret: group.secret });
194
+ }
195
+ }
196
+ return { ok: true, vars };
197
+ }
198
+ async function withAuth(auth, deps, call) {
199
+ const outcome = await call(auth.token);
200
+ if (outcome.kind === 'auth_invalid') {
201
+ if (auth.accountKey)
202
+ deps.markNeedsLogin(auth.accountKey);
203
+ return { kind: 'needs_login' };
204
+ }
205
+ return { kind: 'outcome', outcome };
206
+ }
207
+ function terminalResult() {
208
+ return { ok: false, kind: 'needs_login', message: 'credentials are no longer valid — run `supercli login` again' };
209
+ }
210
+ function failureKind(kind) {
211
+ switch (kind) {
212
+ case 'forbidden':
213
+ return 'forbidden';
214
+ case 'rate_limited':
215
+ return 'rate_limited';
216
+ case 'infra_error':
217
+ return 'infra_error';
218
+ case 'auth_invalid':
219
+ return 'auth_invalid';
220
+ default:
221
+ return 'business_error';
222
+ }
223
+ }
224
+ function nonSuccessMessage(outcome, context) {
225
+ switch (outcome.kind) {
226
+ case 'business_error':
227
+ return (0, runClient_1.describeRunError)(outcome.code, outcome.message);
228
+ case 'forbidden':
229
+ return `${outcome.message} — check --org, or your admin permission on the target org`;
230
+ case 'rate_limited':
231
+ return `${outcome.message} — too many requests; retry later`;
232
+ case 'infra_error':
233
+ return `${context} failed: ${outcome.message}`;
234
+ default:
235
+ return `${context} failed`;
236
+ }
237
+ }
238
+ function valueFromOutcome(outcome) {
239
+ if (outcome.kind === 'success')
240
+ return outcome.data;
241
+ if (outcome.kind === 'soft_success')
242
+ return outcome.resource;
243
+ return undefined;
244
+ }
245
+ function asRecord(value) {
246
+ return value !== null && typeof value === 'object' ? value : undefined;
247
+ }
248
+ function stringField(value, key) {
249
+ const field = asRecord(value)?.[key];
250
+ return typeof field === 'string' && field.length > 0 ? field : undefined;
251
+ }
252
+ /** Resolves the effective token + apiOrigin (env token wins — a clean CI machine needs no keyring). */
253
+ function resolveAuth(deps) {
254
+ const envToken = (0, tokenAuth_1.resolveEnvToken)();
255
+ if (envToken)
256
+ return { token: envToken, apiOrigin: (0, environments_1.resolveApiOrigin)().apiOrigin };
257
+ const account = deps.getCurrentAccount();
258
+ if (!account)
259
+ return { ok: false, kind: 'needs_login', message: 'no account is logged in — run `supercli login` first' };
260
+ const stored = deps.getStoredToken(account);
261
+ if (!stored) {
262
+ deps.markNeedsLogin(account.accountKey);
263
+ return { ok: false, kind: 'needs_login', message: 'no valid credential found locally — run `supercli login` again' };
264
+ }
265
+ return { token: stored, apiOrigin: account.apiOrigin, accountKey: account.accountKey };
266
+ }
267
+ // ---------------------------------------------------------------------------
268
+ // AC-16: docker is missing → say what to do instead, never just die
269
+ // ---------------------------------------------------------------------------
270
+ /**
271
+ * The downgrade path, spelled out. `deploy` cannot build without a daemon, but
272
+ * "cannot build" is NOT "cannot deploy": an image that is already in the registry
273
+ * can be deployed by digest with zero local docker involvement (AC-2), and that
274
+ * is the option a CI runner or an AI agent on a docker-less box actually needs to
275
+ * be told about.
276
+ */
277
+ function dockerUnavailableMessage(probe, opts) {
278
+ const headline = probe.reason === 'not-installed'
279
+ ? `no docker CLI available (${probe.detail}) — nothing was built and nothing was deployed.`
280
+ : `the docker daemon did not answer (${probe.detail}) — nothing was built and nothing was deployed.`;
281
+ const rerun = reissueCommand(opts);
282
+ const lines = [
283
+ headline,
284
+ 'two ways forward:',
285
+ probe.reason === 'not-installed'
286
+ ? '1) install Docker (https://docs.docker.com/get-docker/), then re-run: ' + rerun
287
+ : '1) start Docker (Docker Desktop, `colima start`, or `sudo systemctl start docker`), then re-run: ' + rerun,
288
+ '2) skip the local build entirely — deploy an image that is already pushed, by digest:',
289
+ ` ${rerun} --image ${(0, shell_1.shellQuote)('<registry>/<spid>/<slug>@sha256:<64-hex>')}`,
290
+ ' (any machine or CI job that can push the image can produce that digest: `docker push` prints it, ' +
291
+ "and `docker image inspect --format '{{index .RepoDigests 0}}' <tag>` re-reads it)",
292
+ ];
293
+ return lines.join('\n');
294
+ }
295
+ /** The command the user just ran, minus the flags that would change its meaning. */
296
+ function reissueCommand(opts) {
297
+ const parts = ['supercli deploy'];
298
+ if (opts.spid)
299
+ parts.push(`--spid ${(0, shell_1.shellQuote)(opts.spid)}`);
300
+ if (opts.slug)
301
+ parts.push(`--slug ${(0, shell_1.shellQuote)(opts.slug)}`);
302
+ if (opts.env)
303
+ parts.push(`--env ${(0, shell_1.shellQuote)(opts.env)}`);
304
+ if (opts.dir)
305
+ parts.push(`--dir ${(0, shell_1.shellQuote)(opts.dir)}`);
306
+ if (opts.port)
307
+ parts.push(`--port ${(0, shell_1.shellQuote)(opts.port)}`);
308
+ return parts.join(' ');
309
+ }
310
+ // ---------------------------------------------------------------------------
311
+ // AC-9: non-root rejection → a Dockerfile the user can copy
312
+ // ---------------------------------------------------------------------------
313
+ const NON_ROOT_SIGNALS = [
314
+ 'runasnonroot',
315
+ 'run as root',
316
+ 'must run as non-root',
317
+ 'violates podsecurity',
318
+ 'podsecurity "restricted"',
319
+ 'allowprivilegeescalation',
320
+ 'container has runasnonroot',
321
+ ];
322
+ function isNonRootRejection(text) {
323
+ if (!text)
324
+ return false;
325
+ const haystack = text.toLowerCase();
326
+ return NON_ROOT_SIGNALS.some((signal) => haystack.includes(signal));
327
+ }
328
+ /**
329
+ * The remediation is a Dockerfile fragment, not prose: the fix is two lines, and
330
+ * a user staring at `container has runAsNonRoot and image will run as root` has
331
+ * no way to guess that the cluster's Pod Security admission is what rejected it.
332
+ *
333
+ * 🔴 A NUMERIC uid is what the cluster can actually verify. `USER app` alone
334
+ * leaves the uid to be resolved from the image's /etc/passwd at runtime, which
335
+ * `runAsNonRoot` admission cannot do — the pod is rejected again, and the user
336
+ * concludes the hint was wrong.
337
+ */
338
+ exports.NON_ROOT_REMEDIATION = [
339
+ 'the cluster refuses images that run as root. add a non-root user to your Dockerfile and redeploy:',
340
+ '',
341
+ ' # debian/ubuntu base',
342
+ ' RUN useradd --uid 10001 --create-home app',
343
+ ' USER 10001',
344
+ '',
345
+ ' # alpine base',
346
+ ' RUN adduser -D -u 10001 app',
347
+ ' USER 10001',
348
+ '',
349
+ ' 🔴 use the NUMERIC uid in `USER` (`USER 10001`, not `USER app`): the admission check runs before',
350
+ ' the image filesystem is consulted, so a name-only USER still reads as "may run as root".',
351
+ ' also make sure anything the process writes to (cache dirs, /tmp files) is writable by that uid.',
352
+ ].join('\n');
353
+ function withNonRootHint(message) {
354
+ return isNonRootRejection(message) ? `${message}\n\n${exports.NON_ROOT_REMEDIATION}` : message;
355
+ }
356
+ // ---------------------------------------------------------------------------
357
+ // AC-5 (CLI half): the last N startup lines, attached to the failure
358
+ // ---------------------------------------------------------------------------
359
+ function extractLogLines(payload) {
360
+ const record = asRecord(payload);
361
+ const lines = record?.lines;
362
+ if (Array.isArray(lines)) {
363
+ return lines.filter((line) => typeof line === 'string');
364
+ }
365
+ if (typeof lines === 'string')
366
+ return lines.split('\n');
367
+ if (typeof payload === 'string')
368
+ return payload.split('\n');
369
+ return [];
370
+ }
371
+ async function tailStartupLogs(auth, deps, client, context, spid, slug, env, tail) {
372
+ const outcome = await withAuth(auth, deps, (token) => client.logs({ ...context, accessToken: token }, spid, slug, env, tail));
373
+ if (outcome.kind !== 'outcome') {
374
+ return { lines: [], note: 'startup logs could not be read: the credential is no longer valid' };
375
+ }
376
+ if (outcome.outcome.kind !== 'success' && outcome.outcome.kind !== 'soft_success') {
377
+ return { lines: [], note: `startup logs are not available yet (${nonSuccessMessage(outcome.outcome, 'reading startup logs')})` };
378
+ }
379
+ const lines = extractLogLines(valueFromOutcome(outcome.outcome));
380
+ return lines.length > 0 ? { lines } : { lines: [], note: 'the container produced no startup output' };
381
+ }
382
+ async function runDeploy(opts, deps = exports.defaultDeployDeps) {
383
+ // ---- 1. local validation, before any I/O ----
384
+ const spid = trimFlag(opts.spid);
385
+ const slug = trimFlag(opts.slug);
386
+ const env = trimFlag(opts.env);
387
+ if (!spid || !slug || !env) {
388
+ return { ok: false, message: '--spid, --slug and --env are all required — the project, service and environment are never guessed' };
389
+ }
390
+ if (!SPID_PATTERN.test(spid))
391
+ return { ok: false, message: 'invalid --spid: must be 8 lowercase letters or digits' };
392
+ if (!SLUG_PATTERN.test(slug) || RESERVED_SLUGS.has(slug)) {
393
+ return { ok: false, message: 'invalid --slug: must be 1-32 lowercase letters or digits, and must not be `stg` or `site`' };
394
+ }
395
+ if (!ENV_PATTERN.test(env))
396
+ return { ok: false, message: 'invalid --env: must be 1-10 lowercase letters or digits' };
397
+ const name = trimFlag(opts.name) ?? slug;
398
+ if (Array.from(name).length > 50)
399
+ return { ok: false, message: 'invalid --name: must be 1-50 characters' };
400
+ const port = parseIntFlag(opts.port, '--port', SPEC_LIMITS.port);
401
+ if (!port.ok)
402
+ return { ok: false, message: port.message };
403
+ const cpu = parseIntFlag(opts.cpu, '--cpu', SPEC_LIMITS.cpu);
404
+ if (!cpu.ok)
405
+ return { ok: false, message: cpu.message };
406
+ const memory = parseIntFlag(opts.memory, '--memory', SPEC_LIMITS.memory);
407
+ if (!memory.ok)
408
+ return { ok: false, message: memory.message };
409
+ const maxScale = parseIntFlag(opts.maxScale, '--max-scale', SPEC_LIMITS.maxScale);
410
+ if (!maxScale.ok)
411
+ return { ok: false, message: maxScale.message };
412
+ const logTail = parseIntFlag(opts.logTail, '--log-tail', { min: 1, max: 2_000 });
413
+ if (!logTail.ok)
414
+ return { ok: false, message: logTail.message };
415
+ const envVars = collectEnvVars(opts);
416
+ if (!envVars.ok)
417
+ return { ok: false, message: envVars.message };
418
+ // ---- 2. image plan + path existence (still local, still free) ----
419
+ const explicitImage = trimFlag(opts.image);
420
+ const plan = { mode: explicitImage ? 'prebuilt' : 'build' };
421
+ if (explicitImage) {
422
+ const split = (0, registry_1.splitDigestRef)(explicitImage);
423
+ if (!split) {
424
+ return {
425
+ ok: false,
426
+ message: `invalid --image "${explicitImage}": it must be pinned to a digest, e.g. registry/spid/slug@sha256:<64-hex>. ` +
427
+ "read it back with `docker image inspect --format '{{index .RepoDigests 0}}' <tag>`, or drop --image and let deploy build and push for you",
428
+ };
429
+ }
430
+ plan.imageRef = explicitImage;
431
+ plan.digest = split.digest;
432
+ plan.repository = split.repository;
433
+ }
434
+ else {
435
+ const contextDir = path.resolve(trimFlag(opts.dir) ?? '.');
436
+ const dockerfile = trimFlag(opts.dockerfile) ? path.resolve(opts.dockerfile) : path.join(contextDir, 'Dockerfile');
437
+ const dirState = deps.statPath(contextDir);
438
+ if (dirState === 'missing')
439
+ return { ok: false, message: `build context does not exist: ${contextDir} — nothing was built or deployed` };
440
+ if (dirState !== 'dir')
441
+ return { ok: false, message: `build context is not a directory: ${contextDir} — --dir takes a directory` };
442
+ const fileState = deps.statPath(dockerfile);
443
+ if (fileState === 'missing') {
444
+ return {
445
+ ok: false,
446
+ message: `no Dockerfile at ${dockerfile} — point at one with --dockerfile, or deploy an already-pushed image with ` +
447
+ '--image <ref@sha256:…>',
448
+ };
449
+ }
450
+ if (fileState !== 'file')
451
+ return { ok: false, message: `--dockerfile is not a regular file: ${dockerfile}` };
452
+ plan.contextDir = contextDir;
453
+ plan.dockerfile = dockerfile;
454
+ }
455
+ // ---- 3. auth (env token wins; a 401 is terminal, never retried) ----
456
+ const auth = resolveAuth(deps);
457
+ if ('ok' in auth)
458
+ return auth;
459
+ // ---- 4. org ----
460
+ let orgId;
461
+ const explicitOrg = trimFlag(opts.org);
462
+ if (explicitOrg) {
463
+ const resolution = (0, orgResolve_1.resolveOrgId)([], explicitOrg);
464
+ if (resolution.kind !== 'resolved')
465
+ return { ok: false, message: '--org must be a positive integer' };
466
+ orgId = resolution.orgId;
467
+ }
468
+ else {
469
+ const who = await withAuth(auth, deps, (token) => deps.fetchWhoami(auth.apiOrigin, token));
470
+ if (who.kind !== 'outcome')
471
+ return terminalResult();
472
+ if (who.outcome.kind !== 'success') {
473
+ return {
474
+ ok: false,
475
+ kind: failureKind(who.outcome.kind),
476
+ message: `cannot resolve the org bound to the current token: ${'message' in who.outcome ? who.outcome.message : who.outcome.kind}`,
477
+ };
478
+ }
479
+ orgId = String(who.outcome.data.org_id ?? '');
480
+ if (!orgId || orgId === '0')
481
+ return { ok: false, message: 'the current token is not bound to any org — nothing to deploy to' };
482
+ }
483
+ // ---- 5. registry coordinates (build path only) ----
484
+ // 🔴 EXT-R7: SUPERCLI_REGISTRY is narrowed to the same zone as auth.apiOrigin unless
485
+ // --allow-foreign-registry is explicit — see resolveRegistryHost's docstring.
486
+ const registryResolution = (0, registry_1.resolveRegistryHost)(auth.apiOrigin, {
487
+ allowForeignRegistry: Boolean(opts.allowForeignRegistry),
488
+ });
489
+ const registry = registryResolution.kind === 'resolved' ? registryResolution.host : undefined;
490
+ if (plan.mode === 'build' && registry) {
491
+ plan.repository = (0, registry_1.imageRepository)(registry, spid, slug);
492
+ }
493
+ const client = deps.createRunClient(auth.apiOrigin);
494
+ const context = { accessToken: auth.token, orgId };
495
+ const idempotencyKey = trimFlag(opts.idempotencyKey) ?? crypto.randomUUID();
496
+ const description = trimFlag(opts.description);
497
+ const envVarKeys = envVars.vars.filter((entry) => !entry.is_secret).map((entry) => entry.key);
498
+ const secretKeys = envVars.vars.filter((entry) => entry.is_secret).map((entry) => entry.key);
499
+ const body = () => ({
500
+ name,
501
+ slug,
502
+ env,
503
+ image_ref: plan.imageRef ?? `${plan.repository ?? slug}@${PLACEHOLDER_DIGEST}`,
504
+ image_digest: plan.digest ?? PLACEHOLDER_DIGEST,
505
+ port: port.value ?? SPEC_LIMITS.port.def,
506
+ ...(cpu.value !== undefined ? { cpu_milli: cpu.value } : {}),
507
+ ...(memory.value !== undefined ? { mem_mib: memory.value } : {}),
508
+ ...(maxScale.value !== undefined ? { max_scale: maxScale.value } : {}),
509
+ ...(envVars.vars.length > 0 ? { env_vars: envVars.vars } : {}),
510
+ ...(description ? { description } : {}),
511
+ });
512
+ /**
513
+ * The REDEPLOY body (IND-1) — narrower than create's on purpose: the service, its
514
+ * slug and its display name already exist, so a redeploy only carries the image and
515
+ * the runtime spec. `--name` is therefore inert on this path (documented on the flag),
516
+ * and `--env-var` / `--secret` are refused rather than silently dropped.
517
+ */
518
+ const deployBody = () => ({
519
+ image_ref: plan.imageRef ?? `${plan.repository ?? slug}@${PLACEHOLDER_DIGEST}`,
520
+ image_digest: plan.digest ?? PLACEHOLDER_DIGEST,
521
+ port: port.value ?? SPEC_LIMITS.port.def,
522
+ ...(cpu.value !== undefined ? { cpu_milli: cpu.value } : {}),
523
+ ...(memory.value !== undefined ? { mem_mib: memory.value } : {}),
524
+ ...(maxScale.value !== undefined ? { max_scale: maxScale.value } : {}),
525
+ });
526
+ // ---- 6. dry-run (AC-16): validate only. No image is built, none pushed, nothing created. ----
527
+ if (opts.dryRun) {
528
+ const notes = [];
529
+ if (plan.mode === 'build') {
530
+ if (!registry)
531
+ notes.push(registryIssueMessage(registryResolution, auth.apiOrigin));
532
+ // 🔴 A dry-run never builds, so there is no digest yet. Probing docker is
533
+ // read-only and worth reporting, but it must NOT fail the plan: the whole
534
+ // point of a dry-run is to answer "would this be accepted?", and the answer
535
+ // does not depend on this machine having a daemon right now.
536
+ const probe = deps.docker.probe();
537
+ if (!probe.available) {
538
+ notes.push(`docker is not usable on this machine right now (${probe.detail}); the real deploy would need it, ` +
539
+ 'or an already-pushed --image <ref@sha256:…>');
540
+ }
541
+ notes.push('the image digest is decided at build time — this plan validated everything except the digest itself');
542
+ }
543
+ const validated = await withAuth(auth, deps, (token) => client.createService({ ...context, accessToken: token }, spid, { ...body(), dry_run: true }));
544
+ if (validated.kind !== 'outcome')
545
+ return terminalResult();
546
+ if (validated.outcome.kind !== 'success' && validated.outcome.kind !== 'soft_success') {
547
+ return {
548
+ ok: false,
549
+ kind: failureKind(validated.outcome.kind),
550
+ message: withNonRootHint(nonSuccessMessage(validated.outcome, 'deploy validation')),
551
+ };
552
+ }
553
+ const serverPlan = valueFromOutcome(validated.outcome);
554
+ return {
555
+ ok: true,
556
+ message: [`dry-run validated: ${spid}/${slug}/${env} (nothing built, nothing pushed, no service created)`, ...notes].join('; '),
557
+ result: {
558
+ dryRun: true,
559
+ spid,
560
+ slug,
561
+ env,
562
+ name,
563
+ image: {
564
+ mode: plan.mode,
565
+ ...(plan.imageRef ? { ref: plan.imageRef } : {}),
566
+ ...(plan.digest ? { digest: plan.digest } : { digest: null }),
567
+ ...(plan.repository ? { repository: plan.repository } : {}),
568
+ },
569
+ port: port.value ?? SPEC_LIMITS.port.def,
570
+ cpu_milli: cpu.value ?? null,
571
+ mem_mib: memory.value ?? null,
572
+ max_scale: maxScale.value ?? null,
573
+ // 🔴 keys only. A value never leaves this process in any output channel.
574
+ env_var_keys: envVarKeys,
575
+ secret_keys: secretKeys,
576
+ // 🔴 IND-9: echoed, not stored — the Console API has no field for it (see the flag's help).
577
+ ...(description ? { description } : {}),
578
+ idempotency_key: idempotencyKey,
579
+ notes,
580
+ plan: serverPlan,
581
+ },
582
+ };
583
+ }
584
+ // ---- 7. build + push (skipped for a digest-pinned --image) ----
585
+ if (plan.mode === 'build') {
586
+ if (!registry)
587
+ return { ok: false, message: registryIssueMessage(registryResolution, auth.apiOrigin) };
588
+ // AC-16: probe FIRST, so a machine without docker gets the downgrade path
589
+ // instead of an ENOENT stack from deep inside a spawn.
590
+ const probe = deps.docker.probe();
591
+ if (!probe.available) {
592
+ return { ok: false, message: dockerUnavailableMessage(probe, opts) };
593
+ }
594
+ const repository = plan.repository;
595
+ const tag = (0, registry_1.imageTag)(repository, env);
596
+ const credential = {
597
+ registry,
598
+ username: registry_1.REGISTRY_BASIC_USERNAME,
599
+ // 🔴 AC-17: this token goes into a throwaway DOCKER_CONFIG directory inside
600
+ // the facade and is removed when the build finishes. The user is never asked
601
+ // to `docker login`, and ~/.docker/config.json is neither read nor written.
602
+ secret: auth.token,
603
+ };
604
+ log_1.log.info(`building ${tag} from ${plan.dockerfile}`);
605
+ const built = await deps.docker.buildAndPush({
606
+ credential,
607
+ dockerfile: plan.dockerfile,
608
+ context: plan.contextDir,
609
+ tag,
610
+ ...(trimFlag(opts.platform) ? { platform: trimFlag(opts.platform) } : {}),
611
+ ...(opts.buildArg && opts.buildArg.length > 0 ? { buildArgs: opts.buildArg } : {}),
612
+ });
613
+ if (!built.ok) {
614
+ return {
615
+ ok: false,
616
+ message: withNonRootHint(`docker ${built.stage} failed: ${built.message} — nothing was deployed`),
617
+ };
618
+ }
619
+ plan.digest = built.digest;
620
+ plan.imageRef = (0, registry_1.digestRef)(repository, built.digest);
621
+ log_1.log.info(`pushed ${plan.imageRef}`);
622
+ }
623
+ // ---- 8. create the service, or REDEPLOY it if it is already there (IND-1) ----
624
+ //
625
+ // 🔴 `deploy` must be runnable twice. Before this, the second run of the very same
626
+ // command died on SITE_SLUG_DUPLICATE with "pick another --slug" — i.e. the deploy
627
+ // tool worked exactly once per service.
628
+ //
629
+ // Create FIRST, then disambiguate the collision. Probing first reads simpler but is
630
+ // worse in three concrete ways:
631
+ // · it spends a round trip on every first deploy, which is the common case;
632
+ // · a probe that fails transiently would have to either guess or fail a perfectly
633
+ // good create — reacting to what the server actually answered never can;
634
+ // · probe→create leaves a TOCTOU window; here the unique index is the arbiter and
635
+ // the CLI only interprets its verdict.
636
+ //
637
+ // The one extra GET is what separates the two meanings of SITE_SLUG_DUPLICATE: the
638
+ // name pool is per PROJECT and shared with static sites and with other environments,
639
+ // so "duplicate" alone does NOT imply "your own service, deploy again".
640
+ const attempt = await withAuth(auth, deps, (token) => client.createService({ ...context, accessToken: token }, spid, body(), idempotencyKey));
641
+ if (attempt.kind !== 'outcome')
642
+ return terminalResult();
643
+ let outcome = attempt.outcome;
644
+ let mode = 'create';
645
+ if (outcome.kind === 'business_error' && outcome.code === 'SITE_SLUG_DUPLICATE') {
646
+ const probe = await withAuth(auth, deps, (token) => client.getService({ ...context, accessToken: token }, spid, slug, env));
647
+ if (probe.kind !== 'outcome')
648
+ return terminalResult();
649
+ // Not readable as an existing service in THIS env (NOT_FOUND, or a read we cannot
650
+ // trust) ⇒ leave the create failure standing; describeRunError explains the real
651
+ // collision. Never redeploy something we did not confirm.
652
+ if (probe.outcome.kind === 'success' || probe.outcome.kind === 'soft_success') {
653
+ // 🔴 The redeploy contract carries no env vars. Accepting them here would mean
654
+ // `--secret DATABASE_URL` quietly doing nothing on every run after the first.
655
+ if (envVars.vars.length > 0) {
656
+ return { ok: false, kind: 'business_error', message: redeployEnvVarsMessage(spid, slug, env) };
657
+ }
658
+ const redeployed = await withAuth(auth, deps, (token) => client.deployService({ ...context, accessToken: token }, spid, slug, env, deployBody(), idempotencyKey));
659
+ if (redeployed.kind !== 'outcome')
660
+ return terminalResult();
661
+ mode = 'redeploy';
662
+ outcome = redeployed.outcome;
663
+ }
664
+ }
665
+ if (outcome.kind !== 'success' && outcome.kind !== 'soft_success') {
666
+ return {
667
+ ok: false,
668
+ kind: failureKind(outcome.kind),
669
+ message: withNonRootHint(nonSuccessMessage(outcome, mode === 'redeploy' ? 'redeploying the container service' : 'creating the container service')),
670
+ };
671
+ }
672
+ let view = valueFromOutcome(outcome);
673
+ const idempotentReplay = asRecord(view)?.idempotent_replay === true;
674
+ if (idempotentReplay) {
675
+ // The server replayed the first request with this key and answered with just
676
+ // the service id — re-read the service so the caller still gets a full view.
677
+ const reread = await withAuth(auth, deps, (token) => client.getService({ ...context, accessToken: token }, spid, slug, env));
678
+ if (reread.kind !== 'outcome')
679
+ return terminalResult();
680
+ if (reread.outcome.kind === 'success' || reread.outcome.kind === 'soft_success') {
681
+ view = valueFromOutcome(reread.outcome);
682
+ }
683
+ }
684
+ // ---- 9. readiness ----
685
+ let status = stringField(view, 'status') ?? 'provisioning';
686
+ let attempts = 0;
687
+ while (status === 'provisioning' && attempts < deps.pollAttempts) {
688
+ attempts += 1;
689
+ await deps.sleep(deps.pollIntervalMs);
690
+ const polled = await withAuth(auth, deps, (token) => client.getService({ ...context, accessToken: token }, spid, slug, env));
691
+ if (polled.kind !== 'outcome')
692
+ return terminalResult();
693
+ if (polled.outcome.kind !== 'success' && polled.outcome.kind !== 'soft_success') {
694
+ // A transient read failure must not be reported as a deploy failure: the
695
+ // service was created, we simply cannot see its state right now.
696
+ break;
697
+ }
698
+ view = valueFromOutcome(polled.outcome);
699
+ status = stringField(view, 'status') ?? status;
700
+ }
701
+ const domain = stringField(view, 'domain');
702
+ const label = stringField(view, 'label');
703
+ const statusReason = stringField(view, 'status_reason');
704
+ const baseResult = {
705
+ dryRun: false,
706
+ spid,
707
+ slug,
708
+ env,
709
+ name,
710
+ /** `create` on the first deploy of this (slug, env), `redeploy` on every one after (IND-1). */
711
+ mode,
712
+ image: { mode: plan.mode, ref: plan.imageRef, digest: plan.digest, ...(plan.repository ? { repository: plan.repository } : {}) },
713
+ port: port.value ?? SPEC_LIMITS.port.def,
714
+ env_var_keys: envVarKeys,
715
+ secret_keys: secretKeys,
716
+ // 🔴 IND-9: echoed, not stored — the Console API has no field for it (see the flag's help).
717
+ ...(description ? { description } : {}),
718
+ idempotency_key: idempotencyKey,
719
+ idempotent_replay: idempotentReplay,
720
+ status,
721
+ ...(domain ? { domain } : {}),
722
+ ...(label ? { label } : {}),
723
+ service: view,
724
+ };
725
+ if (status === 'failed' || status === 'timeout') {
726
+ const tail = logTail.value ?? 50;
727
+ const logs = await tailStartupLogs(auth, deps, client, context, spid, slug, env, tail);
728
+ const reason = statusReason ?? (status === 'timeout' ? 'the container did not become ready in time' : 'the container failed to start');
729
+ const parts = [`deploy ${status}: ${reason}`];
730
+ if (logs.lines.length > 0) {
731
+ parts.push(`last ${logs.lines.length} startup log line(s):\n${logs.lines.map((line) => ` | ${line}`).join('\n')}`);
732
+ }
733
+ else if (logs.note) {
734
+ parts.push(logs.note);
735
+ }
736
+ parts.push(`for more context re-run with a larger --log-tail (e.g. --log-tail ${Math.min(tail * 4, 2_000)}), or open the service page in the Console`);
737
+ return { ok: false, kind: 'business_error', message: withNonRootHint(parts.join('\n')) };
738
+ }
739
+ if (status === 'provisioning') {
740
+ // 🔴 The "how do I poll this?" answer differs by path: an idempotency key replays a
741
+ // CREATE, but a redeploy is guarded by the server's state machine instead (a redeploy
742
+ // is refused while the previous one is still `provisioning`), so retrying the same
743
+ // command cannot stack revisions either way. Saying the wrong one is worse than
744
+ // saying nothing.
745
+ const pollHint = mode === 'redeploy'
746
+ ? 're-run the same command to check on it — while it is still `provisioning` the server refuses another ' +
747
+ 'redeploy, so a retry cannot stack a second revision'
748
+ : `re-run the same command with --idempotency-key ${(0, shell_1.shellQuote)(idempotencyKey)} to poll it without creating a second service`;
749
+ return {
750
+ ok: true,
751
+ soft: true,
752
+ message: `accepted: ${spid}/${slug}/${env} is still starting after ${attempts} check(s) — the ` +
753
+ `${mode === 'redeploy' ? 'redeploy' : 'deploy'} is recorded and will converge; ${pollHint}`,
754
+ result: { ...baseResult, pending: true },
755
+ };
756
+ }
757
+ const reachable = domain ? `reachable at https://${domain}` : 'find the public domain on the service page in the Console';
758
+ return {
759
+ ok: true,
760
+ message: `${mode === 'redeploy' ? 'redeployed' : 'deployed'} ${spid}/${slug}/${env} (${status}); ${reachable}`,
761
+ result: { ...baseResult, pending: false },
762
+ };
763
+ }
764
+ /**
765
+ * 🔴 IND-1/IND-9 discipline: a flag that cannot be honoured must fail loudly, not be
766
+ * dropped. The redeploy contract has no `env_vars`, so a second `deploy` carrying
767
+ * `--secret`/`--env-var` would otherwise roll out the new image while silently ignoring
768
+ * the variables the caller believes it just set.
769
+ */
770
+ function redeployEnvVarsMessage(spid, slug, env) {
771
+ return [
772
+ `${spid}/${slug}/${env} already exists, so this run is a REDEPLOY — and --env-var / --secret are only honoured ` +
773
+ 'when the service is first created: the redeploy API carries the image and the runtime spec, not environment variables.',
774
+ 'refusing rather than dropping them silently. nothing was redeployed (the image is already pushed, so nothing is lost).',
775
+ 'two ways forward:',
776
+ '1) drop --env-var / --secret and re-run, to roll out just the new image;',
777
+ "2) set the variables on the service's Environment variables page in the Console — saving there redeploys with them.",
778
+ ].join('\n');
779
+ }
780
+ function registryUnresolvedNote(apiOrigin) {
781
+ return (`cannot work out which container registry to push to for ${apiOrigin} — set ${registry_1.SUPERCLI_REGISTRY_ENV}=<registry-host> ` +
782
+ 'explicitly, or deploy an already-pushed image with --image <ref@sha256:…>. ' +
783
+ '(the registry host is derived from the Console origin, e.g. console.supersdk.com → repo.supersdk.com)');
784
+ }
785
+ /**
786
+ * 🔴 EXT-R7: `SUPERCLI_REGISTRY` names a host outside `apiOrigin`'s own zone.
787
+ * The registry login sends the caller's full-power console token as the Basic
788
+ * password (see `resolveRegistryHost`'s docstring), so refusing by default —
789
+ * and requiring an explicit, auditable `--allow-foreign-registry` to proceed —
790
+ * keeps that token from being handed to an unrelated host by a stray/typo'd
791
+ * env var.
792
+ */
793
+ function registryForeignBlockedNote(host, zone) {
794
+ return (`refusing to push to ${registry_1.SUPERCLI_REGISTRY_ENV}=${host}: it is outside the ${zone} zone this account uses, and the ` +
795
+ 'registry login sends your full-power console token as the password — sending that to an unrelated host is a real ' +
796
+ 'credential-leak risk. Pass --allow-foreign-registry to push there anyway, unset ' +
797
+ `${registry_1.SUPERCLI_REGISTRY_ENV} to use the platform registry (repo.${zone}), or deploy an already-pushed image with ` +
798
+ '--image <ref@sha256:…>');
799
+ }
800
+ function registryIssueMessage(resolution, apiOrigin) {
801
+ return resolution.kind === 'blocked'
802
+ ? registryForeignBlockedNote(resolution.host, resolution.zone)
803
+ : registryUnresolvedNote(apiOrigin);
804
+ }
805
+ function registerDeployCommand(program) {
806
+ const collect = (value, previous = []) => previous.concat([value]);
807
+ program
808
+ .command('deploy')
809
+ .description('Build, push and deploy a container service (SuperRun). Run it again to redeploy the same service.')
810
+ .requiredOption('--spid <spid>', 'project spid (8 lowercase letters or digits)')
811
+ .requiredOption('--slug <slug>', 'service slug; shares the project name pool with static sites')
812
+ .requiredOption('--env <env>', 'project environment (prod, staging, …)')
813
+ .option('--name <name>', 'display name for a NEW service; defaults to the slug. Ignored when the service already exists — a redeploy does not rename it')
814
+ .option('--org <id>', 'organization id; defaults to the org bound to the current token')
815
+ .option('--dir <dir>', 'docker build context; defaults to the current directory')
816
+ .option('--dockerfile <path>', 'Dockerfile to build; defaults to <dir>/Dockerfile')
817
+ .option('--image <ref>', 'deploy an already-pushed, digest-pinned image (repo@sha256:…) and skip the local build')
818
+ .option('--platform <platform>', 'docker build platform; defaults to linux/amd64 (the cluster architecture)', 'linux/amd64')
819
+ .option('--build-arg <KEY=VALUE>', 'docker --build-arg, repeatable', collect)
820
+ .option('--port <port>', 'container port the service listens on', String(SPEC_LIMITS.port.def))
821
+ .option('--cpu <millicores>', 'CPU limit in millicores (1-4000)')
822
+ .option('--memory <MiB>', 'memory limit in MiB (1-8192)')
823
+ .option('--max-scale <n>', 'maximum number of replicas (1-10)')
824
+ // 🔴 IND-1: both env-var flags apply to a NEW service only. On a redeploy the command
825
+ // refuses them out loud rather than rolling out an image while dropping them.
826
+ .option('--env-var <KEY=VALUE>', 'plaintext environment variable for a NEW service, repeatable (KEY alone reads the value from the environment); not accepted on a redeploy', collect)
827
+ // 🔴 <KEY>, never <KEY=VALUE>: the value is read from the environment so it never lands on argv (TC-27).
828
+ .option('--secret <KEY>', 'secret environment variable NAME for a NEW service, repeatable; its value is read from the environment of the same name. Not accepted on a redeploy', collect)
829
+ // 🔴 IND-9: the Console API has no field for this today, so promising it is "recorded"
830
+ // would be a straight lie. It is echoed back in the result and nothing more.
831
+ .option('--description <description>', 'free-text note; NOT stored by the platform (the Console API has no such field) — echoed back in the result so a caller can correlate runs')
832
+ .option('--dry-run', 'validate locally + server-side without building, pushing or creating anything')
833
+ .option('--idempotency-key <key>', 'client idempotency key; replaying the same key returns the first deploy')
834
+ .option('--log-tail <n>', 'startup log lines to print when the deploy fails', '50')
835
+ .option('--allow-foreign-registry', `let ${registry_1.SUPERCLI_REGISTRY_ENV} point outside this account's own zone; the registry login sends your ` +
836
+ 'console token there as the password, so this is an explicit opt-in, never a default')
837
+ .action(async (options, cmd) => {
838
+ const mode = cmd.optsWithGlobals?.()?.output === 'json' ? 'json' : 'human';
839
+ const printer = new resultPrinter_1.ResultPrinter(mode);
840
+ const result = await runDeploy(options);
841
+ if (result.ok) {
842
+ printer.success(result.result ?? {}, { soft: result.soft, humanMessage: result.message });
843
+ }
844
+ else {
845
+ printer.failure(result.kind ?? 'business_error', result.message ?? 'deploy failed');
846
+ }
847
+ });
848
+ }
849
+ //# sourceMappingURL=deploy.js.map