@ericminassian/platform-engine 0.0.0-stage → 0.1.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 (106) hide show
  1. package/dist/clients.d.ts +61 -0
  2. package/dist/clients.js +122 -0
  3. package/dist/clients.js.map +1 -0
  4. package/dist/compat.d.ts +19 -0
  5. package/dist/compat.js +63 -0
  6. package/dist/compat.js.map +1 -0
  7. package/dist/drivers/acm.d.ts +20 -0
  8. package/dist/drivers/acm.js +62 -0
  9. package/dist/drivers/acm.js.map +1 -0
  10. package/dist/drivers/cloudfront.d.ts +52 -0
  11. package/dist/drivers/cloudfront.js +223 -0
  12. package/dist/drivers/cloudfront.js.map +1 -0
  13. package/dist/drivers/cognito.d.ts +27 -0
  14. package/dist/drivers/cognito.js +151 -0
  15. package/dist/drivers/cognito.js.map +1 -0
  16. package/dist/drivers/dynamodb.d.ts +26 -0
  17. package/dist/drivers/dynamodb.js +151 -0
  18. package/dist/drivers/dynamodb.js.map +1 -0
  19. package/dist/drivers/events.d.ts +21 -0
  20. package/dist/drivers/events.js +62 -0
  21. package/dist/drivers/events.js.map +1 -0
  22. package/dist/drivers/iam.d.ts +29 -0
  23. package/dist/drivers/iam.js +137 -0
  24. package/dist/drivers/iam.js.map +1 -0
  25. package/dist/drivers/index.d.ts +16 -0
  26. package/dist/drivers/index.js +17 -0
  27. package/dist/drivers/index.js.map +1 -0
  28. package/dist/drivers/kvs.d.ts +5 -0
  29. package/dist/drivers/kvs.js +28 -0
  30. package/dist/drivers/kvs.js.map +1 -0
  31. package/dist/drivers/lambda.d.ts +48 -0
  32. package/dist/drivers/lambda.js +158 -0
  33. package/dist/drivers/lambda.js.map +1 -0
  34. package/dist/drivers/logs.d.ts +20 -0
  35. package/dist/drivers/logs.js +62 -0
  36. package/dist/drivers/logs.js.map +1 -0
  37. package/dist/drivers/route53.d.ts +30 -0
  38. package/dist/drivers/route53.js +96 -0
  39. package/dist/drivers/route53.js.map +1 -0
  40. package/dist/drivers/s3.d.ts +30 -0
  41. package/dist/drivers/s3.js +126 -0
  42. package/dist/drivers/s3.js.map +1 -0
  43. package/dist/drivers/scheduler.d.ts +21 -0
  44. package/dist/drivers/scheduler.js +59 -0
  45. package/dist/drivers/scheduler.js.map +1 -0
  46. package/dist/drivers/sns.d.ts +7 -0
  47. package/dist/drivers/sns.js +20 -0
  48. package/dist/drivers/sns.js.map +1 -0
  49. package/dist/drivers/sqs.d.ts +18 -0
  50. package/dist/drivers/sqs.js +46 -0
  51. package/dist/drivers/sqs.js.map +1 -0
  52. package/dist/drivers/ssm.d.ts +16 -0
  53. package/dist/drivers/ssm.js +45 -0
  54. package/dist/drivers/ssm.js.map +1 -0
  55. package/dist/drivers/web-function.d.ts +71 -0
  56. package/dist/drivers/web-function.js +227 -0
  57. package/dist/drivers/web-function.js.map +1 -0
  58. package/dist/emulator.d.ts +51 -0
  59. package/dist/emulator.js +142 -0
  60. package/dist/emulator.js.map +1 -0
  61. package/dist/index.d.ts +139 -0
  62. package/dist/index.js +71 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/local.d.ts +12 -0
  65. package/dist/local.js +71 -0
  66. package/dist/local.js.map +1 -0
  67. package/dist/policy.d.ts +47 -0
  68. package/dist/policy.js +332 -0
  69. package/dist/policy.js.map +1 -0
  70. package/dist/stage.d.ts +19 -0
  71. package/dist/stage.js +479 -0
  72. package/dist/stage.js.map +1 -0
  73. package/dist/static.d.ts +9 -0
  74. package/dist/static.js +55 -0
  75. package/dist/static.js.map +1 -0
  76. package/dist/util.d.ts +56 -0
  77. package/dist/util.js +127 -0
  78. package/dist/util.js.map +1 -0
  79. package/package.json +52 -3
  80. package/src/clients.ts +166 -0
  81. package/src/compat.ts +63 -0
  82. package/src/drivers/acm.ts +88 -0
  83. package/src/drivers/cloudfront.ts +291 -0
  84. package/src/drivers/cognito.ts +199 -0
  85. package/src/drivers/dynamodb.ts +206 -0
  86. package/src/drivers/events.ts +92 -0
  87. package/src/drivers/iam.ts +195 -0
  88. package/src/drivers/index.ts +16 -0
  89. package/src/drivers/kvs.ts +55 -0
  90. package/src/drivers/lambda.ts +283 -0
  91. package/src/drivers/logs.ts +81 -0
  92. package/src/drivers/route53.ts +129 -0
  93. package/src/drivers/s3.ts +196 -0
  94. package/src/drivers/scheduler.ts +90 -0
  95. package/src/drivers/sns.ts +33 -0
  96. package/src/drivers/sqs.ts +70 -0
  97. package/src/drivers/ssm.ts +65 -0
  98. package/src/drivers/web-function.ts +352 -0
  99. package/src/emulator.ts +203 -0
  100. package/src/index.ts +182 -0
  101. package/src/local.ts +75 -0
  102. package/src/policy.ts +398 -0
  103. package/src/stage.ts +568 -0
  104. package/src/static.ts +56 -0
  105. package/src/util.ts +175 -0
  106. package/README.md +0 -3
