@ericminassian/platform-engine 0.3.0 → 0.4.1

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 (98) hide show
  1. package/dist/clients.d.ts +8 -0
  2. package/dist/clients.js +22 -1
  3. package/dist/clients.js.map +1 -1
  4. package/dist/compat.d.ts +21 -9
  5. package/dist/compat.js +27 -7
  6. package/dist/compat.js.map +1 -1
  7. package/dist/drivers/appsync.d.ts +49 -0
  8. package/dist/drivers/appsync.js +155 -0
  9. package/dist/drivers/appsync.js.map +1 -0
  10. package/dist/drivers/cognito.d.ts +9 -3
  11. package/dist/drivers/cognito.js +18 -7
  12. package/dist/drivers/cognito.js.map +1 -1
  13. package/dist/drivers/ecr.d.ts +109 -0
  14. package/dist/drivers/ecr.js +303 -0
  15. package/dist/drivers/ecr.js.map +1 -0
  16. package/dist/drivers/ecs.d.ts +163 -0
  17. package/dist/drivers/ecs.js +447 -0
  18. package/dist/drivers/ecs.js.map +1 -0
  19. package/dist/drivers/events.d.ts +10 -0
  20. package/dist/drivers/events.js +13 -1
  21. package/dist/drivers/events.js.map +1 -1
  22. package/dist/drivers/index.d.ts +5 -0
  23. package/dist/drivers/index.js +5 -0
  24. package/dist/drivers/index.js.map +1 -1
  25. package/dist/drivers/kvs.d.ts +3 -0
  26. package/dist/drivers/kvs.js +14 -7
  27. package/dist/drivers/kvs.js.map +1 -1
  28. package/dist/drivers/lambda.d.ts +22 -0
  29. package/dist/drivers/lambda.js +74 -3
  30. package/dist/drivers/lambda.js.map +1 -1
  31. package/dist/drivers/request-function.d.ts +60 -0
  32. package/dist/drivers/request-function.js +167 -0
  33. package/dist/drivers/request-function.js.map +1 -0
  34. package/dist/drivers/s3.d.ts +5 -0
  35. package/dist/drivers/s3.js +26 -0
  36. package/dist/drivers/s3.js.map +1 -1
  37. package/dist/drivers/scheduler.d.ts +24 -0
  38. package/dist/drivers/scheduler.js +60 -5
  39. package/dist/drivers/scheduler.js.map +1 -1
  40. package/dist/drivers/ses.d.ts +77 -0
  41. package/dist/drivers/ses.js +181 -0
  42. package/dist/drivers/ses.js.map +1 -0
  43. package/dist/drivers/sqs.d.ts +11 -0
  44. package/dist/drivers/sqs.js +67 -1
  45. package/dist/drivers/sqs.js.map +1 -1
  46. package/dist/drivers/web-function.d.ts +11 -3
  47. package/dist/drivers/web-function.js +22 -5
  48. package/dist/drivers/web-function.js.map +1 -1
  49. package/dist/emulator.js.map +1 -1
  50. package/dist/images.d.ts +104 -0
  51. package/dist/images.js +182 -0
  52. package/dist/images.js.map +1 -0
  53. package/dist/index.d.ts +130 -6
  54. package/dist/index.js +11 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/local.js +222 -7
  57. package/dist/local.js.map +1 -1
  58. package/dist/policy.d.ts +47 -4
  59. package/dist/policy.js +365 -13
  60. package/dist/policy.js.map +1 -1
  61. package/dist/services.d.ts +155 -0
  62. package/dist/services.js +464 -0
  63. package/dist/services.js.map +1 -0
  64. package/dist/stage.d.ts +33 -8
  65. package/dist/stage.js +598 -125
  66. package/dist/stage.js.map +1 -1
  67. package/dist/static.d.ts +1 -1
  68. package/dist/static.js +2 -36
  69. package/dist/static.js.map +1 -1
  70. package/dist/util.d.ts +22 -0
  71. package/dist/util.js +18 -2
  72. package/dist/util.js.map +1 -1
  73. package/package.json +20 -14
  74. package/src/clients.ts +25 -1
  75. package/src/compat.ts +34 -11
  76. package/src/drivers/appsync.ts +220 -0
  77. package/src/drivers/cognito.ts +19 -9
  78. package/src/drivers/ecr.ts +457 -0
  79. package/src/drivers/ecs.ts +661 -0
  80. package/src/drivers/events.ts +29 -2
  81. package/src/drivers/index.ts +5 -0
  82. package/src/drivers/kvs.ts +21 -12
  83. package/src/drivers/lambda.ts +103 -2
  84. package/src/drivers/request-function.ts +295 -0
  85. package/src/drivers/s3.ts +38 -0
  86. package/src/drivers/scheduler.ts +88 -5
  87. package/src/drivers/ses.ts +267 -0
  88. package/src/drivers/sqs.ts +95 -0
  89. package/src/drivers/web-function.ts +29 -9
  90. package/src/emulator.ts +3 -3
  91. package/src/images.ts +254 -0
  92. package/src/index.ts +129 -7
  93. package/src/local.ts +251 -7
  94. package/src/policy.ts +446 -24
  95. package/src/services.ts +663 -0
  96. package/src/stage.ts +753 -140
  97. package/src/static.ts +2 -37
  98. package/src/util.ts +38 -4
