@elumixor/devkit 0.12.3 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +83 -0
  2. package/package.json +26 -2
  3. package/src/bin/devkit.ts +32 -1
  4. package/src/blob/index.ts +169 -0
  5. package/src/build-targets/web.ts +66 -20
  6. package/src/cloud/aws.ts +108 -0
  7. package/src/cloud/bootstrap.ts +114 -0
  8. package/src/cloud/cli.ts +56 -0
  9. package/src/cloud/commands/context.ts +42 -0
  10. package/src/cloud/commands/destroy.ts +43 -0
  11. package/src/cloud/commands/domains.ts +68 -0
  12. package/src/cloud/commands/env.ts +59 -0
  13. package/src/cloud/commands/init.ts +74 -0
  14. package/src/cloud/commands/logs.ts +35 -0
  15. package/src/cloud/commands/rollback.ts +54 -0
  16. package/src/cloud/commands/status.ts +50 -0
  17. package/src/cloud/edge/router.js +86 -0
  18. package/src/cloud/env.ts +93 -0
  19. package/src/cloud/github.ts +92 -0
  20. package/src/cloud/index.ts +9 -0
  21. package/src/cloud/log-events.ts +56 -0
  22. package/src/cloud/mcp.ts +150 -0
  23. package/src/cloud/names.ts +98 -0
  24. package/src/cloud/nitro-build.ts +42 -0
  25. package/src/cloud/overview.ts +105 -0
  26. package/src/cloud/project.ts +143 -0
  27. package/src/cloud/reconcile/acm.ts +97 -0
  28. package/src/cloud/reconcile/cloudflare.ts +103 -0
  29. package/src/cloud/reconcile/edge.ts +97 -0
  30. package/src/cloud/reconcile/guardrails.ts +112 -0
  31. package/src/cloud/reconcile/iam.ts +328 -0
  32. package/src/cloud/reconcile/kvs.ts +98 -0
  33. package/src/cloud/reconcile/lambda.ts +305 -0
  34. package/src/cloud/reconcile/logs.ts +24 -0
  35. package/src/cloud/reconcile/platform.ts +281 -0
  36. package/src/cloud/reconcile/s3.ts +155 -0
  37. package/src/cloud/reconcile/scheduler.ts +100 -0
  38. package/src/cloud/records.ts +129 -0
  39. package/src/cloud/release.ts +268 -0
  40. package/src/cloud/runtime-wrapper.ts +84 -0
  41. package/src/deploy-targets/aws.ts +26 -0
  42. package/src/run-target.ts +2 -0
  43. package/src/runtime/index.ts +50 -0
