@ericminassian/platform-engine 0.1.0 → 0.3.0

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 (60) hide show
  1. package/dist/clients.d.ts +0 -11
  2. package/dist/clients.js +0 -19
  3. package/dist/clients.js.map +1 -1
  4. package/dist/drivers/cognito.d.ts +0 -9
  5. package/dist/drivers/cognito.js +2 -40
  6. package/dist/drivers/cognito.js.map +1 -1
  7. package/dist/drivers/iam.d.ts +0 -9
  8. package/dist/drivers/iam.js +1 -52
  9. package/dist/drivers/iam.js.map +1 -1
  10. package/dist/drivers/index.d.ts +0 -4
  11. package/dist/drivers/index.js +0 -4
  12. package/dist/drivers/index.js.map +1 -1
  13. package/dist/drivers/s3.d.ts +2 -0
  14. package/dist/drivers/s3.js +5 -0
  15. package/dist/drivers/s3.js.map +1 -1
  16. package/dist/drivers/ssm.d.ts +1 -0
  17. package/dist/drivers/ssm.js +23 -3
  18. package/dist/drivers/ssm.js.map +1 -1
  19. package/dist/drivers/web-function.d.ts +30 -8
  20. package/dist/drivers/web-function.js +42 -5
  21. package/dist/drivers/web-function.js.map +1 -1
  22. package/dist/index.d.ts +6 -4
  23. package/dist/index.js +2 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/local.d.ts +2 -2
  26. package/dist/local.js +2 -2
  27. package/dist/policy.d.ts +0 -6
  28. package/dist/policy.js +4 -18
  29. package/dist/policy.js.map +1 -1
  30. package/dist/stage.d.ts +17 -2
  31. package/dist/stage.js +110 -41
  32. package/dist/stage.js.map +1 -1
  33. package/package.json +2 -6
  34. package/src/clients.ts +0 -26
  35. package/src/drivers/cognito.ts +1 -53
  36. package/src/drivers/iam.ts +0 -70
  37. package/src/drivers/index.ts +0 -4
  38. package/src/drivers/s3.ts +8 -0
  39. package/src/drivers/ssm.ts +23 -2
  40. package/src/drivers/web-function.ts +81 -10
  41. package/src/index.ts +6 -4
  42. package/src/local.ts +2 -2
  43. package/src/policy.ts +4 -23
  44. package/src/stage.ts +116 -44
  45. package/dist/drivers/acm.d.ts +0 -20
  46. package/dist/drivers/acm.js +0 -62
  47. package/dist/drivers/acm.js.map +0 -1
  48. package/dist/drivers/cloudfront.d.ts +0 -52
  49. package/dist/drivers/cloudfront.js +0 -223
  50. package/dist/drivers/cloudfront.js.map +0 -1
  51. package/dist/drivers/route53.d.ts +0 -30
  52. package/dist/drivers/route53.js +0 -96
  53. package/dist/drivers/route53.js.map +0 -1
  54. package/dist/drivers/sns.d.ts +0 -7
  55. package/dist/drivers/sns.js +0 -20
  56. package/dist/drivers/sns.js.map +0 -1
  57. package/src/drivers/acm.ts +0 -88
  58. package/src/drivers/cloudfront.ts +0 -291
  59. package/src/drivers/route53.ts +0 -129
  60. package/src/drivers/sns.ts +0 -33