@@ -0,0 +1,220 @@
1
+ import {
2
+ type Api,
3
+ type ApiKey,
4
+ type AuthMode,
5
+ type ChannelNamespace,
6
+ CreateApiKeyCommand,
7
+ CreateChannelNamespaceCommand,
8
+ DeleteChannelNamespaceCommand,
9
+ GetChannelNamespaceCommand,
10
+ ListApiKeysCommand,
11
+ ListApisCommand,
12
+ UpdateApiKeyCommand,
13
+ UpdateChannelNamespaceCommand,
14
+ } from '@aws-sdk/client-appsync';
15
+ import {
16
+ type PlatformRuntimeConfig,
17
+ platformNames,
18
+ REALTIME_KVS_KEY,
19
+ type RealtimeEdgeEntry,
20
+ type RealtimeSubscribe,
21
+ } from '@ericminassian/platform-core';
22
+ import { type EngineContext, errorName, ignoreNotFound } from '../util.ts';
23
+ import { getKey, putKey } from './kvs.ts';
24
+
25
+ /**
26
+ * AppSync Events: each stage with `realtime` gets a channel namespace in the
27
+ * platform's one Event API (the foundation stack creates the API; the
28
+ * emulator's is created by `ensureLocal`). Namespaces are named, not tagged
29
+ * state, like everything else the engine owns.
30
+ */
31
+
32
+ /**
33
+ * How a namespace authorizes. Browsers never publish: only the stage role
34
+ * (IAM, `appsync:EventPublish` on this namespace) can. Public stages
35
+ * subscribe with the platform's API key; signed-in stages with a token the
36
+ * platform's Lambda authorizer checks.
37
+ */
38
+ export function namespaceAuthModes(subscribe: RealtimeSubscribe): {
39
+ publishAuthModes: AuthMode[];
40
+ subscribeAuthModes: AuthMode[];
41
+ } {
42
+ return {
43
+ publishAuthModes: [{ authType: 'AWS_IAM' }],
44
+ subscribeAuthModes: [{ authType: subscribe === 'public' ? 'API_KEY' : 'AWS_LAMBDA' }],
45
+ };
46
+ }
47
+
48
+ const QUOTA_NAME = 'Event APIs - Channel namespaces per API';
49
+
50
+ /** The Event API with this name (the platform's is `platformNames.realtimeApi`), if it exists. */
51
+ export async function findEventApi(ctx: EngineContext, name: string): Promise<Api | undefined> {
52
+ let nextToken: string | undefined;
53
+ do {
54
+ const res = await ctx.clients.appsync.send(new ListApisCommand(nextToken ? { nextToken } : {}));
55
+ const found = (res.apis ?? []).find((a) => a.name === name && a.eventConfig);
56
+ if (found) return found;
57
+ nextToken = res.nextToken;
58
+ } while (nextToken);
59
+ return undefined;
60
+ }
61
+
62
+ export async function getChannelNamespace(
63
+ ctx: EngineContext,
64
+ apiId: string,
65
+ name: string,
66
+ ): Promise<ChannelNamespace | undefined> {
67
+ const res = await ignoreNotFound(ctx.clients.appsync.send(new GetChannelNamespaceCommand({ apiId, name })));
68
+ return res?.channelNamespace;
69
+ }
70
+
71
+ /** Create the stage's namespace, or bring an existing one's auth modes in line. */
72
+ export async function ensureChannelNamespace(
73
+ ctx: EngineContext,
74
+ spec: { apiId: string; name: string; subscribe: RealtimeSubscribe; tags: Record<string, string> },
75
+ ): Promise<{ name: string; arn?: string }> {
76
+ const modes = namespaceAuthModes(spec.subscribe);
77
+ const existing = await getChannelNamespace(ctx, spec.apiId, spec.name);
78
+ if (existing) {
79
+ if (
80
+ !sameModes(existing.subscribeAuthModes, modes.subscribeAuthModes) ||
81
+ !sameModes(existing.publishAuthModes, modes.publishAuthModes)
82
+ ) {
83
+ await ctx.clients.appsync.send(
84
+ new UpdateChannelNamespaceCommand({ apiId: spec.apiId, name: spec.name, ...modes }),
85
+ );
86
+ ctx.log('info', `subscribers now ${spec.subscribe}`, `channel-namespace ${spec.name}`);
87
+ }
88
+ return {
89
+ name: spec.name,
90
+ ...(existing.channelNamespaceArn ? { arn: existing.channelNamespaceArn } : {}),
91
+ };
92
+ }
93
+ try {
94
+ const res = await ctx.clients.appsync.send(
95
+ new CreateChannelNamespaceCommand({ apiId: spec.apiId, name: spec.name, ...modes, tags: spec.tags }),
96
+ );
97
+ ctx.log('info', 'created channel namespace', `channel-namespace ${spec.name}`);
98
+ const arn = res.channelNamespace?.channelNamespaceArn;
99
+ return { name: spec.name, ...(arn ? { arn } : {}) };
100
+ } catch (e) {
101
+ if (errorName(e) === 'ServiceQuotaExceededException') {
102
+ throw new Error(
103
+ `The platform's realtime API has no room for another channel namespace. Every stage with ` +
104
+ `realtime (preview stages too) has one; destroy unused previews or raise the "${QUOTA_NAME}" ` +
105
+ 'quota (default 50, adjustable) in Service Quotas.',
106
+ { cause: e },
107
+ );
108
+ }
109
+ throw e;
110
+ }
111
+ }
112
+
113
+ export async function deleteChannelNamespace(
114
+ ctx: EngineContext,
115
+ apiId: string,
116
+ name: string,
117
+ ): Promise<boolean> {
118
+ const res = await ignoreNotFound(
119
+ ctx.clients.appsync.send(new DeleteChannelNamespaceCommand({ apiId, name })),
120
+ );
121
+ if (res === undefined) return false;
122
+ ctx.log('info', 'deleted channel namespace', `channel-namespace ${name}`);
123
+ return true;
124
+ }
125
+
126
+ function sameModes(a: AuthMode[] | undefined, b: AuthMode[]): boolean {
127
+ const key = (m: AuthMode[] | undefined) =>
128
+ (m ?? [])
129
+ .map((x) => x.authType ?? '')
130
+ .toSorted((p, q) => (p < q ? -1 : p > q ? 1 : 0))
131
+ .join(',');
132
+ return key(a) === key(b);
133
+ }
134
+
135
+ // ---------------------------------------------------------------- public API key
136
+
137
+ const DAY = 86_400;
138
+ /**
139
+ * AppSync caps a key's life at 365 days from now (rounded down to the hour);
140
+ * a day less keeps clear of that edge. The key is extended, never replaced,
141
+ * so its value (what public browsers subscribe with) stays the same.
142
+ */
143
+ const KEY_LIFETIME = 364 * DAY;
144
+ /** Extend once fewer days than this remain: about monthly with a daily caller. */
145
+ const KEY_RENEW_BELOW = 335 * DAY;
146
+
147
+ /**
148
+ * The API's subscribe-only key for `public` stages, found by its description.
149
+ * Created when missing (or expired); extended when it has under 335 days
150
+ * left. The control plane calls this nightly and on every realtime deploy.
151
+ * Returns the key (its id is the value browsers send).
152
+ */
153
+ export async function ensurePublicApiKey(
154
+ ctx: EngineContext,
155
+ apiId: string,
156
+ nowSeconds = Math.floor(Date.now() / 1000),
157
+ ): Promise<string> {
158
+ const keys: ApiKey[] = [];
159
+ let nextToken: string | undefined;
160
+ do {
161
+ const res = await ctx.clients.appsync.send(
162
+ new ListApiKeysCommand({ apiId, ...(nextToken ? { nextToken } : {}) }),
163
+ );
164
+ keys.push(...(res.apiKeys ?? []));
165
+ nextToken = res.nextToken;
166
+ } while (nextToken);
167
+ const live = keys
168
+ .filter((k) => k.description === platformNames.realtimePublicKey && k.id && (k.expires ?? 0) > nowSeconds)
169
+ .toSorted((a, b) => (b.expires ?? 0) - (a.expires ?? 0))[0];
170
+ if (live?.id) {
171
+ if ((live.expires ?? 0) - nowSeconds < KEY_RENEW_BELOW) {
172
+ await ctx.clients.appsync.send(
173
+ new UpdateApiKeyCommand({ apiId, id: live.id, expires: nowSeconds + KEY_LIFETIME }),
174
+ );
175
+ ctx.log('info', 'extended the public subscribe key', `api-key ${platformNames.realtimePublicKey}`);
176
+ }
177
+ return live.id;
178
+ }
179
+ const created = await ctx.clients.appsync.send(
180
+ new CreateApiKeyCommand({
181
+ apiId,
182
+ description: platformNames.realtimePublicKey,
183
+ expires: nowSeconds + KEY_LIFETIME,
184
+ }),
185
+ );
186
+ const id = created.apiKey?.id;
187
+ if (!id) throw new Error('AppSync created an API key without an id');
188
+ // A new value only reaches browsers through the route-store entry; public
189
+ // stages' open connections keep working, new ones pick up the new key.
190
+ ctx.log('warn', 'created a new public subscribe key', `api-key ${platformNames.realtimePublicKey}`);
191
+ return id;
192
+ }
193
+
194
+ // ---------------------------------------------------------------- platform entry
195
+
196
+ /**
197
+ * Make the platform's realtime usable: the public key exists and is far from
198
+ * expiry, and the router's entry (`REALTIME_KVS_KEY`) names AppSync's domains
199
+ * and that key. Written only when it changed, so the nightly call is a read.
200
+ * Returns the entry (what `plat dev`'s local router serves), or undefined on
201
+ * a platform without realtime. Without a route store (the emulator) nothing
202
+ * is written.
203
+ */
204
+ export async function ensureRealtimePlatform(
205
+ ctx: EngineContext,
206
+ platform: PlatformRuntimeConfig,
207
+ ): Promise<RealtimeEdgeEntry | undefined> {
208
+ const rt = platform.realtime;
209
+ if (!rt) return undefined;
210
+ const key = await ensurePublicApiKey(ctx, rt.apiId);
211
+ const entry: RealtimeEdgeEntry = { v: 1, o: rt.realtimeDomain, h: rt.httpDomain, k: key };
212
+ if (platform.kvsArn) {
213
+ const value = JSON.stringify(entry);
214
+ if ((await getKey(ctx, platform.kvsArn, REALTIME_KVS_KEY)) !== value) {
215
+ await putKey(ctx, platform.kvsArn, REALTIME_KVS_KEY, value);
216
+ ctx.log('info', 'updated the realtime route entry', `route ${REALTIME_KVS_KEY}`);
217
+ }
218
+ }
219
+ return entry;
220
+ }
@@ -53,10 +53,9 @@ export async function ensureUserPool(
53
53
  export interface UserPoolClientSpec {
54
54
  userPoolId: string;
55
55
  name: string;
56
+ /** Where managed login returns after sign-in and sign-out (AWS only). */
56
57
  callbackUrls: string[];
57
58
  logoutUrls: string[];
58
- /** Also allow password flows (the local sign-in page under `plat dev`). */
59
- passwordFlows?: boolean;
60
59
  }
61
60
 
62
61
  export async function findUserPoolClient(
@@ -79,20 +78,31 @@ export async function findUserPoolClient(
79
78
  return undefined;
80
79
  }
81
80
 
82
- /** Public app client (no secret) for the authorization-code + PKCE flow. */
81
+ /**
82
+ * Public app client (no secret). On AWS it signs in through managed login
83
+ * (authorization code + PKCE). The emulator has no managed login, and `plat
84
+ * dev`'s own sign-in page uses password flows instead, so its client has no
85
+ * OAuth settings. It couldn't have them anyway: like Cognito, the emulator
86
+ * (1.0.610 at least) refuses http callback URLs other than localhost's, and a
87
+ * local app is on `http://<app>.localhost`.
88
+ */
83
89
  export async function ensureUserPoolClient(ctx: EngineContext, spec: UserPoolClientSpec): Promise<string> {
84
90
  const cognito = ctx.clients.cognito;
85
91
  const flows: ExplicitAuthFlowsType[] = ['ALLOW_REFRESH_TOKEN_AUTH'];
86
- if (spec.passwordFlows) flows.push('ALLOW_USER_PASSWORD_AUTH', 'ALLOW_ADMIN_USER_PASSWORD_AUTH');
92
+ if (ctx.target !== 'aws') flows.push('ALLOW_USER_PASSWORD_AUTH', 'ALLOW_ADMIN_USER_PASSWORD_AUTH');
87
93
  const config = {
88
94
  UserPoolId: spec.userPoolId,
89
95
  ClientName: spec.name,
90
96
  ExplicitAuthFlows: flows,
91
- AllowedOAuthFlows: ['code' as const],
92
- AllowedOAuthScopes: [...AUTH_SCOPES],
93
- AllowedOAuthFlowsUserPoolClient: true,
94
- CallbackURLs: spec.callbackUrls,
95
- LogoutURLs: spec.logoutUrls,
97
+ ...(ctx.target === 'aws'
98
+ ? {
99
+ AllowedOAuthFlows: ['code' as const],
100
+ AllowedOAuthScopes: [...AUTH_SCOPES],
101
+ AllowedOAuthFlowsUserPoolClient: true,
102
+ CallbackURLs: spec.callbackUrls,
103
+ LogoutURLs: spec.logoutUrls,
104
+ }
105
+ : {}),
96
106
  SupportedIdentityProviders: ['COGNITO'],
97
107
  PreventUserExistenceErrors: 'ENABLED' as const,
98
108
  EnableTokenRevocation: true,