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

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
@@ -4,20 +4,10 @@ import type { StackType } from '../Stack';
4
4
  /**
5
5
  * `RestApiSurface` — an HTTP API, and the infra half of the `rest-api` kind.
6
6
  *
7
- * Deliberately *not* `Api`, which takes a route table and validates each
8
- * route's environment at synth. That component is the endpoint pipeline's, and
9
- * it needs routes; this one is the manifest's, and the manifest's `rest-api`
10
- * node currently carries `endpoints: []` for an application's own API.
11
- *
12
- * So what this provisions is the surface and nothing on it. An API Gateway with
13
- * no routes 404s everything, which is the honest state of things — and it is
14
- * still worth provisioning, because the *address* is what everything downstream
15
- * needs: a site inlines it as `VITE_API_URL`, an auth server puts it on its
16
- * trusted-origin list, and the cookie domain derives from it. Those are blocked
17
- * on the API existing, not on it answering.
18
- *
19
- * The two collapse into one component when the endpoint merge lands and the
20
- * surface node carries its routes.
7
+ * Provisioned before its routes, because its *address* is what everything
8
+ * downstream needs: a site inlines it as `VITE_API_URL`, an auth server puts it
9
+ * on its trusted-origin list, and the cookie domain derives from it. The routes
10
+ * are mounted once everything they link to exists — see {@link mount}.
21
11
  */
22
12
 
23
13
  export interface RestApiSurfaceProps extends sst.aws.ApiGatewayV2Args {
@@ -82,6 +72,25 @@ export class RestApiSurface<
82
72
  };
83
73
  }
84
74
 
75
+ /**
76
+ * Mount one endpoint: a Lambda running the handler the build wrote for it,
77
+ * linked to exactly what that endpoint depends on.
78
+ */
79
+ mount(endpoint: SurfaceRoute) {
80
+ return this.route(
81
+ `${endpoint.method} ${endpoint.path}`,
82
+ {
83
+ handler: endpoint.handler,
84
+ link: endpoint.link ?? [],
85
+ runtime: 'nodejs24.x',
86
+ ...(endpoint.vpc ? { vpc: endpoint.vpc } : {}),
87
+ },
88
+ // `iam` is the one authorizer the gateway enforces itself; every other
89
+ // is the endpoint's own, checked in the handler.
90
+ endpoint.authorizer === 'iam' ? { auth: { iam: true } } : {},
91
+ );
92
+ }
93
+
85
94
  override getSSTLink() {
86
95
  const link = super.getSSTLink();
87
96
  return {
@@ -90,3 +99,16 @@ export class RestApiSurface<
90
99
  };
91
100
  }
92
101
  }
102
+
103
+ /** One endpoint, as {@link RestApiSurface.mount} mounts it. */
104
+ export interface SurfaceRoute {
105
+ method: string;
106
+ path: string;
107
+ /** The built handler — `apps/api/.gkm/aws/routes/getUser.handler`. */
108
+ handler: string;
109
+ /** What the endpoint depends on, and nothing else. */
110
+ link?: unknown[];
111
+ /** The database's network, when the endpoint reaches one. */
112
+ vpc?: sst.aws.Vpc;
113
+ authorizer?: string;
114
+ }
@@ -15,8 +15,10 @@ import type { StackType } from '../Stack';
15
15
  * signing key, the thing that stores it, and the thing that reads it are three
16
16
  * different systems deployed, and one derived string locally.
17
17
  *
18
- * Usable on its own. `Stack.fromManifest` translates a manifest into these, but
19
- * the component takes an ordinary placeholder so it works in a hand-written
18
+ * Usable on its own. `Stack.fromManifest` translates a manifest into these, and
19
+ * hands each a generated placeholder, so a manifest's secret is generated on
20
+ * its first deploy rather than set by hand; the component on its own takes
21
+ * whatever placeholder it is given, so it works in a hand-written
20
22
  * `sst.config.ts` with no manifest anywhere.
21
23
  */
22
24
  export class Secret<
@@ -44,7 +46,7 @@ export class Secret<
44
46
  /**
45
47
  * The one value this secret resolves onto anything that depends on it.
46
48
  *
47
- * `value` is the role, so `provideKey` turns it into the key the app
49
+ * `value` is the role, so `providedKeyFor` turns it into the key the app
48
50
  * declared. Note that a secret's key is its *name* rather than
49
51
  * `<NAME>_VALUE` — `Auth` signs with `AUTH_SECRET`, which is also what
50
52
  * better-auth's own tooling looks for — so the manifest declares that key
@@ -72,5 +74,5 @@ export interface SecretProps {
72
74
  * letting the deploy fail — is the correct handling for a real secret. It
73
75
  * exists for the values that are secrets by habit rather than by need.
74
76
  */
75
- placeholder?: string;
77
+ placeholder?: $util.Input<string>;
76
78
  }
