@ericminassian/platform-core 0.2.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 +1847 -212
- package/dist/api.js +694 -1
- package/dist/api.js.map +1 -1
- package/dist/auth.d.ts +19 -0
- package/dist/auth.js +32 -0
- 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 +69 -13
- 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 +70 -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 +21 -1
- package/dist/config.js +16 -0
- package/dist/config.js.map +1 -1
- package/dist/constants.d.ts +67 -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 +357 -112
- package/dist/manifest.js +270 -72
- package/dist/manifest.js.map +1 -1
- package/dist/naming.d.ts +93 -6
- package/dist/naming.js +98 -6
- package/dist/naming.js.map +1 -1
- package/dist/platform-api.d.ts +7792 -0
- package/dist/platform-api.js +455 -0
- package/dist/platform-api.js.map +1 -0
- 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 +7 -1
- package/dist/router/decide.js +42 -5
- 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 +350 -83
- package/dist/telemetry.js +188 -15
- 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 +28 -8
- package/src/api.ts +864 -238
- package/src/auth.ts +37 -0
- package/src/base64url.ts +13 -0
- package/src/bindings.ts +74 -7
- package/src/cloudfront-function.ts +70 -2
- package/src/compute.ts +86 -0
- package/src/config.ts +34 -2
- package/src/constants.ts +76 -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 +542 -114
- package/src/naming.ts +103 -8
- package/src/platform-api.ts +630 -0
- package/src/realtime.ts +298 -0
- package/src/router/decide.d.ts +7 -1
- package/src/router/decide.js +42 -5
- package/src/router.ts +33 -13
- package/src/runtime-config.ts +70 -0
- package/src/storage.ts +120 -0
- package/src/telemetry.ts +198 -93
- package/src/web-compute.ts +342 -0
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
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import type { RouteRecord } from '../router.ts';
|
|
2
2
|
|
|
3
|
-
export type RouteDecision =
|
|
3
|
+
export type RouteDecision =
|
|
4
|
+
| { t: 'server' }
|
|
5
|
+
| { t: 'static'; key: string }
|
|
6
|
+
| { t: 'health' }
|
|
7
|
+
| { t: 'realtime' }
|
|
8
|
+
| { t: 'storage'; key: string }
|
|
9
|
+
| { t: 'notfound' };
|
|
4
10
|
|
|
5
11
|
export declare function decide(rec: RouteRecord | null | undefined, uri: string): RouteDecision;
|
package/src/router/decide.js
CHANGED
|
@@ -5,16 +5,34 @@
|
|
|
5
5
|
// when inlined.
|
|
6
6
|
//
|
|
7
7
|
// rec: route record from the KeyValueStore (see RouteRecord in router.ts)
|
|
8
|
-
// o - Web Function endpoint
|
|
8
|
+
// o - the server's domain, optional: a Web Function endpoint, or a function URL when c is 'r'
|
|
9
|
+
// (request mode). Which one only changes how the CloudFront Function calls it (OAC, or
|
|
10
|
+
// the origin secret k in a header); `plat dev` runs the server itself.
|
|
9
11
|
// s - static key prefix in the sites bucket, e.g. "foo/prod/d01j..." , optional
|
|
10
12
|
// r - server route prefixes when both o and s exist, e.g. ["/api/"]
|
|
11
13
|
// spa - 1 to serve index.html for unknown non-file paths
|
|
12
|
-
//
|
|
14
|
+
// rt - realtime: { n: channel namespace, m: 'p' | 's' }, optional
|
|
15
|
+
// p - public store names, optional
|
|
16
|
+
// returns { t: 'server' } | { t: 'static', key: '/<prefix>/<path>' } | { t: 'health' } | { t: 'realtime' }
|
|
17
|
+
// | { t: 'storage', key: '/<app>/<stage>/<store>/<key>' } | { t: 'notfound' }
|
|
18
|
+
// health - the router answers /__platform/health itself (HealthResponse with rec.d as the
|
|
19
|
+
// revision): a stage without a server has nothing else to report what it serves.
|
|
20
|
+
// realtime - /__platform/realtime is the router's own: it answers the browser's config, or passes
|
|
21
|
+
// a WebSocket to AppSync. Other /__platform/realtime/* paths (the token) are the server's.
|
|
22
|
+
// storage - /__platform/storage/<store>/<key> of a public store, served from the storage bucket
|
|
23
|
+
// (whose origin path adds `_public`); every other path below /__platform/storage/ is
|
|
24
|
+
// not found, so it never reaches the server. The key stays percent-encoded, as S3
|
|
25
|
+
// decodes it, and keys with `.` or `..` segments (also encoded) are refused.
|
|
13
26
|
|
|
14
27
|
export function decide(rec, uri) {
|
|
15
|
-
if (!rec || (!rec.o && !rec.s)) return { t: 'notfound' };
|
|
16
|
-
if (uri.indexOf('/__platform/') === 0)
|
|
17
|
-
|
|
28
|
+
if (!rec || (!rec.o && !rec.s && !rec.p)) return { t: 'notfound' };
|
|
29
|
+
if (uri.indexOf('/__platform/') === 0) {
|
|
30
|
+
if (uri.indexOf('/__platform/storage/') === 0) return storage(rec, uri.substring(20));
|
|
31
|
+
if (uri === '/__platform/realtime' && rec.rt) return { t: 'realtime' };
|
|
32
|
+
if (rec.o) return { t: 'server' };
|
|
33
|
+
return uri === '/__platform/health' ? { t: 'health' } : { t: 'notfound' };
|
|
34
|
+
}
|
|
35
|
+
if (!rec.s) return rec.o ? { t: 'server' } : { t: 'notfound' };
|
|
18
36
|
if (rec.o) {
|
|
19
37
|
var routes = rec.r || [];
|
|
20
38
|
for (var i = 0; i < routes.length; i++) {
|
|
@@ -30,3 +48,22 @@ export function decide(rec, uri) {
|
|
|
30
48
|
var dir = uri.charAt(uri.length - 1) === '/' ? uri : uri + '/';
|
|
31
49
|
return { t: 'static', key: '/' + rec.s + dir + 'index.html' };
|
|
32
50
|
}
|
|
51
|
+
|
|
52
|
+
function storage(rec, rest) {
|
|
53
|
+
var slash = rest.indexOf('/');
|
|
54
|
+
if (slash <= 0) return { t: 'notfound' };
|
|
55
|
+
var store = rest.substring(0, slash);
|
|
56
|
+
var key = rest.substring(slash + 1);
|
|
57
|
+
if (!rec.p || rec.p.indexOf(store) === -1 || !servableKey(key)) return { t: 'notfound' };
|
|
58
|
+
return { t: 'storage', key: '/' + rec.app + '/' + rec.stage + '/' + store + '/' + key };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// isServableKey in storage.ts. S3 decodes the key once, so an encoded dot or slash counts as one.
|
|
62
|
+
function servableKey(key) {
|
|
63
|
+
if (!key) return false;
|
|
64
|
+
var parts = key.replace(/%2e/gi, '.').replace(/%2f/gi, '/').split('/');
|
|
65
|
+
for (var i = 0; i < parts.length; i++) {
|
|
66
|
+
if (parts[i] === '.' || parts[i] === '..') return false;
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
}
|
package/src/router.ts
CHANGED
|
@@ -1,24 +1,44 @@
|
|
|
1
|
+
import { Schema } from 'effect';
|
|
2
|
+
|
|
1
3
|
export type { RouteDecision } from './router/decide.js';
|
|
2
4
|
export { decide } from './router/decide.js';
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
|
-
* Value stored in the CloudFront KeyValueStore under the public hostname
|
|
6
|
-
* Keys are short because KVS values
|
|
7
|
+
* Value stored in the CloudFront KeyValueStore under the public hostname, and
|
|
8
|
+
* kept with each deployment for rollbacks. Keys are short because KVS values
|
|
9
|
+
* are capped at 1 KB.
|
|
7
10
|
*/
|
|
8
|
-
export
|
|
9
|
-
v: 1
|
|
10
|
-
app:
|
|
11
|
-
stage:
|
|
11
|
+
export const RouteRecordSchema = Schema.Struct({
|
|
12
|
+
v: Schema.Literal(1),
|
|
13
|
+
app: Schema.String,
|
|
14
|
+
stage: Schema.String,
|
|
12
15
|
/** Deployment id currently live. */
|
|
13
|
-
d:
|
|
14
|
-
/** Web Function endpoint
|
|
15
|
-
o
|
|
16
|
+
d: Schema.String,
|
|
17
|
+
/** The server's domain: a Web Function endpoint's, or with `c` a function URL's. */
|
|
18
|
+
o: Schema.optional(Schema.String),
|
|
19
|
+
/**
|
|
20
|
+
* `r`: `o` is a request-mode server (a function URL, `WebCompute`
|
|
21
|
+
* `request`), which the router calls without OAC, sending `k` in
|
|
22
|
+
* `ORIGIN_HEADER`. Absent: a Web Function endpoint, called with OAC.
|
|
23
|
+
*/
|
|
24
|
+
c: Schema.optional(Schema.Literal('r')),
|
|
25
|
+
/** The request-mode server's `originSecret`. */
|
|
26
|
+
k: Schema.optional(Schema.String),
|
|
16
27
|
/** Static prefix in the sites bucket (no leading slash). */
|
|
17
|
-
s
|
|
28
|
+
s: Schema.optional(Schema.String),
|
|
18
29
|
/** Server route prefixes (only meaningful when both `o` and `s` exist). */
|
|
19
|
-
r
|
|
20
|
-
spa
|
|
21
|
-
|
|
30
|
+
r: Schema.optional(Schema.Array(Schema.String)),
|
|
31
|
+
spa: Schema.optional(Schema.Literals([0, 1])),
|
|
32
|
+
/**
|
|
33
|
+
* Realtime (`plat.config.ts` `realtime`): the stage's channel namespace and
|
|
34
|
+
* who subscribes (`p` public with the API key, `s` signed-in with a token).
|
|
35
|
+
* The router answers `REALTIME_PATH` only for records that have it.
|
|
36
|
+
*/
|
|
37
|
+
rt: Schema.optional(Schema.Struct({ n: Schema.String, m: Schema.Literals(['p', 's']) })),
|
|
38
|
+
/** Public stores, which the router serves from the storage bucket at `STORAGE_PATH`. */
|
|
39
|
+
p: Schema.optional(Schema.Array(Schema.String)),
|
|
40
|
+
});
|
|
41
|
+
export type RouteRecord = typeof RouteRecordSchema.Type;
|
|
22
42
|
|
|
23
43
|
export function encodeRouteRecord(rec: RouteRecord): string {
|
|
24
44
|
const json = JSON.stringify(rec);
|
package/src/runtime-config.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { APPSYNC_PUBLISH_PATH, APPSYNC_REALTIME_PATH } from './realtime.ts';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* What the foundation produced: shared resources every stage deploy needs.
|
|
3
5
|
* Stored as JSON in SSM at `platformNames.runtimeConfigParameter` by the
|
|
@@ -26,6 +28,8 @@ export interface PlatformRuntimeConfig {
|
|
|
26
28
|
kvsArn?: string;
|
|
27
29
|
/** The router distribution; Web Function resource policies trust only this. */
|
|
28
30
|
distributionArn?: string;
|
|
31
|
+
/** The edge floor's alarm and trigger; absent without `limits.edgeFloorAt`. */
|
|
32
|
+
edgeFloor?: EdgeFloorRuntimeConfig;
|
|
29
33
|
/** Shared Cognito user pool for app end users. */
|
|
30
34
|
userPoolId?: string;
|
|
31
35
|
/** Hosted login origin, e.g. `https://login.platform.ericminassian.com`. */
|
|
@@ -36,6 +40,72 @@ export interface PlatformRuntimeConfig {
|
|
|
36
40
|
alertsTopicArn?: string;
|
|
37
41
|
/** Telemetry processor (account-level log subscription target). */
|
|
38
42
|
telemetryFunctionArn?: string;
|
|
43
|
+
/** The AppSync Event API stages' channel namespaces live in (absent on platforms that predate it). */
|
|
44
|
+
realtime?: RealtimeRuntimeConfig;
|
|
45
|
+
/** The SES domain every stage sends from (absent on platforms that predate email). */
|
|
46
|
+
email?: EmailRuntimeConfig;
|
|
47
|
+
/** Container compute, ECS on Fargate (absent on platforms that predate it). */
|
|
48
|
+
containers?: ContainersRuntimeConfig;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Where containers run. Tasks get a public IPv4 address in a public subnet
|
|
53
|
+
* (there is no NAT gateway) and accept no inbound traffic.
|
|
54
|
+
*/
|
|
55
|
+
export interface ContainersRuntimeConfig {
|
|
56
|
+
/** ECS cluster name. */
|
|
57
|
+
cluster: string;
|
|
58
|
+
subnets: string[];
|
|
59
|
+
securityGroups: string[];
|
|
60
|
+
/** ECR repository name. */
|
|
61
|
+
repository: string;
|
|
62
|
+
/** `<account>.dkr.ecr.<region>.amazonaws.com/<repository>`. */
|
|
63
|
+
repositoryUri: string;
|
|
64
|
+
/** Pulls images and writes container logs. */
|
|
65
|
+
executionRoleArn: string;
|
|
66
|
+
/** Assumed by EventBridge Scheduler to scale a stage's services (preview stop schedules). */
|
|
67
|
+
schedulerRoleArn: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The edge floor (`limits.edgeFloorAt`): a CloudWatch alarm on the router
|
|
72
|
+
* distribution's requests per minute, and an EventBridge rule that invokes
|
|
73
|
+
* the control plane's worker when it goes off. The web ACL itself belongs to
|
|
74
|
+
* the control plane, which creates it only while the floor is on.
|
|
75
|
+
*/
|
|
76
|
+
export interface EdgeFloorRuntimeConfig {
|
|
77
|
+
alarmArn: string;
|
|
78
|
+
/** The rule's ARN, which the worker's resource policy names. */
|
|
79
|
+
ruleArn: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface EmailRuntimeConfig {
|
|
83
|
+
/** Verified domain identity: `mail.<zone>` (`mail.localhost` in the emulator). */
|
|
84
|
+
domain: string;
|
|
85
|
+
identityArn: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface RealtimeRuntimeConfig {
|
|
89
|
+
apiId: string;
|
|
90
|
+
/** HTTP domain (`<id>.appsync-api.<region>.amazonaws.com`; `127.0.0.1:<port>` in the emulator). */
|
|
91
|
+
httpDomain: string;
|
|
92
|
+
/** Realtime (WebSocket) domain. */
|
|
93
|
+
realtimeDomain: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Where to publish and connect. AWS serves TLS; the emulator serves plain
|
|
98
|
+
* HTTP and WebSocket on local ports.
|
|
99
|
+
*/
|
|
100
|
+
export function realtimeEndpoints(
|
|
101
|
+
cfg: Pick<PlatformRuntimeConfig, 'target'>,
|
|
102
|
+
rt: RealtimeRuntimeConfig,
|
|
103
|
+
): { publishUrl: string; websocketUrl: string } {
|
|
104
|
+
const tls = cfg.target === 'aws';
|
|
105
|
+
return {
|
|
106
|
+
publishUrl: `${tls ? 'https' : 'http'}://${rt.httpDomain}${APPSYNC_PUBLISH_PATH}`,
|
|
107
|
+
websocketUrl: `${tls ? 'wss' : 'ws'}://${rt.realtimeDomain}${APPSYNC_REALTIME_PATH}`,
|
|
108
|
+
};
|
|
39
109
|
}
|
|
40
110
|
|
|
41
111
|
export function cognitoIssuer(region: string, userPoolId: string): string {
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File stores (`storage` in `plat.config.ts`). Every stage's stores share the
|
|
3
|
+
* platform's storage bucket:
|
|
4
|
+
*
|
|
5
|
+
* - a private store is `<app>/<stage>/<store>/` (`names.storagePrefix`);
|
|
6
|
+
* browsers reach its files only through presigned URLs;
|
|
7
|
+
* - a public store is `_public/<app>/<stage>/<store>/`, which the edge serves
|
|
8
|
+
* at `/__platform/storage/<store>/<key>` on the app's own host. The router
|
|
9
|
+
* distribution may read `_public/*` and nothing else, so a routing mistake
|
|
10
|
+
* can't expose a private store. `_` can't start an app name, so no app's
|
|
11
|
+
* prefix collides with it.
|
|
12
|
+
*
|
|
13
|
+
* Isomorphic: the SDK, its browser client, the CLI and the engine share it.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Where the edge serves public stores on every app host: `/__platform/storage/<store>/<key>`. */
|
|
17
|
+
export const STORAGE_PATH = '/__platform/storage/';
|
|
18
|
+
|
|
19
|
+
/** Top-level prefix of public stores in the storage bucket. */
|
|
20
|
+
export const PUBLIC_STORAGE_ROOT = '_public/';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Headers the edge adds to every public-store response (the router
|
|
24
|
+
* distribution's response headers policy; `plat dev` sends the same).
|
|
25
|
+
* `script-src 'none'` keeps an uploaded HTML or SVG file from running script
|
|
26
|
+
* on the app's origin, where its session cookie lives (`sandbox` would also
|
|
27
|
+
* stop PDFs from opening in Chrome).
|
|
28
|
+
*/
|
|
29
|
+
export const STORAGE_RESPONSE_HEADERS = {
|
|
30
|
+
'x-content-type-options': 'nosniff',
|
|
31
|
+
'content-security-policy': "script-src 'none'",
|
|
32
|
+
} as const;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The router's `x-platform-host` for a public store's file, in place of the
|
|
36
|
+
* host. CloudFront's cache key is the rewritten URI plus that header, not the
|
|
37
|
+
* behavior or origin, and an app's server could be asked for the same path
|
|
38
|
+
* (`/<app>/<stage>/<store>/<key>`) on the app's host: with the host in both,
|
|
39
|
+
* its response would be served for the file, and the file for that path. No
|
|
40
|
+
* routed host has this value.
|
|
41
|
+
*/
|
|
42
|
+
export const STORAGE_CACHE_HOST = '__storage';
|
|
43
|
+
|
|
44
|
+
/** `Cache-Control` the edge adds to a public file that carries none: browsers revalidate it. */
|
|
45
|
+
export const STORAGE_DEFAULT_CACHE_CONTROL = 'no-cache';
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Whether the edge serves `key` (as it appears in a URL path, so still
|
|
49
|
+
* percent-encoded): not empty, and without `.` or `..` segments. S3 decodes
|
|
50
|
+
* the key once, so `%2e` counts as a dot and `%2f` as a slash. The router
|
|
51
|
+
* inlines the same check (`router/decide.js`).
|
|
52
|
+
*/
|
|
53
|
+
export function isServableKey(key: string): boolean {
|
|
54
|
+
if (!key) return false;
|
|
55
|
+
return key
|
|
56
|
+
.replace(/%2e/gi, '.')
|
|
57
|
+
.replace(/%2f/gi, '/')
|
|
58
|
+
.split('/')
|
|
59
|
+
.every((part) => part !== '.' && part !== '..');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The path the edge serves a public store's file at, with each key segment
|
|
64
|
+
* percent-encoded: `storagePath('snapshots', 'fires/today 1.json')` →
|
|
65
|
+
* `/__platform/storage/snapshots/fires/today%201.json`.
|
|
66
|
+
*/
|
|
67
|
+
export function storagePath(store: string, key: string): string {
|
|
68
|
+
const k = key.replace(/^\/+/, '');
|
|
69
|
+
const path = k.split('/').map(encodeURIComponent).join('/');
|
|
70
|
+
if (!isServableKey(path)) throw new Error(`Storage key "${key}" can't be served from the edge`);
|
|
71
|
+
return `${STORAGE_PATH}${store}/${path}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Content types by file extension: static files, and store files put without one. */
|
|
75
|
+
const CONTENT_TYPES: Record<string, string> = {
|
|
76
|
+
html: 'text/html; charset=utf-8',
|
|
77
|
+
htm: 'text/html; charset=utf-8',
|
|
78
|
+
css: 'text/css; charset=utf-8',
|
|
79
|
+
js: 'text/javascript; charset=utf-8',
|
|
80
|
+
mjs: 'text/javascript; charset=utf-8',
|
|
81
|
+
cjs: 'text/javascript; charset=utf-8',
|
|
82
|
+
map: 'application/json; charset=utf-8',
|
|
83
|
+
json: 'application/json; charset=utf-8',
|
|
84
|
+
geojson: 'application/geo+json',
|
|
85
|
+
ndjson: 'application/x-ndjson',
|
|
86
|
+
webmanifest: 'application/manifest+json',
|
|
87
|
+
txt: 'text/plain; charset=utf-8',
|
|
88
|
+
csv: 'text/csv; charset=utf-8',
|
|
89
|
+
md: 'text/markdown; charset=utf-8',
|
|
90
|
+
xml: 'application/xml; charset=utf-8',
|
|
91
|
+
svg: 'image/svg+xml',
|
|
92
|
+
png: 'image/png',
|
|
93
|
+
jpg: 'image/jpeg',
|
|
94
|
+
jpeg: 'image/jpeg',
|
|
95
|
+
gif: 'image/gif',
|
|
96
|
+
webp: 'image/webp',
|
|
97
|
+
avif: 'image/avif',
|
|
98
|
+
ico: 'image/x-icon',
|
|
99
|
+
woff: 'font/woff',
|
|
100
|
+
woff2: 'font/woff2',
|
|
101
|
+
ttf: 'font/ttf',
|
|
102
|
+
otf: 'font/otf',
|
|
103
|
+
wasm: 'application/wasm',
|
|
104
|
+
pdf: 'application/pdf',
|
|
105
|
+
zip: 'application/zip',
|
|
106
|
+
gz: 'application/gzip',
|
|
107
|
+
mp4: 'video/mp4',
|
|
108
|
+
webm: 'video/webm',
|
|
109
|
+
mp3: 'audio/mpeg',
|
|
110
|
+
wav: 'audio/wav',
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/** The content type for a file name (or key), `application/octet-stream` when the extension is unknown. */
|
|
114
|
+
export function contentTypeFor(path: string): string {
|
|
115
|
+
const file = path.slice(path.lastIndexOf('/') + 1);
|
|
116
|
+
const dot = file.lastIndexOf('.');
|
|
117
|
+
return (
|
|
118
|
+
(dot === -1 ? undefined : CONTENT_TYPES[file.slice(dot + 1).toLowerCase()]) ?? 'application/octet-stream'
|
|
119
|
+
);
|
|
120
|
+
}
|