@ericminassian/platform-core 0.3.0 → 0.4.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.
- package/dist/api.d.ts +942 -45
- package/dist/api.js +372 -13
- package/dist/api.js.map +1 -1
- package/dist/auth.js +5 -2
- package/dist/auth.js.map +1 -1
- package/dist/base64url.d.ts +3 -0
- package/dist/base64url.js +15 -0
- package/dist/base64url.js.map +1 -0
- package/dist/bindings.d.ts +62 -12
- package/dist/bindings.js +1 -1
- package/dist/bindings.js.map +1 -1
- package/dist/cloudfront-function.d.ts +5 -1
- package/dist/cloudfront-function.js +64 -2
- package/dist/cloudfront-function.js.map +1 -1
- package/dist/compute.d.ts +52 -0
- package/dist/compute.js +65 -0
- package/dist/compute.js.map +1 -0
- package/dist/config.d.ts +18 -0
- package/dist/config.js +9 -0
- package/dist/config.js.map +1 -1
- package/dist/constants.d.ts +56 -1
- package/dist/constants.js +56 -1
- package/dist/constants.js.map +1 -1
- package/dist/email.d.ts +84 -0
- package/dist/email.js +111 -0
- package/dist/email.js.map +1 -0
- package/dist/fingerprint.d.ts +9 -0
- package/dist/fingerprint.js +19 -0
- package/dist/fingerprint.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/jobs.d.ts +111 -0
- package/dist/jobs.js +214 -0
- package/dist/jobs.js.map +1 -0
- package/dist/manifest.d.ts +270 -29
- package/dist/manifest.js +190 -22
- package/dist/manifest.js.map +1 -1
- package/dist/naming.d.ts +83 -7
- package/dist/naming.js +89 -8
- package/dist/naming.js.map +1 -1
- package/dist/platform-api.d.ts +3733 -1278
- package/dist/platform-api.js +120 -8
- package/dist/platform-api.js.map +1 -1
- package/dist/realtime.d.ts +139 -0
- package/dist/realtime.js +201 -0
- package/dist/realtime.js.map +1 -0
- package/dist/router/decide.d.ts +2 -0
- package/dist/router/decide.js +38 -6
- package/dist/router.d.ts +35 -13
- package/dist/router.js +36 -0
- package/dist/router.js.map +1 -1
- package/dist/runtime-config.d.ts +57 -0
- package/dist/runtime-config.js +12 -0
- package/dist/runtime-config.js.map +1 -1
- package/dist/storage.d.ts +55 -0
- package/dist/storage.js +112 -0
- package/dist/storage.js.map +1 -0
- package/dist/telemetry.d.ts +124 -19
- package/dist/telemetry.js +97 -21
- package/dist/telemetry.js.map +1 -1
- package/dist/web-compute.d.ts +191 -0
- package/dist/web-compute.js +257 -0
- package/dist/web-compute.js.map +1 -0
- package/package.json +19 -7
- package/src/api.ts +445 -15
- package/src/auth.ts +6 -2
- package/src/base64url.ts +13 -0
- package/src/bindings.ts +67 -6
- package/src/cloudfront-function.ts +64 -2
- package/src/compute.ts +86 -0
- package/src/config.ts +31 -1
- package/src/constants.ts +64 -1
- package/src/email.ts +168 -0
- package/src/fingerprint.ts +20 -0
- package/src/index.ts +6 -0
- package/src/jobs.ts +281 -0
- package/src/manifest.ts +415 -45
- package/src/naming.ts +93 -9
- package/src/platform-api.ts +134 -8
- package/src/realtime.ts +298 -0
- package/src/router/decide.d.ts +2 -0
- package/src/router/decide.js +38 -6
- package/src/router.ts +33 -13
- package/src/runtime-config.ts +70 -0
- package/src/storage.ts +120 -0
- package/src/telemetry.ts +104 -21
- package/src/web-compute.ts +342 -0
package/src/naming.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { PROD_STAGE } from './constants.ts';
|
|
2
|
-
import { fingerprint } from './
|
|
2
|
+
import { fingerprint } from './fingerprint.ts';
|
|
3
|
+
import { PUBLIC_STORAGE_ROOT } from './storage.ts';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* App names: 3-30 chars, lowercase letters/digits/single hyphens, starting with
|
|
@@ -93,25 +94,73 @@ export function parseStageHost(host: string, domain: string): { app: string; sta
|
|
|
93
94
|
export const names = {
|
|
94
95
|
base: (app: string, stage: string) => `${app}--${stage}`,
|
|
95
96
|
table: (app: string, stage: string) => `${app}--${stage}`,
|
|
97
|
+
/** The server's Lambda Web Function (instance mode). */
|
|
96
98
|
webFunction: (app: string, stage: string) => `${app}--${stage}`,
|
|
97
99
|
/**
|
|
98
|
-
* The
|
|
99
|
-
*
|
|
100
|
-
*
|
|
100
|
+
* The server's Lambda function in request mode. Not a worker function,
|
|
101
|
+
* though it shares their `<app>--<stage>--` prefix: a handler's own
|
|
102
|
+
* function is `…--worker--…`, or a cut of that ending in `-<hash>`.
|
|
103
|
+
*/
|
|
104
|
+
requestFunction: (app: string, stage: string) => `${app}--${stage}--web`,
|
|
105
|
+
/**
|
|
106
|
+
* The Web Function's two endpoints, and the request-mode function's two
|
|
107
|
+
* aliases (each with a function URL), each pinned to one revision or
|
|
108
|
+
* version. Neither name means "current": a deploy uses whichever the live
|
|
109
|
+
* route doesn't (`live` predates the second one).
|
|
101
110
|
*/
|
|
102
111
|
webEndpoints: () => ['live', 'live-b'] as const,
|
|
103
112
|
workerFunction: (app: string, stage: string) => `${app}--${stage}--worker`,
|
|
113
|
+
/**
|
|
114
|
+
* The function a queue, event or cron handler with its own memory or timeout
|
|
115
|
+
* runs in, from the worker's bundle. Function names are ≤ 64 chars of
|
|
116
|
+
* A-Z, a-z, 0-9, `-` and `_`: long names are hashed, and an event type's
|
|
117
|
+
* `.` becomes `_` (which no event type contains). `:` has no such stand-in,
|
|
118
|
+
* so a type with one always carries a hash of the type.
|
|
119
|
+
*/
|
|
120
|
+
handlerFunction: (app: string, stage: string, kind: 'queue' | 'event' | 'cron', name: string) => {
|
|
121
|
+
const full = `${app}--${stage}--worker--${kind}-${name}`;
|
|
122
|
+
const safe = full.replaceAll('.', '_').replaceAll(':', '_');
|
|
123
|
+
return name.includes(':') ? `${safe.slice(0, 55)}-${fingerprint([full])}` : fit(safe, 64);
|
|
124
|
+
},
|
|
104
125
|
/** IAM role name; created under {@link IAM_APP_PATH}. */
|
|
105
126
|
role: (app: string, stage: string) => `${app}--${stage}`,
|
|
106
|
-
|
|
107
|
-
|
|
127
|
+
/**
|
|
128
|
+
* The stage's dead-letter queue (SQS, never polled): every job that failed
|
|
129
|
+
* its last attempt. Queue keys can't contain `--` and the old dead-letter
|
|
130
|
+
* queues end in `--dlq`, so this can't be a pre-0.4.0 queue's name.
|
|
131
|
+
*/
|
|
132
|
+
deadLetters: (app: string, stage: string) => `${app}--${stage}--jobs--dead`,
|
|
133
|
+
/** The SQS queue `plat dev` points the stage's event rules at, to run events in the local worker. */
|
|
134
|
+
devEventTap: (app: string, stage: string) => `${app}--${stage}--plat-dev-events`,
|
|
135
|
+
/** A queue's SQS queue and its dead-letter queue, before queues were pushed (0.4.0). */
|
|
136
|
+
legacyQueue: (app: string, stage: string, key: string) => `${app}--${stage}--${key}`,
|
|
137
|
+
legacyDeadLetterQueue: (app: string, stage: string, key: string) => `${app}--${stage}--${key}--dlq`,
|
|
108
138
|
eventBus: (app: string, stage: string) => `${app}--${stage}`,
|
|
109
139
|
/** EventBridge rule names are ≤ 64 chars; long event types are hashed. */
|
|
110
140
|
eventRule: (app: string, stage: string, eventType: string) =>
|
|
111
141
|
fit(`${app}--${stage}--${eventType.replace(/[^A-Za-z0-9._-]/g, '_')}`, 64),
|
|
112
142
|
scheduleGroup: (app: string, stage: string) => `${app}--${stage}`,
|
|
113
143
|
schedule: (cronKey: string) => cronKey,
|
|
144
|
+
/**
|
|
145
|
+
* A long-running service's ECS service and task definition family (ECS
|
|
146
|
+
* names are their own namespace, so `worker` can't clash with the Lambda).
|
|
147
|
+
*/
|
|
148
|
+
service: (app: string, stage: string, key: string) => `${app}--${stage}--${key}`,
|
|
149
|
+
serviceLogGroup: (app: string, stage: string, key: string) =>
|
|
150
|
+
`/platform/apps/${app}/${stage}/services/${key}`,
|
|
151
|
+
/** Tag of a service's image for one deployment in the container repository (≤ 103 of ECR's 128 chars). */
|
|
152
|
+
serviceImageTag: (app: string, stage: string, key: string, deploymentId: string) =>
|
|
153
|
+
`${app}--${stage}--${key}--${deploymentId}`,
|
|
154
|
+
/**
|
|
155
|
+
* One-shot schedule, in the stage's schedule group, that stops a preview's
|
|
156
|
+
* service. Cron keys can't contain `--`, so it never clashes with a cron.
|
|
157
|
+
*/
|
|
158
|
+
serviceStopSchedule: (key: string) => `${key}--stop`,
|
|
114
159
|
userPoolClient: (app: string, stage: string) => `${app}--${stage}`,
|
|
160
|
+
/** SES tenant and its configuration set (≤ 64 chars each; the base is ≤ 52). */
|
|
161
|
+
emailTenant: (app: string, stage: string) => `${app}--${stage}`,
|
|
162
|
+
/** AppSync Events channel namespace; names are ≤ 50 chars, so long ones are hashed. */
|
|
163
|
+
realtimeNamespace: (app: string, stage: string) => fit(`${app}--${stage}`, 50),
|
|
115
164
|
/**
|
|
116
165
|
* A stage's log groups. Lambda also writes a Web Function's environments to
|
|
117
166
|
* `<web group>.local`, so the engine creates that one too.
|
|
@@ -124,9 +173,12 @@ export const names = {
|
|
|
124
173
|
sharedSecretsPath: (app: string) => `/platform/apps/${app}/_shared/secrets/`,
|
|
125
174
|
/** SSM SecureString holding the stage key (see `Bindings.stageKey`); outside the secrets path. */
|
|
126
175
|
stageKeyParameter: (app: string, stage: string) => `/platform/apps/${app}/${stage}/stage-key`,
|
|
127
|
-
/**
|
|
128
|
-
storagePrefix: (app: string, stage: string,
|
|
129
|
-
|
|
176
|
+
/** A private store's prefix in the shared storage bucket: `<app>/<stage>/<store>/`. */
|
|
177
|
+
storagePrefix: (app: string, stage: string, store?: string) =>
|
|
178
|
+
store ? `${app}/${stage}/${store}/` : `${app}/${stage}/`,
|
|
179
|
+
/** A public store's prefix in the shared storage bucket: `_public/<app>/<stage>/<store>/` (see `storage.ts`). */
|
|
180
|
+
publicStoragePrefix: (app: string, stage: string, store?: string) =>
|
|
181
|
+
`${PUBLIC_STORAGE_ROOT}${names.storagePrefix(app, stage, store)}`,
|
|
130
182
|
/** Prefix inside the shared sites bucket for one deployment's static files. */
|
|
131
183
|
sitePrefix: (app: string, stage: string, deploymentId: string) => `${app}/${stage}/${deploymentId}`,
|
|
132
184
|
artifactKey: (app: string, stage: string, deploymentId: string, file: string) =>
|
|
@@ -147,9 +199,41 @@ export const platformNames = {
|
|
|
147
199
|
routerFunction: 'platform-router',
|
|
148
200
|
userPool: 'platform-users',
|
|
149
201
|
boundaryPolicy: 'platform-app-boundary',
|
|
202
|
+
/** The AppSync Event API every stage's channel namespace lives in. */
|
|
203
|
+
realtimeApi: 'platform-realtime',
|
|
204
|
+
/** Its Lambda authorizer (signed-in subscribe tokens). */
|
|
205
|
+
realtimeAuthorizer: 'platform-realtime-authorizer',
|
|
206
|
+
/** ECS cluster every stage's containers run in (long-running services). */
|
|
207
|
+
containerCluster: 'platform',
|
|
208
|
+
/** VPC and security group containers run in: public subnets, no NAT, egress only. */
|
|
209
|
+
containerNetwork: 'platform-containers',
|
|
210
|
+
/** ECR repository of every container image the platform builds; tags name app, stage and deployment. */
|
|
211
|
+
containerRepository: 'platform-containers',
|
|
212
|
+
/** Role ECS uses to pull images and ship container logs (the app's code runs as its stage role). */
|
|
213
|
+
containerExecutionRole: 'platform-container-execution',
|
|
214
|
+
/** Role EventBridge Scheduler uses to scale containers (a preview's stop schedule). */
|
|
215
|
+
containerSchedulerRole: 'platform-container-scheduler',
|
|
216
|
+
/** Description of the API's subscribe-only key for `public` stages (how the control plane finds it). */
|
|
217
|
+
realtimePublicKey: 'platform-public-subscribe',
|
|
218
|
+
/** The control plane's own app name (services/control-plane/plat.config.ts), stage prod. */
|
|
219
|
+
controlPlaneApp: 'platform',
|
|
150
220
|
controlPlaneRole: 'platform-control-plane',
|
|
151
221
|
ciRole: 'platform-ci',
|
|
152
222
|
alertsTopic: 'platform-alerts',
|
|
223
|
+
/**
|
|
224
|
+
* The edge floor's AWS WAF web ACL, which the control plane creates and attaches to the router
|
|
225
|
+
* while the floor is on; also its CloudWatch metric name. Not `platform-edge`, the always-on web
|
|
226
|
+
* ACL the foundation stack used to own: the stack deletes that one only after updating the
|
|
227
|
+
* distribution, so the two names can't collide while it goes.
|
|
228
|
+
*/
|
|
229
|
+
edgeWebAcl: 'platform-edge-floor',
|
|
230
|
+
/** Its rate-based rule, and that rule's metric name. */
|
|
231
|
+
edgeFloorRule: 'requests-per-client',
|
|
232
|
+
/**
|
|
233
|
+
* The CloudWatch alarm on the router's requests per minute (`limits.edgeFloorAt`) that turns the
|
|
234
|
+
* floor on, and the EventBridge rule that tells the control plane when it goes off.
|
|
235
|
+
*/
|
|
236
|
+
edgeFloorAlarm: 'platform-edge-floor',
|
|
153
237
|
runtimeConfigParameter: '/platform/config/runtime',
|
|
154
238
|
sessionKeyParameter: '/platform/config/session-key',
|
|
155
239
|
githubAppParameterPrefix: '/platform/config/github-app/',
|
package/src/platform-api.ts
CHANGED
|
@@ -29,27 +29,39 @@ import {
|
|
|
29
29
|
CreateDeploymentRequest,
|
|
30
30
|
CreateDeploymentResponse,
|
|
31
31
|
CronRunResponse,
|
|
32
|
+
DeadLetterAction,
|
|
33
|
+
DeadLetterActionResponse,
|
|
34
|
+
DeadLettersResponse,
|
|
35
|
+
CustomMetricsResponse,
|
|
32
36
|
DataCollections,
|
|
33
37
|
DataPage,
|
|
34
38
|
DeploymentRecord,
|
|
39
|
+
EmailSending,
|
|
40
|
+
EdgeFloorResponse,
|
|
41
|
+
EmailStatsResponse,
|
|
35
42
|
ErrorGroup,
|
|
36
43
|
ErrorStatus,
|
|
37
44
|
JobsResponse,
|
|
45
|
+
LimitsResponse,
|
|
38
46
|
LogLine,
|
|
39
47
|
LogsResponse,
|
|
40
48
|
MeResponse,
|
|
41
49
|
MetricsResponse,
|
|
42
50
|
PutSecretRequest,
|
|
43
51
|
QueueStats,
|
|
44
|
-
|
|
52
|
+
RealtimeStatsResponse,
|
|
45
53
|
RollbackRequest,
|
|
46
54
|
RollbackResponse,
|
|
47
55
|
RouteStats,
|
|
48
56
|
SecretsResponse,
|
|
57
|
+
ServiceActionResponse,
|
|
58
|
+
ServicesResponse,
|
|
49
59
|
StageDestroyed,
|
|
50
60
|
StageDestroying,
|
|
51
61
|
StageRecord,
|
|
62
|
+
StartServiceRequest,
|
|
52
63
|
StorageResponse,
|
|
64
|
+
SuppressedResponse,
|
|
53
65
|
TraceResponse,
|
|
54
66
|
UpdateAppRequest,
|
|
55
67
|
UpdateErrorRequest,
|
|
@@ -112,7 +124,10 @@ export class NotFound extends Schema.TaggedError<NotFound, { readonly brand: uni
|
|
|
112
124
|
static readonly of = (what: string) => new NotFound({ code: 'not_found', message: `${what} not found` });
|
|
113
125
|
}
|
|
114
126
|
|
|
115
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* 409: `exists`, `dns_conflict`, `has_stages`, `already_started`, `rollback_failed`,
|
|
129
|
+
* `redrive_failed`, `discard_failed`, `paused_by_aws`, `service_action_failed`.
|
|
130
|
+
*/
|
|
116
131
|
export class Conflict extends Schema.TaggedError<Conflict, { readonly brand: unique symbol }>()(
|
|
117
132
|
'Conflict',
|
|
118
133
|
errorFields,
|
|
@@ -224,13 +239,13 @@ const appStage = { app: Schema.String, stage: Schema.String };
|
|
|
224
239
|
/** `?stage=` defaults to prod; the server validates the name. */
|
|
225
240
|
const stageQuery = { stage: Schema.optional(Schema.String) };
|
|
226
241
|
/** `?range=1h|24h|7d|30d` or `?from=&to=` (epoch ms or ISO), and `?res=1m|1h|1d`. */
|
|
227
|
-
const
|
|
228
|
-
...stageQuery,
|
|
242
|
+
const timeQuery = {
|
|
229
243
|
from: Schema.optional(Schema.String),
|
|
230
244
|
to: Schema.optional(Schema.String),
|
|
231
245
|
range: Schema.optional(Schema.String),
|
|
232
246
|
res: Schema.optional(Schema.String),
|
|
233
247
|
};
|
|
248
|
+
const rangeQuery = { ...stageQuery, ...timeQuery };
|
|
234
249
|
const limit = Schema.optional(Schema.Int);
|
|
235
250
|
|
|
236
251
|
export class SessionApi extends HttpApiGroup.make('session').add(
|
|
@@ -355,6 +370,48 @@ export class ObserveApi extends HttpApiGroup.make('observe')
|
|
|
355
370
|
success: Schema.Array(QueueStats),
|
|
356
371
|
error: errors,
|
|
357
372
|
}),
|
|
373
|
+
/** The stage's dead-letter queue: every job that failed its last attempt. */
|
|
374
|
+
HttpApiEndpoint.get('deadLetters', '/apps/:app/dead-letters', {
|
|
375
|
+
params: app,
|
|
376
|
+
query: stageQuery,
|
|
377
|
+
success: DeadLettersResponse,
|
|
378
|
+
error: errors,
|
|
379
|
+
}),
|
|
380
|
+
/** AppSync Events activity of the stage's channel namespace, from CloudWatch. */
|
|
381
|
+
HttpApiEndpoint.get('realtime', '/apps/:app/realtime', {
|
|
382
|
+
params: app,
|
|
383
|
+
query: rangeQuery,
|
|
384
|
+
success: RealtimeStatsResponse,
|
|
385
|
+
error: errors,
|
|
386
|
+
}),
|
|
387
|
+
/** The stage's sender, SES sending status, today's usage, and SES counts for its tenant. */
|
|
388
|
+
HttpApiEndpoint.get('email', '/apps/:app/email', {
|
|
389
|
+
params: app,
|
|
390
|
+
query: rangeQuery,
|
|
391
|
+
success: EmailStatsResponse,
|
|
392
|
+
error: errors,
|
|
393
|
+
}),
|
|
394
|
+
/** `Metrics.count`/`value` series per name, at 1h or 1d. */
|
|
395
|
+
HttpApiEndpoint.get('customMetrics', '/apps/:app/custom-metrics', {
|
|
396
|
+
params: app,
|
|
397
|
+
query: rangeQuery,
|
|
398
|
+
success: CustomMetricsResponse,
|
|
399
|
+
error: errors,
|
|
400
|
+
}),
|
|
401
|
+
/** `RateLimits` checks per limit: allowed and denied, at 1h or 1d. */
|
|
402
|
+
HttpApiEndpoint.get('limits', '/apps/:app/limits', {
|
|
403
|
+
params: app,
|
|
404
|
+
query: rangeQuery,
|
|
405
|
+
success: LimitsResponse,
|
|
406
|
+
error: errors,
|
|
407
|
+
}),
|
|
408
|
+
/** The stage's long-running services: ECS state, CPU and memory, starts and failed runs. */
|
|
409
|
+
HttpApiEndpoint.get('services', '/apps/:app/services', {
|
|
410
|
+
params: app,
|
|
411
|
+
query: rangeQuery,
|
|
412
|
+
success: ServicesResponse,
|
|
413
|
+
error: errors,
|
|
414
|
+
}),
|
|
358
415
|
HttpApiEndpoint.get('errors', '/apps/:app/errors', {
|
|
359
416
|
params: app,
|
|
360
417
|
query: { ...stageQuery, status: Schema.optional(ErrorStatus) },
|
|
@@ -386,7 +443,8 @@ export class ObserveApi extends HttpApiGroup.make('observe')
|
|
|
386
443
|
query: {
|
|
387
444
|
...rangeQuery,
|
|
388
445
|
q: Schema.optional(Schema.String),
|
|
389
|
-
|
|
446
|
+
/** `web`, `worker` or `service:<name>`. */
|
|
447
|
+
stream: Schema.optional(Schema.String),
|
|
390
448
|
limit,
|
|
391
449
|
next: Schema.optional(Schema.String),
|
|
392
450
|
},
|
|
@@ -400,7 +458,12 @@ export class ObserveApi extends HttpApiGroup.make('observe')
|
|
|
400
458
|
*/
|
|
401
459
|
HttpApiEndpoint.get('tail', '/apps/:app/logs/tail', {
|
|
402
460
|
params: app,
|
|
403
|
-
query: {
|
|
461
|
+
query: {
|
|
462
|
+
...stageQuery,
|
|
463
|
+
q: Schema.optional(Schema.String),
|
|
464
|
+
/** `web`, `worker` or `service:<name>`. */
|
|
465
|
+
stream: Schema.optional(Schema.String),
|
|
466
|
+
},
|
|
404
467
|
success: HttpApiSchema.StreamSse({ events: TailEvent, keepAlive: '20 seconds' }),
|
|
405
468
|
error: errors,
|
|
406
469
|
}),
|
|
@@ -478,10 +541,65 @@ export class ManageApi extends HttpApiGroup.make('manage')
|
|
|
478
541
|
success: CronRunResponse.pipe(HttpApiSchema.status(202)),
|
|
479
542
|
error: errors,
|
|
480
543
|
}),
|
|
481
|
-
|
|
544
|
+
/** The stage's suppression list (its SES tenant's), in SES's order; `next` pages on. */
|
|
545
|
+
HttpApiEndpoint.get('suppressed', '/apps/:app/email/suppressed', {
|
|
546
|
+
params: app,
|
|
547
|
+
query: { ...stageQuery, next: Schema.optional(Schema.String) },
|
|
548
|
+
success: SuppressedResponse,
|
|
549
|
+
error: errors,
|
|
550
|
+
}),
|
|
551
|
+
/** Lets SES send to `address` from this stage again. */
|
|
552
|
+
HttpApiEndpoint.delete('unsuppress', '/apps/:app/email/suppressed/:address', {
|
|
553
|
+
params: { ...app, address: Schema.String },
|
|
554
|
+
query: stageQuery,
|
|
555
|
+
success: HttpApiSchema.NoContent,
|
|
556
|
+
error: errors,
|
|
557
|
+
}),
|
|
558
|
+
/** Resumes sending after a pause by the reputation policy or by hand (not one by AWS). */
|
|
559
|
+
HttpApiEndpoint.post('resumeEmail', '/apps/:app/email/resume', {
|
|
560
|
+
params: app,
|
|
561
|
+
query: stageQuery,
|
|
562
|
+
success: EmailSending,
|
|
563
|
+
error: errors,
|
|
564
|
+
}),
|
|
565
|
+
/** Replaces the service's task with a fresh one on the same build. */
|
|
566
|
+
HttpApiEndpoint.post('restartService', '/apps/:app/services/:name/restart', {
|
|
567
|
+
params: { ...app, name: Schema.String },
|
|
568
|
+
query: stageQuery,
|
|
569
|
+
success: ServiceActionResponse.pipe(HttpApiSchema.status(202)),
|
|
570
|
+
error: errors,
|
|
571
|
+
}),
|
|
572
|
+
/**
|
|
573
|
+
* Runs it (desired 1). It stops again after `minutes` when given; on
|
|
574
|
+
* previews always, by default after its `previewMinutes` (30 when that is 0).
|
|
575
|
+
*/
|
|
576
|
+
HttpApiEndpoint.post('startService', '/apps/:app/services/:name/start', {
|
|
482
577
|
params: { ...app, name: Schema.String },
|
|
483
578
|
query: stageQuery,
|
|
484
|
-
|
|
579
|
+
payload: StartServiceRequest,
|
|
580
|
+
success: ServiceActionResponse.pipe(HttpApiSchema.status(202)),
|
|
581
|
+
error: errors,
|
|
582
|
+
}),
|
|
583
|
+
/** Scales it to zero until it is started again or the stage is redeployed. */
|
|
584
|
+
HttpApiEndpoint.post('stopService', '/apps/:app/services/:name/stop', {
|
|
585
|
+
params: { ...app, name: Schema.String },
|
|
586
|
+
query: stageQuery,
|
|
587
|
+
success: ServiceActionResponse.pipe(HttpApiSchema.status(202)),
|
|
588
|
+
error: errors,
|
|
589
|
+
}),
|
|
590
|
+
/** Runs dead letters again from their first attempt, on the function their handler runs in now. */
|
|
591
|
+
HttpApiEndpoint.post('redrive', '/apps/:app/dead-letters/redrive', {
|
|
592
|
+
params: app,
|
|
593
|
+
query: stageQuery,
|
|
594
|
+
payload: DeadLetterAction,
|
|
595
|
+
success: DeadLetterActionResponse,
|
|
596
|
+
error: errors,
|
|
597
|
+
}),
|
|
598
|
+
HttpApiEndpoint.post('discard', '/apps/:app/dead-letters/discard', {
|
|
599
|
+
params: app,
|
|
600
|
+
query: stageQuery,
|
|
601
|
+
payload: DeadLetterAction,
|
|
602
|
+
success: DeadLetterActionResponse,
|
|
485
603
|
error: errors,
|
|
486
604
|
}),
|
|
487
605
|
)
|
|
@@ -489,6 +607,14 @@ export class ManageApi extends HttpApiGroup.make('manage')
|
|
|
489
607
|
|
|
490
608
|
export class AdminApi extends HttpApiGroup.make('admin')
|
|
491
609
|
.add(HttpApiEndpoint.get('overview', '/admin/overview', { success: AdminOverview, error: errors }))
|
|
610
|
+
/** The edge's per-client request floor: on or off, blocked and allowed requests, recently blocked ones. */
|
|
611
|
+
.add(
|
|
612
|
+
HttpApiEndpoint.get('edge', '/admin/edge', {
|
|
613
|
+
query: timeQuery,
|
|
614
|
+
success: EdgeFloorResponse,
|
|
615
|
+
error: errors,
|
|
616
|
+
}),
|
|
617
|
+
)
|
|
492
618
|
.middleware(Authenticated) {}
|
|
493
619
|
|
|
494
620
|
export class PlatformApi extends HttpApi.make('platform')
|
package/src/realtime.ts
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Realtime: server-to-browser pub/sub on AWS AppSync Events.
|
|
3
|
+
*
|
|
4
|
+
* - One Event API serves the platform; each stage that declares `realtime`
|
|
5
|
+
* gets a channel namespace (`names.realtimeNamespace`).
|
|
6
|
+
* - Browsers connect to `wss://<app host>/__platform/realtime`, which the edge
|
|
7
|
+
* router passes to AppSync, and subscribe there. They never publish: the
|
|
8
|
+
* stage's server and worker publish with its IAM role.
|
|
9
|
+
* - `subscribe: 'public'` stages subscribe with the platform's API key;
|
|
10
|
+
* `'signed-in'` stages with a short-lived token from the app's server
|
|
11
|
+
* (`REALTIME_TOKEN_PATH`), checked by the platform's Lambda authorizer.
|
|
12
|
+
*
|
|
13
|
+
* Everything here is isomorphic (WebCrypto, no Node imports): the SDK, the
|
|
14
|
+
* authorizer and the browser client share it.
|
|
15
|
+
*/
|
|
16
|
+
import { base64url, fromBase64url } from './base64url.ts';
|
|
17
|
+
|
|
18
|
+
/** Where browsers connect (WebSocket) and read their `RealtimeClientConfig` (GET). The router answers both. */
|
|
19
|
+
export const REALTIME_PATH = '/__platform/realtime';
|
|
20
|
+
/** Where signed-in browsers get a `RealtimeToken`; served by the SDK on the app's server. */
|
|
21
|
+
export const REALTIME_TOKEN_PATH = '/__platform/realtime/token';
|
|
22
|
+
/**
|
|
23
|
+
* Key of the platform's realtime entry (`RealtimeEdgeEntry`) in the route
|
|
24
|
+
* store. Not a hostname, so it can never collide with a route record.
|
|
25
|
+
*/
|
|
26
|
+
export const REALTIME_KVS_KEY = '__platform/realtime';
|
|
27
|
+
/** AppSync's paths on its HTTP and realtime domains. */
|
|
28
|
+
export const APPSYNC_PUBLISH_PATH = '/event';
|
|
29
|
+
export const APPSYNC_REALTIME_PATH = '/event/realtime';
|
|
30
|
+
/** Subprotocol every AppSync Events WebSocket offers (the auth header rides in a second one). */
|
|
31
|
+
export const APPSYNC_SUBPROTOCOL = 'aws-appsync-event-ws';
|
|
32
|
+
/** AppSync accepts at most this many events per publish request. */
|
|
33
|
+
export const REALTIME_PUBLISH_BATCH = 5;
|
|
34
|
+
/** AppSync rejects a single event larger than this many bytes. */
|
|
35
|
+
export const REALTIME_MAX_EVENT_BYTES = 240 * 1024;
|
|
36
|
+
|
|
37
|
+
export type RealtimeSubscribe = 'public' | 'signed-in';
|
|
38
|
+
|
|
39
|
+
// ---------------------------------------------------------------- channels
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* One segment of a channel: what AppSync allows, lowercased (a-z, 0-9,
|
|
43
|
+
* hyphens; starts and ends with a letter or digit; at most 50 chars).
|
|
44
|
+
*/
|
|
45
|
+
const SEGMENT = '[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?';
|
|
46
|
+
/**
|
|
47
|
+
* A channel as app code names it: 1-4 segments (`board`, `boards/b1`). The
|
|
48
|
+
* stage's namespace is AppSync's first segment and AppSync allows five.
|
|
49
|
+
*/
|
|
50
|
+
export const CHANNEL_PATTERN = new RegExp(`^${SEGMENT}(?:/${SEGMENT}){0,3}$`);
|
|
51
|
+
/** A declared channel in `plat.config.ts`: a channel, or a prefix of 1-3 segments ending in `/*`. */
|
|
52
|
+
export const CHANNEL_DECLARATION_PATTERN = new RegExp(
|
|
53
|
+
`^${SEGMENT}(?:/${SEGMENT}){0,3}$|^${SEGMENT}(?:/${SEGMENT}){0,2}/\\*$`,
|
|
54
|
+
);
|
|
55
|
+
export const CHANNEL_MESSAGE =
|
|
56
|
+
'must be 1-4 segments of a-z, 0-9 and hyphens separated by "/", optionally ending in "/*"';
|
|
57
|
+
/**
|
|
58
|
+
* Channels under `user/<id>` are private to the signed-in user with that id;
|
|
59
|
+
* they can only be declared as `user/*`, and only with `subscribe: 'signed-in'`.
|
|
60
|
+
*/
|
|
61
|
+
export const USER_CHANNEL_PREFIX = 'user';
|
|
62
|
+
|
|
63
|
+
/** Whether `channel` (or a wildcard subscription like `boards/*`) falls under the declared `pattern`. */
|
|
64
|
+
export function channelMatches(pattern: string, channel: string): boolean {
|
|
65
|
+
if (!pattern.endsWith('/*')) return pattern === channel;
|
|
66
|
+
const prefix = pattern.slice(0, -1); // keeps the trailing "/"
|
|
67
|
+
return channel.startsWith(prefix) && channel.length > prefix.length;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The declared pattern a channel (or wildcard subscription) belongs to, if any. */
|
|
71
|
+
export function declaredChannel(patterns: readonly string[], channel: string): string | undefined {
|
|
72
|
+
return patterns.find((p) => channelMatches(p, channel));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A channel app code may publish to: concrete (no wildcard) and well formed. */
|
|
76
|
+
export function isChannel(channel: string): boolean {
|
|
77
|
+
return CHANNEL_PATTERN.test(channel);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A channel a browser may subscribe to: a channel, or a declared-style `prefix/*` wildcard. */
|
|
81
|
+
export function isSubscription(channel: string): boolean {
|
|
82
|
+
return CHANNEL_DECLARATION_PATTERN.test(channel);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** AppSync's channel path for an app channel: `/<namespace>/<channel>`. */
|
|
86
|
+
export function channelPath(namespace: string, channel: string): string {
|
|
87
|
+
return `/${namespace}/${channel}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The app channel inside an AppSync channel path, or undefined if it's in another namespace. */
|
|
91
|
+
export function appChannel(namespace: string, path: string): string | undefined {
|
|
92
|
+
const prefix = `/${namespace}/`;
|
|
93
|
+
return path.startsWith(prefix) ? path.slice(prefix.length) : undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Problems with a stage's realtime declaration, as messages for the
|
|
98
|
+
* `realtime` path of `plat.config.ts`. Shared by manifest validation and tests.
|
|
99
|
+
*/
|
|
100
|
+
export function realtimeIssues(r: {
|
|
101
|
+
subscribe: RealtimeSubscribe;
|
|
102
|
+
channels: readonly string[];
|
|
103
|
+
auth: boolean;
|
|
104
|
+
server: boolean;
|
|
105
|
+
}): Array<{ path: string[]; message: string }> {
|
|
106
|
+
const issues: Array<{ path: string[]; message: string }> = [];
|
|
107
|
+
if (r.channels.length === 0)
|
|
108
|
+
issues.push({ path: ['channels'], message: 'declare at least one channel, e.g. `board: channel<T>()`' });
|
|
109
|
+
if (r.subscribe === 'signed-in' && !r.auth)
|
|
110
|
+
issues.push({ path: ['subscribe'], message: "'signed-in' needs `auth: true`" });
|
|
111
|
+
if (r.subscribe === 'signed-in' && !r.server)
|
|
112
|
+
issues.push({
|
|
113
|
+
path: ['subscribe'],
|
|
114
|
+
message: "'signed-in' needs `web.server`: it issues the subscribe tokens",
|
|
115
|
+
});
|
|
116
|
+
for (const c of r.channels) {
|
|
117
|
+
const first = c.split('/')[0];
|
|
118
|
+
if (first !== USER_CHANNEL_PREFIX) continue;
|
|
119
|
+
if (c !== `${USER_CHANNEL_PREFIX}/*`)
|
|
120
|
+
issues.push({
|
|
121
|
+
path: ['channels', c],
|
|
122
|
+
message: `"${USER_CHANNEL_PREFIX}" channels are private to one user: declare them as "${USER_CHANNEL_PREFIX}/*"`,
|
|
123
|
+
});
|
|
124
|
+
else if (r.subscribe !== 'signed-in')
|
|
125
|
+
issues.push({
|
|
126
|
+
path: ['channels', c],
|
|
127
|
+
message: `"${USER_CHANNEL_PREFIX}/*" channels are private to one user, so they need subscribe: 'signed-in'`,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return issues;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Whether a signed-in user may subscribe to an app channel (or wildcard).
|
|
135
|
+
* Channels under `user/<id>` belong to that user alone; a wildcard that could
|
|
136
|
+
* reach another user's channels (`*`, `user/*`) is refused. Every other
|
|
137
|
+
* channel is open to any signed-in user of the app.
|
|
138
|
+
*/
|
|
139
|
+
export function canSubscribe(userId: string, channel: string): boolean {
|
|
140
|
+
if (!isSubscription(channel)) return false;
|
|
141
|
+
const [first, second] = channel.split('/');
|
|
142
|
+
if (first !== USER_CHANNEL_PREFIX) return true;
|
|
143
|
+
return second === userId;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------- wire formats
|
|
147
|
+
|
|
148
|
+
/** What the router answers at `REALTIME_PATH` (GET): how a browser connects and subscribes. */
|
|
149
|
+
export interface RealtimeClientConfig {
|
|
150
|
+
v: 1;
|
|
151
|
+
/** AppSync's HTTP domain. Every connection and subscription must name it as `host`. */
|
|
152
|
+
host: string;
|
|
153
|
+
/** The stage's channel namespace; AppSync channels are `/<namespace>/<channel>`. */
|
|
154
|
+
namespace: string;
|
|
155
|
+
subscribe: RealtimeSubscribe;
|
|
156
|
+
/** For `public`: the platform's subscribe-only API key. */
|
|
157
|
+
apiKey?: string;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What the SDK answers at `REALTIME_TOKEN_PATH` for a signed-in user. */
|
|
161
|
+
export interface RealtimeToken {
|
|
162
|
+
token: string;
|
|
163
|
+
/** Epoch milliseconds. */
|
|
164
|
+
expiresAt: number;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The platform entry in the route store (`REALTIME_KVS_KEY`), written by the
|
|
169
|
+
* control plane: where AppSync is, and the public API key. One entry for every
|
|
170
|
+
* stage, so a replaced key reaches every app at once.
|
|
171
|
+
*/
|
|
172
|
+
export interface RealtimeEdgeEntry {
|
|
173
|
+
v: 1;
|
|
174
|
+
/** Realtime domain (the WebSocket origin). */
|
|
175
|
+
o: string;
|
|
176
|
+
/** HTTP domain (the `host` browsers name). */
|
|
177
|
+
h: string;
|
|
178
|
+
/** Subscribe-only API key for `public` stages. */
|
|
179
|
+
k: string;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ---------------------------------------------------------------- tokens
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Claims of a subscribe token. Short keys: the token rides in the WebSocket
|
|
186
|
+
* subprotocol header and in every subscribe message.
|
|
187
|
+
*/
|
|
188
|
+
export interface RealtimeClaims {
|
|
189
|
+
/** App and stage: the authorizer finds the stage key and namespace from them. */
|
|
190
|
+
a: string;
|
|
191
|
+
s: string;
|
|
192
|
+
/** User id. */
|
|
193
|
+
u: string;
|
|
194
|
+
/** Expiry, epoch seconds. */
|
|
195
|
+
e: number;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const TOKEN_PREFIX = 'pt1';
|
|
199
|
+
/** Lets AppSync refuse malformed tokens before invoking the authorizer (`identityValidationExpression`). */
|
|
200
|
+
export const REALTIME_TOKEN_PATTERN = '^pt1\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$';
|
|
201
|
+
/** How long a subscribe token lasts. Open subscriptions outlive it; new ones need a fresh token. */
|
|
202
|
+
export const REALTIME_TOKEN_TTL_SECONDS = 15 * 60;
|
|
203
|
+
const HKDF_INFO = 'platform:realtime-token:v1';
|
|
204
|
+
|
|
205
|
+
const encoder = new TextEncoder();
|
|
206
|
+
|
|
207
|
+
/** The HMAC key for a stage's tokens, derived from its stage key (base64url) with HKDF. */
|
|
208
|
+
async function tokenKey(stageKey: string) {
|
|
209
|
+
const raw = await crypto.subtle.importKey('raw', fromBase64url(stageKey), 'HKDF', false, ['deriveKey']);
|
|
210
|
+
return crypto.subtle.deriveKey(
|
|
211
|
+
{ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: encoder.encode(HKDF_INFO) },
|
|
212
|
+
raw,
|
|
213
|
+
{ name: 'HMAC', hash: 'SHA-256', length: 256 },
|
|
214
|
+
false,
|
|
215
|
+
['sign', 'verify'],
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A signed subscribe token: `pt1.<claims>.<HMAC-SHA256>`, all base64url. */
|
|
220
|
+
export async function signRealtimeToken(stageKey: string, claims: RealtimeClaims): Promise<string> {
|
|
221
|
+
const body = `${TOKEN_PREFIX}.${base64url(encoder.encode(JSON.stringify(claims)))}`;
|
|
222
|
+
const sig = await crypto.subtle.sign('HMAC', await tokenKey(stageKey), encoder.encode(body));
|
|
223
|
+
return `${body}.${base64url(new Uint8Array(sig))}`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The claims of a token, unverified: the authorizer needs `a` and `s` to find
|
|
228
|
+
* the stage key it then verifies with. Undefined when malformed.
|
|
229
|
+
*/
|
|
230
|
+
export function peekRealtimeToken(token: string): RealtimeClaims | undefined {
|
|
231
|
+
const parts = token.split('.');
|
|
232
|
+
if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return undefined;
|
|
233
|
+
try {
|
|
234
|
+
const c = JSON.parse(new TextDecoder().decode(fromBase64url(parts[1]!))) as Partial<RealtimeClaims>;
|
|
235
|
+
if (
|
|
236
|
+
typeof c.a !== 'string' ||
|
|
237
|
+
typeof c.s !== 'string' ||
|
|
238
|
+
typeof c.u !== 'string' ||
|
|
239
|
+
typeof c.e !== 'number'
|
|
240
|
+
)
|
|
241
|
+
return undefined;
|
|
242
|
+
return { a: c.a, s: c.s, u: c.u, e: c.e };
|
|
243
|
+
} catch {
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** The claims, if the signature is the stage key's and the token hasn't expired. */
|
|
249
|
+
export async function verifyRealtimeToken(
|
|
250
|
+
stageKey: string,
|
|
251
|
+
token: string,
|
|
252
|
+
nowSeconds: number,
|
|
253
|
+
): Promise<RealtimeClaims | undefined> {
|
|
254
|
+
const claims = peekRealtimeToken(token);
|
|
255
|
+
if (!claims || claims.e <= nowSeconds) return undefined;
|
|
256
|
+
const dot = token.lastIndexOf('.');
|
|
257
|
+
let sig: Uint8Array<ArrayBuffer>;
|
|
258
|
+
try {
|
|
259
|
+
sig = fromBase64url(token.slice(dot + 1));
|
|
260
|
+
} catch {
|
|
261
|
+
return undefined;
|
|
262
|
+
}
|
|
263
|
+
const ok = await crypto.subtle.verify(
|
|
264
|
+
'HMAC',
|
|
265
|
+
await tokenKey(stageKey),
|
|
266
|
+
sig,
|
|
267
|
+
encoder.encode(token.slice(0, dot)),
|
|
268
|
+
);
|
|
269
|
+
return ok ? claims : undefined;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ---------------------------------------------------------------- authorizer
|
|
273
|
+
|
|
274
|
+
export type RealtimeOperation = 'EVENT_CONNECT' | 'EVENT_SUBSCRIBE' | 'EVENT_PUBLISH';
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* The authorizer's decision for a verified token (pure, so it's unit-tested
|
|
278
|
+
* here and the Lambda only adds SSM and AppSync plumbing).
|
|
279
|
+
*
|
|
280
|
+
* - Connect: any valid token.
|
|
281
|
+
* - Subscribe: the stage's own namespace, and `canSubscribe`.
|
|
282
|
+
* - Publish: never; browsers only subscribe (servers publish with IAM).
|
|
283
|
+
*/
|
|
284
|
+
export function authorizeRealtime(input: {
|
|
285
|
+
operation: RealtimeOperation;
|
|
286
|
+
claims: RealtimeClaims;
|
|
287
|
+
/** The namespace the token's stage owns (`names.realtimeNamespace(a, s)`). */
|
|
288
|
+
namespace: string;
|
|
289
|
+
/** AppSync's request: namespace name and channel path (null on connect). */
|
|
290
|
+
channelNamespace: string | null;
|
|
291
|
+
channel: string | null;
|
|
292
|
+
}): boolean {
|
|
293
|
+
if (input.operation === 'EVENT_CONNECT') return true;
|
|
294
|
+
if (input.operation !== 'EVENT_SUBSCRIBE') return false;
|
|
295
|
+
if (input.channelNamespace !== input.namespace || !input.channel) return false;
|
|
296
|
+
const channel = appChannel(input.namespace, input.channel);
|
|
297
|
+
return channel !== undefined && canSubscribe(input.claims.u, channel);
|
|
298
|
+
}
|
package/src/router/decide.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ export type RouteDecision =
|
|
|
4
4
|
| { t: 'server' }
|
|
5
5
|
| { t: 'static'; key: string }
|
|
6
6
|
| { t: 'health' }
|
|
7
|
+
| { t: 'realtime' }
|
|
8
|
+
| { t: 'storage'; key: string }
|
|
7
9
|
| { t: 'notfound' };
|
|
8
10
|
|
|
9
11
|
export declare function decide(rec: RouteRecord | null | undefined, uri: string): RouteDecision;
|