@@ -1,3 +1,4 @@
1
+ import { WildcardSiteNeedsDomain } from '../errors';
1
2
  import { type GkmLinkable, ResourceType } from '../Linkable';
2
3
  import type { StackType } from '../Stack';
3
4
 
@@ -14,6 +15,14 @@ import type { StackType } from '../Stack';
14
15
  * which provided values may be shipped to a browser, and renamed by the
15
16
  * variant's prefix. That derivation is shared with the local target, so a site
16
17
  * built by `gkm dev` and the same site built by a deploy inline the same names.
18
+ *
19
+ * A site on every subdomain (`tenants`) is the same distribution under one
20
+ * `*.<domain>` alternate domain name: a wildcard certificate in us-east-1,
21
+ * validated through the stack's hosted zone at deploy time, and one
22
+ * `*.<domain>` alias record. Nothing is created per tenant — a tenant exists
23
+ * because the app says so, and its `hosts` route is what answers an unknown
24
+ * one. Every named host keeps its own record, which Route 53 prefers over the
25
+ * wildcard, so `api.<domain>` is never the tenants' site.
17
26
  */
18
27
  export class StaticSite<
19
28
  TStage extends string = string,
@@ -23,6 +32,7 @@ export class StaticSite<
23
32
  implements GkmLinkable
