@geekmidas/cli 10.0.0-alpha.21 → 10.0.0-alpha.22

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.
@@ -1,7 +1,7 @@
1
1
  import { o as loadWorkspaceConfig } from "./config-DdKkoUE1.mjs";
2
2
  import { T as assertDeployedStage } from "./workspace-Bu3xNCej.mjs";
3
3
  import { c as getKeyPath, r as secretsExist } from "./storage-TP0x118M.mjs";
4
- import { a as isRemoteStore, r as pushStageSecrets } from "./transfer-Gsxfy6m-.mjs";
4
+ import { a as isRemoteStore, r as pushStageSecrets } from "./transfer-Bk5YlRyB.mjs";
5
5
  import { existsSync, readFileSync } from "node:fs";
6
6
  import { execFileSync } from "node:child_process";
7
7
  import { AttachRolePolicyCommand, CreateOpenIDConnectProviderCommand, CreateRoleCommand, GetRoleCommand, IAMClient, ListOpenIDConnectProvidersCommand, UpdateAssumeRolePolicyCommand } from "@aws-sdk/client-iam";
@@ -213,4 +213,4 @@ var SsoSessionExpired = class extends Error {
213
213
  //#endregion
214
214
  export { deployGithubCommand };
215
215
 
216
- //# sourceMappingURL=github-De-yMwVt.mjs.map
216
+ //# sourceMappingURL=github-B4OQQZBV.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"github-De-yMwVt.mjs","names":[],"sources":["../src/deploy/github.ts"],"sourcesContent":["/**\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 * SSM the deploy job pulls them with the role instead, so no key is handed to\n * GitHub, and this pushes the stage's local secrets to SSM in the same account,\n * with the same profile. Re-running it converges rather than duplicating.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport {\n\tAttachRolePolicyCommand,\n\tCreateOpenIDConnectProviderCommand,\n\tCreateRoleCommand,\n\tGetRoleCommand,\n\tIAMClient,\n\ttype IAMClientConfig,\n\tListOpenIDConnectProvidersCommand,\n\tUpdateAssumeRolePolicyCommand,\n} from '@aws-sdk/client-iam';\nimport { loadWorkspaceConfig } from '../config.js';\nimport { getKeyPath } from '../secrets/keystore.js';\nimport { secretsExist } from '../secrets/storage.js';\nimport { isRemoteStore } from '../secrets/store.js';\nimport { pushStageSecrets } from '../secrets/transfer.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\n\nconst logger = console;\n\nconst GITHUB_OIDC_HOST = 'token.actions.githubusercontent.com';\nconst AUDIENCE = 'sts.amazonaws.com';\n\n/**\n * What SST needs to create a stack is most of AWS, so this is the default —\n * said out loud in the output, and replaceable with `--policy-arn`.\n */\nexport const DEFAULT_POLICY_ARN = 'arn:aws:iam::aws:policy/AdministratorAccess';\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. */\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...(input === undefined\n\t\t\t? {}\n\t\t\t: { input, stdio: ['pipe', 'pipe', 'pipe'] as const }),\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 running in this repository's\n * `<stage>` environment, and nothing else — not another branch's job, not\n * another environment's. That is what keeps a staging deploy from using the\n * production role.\n */\nexport function trustPolicy(\n\tproviderArn: string,\n\trepo: string,\n\tstage: string,\n): 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`]: `repo:${repo}:environment:${stage}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\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/** The deploy role, created or brought back to this trust and policy. */\nexport async function ensureRole(\n\tiam: IAMClient,\n\tname: string,\n\ttrust: string,\n\tpolicyArn: string,\n): Promise<string> {\n\tlet arn: string;\n\ttry {\n\t\tconst { Role } = await iam.send(new GetRoleCommand({ RoleName: name }));\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} catch (error) {\n\t\tif ((error as { name?: string }).name !== 'NoSuchEntityException') {\n\t\t\tthrow error;\n\t\t}\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}\n\n\t// Attaching an attached policy is a no-op, so this converges too.\n\tawait iam.send(\n\t\tnew AttachRolePolicyCommand({ RoleName: name, PolicyArn: policyArn }),\n\t);\n\treturn arn;\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 }> {\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\tconst policyArn = options.policyArn ?? DEFAULT_POLICY_ARN;\n\tconst keyPath = getKeyPath(options.stage, workspace.name);\n\tconst hasKey = existsSync(keyPath);\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\tconst hasSecrets = secretsExist(options.stage, workspace.root);\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\tlogger.log(\n\t\t` Policy: ${policyArn}${options.policyArn ? '' : ' (default; --policy-arn to narrow)'}`,\n\t);\n\tlogger.log(` Trusted by: repo:${repo}:environment:${options.stage} only`);\n\tif (remote) {\n\t\tlogger.log(\n\t\t\t` Secrets: ${hasSecrets ? `pushed to the store with ${via}` : `none on this machine — gkm secrets:push --stage ${options.stage} later`}`,\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\tlogger.log('\\n --dry-run: nothing changed.\\n');\n\t\treturn { repo };\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 roleArn = await ensureRole(\n\t\tiam,\n\t\trole,\n\t\ttrustPolicy(providerArn, repo, options.stage),\n\t\tpolicyArn,\n\t);\n\tlogger.log(`\\n ✓ AWS: ${roleArn}`);\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\tif (hasSecrets) {\n\t\t\tawait pushStageSecrets(workspace, options.stage, {\n\t\t\t\t...(options.profile ? { profile: options.profile } : {}),\n\t\t\t});\n\t\t\tlogger.log(\n\t\t\t\t` ✓ Secrets: \"${options.stage}\" pushed to the store with ${via}`,\n\t\t\t);\n\t\t} else {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ No secrets for \"${options.stage}\" on this machine; the deploy job pulls them from the store, so push them: gkm secrets:push --stage ${options.stage}${options.profile ? ` --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\treadFileSync(keyPath, 'utf-8').trim(),\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 };\n}\n\n/** The profile's SSO login has lapsed; the fix is one command away. */\nexport class SsoSessionExpired extends Error {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,SAAS;AAEf,MAAM,mBAAmB;AACzB,MAAM,WAAW;AAsBjB,MAAM,aAAiB,MAAM,UAC5B,aAAa,MAAM,MAAM;CACxB,UAAU;CACV,GAAI,UAAU,KAAA,IACX,CAAC,IACD;EAAE;EAAO,OAAO;GAAC;GAAQ;GAAQ;EAAM;CAAW;AACtD,CAAC,CAAC,CAAC,KAAK;;AAGT,SAAgB,SAAS,SAAiB,OAAuB;CAChE,OAAO,GAAG,QAAQ,UAAU,QAC1B,YAAY,CAAC,CACb,QAAQ,qBAAqB,GAAG,CAAC,CACjC,MAAM,GAAG,EAAE;AACd;;;;;;;AAQA,SAAgB,YACf,aACA,MACA,OACS;CACT,OAAO,KAAK,UAAU;EACrB,SAAS;EACT,WAAW,CACV;GACC,QAAQ;GACR,WAAW,EAAE,WAAW,YAAY;GACpC,QAAQ;GACR,WAAW,EACV,cAAc;KACZ,GAAG,iBAAiB,QAAQ;KAC5B,GAAG,iBAAiB,QAAQ,QAAQ,KAAK,eAAe;GAC1D,EACD;EACD,CACD;CACD,CAAC;AACF;;AAGA,eAAsB,mBAAmB,KAAiC;CACzE,MAAM,EAAE,4BAA4B,CAAC,MAAM,MAAM,IAAI,KACpD,IAAI,kCAAkC,CAAC,CAAC,CACzC;CACA,MAAM,WAAW,0BAA0B,MAAM,MAChD,EAAE,KAAK,SAAS,iBAAiB,kBAAkB,CACpD,CAAC,EAAE;CACH,IAAI,UAAU,OAAO;CAQrB,QAAO,MANe,IAAI,KACzB,IAAI,mCAAmC;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EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;CACD,CAAC;CACD,OAAO,IAAI,4BAA4B,QAAQ,MAAM,gBAAgB;CAErE,IAAI,QAAQ;EACX,IAAI,YAAY;GACf,MAAM,iBAAiB,WAAW,QAAQ,OAAO,EAChD,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC,EACvD,CAAC;GACD,OAAO,IACN,iBAAiB,QAAQ,MAAM,6BAA6B,KAC7D;EACD,OACC,OAAO,IACN,uBAAuB,QAAQ,MAAM,sGAAsG,QAAQ,QAAQ,QAAQ,UAAU,cAAc,QAAQ,YAAY,GAAG,EACnN;CAEF,OAAO,IAAI,QAAQ;EAElB,GACC;GACC;GACA;GACA;GACA;GACA,QAAQ;GACR;GACA;EACD,GACA,aAAa,SAAS,OAAO,CAAC,CAAC,KAAK,CACrC;EACA,OAAO,IAAI,6BAA6B;CACzC,OACC,OAAO,IACN,2BAA2B,QAAQ,MAAM,kCAAkC,QAAQ,MAAM,mBAC1F;CAGD,OAAO,IACN,kDAAkD,QAAQ,MAAM,4CACjE;CACA,OAAO;EAAE;EAAS;CAAK;AACxB;;AAGA,IAAa,oBAAb,cAAuC,MAAM;CACvB;CAArB,YAAY,SAA0B;EACrC,MACC,gCAAgC,QAAQ,4DAA4D,SACrG;EAHoB,KAAA,UAAA;EAIpB,KAAK,OAAO;CACb;AACD"}
1
+ {"version":3,"file":"github-B4OQQZBV.mjs","names":[],"sources":["../src/deploy/github.ts"],"sourcesContent":["/**\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 * SSM the deploy job pulls them with the role instead, so no key is handed to\n * GitHub, and this pushes the stage's local secrets to SSM in the same account,\n * with the same profile. Re-running it converges rather than duplicating.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport {\n\tAttachRolePolicyCommand,\n\tCreateOpenIDConnectProviderCommand,\n\tCreateRoleCommand,\n\tGetRoleCommand,\n\tIAMClient,\n\ttype IAMClientConfig,\n\tListOpenIDConnectProvidersCommand,\n\tUpdateAssumeRolePolicyCommand,\n} from '@aws-sdk/client-iam';\nimport { loadWorkspaceConfig } from '../config.js';\nimport { getKeyPath } from '../secrets/keystore.js';\nimport { secretsExist } from '../secrets/storage.js';\nimport { isRemoteStore } from '../secrets/store.js';\nimport { pushStageSecrets } from '../secrets/transfer.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\n\nconst logger = console;\n\nconst GITHUB_OIDC_HOST = 'token.actions.githubusercontent.com';\nconst AUDIENCE = 'sts.amazonaws.com';\n\n/**\n * What SST needs to create a stack is most of AWS, so this is the default —\n * said out loud in the output, and replaceable with `--policy-arn`.\n */\nexport const DEFAULT_POLICY_ARN = 'arn:aws:iam::aws:policy/AdministratorAccess';\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. */\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...(input === undefined\n\t\t\t? {}\n\t\t\t: { input, stdio: ['pipe', 'pipe', 'pipe'] as const }),\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 running in this repository's\n * `<stage>` environment, and nothing else — not another branch's job, not\n * another environment's. That is what keeps a staging deploy from using the\n * production role.\n */\nexport function trustPolicy(\n\tproviderArn: string,\n\trepo: string,\n\tstage: string,\n): 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`]: `repo:${repo}:environment:${stage}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\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/** The deploy role, created or brought back to this trust and policy. */\nexport async function ensureRole(\n\tiam: IAMClient,\n\tname: string,\n\ttrust: string,\n\tpolicyArn: string,\n): Promise<string> {\n\tlet arn: string;\n\ttry {\n\t\tconst { Role } = await iam.send(new GetRoleCommand({ RoleName: name }));\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} catch (error) {\n\t\tif ((error as { name?: string }).name !== 'NoSuchEntityException') {\n\t\t\tthrow error;\n\t\t}\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}\n\n\t// Attaching an attached policy is a no-op, so this converges too.\n\tawait iam.send(\n\t\tnew AttachRolePolicyCommand({ RoleName: name, PolicyArn: policyArn }),\n\t);\n\treturn arn;\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 }> {\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\tconst policyArn = options.policyArn ?? DEFAULT_POLICY_ARN;\n\tconst keyPath = getKeyPath(options.stage, workspace.name);\n\tconst hasKey = existsSync(keyPath);\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\tconst hasSecrets = secretsExist(options.stage, workspace.root);\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\tlogger.log(\n\t\t` Policy: ${policyArn}${options.policyArn ? '' : ' (default; --policy-arn to narrow)'}`,\n\t);\n\tlogger.log(` Trusted by: repo:${repo}:environment:${options.stage} only`);\n\tif (remote) {\n\t\tlogger.log(\n\t\t\t` Secrets: ${hasSecrets ? `pushed to the store with ${via}` : `none on this machine — gkm secrets:push --stage ${options.stage} later`}`,\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\tlogger.log('\\n --dry-run: nothing changed.\\n');\n\t\treturn { repo };\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 roleArn = await ensureRole(\n\t\tiam,\n\t\trole,\n\t\ttrustPolicy(providerArn, repo, options.stage),\n\t\tpolicyArn,\n\t);\n\tlogger.log(`\\n ✓ AWS: ${roleArn}`);\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\tif (hasSecrets) {\n\t\t\tawait pushStageSecrets(workspace, options.stage, {\n\t\t\t\t...(options.profile ? { profile: options.profile } : {}),\n\t\t\t});\n\t\t\tlogger.log(\n\t\t\t\t` ✓ Secrets: \"${options.stage}\" pushed to the store with ${via}`,\n\t\t\t);\n\t\t} else {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ No secrets for \"${options.stage}\" on this machine; the deploy job pulls them from the store, so push them: gkm secrets:push --stage ${options.stage}${options.profile ? ` --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\treadFileSync(keyPath, 'utf-8').trim(),\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 };\n}\n\n/** The profile's SSO login has lapsed; the fix is one command away. */\nexport class SsoSessionExpired extends Error {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,SAAS;AAEf,MAAM,mBAAmB;AACzB,MAAM,WAAW;AAsBjB,MAAM,aAAiB,MAAM,UAC5B,aAAa,MAAM,MAAM;CACxB,UAAU;CACV,GAAI,UAAU,KAAA,IACX,CAAC,IACD;EAAE;EAAO,OAAO;GAAC;GAAQ;GAAQ;EAAM;CAAW;AACtD,CAAC,CAAC,CAAC,KAAK;;AAGT,SAAgB,SAAS,SAAiB,OAAuB;CAChE,OAAO,GAAG,QAAQ,UAAU,QAC1B,YAAY,CAAC,CACb,QAAQ,qBAAqB,GAAG,CAAC,CACjC,MAAM,GAAG,EAAE;AACd;;;;;;;AAQA,SAAgB,YACf,aACA,MACA,OACS;CACT,OAAO,KAAK,UAAU;EACrB,SAAS;EACT,WAAW,CACV;GACC,QAAQ;GACR,WAAW,EAAE,WAAW,YAAY;GACpC,QAAQ;GACR,WAAW,EACV,cAAc;KACZ,GAAG,iBAAiB,QAAQ;KAC5B,GAAG,iBAAiB,QAAQ,QAAQ,KAAK,eAAe;GAC1D,EACD;EACD,CACD;CACD,CAAC;AACF;;AAGA,eAAsB,mBAAmB,KAAiC;CACzE,MAAM,EAAE,4BAA4B,CAAC,MAAM,MAAM,IAAI,KACpD,IAAI,kCAAkC,CAAC,CAAC,CACzC;CACA,MAAM,WAAW,0BAA0B,MAAM,MAChD,EAAE,KAAK,SAAS,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,SAAS;CAGlC,GAAG;EAAC;EAAO;EAAY;EAAO,SAAS,KAAK,gBAAgB,QAAQ;CAAO,CAAC;CAC5E,GAAG;EACF;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;CACD,CAAC;CACD,OAAO,IAAI,4BAA4B,QAAQ,MAAM,gBAAgB;CAErE,IAAI,QAAQ;EACX,IAAI,YAAY;GACf,MAAM,iBAAiB,WAAW,QAAQ,OAAO,EAChD,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC,EACvD,CAAC;GACD,OAAO,IACN,iBAAiB,QAAQ,MAAM,6BAA6B,KAC7D;EACD,OACC,OAAO,IACN,uBAAuB,QAAQ,MAAM,sGAAsG,QAAQ,QAAQ,QAAQ,UAAU,cAAc,QAAQ,YAAY,GAAG,EACnN;CAEF,OAAO,IAAI,QAAQ;EAElB,GACC;GACC;GACA;GACA;GACA;GACA,QAAQ;GACR;GACA;EACD,GACA,aAAa,SAAS,OAAO,CAAC,CAAC,KAAK,CACrC;EACA,OAAO,IAAI,6BAA6B;CACzC,OACC,OAAO,IACN,2BAA2B,QAAQ,MAAM,kCAAkC,QAAQ,MAAM,mBAC1F;CAGD,OAAO,IACN,kDAAkD,QAAQ,MAAM,4CACjE;CACA,OAAO;EAAE;EAAS;CAAK;AACxB;;AAGA,IAAa,oBAAb,cAAuC,MAAM;CACvB;CAArB,YAAY,SAA0B;EACrC,MACC,gCAAgC,QAAQ,4DAA4D,SACrG;EAHoB,KAAA,UAAA;EAIpB,KAAK,OAAO;CACb;AACD"}
@@ -1,7 +1,7 @@
1
1
  const require_config = require("./config-DSXI480r.cjs");
2
2
  const require_workspace = require("./workspace-CRD9YinV.cjs");
3
3
  const require_storage = require("./storage-DgypfSD6.cjs");
4
- const require_transfer = require("./transfer-CXoyQZbB.cjs");
4
+ const require_transfer = require("./transfer-BZbyaV3I.cjs");
5
5
  let node_fs = require("node:fs");
6
6
  let node_child_process = require("node:child_process");
7
7
  let _aws_sdk_client_iam = require("@aws-sdk/client-iam");
@@ -213,4 +213,4 @@ var SsoSessionExpired = class extends Error {
213
213
  //#endregion
214
214
  exports.deployGithubCommand = deployGithubCommand;
215
215
 
216
- //# sourceMappingURL=github-Bho-C6Zg.cjs.map
216
+ //# sourceMappingURL=github-BpsnSDw2.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"github-Bho-C6Zg.cjs","names":["execFileSync","ListOpenIDConnectProvidersCommand","CreateOpenIDConnectProviderCommand","GetRoleCommand","UpdateAssumeRolePolicyCommand","CreateRoleCommand","AttachRolePolicyCommand","IAMClient","loadWorkspaceConfig","getKeyPath","existsSync","isRemoteStore","secretsExist","pushStageSecrets","readFileSync"],"sources":["../src/deploy/github.ts"],"sourcesContent":["/**\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 * SSM the deploy job pulls them with the role instead, so no key is handed to\n * GitHub, and this pushes the stage's local secrets to SSM in the same account,\n * with the same profile. Re-running it converges rather than duplicating.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport {\n\tAttachRolePolicyCommand,\n\tCreateOpenIDConnectProviderCommand,\n\tCreateRoleCommand,\n\tGetRoleCommand,\n\tIAMClient,\n\ttype IAMClientConfig,\n\tListOpenIDConnectProvidersCommand,\n\tUpdateAssumeRolePolicyCommand,\n} from '@aws-sdk/client-iam';\nimport { loadWorkspaceConfig } from '../config.js';\nimport { getKeyPath } from '../secrets/keystore.js';\nimport { secretsExist } from '../secrets/storage.js';\nimport { isRemoteStore } from '../secrets/store.js';\nimport { pushStageSecrets } from '../secrets/transfer.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\n\nconst logger = console;\n\nconst GITHUB_OIDC_HOST = 'token.actions.githubusercontent.com';\nconst AUDIENCE = 'sts.amazonaws.com';\n\n/**\n * What SST needs to create a stack is most of AWS, so this is the default —\n * said out loud in the output, and replaceable with `--policy-arn`.\n */\nexport const DEFAULT_POLICY_ARN = 'arn:aws:iam::aws:policy/AdministratorAccess';\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. */\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...(input === undefined\n\t\t\t? {}\n\t\t\t: { input, stdio: ['pipe', 'pipe', 'pipe'] as const }),\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 running in this repository's\n * `<stage>` environment, and nothing else — not another branch's job, not\n * another environment's. That is what keeps a staging deploy from using the\n * production role.\n */\nexport function trustPolicy(\n\tproviderArn: string,\n\trepo: string,\n\tstage: string,\n): 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`]: `repo:${repo}:environment:${stage}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\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/** The deploy role, created or brought back to this trust and policy. */\nexport async function ensureRole(\n\tiam: IAMClient,\n\tname: string,\n\ttrust: string,\n\tpolicyArn: string,\n): Promise<string> {\n\tlet arn: string;\n\ttry {\n\t\tconst { Role } = await iam.send(new GetRoleCommand({ RoleName: name }));\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} catch (error) {\n\t\tif ((error as { name?: string }).name !== 'NoSuchEntityException') {\n\t\t\tthrow error;\n\t\t}\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}\n\n\t// Attaching an attached policy is a no-op, so this converges too.\n\tawait iam.send(\n\t\tnew AttachRolePolicyCommand({ RoleName: name, PolicyArn: policyArn }),\n\t);\n\treturn arn;\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 }> {\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\tconst policyArn = options.policyArn ?? DEFAULT_POLICY_ARN;\n\tconst keyPath = getKeyPath(options.stage, workspace.name);\n\tconst hasKey = existsSync(keyPath);\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\tconst hasSecrets = secretsExist(options.stage, workspace.root);\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\tlogger.log(\n\t\t` Policy: ${policyArn}${options.policyArn ? '' : ' (default; --policy-arn to narrow)'}`,\n\t);\n\tlogger.log(` Trusted by: repo:${repo}:environment:${options.stage} only`);\n\tif (remote) {\n\t\tlogger.log(\n\t\t\t` Secrets: ${hasSecrets ? `pushed to the store with ${via}` : `none on this machine — gkm secrets:push --stage ${options.stage} later`}`,\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\tlogger.log('\\n --dry-run: nothing changed.\\n');\n\t\treturn { repo };\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 roleArn = await ensureRole(\n\t\tiam,\n\t\trole,\n\t\ttrustPolicy(providerArn, repo, options.stage),\n\t\tpolicyArn,\n\t);\n\tlogger.log(`\\n ✓ AWS: ${roleArn}`);\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\tif (hasSecrets) {\n\t\t\tawait pushStageSecrets(workspace, options.stage, {\n\t\t\t\t...(options.profile ? { profile: options.profile } : {}),\n\t\t\t});\n\t\t\tlogger.log(\n\t\t\t\t` ✓ Secrets: \"${options.stage}\" pushed to the store with ${via}`,\n\t\t\t);\n\t\t} else {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ No secrets for \"${options.stage}\" on this machine; the deploy job pulls them from the store, so push them: gkm secrets:push --stage ${options.stage}${options.profile ? ` --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\treadFileSync(keyPath, 'utf-8').trim(),\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 };\n}\n\n/** The profile's SSO login has lapsed; the fix is one command away. */\nexport class SsoSessionExpired extends Error {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,SAAS;AAEf,MAAM,mBAAmB;AACzB,MAAM,WAAW;AAsBjB,MAAM,aAAiB,M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AAE,SAAS,QAAQ,QAAQ,IAAI,CAAC,EACvD,CAAC;GACD,OAAO,IACN,iBAAiB,QAAQ,MAAM,6BAA6B,KAC7D;EACD,OACC,OAAO,IACN,uBAAuB,QAAQ,MAAM,sGAAsG,QAAQ,QAAQ,QAAQ,UAAU,cAAc,QAAQ,YAAY,GAAG,EACnN;CAEF,OAAO,IAAI,QAAQ;EAElB,GACC;GACC;GACA;GACA;GACA;GACA,QAAQ;GACR;GACA;EACD,IAAA,GACAC,QAAAA,aAAAA,CAAa,SAAS,OAAO,CAAC,CAAC,KAAK,CACrC;EACA,OAAO,IAAI,6BAA6B;CACzC,OACC,OAAO,IACN,2BAA2B,QAAQ,MAAM,kCAAkC,QAAQ,MAAM,mBAC1F;CAGD,OAAO,IACN,kDAAkD,QAAQ,MAAM,4CACjE;CACA,OAAO;EAAE;EAAS;CAAK;AACxB;;AAGA,IAAa,oBAAb,cAAuC,MAAM;CACvB;CAArB,YAAY,SAA0B;EACrC,MACC,gCAAgC,QAAQ,4DAA4D,SACrG;EAHoB,KAAA,UAAA;EAIpB,KAAK,OAAO;CACb;AACD"}
1
+ {"version":3,"file":"github-BpsnSDw2.cjs","names":["execFileSync","ListOpenIDConnectProvidersCommand","CreateOpenIDConnectProviderCommand","GetRoleCommand","UpdateAssumeRolePolicyCommand","CreateRoleCommand","AttachRolePolicyCommand","IAMClient","loadWorkspaceConfig","getKeyPath","existsSync","isRemoteStore","secretsExist","pushStageSecrets","readFileSync"],"sources":["../src/deploy/github.ts"],"sourcesContent":["/**\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 * SSM the deploy job pulls them with the role instead, so no key is handed to\n * GitHub, and this pushes the stage's local secrets to SSM in the same account,\n * with the same profile. Re-running it converges rather than duplicating.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport {\n\tAttachRolePolicyCommand,\n\tCreateOpenIDConnectProviderCommand,\n\tCreateRoleCommand,\n\tGetRoleCommand,\n\tIAMClient,\n\ttype IAMClientConfig,\n\tListOpenIDConnectProvidersCommand,\n\tUpdateAssumeRolePolicyCommand,\n} from '@aws-sdk/client-iam';\nimport { loadWorkspaceConfig } from '../config.js';\nimport { getKeyPath } from '../secrets/keystore.js';\nimport { secretsExist } from '../secrets/storage.js';\nimport { isRemoteStore } from '../secrets/store.js';\nimport { pushStageSecrets } from '../secrets/transfer.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\n\nconst logger = console;\n\nconst GITHUB_OIDC_HOST = 'token.actions.githubusercontent.com';\nconst AUDIENCE = 'sts.amazonaws.com';\n\n/**\n * What SST needs to create a stack is most of AWS, so this is the default —\n * said out loud in the output, and replaceable with `--policy-arn`.\n */\nexport const DEFAULT_POLICY_ARN = 'arn:aws:iam::aws:policy/AdministratorAccess';\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. */\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...(input === undefined\n\t\t\t? {}\n\t\t\t: { input, stdio: ['pipe', 'pipe', 'pipe'] as const }),\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 running in this repository's\n * `<stage>` environment, and nothing else — not another branch's job, not\n * another environment's. That is what keeps a staging deploy from using the\n * production role.\n */\nexport function trustPolicy(\n\tproviderArn: string,\n\trepo: string,\n\tstage: string,\n): 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`]: `repo:${repo}:environment:${stage}`,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\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/** The deploy role, created or brought back to this trust and policy. */\nexport async function ensureRole(\n\tiam: IAMClient,\n\tname: string,\n\ttrust: string,\n\tpolicyArn: string,\n): Promise<string> {\n\tlet arn: string;\n\ttry {\n\t\tconst { Role } = await iam.send(new GetRoleCommand({ RoleName: name }));\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} catch (error) {\n\t\tif ((error as { name?: string }).name !== 'NoSuchEntityException') {\n\t\t\tthrow error;\n\t\t}\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}\n\n\t// Attaching an attached policy is a no-op, so this converges too.\n\tawait iam.send(\n\t\tnew AttachRolePolicyCommand({ RoleName: name, PolicyArn: policyArn }),\n\t);\n\treturn arn;\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 }> {\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\tconst policyArn = options.policyArn ?? DEFAULT_POLICY_ARN;\n\tconst keyPath = getKeyPath(options.stage, workspace.name);\n\tconst hasKey = existsSync(keyPath);\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\tconst hasSecrets = secretsExist(options.stage, workspace.root);\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\tlogger.log(\n\t\t` Policy: ${policyArn}${options.policyArn ? '' : ' (default; --policy-arn to narrow)'}`,\n\t);\n\tlogger.log(` Trusted by: repo:${repo}:environment:${options.stage} only`);\n\tif (remote) {\n\t\tlogger.log(\n\t\t\t` Secrets: ${hasSecrets ? `pushed to the store with ${via}` : `none on this machine — gkm secrets:push --stage ${options.stage} later`}`,\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\tlogger.log('\\n --dry-run: nothing changed.\\n');\n\t\treturn { repo };\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 roleArn = await ensureRole(\n\t\tiam,\n\t\trole,\n\t\ttrustPolicy(providerArn, repo, options.stage),\n\t\tpolicyArn,\n\t);\n\tlogger.log(`\\n ✓ AWS: ${roleArn}`);\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\tif (hasSecrets) {\n\t\t\tawait pushStageSecrets(workspace, options.stage, {\n\t\t\t\t...(options.profile ? { profile: options.profile } : {}),\n\t\t\t});\n\t\t\tlogger.log(\n\t\t\t\t` ✓ Secrets: \"${options.stage}\" pushed to the store with ${via}`,\n\t\t\t);\n\t\t} else {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ No secrets for \"${options.stage}\" on this machine; the deploy job pulls them from the store, so push them: gkm secrets:push --stage ${options.stage}${options.profile ? ` --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\treadFileSync(keyPath, 'utf-8').trim(),\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 };\n}\n\n/** The profile's SSO login has lapsed; the fix is one command away. */\nexport class SsoSessionExpired extends Error {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,SAAS;AAEf,MAAM,mBAAmB;AACzB,MAAM,WAAW;AAsBjB,MAAM,aAAiB,MAAM,WAAA,GAC5BA,mBAAAA,aAAAA,CAAa,MAAM,MAAM;CACxB,UAAU;CACV,GAAI,UAAU,KAAA,IACX,CAAC,IACD;EAAE;EAAO,OAAO;GAAC;GAAQ;GAAQ;EAAM;CAAW;AACtD,CAAC,CAAC,CAAC,KAAK;;AAGT,SAAgB,SAAS,SAAiB,OAAuB;CAChE,OAAO,GAAG,QAAQ,UAAU,QAC1B,YAAY,CAAC,CACb,QAAQ,qBAAqB,GAAG,CAAC,CACjC,MAAM,GAAG,EAAE;AACd;;;;;;;AAQA,SAAgB,YACf,aACA,MACA,OACS;CACT,OAAO,KAAK,UAAU;EACrB,SAAS;EACT,WAAW,CACV;GACC,QAAQ;GACR,WAAW,EAAE,WAAW,YAAY;GACpC,QAAQ;GACR,WAAW,EACV,cAAc;KACZ,GAAG,iBAAiB,QAAQ;KAC5B,GAAG,iBAAiB,QAAQ,QAAQ,KAAK,eAAe;GAC1D,EACD;EACD,CACD;CACD,CAAC;AACF;;AAGA,eAAsB,mBAAmB,KAAiC;CACzE,MAAM,EAAE,4BAA4B,CAAC,MAAM,MAAM,IAAI,KACpD,IAAIC,oBAAAA,kCAAkC,CAAC,CAAC,CACzC;CACA,MAAM,WAAW,0BAA0B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Pl7ul.cjs");
4
4
  const require_discover = require("./discover-BERGFg8v.cjs");
5
5
  const require_config = require("./config-DSXI480r.cjs");
6
6
  const require_workspace = require("./workspace-CRD9YinV.cjs");
7
- const require_credentials = require("./credentials-BfmmB4WD.cjs");
7
+ const require_credentials = require("./credentials-COrSpZfF.cjs");
8
8
  const require_generator = require("./generator-Wdfp0jCS.cjs");
9
9
  const require_storage = require("./storage-DgypfSD6.cjs");
10
- const require_openapi = require("./openapi-B8bu_OXN.cjs");
10
+ const require_openapi = require("./openapi-CN69hrf0.cjs");
11
11
  const require_emit = require("./emit-BdoPFjZf.cjs");
12
12
  const require_reconcile = require("./reconcile-hx_vBvux.cjs");
13
- const require_transfer = require("./transfer-CXoyQZbB.cjs");
13
+ const require_transfer = require("./transfer-BZbyaV3I.cjs");
14
14
  let commander = require("commander");
15
15
  let node_process = require("node:process");
16
16
  let node_readline_promises = require("node:readline/promises");
@@ -41,8 +41,10 @@ let node_dns_promises = require("node:dns/promises");
41
41
  let node_module = require("node:module");
42
42
  let prompts = require("prompts");
43
43
  prompts = require_rolldown_runtime.__toESM(prompts, 1);
44
+ let _geekmidas_envkit = require("@geekmidas/envkit");
45
+ let _geekmidas_services = require("@geekmidas/services");
44
46
  //#region package.json
45
- var version = "10.0.0-alpha.21";
47
+ var version = "10.0.0-alpha.22";
46
48
  //#endregion
47
49
  //#region src/auth/credentials.ts
48
50
  /**
@@ -8418,26 +8420,26 @@ function loadPackageJson() {
8418
8420
  * Run: pnpm --filter @geekmidas/cli sync-versions
8419
8421
  */
8420
8422
  const GEEKMIDAS_VERSIONS = {
8421
- "@geekmidas/audit": "~10.0.0-alpha.21",
8422
- "@geekmidas/auth": "~10.0.0-alpha.21",
8423
- "@geekmidas/cache": "~10.0.0-alpha.21",
8424
- "@geekmidas/client": "~10.0.0-alpha.21",
8425
- "@geekmidas/cloud": "~10.0.0-alpha.21",
8426
- "@geekmidas/constructs": "~10.0.0-alpha.21",
8427
- "@geekmidas/db": "~10.0.0-alpha.21",
8428
- "@geekmidas/emailkit": "~10.0.0-alpha.21",
8429
- "@geekmidas/envkit": "~10.0.0-alpha.21",
8430
- "@geekmidas/errors": "~10.0.0-alpha.21",
8431
- "@geekmidas/events": "~10.0.0-alpha.21",
8432
- "@geekmidas/logger": "~10.0.0-alpha.21",
8433
- "@geekmidas/manifest": "~10.0.0-alpha.21",
8434
- "@geekmidas/rate-limit": "~10.0.0-alpha.21",
8435
- "@geekmidas/schema": "~10.0.0-alpha.21",
8436
- "@geekmidas/services": "~10.0.0-alpha.21",
8437
- "@geekmidas/storage": "~10.0.0-alpha.21",
8438
- "@geekmidas/studio": "~10.0.0-alpha.21",
8439
- "@geekmidas/telescope": "~10.0.0-alpha.21",
8440
- "@geekmidas/testkit": "~10.0.0-alpha.21",
8423
+ "@geekmidas/audit": "~10.0.0-alpha.22",
8424
+ "@geekmidas/auth": "~10.0.0-alpha.22",
8425
+ "@geekmidas/cache": "~10.0.0-alpha.22",
8426
+ "@geekmidas/client": "~10.0.0-alpha.22",
8427
+ "@geekmidas/cloud": "~10.0.0-alpha.22",
8428
+ "@geekmidas/constructs": "~10.0.0-alpha.22",
8429
+ "@geekmidas/db": "~10.0.0-alpha.22",
8430
+ "@geekmidas/emailkit": "~10.0.0-alpha.22",
8431
+ "@geekmidas/envkit": "~10.0.0-alpha.22",
8432
+ "@geekmidas/errors": "~10.0.0-alpha.22",
8433
+ "@geekmidas/events": "~10.0.0-alpha.22",
8434
+ "@geekmidas/logger": "~10.0.0-alpha.22",
8435
+ "@geekmidas/manifest": "~10.0.0-alpha.22",
8436
+ "@geekmidas/rate-limit": "~10.0.0-alpha.22",
8437
+ "@geekmidas/schema": "~10.0.0-alpha.22",
8438
+ "@geekmidas/services": "~10.0.0-alpha.22",
8439
+ "@geekmidas/storage": "~10.0.0-alpha.22",
8440
+ "@geekmidas/studio": "~10.0.0-alpha.22",
8441
+ "@geekmidas/telescope": "~10.0.0-alpha.22",
8442
+ "@geekmidas/testkit": "~10.0.0-alpha.22",
8441
8443
  "@geekmidas/cli": `~${loadPackageJson().version}`
8442
8444
  };
8443
8445
  //#endregion
@@ -15138,6 +15140,223 @@ function printSummary(workspace, stage) {
15138
15140
  logger$1.log("");
15139
15141
  }
15140
15142
  //#endregion
15143
+ //#region src/test/harness.ts
15144
+ /**
15145
+ * What `gkm test` writes for a feature test to be built from.
15146
+ *
15147
+ * `gkm test` already discovers an app's constructs and resolves the test
15148
+ * stage's environment; this keeps both, under `.gkm/test/`:
15149
+ *
15150
+ * - `manifest.json` — which construct and endpoint is exported where, and the
15151
+ * environment the test stage resolved, keyed as the constructs derive keys.
15152
+ * - `clients/<surface>.ts` — each surface's typed client, from the same
15153
+ * generator `gkm build` uses for the app's own.
15154
+ * - `index.ts` — the configured `it`, and a `Browser` holding one client per
15155
+ * surface and one per auth server, each on the browser's `fetch`.
15156
+ *
15157
+ * A test imports `it` from there and declares nothing — not a construct, not an
15158
+ * environment key, not a client.
15159
+ */
15160
+ /**
15161
+ * The variable the manifest's path travels in — what
15162
+ * `@geekmidas/constructs/testing` reads. Its own constant rather than an import:
15163
+ * that entry carries the whole harness (MSW, Hono, Vitest), and importing it
15164
+ * here put all of it on the start-up path of every `gkm` command.
15165
+ */
15166
+ const TEST_MANIFEST_ENV = "GKM_TEST_MANIFEST";
15167
+ /** Where the harness lives, relative to the workspace root. */
15168
+ const TEST_HARNESS_DIR = ".gkm/test";
15169
+ /**
15170
+ * Better-auth's client plugin for each server plugin id.
15171
+ *
15172
+ * Written down rather than derived: the ids and the client names do not follow
15173
+ * one rule (`admin` pairs with `adminClient`, `email-otp` with
15174
+ * `emailOTPClient`), and a guess that missed would hand a test a client
15175
+ * silently lacking every method of that plugin. A server plugin not listed has
15176
+ * no client counterpart — `bearer`, `open-api` — or needs one from another
15177
+ * package, and is left out.
15178
+ */
15179
+ const CLIENT_PLUGINS = {
15180
+ admin: "adminClient",
15181
+ anonymous: "anonymousClient",
15182
+ "device-authorization": "deviceAuthorizationClient",
15183
+ "email-otp": "emailOTPClient",
15184
+ jwt: "jwtClient",
15185
+ "last-login-method": "lastLoginMethodClient",
15186
+ "magic-link": "magicLinkClient",
15187
+ "multi-session": "multiSessionClient",
15188
+ "oauth-popup": "oauthPopupClient",
15189
+ "one-tap": "oneTapClient",
15190
+ "one-time-token": "oneTimeTokenClient",
15191
+ organization: "organizationClient",
15192
+ "phone-number": "phoneNumberClient",
15193
+ siwe: "siweClient",
15194
+ "two-factor": "twoFactorClient",
15195
+ username: "usernameClient"
15196
+ };
15197
+ /** Write the manifest, the clients and the harness; return the manifest path. */
15198
+ async function writeTestHarness(options) {
15199
+ const sources = {};
15200
+ const declared = await require_discover.discover({
15201
+ patterns: options.patterns,
15202
+ cwd: options.root,
15203
+ sources
15204
+ });
15205
+ const endpoints = (await new require_openapi.EndpointGenerator().load(options.patterns, options.root)).map(({ key, construct, path }) => ({
15206
+ surface: construct.owner ?? construct.surface?.id,
15207
+ construct,
15208
+ source: {
15209
+ file: path.absolute,
15210
+ export: key
15211
+ }
15212
+ })).filter((endpoint) => endpoint.surface !== void 0);
15213
+ const manifest = {
15214
+ stage: options.stage,
15215
+ constructs: Object.fromEntries(Object.entries(declared).flatMap(([id, declaration]) => {
15216
+ const source = sources[id];
15217
+ return source ? [[id, {
15218
+ kind: declaration.kind,
15219
+ source: {
15220
+ file: source.file,
15221
+ export: source.exportName
15222
+ }
15223
+ }]] : [];
15224
+ })),
15225
+ endpoints: endpoints.map(({ surface, source }) => ({
15226
+ surface,
15227
+ source
15228
+ })),
15229
+ env: options.env
15230
+ };
15231
+ const surfaces = [...new Set(endpoints.map(({ surface }) => surface))];
15232
+ const generator = new require_openapi.OpenApiTsGenerator();
15233
+ const clients = await Promise.all(surfaces.map(async (surface) => ({
15234
+ file: `${(0, _geekmidas_manifest.kebabCase)(surface)}.ts`,
15235
+ content: await generator.generate(endpoints.filter((endpoint) => endpoint.surface === surface).map(({ construct }) => construct), {
15236
+ title: surface,
15237
+ version: "1.0.0"
15238
+ })
15239
+ })));
15240
+ const auths = await authClients(declared, sources, options.env);
15241
+ const drivers = driversFor({
15242
+ appRoot: options.root,
15243
+ cache: cacheBackendsIn(declared, options.cacheBackend)
15244
+ });
15245
+ const database = await databaseSource(declared, sources, endpoints.map(({ construct }) => construct));
15246
+ const harnessFor = (dir) => harnessModule({
15247
+ dir,
15248
+ database,
15249
+ surfaces: surfaces.map((id, index) => ({
15250
+ id,
15251
+ secured: clients[index].content.includes("authStrategies:")
15252
+ })),
15253
+ auths,
15254
+ drivers
15255
+ });
15256
+ const json = `${JSON.stringify(manifest, null, 2)}\n`;
15257
+ return (await Promise.all([...new Set(options.targets)].map(async (target) => {
15258
+ const dir = (0, node_path.join)(target, TEST_HARNESS_DIR);
15259
+ await (0, node_fs_promises.rm)(dir, {
15260
+ recursive: true,
15261
+ force: true
15262
+ });
15263
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(dir, "clients"), { recursive: true });
15264
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(dir, "manifest.json"), json);
15265
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(dir, "index.ts"), harnessFor(dir));
15266
+ for (const client of clients) await (0, node_fs_promises.writeFile)((0, node_path.join)(dir, "clients", client.file), client.content);
15267
+ return (0, node_path.join)(dir, "manifest.json");
15268
+ })))[0];
15269
+ }
15270
+ /** Each auth server, with the client plugins its server plugins pair with. */
15271
+ async function authClients(declared, sources, env) {
15272
+ const clients = [];
15273
+ const envParser = new _geekmidas_envkit.EnvironmentParser({ ...env });
15274
+ for (const [id, declaration] of Object.entries(declared)) {
15275
+ const source = sources[id];
15276
+ if (declaration.kind !== "rest-api" || !source) continue;
15277
+ const exported = (await import(source.file))[source.exportName];
15278
+ if (!isBetterAuth(exported) || exported.id !== id) continue;
15279
+ const ids = await exported.pluginIds({
15280
+ envParser,
15281
+ context: _geekmidas_services.serviceContext
15282
+ });
15283
+ clients.push({
15284
+ id,
15285
+ basePath: exported.basePath,
15286
+ plugins: ids.flatMap((plugin) => CLIENT_PLUGINS[plugin] ?? [])
15287
+ });
15288
+ }
15289
+ return clients;
15290
+ }
15291
+ function isBetterAuth(value) {
15292
+ return typeof value === "object" && value !== null && "pluginIds" in value && "basePath" in value;
15293
+ }
15294
+ /** `Api` → `api`, `AdminApi` → `adminApi`: a construct id as a property name. */
15295
+ function propertyOf(id) {
15296
+ return id.charAt(0).toLowerCase() + id.slice(1);
15297
+ }
15298
+ /**
15299
+ * The database a test's `db` is — the one the endpoints were given with
15300
+ * `.database()`, found by the service they hold, which is the construct's own.
15301
+ * The same rule `featureTest` applies at runtime, applied here so `db` can be
15302
+ * typed by the construct's schema.
15303
+ */
15304
+ async function databaseSource(declared, sources, endpoints) {
15305
+ const services = new Set(endpoints.map((endpoint) => endpoint.databaseService).filter(Boolean));
15306
+ if (services.size === 0) return void 0;
15307
+ for (const [id, declaration] of Object.entries(declared)) {
15308
+ const source = sources[id];
15309
+ if (!source || !declaration.kind.startsWith("database")) continue;
15310
+ const exported = (await import(source.file))[source.exportName];
15311
+ if (services.has(exported?.service)) return source;
15312
+ }
15313
+ }
15314
+ /** An import specifier for `file`, from the harness written into `dir`. */
15315
+ function specifierFrom(dir, file) {
15316
+ const path = (0, node_path.relative)(dir, file).replace(/\.tsx?$/, ".js");
15317
+ return path.startsWith(".") ? path : `./${path}`;
15318
+ }
15319
+ function harnessModule(options) {
15320
+ const { surfaces, auths, drivers, database, dir } = options;
15321
+ const plugins = [...new Set(auths.flatMap(({ plugins }) => plugins))].sort();
15322
+ const imports = [
15323
+ `import {${database ? " type DatabaseOf," : ""} featureTest, loadTestManifest } from '@geekmidas/constructs/testing';`,
15324
+ ...database ? [`import type { ${database.exportName} as __database } from '${specifierFrom(dir, database.file)}';`] : [],
15325
+ `import { Browser as TestBrowser } from '@geekmidas/testkit/browser';`,
15326
+ ...surfaces.map(({ id }) => `import { createApi as create${id} } from './clients/${(0, _geekmidas_manifest.kebabCase)(id)}.js';`),
15327
+ ...auths.length ? [`import { createAuthClient } from 'better-auth/client';`] : [],
15328
+ ...plugins.length ? [`import { ${plugins.join(", ")} } from 'better-auth/client/plugins';`] : [],
15329
+ ...drivers.imports ? [drivers.imports] : []
15330
+ ];
15331
+ const url = (id) => `manifest.env[${JSON.stringify((0, _geekmidas_manifest.provideKey)(id, "url"))}]!`;
15332
+ const members = [...surfaces.map(({ id, secured }) => ` /** \`${id}\`, at ${(0, _geekmidas_manifest.provideKey)(id, "url")}. */
15333
+ readonly ${propertyOf(id)} = create${id}({
15334
+ baseURL: ${url(id)},
15335
+ fetch: this.fetch,${secured ? `
15336
+ // Served in-process: no authorizer runs, so nothing is signed. A scheme
15337
+ // with no strategy sends its request without credentials.
15338
+ authStrategies: {} as never,` : ""}
15339
+ });`), ...auths.map((auth) => ` /** \`${auth.id}\`, at ${(0, _geekmidas_manifest.provideKey)(auth.id, "url")}. */
15340
+ readonly ${propertyOf(auth.id)} = createAuthClient({
15341
+ baseURL: \`\${${url(auth.id)}}${auth.basePath}\`,
15342
+ plugins: [${auth.plugins.map((plugin) => `${plugin}()`).join(", ")}],
15343
+ fetchOptions: { customFetchImpl: this.fetch },
15344
+ });`)];
15345
+ return `// Generated by \`gkm test\` from the app's constructs — do not edit.
15346
+ ${imports.join("\n")}
15347
+
15348
+ ${drivers.setup ? `// The drivers the app's server entry registers, registered the same way.\n${drivers.setup}\n\n` : ""}const manifest = loadTestManifest(new URL('./manifest.json', import.meta.url));
15349
+
15350
+ /** A browser with a client for every surface the app declares. */
15351
+ export class Browser extends TestBrowser {
15352
+ ${members.join("\n\n")}
15353
+ }
15354
+
15355
+ /** \`it\`, for a test that drives the app the way it runs deployed. */
15356
+ export const it = featureTest${database ? "<Browser, DatabaseOf<typeof __database>>" : ""}({ manifest, browser: Browser });
15357
+ `;
15358
+ }
15359
+ //#endregion
15141
15360
  //#region src/test/index.ts
15142
15361
  /**
15143
15362
  * Run tests with secrets, dependency URLs, and .env files loaded.
@@ -15156,7 +15375,7 @@ async function testCommand(options = {}) {
15156
15375
  if (defaultEnv.loaded.length > 0) console.log(` 📦 Loaded env: ${defaultEnv.loaded.join(", ")}`);
15157
15376
  const result = await require_credentials.prepareEntryCredentials({
15158
15377
  stage,
15159
- startDocker: true,
15378
+ startDocker: !options.prepare,
15160
15379
  secretsFileName: "test-secrets.json",
15161
15380
  resolveDockerPorts: "full",
15162
15381
  reconcileStage: "test"
@@ -15178,6 +15397,19 @@ async function testCommand(options = {}) {
15178
15397
  const gkmDir = (0, node_path.join)(cwd, ".gkm");
15179
15398
  const preloadPath = (0, node_path.join)(gkmDir, "test-credentials-preload.ts");
15180
15399
  await require_credentials.createCredentialsPreload(preloadPath, result.secretsJsonPath);
15400
+ const workspace = await require_config.loadWorkspaceConfig(cwd).then((loaded) => loaded.workspace).catch(() => void 0);
15401
+ const manifestPath = workspace && require_credentials.usesConstructs(workspace) ? await writeTestHarness({
15402
+ root: workspace.root,
15403
+ targets: [workspace.root, ...Object.values(workspace.apps).map((app) => (0, node_path.isAbsolute)(app.path) ? app.path : (0, node_path.join)(workspace.root, app.path))],
15404
+ patterns: require_credentials.constructGlobs(workspace),
15405
+ cacheBackend: require_credentials.backendsOf(workspace).cache,
15406
+ stage: require_workspace.TEST_STAGE,
15407
+ env: finalCredentials
15408
+ }) : void 0;
15409
+ if (options.prepare) {
15410
+ console.log(manifestPath ? ` 🧪 Test harness written beside ${manifestPath}` : " 🧪 Nothing to prepare: this project declares no constructs");
15411
+ return;
15412
+ }
15181
15413
  const nodeOptions = [
15182
15414
  process.env.NODE_OPTIONS ?? "",
15183
15415
  "--import=tsx",
@@ -15195,6 +15427,7 @@ async function testCommand(options = {}) {
15195
15427
  env: {
15196
15428
  ...process.env,
15197
15429
  ...finalCredentials,
15430
+ ...manifestPath ? { [TEST_MANIFEST_ENV]: manifestPath } : {},
15198
15431
  NODE_ENV: "test",
15199
15432
  NODE_OPTIONS: nodeOptions
15200
15433
  }
@@ -15640,7 +15873,7 @@ program.command("exec").description("Run a command with secrets injected into Cr
15640
15873
  process.exit(1);
15641
15874
  }
15642
15875
  });
15643
- program.command("test").description("Run tests with secrets loaded from environment").option("--stage <stage>", "Stage to load secrets from (default: stages.local)").option("--run", "Run tests once without watch mode").option("--watch", "Enable watch mode").option("--coverage", "Generate coverage report").option("--ui", "Open Vitest UI").option("--auto-setup", "Generate a fresh stage (secrets + key) from the workspace config when none exists (for CI; also via GKM_AUTO_SETUP)").argument("[pattern]", "Pattern to filter tests").action(async (pattern, options) => {
15876
+ program.command("test").description("Run tests with secrets loaded from environment").option("--stage <stage>", "Stage to load secrets from (default: stages.local)").option("--run", "Run tests once without watch mode").option("--watch", "Enable watch mode").option("--coverage", "Generate coverage report").option("--ui", "Open Vitest UI").option("--auto-setup", "Generate a fresh stage (secrets + key) from the workspace config when none exists (for CI; also via GKM_AUTO_SETUP)").option("--prepare", "Write the test manifest and #test harness, then stop — for a typecheck that runs before the suite").argument("[pattern]", "Pattern to filter tests").action(async (pattern, options) => {
15644
15877
  try {
15645
15878
  const globalOptions = program.opts();
15646
15879
  if (globalOptions.cwd) process.chdir(globalOptions.cwd);
@@ -15772,7 +16005,7 @@ program.command("secrets:push").description("Send a deployed stage's secrets to
15772
16005
  const globalOptions = program.opts();
15773
16006
  if (globalOptions.cwd) process.chdir(globalOptions.cwd);
15774
16007
  const { loadWorkspaceConfig } = await Promise.resolve().then(() => require("./config.cjs"));
15775
- const { pushStageSecrets } = await Promise.resolve().then(() => require("./transfer-CXoyQZbB.cjs")).then((n) => n.transfer_exports);
16008
+ const { pushStageSecrets } = await Promise.resolve().then(() => require("./transfer-BZbyaV3I.cjs")).then((n) => n.transfer_exports);
15776
16009
  const { workspace } = await loadWorkspaceConfig();
15777
16010
  const { addedKeys } = await pushStageSecrets(workspace, options.stage, { profile: options.profile });
15778
16011
  for (const key of addedKeys) console.log(` + ${key} (reconciled)`);
@@ -15787,7 +16020,7 @@ program.command("secrets:pull").description("Bring a deployed stage's secrets fr
15787
16020
  const globalOptions = program.opts();
15788
16021
  if (globalOptions.cwd) process.chdir(globalOptions.cwd);
15789
16022
  const { loadWorkspaceConfig } = await Promise.resolve().then(() => require("./config.cjs"));
15790
- const { pullStageSecrets } = await Promise.resolve().then(() => require("./transfer-CXoyQZbB.cjs")).then((n) => n.transfer_exports);
16023
+ const { pullStageSecrets } = await Promise.resolve().then(() => require("./transfer-BZbyaV3I.cjs")).then((n) => n.transfer_exports);
15791
16024
  const { workspace } = await loadWorkspaceConfig();
15792
16025
  const { addedKeys } = await pullStageSecrets(workspace, options.stage, { profile: options.profile });
15793
16026
  for (const key of addedKeys) console.log(` + ${key} (reconciled)`);
@@ -15811,7 +16044,7 @@ program.command("secrets:reconcile").description("Backfill missing custom secret
15811
16044
  console.error(`No secrets found for stage "${stage}". Run "gkm secrets:init --stage ${stage}" first.`);
15812
16045
  process.exit(1);
15813
16046
  }
15814
- const { derivedContainers } = await Promise.resolve().then(() => require("./credentials-BfmmB4WD.cjs")).then((n) => n.workspace_exports);
16047
+ const { derivedContainers } = await Promise.resolve().then(() => require("./credentials-COrSpZfF.cjs")).then((n) => n.workspace_exports);
15815
16048
  const result = reconcileMissingSecrets(secrets, workspace, await derivedContainers(workspace, stage));
15816
16049
  if (!result) {
15817
16050
  console.log(`\n✓ Secrets for stage "${stage}" are up-to-date`);
@@ -15870,7 +16103,7 @@ program.command("deploy:github").description("Let GitHub Actions deploy a stage:
15870
16103
  try {
15871
16104
  const globalOptions = program.opts();
15872
16105
  if (globalOptions.cwd) process.chdir(globalOptions.cwd);
15873
- const { deployGithubCommand } = await Promise.resolve().then(() => require("./github-Bho-C6Zg.cjs"));
16106
+ const { deployGithubCommand } = await Promise.resolve().then(() => require("./github-BpsnSDw2.cjs"));
15874
16107
  await deployGithubCommand(options);
15875
16108
  } catch (error) {
15876
16109
  console.error(formatError(error));