@@ -0,0 +1,291 @@
1
+ import {
2
+ type CachePolicyConfig,
3
+ CreateCachePolicyCommand,
4
+ CreateDistributionWithTagsCommand,
5
+ CreateFunctionCommand,
6
+ CreateKeyValueStoreCommand,
7
+ CreateOriginAccessControlCommand,
8
+ DescribeFunctionCommand,
9
+ DescribeKeyValueStoreCommand,
10
+ type DistributionConfig,
11
+ GetCachePolicyConfigCommand,
12
+ GetDistributionConfigCommand,
13
+ GetFunctionCommand,
14
+ ListCachePoliciesCommand,
15
+ ListDistributionsCommand,
16
+ ListKeyValueStoresCommand,
17
+ ListOriginAccessControlsCommand,
18
+ PublishFunctionCommand,
19
+ UpdateCachePolicyCommand,
20
+ UpdateDistributionCommand,
21
+ UpdateFunctionCommand,
22
+ } from '@aws-sdk/client-cloudfront';
23
+ import { type EngineContext, ignoreNotFound, tagList, waitFor } from '../util.ts';
24
+
25
+ /** AWS managed origin request policy `Managed-AllViewerExceptHostHeader` (Web Function origins need it). */
26
+ export const ALL_VIEWER_EXCEPT_HOST_HEADER = 'b689b0a8-53d0-40ab-baf2-68738e2966ac';
27
+ /** Route 53 hosted zone id for every CloudFront alias target. */
28
+ export const CLOUDFRONT_HOSTED_ZONE_ID = 'Z2FDTNDATAQYW2';
29
+
30
+ export async function ensureKeyValueStore(
31
+ ctx: EngineContext,
32
+ spec: { name: string; comment?: string },
33
+ ): Promise<{ arn: string; id: string }> {
34
+ const cf = ctx.clients.cloudfront;
35
+ let Marker: string | undefined;
36
+ do {
37
+ const res = await cf.send(new ListKeyValueStoresCommand({ Marker }));
38
+ const found = (res.KeyValueStoreList?.Items ?? []).find((k) => k.Name === spec.name);
39
+ if (found?.ARN && found.Id) return { arn: found.ARN, id: found.Id };
40
+ Marker = res.KeyValueStoreList?.NextMarker;
41
+ } while (Marker);
42
+ const res = await cf.send(new CreateKeyValueStoreCommand({ Name: spec.name, Comment: spec.comment }));
43
+ const kvs = res.KeyValueStore!;
44
+ ctx.log('info', 'created key value store', `kvs ${spec.name}`);
45
+ await waitFor(`key value store ${spec.name}`, async () => {
46
+ const d = await cf.send(new DescribeKeyValueStoreCommand({ Name: spec.name }));
47
+ return d.KeyValueStore?.Status === 'READY' || d.KeyValueStore?.Status === undefined;
48
+ });
49
+ return { arn: kvs.ARN!, id: kvs.Id! };
50
+ }
51
+
52
+ /** Create/update a CloudFront Function (runtime 2.0) and publish it to LIVE. Returns the function ARN. */
53
+ export async function ensureRouterFunction(
54
+ ctx: EngineContext,
55
+ spec: { name: string; code: string; kvsArn?: string; comment?: string },
56
+ ): Promise<string> {
57
+ const cf = ctx.clients.cloudfront;
58
+ const code = new TextEncoder().encode(spec.code);
59
+ const FunctionConfig = {
60
+ Comment: spec.comment ?? 'platform router',
61
+ Runtime: 'cloudfront-js-2.0' as const,
62
+ ...(spec.kvsArn
63
+ ? { KeyValueStoreAssociations: { Quantity: 1, Items: [{ KeyValueStoreARN: spec.kvsArn }] } }
64
+ : {}),
65
+ };
66
+ const existing = await ignoreNotFound(
67
+ cf.send(new DescribeFunctionCommand({ Name: spec.name, Stage: 'DEVELOPMENT' })),
68
+ );
69
+ let etag: string | undefined;
70
+ if (!existing?.ETag) {
71
+ const res = await cf.send(
72
+ new CreateFunctionCommand({ Name: spec.name, FunctionConfig, FunctionCode: code }),
73
+ );
74
+ etag = res.ETag;
75
+ ctx.log('info', 'created router function', `cloudfront-function ${spec.name}`);
76
+ } else {
77
+ const live = await ignoreNotFound(cf.send(new GetFunctionCommand({ Name: spec.name, Stage: 'LIVE' })));
78
+ const liveCode = live?.FunctionCode ? new TextDecoder().decode(live.FunctionCode) : undefined;
79
+ if (liveCode === spec.code) return existing.FunctionSummary!.FunctionMetadata!.FunctionARN!;
80
+ const res = await cf.send(
81
+ new UpdateFunctionCommand({
82
+ Name: spec.name,
83
+ IfMatch: existing.ETag,
84
+ FunctionConfig,
85
+ FunctionCode: code,
86
+ }),
87
+ );
88
+ etag = res.ETag;
89
+ ctx.log('info', 'updated router function', `cloudfront-function ${spec.name}`);
90
+ }
91
+ const published = await cf.send(new PublishFunctionCommand({ Name: spec.name, IfMatch: etag }));
92
+ return published.FunctionSummary!.FunctionMetadata!.FunctionARN!;
93
+ }
94
+
95
+ export async function ensureOriginAccessControl(
96
+ ctx: EngineContext,
97
+ spec: { name: string; originType: 's3' | 'lambda'; signingBehavior?: 'always' | 'always-amz-auth' },
98
+ ): Promise<string> {
99
+ const cf = ctx.clients.cloudfront;
100
+ let Marker: string | undefined;
101
+ do {
102
+ const res = await cf.send(new ListOriginAccessControlsCommand({ Marker }));
103
+ const found = (res.OriginAccessControlList?.Items ?? []).find((o) => o.Name === spec.name);
104
+ if (found?.Id) return found.Id;
105
+ Marker = res.OriginAccessControlList?.NextMarker;
106
+ } while (Marker);
107
+ const res = await cf.send(
108
+ new CreateOriginAccessControlCommand({
109
+ OriginAccessControlConfig: {
110
+ Name: spec.name,
111
+ SigningProtocol: 'sigv4',
112
+ SigningBehavior: (spec.signingBehavior ?? 'always') as never,
113
+ OriginAccessControlOriginType: spec.originType,
114
+ },
115
+ }),
116
+ );
117
+ ctx.log('info', 'created origin access control', `oac ${spec.name}`);
118
+ return res.OriginAccessControl!.Id!;
119
+ }
120
+
121
+ export async function ensureCachePolicy(ctx: EngineContext, config: CachePolicyConfig): Promise<string> {
122
+ const cf = ctx.clients.cloudfront;
123
+ const list = await cf.send(new ListCachePoliciesCommand({ Type: 'custom' }));
124
+ const found = (list.CachePolicyList?.Items ?? []).find(
125
+ (p) => p.CachePolicy?.CachePolicyConfig?.Name === config.Name,
126
+ );
127
+ if (found?.CachePolicy?.Id) {
128
+ const id = found.CachePolicy.Id;
129
+ const current = await cf.send(new GetCachePolicyConfigCommand({ Id: id }));
130
+ if (diffPaths(normalize(current.CachePolicyConfig), normalize(config)).length) {
131
+ await cf.send(
132
+ new UpdateCachePolicyCommand({ Id: id, IfMatch: current.ETag, CachePolicyConfig: config }),
133
+ );
134
+ ctx.log('info', 'updated cache policy', `cache-policy ${config.Name}`);
135
+ }
136
+ return id;
137
+ }
138
+ const res = await cf.send(new CreateCachePolicyCommand({ CachePolicyConfig: config }));
139
+ ctx.log('info', 'created cache policy', `cache-policy ${config.Name}`);
140
+ return res.CachePolicy!.Id!;
141
+ }
142
+
143
+ /** The platform router's cache policy: origins decide caching; the host is part of the key. */
144
+ export function routerCachePolicy(name: string): CachePolicyConfig {
145
+ return {
146
+ Name: name,
147
+ Comment: 'platform router: origin-controlled caching, per-host keys',
148
+ MinTTL: 0,
149
+ DefaultTTL: 0,
150
+ MaxTTL: 31_536_000,
151
+ ParametersInCacheKeyAndForwardedToOrigin: {
152
+ EnableAcceptEncodingGzip: true,
153
+ EnableAcceptEncodingBrotli: true,
154
+ HeadersConfig: {
155
+ HeaderBehavior: 'whitelist',
156
+ Headers: { Quantity: 2, Items: ['x-platform-host', 'authorization'] },
157
+ },
158
+ CookiesConfig: { CookieBehavior: 'none' },
159
+ QueryStringsConfig: { QueryStringBehavior: 'all' },
160
+ },
161
+ };
162
+ }
163
+
164
+ export interface DistributionState {
165
+ id: string;
166
+ arn: string;
167
+ domainName: string;
168
+ status: string;
169
+ }
170
+
171
+ /**
172
+ * A distribution identified by its `Comment` (CloudFront has no names).
173
+ * `config` is the full desired DistributionConfig minus CallerReference.
174
+ */
175
+ export async function ensureDistribution(
176
+ ctx: EngineContext,
177
+ spec: {
178
+ comment: string;
179
+ config: Omit<DistributionConfig, 'CallerReference' | 'Comment'>;
180
+ tags?: Record<string, string>;
181
+ },
182
+ ): Promise<DistributionState> {
183
+ const cf = ctx.clients.cloudfront;
184
+ const existing = await findDistribution(ctx, spec.comment);
185
+ if (!existing) {
186
+ const res = await cf.send(
187
+ new CreateDistributionWithTagsCommand({
188
+ DistributionConfigWithTags: {
189
+ DistributionConfig: {
190
+ ...spec.config,
191
+ Comment: spec.comment,
192
+ CallerReference: `${spec.comment}-${Date.now()}`,
193
+ },
194
+ Tags: { Items: tagList(spec.tags ?? {}) },
195
+ },
196
+ }),
197
+ );
198
+ const d = res.Distribution!;
199
+ ctx.log('info', 'created distribution (propagation takes a few minutes)', `distribution ${spec.comment}`);
200
+ return { id: d.Id!, arn: d.ARN!, domainName: d.DomainName!, status: d.Status! };
201
+ }
202
+ const current = await cf.send(new GetDistributionConfigCommand({ Id: existing.id }));
203
+ // UpdateDistribution replaces the whole config and rejects one that omits
204
+ // required fields (SmoothStreaming, FieldLevelEncryptionId, ...), so the
205
+ // desired settings are deep-merged over what CloudFront returned.
206
+ const merged = deepMerge(current.DistributionConfig!, {
207
+ ...spec.config,
208
+ Comment: spec.comment,
209
+ CallerReference: current.DistributionConfig!.CallerReference,
210
+ }) as DistributionConfig;
211
+ const changed = diffPaths(normalize(current.DistributionConfig!), normalize(merged));
212
+ if (changed.length) {
213
+ await cf.send(
214
+ new UpdateDistributionCommand({ Id: existing.id, IfMatch: current.ETag, DistributionConfig: merged }),
215
+ );
216
+ ctx.log(
217
+ 'info',
218
+ `updated distribution (${changed.slice(0, 5).join(', ')})`,
219
+ `distribution ${spec.comment}`,
220
+ );
221
+ }
222
+ return existing;
223
+ }
224
+
225
+ export async function findDistribution(
226
+ ctx: EngineContext,
227
+ comment: string,
228
+ ): Promise<DistributionState | undefined> {
229
+ const cf = ctx.clients.cloudfront;
230
+ let Marker: string | undefined;
231
+ do {
232
+ const res = await cf.send(new ListDistributionsCommand({ Marker }));
233
+ const found = (res.DistributionList?.Items ?? []).find((d) => d.Comment === comment);
234
+ if (found)
235
+ return { id: found.Id!, arn: found.ARN!, domainName: found.DomainName!, status: found.Status! };
236
+ Marker = res.DistributionList?.IsTruncated ? res.DistributionList.NextMarker : undefined;
237
+ } while (Marker);
238
+ return undefined;
239
+ }
240
+
241
+ /**
242
+ * Overlay `patch` on `base`: objects merge key by key, equal-length arrays
243
+ * merge element by element (CloudFront lists like Origins keep their order),
244
+ * anything else is replaced. Undefined patch values keep the base value.
245
+ */
246
+ export function deepMerge(base: unknown, patch: unknown): unknown {
247
+ if (patch === undefined) return base;
248
+ if (Array.isArray(base) && Array.isArray(patch)) {
249
+ return base.length === patch.length ? patch.map((p, i) => deepMerge(base[i], p)) : patch;
250
+ }
251
+ if (isPlainObject(base) && isPlainObject(patch)) {
252
+ const out: Record<string, unknown> = { ...base };
253
+ for (const [k, v] of Object.entries(patch)) out[k] = deepMerge(base[k], v);
254
+ return out;
255
+ }
256
+ return patch;
257
+ }
258
+
259
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
260
+ return typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Date);
261
+ }
262
+
263
+ /** Paths where two normalized values differ, e.g. `DefaultCacheBehavior.Compress`. */
264
+ export function diffPaths(a: unknown, b: unknown, path = ''): string[] {
265
+ if (JSON.stringify(a) === JSON.stringify(b)) return [];
266
+ if (isPlainObject(a) && isPlainObject(b)) {
267
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
268
+ return [...keys].flatMap((k) => diffPaths(a[k], b[k], path ? `${path}.${k}` : k));
269
+ }
270
+ if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) {
271
+ return a.flatMap((v, i) => diffPaths(v, b[i], `${path}[${i}]`));
272
+ }
273
+ return [path || '(root)'];
274
+ }
275
+
276
+ /** Drop undefined fields so a fetched config and a desired config compare equal. */
277
+ function normalize(v: unknown): unknown {
278
+ // String lists in a distribution config (methods, aliases, header names) are
279
+ // sets; CloudFront returns them in its own order.
280
+ if (Array.isArray(v) && v.every((x) => typeof x === 'string')) return [...v].sort();
281
+ if (Array.isArray(v)) return v.map(normalize);
282
+ if (v && typeof v === 'object') {
283
+ const out: Record<string, unknown> = {};
284
+ for (const k of Object.keys(v as object).sort()) {
285
+ const val = (v as Record<string, unknown>)[k];
286
+ if (val !== undefined) out[k] = normalize(val);
287
+ }
288
+ return out;
289
+ }
290
+ return v;
291
+ }
@@ -0,0 +1,199 @@
1
+ import {
2
+ CreateManagedLoginBrandingCommand,
3
+ CreateUserPoolClientCommand,
4
+ CreateUserPoolCommand,
5
+ CreateUserPoolDomainCommand,
6
+ DeleteUserPoolClientCommand,
7
+ DescribeUserPoolDomainCommand,
8
+ type ExplicitAuthFlowsType,
9
+ ListUserPoolClientsCommand,
10
+ ListUserPoolsCommand,
11
+ UpdateUserPoolClientCommand,
12
+ } from '@aws-sdk/client-cognito-identity-provider';
13
+ import { AUTH_SCOPES } from '@ericminassian/platform-core';
14
+ import { type EngineContext, errorName, ignoreNotFound, isNotImplemented, retry } from '../util.ts';
15
+
16
+ /** Shared user pool for app end users: email sign-in, self sign-up, Essentials tier (managed login). */
17
+ export async function ensureUserPool(
18
+ ctx: EngineContext,
19
+ spec: { name: string; tags?: Record<string, string> },
20
+ ): Promise<string> {
21
+ const cognito = ctx.clients.cognito;
22
+ let NextToken: string | undefined;
23
+ do {
24
+ const res = await cognito.send(new ListUserPoolsCommand({ MaxResults: 60, NextToken }));
25
+ const found = (res.UserPools ?? []).find((p) => p.Name === spec.name);
26
+ if (found?.Id) return found.Id;
27
+ NextToken = res.NextToken;
28
+ } while (NextToken);
29
+ const res = await cognito.send(
30
+ new CreateUserPoolCommand({
31
+ PoolName: spec.name,
32
+ UsernameAttributes: ['email'],
33
+ AutoVerifiedAttributes: ['email'],
34
+ UsernameConfiguration: { CaseSensitive: false },
35
+ AdminCreateUserConfig: { AllowAdminCreateUserOnly: false },
36
+ AccountRecoverySetting: { RecoveryMechanisms: [{ Name: 'verified_email', Priority: 1 }] },
37
+ Policies: {
38
+ PasswordPolicy: {
39
+ MinimumLength: 10,
40
+ RequireLowercase: false,
41
+ RequireUppercase: false,
42
+ RequireNumbers: false,
43
+ RequireSymbols: false,
44
+ },
45
+ },
46
+ UserPoolTier: ctx.target === 'aws' ? 'ESSENTIALS' : undefined,
47
+ DeletionProtection: ctx.target === 'aws' ? 'ACTIVE' : 'INACTIVE',
48
+ UserPoolTags: spec.tags,
49
+ }),
50
+ );
51
+ ctx.log('info', 'created user pool', `user-pool ${spec.name}`);
52
+ return res.UserPool!.Id!;
53
+ }
54
+
55
+ export interface UserPoolClientSpec {
56
+ userPoolId: string;
57
+ name: string;
58
+ callbackUrls: string[];
59
+ logoutUrls: string[];
60
+ /** Also allow password flows (the local sign-in page under `plat dev`). */
61
+ passwordFlows?: boolean;
62
+ }
63
+
64
+ export async function findUserPoolClient(
65
+ ctx: EngineContext,
66
+ userPoolId: string,
67
+ name: string,
68
+ ): Promise<string | undefined> {
69
+ let NextToken: string | undefined;
70
+ do {
71
+ const res = await ignoreNotFound(
72
+ ctx.clients.cognito.send(
73
+ new ListUserPoolClientsCommand({ UserPoolId: userPoolId, MaxResults: 60, NextToken }),
74
+ ),
75
+ );
76
+ if (!res) return undefined;
77
+ const found = (res.UserPoolClients ?? []).find((c) => c.ClientName === name);
78
+ if (found?.ClientId) return found.ClientId;
79
+ NextToken = res.NextToken;
80
+ } while (NextToken);
81
+ return undefined;
82
+ }
83
+
84
+ /** Public app client (no secret) for the authorization-code + PKCE flow. */
85
+ export async function ensureUserPoolClient(ctx: EngineContext, spec: UserPoolClientSpec): Promise<string> {
86
+ const cognito = ctx.clients.cognito;
87
+ const flows: ExplicitAuthFlowsType[] = ['ALLOW_REFRESH_TOKEN_AUTH'];
88
+ if (spec.passwordFlows) flows.push('ALLOW_USER_PASSWORD_AUTH', 'ALLOW_ADMIN_USER_PASSWORD_AUTH');
89
+ const config = {
90
+ UserPoolId: spec.userPoolId,
91
+ ClientName: spec.name,
92
+ ExplicitAuthFlows: flows,
93
+ AllowedOAuthFlows: ['code' as const],
94
+ AllowedOAuthScopes: [...AUTH_SCOPES],
95
+ AllowedOAuthFlowsUserPoolClient: true,
96
+ CallbackURLs: spec.callbackUrls,
97
+ LogoutURLs: spec.logoutUrls,
98
+ SupportedIdentityProviders: ['COGNITO'],
99
+ PreventUserExistenceErrors: 'ENABLED' as const,
100
+ EnableTokenRevocation: true,
101
+ AccessTokenValidity: 60,
102
+ IdTokenValidity: 60,
103
+ RefreshTokenValidity: 30,
104
+ TokenValidityUnits: {
105
+ AccessToken: 'minutes' as const,
106
+ IdToken: 'minutes' as const,
107
+ RefreshToken: 'days' as const,
108
+ },
109
+ };
110
+ const existing = await findUserPoolClient(ctx, spec.userPoolId, spec.name);
111
+ if (existing) {
112
+ await cognito.send(new UpdateUserPoolClientCommand({ ...config, ClientId: existing }));
113
+ return existing;
114
+ }
115
+ const res = await cognito.send(new CreateUserPoolClientCommand({ ...config, GenerateSecret: false }));
116
+ const clientId = res.UserPoolClient!.ClientId!;
117
+ ctx.log('info', 'created app client', `user-pool-client ${spec.name}`);
118
+ // Managed login (v2) renders a client's pages only once it has a branding style.
119
+ // The emulator has no hosted login (and mis-serializes this response), so skip it there.
120
+ if (ctx.target !== 'aws') return clientId;
121
+ try {
122
+ await cognito.send(
123
+ new CreateManagedLoginBrandingCommand({
124
+ UserPoolId: spec.userPoolId,
125
+ ClientId: clientId,
126
+ UseCognitoProvidedValues: true,
127
+ }),
128
+ );
129
+ } catch (e) {
130
+ if (isNotImplemented(e))
131
+ ctx.log('warn', 'managed login branding not supported here', `user-pool-client ${spec.name}`);
132
+ else if (!/Exists|Conflict/.test(errorName(e))) throw e;
133
+ }
134
+ return clientId;
135
+ }
136
+
137
+ export async function deleteUserPoolClient(
138
+ ctx: EngineContext,
139
+ userPoolId: string,
140
+ name: string,
141
+ ): Promise<boolean> {
142
+ const id = await findUserPoolClient(ctx, userPoolId, name);
143
+ if (!id) return false;
144
+ await ignoreNotFound(
145
+ ctx.clients.cognito.send(new DeleteUserPoolClientCommand({ UserPoolId: userPoolId, ClientId: id })),
146
+ );
147
+ ctx.log('info', 'deleted app client', `user-pool-client ${name}`);
148
+ return true;
149
+ }
150
+
151
+ /**
152
+ * Managed login (v2) on a custom domain. Returns the CloudFront domain Route 53
153
+ * must alias the custom domain to. The certificate must be in us-east-1.
154
+ */
155
+ export async function ensureUserPoolDomain(
156
+ ctx: EngineContext,
157
+ spec: { userPoolId: string; domain: string; certificateArn: string },
158
+ ): Promise<string | undefined> {
159
+ const cognito = ctx.clients.cognito;
160
+ const existing = await cognito.send(new DescribeUserPoolDomainCommand({ Domain: spec.domain }));
161
+ if (existing.DomainDescription?.UserPoolId) {
162
+ if (existing.DomainDescription.UserPoolId !== spec.userPoolId) {
163
+ throw new Error(`domain ${spec.domain} belongs to another user pool`);
164
+ }
165
+ return existing.DomainDescription.CloudFrontDistribution;
166
+ }
167
+ // Cognito requires the parent domain to resolve to an A record before it
168
+ // accepts a custom domain. On a first run the parent is an alias to a
169
+ // CloudFront distribution created moments earlier, which resolves only once
170
+ // the distribution has deployed (several minutes), so keep retrying.
171
+ let waiting = false;
172
+ const res = await retry(
173
+ () =>
174
+ cognito.send(
175
+ new CreateUserPoolDomainCommand({
176
+ Domain: spec.domain,
177
+ UserPoolId: spec.userPoolId,
178
+ ManagedLoginVersion: 2,
179
+ CustomDomainConfig: { CertificateArn: spec.certificateArn },
180
+ }),
181
+ ),
182
+ {
183
+ attempts: 120,
184
+ delayMs: 5_000,
185
+ when: (e) => {
186
+ const parentMissing = /resolve a DNS A record for the parent domain/i.test(
187
+ String((e as Error).message),
188
+ );
189
+ if (parentMissing && !waiting) {
190
+ waiting = true;
191
+ ctx.log('info', `waiting for the parent of ${spec.domain} to resolve (CloudFront still deploying)`);
192
+ }
193
+ return parentMissing;
194
+ },
195
+ },
196
+ );
197
+ ctx.log('info', 'created managed login domain', `user-pool-domain ${spec.domain}`);
198
+ return res.CloudFrontDomain;
199
+ }
@@ -0,0 +1,206 @@
1
+ import {
2
+ type AttributeDefinition,
3
+ CreateTableCommand,
4
+ DeleteTableCommand,
5
+ DescribeContinuousBackupsCommand,
6
+ DescribeTableCommand,
7
+ DescribeTimeToLiveCommand,
8
+ type GlobalSecondaryIndex,
9
+ TagResourceCommand,
10
+ UpdateContinuousBackupsCommand,
11
+ UpdateTableCommand,
12
+ UpdateTimeToLiveCommand,
13
+ } from '@aws-sdk/client-dynamodb';
14
+ import { type EngineContext, ignoreNotFound, tagList, waitFor } from '../util.ts';
15
+
16
+ export interface TableSpec {
17
+ name: string;
18
+ /** Partition/sort key attribute names (all strings). */
19
+ pk: string;
20
+ sk?: string;
21
+ /** GSIs as `[indexName, pkAttr, skAttr?]` (string attributes, projection ALL). */
22
+ gsis?: Array<[string, string, string?]>;
23
+ ttlAttribute?: string;
24
+ pointInTimeRecovery?: boolean;
25
+ deletionProtection?: boolean;
26
+ tags?: Record<string, string>;
27
+ }
28
+
29
+ export interface TableState {
30
+ name: string;
31
+ arn: string;
32
+ created: boolean;
33
+ }
34
+
35
+ /** The per-stage table: `pk`/`sk`, three generic GSIs and TTL on `_ttl`. */
36
+ export function stageTableSpec(
37
+ name: string,
38
+ opts: { prod: boolean; tags: Record<string, string> },
39
+ ): TableSpec {
40
+ return {
41
+ name,
42
+ pk: 'pk',
43
+ sk: 'sk',
44
+ gsis: [
45
+ ['gsi1', 'gsi1pk', 'gsi1sk'],
46
+ ['gsi2', 'gsi2pk', 'gsi2sk'],
47
+ ['gsi3', 'gsi3pk', 'gsi3sk'],
48
+ ],
49
+ ttlAttribute: '_ttl',
50
+ pointInTimeRecovery: opts.prod,
51
+ deletionProtection: opts.prod,
52
+ tags: opts.tags,
53
+ };
54
+ }
55
+
56
+ export async function ensureTable(ctx: EngineContext, spec: TableSpec): Promise<TableState> {
57
+ const ddb = ctx.clients.dynamodb;
58
+ const existing = await ignoreNotFound(ddb.send(new DescribeTableCommand({ TableName: spec.name })));
59
+ let created = false;
60
+ let arn = existing?.Table?.TableArn;
61
+
62
+ if (!existing?.Table) {
63
+ const attrs = new Map<string, AttributeDefinition>();
64
+ const addAttr = (n: string) => attrs.set(n, { AttributeName: n, AttributeType: 'S' });
65
+ addAttr(spec.pk);
66
+ if (spec.sk) addAttr(spec.sk);
67
+ const gsis: GlobalSecondaryIndex[] = (spec.gsis ?? []).map(([IndexName, pk, sk]) => {
68
+ addAttr(pk);
69
+ if (sk) addAttr(sk);
70
+ return {
71
+ IndexName,
72
+ KeySchema: [
73
+ { AttributeName: pk, KeyType: 'HASH' },
74
+ ...(sk ? [{ AttributeName: sk, KeyType: 'RANGE' as const }] : []),
75
+ ],
76
+ Projection: { ProjectionType: 'ALL' },
77
+ };
78
+ });
79
+ const res = await ddb.send(
80
+ new CreateTableCommand({
81
+ TableName: spec.name,
82
+ BillingMode: 'PAY_PER_REQUEST',
83
+ AttributeDefinitions: [...attrs.values()],
84
+ KeySchema: [
85
+ { AttributeName: spec.pk, KeyType: 'HASH' },
86
+ ...(spec.sk ? [{ AttributeName: spec.sk, KeyType: 'RANGE' as const }] : []),
87
+ ],
88
+ GlobalSecondaryIndexes: gsis.length ? gsis : undefined,
89
+ DeletionProtectionEnabled: spec.deletionProtection ?? false,
90
+ Tags: spec.tags ? tagList(spec.tags) : undefined,
91
+ }),
92
+ );
93
+ arn = res.TableDescription?.TableArn;
94
+ created = true;
95
+ ctx.log('info', 'created table', `table ${spec.name}`);
96
+ }
97
+
98
+ await waitActive(ctx, spec.name);
99
+
100
+ if (!created && existing?.Table) {
101
+ // Add any missing GSIs (DynamoDB allows one index creation per UpdateTable call).
102
+ const have = new Set((existing.Table.GlobalSecondaryIndexes ?? []).map((g) => g.IndexName));
103
+ for (const [IndexName, pk, sk] of spec.gsis ?? []) {
104
+ if (have.has(IndexName)) continue;
105
+ await ddb.send(
106
+ new UpdateTableCommand({
107
+ TableName: spec.name,
108
+ AttributeDefinitions: [
109
+ { AttributeName: pk, AttributeType: 'S' },
110
+ ...(sk ? [{ AttributeName: sk, AttributeType: 'S' as const }] : []),
111
+ ],
112
+ GlobalSecondaryIndexUpdates: [
113
+ {
114
+ Create: {
115
+ IndexName,
116
+ KeySchema: [
117
+ { AttributeName: pk, KeyType: 'HASH' },
118
+ ...(sk ? [{ AttributeName: sk, KeyType: 'RANGE' as const }] : []),
119
+ ],
120
+ Projection: { ProjectionType: 'ALL' },
121
+ },
122
+ },
123
+ ],
124
+ }),
125
+ );
126
+ ctx.log('info', `adding index ${IndexName}`, `table ${spec.name}`);
127
+ await waitActive(ctx, spec.name);
128
+ }
129
+ if (
130
+ spec.deletionProtection !== undefined &&
131
+ existing.Table.DeletionProtectionEnabled !== spec.deletionProtection
132
+ ) {
133
+ await ddb.send(
134
+ new UpdateTableCommand({ TableName: spec.name, DeletionProtectionEnabled: spec.deletionProtection }),
135
+ );
136
+ await waitActive(ctx, spec.name);
137
+ }
138
+ if (spec.tags && arn)
139
+ await ddb.send(new TagResourceCommand({ ResourceArn: arn, Tags: tagList(spec.tags) }));
140
+ }
141
+
142
+ if (spec.ttlAttribute) {
143
+ const ttl = await ddb.send(new DescribeTimeToLiveCommand({ TableName: spec.name }));
144
+ const status = ttl.TimeToLiveDescription?.TimeToLiveStatus;
145
+ if (status !== 'ENABLED' && status !== 'ENABLING') {
146
+ await ddb.send(
147
+ new UpdateTimeToLiveCommand({
148
+ TableName: spec.name,
149
+ TimeToLiveSpecification: { Enabled: true, AttributeName: spec.ttlAttribute },
150
+ }),
151
+ );
152
+ }
153
+ }
154
+
155
+ if (spec.pointInTimeRecovery !== undefined) {
156
+ const backups = await ddb.send(new DescribeContinuousBackupsCommand({ TableName: spec.name }));
157
+ const enabled =
158
+ backups.ContinuousBackupsDescription?.PointInTimeRecoveryDescription?.PointInTimeRecoveryStatus ===
159
+ 'ENABLED';
160
+ if (enabled !== spec.pointInTimeRecovery) {
161
+ await ddb.send(
162
+ new UpdateContinuousBackupsCommand({
163
+ TableName: spec.name,
164
+ PointInTimeRecoverySpecification: { PointInTimeRecoveryEnabled: spec.pointInTimeRecovery },
165
+ }),
166
+ );
167
+ }
168
+ }
169
+
170
+ if (!arn) {
171
+ const d = await ddb.send(new DescribeTableCommand({ TableName: spec.name }));
172
+ arn = d.Table!.TableArn!;
173
+ }
174
+ return { name: spec.name, arn, created };
175
+ }
176
+
177
+ async function waitActive(ctx: EngineContext, name: string): Promise<void> {
178
+ await waitFor(`table ${name} ACTIVE`, async () => {
179
+ const d = await ctx.clients.dynamodb.send(new DescribeTableCommand({ TableName: name }));
180
+ const t = d.Table;
181
+ return (
182
+ t?.TableStatus === 'ACTIVE' && (t.GlobalSecondaryIndexes ?? []).every((g) => g.IndexStatus === 'ACTIVE')
183
+ );
184
+ });
185
+ }
186
+
187
+ export async function describeTable(ctx: EngineContext, name: string) {
188
+ return (await ignoreNotFound(ctx.clients.dynamodb.send(new DescribeTableCommand({ TableName: name }))))
189
+ ?.Table;
190
+ }
191
+
192
+ export async function deleteTable(ctx: EngineContext, name: string): Promise<boolean> {
193
+ const ddb = ctx.clients.dynamodb;
194
+ const t = await describeTable(ctx, name);
195
+ if (!t) return false;
196
+ if (t.DeletionProtectionEnabled) {
197
+ await ddb.send(new UpdateTableCommand({ TableName: name, DeletionProtectionEnabled: false }));
198
+ await waitActive(ctx, name);
199
+ }
200
+ await ignoreNotFound(ddb.send(new DeleteTableCommand({ TableName: name })));
201
+ await waitFor(`table ${name} deleted`, async () => !(await describeTable(ctx, name)), {
202
+ timeoutMs: 120_000,
203
+ });
204
+ ctx.log('info', 'deleted table', `table ${name}`);
205
+ return true;
206
+ }