24
33
  {
25
34
  readonly _id!: string;
35
+ private readonly tenants?: { domain: string; protectedSubdomains: string };
26
36
 
27
37
  get _type() {
28
38
  return ResourceType.StaticSite;
@@ -33,7 +43,8 @@ export class StaticSite<
33
43
  name: string,
34
44
  props: StaticSiteProps = {},
35
45
  ) {
36
- const { variant = 'static', ...args } = props;
46
+ const { variant = 'static', tenants, ...args } = props;
47
+ if (tenants && !_stack.domain) throw new WildcardSiteNeedsDomain(name);
37
48
 
38
49
  super(name, {
39
50
  // The variant's build, unless the caller supplied one. A site is
@@ -42,9 +53,30 @@ export class StaticSite<
42
53
  // exactly what the variant knows and the declaration deliberately does
43
54
  // not.
44
55
  build: BUILDS[variant],
56
+ // Every tenant's host on one distribution. SST requests the `*.`
57
+ // certificate and validates it through the zone, then writes the
58
+ // alias; a zone left unresolved is looked up by the domain's name.
59
+ ...(tenants
60
+ ? {
61
+ domain: {
62
+ name: `*.${_stack.domain}`,
63
+ dns: sst.aws.dns(
64
+ _stack.app.hostedZoneId
65
+ ? { zone: _stack.app.hostedZoneId }
66
+ : {},
67
+ ),
68
+ },
69
+ }
70
+ : {}),
45
71
  ...args,
46
72
  });
47
73
  this._id = name;
74
+ if (tenants) {
75
+ this.tenants = {
76
+ domain: _stack.domain,
77
+ protectedSubdomains: tenants.protectedSubdomains.join(','),
78
+ };
79
+ }
48
80
  }
49
81
 
50
82
  /**
@@ -56,6 +88,11 @@ export class StaticSite<
56
88
  * site was meant to remove.
57
89
  */
58
90
  provides(): Record<string, $util.Input<string>> {
91
+ // A tenants' site is at `https://*.<domain>`, the address every target
92
+ // gives it: what the surfaces it calls trust, one label in for the `*`.
93
+ if (this.tenants) {
94
+ return { url: `https://*.${this.tenants.domain}`, ...this.tenants };
95
+ }
59
96
  return { url: this.url };
60
97
  }
61
98
 
@@ -71,6 +108,12 @@ export class StaticSite<
71
108
  export interface StaticSiteProps extends sst.aws.StaticSiteArgs {
72
109
  /** Which framework builds it, for the default build command. */
73
110
  variant?: 'static' | 'next' | 'tanstack';
111
+ /**
112
+ * Serve it on every subdomain of the stack's domain — a site declared
113
+ * `subdomain: '*'`. `protectedSubdomains` are the labels no tenant may
114
+ * take, provided to the site so it refuses them as slugs.
115
+ */
116
+ tenants?: { protectedSubdomains: readonly string[] };
74
117
  }
75
118
 
76
119
  /**
@@ -0,0 +1,160 @@
1
+ import { apiGatewayWebSocketUrl } from '@geekmidas/manifest';
2
+ import { type GkmLinkable, ResourceType } from '../Linkable';
3
+ import type { StackType } from '../Stack';
4
+
5
+ /**
6
+ * `WebSocketApiSurface` — an API Gateway WebSocket API, and the infra half of
7
+ * the `websocket-api` kind on AWS.
8
+ *
9
+ * The same surface a compose stage runs as a Node process: there the process
10
+ * holds the sockets and Redis carries a send to whichever replica holds one;
11
+ * here API Gateway holds them, and each route is a Lambda the build wrote
12
+ * (`AmazonApiGatewayWebSocket`). What the gateway does not keep — a
13
+ * connection's `data`, and the list a broadcast fans out to — goes in a
14
+ * DynamoDB table this component makes beside the API, so a surface declares
15
+ * nothing more to deploy here.
16
+ *
17
+ * Linked, it hands a function its `<ID>_URL` (`wss://`), its
18
+ * `<ID>_TRUSTED_ORIGINS`, and an `apigateway://` publisher string naming the
19
+ * management endpoint and the table — with `execute-api:ManageConnections`
20
+ * and the table's access, so `services.<surface>` works from any Lambda that
21
+ * declared the edge, and from the surface's own routes.
22
+ */
23
+
24
+ export interface WebSocketApiSurfaceProps
25
+ extends sst.aws.ApiGatewayWebSocketArgs {
26
+ /** Who may open it, resolved once everything is provisioned. */
27
+ callers?: Promise<{ trustedOrigins: string; cookieDomain?: string }>;
28
+ /**
29
+ * The key a frame names its action under — the surface's
30
+ * `frame.discriminator`. Absent, `action`.
31
+ */
32
+ discriminator?: string;
33
+ }
34
+
35
+ export class WebSocketApiSurface<
36
+ TStage extends string = string,
37
+ TDomain extends string = string,
38
+ >
39
+ extends sst.aws.ApiGatewayWebSocket
40
+ implements GkmLinkable
41
+ {
42
+ readonly _id!: string;
43
+
44
+ /** Where its open connections are kept. */
45
+ readonly connections: sst.aws.Dynamo;
46
+
47
+ get _type() {
48
+ return ResourceType.WebSocketApi;
49
+ }
50
+
51
+ private readonly callers: Promise<{ trustedOrigins: string }>;
52
+
53
+ constructor(
54
+ _stack: StackType<TStage, TDomain>,
55
+ name: string,
56
+ props: WebSocketApiSurfaceProps = {},
57
+ ) {
58
+ const { callers, discriminator, ...args } = props;
59
+ const own = args.transform?.api;
60
+ // API Gateway routes on the key the surface's frames name their action
61
+ // under — the route a frame reaches is the one `message()` would
62
+ // dispatch it to. The caller's own transform still runs after it.
63
+ const api = ((
64
+ apiArgs: { routeSelectionExpression?: unknown },
65
+ ...rest: unknown[]
66
+ ) => {
67
+ apiArgs.routeSelectionExpression =
68
+ routeSelectionExpression(discriminator);
69
+ if (typeof own === 'function') {
70
+ (own as (...a: unknown[]) => void)(apiArgs, ...rest);
71
+ } else if (own) {
72
+ Object.assign(apiArgs, own);
73
+ }
74
+ }) as NonNullable<
75
+ NonNullable<sst.aws.ApiGatewayWebSocketArgs['transform']>['api']
76
+ >;
77
+
78
+ super(name, { ...args, transform: { ...args.transform, api } });
79
+ this._id = name;
80
+ this.callers = callers ?? Promise.resolve({ trustedOrigins: '' });
81
+ this.connections = new sst.aws.Dynamo(`${name}Connections`, {
82
+ fields: { connectionId: 'string' },
83
+ primaryIndex: { hashKey: 'connectionId' },
84
+ // API Gateway closes a connection after two hours; a row whose
85
+ // `$disconnect` never ran expires after that.
86
+ ttl: 'expiresAt',
87
+ });
88
+ }
89
+
90
+ provides(): Record<string, $util.Input<string>> {
91
+ return {
92
+ url: this.url,
93
+ // Deferred for the reason a REST surface's are: a caller's address
94
+ // is known only once it is provisioned. See `RestApiSurface`.
95
+ trustedOrigins: $util.output(this.callers.then((c) => c.trustedOrigins)),
96
+ publisherConnectionString: $util
97
+ .all([this.managementEndpoint, this.connections.name])
98
+ .apply(([endpoint, table]) =>
99
+ apiGatewayWebSocketUrl({
100
+ region:
101
+ regionOfEndpoint(endpoint as string) ??
102
+ $app.providers?.aws?.region ??
103
+ 'us-east-1',
104
+ endpoint: endpoint as string,
105
+ table: table as string,
106
+ }),
107
+ ),
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Mount one route: a Lambda running the handler the build wrote for it,
113
+ * linked to what that route depends on and to the surface itself — its
114
+ * table and its management API, which every route reaches.
115
+ */
116
+ mount(route: WebSocketSurfaceRoute) {
117
+ return this.route(route.action, {
118
+ handler: route.handler,
119
+ link: [this, ...(route.link ?? []).filter((link) => link !== this)],
120
+ runtime: 'nodejs24.x',
121
+ ...(route.vpc ? { vpc: route.vpc } : {}),
122
+ });
123
+ }
124
+
125
+ override getSSTLink() {
126
+ const own = super.getSSTLink();
127
+ const table = this.connections.getSSTLink();
128
+ return {
129
+ ...own,
130
+ properties: { ...own.properties, ...this.provides() },
131
+ include: [...(own.include ?? []), ...(table.include ?? [])],
132
+ };
133
+ }
134
+ }
135
+
136
+ /** One route, as {@link WebSocketApiSurface.mount} mounts it. */
137
+ export interface WebSocketSurfaceRoute {
138
+ /** The route key: an action, `$connect`, `$disconnect` or `$default`. */
139
+ action: string;
140
+ /** The built handler — `apps/realtime/.gkm/aws/websocket/connect.handler`. */
141
+ handler: string;
142
+ /** What the route depends on; the surface itself is added. */
143
+ link?: unknown[];
144
+ /** The database's network, when the route reaches one. */
145
+ vpc?: sst.aws.Vpc;
146
+ }
147
+
148
+ /** `$request.body.<key>`, the key a surface's frames name their action under. */
149
+ export function routeSelectionExpression(discriminator?: string): string {
150
+ return `$request.body.${discriminator ?? 'action'}`;
151
+ }
152
+
153
+ /** The region in a management endpoint's host: `<api>.execute-api.<region>.…`. */
154
+ export function regionOfEndpoint(endpoint: string): string | undefined {
155
+ try {
156
+ return /\.execute-api\.([a-z0-9-]+)\./.exec(new URL(endpoint).host)?.[1];
157
+ } catch {
158
+ return undefined;
159
+ }
160
+ }
@@ -28,6 +28,13 @@ export interface BootstrapTenant {
28
28
  runtime: string;
29
29
  owner: string;
30
30
  reader?: string;
31
+ /**
32
+ * The database's own roles rather than a tenant's: its owner may create in
33
+ * the database, for trusted extensions.
34
+ */
35
+ ownsDatabase?: boolean;
36
+ /** Extensions the database declared, created as the master. */
37
+ extensions?: readonly string[];
31
38
  passwords: { runtime: string; owner: string; reader?: string };
32
39
  }
33
40
 
@@ -75,7 +82,11 @@ export async function handler(event: BootstrapEvent): Promise<BootstrapResult> {
75
82
 
76
83
  try {
77
84
  for (const tenant of event.tenants) {
78
- for (const statement of roleStatements(tenant)) {
85
+ const spec = {
86
+ ...tenant,
87
+ ...(tenant.ownsDatabase ? { database: event.master.database } : {}),
88
+ };
89
+ for (const statement of roleStatements(spec)) {
79
90
  if (statement.exists) {
80
91
  const { rows } = await client.query(
81
92
  statement.exists.sql,
package/src/sst/errors.ts CHANGED
@@ -63,3 +63,40 @@ export class UnresolvedDependency extends Error {
63
63
  this.available = available;
64
64
  }
65
65
  }
66
+
67
+ /**
68
+ * A site declared `subdomain: '*'` on a stack with no domain: its tenants'
69
+ * hosts are `<slug>.<domain>`, and without the domain there is nothing for
70
+ * the `*` to stand in front of.
71
+ */
72
+ export class WildcardSiteNeedsDomain extends Error {
73
+ constructor(readonly id: string) {
74
+ super(
75
+ `'${id}' answers on every subdomain, so its stack needs a domain: ` +
76
+ `pass the stage's domain (and its Route 53 hosted zone) to \`new App({ domain, hostedZoneId })\` in sst.config.ts.`,
77
+ );
78
+ this.name = 'WildcardSiteNeedsDomain';
79
+ }
80
+ }
81
+
82
+ /**
83
+ * A surface or site with `aliases` or `redirects` on an AWS stage. Only a
84
+ * wildcard site is given a custom domain there; every other surface answers
85
+ * on the address AWS assigns it, so there is no domain to put the extra
86
+ * labels under — and dropping them silently would deploy a host that never
87
+ * answers.
88
+ */
89
+ export class HostLabelNeedsCustomDomain extends Error {
90
+ constructor(
91
+ readonly id: string,
92
+ readonly labels: readonly string[],
93
+ ) {
94
+ super(
95
+ `'${id}' answers on ${labels.map((label) => `'${label}'`).join(', ')} ` +
96
+ `besides its own host, but on AWS it has no custom domain to put ` +
97
+ `them under. Deploy this stage with gkm compose, or drop its ` +
98
+ `\`aliases\` and \`redirects\` for it.`,
99
+ );
100
+ this.name = 'HostLabelNeedsCustomDomain';
101
+ }
102
+ }