@geekmidas/cli 10.0.0-alpha.111 → 10.0.0-alpha.113

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.
Files changed (37) hide show
  1. package/dist/{cli-Br5ApIgR.mjs → cli-DDY3jfTt.mjs} +3 -3
  2. package/dist/{cli-Br5ApIgR.mjs.map → cli-DDY3jfTt.mjs.map} +1 -1
  3. package/dist/{eas-BkLA60P2.cjs → eas-Cne743nQ.cjs} +21 -3
  4. package/dist/eas-Cne743nQ.cjs.map +1 -0
  5. package/dist/{eas-6ezdJtry.mjs → eas-DEpwISrQ.mjs} +25 -7
  6. package/dist/eas-DEpwISrQ.mjs.map +1 -0
  7. package/dist/{github-D2eABlxM.mjs → github-BMakI-k3.mjs} +5 -4
  8. package/dist/github-BMakI-k3.mjs.map +1 -0
  9. package/dist/{github-DDOHjdS9.cjs → github-C3gblUvr.cjs} +5 -3
  10. package/dist/github-C3gblUvr.cjs.map +1 -0
  11. package/dist/{googlePlay-DNgybe5t.cjs → googlePlay-B6uiHi65.cjs} +2 -2
  12. package/dist/{googlePlay-DNgybe5t.cjs.map → googlePlay-B6uiHi65.cjs.map} +1 -1
  13. package/dist/{googlePlay-DY9vZQ1p.mjs → googlePlay-BYZ-J5sC.mjs} +4 -4
  14. package/dist/{googlePlay-DY9vZQ1p.mjs.map → googlePlay-BYZ-J5sC.mjs.map} +1 -1
  15. package/dist/index.cjs +167 -74
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.mjs +176 -85
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/{migrate-B9GswIAr.mjs → migrate-xHYaeBkd.mjs} +2 -2
  20. package/dist/{migrate-B9GswIAr.mjs.map → migrate-xHYaeBkd.mjs.map} +1 -1
  21. package/dist/{publish-B-EIjfQ0.mjs → publish-CSctCNf4.mjs} +2 -2
  22. package/dist/{publish-B-EIjfQ0.mjs.map → publish-CSctCNf4.mjs.map} +1 -1
  23. package/dist/{publish-CPgSbtcs.cjs → publish-SDG1WfYn.cjs} +2 -2
  24. package/dist/{publish-CPgSbtcs.cjs.map → publish-SDG1WfYn.cjs.map} +1 -1
  25. package/dist/serverSetup--O61SRvg.mjs +558 -0
  26. package/dist/serverSetup--O61SRvg.mjs.map +1 -0
  27. package/dist/serverSetup-BCbD8ksJ.cjs +558 -0
  28. package/dist/serverSetup-BCbD8ksJ.cjs.map +1 -0
  29. package/dist/{stage-DjxR_7C0.mjs → stage-ClKTHQoM.mjs} +2 -2
  30. package/dist/{stage-DjxR_7C0.mjs.map → stage-ClKTHQoM.mjs.map} +1 -1
  31. package/dist/{terminal-mXM-Lqc6.mjs → terminal-CybB-cjk.mjs} +2 -2
  32. package/dist/{terminal-mXM-Lqc6.mjs.map → terminal-CybB-cjk.mjs.map} +1 -1
  33. package/package.json +15 -15
  34. package/dist/eas-6ezdJtry.mjs.map +0 -1
  35. package/dist/eas-BkLA60P2.cjs.map +0 -1
  36. package/dist/github-D2eABlxM.mjs.map +0 -1
  37. package/dist/github-DDOHjdS9.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"stage-DjxR_7C0.mjs","names":[],"sources":["../src/exec/stage.ts"],"sourcesContent":["/**\n * `gkm exec --stage <stage> -- <command>`: a command run on this machine as\n * a deployed compose stage's app — a data import, a backfill, a report.\n *\n * The app's environment is the one its container runs with, derived the way\n * the deploy derives it (`composeStack`) from the stage's secrets, read from\n * the stage's store the way the deploy reads them. Only what the container\n * reaches on the stack's network is moved: each service it names that the\n * server publishes on its loopback — Postgres, MinIO — is reached through an\n * SSH tunnel on the deploy's own login (`ServerAccess.tunnel`), and each\n * sibling app through its public address.\n *\n * Nothing is written to disk. The values exist only in the command's\n * environment, and its Credentials are filled from there by a preload that\n * is a `data:` URL naming the keys — never their values.\n */\n\nimport { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { type ComposeDocker, dockerCompose } from '../compose/docker.js';\nimport { deployedStackSecrets } from '../compose/secrets.js';\nimport {\n\ttype ComposeServer,\n\tcomposeServer,\n\tdockerHost,\n\ttype ServerAccess,\n\tsshAccess,\n\ttype Tunnel,\n} from '../compose/server.js';\nimport { type ComposeStack, composeStack } from '../compose/stack.js';\nimport { edgeAlias } from '../compose/traefik.js';\nimport {\n\tloadWorkspaceAppInfo,\n\tloadWorkspaceConfig,\n\tNotInAnApp,\n} from '../config.js';\nimport { deployIdentity } from '../deploy/identity.js';\nimport { GkmError } from '../errors';\nimport { prompt } from '../prompt.js';\nimport { deploysWithCompose } from '../providers/dns.js';\nimport { discover } from '../reconcile/discover.js';\nimport { constructGlobs } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport type { StageSecrets } from '../secrets/types.js';\nimport { edgePorts } from '../target/compose/phases.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\nconst logger = console;\n\n/** The stage is not one the compose target deploys. */\nexport class ExecStageNotComposed extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(\n\t\t\t`gkm exec --stage runs a command against a compose stage's server, and ` +\n\t\t\t\t`'${stage}' is not deployed with compose. Set deploy.default: 'compose' ` +\n\t\t\t\t'in gkm.config.ts, or run the command where the stage runs.',\n\t\t);\n\t\tthis.name = 'ExecStageNotComposed';\n\t}\n}\n\n/** The stage's secrets lack what its deploy generates: it was never deployed. */\nexport class ExecStageNotDeployed extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly missing: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' has no ${missing.join(', ')} in its secrets yet, so what its ` +\n\t\t\t\t'apps run with is not decided. Deploy it first: ' +\n\t\t\t\t`gkm deploy --stage ${stage}.`,\n\t\t);\n\t\tthis.name = 'ExecStageNotDeployed';\n\t}\n}\n\n/** The directory is not one of the stack's apps. */\nexport class ExecAppNotInStack extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly app: string | undefined,\n\t\treadonly apps: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`${app ? `'${app}' is not` : 'This directory is not in'} one of the apps ` +\n\t\t\t\t`'${stage}' runs (${apps.join(', ')}), so there is no environment to run ` +\n\t\t\t\t`as. Run from an app's directory: cd apps/${apps[0] ?? '<app>'} && ` +\n\t\t\t\t`gkm exec --stage ${stage} -- <command>.`,\n\t\t);\n\t\tthis.name = 'ExecAppNotInStack';\n\t}\n}\n\n/** A protected stage, and nobody said yes. */\nexport class ExecNotConfirmed extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(`Nothing was run against '${stage}'.`);\n\t\tthis.name = 'ExecNotConfirmed';\n\t}\n}\n\nexport interface StageExecOptions {\n\tstage: string;\n\t/** The AWS profile for the stage's account, where its secrets are kept. */\n\tprofile?: string;\n\t/**\n\t * The SSH login to reach the server as, in place of\n\t * `deploy.compose.server.<stage>.user` — a person's own, where the\n\t * deploy's key lives only in CI.\n\t */\n\tsshUser?: string;\n\t/** Run against a protected stage without asking. */\n\tyes?: boolean;\n\tcwd?: string;\n}\n\n/** What the command needs from outside the process, so tests can stand in. */\nexport interface StageExecDeps {\n\t/** The server's Docker, asked which port each service publishes. */\n\tdocker: ComposeDocker;\n\t/** The tunnels to the server's loopback. */\n\tserver: ServerAccess;\n\t/** Asked before running against a protected stage. */\n\tconfirm: (question: string) => Promise<boolean>;\n\t/** Where the edge's ports are read from, as the deploy reads them. */\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport const defaultStageExecDeps: StageExecDeps = {\n\tdocker: dockerCompose,\n\tserver: sshAccess,\n\tconfirm: async (question) => {\n\t\tconst answer = await prompt(`${question} [y/N] `, {\n\t\t\tinstead: 'Pass --yes to run without asking.',\n\t\t});\n\t\treturn /^y(es)?$/i.test(answer.trim());\n\t},\n\tenv: process.env,\n};\n\n/** A service on the stack's network the app's environment names. */\nexport interface StackAddress {\n\tservice: string;\n\tport: number;\n}\n\n/**\n * The environment an app runs with on the stage: a backend's container's,\n * over the keys of each worker built from it; a site's or a mobile app's,\n * the public values its build reads.\n *\n * @throws {ExecAppNotInStack}\n */\nexport function appEnvironment(\n\tstack: Pick<ComposeStack, 'stage' | 'apps' | 'workers' | 'mobileApps'>,\n\tappName: string | undefined,\n): Record<string, string> {\n\tconst mobile = stack.mobileApps.find(\n\t\t(candidate) => candidate.name === appName,\n\t);\n\tif (mobile) return { ...mobile.values };\n\tconst app = stack.apps.find((candidate) => candidate.name === appName);\n\tif (!app) {\n\t\tthrow new ExecAppNotInStack(stack.stage, appName, [\n\t\t\t...stack.apps.map((candidate) => candidate.name),\n\t\t\t...stack.mobileApps.map((candidate) => candidate.name),\n\t\t]);\n\t}\n\tif (app.kind === 'site') return { ...app.build?.args };\n\tconst workers = stack.workers.filter((worker) => worker.host === app.name);\n\treturn Object.assign(\n\t\t{},\n\t\t...workers.map((worker) => worker.env ?? {}),\n\t\tapp.env ?? {},\n\t);\n}\n\n/** `host:port`, at a URL's authority — after `//` or a login's `@`. */\nfunction authority(host: string, port: number): RegExp {\n\treturn new RegExp(\n\t\t`(?<=[/@,])${host.replace(/[.-]/g, '\\\\$&')}:${port}(?!\\\\d)`,\n\t\t'g',\n\t);\n}\n\n/**\n * Each of the stack's services the environment reaches on the stack's\n * network, once: `postgres:5432`, `minio:9000`.\n */\nexport function stackAddresses(\n\tenv: Readonly<Record<string, string>>,\n\tstack: Pick<ComposeStack, 'infra'>,\n): StackAddress[] {\n\tconst found = new Map<string, StackAddress>();\n\tconst pattern = /(?<=[/@,])([a-z0-9-]+):(\\d+)(?!\\d)/g;\n\tfor (const value of Object.values(env)) {\n\t\tfor (const match of value.matchAll(pattern)) {\n\t\t\tconst service = match[1]!;\n\t\t\tif (!stack.infra.includes(service)) continue;\n\t\t\tconst port = Number(match[2]);\n\t\t\tfound.set(`${service}:${port}`, { service, port });\n\t\t}\n\t}\n\treturn [...found.values()];\n}\n\n/**\n * The environment as this machine reaches it: each service at its tunnel's\n * local port, and each sibling app at its public address. What has no\n * tunnel is left as the container has it.\n */\nexport function throughTunnels(\n\tenv: Readonly<Record<string, string>>,\n\tstack: Pick<ComposeStack, 'apps' | 'project'>,\n\ttunnels: ReadonlyMap<string, number>,\n): Record<string, string> {\n\tconst rewrites: [RegExp, string][] = [];\n\tfor (const [address, port] of tunnels) {\n\t\tconst [service, inside] = address.split(':');\n\t\trewrites.push([authority(service!, Number(inside)), `127.0.0.1:${port}`]);\n\t}\n\tfor (const app of stack.apps) {\n\t\tfor (const host of [app.name, edgeAlias(stack.project, app.name)]) {\n\t\t\trewrites.push([\n\t\t\t\tnew RegExp(\n\t\t\t\t\t`http://${host.replace(/[.-]/g, '\\\\$&')}:${app.port}(?!\\\\d)`,\n\t\t\t\t\t'g',\n\t\t\t\t),\n\t\t\t\tapp.url,\n\t\t\t]);\n\t\t}\n\t}\n\tconst out: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tout[key] = rewrites.reduce(\n\t\t\t(current, [pattern, replacement]) =>\n\t\t\t\tcurrent.replace(pattern, () => replacement),\n\t\t\tvalue,\n\t\t);\n\t}\n\treturn out;\n}\n\n/**\n * The preload that fills Credentials from the command's own environment: a\n * `data:` URL holding the keys, so no file — and no value — is written.\n */\nexport function credentialsImport(keys: readonly string[]): string {\n\tconst source =\n\t\t'globalThis.__gkm_credentials__=Object.fromEntries(' +\n\t\t`${JSON.stringify(keys)}.map((k)=>[k,process.env[k]]));`;\n\treturn `--import=data:text/javascript,${encodeURIComponent(source)}`;\n}\n\n/** A deployed compose stage, as its deploy has it, and the app here. */\nexport interface LoadedStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tstack: ComposeStack;\n\t/** The stage's secrets, as its deploy reads them. */\n\tsecrets: StageSecrets;\n\t/** The app this directory is, if it is one. */\n\tappName: string | undefined;\n\tprotectedStage: boolean;\n}\n\n/**\n * The stage's stack, and the app this directory is, as the deploy has them:\n * its secrets read from its store, its values derived as the deploy derives\n * them. Nothing is reached but the store — no server, no SSH.\n *\n * @throws {UndeclaredStage}, {ExecStageNotComposed}, {ExecStageNotDeployed}\n */\nexport async function loadStage(\n\toptions: Pick<StageExecOptions, 'stage' | 'profile' | 'cwd'>,\n\tenv: NodeJS.ProcessEnv = process.env,\n): Promise<LoadedStage> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst { stage } = options;\n\t// Outside an app the workspace is still loaded, so the stage is checked\n\t// before the directory is refused.\n\tconst info = await loadWorkspaceAppInfo(cwd).catch((error) => {\n\t\tif (error instanceof NotInAnApp) return undefined;\n\t\tthrow error;\n\t});\n\tconst workspace =\n\t\tinfo?.workspace ?? (await loadWorkspaceConfig(cwd)).workspace;\n\n\tassertDeployedStage(workspace.stages, stage);\n\tif (!deploysWithCompose(workspace)) throw new ExecStageNotComposed(stage);\n\n\tconst runnables: Record<string, string[]> = {};\n\tconst background: Record<string, string[]> = {};\n\tconst manifest: ConstructManifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\trunnables,\n\t\tbackground,\n\t});\n\n\tconst store = await secretsStoreFor(workspace, stage, {\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst { secrets, generated } = deployedStackSecrets(\n\t\tworkspace,\n\t\tstage,\n\t\tawait store.read(stage),\n\t\tmanifest,\n\t);\n\tif (generated.length > 0) throw new ExecStageNotDeployed(stage, generated);\n\n\tconst stack = composeStack({\n\t\tworkspace,\n\t\tmanifest,\n\t\trunnables,\n\t\tbackground,\n\t\tstage,\n\t\tidentity: deployIdentity(workspace, stage),\n\t\t// Built, so a site's public values are resolved as its build has them.\n\t\timages: { mode: 'build', tag: 'exec' },\n\t\tsecrets,\n\t\tports: edgePorts(env),\n\t});\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tstack,\n\t\tsecrets,\n\t\tappName: info?.appName,\n\t\tprotectedStage: workspace.stages.protected?.includes(stage) ?? false,\n\t};\n}\n\n/** The stage's server, as SSH reaches it: `--ssh-user` over the config's. */\nfunction stageServer(\n\tloaded: LoadedStage,\n\toptions: StageExecOptions,\n): ComposeServer {\n\tconst server = composeServer({\n\t\tstage: options.stage,\n\t\tlocal: false,\n\t\tconfig: loaded.workspace.deploy?.compose?.server,\n\t\tcustom: loaded.secrets.custom,\n\t})!;\n\tif (options.sshUser) server.user = options.sshUser;\n\treturn server;\n}\n\n/**\n * Run `commandArgs` as the app this directory is, on the stage — through a\n * tunnel to each service it reaches — and return its exit code. Every tunnel\n * is closed once it exits, whatever it exits with.\n *\n * @throws {ExecStageNotComposed}, {ExecStageNotDeployed}, {ExecAppNotInStack},\n * {ExecNotConfirmed}, {ComposeServerUnreachable}\n */\nexport async function execOnStage(\n\tcommandArgs: readonly [string, ...string[]],\n\toptions: StageExecOptions,\n\tdeps: StageExecDeps = defaultStageExecDeps,\n): Promise<number> {\n\tconst { stage } = options;\n\tconst loaded = await loadStage(options, deps.env);\n\tconst { stack, appName, protectedStage } = loaded;\n\tconst env = appEnvironment(stack, appName);\n\n\tif (protectedStage && !options.yes) {\n\t\tconst question = `'${stage}' is a protected stage. Run ${commandArgs.join(' ')} against it?`;\n\t\tif (!(await deps.confirm(question))) throw new ExecNotConfirmed(stage);\n\t}\n\n\t// Only what reaches a service on the stack needs the server: a site's or\n\t// a mobile app's values are public addresses, and need no SSH at all.\n\tconst addresses = stackAddresses(env, stack);\n\tif (addresses.length === 0) {\n\t\tlogger.log(`📦 App: ${appName} on '${stage}'`);\n\t\tlogger.log(`🔐 Loaded ${Object.keys(env).length} value(s) for '${stage}'`);\n\t\treturn run(commandArgs, env, options.cwd);\n\t}\n\n\tconst server = stageServer(loaded, options);\n\tlogger.log(`📦 App: ${appName} on '${stage}' (${server.host})`);\n\n\t// The deploy's own check: SSH logs in and Docker answers, before any\n\t// tunnel is asked for — so a key the server refuses is said as that.\n\tawait deps.server.check(server);\n\n\tconst tunnels: Tunnel[] = [];\n\tconst ports = new Map<string, number>();\n\ttry {\n\t\tfor (const address of addresses) {\n\t\t\tconst published = await deps.docker.published(\n\t\t\t\t{ host: dockerHost(server) },\n\t\t\t\tstack.project,\n\t\t\t\taddress.service,\n\t\t\t\taddress.port,\n\t\t\t);\n\t\t\tif (published === undefined) {\n\t\t\t\tlogger.log(\n\t\t\t\t\t`⚠️ ${address.service} is not published on the server (no running ` +\n\t\t\t\t\t\t`${stack.project} ${address.service} publishes ${address.port}), so ` +\n\t\t\t\t\t\t'it is unreachable from here; its address is passed on unchanged.',\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst tunnel = await deps.server.tunnel(server, published);\n\t\t\ttunnels.push(tunnel);\n\t\t\tports.set(`${address.service}:${address.port}`, tunnel.port);\n\t\t\tlogger.log(`🚇 ${address.service} → 127.0.0.1:${tunnel.port} (over SSH)`);\n\t\t}\n\n\t\tconst credentials = throughTunnels(env, stack, ports);\n\t\tlogger.log(\n\t\t\t`🔐 Loaded ${Object.keys(credentials).length} value(s) for '${stage}'`,\n\t\t);\n\t\treturn await run(commandArgs, credentials, options.cwd);\n\t} finally {\n\t\tawait Promise.all(tunnels.map((tunnel) => tunnel.close()));\n\t}\n}\n\n/**\n * The command, with the values in its environment and its Credentials. A\n * Ctrl-C reaches it — it is in the terminal's process group — and this\n * process waits for it to exit rather than leaving before the tunnels close.\n */\nfunction run(\n\tcommandArgs: readonly [string, ...string[]],\n\tcredentials: Record<string, string>,\n\tcwd: string | undefined,\n): Promise<number> {\n\tconst [cmd, ...args] = commandArgs;\n\tlogger.log(`🚀 Running: ${commandArgs.join(' ')}`);\n\n\tconst inherited = (process.env.NODE_OPTIONS ?? '')\n\t\t.replace(/--import[= ]\\S+/g, '')\n\t\t.trim();\n\tconst nodeOptions = [inherited, credentialsImport(Object.keys(credentials))]\n\t\t.filter(Boolean)\n\t\t.join(' ');\n\n\tconst wait = () => {};\n\tprocess.on('SIGINT', wait);\n\tprocess.on('SIGTERM', wait);\n\treturn new Promise<number>((resolve) => {\n\t\tconst child = spawn(cmd, args, {\n\t\t\t...(cwd ? { cwd } : {}),\n\t\t\tstdio: 'inherit',\n\t\t\tenv: { ...process.env, ...credentials, NODE_OPTIONS: nodeOptions },\n\t\t});\n\t\tchild.on('close', (code, signal) => {\n\t\t\tresolve(code ?? 128 + (signal ? constants.signals[signal] : 0));\n\t\t});\n\t\tchild.on('error', (error) => {\n\t\t\tlogger.error(`Failed to run command: ${error.message}`);\n\t\t\tresolve(1);\n\t\t});\n\t}).finally(() => {\n\t\tprocess.off('SIGINT', wait);\n\t\tprocess.off('SIGTERM', wait);\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,SAAS;;AAGf,IAAa,uBAAb,cAA0C,SAAS;CAC7B;CAArB,YAAY,OAAwB;EACnC,MACC,0EACK,MAAM,yHAEZ;EALoB,KAAA,QAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,uBAAb,cAA0C,SAAS;CAExC;CACA;CAFV,YACC,OACA,SACC;EACD,MACC,IAAI,MAAM,WAAW,QAAQ,KAAK,IAAI,EAAE,qGAEjB,MAAM,EAC9B;EAPS,KAAA,QAAA;EACA,KAAA,UAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,oBAAb,cAAuC,SAAS;CAErC;CACA;CACA;CAHV,YACC,OACA,KACA,MACC;EACD,MACC,GAAG,MAAM,IAAI,IAAI,YAAY,2BAA2B,oBACnD,MAAM,UAAU,KAAK,KAAK,IAAI,EAAE,gFACQ,KAAK,MAAM,QAAQ,uBAC3C,MAAM,eAC5B;EATS,KAAA,QAAA;EACA,KAAA,MAAA;EACA,KAAA,OAAA;EAQT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,mBAAb,cAAsC,SAAS;CACzB;CAArB,YAAY,OAAwB;EACnC,MAAM,4BAA4B,MAAM,GAAG;EADvB,KAAA,QAAA;EAEpB,KAAK,OAAO;CACb;AACD;AA6BA,MAAa,uBAAs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E;EACA,OAAO,MAAM,IAAI,aAAa,aAAa,QAAQ,GAAG;CACvD,UAAU;EACT,MAAM,QAAQ,IAAI,QAAQ,KAAK,WAAW,OAAO,MAAM,CAAC,CAAC;CAC1D;AACD;;;;;;AAOA,SAAS,IACR,aACA,aACA,KACkB;CAClB,MAAM,CAAC,KAAK,GAAG,QAAQ;CACvB,OAAO,IAAI,eAAe,YAAY,KAAK,GAAG,GAAG;CAKjD,MAAM,cAAc,EAHD,QAAQ,IAAI,gBAAgB,GAAA,CAC7C,QAAQ,oBAAoB,EAAE,CAAC,CAC/B,KAC2B,GAAG,kBAAkB,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,CAC1E,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;CAEV,MAAM,aAAa,CAAC;CACpB,QAAQ,GAAG,UAAU,IAAI;CACzB,QAAQ,GAAG,WAAW,IAAI;CAC1B,OAAO,IAAI,SAAiB,YAAY;EACvC,MAAM,QAAQ,MAAM,KAAK,MAAM;GAC9B,GAAI,MAAM,EAAE,IAAI,IAAI,CAAC;GACrB,OAAO;GACP,KAAK;IAAE,GAAG,QAAQ;IAAK,GAAG;IAAa,cAAc;GAAY;EAClE,CAAC;EACD,MAAM,GAAG,UAAU,MAAM,WAAW;GACnC,QAAQ,QAAQ,OAAO,SAAS,UAAU,QAAQ,UAAU,EAAE;EAC/D,CAAC;EACD,MAAM,GAAG,UAAU,UAAU;GAC5B,OAAO,MAAM,0BAA0B,MAAM,SAAS;GACtD,QAAQ,CAAC;EACV,CAAC;CACF,CAAC,CAAC,CAAC,cAAc;EAChB,QAAQ,IAAI,UAAU,IAAI;EAC1B,QAAQ,IAAI,WAAW,IAAI;CAC5B,CAAC;AACF"}
