@geekmidas/cli 10.0.0-alpha.78 → 10.0.0-alpha.80

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 (129) hide show
  1. package/dist/{add-D2XKszYP.mjs → add-CIxT-Iq6.mjs} +2 -2
  2. package/dist/{add-D2XKszYP.mjs.map → add-CIxT-Iq6.mjs.map} +1 -1
  3. package/dist/{add-BvOICikp.cjs → add-DJ0VE-y-.cjs} +7 -7
  4. package/dist/{add-BvOICikp.cjs.map → add-DJ0VE-y-.cjs.map} +1 -1
  5. package/dist/{aws-Bja4zGSs.mjs → aws-B-6uEhgP.mjs} +8 -2
  6. package/dist/{aws-Bja4zGSs.mjs.map → aws-B-6uEhgP.mjs.map} +1 -1
  7. package/dist/{aws-CQAuluiu.cjs → aws-BTawF0F-.cjs} +19 -2
  8. package/dist/{aws-CQAuluiu.cjs.map → aws-BTawF0F-.cjs.map} +1 -1
  9. package/dist/{bundler-C6T-1OLT.cjs → bundler-BlbSLFLn.cjs} +3 -3
  10. package/dist/{bundler-C6T-1OLT.cjs.map → bundler-BlbSLFLn.cjs.map} +1 -1
  11. package/dist/{bundler-CtHzKqnZ.mjs → bundler-D4pl87A5.mjs} +3 -3
  12. package/dist/{bundler-CtHzKqnZ.mjs.map → bundler-D4pl87A5.mjs.map} +1 -1
  13. package/dist/{cli-BgPyhx1i.mjs → cli-7aLfgIGt.mjs} +3 -3
  14. package/dist/{cli-BgPyhx1i.mjs.map → cli-7aLfgIGt.mjs.map} +1 -1
  15. package/dist/{cli-K6Vj_pPW.cjs → cli-BkNZBe_-.cjs} +4 -4
  16. package/dist/{cli-K6Vj_pPW.cjs.map → cli-BkNZBe_-.cjs.map} +1 -1
  17. package/dist/{compose-B7MC19eC.cjs → compose-Bn4OJONR.cjs} +88 -60
  18. package/dist/{compose-B7MC19eC.cjs.map → compose-Bn4OJONR.cjs.map} +1 -1
  19. package/dist/{compose-DByK353T.mjs → compose-n7K8H5j8.mjs} +36 -8
  20. package/dist/{compose-DByK353T.mjs.map → compose-n7K8H5j8.mjs.map} +1 -1
  21. package/dist/{config-Bql0AmJt.d.mts → config-L_6NivCp.d.mts} +3 -3
  22. package/dist/{config-Bql0AmJt.d.mts.map → config-L_6NivCp.d.mts.map} +1 -1
  23. package/dist/{config-DlNpHK8p.d.cts → config-Mr4rcXFC.d.cts} +3 -3
  24. package/dist/{config-DlNpHK8p.d.cts.map → config-Mr4rcXFC.d.cts.map} +1 -1
  25. package/dist/config.d.cts +3 -3
  26. package/dist/config.d.mts +3 -3
  27. package/dist/{databases-C2p5LGAp.cjs → databases-BY-pEImp.cjs} +185 -7
  28. package/dist/databases-BY-pEImp.cjs.map +1 -0
  29. package/dist/{databases-hUHTuwhx.mjs → databases-CzszQV0N.mjs} +153 -5
  30. package/dist/databases-CzszQV0N.mjs.map +1 -0
  31. package/dist/deploy/public.cjs +12 -11
  32. package/dist/deploy/public.d.cts +19 -3
  33. package/dist/deploy/public.d.cts.map +1 -1
  34. package/dist/deploy/public.d.mts +19 -3
  35. package/dist/deploy/public.d.mts.map +1 -1
  36. package/dist/deploy/public.mjs +6 -6
  37. package/dist/{deploy-BerP7ppB.mjs → deploy-DK4Y6ev4.mjs} +3 -3
  38. package/dist/{deploy-BerP7ppB.mjs.map → deploy-DK4Y6ev4.mjs.map} +1 -1
  39. package/dist/{deploy-Dt42xiQA.cjs → deploy-Ppnh8MHS.cjs} +9 -9
  40. package/dist/{deploy-Dt42xiQA.cjs.map → deploy-Ppnh8MHS.cjs.map} +1 -1
  41. package/dist/{dokploy-ssZQRK2C.mjs → dokploy-Bjq05wkw.mjs} +2 -2
  42. package/dist/{dokploy-ssZQRK2C.mjs.map → dokploy-Bjq05wkw.mjs.map} +1 -1
  43. package/dist/{dokploy-NG9UrVrP.cjs → dokploy-CJvdoNc3.cjs} +2 -2
  44. package/dist/{dokploy-NG9UrVrP.cjs.map → dokploy-CJvdoNc3.cjs.map} +1 -1
  45. package/dist/{encryption-De6MN0O5.mjs → encryption-BrsOJFFz.mjs} +2 -2
  46. package/dist/{encryption-De6MN0O5.mjs.map → encryption-BrsOJFFz.mjs.map} +1 -1
  47. package/dist/{encryption-CbMI24fI.cjs → encryption-CAyR6D7B.cjs} +5 -5
  48. package/dist/{encryption-CbMI24fI.cjs.map → encryption-CAyR6D7B.cjs.map} +1 -1
  49. package/dist/{engine-CoCsNoW_.cjs → engine-DzBZR5D0.cjs} +118 -82
  50. package/dist/engine-DzBZR5D0.cjs.map +1 -0
  51. package/dist/{engine-DOjGIgl4.mjs → engine-ba9CvjTo.mjs} +53 -17
  52. package/dist/engine-ba9CvjTo.mjs.map +1 -0
  53. package/dist/github-BLjU59Ye.cjs +669 -0
  54. package/dist/github-BLjU59Ye.cjs.map +1 -0
  55. package/dist/github-CVdbVlT5.mjs +669 -0
  56. package/dist/github-CVdbVlT5.mjs.map +1 -0
  57. package/dist/{index-BXO0vlme.d.mts → index-C0UmP_lg.d.mts} +2 -2
  58. package/dist/{index-BXO0vlme.d.mts.map → index-C0UmP_lg.d.mts.map} +1 -1
  59. package/dist/{index-Rs0Fua-q.d.cts → index-DTEPwLml.d.cts} +2 -2
  60. package/dist/{index-Rs0Fua-q.d.cts.map → index-DTEPwLml.d.cts.map} +1 -1
  61. package/dist/index.cjs +114 -114
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.mjs +41 -41
  64. package/dist/index.mjs.map +1 -1
  65. package/dist/{migrate-Cgoy58Sh.cjs → migrate-DkB833Jj.cjs} +8 -9
  66. package/dist/{migrate-Cgoy58Sh.cjs.map → migrate-DkB833Jj.cjs.map} +1 -1
  67. package/dist/{migrate-CNKaQl3K.mjs → migrate-DlBgATa-.mjs} +3 -4
  68. package/dist/{migrate-CNKaQl3K.mjs.map → migrate-DlBgATa-.mjs.map} +1 -1
  69. package/dist/{migrate-B4GBvCNY.cjs → migrate-iEdyEx4S.cjs} +4 -4
  70. package/dist/{migrate-B4GBvCNY.cjs.map → migrate-iEdyEx4S.cjs.map} +1 -1
  71. package/dist/{migrate-BQ4wVKq_.mjs → migrate-pfu4aYzX.mjs} +2 -2
  72. package/dist/{migrate-BQ4wVKq_.mjs.map → migrate-pfu4aYzX.mjs.map} +1 -1
  73. package/dist/openapi.d.cts +1 -1
  74. package/dist/openapi.d.mts +1 -1
  75. package/dist/reconcile/public.d.cts +1 -1
  76. package/dist/reconcile/public.d.mts +1 -1
  77. package/dist/{resolve-CEaqRBzY.cjs → resolve-4_5N67Fk.cjs} +3 -3
  78. package/dist/{resolve-CEaqRBzY.cjs.map → resolve-4_5N67Fk.cjs.map} +1 -1
  79. package/dist/{resolve-mvaystiE.mjs → resolve-CQPn66jr.mjs} +3 -3
  80. package/dist/{resolve-mvaystiE.mjs.map → resolve-CQPn66jr.mjs.map} +1 -1
  81. package/dist/{rollback-S2C-Y9pB.mjs → rollback-C0cbdsM-.mjs} +3 -3
  82. package/dist/{rollback-S2C-Y9pB.mjs.map → rollback-C0cbdsM-.mjs.map} +1 -1
  83. package/dist/{rollback-F3P-rA-r.cjs → rollback-CgYUPLbq.cjs} +5 -5
  84. package/dist/{rollback-F3P-rA-r.cjs.map → rollback-CgYUPLbq.cjs.map} +1 -1
  85. package/dist/{runtime-D9AxGzrw.d.cts → runtime-D6A-C6zh.d.cts} +2 -2
  86. package/dist/{runtime-D9AxGzrw.d.cts.map → runtime-D6A-C6zh.d.cts.map} +1 -1
  87. package/dist/{runtime-Dflki3Vs.d.mts → runtime-ekxfPNM-.d.mts} +2 -2
  88. package/dist/{runtime-Dflki3Vs.d.mts.map → runtime-ekxfPNM-.d.mts.map} +1 -1
  89. package/dist/sandbox/migrate-worker.cjs +22 -8
  90. package/dist/sandbox/migrate-worker.cjs.map +1 -1
  91. package/dist/sandbox/migrate-worker.mjs +22 -8
  92. package/dist/sandbox/migrate-worker.mjs.map +1 -1
  93. package/dist/{secretsManager-Ti0oZwsS.mjs → secretsManager-Chs9VV2r.mjs} +8 -2
  94. package/dist/{secretsManager-Ti0oZwsS.mjs.map → secretsManager-Chs9VV2r.mjs.map} +1 -1
  95. package/dist/{secretsManager-DUXW3fQt.cjs → secretsManager-DcMlHnRC.cjs} +19 -2
  96. package/dist/{secretsManager-DUXW3fQt.cjs.map → secretsManager-DcMlHnRC.cjs.map} +1 -1
  97. package/dist/{stale-C5FqIVc8.mjs → seeds-BdkFpW0P.mjs} +64 -6
  98. package/dist/seeds-BdkFpW0P.mjs.map +1 -0
  99. package/dist/{stale-BsiPJI7Y.cjs → seeds-ZljwYV_p.cjs} +81 -5
  100. package/dist/seeds-ZljwYV_p.cjs.map +1 -0
  101. package/dist/sniffer-BjG-1mlD.cjs.map +1 -1
  102. package/dist/sniffer-ByWtH28i.mjs.map +1 -1
  103. package/dist/target/public.cjs +1 -1
  104. package/dist/target/public.d.cts +2 -2
  105. package/dist/target/public.d.mts +2 -2
  106. package/dist/target/public.mjs +1 -1
  107. package/dist/{types-DKxkXsKC.d.mts → types-BzCavjGt.d.mts} +29 -2
  108. package/dist/types-BzCavjGt.d.mts.map +1 -0
  109. package/dist/{types-ByY0zi3n.d.cts → types-DZtj9jeI.d.cts} +29 -2
  110. package/dist/types-DZtj9jeI.d.cts.map +1 -0
  111. package/dist/workspace/index.d.cts +2 -2
  112. package/dist/workspace/index.d.mts +2 -2
  113. package/package.json +15 -15
  114. package/dist/databases-C2p5LGAp.cjs.map +0 -1
  115. package/dist/databases-hUHTuwhx.mjs.map +0 -1
  116. package/dist/engine-CoCsNoW_.cjs.map +0 -1
  117. package/dist/engine-DOjGIgl4.mjs.map +0 -1
  118. package/dist/github-CwX9z89E.mjs +0 -213
  119. package/dist/github-CwX9z89E.mjs.map +0 -1
  120. package/dist/github-D9vGqdLk.cjs +0 -213
  121. package/dist/github-D9vGqdLk.cjs.map +0 -1
  122. package/dist/provider-B3Sv_a74.cjs +0 -173
  123. package/dist/provider-B3Sv_a74.cjs.map +0 -1
  124. package/dist/provider-D7rQzzzf.mjs +0 -138
  125. package/dist/provider-D7rQzzzf.mjs.map +0 -1
  126. package/dist/stale-BsiPJI7Y.cjs.map +0 -1
  127. package/dist/stale-C5FqIVc8.mjs.map +0 -1
  128. package/dist/types-ByY0zi3n.d.cts.map +0 -1
  129. package/dist/types-DKxkXsKC.d.mts.map +0 -1
