@geekmidas/cloud 10.0.0-alpha.18 → 10.0.0-alpha.180

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 (35) hide show
  1. package/README.md +26 -6
  2. package/package.json +9 -8
  3. package/src/sst/__tests__/api.spec.ts +0 -46
  4. package/src/sst/__tests__/bootstrap.spec.ts +15 -0
  5. package/src/sst/__tests__/encryption.spec.ts +90 -0
  6. package/src/sst/__tests__/fromManifest.inbox.spec.ts +157 -0
  7. package/src/sst/__tests__/fromManifest.integration.spec.ts +87 -3
  8. package/src/sst/__tests__/fromManifest.secret.spec.ts +79 -0
  9. package/src/sst/__tests__/fromManifest.spec.ts +412 -18
  10. package/src/sst/__tests__/function.spec.ts +0 -71
  11. package/src/sst/__tests__/hostLabels.spec.ts +74 -0
  12. package/src/sst/__tests__/surfaces.spec.ts +68 -5
  13. package/src/sst/__tests__/websocket.spec.ts +207 -0
  14. package/src/sst/__tests__/wildcardSite.spec.ts +195 -0
  15. package/src/sst/__type-tests__/overrides.type-test.ts +152 -0
  16. package/src/sst/aws/Api.ts +0 -43
  17. package/src/sst/aws/Credential.ts +42 -9
  18. package/src/sst/aws/Cron.ts +5 -45
  19. package/src/sst/aws/DatabaseBootstrap.ts +6 -0
  20. package/src/sst/aws/Encryption.ts +91 -0
  21. package/src/sst/aws/ExternalApi.ts +58 -0
  22. package/src/sst/aws/Function.ts +9 -38
  23. package/src/sst/aws/Inbox.ts +141 -0
  24. package/src/sst/aws/ObjectStorage.ts +3 -3
  25. package/src/sst/aws/Queue.ts +34 -1
  26. package/src/sst/aws/RestApiSurface.ts +36 -14
  27. package/src/sst/aws/Secret.ts +6 -4
  28. package/src/sst/aws/StaticSite.ts +44 -1
  29. package/src/sst/aws/WebSocketApiSurface.ts +160 -0
  30. package/src/sst/aws/bootstrap/handler.ts +12 -1
  31. package/src/sst/errors.ts +37 -0
  32. package/src/sst/fromManifest.ts +624 -71
  33. package/src/sst/index.ts +21 -1
  34. package/src/sst/overrides.ts +149 -0
  35. package/src/sst/__type-tests__/manifest.type-test.ts +0 -77
@@ -19,6 +19,8 @@ import type {
19
19
  Declaration,
20
20
  DeclarationKind,
21
21
  Dependency,
22
+ SecretDeclaration,
23
+ SecretFormat,
22
24
  SiteDeclaration,
23
25
  } from '@geekmidas/manifest';