@@ -0,0 +1,328 @@
1
+ import {
2
+ AttachRolePolicyCommand,
3
+ AttachUserPolicyCommand,
4
+ CreateAccessKeyCommand,
5
+ CreatePolicyCommand,
6
+ CreatePolicyVersionCommand,
7
+ CreateRoleCommand,
8
+ CreateUserCommand,
9
+ DeletePolicyVersionCommand,
10
+ DeleteRoleCommand,
11
+ DeleteRolePolicyCommand,
12
+ GetPolicyCommand,
13
+ GetPolicyVersionCommand,
14
+ GetRoleCommand,
15
+ GetUserCommand,
16
+ ListPolicyVersionsCommand,
17
+ ListRolePoliciesCommand,
18
+ PutRolePolicyCommand,
19
+ } from "@aws-sdk/client-iam";
20
+ import { $ } from "bun";
21
+ import { accountId, iam, orUndefined, platformTags, retryWhile } from "../aws.ts";
22
+ import { platform, REGION } from "../names.ts";
23
+ import type { Target } from "../project.ts";
24
+ import { buckets } from "./s3.ts";
25
+
26
+ type PolicyDocument = { Version: "2012-10-17"; Statement: readonly Record<string, unknown>[] };
27
+
28
+ const assumeRole = (service: string): PolicyDocument => ({
29
+ Version: "2012-10-17",
30
+ Statement: [{ Effect: "Allow", Principal: { Service: service }, Action: "sts:AssumeRole" }],
31
+ });
32
+
33
+ /** Creates the role if missing and makes its one inline policy match; returns the ARN. */
34
+ export async function ensureRole(
35
+ name: string,
36
+ trust: PolicyDocument,
37
+ policy: PolicyDocument | undefined,
38
+ description: string,
39
+ ) {
40
+ const existing = await orUndefined(iam().send(new GetRoleCommand({ RoleName: name })), "NoSuchEntityException");
41
+ const arn =
42
+ existing?.Role?.Arn ??
43
+ (
44
+ await iam().send(
45
+ new CreateRoleCommand({
46
+ RoleName: name,
47
+ AssumeRolePolicyDocument: JSON.stringify(trust),
48
+ Description: description,
49
+ Tags: platformTags(),
50
+ }),
51
+ )
52
+ ).Role?.Arn;
53
+ if (!arn) throw new Error(`IAM returned no ARN for role ${name}`);
54
+ // A role just created is not always visible to the next call yet.
55
+ if (policy)
56
+ await retryWhile(
57
+ () =>
58
+ iam().send(
59
+ new PutRolePolicyCommand({ RoleName: name, PolicyName: name, PolicyDocument: JSON.stringify(policy) }),
60
+ ),
61
+ ["NoSuchEntityException"],
62
+ );
63
+ return { arn, created: !existing };
64
+ }
65
+
66
+ /**
67
+ * A managed policy whose default version is `document`. Inline policies are capped at 2 KB on a
68
+ * user, and the deploy policy is bigger than that, so it is managed and attached to both principals.
69
+ */
70
+ export async function ensureManagedPolicy(name: string, document: PolicyDocument) {
71
+ const account = await accountId();
72
+ const arn = `arn:aws:iam::${account}:policy/${name}`;
73
+ const wanted = JSON.stringify(document);
74
+ const existing = await orUndefined(iam().send(new GetPolicyCommand({ PolicyArn: arn })), "NoSuchEntityException");
75
+ if (!existing) {
76
+ await iam().send(new CreatePolicyCommand({ PolicyName: name, PolicyDocument: wanted, Tags: platformTags() }));
77
+ return arn;
78
+ }
79
+ const current = await iam().send(
80
+ new GetPolicyVersionCommand({ PolicyArn: arn, VersionId: existing.Policy?.DefaultVersionId }),
81
+ );
82
+ const currentDocument = decodeURIComponent(current.PolicyVersion?.Document ?? "");
83
+ if (currentDocument && JSON.stringify(JSON.parse(currentDocument)) === wanted) return arn;
84
+ // IAM keeps five versions; the oldest non-default one makes room for the new default.
85
+ const versions = (await iam().send(new ListPolicyVersionsCommand({ PolicyArn: arn }))).Versions ?? [];
86
+ if (versions.length >= 5) {
87
+ const oldest = versions
88
+ .filter((version) => !version.IsDefaultVersion)
89
+ .sort((a, b) => (a.CreateDate?.getTime() ?? 0) - (b.CreateDate?.getTime() ?? 0))[0];
90
+ if (oldest?.VersionId)
91
+ await iam().send(new DeletePolicyVersionCommand({ PolicyArn: arn, VersionId: oldest.VersionId }));
92
+ }
93
+ await iam().send(new CreatePolicyVersionCommand({ PolicyArn: arn, PolicyDocument: wanted, SetAsDefault: true }));
94
+ return arn;
95
+ }
96
+
97
+ export async function deleteRole(name: string) {
98
+ const policies = await orUndefined(
99
+ iam().send(new ListRolePoliciesCommand({ RoleName: name })),
100
+ "NoSuchEntityException",
101
+ );
102
+ if (!policies) return;
103
+ for (const PolicyName of policies.PolicyNames ?? [])
104
+ await iam().send(new DeleteRolePolicyCommand({ RoleName: name, PolicyName }));
105
+ await iam().send(new DeleteRoleCommand({ RoleName: name }));
106
+ }
107
+
108
+ /** A function may write its own logs and touch its own blob prefix — nothing else. */
109
+ export async function ensureFunctionRole(target: Target) {
110
+ const account = await accountId();
111
+ const { blobs } = await buckets();
112
+ const prefix = `${target.project}/${target.stage}/`;
113
+ return ensureRole(
114
+ target.roleName,
115
+ assumeRole("lambda.amazonaws.com"),
116
+ {
117
+ Version: "2012-10-17",
118
+ Statement: [
119
+ {
120
+ Effect: "Allow",
121
+ Action: ["logs:CreateLogStream", "logs:PutLogEvents"],
122
+ Resource: `arn:aws:logs:${REGION}:${account}:log-group:${target.logGroup}:*`,
123
+ },
124
+ {
125
+ Effect: "Allow",
126
+ Action: ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:GetObjectAttributes"],
127
+ Resource: `arn:aws:s3:::${blobs}/${prefix}*`,
128
+ },
129
+ {
130
+ Effect: "Allow",
131
+ Action: "s3:ListBucket",
132
+ Resource: `arn:aws:s3:::${blobs}`,
133
+ Condition: { StringLike: { "s3:prefix": [`${prefix}*`] } },
134
+ },
135
+ ...target.permissions.map((permission) => ({ Effect: "Allow", ...permission })),
136
+ ],
137
+ },
138
+ `Devkit Cloud: ${target.project} ${target.stage} function`,
139
+ );
140
+ }
141
+
142
+ /** EventBridge Scheduler invokes `dk-*` functions through this one role. */
143
+ export async function ensureSchedulerRole() {
144
+ const account = await accountId();
145
+ return ensureRole(
146
+ platform.schedulerRole,
147
+ assumeRole("scheduler.amazonaws.com"),
148
+ {
149
+ Version: "2012-10-17",
150
+ Statement: [
151
+ {
152
+ Effect: "Allow",
153
+ Action: "lambda:InvokeFunction",
154
+ Resource: `arn:aws:lambda:${REGION}:${account}:function:dk-*`,
155
+ },
156
+ ],
157
+ },
158
+ "Devkit Cloud: lets EventBridge Scheduler call project functions",
159
+ );
160
+ }
161
+
162
+ /**
163
+ * The deploy role: what GitHub Actions assumes through OIDC, and what the local `devkit` profile
164
+ * is limited to. Everything it may touch is named `dk-*` or lives in the platform's buckets.
165
+ */
166
+ export async function deployPolicy(): Promise<PolicyDocument> {
167
+ const account = await accountId();
168
+ const { sites, blobs } = await buckets();
169
+ return {
170
+ Version: "2012-10-17",
171
+ Statement: [
172
+ { Effect: "Allow", Action: "sts:GetCallerIdentity", Resource: "*" },
173
+ {
174
+ Effect: "Allow",
175
+ Action: ["s3:ListBucket", "s3:GetBucketLocation"],
176
+ Resource: [`arn:aws:s3:::${sites}`, `arn:aws:s3:::${blobs}`],
177
+ },
178
+ {
179
+ Effect: "Allow",
180
+ Action: ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
181
+ Resource: [`arn:aws:s3:::${sites}/*`, `arn:aws:s3:::${blobs}/*`],
182
+ },
183
+ { Effect: "Allow", Action: "lambda:*", Resource: `arn:aws:lambda:${REGION}:${account}:function:dk-*` },
184
+ { Effect: "Allow", Action: ["lambda:ListFunctions", "lambda:GetAccountSettings"], Resource: "*" },
185
+ {
186
+ Effect: "Allow",
187
+ Action: [
188
+ "iam:GetRole",
189
+ "iam:CreateRole",
190
+ "iam:PutRolePolicy",
191
+ "iam:ListRolePolicies",
192
+ "iam:DeleteRolePolicy",
193
+ "iam:DeleteRole",
194
+ "iam:TagRole",
195
+ ],
196
+ Resource: `arn:aws:iam::${account}:role/dk-*`,
197
+ },
198
+ {
199
+ Effect: "Allow",
200
+ Action: "iam:PassRole",
201
+ Resource: `arn:aws:iam::${account}:role/dk-*`,
202
+ Condition: { StringEquals: { "iam:PassedToService": ["lambda.amazonaws.com", "scheduler.amazonaws.com"] } },
203
+ },
204
+ {
205
+ Effect: "Allow",
206
+ Action: ["logs:CreateLogGroup", "logs:PutRetentionPolicy", "logs:DeleteLogGroup", "logs:TagResource"],
207
+ Resource: `arn:aws:logs:${REGION}:${account}:log-group:/aws/lambda/dk-*`,
208
+ },
209
+ {
210
+ Effect: "Allow",
211
+ Action: [
212
+ "logs:DescribeLogGroups",
213
+ "logs:FilterLogEvents",
214
+ "logs:StartLiveTail",
215
+ "logs:GetLogEvents",
216
+ "logs:DescribeLogStreams",
217
+ ],
218
+ Resource: "*",
219
+ },
220
+ { Effect: "Allow", Action: "cloudwatch:GetMetricData", Resource: "*" },
221
+ {
222
+ Effect: "Allow",
223
+ Action: "scheduler:*",
224
+ Resource: [
225
+ `arn:aws:scheduler:${REGION}:${account}:schedule/${platform.scheduleGroup}/dk-*`,
226
+ `arn:aws:scheduler:${REGION}:${account}:schedule-group/${platform.scheduleGroup}`,
227
+ ],
228
+ },
229
+ { Effect: "Allow", Action: "scheduler:ListSchedules", Resource: "*" },
230
+ {
231
+ Effect: "Allow",
232
+ Action: ["ssm:GetParametersByPath", "ssm:GetParameter", "ssm:PutParameter", "ssm:DeleteParameter"],
233
+ Resource: `arn:aws:ssm:${REGION}:${account}:parameter/dk/*`,
234
+ },
235
+ {
236
+ Effect: "Allow",
237
+ Action: ["cloudfront-keyvaluestore:*"],
238
+ Resource: `arn:aws:cloudfront::${account}:key-value-store/*`,
239
+ },
240
+ {
241
+ Effect: "Allow",
242
+ Action: [
243
+ "cloudfront:DescribeKeyValueStore",
244
+ "cloudfront:ListKeyValueStores",
245
+ "cloudfront:GetDistribution",
246
+ "cloudfront:GetDistributionConfig",
247
+ "cloudfront:UpdateDistribution",
248
+ "cloudfront:ListDistributions",
249
+ "cloudfront:ListTagsForResource",
250
+ ],
251
+ Resource: "*",
252
+ },
253
+ {
254
+ Effect: "Allow",
255
+ Action: [
256
+ "acm:ListCertificates",
257
+ "acm:DescribeCertificate",
258
+ "acm:RequestCertificate",
259
+ "acm:AddTagsToCertificate",
260
+ "acm:DeleteCertificate",
261
+ ],
262
+ Resource: "*",
263
+ },
264
+ ],
265
+ };
266
+ }
267
+
268
+ /** The role GitHub Actions assumes: only `elumixor/*` repos, only on the branches that deploy. */
269
+ export async function ensureDeployRole(branches: readonly string[]) {
270
+ const account = await accountId();
271
+ const policyArn = await ensureManagedPolicy(platform.deployPolicy, await deployPolicy());
272
+ const role = await ensureRole(
273
+ platform.deployRole,
274
+ {
275
+ Version: "2012-10-17",
276
+ Statement: [
277
+ {
278
+ Effect: "Allow",
279
+ Principal: { Federated: `arn:aws:iam::${account}:oidc-provider/token.actions.githubusercontent.com` },
280
+ Action: "sts:AssumeRoleWithWebIdentity",
281
+ Condition: {
282
+ StringEquals: { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
283
+ StringLike: {
284
+ "token.actions.githubusercontent.com:sub": branches.map(
285
+ (branch) => `repo:elumixor/*:ref:refs/heads/${branch}`,
286
+ ),
287
+ },
288
+ },
289
+ },
290
+ ],
291
+ },
292
+ undefined,
293
+ "Devkit Cloud: what GitHub Actions deploys with",
294
+ );
295
+ await retryWhile(
296
+ () => iam().send(new AttachRolePolicyCommand({ RoleName: platform.deployRole, PolicyArn: policyArn })),
297
+ ["NoSuchEntityException"],
298
+ );
299
+ return role;
300
+ }
301
+
302
+ /**
303
+ * The scoped `devkit` profile for deploying from a laptop, so the admin key never has to be used
304
+ * for day-to-day deploys. The access key is made once and written straight into the AWS CLI's
305
+ * config; a second run leaves an existing profile alone.
306
+ */
307
+ export async function ensureLocalDeployProfile() {
308
+ const user = platform.localDeployUser;
309
+ const existing = await orUndefined(iam().send(new GetUserCommand({ UserName: user })), "NoSuchEntityException");
310
+ if (!existing) await iam().send(new CreateUserCommand({ UserName: user, Tags: platformTags() }));
311
+ const policyArn = await ensureManagedPolicy(platform.deployPolicy, await deployPolicy());
312
+ await retryWhile(
313
+ () => iam().send(new AttachUserPolicyCommand({ UserName: user, PolicyArn: policyArn })),
314
+ ["NoSuchEntityException"],
315
+ );
316
+
317
+ const configured = (
318
+ await $`aws configure get aws_access_key_id --profile ${platform.localProfile}`.quiet().nothrow().text()
319
+ ).trim();
320
+ if (configured) return { created: !existing, profile: "kept" as const };
321
+
322
+ const key = await iam().send(new CreateAccessKeyCommand({ UserName: user }));
323
+ if (!key.AccessKey?.AccessKeyId || !key.AccessKey.SecretAccessKey) throw new Error("IAM returned no access key");
324
+ await $`aws configure set aws_access_key_id ${key.AccessKey.AccessKeyId} --profile ${platform.localProfile}`.quiet();
325
+ await $`aws configure set aws_secret_access_key ${key.AccessKey.SecretAccessKey} --profile ${platform.localProfile}`.quiet();
326
+ await $`aws configure set region ${REGION} --profile ${platform.localProfile}`.quiet();
327
+ return { created: !existing, profile: "written" as const };
328
+ }
@@ -0,0 +1,98 @@
1
+ import { DescribeKeyValueStoreCommand as DescribeStore } from "@aws-sdk/client-cloudfront";
2
+ import {
3
+ DeleteKeyCommand,
4
+ DescribeKeyValueStoreCommand,
5
+ GetKeyCommand,
6
+ ListKeysCommand,
7
+ UpdateKeysCommand,
8
+ } from "@aws-sdk/client-cloudfront-keyvaluestore";
9
+ import { CloudError, cloudfront, kvs, orUndefined } from "../aws.ts";
10
+ import { EDGE_SECRET_KEY, platform } from "../names.ts";
11
+ import type { Routing } from "../project.ts";
12
+
13
+ /**
14
+ * What the router reads for one hostname: which project, stage and deploy to serve, where its
15
+ * function answers, which path prefixes are the API, and how to serve the rest. Kept short — a
16
+ * KVS value may be 1 KB at most.
17
+ */
18
+ export interface RouteRecord {
19
+ p: string;
20
+ s: string;
21
+ d: string;
22
+ fn: string;
23
+ api: readonly string[];
24
+ mode: Routing;
25
+ }
26
+
27
+ let storeArn: Promise<string> | undefined;
28
+
29
+ /** The route store's ARN, looked up by name once per run. */
30
+ export function routeStoreArn() {
31
+ storeArn ??= cloudfront()
32
+ .send(new DescribeStore({ Name: platform.kvs }))
33
+ .then((result) => {
34
+ if (!result.KeyValueStore?.ARN) throw new CloudError(`KeyValueStore ${platform.kvs} has no ARN`);
35
+ return result.KeyValueStore.ARN;
36
+ })
37
+ .catch((error: unknown) => {
38
+ if (error instanceof Error && error.name === "EntityNotFound")
39
+ throw new CloudError(`No KeyValueStore ${platform.kvs} — run \`devkit cloud bootstrap\` first`);
40
+ throw error;
41
+ });
42
+ return storeArn;
43
+ }
44
+
45
+ /** Every write needs the store's current ETag, so a batch is read-then-write. */
46
+ async function etag(arn: string) {
47
+ const described = await kvs().send(new DescribeKeyValueStoreCommand({ KvsARN: arn }));
48
+ if (!described.ETag) throw new CloudError("KeyValueStore described without an ETag");
49
+ return described.ETag;
50
+ }
51
+
52
+ /** Writes and deletes in one call — the whole stage flips at once, or not at all. */
53
+ export async function updateKeys(puts: Record<string, string>, deletes: readonly string[] = []) {
54
+ const arn = await routeStoreArn();
55
+ const Puts = Object.entries(puts).map(([Key, Value]) => ({ Key, Value }));
56
+ const Deletes = deletes.map((Key) => ({ Key }));
57
+ if (!Puts.length && !Deletes.length) return;
58
+ await kvs().send(new UpdateKeysCommand({ KvsARN: arn, IfMatch: await etag(arn), Puts, Deletes }));
59
+ }
60
+
61
+ export async function putRoutes(records: Readonly<Record<string, RouteRecord>>) {
62
+ await updateKeys(Object.fromEntries(Object.entries(records).map(([host, record]) => [host, JSON.stringify(record)])));
63
+ }
64
+
65
+ export async function getRoute(host: string): Promise<RouteRecord | undefined> {
66
+ const result = await orUndefined(
67
+ kvs().send(new GetKeyCommand({ KvsARN: await routeStoreArn(), Key: host })),
68
+ "ResourceNotFoundException",
69
+ );
70
+ return result?.Value ? (JSON.parse(result.Value) as RouteRecord) : undefined;
71
+ }
72
+
73
+ export async function deleteRoute(host: string) {
74
+ const arn = await routeStoreArn();
75
+ await orUndefined(
76
+ kvs().send(new DeleteKeyCommand({ KvsARN: arn, IfMatch: await etag(arn), Key: host })),
77
+ "ResourceNotFoundException",
78
+ );
79
+ }
80
+
81
+ /** Every hostname → record pair in the store, for `status` across projects. */
82
+ export async function listRoutes(): Promise<Record<string, RouteRecord>> {
83
+ const arn = await routeStoreArn();
84
+ const routes: Record<string, RouteRecord> = {};
85
+ let NextToken: string | undefined;
86
+ do {
87
+ const page = await kvs().send(new ListKeysCommand({ KvsARN: arn, NextToken }));
88
+ for (const item of page.Items ?? []) {
89
+ if (item.Key && item.Value && item.Key !== EDGE_SECRET_KEY) routes[item.Key] = JSON.parse(item.Value);
90
+ }
91
+ NextToken = page.NextToken;
92
+ } while (NextToken);
93
+ return routes;
94
+ }
95
+
96
+ export async function putEdgeSecret(secret: string) {
97
+ await updateKeys({ [EDGE_SECRET_KEY]: secret });
98
+ }