@geekmidas/cli 10.0.0-alpha.162 → 10.0.0-alpha.163
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.
- package/dist/{cli-Brr1IVq1.mjs → cli-BAn-gJ6S.mjs} +2 -2
- package/dist/{cli-Brr1IVq1.mjs.map → cli-BAn-gJ6S.mjs.map} +1 -1
- package/dist/{cli-D--xSSlK.cjs → cli-CI-wO3-w.cjs} +2 -2
- package/dist/{cli-D--xSSlK.cjs.map → cli-CI-wO3-w.cjs.map} +1 -1
- package/dist/deploy/public.cjs +1 -1
- package/dist/deploy/public.mjs +1 -1
- package/dist/{deploy-Bb-o2KYC.mjs → deploy-C4Qb-A-z.mjs} +26 -6
- package/dist/{deploy-Bb-o2KYC.mjs.map → deploy-C4Qb-A-z.mjs.map} +1 -1
- package/dist/{deploy-Ck0zXkM7.cjs → deploy-CGywNg5R.cjs} +26 -6
- package/dist/{deploy-Ck0zXkM7.cjs.map → deploy-CGywNg5R.cjs.map} +1 -1
- package/dist/{destroy-JHapr9UF.cjs → destroy-IUx8vz1q.cjs} +2 -2
- package/dist/{destroy-JHapr9UF.cjs.map → destroy-IUx8vz1q.cjs.map} +1 -1
- package/dist/{destroy-DIV6l_94.mjs → destroy-xjqqzAmU.mjs} +2 -2
- package/dist/{destroy-DIV6l_94.mjs.map → destroy-xjqqzAmU.mjs.map} +1 -1
- package/dist/{github-CRvdaD2Y.cjs → github-82k5-OZO.cjs} +4 -3
- package/dist/github-82k5-OZO.cjs.map +1 -0
- package/dist/{github-BOXn5NEP.mjs → github-DxgGIvq1.mjs} +4 -3
- package/dist/github-DxgGIvq1.mjs.map +1 -0
- package/dist/index.cjs +27 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +27 -27
- package/dist/index.mjs.map +1 -1
- package/dist/{serverSetup-BoxtHWkI.cjs → serverSetup-BXk8SGuz.cjs} +2 -2
- package/dist/{serverSetup-BoxtHWkI.cjs.map → serverSetup-BXk8SGuz.cjs.map} +1 -1
- package/dist/{serverSetup-DxcbUlwE.mjs → serverSetup-CzoKT3nH.mjs} +2 -2
- package/dist/{serverSetup-DxcbUlwE.mjs.map → serverSetup-CzoKT3nH.mjs.map} +1 -1
- package/package.json +15 -15
- package/dist/github-BOXn5NEP.mjs.map +0 -1
- package/dist/github-CRvdaD2Y.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"destroy-DIV6l_94.mjs","names":[],"sources":["../src/providers/s3/destroy.ts","../src/compose/destroy.ts"],"sourcesContent":["/**\n * What `gkm compose --destroy` deletes in the stage's AWS account: each\n * resource a deploy recorded in the stage's state, and only once it is\n * proven gkm's own for this stage.\n *\n * A record alone proves nothing — a deploy records what it found and adopted\n * exactly as what it made (a certificate for the host, a bucket with no\n * tags). So each is checked against what gkm marks its own with: the\n * `gkm:project` and `gkm:stage` tags on a bucket, a user, a certificate, a\n * distribution, a topic or a queue; the stage's own name on an origin access\n * control and a headers policy, which take no tags. What fails the check is\n * left where it is, and said so.\n *\n * Nothing here runs on its own: `planAwsDestroy` reads, and returns a step\n * per resource whose `remove()` the command calls — after the person typed\n * the stage's name — in the order AWS needs: a distribution disabled and\n * gone before its certificate, a user's keys and policies before the user,\n * a bucket emptied before it is deleted.\n */\n\nimport type { ResourceRecord } from '../../deploy/StateStore.js';\nimport { GkmError } from '../../errors.js';\nimport { type AwsProvisioning, awsClientConfig, awsEndpoint } from '../aws.js';\nimport { TAG_PROJECT, TAG_STAGE } from '../iam.js';\nimport { type CdnClients, cdnName, defaultCdnClients } from './cdn.js';\nimport { defaultClients } from './index.js';\nimport { IAM_USER_PATH } from './naming.js';\n\n/** What a destroy step is about, as the person reads it. */\nexport interface AwsDestroyStep {\n\t/** The state record it is kept as: forgotten once it is gone. */\n\tkey: string;\n\tlabel: string;\n\t/** Why it is not deleted. Absent for one that will be. */\n\tleftAlone?: string;\n\t/** Already gone from the account: only its record is forgotten. */\n\tgone?: boolean;\n\t/** Deleted along with its user's step: only its record is forgotten here. */\n\twithUser?: boolean;\n\t/** Deletes it. Absent when it is left alone or already gone. */\n\tremove?: () => Promise<void>;\n}\n\n/** A DNS record a resource here needs, worked out from the resource. */\nexport interface AwsDnsRecord {\n\thost: string;\n\ttype: 'CNAME';\n\tvalue: string;\n}\n\nexport interface AwsDestroyPlan {\n\t/** In the order they are removed. */\n\tsteps: AwsDestroyStep[];\n\t/**\n\t * The records the s3 provider wrote for what it deletes — a CDN's name, a\n\t * certificate's validation — which no state record names.\n\t */\n\tdns: AwsDnsRecord[];\n}\n\nexport interface AwsDestroyInput {\n\tresources: Record<string, ResourceRecord>;\n\t/** `deployIdentity(…).key` — what `gkm:project` holds. */\n\tidentityKey: string;\n\t/** `deployIdentity(…).scope` — what CDN resource names start with. */\n\tscope: string;\n\tstage: string;\n\tcredential: AwsProvisioning;\n\t/** How long a disabled distribution is waited on, and how often asked. */\n\twait?: { timeoutMs: number; intervalMs: number };\n\t/** For tests: where the clients come from. */\n\tclients?: {\n\t\ts3?: typeof defaultClients;\n\t\tcdn?: (credential: AwsProvisioning) => Promise<CdnClients>;\n\t};\n}\n\n/** The record types this plans. Every other is the command's to report. */\nexport const AWS_RESOURCE_TYPES = [\n\t'cloudfront-distribution',\n\t'cloudfront-oac',\n\t'cloudfront-headers',\n\t'acm-certificate',\n\t'sns-subscription',\n\t'sns-topic',\n\t'sqs-queue',\n\t'iam-access-key',\n\t'iam-user',\n\t's3-bucket',\n] as const;\n\n/** A distribution disabled before it is deleted can take this long. */\nconst DISABLE_WAIT = { timeoutMs: 45 * 60_000, intervalMs: 20_000 };\n\n/** A disabled distribution that never finished deploying. */\nexport class DistributionStillDeploying extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly waitedMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`CloudFront distribution ${id} was disabled, and is still deploying after ` +\n\t\t\t\t`${Math.round(waitedMs / 60_000)} minutes. CloudFront deletes only a ` +\n\t\t\t\t'disabled distribution that has finished deploying. Run the destroy ' +\n\t\t\t\t'again later: everything deleted so far is forgotten, and it carries ' +\n\t\t\t\t'on from here.',\n\t\t);\n\t\tthis.name = 'DistributionStillDeploying';\n\t}\n}\n\n/** What an AWS SDK error is called, whichever field carries it. */\nfunction errorName(error: unknown): string {\n\tconst e = error as { name?: string; Code?: string };\n\treturn e?.Code ?? e?.name ?? '';\n}\n\n/** A read whose \"there is none\" answer is one of `missing`. */\nasync function readOr<T>(\n\tread: () => Promise<T>,\n\tmissing: readonly string[],\n): Promise<T | undefined> {\n\ttry {\n\t\treturn await read();\n\t} catch (error) {\n\t\tif (missing.includes(errorName(error))) return undefined;\n\t\tthrow error;\n\t}\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Whether a tag list says gkm made it for this project's stage. */\nfunction ours(\n\ttags: readonly { Key?: string; Value?: string }[] | undefined,\n\tinput: Pick<AwsDestroyInput, 'identityKey' | 'stage'>,\n): boolean {\n\tconst of = (key: string) => tags?.find((t) => t.Key === key)?.Value;\n\treturn of(TAG_PROJECT) === input.identityKey && of(TAG_STAGE) === input.stage;\n}\n\nconst NOT_TAGGED =\n\t\"not tagged as this stage's (gkm:project, gkm:stage): gkm found it, it did not make it\";\n\n/** The id after the type in a record's key: `cloudfront-oac:Uploads` → `Uploads`. */\nfunction keyId(record: ResourceRecord): string {\n\treturn record.key.slice(record.key.indexOf(':') + 1);\n}\n\n/** The file server a CDN record is for: `cloudfront-headers:Uploads:cors` → `Uploads`. */\nfunction serverOf(record: ResourceRecord): string {\n\treturn keyId(record).split(':')[0] ?? '';\n}\n\n/**\n * Each AWS resource the stage's state records, checked, in the order it is\n * deleted — and the DNS records the deleted ones were given.\n */\nexport async function planAwsDestroy(\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyPlan> {\n\tconst steps: AwsDestroyStep[] = [];\n\tconst dns: AwsDnsRecord[] = [];\n\tconst records = Object.values(input.resources);\n\tconst of = (type: string) => records.filter((r) => r.type === type);\n\tconst wait = input.wait ?? DISABLE_WAIT;\n\n\tconst cdnRecords = [\n\t\t...of('cloudfront-distribution'),\n\t\t...of('cloudfront-oac'),\n\t\t...of('cloudfront-headers'),\n\t\t...of('acm-certificate'),\n\t];\n\tif (cdnRecords.length > 0) {\n\t\tconst cdn = await (input.clients?.cdn ?? defaultCdnClients)(\n\t\t\tinput.credential,\n\t\t);\n\t\t// A distribution left alone keeps what it uses: deleting its origin\n\t\t// access control, a headers policy or its certificate would break it.\n\t\tconst kept = new Map<string, string>();\n\t\tfor (const record of of('cloudfront-distribution')) {\n\t\t\tconst step = await distributionStep(cdn, record, input, wait, dns);\n\t\t\tif (step.leftAlone) kept.set(serverOf(record), step.label);\n\t\t\tsteps.push(step);\n\t\t}\n\t\tconst usedBy = async (\n\t\t\trecord: ResourceRecord,\n\t\t\tstep: () => Promise<AwsDestroyStep>,\n\t\t): Promise<AwsDestroyStep> => {\n\t\t\tconst holder = kept.get(serverOf(record));\n\t\t\tif (!holder) return step();\n\t\t\tconst label = (await step()).label;\n\t\t\treturn {\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel,\n\t\t\t\tleftAlone: `used by ${holder}, which is left alone`,\n\t\t\t};\n\t\t};\n\t\tfor (const record of of('cloudfront-oac')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => originAccessControlStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('cloudfront-headers')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => headersPolicyStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('acm-certificate')) {\n\t\t\t// Its validation record goes only with the certificate itself.\n\t\t\tconst found: AwsDnsRecord[] = [];\n\t\t\tconst step = await usedBy(record, () =>\n\t\t\t\tcertificateStep(cdn, record, input, found),\n\t\t\t);\n\t\t\tif (!step.leftAlone) dns.push(...found);\n\t\t\tsteps.push(step);\n\t\t}\n\t}\n\n\tconst eventRecords = [\n\t\t...of('sns-subscription'),\n\t\t...of('sns-topic'),\n\t\t...of('sqs-queue'),\n\t];\n\tif (eventRecords.length > 0) {\n\t\tconst events = await eventClients(input.credential, records);\n\t\tfor (const record of of('sns-subscription')) {\n\t\t\tsteps.push(subscriptionStep(events, record));\n\t\t}\n\t\tfor (const record of of('sns-topic')) {\n\t\t\tsteps.push(await topicStep(events, record, input));\n\t\t}\n\t\tfor (const record of of('sqs-queue')) {\n\t\t\tsteps.push(await queueStep(events, record, input));\n\t\t}\n\t}\n\n\tconst users = of('iam-user');\n\tconst keys = of('iam-access-key');\n\tconst buckets = of('s3-bucket');\n\tif (users.length + keys.length + buckets.length > 0) {\n\t\tconst global = await (input.clients?.s3 ?? defaultClients)(\n\t\t\tinput.credential,\n\t\t\tregionOf(buckets[0]) ?? 'us-east-1',\n\t\t);\n\t\tconst userSteps = new Map<string, AwsDestroyStep>();\n\t\tfor (const record of users) {\n\t\t\tconst step = await userStep(global, record, input);\n\t\t\tuserSteps.set(record.id ?? '', step);\n\t\t\tsteps.push(step);\n\t\t}\n\t\t// A key goes with its user, and is checked through it.\n\t\tfor (const record of keys) {\n\t\t\tconst user = (record.data as { user?: string } | undefined)?.user;\n\t\t\tconst owner = user ? userSteps.get(user) : undefined;\n\t\t\tsteps.push({\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel: `IAM access key ${record.id ?? ''} of ${user ?? 'an unknown user'}`,\n\t\t\t\t...(owner?.leftAlone\n\t\t\t\t\t? { leftAlone: `its user is left alone: ${owner.leftAlone}` }\n\t\t\t\t\t: owner\n\t\t\t\t\t\t? { withUser: true }\n\t\t\t\t\t\t: { leftAlone: 'its user is not one this stage recorded' }),\n\t\t\t});\n\t\t}\n\t\tfor (const record of buckets) {\n\t\t\tconst region = regionOf(record) ?? global.region;\n\t\t\tconst clients =\n\t\t\t\tregion === global.region\n\t\t\t\t\t? global\n\t\t\t\t\t: await (input.clients?.s3 ?? defaultClients)(\n\t\t\t\t\t\t\tinput.credential,\n\t\t\t\t\t\t\tregion,\n\t\t\t\t\t\t);\n\t\t\tsteps.push(await bucketStep(clients, record, input));\n\t\t}\n\t}\n\n\treturn { steps, dns };\n}\n\nfunction regionOf(record: ResourceRecord | undefined): string | undefined {\n\treturn (record?.data as { region?: string } | undefined)?.region;\n}\n\n// ---------------------------------------------------------------------------\n// CloudFront and ACM\n// ---------------------------------------------------------------------------\n\nasync function distributionStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\twait: { timeoutMs: number; intervalMs: number },\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetDistributionCommand({ Id: id })),\n\t\t['NoSuchDistribution'],\n\t);\n\tconst distribution = found?.Distribution;\n\tconst aliases = distribution?.DistributionConfig?.Aliases?.Items ?? [];\n\tconst label = `CloudFront distribution ${id}${aliases.length ? ` (${aliases.join(', ')})` : ''}`;\n\tif (!distribution) return { key: record.key, label, gone: true };\n\n\t// Its tags, or the comment gkm writes on every distribution it makes —\n\t// `gkm <project> <stage> <file server>`, which nothing else writes.\n\tconst tags = await cloudfront.send(\n\t\tnew CF.ListTagsForResourceCommand({ Resource: distribution.ARN }),\n\t);\n\tconst comment = `gkm ${input.identityKey} ${input.stage} ${serverOf(record)}`;\n\tconst marked =\n\t\tdistribution.DistributionConfig?.Comment === comment.slice(0, 128);\n\tif (!ours(tags.Tags?.Items, input) && !marked) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `${NOT_TAGGED}, and its comment is not \"${comment}\"`,\n\t\t};\n\t}\n\tfor (const host of aliases) {\n\t\tdns.push({ host, type: 'CNAME', value: distribution.DomainName ?? '' });\n\t}\n\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tlet current = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tif (current.DistributionConfig?.Enabled) {\n\t\t\t\tawait cloudfront.send(\n\t\t\t\t\tnew CF.UpdateDistributionCommand({\n\t\t\t\t\t\tId: id,\n\t\t\t\t\t\tIfMatch: current.ETag,\n\t\t\t\t\t\tDistributionConfig: {\n\t\t\t\t\t\t\t...current.DistributionConfig,\n\t\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst started = Date.now();\n\t\t\tfor (;;) {\n\t\t\t\tconst state = await cloudfront.send(\n\t\t\t\t\tnew CF.GetDistributionCommand({ Id: id }),\n\t\t\t\t);\n\t\t\t\tif (state.Distribution?.Status === 'Deployed') break;\n\t\t\t\tif (Date.now() - started > wait.timeoutMs) {\n\t\t\t\t\tthrow new DistributionStillDeploying(id, Date.now() - started);\n\t\t\t\t}\n\t\t\t\tawait sleep(wait.intervalMs);\n\t\t\t}\n\t\t\tcurrent = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteDistributionCommand({ Id: id, IfMatch: current.ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function originAccessControlStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst expected = cdnName(input.scope, input.stage, keyId(record));\n\tconst label = `CloudFront origin access control ${expected}`;\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetOriginAccessControlCommand({ Id: id })),\n\t\t['NoSuchOriginAccessControl'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.OriginAccessControl?.OriginAccessControlConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetOriginAccessControlCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteOriginAccessControlCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function headersPolicyStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\t// `cloudfront-headers:<server>:<kind>`\n\tconst [server = '', kind = ''] = keyId(record).split(':');\n\tconst expected = `${cdnName(input.scope, input.stage, server)}-${kind}`;\n\tconst label = `CloudFront response headers policy ${expected}`;\n\tconst found = await readOr(\n\t\t() =>\n\t\t\tcloudfront.send(new CF.GetResponseHeadersPolicyConfigCommand({ Id: id })),\n\t\t['NoSuchResponseHeadersPolicy'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.ResponseHeadersPolicyConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetResponseHeadersPolicyConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteResponseHeadersPolicyCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function certificateStep(\n\t{ ACM, acm }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst host = (record.data as { host?: string } | undefined)?.host ?? arn;\n\tconst label = `ACM certificate ${host} (us-east-1)`;\n\tconst found = await readOr(\n\t\t() => acm.send(new ACM.DescribeCertificateCommand({ CertificateArn: arn })),\n\t\t['ResourceNotFoundException'],\n\t);\n\tif (!found?.Certificate) return { key: record.key, label, gone: true };\n\tconst tags = await acm.send(\n\t\tnew ACM.ListTagsForCertificateCommand({ CertificateArn: arn }),\n\t);\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\tfor (const option of found.Certificate.DomainValidationOptions ?? []) {\n\t\tconst r = option.ResourceRecord;\n\t\tif (r?.Name && r.Value && r.Type === 'CNAME') {\n\t\t\tdns.push({ host: r.Name, type: 'CNAME', value: r.Value });\n\t\t}\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait acm.send(new ACM.DeleteCertificateCommand({ CertificateArn: arn }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// SNS and SQS\n// ---------------------------------------------------------------------------\n\ninterface EventClients {\n\tSNS: typeof import('@aws-sdk/client-sns');\n\tSQS: typeof import('@aws-sdk/client-sqs');\n\tsns: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sns')['SNSClient']>>;\n\tsqs: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sqs')['SQSClient']>>;\n}\n\nasync function eventClients(\n\tcredential: AwsProvisioning,\n\t_records: readonly ResourceRecord[],\n): Promise<EventClients> {\n\tconst SNS = await import('@aws-sdk/client-sns');\n\tconst SQS = await import('@aws-sdk/client-sqs');\n\tconst sns = new Map<string, InstanceType<typeof SNS.SNSClient>>();\n\tconst sqs = new Map<string, InstanceType<typeof SQS.SQSClient>>();\n\treturn {\n\t\tSNS,\n\t\tSQS,\n\t\tsns: async (region) => {\n\t\t\tif (!sns.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SNS');\n\t\t\t\tsns.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SNS.SNSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sns.get(region)!;\n\t\t},\n\t\tsqs: async (region) => {\n\t\t\tif (!sqs.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SQS');\n\t\t\t\tsqs.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SQS.SQSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sqs.get(region)!;\n\t\t},\n\t};\n}\n\n/** `arn:aws:sns:<region>:<account>:<name>` */\nfunction arnParts(arn: string) {\n\tconst [, , , region = '', account = '', ...rest] = arn.split(':');\n\treturn { region, account, name: rest.join(':') };\n}\n\nfunction subscriptionStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n): AwsDestroyStep {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS subscription ${keyId(record)}`;\n\t// Made by gkm, to its own push endpoint: a pending one has no ARN yet.\n\tif (!arn.startsWith('arn:')) return { key: record.key, label, gone: true };\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst client = await sns(arnParts(arn).region);\n\t\t\tawait readOr(\n\t\t\t\t() => client.send(new SNS.UnsubscribeCommand({ SubscriptionArn: arn })),\n\t\t\t\t['NotFound', 'NotFoundException'],\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function topicStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS topic ${arnParts(arn).name}`;\n\tconst client = await sns(arnParts(arn).region);\n\tconst tags = await readOr(\n\t\t() => client.send(new SNS.ListTagsForResourceCommand({ ResourceArn: arn })),\n\t\t[\n\t\t\t'NotFound',\n\t\t\t'NotFoundException',\n\t\t\t'ResourceNotFound',\n\t\t\t'ResourceNotFoundException',\n\t\t],\n\t);\n\tif (!tags) return { key: record.key, label, gone: true };\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SNS.DeleteTopicCommand({ TopicArn: arn }));\n\t\t},\n\t};\n}\n\nasync function queueStep(\n\t{ SQS, sqs }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst { region, account, name } = arnParts(arn);\n\tconst label = `SQS queue ${name}`;\n\tconst client = await sqs(region);\n\tconst url = await readOr(\n\t\t() =>\n\t\t\tclient.send(\n\t\t\t\tnew SQS.GetQueueUrlCommand({\n\t\t\t\t\tQueueName: name,\n\t\t\t\t\tQueueOwnerAWSAccountId: account,\n\t\t\t\t}),\n\t\t\t),\n\t\t['QueueDoesNotExist', 'AWS.SimpleQueueService.NonExistentQueue'],\n\t);\n\tif (!url?.QueueUrl) return { key: record.key, label, gone: true };\n\tconst queueUrl = url.QueueUrl;\n\tconst tags = await client.send(\n\t\tnew SQS.ListQueueTagsCommand({ QueueUrl: queueUrl }),\n\t);\n\tconst list = Object.entries(tags.Tags ?? {}).map(([Key, Value]) => ({\n\t\tKey,\n\t\tValue,\n\t}));\n\tif (!ours(list, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SQS.DeleteQueueCommand({ QueueUrl: queueUrl }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// IAM and S3\n// ---------------------------------------------------------------------------\n\ntype S3Clients = Awaited<ReturnType<typeof defaultClients>>;\n\nasync function userStep(\n\t{ IAM, iam }: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst name = record.id ?? '';\n\tconst label = `IAM user ${name}, its access keys and policies`;\n\tconst found = await readOr(\n\t\t() => iam.send(new IAM.GetUserCommand({ UserName: name })),\n\t\t['NoSuchEntity', 'NoSuchEntityException'],\n\t);\n\tif (!found?.User) return { key: record.key, label, gone: true };\n\tconst tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: name }));\n\tif (found.User.Path !== IAM_USER_PATH || !ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst keys = await iam.send(\n\t\t\t\tnew IAM.ListAccessKeysCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const key of keys.AccessKeyMetadata ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteAccessKeyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tAccessKeyId: key.AccessKeyId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst inline = await iam.send(\n\t\t\t\tnew IAM.ListUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of inline.PolicyNames ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyName: policy,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst attached = await iam.send(\n\t\t\t\tnew IAM.ListAttachedUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of attached.AttachedPolicies ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DetachUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyArn: policy.PolicyArn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait iam.send(new IAM.DeleteUserCommand({ UserName: name }));\n\t\t},\n\t};\n}\n\n/** Every object version and delete marker in a bucket, a page at a time. */\nasync function* bucketVersions({ S3, s3 }: S3Clients, bucket: string) {\n\tlet KeyMarker: string | undefined;\n\tlet VersionIdMarker: string | undefined;\n\tfor (;;) {\n\t\tconst page = await s3.send(\n\t\t\tnew S3.ListObjectVersionsCommand({\n\t\t\t\tBucket: bucket,\n\t\t\t\t...(KeyMarker ? { KeyMarker } : {}),\n\t\t\t\t...(VersionIdMarker ? { VersionIdMarker } : {}),\n\t\t\t}),\n\t\t);\n\t\tconst objects = [...(page.Versions ?? []), ...(page.DeleteMarkers ?? [])]\n\t\t\t.filter((o) => o.Key)\n\t\t\t.map((o) => ({\n\t\t\t\tKey: o.Key!,\n\t\t\t\t// `null` is the one version an unversioned bucket's object has:\n\t\t\t\t// named or not, the same object is deleted.\n\t\t\t\t...(o.VersionId && o.VersionId !== 'null'\n\t\t\t\t\t? { VersionId: o.VersionId }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\tif (objects.length > 0) yield objects;\n\t\tif (!page.IsTruncated) return;\n\t\tKeyMarker = page.NextKeyMarker;\n\t\tVersionIdMarker = page.NextVersionIdMarker;\n\t}\n}\n\nasync function bucketStep(\n\tclients: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst { S3, s3 } = clients;\n\tconst bucket = record.id ?? '';\n\tconst tagging = await readOr(\n\t\t() => s3.send(new S3.GetBucketTaggingCommand({ Bucket: bucket })),\n\t\t['NoSuchBucket', 'NoSuchTagSet', 'NoSuchTagSetError'],\n\t);\n\tconst exists = await readOr(\n\t\t() => s3.send(new S3.HeadBucketCommand({ Bucket: bucket })),\n\t\t['NotFound', 'NoSuchBucket'],\n\t);\n\tconst base = `S3 bucket ${bucket}`;\n\tif (!exists) return { key: record.key, label: base, gone: true };\n\tif (!ours(tagging?.TagSet, input)) {\n\t\treturn { key: record.key, label: base, leftAlone: NOT_TAGGED };\n\t}\n\tlet count = 0;\n\tfor await (const page of bucketVersions(clients, bucket))\n\t\tcount += page.length;\n\treturn {\n\t\tkey: record.key,\n\t\tlabel: `${base}, emptied first: ${count} object version${count === 1 ? '' : 's'}`,\n\t\tremove: async () => {\n\t\t\t// Until it lists nothing: deleting a version-less object in a bucket\n\t\t\t// whose versioning was suspended leaves a delete marker behind.\n\t\t\tfor (let pass = 0; pass < 5; pass++) {\n\t\t\t\tlet deleted = 0;\n\t\t\t\tfor await (const page of bucketVersions(clients, bucket)) {\n\t\t\t\t\t// At most a thousand a call.\n\t\t\t\t\tfor (let i = 0; i < page.length; i += 1000) {\n\t\t\t\t\t\tawait s3.send(\n\t\t\t\t\t\t\tnew S3.DeleteObjectsCommand({\n\t\t\t\t\t\t\t\tBucket: bucket,\n\t\t\t\t\t\t\t\tDelete: { Objects: page.slice(i, i + 1000), Quiet: true },\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tdeleted += page.length;\n\t\t\t\t}\n\t\t\t\tif (deleted === 0) break;\n\t\t\t}\n\t\t\tawait s3.send(new S3.DeleteBucketCommand({ Bucket: bucket }));\n\t\t},\n\t};\n}\n","/**\n * `gkm compose --stage <stage> --destroy`: everything a deploy made for the\n * stage, deleted for good.\n *\n * The one thing in gkm that deletes what a deploy created — a deploy itself\n * never does. So it is careful in three ways:\n *\n * - **Only what is provably gkm's.** Each AWS resource is checked against\n * what gkm marks its own with before it is deleted (see\n * `providers/s3/destroy.ts`); a DNS record only while it still holds the\n * value gkm wrote. What fails is listed, and left where it is.\n * - **Only with a person typing the stage.** The whole plan is printed\n * first, then the compose project's name — `<project>-<stage>` — has to be\n * typed back. Nothing skips that: there is no flag that answers it, and\n * with no terminal to ask at it refuses before reading anything.\n * - **Resumable.** Each resource's record is forgotten as soon as it is gone,\n * so a run that stops part way — a distribution still deploying — carries\n * on from there when it is run again.\n *\n * What other stages or projects share is never touched: the project bucket\n * that holds every stage's state, the shared Traefik edge, the server's own\n * setup (`gkm compose:server`). The stage's secrets are kept unless\n * `--secrets` is passed.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { loadWorkspaceConfig } from '../config';\nimport {\n\ttype CredentialProvider,\n\tstoredCredentials,\n} from '../deploy/credentials.js';\nimport { dnsRecordFqdn, dnsResources } from '../deploy/dnsResources.js';\nimport { deployIdentity } from '../deploy/identity.js';\nimport { createStateStore, type StateStore } from '../deploy/StateStore.js';\nimport { GkmError } from '../errors';\nimport { canPrompt, prompt } from '../prompt';\nimport {\n\ttype AwsProvisioning,\n\tawsProvisioningCredentials,\n} from '../providers/aws.js';\nimport {\n\tAWS_RESOURCE_TYPES,\n\ttype AwsDestroyInput,\n\ttype AwsDestroyStep,\n\tplanAwsDestroy,\n} from '../providers/s3/destroy.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { stackOverrideFile } from '../target/compose/index';\nimport type { DnsProvider } from '../target/dokploy/dns/DnsProvider.js';\nimport {\n\textractSubdomain,\n\tfindRootDomain,\n\tnormalizeDnsConfig,\n} from '../target/dokploy/dns/index.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport type {\n\tDnsProvider as DnsProviderConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport {\n\tdnsCredentials,\n\tpruneStackDns,\n\ttype RecordedDnsRecord,\n\trecordTtl,\n} from './dns';\nimport { type ComposeDocker, dockerCompose, type StackRef } from './docker';\nimport { edgeRef, removeEdgeRoutes } from './edge';\nimport { composeServer, dockerHost, sshTarget } from './server';\nimport { composeProject, stackDir } from './stack';\nimport { EDGE_PROJECT } from './traefik';\n\nexport interface ComposeDestroyOptions {\n\tcwd?: string;\n\tstage: string;\n\t/** Delete the stage's secrets too. Kept otherwise. */\n\tsecrets?: boolean;\n\t/** Print what would be deleted; delete nothing, ask nothing. */\n\tdryRun?: boolean;\n}\n\nexport interface ComposeDestroyDeps {\n\tdocker?: ComposeDocker;\n\t/** Whether a person is at a terminal to answer. */\n\tinteractive?: () => boolean;\n\t/** Ask the person, and resolve with what they typed. */\n\task?: (question: string) => Promise<string>;\n\t/** Where the DNS providers' tokens come from. */\n\tcredentials?: CredentialProvider;\n\t/** The provider for a domain — `createDnsProvider` by default. */\n\tdnsProviderFor?: (config: DnsProviderConfig) => Promise<DnsProvider | null>;\n\t/**\n\t * How the AWS account's credential is found — the machine's, as a deploy\n\t * finds it, by default.\n\t */\n\tawsCredentials?: () => Promise<AwsProvisioning | undefined>;\n\t/** For tests: the AWS clients and how long a distribution is waited on. */\n\taws?: Pick<AwsDestroyInput, 'clients' | 'wait'>;\n\tstate?: StateStore;\n\tenv?: NodeJS.ProcessEnv;\n\thome?: string;\n\tlog?: (line: string) => void;\n}\n\n/** A destroy with no terminal to type the stage's name at. */\nexport class ComposeDestroyNeedsTerminal extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Destroying '${stage}' deletes everything its deploys made, and asks you to ` +\n\t\t\t\t`type ${project} first — there is no terminal here to ask at, and no flag ` +\n\t\t\t\t'answers it. Run it yourself, from a terminal. `--dry-run` prints what it ' +\n\t\t\t\t'would delete, anywhere.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsTerminal';\n\t}\n}\n\n/** What was typed was not the project's name. */\nexport class ComposeDestroyNotConfirmed extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Nothing was deleted: destroying '${stage}' needs ${project} typed exactly.`,\n\t\t);\n\t\tthis.name = 'ComposeDestroyNotConfirmed';\n\t}\n}\n\n/** AWS resources to delete, and no credentials to delete them with. */\nexport class ComposeDestroyNeedsAwsCredentials extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly resources: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' has ${resources.length} AWS resource${resources.length === 1 ? '' : 's'} ` +\n\t\t\t\t`to delete (${resources.slice(0, 3).join(', ')}${resources.length > 3 ? ', …' : ''}), ` +\n\t\t\t\t\"and no AWS credentials were found to delete them with. Supply the stage's \" +\n\t\t\t\t'account the way a deploy does — AWS_PROFILE, or AWS_ACCESS_KEY_ID and ' +\n\t\t\t\t'AWS_SECRET_ACCESS_KEY — and run it again. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsAwsCredentials';\n\t}\n}\n\n/** `--secrets`, and a store that cannot delete. */\nexport class SecretsStoreCannotDelete extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`--secrets deletes '${stage}''s secrets, and its store (${store}) has no ` +\n\t\t\t\t'delete(stage). Give the custom store one, or run without --secrets and ' +\n\t\t\t\t'delete them where they are kept. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'SecretsStoreCannotDelete';\n\t}\n}\n\n/** One line of the plan, and how it is carried out. */\ninterface Step {\n\tlabel: string;\n\tleftAlone?: string;\n\t/** Forgotten from the stage's state once done. */\n\tkeys?: string[];\n\trun?: () => Promise<void>;\n}\n\n/** What a record of each type is to destroy. */\nconst KEPT_TYPES: Record<string, string> = {\n\t// The server's setup — its users, firewall, Docker — is the server's.\n\tserver:\n\t\t\"the server's setup is kept: gkm compose:server made it, for any stage\",\n};\n\n/** Records that name no resource of their own — a key in the secrets. */\nconst VALUE_TYPES = new Set(['url']);\n\n/**\n * The stage's stack: its project on the server (or this machine), as\n * `gkm compose --down` finds it.\n */\nexport async function composeStackRef(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n): Promise<{\n\tref: StackRef;\n\tdir: string;\n\tserver?: ReturnType<typeof composeServer>;\n}> {\n\tconst local = stage === workspace.stages.local;\n\tconst server = local\n\t\t? undefined\n\t\t: composeServer({\n\t\t\t\tstage,\n\t\t\t\tlocal,\n\t\t\t\tconfig: workspace.deploy?.compose?.server,\n\t\t\t\tcustom: (await (await secretsStoreFor(workspace, stage)).read(stage))\n\t\t\t\t\t?.custom,\n\t\t\t});\n\tconst override = stackOverrideFile(workspace.root, stage);\n\tconst dir = join(workspace.root, stackDir(stage));\n\tconst ref: StackRef = {\n\t\tproject: composeProject(deployIdentity(workspace, stage)),\n\t\tfile: join(dir, 'docker-compose.yml'),\n\t\t...(existsSync(override) ? { overrides: [override] } : {}),\n\t\tcwd: workspace.root,\n\t\t...(server ? { host: dockerHost(server) } : {}),\n\t};\n\treturn { ref, dir, ...(server ? { server } : {}) };\n}\n\n/** `gkm compose --stage <stage> --destroy`. */\nexport async function composeDestroyCommand(\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps = {},\n): Promise<void> {\n\tconst log = deps.log ?? ((line: string) => console.log(line));\n\tconst env = deps.env ?? process.env;\n\tconst cwd = resolve(options.cwd ?? process.cwd());\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst { stage } = options;\n\tconst local = stage === workspace.stages.local;\n\tif (!local) assertDeployedStage(workspace.stages, stage);\n\n\tconst identity = deployIdentity(workspace, stage);\n\tconst project = composeProject(identity);\n\tconst interactive = deps.interactive ?? canPrompt;\n\tif (!options.dryRun && !interactive()) {\n\t\tthrow new ComposeDestroyNeedsTerminal(stage, project);\n\t}\n\n\tconst state =\n\t\tdeps.state ??\n\t\t(await createStateStore({\n\t\t\tconfig: local ? undefined : workspace.state,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tworkspaceName: workspace.name,\n\t\t\tnamespace: workspace.deploy?.namespace,\n\t\t}));\n\t// Held throughout: a deploy of the stage while it is torn down would\n\t// make what this is deleting.\n\tconst lock = options.dryRun\n\t\t? undefined\n\t\t: await state.lock(stage, { operation: 'destroy' });\n\ttry {\n\t\tconst steps = await plan(workspace, stage, options, deps, state, env);\n\t\tconst { ref } = await composeStackRef(workspace, stage);\n\n\t\tlog(\n\t\t\t`\\n🧨 ${options.dryRun ? 'Would delete' : 'This deletes'} stage '${stage}' of ${workspace.name} for good:\\n`,\n\t\t);\n\t\tconst doing = steps.filter((s) => !s.leftAlone);\n\t\tconst kept = steps.filter((s) => s.leftAlone);\n\t\tfor (const step of doing) log(` - ${step.label}`);\n\t\tif (kept.length > 0) {\n\t\t\tlog('\\n Left where it is:');\n\t\t\tfor (const step of kept) log(` · ${step.label} — ${step.leftAlone}`);\n\t\t}\n\t\tif (!options.secrets) {\n\t\t\tlog(\n\t\t\t\t\"\\n The stage's secrets are kept: a deploy of it again reuses them. --secrets deletes them too.\",\n\t\t\t);\n\t\t}\n\n\t\tif (options.dryRun) {\n\t\t\tlog('\\n--dry-run: nothing was deleted.');\n\t\t\treturn;\n\t\t}\n\n\t\tconst ask =\n\t\t\tdeps.ask ??\n\t\t\t((question: string) =>\n\t\t\t\tprompt(question, {\n\t\t\t\t\tinstead: 'Run it yourself, from a terminal.',\n\t\t\t\t}));\n\t\tconst typed = await ask(`\\n Type ${project} to destroy it: `);\n\t\tif (typed.trim() !== project) {\n\t\t\tthrow new ComposeDestroyNotConfirmed(stage, project);\n\t\t}\n\n\t\tlog('');\n\t\tfor (const step of doing) {\n\t\t\tawait step.run?.();\n\t\t\tfor (const key of step.keys ?? []) {\n\t\t\t\tawait state.deleteResource(stage, key);\n\t\t\t}\n\t\t\tlog(` ✓ ${step.label}`);\n\t\t}\n\t\tlog(`\\n💥 '${stage}' destroyed. ${ref.project} is gone.`);\n\t} finally {\n\t\tawait lock?.release();\n\t}\n}\n\n/** Every step, in the order it is carried out. */\nasync function plan(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps,\n\tstate: StateStore,\n\tenv: NodeJS.ProcessEnv,\n): Promise<Step[]> {\n\tconst steps: Step[] = [];\n\tconst resources = (await state.read(stage))?.resources ?? {};\n\tconst records = Object.values(resources);\n\n\t// ── The stack: containers, volumes, its routes on the edge ─────────────\n\tconst { ref, dir, server } = await composeStackRef(workspace, stage);\n\tconst docker = deps.docker ?? dockerCompose;\n\tsteps.push({\n\t\tlabel: `${server ? `on ${sshTarget(server)}: ` : ''}stack ${ref.project} — its containers, its volumes and their data, its routes on ${EDGE_PROJECT}`,\n\t\trun: async () => {\n\t\t\tconst edgeFile = join(dir, `${EDGE_PROJECT}.yml`);\n\t\t\tif (server || existsSync(edgeFile)) {\n\t\t\t\tawait removeEdgeRoutes(\n\t\t\t\t\tdocker,\n\t\t\t\t\tedgeRef(edgeFile, { host: ref.host }),\n\t\t\t\t\tref.project,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait docker.down(ref, { volumes: true });\n\t\t},\n\t});\n\n\t// ── AWS ─────────────────────────────────────────────────────────────────\n\tconst aws = records.filter((r) =>\n\t\t(AWS_RESOURCE_TYPES as readonly string[]).includes(r.type),\n\t);\n\tlet cdnDns: RecordedDnsRecord[] = [];\n\tif (aws.length > 0) {\n\t\tconst credential = await (\n\t\t\tdeps.awsCredentials ??\n\t\t\t(() =>\n\t\t\t\tawsProvisioningCredentials({\n\t\t\t\t\tstage,\n\t\t\t\t\tenv,\n\t\t\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t\t\t}))\n\t\t)();\n\t\tif (!credential) {\n\t\t\tthrow new ComposeDestroyNeedsAwsCredentials(\n\t\t\t\tstage,\n\t\t\t\taws.map((r) => r.key),\n\t\t\t);\n\t\t}\n\t\tconst identity = deployIdentity(workspace, stage);\n\t\tconst planned = await planAwsDestroy({\n\t\t\tresources,\n\t\t\tidentityKey: identity.key,\n\t\t\tscope: identity.scope,\n\t\t\tstage,\n\t\t\tcredential,\n\t\t\t...(deps.aws ?? {}),\n\t\t});\n\t\tfor (const step of planned.steps) steps.push(awsStep(step));\n\t\tcdnDns = providerDnsRecords(workspace, planned.dns);\n\t}\n\n\t// ── DNS: what the stage recorded, and what its CDN was given ───────────\n\tconst recorded = dnsResources(resources).map((r) => ({\n\t\t...r,\n\t\tfqdn: r.fqdn || dnsRecordFqdn(r.domain, r.name),\n\t}));\n\tconst seen = new Set(recorded.map((r) => `${r.fqdn} ${r.type}`));\n\tconst dnsRecords: RecordedDnsRecord[] = [\n\t\t...recorded,\n\t\t...cdnDns.filter((r) => !seen.has(`${r.fqdn} ${r.type}`)),\n\t];\n\tif (dnsRecords.length > 0) {\n\t\t// The providers' tokens are read now: a missing one stops the destroy\n\t\t// before anything is deleted, rather than after the stack is gone.\n\t\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\t\tconst domains = [...new Set(dnsRecords.map((r) => r.domain))]\n\t\t\t.filter((domain) => dns[domain])\n\t\t\t.map((domain) => ({ domain, config: dns[domain]! }));\n\t\tconst tokens = await dnsCredentials(\n\t\t\tstage,\n\t\t\tdomains,\n\t\t\tdeps.credentials ?? storedCredentials({ env }),\n\t\t);\n\t\tconst log = deps.log ?? ((line: string) => console.log(line));\n\t\tsteps.push({\n\t\t\tlabel: `DNS: ${dnsRecords.map((r) => `${r.type} ${r.fqdn}`).join(', ')} — each only while it holds the value gkm wrote`,\n\t\t\tkeys: recorded.map(\n\t\t\t\t(r) => `dns-record:${r.fqdn.toLowerCase()}:${r.type.toUpperCase()}`,\n\t\t\t),\n\t\t\trun: async () => {\n\t\t\t\tawait pruneStackDns(dnsRecords, {\n\t\t\t\t\tstage,\n\t\t\t\t\tdns: workspace.dns,\n\t\t\t\t\tlog,\n\t\t\t\t\tcredentials: {\n\t\t\t\t\t\t...(tokens.godaddy ? { credential: tokens.godaddy } : {}),\n\t\t\t\t\t\tlog,\n\t\t\t\t\t},\n\t\t\t\t\t...(tokens.hostinger ? { hostinger: tokens.hostinger } : {}),\n\t\t\t\t\t...(deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}),\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\t// ── What gkm cannot delete, and what names nothing ──────────────────────\n\tconst handled = new Set<string>([\n\t\t...(AWS_RESOURCE_TYPES as readonly string[]),\n\t\t'dns-record',\n\t]);\n\tconst values = records.filter((r) => VALUE_TYPES.has(r.type));\n\tfor (const record of records) {\n\t\tif (handled.has(record.type) || VALUE_TYPES.has(record.type)) continue;\n\t\tsteps.push({\n\t\t\tlabel: `${record.type} ${record.id ?? record.key}`,\n\t\t\tleftAlone:\n\t\t\t\tKEPT_TYPES[record.type] ??\n\t\t\t\t`gkm does not delete a ${record.type} yet: delete it by hand`,\n\t\t});\n\t}\n\n\t// ── The stage's secrets ────────────────────────────────────────────────\n\tif (options.secrets) {\n\t\tconst store = await secretsStoreFor(workspace, stage, {\n\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t});\n\t\tif (!store.delete) throw new SecretsStoreCannotDelete(stage, store.name);\n\t\tsteps.push({\n\t\t\tlabel: `the stage's secrets, in its ${store.name} store`,\n\t\t\t// The keys the deleted resources were reached by go with them.\n\t\t\tkeys: values.map((r) => r.key),\n\t\t\trun: () => store.delete!(stage),\n\t\t});\n\t} else if (values.length > 0) {\n\t\t// Their resources are gone; the keys stay in the kept secrets, and a\n\t\t// deploy writes them again.\n\t\tsteps.push({\n\t\t\tlabel: `${values.length} record${values.length === 1 ? '' : 's'} of keys written into the secrets`,\n\t\t\tkeys: values.map((r) => r.key),\n\t\t});\n\t}\n\n\treturn steps;\n}\n\nfunction awsStep(step: AwsDestroyStep): Step {\n\tif (step.leftAlone) return { label: step.label, leftAlone: step.leftAlone };\n\treturn {\n\t\tlabel: step.gone\n\t\t\t? `${step.label} (already gone)`\n\t\t\t: step.withUser\n\t\t\t\t? `${step.label} — deleted with its user`\n\t\t\t\t: step.label,\n\t\tkeys: [step.key],\n\t\t...(step.remove ? { run: step.remove } : {}),\n\t};\n}\n\n/** The CDN's records, as the DNS prune takes them. */\nfunction providerDnsRecords(\n\tworkspace: NormalizedWorkspace,\n\trecords: readonly { host: string; type: 'CNAME'; value: string }[],\n): RecordedDnsRecord[] {\n\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\tconst out: RecordedDnsRecord[] = [];\n\tfor (const record of records) {\n\t\tconst host = record.host.toLowerCase().replace(/\\.$/, '');\n\t\tconst domain = findRootDomain(host, dns);\n\t\tif (!domain) continue;\n\t\tconst config = dns[domain]!;\n\t\tout.push({\n\t\t\tfqdn: host,\n\t\t\tdomain,\n\t\t\tname: extractSubdomain(host, domain),\n\t\t\ttype: record.type,\n\t\t\tvalue: record.value.replace(/\\.$/, ''),\n\t\t\tttl: recordTtl(config),\n\t\t\t...(typeof config.provider === 'string'\n\t\t\t\t? { provider: config.provider }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\treturn out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,qBAAqB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAM,eAAe;CAAE,WAAW;CAAa,YAAY;AAAO;;AAGlE,IAAa,6BAAb,cAAgD,SAAS;CAE9C;CACA;CAFV,YACC,IACA,UACC;EACD,MACC,2BAA2B,GAAG,8CAC1B,KAAK,MAAM,WAAW,GAAM,EAAE,yLAInC;EATS,KAAA,KAAA;EACA,KAAA,WAAA;EAST,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,UAAU,OAAwB;CAC1C,MAAM,IAAI;CACV,OAAO,GAAG,QAAQ,GAAG,QAAQ;AAC9B;;AAGA,eAAe,OACd,MACA,SACyB;CACzB,IAAI;EACH,OAAO,MAAM,KAAK;CACnB,SAAS,OAAO;EACf,IAAI,QAAQ,SAAS,UAAU,KAAK,CAAC,GAAG,OAAO,KAAA;EAC/C,MAAM;CACP;AACD;AAEA,MAAM,SAAS,OAAe,IAAI,SAAS,MAAM,WAAW,GAAG,EAAE,CAAC;;AAGlE,SAAS,KACR,MACA,OACU;CACV,MAAM,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AAM,iBAAiB,MAAM,MAAM;GACnC,MAAM,OAAO;GACb,OAAO,OAAO,MAAM,QAAQ,OAAO,EAAE;GACrC,KAAK,UAAU,MAAM;GACrB,GAAI,OAAO,OAAO,aAAa,WAC5B,EAAE,UAAU,OAAO,SAAS,IAC5B,CAAC;EACL,CAAC;CACF;CACA,OAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"destroy-xjqqzAmU.mjs","names":[],"sources":["../src/providers/s3/destroy.ts","../src/compose/destroy.ts"],"sourcesContent":["/**\n * What `gkm compose --destroy` deletes in the stage's AWS account: each\n * resource a deploy recorded in the stage's state, and only once it is\n * proven gkm's own for this stage.\n *\n * A record alone proves nothing — a deploy records what it found and adopted\n * exactly as what it made (a certificate for the host, a bucket with no\n * tags). So each is checked against what gkm marks its own with: the\n * `gkm:project` and `gkm:stage` tags on a bucket, a user, a certificate, a\n * distribution, a topic or a queue; the stage's own name on an origin access\n * control and a headers policy, which take no tags. What fails the check is\n * left where it is, and said so.\n *\n * Nothing here runs on its own: `planAwsDestroy` reads, and returns a step\n * per resource whose `remove()` the command calls — after the person typed\n * the stage's name — in the order AWS needs: a distribution disabled and\n * gone before its certificate, a user's keys and policies before the user,\n * a bucket emptied before it is deleted.\n */\n\nimport type { ResourceRecord } from '../../deploy/StateStore.js';\nimport { GkmError } from '../../errors.js';\nimport { type AwsProvisioning, awsClientConfig, awsEndpoint } from '../aws.js';\nimport { TAG_PROJECT, TAG_STAGE } from '../iam.js';\nimport { type CdnClients, cdnName, defaultCdnClients } from './cdn.js';\nimport { defaultClients } from './index.js';\nimport { IAM_USER_PATH } from './naming.js';\n\n/** What a destroy step is about, as the person reads it. */\nexport interface AwsDestroyStep {\n\t/** The state record it is kept as: forgotten once it is gone. */\n\tkey: string;\n\tlabel: string;\n\t/** Why it is not deleted. Absent for one that will be. */\n\tleftAlone?: string;\n\t/** Already gone from the account: only its record is forgotten. */\n\tgone?: boolean;\n\t/** Deleted along with its user's step: only its record is forgotten here. */\n\twithUser?: boolean;\n\t/** Deletes it. Absent when it is left alone or already gone. */\n\tremove?: () => Promise<void>;\n}\n\n/** A DNS record a resource here needs, worked out from the resource. */\nexport interface AwsDnsRecord {\n\thost: string;\n\ttype: 'CNAME';\n\tvalue: string;\n}\n\nexport interface AwsDestroyPlan {\n\t/** In the order they are removed. */\n\tsteps: AwsDestroyStep[];\n\t/**\n\t * The records the s3 provider wrote for what it deletes — a CDN's name, a\n\t * certificate's validation — which no state record names.\n\t */\n\tdns: AwsDnsRecord[];\n}\n\nexport interface AwsDestroyInput {\n\tresources: Record<string, ResourceRecord>;\n\t/** `deployIdentity(…).key` — what `gkm:project` holds. */\n\tidentityKey: string;\n\t/** `deployIdentity(…).scope` — what CDN resource names start with. */\n\tscope: string;\n\tstage: string;\n\tcredential: AwsProvisioning;\n\t/** How long a disabled distribution is waited on, and how often asked. */\n\twait?: { timeoutMs: number; intervalMs: number };\n\t/** For tests: where the clients come from. */\n\tclients?: {\n\t\ts3?: typeof defaultClients;\n\t\tcdn?: (credential: AwsProvisioning) => Promise<CdnClients>;\n\t};\n}\n\n/** The record types this plans. Every other is the command's to report. */\nexport const AWS_RESOURCE_TYPES = [\n\t'cloudfront-distribution',\n\t'cloudfront-oac',\n\t'cloudfront-headers',\n\t'acm-certificate',\n\t'sns-subscription',\n\t'sns-topic',\n\t'sqs-queue',\n\t'iam-access-key',\n\t'iam-user',\n\t's3-bucket',\n] as const;\n\n/** A distribution disabled before it is deleted can take this long. */\nconst DISABLE_WAIT = { timeoutMs: 45 * 60_000, intervalMs: 20_000 };\n\n/** A disabled distribution that never finished deploying. */\nexport class DistributionStillDeploying extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly waitedMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`CloudFront distribution ${id} was disabled, and is still deploying after ` +\n\t\t\t\t`${Math.round(waitedMs / 60_000)} minutes. CloudFront deletes only a ` +\n\t\t\t\t'disabled distribution that has finished deploying. Run the destroy ' +\n\t\t\t\t'again later: everything deleted so far is forgotten, and it carries ' +\n\t\t\t\t'on from here.',\n\t\t);\n\t\tthis.name = 'DistributionStillDeploying';\n\t}\n}\n\n/** What an AWS SDK error is called, whichever field carries it. */\nfunction errorName(error: unknown): string {\n\tconst e = error as { name?: string; Code?: string };\n\treturn e?.Code ?? e?.name ?? '';\n}\n\n/** A read whose \"there is none\" answer is one of `missing`. */\nasync function readOr<T>(\n\tread: () => Promise<T>,\n\tmissing: readonly string[],\n): Promise<T | undefined> {\n\ttry {\n\t\treturn await read();\n\t} catch (error) {\n\t\tif (missing.includes(errorName(error))) return undefined;\n\t\tthrow error;\n\t}\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Whether a tag list says gkm made it for this project's stage. */\nfunction ours(\n\ttags: readonly { Key?: string; Value?: string }[] | undefined,\n\tinput: Pick<AwsDestroyInput, 'identityKey' | 'stage'>,\n): boolean {\n\tconst of = (key: string) => tags?.find((t) => t.Key === key)?.Value;\n\treturn of(TAG_PROJECT) === input.identityKey && of(TAG_STAGE) === input.stage;\n}\n\nconst NOT_TAGGED =\n\t\"not tagged as this stage's (gkm:project, gkm:stage): gkm found it, it did not make it\";\n\n/** The id after the type in a record's key: `cloudfront-oac:Uploads` → `Uploads`. */\nfunction keyId(record: ResourceRecord): string {\n\treturn record.key.slice(record.key.indexOf(':') + 1);\n}\n\n/** The file server a CDN record is for: `cloudfront-headers:Uploads:cors` → `Uploads`. */\nfunction serverOf(record: ResourceRecord): string {\n\treturn keyId(record).split(':')[0] ?? '';\n}\n\n/**\n * Each AWS resource the stage's state records, checked, in the order it is\n * deleted — and the DNS records the deleted ones were given.\n */\nexport async function planAwsDestroy(\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyPlan> {\n\tconst steps: AwsDestroyStep[] = [];\n\tconst dns: AwsDnsRecord[] = [];\n\tconst records = Object.values(input.resources);\n\tconst of = (type: string) => records.filter((r) => r.type === type);\n\tconst wait = input.wait ?? DISABLE_WAIT;\n\n\tconst cdnRecords = [\n\t\t...of('cloudfront-distribution'),\n\t\t...of('cloudfront-oac'),\n\t\t...of('cloudfront-headers'),\n\t\t...of('acm-certificate'),\n\t];\n\tif (cdnRecords.length > 0) {\n\t\tconst cdn = await (input.clients?.cdn ?? defaultCdnClients)(\n\t\t\tinput.credential,\n\t\t);\n\t\t// A distribution left alone keeps what it uses: deleting its origin\n\t\t// access control, a headers policy or its certificate would break it.\n\t\tconst kept = new Map<string, string>();\n\t\tfor (const record of of('cloudfront-distribution')) {\n\t\t\tconst step = await distributionStep(cdn, record, input, wait, dns);\n\t\t\tif (step.leftAlone) kept.set(serverOf(record), step.label);\n\t\t\tsteps.push(step);\n\t\t}\n\t\tconst usedBy = async (\n\t\t\trecord: ResourceRecord,\n\t\t\tstep: () => Promise<AwsDestroyStep>,\n\t\t): Promise<AwsDestroyStep> => {\n\t\t\tconst holder = kept.get(serverOf(record));\n\t\t\tif (!holder) return step();\n\t\t\tconst label = (await step()).label;\n\t\t\treturn {\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel,\n\t\t\t\tleftAlone: `used by ${holder}, which is left alone`,\n\t\t\t};\n\t\t};\n\t\tfor (const record of of('cloudfront-oac')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => originAccessControlStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('cloudfront-headers')) {\n\t\t\tsteps.push(\n\t\t\t\tawait usedBy(record, () => headersPolicyStep(cdn, record, input)),\n\t\t\t);\n\t\t}\n\t\tfor (const record of of('acm-certificate')) {\n\t\t\t// Its validation record goes only with the certificate itself.\n\t\t\tconst found: AwsDnsRecord[] = [];\n\t\t\tconst step = await usedBy(record, () =>\n\t\t\t\tcertificateStep(cdn, record, input, found),\n\t\t\t);\n\t\t\tif (!step.leftAlone) dns.push(...found);\n\t\t\tsteps.push(step);\n\t\t}\n\t}\n\n\tconst eventRecords = [\n\t\t...of('sns-subscription'),\n\t\t...of('sns-topic'),\n\t\t...of('sqs-queue'),\n\t];\n\tif (eventRecords.length > 0) {\n\t\tconst events = await eventClients(input.credential, records);\n\t\tfor (const record of of('sns-subscription')) {\n\t\t\tsteps.push(subscriptionStep(events, record));\n\t\t}\n\t\tfor (const record of of('sns-topic')) {\n\t\t\tsteps.push(await topicStep(events, record, input));\n\t\t}\n\t\tfor (const record of of('sqs-queue')) {\n\t\t\tsteps.push(await queueStep(events, record, input));\n\t\t}\n\t}\n\n\tconst users = of('iam-user');\n\tconst keys = of('iam-access-key');\n\tconst buckets = of('s3-bucket');\n\tif (users.length + keys.length + buckets.length > 0) {\n\t\tconst global = await (input.clients?.s3 ?? defaultClients)(\n\t\t\tinput.credential,\n\t\t\tregionOf(buckets[0]) ?? 'us-east-1',\n\t\t);\n\t\tconst userSteps = new Map<string, AwsDestroyStep>();\n\t\tfor (const record of users) {\n\t\t\tconst step = await userStep(global, record, input);\n\t\t\tuserSteps.set(record.id ?? '', step);\n\t\t\tsteps.push(step);\n\t\t}\n\t\t// A key goes with its user, and is checked through it.\n\t\tfor (const record of keys) {\n\t\t\tconst user = (record.data as { user?: string } | undefined)?.user;\n\t\t\tconst owner = user ? userSteps.get(user) : undefined;\n\t\t\tsteps.push({\n\t\t\t\tkey: record.key,\n\t\t\t\tlabel: `IAM access key ${record.id ?? ''} of ${user ?? 'an unknown user'}`,\n\t\t\t\t...(owner?.leftAlone\n\t\t\t\t\t? { leftAlone: `its user is left alone: ${owner.leftAlone}` }\n\t\t\t\t\t: owner\n\t\t\t\t\t\t? { withUser: true }\n\t\t\t\t\t\t: { leftAlone: 'its user is not one this stage recorded' }),\n\t\t\t});\n\t\t}\n\t\tfor (const record of buckets) {\n\t\t\tconst region = regionOf(record) ?? global.region;\n\t\t\tconst clients =\n\t\t\t\tregion === global.region\n\t\t\t\t\t? global\n\t\t\t\t\t: await (input.clients?.s3 ?? defaultClients)(\n\t\t\t\t\t\t\tinput.credential,\n\t\t\t\t\t\t\tregion,\n\t\t\t\t\t\t);\n\t\t\tsteps.push(await bucketStep(clients, record, input));\n\t\t}\n\t}\n\n\treturn { steps, dns };\n}\n\nfunction regionOf(record: ResourceRecord | undefined): string | undefined {\n\treturn (record?.data as { region?: string } | undefined)?.region;\n}\n\n// ---------------------------------------------------------------------------\n// CloudFront and ACM\n// ---------------------------------------------------------------------------\n\nasync function distributionStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\twait: { timeoutMs: number; intervalMs: number },\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetDistributionCommand({ Id: id })),\n\t\t['NoSuchDistribution'],\n\t);\n\tconst distribution = found?.Distribution;\n\tconst aliases = distribution?.DistributionConfig?.Aliases?.Items ?? [];\n\tconst label = `CloudFront distribution ${id}${aliases.length ? ` (${aliases.join(', ')})` : ''}`;\n\tif (!distribution) return { key: record.key, label, gone: true };\n\n\t// Its tags, or the comment gkm writes on every distribution it makes —\n\t// `gkm <project> <stage> <file server>`, which nothing else writes.\n\tconst tags = await cloudfront.send(\n\t\tnew CF.ListTagsForResourceCommand({ Resource: distribution.ARN }),\n\t);\n\tconst comment = `gkm ${input.identityKey} ${input.stage} ${serverOf(record)}`;\n\tconst marked =\n\t\tdistribution.DistributionConfig?.Comment === comment.slice(0, 128);\n\tif (!ours(tags.Tags?.Items, input) && !marked) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `${NOT_TAGGED}, and its comment is not \"${comment}\"`,\n\t\t};\n\t}\n\tfor (const host of aliases) {\n\t\tdns.push({ host, type: 'CNAME', value: distribution.DomainName ?? '' });\n\t}\n\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tlet current = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tif (current.DistributionConfig?.Enabled) {\n\t\t\t\tawait cloudfront.send(\n\t\t\t\t\tnew CF.UpdateDistributionCommand({\n\t\t\t\t\t\tId: id,\n\t\t\t\t\t\tIfMatch: current.ETag,\n\t\t\t\t\t\tDistributionConfig: {\n\t\t\t\t\t\t\t...current.DistributionConfig,\n\t\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst started = Date.now();\n\t\t\tfor (;;) {\n\t\t\t\tconst state = await cloudfront.send(\n\t\t\t\t\tnew CF.GetDistributionCommand({ Id: id }),\n\t\t\t\t);\n\t\t\t\tif (state.Distribution?.Status === 'Deployed') break;\n\t\t\t\tif (Date.now() - started > wait.timeoutMs) {\n\t\t\t\t\tthrow new DistributionStillDeploying(id, Date.now() - started);\n\t\t\t\t}\n\t\t\t\tawait sleep(wait.intervalMs);\n\t\t\t}\n\t\t\tcurrent = await cloudfront.send(\n\t\t\t\tnew CF.GetDistributionConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteDistributionCommand({ Id: id, IfMatch: current.ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function originAccessControlStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\tconst expected = cdnName(input.scope, input.stage, keyId(record));\n\tconst label = `CloudFront origin access control ${expected}`;\n\tconst found = await readOr(\n\t\t() => cloudfront.send(new CF.GetOriginAccessControlCommand({ Id: id })),\n\t\t['NoSuchOriginAccessControl'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.OriginAccessControl?.OriginAccessControlConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetOriginAccessControlCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteOriginAccessControlCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function headersPolicyStep(\n\t{ CF, cloudfront }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst id = record.id ?? '';\n\t// `cloudfront-headers:<server>:<kind>`\n\tconst [server = '', kind = ''] = keyId(record).split(':');\n\tconst expected = `${cdnName(input.scope, input.stage, server)}-${kind}`;\n\tconst label = `CloudFront response headers policy ${expected}`;\n\tconst found = await readOr(\n\t\t() =>\n\t\t\tcloudfront.send(new CF.GetResponseHeadersPolicyConfigCommand({ Id: id })),\n\t\t['NoSuchResponseHeadersPolicy'],\n\t);\n\tif (!found) return { key: record.key, label, gone: true };\n\tconst name = found.ResponseHeadersPolicyConfig?.Name;\n\tif (name !== expected) {\n\t\treturn {\n\t\t\tkey: record.key,\n\t\t\tlabel,\n\t\t\tleftAlone: `named ${name}, not this stage's ${expected}`,\n\t\t};\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst { ETag } = await cloudfront.send(\n\t\t\t\tnew CF.GetResponseHeadersPolicyConfigCommand({ Id: id }),\n\t\t\t);\n\t\t\tawait cloudfront.send(\n\t\t\t\tnew CF.DeleteResponseHeadersPolicyCommand({ Id: id, IfMatch: ETag }),\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function certificateStep(\n\t{ ACM, acm }: CdnClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n\tdns: AwsDnsRecord[],\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst host = (record.data as { host?: string } | undefined)?.host ?? arn;\n\tconst label = `ACM certificate ${host} (us-east-1)`;\n\tconst found = await readOr(\n\t\t() => acm.send(new ACM.DescribeCertificateCommand({ CertificateArn: arn })),\n\t\t['ResourceNotFoundException'],\n\t);\n\tif (!found?.Certificate) return { key: record.key, label, gone: true };\n\tconst tags = await acm.send(\n\t\tnew ACM.ListTagsForCertificateCommand({ CertificateArn: arn }),\n\t);\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\tfor (const option of found.Certificate.DomainValidationOptions ?? []) {\n\t\tconst r = option.ResourceRecord;\n\t\tif (r?.Name && r.Value && r.Type === 'CNAME') {\n\t\t\tdns.push({ host: r.Name, type: 'CNAME', value: r.Value });\n\t\t}\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait acm.send(new ACM.DeleteCertificateCommand({ CertificateArn: arn }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// SNS and SQS\n// ---------------------------------------------------------------------------\n\ninterface EventClients {\n\tSNS: typeof import('@aws-sdk/client-sns');\n\tSQS: typeof import('@aws-sdk/client-sqs');\n\tsns: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sns')['SNSClient']>>;\n\tsqs: (\n\t\tregion: string,\n\t) => Promise<InstanceType<typeof import('@aws-sdk/client-sqs')['SQSClient']>>;\n}\n\nasync function eventClients(\n\tcredential: AwsProvisioning,\n\t_records: readonly ResourceRecord[],\n): Promise<EventClients> {\n\tconst SNS = await import('@aws-sdk/client-sns');\n\tconst SQS = await import('@aws-sdk/client-sqs');\n\tconst sns = new Map<string, InstanceType<typeof SNS.SNSClient>>();\n\tconst sqs = new Map<string, InstanceType<typeof SQS.SQSClient>>();\n\treturn {\n\t\tSNS,\n\t\tSQS,\n\t\tsns: async (region) => {\n\t\t\tif (!sns.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SNS');\n\t\t\t\tsns.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SNS.SNSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sns.get(region)!;\n\t\t},\n\t\tsqs: async (region) => {\n\t\t\tif (!sqs.has(region)) {\n\t\t\t\tconst endpoint = awsEndpoint(process.env, 'SQS');\n\t\t\t\tsqs.set(\n\t\t\t\t\tregion,\n\t\t\t\t\tnew SQS.SQSClient({\n\t\t\t\t\t\t...(await awsClientConfig(credential, region)),\n\t\t\t\t\t\t...(endpoint ? { endpoint } : {}),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn sqs.get(region)!;\n\t\t},\n\t};\n}\n\n/** `arn:aws:sns:<region>:<account>:<name>` */\nfunction arnParts(arn: string) {\n\tconst [, , , region = '', account = '', ...rest] = arn.split(':');\n\treturn { region, account, name: rest.join(':') };\n}\n\nfunction subscriptionStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n): AwsDestroyStep {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS subscription ${keyId(record)}`;\n\t// Made by gkm, to its own push endpoint: a pending one has no ARN yet.\n\tif (!arn.startsWith('arn:')) return { key: record.key, label, gone: true };\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst client = await sns(arnParts(arn).region);\n\t\t\tawait readOr(\n\t\t\t\t() => client.send(new SNS.UnsubscribeCommand({ SubscriptionArn: arn })),\n\t\t\t\t['NotFound', 'NotFoundException'],\n\t\t\t);\n\t\t},\n\t};\n}\n\nasync function topicStep(\n\t{ SNS, sns }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst label = `SNS topic ${arnParts(arn).name}`;\n\tconst client = await sns(arnParts(arn).region);\n\tconst tags = await readOr(\n\t\t() => client.send(new SNS.ListTagsForResourceCommand({ ResourceArn: arn })),\n\t\t[\n\t\t\t'NotFound',\n\t\t\t'NotFoundException',\n\t\t\t'ResourceNotFound',\n\t\t\t'ResourceNotFoundException',\n\t\t],\n\t);\n\tif (!tags) return { key: record.key, label, gone: true };\n\tif (!ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SNS.DeleteTopicCommand({ TopicArn: arn }));\n\t\t},\n\t};\n}\n\nasync function queueStep(\n\t{ SQS, sqs }: EventClients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst arn = record.id ?? '';\n\tconst { region, account, name } = arnParts(arn);\n\tconst label = `SQS queue ${name}`;\n\tconst client = await sqs(region);\n\tconst url = await readOr(\n\t\t() =>\n\t\t\tclient.send(\n\t\t\t\tnew SQS.GetQueueUrlCommand({\n\t\t\t\t\tQueueName: name,\n\t\t\t\t\tQueueOwnerAWSAccountId: account,\n\t\t\t\t}),\n\t\t\t),\n\t\t['QueueDoesNotExist', 'AWS.SimpleQueueService.NonExistentQueue'],\n\t);\n\tif (!url?.QueueUrl) return { key: record.key, label, gone: true };\n\tconst queueUrl = url.QueueUrl;\n\tconst tags = await client.send(\n\t\tnew SQS.ListQueueTagsCommand({ QueueUrl: queueUrl }),\n\t);\n\tconst list = Object.entries(tags.Tags ?? {}).map(([Key, Value]) => ({\n\t\tKey,\n\t\tValue,\n\t}));\n\tif (!ours(list, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tawait client.send(new SQS.DeleteQueueCommand({ QueueUrl: queueUrl }));\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// IAM and S3\n// ---------------------------------------------------------------------------\n\ntype S3Clients = Awaited<ReturnType<typeof defaultClients>>;\n\nasync function userStep(\n\t{ IAM, iam }: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst name = record.id ?? '';\n\tconst label = `IAM user ${name}, its access keys and policies`;\n\tconst found = await readOr(\n\t\t() => iam.send(new IAM.GetUserCommand({ UserName: name })),\n\t\t['NoSuchEntity', 'NoSuchEntityException'],\n\t);\n\tif (!found?.User) return { key: record.key, label, gone: true };\n\tconst tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: name }));\n\tif (found.User.Path !== IAM_USER_PATH || !ours(tags.Tags, input)) {\n\t\treturn { key: record.key, label, leftAlone: NOT_TAGGED };\n\t}\n\treturn {\n\t\tkey: record.key,\n\t\tlabel,\n\t\tremove: async () => {\n\t\t\tconst keys = await iam.send(\n\t\t\t\tnew IAM.ListAccessKeysCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const key of keys.AccessKeyMetadata ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteAccessKeyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tAccessKeyId: key.AccessKeyId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst inline = await iam.send(\n\t\t\t\tnew IAM.ListUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of inline.PolicyNames ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DeleteUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyName: policy,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst attached = await iam.send(\n\t\t\t\tnew IAM.ListAttachedUserPoliciesCommand({ UserName: name }),\n\t\t\t);\n\t\t\tfor (const policy of attached.AttachedPolicies ?? []) {\n\t\t\t\tawait iam.send(\n\t\t\t\t\tnew IAM.DetachUserPolicyCommand({\n\t\t\t\t\t\tUserName: name,\n\t\t\t\t\t\tPolicyArn: policy.PolicyArn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait iam.send(new IAM.DeleteUserCommand({ UserName: name }));\n\t\t},\n\t};\n}\n\n/** Every object version and delete marker in a bucket, a page at a time. */\nasync function* bucketVersions({ S3, s3 }: S3Clients, bucket: string) {\n\tlet KeyMarker: string | undefined;\n\tlet VersionIdMarker: string | undefined;\n\tfor (;;) {\n\t\tconst page = await s3.send(\n\t\t\tnew S3.ListObjectVersionsCommand({\n\t\t\t\tBucket: bucket,\n\t\t\t\t...(KeyMarker ? { KeyMarker } : {}),\n\t\t\t\t...(VersionIdMarker ? { VersionIdMarker } : {}),\n\t\t\t}),\n\t\t);\n\t\tconst objects = [...(page.Versions ?? []), ...(page.DeleteMarkers ?? [])]\n\t\t\t.filter((o) => o.Key)\n\t\t\t.map((o) => ({\n\t\t\t\tKey: o.Key!,\n\t\t\t\t// `null` is the one version an unversioned bucket's object has:\n\t\t\t\t// named or not, the same object is deleted.\n\t\t\t\t...(o.VersionId && o.VersionId !== 'null'\n\t\t\t\t\t? { VersionId: o.VersionId }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\tif (objects.length > 0) yield objects;\n\t\tif (!page.IsTruncated) return;\n\t\tKeyMarker = page.NextKeyMarker;\n\t\tVersionIdMarker = page.NextVersionIdMarker;\n\t}\n}\n\nasync function bucketStep(\n\tclients: S3Clients,\n\trecord: ResourceRecord,\n\tinput: AwsDestroyInput,\n): Promise<AwsDestroyStep> {\n\tconst { S3, s3 } = clients;\n\tconst bucket = record.id ?? '';\n\tconst tagging = await readOr(\n\t\t() => s3.send(new S3.GetBucketTaggingCommand({ Bucket: bucket })),\n\t\t['NoSuchBucket', 'NoSuchTagSet', 'NoSuchTagSetError'],\n\t);\n\tconst exists = await readOr(\n\t\t() => s3.send(new S3.HeadBucketCommand({ Bucket: bucket })),\n\t\t['NotFound', 'NoSuchBucket'],\n\t);\n\tconst base = `S3 bucket ${bucket}`;\n\tif (!exists) return { key: record.key, label: base, gone: true };\n\tif (!ours(tagging?.TagSet, input)) {\n\t\treturn { key: record.key, label: base, leftAlone: NOT_TAGGED };\n\t}\n\tlet count = 0;\n\tfor await (const page of bucketVersions(clients, bucket))\n\t\tcount += page.length;\n\treturn {\n\t\tkey: record.key,\n\t\tlabel: `${base}, emptied first: ${count} object version${count === 1 ? '' : 's'}`,\n\t\tremove: async () => {\n\t\t\t// Until it lists nothing: deleting a version-less object in a bucket\n\t\t\t// whose versioning was suspended leaves a delete marker behind.\n\t\t\tfor (let pass = 0; pass < 5; pass++) {\n\t\t\t\tlet deleted = 0;\n\t\t\t\tfor await (const page of bucketVersions(clients, bucket)) {\n\t\t\t\t\t// At most a thousand a call.\n\t\t\t\t\tfor (let i = 0; i < page.length; i += 1000) {\n\t\t\t\t\t\tawait s3.send(\n\t\t\t\t\t\t\tnew S3.DeleteObjectsCommand({\n\t\t\t\t\t\t\t\tBucket: bucket,\n\t\t\t\t\t\t\t\tDelete: { Objects: page.slice(i, i + 1000), Quiet: true },\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tdeleted += page.length;\n\t\t\t\t}\n\t\t\t\tif (deleted === 0) break;\n\t\t\t}\n\t\t\tawait s3.send(new S3.DeleteBucketCommand({ Bucket: bucket }));\n\t\t},\n\t};\n}\n","/**\n * `gkm compose --stage <stage> --destroy`: everything a deploy made for the\n * stage, deleted for good.\n *\n * The one thing in gkm that deletes what a deploy created — a deploy itself\n * never does. So it is careful in three ways:\n *\n * - **Only what is provably gkm's.** Each AWS resource is checked against\n * what gkm marks its own with before it is deleted (see\n * `providers/s3/destroy.ts`); a DNS record only while it still holds the\n * value gkm wrote. What fails is listed, and left where it is.\n * - **Only with a person typing the stage.** The whole plan is printed\n * first, then the compose project's name — `<project>-<stage>` — has to be\n * typed back. Nothing skips that: there is no flag that answers it, and\n * with no terminal to ask at it refuses before reading anything.\n * - **Resumable.** Each resource's record is forgotten as soon as it is gone,\n * so a run that stops part way — a distribution still deploying — carries\n * on from there when it is run again.\n *\n * What other stages or projects share is never touched: the project bucket\n * that holds every stage's state, the shared Traefik edge, the server's own\n * setup (`gkm compose:server`). The stage's secrets are kept unless\n * `--secrets` is passed.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { loadWorkspaceConfig } from '../config';\nimport {\n\ttype CredentialProvider,\n\tstoredCredentials,\n} from '../deploy/credentials.js';\nimport { dnsRecordFqdn, dnsResources } from '../deploy/dnsResources.js';\nimport { deployIdentity } from '../deploy/identity.js';\nimport { createStateStore, type StateStore } from '../deploy/StateStore.js';\nimport { GkmError } from '../errors';\nimport { canPrompt, prompt } from '../prompt';\nimport {\n\ttype AwsProvisioning,\n\tawsProvisioningCredentials,\n} from '../providers/aws.js';\nimport {\n\tAWS_RESOURCE_TYPES,\n\ttype AwsDestroyInput,\n\ttype AwsDestroyStep,\n\tplanAwsDestroy,\n} from '../providers/s3/destroy.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { stackOverrideFile } from '../target/compose/index';\nimport type { DnsProvider } from '../target/dokploy/dns/DnsProvider.js';\nimport {\n\textractSubdomain,\n\tfindRootDomain,\n\tnormalizeDnsConfig,\n} from '../target/dokploy/dns/index.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport type {\n\tDnsProvider as DnsProviderConfig,\n\tNormalizedWorkspace,\n} from '../workspace/types.js';\nimport {\n\tdnsCredentials,\n\tpruneStackDns,\n\ttype RecordedDnsRecord,\n\trecordTtl,\n} from './dns';\nimport { type ComposeDocker, dockerCompose, type StackRef } from './docker';\nimport { edgeRef, removeEdgeRoutes } from './edge';\nimport { composeServer, dockerHost, sshTarget } from './server';\nimport { composeProject, stackDir } from './stack';\nimport { EDGE_PROJECT } from './traefik';\n\nexport interface ComposeDestroyOptions {\n\tcwd?: string;\n\tstage: string;\n\t/** Delete the stage's secrets too. Kept otherwise. */\n\tsecrets?: boolean;\n\t/** Print what would be deleted; delete nothing, ask nothing. */\n\tdryRun?: boolean;\n}\n\nexport interface ComposeDestroyDeps {\n\tdocker?: ComposeDocker;\n\t/** Whether a person is at a terminal to answer. */\n\tinteractive?: () => boolean;\n\t/** Ask the person, and resolve with what they typed. */\n\task?: (question: string) => Promise<string>;\n\t/** Where the DNS providers' tokens come from. */\n\tcredentials?: CredentialProvider;\n\t/** The provider for a domain — `createDnsProvider` by default. */\n\tdnsProviderFor?: (config: DnsProviderConfig) => Promise<DnsProvider | null>;\n\t/**\n\t * How the AWS account's credential is found — the machine's, as a deploy\n\t * finds it, by default.\n\t */\n\tawsCredentials?: () => Promise<AwsProvisioning | undefined>;\n\t/** For tests: the AWS clients and how long a distribution is waited on. */\n\taws?: Pick<AwsDestroyInput, 'clients' | 'wait'>;\n\tstate?: StateStore;\n\tenv?: NodeJS.ProcessEnv;\n\thome?: string;\n\tlog?: (line: string) => void;\n}\n\n/** A destroy with no terminal to type the stage's name at. */\nexport class ComposeDestroyNeedsTerminal extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Destroying '${stage}' deletes everything its deploys made, and asks you to ` +\n\t\t\t\t`type ${project} first — there is no terminal here to ask at, and no flag ` +\n\t\t\t\t'answers it. Run it yourself, from a terminal. `--dry-run` prints what it ' +\n\t\t\t\t'would delete, anywhere.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsTerminal';\n\t}\n}\n\n/** What was typed was not the project's name. */\nexport class ComposeDestroyNotConfirmed extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly project: string,\n\t) {\n\t\tsuper(\n\t\t\t`Nothing was deleted: destroying '${stage}' needs ${project} typed exactly.`,\n\t\t);\n\t\tthis.name = 'ComposeDestroyNotConfirmed';\n\t}\n}\n\n/** AWS resources to delete, and no credentials to delete them with. */\nexport class ComposeDestroyNeedsAwsCredentials extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly resources: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' has ${resources.length} AWS resource${resources.length === 1 ? '' : 's'} ` +\n\t\t\t\t`to delete (${resources.slice(0, 3).join(', ')}${resources.length > 3 ? ', …' : ''}), ` +\n\t\t\t\t\"and no AWS credentials were found to delete them with. Supply the stage's \" +\n\t\t\t\t'account the way a deploy does — AWS_PROFILE, or AWS_ACCESS_KEY_ID and ' +\n\t\t\t\t'AWS_SECRET_ACCESS_KEY — and run it again. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'ComposeDestroyNeedsAwsCredentials';\n\t}\n}\n\n/** `--secrets`, and a store that cannot delete. */\nexport class SecretsStoreCannotDelete extends GkmError {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`--secrets deletes '${stage}''s secrets, and its store (${store}) has no ` +\n\t\t\t\t'delete(stage). Give the custom store one, or run without --secrets and ' +\n\t\t\t\t'delete them where they are kept. Nothing was deleted.',\n\t\t);\n\t\tthis.name = 'SecretsStoreCannotDelete';\n\t}\n}\n\n/** One line of the plan, and how it is carried out. */\ninterface Step {\n\tlabel: string;\n\tleftAlone?: string;\n\t/** Forgotten from the stage's state once done. */\n\tkeys?: string[];\n\trun?: () => Promise<void>;\n}\n\n/** What a record of each type is to destroy. */\nconst KEPT_TYPES: Record<string, string> = {\n\t// The server's setup — its users, firewall, Docker — is the server's.\n\tserver:\n\t\t\"the server's setup is kept: gkm compose:server made it, for any stage\",\n};\n\n/** Records that name no resource of their own — a key in the secrets. */\nconst VALUE_TYPES = new Set(['url']);\n\n/**\n * The stage's stack: its project on the server (or this machine), as\n * `gkm compose --down` finds it.\n */\nexport async function composeStackRef(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n): Promise<{\n\tref: StackRef;\n\tdir: string;\n\tserver?: ReturnType<typeof composeServer>;\n}> {\n\tconst local = stage === workspace.stages.local;\n\tconst server = local\n\t\t? undefined\n\t\t: composeServer({\n\t\t\t\tstage,\n\t\t\t\tlocal,\n\t\t\t\tconfig: workspace.deploy?.compose?.server,\n\t\t\t\tcustom: (await (await secretsStoreFor(workspace, stage)).read(stage))\n\t\t\t\t\t?.custom,\n\t\t\t});\n\tconst override = stackOverrideFile(workspace.root, stage);\n\tconst dir = join(workspace.root, stackDir(stage));\n\tconst ref: StackRef = {\n\t\tproject: composeProject(deployIdentity(workspace, stage)),\n\t\tfile: join(dir, 'docker-compose.yml'),\n\t\t...(existsSync(override) ? { overrides: [override] } : {}),\n\t\tcwd: workspace.root,\n\t\t...(server ? { host: dockerHost(server) } : {}),\n\t};\n\treturn { ref, dir, ...(server ? { server } : {}) };\n}\n\n/** `gkm compose --stage <stage> --destroy`. */\nexport async function composeDestroyCommand(\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps = {},\n): Promise<void> {\n\tconst log = deps.log ?? ((line: string) => console.log(line));\n\tconst env = deps.env ?? process.env;\n\tconst cwd = resolve(options.cwd ?? process.cwd());\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst { stage } = options;\n\tconst local = stage === workspace.stages.local;\n\tif (!local) assertDeployedStage(workspace.stages, stage);\n\n\tconst identity = deployIdentity(workspace, stage);\n\tconst project = composeProject(identity);\n\tconst interactive = deps.interactive ?? canPrompt;\n\tif (!options.dryRun && !interactive()) {\n\t\tthrow new ComposeDestroyNeedsTerminal(stage, project);\n\t}\n\n\tconst state =\n\t\tdeps.state ??\n\t\t(await createStateStore({\n\t\t\tconfig: local ? undefined : workspace.state,\n\t\t\tworkspaceRoot: workspace.root,\n\t\t\tworkspaceName: workspace.name,\n\t\t\tnamespace: workspace.deploy?.namespace,\n\t\t}));\n\t// Held throughout: a deploy of the stage while it is torn down would\n\t// make what this is deleting.\n\tconst lock = options.dryRun\n\t\t? undefined\n\t\t: await state.lock(stage, { operation: 'destroy' });\n\ttry {\n\t\tconst steps = await plan(workspace, stage, options, deps, state, env);\n\t\tconst { ref } = await composeStackRef(workspace, stage);\n\n\t\tlog(\n\t\t\t`\\n🧨 ${options.dryRun ? 'Would delete' : 'This deletes'} stage '${stage}' of ${workspace.name} for good:\\n`,\n\t\t);\n\t\tconst doing = steps.filter((s) => !s.leftAlone);\n\t\tconst kept = steps.filter((s) => s.leftAlone);\n\t\tfor (const step of doing) log(` - ${step.label}`);\n\t\tif (kept.length > 0) {\n\t\t\tlog('\\n Left where it is:');\n\t\t\tfor (const step of kept) log(` · ${step.label} — ${step.leftAlone}`);\n\t\t}\n\t\tif (!options.secrets) {\n\t\t\tlog(\n\t\t\t\t\"\\n The stage's secrets are kept: a deploy of it again reuses them. --secrets deletes them too.\",\n\t\t\t);\n\t\t}\n\n\t\tif (options.dryRun) {\n\t\t\tlog('\\n--dry-run: nothing was deleted.');\n\t\t\treturn;\n\t\t}\n\n\t\tconst ask =\n\t\t\tdeps.ask ??\n\t\t\t((question: string) =>\n\t\t\t\tprompt(question, {\n\t\t\t\t\tinstead: 'Run it yourself, from a terminal.',\n\t\t\t\t}));\n\t\tconst typed = await ask(`\\n Type ${project} to destroy it: `);\n\t\tif (typed.trim() !== project) {\n\t\t\tthrow new ComposeDestroyNotConfirmed(stage, project);\n\t\t}\n\n\t\tlog('');\n\t\tfor (const step of doing) {\n\t\t\tawait step.run?.();\n\t\t\tfor (const key of step.keys ?? []) {\n\t\t\t\tawait state.deleteResource(stage, key);\n\t\t\t}\n\t\t\tlog(` ✓ ${step.label}`);\n\t\t}\n\t\tlog(`\\n💥 '${stage}' destroyed. ${ref.project} is gone.`);\n\t} finally {\n\t\tawait lock?.release();\n\t}\n}\n\n/** Every step, in the order it is carried out. */\nasync function plan(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\toptions: ComposeDestroyOptions,\n\tdeps: ComposeDestroyDeps,\n\tstate: StateStore,\n\tenv: NodeJS.ProcessEnv,\n): Promise<Step[]> {\n\tconst steps: Step[] = [];\n\tconst resources = (await state.read(stage))?.resources ?? {};\n\tconst records = Object.values(resources);\n\n\t// ── The stack: containers, volumes, its routes on the edge ─────────────\n\tconst { ref, dir, server } = await composeStackRef(workspace, stage);\n\tconst docker = deps.docker ?? dockerCompose;\n\tsteps.push({\n\t\tlabel: `${server ? `on ${sshTarget(server)}: ` : ''}stack ${ref.project} — its containers, its volumes and their data, its routes on ${EDGE_PROJECT}`,\n\t\trun: async () => {\n\t\t\tconst edgeFile = join(dir, `${EDGE_PROJECT}.yml`);\n\t\t\tif (server || existsSync(edgeFile)) {\n\t\t\t\tawait removeEdgeRoutes(\n\t\t\t\t\tdocker,\n\t\t\t\t\tedgeRef(edgeFile, { host: ref.host }),\n\t\t\t\t\tref.project,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait docker.down(ref, { volumes: true });\n\t\t},\n\t});\n\n\t// ── AWS ─────────────────────────────────────────────────────────────────\n\tconst aws = records.filter((r) =>\n\t\t(AWS_RESOURCE_TYPES as readonly string[]).includes(r.type),\n\t);\n\tlet cdnDns: RecordedDnsRecord[] = [];\n\tif (aws.length > 0) {\n\t\tconst credential = await (\n\t\t\tdeps.awsCredentials ??\n\t\t\t(() =>\n\t\t\t\tawsProvisioningCredentials({\n\t\t\t\t\tstage,\n\t\t\t\t\tenv,\n\t\t\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t\t\t}))\n\t\t)();\n\t\tif (!credential) {\n\t\t\tthrow new ComposeDestroyNeedsAwsCredentials(\n\t\t\t\tstage,\n\t\t\t\taws.map((r) => r.key),\n\t\t\t);\n\t\t}\n\t\tconst identity = deployIdentity(workspace, stage);\n\t\tconst planned = await planAwsDestroy({\n\t\t\tresources,\n\t\t\tidentityKey: identity.key,\n\t\t\tscope: identity.scope,\n\t\t\tstage,\n\t\t\tcredential,\n\t\t\t...(deps.aws ?? {}),\n\t\t});\n\t\tfor (const step of planned.steps) steps.push(awsStep(step));\n\t\tcdnDns = providerDnsRecords(workspace, planned.dns);\n\t}\n\n\t// ── DNS: what the stage recorded, and what its CDN was given ───────────\n\tconst recorded = dnsResources(resources).map((r) => ({\n\t\t...r,\n\t\tfqdn: r.fqdn || dnsRecordFqdn(r.domain, r.name),\n\t}));\n\tconst seen = new Set(recorded.map((r) => `${r.fqdn} ${r.type}`));\n\tconst dnsRecords: RecordedDnsRecord[] = [\n\t\t...recorded,\n\t\t...cdnDns.filter((r) => !seen.has(`${r.fqdn} ${r.type}`)),\n\t];\n\tif (dnsRecords.length > 0) {\n\t\t// The providers' tokens are read now: a missing one stops the destroy\n\t\t// before anything is deleted, rather than after the stack is gone.\n\t\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\t\tconst domains = [...new Set(dnsRecords.map((r) => r.domain))]\n\t\t\t.filter((domain) => dns[domain])\n\t\t\t.map((domain) => ({ domain, config: dns[domain]! }));\n\t\tconst tokens = await dnsCredentials(\n\t\t\tstage,\n\t\t\tdomains,\n\t\t\tdeps.credentials ?? storedCredentials({ env }),\n\t\t);\n\t\tconst log = deps.log ?? ((line: string) => console.log(line));\n\t\tsteps.push({\n\t\t\tlabel: `DNS: ${dnsRecords.map((r) => `${r.type} ${r.fqdn}`).join(', ')} — each only while it holds the value gkm wrote`,\n\t\t\tkeys: recorded.map(\n\t\t\t\t(r) => `dns-record:${r.fqdn.toLowerCase()}:${r.type.toUpperCase()}`,\n\t\t\t),\n\t\t\trun: async () => {\n\t\t\t\tawait pruneStackDns(dnsRecords, {\n\t\t\t\t\tstage,\n\t\t\t\t\tdns: workspace.dns,\n\t\t\t\t\tlog,\n\t\t\t\t\tcredentials: {\n\t\t\t\t\t\t...(tokens.godaddy ? { credential: tokens.godaddy } : {}),\n\t\t\t\t\t\tlog,\n\t\t\t\t\t},\n\t\t\t\t\t...(tokens.hostinger ? { hostinger: tokens.hostinger } : {}),\n\t\t\t\t\t...(deps.dnsProviderFor ? { providerFor: deps.dnsProviderFor } : {}),\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\t// ── What gkm cannot delete, and what names nothing ──────────────────────\n\tconst handled = new Set<string>([\n\t\t...(AWS_RESOURCE_TYPES as readonly string[]),\n\t\t'dns-record',\n\t]);\n\tconst values = records.filter((r) => VALUE_TYPES.has(r.type));\n\tfor (const record of records) {\n\t\tif (handled.has(record.type) || VALUE_TYPES.has(record.type)) continue;\n\t\tsteps.push({\n\t\t\tlabel: `${record.type} ${record.id ?? record.key}`,\n\t\t\tleftAlone:\n\t\t\t\tKEPT_TYPES[record.type] ??\n\t\t\t\t`gkm does not delete a ${record.type} yet: delete it by hand`,\n\t\t});\n\t}\n\n\t// ── The stage's secrets ────────────────────────────────────────────────\n\tif (options.secrets) {\n\t\tconst store = await secretsStoreFor(workspace, stage, {\n\t\t\t...(deps.home ? { home: deps.home } : {}),\n\t\t});\n\t\tif (!store.delete) throw new SecretsStoreCannotDelete(stage, store.name);\n\t\tsteps.push({\n\t\t\tlabel: `the stage's secrets, in its ${store.name} store`,\n\t\t\t// The keys the deleted resources were reached by go with them.\n\t\t\tkeys: values.map((r) => r.key),\n\t\t\trun: () => store.delete!(stage),\n\t\t});\n\t} else if (values.length > 0) {\n\t\t// Their resources are gone; the keys stay in the kept secrets, and a\n\t\t// deploy writes them again.\n\t\tsteps.push({\n\t\t\tlabel: `${values.length} record${values.length === 1 ? '' : 's'} of keys written into the secrets`,\n\t\t\tkeys: values.map((r) => r.key),\n\t\t});\n\t}\n\n\treturn steps;\n}\n\nfunction awsStep(step: AwsDestroyStep): Step {\n\tif (step.leftAlone) return { label: step.label, leftAlone: step.leftAlone };\n\treturn {\n\t\tlabel: step.gone\n\t\t\t? `${step.label} (already gone)`\n\t\t\t: step.withUser\n\t\t\t\t? `${step.label} — deleted with its user`\n\t\t\t\t: step.label,\n\t\tkeys: [step.key],\n\t\t...(step.remove ? { run: step.remove } : {}),\n\t};\n}\n\n/** The CDN's records, as the DNS prune takes them. */\nfunction providerDnsRecords(\n\tworkspace: NormalizedWorkspace,\n\trecords: readonly { host: string; type: 'CNAME'; value: string }[],\n): RecordedDnsRecord[] {\n\tconst dns = workspace.dns ? normalizeDnsConfig(workspace.dns) : {};\n\tconst out: RecordedDnsRecord[] = [];\n\tfor (const record of records) {\n\t\tconst host = record.host.toLowerCase().replace(/\\.$/, '');\n\t\tconst domain = findRootDomain(host, dns);\n\t\tif (!domain) continue;\n\t\tconst config = dns[domain]!;\n\t\tout.push({\n\t\t\tfqdn: host,\n\t\t\tdomain,\n\t\t\tname: extractSubdomain(host, domain),\n\t\t\ttype: record.type,\n\t\t\tvalue: record.value.replace(/\\.$/, ''),\n\t\t\tttl: recordTtl(config),\n\t\t\t...(typeof config.provider === 'string'\n\t\t\t\t? { provider: config.provider }\n\t\t\t\t: {}),\n\t\t});\n\t}\n\treturn out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,qBAAqB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAM,eAAe;CAAE,WAAW;CAAa,YAAY;AAAO;;AAGlE,IAAa,6BAAb,cAAgD,SAAS;CAE9C;CACA;CAFV,YACC,IACA,UACC;EACD,MACC,2BAA2B,GAAG,8CAC1B,KAAK,MAAM,WAAW,GAAM,EAAE,yLAInC;EATS,KAAA,KAAA;EACA,KAAA,WAAA;EAST,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,UAAU,OAAwB;CAC1C,MAAM,IAAI;CACV,OAAO,GAAG,QAAQ,GAAG,QAAQ;AAC9B;;AAGA,eAAe,OACd,MACA,SACyB;CACzB,IAAI;EACH,OAAO,MAAM,KAAK;CACnB,SAAS,OAAO;EACf,IAAI,QAAQ,SAAS,UAAU,KAAK,CAAC,GAAG,OAAO,KAAA;EAC/C,MAAM;CACP;AACD;AAEA,MAAM,SAAS,OAAe,IAAI,SAAS,MAAM,WAAW,GAAG,EAAE,CAAC;;AAGlE,SAAS,KACR,MACA,OACU;CACV,MAAM,MAAM,QAAgB,MAAM,MAAM,MAAM,EAAE,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OAAO;GACb,OAAO,OAAO,MAAM,QAAQ,OAAO,EAAE;GACrC,KAAK,UAAU,MAAM;GACrB,GAAI,OAAO,OAAO,aAAa,WAC5B,EAAE,UAAU,OAAO,SAAS,IAC5B,CAAC;EACL,CAAC;CACF;CACA,OAAO;AACR"}
|
|
@@ -5,7 +5,7 @@ const require_apps = require("./apps-5iJb710M.cjs");
|
|
|
5
5
|
const require_config = require("./config-CLXSXbcs.cjs");
|
|
6
6
|
const require_discover = require("./discover-CRywE7yc.cjs");
|
|
7
7
|
const require_snsSubscriptions = require("./snsSubscriptions-CSyPnoEQ.cjs");
|
|
8
|
-
const require_deploy = require("./deploy-
|
|
8
|
+
const require_deploy = require("./deploy-CGywNg5R.cjs");
|
|
9
9
|
const require_projectBucket = require("./projectBucket-DUtWAxWn.cjs");
|
|
10
10
|
const require_aws = require("./aws-DKC2m3sT.cjs");
|
|
11
11
|
const require_secretsManager = require("./secretsManager-D8on44WI.cjs");
|
|
@@ -456,8 +456,9 @@ function deployAccess(workspace, stage, policyArn, manifest = {}) {
|
|
|
456
456
|
Sid: "StageMailIdentity",
|
|
457
457
|
Effect: "Allow",
|
|
458
458
|
Action: [
|
|
459
|
-
"ses:
|
|
459
|
+
"ses:GetIdentityDkimAttributes",
|
|
460
460
|
"ses:VerifyDomainDkim",
|
|
461
|
+
"ses:SetIdentityDkimEnabled",
|
|
461
462
|
"ses:GetSendQuota"
|
|
462
463
|
],
|
|
463
464
|
Resource: "*"
|
|
@@ -930,4 +931,4 @@ var SsoSessionExpired = class extends require_errors.GkmError {
|
|
|
930
931
|
exports.deployGithubCommand = deployGithubCommand;
|
|
931
932
|
exports.ghCli = ghCli;
|
|
932
933
|
|
|
933
|
-
//# sourceMappingURL=github-
|
|
934
|
+
//# sourceMappingURL=github-82k5-OZO.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"github-82k5-OZO.cjs","names":["GkmError","projectBucketName","deployIdentity","PROJECT_BUCKET_CREATE_ACTIONS","s3SecretsLocation","s3SecretsKey","secretsParameterName","secretsManagerSecretName","stageProvider","bucketName","iamUserName","IAM_USER_PATH","emailUserName","stageBackups","backupsUserName","PROJECT_BUCKET_LIFECYCLE_ACTIONS","stageDnsDomains","execFileSync","ListOpenIDConnectProvidersCommand","CreateOpenIDConnectProviderCommand","GetRoleCommand","UpdateAssumeRolePolicyCommand","ListRoleTagsCommand","CreateRoleCommand","DetachRolePolicyCommand","DeleteRolePolicyCommand","AttachRolePolicyCommand","TagRoleCommand","PutRolePolicyCommand","UntagRoleCommand","ListAttachedRolePoliciesCommand","IAMClient","loadWorkspaceConfig","discover","constructGlobs","readKey","keystoreProject","getKeyPath","isRemoteStore","secretsStoreFor","GkmError"],"sources":["../src/deploy/githubOidc.ts","../src/deploy/githubPolicy.ts","../src/deploy/github.ts"],"sourcesContent":["/**\n * The `sub` GitHub puts in a deploy job's OIDC token — what the deploy role's\n * trust policy has to match exactly.\n *\n * It is not always `repo:<owner>/<name>:environment:<stage>`. A repository\n * (or its organisation) decides the format, and says which through\n * `GET /repos/{owner}/{repo}/actions/oidc/customization/sub`:\n *\n * - the default: `repo:<owner>/<name>:environment:<stage>`;\n * - the immutable subject — the default for repositories created after\n * 15 July 2026, opt-in before — puts the owner's and the repository's ids in\n * the `repo` segment: `repo:<owner>@<ownerId>/<name>@<repoId>:environment:<stage>`.\n * The API hands that segment back as `sub_claim_prefix`;\n * - a custom template (`use_default: false`) builds the `sub` from\n * `include_claim_keys`, in order, each as `<key>:<value>` joined by `:`,\n * where `context` is `environment:<stage>` in an environment job.\n *\n * A `:` inside a value is sent as `%3A`.\n *\n * See https://docs.github.com/en/actions/reference/security/oidc.\n */\n\nimport { GkmError } from '../errors';\nimport type { Gh } from './github.js';\n\n/** `GET /repos/{owner}/{repo}/actions/oidc/customization/sub`. */\nexport interface OidcSubjectCustomization {\n\tuse_default: boolean;\n\tinclude_claim_keys?: string[];\n\tuse_immutable_subject?: boolean;\n\t/** The `repo` segment of the subject, as GitHub will send it. */\n\tsub_claim_prefix?: string;\n}\n\n/** What `GET /repos/{owner}/{repo}` says that a subject may include. */\nexport interface RepoFacts {\n\townerId: number;\n\trepoId: number;\n\tvisibility: string;\n}\n\n/**\n * Template keys whose values are known for a repository's environment job\n * before the job runs. Anything else — `job_workflow_ref`, `ref`, `sha`,\n * `run_id`, `workflow`, `actor`, a custom property — depends on the run.\n */\nexport const SUPPORTED_CLAIM_KEYS = [\n\t'repo',\n\t'context',\n\t'environment',\n\t'repository',\n\t'repository_owner',\n\t'repository_owner_id',\n\t'repository_id',\n\t'repository_visibility',\n] as const;\n\nconst NEEDS_FACTS = new Set([\n\t'repository_owner_id',\n\t'repository_id',\n\t'repository_visibility',\n]);\n\n/** A `:` inside a claim value is sent as `%3A`. */\nfunction claim(value: string): string {\n\treturn value.replaceAll(':', '%3A');\n}\n\n/** Which kind of subject the repository uses, for the output. */\nexport type OidcSubjectKind = 'default' | 'immutable' | 'custom' | 'assumed';\n\n/** Whether {@link oidcSubject} needs the repository's ids or visibility. */\nexport function needsRepoFacts(\n\tcustomization: OidcSubjectCustomization,\n): boolean {\n\tconst immutableWithoutPrefix =\n\t\tcustomization.use_immutable_subject === true &&\n\t\t!customization.sub_claim_prefix;\n\tif (customization.use_default) return immutableWithoutPrefix;\n\n\tconst keys = customization.include_claim_keys ?? [];\n\treturn keys.some(\n\t\t(key) => NEEDS_FACTS.has(key) || (key === 'repo' && immutableWithoutPrefix),\n\t);\n}\n\n/**\n * The exact `sub` of a job in `repo`'s `stage` environment.\n *\n * @throws OidcSubjectNotSupported when a custom template includes a claim\n * whose value depends on the run, so no one subject can be trusted.\n */\nexport function oidcSubject(\n\trepo: string,\n\tstage: string,\n\tcustomization: OidcSubjectCustomization,\n\tfacts?: RepoFacts,\n): { subject: string; kind: OidcSubjectKind } {\n\tconst [owner = '', name = ''] = repo.split('/');\n\tconst environment = `environment:${claim(stage)}`;\n\n\tconst repoSegment = (): string => {\n\t\tif (customization.sub_claim_prefix) return customization.sub_claim_prefix;\n\t\tif (customization.use_immutable_subject) {\n\t\t\tif (!facts) throw new RepoFactsRequired(repo);\n\t\t\treturn `repo:${owner}@${facts.ownerId}/${name}@${facts.repoId}`;\n\t\t}\n\t\treturn `repo:${repo}`;\n\t};\n\tconst immutable =\n\t\tcustomization.use_immutable_subject === true ||\n\t\tcustomization.sub_claim_prefix !== undefined;\n\n\tif (customization.use_default) {\n\t\treturn {\n\t\t\tsubject: `${repoSegment()}:${environment}`,\n\t\t\tkind: immutable ? 'immutable' : 'default',\n\t\t};\n\t}\n\n\tconst keys = customization.include_claim_keys ?? [];\n\tconst unsupported = keys.filter(\n\t\t(key) => !(SUPPORTED_CLAIM_KEYS as readonly string[]).includes(key),\n\t);\n\tif (keys.length === 0 || unsupported.length > 0) {\n\t\tthrow new OidcSubjectNotSupported(repo, keys, unsupported);\n\t}\n\tif (keys.some((key) => NEEDS_FACTS.has(key)) && !facts) {\n\t\tthrow new RepoFactsRequired(repo);\n\t}\n\n\tconst parts = keys.map((key) => {\n\t\tswitch (key) {\n\t\t\tcase 'repo':\n\t\t\t\treturn repoSegment();\n\t\t\tcase 'context':\n\t\t\tcase 'environment':\n\t\t\t\treturn environment;\n\t\t\tcase 'repository':\n\t\t\t\treturn `repository:${claim(repo)}`;\n\t\t\tcase 'repository_owner':\n\t\t\t\treturn `repository_owner:${claim(owner)}`;\n\t\t\tcase 'repository_owner_id':\n\t\t\t\treturn `repository_owner_id:${facts!.ownerId}`;\n\t\t\tcase 'repository_id':\n\t\t\t\treturn `repository_id:${facts!.repoId}`;\n\t\t\tdefault:\n\t\t\t\treturn `repository_visibility:${claim(facts!.visibility)}`;\n\t\t}\n\t});\n\treturn { subject: parts.join(':'), kind: 'custom' };\n}\n\n/** What {@link resolveOidcSubject} found. */\nexport interface ResolvedOidcSubject {\n\tsubject: string;\n\tkind: OidcSubjectKind;\n\t/** Set when the format could not be read and the default was assumed. */\n\twarning?: string;\n}\n\n/** The endpoint a repository's subject format is read from. */\nexport function customizationEndpoint(repo: string): string {\n\treturn `repos/${repo}/actions/oidc/customization/sub`;\n}\n\n/**\n * The `sub` GitHub will send for `repo`'s `stage` environment, read from the\n * repository's OIDC settings through `gh`.\n *\n * A repository on a custom template that names no keys of its own uses its\n * organisation's, read from `orgs/{owner}/actions/oidc/customization/sub`.\n * When the settings cannot be read at all — no permission, or a GitHub\n * Enterprise Server without the endpoint — the default format is assumed, with\n * a warning saying where to check it.\n */\nexport function resolveOidcSubject(\n\tgh: Gh,\n\trepo: string,\n\tstage: string,\n): ResolvedOidcSubject {\n\tconst endpoint = customizationEndpoint(repo);\n\tlet customization: OidcSubjectCustomization;\n\ttry {\n\t\tcustomization = JSON.parse(gh(['api', endpoint]));\n\t} catch {\n\t\treturn {\n\t\t\tsubject: `repo:${repo}:environment:${claim(stage)}`,\n\t\t\tkind: 'assumed',\n\t\t\twarning: `Could not read ${endpoint}, so the default subject format is assumed. Check it with: gh api ${endpoint} — a repository on the immutable subject or a custom template sends a different sub, and the role would not be assumable.`,\n\t\t};\n\t}\n\n\tif (\n\t\t!customization.use_default &&\n\t\t(customization.include_claim_keys ?? []).length === 0\n\t) {\n\t\t// The repository follows its organisation's template.\n\t\tconst [owner = ''] = repo.split('/');\n\t\tconst orgEndpoint = `orgs/${owner}/actions/oidc/customization/sub`;\n\t\tlet org: { include_claim_keys?: string[]; use_immutable_subject?: boolean };\n\t\ttry {\n\t\t\torg = JSON.parse(gh(['api', orgEndpoint]));\n\t\t} catch {\n\t\t\tthrow new OrgOidcTemplateUnreadable(repo, orgEndpoint);\n\t\t}\n\t\tcustomization = {\n\t\t\t...customization,\n\t\t\tinclude_claim_keys: org.include_claim_keys ?? [],\n\t\t\tuse_immutable_subject:\n\t\t\t\tcustomization.use_immutable_subject ?? org.use_immutable_subject,\n\t\t};\n\t}\n\n\tconst facts = needsRepoFacts(customization)\n\t\t? readRepoFacts(gh, repo)\n\t\t: undefined;\n\treturn oidcSubject(repo, stage, customization, facts);\n}\n\nfunction readRepoFacts(gh: Gh, repo: string): RepoFacts {\n\tconst raw = JSON.parse(gh(['api', `repos/${repo}`])) as {\n\t\tid: number;\n\t\towner: { id: number };\n\t\tvisibility: string;\n\t};\n\treturn {\n\t\townerId: raw.owner.id,\n\t\trepoId: raw.id,\n\t\tvisibility: raw.visibility,\n\t};\n}\n\n/**\n * The repository's custom subject template includes a claim whose value\n * depends on the run — or names none — so no one subject can be trusted.\n */\nexport class OidcSubjectNotSupported extends GkmError {\n\tconstructor(\n\t\treadonly repo: string,\n\t\treadonly includeClaimKeys: string[],\n\t\treadonly unsupportedKeys: string[],\n\t) {\n\t\tsuper(\n\t\t\t`${repo} builds its OIDC subject from a custom template, ${JSON.stringify(includeClaimKeys)}, and ${\n\t\t\t\tunsupportedKeys.length > 0\n\t\t\t\t\t? `${unsupportedKeys.join(', ')} depend${unsupportedKeys.length === 1 ? 's' : ''} on the run`\n\t\t\t\t\t: 'it names no claims'\n\t\t\t}, so the deploy role cannot trust one exact subject. Set the repository back to the default subject — gh api --method PUT ${customizationEndpoint(repo)} -F use_default=true — (or keep the immutable one by also passing -F use_immutable_subject=true), or use a template built only from ${SUPPORTED_CLAIM_KEYS.join(', ')}; then run this again.`,\n\t\t);\n\t\tthis.name = 'OidcSubjectNotSupported';\n\t}\n}\n\n/** The subject needs the repository's ids, and none were read. */\nexport class RepoFactsRequired extends GkmError {\n\tconstructor(readonly repo: string) {\n\t\tsuper(\n\t\t\t`The OIDC subject of ${repo} includes its owner and repository ids; read them with gh api repos/${repo} and pass them in.`,\n\t\t);\n\t\tthis.name = 'RepoFactsRequired';\n\t}\n}\n\n/**\n * The repository uses its organisation's subject template, and that template\n * could not be read — so what GitHub sends is unknown, and is not guessed.\n */\nexport class OrgOidcTemplateUnreadable extends GkmError {\n\tconstructor(\n\t\treadonly repo: string,\n\t\treadonly endpoint: string,\n\t) {\n\t\tsuper(\n\t\t\t`${repo} uses its organisation's OIDC subject template, and ${endpoint} could not be read. Run this as an organisation owner (gh auth refresh -s admin:org), or set the repository back to the default subject with gh api --method PUT ${customizationEndpoint(repo)} -F use_default=true; then run this again.`,\n\t\t);\n\t\tthis.name = 'OrgOidcTemplateUnreadable';\n\t}\n}\n","/**\n * What the deploy role may do in the stage's account.\n *\n * An SST stage creates its own stack, which is most of AWS, so its role gets\n * `AdministratorAccess`. A stage deployed with the `compose` target builds and\n * runs containers on a server; from AWS its deploy job needs only the stage's\n * secrets — read, and written back when a deploy generates a new one: the one\n * object in the project bucket, or the SSM parameter or Secrets Manager secret\n * — and,\n * when the deploy state is kept in AWS, the stage's state, and, when the\n * stage's domain is in Route53, the records of its hosted zone, and, when an\n * `s3` provider backs its buckets, those buckets and the IAM user each is\n * reached with — by the names the provider gives them — and, when it runs\n * Postgres, the project bucket its backups go to and the backups user. So a\n * compose stage gets an inline policy naming exactly those resources and\n * nothing else.\n *\n * `--policy-arn` replaces either.\n */\n\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { stageBackups } from '../backups/config.js';\nimport { backupsUserName } from '../backups/provision.js';\nimport { stageDnsDomains } from '../compose/dns.js';\nimport { stageProvider } from '../providers/config.js';\nimport {\n\tPROJECT_BUCKET_CREATE_ACTIONS,\n\tPROJECT_BUCKET_LIFECYCLE_ACTIONS,\n\tprojectBucketName,\n} from '../providers/projectBucket.js';\nimport {\n\tbucketName,\n\tIAM_USER_PATH,\n\tiamUserName,\n\tSUFFIX_LENGTH,\n} from '../providers/s3/naming.js';\nimport { emailUserName } from '../providers/ses/config.js';\nimport { secretsParameterName } from '../secrets/aws.js';\nimport { s3SecretsKey, s3SecretsLocation } from '../secrets/providers.js';\nimport { secretsManagerSecretName } from '../secrets/secretsManager.js';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport { deployIdentity } from './identity.js';\n\n/**\n * What SST needs to create a stack is most of AWS, so this is the default\n * outside compose — said out loud in the output, and replaceable with\n * `--policy-arn`.\n */\nexport const DEFAULT_POLICY_ARN = 'arn:aws:iam::aws:policy/AdministratorAccess';\n\n/** The name of the inline policy a compose stage's role is given. */\nexport const SCOPED_POLICY_NAME = 'gkm-deploy';\n\n/** One statement of an IAM policy document. */\nexport interface PolicyStatement {\n\tSid: string;\n\tEffect: 'Allow';\n\tAction: string[];\n\tResource: string | string[];\n\tCondition?: Record<string, Record<string, string>>;\n}\n\n/** What the role is given. */\nexport type DeployAccess =\n\t| {\n\t\t\tkind: 'managed';\n\t\t\tpolicyArn: string;\n\t\t\t/** Why, for the output. */\n\t\t\treason: string;\n\t }\n\t| {\n\t\t\tkind: 'scoped';\n\t\t\t/** The statements, in the account the role is in. */\n\t\t\tstatements(account: string): PolicyStatement[];\n\t\t\t/** What each statement is for, for the output. */\n\t\t\tdescribe: string[];\n\t };\n\n/** Every target the stage's apps deploy through. */\nexport function deployTargets(workspace: NormalizedWorkspace): string[] {\n\tconst targets = new Set<string>([workspace.deploy?.default ?? 'dokploy']);\n\tfor (const app of Object.values(workspace.apps)) {\n\t\ttargets.add(app.resolvedDeployTarget);\n\t}\n\treturn [...targets].sort();\n}\n\n/**\n * The access the stage's deploy role is given: `--policy-arn` when passed,\n * the scoped policy for a stage only the compose target deploys, and\n * `AdministratorAccess` otherwise.\n */\nexport function deployAccess(\n\tworkspace: NormalizedWorkspace,\n\tstage: string,\n\tpolicyArn?: string,\n\t/** The stage's constructs: its buckets, and whether it runs Postgres. */\n\tmanifest: ConstructManifest = {},\n): DeployAccess {\n\tconst buckets = Object.entries(manifest)\n\t\t.filter(([, d]) => d.kind === 'objects')\n\t\t.map(([id]) => id);\n\tif (policyArn) {\n\t\treturn { kind: 'managed', policyArn, reason: '--policy-arn' };\n\t}\n\n\tconst targets = deployTargets(workspace);\n\tif (targets.length !== 1 || targets[0] !== 'compose') {\n\t\treturn {\n\t\t\tkind: 'managed',\n\t\t\tpolicyArn: DEFAULT_POLICY_ARN,\n\t\t\treason: `the ${targets.join(', ')} target${targets.length === 1 ? '' : 's'} deploy${targets.length === 1 ? 's' : ''} infrastructure; --policy-arn to narrow`,\n\t\t};\n\t}\n\n\tconst project = workspace.name;\n\tconst store = workspace.secrets.store ?? 'file';\n\tconst state = workspace.state;\n\tconst custom =\n\t\t(typeof store === 'object' && typeof store.provider === 'object') ||\n\t\t(state !== undefined && typeof state.provider === 'object');\n\tif (custom) {\n\t\treturn {\n\t\t\tkind: 'managed',\n\t\t\tpolicyArn: DEFAULT_POLICY_ARN,\n\t\t\treason: `a custom ${typeof store === 'object' && typeof store.provider === 'object' ? 'secrets store' : 'state provider'} cannot be scoped; --policy-arn to narrow`,\n\t\t};\n\t}\n\n\tconst describe: string[] = [];\n\tconst build: ((account: string) => PolicyStatement[])[] = [];\n\n\t// The project bucket's name is fixed by the account, so the role is given\n\t// exactly it, and the actions that create it for whichever run is first.\n\tconst projectBucketIn = (account: string) =>\n\t\tprojectBucketName(deployIdentity(workspace, stage).scope, account);\n\tconst projectBucketStatement = (account: string): PolicyStatement => ({\n\t\tSid: 'ProjectBucket',\n\t\tEffect: 'Allow',\n\t\tAction: [...PROJECT_BUCKET_CREATE_ACTIONS],\n\t\tResource: `arn:aws:s3:::${projectBucketIn(account)}`,\n\t});\n\t// Whether the state's statements already cover the secrets' bucket.\n\tconst stateInSecretsBucket =\n\t\ttypeof store === 'object' &&\n\t\tstore.provider === 's3' &&\n\t\tstate?.provider === 's3' &&\n\t\tstate.bucket === (store as { bucket?: string }).bucket;\n\n\tif (typeof store === 'object' && store.provider === 's3') {\n\t\tconst location = s3SecretsLocation(store, state);\n\t\tconst key = s3SecretsKey(location.prefix, project, stage);\n\t\tconst named = location.bucket;\n\t\tconst bucketIn = (account: string) => named ?? projectBucketIn(account);\n\t\tdescribe.push(\n\t\t\tnamed\n\t\t\t\t? `read and update s3://${named}/${key}`\n\t\t\t\t: `read and update ${key} in the project bucket ${projectBucketIn('<account>')}${stateInSecretsBucket ? '' : ', creating it'}`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageSecrets',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['s3:GetObject', 's3:PutObject'],\n\t\t\t\tResource: `arn:aws:s3:::${bucketIn(account)}/${key}`,\n\t\t\t},\n\t\t\t// The state's statements give these when it is in the same bucket.\n\t\t\t...(stateInSecretsBucket\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// HeadBucket, and secrets not written yet a 404, not a 403.\n\t\t\t\t\t\t\tSid: 'StageSecretsBucket',\n\t\t\t\t\t\t\tEffect: 'Allow' as const,\n\t\t\t\t\t\t\tAction: ['s3:ListBucket'],\n\t\t\t\t\t\t\tResource: `arn:aws:s3:::${bucketIn(account)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(named ? [] : [projectBucketStatement(account)]),\n\t\t\t\t\t]),\n\t\t]);\n\t} else if (typeof store === 'object' && store.provider === 'ssm') {\n\t\tconst { region } = store;\n\t\tconst name = secretsParameterName(project, stage);\n\t\tdescribe.push(`read and update ${name} (SSM, ${region})`);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageSecrets',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['ssm:GetParameter', 'ssm:PutParameter'],\n\t\t\t\tResource: `arn:aws:ssm:${region}:${account}:parameter${name}`,\n\t\t\t},\n\t\t]);\n\t} else if (\n\t\ttypeof store === 'object' &&\n\t\tstore.provider === 'secrets-manager'\n\t) {\n\t\tconst { region, kmsKeyId } = store as { region: string; kmsKeyId?: string };\n\t\tconst name = secretsManagerSecretName(project, stage);\n\t\tdescribe.push(`read and update ${name} (Secrets Manager, ${region})`);\n\t\tbuild.push((account) => {\n\t\t\tconst statements: PolicyStatement[] = [\n\t\t\t\t{\n\t\t\t\t\tSid: 'StageSecrets',\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tAction: [\n\t\t\t\t\t\t'secretsmanager:GetSecretValue',\n\t\t\t\t\t\t'secretsmanager:PutSecretValue',\n\t\t\t\t\t\t'secretsmanager:CreateSecret',\n\t\t\t\t\t],\n\t\t\t\t\t// Secrets Manager appends six random characters to a secret's ARN.\n\t\t\t\t\tResource: `arn:aws:secretsmanager:${region}:${account}:secret:${name}-??????`,\n\t\t\t\t},\n\t\t\t];\n\t\t\tif (kmsKeyId) {\n\t\t\t\tstatements.push({\n\t\t\t\t\tSid: 'StageSecretsKey',\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tAction: ['kms:Decrypt', 'kms:GenerateDataKey'],\n\t\t\t\t\tResource: kmsKeyId.startsWith('arn:') ? kmsKeyId : '*',\n\t\t\t\t\tCondition: {\n\t\t\t\t\t\tStringEquals: {\n\t\t\t\t\t\t\t'kms:ViaService': `secretsmanager.${region}.amazonaws.com`,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn statements;\n\t\t});\n\t}\n\n\tif (state?.provider === 'ssm') {\n\t\tconst { region } = state;\n\t\tconst path = `/gkm/${project}/${stage}/`;\n\t\tdescribe.push(\n\t\t\t`read and write the deploy state under ${path} (SSM, ${region})`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageState',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['ssm:GetParameter', 'ssm:PutParameter', 'ssm:DeleteParameter'],\n\t\t\t\tResource: `arn:aws:ssm:${region}:${account}:parameter${path}*`,\n\t\t\t},\n\t\t]);\n\t} else if (state?.provider === 's3') {\n\t\tconst prefix = (state.prefix ?? 'gkm').replace(/\\/+$/, '');\n\t\tconst path = `${prefix ? `${prefix}/` : ''}${project}/${stage}/`;\n\t\tconst named = state.bucket;\n\t\t// No bucket named: the project bucket, which the first deploy creates.\n\t\tconst bucketIn = (account: string) => named ?? projectBucketIn(account);\n\t\tdescribe.push(\n\t\t\tnamed\n\t\t\t\t? `read and write the deploy state under s3://${named}/${path}`\n\t\t\t\t: `create the project bucket ${projectBucketIn('<account>')}, and read and write the deploy state under ${path} in it`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t...stateBucketStatements(bucketIn(account), path),\n\t\t\t...(named ? [] : [projectBucketStatement(account)]),\n\t\t]);\n\t}\n\n\t// The deploy creates each bucket an s3 provider backs, and the IAM user\n\t// and key it is reached with: by their names — the good one, or the good\n\t// one with a clash's six-character suffix — and nothing else.\n\tconst objects = stageProvider(workspace, 'objects', stage);\n\tif (objects.mode === 'provider' && objects.name === 's3' && buckets.length) {\n\t\tconst { scope } = deployIdentity(workspace, stage);\n\t\tconst names = [...buckets].sort().map((id) => ({\n\t\t\tbucket: bucketName({ scope, stage, id }),\n\t\t\tuser: iamUserName({ scope, stage, id }),\n\t\t}));\n\t\tconst suffix = '?'.repeat(SUFFIX_LENGTH - 1);\n\t\tdescribe.push(\n\t\t\t`create and configure the buckets ${names.map((n) => n.bucket).join(', ')}, their IAM users, and — for a bucket a subscriber watches — its events topic, dead-letter queue and subscriptions (S3, IAM, SNS, SQS)`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageBuckets',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t's3:CreateBucket',\n\t\t\t\t\t's3:ListBucket',\n\t\t\t\t\t's3:GetBucketTagging',\n\t\t\t\t\t's3:PutBucketTagging',\n\t\t\t\t\t's3:GetBucketPublicAccessBlock',\n\t\t\t\t\t's3:PutBucketPublicAccessBlock',\n\t\t\t\t\t's3:GetBucketPolicy',\n\t\t\t\t\t's3:PutBucketPolicy',\n\t\t\t\t\t's3:GetEncryptionConfiguration',\n\t\t\t\t\t's3:PutEncryptionConfiguration',\n\t\t\t\t\t's3:GetBucketVersioning',\n\t\t\t\t\t's3:PutBucketVersioning',\n\t\t\t\t\t's3:GetBucketCORS',\n\t\t\t\t\t's3:PutBucketCORS',\n\t\t\t\t\t's3:GetBucketNotification',\n\t\t\t\t\t's3:PutBucketNotification',\n\t\t\t\t\t// A construct's `expire`, and removing it: S3 authorises\n\t\t\t\t\t// DeleteBucketLifecycle as PutLifecycleConfiguration.\n\t\t\t\t\t's3:GetLifecycleConfiguration',\n\t\t\t\t\t's3:PutLifecycleConfiguration',\n\t\t\t\t],\n\t\t\t\tResource: names.flatMap((n) => [\n\t\t\t\t\t`arn:aws:s3:::${n.bucket}`,\n\t\t\t\t\t`arn:aws:s3:::${n.bucket}-${suffix}`,\n\t\t\t\t]),\n\t\t\t},\n\t\t\t// A watched bucket's events: its topic and the subscriptions to it —\n\t\t\t// in whichever region the bucket is — and its dead-letter queue.\n\t\t\t{\n\t\t\t\tSid: 'StageBucketTopics',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'sns:CreateTopic',\n\t\t\t\t\t'sns:TagResource',\n\t\t\t\t\t'sns:GetTopicAttributes',\n\t\t\t\t\t'sns:SetTopicAttributes',\n\t\t\t\t\t'sns:Subscribe',\n\t\t\t\t\t'sns:Unsubscribe',\n\t\t\t\t\t'sns:ListSubscriptionsByTopic',\n\t\t\t\t\t'sns:GetSubscriptionAttributes',\n\t\t\t\t\t'sns:SetSubscriptionAttributes',\n\t\t\t\t],\n\t\t\t\tResource: names.flatMap((n) =>\n\t\t\t\t\t[`${n.bucket}-events`, `${n.bucket}-${suffix}-events`].flatMap(\n\t\t\t\t\t\t(topic) => [\n\t\t\t\t\t\t\t`arn:aws:sns:*:${account}:${topic}`,\n\t\t\t\t\t\t\t`arn:aws:sns:*:${account}:${topic}:*`,\n\t\t\t\t\t\t],\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageBucketDeadLetters',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'sqs:CreateQueue',\n\t\t\t\t\t'sqs:TagQueue',\n\t\t\t\t\t'sqs:GetQueueUrl',\n\t\t\t\t\t'sqs:GetQueueAttributes',\n\t\t\t\t\t'sqs:SetQueueAttributes',\n\t\t\t\t],\n\t\t\t\tResource: names.flatMap((n) => [\n\t\t\t\t\t`arn:aws:sqs:*:${account}:${n.bucket}-events-dlq`,\n\t\t\t\t\t`arn:aws:sqs:*:${account}:${n.bucket}-${suffix}-events-dlq`,\n\t\t\t\t]),\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageBucketUsers',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'iam:GetUser',\n\t\t\t\t\t'iam:CreateUser',\n\t\t\t\t\t'iam:TagUser',\n\t\t\t\t\t'iam:ListUserTags',\n\t\t\t\t\t'iam:GetUserPolicy',\n\t\t\t\t\t'iam:PutUserPolicy',\n\t\t\t\t\t'iam:ListAccessKeys',\n\t\t\t\t\t'iam:CreateAccessKey',\n\t\t\t\t\t'iam:DeleteAccessKey',\n\t\t\t\t],\n\t\t\t\tResource: names.map(\n\t\t\t\t\t(n) => `arn:aws:iam::${account}:user${IAM_USER_PATH}${n.user}`,\n\t\t\t\t),\n\t\t\t},\n\t\t]);\n\n\t\t// Each file server behind a CDN: its certificate, its origin access\n\t\t// control, its response headers policies and its distribution. Neither\n\t\t// ACM nor CloudFront scopes creating these to a name, so they are on\n\t\t// every resource of the account; nothing here deletes.\n\t\tconst served = Object.values(manifest).some(\n\t\t\t(d) => d.kind === 'file-server',\n\t\t);\n\t\tif (served && (objects.config as { cdn?: boolean }).cdn !== false) {\n\t\t\tdescribe.push(\n\t\t\t\t'create the file servers’ certificates and CloudFront distributions (ACM, CloudFront)',\n\t\t\t);\n\t\t\tbuild.push(() => [\n\t\t\t\t{\n\t\t\t\t\tSid: 'StageFileServerCertificates',\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tAction: [\n\t\t\t\t\t\t'acm:RequestCertificate',\n\t\t\t\t\t\t'acm:DescribeCertificate',\n\t\t\t\t\t\t'acm:ListCertificates',\n\t\t\t\t\t\t'acm:AddTagsToCertificate',\n\t\t\t\t\t],\n\t\t\t\t\tResource: '*',\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tSid: 'StageFileServerCdn',\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tAction: [\n\t\t\t\t\t\t'cloudfront:CreateDistribution',\n\t\t\t\t\t\t'cloudfront:CreateDistributionWithTags',\n\t\t\t\t\t\t'cloudfront:GetDistribution',\n\t\t\t\t\t\t'cloudfront:GetDistributionConfig',\n\t\t\t\t\t\t'cloudfront:UpdateDistribution',\n\t\t\t\t\t\t'cloudfront:ListDistributions',\n\t\t\t\t\t\t'cloudfront:TagResource',\n\t\t\t\t\t\t'cloudfront:CreateOriginAccessControl',\n\t\t\t\t\t\t'cloudfront:GetOriginAccessControl',\n\t\t\t\t\t\t'cloudfront:ListOriginAccessControls',\n\t\t\t\t\t\t'cloudfront:CreateResponseHeadersPolicy',\n\t\t\t\t\t\t'cloudfront:GetResponseHeadersPolicy',\n\t\t\t\t\t\t'cloudfront:GetResponseHeadersPolicyConfig',\n\t\t\t\t\t\t'cloudfront:UpdateResponseHeadersPolicy',\n\t\t\t\t\t\t'cloudfront:ListResponseHeadersPolicies',\n\t\t\t\t\t],\n\t\t\t\t\tResource: '*',\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t}\n\n\t// The deploy creates each mail construct's sender when an ses provider\n\t// sends its mail: the identity, verified by DKIM — SES scopes none of\n\t// these to a name — and each construct's IAM user and key, by name.\n\tconst emails = Object.entries(manifest)\n\t\t.filter(([, d]) => d.kind === 'email')\n\t\t.map(([id]) => id)\n\t\t.sort();\n\tconst email = stageProvider(workspace, 'email', stage);\n\tif (email.mode === 'provider' && email.name === 'ses' && emails.length) {\n\t\tconst { scope } = deployIdentity(workspace, stage);\n\t\tconst users = emails.map((id) => emailUserName(scope, stage, id));\n\t\tdescribe.push(\n\t\t\t`verify the sending domain in SES and create the mail users ${users.join(', ')} and their keys (SES, IAM)`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageMailIdentity',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'ses:GetIdentityDkimAttributes',\n\t\t\t\t\t'ses:VerifyDomainDkim',\n\t\t\t\t\t'ses:SetIdentityDkimEnabled',\n\t\t\t\t\t'ses:GetSendQuota',\n\t\t\t\t],\n\t\t\t\tResource: '*',\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageMailUsers',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'iam:GetUser',\n\t\t\t\t\t'iam:CreateUser',\n\t\t\t\t\t'iam:TagUser',\n\t\t\t\t\t'iam:ListUserTags',\n\t\t\t\t\t'iam:GetUserPolicy',\n\t\t\t\t\t'iam:PutUserPolicy',\n\t\t\t\t\t'iam:ListAccessKeys',\n\t\t\t\t\t'iam:CreateAccessKey',\n\t\t\t\t\t'iam:DeleteAccessKey',\n\t\t\t\t],\n\t\t\t\tResource: users.map(\n\t\t\t\t\t(user) => `arn:aws:iam::${account}:user${IAM_USER_PATH}${user}`,\n\t\t\t\t),\n\t\t\t},\n\t\t]);\n\t}\n\n\t// The stage's backups: the deploy creates the project bucket if it is not\n\t// there, keeps its lifecycle, and creates the backups user and its key.\n\t// The role never reads the backups — `gkm backup:list` and `:restore`\n\t// run with a person's own credentials.\n\tif (stageBackups(workspace, manifest, stage).mode === 'on') {\n\t\tconst { scope } = deployIdentity(workspace, stage);\n\t\tconst user = backupsUserName(scope, stage);\n\t\tconst bucketIn = (account: string) => projectBucketName(scope, account);\n\t\tdescribe.push(\n\t\t\t`create the project bucket ${bucketIn('<account>')} and keep its lifecycle, and create the backups user ${user} and its key (S3, IAM)`,\n\t\t);\n\t\tbuild.push((account) => [\n\t\t\t{\n\t\t\t\tSid: 'StageBackupsBucket',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t's3:ListBucket',\n\t\t\t\t\t...new Set([\n\t\t\t\t\t\t...PROJECT_BUCKET_CREATE_ACTIONS,\n\t\t\t\t\t\t...PROJECT_BUCKET_LIFECYCLE_ACTIONS,\n\t\t\t\t\t]),\n\t\t\t\t],\n\t\t\t\tResource: `arn:aws:s3:::${bucketIn(account)}`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageBackupsUser',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'iam:GetUser',\n\t\t\t\t\t'iam:CreateUser',\n\t\t\t\t\t'iam:TagUser',\n\t\t\t\t\t'iam:ListUserTags',\n\t\t\t\t\t'iam:GetUserPolicy',\n\t\t\t\t\t'iam:PutUserPolicy',\n\t\t\t\t\t'iam:ListAccessKeys',\n\t\t\t\t\t'iam:CreateAccessKey',\n\t\t\t\t\t'iam:DeleteAccessKey',\n\t\t\t\t],\n\t\t\t\tResource: `arn:aws:iam::${account}:user${IAM_USER_PATH}${user}`,\n\t\t\t},\n\t\t]);\n\t}\n\n\t// The deploy writes the stage's hosts' records: in Route53, only that\n\t// zone's — and, with no hostedZoneId to name it, the zone is looked up\n\t// by name, which IAM cannot scope.\n\tfor (const { domain, config } of stageDnsDomains(\n\t\tstage,\n\t\tworkspace.domains,\n\t\tworkspace.dns,\n\t)) {\n\t\tif (config.provider !== 'route53') continue;\n\t\tconst zoneId = (config as { hostedZoneId?: string }).hostedZoneId?.replace(\n\t\t\t/^\\/?hostedzone\\//,\n\t\t\t'',\n\t\t);\n\t\tdescribe.push(\n\t\t\t`write the A, AAAA and CNAME records of ${domain} (Route53${zoneId ? `, ${zoneId}` : ''})`,\n\t\t);\n\t\tbuild.push(() => [\n\t\t\t{\n\t\t\t\tSid: 'StageDnsRecords',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: [\n\t\t\t\t\t'route53:ChangeResourceRecordSets',\n\t\t\t\t\t'route53:ListResourceRecordSets',\n\t\t\t\t],\n\t\t\t\tResource: `arn:aws:route53:::hostedzone/${zoneId ?? '*'}`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tSid: 'StageDnsChanges',\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tAction: ['route53:GetChange'],\n\t\t\t\tResource: 'arn:aws:route53:::change/*',\n\t\t\t},\n\t\t\t...(zoneId\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSid: 'StageDnsZones',\n\t\t\t\t\t\t\tEffect: 'Allow' as const,\n\t\t\t\t\t\t\tAction: ['route53:ListHostedZonesByName'],\n\t\t\t\t\t\t\tResource: '*',\n\t\t\t\t\t\t},\n\t\t\t\t\t]),\n\t\t]);\n\t}\n\n\treturn {\n\t\tkind: 'scoped',\n\t\tstatements: (account) => build.flatMap((statements) => statements(account)),\n\t\tdescribe,\n\t};\n}\n\n/**\n * Reading and writing one stage's deploy state in `bucket`, as the deploy\n * role is given it.\n */\nexport function stateBucketStatements(\n\tbucket: string,\n\tpath: string,\n): PolicyStatement[] {\n\treturn [\n\t\t{\n\t\t\tSid: 'StageState',\n\t\t\tEffect: 'Allow',\n\t\t\tAction: ['s3:GetObject', 's3:PutObject', 's3:DeleteObject'],\n\t\t\tResource: `arn:aws:s3:::${bucket}/${path}*`,\n\t\t},\n\t\t// HeadBucket, and a state not written yet a 404 rather than a 403.\n\t\t{\n\t\t\tSid: 'StageStateBucket',\n\t\t\tEffect: 'Allow',\n\t\t\tAction: ['s3:ListBucket'],\n\t\t\tResource: `arn:aws:s3:::${bucket}`,\n\t\t},\n\t];\n}\n\n/** The scoped access as a policy document, or null when it allows nothing. */\nexport function scopedPolicyDocument(\n\tstatements: PolicyStatement[],\n): string | null {\n\tif (statements.length === 0) return null;\n\treturn JSON.stringify({ Version: '2012-10-17', Statement: statements });\n}\n\n/** The account an IAM ARN is in: `arn:aws:iam::<account>:…`. */\nexport function accountOf(arn: string): string {\n\treturn arn.split(':')[4] ?? '';\n}\n","/**\n * `gkm deploy:github` — let GitHub Actions deploy one stage, with no keys.\n *\n * A stage usually lives in its own AWS account — staging in one, production in\n * another — so this runs once per stage, with that account's profile:\n *\n * gkm deploy:github --stage staging --profile acme-dev\n * gkm deploy:github --stage prod --profile acme-prod\n *\n * In the stage's account it makes sure GitHub's OIDC provider exists, and a\n * role that only this repository's `<stage>` environment can assume. On\n * GitHub it creates that environment and gives it what the generated deploy\n * workflow reads: `AWS_ROLE_ARN`, and — when the stage's secrets are kept in\n * the local file — its key as `GKM_SECRETS_KEY`. With `secrets.store` set to\n * S3, SSM or Secrets Manager the deploy job reads them with the role instead, so\n * no key is handed to GitHub, and this checks the stage's store in the same\n * account, with the same profile. Re-running it converges rather than duplicating.\n *\n * The role trusts the exact `sub` GitHub sends for the environment, read from\n * the repository's OIDC subject settings (`githubOidc.ts`) — the default, the\n * immutable subject with the owner's and repository's ids, or a custom\n * template. A re-run rewrites an existing role's trust to it, so running this\n * again repairs a role that trusted the wrong format. What the role may do is\n * `githubPolicy.ts`: `AdministratorAccess` for SST, and for a compose stage\n * only its own secrets (and deploy state, when that is in AWS).\n */\n\nimport { execFileSync } from 'node:child_process';\nimport {\n\tAttachRolePolicyCommand,\n\tCreateOpenIDConnectProviderCommand,\n\tCreateRoleCommand,\n\tDeleteRolePolicyCommand,\n\tDetachRolePolicyCommand,\n\tGetRoleCommand,\n\tIAMClient,\n\ttype IAMClientConfig,\n\tListAttachedRolePoliciesCommand,\n\tListOpenIDConnectProvidersCommand,\n\tListRoleTagsCommand,\n\tPutRolePolicyCommand,\n\tTagRoleCommand,\n\tUntagRoleCommand,\n\tUpdateAssumeRolePolicyCommand,\n} from '@aws-sdk/client-iam';\nimport { loadWorkspaceConfig } from '../config.js';\nimport { GkmError } from '../errors';\nimport { discover } from '../reconcile/discover.js';\nimport { constructGlobs } from '../reconcile/workspace.js';\nimport { getKeyPath, keystoreProject, readKey } from '../secrets/keystore.js';\nimport { isRemoteStore, secretsStoreFor } from '../secrets/store.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport { resolveOidcSubject } from './githubOidc.js';\nimport {\n\taccountOf,\n\tdeployAccess,\n\tSCOPED_POLICY_NAME,\n\tscopedPolicyDocument,\n} from './githubPolicy.js';\n\nexport { DEFAULT_POLICY_ARN, SCOPED_POLICY_NAME } from './githubPolicy.js';\n\nconst logger = console;\n\nconst GITHUB_OIDC_HOST = 'token.actions.githubusercontent.com';\nconst AUDIENCE = 'sts.amazonaws.com';\n\n/**\n * The tag recording which managed policy gkm attached to the role — so a\n * re-run detaches only what gkm put there, never a policy someone else did.\n */\nexport const POLICY_TAG = 'gkm:policy-arn';\n\nexport interface DeployGithubOptions {\n\tstage: string;\n\t/** The AWS profile for the stage's account. */\n\tprofile?: string;\n\t/** `owner/name`; defaults to the repository `gh` sees here. */\n\trepo?: string;\n\t/** The policy the deploy role gets, in place of the default. */\n\tpolicyArn?: string;\n\tdryRun?: boolean;\n}\n\n/** Runs `gh` with the given arguments and optional stdin, returning stdout. */\nexport type Gh = (args: string[], input?: string) => string;\n\n/** The system's `gh`. */\nexport const ghCli: Gh = (args, input) =>\n\texecFileSync('gh', args, {\n\t\tencoding: 'utf-8',\n\t\t// stderr captured, so a read that fails (a 404) is not printed as noise.\n\t\tstdio: ['pipe', 'pipe', 'pipe'],\n\t\t...(input === undefined ? {} : { input }),\n\t}).trim();\n\n/** The role a stage deploys as: `<project>-github-<stage>`, within IAM's 64. */\nexport function roleName(project: string, stage: string): string {\n\treturn `${project}-github-${stage}`\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9+=,.@_-]/g, '-')\n\t\t.slice(0, 64);\n}\n\n/**\n * Who may assume the role: a workflow job whose OIDC token carries exactly\n * `subject` — the repository's `<stage>` environment, in the format the\n * repository sends (see `githubOidc.ts`), and nothing else. Not another\n * branch's job, not another environment's: that is what keeps a staging\n * deploy from using the production role.\n */\nexport function trustPolicy(providerArn: string, subject: string): string {\n\treturn JSON.stringify({\n\t\tVersion: '2012-10-17',\n\t\tStatement: [\n\t\t\t{\n\t\t\t\tEffect: 'Allow',\n\t\t\t\tPrincipal: { Federated: providerArn },\n\t\t\t\tAction: 'sts:AssumeRoleWithWebIdentity',\n\t\t\t\tCondition: {\n\t\t\t\t\tStringEquals: {\n\t\t\t\t\t\t[`${GITHUB_OIDC_HOST}:aud`]: AUDIENCE,\n\t\t\t\t\t\t[`${GITHUB_OIDC_HOST}:sub`]: subject,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t});\n}\n\n/**\n * The subject a trust policy trusts, or undefined when it names none. IAM\n * hands documents back URL-encoded.\n */\nexport function trustedSubject(\n\tdocument: string | undefined,\n): string | undefined {\n\tif (!document) return undefined;\n\tlet parsed: {\n\t\tStatement?: { Condition?: Record<string, Record<string, unknown>> }[];\n\t};\n\ttry {\n\t\tparsed = JSON.parse(safeDecode(document));\n\t} catch {\n\t\treturn undefined;\n\t}\n\tfor (const statement of parsed.Statement ?? []) {\n\t\tfor (const operator of Object.values(statement.Condition ?? {})) {\n\t\t\tconst value = operator[`${GITHUB_OIDC_HOST}:sub`];\n\t\t\tif (typeof value === 'string') return value;\n\t\t\tif (Array.isArray(value)) return value.join(', ');\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction safeDecode(value: string): string {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n\n/** GitHub's OIDC provider in this account, created if it is not there. */\nexport async function ensureOidcProvider(iam: IAMClient): Promise<string> {\n\tconst { OpenIDConnectProviderList = [] } = await iam.send(\n\t\tnew ListOpenIDConnectProvidersCommand({}),\n\t);\n\tconst existing = OpenIDConnectProviderList.find((p) =>\n\t\tp.Arn?.endsWith(`oidc-provider/${GITHUB_OIDC_HOST}`),\n\t)?.Arn;\n\tif (existing) return existing;\n\n\tconst created = await iam.send(\n\t\tnew CreateOpenIDConnectProviderCommand({\n\t\t\tUrl: `https://${GITHUB_OIDC_HOST}`,\n\t\t\tClientIDList: [AUDIENCE],\n\t\t}),\n\t);\n\treturn created.OpenIDConnectProviderArn!;\n}\n\n/**\n * What the role is given: a managed policy, attached; or an inline policy\n * document — null for none at all.\n */\nexport type RoleAccess = { managed: string } | { inline: string | null };\n\n/** What {@link ensureRole} did. */\nexport interface RoleOutcome {\n\tarn: string;\n\tcreated: boolean;\n\t/** The subject the role trusted before, when it existed. */\n\tpreviousSubject?: string;\n\t/** Managed policies gkm had attached and detached now. */\n\tdetached: string[];\n\t/**\n\t * Managed policies still attached that the role no longer needs, which gkm\n\t * did not record attaching — left alone, for a person to detach.\n\t */\n\tleftAttached: string[];\n}\n\nfunction isNoSuchEntity(error: unknown): boolean {\n\treturn (error as { name?: string }).name === 'NoSuchEntityException';\n}\n\n/**\n * The deploy role, created or brought back to this trust and access.\n *\n * Converges: re-running rewrites the trust, and moves the role from one access\n * to another — detaching a managed policy only when the role's\n * {@link POLICY_TAG} says gkm attached it.\n */\nexport async function ensureRole(\n\tiam: IAMClient,\n\tname: string,\n\ttrust: string,\n\taccess: RoleAccess,\n): Promise<RoleOutcome> {\n\tlet arn: string;\n\tlet created = false;\n\tlet previousSubject: string | undefined;\n\tlet recorded: string | undefined;\n\ttry {\n\t\tconst { Role } = await iam.send(new GetRoleCommand({ RoleName: name }));\n\t\tpreviousSubject = trustedSubject(Role!.AssumeRolePolicyDocument);\n\t\tawait iam.send(\n\t\t\tnew UpdateAssumeRolePolicyCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tPolicyDocument: trust,\n\t\t\t}),\n\t\t);\n\t\tarn = Role!.Arn!;\n\t\tconst { Tags = [] } = await iam.send(\n\t\t\tnew ListRoleTagsCommand({ RoleName: name }),\n\t\t);\n\t\trecorded = Tags.find((tag) => tag.Key === POLICY_TAG)?.Value;\n\t} catch (error) {\n\t\tif (!isNoSuchEntity(error)) throw error;\n\t\tconst { Role } = await iam.send(\n\t\t\tnew CreateRoleCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tAssumeRolePolicyDocument: trust,\n\t\t\t\tDescription: 'Deploys from GitHub Actions (gkm deploy:github)',\n\t\t\t\t// SST deploys can run long; the default hour is tight.\n\t\t\t\tMaxSessionDuration: 3600 * 2,\n\t\t\t}),\n\t\t);\n\t\tarn = Role!.Arn!;\n\t\tcreated = true;\n\t}\n\n\tconst detached: string[] = [];\n\tconst leftAttached: string[] = [];\n\tconst detach = async (policyArn: string) => {\n\t\ttry {\n\t\t\tawait iam.send(\n\t\t\t\tnew DetachRolePolicyCommand({ RoleName: name, PolicyArn: policyArn }),\n\t\t\t);\n\t\t\tdetached.push(policyArn);\n\t\t} catch (error) {\n\t\t\t// Already gone — by hand, or a run that stopped halfway.\n\t\t\tif (!isNoSuchEntity(error)) throw error;\n\t\t}\n\t};\n\tconst deleteInline = async () => {\n\t\ttry {\n\t\t\tawait iam.send(\n\t\t\t\tnew DeleteRolePolicyCommand({\n\t\t\t\t\tRoleName: name,\n\t\t\t\t\tPolicyName: SCOPED_POLICY_NAME,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (!isNoSuchEntity(error)) throw error;\n\t\t}\n\t};\n\n\tif ('managed' in access) {\n\t\t// Attaching an attached policy is a no-op, so this converges too.\n\t\tawait iam.send(\n\t\t\tnew AttachRolePolicyCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tPolicyArn: access.managed,\n\t\t\t}),\n\t\t);\n\t\tif (recorded && recorded !== access.managed) await detach(recorded);\n\t\tif (recorded !== access.managed) {\n\t\t\tawait iam.send(\n\t\t\t\tnew TagRoleCommand({\n\t\t\t\t\tRoleName: name,\n\t\t\t\t\tTags: [{ Key: POLICY_TAG, Value: access.managed }],\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tif (!created) await deleteInline();\n\t\treturn { arn, created, previousSubject, detached, leftAttached };\n\t}\n\n\tif (access.inline) {\n\t\tawait iam.send(\n\t\t\tnew PutRolePolicyCommand({\n\t\t\t\tRoleName: name,\n\t\t\t\tPolicyName: SCOPED_POLICY_NAME,\n\t\t\t\tPolicyDocument: access.inline,\n\t\t\t}),\n\t\t);\n\t} else if (!created) {\n\t\tawait deleteInline();\n\t}\n\tif (created) return { arn, created, previousSubject, detached, leftAttached };\n\n\tif (recorded) {\n\t\tawait detach(recorded);\n\t\tawait iam.send(\n\t\t\tnew UntagRoleCommand({ RoleName: name, TagKeys: [POLICY_TAG] }),\n\t\t);\n\t}\n\t// A role from before gkm recorded what it attached: what is attached may\n\t// be gkm's or someone's own, so it is named, not detached.\n\tconst { AttachedPolicies = [] } = await iam.send(\n\t\tnew ListAttachedRolePoliciesCommand({ RoleName: name }),\n\t);\n\tfor (const policy of AttachedPolicies) {\n\t\tif (policy.PolicyArn && !detached.includes(policy.PolicyArn)) {\n\t\t\tleftAttached.push(policy.PolicyArn);\n\t\t}\n\t}\n\treturn { arn, created, previousSubject, detached, leftAttached };\n}\n\n/**\n * An IAM client for the stage's account.\n *\n * `fromIni` for a named profile, deliberately: it resolves exactly that\n * profile — keys, assume-role, `credential_process` or SSO, whichever\n * ~/.aws/config says — and never falls back to AWS_* in the environment. The\n * provider chain checks the environment first, so exported staging keys would\n * quietly win over `--profile prod` and the production role would land in the\n * staging account.\n */\nexport async function iamFor(\n\tprofile?: string,\n\tendpoint?: string,\n): Promise<IAMClient> {\n\tconst config: IAMClientConfig = { region: 'us-east-1' };\n\tif (profile) {\n\t\tconst { fromIni } = await import('@aws-sdk/credential-providers');\n\t\tconfig.credentials = fromIni({ profile });\n\t}\n\tif (endpoint) {\n\t\tconfig.endpoint = endpoint;\n\t\tconfig.credentials = { accessKeyId: 'test', secretAccessKey: 'test' };\n\t}\n\treturn new IAMClient(config);\n}\n\nexport async function deployGithubCommand(\n\toptions: DeployGithubOptions,\n\tdeps: { iam?: IAMClient; gh?: Gh; cwd?: string } = {},\n): Promise<{ roleArn?: string; repo: string; subject: string }> {\n\tconst gh = deps.gh ?? ghCli;\n\tconst { workspace } = await loadWorkspaceConfig(deps.cwd);\n\tassertDeployedStage(workspace.stages, options.stage);\n\n\tconst repo =\n\t\toptions.repo ??\n\t\tgh(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']);\n\tconst role = roleName(workspace.name, options.stage);\n\t// The exact subject GitHub will send — read from the repository's OIDC\n\t// settings, before anything is changed, so a format no role can trust\n\t// fails here.\n\tconst oidc = resolveOidcSubject(gh, repo, options.stage);\n\t// The buckets an s3 provider creates are named after their constructs,\n\t// and a stage with a database is backed up: the role is scoped to\n\t// exactly those.\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t});\n\tconst access = deployAccess(\n\t\tworkspace,\n\t\toptions.stage,\n\t\toptions.policyArn,\n\t\tmanifest,\n\t);\n\t// Read through the keystore so a key still at the place keys used to be kept\n\t// is found, and copied to where it is kept now.\n\tconst key = await readKey(options.stage, keystoreProject(workspace));\n\tconst keyPath = getKeyPath(options.stage, keystoreProject(workspace));\n\tconst hasKey = key !== null;\n\t// A stage whose secrets are in a store is read from there by the deploy job,\n\t// with the role; it needs no key on GitHub.\n\tconst remote = isRemoteStore(workspace, options.stage);\n\t// Read from the stage's own store, with the same credentials the role is\n\t// created with: what the deploy job will find there.\n\tconst store = await secretsStoreFor(workspace, options.stage, {\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst hasSecrets = remote && (await store.read(options.stage)) !== null;\n\tconst via = options.profile\n\t\t? `profile \"${options.profile}\"`\n\t\t: 'the default credentials';\n\n\tlogger.log(`\\n🔐 GitHub → AWS for stage \"${options.stage}\"\\n`);\n\tlogger.log(` Repository: ${repo}`);\n\tlogger.log(` AWS profile: ${options.profile ?? '(default credentials)'}`);\n\tlogger.log(` Role: ${role}`);\n\tif (access.kind === 'managed') {\n\t\tlogger.log(` Policy: ${access.policyArn} (${access.reason})`);\n\t} else if (access.describe.length > 0) {\n\t\tlogger.log(\n\t\t\t` Policy: inline \"${SCOPED_POLICY_NAME}\", scoped to the compose deploy — only:`,\n\t\t);\n\t\tfor (const line of access.describe) logger.log(` ${line}`);\n\t} else {\n\t\tlogger.log(\n\t\t\t' Policy: none — a compose deploy with file secrets and local state reads nothing from AWS',\n\t\t);\n\t}\n\tlogger.log(\n\t\t` Trusted by: ${oidc.subject} only (${SUBJECT_KINDS[oidc.kind]})`,\n\t);\n\tif (oidc.warning) logger.log(` ⚠ ${oidc.warning}`);\n\tif (remote) {\n\t\tlogger.log(\n\t\t\t` Secrets: ${hasSecrets ? `in the store (${store.name}), read with ${via}` : `none in the store yet — gkm secrets:set <KEY> '…' --stage ${options.stage}`}`,\n\t\t);\n\t} else {\n\t\tlogger.log(\n\t\t\t` Secrets key: ${hasKey ? keyPath : `none at ${keyPath} — run gkm secrets:init --stage ${options.stage} first`}`,\n\t\t);\n\t}\n\n\tif (options.dryRun) {\n\t\tif (access.kind === 'scoped') {\n\t\t\tconst document = scopedPolicyDocument(access.statements('<account>'));\n\t\t\tif (document) {\n\t\t\t\tlogger.log(\n\t\t\t\t\t`\\n Inline policy:\\n${JSON.stringify(JSON.parse(document), null, 2).replace(/^/gm, ' ')}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tlogger.log('\\n --dry-run: nothing changed.\\n');\n\t\treturn { repo, subject: oidc.subject };\n\t}\n\n\tconst iam = deps.iam ?? (await iamFor(options.profile));\n\tconst providerArn = await ensureOidcProvider(iam).catch((error) => {\n\t\t// The first AWS call is where an expired SSO login surfaces; the SDK's\n\t\t// message does not say which profile, and this command knows.\n\t\tif (/SSO session/i.test(String(error?.message)) && options.profile) {\n\t\t\tthrow new SsoSessionExpired(options.profile);\n\t\t}\n\t\tthrow error;\n\t});\n\tconst outcome = await ensureRole(\n\t\tiam,\n\t\trole,\n\t\ttrustPolicy(providerArn, oidc.subject),\n\t\taccess.kind === 'managed'\n\t\t\t? { managed: access.policyArn }\n\t\t\t: {\n\t\t\t\t\tinline: scopedPolicyDocument(\n\t\t\t\t\t\taccess.statements(accountOf(providerArn)),\n\t\t\t\t\t),\n\t\t\t\t},\n\t);\n\tconst roleArn = outcome.arn;\n\tlogger.log(`\\n ✓ AWS: ${roleArn}${outcome.created ? ' (created)' : ''}`);\n\tif (!outcome.created) {\n\t\tlogger.log(\n\t\t\toutcome.previousSubject === oidc.subject\n\t\t\t\t? ` ✓ Trust: unchanged, ${oidc.subject}`\n\t\t\t\t: ` ✓ Trust: ${outcome.previousSubject ?? '(no subject)'} → ${oidc.subject}`,\n\t\t);\n\t}\n\tfor (const detached of outcome.detached) {\n\t\tlogger.log(` ✓ Detached ${detached} (attached by gkm, no longer needed)`);\n\t}\n\tif (access.kind === 'scoped') {\n\t\tfor (const attached of outcome.leftAttached) {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ ${attached} is still attached to ${role}. gkm has no record of attaching it, so it is left; the compose deploy does not need it. Detach it with: aws iam detach-role-policy --role-name ${role} --policy-arn ${attached}${options.profile ? ` --profile ${options.profile}` : ''}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// The environment the generated deploy workflow runs the stage in.\n\tgh(['api', '--method', 'PUT', `repos/${repo}/environments/${options.stage}`]);\n\tgh([\n\t\t'variable',\n\t\t'set',\n\t\t'AWS_ROLE_ARN',\n\t\t'--env',\n\t\toptions.stage,\n\t\t'--repo',\n\t\trepo,\n\t\t'--body',\n\t\troleArn,\n\t]);\n\tlogger.log(` ✓ GitHub: environment \"${options.stage}\", AWS_ROLE_ARN`);\n\n\tif (remote) {\n\t\t// Nothing to send: the deploy job reads the stage's store itself.\n\t\tif (!hasSecrets) {\n\t\t\tlogger.log(\n\t\t\t\t` ⚠ The \"${options.stage}\" store holds no secrets yet; set them with gkm secrets:set <KEY> '…' --stage ${options.stage}${options.profile ? ` (AWS_PROFILE=${options.profile})` : ''}.`,\n\t\t\t);\n\t\t}\n\t} else if (hasKey) {\n\t\t// Through stdin, so the key is never an argument a process list shows.\n\t\tgh(\n\t\t\t[\n\t\t\t\t'secret',\n\t\t\t\t'set',\n\t\t\t\t'GKM_SECRETS_KEY',\n\t\t\t\t'--env',\n\t\t\t\toptions.stage,\n\t\t\t\t'--repo',\n\t\t\t\trepo,\n\t\t\t],\n\t\t\tkey!,\n\t\t);\n\t\tlogger.log(' ✓ GitHub: GKM_SECRETS_KEY');\n\t} else {\n\t\tlogger.log(\n\t\t\t` ⚠ No secrets key for \"${options.stage}\"; run gkm secrets:init --stage ${options.stage}, then this again.`,\n\t\t);\n\t}\n\n\tlogger.log(\n\t\t`\\n Protect it: add required reviewers to the \"${options.stage}\" environment in the repository settings.\\n`,\n\t);\n\treturn { roleArn, repo, subject: oidc.subject };\n}\n\nconst SUBJECT_KINDS = {\n\tdefault: \"the repository's default subject\",\n\timmutable: \"the repository's immutable subject\",\n\tcustom: \"the repository's custom subject template\",\n\tassumed: 'assumed: the default format',\n} as const;\n\n/** The profile's SSO login has lapsed; the fix is one command away. */\nexport class SsoSessionExpired extends GkmError {\n\tconstructor(readonly profile: string) {\n\t\tsuper(\n\t\t\t`The SSO session for profile \"${profile}\" has expired or is invalid. Run: aws sso login --profile ${profile}`,\n\t\t);\n\t\tthis.name = 'SsoSessionExpired';\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,uBAAuB;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;AAEA,MAAM,8BAAc,IAAI,IAAI;CAC3B;CACA;CACA;AACD,CAAC;;AAGD,SAAS,MAAM,OAAuB;CACrC,OAAO,MAAM,WAAW,KAAK,KAAK;AACnC;;AAMA,SAAgB,eACf,eACU;CACV,MAAM,yBACL,cAAc,0BAA0B,QACxC,CAAC,cAAc;CAChB,IAAI,cAAc,aAAa,OAAO;CAGtC,QADa,cAAc,sBAAsB,CAAC,EAAA,CACtC,MACV,QAAQ,YAAY,IAAI,GAAG,KAAM,QAAQ,UAAU,sBACrD;AACD;;;;;;;AAQA,SAAgB,YACf,MACA,OACA,eACA,OAC6C;CAC7C,MAAM,CAAC,QAAQ,IAAI,OAAO,MAAM,KAAK,MAAM,GAAG;CAC9C,MAAM,cAAc,eAAe,MAAM,KAAK;CAE9C,MAAM,oBAA4B;EACjC,IAAI,cAAc,kBAAkB,OAAO,cAAc;EACzD,IAA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Q,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;EAAM,SAAS,KAAK;CAAQ;AAC/C;AAEA,MAAM,gBAAgB;CACrB,SAAS;CACT,WAAW;CACX,QAAQ;CACR,SAAS;AACV;;AAGA,IAAa,oBAAb,cAAuCC,eAAAA,SAAS;CAC1B;CAArB,YAAY,SAA0B;EACrC,MACC,gCAAgC,QAAQ,4DAA4D,SACrG;EAHoB,KAAA,UAAA;EAIpB,KAAK,OAAO;CACb;AACD"}
|
|
@@ -5,7 +5,7 @@ import { Yt as stageBackups, f as constructGlobs } from "./apps-BE97n0jO.mjs";
|
|
|
5
5
|
import { m as loadWorkspaceConfig } from "./config-Da9bxnkT.mjs";
|
|
6
6
|
import { i as discover } from "./discover-DbDrCQ8h.mjs";
|
|
7
7
|
import { v as stageDnsDomains } from "./snsSubscriptions-DgbFGyac.mjs";
|
|
8
|
-
import { l as backupsUserName } from "./deploy-
|
|
8
|
+
import { l as backupsUserName } from "./deploy-C4Qb-A-z.mjs";
|
|
9
9
|
import { n as PROJECT_BUCKET_LIFECYCLE_ACTIONS, o as projectBucketName, t as PROJECT_BUCKET_CREATE_ACTIONS } from "./projectBucket-DPaUiLyY.mjs";
|
|
10
10
|
import { n as secretsParameterName } from "./aws-C5LAU_Ii.mjs";
|
|
11
11
|
import { t as secretsManagerSecretName } from "./secretsManager-CJyxFcBH.mjs";
|
|
@@ -456,8 +456,9 @@ function deployAccess(workspace, stage, policyArn, manifest = {}) {
|
|
|
456
456
|
Sid: "StageMailIdentity",
|
|
457
457
|
Effect: "Allow",
|
|
458
458
|
Action: [
|
|
459
|
-
"ses:
|
|
459
|
+
"ses:GetIdentityDkimAttributes",
|
|
460
460
|
"ses:VerifyDomainDkim",
|
|
461
|
+
"ses:SetIdentityDkimEnabled",
|
|
461
462
|
"ses:GetSendQuota"
|
|
462
463
|
],
|
|
463
464
|
Resource: "*"
|
|
@@ -929,4 +930,4 @@ var SsoSessionExpired = class extends GkmError {
|
|
|
929
930
|
//#endregion
|
|
930
931
|
export { deployGithubCommand, ghCli };
|
|
931
932
|
|
|
932
|
-
//# sourceMappingURL=github-
|
|
933
|
+
//# sourceMappingURL=github-DxgGIvq1.mjs.map
|