24
26
  import {
@@ -26,11 +28,23 @@ import {
26
28
  cookieDomain,
27
29
  DEFAULT_POSTGRES_VERSION,
28
30
  dependentsOf,
29
- PUBLIC,
31
+ hostLabels,
32
+ IMAGE_ORIGINS_KEY,
33
+ imageOriginSources,
34
+ imageOrigins,
35
+ isHostedDeclaration,
36
+ isWildcardSite,
37
+ mobileOrigins,
30
38
  PUBLIC_PREFIX,
31
39
  providedKeyFor,
32
40
  provisionOrder,
41
+ publicValues,
42
+ SECRET_LENGTH,
43
+ SECRET_SYMBOLS,
44
+ schemeBase,
33
45
  } from '@geekmidas/manifest';
46
+ import { s3Url } from '@geekmidas/storage/aws';
47
+ import { RandomPassword } from '@pulumi/random';
34
48
  import {
35
49
  Cache,
36
50
  CacheIsAmbiguous,
@@ -39,23 +53,31 @@ import {
39
53
  withCacheTable,
40
54
  } from './aws/Cache';
41
55
  import { Credential } from './aws/Credential';
56
+ import { Cron, type CronSchedule } from './aws/Cron';
42
57
  import { Database, DatabaseNeedsVpc, type DatabaseProps } from './aws/Database';
43
58
  import { DatabaseBootstrap } from './aws/DatabaseBootstrap';
44
59
  import { DatabaseReader, DatabaseSchema } from './aws/DerivedDatabase';
45
60
  import { Email, EmailNeedsSender } from './aws/Email';
61
+ import { Encryption, type EncryptionProps } from './aws/Encryption';
62
+ import { ExternalApi, type ExternalApiProps } from './aws/ExternalApi';
46
63
  import { FileServer } from './aws/FileServer';
64
+ import { Function } from './aws/Function';
65
+ import { Inbox, InboxTopic } from './aws/Inbox';
47
66
  import { ObjectStorage } from './aws/ObjectStorage';
48
67
  import { Queue } from './aws/Queue';
49
68
  import { RestApiSurface } from './aws/RestApiSurface';
50
- import { Secret } from './aws/Secret';
69
+ import { Secret, type SecretProps } from './aws/Secret';
51
70
  import { StaticSite } from './aws/StaticSite';
52
71
  import { Topic } from './aws/Topic';
72
+ import { WebSocketApiSurface } from './aws/WebSocketApiSurface';
53
73
  import {
74
+ HostLabelNeedsCustomDomain,
54
75
  ProvidesMismatch,
55
76
  UnknownDeclarationKind,
56
77
  UnresolvedDependency,
57
78
  } from './errors';
58
79
  import type { GkmLinkable } from './Linkable';
80
+ import type { ManifestBackends, ManifestOverrides } from './overrides';
59
81
  import type { StackType } from './Stack';
60
82
 
61
83
  /**
@@ -105,6 +127,8 @@ export interface ProvisionContext {
105
127
  */
106
128
  cache?: 'upstash' | 'elasticache' | 'db';
107
129
  email?: 'resend' | 'ses' | 'smtp';
130
+ /** The labels no tenant of a wildcard site may take. */
131
+ protectedSubdomains?: readonly string[];
108
132
  /**
109
133
  * One deferred caller list per surface, resolved once everything exists.
110
134
  *
@@ -133,21 +157,6 @@ type Provisioner = (
133
157
  context: ProvisionContext,
134
158
  ) => Provisioned;
135
159
 
136
- /**
137
- * Provider-specific props, per construct id.
138
- *
139
- * Neutral options — `versioned`, and later `cdn` — travel in the declaration,
140
- * because the app legitimately has an opinion about them. Anything with S3 in
141
- * its name does not belong in application code, so lifecycle rules, CORS, and
142
- * canned ACLs are supplied here, in the deploy layer, keyed by the id they
143
- * apply to and typed against the component that receives them.
144
- *
145
- * A third escape hatch needs no API at all: `fromManifest` returns the
146
- * components, so `provisioned.Uploads.nodes.bucket` is reachable for anything
147
- * neither route covers.
148
- */
149
- export type ComponentOverrides = Record<string, Record<string, unknown>>;
150
-
151
160
  /**
152
161
  * Which component provisions which kind.
153
162
  *
@@ -189,7 +198,15 @@ const PROVISIONERS: Partial<Record<DeclarationKind, Provisioner>> = {
189
198
  return new StaticSite(stack, d.id, {
190
199
  path: d.app.path,
191
200
  variant: d.variant,
192
- environment: siteEnvironment(d, context),
201
+ environment: siteEnvironment(d, context, stack),
202
+ // Every subdomain, on one distribution: see `StaticSite`.
203
+ ...(isWildcardSite(d)
204
+ ? {
205
+ tenants: {
206
+ protectedSubdomains: context.protectedSubdomains ?? [],
207
+ },
208
+ }
209
+ : {}),
193
210
  ...props,
194
211
  });
195
212
  },
@@ -206,6 +223,12 @@ const PROVISIONERS: Partial<Record<DeclarationKind, Provisioner>> = {
206
223
  // producer's and subscribers' business, and SNS has no per-event
207
224
  // configuration to map it onto.
208
225
  topic: (stack, d, props) => new Topic(stack, d.id, props),
226
+ // What receives the mail is its provider's, made before SST runs; the
227
+ // inbox is the values that made, linked. See `aws/Inbox`.
228
+ inbox: (stack, d, props) => {
229
+ if (d.kind !== 'inbox') throw new UnknownDeclarationKind(d.kind, []);
230
+ return new Inbox(stack, d.id, { ...props, topicId: d.topic });
231
+ },
209
232
 
210
233
  database: (stack, d, props, context) => {
211
234
  if (d.kind !== 'database') throw new UnknownDeclarationKind(d.kind, []);
@@ -241,6 +264,10 @@ const PROVISIONERS: Partial<Record<DeclarationKind, Provisioner>> = {
241
264
  schema: d.schema,
242
265
  runtime,
243
266
  owner: ownerRole(runtime),
267
+ ownsDatabase: true,
268
+ // RDS ships PostGIS, so the image is not a question here — only the
269
+ // `CREATE EXTENSION`, which the master can run and the owner cannot.
270
+ ...(d.extensions?.length ? { extensions: d.extensions } : {}),
244
271
  ...(hasReader(d.id, context) ? { reader: readerRole(runtime) } : {}),
245
272
  });
246
273
 
@@ -374,17 +401,12 @@ const PROVISIONERS: Partial<Record<DeclarationKind, Provisioner>> = {
374
401
  },
375
402
 
376
403
  /**
377
- * The surface, without its routes.
404
+ * The surface, without its routes yet.
378
405
  *
379
- * An API Gateway with no routes 404s everything, and that is the honest
380
- * state: the *surface* is what this kind declares, and mounting handlers on
381
- * it is the endpoint merge that has not landed — routes still reach the
382
- * deploy target through the separate `RouteInfo[]` pipeline.
383
- *
384
- * Provisioning it anyway is not ceremony. Its address is what a site inlines
385
- * as `VITE_API_URL`, what an auth server puts on its trusted-origin list, and
386
- * what the cookie domain derives from — so everything downstream of the API
387
- * is blocked on the API *existing*, not on it answering.
406
+ * Its address is what a site inlines as `VITE_API_URL`, what an auth server
407
+ * puts on its trusted-origin list, and what the cookie domain derives from —
408
+ * so it is provisioned in order, and its endpoints are mounted by
409
+ * {@link mountRoutes} once everything they link to exists.
388
410
  */
389
411
  'rest-api': (stack, d, props, context) =>
390
412
  new RestApiSurface(stack, d.id, {
@@ -392,10 +414,55 @@ const PROVISIONERS: Partial<Record<DeclarationKind, Provisioner>> = {
392
414
  callers: context.callers?.get(d.id)?.promise,
393
415
  }),
394
416
 
395
- secret: (stack, d, props) => new Secret(stack, d.id, props),
417
+ /**
418
+ * An API Gateway WebSocket API and its connection table, without its
419
+ * routes yet — mounted by {@link mountWebSocketRoutes} once everything
420
+ * they link to exists, as a REST surface's endpoints are.
421
+ */
422
+ 'websocket-api': (stack, d, props, context) =>
423
+ new WebSocketApiSurface(stack, d.id, {
424
+ ...(props as sst.aws.ApiGatewayWebSocketArgs),
425
+ callers: context.callers?.get(d.id)?.promise,
426
+ ...(d.kind === 'websocket-api' && d.discriminator
427
+ ? { discriminator: d.discriminator }
428
+ : {}),
429
+ }),
430
+
431
+ // Generated on the first deploy and kept in the stage's state, as a server
432
+ // stage keeps it in its secrets: every later deploy reads the same value
433
+ // back. One set with `sst secret set` wins over it.
434
+ secret: (stack, d, props) =>
435
+ new Secret(stack, d.id, {
436
+ placeholder: generatedSecret(d.id, d as SecretDeclaration),
437
+ ...(props as SecretProps),
438
+ }),
396
439
 
397
440
  // The same storage as a secret, under a different role — see the component.
398
441
  credential: (stack, d, props) => new Credential(stack, d.id, props),
442
+
443
+ // In the stage's region, as mail is: a key in another region is a key
444
+ // every call crosses the world to reach.
445
+ encryption: (stack, d, props) =>
446
+ new Encryption(stack, d.id, {
447
+ ...(props as Partial<EncryptionProps>),
448
+ region:
449
+ (props as Partial<EncryptionProps>).region ??
450
+ $app.providers?.aws?.region ??
451
+ 'us-east-1',
452
+ }),
453
+
454
+ // Nothing to provision: the URL this stage calls, and the credentials kept
455
+ // as a secret.
456
+ 'external-api': (stack, d, props) => {
457
+ if (d.kind !== 'external-api') {
458
+ throw new UnknownDeclarationKind(d.kind, []);
459
+ }
460
+
461
+ return new ExternalApi(stack, d.id, {
462
+ ...(props as Partial<ExternalApiProps>),
463
+ url: d.url,
464
+ });
465
+ },
399
466
  };
400
467
 
401
468
  /**
@@ -414,34 +481,74 @@ const PROVISIONERS: Partial<Record<DeclarationKind, Provisioner>> = {
414
481
  export function siteEnvironment(
415
482
  declaration: SiteDeclaration,
416
483
  context: ProvisionContext,
484
+ stack?: StackType,
417
485
  ): Record<string, $util.Input<string>> {
418
486
  const prefix = PUBLIC_PREFIX[declaration.variant];
419
487
  const environment: Record<string, $util.Input<string>> = {};
420
488
 
421
- for (const edge of declaration.dependencies) {
422
- const target = context.manifest[edge.target];
423
- if (!target) continue;
424
-
425
- const roles = PUBLIC[target.kind] ?? [];
426
- if (roles.length === 0) continue;
489
+ // A wildcard site takes its tenant off the host it is reached on, so it
490
+ // inlines the domain to take the label off against, and the labels no
491
+ // tenant may be — the same two keys `publicEnvFor` names locally.
492
+ if (isWildcardSite(declaration) && stack?.domain) {
493
+ const own = {
494
+ domain: stack.domain,
495
+ protectedSubdomains: (context.protectedSubdomains ?? []).join(','),
496
+ };
497
+ for (const [role, value] of Object.entries(own)) {
498
+ environment[`${prefix}${providedKeyFor(declaration.id, 'site', role)}`] =
499
+ value;
500
+ }
501
+ }
427
502
 
428
- const component = context.provisioned[edge.target];
503
+ // The one walk of a frontend's edges every target makes (`publicValues`):
504
+ // each value is read off the component that provides it.
505
+ for (const { id, kind, role, key } of publicValues(
506
+ declaration,
507
+ context.manifest,
508
+ )) {
509
+ const component = context.provisioned[id];
429
510
  if (!component) {
430
- throw new UnresolvedDependency(
431
- edge.target,
432
- Object.keys(context.provisioned),
433
- );
511
+ throw new UnresolvedDependency(id, Object.keys(context.provisioned));
434
512
  }
435
513
 
436
514
  const provided = component.provides();
437
- for (const role of roles) {
438
- const value = provided[role as string];
439
- if (value === undefined) continue;
440
-
441
- environment[
442
- `${prefix}${providedKeyFor(edge.target, target.kind, role as string)}`
443
- ] = value;
515
+ let value = provided[role];
516
+ // A bucket's signed origin is derived from its connection, not
517
+ // provided: where its presigned links point is a function of it.
518
+ if (
519
+ value === undefined &&
520
+ kind === 'objects' &&
521
+ role === 'signedOrigin' &&
522
+ provided.connectionString !== undefined
523
+ ) {
524
+ value = $util
525
+ .output(provided.connectionString)
526
+ .apply((connection) => s3Url.signedOrigin(s3Url.parse(connection)));
444
527
  }
528
+ if (value !== undefined) environment[`${prefix}${key}`] = value;
529
+ }
530
+
531
+ // The origins its pages load files from, as one list: composed from the
532
+ // values just inlined, under the names `imageOriginSources` gives them.
533
+ const inlined = imageOriginSources(declaration, context.manifest).flatMap(
534
+ (source) => {
535
+ const value = environment[`${prefix}${source}`];
536
+ return value === undefined ? [] : [{ source, value }];
537
+ },
538
+ );
539
+ if (inlined.length > 0) {
540
+ environment[`${prefix}${IMAGE_ORIGINS_KEY}`] = $util
541
+ .all(inlined.map(({ value }) => value))
542
+ .apply((values) => {
543
+ const resolved = new Map(
544
+ inlined.map(({ source }, index) => [source, values[index]]),
545
+ );
546
+ return (
547
+ imageOrigins([...resolved.keys()], (source) =>
548
+ resolved.get(source),
549
+ ) ?? ''
550
+ );
551
+ });
445
552
  }
446
553
 
447
554
  return environment;
@@ -576,9 +683,7 @@ function rootCluster(component: Provisioned): Database {
576
683
  * printed: one line per route, naming what it can reach.
577
684
  *
578
685
  * A surface with no routes says so rather than printing nothing, because "no
579
- * routes yet" and "this printed nothing" look identical otherwise — and for an
580
- * application's own API that is currently the true state, pending the endpoint
581
- * merge.
686
+ * routes" and "this printed nothing" look identical otherwise.
582
687
  *
583
688
  * Pure, so what gets printed can be asserted without a deploy.
584
689
  */
@@ -586,13 +691,26 @@ export function describeRoutes(manifest: ConstructManifest): string[] {
586
691
  const lines: string[] = [];
587
692
 
588
693
  for (const [id, declaration] of Object.entries(manifest)) {
694
+ if (declaration.kind === 'websocket-api') {
695
+ lines.push(`${id}:`);
696
+ for (const route of declaration.routes ?? []) {
697
+ const reaches = route.dependencies
698
+ .map((edge) => `${edge.target} (${edge.kind})`)
699
+ .join(', ');
700
+ lines.push(` ${route.action} → ${reaches || 'its connections'}`);
701
+ }
702
+ if (declaration.auth) {
703
+ lines.push(` auth ${declaration.auth.target} ($connect verifies)`);
704
+ }
705
+ continue;
706
+ }
589
707
  if (declaration.kind !== 'rest-api') continue;
590
708
 
591
709
  lines.push(`${id}:`);
592
710
 
593
711
  if (declaration.endpoints.length === 0) {
594
- // Empty is now genuinely empty: the build folds discovered routes into
595
- // the surface that serves them, so a surface with none has none.
712
+ // Empty is genuinely empty: discovery nests every route in the
713
+ // surface that serves it, so a surface with none has none.
596
714
  lines.push(' (no routes)');
597
715
  }
598
716
 
@@ -606,11 +724,11 @@ export function describeRoutes(manifest: ConstructManifest): string[] {
606
724
  );
607
725
  }
608
726
 
609
- // A caller relationship, printed apart from the routes because it grants
610
- // nothing — see `RestApiDeclaration.calls`.
611
- if (declaration.calls?.length) {
727
+ // What authenticates it, printed apart from the routes because it grants
728
+ // nothing: the auth server learns this surface's origin.
729
+ if (declaration.auth) {
612
730
  lines.push(
613
- ` calls ${declaration.calls.map((edge) => edge.target).join(', ')} (origin only; grants nothing)`,
731
+ ` auth ${declaration.auth.target} (origin only; grants nothing)`,
614
732
  );
615
733
  }
616
734
  }
@@ -618,6 +736,22 @@ export function describeRoutes(manifest: ConstructManifest): string[] {
618
736
  return lines;
619
737
  }
620
738
 
739
+ /**
740
+ * An AWS stage refuses aliases and redirects outright: no surface but a
741
+ * wildcard site has a custom domain there to put them under.
742
+ *
743
+ * @throws {HostLabelNeedsCustomDomain} naming the first construct with either
744
+ */
745
+ export function assertNoHostLabels(manifest: ConstructManifest): void {
746
+ for (const [id, declaration] of Object.entries(manifest)) {
747
+ if (!isHostedDeclaration(declaration)) continue;
748
+ const { aliases, redirects } = hostLabels(declaration);
749
+ if (aliases.length || redirects.length) {
750
+ throw new HostLabelNeedsCustomDomain(id, [...aliases, ...redirects]);
751
+ }
752
+ }
753
+ }
754
+
621
755
  /** A promise with its settle function, for a value that arrives later. */
622
756
  function defer(): Deferred {
623
757
  let resolve!: Deferred['resolve'];
@@ -647,6 +781,10 @@ async function callersOf(
647
781
  id: string,
648
782
  manifest: ConstructManifest,
649
783
  provisioned: ProvisionedManifest,
784
+ /** The app's name — a mobile caller's scheme base when it gives none. */
785
+ project: string,
786
+ /** The stack's domain, which a caller's aliases are labels under. */
787
+ domain?: string,
650
788
  ): Promise<{ trustedOrigins: string; cookieDomain?: string }> {
651
789
  // Every address here is a Pulumi output, not a string — a CloudFront domain
652
790
  // and an API Gateway endpoint are both known only after their resource
@@ -660,20 +798,42 @@ async function callersOf(
660
798
  ),
661
799
  );
662
800
 
801
+ // A caller's aliases are hosts it really answers on, so each is an
802
+ // origin beside its own; its redirects never run a page, so none is.
803
+ const aliases = domain
804
+ ? dependentsOf(manifest, id).flatMap((caller) => {
805
+ const declaration = manifest[caller];
806
+ return isHostedDeclaration(declaration)
807
+ ? hostLabels(declaration).aliases.map(
808
+ (label) => `https://${label}.${domain}`,
809
+ )
810
+ : [];
811
+ })
812
+ : [];
813
+
663
814
  const origins = [
664
815
  ...new Set(
665
- urls
816
+ [...urls, ...aliases]
666
817
  .map((url) => (url ? originOf(url) : undefined))
667
818
  .filter((origin): origin is string => Boolean(origin)),
668
819
  ),
669
820
  ].sort();
670
821
 
671
822
  const own = await resolved(provisioned[id]?.provides().url);
672
- const domain = cookieDomain([...(own ? [own] : []), ...origins]);
823
+ const shared = cookieDomain([...(own ? [own] : []), ...origins]);
824
+
825
+ // A mobile caller is reached by its scheme — the bare one, deployed: what
826
+ // the store build registers.
827
+ const schemes = dependentsOf(manifest, id).flatMap((caller) => {
828
+ const app = manifest[caller];
829
+ return app?.kind === 'mobile-app'
830
+ ? mobileOrigins(schemeBase(project, app.scheme))
831
+ : [];
832
+ });
673
833
 
674
834
  return {
675
- trustedOrigins: origins.join(','),
676
- ...(domain ? { cookieDomain: domain } : {}),
835
+ trustedOrigins: [...origins, ...schemes].join(','),
836
+ ...(shared ? { cookieDomain: shared } : {}),
677
837
  };
678
838
  }
679
839
 
@@ -722,6 +882,334 @@ export function isServed(id: string, manifest: ConstructManifest): boolean {
722
882
  );
723
883
  }
724
884
 
885
+ /**
886
+ * Kinds the in-order pass skips.
887
+ *
888
+ * - `mobile-app` ships through EAS and the stores. It is in the manifest for
889
+ * what it makes the surfaces trust, which `callersOf` reads off the graph.
890
+ * - `worker` is a process, not a resource: what it runs is provisioned as
891
+ * what it is — a queue's consumer by {@link subscribeConsumers}.
892
+ * - `cron` and `function` are Lambdas linked to what they depend on, so they
893
+ * are provisioned once all of it exists, by {@link provisionCompute}.
894
+ * - `telemetry` provisions nothing: where it goes is the stage's
895
+ * `deploy.telemetry`, a provider somebody else runs.
896
+ */
897
+ export const PROVISIONED_ELSEWHERE: ReadonlySet<DeclarationKind> =
898
+ new Set<DeclarationKind>([
899
+ 'mobile-app',
900
+ 'worker',
901
+ 'cron',
902
+ 'function',
903
+ 'telemetry',
904
+ ]);
905
+
906
+ /**
907
+ * Every function and cron: a Lambda running the handler the build wrote,
908
+ * linked to exactly what it depends on, in the database's network when it
909
+ * reaches one. A cron is that Lambda on its schedule; a function is reached
910
+ * at its URL, which only callers granted IAM access can invoke.
911
+ *
912
+ * After everything else is provisioned, because each links to things
913
+ * `provisionOrder` does not order before it.
914
+ */
915
+ export function provisionCompute(
916
+ stack: StackType,
917
+ manifest: ConstructManifest,
918
+ provisioned: ProvisionedManifest,
919
+ ): Cron[] {
920
+ const crons: Cron[] = [];
921
+
922
+ for (const [id, declaration] of Object.entries(manifest)) {
923
+ if (declaration?.kind !== 'function' && declaration?.kind !== 'cron') {
924
+ continue;
925
+ }
926
+
927
+ const { link } = resolveEdges(declaration.dependencies, provisioned);
928
+ const vpc = vpcFor(link);
929
+ const lambda = new Function(
930
+ stack,
931
+ declaration.kind === 'cron' ? `${id}Function` : id,
932
+ {
933
+ name: stack.logicalPrefixedName(id),
934
+ handler: declaration.handler,
935
+ link,
936
+ ...(vpc ? { vpc } : {}),
937
+ ...(declaration.kind === 'function'
938
+ ? { url: { authorization: 'iam' } }
939
+ : {}),
940
+ },
941
+ );
942
+
943
+ if (declaration.kind === 'cron') {
944
+ crons.push(
945
+ new Cron(stack, id, {
946
+ processor: lambda,
947
+ schedule: declaration.schedule as CronSchedule,
948
+ }),
949
+ );
950
+ continue;
951
+ }
952
+
953
+ assertProvides(
954
+ id,
955
+ declaration.provides,
956
+ Object.keys(lambda.provides()).map((role) =>
957
+ providedKeyFor(id, declaration.kind, role),
958
+ ),
959
+ );
960
+ provisioned[id] = lambda;
961
+ }
962
+
963
+ return crons;
964
+ }
965
+
966
+ /**
967
+ * Every file server's processors: each a Lambda behind a function URL with
968
+ * IAM auth, served through the file server's router on its pattern's prefix
969
+ * — so the CDN signs each request (origin access control) and the URL cannot
970
+ * be called around the cache. Linked to the bucket it reads and what it
971
+ * depends on; its native packages installed for the Lambda, not bundled.
972
+ *
973
+ * After everything else, for the reason {@link provisionCompute} is.
974
+ */
975
+ export function provisionProcessors(
976
+ stack: StackType,
977
+ manifest: ConstructManifest,
978
+ provisioned: ProvisionedManifest,
979
+ ): Function[] {
980
+ const lambdas: Function[] = [];
981
+
982
+ for (const [id, declaration] of Object.entries(manifest)) {
983
+ if (declaration?.kind !== 'file-server') continue;
984
+ const router = provisioned[id];
985
+ if (!router) continue;
986
+
987
+ for (const processor of declaration.processors ?? []) {
988
+ const { link } = resolveEdges(processor.dependencies, provisioned);
989
+ const vpc = vpcFor(link);
990
+ const native = processor.native ?? [];
991
+ lambdas.push(
992
+ new Function(stack, `${id}${processor.id}`, {
993
+ name: stack.logicalPrefixedName(`${id}${processor.id}`),
994
+ handler: processor.handler,
995
+ link,
996
+ ...(vpc ? { vpc } : {}),
997
+ ...(processor.timeout !== undefined
998
+ ? {
999
+ timeout:
1000
+ `${Math.ceil(processor.timeout / 1000)} seconds` as sst.aws.FunctionArgs['timeout'],
1001
+ }
1002
+ : {}),
1003
+ ...(processor.memorySize !== undefined
1004
+ ? {
1005
+ memory:
1006
+ `${processor.memorySize} MB` as sst.aws.FunctionArgs['memory'],
1007
+ }
1008
+ : {}),
1009
+ ...(native.length ? { nodejs: { install: [...native] } } : {}),
1010
+ url: {
1011
+ authorization: 'iam',
1012
+ router: {
1013
+ instance: router as unknown as sst.aws.Router,
1014
+ path: processor.prefix.replace(/\/$/, ''),
1015
+ },
1016
+ },
1017
+ }),
1018
+ );
1019
+ }
1020
+ }
1021
+
1022
+ return lambdas;
1023
+ }
1024
+
1025
+ /** A provisioned queue: what {@link subscribeConsumers} subscribes through. */
1026
+ interface Consumable {
1027
+ consume(consumer: {
1028
+ handler: string;
1029
+ link?: unknown[];
1030
+ vpc?: sst.aws.Vpc;
1031
+ }): unknown;
1032
+ }
1033
+
1034
+ /**
1035
+ * The network a function has to run in to reach what it links to.
1036
+ *
1037
+ * A database is private to its VPC, so a handler linked to one — or to a
1038
+ * schema tenant or reader of one — runs inside it, or its connection times out.
1039
+ */
1040
+ export function vpcFor(link: readonly Provisioned[]): sst.aws.Vpc | undefined {
1041
+ for (const component of link) {
1042
+ const cluster = rootCluster(component);
1043
+ if (cluster instanceof Database) return cluster.vpc;
1044
+ }
1045
+
1046
+ return undefined;
1047
+ }
1048
+
1049
+ /**
1050
+ * Mount every surface's endpoints — the handlers the build wrote, each linked
1051
+ * to exactly what that endpoint depends on.
1052
+ *
1053
+ * After every construct is provisioned, for the reason consumers are: an
1054
+ * endpoint links to things `provisionOrder` does not order before its surface.
1055
+ */
1056
+ export function mountRoutes(
1057
+ manifest: ConstructManifest,
1058
+ provisioned: ProvisionedManifest,
1059
+ ): void {
1060
+ for (const [id, declaration] of Object.entries(manifest)) {
1061
+ if (declaration?.kind !== 'rest-api') continue;
1062
+
1063
+ const surface = provisioned[id];
1064
+ if (!(surface instanceof RestApiSurface)) continue;
1065
+
1066
+ for (const endpoint of declaration.endpoints) {
1067
+ const { link } = resolveEdges(endpoint.dependencies, provisioned);
1068
+ const vpc = vpcFor(link);
1069
+ surface.mount({
1070
+ method: endpoint.method,
1071
+ path: endpoint.path,
1072
+ handler: endpoint.handler,
1073
+ link,
1074
+ ...(vpc ? { vpc } : {}),
1075
+ ...(endpoint.authorizer ? { authorizer: endpoint.authorizer } : {}),
1076
+ });
1077
+ }
1078
+ }
1079
+ }
1080
+
1081
+ /**
1082
+ * Mount every WebSocket surface's routes — the Lambdas the build wrote, each
1083
+ * linked to what that route depends on and to the surface itself (its
1084
+ * connection table and management API). `$connect` is also linked to what
1085
+ * authenticates the surface, since it verifies the handshake's session.
1086
+ *
1087
+ * After every construct is provisioned, for the reason endpoints are.
1088
+ */
1089
+ export function mountWebSocketRoutes(
1090
+ manifest: ConstructManifest,
1091
+ provisioned: ProvisionedManifest,
1092
+ ): void {
1093
+ for (const [id, declaration] of Object.entries(manifest)) {
1094
+ if (declaration?.kind !== 'websocket-api') continue;
1095
+
1096
+ const surface = provisioned[id];
1097
+ if (!(surface instanceof WebSocketApiSurface)) continue;
1098
+
1099
+ for (const route of declaration.routes ?? []) {
1100
+ const edges =
1101
+ route.action === '$connect' && declaration.auth
1102
+ ? [...route.dependencies, declaration.auth]
1103
+ : route.dependencies;
1104
+ const { link } = resolveEdges(edges, provisioned);
1105
+ const vpc = vpcFor(link);
1106
+ surface.mount({
1107
+ action: route.action,
1108
+ handler: route.handler,
1109
+ link,
1110
+ ...(vpc ? { vpc } : {}),
1111
+ });
1112
+ }
1113
+ }
1114
+ }
1115
+
1116
+ /**
1117
+ * Subscribe every queue's one consumer — the handler the build wrote for it,
1118
+ * linked to what that consumer depends on.
1119
+ *
1120
+ * After every construct is provisioned, because a consumer links to things
1121
+ * that `provisionOrder` does not order before the queue.
1122
+ */
1123
+ export function subscribeConsumers(
1124
+ manifest: ConstructManifest,
1125
+ provisioned: ProvisionedManifest,
1126
+ ): void {
1127
+ for (const [id, declaration] of Object.entries(manifest)) {
1128
+ if (declaration?.kind !== 'queue') continue;
1129
+
1130
+ const queue = provisioned[id] as unknown as Consumable | undefined;
1131
+ if (!queue) continue;
1132
+
1133
+ const { link } = resolveEdges(declaration.worker.dependencies, provisioned);
1134
+ const vpc = vpcFor(link);
1135
+ queue.consume({
1136
+ handler: declaration.worker.handler,
1137
+ link,
1138
+ ...(vpc ? { vpc } : {}),
1139
+ });
1140
+ }
1141
+ }
1142
+
1143
+ /** The topics inboxes declared: their provider's, never SST's to create. */
1144
+ export function inboxTopicIds(manifest: ConstructManifest): Set<string> {
1145
+ return new Set(
1146
+ Object.values(manifest).flatMap((declaration) =>
1147
+ declaration.kind === 'inbox' ? [declaration.topic] : [],
1148
+ ),
1149
+ );
1150
+ }
1151
+
1152
+ /**
1153
+ * Each inbox's topic, as the provider made it — the ARN the inbox read from
1154
+ * the deploy — under the topic's own id, so its declaration's contract is
1155
+ * checked like any other.
1156
+ */
1157
+ export function referenceInboxTopics(
1158
+ manifest: ConstructManifest,
1159
+ provisioned: ProvisionedManifest,
1160
+ ): void {
1161
+ for (const declaration of Object.values(manifest)) {
1162
+ if (declaration.kind !== 'inbox') continue;
1163
+ const inbox = provisioned[declaration.id];
1164
+ if (!(inbox instanceof Inbox)) continue;
1165
+
1166
+ const topic = new InboxTopic(declaration.topic, inbox);
1167
+ const topicDeclaration = manifest[declaration.topic];
1168
+ assertProvides(
1169
+ declaration.topic,
1170
+ topicDeclaration?.provides,
1171
+ Object.keys(topic.provides()).map((role) =>
1172
+ providedKeyFor(declaration.topic, 'topic', role),
1173
+ ),
1174
+ );
1175
+ provisioned[declaration.topic] = topic as unknown as Provisioned;
1176
+ }
1177
+ }
1178
+
1179
+ /**
1180
+ * Subscribe each inbox subscriber's Lambda to its inbox's topic — the
1181
+ * provider's, by ARN — linked to what it depends on, its inbox included.
1182
+ *
1183
+ * Unfiltered: SES publishes its receipt notification with no `type` attribute
1184
+ * to filter on, and every message on an inbox's topic is for its subscribers.
1185
+ * The subscriber's adaptor reads the notification as `email.received`.
1186
+ */
1187
+ export function subscribeInboxes(
1188
+ manifest: ConstructManifest,
1189
+ provisioned: ProvisionedManifest,
1190
+ ): void {
1191
+ for (const declaration of Object.values(manifest)) {
1192
+ if (declaration.kind !== 'inbox') continue;
1193
+ const inbox = provisioned[declaration.id];
1194
+ const topic = manifest[declaration.topic];
1195
+ if (!(inbox instanceof Inbox) || topic?.kind !== 'topic') continue;
1196
+
1197
+ for (const subscriber of topic.subscribers) {
1198
+ const { link } = resolveEdges(subscriber.dependencies, provisioned);
1199
+ const vpc = vpcFor(link);
1200
+ sst.aws.SnsTopic.subscribe(
1201
+ `${subscriber.id}Subscription`,
1202
+ inbox.topicArn,
1203
+ {
1204
+ handler: subscriber.handler,
1205
+ link,
1206
+ ...(vpc ? { vpc } : {}),
1207
+ },
1208
+ );
1209
+ }
1210
+ }
1211
+ }
1212
+
725
1213
  /** The provisioner for a kind. Pure — the lookup is testable without Pulumi. */
726
1214
  export function provisionerFor(kind: DeclarationKind): Provisioner {
727
1215
  const provisioner = PROVISIONERS[kind];
@@ -760,21 +1248,36 @@ export function assertProvides(
760
1248
  * tenant, a read replica, and the surface over a bucket all resolve an address
761
1249
  * off something else, and a pass in map order would find it half the time.
762
1250
  */
763
- export function fromManifest(
1251
+ export function fromManifest<
1252
+ const M extends ConstructManifest,
1253
+ const B extends ManifestBackends = {},
1254
+ >(
764
1255
  stack: StackType,
765
- manifest: ConstructManifest,
766
- overrides: ComponentOverrides = {},
1256
+ manifest: M,
1257
+ /**
1258
+ * Provider-specific props, per construct id — typed from the manifest, so
1259
+ * only its ids are keys, each takes what its kind's component reads, and
1260
+ * what the synth cannot guess (a database's `vpc`, mail's `from`) is
1261
+ * required. See {@link ManifestOverrides}.
1262
+ *
1263
+ * Neutral options — `versioned`, `fifo` — travel in the declaration,
1264
+ * because the app legitimately has an opinion about them. Anything with S3
1265
+ * in its name does not belong in application code, so it is supplied here.
1266
+ * A third escape hatch needs no API: the components are returned, so
1267
+ * `provisioned.Uploads.nodes.bucket` is reachable for anything else.
1268
+ */
1269
+ overrides: ManifestOverrides<M, B>,
767
1270
  /**
768
1271
  * The backend choices that are config rather than declaration.
769
1272
  *
770
1273
  * Defaulted the same way the local target defaults them, so a stage deployed
771
- * without saying gets the same backend a developer ran against.
1274
+ * without saying gets the same backend a developer ran against. Typed
1275
+ * literally, because the backend decides what is required above: an
1276
+ * ElastiCache cache needs a `vpc`, Resend or SMTP mail a `url`.
772
1277
  */
773
- backends: {
774
- cache?: 'upstash' | 'elasticache' | 'db';
775
- email?: 'resend' | 'ses' | 'smtp';
776
- } = {},
1278
+ backends: B = {} as B,
777
1279
  ): ProvisionedManifest {
1280
+ assertNoHostLabels(manifest);
778
1281
  const provisioned: ProvisionedManifest = {};
779
1282
 
780
1283
  // In provisioning order, so a derived node finds the component its parent
@@ -795,7 +1298,12 @@ export function fromManifest(
795
1298
  // the things that call it exist.
796
1299
  const callers = new Map<string, Deferred>();
797
1300
  for (const [id, declaration] of Object.entries(manifest)) {
798
- if (declaration.kind === 'rest-api') callers.set(id, defer());
1301
+ if (
1302
+ declaration.kind === 'rest-api' ||
1303
+ declaration.kind === 'websocket-api'
1304
+ ) {
1305
+ callers.set(id, defer());
1306
+ }
799
1307
  }
800
1308
 
801
1309
  const context: ProvisionContext = {
@@ -805,16 +1313,24 @@ export function fromManifest(
805
1313
  bootstraps: new Map<string, DatabaseBootstrap>(),
806
1314
  ...(backends.cache ? { cache: backends.cache } : {}),
807
1315
  ...(backends.email ? { email: backends.email } : {}),
1316
+ ...(backends.protectedSubdomains
1317
+ ? { protectedSubdomains: backends.protectedSubdomains }
1318
+ : {}),
808
1319
  };
809
1320
 
1321
+ const inboxTopics = inboxTopicIds(manifest);
1322
+
810
1323
  for (const id of [...rest, ...sites]) {
811
1324
  const declaration = manifest[id];
812
1325
  if (!declaration) continue;
1326
+ if (PROVISIONED_ELSEWHERE.has(declaration.kind)) continue;
1327
+ // Its provider made it: referenced once its inbox is, below.
1328
+ if (inboxTopics.has(id)) continue;
813
1329
 
814
1330
  const component = provisionerFor(declaration.kind)(
815
1331
  stack,
816
1332
  declaration,
817
- overrides[id] ?? {},
1333
+ (overrides as Record<string, Record<string, unknown>>)[id] ?? {},
818
1334
  context,
819
1335
  );
820
1336
 
@@ -833,6 +1349,17 @@ export function fromManifest(
833
1349
  provisioned[id] = component;
834
1350
  }
835
1351
 
1352
+ referenceInboxTopics(manifest, provisioned);
1353
+
1354
+ // The functions and crons, each queue's one consumer and each surface's
1355
+ // endpoints, once everything they link to exists.
1356
+ provisionCompute(stack, manifest, provisioned);
1357
+ subscribeInboxes(manifest, provisioned);
1358
+ provisionProcessors(stack, manifest, provisioned);
1359
+ subscribeConsumers(manifest, provisioned);
1360
+ mountRoutes(manifest, provisioned);
1361
+ mountWebSocketRoutes(manifest, provisioned);
1362
+
836
1363
  for (const line of describeRoutes(manifest)) console.log(line);
837
1364
 
838
1365
  // Now everything exists, so every surface's callers can be resolved — the
@@ -840,7 +1367,9 @@ export function fromManifest(
840
1367
  for (const [id, deferred] of callers) {
841
1368
  // Resolved with the promise itself: the addresses it needs are Pulumi
842
1369
  // outputs, so the answer arrives when they do.
843
- deferred.resolve(callersOf(id, manifest, provisioned));
1370
+ deferred.resolve(
1371
+ callersOf(id, manifest, provisioned, $app.name, stack.domain),
1372
+ );
844
1373
  }
845
1374
 
846
1375
  // Last, and only now: the roles exist as passwords and secrets from the
@@ -855,6 +1384,30 @@ export function fromManifest(
855
1384
  return provisioned;
856
1385
  }
857
1386
 
1387
+ /**
1388
+ * A secret in its declared format — the alphabet `drawSecret` draws from on
1389
+ * every other stage, with one symbol guaranteed as it guarantees one.
1390
+ *
1391
+ * The format is fixed at the first deploy, as a server stage's is: changing it
1392
+ * would replace the password, and every later deploy is meant to read back the
1393
+ * one it had.
1394
+ */
1395
+ function generatedSecret(id: string, format: SecretFormat) {
1396
+ const symbols = [...new Set(format.symbols ?? SECRET_SYMBOLS)].join('');
1397
+
1398
+ return new RandomPassword(
1399
+ `${id}Generated`,
1400
+ {
1401
+ length: format.length ?? SECRET_LENGTH,
1402
+ special: symbols.length > 0,
1403
+ ...(symbols ? { overrideSpecial: symbols, minSpecial: 1 } : {}),
1404
+ },
1405
+ {
1406
+ ignoreChanges: ['length', 'special', 'overrideSpecial', 'minSpecial'],
1407
+ },
1408
+ ).result;
1409
+ }
1410
+
858
1411
  /** What one function receives from its edges. */
859
1412
  export interface ResolvedEdges {
860
1413
  /** The components it may reach. SST turns these into IAM *and* injects their