@sequenceholdings/studio-cli 0.4.7 → 0.5.1

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.
@@ -2,7 +2,7 @@
2
2
  * Deploy lifecycle verbs for `seq-studio pipeline plan|deploy|promote|rollback`
3
3
  * (SEQ-2450). Wraps the /api/data-pipelines plan/deploy APIs.
4
4
  */
5
- import { getAccessToken, NotLoggedInError } from '../auth.js';
5
+ import { getAccessToken, getAccessTokenWithMode, NotLoggedInError } from '../auth.js';
6
6
  import { AtlasApiError, getJson, postJson } from '../atlas-client.js';
7
7
  import { resolveConfiguredEnv } from '../config.js';
8
8
  import { parseDurationMs } from '@sequenceholdings/lattice';
@@ -51,7 +51,7 @@ function deploymentStatusLabel(detail) {
51
51
  return `${detail.status} — ${detail.statusDetail}`;
52
52
  return detail.status;
53
53
  }
54
- export async function envAndToken(args) {
54
+ export async function envAndToken(args, options = {}) {
55
55
  const requested = typeof args.flags.e === 'string' ? args.flags.e : typeof args.flags.env === 'string' ? args.flags.env : undefined;
56
56
  if (!requested) {
57
57
  throw new Error('missing -e/--env <environment>');
@@ -59,7 +59,15 @@ export async function envAndToken(args) {
59
59
  const env = await resolveConfiguredEnv({ requested });
60
60
  let token;
61
61
  try {
62
- token = await getAccessToken({ env: env.name, targetUrl: env.url });
62
+ if (options.human) {
63
+ const auth = await getAccessTokenWithMode({ env: env.name, targetUrl: env.url });
64
+ if (auth.authMode !== 'user')
65
+ throw new Error('Publishing a local clone requires a user login. Run seq-studio login for this environment, then retry.');
66
+ token = auth.token;
67
+ }
68
+ else {
69
+ token = await getAccessToken({ env: env.name, targetUrl: env.url });
70
+ }
63
71
  }
64
72
  catch (error) {
65
73
  if (error instanceof NotLoggedInError)
@@ -201,7 +209,7 @@ export async function pipelineDeployCommand(args) {
201
209
  const runNow = flagOn(args.flags, 'run-now');
202
210
  const waitTimeoutMs = deploymentWaitTimeoutMs(args);
203
211
  const allowDestructiveResourceKeys = repeatedFlagStrings(args, 'allow-destructive');
204
- const { env, token } = await envAndToken(args);
212
+ const { env, token } = await envAndToken(args, { human: Boolean(dir) });
205
213
  let target;
206
214
  try {
207
215
  target = await resolvePipelineTarget({ args, env, token });
@@ -45,22 +45,13 @@ export declare function reposListCommand(args: ParsedArgs): Promise<number>;
45
45
  export declare function reposShowCommand(args: ParsedArgs): Promise<number>;
46
46
  export declare function reposCreateCommand(args: ParsedArgs): Promise<number>;
47
47
  export declare function reposPullCommand(args: ParsedArgs): Promise<number>;
48
- /**
49
- * Preferred clone verb.
50
- *
51
- * With `ATLAS_GIT_PAT`:
52
- * - `--url <clone-url>` or `--id <repo-uuid>` → smart-HTTP clone with no seqapi
53
- * - `<ns>/<name>` → needs Auth0 to resolve the UUID, then smart-HTTP clone
54
- * Without a PAT: JSON materialize (needs Auth0) + PAT setup hints.
55
- *
56
- * `gitClone` is injectable for tests.
57
- */
48
+ /** Git clone always uses the selected human login, never an ambient PAT. */
58
49
  export declare function reposCloneCommand(args: ParsedArgs, deps?: {
59
50
  gitClone?: RunGitClone;
60
51
  }): Promise<number>;
61
52
  /**
62
53
  * Validate clone URL shape and that the origin matches the resolved Atlas env
63
- * so askpass never sends ATLAS_GIT_PAT to an attacker-controlled host.
54
+ * so askpass never sends a login token to an attacker-controlled host.
64
55
  */
65
56
  export declare function normalizeCloneUrl(raw: string, env: ResolvedEnv): string;
66
57
  type DiscoveredCliCheck = {
@@ -5,9 +5,8 @@ import { REPOS_USAGE } from '../command-help.js';
5
5
  *
6
6
  * Everything here is API-driven (Auth0 bearer via seq-studio login), matching the
7
7
  * rest of seq-studio. `pull` materializes a tree over the JSON API; `clone`
8
- * prefers a real `git clone` when `ATLAS_GIT_PAT` is set (smart-HTTP URL from
9
- * `show`), otherwise falls back to the same JSON materialize path and hints
10
- * at `seq-studio auth pat create`.
8
+ * uses a real Git checkout and a login credential helper by default.
9
+ * Explicit JSON transport downloads files without a Git checkout.
11
10
  *
12
11
  * Repo addressing is `<namespace>/<name>` everywhere; the API is id-addressed,
13
12
  * so commands resolve the path via the namespaces + repos endpoints (the same
@@ -26,11 +25,8 @@ import { printCliError } from '../cli-errors.js';
26
25
  import { PREVIEW_DOMAIN } from '../preview.js';
27
26
  import { confirmYes } from '../prompt.js';
28
27
  import { buildContext, clientOptions, flagBool, LOG, } from '../functions/commands.js';
29
- import { looksLikeCommitSha, resolveGitPatFromEnv, runGitClone, } from './git-clone.js';
30
- import { formatPatSetupHint } from '../pat-hints.js';
31
- import { tryGetAccessToken } from '../auth.js';
32
- import { resolveConfiguredEnv } from '../config.js';
33
- import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
28
+ import { looksLikeCommitSha, runGitClone, } from './git-clone.js';
29
+ import { configureGitLogin } from './git-credential.js';
34
30
  const PAGE_SIZE = 200;
35
31
  // ---------------------------------------------------------------------------
36
32
  // Helpers
@@ -256,7 +252,7 @@ export async function reposShowCommand(args) {
256
252
  }
257
253
  console.log(` created: ${shortDate(repo.createdAt)} by ${repo.createdBy}`);
258
254
  console.log(` updated: ${shortDate(repo.updatedAt)}`);
259
- console.log(` clone (PAT as basic-auth password): ${cloneUrl(ctx, repo.id)}`);
255
+ console.log(` clone (seq-studio login): ${cloneUrl(ctx, repo.id)}`);
260
256
  // Best-effort cross-link to a matching Artifact Studio project on this env
261
257
  // (same slug as the repo name). Failures are silent — not every repo is an
262
258
  // artifact, and the projects endpoint may 403 for some principals.
@@ -348,166 +344,83 @@ export async function reposPullCommand(args) {
348
344
  verb: 'pulled',
349
345
  });
350
346
  }
351
- /**
352
- * Preferred clone verb.
353
- *
354
- * With `ATLAS_GIT_PAT`:
355
- * - `--url <clone-url>` or `--id <repo-uuid>` → smart-HTTP clone with no seqapi
356
- * - `<ns>/<name>` → needs Auth0 to resolve the UUID, then smart-HTTP clone
357
- * Without a PAT: JSON materialize (needs Auth0) + PAT setup hints.
358
- *
359
- * `gitClone` is injectable for tests.
360
- */
361
- export async function reposCloneCommand(args, deps = {}) {
347
+ function parseCloneOptions(args) {
362
348
  const force = flagBool(args.flags, 'force');
363
- const full = flagBool(args.flags, 'full');
364
349
  const ref = stringFlag(args.flags, 'ref');
365
- const depth = smartHttpCloneDepth({ ref, full });
350
+ const depth = smartHttpCloneDepth({ ref, full: flagBool(args.flags, 'full') });
366
351
  const outputFlag = stringFlag(args.flags, 'output');
367
352
  const outFlag = stringFlag(args.flags, 'out');
368
- if (outputFlag !== undefined && outFlag !== undefined) {
353
+ if (outputFlag !== undefined && outFlag !== undefined)
369
354
  throw new Error('Pass only one of --output or --out.');
370
- }
371
355
  const output = outputFlag ?? outFlag;
372
- const pat = resolveGitPatFromEnv();
373
- const transportFlag = stringFlag(args.flags, 'transport') ?? 'auto';
374
- if (!['auto', 'git', 'json'].includes(transportFlag)) {
375
- throw new Error('--transport must be one of: auto, git, json.');
376
- }
377
- const transport = transportFlag;
378
356
  const urlFlag = stringFlag(args.flags, 'url');
379
357
  const idFlag = stringFlag(args.flags, 'id');
380
358
  const positional = args.positional[0];
381
- if (urlFlag && idFlag) {
359
+ if (urlFlag && idFlag)
382
360
  throw new Error('Pass only one of --url or --id.');
383
- }
384
- if ((urlFlag || idFlag) && positional) {
361
+ if ((urlFlag || idFlag) && positional)
385
362
  throw new Error('Pass either <ns>/<name> or --url/--id, not both.');
363
+ const transport = stringFlag(args.flags, 'transport') ?? 'auto';
364
+ if (!['auto', 'git', 'json'].includes(transport))
365
+ throw new Error('--transport must be one of: auto, git, json.');
366
+ if (transport === 'json' && !positional)
367
+ throw new Error('--transport json requires <namespace>/<name>.');
368
+ return { force, ref, depth, output, urlFlag, idFlag, positional, transport };
369
+ }
370
+ async function gitCloneContext(args) {
371
+ const ctx = await reposContext(args);
372
+ if (ctx.authMode === 'm2m') {
373
+ throw new Error(`Git clone requires a user login: seq-studio login --env ${ctx.env.name}. Use repos pull for M2M JSON materialization.`);
386
374
  }
387
- // --url/--id are PAT-only (no JSON materialize for a bare UUID/URL).
388
- if ((urlFlag || idFlag) && (!pat || transport === 'json')) {
389
- const env = await resolveEnvOnly(args);
390
- const lines = [
391
- `${LOG} --url/--id requires ATLAS_GIT_PAT and Git transport (JSON materialize needs <ns>/<name>).`,
392
- ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
393
- ];
394
- throw new Error(lines.join('\n'));
395
- }
396
- if (transport === 'git' && !pat) {
397
- const env = await resolveEnvOnly(args);
398
- throw new Error([
399
- `${LOG} --transport git requires ATLAS_GIT_PAT with repo:read access for ${env.name}.`,
400
- ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
401
- ].join('\n'));
402
- }
403
- // PAT-only path: clone by URL or repo UUID without seqapi/Auth0.
404
- if (pat && (urlFlag || idFlag)) {
405
- const env = await resolveEnvOnly(args);
406
- const targetUrl = urlFlag
407
- ? normalizeCloneUrl(urlFlag, env)
408
- : cloneUrl({ env, token: '' }, idFlag);
409
- const destDir = resolve(output ?? defaultOutFromCloneTarget({ url: targetUrl, id: idFlag }));
410
- prepareCloneDest({ destDir, force });
411
- const clone = deps.gitClone ?? runGitClone;
412
- await clone({
413
- cloneUrl: targetUrl,
414
- destDir,
415
- pat,
416
- ...(ref ? { ref } : {}),
417
- ...(depth != null ? { depth } : {}),
418
- }).catch((error) => {
419
- throw withGitAuthHint({ error, envName: env.name });
420
- });
421
- console.log(`${LOG} cloned ${targetUrl} → ${destDir}` +
422
- (ref ? ` (ref ${ref})` : '') +
423
- ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
424
- return 0;
425
- }
426
- // <ns>/<name> path — needs Auth0 for resolveRepo (JSON API) whether or not
427
- // we then use smart-HTTP. Without Auth0, point users at --url from the UI.
428
- if (!positional) {
375
+ return ctx;
376
+ }
377
+ /** Git clone always uses the selected human login, never an ambient PAT. */
378
+ export async function reposCloneCommand(args, deps = {}) {
379
+ const { force, ref, depth, output, urlFlag, idFlag, positional, transport } = parseCloneOptions(args);
380
+ if (!positional && !urlFlag && !idFlag) {
429
381
  console.error('usage: seq-studio repos clone <ns>/<name> | --url <clone-url> | --id <uuid> -e <env> [--ref r] [--output dir] [--full]');
430
382
  return 1;
431
383
  }
432
- const { namespace, name } = parseRepoPath(positional);
433
- const token = await tryGetAccessToken();
434
- if (!token) {
435
- const env = await resolveEnvOnly(args);
436
- const lines = pat
437
- ? [
438
- `ATLAS_GIT_PAT is set, but resolving ${namespace}/${name} needs Auth0 (` +
439
- `seq-studio login).`,
440
- ` Or copy the clone URL from Repositories → Clone, then:`,
441
- ` ATLAS_GIT_PAT=<token> seq-studio repos clone --url <https://…/repos/<id>/git> -e ${env.name}`,
442
- ]
443
- : [
444
- `${LOG} no ATLAS_GIT_PAT and not logged in.`,
445
- ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
446
- ` Then: seq-studio repos clone ${namespace}/${name} -e ${env.name}`,
447
- ];
448
- throw new Error(lines.join('\n'));
449
- }
450
- const ctx = await reposContext(args);
451
- const destDir = resolve(output ?? name);
452
- if (pat && transport !== 'json') {
453
- prepareCloneDest({ destDir, force });
384
+ if (transport === 'json') {
385
+ const { namespace, name } = parseRepoPath(positional);
386
+ const ctx = await reposContext(args);
387
+ const destDir = resolve(output ?? name);
388
+ assertDestWritable({ destDir, force });
389
+ console.log(`${LOG} materializing via JSON API as the signed-in Atlas identity (no .git dir; ignoring ATLAS_GIT_PAT).`);
390
+ return materializeTree({ ctx, namespace, name, destDir, ref, verb: 'cloned' });
391
+ }
392
+ const ctx = await gitCloneContext(args);
393
+ const env = ctx.env;
394
+ let targetUrl;
395
+ let defaultOut;
396
+ if (positional) {
397
+ const { namespace, name } = parseRepoPath(positional);
454
398
  const resolved = await resolveRepo({ ...clientOptions(ctx), namespace, name });
455
- const targetUrl = cloneUrl(ctx, resolved.id);
456
- const clone = deps.gitClone ?? runGitClone;
457
- await clone({
458
- cloneUrl: targetUrl,
459
- destDir,
460
- pat,
461
- ...(ref ? { ref } : {}),
462
- ...(depth != null ? { depth } : {}),
463
- }).catch((error) => {
464
- throw withGitAuthHint({ error, envName: ctx.env.name });
465
- });
466
- console.log(`${LOG} cloned ${namespace}/${name} → ${destDir}` +
467
- (ref ? ` (ref ${ref})` : '') +
468
- ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
469
- return 0;
470
- }
471
- assertDestWritable({ destDir, force });
472
- console.log(transport === 'json'
473
- ? `${LOG} materializing via JSON API as the signed-in Atlas identity (no .git dir; ignoring ATLAS_GIT_PAT).`
474
- : `${LOG} no ATLAS_GIT_PAT — materializing via JSON API (no .git dir).`);
475
- for (const line of formatPatSetupHint({ envUrl: ctx.env.url, envName: ctx.env.name })) {
476
- console.log(line);
477
- }
478
- return materializeTree({
479
- ctx,
480
- namespace,
481
- name,
482
- destDir,
483
- ref,
484
- verb: 'cloned',
399
+ targetUrl = cloneUrl(ctx, resolved.id);
400
+ defaultOut = name;
401
+ }
402
+ else {
403
+ targetUrl = urlFlag ?? cloneUrl({ env, token: '' }, idFlag);
404
+ defaultOut = defaultOutFromCloneTarget({ url: targetUrl, id: idFlag });
405
+ }
406
+ targetUrl = normalizeCloneUrl(targetUrl, env);
407
+ const destDir = resolve(output ?? defaultOut);
408
+ prepareCloneDest({ destDir, force });
409
+ await (deps.gitClone ?? runGitClone)({
410
+ cloneUrl: targetUrl, destDir, pat: ctx.token,
411
+ ...(ref ? { ref } : {}),
412
+ ...(depth != null ? { depth } : {}),
485
413
  });
486
- }
487
- function withGitAuthHint({ error, envName }) {
488
- const message = error instanceof Error ? error.message : String(error);
489
- if (!/(authentication failed|could not read username|http\s*(401|403)|returned error:\s*(401|403))/i.test(message)) {
490
- return error instanceof Error ? error : new Error(message);
491
- }
492
- return new Error(`${message}\n${LOG} Git-service rejected ATLAS_GIT_PAT for ${envName}. Check that it is current and has repo:read access for this environment. ` +
493
- `If your signed-in Atlas account can read the repo, retry with --transport json to materialize without using the ambient PAT (this creates no .git directory).`, { cause: error });
494
- }
495
- /** Resolve -e/--env without requiring Auth0 (for PAT-only --url/--id clones). */
496
- async function resolveEnvOnly(args) {
497
- if (args.flags.env === true || args.flags.e === true) {
498
- throw new Error('-e/--env requires a value — see: seq-studio envs list.');
499
- }
500
- const requested = (typeof args.flags.env === 'string' ? args.flags.env : undefined) ??
501
- (typeof args.flags.e === 'string' ? args.flags.e : undefined);
502
- // Same contract as buildContext: never silently fall back to `local`.
503
- if (!requested) {
504
- throw new Error(REQUIRE_EXPLICIT_ENV_MESSAGE);
505
- }
506
- return resolveConfiguredEnv({ requested });
414
+ await configureGitLogin({ destDir, envName: env.name, cloneUrl: targetUrl });
415
+ console.log(`${LOG} cloned ${positional ?? targetUrl} → ${destDir}` +
416
+ (ref ? ` (ref ${ref})` : '') +
417
+ ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
418
+ console.log(`${LOG} git pull/push now use your seq-studio login. After expiry: seq-studio login --env ${env.name}`);
419
+ return 0;
507
420
  }
508
421
  /**
509
422
  * Validate clone URL shape and that the origin matches the resolved Atlas env
510
- * so askpass never sends ATLAS_GIT_PAT to an attacker-controlled host.
423
+ * so askpass never sends a login token to an attacker-controlled host.
511
424
  */
512
425
  export function normalizeCloneUrl(raw, env) {
513
426
  let url;
@@ -515,18 +428,19 @@ export function normalizeCloneUrl(raw, env) {
515
428
  url = new URL(raw);
516
429
  }
517
430
  catch {
518
- throw new Error(`--url must be a valid HTTPS clone URL (got "${raw}").`);
431
+ throw new Error('--url must be a valid HTTPS clone URL.');
519
432
  }
520
433
  if (url.protocol !== 'https:' && url.protocol !== 'http:') {
521
434
  throw new Error(`--url must be http(s) (got ${url.protocol}).`);
522
435
  }
523
- // HTTPS everywhere except local (http://localhost:5001).
524
- if (env.name !== 'local' && url.protocol !== 'https:') {
436
+ // Permit HTTP only on loopback, including registered local worktree servers.
437
+ if (url.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) {
525
438
  throw new Error(`--url must use HTTPS for ${env.name} (got ${url.protocol}).`);
526
439
  }
527
- url.username = '';
528
- url.password = '';
529
- if (!/\/api\/git-service\/repos\/[^/]+\/git\/?$/.test(url.pathname)) {
440
+ if (url.username || url.password || url.search || url.hash) {
441
+ throw new Error('--url must not contain credentials, query parameters, or a fragment.');
442
+ }
443
+ if (!/^\/api\/git-service\/repos\/[\w-]+(?:\/git|\.git)\/?$/.test(url.pathname)) {
530
444
  throw new Error(`--url must look like …/api/git-service/repos/<id>/git (got ${url.pathname}).`);
531
445
  }
532
446
  let expected;
@@ -545,7 +459,7 @@ export function normalizeCloneUrl(raw, env) {
545
459
  function defaultOutFromCloneTarget({ url, id, }) {
546
460
  if (id)
547
461
  return id;
548
- const match = /\/repos\/([^/]+)\/git\/?$/.exec(new URL(url).pathname);
462
+ const match = /\/repos\/([^/]+?)(?:\/git|\.git)\/?$/.exec(new URL(url).pathname);
549
463
  return match?.[1] ?? 'repo';
550
464
  }
551
465
  /**
@@ -1,10 +1 @@
1
- export { looksLikeCommitSha, redactCloneUrl, resolveGitPatFromEnv, runGitClone, withGitAskpass, type RunGitClone, } from '@sequenceholdings/artifact-studio/git-clone';
2
- /**
3
- * Write a credential via `git credential approve` so subsequent clones against
4
- * the same host can authenticate without embedding the PAT in the URL.
5
- */
6
- export declare function storeGitCredentials({ cloneUrl, pat, username, }: {
7
- cloneUrl: string;
8
- pat: string;
9
- username?: string;
10
- }): Promise<void>;
1
+ export { looksLikeCommitSha, redactCloneUrl, runGitClone, withGitAskpass, type RunGitClone, } from '@sequenceholdings/artifact-studio/git-clone';
@@ -1,49 +1 @@
1
- /**
2
- * Smart-HTTP git clone helpers for platform git-service.
3
- *
4
- * The clone primitives (askpass, runGitClone, PAT/URL helpers) are the
5
- * canonical implementation in `@sequenceholdings/artifact-studio/git-clone` so
6
- * the `repos` tool and the artifact `--repo` deploy path share one code path.
7
- * We re-export them here to keep the historical import site stable, and add
8
- * `storeGitCredentials` (git credential-helper writer) which is studio-cli
9
- * specific.
10
- */
11
- import { spawn } from 'node:child_process';
12
- export { looksLikeCommitSha, redactCloneUrl, resolveGitPatFromEnv, runGitClone, withGitAskpass, } from '@sequenceholdings/artifact-studio/git-clone';
13
- /**
14
- * Write a credential via `git credential approve` so subsequent clones against
15
- * the same host can authenticate without embedding the PAT in the URL.
16
- */
17
- export async function storeGitCredentials({ cloneUrl, pat, username = 'git', }) {
18
- const parsed = new URL(cloneUrl);
19
- const protocol = parsed.protocol.replace(/:$/, '');
20
- const host = parsed.host;
21
- const path = parsed.pathname;
22
- const payload = [
23
- `protocol=${protocol}`,
24
- `host=${host}`,
25
- `path=${path}`,
26
- `username=${username}`,
27
- `password=${pat}`,
28
- '',
29
- ].join('\n');
30
- await new Promise((resolve, reject) => {
31
- const child = spawn('git', ['credential', 'approve'], {
32
- stdio: ['pipe', 'ignore', 'pipe'],
33
- });
34
- let stderr = '';
35
- child.stderr?.on('data', (chunk) => {
36
- stderr += chunk.toString();
37
- });
38
- child.on('error', (err) => reject(err));
39
- child.on('close', (code) => {
40
- if (code === 0) {
41
- resolve();
42
- return;
43
- }
44
- reject(new Error(`git credential approve failed (exit ${code ?? 'null'}): ${stderr.trim() || 'no stderr'}`));
45
- });
46
- child.stdin?.write(payload);
47
- child.stdin?.end();
48
- });
49
- }
1
+ export { looksLikeCommitSha, redactCloneUrl, runGitClone, withGitAskpass, } from '@sequenceholdings/artifact-studio/git-clone';
@@ -0,0 +1,15 @@
1
+ import type { ParsedArgs } from '../process/commands.js';
2
+ /** Only send a login credential to the exact repository pinned at clone time. */
3
+ export declare function gitCredentialResponse({ input, operation, envName, cloneUrl, }: {
4
+ input: string;
5
+ operation: string;
6
+ envName: string;
7
+ cloneUrl: string;
8
+ }): Promise<string>;
9
+ /** Store only a helper command, bound to this environment and repository URL. */
10
+ export declare function configureGitLogin({ destDir, envName, cloneUrl, }: {
11
+ destDir: string;
12
+ envName: string;
13
+ cloneUrl: string;
14
+ }): Promise<void>;
15
+ export declare function gitCredentialCommand(args: ParsedArgs): Promise<number>;
@@ -0,0 +1,91 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { getAccessTokenWithMode } from '../auth.js';
4
+ import { resolveConfiguredEnv } from '../config.js';
5
+ const exec = promisify(execFile);
6
+ function matchesGitDestination(input, url) {
7
+ const fields = new Map();
8
+ for (const line of input.split('\n')) {
9
+ if (!line)
10
+ break;
11
+ const index = line.indexOf('=');
12
+ if (index < 1)
13
+ return false;
14
+ const key = line.slice(0, index);
15
+ // Git sends repeatable capability[]/wwwauth[] fields. Ignore extensions;
16
+ // only duplicate destination fields make credential routing ambiguous.
17
+ if (!['protocol', 'host', 'path'].includes(key))
18
+ continue;
19
+ if (fields.has(key))
20
+ return false;
21
+ fields.set(key, line.slice(index + 1));
22
+ }
23
+ if (url.username || url.password || url.search || url.hash ||
24
+ !/^\/api\/git-service\/repos\/[\w-]+(?:\/git|\.git)$/.test(url.pathname) ||
25
+ fields.get('protocol') !== url.protocol.slice(0, -1) ||
26
+ fields.get('host') !== url.host ||
27
+ fields.get('path') !== url.pathname.slice(1))
28
+ return false;
29
+ return true;
30
+ }
31
+ /** Only send a login credential to the exact repository pinned at clone time. */
32
+ export async function gitCredentialResponse({ input, operation, envName, cloneUrl, }) {
33
+ // Git asks helpers to store/erase credentials after success/failure. Our source
34
+ // of truth is the CLI session; never persist its token or erase it on a Git 401.
35
+ if (operation === 'store' || operation === 'erase')
36
+ return '';
37
+ if (operation !== 'get')
38
+ throw new Error('Expected Git credential operation: get, store, or erase.');
39
+ const url = new URL(cloneUrl);
40
+ if (!matchesGitDestination(input, url))
41
+ return '';
42
+ const env = await resolveConfiguredEnv({ requested: envName });
43
+ if (url.origin !== new URL(env.url).origin)
44
+ throw new Error('Git remote origin no longer matches the registered environment.');
45
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) {
46
+ throw new Error('Git login credentials require HTTPS (except local loopback).');
47
+ }
48
+ try {
49
+ const auth = await getAccessTokenWithMode({ env: env.name, targetUrl: env.url, allowInteractiveLogin: false });
50
+ if (auth.authMode !== 'user' || !auth.token || /[\r\n\0]/.test(auth.token))
51
+ throw new Error('User login required');
52
+ return `username=git\npassword=${auth.token}\n\n`;
53
+ }
54
+ catch {
55
+ throw new Error(`Git login unavailable. Run seq-studio login --env ${envName}, then retry. Machine identities cannot authenticate Git; use supported JSON source workflows.`);
56
+ }
57
+ }
58
+ function shellQuote(value) {
59
+ return `'${value.replace(/'/g, "'\\''")}'`;
60
+ }
61
+ /** Store only a helper command, bound to this environment and repository URL. */
62
+ export async function configureGitLogin({ destDir, envName, cloneUrl, }) {
63
+ // Resolve the installed CLI via PATH so package/Node upgrades do not leave
64
+ // existing repositories pinned to a deleted version-specific executable.
65
+ const helper = `!seq-studio auth git-credential --env ${shellQuote(envName)} --url ${shellQuote(cloneUrl)}`;
66
+ const config = async (...args) => { await exec('git', ['-C', destDir, 'config', '--local', ...args]); };
67
+ // An empty helper resets inherited credential stores for this URL. That keeps
68
+ // an Auth0 access token out of the user's global store/keychain on approval.
69
+ await config('--replace-all', `credential.${cloneUrl}.helper`, '');
70
+ await config('--add', `credential.${cloneUrl}.helper`, helper);
71
+ await config(`credential.${cloneUrl}.useHttpPath`, 'true');
72
+ await config(`http.${cloneUrl}.followRedirects`, 'false');
73
+ }
74
+ export async function gitCredentialCommand(args) {
75
+ const envName = args.flags.env ?? args.flags.e;
76
+ const cloneUrl = args.flags.url;
77
+ const operation = args.positional[0];
78
+ if (typeof envName !== 'string' || typeof cloneUrl !== 'string' || !operation || args.positional.length !== 1) {
79
+ throw new Error('usage: seq-studio auth git-credential --env <env> --url <clone-url> <get|store|erase>');
80
+ }
81
+ let input = '';
82
+ for await (const chunk of process.stdin) {
83
+ input += chunk.toString();
84
+ if (input.length > 16_384)
85
+ throw new Error('Git credential input too large.');
86
+ if (input.includes('\n\n'))
87
+ break;
88
+ }
89
+ process.stdout.write(await gitCredentialResponse({ input, operation, envName, cloneUrl }));
90
+ return 0;
91
+ }
@@ -0,0 +1,69 @@
1
+ import { z } from 'zod';
2
+ export declare const TEMPLATE_NAMESPACE = "templates";
3
+ export declare const TEMPLATE_CATALOG_REPO = "catalog";
4
+ export declare const TEMPLATE_METADATA_PATH = ".seq/template.json";
5
+ export declare const TEMPLATE_RELEASE_PATH = ".seq/template-release.json";
6
+ export declare const templateMetadataSchema: z.ZodObject<{
7
+ schemaVersion: z.ZodLiteral<1>;
8
+ name: z.ZodString;
9
+ description: z.ZodString;
10
+ includes: z.ZodArray<z.ZodEnum<{
11
+ function: "function";
12
+ process: "process";
13
+ artifact: "artifact";
14
+ pipeline: "pipeline";
15
+ orm: "orm";
16
+ agent: "agent";
17
+ workspace: "workspace";
18
+ }>>;
19
+ }, z.core.$strict>;
20
+ export declare const templateReleaseSchema: z.ZodObject<{
21
+ schemaVersion: z.ZodLiteral<1>;
22
+ name: z.ZodString;
23
+ version: z.ZodString;
24
+ description: z.ZodString;
25
+ includes: z.ZodArray<z.ZodEnum<{
26
+ function: "function";
27
+ process: "process";
28
+ artifact: "artifact";
29
+ pipeline: "pipeline";
30
+ orm: "orm";
31
+ agent: "agent";
32
+ workspace: "workspace";
33
+ }>>;
34
+ source: z.ZodObject<{
35
+ environment: z.ZodEnum<{
36
+ banksouth: "banksouth";
37
+ staging: "staging";
38
+ }>;
39
+ repo: z.ZodString;
40
+ commit: z.ZodString;
41
+ }, z.core.$strip>;
42
+ digest: z.ZodString;
43
+ scope: z.ZodUnion<readonly [z.ZodObject<{
44
+ kind: z.ZodLiteral<"all">;
45
+ }, z.core.$strip>, z.ZodObject<{
46
+ kind: z.ZodLiteral<"one">;
47
+ deployment: z.ZodString;
48
+ }, z.core.$strip>]>;
49
+ publishedAt: z.ZodString;
50
+ }, z.core.$strict>;
51
+ export type TemplateMetadata = z.infer<typeof templateMetadataSchema>;
52
+ export type TemplateRelease = z.infer<typeof templateReleaseSchema>;
53
+ export type TemplateFile = {
54
+ path: string;
55
+ content: string;
56
+ mode: '100644' | '100755';
57
+ };
58
+ export type TemplateSourceEnvironment = TemplateRelease['source']['environment'];
59
+ /** Staging rehearsal stays in staging; cross-deployment releases use BankSouth. */
60
+ export declare function validateTemplatePublishRoute(from: string | undefined, to: string): TemplateSourceEnvironment;
61
+ export declare function parseTemplateSelection(input: string): {
62
+ name: string;
63
+ version: string;
64
+ };
65
+ export declare function releaseBranch(value: string): string;
66
+ export declare function ledgerPath(name: string, releaseVersion: string): string;
67
+ /** Hash the actual source bytes and executable bits, independent of Git commit IDs. */
68
+ export declare function templateDigest(files: readonly TemplateFile[]): string;
69
+ export declare function targetIncludesRelease(release: TemplateRelease, deployment: string): boolean;