package/src/policy.ts CHANGED
@@ -35,10 +35,12 @@ export function stageRolePolicy(input: StagePolicyInput): PolicyDocument {
35
35
  const base = names.base(app, stage);
36
36
  const statements: PolicyStatement[] = [];
37
37
 
38
+ // No logs:CreateLogGroup: the engine creates the stage's groups. With it, logs still in flight
39
+ // when a stage is destroyed recreate the groups right after destroy deletes them.
38
40
  statements.push({
39
41
  Sid: 'Logs',
40
42
  Effect: 'Allow',
41
- Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
43
+ Action: ['logs:CreateLogStream', 'logs:PutLogEvents'],
42
44
  Resource: [
43
45
  `arn:aws:logs:${region}:${acct}:log-group:${names.logGroupPrefix(app, stage)}*`,
44
46
  `arn:aws:logs:${region}:${acct}:log-group:${names.logGroupPrefix(app, stage)}*:log-stream:*`,
@@ -156,7 +158,7 @@ export function boundaryPolicy(input: {
156
158
  {
157
159
  Sid: 'StageLogs',
158
160
  Effect: 'Allow',
159
- Action: ['logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:PutLogEvents'],
161
+ Action: ['logs:CreateLogStream', 'logs:PutLogEvents'],
160
162
  Resource: `arn:aws:logs:${region}:${acct}:log-group:/platform/apps/*`,
161
163
  },
162
164
  {
@@ -370,27 +372,6 @@ export function controlPlanePolicy(input: {
370
372
  return policy(...statements);
371
373
  }
372
374
 
373
- /** Trust for the platform repo's CI role: GitHub Actions OIDC, main branch only. */
374
- export function githubCiTrustPolicy(input: {
375
- accountId: string;
376
- owner: string;
377
- repo: string;
378
- }): PolicyDocument {
379
- return policy({
380
- Effect: 'Allow',
381
- Principal: {
382
- Federated: `arn:aws:iam::${input.accountId}:oidc-provider/token.actions.githubusercontent.com`,
383
- },
384
- Action: 'sts:AssumeRoleWithWebIdentity',
385
- Condition: {
386
- StringEquals: {
387
- 'token.actions.githubusercontent.com:aud': 'sts.amazonaws.com',
388
- 'token.actions.githubusercontent.com:sub': `repo:${input.owner}/${input.repo}:ref:refs/heads/main`,
389
- },
390
- },
391
- });
392
- }
393
-
394
375
  export function serviceTrustPolicy(...services: string[]): PolicyDocument {
395
376
  return policy({ Effect: 'Allow', Principal: { Service: services }, Action: 'sts:AssumeRole' });
396
377
  }
package/src/stage.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { DescribeEventBusCommand } from '@aws-sdk/client-eventbridge';
2
3
  import { GetRoleCommand } from '@aws-sdk/client-iam';
3
4
  import { GetFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
@@ -26,7 +27,7 @@ import { deleteUserPoolClient, ensureUserPoolClient } from './drivers/cognito.ts
26
27
  import { deleteTable, describeTable, ensureTable, stageTableSpec } from './drivers/dynamodb.ts';
27
28
  import { deleteEventBus, deleteRule, ensureEventBus, ensureRule, listRules } from './drivers/events.ts';
28
29
  import { deleteRole, ensureRole } from './drivers/iam.ts';
29
- import { deleteRoute, putRoute } from './drivers/kvs.ts';
30
+ import { deleteRoute, getRoute, putRoute } from './drivers/kvs.ts';
30
31
  import {
31
32
  deleteEventSourceMapping,
32
33
  deleteFunction,
@@ -37,7 +38,7 @@ import {
37
38
  removePermission,
38
39
  } from './drivers/lambda.ts';
39
40
  import { deleteLogGroup, ensureLogGroup, listLogGroups } from './drivers/logs.ts';
40
- import { deletePrefix, listChildPrefixes, publishStaticZip } from './drivers/s3.ts';
41
+ import { deletePrefix, hasObjects, listChildPrefixes, publishStaticZip } from './drivers/s3.ts';
41
42
  import {
42
43
  deleteSchedule,
43
44
  deleteScheduleGroup,
@@ -46,16 +47,14 @@ import {
46
47
  listSchedules,
47
48
  } from './drivers/scheduler.ts';
48
49
  import { deleteQueue, ensureQueue, listQueues } from './drivers/sqs.ts';
49
- import { deleteParametersByPath } from './drivers/ssm.ts';
50
+ import { deleteParameter, deleteParametersByPath, ensureParameterOnce } from './drivers/ssm.ts';
50
51
  import {
51
52
  createRevision,
52
53
  deleteWebFunction,
53
- ensureEndpoint,
54
- ensureRouterAccess,
54
+ endpointForRevision,
55
55
  ensureWebFunction,
56
- getEndpoint,
56
+ getRevisionState,
57
57
  pruneRevisions,
58
- setEndpointRevision,
59
58
  } from './drivers/web-function.ts';
60
59
  import type {
61
60
  DeployStageInput,
@@ -67,8 +66,11 @@ import type {
67
66
  import { stageRolePolicy, stageTrustPolicy } from './policy.ts';
68
67
  import { type EngineContext, ignoreNotFound, stageTags } from './util.ts';
69
68
 
70
- /** Static deployments kept per stage (current + previous ones for rollback). */
71
- const STATIC_DEPLOYMENTS_KEPT = 3;
69
+ /**
70
+ * Deployments whose static files and server revision are kept per stage (the
71
+ * newest ones, plus whatever the routes still use), so rollback can reach them.
72
+ */
73
+ const DEPLOYMENTS_KEPT = 3;
72
74
 
73
75
  /**
74
76
  * Public host of a stage. Under `plat dev` the `local` stage is simply
@@ -115,10 +117,18 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
115
117
 
116
118
  ctx.log('info', `deploying ${app}/${stage} (${deploymentId})`);
117
119
 
118
- // 1. Log groups (retention set before anything writes to them).
120
+ // 1. Log groups (retention set before anything writes to them). These are all of them: the stage
121
+ // role can't create log groups (see stageRolePolicy).
119
122
  const webLogGroup = names.logGroup(app, stage, 'web');
120
123
  const workerLogGroup = names.logGroup(app, stage, 'worker');
121
- if (hasWeb) await ensureLogGroup(ctx, { name: webLogGroup, retentionDays: retention, tags });
124
+ if (hasWeb) {
125
+ await ensureLogGroup(ctx, { name: webLogGroup, retentionDays: retention, tags });
126
+ await ensureLogGroup(ctx, {
127
+ name: names.logGroup(app, stage, 'web.local'),
128
+ retentionDays: retention,
129
+ tags,
130
+ });
131
+ }
122
132
  if (hasWorker) await ensureLogGroup(ctx, { name: workerLogGroup, retentionDays: retention, tags });
123
133
 
124
134
  // 2. Data.
@@ -130,7 +140,7 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
130
140
  } else if (await describeTable(ctx, names.table(app, stage))) {
131
141
  ctx.log(
132
142
  'warn',
133
- 'db is off in platform.json but the table still exists; keeping it (data)',
143
+ 'db is off in plat.config.ts but the table still exists; keeping it (data)',
134
144
  `table ${names.table(app, stage)}`,
135
145
  );
136
146
  }
@@ -213,7 +223,18 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
213
223
  await deleteUserPoolClient(ctx, platform.userPoolId, names.userPoolClient(app, stage));
214
224
  }
215
225
 
216
- // 7. Bindings.
226
+ // 7. Stage key. Created once and kept for the stage's life, so db cursors
227
+ // survive redeploys. It goes in the bindings instead of being read from SSM
228
+ // at runtime (no extra call or IAM grant) because it only guards SDK-issued
229
+ // tokens: a leaked key lets someone read or forge cursors, not read data.
230
+ const stageKey = await ensureParameterOnce(ctx, {
231
+ name: names.stageKeyParameter(app, stage),
232
+ secure: true,
233
+ description: `Stage key for ${app}/${stage} (SDK-sealed tokens such as db cursors)`,
234
+ generate: () => randomBytes(32).toString('base64url'),
235
+ });
236
+
237
+ // 8. Bindings.
217
238
  const bindings: Bindings = {
218
239
  v: 1,
219
240
  app,
@@ -241,6 +262,7 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
241
262
  },
242
263
  ...(auth ? { auth } : {}),
243
264
  ...(hasWorker ? { worker: workerName } : {}),
265
+ stageKey,
244
266
  };
245
267
  const env = {
246
268
  [BINDINGS_ENV]: encodeBindings(bindings),
@@ -249,7 +271,7 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
249
271
  ...input.extraEnv,
250
272
  };
251
273
 
252
- // 8. Worker + its triggers.
274
+ // 9. Worker + its triggers.
253
275
  let workerFunction: DeployStageResult['workerFunction'];
254
276
  if (hasWorker && m.worker && input.artifacts.worker) {
255
277
  const fn = await ensureFunction(ctx, {
@@ -284,7 +306,12 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
284
306
  await removeWorker(ctx, app, stage);
285
307
  }
286
308
 
287
- // 9. Static files (new prefix per deployment; the old one keeps serving until the route flips).
309
+ // The route the edge serves now. The new revision goes on the endpoint it doesn't use, and GC keeps
310
+ // its static files: edges keep serving it until they pick up the new route.
311
+ const liveRoute =
312
+ webMode === 'function' && platform.kvsArn ? await getRoute(ctx, platform.kvsArn, host) : undefined;
313
+
314
+ // 10. Static files (new prefix per deployment; the old one keeps serving until the route flips).
288
315
  let staticPrefix: string | undefined;
289
316
  if (input.artifacts.static) {
290
317
  staticPrefix = names.sitePrefix(app, stage, deploymentId);
@@ -296,7 +323,7 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
296
323
  resources.push({ type: 'static', name: staticPrefix });
297
324
  }
298
325
 
299
- // 10. Web Function revision → endpoint.
326
+ // 11. Web Function revision → an endpoint the live route doesn't use.
300
327
  let webFunction: DeployStageResult['webFunction'];
301
328
  if (hasWeb && m.web && input.artifacts.server) {
302
329
  const fnName = names.webFunction(app, stage);
@@ -311,35 +338,29 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
311
338
  logGroup: webLogGroup,
312
339
  description: deploymentId,
313
340
  };
314
- const before = await getEndpoint(ctx, fnName, names.webEndpoint());
315
- const previous = (before?.revisionWeights ?? []).map((w) => w.revisionId!).filter(Boolean);
316
341
  const fn = await ensureWebFunction(ctx, {
317
342
  name: fnName,
318
343
  tags,
319
- initial: { revision, endpointName: names.webEndpoint() },
344
+ initial: { revision, endpointName: names.webEndpoints()[0] },
320
345
  });
321
346
  const fnArn = fn.arn;
322
347
  const revisionId = fn.initialRevisionId ?? (await createRevision(ctx, revision));
323
- const endpoint = await ensureEndpoint(ctx, {
348
+ const endpoint = await endpointForRevision(ctx, {
324
349
  functionName: fnName,
325
- endpointName: names.webEndpoint(),
350
+ functionArn: fnArn,
351
+ endpointNames: names.webEndpoints(),
326
352
  revisionId,
353
+ ...(liveRoute?.o ? { liveDomain: liveRoute.o } : {}),
354
+ ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
327
355
  });
328
- if (platform.distributionArn) {
329
- await ensureRouterAccess(ctx, {
330
- functionArn: fnArn,
331
- endpointArn: endpoint.arn,
332
- distributionArn: platform.distributionArn,
333
- });
334
- }
335
- await pruneRevisions(ctx, fnName, { keepNewest: 2, keep: [revisionId, ...previous] });
356
+ await pruneRevisions(ctx, fnName, { keepNewest: DEPLOYMENTS_KEPT, keep: endpoint.pinned });
336
357
  webFunction = { name: fnName, endpointDomain: endpoint.domainName, revisionId };
337
358
  resources.push({ type: 'web-function', name: fnName, arn: fnArn });
338
359
  } else if (webMode === 'function') {
339
360
  await deleteWebFunction(ctx, names.webFunction(app, stage));
340
361
  }
341
362
 
342
- // 11. Route flip — the only step that changes what users see.
363
+ // 12. Route flip — the only step that changes what users see.
343
364
  let route: RouteRecord | undefined;
344
365
  if (webMode === 'function' && (webFunction || staticPrefix)) {
345
366
  route = {
@@ -360,18 +381,15 @@ export async function deployStage(ctx: EngineContext, input: DeployStageInput):
360
381
  }
361
382
  }
362
383
 
363
- // 12. Garbage-collect old static deployments.
384
+ // 13. Garbage-collect old static deployments.
364
385
  if (staticPrefix) {
365
- const prefixes = (await listChildPrefixes(ctx, platform.sitesBucket, `${app}/${stage}/`))
366
- .sort()
367
- .reverse();
368
- for (const p of prefixes.slice(STATIC_DEPLOYMENTS_KEPT)) {
369
- if (p.startsWith(staticPrefix)) continue;
386
+ const prefixes = await listChildPrefixes(ctx, platform.sitesBucket, `${app}/${stage}/`);
387
+ for (const p of staleStaticPrefixes(prefixes, [staticPrefix, liveRoute?.s])) {
370
388
  await deletePrefix(ctx, platform.sitesBucket, p);
371
389
  }
372
390
  }
373
391
 
374
- // 13. Queues removed from the manifest.
392
+ // 14. Queues removed from the manifest.
375
393
  const wantedQueues = new Set(
376
394
  Object.keys(m.queues).flatMap((k) => [names.queue(app, stage, k), names.deadLetterQueue(app, stage, k)]),
377
395
  );
@@ -488,17 +506,70 @@ async function removeWorker(ctx: EngineContext, app: string, stage: string): Pro
488
506
  await deleteFunction(ctx, workerName);
489
507
  }
490
508
 
491
- export async function rollbackStage(ctx: EngineContext, input: RollbackStageInput): Promise<void> {
492
- const { app, stage, platform } = input;
509
+ /**
510
+ * Static prefixes (`<app>/<stage>/<deployment>/`) to delete after a deploy:
511
+ * all but the newest few, never one in `keep`. That includes the prefix the
512
+ * previous route pointed at: edges that haven't picked up the new route
513
+ * still serve it, and it is what a rollback returns to. After a rollback to
514
+ * an earlier deployment it can be older than the newest few.
515
+ */
516
+ export function staleStaticPrefixes(prefixes: string[], keep: Array<string | undefined>): string[] {
517
+ const kept = new Set(keep.filter(Boolean).map((k) => `${k}/`));
518
+ // Deployment ids sort by creation time.
519
+ return [...prefixes]
520
+ .sort()
521
+ .reverse()
522
+ .slice(DEPLOYMENTS_KEPT)
523
+ .filter((p) => !kept.has(p));
524
+ }
525
+
526
+ /**
527
+ * Rollback targets lose their files to garbage collection after enough
528
+ * deploys. Check before changing anything, so a stage is never pointed at a
529
+ * deployment that can no longer serve.
530
+ */
531
+ async function assertCanRollBack(ctx: EngineContext, input: RollbackStageInput): Promise<void> {
532
+ const { app, stage, platform, route } = input;
533
+ const gone = (what: string) => new Error(`deployment ${route.d} can't be rolled back to: ${what}`);
534
+ if (route.s && !(await hasObjects(ctx, platform.sitesBucket, `${route.s}/`))) {
535
+ throw gone('its static files have been cleaned up');
536
+ }
493
537
  if (input.revisionId) {
494
- await setEndpointRevision(ctx, {
495
- functionName: names.webFunction(app, stage),
496
- endpointName: names.webEndpoint(),
538
+ const state = await getRevisionState(ctx, names.webFunction(app, stage), input.revisionId);
539
+ if (!state) throw gone('its server revision has been cleaned up');
540
+ if (state !== 'Active') throw gone(`its server revision is ${state}`);
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Point the stage back at an earlier deployment. Its revision usually still
546
+ * has an endpoint pinned to it (always for the previous deployment), so the
547
+ * route write is the whole switch; otherwise the endpoint the live route
548
+ * doesn't use is pointed at it first. Returns the route written: its
549
+ * endpoint can differ from the one recorded at deploy time.
550
+ */
551
+ export async function rollbackStage(ctx: EngineContext, input: RollbackStageInput): Promise<RouteRecord> {
552
+ const { app, stage, platform } = input;
553
+ await assertCanRollBack(ctx, input);
554
+ const host = hostFor(platform, app, stage);
555
+ let route = input.route;
556
+ if (input.revisionId && route.o) {
557
+ const functionName = names.webFunction(app, stage);
558
+ const fn = await ctx.clients.lambdaWeb.send(new GetWebFunctionCommand({ functionName }));
559
+ const live = platform.kvsArn ? await getRoute(ctx, platform.kvsArn, host) : undefined;
560
+ const endpoint = await endpointForRevision(ctx, {
561
+ functionName,
562
+ functionArn: fn.functionArn!,
563
+ endpointNames: names.webEndpoints(),
497
564
  revisionId: input.revisionId,
565
+ ...(live?.o ? { liveDomain: live.o } : {}),
566
+ ...(platform.distributionArn ? { distributionArn: platform.distributionArn } : {}),
498
567
  });
568
+ route = { ...route, o: endpoint.domainName };
499
569
  }
500
- if (platform.kvsArn) await putRoute(ctx, platform.kvsArn, hostFor(platform, app, stage), input.route);
501
- ctx.log('info', `rolled back ${app}/${stage} to ${input.route.d}`);
570
+ if (platform.kvsArn) await putRoute(ctx, platform.kvsArn, host, route);
571
+ ctx.log('info', `rolled back ${app}/${stage} to ${route.d}`);
572
+ return route;
502
573
  }
503
574
 
504
575
  /** Remove a stage. Order: stop traffic, stop triggers, compute, messaging, identity, then (optionally) data. */
@@ -515,6 +586,7 @@ export async function destroyStage(ctx: EngineContext, input: DestroyStageInput)
515
586
  if (platform.userPoolId)
516
587
  await deleteUserPoolClient(ctx, platform.userPoolId, names.userPoolClient(app, stage));
517
588
  await deleteRole(ctx, names.role(app, stage));
589
+ await deleteParameter(ctx, names.stageKeyParameter(app, stage));
518
590
  for (const g of await listLogGroups(ctx, names.logGroupPrefix(app, stage))) await deleteLogGroup(ctx, g);
519
591
  await deletePrefix(ctx, platform.sitesBucket, `${app}/${stage}/`);
520
592
  await deletePrefix(ctx, platform.artifactsBucket, `${app}/${stage}/`);
@@ -1,20 +0,0 @@
1
- import { type EngineContext } from '../util.ts';
2
- export interface CertificateState {
3
- arn: string;
4
- status: string;
5
- /** DNS records ACM wants for validation (CNAMEs). */
6
- validation: Array<{
7
- domain: string;
8
- name: string;
9
- value: string;
10
- status?: string;
11
- }>;
12
- }
13
- /** A DNS-validated public certificate in us-east-1 (for CloudFront and Cognito custom domains). */
14
- export declare function ensureCertificate(ctx: EngineContext, spec: {
15
- domainName: string;
16
- alternativeNames?: string[];
17
- tags?: Record<string, string>;
18
- }): Promise<CertificateState>;
19
- export declare function describeCertificate(ctx: EngineContext, arn: string): Promise<CertificateState>;
20
- export declare function waitCertificateIssued(ctx: EngineContext, arn: string, timeoutMs?: number): Promise<void>;
@@ -1,62 +0,0 @@
1
- import { DescribeCertificateCommand, ListCertificatesCommand, RequestCertificateCommand, } from '@aws-sdk/client-acm';
2
- import { tagList, waitFor } from '../util.js';
3
- /** A DNS-validated public certificate in us-east-1 (for CloudFront and Cognito custom domains). */
4
- export async function ensureCertificate(ctx, spec) {
5
- const acm = ctx.clients.acm;
6
- const wantedSans = [...new Set([spec.domainName, ...(spec.alternativeNames ?? [])])].sort();
7
- let arn;
8
- let NextToken;
9
- do {
10
- const res = await acm.send(new ListCertificatesCommand({ CertificateStatuses: ['ISSUED', 'PENDING_VALIDATION'], NextToken }));
11
- for (const c of res.CertificateSummaryList ?? []) {
12
- if (c.DomainName !== spec.domainName || !c.CertificateArn)
13
- continue;
14
- const d = await acm.send(new DescribeCertificateCommand({ CertificateArn: c.CertificateArn }));
15
- const sans = [...(d.Certificate?.SubjectAlternativeNames ?? [])].sort();
16
- if (JSON.stringify(sans) === JSON.stringify(wantedSans)) {
17
- arn = c.CertificateArn;
18
- break;
19
- }
20
- }
21
- NextToken = arn ? undefined : res.NextToken;
22
- } while (NextToken);
23
- if (!arn) {
24
- const res = await acm.send(new RequestCertificateCommand({
25
- DomainName: spec.domainName,
26
- SubjectAlternativeNames: wantedSans,
27
- ValidationMethod: 'DNS',
28
- IdempotencyToken: spec.domainName.replace(/[^A-Za-z0-9]/g, '').slice(0, 32),
29
- Tags: spec.tags ? tagList(spec.tags) : undefined,
30
- }));
31
- arn = res.CertificateArn;
32
- ctx.log('info', 'requested certificate', `certificate ${spec.domainName}`);
33
- }
34
- return describeCertificate(ctx, arn);
35
- }
36
- export async function describeCertificate(ctx, arn) {
37
- // Validation records appear a few seconds after the request.
38
- return waitFor(`certificate ${arn} validation records`, async () => {
39
- const d = await ctx.clients.acm.send(new DescribeCertificateCommand({ CertificateArn: arn }));
40
- const cert = d.Certificate;
41
- const validation = (cert.DomainValidationOptions ?? [])
42
- .filter((o) => o.ResourceRecord?.Name)
43
- .map((o) => ({
44
- domain: o.DomainName,
45
- name: o.ResourceRecord.Name,
46
- value: o.ResourceRecord.Value,
47
- ...(o.ValidationStatus ? { status: o.ValidationStatus } : {}),
48
- }));
49
- if (cert.Status === 'PENDING_VALIDATION' && validation.length === 0)
50
- return false;
51
- return { arn, status: cert.Status ?? 'UNKNOWN', validation };
52
- });
53
- }
54
- export async function waitCertificateIssued(ctx, arn, timeoutMs = 15 * 60_000) {
55
- await waitFor(`certificate ${arn} issued`, async () => {
56
- const d = await ctx.clients.acm.send(new DescribeCertificateCommand({ CertificateArn: arn }));
57
- if (d.Certificate?.Status === 'FAILED')
58
- throw new Error(`certificate ${arn} failed validation`);
59
- return d.Certificate?.Status === 'ISSUED';
60
- }, { timeoutMs, intervalMs: 10_000 });
61
- }
62
- //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Ae,GAAG,oBAAoB,CAAC,CAAC;QAChG,OAAO,CAAC,CAAC,WAAW,EAAE,MAAM,KAAK,QAAQ,CAAC;IAC5C,CAAC,EACD,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,CAClC,CAAC;AACJ,CAAC"}
@@ -1,52 +0,0 @@
1
- import { type CachePolicyConfig, type DistributionConfig } from '@aws-sdk/client-cloudfront';
2
- import { type EngineContext } from '../util.ts';
3
- /** AWS managed origin request policy `Managed-AllViewerExceptHostHeader` (Web Function origins need it). */
4
- export declare const ALL_VIEWER_EXCEPT_HOST_HEADER = "b689b0a8-53d0-40ab-baf2-68738e2966ac";
5
- /** Route 53 hosted zone id for every CloudFront alias target. */
6
- export declare const CLOUDFRONT_HOSTED_ZONE_ID = "Z2FDTNDATAQYW2";
7
- export declare function ensureKeyValueStore(ctx: EngineContext, spec: {
8
- name: string;
9
- comment?: string;
10
- }): Promise<{
11
- arn: string;
12
- id: string;
13
- }>;
14
- /** Create/update a CloudFront Function (runtime 2.0) and publish it to LIVE. Returns the function ARN. */
15
- export declare function ensureRouterFunction(ctx: EngineContext, spec: {
16
- name: string;
17
- code: string;
18
- kvsArn?: string;
19
- comment?: string;
20
- }): Promise<string>;
21
- export declare function ensureOriginAccessControl(ctx: EngineContext, spec: {
22
- name: string;
23
- originType: 's3' | 'lambda';
24
- signingBehavior?: 'always' | 'always-amz-auth';
25
- }): Promise<string>;
26
- export declare function ensureCachePolicy(ctx: EngineContext, config: CachePolicyConfig): Promise<string>;
27
- /** The platform router's cache policy: origins decide caching; the host is part of the key. */
28
- export declare function routerCachePolicy(name: string): CachePolicyConfig;
29
- export interface DistributionState {
30
- id: string;
31
- arn: string;
32
- domainName: string;
33
- status: string;
34
- }
35
- /**
36
- * A distribution identified by its `Comment` (CloudFront has no names).
37
- * `config` is the full desired DistributionConfig minus CallerReference.
38
- */
39
- export declare function ensureDistribution(ctx: EngineContext, spec: {
40
- comment: string;
41
- config: Omit<DistributionConfig, 'CallerReference' | 'Comment'>;
42
- tags?: Record<string, string>;
43
- }): Promise<DistributionState>;
44
- export declare function findDistribution(ctx: EngineContext, comment: string): Promise<DistributionState | undefined>;
45
- /**
46
- * Overlay `patch` on `base`: objects merge key by key, equal-length arrays
47
- * merge element by element (CloudFront lists like Origins keep their order),
48
- * anything else is replaced. Undefined patch values keep the base value.
49
- */
50
- export declare function deepMerge(base: unknown, patch: unknown): unknown;
51
- /** Paths where two normalized values differ, e.g. `DefaultCacheBehavior.Compress`. */
52
- export declare function diffPaths(a: unknown, b: unknown, path?: string): string[];