@@ -1,213 +0,0 @@
1
- import { k as assertDeployedStage } from "./workspace-BBdqmkch.mjs";
2
- import { loadWorkspaceConfig } from "./config.mjs";
3
- import { $t as readKey, Gt as isRemoteStore, Kt as secretsStoreFor, Xt as getKeyPath, Zt as keystoreProject } from "./stale-C5FqIVc8.mjs";
4
- import { execFileSync } from "node:child_process";
5
- import { AttachRolePolicyCommand, CreateOpenIDConnectProviderCommand, CreateRoleCommand, GetRoleCommand, IAMClient, ListOpenIDConnectProvidersCommand, UpdateAssumeRolePolicyCommand } from "@aws-sdk/client-iam";
6
- //#region src/deploy/github.ts
7
- /**
8
- * `gkm deploy:github` — let GitHub Actions deploy one stage, with no keys.
9
- *
10
- * A stage usually lives in its own AWS account — staging in one, production in
11
- * another — so this runs once per stage, with that account's profile:
12
- *
13
- * gkm deploy:github --stage staging --profile acme-dev
14
- * gkm deploy:github --stage prod --profile acme-prod
15
- *
16
- * In the stage's account it makes sure GitHub's OIDC provider exists, and a
17
- * role that only this repository's `<stage>` environment can assume. On
18
- * GitHub it creates that environment and gives it what the generated deploy
19
- * workflow reads: `AWS_ROLE_ARN`, and — when the stage's secrets are kept in
20
- * the local file — its key as `GKM_SECRETS_KEY`. With `secrets.store` set to
21
- * SSM or Secrets Manager the deploy job reads them with the role instead, so
22
- * no key is handed to GitHub, and this checks the stage's store in the same
23
- * account, with the same profile. Re-running it converges rather than duplicating.
24
- */
25
- const logger = console;
26
- const GITHUB_OIDC_HOST = "token.actions.githubusercontent.com";
27
- const AUDIENCE = "sts.amazonaws.com";
28
- const defaultGh = (args, input) => execFileSync("gh", args, {
29
- encoding: "utf-8",
30
- ...input === void 0 ? {} : {
31
- input,
32
- stdio: [
33
- "pipe",
34
- "pipe",
35
- "pipe"
36
- ]
37
- }
38
- }).trim();
39
- /** The role a stage deploys as: `<project>-github-<stage>`, within IAM's 64. */
40
- function roleName(project, stage) {
41
- return `${project}-github-${stage}`.toLowerCase().replace(/[^a-z0-9+=,.@_-]/g, "-").slice(0, 64);
42
- }
43
- /**
44
- * Who may assume the role: a workflow job running in this repository's
45
- * `<stage>` environment, and nothing else — not another branch's job, not
46
- * another environment's. That is what keeps a staging deploy from using the
47
- * production role.
48
- */
49
- function trustPolicy(providerArn, repo, stage) {
50
- return JSON.stringify({
51
- Version: "2012-10-17",
52
- Statement: [{
53
- Effect: "Allow",
54
- Principal: { Federated: providerArn },
55
- Action: "sts:AssumeRoleWithWebIdentity",
56
- Condition: { StringEquals: {
57
- [`${GITHUB_OIDC_HOST}:aud`]: AUDIENCE,
58
- [`${GITHUB_OIDC_HOST}:sub`]: `repo:${repo}:environment:${stage}`
59
- } }
60
- }]
61
- });
62
- }
63
- /** GitHub's OIDC provider in this account, created if it is not there. */
64
- async function ensureOidcProvider(iam) {
65
- const { OpenIDConnectProviderList = [] } = await iam.send(new ListOpenIDConnectProvidersCommand({}));
66
- const existing = OpenIDConnectProviderList.find((p) => p.Arn?.endsWith(`oidc-provider/${GITHUB_OIDC_HOST}`))?.Arn;
67
- if (existing) return existing;
68
- return (await iam.send(new CreateOpenIDConnectProviderCommand({
69
- Url: `https://${GITHUB_OIDC_HOST}`,
70
- ClientIDList: [AUDIENCE]
71
- }))).OpenIDConnectProviderArn;
72
- }
73
- /** The deploy role, created or brought back to this trust and policy. */
74
- async function ensureRole(iam, name, trust, policyArn) {
75
- let arn;
76
- try {
77
- const { Role } = await iam.send(new GetRoleCommand({ RoleName: name }));
78
- await iam.send(new UpdateAssumeRolePolicyCommand({
79
- RoleName: name,
80
- PolicyDocument: trust
81
- }));
82
- arn = Role.Arn;
83
- } catch (error) {
84
- if (error.name !== "NoSuchEntityException") throw error;
85
- const { Role } = await iam.send(new CreateRoleCommand({
86
- RoleName: name,
87
- AssumeRolePolicyDocument: trust,
88
- Description: "Deploys from GitHub Actions (gkm deploy:github)",
89
- MaxSessionDuration: 7200
90
- }));
91
- arn = Role.Arn;
92
- }
93
- await iam.send(new AttachRolePolicyCommand({
94
- RoleName: name,
95
- PolicyArn: policyArn
96
- }));
97
- return arn;
98
- }
99
- /**
100
- * An IAM client for the stage's account.
101
- *
102
- * `fromIni` for a named profile, deliberately: it resolves exactly that
103
- * profile — keys, assume-role, `credential_process` or SSO, whichever
104
- * ~/.aws/config says — and never falls back to AWS_* in the environment. The
105
- * provider chain checks the environment first, so exported staging keys would
106
- * quietly win over `--profile prod` and the production role would land in the
107
- * staging account.
108
- */
109
- async function iamFor(profile, endpoint) {
110
- const config = { region: "us-east-1" };
111
- if (profile) {
112
- const { fromIni } = await import("@aws-sdk/credential-providers");
113
- config.credentials = fromIni({ profile });
114
- }
115
- if (endpoint) {
116
- config.endpoint = endpoint;
117
- config.credentials = {
118
- accessKeyId: "test",
119
- secretAccessKey: "test"
120
- };
121
- }
122
- return new IAMClient(config);
123
- }
124
- async function deployGithubCommand(options, deps = {}) {
125
- const gh = deps.gh ?? defaultGh;
126
- const { workspace } = await loadWorkspaceConfig(deps.cwd);
127
- assertDeployedStage(workspace.stages, options.stage);
128
- const repo = options.repo ?? gh([
129
- "repo",
130
- "view",
131
- "--json",
132
- "nameWithOwner",
133
- "-q",
134
- ".nameWithOwner"
135
- ]);
136
- const role = roleName(workspace.name, options.stage);
137
- const policyArn = options.policyArn ?? "arn:aws:iam::aws:policy/AdministratorAccess";
138
- const key = await readKey(options.stage, keystoreProject(workspace));
139
- const keyPath = getKeyPath(options.stage, keystoreProject(workspace));
140
- const hasKey = key !== null;
141
- const remote = isRemoteStore(workspace, options.stage);
142
- const store = await secretsStoreFor(workspace, options.stage, { ...options.profile ? { profile: options.profile } : {} });
143
- const hasSecrets = remote && await store.read(options.stage) !== null;
144
- const via = options.profile ? `profile "${options.profile}"` : "the default credentials";
145
- logger.log(`\n🔐 GitHub → AWS for stage "${options.stage}"\n`);
146
- logger.log(` Repository: ${repo}`);
147
- logger.log(` AWS profile: ${options.profile ?? "(default credentials)"}`);
148
- logger.log(` Role: ${role}`);
149
- logger.log(` Policy: ${policyArn}${options.policyArn ? "" : " (default; --policy-arn to narrow)"}`);
150
- logger.log(` Trusted by: repo:${repo}:environment:${options.stage} only`);
151
- if (remote) logger.log(` Secrets: ${hasSecrets ? `in the store (${store.name}), read with ${via}` : `none in the store yet — gkm secrets:set <KEY> '…' --stage ${options.stage}`}`);
152
- else logger.log(` Secrets key: ${hasKey ? keyPath : `none at ${keyPath} — run gkm secrets:init --stage ${options.stage} first`}`);
153
- if (options.dryRun) {
154
- logger.log("\n --dry-run: nothing changed.\n");
155
- return { repo };
156
- }
157
- const iam = deps.iam ?? await iamFor(options.profile);
158
- const roleArn = await ensureRole(iam, role, trustPolicy(await ensureOidcProvider(iam).catch((error) => {
159
- if (/SSO session/i.test(String(error?.message)) && options.profile) throw new SsoSessionExpired(options.profile);
160
- throw error;
161
- }), repo, options.stage), policyArn);
162
- logger.log(`\n ✓ AWS: ${roleArn}`);
163
- gh([
164
- "api",
165
- "--method",
166
- "PUT",
167
- `repos/${repo}/environments/${options.stage}`
168
- ]);
169
- gh([
170
- "variable",
171
- "set",
172
- "AWS_ROLE_ARN",
173
- "--env",
174
- options.stage,
175
- "--repo",
176
- repo,
177
- "--body",
178
- roleArn
179
- ]);
180
- logger.log(` ✓ GitHub: environment "${options.stage}", AWS_ROLE_ARN`);
181
- if (remote) {
182
- if (!hasSecrets) logger.log(` ⚠ The "${options.stage}" store holds no secrets yet; set them with gkm secrets:set <KEY> '…' --stage ${options.stage}${options.profile ? ` (AWS_PROFILE=${options.profile})` : ""}.`);
183
- } else if (hasKey) {
184
- gh([
185
- "secret",
186
- "set",
187
- "GKM_SECRETS_KEY",
188
- "--env",
189
- options.stage,
190
- "--repo",
191
- repo
192
- ], key);
193
- logger.log(" ✓ GitHub: GKM_SECRETS_KEY");
194
- } else logger.log(` ⚠ No secrets key for "${options.stage}"; run gkm secrets:init --stage ${options.stage}, then this again.`);
195
- logger.log(`\n Protect it: add required reviewers to the "${options.stage}" environment in the repository settings.\n`);
196
- return {
197
- roleArn,
198
- repo
199
- };
200
- }
201
- /** The profile's SSO login has lapsed; the fix is one command away. */
202
- var SsoSessionExpired = class extends Error {
203
- profile;
204
- constructor(profile) {
205
- super(`The SSO session for profile "${profile}" has expired or is invalid. Run: aws sso login --profile ${profile}`);
206
- this.profile = profile;
207
- this.name = "SsoSessionExpired";
208
- }
209
- };
210
- //#endregion
211
- export { deployGithubCommand };
212
-
213
- //# sourceMappingURL=github-CwX9z89E.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"github-CwX9z89E.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 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\nimport { execFileSync } from 'node:child_process';\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, keystoreProject, readKey } from '../secrets/keystore.js';\nimport { isRemoteStore, secretsStoreFor } from '../secrets/store.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\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\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 ? `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\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\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 };\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":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,SAAS;AAEf,MAAM,mBAAmB;AACzB,MAAM,WAAW;AAsBjB,M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,YACJ,OAAO,IACN,YAAY,QAAQ,MAAM,gFAAgF,QAAQ,QAAQ,QAAQ,UAAU,iBAAiB,QAAQ,QAAQ,KAAK,GAAG,EACtL;CAAA,OAEK,IAAI,QAAQ;EAElB,GACC;GACC;GACA;GACA;GACA;GACA,QAAQ;GACR;GACA;EACD,GACA,GACD;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,213 +0,0 @@
1
- const require_workspace = require("./workspace-Bp8FEkF-.cjs");
2
- const require_config = require("./config.cjs");
3
- const require_stale = require("./stale-BsiPJI7Y.cjs");
4
- let node_child_process = require("node:child_process");
5
- let _aws_sdk_client_iam = require("@aws-sdk/client-iam");
6
- //#region src/deploy/github.ts
7
- /**
8
- * `gkm deploy:github` — let GitHub Actions deploy one stage, with no keys.
9
- *
10
- * A stage usually lives in its own AWS account — staging in one, production in
11
- * another — so this runs once per stage, with that account's profile:
12
- *
13
- * gkm deploy:github --stage staging --profile acme-dev
14
- * gkm deploy:github --stage prod --profile acme-prod
15
- *
16
- * In the stage's account it makes sure GitHub's OIDC provider exists, and a
17
- * role that only this repository's `<stage>` environment can assume. On
18
- * GitHub it creates that environment and gives it what the generated deploy
19
- * workflow reads: `AWS_ROLE_ARN`, and — when the stage's secrets are kept in
20
- * the local file — its key as `GKM_SECRETS_KEY`. With `secrets.store` set to
21
- * SSM or Secrets Manager the deploy job reads them with the role instead, so
22
- * no key is handed to GitHub, and this checks the stage's store in the same
23
- * account, with the same profile. Re-running it converges rather than duplicating.
24
- */
25
- const logger = console;
26
- const GITHUB_OIDC_HOST = "token.actions.githubusercontent.com";
27
- const AUDIENCE = "sts.amazonaws.com";
28
- const defaultGh = (args, input) => (0, node_child_process.execFileSync)("gh", args, {
29
- encoding: "utf-8",
30
- ...input === void 0 ? {} : {
31
- input,
32
- stdio: [
33
- "pipe",
34
- "pipe",
35
- "pipe"
36
- ]
37
- }
38
- }).trim();
39
- /** The role a stage deploys as: `<project>-github-<stage>`, within IAM's 64. */
40
- function roleName(project, stage) {
41
- return `${project}-github-${stage}`.toLowerCase().replace(/[^a-z0-9+=,.@_-]/g, "-").slice(0, 64);
42
- }
43
- /**
44
- * Who may assume the role: a workflow job running in this repository's
45
- * `<stage>` environment, and nothing else — not another branch's job, not
46
- * another environment's. That is what keeps a staging deploy from using the
47
- * production role.
48
- */
49
- function trustPolicy(providerArn, repo, stage) {
50
- return JSON.stringify({
51
- Version: "2012-10-17",
52
- Statement: [{
53
- Effect: "Allow",
54
- Principal: { Federated: providerArn },
55
- Action: "sts:AssumeRoleWithWebIdentity",
56
- Condition: { StringEquals: {
57
- [`${GITHUB_OIDC_HOST}:aud`]: AUDIENCE,
58
- [`${GITHUB_OIDC_HOST}:sub`]: `repo:${repo}:environment:${stage}`
59
- } }
60
- }]
61
- });
62
- }
63
- /** GitHub's OIDC provider in this account, created if it is not there. */
64
- async function ensureOidcProvider(iam) {
65
- const { OpenIDConnectProviderList = [] } = await iam.send(new _aws_sdk_client_iam.ListOpenIDConnectProvidersCommand({}));
66
- const existing = OpenIDConnectProviderList.find((p) => p.Arn?.endsWith(`oidc-provider/${GITHUB_OIDC_HOST}`))?.Arn;
67
- if (existing) return existing;
68
- return (await iam.send(new _aws_sdk_client_iam.CreateOpenIDConnectProviderCommand({
69
- Url: `https://${GITHUB_OIDC_HOST}`,
70
- ClientIDList: [AUDIENCE]
71
- }))).OpenIDConnectProviderArn;
72
- }
73
- /** The deploy role, created or brought back to this trust and policy. */
74
- async function ensureRole(iam, name, trust, policyArn) {
75
- let arn;
76
- try {
77
- const { Role } = await iam.send(new _aws_sdk_client_iam.GetRoleCommand({ RoleName: name }));
78
- await iam.send(new _aws_sdk_client_iam.UpdateAssumeRolePolicyCommand({
79
- RoleName: name,
80
- PolicyDocument: trust
81
- }));
82
- arn = Role.Arn;
83
- } catch (error) {
84
- if (error.name !== "NoSuchEntityException") throw error;
85
- const { Role } = await iam.send(new _aws_sdk_client_iam.CreateRoleCommand({
86
- RoleName: name,
87
- AssumeRolePolicyDocument: trust,
88
- Description: "Deploys from GitHub Actions (gkm deploy:github)",
89
- MaxSessionDuration: 7200
90
- }));
91
- arn = Role.Arn;
92
- }
93
- await iam.send(new _aws_sdk_client_iam.AttachRolePolicyCommand({
94
- RoleName: name,
95
- PolicyArn: policyArn
96
- }));
97
- return arn;
98
- }
99
- /**
100
- * An IAM client for the stage's account.
101
- *
102
- * `fromIni` for a named profile, deliberately: it resolves exactly that
103
- * profile — keys, assume-role, `credential_process` or SSO, whichever
104
- * ~/.aws/config says — and never falls back to AWS_* in the environment. The
105
- * provider chain checks the environment first, so exported staging keys would
106
- * quietly win over `--profile prod` and the production role would land in the
107
- * staging account.
108
- */
109
- async function iamFor(profile, endpoint) {
110
- const config = { region: "us-east-1" };
111
- if (profile) {
112
- const { fromIni } = await import("@aws-sdk/credential-providers");
113
- config.credentials = fromIni({ profile });
114
- }
115
- if (endpoint) {
116
- config.endpoint = endpoint;
117
- config.credentials = {
118
- accessKeyId: "test",
119
- secretAccessKey: "test"
120
- };
121
- }
122
- return new _aws_sdk_client_iam.IAMClient(config);
123
- }
124
- async function deployGithubCommand(options, deps = {}) {
125
- const gh = deps.gh ?? defaultGh;
126
- const { workspace } = await require_config.loadWorkspaceConfig(deps.cwd);
127
- require_workspace.assertDeployedStage(workspace.stages, options.stage);
128
- const repo = options.repo ?? gh([
129
- "repo",
130
- "view",
131
- "--json",
132
- "nameWithOwner",
133
- "-q",
134
- ".nameWithOwner"
135
- ]);
136
- const role = roleName(workspace.name, options.stage);
137
- const policyArn = options.policyArn ?? "arn:aws:iam::aws:policy/AdministratorAccess";
138
- const key = await require_stale.readKey(options.stage, require_stale.keystoreProject(workspace));
139
- const keyPath = require_stale.getKeyPath(options.stage, require_stale.keystoreProject(workspace));
140
- const hasKey = key !== null;
141
- const remote = require_stale.isRemoteStore(workspace, options.stage);
142
- const store = await require_stale.secretsStoreFor(workspace, options.stage, { ...options.profile ? { profile: options.profile } : {} });
143
- const hasSecrets = remote && await store.read(options.stage) !== null;
144
- const via = options.profile ? `profile "${options.profile}"` : "the default credentials";
145
- logger.log(`\n🔐 GitHub → AWS for stage "${options.stage}"\n`);
146
- logger.log(` Repository: ${repo}`);
147
- logger.log(` AWS profile: ${options.profile ?? "(default credentials)"}`);
148
- logger.log(` Role: ${role}`);
149
- logger.log(` Policy: ${policyArn}${options.policyArn ? "" : " (default; --policy-arn to narrow)"}`);
150
- logger.log(` Trusted by: repo:${repo}:environment:${options.stage} only`);
151
- if (remote) logger.log(` Secrets: ${hasSecrets ? `in the store (${store.name}), read with ${via}` : `none in the store yet — gkm secrets:set <KEY> '…' --stage ${options.stage}`}`);
152
- else logger.log(` Secrets key: ${hasKey ? keyPath : `none at ${keyPath} — run gkm secrets:init --stage ${options.stage} first`}`);
153
- if (options.dryRun) {
154
- logger.log("\n --dry-run: nothing changed.\n");
155
- return { repo };
156
- }
157
- const iam = deps.iam ?? await iamFor(options.profile);
158
- const roleArn = await ensureRole(iam, role, trustPolicy(await ensureOidcProvider(iam).catch((error) => {
159
- if (/SSO session/i.test(String(error?.message)) && options.profile) throw new SsoSessionExpired(options.profile);
160
- throw error;
161
- }), repo, options.stage), policyArn);
162
- logger.log(`\n ✓ AWS: ${roleArn}`);
163
- gh([
164
- "api",
165
- "--method",
166
- "PUT",
167
- `repos/${repo}/environments/${options.stage}`
168
- ]);
169
- gh([
170
- "variable",
171
- "set",
172
- "AWS_ROLE_ARN",
173
- "--env",
174
- options.stage,
175
- "--repo",
176
- repo,
177
- "--body",
178
- roleArn
179
- ]);
180
- logger.log(` ✓ GitHub: environment "${options.stage}", AWS_ROLE_ARN`);
181
- if (remote) {
182
- if (!hasSecrets) logger.log(` ⚠ The "${options.stage}" store holds no secrets yet; set them with gkm secrets:set <KEY> '…' --stage ${options.stage}${options.profile ? ` (AWS_PROFILE=${options.profile})` : ""}.`);
183
- } else if (hasKey) {
184
- gh([
185
- "secret",
186
- "set",
187
- "GKM_SECRETS_KEY",
188
- "--env",
189
- options.stage,
190
- "--repo",
191
- repo
192
- ], key);
193
- logger.log(" ✓ GitHub: GKM_SECRETS_KEY");
194
- } else logger.log(` ⚠ No secrets key for "${options.stage}"; run gkm secrets:init --stage ${options.stage}, then this again.`);
195
- logger.log(`\n Protect it: add required reviewers to the "${options.stage}" environment in the repository settings.\n`);
196
- return {
197
- roleArn,
198
- repo
199
- };
200
- }
201
- /** The profile's SSO login has lapsed; the fix is one command away. */
202
- var SsoSessionExpired = class extends Error {
203
- profile;
204
- constructor(profile) {
205
- super(`The SSO session for profile "${profile}" has expired or is invalid. Run: aws sso login --profile ${profile}`);
206
- this.profile = profile;
207
- this.name = "SsoSessionExpired";
208
- }
209
- };
210
- //#endregion
211
- exports.deployGithubCommand = deployGithubCommand;
212
-
213
- //# sourceMappingURL=github-D9vGqdLk.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"github-D9vGqdLk.cjs","names":["execFileSync","ListOpenIDConnectProvidersCommand","CreateOpenIDConnectProviderCommand","GetRoleCommand","UpdateAssumeRolePolicyCommand","CreateRoleCommand","AttachRolePolicyCommand","IAMClient","loadWorkspaceConfig","readKey","keystoreProject","getKeyPath","isRemoteStore","secretsStoreFor"],"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 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\nimport { execFileSync } from 'node:child_process';\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, keystoreProject, readKey } from '../secrets/keystore.js';\nimport { isRemoteStore, secretsStoreFor } from '../secrets/store.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\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\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 ? `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\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\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 };\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":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,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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K,OAAO;CACb;AACD"}
@@ -1,173 +0,0 @@
1
- let node_path = require("node:path");
2
- let node_fs_promises = require("node:fs/promises");
3
- let node_url = require("node:url");
4
- //#region src/migrate/provider.ts
5
- /**
6
- * One construct's migrations and seeds, read from its folders.
7
- *
8
- * Two kinds of file, told apart by extension rather than by configuration: a
9
- * script exports `up` (and may export `down`) — or `seed(db, { stage })`, in
10
- * `seeds/` — and a
11
- * `.sql` file is run whole. The second is what makes a folder independent of
12
- * the client the app uses — Better Auth's schema is SQL whatever the
13
- * application queries with.
14
- */
15
- const SCRIPTS = /* @__PURE__ */ new Set([
16
- ".ts",
17
- ".mts",
18
- ".js",
19
- ".mjs"
20
- ]);
21
- /** Two files in one folder that would be one migration. */
22
- var DuplicateMigration = class extends Error {
23
- folder;
24
- migration;
25
- constructor(folder, migration) {
26
- super(`${folder} has two migrations named '${migration}' — a script and a .sql file with the same name. A migration is recorded by name, so only one of them could ever run; rename or remove the other.`);
27
- this.folder = folder;
28
- this.migration = migration;
29
- this.name = "DuplicateMigration";
30
- }
31
- };
32
- /** A script in a migrations folder that exports no `up`. */
33
- var MigrationHasNoUp = class extends Error {
34
- file;
35
- constructor(file) {
36
- super(`${file} is in a migrations folder but exports no \`up\` function. Export \`async function up(db: Kysely<unknown>)\`, or move the file out of the folder if it is not a migration.`);
37
- this.file = file;
38
- this.name = "MigrationHasNoUp";
39
- }
40
- };
41
- /** A script in a seeds folder that exports no `seed`. */
42
- var SeedHasNoSeed = class extends Error {
43
- file;
44
- constructor(file) {
45
- super(`${file} is in a seeds folder but exports no \`seed\` function. Export \`async function seed(db, { stage })\`, or move the file out of the folder if it is not a seed.`);
46
- this.file = file;
47
- this.name = "SeedHasNoSeed";
48
- }
49
- };
50
- /**
51
- * The migration files in a folder, by name, without reading them.
52
- *
53
- * Also what `gkm dev` compares against a construct's history to report what
54
- * is pending, which is why it is separate from loading them.
55
- */
56
- async function migrationFiles(folder) {
57
- const entries = await (0, node_fs_promises.readdir)(folder, { withFileTypes: true }).catch((error) => {
58
- if (error.code === "ENOENT") return [];
59
- throw error;
60
- });
61
- const files = /* @__PURE__ */ new Map();
62
- for (const entry of entries) {
63
- if (!entry.isFile() || !isMigration(entry.name)) continue;
64
- const name = entry.name.slice(0, -(0, node_path.extname)(entry.name).length);
65
- if (files.has(name)) throw new DuplicateMigration(folder, name);
66
- files.set(name, (0, node_path.join)(folder, entry.name));
67
- }
68
- return files;
69
- }
70
- /** A Kysely provider over one construct's folder. */
71
- function folderProvider(folder, raw) {
72
- return { async getMigrations() {
73
- const migrations = {};
74
- for (const [name, file] of await migrationFiles(folder)) migrations[name] = (0, node_path.extname)(file) === ".sql" ? await sqlMigration(file, raw) : await scriptMigration(file);
75
- return migrations;
76
- } };
77
- }
78
- /**
79
- * The seeds in a folder, loaded, in name order.
80
- *
81
- * Every one runs on every pass — there is no history to consult — so the order
82
- * is the only thing between two seeds where one reads what another writes.
83
- * Name them to sort that way.
84
- */
85
- async function loadSeeds(folder, raw) {
86
- const files = [...await migrationFiles(folder)].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
87
- const seeds = [];
88
- for (const [name, file] of files) seeds.push({
89
- name,
90
- run: (0, node_path.extname)(file) === ".sql" ? (await sqlMigration(file, raw)).up : await scriptSeed(file)
91
- });
92
- return seeds;
93
- }
94
- /**
95
- * A seed script, imported as it is on disk now.
96
- *
97
- * Keyed by its modification time: a seed is run again after it is edited, and
98
- * a process that has imported it once would otherwise run the old one.
99
- */
100
- async function scriptSeed(file) {
101
- const url = (0, node_url.pathToFileURL)(file);
102
- url.searchParams.set("mtime", String((await (0, node_fs_promises.stat)(file)).mtimeMs));
103
- const module = await import(url.href);
104
- if (typeof module.seed !== "function") throw new SeedHasNoSeed(file);
105
- return module.seed;
106
- }
107
- function isMigration(file) {
108
- if (file.endsWith(".d.ts")) return false;
109
- if (/\.(spec|test)\.[cm]?[jt]s$/.test(file)) return false;
110
- const extension = (0, node_path.extname)(file);
111
- return extension === ".sql" || SCRIPTS.has(extension);
112
- }
113
- async function scriptMigration(file) {
114
- const module = await import((0, node_url.pathToFileURL)(file).href);
115
- if (typeof module.up !== "function") throw new MigrationHasNoUp(file);
116
- return {
117
- up: module.up,
118
- ...typeof module.down === "function" ? { down: module.down } : {}
119
- };
120
- }
121
- /**
122
- * A `.sql` file, run whole.
123
- *
124
- * One query rather than split on `;`: with no parameters, Postgres takes
125
- * several statements in one message, and splitting by hand breaks on the first
126
- * `;` inside a string or a function body. There is no `down` — a generated
127
- * schema is rolled back by a migration that says how, not by guessing.
128
- */
129
- async function sqlMigration(file, raw) {
130
- const statements = await (0, node_fs_promises.readFile)(file, "utf-8");
131
- return { up: async (db) => {
132
- await raw.raw(statements).execute(db);
133
- } };
134
- }
135
- //#endregion
136
- Object.defineProperty(exports, "DuplicateMigration", {
137
- enumerable: true,
138
- get: function() {
139
- return DuplicateMigration;
140
- }
141
- });
142
- Object.defineProperty(exports, "MigrationHasNoUp", {
143
- enumerable: true,
144
- get: function() {
145
- return MigrationHasNoUp;
146
- }
147
- });
148
- Object.defineProperty(exports, "SeedHasNoSeed", {
149
- enumerable: true,
150
- get: function() {
151
- return SeedHasNoSeed;
152
- }
153
- });
154
- Object.defineProperty(exports, "folderProvider", {
155
- enumerable: true,
156
- get: function() {
157
- return folderProvider;
158
- }
159
- });
160
- Object.defineProperty(exports, "loadSeeds", {
161
- enumerable: true,
162
- get: function() {
163
- return loadSeeds;
164
- }
165
- });
166
- Object.defineProperty(exports, "migrationFiles", {
167
- enumerable: true,
168
- get: function() {
169
- return migrationFiles;
170
- }
171
- });
172
-
173
- //# sourceMappingURL=provider-B3Sv_a74.cjs.map