1
+ {"version":3,"file":"stage-ClKTHQoM.mjs","names":[],"sources":["../src/exec/stage.ts"],"sourcesContent":["/**\n * `gkm exec --stage <stage> -- <command>`: a command run on this machine as\n * a deployed compose stage's app — a data import, a backfill, a report.\n *\n * The app's environment is the one its container runs with, derived the way\n * the deploy derives it (`composeStack`) from the stage's secrets, read from\n * the stage's store the way the deploy reads them. Only what the container\n * reaches on the stack's network is moved: each service it names that the\n * server publishes on its loopback — Postgres, MinIO — is reached through an\n * SSH tunnel on the deploy's own login (`ServerAccess.tunnel`), and each\n * sibling app through its public address.\n *\n * Nothing is written to disk. The values exist only in the command's\n * environment, and its Credentials are filled from there by a preload that\n * is a `data:` URL naming the keys — never their values.\n */\n\nimport { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { type ComposeDocker, dockerCompose } from '../compose/docker.js';\nimport { deployedStackSecrets } from '../compose/secrets.js';\nimport {\n\ttype ComposeServer,\n\tcomposeServer,\n\tdockerHost,\n\ttype ServerAccess,\n\tsshAccess,\n\ttype Tunnel,\n} from '../compose/server.js';\nimport { type ComposeStack, composeStack } from '../compose/stack.js';\nimport { edgeAlias } from '../compose/traefik.js';\nimport {\n\tloadWorkspaceAppInfo,\n\tloadWorkspaceConfig,\n\tNotInAnApp,\n} from '../config.js';\nimport { deployIdentity } from '../deploy/identity.js';\nimport { GkmError } from '../errors';\nimport { prompt } from '../prompt.js';\nimport { deploysWithCompose } from '../providers/dns.js';\nimport { discover } from '../reconcile/discover.js';\nimport { constructGlobs } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport type { StageSecrets } from '../secrets/types.js';\nimport { edgePorts } from '../target/compose/phases.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\n\nconst logger = console;\n\n/** The stage is not one the compose target deploys. */\nexport class ExecStageNotComposed extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(\n\t\t\t`gkm exec --stage runs a command against a compose stage's server, and ` +\n\t\t\t\t`'${stage}' is not deployed with compose. Set deploy.default: 'compose' ` +\n\t\t\t\t'in gkm.config.ts, or run the command where the stage runs.',\n\t\t);\n\t\tthis.name = 'ExecStageNotComposed';\n\t}\n}\n\n/** The stage's secrets lack what its deploy generates: it was never deployed. */\nexport class ExecStageNotDeployed extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly missing: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' has no ${missing.join(', ')} in its secrets yet, so what its ` +\n\t\t\t\t'apps run with is not decided. Deploy it first: ' +\n\t\t\t\t`gkm deploy --stage ${stage}.`,\n\t\t);\n\t\tthis.name = 'ExecStageNotDeployed';\n\t}\n}\n\n/** The directory is not one of the stack's apps. */\nexport class ExecAppNotInStack extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly app: string | undefined,\n\t\treadonly apps: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`${app ? `'${app}' is not` : 'This directory is not in'} one of the apps ` +\n\t\t\t\t`'${stage}' runs (${apps.join(', ')}), so there is no environment to run ` +\n\t\t\t\t`as. Run from an app's directory: cd apps/${apps[0] ?? '<app>'} && ` +\n\t\t\t\t`gkm exec --stage ${stage} -- <command>.`,\n\t\t);\n\t\tthis.name = 'ExecAppNotInStack';\n\t}\n}\n\n/** A protected stage, and nobody said yes. */\nexport class ExecNotConfirmed extends GkmError {\n\tconstructor(readonly stage: string) {\n\t\tsuper(`Nothing was run against '${stage}'.`);\n\t\tthis.name = 'ExecNotConfirmed';\n\t}\n}\n\nexport interface StageExecOptions {\n\tstage: string;\n\t/** The AWS profile for the stage's account, where its secrets are kept. */\n\tprofile?: string;\n\t/**\n\t * The SSH login to reach the server as, in place of\n\t * `deploy.compose.server.<stage>.user` — a person's own, where the\n\t * deploy's key lives only in CI.\n\t */\n\tsshUser?: string;\n\t/** Run against a protected stage without asking. */\n\tyes?: boolean;\n\tcwd?: string;\n}\n\n/** What the command needs from outside the process, so tests can stand in. */\nexport interface StageExecDeps {\n\t/** The server's Docker, asked which port each service publishes. */\n\tdocker: ComposeDocker;\n\t/** The tunnels to the server's loopback. */\n\tserver: ServerAccess;\n\t/** Asked before running against a protected stage. */\n\tconfirm: (question: string) => Promise<boolean>;\n\t/** Where the edge's ports are read from, as the deploy reads them. */\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport const defaultStageExecDeps: StageExecDeps = {\n\tdocker: dockerCompose,\n\tserver: sshAccess,\n\tconfirm: async (question) => {\n\t\tconst answer = await prompt(`${question} [y/N] `, {\n\t\t\tinstead: 'Pass --yes to run without asking.',\n\t\t});\n\t\treturn /^y(es)?$/i.test(answer.trim());\n\t},\n\tenv: process.env,\n};\n\n/** A service on the stack's network the app's environment names. */\nexport interface StackAddress {\n\tservice: string;\n\tport: number;\n}\n\n/**\n * The environment an app runs with on the stage: a backend's container's,\n * over the keys of each worker built from it; a site's or a mobile app's,\n * the public values its build reads.\n *\n * @throws {ExecAppNotInStack}\n */\nexport function appEnvironment(\n\tstack: Pick<ComposeStack, 'stage' | 'apps' | 'workers' | 'mobileApps'>,\n\tappName: string | undefined,\n): Record<string, string> {\n\tconst mobile = stack.mobileApps.find(\n\t\t(candidate) => candidate.name === appName,\n\t);\n\tif (mobile) return { ...mobile.values };\n\tconst app = stack.apps.find((candidate) => candidate.name === appName);\n\tif (!app) {\n\t\tthrow new ExecAppNotInStack(stack.stage, appName, [\n\t\t\t...stack.apps.map((candidate) => candidate.name),\n\t\t\t...stack.mobileApps.map((candidate) => candidate.name),\n\t\t]);\n\t}\n\tif (app.kind === 'site') return { ...app.build?.args };\n\tconst workers = stack.workers.filter((worker) => worker.host === app.name);\n\treturn Object.assign(\n\t\t{},\n\t\t...workers.map((worker) => worker.env ?? {}),\n\t\tapp.env ?? {},\n\t);\n}\n\n/** `host:port`, at a URL's authority — after `//` or a login's `@`. */\nfunction authority(host: string, port: number): RegExp {\n\treturn new RegExp(\n\t\t`(?<=[/@,])${host.replace(/[.-]/g, '\\\\$&')}:${port}(?!\\\\d)`,\n\t\t'g',\n\t);\n}\n\n/**\n * Each of the stack's services the environment reaches on the stack's\n * network, once: `postgres:5432`, `minio:9000`.\n */\nexport function stackAddresses(\n\tenv: Readonly<Record<string, string>>,\n\tstack: Pick<ComposeStack, 'infra'>,\n): StackAddress[] {\n\tconst found = new Map<string, StackAddress>();\n\tconst pattern = /(?<=[/@,])([a-z0-9-]+):(\\d+)(?!\\d)/g;\n\tfor (const value of Object.values(env)) {\n\t\tfor (const match of value.matchAll(pattern)) {\n\t\t\tconst service = match[1]!;\n\t\t\tif (!stack.infra.includes(service)) continue;\n\t\t\tconst port = Number(match[2]);\n\t\t\tfound.set(`${service}:${port}`, { service, port });\n\t\t}\n\t}\n\treturn [...found.values()];\n}\n\n/**\n * The environment as this machine reaches it: each service at its tunnel's\n * local port, and each sibling app at its public address. What has no\n * tunnel is left as the container has it.\n */\nexport function throughTunnels(\n\tenv: Readonly<Record<string, string>>,\n\tstack: Pick<ComposeStack, 'apps' | 'project'>,\n\ttunnels: ReadonlyMap<string, number>,\n): Record<string, string> {\n\tconst rewrites: [RegExp, string][] = [];\n\tfor (const [address, port] of tunnels) {\n\t\tconst [service, inside] = address.split(':');\n\t\trewrites.push([authority(service!, Number(inside)), `127.0.0.1:${port}`]);\n\t}\n\tfor (const app of stack.apps) {\n\t\tfor (const host of [app.name, edgeAlias(stack.project, app.name)]) {\n\t\t\trewrites.push([\n\t\t\t\tnew RegExp(\n\t\t\t\t\t`http://${host.replace(/[.-]/g, '\\\\$&')}:${app.port}(?!\\\\d)`,\n\t\t\t\t\t'g',\n\t\t\t\t),\n\t\t\t\tapp.url,\n\t\t\t]);\n\t\t}\n\t}\n\tconst out: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tout[key] = rewrites.reduce(\n\t\t\t(current, [pattern, replacement]) =>\n\t\t\t\tcurrent.replace(pattern, () => replacement),\n\t\t\tvalue,\n\t\t);\n\t}\n\treturn out;\n}\n\n/**\n * The preload that fills Credentials from the command's own environment: a\n * `data:` URL holding the keys, so no file — and no value — is written.\n */\nexport function credentialsImport(keys: readonly string[]): string {\n\tconst source =\n\t\t'globalThis.__gkm_credentials__=Object.fromEntries(' +\n\t\t`${JSON.stringify(keys)}.map((k)=>[k,process.env[k]]));`;\n\treturn `--import=data:text/javascript,${encodeURIComponent(source)}`;\n}\n\n/** A deployed compose stage, as its deploy has it, and the app here. */\nexport interface LoadedStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tstack: ComposeStack;\n\t/** The stage's secrets, as its deploy reads them. */\n\tsecrets: StageSecrets;\n\t/** The app this directory is, if it is one. */\n\tappName: string | undefined;\n\tprotectedStage: boolean;\n}\n\n/**\n * The stage's stack, and the app this directory is, as the deploy has them:\n * its secrets read from its store, its values derived as the deploy derives\n * them. Nothing is reached but the store — no server, no SSH.\n *\n * @throws {UndeclaredStage}, {ExecStageNotComposed}, {ExecStageNotDeployed}\n */\nexport async function loadStage(\n\toptions: Pick<StageExecOptions, 'stage' | 'profile' | 'cwd'>,\n\tenv: NodeJS.ProcessEnv = process.env,\n): Promise<LoadedStage> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst { stage } = options;\n\t// Outside an app the workspace is still loaded, so the stage is checked\n\t// before the directory is refused.\n\tconst info = await loadWorkspaceAppInfo(cwd).catch((error) => {\n\t\tif (error instanceof NotInAnApp) return undefined;\n\t\tthrow error;\n\t});\n\tconst workspace =\n\t\tinfo?.workspace ?? (await loadWorkspaceConfig(cwd)).workspace;\n\n\tassertDeployedStage(workspace.stages, stage);\n\tif (!deploysWithCompose(workspace)) throw new ExecStageNotComposed(stage);\n\n\tconst runnables: Record<string, string[]> = {};\n\tconst background: Record<string, string[]> = {};\n\tconst manifest: ConstructManifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\trunnables,\n\t\tbackground,\n\t});\n\n\tconst store = await secretsStoreFor(workspace, stage, {\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst { secrets, generated } = deployedStackSecrets(\n\t\tworkspace,\n\t\tstage,\n\t\tawait store.read(stage),\n\t\tmanifest,\n\t);\n\tif (generated.length > 0) throw new ExecStageNotDeployed(stage, generated);\n\n\tconst stack = composeStack({\n\t\tworkspace,\n\t\tmanifest,\n\t\trunnables,\n\t\tbackground,\n\t\tstage,\n\t\tidentity: deployIdentity(workspace, stage),\n\t\t// Built, so a site's public values are resolved as its build has them.\n\t\timages: { mode: 'build', tag: 'exec' },\n\t\tsecrets,\n\t\tports: edgePorts(env),\n\t});\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tstack,\n\t\tsecrets,\n\t\tappName: info?.appName,\n\t\tprotectedStage: workspace.stages.protected?.includes(stage) ?? false,\n\t};\n}\n\n/** The stage's server, as SSH reaches it: `--ssh-user` over the config's. */\nfunction stageServer(\n\tloaded: LoadedStage,\n\toptions: StageExecOptions,\n): ComposeServer {\n\tconst server = composeServer({\n\t\tstage: options.stage,\n\t\tlocal: false,\n\t\tconfig: loaded.workspace.deploy?.compose?.server,\n\t\tcustom: loaded.secrets.custom,\n\t})!;\n\tif (options.sshUser) server.user = options.sshUser;\n\treturn server;\n}\n\n/**\n * Run `commandArgs` as the app this directory is, on the stage — through a\n * tunnel to each service it reaches — and return its exit code. Every tunnel\n * is closed once it exits, whatever it exits with.\n *\n * @throws {ExecStageNotComposed}, {ExecStageNotDeployed}, {ExecAppNotInStack},\n * {ExecNotConfirmed}, {ComposeServerUnreachable}\n */\nexport async function execOnStage(\n\tcommandArgs: readonly [string, ...string[]],\n\toptions: StageExecOptions,\n\tdeps: StageExecDeps = defaultStageExecDeps,\n): Promise<number> {\n\tconst { stage } = options;\n\tconst loaded = await loadStage(options, deps.env);\n\tconst { stack, appName, protectedStage } = loaded;\n\tconst env = appEnvironment(stack, appName);\n\n\tif (protectedStage && !options.yes) {\n\t\tconst question = `'${stage}' is a protected stage. Run ${commandArgs.join(' ')} against it?`;\n\t\tif (!(await deps.confirm(question))) throw new ExecNotConfirmed(stage);\n\t}\n\n\t// Only what reaches a service on the stack needs the server: a site's or\n\t// a mobile app's values are public addresses, and need no SSH at all.\n\tconst addresses = stackAddresses(env, stack);\n\tif (addresses.length === 0) {\n\t\tlogger.log(`📦 App: ${appName} on '${stage}'`);\n\t\tlogger.log(`🔐 Loaded ${Object.keys(env).length} value(s) for '${stage}'`);\n\t\treturn run(commandArgs, env, options.cwd);\n\t}\n\n\tconst server = stageServer(loaded, options);\n\tlogger.log(`📦 App: ${appName} on '${stage}' (${server.host})`);\n\n\t// The deploy's own check: SSH logs in and Docker answers, before any\n\t// tunnel is asked for — so a key the server refuses is said as that.\n\tawait deps.server.check(server);\n\n\tconst tunnels: Tunnel[] = [];\n\tconst ports = new Map<string, number>();\n\ttry {\n\t\tfor (const address of addresses) {\n\t\t\tconst published = await deps.docker.published(\n\t\t\t\t{ host: dockerHost(server) },\n\t\t\t\tstack.project,\n\t\t\t\taddress.service,\n\t\t\t\taddress.port,\n\t\t\t);\n\t\t\tif (published === undefined) {\n\t\t\t\tlogger.log(\n\t\t\t\t\t`⚠️ ${address.service} is not published on the server (no running ` +\n\t\t\t\t\t\t`${stack.project} ${address.service} publishes ${address.port}), so ` +\n\t\t\t\t\t\t'it is unreachable from here; its address is passed on unchanged.',\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst tunnel = await deps.server.tunnel(server, published);\n\t\t\ttunnels.push(tunnel);\n\t\t\tports.set(`${address.service}:${address.port}`, tunnel.port);\n\t\t\tlogger.log(`🚇 ${address.service} → 127.0.0.1:${tunnel.port} (over SSH)`);\n\t\t}\n\n\t\tconst credentials = throughTunnels(env, stack, ports);\n\t\tlogger.log(\n\t\t\t`🔐 Loaded ${Object.keys(credentials).length} value(s) for '${stage}'`,\n\t\t);\n\t\treturn await run(commandArgs, credentials, options.cwd);\n\t} finally {\n\t\tawait Promise.all(tunnels.map((tunnel) => tunnel.close()));\n\t}\n}\n\n/**\n * The command, with the values in its environment and its Credentials. A\n * Ctrl-C reaches it — it is in the terminal's process group — and this\n * process waits for it to exit rather than leaving before the tunnels close.\n */\nfunction run(\n\tcommandArgs: readonly [string, ...string[]],\n\tcredentials: Record<string, string>,\n\tcwd: string | undefined,\n): Promise<number> {\n\tconst [cmd, ...args] = commandArgs;\n\tlogger.log(`🚀 Running: ${commandArgs.join(' ')}`);\n\n\tconst inherited = (process.env.NODE_OPTIONS ?? '')\n\t\t.replace(/--import[= ]\\S+/g, '')\n\t\t.trim();\n\tconst nodeOptions = [inherited, credentialsImport(Object.keys(credentials))]\n\t\t.filter(Boolean)\n\t\t.join(' ');\n\n\tconst wait = () => {};\n\tprocess.on('SIGINT', wait);\n\tprocess.on('SIGTERM', wait);\n\treturn new Promise<number>((resolve) => {\n\t\tconst child = spawn(cmd, args, {\n\t\t\t...(cwd ? { cwd } : {}),\n\t\t\tstdio: 'inherit',\n\t\t\tenv: { ...process.env, ...credentials, NODE_OPTIONS: nodeOptions },\n\t\t});\n\t\tchild.on('close', (code, signal) => {\n\t\t\tresolve(code ?? 128 + (signal ? constants.signals[signal] : 0));\n\t\t});\n\t\tchild.on('error', (error) => {\n\t\t\tlogger.error(`Failed to run command: ${error.message}`);\n\t\t\tresolve(1);\n\t\t});\n\t}).finally(() => {\n\t\tprocess.off('SIGINT', wait);\n\t\tprocess.off('SIGTERM', wait);\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,SAAS;;AAGf,IAAa,uBAAb,cAA0C,SAAS;CAC7B;CAArB,YAAY,OAAwB;EACnC,MACC,0EACK,MAAM,yHAEZ;EALoB,KAAA,QAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,uBAAb,cAA0C,SAAS;CAExC;CACA;CAFV,YACC,OACA,SACC;EACD,MACC,IAAI,MAAM,WAAW,QAAQ,KAAK,IAAI,EAAE,qGAEjB,MAAM,EAC9B;EAPS,KAAA,QAAA;EACA,KAAA,UAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,oBAAb,cAAuC,SAAS;CAErC;CACA;CACA;CAHV,YAC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C/D,CAAC;EACD,MAAM,GAAG,UAAU,UAAU;GAC5B,OAAO,MAAM,0BAA0B,MAAM,SAAS;GACtD,QAAQ,CAAC;EACV,CAAC;CACF,CAAC,CAAC,CAAC,cAAc;EAChB,QAAQ,IAAI,UAAU,IAAI;EAC1B,QAAQ,IAAI,WAAW,IAAI;CAC5B,CAAC;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
2
  import { f as storeDokployCredentials, n as chainCredentials, r as storedCredentials } from "./credentials-B5N5yKk6.mjs";
3
3
  import { f as output } from "./discover-Ca8U75dl.mjs";
4
- import { c as prompt, o as validateDokployToken, s as canPrompt } from "./index.mjs";
4
+ import { c as validateDokployToken, l as canPrompt, u as prompt } from "./index.mjs";
5
5
  //#region src/deploy/terminal.ts
6
6
  /**
7
7
  * The credentials `gkm deploy` can ask a person for. CLI layer only.
@@ -82,4 +82,4 @@ function terminalCredentials(base = storedCredentials()) {
82
82
  //#endregion
83
83
  export { terminalCredentials };
84
84
 
85
- //# sourceMappingURL=terminal-mXM-Lqc6.mjs.map
85
+ //# sourceMappingURL=terminal-CybB-cjk.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"terminal-mXM-Lqc6.mjs","names":[],"sources":["../src/deploy/terminal.ts"],"sourcesContent":["/**\n * The credentials `gkm deploy` can ask a person for. CLI layer only.\n *\n * `deploy()` asks its `CredentialProvider` and stops with `MissingCredential`\n * when the answer is nothing. At a terminal, `gkm deploy` would rather ask:\n * this provider reads the environment and the stored login first, and only\n * when both are empty prompts — and stores a Dokploy login it validated, so\n * the next deploy does not ask again. With no terminal it answers nothing, and\n * the deploy says what was missing instead of waiting on a prompt nobody sees.\n */\n\nimport { validateDokployToken } from '../auth';\nimport { storeDokployCredentials } from '../auth/credentials';\nimport { GkmError } from '../errors';\nimport { output } from '../output';\nimport { canPrompt, prompt } from '../prompt';\nimport {\n\ttype CredentialProvider,\n\ttype CredentialRequest,\n\tchainCredentials,\n\tstoredCredentials,\n} from './credentials';\n\nconst logger = output;\n\n/** What answers a deploy prompt without a terminal. */\nconst INSTEAD = 'Please configure manually.';\n\n/** The Dokploy URL typed at the prompt is not a URL. */\nexport class DokployEndpointInvalid extends GkmError {\n\tconstructor(readonly endpoint: string) {\n\t\tsuper('Invalid URL format');\n\t\tthis.name = 'DokployEndpointInvalid';\n\t}\n}\n\n/** Dokploy refused the token typed at the prompt; nothing was stored. */\nexport class DokployTokenRejected extends GkmError {\n\tconstructor(readonly endpoint: string) {\n\t\tsuper('Invalid credentials. Please check your token.');\n\t\tthis.name = 'DokployTokenRejected';\n\t}\n}\n\n/** Asks the person at the terminal for what nothing else supplied. */\nfunction asking(): CredentialProvider {\n\treturn {\n\t\tasync get(asked) {\n\t\t\tif (!canPrompt()) return undefined;\n\t\t\t// The union, so checking `kind` narrows it: `K` itself never is.\n\t\t\tconst request = asked as CredentialRequest;\n\n\t\t\tif (request.kind === 'dokploy') {\n\t\t\t\tlogger.log(\"\\n📋 Dokploy credentials not found. Let's set them up.\");\n\t\t\t\tconst endpoint = (\n\t\t\t\t\tawait prompt('Dokploy URL (e.g., https://dokploy.example.com): ', {\n\t\t\t\t\t\tinstead: INSTEAD,\n\t\t\t\t\t})\n\t\t\t\t).replace(/\\/$/, '');\n\n\t\t\t\ttry {\n\t\t\t\t\tnew URL(endpoint);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DokployEndpointInvalid(endpoint);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(`\\nGenerate a token at: ${endpoint}/settings/profile\\n`);\n\t\t\t\tconst token = await prompt('API Token: ', {\n\t\t\t\t\thidden: true,\n\t\t\t\t\tinstead: INSTEAD,\n\t\t\t\t});\n\n\t\t\t\tlogger.log('\\nValidating credentials...');\n\t\t\t\tif (!(await validateDokployToken(endpoint, token))) {\n\t\t\t\t\tthrow new DokployTokenRejected(endpoint);\n\t\t\t\t}\n\n\t\t\t\tawait storeDokployCredentials(token, endpoint);\n\t\t\t\tlogger.log('✓ Credentials saved');\n\t\t\t\treturn { endpoint, token } as never;\n\t\t\t}\n\n\t\t\t// AWS is a profile or a role, set up with the AWS CLI — not keys\n\t\t\t// typed into a deploy.\n\t\t\tif (request.kind !== 'registry') return undefined;\n\n\t\t\tlogger.log(\n\t\t\t\t` Dokploy has no registry for ${request.url}. Let's create one.`,\n\t\t\t);\n\t\t\tconst username = await prompt('Registry username: ', {\n\t\t\t\tinstead: INSTEAD,\n\t\t\t});\n\t\t\tconst password = await prompt('Registry password/token: ', {\n\t\t\t\thidden: true,\n\t\t\t\tinstead: INSTEAD,\n\t\t\t});\n\t\t\treturn { username, password } as never;\n\t\t},\n\t};\n}\n\n/**\n * The environment, then the stored login, then — at a terminal — the person\n * running the command.\n */\nexport function terminalCredentials(\n\tbase: CredentialProvider = storedCredentials(),\n): CredentialProvider {\n\treturn chainCredentials(base, asking());\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,SAAS;;AAGf,MAAM,UAAU;;AAGhB,IAAa,yBAAb,cAA4C,SAAS;CAC/B;CAArB,YAAY,UAA2B;EACtC,MAAM,oBAAoB;EADN,KAAA,WAAA;EAEpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,uBAAb,cAA0C,SAAS;CAC7B;CAArB,YAAY,UAA2B;EACtC,MAAM,+CAA+C;EADjC,KAAA,WAAA;EAEpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,SAA6B;CACrC,OAAO,EACN,MAAM,IAAI,OAAO;EAChB,IAAI,CAAC,UAAU,GAAG,OAAO,KAAA;EAEzB,MAAM,UAAU;EAEhB,IAAI,QAAQ,SAAS,WAAW;GAC/B,OAAO,IAAI,wDAAwD;GACnE,MAAM,YACL,MAAM,OAAO,qDAAqD,EACjE,SAAS,QACV,CAAC,EAAA,CACA,QAAQ,OAAO,EAAE;GAEnB,IAAI;IACH,IAAI,IAAI,QAAQ;GACjB,QAAQ;IACP,MAAM,IAAI,uBAAuB,QAAQ;GAC1C;GAEA,OAAO,IAAI,0BAA0B,SAAS,oBAAoB;GAClE,MAAM,QAAQ,MAAM,OAAO,eAAe;IACzC,QAAQ;IACR,SAAS;GACV,CAAC;GAED,OAAO,IAAI,6BAA6B;GACxC,IAAI,CAAE,MAAM,qBAAqB,UAAU,KAAK,GAC/C,MAAM,IAAI,qBAAqB,QAAQ;GAGxC,MAAM,wBAAwB,OAAO,QAAQ;GAC7C,OAAO,IAAI,qBAAqB;GAChC,OAAO;IAAE;IAAU;GAAM;EAC1B;EAIA,IAAI,QAAQ,SAAS,YAAY,OAAO,KAAA;EAExC,OAAO,IACN,kCAAkC,QAAQ,IAAI,oBAC/C;EAQA,OAAO;GAAE,UAAA,MAPc,OAAO,uBAAuB,EACpD,SAAS,QACV,CAAC;GAKkB,UAAA,MAJI,OAAO,6BAA6B;IAC1D,QAAQ;IACR,SAAS;GACV,CAAC;EAC2B;CAC7B,EACD;AACD;;;;;AAMA,SAAgB,oBACf,OAA2B,kBAAkB,GACxB;CACrB,OAAO,iBAAiB,MAAM,OAAO,CAAC;AACvC"}
1
+ {"version":3,"file":"terminal-CybB-cjk.mjs","names":[],"sources":["../src/deploy/terminal.ts"],"sourcesContent":["/**\n * The credentials `gkm deploy` can ask a person for. CLI layer only.\n *\n * `deploy()` asks its `CredentialProvider` and stops with `MissingCredential`\n * when the answer is nothing. At a terminal, `gkm deploy` would rather ask:\n * this provider reads the environment and the stored login first, and only\n * when both are empty prompts — and stores a Dokploy login it validated, so\n * the next deploy does not ask again. With no terminal it answers nothing, and\n * the deploy says what was missing instead of waiting on a prompt nobody sees.\n */\n\nimport { validateDokployToken } from '../auth';\nimport { storeDokployCredentials } from '../auth/credentials';\nimport { GkmError } from '../errors';\nimport { output } from '../output';\nimport { canPrompt, prompt } from '../prompt';\nimport {\n\ttype CredentialProvider,\n\ttype CredentialRequest,\n\tchainCredentials,\n\tstoredCredentials,\n} from './credentials';\n\nconst logger = output;\n\n/** What answers a deploy prompt without a terminal. */\nconst INSTEAD = 'Please configure manually.';\n\n/** The Dokploy URL typed at the prompt is not a URL. */\nexport class DokployEndpointInvalid extends GkmError {\n\tconstructor(readonly endpoint: string) {\n\t\tsuper('Invalid URL format');\n\t\tthis.name = 'DokployEndpointInvalid';\n\t}\n}\n\n/** Dokploy refused the token typed at the prompt; nothing was stored. */\nexport class DokployTokenRejected extends GkmError {\n\tconstructor(readonly endpoint: string) {\n\t\tsuper('Invalid credentials. Please check your token.');\n\t\tthis.name = 'DokployTokenRejected';\n\t}\n}\n\n/** Asks the person at the terminal for what nothing else supplied. */\nfunction asking(): CredentialProvider {\n\treturn {\n\t\tasync get(asked) {\n\t\t\tif (!canPrompt()) return undefined;\n\t\t\t// The union, so checking `kind` narrows it: `K` itself never is.\n\t\t\tconst request = asked as CredentialRequest;\n\n\t\t\tif (request.kind === 'dokploy') {\n\t\t\t\tlogger.log(\"\\n📋 Dokploy credentials not found. Let's set them up.\");\n\t\t\t\tconst endpoint = (\n\t\t\t\t\tawait prompt('Dokploy URL (e.g., https://dokploy.example.com): ', {\n\t\t\t\t\t\tinstead: INSTEAD,\n\t\t\t\t\t})\n\t\t\t\t).replace(/\\/$/, '');\n\n\t\t\t\ttry {\n\t\t\t\t\tnew URL(endpoint);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new DokployEndpointInvalid(endpoint);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(`\\nGenerate a token at: ${endpoint}/settings/profile\\n`);\n\t\t\t\tconst token = await prompt('API Token: ', {\n\t\t\t\t\thidden: true,\n\t\t\t\t\tinstead: INSTEAD,\n\t\t\t\t});\n\n\t\t\t\tlogger.log('\\nValidating credentials...');\n\t\t\t\tif (!(await validateDokployToken(endpoint, token))) {\n\t\t\t\t\tthrow new DokployTokenRejected(endpoint);\n\t\t\t\t}\n\n\t\t\t\tawait storeDokployCredentials(token, endpoint);\n\t\t\t\tlogger.log('✓ Credentials saved');\n\t\t\t\treturn { endpoint, token } as never;\n\t\t\t}\n\n\t\t\t// AWS is a profile or a role, set up with the AWS CLI — not keys\n\t\t\t// typed into a deploy.\n\t\t\tif (request.kind !== 'registry') return undefined;\n\n\t\t\tlogger.log(\n\t\t\t\t` Dokploy has no registry for ${request.url}. Let's create one.`,\n\t\t\t);\n\t\t\tconst username = await prompt('Registry username: ', {\n\t\t\t\tinstead: INSTEAD,\n\t\t\t});\n\t\t\tconst password = await prompt('Registry password/token: ', {\n\t\t\t\thidden: true,\n\t\t\t\tinstead: INSTEAD,\n\t\t\t});\n\t\t\treturn { username, password } as never;\n\t\t},\n\t};\n}\n\n/**\n * The environment, then the stored login, then — at a terminal — the person\n * running the command.\n */\nexport function terminalCredentials(\n\tbase: CredentialProvider = storedCredentials(),\n): CredentialProvider {\n\treturn chainCredentials(base, asking());\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,SAAS;;AAGf,MAAM,UAAU;;AAGhB,IAAa,yBAAb,cAA4C,SAAS;CAC/B;CAArB,YAAY,UAA2B;EACtC,MAAM,oBAAoB;EADN,KAAA,WAAA;EAEpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,uBAAb,cAA0C,SAAS;CAC7B;CAArB,YAAY,UAA2B;EACtC,MAAM,+CAA+C;EADjC,KAAA,WAAA;EAEpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,SAA6B;CACrC,OAAO,EACN,MAAM,IAAI,OAAO;EAChB,IAAI,CAAC,UAAU,GAAG,OAAO,KAAA;EAEzB,MAAM,UAAU;EAEhB,IAAI,QAAQ,SAAS,WAAW;GAC/B,OAAO,IAAI,wDAAwD;GACnE,MAAM,YACL,MAAM,OAAO,qDAAqD,EACjE,SAAS,QACV,CAAC,EAAA,CACA,QAAQ,OAAO,EAAE;GAEnB,IAAI;IACH,IAAI,IAAI,QAAQ;GACjB,QAAQ;IACP,MAAM,IAAI,uBAAuB,QAAQ;GAC1C;GAEA,OAAO,IAAI,0BAA0B,SAAS,oBAAoB;GAClE,MAAM,QAAQ,MAAM,OAAO,eAAe;IACzC,QAAQ;IACR,SAAS;GACV,CAAC;GAED,OAAO,IAAI,6BAA6B;GACxC,IAAI,CAAE,MAAM,qBAAqB,UAAU,KAAK,GAC/C,MAAM,IAAI,qBAAqB,QAAQ;GAGxC,MAAM,wBAAwB,OAAO,QAAQ;GAC7C,OAAO,IAAI,qBAAqB;GAChC,OAAO;IAAE;IAAU;GAAM;EAC1B;EAIA,IAAI,QAAQ,SAAS,YAAY,OAAO,KAAA;EAExC,OAAO,IACN,kCAAkC,QAAQ,IAAI,oBAC/C;EAQA,OAAO;GAAE,UAAA,MAPc,OAAO,uBAAuB,EACpD,SAAS,QACV,CAAC;GAKkB,UAAA,MAJI,OAAO,6BAA6B;IAC1D,QAAQ;IACR,SAAS;GACV,CAAC;EAC2B;CAC7B,EACD;AACD;;;;;AAMA,SAAgB,oBACf,OAA2B,kBAAkB,GACxB;CACrB,OAAO,iBAAiB,MAAM,OAAO,CAAC;AACvC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/cli",
3
- "version": "10.0.0-alpha.111",
3
+ "version": "10.0.0-alpha.113",
4
4
  "description": "CLI tools for building Lambda handlers, server applications, and generating OpenAPI specs",
5
5
  "private": false,
6
6
  "type": "module",
@@ -120,16 +120,16 @@
120
120
  "prompts": "~2.4.2",
121
121
  "tsx": "~4.23.15",
122
122
  "yaml": "~2.9.1",
123
- "@geekmidas/cache": "10.0.0-alpha.111",
124
- "@geekmidas/constructs": "~10.0.0-alpha.111",
125
- "@geekmidas/db": "10.0.0-alpha.111",
126
- "@geekmidas/envkit": "~10.0.0-alpha.111",
127
- "@geekmidas/errors": "~10.0.0-alpha.111",
128
- "@geekmidas/logger": "~10.0.0-alpha.111",
129
- "@geekmidas/manifest": "10.0.0-alpha.111",
130
- "@geekmidas/schema": "~10.0.0-alpha.111",
131
- "@geekmidas/services": "~10.0.0-alpha.111",
132
- "@geekmidas/storage": "~10.0.0-alpha.111"
123
+ "@geekmidas/cache": "10.0.0-alpha.113",
124
+ "@geekmidas/constructs": "~10.0.0-alpha.113",
125
+ "@geekmidas/db": "10.0.0-alpha.113",
126
+ "@geekmidas/envkit": "~10.0.0-alpha.113",
127
+ "@geekmidas/errors": "~10.0.0-alpha.113",
128
+ "@geekmidas/logger": "~10.0.0-alpha.113",
129
+ "@geekmidas/manifest": "10.0.0-alpha.113",
130
+ "@geekmidas/schema": "~10.0.0-alpha.113",
131
+ "@geekmidas/services": "~10.0.0-alpha.113",
132
+ "@geekmidas/storage": "~10.0.0-alpha.113"
133
133
  },
134
134
  "devDependencies": {
135
135
  "@hono/node-server": "~1.19.5",
@@ -144,12 +144,12 @@
144
144
  "typescript": "~7.0.2",
145
145
  "vitest": "~5.0.2",
146
146
  "zod": "~4.6.5",
147
- "@geekmidas/emailkit": "~10.0.0-alpha.111",
148
- "@geekmidas/events": "~10.0.0-alpha.111",
149
- "@geekmidas/testkit": "10.0.0-alpha.111"
147
+ "@geekmidas/emailkit": "~10.0.0-alpha.113",
148
+ "@geekmidas/events": "~10.0.0-alpha.113",
149
+ "@geekmidas/testkit": "10.0.0-alpha.113"
150
150
  },
151
151
  "peerDependencies": {
152
- "@geekmidas/telescope": "~10.0.0-alpha.111"
152
+ "@geekmidas/telescope": "~10.0.0-alpha.113"
153
153
  },
154
154
  "peerDependenciesMeta": {
155
155
  "@geekmidas/telescope": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"eas-6ezdJtry.mjs","names":[],"sources":["../src/mobile/eas.ts"],"sourcesContent":["/**\n * `gkm eas:sync --stage <stage>`: a mobile app's EAS project set up for a\n * deployed stage, from what the workspace declares — so a store build, which\n * EAS runs on its own machines, outside gkm, is built with the same values\n * the stage's servers were deployed with.\n *\n * - **`eas.json`**: the stage's build profile (`build.<stage>`) reads its EAS\n * environment and listens on its channel; its submit profile\n * (`submit.<stage>.android`) has its Play track and release status — see\n * `mobileStage`. Every other field is left as it is.\n * - **The EAS environment**: each value the app's build reads for the stage\n * (`StackMobileApp.values`) — its scheme, its edges' public URLs under\n * `EXPO_PUBLIC_`, and every stage secret already named so — set with\n * `eas env:set`, as `plaintext`: a bundle inlines them, so none is secret.\n * Nothing else is written: no server key reaches EAS.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { delimiter, join } from 'node:path';\nimport type {\n\tConstructManifest,\n\tMobileAppDeclaration,\n} from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport { loadStage } from '../exec/stage.js';\nimport { appKey } from '../workspace/derive.js';\nimport { type MobileStage, mobileStage } from './stage.js';\n\nconst logger = console;\n\n/** The workspace declares no `MobileApp`: nothing to set up. */\nexport class NoMobileApp extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'The workspace declares no MobileApp, so there is no EAS project to set ' +\n\t\t\t\t\"up. Declare one: new MobileApp('App', { path: 'apps/app' }).dependsOn([api, auth]).\",\n\t\t);\n\t\tthis.name = 'NoMobileApp';\n\t}\n}\n\n/** Several `MobileApp`s, and nothing to say which. */\nexport class MobileAppNotChosen extends GkmError {\n\tconstructor(readonly apps: readonly string[]) {\n\t\tsuper(\n\t\t\t`The workspace declares ${apps.length} mobile apps (${apps.join(', ')}). ` +\n\t\t\t\t`Run from one's directory, or name it: --app ${apps[0]}.`,\n\t\t);\n\t\tthis.name = 'MobileAppNotChosen';\n\t}\n}\n\n/** `--app` names no `MobileApp`. */\nexport class MobileAppUnknown extends GkmError {\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly apps: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${app}' is not one of the workspace's mobile apps (${apps.join(', ')}).`,\n\t\t);\n\t\tthis.name = 'MobileAppUnknown';\n\t}\n}\n\n/** `eas` is not installed where the app is. */\nexport class EasCliMissing extends GkmError {\n\tconstructor(readonly dir: string) {\n\t\tsuper(\n\t\t\t`No \\`eas\\` to run in ${dir}. Add it to the app: pnpm add -D eas-cli ` +\n\t\t\t\t'(or install it globally: npm install -g eas-cli).',\n\t\t);\n\t\tthis.name = 'EasCliMissing';\n\t}\n}\n\n/** `eas` refused a command. */\nexport class EasCommandFailed extends GkmError {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly code: number | null,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`\\`eas ${command}\\` failed (exit ${code}): ${stderr.trim() || 'it said nothing'}. ` +\n\t\t\t\t'In CI, EXPO_TOKEN must be set; on this machine, `eas login`.',\n\t\t);\n\t\tthis.name = 'EasCommandFailed';\n\t}\n}\n\n/** A platform EAS builds for. */\nexport type EasPlatform = 'ios' | 'android';\n\n/** What gkm asks of EAS, so tests can stand in. */\nexport interface EasCli {\n\t/** Create or update a variable in one of the project's environments. */\n\tsetEnv(\n\t\tdir: string,\n\t\tvariable: { environment: string; name: string; value: string },\n\t): Promise<void>;\n\t/**\n\t * The fingerprint of the app's native code, as a build with `profile`\n\t * would compute it — what its runtime version is.\n\t */\n\tfingerprint(\n\t\tdir: string,\n\t\toptions: { platform: EasPlatform; profile: string },\n\t): Promise<string>;\n\t/** A finished store build of `profile` with that fingerprint, if any. */\n\tstoreBuild(\n\t\tdir: string,\n\t\toptions: { platform: EasPlatform; profile: string; fingerprint: string },\n\t): Promise<string | undefined>;\n\t/** Start a store build of `profile`, submitted to the store when asked. */\n\tbuild(\n\t\tdir: string,\n\t\toptions: {\n\t\t\tplatform: EasPlatform;\n\t\t\tprofile: string;\n\t\t\tsubmit: boolean;\n\t\t\twait: boolean;\n\t\t},\n\t): Promise<void>;\n\t/** Publish an update of the app's JavaScript on a channel. */\n\tupdate(\n\t\tdir: string,\n\t\toptions: {\n\t\t\tplatform: EasPlatform;\n\t\t\tchannel: string;\n\t\t\tenvironment: string;\n\t\t\tmessage: string;\n\t\t},\n\t): Promise<void>;\n}\n\n/**\n * Run `eas` in `dir`: the app's own, else the workspace's, else the one on\n * PATH. What it prints on stdout is answered; a failure is\n * {@link EasCommandFailed} with what it said.\n */\nfunction runEas(\n\troot: string,\n\tdir: string,\n\targs: readonly string[],\n\toptions: { inherit?: boolean; env?: Readonly<Record<string, string>> } = {},\n): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn('eas', [...args, '--non-interactive'], {\n\t\t\tcwd: dir,\n\t\t\t// A build's or an update's progress is the user's to read.\n\t\t\tstdio: ['ignore', options.inherit ? 'inherit' : 'pipe', 'pipe'],\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...options.env,\n\t\t\t\tPATH: [\n\t\t\t\t\tjoin(dir, 'node_modules', '.bin'),\n\t\t\t\t\tjoin(root, 'node_modules', '.bin'),\n\t\t\t\t\tprocess.env.PATH,\n\t\t\t\t].join(delimiter),\n\t\t\t},\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t\tif (options.inherit) process.stderr.write(chunk);\n\t\t});\n\t\tconst command = args.slice(0, 3).join(' ');\n\t\tchild.on('error', (error: NodeJS.ErrnoException) =>\n\t\t\treject(\n\t\t\t\terror.code === 'ENOENT'\n\t\t\t\t\t? new EasCliMissing(dir)\n\t\t\t\t\t: new EasCommandFailed(command, null, error.message),\n\t\t\t),\n\t\t);\n\t\tchild.on('close', (code) =>\n\t\t\tcode === 0\n\t\t\t\t? resolve(stdout)\n\t\t\t\t: reject(new EasCommandFailed(command, code, stderr)),\n\t\t);\n\t});\n}\n\n/** The JSON `eas … --json` printed, read for `what`. */\nfunction easJson(output: string, what: string): unknown {\n\ttry {\n\t\treturn JSON.parse(output);\n\t} catch {\n\t\tthrow new EasCommandFailed(what, 0, `not JSON: ${output.slice(0, 200)}`);\n\t}\n}\n\n/**\n * The real one — never a prompt (`--non-interactive`). `env` is what the\n * app's `app.config.ts` reads for the stage: every `eas` command evaluates\n * it, and one that reads a value it lacks fails before it starts — and a\n * fingerprint computed here must match the one EAS computes with the\n * stage's values.\n */\nexport function easCli(\n\troot: string,\n\tenv: Readonly<Record<string, string>> = {},\n): EasCli {\n\tconst run = (\n\t\tdir: string,\n\t\targs: readonly string[],\n\t\toptions: { inherit?: boolean } = {},\n\t) => runEas(root, dir, args, { ...options, env });\n\treturn {\n\t\tasync setEnv(dir, { environment, name, value }) {\n\t\t\tawait run(dir, [\n\t\t\t\t'env:set',\n\t\t\t\t'--environment',\n\t\t\t\tenvironment,\n\t\t\t\t'--name',\n\t\t\t\tname,\n\t\t\t\t'--value',\n\t\t\t\tvalue,\n\t\t\t\t'--visibility',\n\t\t\t\t'plaintext',\n\t\t\t\t'--scope',\n\t\t\t\t'project',\n\t\t\t]);\n\t\t},\n\n\t\tasync fingerprint(dir, { platform, profile }) {\n\t\t\tconst output = await run(dir, [\n\t\t\t\t'fingerprint:generate',\n\t\t\t\t'--platform',\n\t\t\t\tplatform,\n\t\t\t\t'--build-profile',\n\t\t\t\tprofile,\n\t\t\t\t'--json',\n\t\t\t]);\n\t\t\tconst hash = (\n\t\t\t\teasJson(output, 'fingerprint:generate') as { hash?: unknown }\n\t\t\t).hash;\n\t\t\tif (typeof hash !== 'string') {\n\t\t\t\tthrow new EasCommandFailed('fingerprint:generate', 0, 'no hash');\n\t\t\t}\n\t\t\treturn hash;\n\t\t},\n\n\t\tasync storeBuild(dir, { platform, profile, fingerprint }) {\n\t\t\tconst output = await run(dir, [\n\t\t\t\t'build:list',\n\t\t\t\t'--platform',\n\t\t\t\tplatform,\n\t\t\t\t'--build-profile',\n\t\t\t\tprofile,\n\t\t\t\t'--fingerprint-hash',\n\t\t\t\tfingerprint,\n\t\t\t\t'--status',\n\t\t\t\t'finished',\n\t\t\t\t'--distribution',\n\t\t\t\t'store',\n\t\t\t\t'--limit',\n\t\t\t\t'1',\n\t\t\t\t'--json',\n\t\t\t]);\n\t\t\tconst builds = easJson(output, 'build:list');\n\t\t\tif (!Array.isArray(builds)) return undefined;\n\t\t\tconst id = (builds[0] as { id?: unknown } | undefined)?.id;\n\t\t\treturn typeof id === 'string' ? id : undefined;\n\t\t},\n\n\t\tasync build(dir, { platform, profile, submit, wait }) {\n\t\t\tawait run(\n\t\t\t\tdir,\n\t\t\t\t[\n\t\t\t\t\t'build',\n\t\t\t\t\t'--platform',\n\t\t\t\t\tplatform,\n\t\t\t\t\t'--profile',\n\t\t\t\t\tprofile,\n\t\t\t\t\t...(submit ? ['--auto-submit'] : []),\n\t\t\t\t\t...(wait ? [] : ['--no-wait']),\n\t\t\t\t],\n\t\t\t\t{ inherit: true },\n\t\t\t);\n\t\t},\n\n\t\tasync update(dir, { platform, channel, environment, message }) {\n\t\t\tawait run(\n\t\t\t\tdir,\n\t\t\t\t[\n\t\t\t\t\t'update',\n\t\t\t\t\t'--platform',\n\t\t\t\t\tplatform,\n\t\t\t\t\t'--channel',\n\t\t\t\t\tchannel,\n\t\t\t\t\t'--environment',\n\t\t\t\t\tenvironment,\n\t\t\t\t\t'--message',\n\t\t\t\t\tmessage,\n\t\t\t\t],\n\t\t\t\t{ inherit: true },\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * The mobile app a command is about: the one `--app` names, else the one\n * this directory is, else the only one.\n *\n * @throws {NoMobileApp}, {MobileAppNotChosen}, {MobileAppUnknown}\n */\nexport function chooseMobileApp(\n\tmanifest: ConstructManifest,\n\tapp: string | undefined,\n\there: string | undefined,\n): MobileAppDeclaration {\n\tconst declarations = Object.values(manifest).filter(\n\t\t(declaration): declaration is MobileAppDeclaration =>\n\t\t\tdeclaration.kind === 'mobile-app',\n\t);\n\tconst names = declarations.map((declaration) => appKey(declaration.id));\n\tif (declarations.length === 0) throw new NoMobileApp();\n\tconst name =\n\t\tapp ??\n\t\t(here && names.includes(here)\n\t\t\t? here\n\t\t\t: names.length === 1\n\t\t\t\t? names[0]\n\t\t\t\t: undefined);\n\tif (!name) throw new MobileAppNotChosen(names);\n\tconst declaration = declarations.find((d) => appKey(d.id) === name);\n\tif (!declaration) throw new MobileAppUnknown(name, names);\n\treturn declaration;\n}\n\n/** `eas.json`, as far as gkm writes it. */\ninterface EasJson {\n\tbuild?: Record<string, Record<string, unknown>>;\n\tsubmit?: Record<string, Record<string, unknown>>;\n\t[key: string]: unknown;\n}\n\n/**\n * `eas.json` with the stage's build and submit profiles as `stage` says:\n * every field gkm does not decide is kept.\n */\nexport function withStageProfiles(\n\teasJson: EasJson,\n\tstage: MobileStage,\n): EasJson {\n\tconst build = easJson.build?.[stage.stage] ?? {};\n\tconst submit = easJson.submit?.[stage.stage] ?? {};\n\tconst android = (submit.android as Record<string, unknown> | undefined) ?? {};\n\treturn {\n\t\t...easJson,\n\t\tbuild: {\n\t\t\t...easJson.build,\n\t\t\t[stage.stage]: {\n\t\t\t\t...build,\n\t\t\t\tenvironment: stage.environment,\n\t\t\t\tchannel: stage.channel,\n\t\t\t},\n\t\t},\n\t\tsubmit: {\n\t\t\t...easJson.submit,\n\t\t\t[stage.stage]: {\n\t\t\t\t...submit,\n\t\t\t\tandroid: {\n\t\t\t\t\t...android,\n\t\t\t\t\ttrack: stage.android.track,\n\t\t\t\t\treleaseStatus: stage.android.releaseStatus,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport interface EasSyncOptions {\n\tstage: string;\n\t/** The mobile app, by its app key; the one here, or the only one, if not. */\n\tapp?: string;\n\t/** The AWS profile for the stage's account, where its secrets are kept. */\n\tprofile?: string;\n\tcwd?: string;\n\t/** Say what would be written, and write nothing. */\n\tdryRun?: boolean;\n}\n\n/** What a sync wrote — or, dry, would. */\nexport interface EasSyncResult {\n\tapp: string;\n\t/** The workspace's root, where its `eas` may be installed. */\n\troot: string;\n\tdir: string;\n\tstage: MobileStage;\n\tvalues: Record<string, string>;\n\t/** Whether `eas.json` changed. */\n\teasJsonChanged: boolean;\n}\n\n/**\n * Set up a mobile app's EAS project for a deployed stage.\n *\n * @throws {NoMobileApp}, {MobileAppNotChosen}, {MobileAppUnknown},\n * {MobileAppStageUndeclared}, {EasCliMissing}, {EasCommandFailed} — and\n * what loading the stage throws: {UndeclaredStage}, {ExecStageNotComposed},\n * {ExecStageNotDeployed}\n */\nexport async function easSync(\n\toptions: EasSyncOptions,\n\teas?: EasCli,\n): Promise<EasSyncResult> {\n\tconst loaded = await loadStage(options);\n\tconst { workspace, manifest, stack } = loaded;\n\n\tconst declaration = chooseMobileApp(manifest, options.app, loaded.appName);\n\tconst name = appKey(declaration.id);\n\n\tconst stage = mobileStage(workspace, declaration, options.stage);\n\tconst values =\n\t\tstack.mobileApps.find((candidate) => candidate.name === name)?.values ?? {};\n\tconst dir = join(workspace.root, declaration.app.path);\n\n\tconst path = join(dir, 'eas.json');\n\tconst before = existsSync(path)\n\t\t? (JSON.parse(await readFile(path, 'utf8')) as EasJson)\n\t\t: {};\n\tconst after = withStageProfiles(before, stage);\n\tconst easJsonChanged = JSON.stringify(before) !== JSON.stringify(after);\n\n\tconst where = `${name} on '${stage.stage}': EAS environment '${stage.environment}', channel '${stage.channel}', Play track '${stage.android.track}' (${stage.android.releaseStatus})`;\n\tif (options.dryRun) {\n\t\tlogger.log(`📱 ${where} (dry run)`);\n\t\tif (easJsonChanged) {\n\t\t\tlogger.log(\n\t\t\t\t` would write build.${stage.stage} and submit.${stage.stage} in ${path}`,\n\t\t\t);\n\t\t}\n\t\tfor (const [key, value] of Object.entries(values)) {\n\t\t\tlogger.log(` would set ${key}=${value}`);\n\t\t}\n\t\treturn {\n\t\t\tapp: name,\n\t\t\troot: workspace.root,\n\t\t\tdir,\n\t\t\tstage,\n\t\t\tvalues,\n\t\t\teasJsonChanged,\n\t\t};\n\t}\n\n\tlogger.log(`📱 ${where}`);\n\tif (easJsonChanged) {\n\t\tawait writeFile(path, `${JSON.stringify(after, null, 2)}\\n`);\n\t\tlogger.log(\n\t\t\t` wrote build.${stage.stage} and submit.${stage.stage} in ${path}`,\n\t\t);\n\t}\n\tconst cli = eas ?? easCli(workspace.root, values);\n\tfor (const [key, value] of Object.entries(values)) {\n\t\tawait cli.setEnv(dir, { environment: stage.environment, name: key, value });\n\t\tlogger.log(` set ${key}`);\n\t}\n\treturn {\n\t\tapp: name,\n\t\troot: workspace.root,\n\t\tdir,\n\t\tstage,\n\t\tvalues,\n\t\teasJsonChanged,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,SAAS;;AAGf,IAAa,cAAb,cAAiC,SAAS;CACzC,cAAc;EACb,MACC,4JAED;EACA,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwC,SAAS;CAC3B;CAArB,YAAY,MAAkC;EAC7C,MACC,0BAA0B,KAAK,OAAO,gBAAgB,KAAK,KAAK,IAAI,EAAE,iDACtB,KAAK,GAAG,EACzD;EAJoB,KAAA,OAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,mBAAb,cAAsC,SAAS;CAEpC;CACA;CAFV,YACC,KACA,MACC;EACD,MACC,IAAI,IAAI,+CAA+C,KAAK,KAAK,IAAI,EAAE,GACxE;EALS,KAAA,MAAA;EACA,KAAA,OAAA;EAKT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,gBAAb,cAAmC,SAAS;CACtB;CAArB,YAAY,KAAsB;EACjC,MACC,wBAAwB,IAAI,2FAE7B;EAJoB,KAAA,MAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,mBAAb,cAAsC,SAAS;CAEpC;CACA;CACA;CAHV,YACC,SACA,MACA,QACC;EACD,MACC,SAAS,QAAQ,kBAAkB,KAAK,KAAK,OAAO,KAAK,KAAK,kBAAkB,iEAEjF;EAPS,KAAA,UAAA;EACA,KAAA,OAAA;EACA,KAAA,SAAA;EAMT,KAAK,OAAO;CACb;AACD;;;;;;AAoDA,SAAS,OACR,MACA,KACA,MACA,UAAyE,CAAC,GACxD;CAClB,OAAO,IAAI,SAAS,SAAS,WAAW;EACvC,MAAM,QAAQ,MAAM,OAAO,CAAC,GAAG,M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WAAW,IAAI,IAC1B,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC,IACxC,CAAC;CACJ,MAAM,QAAQ,kBAAkB,QAAQ,KAAK;CAC7C,MAAM,iBAAiB,KAAK,UAAU,MAAM,MAAM,KAAK,UAAU,KAAK;CAEtE,MAAM,QAAQ,GAAG,KAAK,OAAO,MAAM,MAAM,sBAAsB,MAAM,YAAY,cAAc,MAAM,QAAQ,iBAAiB,MAAM,QAAQ,MAAM,KAAK,MAAM,QAAQ,cAAc;CACnL,IAAI,QAAQ,QAAQ;EACnB,OAAO,IAAI,MAAM,MAAM,WAAW;EAClC,IAAI,gBACH,OAAO,IACN,wBAAwB,MAAM,MAAM,cAAc,MAAM,MAAM,MAAM,MACrE;EAED,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC/C,OAAO,IAAI,gBAAgB,IAAI,GAAG,OAAO;EAE1C,OAAO;GACN,KAAK;GACL,MAAM,UAAU;GAChB;GACA;GACA;GACA;EACD;CACD;CAEA,OAAO,IAAI,MAAM,OAAO;CACxB,IAAI,gBAAgB;EACnB,MAAM,UAAU,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,GAAG;EAC3D,OAAO,IACN,kBAAkB,MAAM,MAAM,cAAc,MAAM,MAAM,MAAM,MAC/D;CACD;CACA,MAAM,MAAM,OAAO,OAAO,UAAU,MAAM,MAAM;CAChD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EAClD,MAAM,IAAI,OAAO,KAAK;GAAE,aAAa,MAAM;GAAa,MAAM;GAAK;EAAM,CAAC;EAC1E,OAAO,IAAI,UAAU,KAAK;CAC3B;CACA,OAAO;EACN,KAAK;EACL,MAAM,UAAU;EAChB;EACA;EACA;EACA;CACD;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"eas-BkLA60P2.cjs","names":["GkmError","spawn","join","delimiter","appKey","loadStage","mobileStage","existsSync","readFile","writeFile"],"sources":["../src/mobile/eas.ts"],"sourcesContent":["/**\n * `gkm eas:sync --stage <stage>`: a mobile app's EAS project set up for a\n * deployed stage, from what the workspace declares — so a store build, which\n * EAS runs on its own machines, outside gkm, is built with the same values\n * the stage's servers were deployed with.\n *\n * - **`eas.json`**: the stage's build profile (`build.<stage>`) reads its EAS\n * environment and listens on its channel; its submit profile\n * (`submit.<stage>.android`) has its Play track and release status — see\n * `mobileStage`. Every other field is left as it is.\n * - **The EAS environment**: each value the app's build reads for the stage\n * (`StackMobileApp.values`) — its scheme, its edges' public URLs under\n * `EXPO_PUBLIC_`, and every stage secret already named so — set with\n * `eas env:set`, as `plaintext`: a bundle inlines them, so none is secret.\n * Nothing else is written: no server key reaches EAS.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { delimiter, join } from 'node:path';\nimport type {\n\tConstructManifest,\n\tMobileAppDeclaration,\n} from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport { loadStage } from '../exec/stage.js';\nimport { appKey } from '../workspace/derive.js';\nimport { type MobileStage, mobileStage } from './stage.js';\n\nconst logger = console;\n\n/** The workspace declares no `MobileApp`: nothing to set up. */\nexport class NoMobileApp extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'The workspace declares no MobileApp, so there is no EAS project to set ' +\n\t\t\t\t\"up. Declare one: new MobileApp('App', { path: 'apps/app' }).dependsOn([api, auth]).\",\n\t\t);\n\t\tthis.name = 'NoMobileApp';\n\t}\n}\n\n/** Several `MobileApp`s, and nothing to say which. */\nexport class MobileAppNotChosen extends GkmError {\n\tconstructor(readonly apps: readonly string[]) {\n\t\tsuper(\n\t\t\t`The workspace declares ${apps.length} mobile apps (${apps.join(', ')}). ` +\n\t\t\t\t`Run from one's directory, or name it: --app ${apps[0]}.`,\n\t\t);\n\t\tthis.name = 'MobileAppNotChosen';\n\t}\n}\n\n/** `--app` names no `MobileApp`. */\nexport class MobileAppUnknown extends GkmError {\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly apps: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${app}' is not one of the workspace's mobile apps (${apps.join(', ')}).`,\n\t\t);\n\t\tthis.name = 'MobileAppUnknown';\n\t}\n}\n\n/** `eas` is not installed where the app is. */\nexport class EasCliMissing extends GkmError {\n\tconstructor(readonly dir: string) {\n\t\tsuper(\n\t\t\t`No \\`eas\\` to run in ${dir}. Add it to the app: pnpm add -D eas-cli ` +\n\t\t\t\t'(or install it globally: npm install -g eas-cli).',\n\t\t);\n\t\tthis.name = 'EasCliMissing';\n\t}\n}\n\n/** `eas` refused a command. */\nexport class EasCommandFailed extends GkmError {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly code: number | null,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`\\`eas ${command}\\` failed (exit ${code}): ${stderr.trim() || 'it said nothing'}. ` +\n\t\t\t\t'In CI, EXPO_TOKEN must be set; on this machine, `eas login`.',\n\t\t);\n\t\tthis.name = 'EasCommandFailed';\n\t}\n}\n\n/** A platform EAS builds for. */\nexport type EasPlatform = 'ios' | 'android';\n\n/** What gkm asks of EAS, so tests can stand in. */\nexport interface EasCli {\n\t/** Create or update a variable in one of the project's environments. */\n\tsetEnv(\n\t\tdir: string,\n\t\tvariable: { environment: string; name: string; value: string },\n\t): Promise<void>;\n\t/**\n\t * The fingerprint of the app's native code, as a build with `profile`\n\t * would compute it — what its runtime version is.\n\t */\n\tfingerprint(\n\t\tdir: string,\n\t\toptions: { platform: EasPlatform; profile: string },\n\t): Promise<string>;\n\t/** A finished store build of `profile` with that fingerprint, if any. */\n\tstoreBuild(\n\t\tdir: string,\n\t\toptions: { platform: EasPlatform; profile: string; fingerprint: string },\n\t): Promise<string | undefined>;\n\t/** Start a store build of `profile`, submitted to the store when asked. */\n\tbuild(\n\t\tdir: string,\n\t\toptions: {\n\t\t\tplatform: EasPlatform;\n\t\t\tprofile: string;\n\t\t\tsubmit: boolean;\n\t\t\twait: boolean;\n\t\t},\n\t): Promise<void>;\n\t/** Publish an update of the app's JavaScript on a channel. */\n\tupdate(\n\t\tdir: string,\n\t\toptions: {\n\t\t\tplatform: EasPlatform;\n\t\t\tchannel: string;\n\t\t\tenvironment: string;\n\t\t\tmessage: string;\n\t\t},\n\t): Promise<void>;\n}\n\n/**\n * Run `eas` in `dir`: the app's own, else the workspace's, else the one on\n * PATH. What it prints on stdout is answered; a failure is\n * {@link EasCommandFailed} with what it said.\n */\nfunction runEas(\n\troot: string,\n\tdir: string,\n\targs: readonly string[],\n\toptions: { inherit?: boolean; env?: Readonly<Record<string, string>> } = {},\n): Promise<string> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn('eas', [...args, '--non-interactive'], {\n\t\t\tcwd: dir,\n\t\t\t// A build's or an update's progress is the user's to read.\n\t\t\tstdio: ['ignore', options.inherit ? 'inherit' : 'pipe', 'pipe'],\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...options.env,\n\t\t\t\tPATH: [\n\t\t\t\t\tjoin(dir, 'node_modules', '.bin'),\n\t\t\t\t\tjoin(root, 'node_modules', '.bin'),\n\t\t\t\t\tprocess.env.PATH,\n\t\t\t\t].join(delimiter),\n\t\t\t},\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t\tif (options.inherit) process.stderr.write(chunk);\n\t\t});\n\t\tconst command = args.slice(0, 3).join(' ');\n\t\tchild.on('error', (error: NodeJS.ErrnoException) =>\n\t\t\treject(\n\t\t\t\terror.code === 'ENOENT'\n\t\t\t\t\t? new EasCliMissing(dir)\n\t\t\t\t\t: new EasCommandFailed(command, null, error.message),\n\t\t\t),\n\t\t);\n\t\tchild.on('close', (code) =>\n\t\t\tcode === 0\n\t\t\t\t? resolve(stdout)\n\t\t\t\t: reject(new EasCommandFailed(command, code, stderr)),\n\t\t);\n\t});\n}\n\n/** The JSON `eas … --json` printed, read for `what`. */\nfunction easJson(output: string, what: string): unknown {\n\ttry {\n\t\treturn JSON.parse(output);\n\t} catch {\n\t\tthrow new EasCommandFailed(what, 0, `not JSON: ${output.slice(0, 200)}`);\n\t}\n}\n\n/**\n * The real one — never a prompt (`--non-interactive`). `env` is what the\n * app's `app.config.ts` reads for the stage: every `eas` command evaluates\n * it, and one that reads a value it lacks fails before it starts — and a\n * fingerprint computed here must match the one EAS computes with the\n * stage's values.\n */\nexport function easCli(\n\troot: string,\n\tenv: Readonly<Record<string, string>> = {},\n): EasCli {\n\tconst run = (\n\t\tdir: string,\n\t\targs: readonly string[],\n\t\toptions: { inherit?: boolean } = {},\n\t) => runEas(root, dir, args, { ...options, env });\n\treturn {\n\t\tasync setEnv(dir, { environment, name, value }) {\n\t\t\tawait run(dir, [\n\t\t\t\t'env:set',\n\t\t\t\t'--environment',\n\t\t\t\tenvironment,\n\t\t\t\t'--name',\n\t\t\t\tname,\n\t\t\t\t'--value',\n\t\t\t\tvalue,\n\t\t\t\t'--visibility',\n\t\t\t\t'plaintext',\n\t\t\t\t'--scope',\n\t\t\t\t'project',\n\t\t\t]);\n\t\t},\n\n\t\tasync fingerprint(dir, { platform, profile }) {\n\t\t\tconst output = await run(dir, [\n\t\t\t\t'fingerprint:generate',\n\t\t\t\t'--platform',\n\t\t\t\tplatform,\n\t\t\t\t'--build-profile',\n\t\t\t\tprofile,\n\t\t\t\t'--json',\n\t\t\t]);\n\t\t\tconst hash = (\n\t\t\t\teasJson(output, 'fingerprint:generate') as { hash?: unknown }\n\t\t\t).hash;\n\t\t\tif (typeof hash !== 'string') {\n\t\t\t\tthrow new EasCommandFailed('fingerprint:generate', 0, 'no hash');\n\t\t\t}\n\t\t\treturn hash;\n\t\t},\n\n\t\tasync storeBuild(dir, { platform, profile, fingerprint }) {\n\t\t\tconst output = await run(dir, [\n\t\t\t\t'build:list',\n\t\t\t\t'--platform',\n\t\t\t\tplatform,\n\t\t\t\t'--build-profile',\n\t\t\t\tprofile,\n\t\t\t\t'--fingerprint-hash',\n\t\t\t\tfingerprint,\n\t\t\t\t'--status',\n\t\t\t\t'finished',\n\t\t\t\t'--distribution',\n\t\t\t\t'store',\n\t\t\t\t'--limit',\n\t\t\t\t'1',\n\t\t\t\t'--json',\n\t\t\t]);\n\t\t\tconst builds = easJson(output, 'build:list');\n\t\t\tif (!Array.isArray(builds)) return undefined;\n\t\t\tconst id = (builds[0] as { id?: unknown } | undefined)?.id;\n\t\t\treturn typeof id === 'string' ? id : undefined;\n\t\t},\n\n\t\tasync build(dir, { platform, profile, submit, wait }) {\n\t\t\tawait run(\n\t\t\t\tdir,\n\t\t\t\t[\n\t\t\t\t\t'build',\n\t\t\t\t\t'--platform',\n\t\t\t\t\tplatform,\n\t\t\t\t\t'--profile',\n\t\t\t\t\tprofile,\n\t\t\t\t\t...(submit ? ['--auto-submit'] : []),\n\t\t\t\t\t...(wait ? [] : ['--no-wait']),\n\t\t\t\t],\n\t\t\t\t{ inherit: true },\n\t\t\t);\n\t\t},\n\n\t\tasync update(dir, { platform, channel, environment, message }) {\n\t\t\tawait run(\n\t\t\t\tdir,\n\t\t\t\t[\n\t\t\t\t\t'update',\n\t\t\t\t\t'--platform',\n\t\t\t\t\tplatform,\n\t\t\t\t\t'--channel',\n\t\t\t\t\tchannel,\n\t\t\t\t\t'--environment',\n\t\t\t\t\tenvironment,\n\t\t\t\t\t'--message',\n\t\t\t\t\tmessage,\n\t\t\t\t],\n\t\t\t\t{ inherit: true },\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * The mobile app a command is about: the one `--app` names, else the one\n * this directory is, else the only one.\n *\n * @throws {NoMobileApp}, {MobileAppNotChosen}, {MobileAppUnknown}\n */\nexport function chooseMobileApp(\n\tmanifest: ConstructManifest,\n\tapp: string | undefined,\n\there: string | undefined,\n): MobileAppDeclaration {\n\tconst declarations = Object.values(manifest).filter(\n\t\t(declaration): declaration is MobileAppDeclaration =>\n\t\t\tdeclaration.kind === 'mobile-app',\n\t);\n\tconst names = declarations.map((declaration) => appKey(declaration.id));\n\tif (declarations.length === 0) throw new NoMobileApp();\n\tconst name =\n\t\tapp ??\n\t\t(here && names.includes(here)\n\t\t\t? here\n\t\t\t: names.length === 1\n\t\t\t\t? names[0]\n\t\t\t\t: undefined);\n\tif (!name) throw new MobileAppNotChosen(names);\n\tconst declaration = declarations.find((d) => appKey(d.id) === name);\n\tif (!declaration) throw new MobileAppUnknown(name, names);\n\treturn declaration;\n}\n\n/** `eas.json`, as far as gkm writes it. */\ninterface EasJson {\n\tbuild?: Record<string, Record<string, unknown>>;\n\tsubmit?: Record<string, Record<string, unknown>>;\n\t[key: string]: unknown;\n}\n\n/**\n * `eas.json` with the stage's build and submit profiles as `stage` says:\n * every field gkm does not decide is kept.\n */\nexport function withStageProfiles(\n\teasJson: EasJson,\n\tstage: MobileStage,\n): EasJson {\n\tconst build = easJson.build?.[stage.stage] ?? {};\n\tconst submit = easJson.submit?.[stage.stage] ?? {};\n\tconst android = (submit.android as Record<string, unknown> | undefined) ?? {};\n\treturn {\n\t\t...easJson,\n\t\tbuild: {\n\t\t\t...easJson.build,\n\t\t\t[stage.stage]: {\n\t\t\t\t...build,\n\t\t\t\tenvironment: stage.environment,\n\t\t\t\tchannel: stage.channel,\n\t\t\t},\n\t\t},\n\t\tsubmit: {\n\t\t\t...easJson.submit,\n\t\t\t[stage.stage]: {\n\t\t\t\t...submit,\n\t\t\t\tandroid: {\n\t\t\t\t\t...android,\n\t\t\t\t\ttrack: stage.android.track,\n\t\t\t\t\treleaseStatus: stage.android.releaseStatus,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport interface EasSyncOptions {\n\tstage: string;\n\t/** The mobile app, by its app key; the one here, or the only one, if not. */\n\tapp?: string;\n\t/** The AWS profile for the stage's account, where its secrets are kept. */\n\tprofile?: string;\n\tcwd?: string;\n\t/** Say what would be written, and write nothing. */\n\tdryRun?: boolean;\n}\n\n/** What a sync wrote — or, dry, would. */\nexport interface EasSyncResult {\n\tapp: string;\n\t/** The workspace's root, where its `eas` may be installed. */\n\troot: string;\n\tdir: string;\n\tstage: MobileStage;\n\tvalues: Record<string, string>;\n\t/** Whether `eas.json` changed. */\n\teasJsonChanged: boolean;\n}\n\n/**\n * Set up a mobile app's EAS project for a deployed stage.\n *\n * @throws {NoMobileApp}, {MobileAppNotChosen}, {MobileAppUnknown},\n * {MobileAppStageUndeclared}, {EasCliMissing}, {EasCommandFailed} — and\n * what loading the stage throws: {UndeclaredStage}, {ExecStageNotComposed},\n * {ExecStageNotDeployed}\n */\nexport async function easSync(\n\toptions: EasSyncOptions,\n\teas?: EasCli,\n): Promise<EasSyncResult> {\n\tconst loaded = await loadStage(options);\n\tconst { workspace, manifest, stack } = loaded;\n\n\tconst declaration = chooseMobileApp(manifest, options.app, loaded.appName);\n\tconst name = appKey(declaration.id);\n\n\tconst stage = mobileStage(workspace, declaration, options.stage);\n\tconst values =\n\t\tstack.mobileApps.find((candidate) => candidate.name === name)?.values ?? {};\n\tconst dir = join(workspace.root, declaration.app.path);\n\n\tconst path = join(dir, 'eas.json');\n\tconst before = existsSync(path)\n\t\t? (JSON.parse(await readFile(path, 'utf8')) as EasJson)\n\t\t: {};\n\tconst after = withStageProfiles(before, stage);\n\tconst easJsonChanged = JSON.stringify(before) !== JSON.stringify(after);\n\n\tconst where = `${name} on '${stage.stage}': EAS environment '${stage.environment}', channel '${stage.channel}', Play track '${stage.android.track}' (${stage.android.releaseStatus})`;\n\tif (options.dryRun) {\n\t\tlogger.log(`📱 ${where} (dry run)`);\n\t\tif (easJsonChanged) {\n\t\t\tlogger.log(\n\t\t\t\t` would write build.${stage.stage} and submit.${stage.stage} in ${path}`,\n\t\t\t);\n\t\t}\n\t\tfor (const [key, value] of Object.entries(values)) {\n\t\t\tlogger.log(` would set ${key}=${value}`);\n\t\t}\n\t\treturn {\n\t\t\tapp: name,\n\t\t\troot: workspace.root,\n\t\t\tdir,\n\t\t\tstage,\n\t\t\tvalues,\n\t\t\teasJsonChanged,\n\t\t};\n\t}\n\n\tlogger.log(`📱 ${where}`);\n\tif (easJsonChanged) {\n\t\tawait writeFile(path, `${JSON.stringify(after, null, 2)}\\n`);\n\t\tlogger.log(\n\t\t\t` wrote build.${stage.stage} and submit.${stage.stage} in ${path}`,\n\t\t);\n\t}\n\tconst cli = eas ?? easCli(workspace.root, values);\n\tfor (const [key, value] of Object.entries(values)) {\n\t\tawait cli.setEnv(dir, { environment: stage.environment, name: key, value });\n\t\tlogger.log(` set ${key}`);\n\t}\n\treturn {\n\t\tapp: name,\n\t\troot: workspace.root,\n\t\tdir,\n\t\tstage,\n\t\tvalues,\n\t\teasJsonChanged,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,SAAS;;AAGf,IAAa,cAAb,cAAiCA,eAAAA,SAAS;CACzC,cAAc;EACb,MACC,4JAED;EACA,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwCA,eAAAA,SAAS;CAC3B;CAArB,YAAY,MAAkC;EAC7C,MACC,0BAA0B,KAAK,OAAO,gBAAgB,KAAK,KAAK,IAAI,EAAE,iDACtB,KAAK,GAAG,EACzD;EAJoB,KAAA,OAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,mBAAb,cAAsCA,eAAAA,SAAS;CAEpC;CACA;CAFV,YACC,KACA,MACC;EACD,MACC,IAAI,IAAI,+CAA+C,KAAK,KAAK,IAAI,EAAE,GACxE;EALS,KAAA,MAAA;EACA,KAAA,OAAA;EAKT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,gBAAb,cAAmCA,eAAAA,SAAS;CACtB;CAArB,YAAY,KAAsB;EACjC,MACC,wBAAwB,IAAI,2FAE7B;EAJoB,KAAA,MAAA;EAKpB,KAAK,OAAO;CAC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OAAO,IAAI,MAAM,OAAO;CACxB,IAAI,gBAAgB;EACnB,OAAA,GAAMC,iBAAAA,UAAAA,CAAU,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,GAAG;EAC3D,OAAO,IACN,kBAAkB,MAAM,MAAM,cAAc,MAAM,MAAM,MAAM,MAC/D;CACD;CACA,MAAM,MAAM,OAAO,OAAO,UAAU,MAAM,MAAM;CAChD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EAClD,MAAM,IAAI,OAAO,KAAK;GAAE,aAAa,MAAM;GAAa,MAAM;GAAK;EAAM,CAAC;EAC1E,OAAO,IAAI,UAAU,KAAK;CAC3B;CACA,OAAO;EACN,KAAK;EACL,MAAM,UAAU;EAChB;EACA;EACA;EACA;CACD;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"github-D2eABlxM.mjs","names":[],"sources":["../src/deploy/githubOidc.ts","../src/deploy/githubPolicy.ts","../src/deploy/github.ts"],"sourcesContent":["/**\n * The `sub` GitHub puts in a deploy job's OIDC token — what the deploy role's\n * trust policy has to match exactly.\n *\n * It is not always `repo:<owner>/<name>:environment:<stage>`. A repository\n * (or its organisation) decides the format, and says which through\n * `GET /repos/{owner}/{repo}/actions/oidc/customization/sub`:\n *\n * - the default: `repo:<owner>/<name>:environment:<stage>`;\n * - the immutable subject — the default for repositories created after\n * 15 July 2026, opt-in before — puts the owner's and the repository's ids in\n * the `repo` segment: `repo:<owner>@<ownerId>/<name>@<repoId>:environment:<stage>`.\n * The API hands that segment back as `sub_claim_prefix`;\n * - a custom template (`use_default: false`) builds the `sub` from\n * `include_claim_keys`, in order, each as `<key>:<value>` joined by `:`,\n * where `context` is `environment:<stage>` in an environment job.\n *\n * A `:` inside a value is sent as `%3A`.\n *\n * See https://docs.github.com/en/actions/reference/security/oidc.\n */\n\nimport { GkmError } from '../errors';\nimport type { Gh } from './github.js';\n\n/** `GET /repos/{owner}/{repo}/actions/oidc/customization/sub`. */\nexport interface OidcSubjectCustomization {\n\tuse_default: boolean;\n\tinclude_claim_keys?: string[];\n\tuse_immutable_subject?: boolean;\n\t/** The `repo` segment of the subject, as GitHub will send it. */\n\tsub_claim_prefix?: string;\n}\n\n/** What `GET /repos/{owner}/{repo}` says that a subject may include. */\nexport interface RepoFacts {\n\townerId: number;\n\trepoId: number;\n\tvisibility: string;\n}\n\n/**\n * Template keys whose values are known for a repository's environment job\n * before the job runs. Anything else — `job_workflow_ref`, `ref`, `sha`,\n * `run_id`, `workflow`, `actor`, a custom property — depends on the run.\n */\nexport const SUPPORTED_CLAIM_KEYS = [\n\t'repo',\n\t'context',\n\t'environment',\n\t'repository',\n\t'repository_owner',\n\t'repository_owner_id',\n\t'repository_id',\n\t'repository_visibility',\n] as const;\n\nconst NEEDS_FACTS = new Set([\n\t'repository_owner_id',\n\t'repository_id',\n\t'repository_visibility',\n]);\n\n/** A `:` inside a claim value is sent as `%3A`. */\nfunction claim(value: string): string {\n\treturn value.replaceAll(':', '%3A');\n}\n\n/** Which kind of subject the repository uses, for the output. */\nexport type OidcSubjectKind = 'default' | 'immutable' | 'custom' | 'assumed';\n\n/** Whether {@link oidcSubject} needs the repository's ids or visibility. */\nexport function needsRepoFacts(\n\tcustomization: OidcSubjectCustomization,\n): boolean {\n\tconst immutableWithoutPrefix =\n\t\tcustomization.use_immutable_subject === true &&\n\t\t!customization.sub_claim_prefix;\n\tif (customization.use_default) return immutableWithoutPrefix;\n\n\tconst keys = customization.include_claim_keys ?? [];\n\treturn keys.some(\n\t\t(key) => NEEDS_FACTS.has(key) || (key === 'repo' && immutableWithoutPrefix),\n\t);\n}\n\n/**\n * The exact `sub` of a job in `repo`'s `stage` environment.\n *\n * @throws OidcSubjectNotSupported when a custom template includes a claim\n * whose value depends on the run, so no one subject can be trusted.\n */\nexport function oidcSubject(\n\trepo: string,\n\tstage: string,\n\tcustomization: OidcSubjectCustomization,\n\tfacts?: RepoFacts,\n): { subject: string; kind: OidcSubjectKind } {\n\tconst [owner = '', name = ''] = repo.split('/');\n\tconst environment = `environment:${claim(stage)}`;\n\n\tconst repoSegment = (): string => {\n\t\tif (customization.sub_claim_prefix) return customization.sub_claim_prefix;\n\t\tif (customization.use_immutable_subject) {\n\t\t\tif (!facts) throw new RepoFactsRequired(repo);\n\t\t\treturn `repo:${owner}@${facts.ownerId}/${name}@${facts.repoId}`;\n\t\t}\n\t\treturn `repo:${repo}`;\n\t};\n\tconst immutable =\n\t\tcustomization.use_immutable_subject === true ||\n\t\tcustomization.sub_claim_prefix !== undefined;\n\n\tif (customization.use_default) {\n\t\treturn {\n\t\t\tsubject: `${repoSegment()}:${environment}`,\n\t\t\tkind: immutable ? 'immutable' : 'default',\n\t\t};\n\t}\n\n\tconst keys = customization.include_claim_keys ?? [];\n\tconst unsupported = keys.filter(\n\t\t(key) => !(SUPPORTED_CLAIM_KEYS as readonly string[]).includes(key),\n\t);\n\tif (keys.length === 0 || unsupported.length > 0) {\n\t\tthrow new OidcSubjectNotSupported(repo, keys, unsupported);\n\t}\n\tif (keys.some((key) => NEEDS_FACTS.has(key)) && !facts) {\n\t\tthrow new RepoFactsRequired(repo);\n\t}\n\n\tconst parts = keys.map((key) => {\n\t\tswitch (key) {\n\t\t\tcase 'repo':\n\t\t\t\treturn repoSegment();\n\t\t\tcase 'context':\n\t\t\tcase 'environment':\n\t\t\t\treturn environment;\n\t\t\tcase 'repository':\n\t\t\t\treturn `repository:${claim(repo)}`;\n\t\t\tcase 'repository_owner':\n\t\t\t\treturn `repository_owner:${claim(owner)}`;\n\t\t\tcase 'repository_owner_id':\n\t\t\t\treturn `repository_owner_id:${facts!.ownerId}`;\n\t\t\tcase 'repository_id':\n\t\t\t\treturn `repository_id:${facts!.repoId}`;\n\t\t\tdefault:\n\t\t\t\treturn `repository_visibility:${claim(facts!.visibility)}`;\n\t\t}\n\t});\n\treturn { subject: parts.join(':'), kind: 'custom' };\n}\n\n/** What {@link resolveOidcSubject} found. */\nexport interface ResolvedOidcSubject {\n\tsubject: string;\n\tkind: OidcSubjectKind;\n\t/** Set when the format could not be read and the default was assumed. */\n\twarning?: string;\n}\n\n/** The endpoint a repository's subject format is read from. */\nexport function customizationEndpoint(repo: string): string {\n\treturn `repos/${repo}/actions/oidc/customization/sub`;\n}\n\n/**\n * The `sub` GitHub will send for `repo`'s `stage` environment, read from the\n * repository's OIDC settings through `gh`.\n *\n * A repository on a custom template that names no keys of its own uses its\n * organisation's, read from `orgs/{owner}/actions/oidc/customization/sub`.\n * When the settings cannot be read at all — no permission, or a GitHub\n * Enterprise Server without the endpoint — the default format is assumed, with\n * a warning saying where to check it.\n */\nexport function resolveOidcSubject(\n\tgh: Gh,\n\trepo: string,\n\tstage: string,\n): ResolvedOidcSubject {\n\tconst endpoint = customizationEndpoint(repo);\n\tlet customization: OidcSubjectCustomization;\n\ttry {\n\t\tcustomization = JSON.parse(gh(['api', endpoint]));\n\t} catch {\n\t\treturn {\n\t\t\tsubject: `repo:${repo}:environment:${claim(stage)}`,\n\t\t\tkind: 'assumed',\n\t\t\twarning: `Could not read ${endpoint}, so the default subject format is assumed. Check it with: gh api ${endpoint} — a repository on the immutable subject or a custom template sends a different sub, and the role would not be assumable.`,\n\t\t};\n\t}\n\n\tif (\n\t\t!customization.use_default &&\n\t\t(customization.include_claim_keys ?? []).length === 0\n\t) {\n\t\t// The repository follows its organisation's template.\n\t\tconst [owner = ''] = repo.split('/');\n\t\tconst orgEndpoint = `orgs/${owner}/actions/oidc/customization/sub`;\n\t\tlet org: { include_claim_keys?: string[]; use_immutable_subject?: boolean };\n\t\ttry {\n\t\t\torg = JSON.parse(gh(['api', orgEndpoint]));\n\t\t} catch {\n\t\t\tthrow new OrgOidcTemplateUnreadable(repo, orgEndpoint);\n\t\t}\n\t\tcustomization = {\n\t\t\t...customization,\n\t\t\tinclude_claim_keys: org.include_claim_keys ?? [],\n\t\t\tuse_immutable_subject:\n\t\t\t\tcustomization.use_immutable_subject ?? org.use_immutable_subject,\n\t\t};\n\t}\n\n\tconst facts = needsRepoFacts(customization)\n\t\t? readRepoFacts(gh, repo)\n\t\t: undefined;\n\treturn oidcSubject(repo, stage, customization, facts);\n}\n\nfunction readRepoFacts(gh: Gh, repo: string): RepoFacts {\n\tconst raw = JSON.parse(gh(['api', `repos/${repo}`])) as {\n\t\tid: number;\n\t\towner: { id: number };\n\t\tvisibility: string;\n\t};\n\treturn {\n\t\townerId: raw.owner.id,\n\t\trepoId: raw.id,\n\t\tvisibility: raw.visibility,\n\t};\n}\n\n/**\n * The repository's custom subject template includes a claim whose value\n * depends on the run — or names none — so no one subject can be trusted.\n */\nexport class OidcSubjectNotSupported extends GkmError {\n\tconstructor(\n\t\treadonly repo: string,\n\t\treadonly includeClaimKeys: string[],\n\t\treadonly unsupportedKeys: string[],\n\t) {\n\t\tsuper(\n\t\t\t`${repo} builds its OIDC subject from a custom template, ${JSON.stringify(includeClaimKeys)}, and ${\n\t\t\t\tunsupportedKeys.length > 0\n\t\t\t\t\t? `${unsupportedKeys.join(', ')} depend${unsupportedKeys.length === 1 ? 's' : ''} on the run`\n\t\t\t\t\t: 'it names no claims'\n\t\t\t}, so the deploy role cannot trust one exact subject. Set the repository back to the default subject — gh api --method PUT ${customizationEndpoint(repo)} -F use_default=true — (or keep the immutable one by also passing -F use_immutable_subject=true), or use a template built only from ${SUPPORTED_CLAIM_KEYS.join(', ')}; then run this again.`,\n\t\t);\n\t\tthis.name = 'OidcSubjectNotSupported';\n\t}\n}\n\n/** The subject needs the repository's ids, and none were read. */\nexport class RepoFactsRequired extends GkmError {\n\tconstructor(readonly repo: string) {\n\t\tsuper(\n\t\t\t`The OIDC subject of ${repo} includes its owner and repository ids; read them with gh api repos/${repo} and pass them in.`,\n\t\t);\n\t\tthis.name = 'RepoFactsRequired';\n\t}\n}\n\n/**\n * The repository uses its organisation's subject template, and that template\n * could not be read — so what GitHub sends is unknown, and is not guessed.\n */\nexport class OrgOidcTemplateUnreadable extends GkmError {\n\tconstructor(\n\t\treadonly repo: string,\n\t\treadonly endpoint: string,\n\t) {\n\t\tsuper(\n\t\t\t`${repo} uses its organisation's OIDC subject template, and ${endpoint} could not be read. Run this as an organisation owner (gh auth refresh -s admin:org), or set the repository back to the default subject with gh api --method PUT ${customizationEndpoint(repo)} -F use_default=true; then run this again.`,\n\t\t);\n\t\tthis.name = 'OrgOidcTemplateUnreadable';\n\t}\n}\n","/**\n * What the deploy role may do in the stage's account.\n *\n * An SST stage creates its own stack, which is most of AWS, so its role gets\n * `AdministratorAccess`. A stage deployed with the `compose` target builds and\n * runs containers on a server; from AWS its deploy job needs only the stage's\n * secrets — read, and written back when a deploy generates a new one: the one\n * object in the project bucket, or the SSM parameter or Secrets Manager secret\n * — and,\n * when the deploy state is kept in AWS, the stage's state, and, when the\n * stage's domain is in Route53, the records of its hosted zone, and, when an\n * `s3` provider backs its buckets, those buckets and the IAM user each is\n * reached with — by the names the provider gives them — and, when it runs\n * Postgres, the project bucket its backups go to and the backups user. So a\n * compose stage gets an inline policy naming exactly those resources and\n * nothing else.\n *\n * `--policy-arn` replaces either.\n */\n\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { stageBackups } from '../backups/config.js';\nimport { backupsUserName } from '../backups/provision.js';\nimport { stageDnsDomains } from '../compose/dns.js';\nimport { stageProvider } from '../providers/config.js';\nimport {\n\tPROJECT_BUCKET_CREATE_ACTIONS,\n\tPROJECT_BUCKET_LIFECYCLE_ACTIONS,\n\tprojectBucketName,\n} from '../providers/projectBucket.js';\nimport {\n\tbucketName,\n\tIAM_USER_PATH,\n\tiamUserName,\n\tSUFFIX_LENGTH,\n} from '../providers/s3/naming.js';\nimport { secretsParameterName } from '../secrets/aws.js';\nimport { s3SecretsKey, s3SecretsLocation } from '../secrets/providers.js';\nimport { secretsManagerSecretName } from '../secrets/secretsManager.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { deployIdentity } from './identity.js';\n\n/**\n * What SST needs to create a stack is most of AWS, so this is the default\n * outside compose — said out loud in the output, and replaceable with\n * `--policy-arn`.\n */\nexport const DEFAULT_POLICY_ARN = 'arn:aws:iam::aws:policy/AdministratorAccess';\n\n/** The name of the inline policy a compose stage's role is given. */\nexport const SCOPED_POLICY_NAME = 'gkm-deploy';\n\n/** One statement of an IAM policy document. */\nexport interface PolicyStatement {\n\tSid: string;\n\tEffect: 'Allow';\n\tAction: string[];\n\tResource: string | string[];\n\tCondition?: Record<string, Record<string, string>>;\n}\n\n/** What the role is given. */\nexport type DeployAccess =\n\t| {\n\t\t\tkind: 'managed';\n\t\t\tpolicyArn: string;\n\t\t\t/** Why, for the output. */\n\t\t\treason: string;\n\t }\n\t| {\n\t\t\tkind: 'scoped';\n\t\t\t/** The statements, in the account the role is in. */\n\t\t\tstatements(account: string): PolicyStatement[];\n\t\t\t/** What each statement is for, for the output. */\n\t\t\tdescribe: string[];\n\t };\n\n/** Every target the stage's apps deploy through. */\nexport function deployTargets(workspace: NormalizedWorkspace): string[] {\n\tconst targets = new Set<string>([workspace.deploy?.default ?? 'dokploy']);\n\tfor (const app of Object.values(workspace.apps)) {\n\t\ttargets.add(app.resolvedDeployTarget);\n\t}\n\treturn [...targets].sort();\n}\n\n/**\n * The access the stage's deploy role is given: `--policy-arn` when passed,\n * the scoped policy for a stage only the compose target deploys, and\n * `AdministratorAccess` otherwise.\n */\nexport function deployAccess(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\tpolicyArn?: string,\n\t/** The stage's constructs: its buckets, and whether it runs Postgres. */\n\tmanifest: ConstructManifest = {},\n): DeployAccess {\n\tconst buckets = Object.entries(manifest)\n\t\t.filter(([, d]) => d.kind === 'objects')\n\t\t.map(([id]) => id);\n\tif (policyArn) {\n\t\treturn { kind: 'managed', policyArn, reason: '--policy-arn' };\n\t}\n\n\tconst targets = deployTargets(workspace);\n\tif (targets.length !== 1 || targets[0] !== 'compose') {\n\t\treturn {\n\t\t\tkind: 'managed',\n\t\t\tpolicyArn: DEFAULT_POLICY_ARN,\n\t\t\treason: `the ${targets.join(', ')} target${targets.length === 1 ? '' : 's'} deploy${targets.length === 1 ? 's' : ''} infrastructure; --policy-arn to narrow`,\n\t\t};\n\t}\n\n\tconst project = workspace.name;\n\tconst store = workspace.secrets.store ?? 'file';\n\tconst state = workspace.state;\n\tconst custom =\n\t\t(typeof store === 'object' && typeof store.provider === 'object') ||\n\t\t(state !== undefined && typeof state.provider === 'object');\n\tif (custom) {\n\t\treturn {\n\t\t\tkind: 'managed',\n\t\t\tpolicyArn: DEFAULT_POLICY_ARN,\n\t\t\treason: `a custom ${typeof store === 'object' && typeof store.provider === 'object' ? 'secrets store' : 'state provider'} cannot be scoped; --policy-arn to narrow`,\n\t\t};\n\t}\n\n\tconst describe: string[] = [];\n\tconst build: ((account: string) => PolicyStatement[])[] = [];\n\n\t// The project bucket's name is fixed by the account, so the role is given\n\t// exactly it, and the actions that create it for whichever run is first.\n\tconst projectBucketIn = (account: string) =>\n\t\tprojectBucketName(deployIdentity(workspace, stage).scope, account);\n\tconst projectBucketStatement = (account: string): PolicyStatement => ({\n\t\tSid: 'ProjectBucket',\n\t\tEffect: 'Allow',\n\t\tAction: [...PROJECT_BUCKET_CREATE_ACTIONS],\n\t\tResource: `arn:aws:s3:::${projectBucketIn(account)}`,\n\t});\n\t// Whether the state's statements already cover the secrets' bucket.\n\tconst stateInSecretsBucket =\n\t\ttypeof store === 'object' &&\n\t\tstore.provider === 's3' &&\n\t\tstate?.provider === 's3' &&\n\t\tstate.bucket === (store as { bucket?: string }).bucket;\n\n\tif (typeof store === 'object' && store.provider === 's3') {\n\t\tconst location = s3SecretsLocation(store, state);\n\t\tconst key = s3SecretsKey(location.prefix, project, stage);\n\t\tconst named = location.bucket;\n\t\tconst bucketIn = (account: string) => named ?? projectBucketIn(account);\n\t\tdescribe.push(\n\t\t\tnamed\n\t\t\t\t? `read and update s3://${named}/${key}`\n\t\t\t\t: `read and update ${key} in the project bucket ${projectBucketIn('<account>')}${stateInSecretsBucket ? '' : ', creating it'}`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageSecrets',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['s3:GetObject', 's3:PutObject'],\n\t\t\t\tResource: `arn:aws:s3:::${bucketIn(account)}/${key}`,\n\t\t\t},\n\t\t\t// The state's statements give these when it is in the same bucket.\n\t\t\t...(stateInSecretsBucket\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// HeadBucket, and secrets not written yet a 404, not a 403.\n\t\t\t\t\t\t\tSid: 'StageSecretsBucket',\n\t\t\t\t\t\t\tEffect: 'Allow' as const,\n\t\t\t\t\t\t\tAction: ['s3:ListBucket'],\n\t\t\t\t\t\t\tResource: `arn:aws:s3:::${bucketIn(account)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(named ? [] : [projectBucketStatement(account)]),\n\t\t\t\t\t]),\n\t\t]);\n\t} else if (typeof store === 'object' && store.provider === 'ssm') {\n\t\tconst { region } = store;\n\t\tconst name = secretsParameterName(project, stage);\n\t\tdescribe.push(`read and update ${name} (SSM, ${region})`);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageSecrets',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['ssm:GetParameter', 'ssm:PutParameter'],\n\t\t\t\tResource: `arn:aws:ssm:${region}:${account}:parameter${name}`,\n\t\t\t},\n\t\t]);\n\t} else if (\n\t\ttypeof store === 'object' &&\n\t\tstore.provider === 'secrets-manager'\n\t) {\n\t\tconst { region, kmsKeyId } = store as { region: string; kmsKeyId?: string };\n\t\tconst name = secretsManagerSecretName(project, stage);\n\t\tdescribe.push(`read and update ${name} (Secrets Manager, ${region})`);\n\t\tbuild.push((account) => {\n\t\t\tconst statements: PolicyStatement[] = [\n\t\t\t\t{\n\t\t\t\t\tSid: 'StageSecrets',\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tAction: [\n\t\t\t\t\t\t'secretsmanager:GetSecretValue',\n\t\t\t\t\t\t'secretsmanager:PutSecretValue',\n\t\t\t\t\t\t'secretsmanager:CreateSecret',\n\t\t\t\t\t],\n\t\t\t\t\t// Secrets Manager appends six random characters to a secret's ARN.\n\t\t\t\t\tResource: `arn:aws:secretsmanager:${region}:${account}:secret:${name}-??????`,\n\t\t\t\t},\n\t\t\t];\n\t\t\tif (kmsKeyId) {\n\t\t\t\tstatements.push({\n\t\t\t\t\tSid: 'StageSecretsKey',\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tAction: ['kms:Decrypt', 'kms:GenerateDataKey'],\n\t\t\t\t\tResource: kmsKeyId.startsWith('arn:') ? kmsKeyId : '*',\n\t\t\t\t\tCondition: {\n\t\t\t\t\t\tStringEquals: {\n\t\t\t\t\t\t\t'kms:ViaService': `secretsmanager.${region}.amazonaws.com`,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn statements;\n\t\t});\n\t}\n\n\tif (state?.provider === 'ssm') {\n\t\tconst { region } = state;\n\t\tconst path = `/gkm/${project}/${stage}/`;\n\t\tdescribe.push(\n\t\t\t`read and write the deploy state under ${path} (SSM, ${region})`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageState',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['ssm:GetParameter', 'ssm:PutParameter', 'ssm:DeleteParameter'],\n\t\t\t\tResource: `arn:aws:ssm:${region}:${account}:parameter${path}*`,\n\t\t\t},\n\t\t]);\n\t} else if (state?.provider === 's3') {\n\t\tconst prefix = (state.prefix ?? 'gkm').replace(/\\/+$/, '');\n\t\tconst path = `${prefix ? `${prefix}/` : ''}${project}/${stage}/`;\n\t\tconst named = state.bucket;\n\t\t// No bucket named: the project bucket, which the first deploy creates.\n\t\tconst bucketIn = (account: string) => named ?? projectBucketIn(account);\n\t\tdescribe.push(\n\t\t\tnamed\n\t\t\t\t? `read and write the deploy state under s3://${named}/${path}`\n\t\t\t\t: `create the project bucket ${projectBucketIn('<account>')}, and read and write the deploy state under ${path} in it`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t...stateBucketStatements(bucketIn(account), path),\n\t\t\t...(named ? [] : [projectBucketStatement(account)]),\n\t\t]);\n\t}\n\n\t// The deploy creates each bucket an s3 provider backs, and the IAM user\n\t// and key it is reached with: by their names — the good one, or the good\n\t// one with a clash's six-character suffix — and nothing else.\n\tconst objects = stageProvider(workspace, 'objects', stage);\n\tif (objects.mode === 'provider' && objects.name === 's3' && buckets.length) {\n\t\tconst { scope } = deployIdentity(workspace, stage);\n\t\tconst names = [...buckets].sort().map((id) => ({\n\t\t\tbucket: bucketName({ scope, stage, id }),\n\t\t\tuser: iamUserName({ scope, stage, id }),\n\t\t}));\n\t\tconst suffix = '?'.repeat(SUFFIX_LENGTH - 1);\n\t\tdescribe.push(\n\t\t\t`create and configure the buckets ${names.map((n) => n.bucket).join(', ')} and their IAM users (S3, IAM)`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageBuckets',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t's3:CreateBucket',\n\t\t\t\t\t's3:ListBucket',\n\t\t\t\t\t's3:GetBucketTagging',\n\t\t\t\t\t's3:PutBucketTagging',\n\t\t\t\t\t's3:GetBucketPublicAccessBlock',\n\t\t\t\t\t's3:PutBucketPublicAccessBlock',\n\t\t\t\t\t's3:GetBucketPolicy',\n\t\t\t\t\t's3:PutBucketPolicy',\n\t\t\t\t\t's3:GetEncryptionConfiguration',\n\t\t\t\t\t's3:PutEncryptionConfiguration',\n\t\t\t\t\t's3:GetBucketVersioning',\n\t\t\t\t\t's3:PutBucketVersioning',\n\t\t\t\t\t's3:GetBucketCORS',\n\t\t\t\t\t's3:PutBucketCORS',\n\t\t\t\t],\n\t\t\t\tResource: names.flatMap((n) => [\n\t\t\t\t\t`arn:aws:s3:::${n.bucket}`,\n\t\t\t\t\t`arn:aws:s3:::${n.bucket}-${suffix}`,\n\t\t\t\t]),\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageBucketUsers',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'iam:GetUser',\n\t\t\t\t\t'iam:CreateUser',\n\t\t\t\t\t'iam:TagUser',\n\t\t\t\t\t'iam:ListUserTags',\n\t\t\t\t\t'iam:GetUserPolicy',\n\t\t\t\t\t'iam:PutUserPolicy',\n\t\t\t\t\t'iam:ListAccessKeys',\n\t\t\t\t\t'iam:CreateAccessKey',\n\t\t\t\t\t'iam:DeleteAccessKey',\n\t\t\t\t],\n\t\t\t\tResource: names.map(\n\t\t\t\t\t(n) => `arn:aws:iam::${account}:user${IAM_USER_PATH}${n.user}`,\n\t\t\t\t),\n\t\t\t},\n\t\t]);\n\t}\n\n\t// The stage's backups: the deploy creates the project bucket if it is not\n\t// there, keeps its lifecycle, and creates the backups user and its key.\n\t// The role never reads the backups — `gkm backup:list` and `:restore`\n\t// run with a person's own credentials.\n\tif (stageBackups(workspace, manifest, stage).mode === 'on') {\n\t\tconst { scope } = deployIdentity(workspace, stage);\n\t\tconst user = backupsUserName(scope, stage);\n\t\tconst bucketIn = (account: string) => projectBucketName(scope, account);\n\t\tdescribe.push(\n\t\t\t`create the project bucket ${bucketIn('<account>')} and keep its lifecycle, and create the backups user ${user} and its key (S3, IAM)`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageBackupsBucket',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t's3:ListBucket',\n\t\t\t\t\t...new Set([\n\t\t\t\t\t\t...PROJECT_BUCKET_CREATE_ACTIONS,\n\t\t\t\t\t\t...PROJECT_BUCKET_LIFECYCLE_ACTIONS,\n\t\t\t\t\t]),\n\t\t\t\t],\n\t\t\t\tResource: `arn:aws:s3:::${bucketIn(account)}`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageBackupsUser',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'iam:GetUser',\n\t\t\t\t\t'iam:CreateUser',\n\t\t\t\t\t'iam:TagUser',\n\t\t\t\t\t'iam:ListUserTags',\n\t\t\t\t\t'iam:GetUserPolicy',\n\t\t\t\t\t'iam:PutUserPolicy',\n\t\t\t\t\t'iam:ListAccessKeys',\n\t\t\t\t\t'iam:CreateAccessKey',\n\t\t\t\t\t'iam:DeleteAccessKey',\n\t\t\t\t],\n\t\t\t\tResource: `arn:aws:iam::${account}:user${IAM_USER_PATH}${user}`,\n\t\t\t},\n\t\t]);\n\t}\n\n\t// The deploy writes the stage's hosts' records: in Route53, only that\n\t// zone's — and, with no hostedZoneId to name it, the zone is looked up\n\t// by name, which IAM cannot scope.\n\tfor (const { domain, config } of stageDnsDomains(\n\t\tstage,\n\t\tworkspace.domains,\n\t\tworkspace.dns,\n\t)) {\n\t\tif (config.provider !== 'route53') continue;\n\t\tconst zoneId = (config as { hostedZoneId?: string }).hostedZoneId?.replace(\n\t\t\t/^\\/?hostedzone\\//,\n\t\t\t'',\n\t\t);\n\t\tdescribe.push(\n\t\t\t`write the A, AAAA and CNAME records of ${domain} (Route53${zoneId ? `, ${zoneId}` : ''})`,\n\t\t);\n\t\tbuild.push(() => [\n\t\t\t{\n\t\t\t\tSid: 'StageDnsRecords',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'route53:ChangeResourceRecordSets',\n\t\t\t\t\t'route53:ListResourceRecordSets',\n\t\t\t\t],\n\t\t\t\tResource: `arn:aws:route53:::hostedzone/${zoneId ?? '*'}`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageDnsChanges',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['route53:GetChange'],\n\t\t\t\tResource: 'arn:aws:route53:::change/*',\n\t\t\t},\n\t\t\t...(zoneId\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSid: 'StageDnsZones',\n\t\t\t\t\t\t\tEffect: 'Allow' as const,\n\t\t\t\t\t\t\tAction: ['route53:ListHostedZonesByName'],\n\t\t\t\t\t\t\tResource: '*',\n\t\t\t\t\t\t},\n\t\t\t\t\t]),\n\t\t]);\n\t}\n\n\treturn {\n\t\tkind: 'scoped',\n\t\tstatements: (account) => build.flatMap((statements) => statements(account)),\n\t\tdescribe,\n\t};\n}\n\n/**\n * Reading and writing one stage's deploy state in `bucket`, as the deploy\n * role is given it.\n */\nexport function stateBucketStatements(\n\tbucket: string,\n\tpath: string,\n): PolicyStatement[] {\n\treturn [\n\t\t{\n\t\t\tSid: 'StageState',\n\t\t\tEffect: 'Allow',\n\t\t\tAction: ['s3:GetObject', 's3:PutObject', 's3:DeleteObject'],\n\t\t\tResource: `arn:aws:s3:::${bucket}/${path}*`,\n\t\t},\n\t\t// HeadBucket, and a state not written yet a 404 rather than a 403.\n\t\t{\n\t\t\tSid: 'StageStateBucket',\n\t\t\tEffect: 'Allow',\n\t\t\tAction: ['s3:ListBucket'],\n\t\t\tResource: `arn:aws:s3:::${bucket}`,\n\t\t},\n\t];\n}\n\n/** The scoped access as a policy document, or null when it allows nothing. */\nexport function scopedPolicyDocument(\n\tstatements: PolicyStatement[],\n): string | null {\n\tif (statements.length === 0) return null;\n\treturn JSON.stringify({ Version: '2012-10-17', Statement: statements });\n}\n\n/** The account an IAM ARN is in: `arn:aws:iam::<account>:…`. */\nexport function accountOf(arn: string): string {\n\treturn arn.split(':')[4] ?? '';\n}\n","/**\n * `gkm deploy:github` — let GitHub Actions deploy one stage, with no keys.\n *\n * A stage usually lives in its own AWS account — staging in one, production in\n * another — so this runs once per stage, with that account's profile:\n *\n * gkm deploy:github --stage staging --profile acme-dev\n * gkm deploy:github --stage prod --profile acme-prod\n *\n * In the stage's account it makes sure GitHub's OIDC provider exists, and a\n * role that only this repository's `<stage>` environment can assume. On\n * GitHub it creates that environment and gives it what the generated deploy\n * workflow reads: `AWS_ROLE_ARN`, and — when the stage's secrets are kept in\n * the local file — its key as `GKM_SECRETS_KEY`. With `secrets.store` set to\n * S3, SSM or Secrets Manager the deploy job reads them with the role instead, so\n * no key is handed to GitHub, and this checks the stage's store in the same\n * account, with the same profile. Re-running it converges rather than duplicating.\n *\n * The role trusts the exact `sub` GitHub sends for the environment, read from\n * the repository's OIDC subject settings (`githubOidc.ts`) — the default, the\n * immutable subject with the owner's and repository's ids, or a custom\n * template. A re-run rewrites an existing role's trust to it, so running this\n * again repairs a role that trusted the wrong format. What the role may do is\n * `githubPolicy.ts`: `AdministratorAccess` for SST, and for a compose stage\n * only its own secrets (and deploy state, when that is in AWS).\n */\n\nimport { execFileSync } from 'node:child_process';\nimport {\n\tAttachRolePolicyCommand,\n\tCreateOpenIDConnectProviderCommand,\n\tCreateRoleCommand,\n\tDeleteRolePolicyCommand,\n\tDetachRolePolicyCommand,\n\tGetRoleCommand,\n\tIAMClient,\n\ttype IAMClientConfig,\n\tListAttachedRolePoliciesCommand,\n\tListOpenIDConnectProvidersCommand,\n\tListRoleTagsCommand,\n\tPutRolePolicyCommand,\n\tTagRoleCommand,\n\tUntagRoleCommand,\n\tUpdateAssumeRolePolicyCommand,\n} from '@aws-sdk/client-iam';\nimport { loadWorkspaceConfig } from '../config.js';\nimport { GkmError } from '../errors';\nimport { discover } from '../reconcile/discover.js';\nimport { constructGlobs } from '../reconcile/workspace.js';\nimport { getKeyPath, keystoreProject, readKey } from '../secrets/keystore.js';\nimport { isRemoteStore, secretsStoreFor } from '../secrets/store.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport { resolveOidcSubject } from './githubOidc.js';\nimport {\n\taccountOf,\n\tdeployAccess,\n\tSCOPED_POLICY_NAME,\n\tscopedPolicyDocument,\n} from './githubPolicy.js';\n\nexport { DEFAULT_POLICY_ARN, SCOPED_POLICY_NAME } from './githubPolicy.js';\n\nconst logger = console;\n\nconst GITHUB_OIDC_HOST = 'token.actions.githubusercontent.com';\nconst AUDIENCE = 'sts.amazonaws.com';\n\n/**\n * The tag recording which managed policy gkm attached to the role — so a\n * re-run detaches only what gkm put there, never a policy someone else did.\n */\nexport const POLICY_TAG = 'gkm:policy-arn';\n\nexport interface DeployGithubOptions {\n\tstage: string;\n\t/** The AWS profile for the stage's account. */\n\tprofile?: string;\n\t/** `owner/name`; defaults to the repository `gh` sees here. */\n\trepo?: string;\n\t/** The policy the deploy role gets, in place of the default. */\n\tpolicyArn?: string;\n\tdryRun?: boolean;\n}\n\n/** Runs `gh` with the given arguments and optional stdin, returning stdout. */\nexport type Gh = (args: string[], input?: string) => string;\n\nconst defaultGh: Gh = (args, input) =>\n\texecFileSync('gh', args, {\n\t\tencoding: 'utf-8',\n\t\t// stderr captured, so a read that fails (a 404) is not printed as noise.\n\t\tstdio: ['pipe', 'pipe', 'pipe'],\n\t\t...(input === undefined ? {} : { input }),\n\t}).trim();\n\n/** The role a stage deploys as: `<project>-github-<stage>`, within IAM's 64. */\nexport function roleName(project: string, stage: string): string {\n\treturn `${project}-github-${stage}`\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9+=,.@_-]/g, '-')\n\t\t.slice(0, 64);\n}\n\n/**\n * Who may assume the role: a workflow job whose OIDC token carries exactly\n * `subject` — the repository's `<stage>` environment, in the format the\n * repository sends (see `githubOidc.ts`), and nothing else. Not another\n * branch's job, not another environment's: that is what keeps a staging\n * deploy from using the production role.\n */\nexport function trustPolicy(providerArn: string, subject: string): string {\n\treturn JSON.stringify({\n\t\tVersion: '2012-10-17',\n\t\tStatement: [\n\t\t\t{\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tPrincipal: { Federated: providerArn },\n\t\t\t\tAction: 'sts:AssumeRoleWithWebIdentity',\n\t\t\t\tCondition: {\n\t\t\t\t\tStringEquals: {\n\t\t\t\t\t\t[`${GITHUB_OIDC_HOST}:aud`]: AUDIENCE,\n\t\t\t\t\t\t[`${GITHUB_OIDC_HOST}:sub`]: subject,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t});\n}\n\n/**\n * The subject a trust policy trusts, or undefined when it names none. IAM\n * hands documents back URL-encoded.\n */\nexport function trustedSubject(\n\tdocument: string | undefined,\n): string | undefined {\n\tif (!document) return undefined;\n\tlet parsed: {\n\t\tStatement?: { Condition?: Record<string, Record<string, unknown>> }[];\n\t};\n\ttry {\n\t\tparsed = JSON.parse(safeDecode(document));\n\t} catch {\n\t\treturn undefined;\n\t}\n\tfor (const statement of parsed.Statement ?? []) {\n\t\tfor (const operator of Object.values(statement.Condition ?? {})) {\n\t\t\tconst value = operator[`${GITHUB_OIDC_HOST}:sub`];\n\t\t\tif (typeof value === 'string') return value;\n\t\t\tif (Array.isArray(value)) return value.join(', ');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction safeDecode(value: string): string {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n\n/** GitHub's OIDC provider in this account, created if it is not there. */\nexport async function ensureOidcProvider(iam: IAMClient): Promise<string> {\n\tconst { OpenIDConnectProviderList = [] } = await iam.send(\n\t\tnew ListOpenIDConnectProvidersCommand({}),\n\t);\n\tconst existing = OpenIDConnectProviderList.find((p) =>\n\t\tp.Arn?.endsWith(`oidc-provider/${GITHUB_OIDC_HOST}`),\n\t)?.Arn;\n\tif (existing) return existing;\n\n\tconst created = await iam.send(\n\t\tnew CreateOpenIDConnectProviderCommand({\n\t\t\tUrl: `https://${GITHUB_OIDC_HOST}`,\n\t\t\tClientIDList: [AUDIENCE],\n\t\t}),\n\t);\n\treturn created.OpenIDConnectProviderArn!;\n}\n\n/**\n * What the role is given: a managed policy, attached; or an inline policy\n * document — null for none at all.\n */\nexport type RoleAccess = { managed: string } | { inline: string | null };\n\n/** What {@link ensureRole} did. */\nexport interface RoleOutcome {\n\tarn: string;\n\tcreated: boolean;\n\t/** The subject the role trusted before, when it existed. */\n\tpreviousSubject?: string;\n\t/** Managed policies gkm had attached and detached now. */\n\tdetached: string[];\n\t/**\n\t * Managed policies still attached that the role no longer needs, which gkm\n\t * did not record attaching — left alone, for a person to detach.\n\t */\n\tleftAttached: string[];\n}\n\nfunction isNoSuchEntity(error: unknown): boolean {\n\treturn (error as { name?: string }).name === 'NoSuchEntityException';\n}\n\n/**\n * The deploy role, created or brought back to this trust and access.\n *\n * Converges: re-running rewrites the trust, and moves the role from one access\n * to another — detaching a managed policy only when the role's\n * {@link POLICY_TAG} says gkm attached it.\n */\nexport async function ensureRole(\n\tiam: IAMClient,\n\tname: string,\n\ttrust: string,\n\taccess: RoleAccess,\n): Promise<RoleOutcome> {\n\tlet arn: string;\n\tlet created = false;\n\tlet previousSubject: string | undefined;\n\tlet recorded: string | undefined;\n\ttry {\n\t\tconst { Role } = await iam.send(new GetRoleCommand({ RoleName: name }));\n\t\tpreviousSubject = trustedSubject(Role!.AssumeRolePolicyDocument);\n\t\tawait iam.send(\n\t\t\tnew UpdateAssumeRolePolicyCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tPolicyDocument: trust,\n\t\t\t}),\n\t\t);\n\t\tarn = Role!.Arn!;\n\t\tconst { Tags = [] } = await iam.send(\n\t\t\tnew ListRoleTagsCommand({ RoleName: name }),\n\t\t);\n\t\trecorded = Tags.find((tag) => tag.Key === POLICY_TAG)?.Value;\n\t} catch (error) {\n\t\tif (!isNoSuchEntity(error)) throw error;\n\t\tconst { Role } = await iam.send(\n\t\t\tnew CreateRoleCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tAssumeRolePolicyDocument: trust,\n\t\t\t\tDescription: 'Deploys from GitHub Actions (gkm deploy:github)',\n\t\t\t\t// SST deploys can run long; the default hour is tight.\n\t\t\t\tMaxSessionDuration: 3600 * 2,\n\t\t\t}),\n\t\t);\n\t\tarn = Role!.Arn!;\n\t\tcreated = true;\n\t}\n\n\tconst detached: string[] = [];\n\tconst leftAttached: string[] = [];\n\tconst detach = async (policyArn: string) => {\n\t\ttry {\n\t\t\tawait iam.send(\n\t\t\t\tnew DetachRolePolicyCommand({ RoleName: name, PolicyArn: policyArn }),\n\t\t\t);\n\t\t\tdetached.push(policyArn);\n\t\t} catch (error) {\n\t\t\t// Already gone — by hand, or a run that stopped halfway.\n\t\t\tif (!isNoSuchEntity(error)) throw error;\n\t\t}\n\t};\n\tconst deleteInline = async () => {\n\t\ttry {\n\t\t\tawait iam.send(\n\t\t\t\tnew DeleteRolePolicyCommand({\n\t\t\t\t\tRoleName: name,\n\t\t\t\t\tPolicyName: SCOPED_POLICY_NAME,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (!isNoSuchEntity(error)) throw error;\n\t\t}\n\t};\n\n\tif ('managed' in access) {\n\t\t// Attaching an attached policy is a no-op, so this converges too.\n\t\tawait iam.send(\n\t\t\tnew AttachRolePolicyCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tPolicyArn: access.managed,\n\t\t\t}),\n\t\t);\n\t\tif (recorded && recorded !== access.managed) await detach(recorded);\n\t\tif (recorded !== access.managed) {\n\t\t\tawait iam.send(\n\t\t\t\tnew TagRoleCommand({\n\t\t\t\t\tRoleName: name,\n\t\t\t\t\tTags: [{ Key: POLICY_TAG, Value: access.managed }],\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tif (!created) await deleteInline();\n\t\treturn { arn, created, previousSubject, detached, leftAttached };\n\t}\n\n\tif (access.inline) {\n\t\tawait iam.send(\n\t\t\tnew PutRolePolicyCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tPolicyName: SCOPED_POLICY_NAME,\n\t\t\t\tPolicyDocument: access.inline,\n\t\t\t}),\n\t\t);\n\t} else if (!created) {\n\t\tawait deleteInline();\n\t}\n\tif (created) return { arn, created, previousSubject, detached, leftAttached };\n\n\tif (recorded) {\n\t\tawait detach(recorded);\n\t\tawait iam.send(\n\t\t\tnew UntagRoleCommand({ RoleName: name, TagKeys: [POLICY_TAG] }),\n\t\t);\n\t}\n\t// A role from before gkm recorded what it attached: what is attached may\n\t// be gkm's or someone's own, so it is named, not detached.\n\tconst { AttachedPolicies = [] } = await iam.send(\n\t\tnew ListAttachedRolePoliciesCommand({ RoleName: name }),\n\t);\n\tfor (const policy of AttachedPolicies) {\n\t\tif (policy.PolicyArn && !detached.includes(policy.PolicyArn)) {\n\t\t\tleftAttached.push(policy.PolicyArn);\n\t\t}\n\t}\n\treturn { arn, created, previousSubject, detached, leftAttached };\n}\n\n/**\n * An IAM client for the stage's account.\n *\n * `fromIni` for a named profile, deliberately: it resolves exactly that\n * profile — keys, assume-role, `credential_process` or SSO, whichever\n * ~/.aws/config says — and never falls back to AWS_* in the environment. The\n * provider chain checks the environment first, so exported staging keys would\n * quietly win over `--profile prod` and the production role would land in the\n * staging account.\n */\nexport async function iamFor(\n\tprofile?: string,\n\tendpoint?: string,\n): Promise<IAMClient> {\n\tconst config: IAMClientConfig = { region: 'us-east-1' };\n\tif (profile) {\n\t\tconst { fromIni } = await import('@aws-sdk/credential-providers');\n\t\tconfig.credentials = fromIni({ profile });\n\t}\n\tif (endpoint) {\n\t\tconfig.endpoint = endpoint;\n\t\tconfig.credentials = { accessKeyId: 'test', secretAccessKey: 'test' };\n\t}\n\treturn new IAMClient(config);\n}\n\nexport async function deployGithubCommand(\n\toptions: DeployGithubOptions,\n\tdeps: { iam?: IAMClient; gh?: Gh; cwd?: string } = {},\n): Promise<{ roleArn?: string; repo: string; subject: string }> {\n\tconst gh = deps.gh ?? defaultGh;\n\tconst { workspace } = await loadWorkspaceConfig(deps.cwd);\n\tassertDeployedStage(workspace.stages, options.stage);\n\n\tconst repo =\n\t\toptions.repo ??\n\t\tgh(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']);\n\tconst role = roleName(workspace.name, options.stage);\n\t// The exact subject GitHub will send — read from the repository's OIDC\n\t// settings, before anything is changed, so a format no role can trust\n\t// fails here.\n\tconst oidc = resolveOidcSubject(gh, repo, options.stage);\n\t// The buckets an s3 provider creates are named after their constructs,\n\t// and a stage with a database is backed up: the role is scoped to\n\t// exactly those.\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t});\n\tconst access = deployAccess(\n\t\tworkspace,\n\t\toptions.stage,\n\t\toptions.policyArn,\n\t\tmanifest,\n\t);\n\t// Read through the keystore so a key still at the place keys used to be kept\n\t// is found, and copied to where it is kept now.\n\tconst key = await readKey(options.stage, keystoreProject(workspace));\n\tconst keyPath = getKeyPath(options.stage, keystoreProject(workspace));\n\tconst hasKey = key !== null;\n\t// A stage whose secrets are in a store is read from there by the deploy job,\n\t// with the role; it needs no key on GitHub.\n\tconst remote = isRemoteStore(workspace, options.stage);\n\t// Read from the stage's own store, with the same credentials the role is\n\t// created with: what the deploy job will find there.\n\tconst store = await secretsStoreFor(workspace, options.stage, {\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst hasSecrets = remote && (await store.read(options.stage)) !== null;\n\tconst via = options.profile\n\t\t? `profile \"${options.profile}\"`\n\t\t: 'the default credentials';\n\n\tlogger.log(`\\n🔐 GitHub → AWS for stage \"${options.stage}\"\\n`);\n\tlogger.log(` Repository: ${repo}`);\n\tlogger.log(` AWS profile: ${options.profile ?? '(default credentials)'}`);\n\tlogger.log(` Role: ${role}`);\n\tif (access.kind === 'managed') {\n\t\tlogger.log(` Policy: ${access.policyArn} (${access.reason})`);\n\t} else if (access.describe.length > 0) {\n\t\tlogger.log(\n\t\t\t` Policy: inline \"${SCOPED_POLICY_NAME}\", scoped to the compose deploy — only:`,\n\t\t);\n\t\tfor (const line of access.describe) logger.log(` ${line}`);\n\t} else {\n\t\tlogger.log(\n\t\t\t' Policy: none — a compose deploy with file secrets and local state reads nothing from AWS',\n\t\t);\n\t}\n\tlogger.log(\n\t\t` Trusted by: ${oidc.subject} only (${SUBJECT_KINDS[oidc.kind]})`,\n\t);\n\tif (oidc.warning) logger.log(` ⚠ ${oidc.warning}`);\n\tif (remote) {\n\t\tlogger.log(\n\t\t\t` Secrets: ${hasSecrets ? `in the store (${store.name}), read with ${via}` : `none in the store yet — gkm secrets:set <KEY> '…' --stage ${options.stage}`}`,\n\t\t);\n\t} else {\n\t\tlogger.log(\n\t\t\t` Secrets key: ${hasKey ? keyPath : `none at ${keyPath} — run gkm secrets:init --stage ${options.stage} first`}`,\n\t\t);\n\t}\n\n\tif (options.dryRun) {\n\t\tif (access.kind === 'scoped') {\n\t\t\tconst document = scopedPolicyDocument(access.statements('<account>'));\n\t\t\tif (document) {\n\t\t\t\tlogger.log(\n\t\t\t\t\t`\\n Inline policy:\\n${JSON.stringify(JSON.parse(document), null, 2).replace(/^/gm, ' ')}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tlogger.log('\\n --dry-run: nothing changed.\\n');\n\t\treturn { repo, subject: oidc.subject };\n\t}\n\n\tconst iam = deps.iam ?? (await iamFor(options.profile));\n\tconst providerArn = await ensureOidcProvider(iam).catch((error) => {\n\t\t// The first AWS call is where an expired SSO login surfaces; the SDK's\n\t\t// message does not say which profile, and this command knows.\n\t\tif (/SSO session/i.test(String(error?.message)) && options.profile) {\n\t\t\tthrow new SsoSessionExpired(options.profile);\n\t\t}\n\t\tthrow error;\n\t});\n\tconst outcome = await ensureRole(\n\t\tiam,\n\t\trole,\n\t\ttrustPolicy(providerArn, oidc.subject),\n\t\taccess.kind === 'managed'\n\t\t\t? { managed: access.policyArn }\n\t\t\t: {\n\t\t\t\t\tinline: scopedPolicyDocument(\n\t\t\t\t\t\taccess.statements(accountOf(providerArn)),\n\t\t\t\t\t),\n\t\t\t\t},\n\t);\n\tconst roleArn = outcome.arn;\n\tlogger.log(`\\n ✓ AWS: ${roleArn}${outcome.created ? ' (created)' : ''}`);\n\tif (!outcome.created) {\n\t\tlogger.log(\n\t\t\toutcome.previousSubject === oidc.subject\n\t\t\t\t? ` ✓ Trust: unchanged, ${oidc.subject}`\n\t\t\t\t: ` ✓ Trust: ${outcome.previousSubject ?? '(no subject)'} → ${oidc.subject}`,\n\t\t);\n\t}\n\tfor (const detached of outcome.detached) {\n\t\tlogger.log(` ✓ Detached ${detached} (attached by gkm, no longer needed)`);\n\t}\n\tif (access.kind === 'scoped') {\n\t\tfor (const attached of outcome.leftAttached) {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ ${attached} is still attached to ${role}. gkm has no record of attaching it, so it is left; the compose deploy does not need it. Detach it with: aws iam detach-role-policy --role-name ${role} --policy-arn ${attached}${options.profile ? ` --profile ${options.profile}` : ''}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// The environment the generated deploy workflow runs the stage in.\n\tgh(['api', '--method', 'PUT', `repos/${repo}/environments/${options.stage}`]);\n\tgh([\n\t\t'variable',\n\t\t'set',\n\t\t'AWS_ROLE_ARN',\n\t\t'--env',\n\t\toptions.stage,\n\t\t'--repo',\n\t\trepo,\n\t\t'--body',\n\t\troleArn,\n\t]);\n\tlogger.log(` ✓ GitHub: environment \"${options.stage}\", AWS_ROLE_ARN`);\n\n\tif (remote) {\n\t\t// Nothing to send: the deploy job reads the stage's store itself.\n\t\tif (!hasSecrets) {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ The \"${options.stage}\" store holds no secrets yet; set them with gkm secrets:set <KEY> '…' --stage ${options.stage}${options.profile ? ` (AWS_PROFILE=${options.profile})` : ''}.`,\n\t\t\t);\n\t\t}\n\t} else if (hasKey) {\n\t\t// Through stdin, so the key is never an argument a process list shows.\n\t\tgh(\n\t\t\t[\n\t\t\t\t'secret',\n\t\t\t\t'set',\n\t\t\t\t'GKM_SECRETS_KEY',\n\t\t\t\t'--env',\n\t\t\t\toptions.stage,\n\t\t\t\t'--repo',\n\t\t\t\trepo,\n\t\t\t],\n\t\t\tkey!,\n\t\t);\n\t\tlogger.log(' ✓ GitHub: GKM_SECRETS_KEY');\n\t} else {\n\t\tlogger.log(\n\t\t\t` ⚠ No secrets key for \"${options.stage}\"; run gkm secrets:init --stage ${options.stage}, then this again.`,\n\t\t);\n\t}\n\n\tlogger.log(\n\t\t`\\n Protect it: add required reviewers to the \"${options.stage}\" environment in the repository settings.\\n`,\n\t);\n\treturn { roleArn, repo, subject: oidc.subject };\n}\n\nconst SUBJECT_KINDS = {\n\tdefault: \"the repository's default subject\",\n\timmutable: \"the repository's immutable subject\",\n\tcustom: \"the repository's custom subject template\",\n\tassumed: 'assumed: the default format',\n} as const;\n\n/** The profile's SSO login has lapsed; the fix is one command away. */\nexport class SsoSessionExpired extends GkmError {\n\tconstructor(readonly profile: string) {\n\t\tsuper(\n\t\t\t`The SSO session for profile \"${profile}\" has expired or is invalid. Run: aws sso login --profile ${profile}`,\n\t\t);\n\t\tthis.name = 'SsoSessionExpired';\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,uBAAuB;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;AAEA,MAAM,8BAAc,IAAI,IAAI;CAC3B;CACA;CACA;AACD,CAAC;;AAGD,SAAS,MAAM,OAAuB;CACrC,OAAO,MAAM,WAAW,KAAK,KAAK;AACnC;;AAMA,SAAgB,eACf,eACU;CACV,MAAM,yBACL,cAAc,0BAA0B,QACxC,CAAC,cAAc;CAChB,IAAI,cAAc,aAAa,OAAO;CAGtC,QADa,cAAc,sBAAsB,CAAC,EAAA,CACtC,MACV,QAAQ,YAAY,IAAI,GAAG,KAAM,QAAQ,UAAU,sBACrD;AACD;;;;;;;AAQA,SAAgB,YACf,MACA,OACA,eACA,OAC6C;CAC7C,MAAM,CAAC,QAAQ,IAAI,OAAO,MAAM,KAAK,MAAM,GAAG;CAC9C,MAAM,cAAc,eAAe,MAAM,KAAK;CAE9C,MAAM,oBAA4B;EACjC,IAAI,cAAc,kBAAkB,OAAO,cAAc;EACzD,IAAI,cAAc,uBAAuB;GACxC,IAAI,CAAC,OAAO,MAAM,IAAI,kBAAkB,IAAI;GAC5C,OAAO,QAAQ,MAAM,GAAG,MAAM,QAAQ,GAAG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