@grovemotorco/manifold 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/listen.js ADDED
@@ -0,0 +1,566 @@
1
+ import { E as sha256Hex, N as utf8Encode, O as toBase64, k as toBase64Url, l as fromBase64, t as matchesEventTypes, v as randomBytes } from "./filter-DQnhobby.js";
2
+ import { B as LIMITS, Bt as TargetLabel, G as ListenerSessionId, It as SourceKey, Q as Millis, W as ListenerName, Xt as LOCAL_ID_PREFIX, Y as LocalId, _t as RequestRecord, gt as RequestId, h as Count, nn as isLocalId, on as newLocalId, q as LocalAttemptKind, vt as RequestStatus, w as EventTypeGlob, wt as RouteId, z as KiB } from "./domain-Dye3ZdC_.js";
3
+ import { API_PREFIX } from "./api.js";
4
+ import * as Schema from "effect/Schema";
5
+ import * as Predicate from "effect/Predicate";
6
+ import * as Option from "effect/Option";
7
+ import * as Data from "effect/Data";
8
+ // src/api/listen.ts
9
+ /**
10
+ * `@grovemotorco/manifold/listen`: the local development relay's wire contract
11
+ * (docs/LOCAL-RELAY.md §4.5), shared by the SourceDO and the `manifold` CLI.
12
+ *
13
+ * ## The WebSocket
14
+ *
15
+ * `GET /api/v1/sources/{key}/listen` (`listenPath`, `listenUrl`), outside the
16
+ * `HttpApi` definition. The Worker matches it before handing `/api/*` to the
17
+ * HttpApi.
18
+ *
19
+ * 1. The request must carry `Upgrade: websocket`; otherwise `426` (code
20
+ * `bad_request`, with an `Upgrade: websocket` response header).
21
+ * 2. Credentials, as for the admin API: `Authorization: Bearer <token>` with a
22
+ * listen token (`mfl_…`, the intended credential) or the admin token, or a
23
+ * Cloudflare Access JWT in `cf-access-jwt-assertion`. Missing or invalid →
24
+ * `401 unauthorized`; admin auth not configured → `503 unavailable`.
25
+ * 3. A listen token is checked by the source's SourceDO
26
+ * (`authorizeListenToken` in src/runtime/rpc.ts, with `hashListenToken`).
27
+ * A token that matches none of that source's tokens (revoked, expired,
28
+ * another source's, or the source does not exist) → `401`. Unknown or
29
+ * deleted source (admin token, Access), `listeners: "off"` or
30
+ * `MANIFOLD_LISTENERS=off` → `404 not_found` (the CLI exits `4`). The
31
+ * SourceDO could not be reached → `502 unavailable` (transient; retry).
32
+ * 4. The Worker strips every inbound `manifold-*` header, `authorization`,
33
+ * `cookie` and `cf-access-jwt-assertion`, sets `LISTEN_UPGRADE_HEADERS`,
34
+ * and passes the request to the SourceDO's `fetch`.
35
+ * 5. With `LISTEN_LIMITS.listenersPerSource` sessions already open the
36
+ * SourceDO answers `409 conflict` and does not upgrade. Otherwise it
37
+ * accepts with the hibernation API (`101`).
38
+ *
39
+ * Error answers before the upgrade are the API's `{ error: { code, message } }`.
40
+ *
41
+ * ## Frames
42
+ *
43
+ * JSON text frames of at most `LISTEN_LIMITS.frameBytes` (UTF-8). Every frame
44
+ * is an object with a string `type`. A frame of an unknown type is ignored by
45
+ * both sides (`parse*Frame` → `Unknown`), so either side can be newer; a
46
+ * malformed frame of a known type is ignored by the CLI and closes the
47
+ * session with `LISTEN_CLOSE.protocolError` on the server.
48
+ *
49
+ * 1. The client sends `hello` within `LISTEN_TIMINGS.helloTimeoutMs`
50
+ * (else `LISTEN_CLOSE.helloTimeout`). A `protocol` other than
51
+ * `LISTEN_PROTOCOL` gets `bye: unsupported_protocol`.
52
+ * 2. The server answers `ready`, then (at most one of) the resume or the
53
+ * replay the hello asked for, then live requests if `live`. Frames go out
54
+ * in this order; a live request is never sent ahead of resume or replay
55
+ * frames queued before it (the object is single threaded).
56
+ * 3. The client answers each forward with a `result` frame (one per target per
57
+ * attempt). It may send `replay` frames at any time.
58
+ * 4. Keep-alive: the client sends `LISTEN_PING` every
59
+ * `LISTEN_TIMINGS.keepAliveMs`; the platform answers `LISTEN_PONG` without
60
+ * waking the object (`setWebSocketAutoResponse`).
61
+ * 5. The server ends a session with a `bye` frame, then closes with the code
62
+ * `byeCloseCode(reason)`. The client ends it with close code `1000`.
63
+ */
64
+ /** The protocol version in `hello` and `ready`. */
65
+ const LISTEN_PROTOCOL = 1;
66
+ const LISTEN_LIMITS = {
67
+ /** Open sessions per source; the next upgrade answers `409`. */
68
+ listenersPerSource: 10,
69
+ /** Largest frame either side sends, UTF-8 bytes. */
70
+ frameBytes: 64 * KiB,
71
+ /** Requests per replay (frame or `send-local`) and per resume. */
72
+ replayMax: LIMITS.replayRangeMax,
73
+ /** Bodies up to this size travel in the frame (base64); larger ones are fetched from the raw-body endpoint. */
74
+ inlineBodyBytes: LIMITS.inlineBodyBytes,
75
+ /** Globs in a `hello`. */
76
+ eventTypes: 20,
77
+ /** `result.error`, characters. */
78
+ resultErrorChars: 300,
79
+ /** `local_attempts` rows older than this are removed by hourly maintenance. */
80
+ localAttemptsRetentionMs: 864e5,
81
+ /** `local_attempts` keeps at most this many rows per source (oldest removed first). */
82
+ localAttemptsMaxRows: 2e3,
83
+ /** `RequestDetail.localAttempts` lists at most this many, newest first. */
84
+ localAttemptsPerRequest: 100
85
+ };
86
+ const LISTEN_TIMINGS = {
87
+ /** The client must send `hello` this soon after the socket opens. */
88
+ helloTimeoutMs: 1e4,
89
+ /** The client sends `LISTEN_PING` this often. */
90
+ keepAliveMs: 3e4,
91
+ /** The client reconnects with exponential backoff from this… */
92
+ reconnectMinMs: 1e3,
93
+ /** …to this, jittered, forever (docs/LOCAL-RELAY.md §6.2). */
94
+ reconnectMaxMs: 3e4
95
+ };
96
+ /** The keep-alive request. Answered by the platform with `LISTEN_PONG`, without waking the object. */
97
+ const LISTEN_PING = `{"type":"ping"}`;
98
+ const LISTEN_PONG = `{"type":"pong"}`;
99
+ /**
100
+ * Headers the Worker sets on the upgrade request it passes to the SourceDO,
101
+ * after removing every inbound `manifold-*` header (so a client cannot set
102
+ * them). Values are plain strings.
103
+ */
104
+ const LISTEN_UPGRADE_HEADERS = {
105
+ /** The audit actor: `listen:<tokenId>`, `token` or `access:<email>` (`actorLabel`). */
106
+ actor: "manifold-listen-actor",
107
+ /** The listen token's id (`ltk_…`); absent for the admin token and Access. */
108
+ tokenId: "manifold-listen-token-id"
109
+ };
110
+ /**
111
+ * Close codes. `1000`–`1011` are the standard ones; `4000`–`4099` are ours,
112
+ * one per `bye` reason so a client that missed the `bye` frame still knows.
113
+ */
114
+ const LISTEN_CLOSE = {
115
+ /** Either side ended the session normally (CLI `Ctrl-C`). */
116
+ normal: 1e3,
117
+ /** The server is restarting or the object is being evicted. Reconnect. */
118
+ goingAway: 1001,
119
+ /** A malformed frame of a known type, or a second `hello`. */
120
+ protocolError: 1002,
121
+ /** A frame over `LISTEN_LIMITS.frameBytes`. */
122
+ tooBig: 1009,
123
+ internalError: 1011,
124
+ replaced: 4e3,
125
+ revoked: 4001,
126
+ sourceDeleted: 4002,
127
+ tooManyListeners: 4003,
128
+ disconnected: 4004,
129
+ listenersOff: 4005,
130
+ unsupportedProtocol: 4006,
131
+ badHello: 4007,
132
+ helloTimeout: 4008,
133
+ /** The client read too slowly and its send buffer passed the limit (§7 of LOCAL-RELAY.md). Reconnect with resume. */
134
+ slowConsumer: 4009,
135
+ /** `live: false` and the replay is done. */
136
+ done: 4010
137
+ };
138
+ /**
139
+ * `bye` reasons the server sends. `reason` is decoded as any string so a
140
+ * newer server's reasons reach an older CLI; these are the known ones:
141
+ *
142
+ * - `replaced`: a new session with the same name and the same credential
143
+ * took over. Do not reconnect.
144
+ * - `revoked`: the listen token was revoked or expired. Do not reconnect.
145
+ * - `source_deleted`. Do not reconnect.
146
+ * - `too_many_listeners`: a race past the `409` check. Retry later.
147
+ * - `disconnected`: an operator disconnected it (`DELETE …/listeners/{id}`). Do not reconnect.
148
+ * - `listeners_off`: the source's `listeners` was set to `off`. Do not reconnect.
149
+ * - `unsupported_protocol`: `hello.protocol` is not `LISTEN_PROTOCOL`. Upgrade the CLI.
150
+ * - `bad_hello`: the hello was invalid (unknown `likeRoute`, both `resumeAfter` and `replay`, …).
151
+ * - `slow_consumer`: see `LISTEN_CLOSE.slowConsumer`. Reconnect with resume.
152
+ * - `done`: `live: false` and the replay is finished.
153
+ */
154
+ const ByeReason = Schema.Literals([
155
+ "replaced",
156
+ "revoked",
157
+ "source_deleted",
158
+ "too_many_listeners",
159
+ "disconnected",
160
+ "listeners_off",
161
+ "unsupported_protocol",
162
+ "bad_hello",
163
+ "slow_consumer",
164
+ "done"
165
+ ]).annotate({ identifier: "ByeReason" });
166
+ const BYE_CLOSE = {
167
+ replaced: LISTEN_CLOSE.replaced,
168
+ revoked: LISTEN_CLOSE.revoked,
169
+ source_deleted: LISTEN_CLOSE.sourceDeleted,
170
+ too_many_listeners: LISTEN_CLOSE.tooManyListeners,
171
+ disconnected: LISTEN_CLOSE.disconnected,
172
+ listeners_off: LISTEN_CLOSE.listenersOff,
173
+ unsupported_protocol: LISTEN_CLOSE.unsupportedProtocol,
174
+ bad_hello: LISTEN_CLOSE.badHello,
175
+ slow_consumer: LISTEN_CLOSE.slowConsumer,
176
+ done: LISTEN_CLOSE.done
177
+ };
178
+ /** The close code that follows a `bye` with this reason. */
179
+ const byeCloseCode = (reason) => BYE_CLOSE[reason];
180
+ const FINAL_CLOSE_CODES = /* @__PURE__ */ new Set([
181
+ LISTEN_CLOSE.normal,
182
+ LISTEN_CLOSE.replaced,
183
+ LISTEN_CLOSE.revoked,
184
+ LISTEN_CLOSE.sourceDeleted,
185
+ LISTEN_CLOSE.disconnected,
186
+ LISTEN_CLOSE.listenersOff,
187
+ LISTEN_CLOSE.unsupportedProtocol,
188
+ LISTEN_CLOSE.badHello,
189
+ LISTEN_CLOSE.done
190
+ ]);
191
+ /**
192
+ * True when the CLI must not reconnect after this close code. Every other
193
+ * code (network loss `1006`, `1001`, `1011`, `4003`, `4008`, `4009`, unknown
194
+ * codes) is retried with the reconnect schedule and `resumeAfter`.
195
+ */
196
+ const isFinalClose = (code) => FINAL_CLOSE_CODES.has(code);
197
+ /**
198
+ * `notice` codes the server sends. `code` is decoded as any string, so a
199
+ * notice with an unknown code is still delivered (and can be printed); these
200
+ * are the known ones:
201
+ *
202
+ * - `gap`: a resume found more than `LISTEN_LIMITS.replayMax` requests after
203
+ * the cursor (`count` of them were skipped), or the cursor is older than
204
+ * the source's retention. Sent before the resume's requests, which are the
205
+ * newest `replayMax`.
206
+ * - `resume_done`: the resume's requests were all sent (`count`).
207
+ * - `replay_done`: a replay (hello `replay`, a `replay` frame with its `ref`, or
208
+ * a `send-local`) was all sent (`count`).
209
+ * - `limit`: a request could not be sent because its frame would pass
210
+ * `LISTEN_LIMITS.frameBytes` even without its body, or a replay was cut at
211
+ * `replayMax`. `message` names the request id.
212
+ */
213
+ const NoticeCode = Schema.Literals([
214
+ "gap",
215
+ "resume_done",
216
+ "replay_done",
217
+ "limit"
218
+ ]).annotate({ identifier: "NoticeCode" });
219
+ const OpenString = (max) => Schema.String.check(Schema.isMaxLength(max));
220
+ /** `--last <n>`: the newest `n` matching stored requests. `--since`: those received at or after `since`. */
221
+ const HelloReplay = Schema.Union([Schema.Struct({ last: Schema.Int.check(Schema.isBetween({
222
+ minimum: 1,
223
+ maximum: LISTEN_LIMITS.replayMax
224
+ })) }), Schema.Struct({ since: Millis })]).annotate({ identifier: "HelloReplay" });
225
+ /**
226
+ * Opens the session. Filter: `eventTypes` globs, or `likeRoute` (a route of
227
+ * this source) whose filter is copied; with `likeRoute` set, `eventTypes` is
228
+ * ignored and should be `["*"]` (see `effectiveEventTypes`). A hello replay
229
+ * (`replay`) and resume (`resumeAfter`, the newest live or resume request id
230
+ * the CLI saw) are both filtered and both leave out `duplicate` requests;
231
+ * at most one of them may be set.
232
+ */
233
+ const HelloFrame = Schema.Struct({
234
+ type: Schema.Literal("hello"),
235
+ /** `LISTEN_PROTOCOL`. Any integer decodes, so a newer client can be refused with `bye: unsupported_protocol`. */
236
+ protocol: Schema.Int,
237
+ name: ListenerName,
238
+ eventTypes: Schema.NonEmptyArray(EventTypeGlob).check(Schema.isMaxLength(LISTEN_LIMITS.eventTypes)),
239
+ likeRoute: Schema.optionalKey(RouteId),
240
+ resumeAfter: Schema.optionalKey(RequestId),
241
+ replay: Schema.optionalKey(HelloReplay),
242
+ /** False for `--no-live`: replay, then `bye: done`. */
243
+ live: Schema.Boolean
244
+ }).check(Schema.makeFilter((hello) => hello.resumeAfter === void 0 || hello.replay === void 0 || "set at most one of resumeAfter and replay")).annotate({ identifier: "HelloFrame" });
245
+ /**
246
+ * The outcome of one attempt to forward one `request` frame to one local
247
+ * target. `statusCode` when a response arrived (any status, `3xx` included:
248
+ * redirects are not followed), `error` otherwise; exactly one of them.
249
+ */
250
+ const ResultFrame = Schema.Struct({
251
+ type: Schema.Literal("result"),
252
+ localId: LocalId,
253
+ requestId: RequestId,
254
+ /** The `kind` of the `request` frame. */
255
+ kind: LocalAttemptKind,
256
+ /** `targetLabel(url)`, never the full URL. */
257
+ target: TargetLabel,
258
+ attempt: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
259
+ durationMs: Count,
260
+ statusCode: Schema.optionalKey(Schema.Int.check(Schema.isBetween({
261
+ minimum: 100,
262
+ maximum: 599
263
+ }))),
264
+ error: Schema.optionalKey(OpenString(LISTEN_LIMITS.resultErrorChars))
265
+ }).check(Schema.makeFilter((result) => result.statusCode === void 0 !== (result.error === void 0) || "set exactly one of statusCode and error")).annotate({ identifier: "ResultFrame" });
266
+ const replayRangeFields = {
267
+ since: Schema.optionalKey(Millis),
268
+ until: Schema.optionalKey(Millis),
269
+ eventType: Schema.optionalKey(EventTypeGlob),
270
+ /** Without it, `duplicate` requests are left out. */
271
+ status: Schema.optionalKey(RequestStatus),
272
+ /** The newest matching requests, at most this many (default 50); sent oldest first. */
273
+ limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({
274
+ minimum: 1,
275
+ maximum: LISTEN_LIMITS.replayMax
276
+ })))
277
+ };
278
+ /**
279
+ * Asks for stored requests on this socket, as `request` frames of kind
280
+ * `replay`, then `notice: replay_done` with the same `ref`. By ids
281
+ * (`requestIds`) or by a range; not both. The session's filter does not
282
+ * apply: what is asked for is sent.
283
+ */
284
+ const ReplayFrame = Schema.Struct({
285
+ type: Schema.Literal("replay"),
286
+ /** Echoed in the `replay_done` notice. */
287
+ ref: Schema.optionalKey(OpenString(64)),
288
+ requestIds: Schema.optionalKey(Schema.NonEmptyArray(RequestId).check(Schema.isMaxLength(LISTEN_LIMITS.replayMax))),
289
+ ...replayRangeFields
290
+ }).check(Schema.makeFilter((frame) => {
291
+ if (frame.requestIds === void 0) return void 0;
292
+ const range = Object.entries(frame).filter(([key, value]) => Object.hasOwn(replayRangeFields, key) && value !== void 0).map(([key]) => key);
293
+ return range.length === 0 || `requestIds cannot be combined with ${range.join(", ")}`;
294
+ })).annotate({ identifier: "ReplayFrame" });
295
+ /** `LISTEN_PING` as a frame. Normally answered by the platform, never seen by the object. */
296
+ const PingFrame = Schema.Struct({ type: Schema.Literal("ping") }).annotate({ identifier: "PingFrame" });
297
+ const ClientFrame = Schema.Union([
298
+ HelloFrame,
299
+ ResultFrame,
300
+ ReplayFrame,
301
+ PingFrame
302
+ ]).annotate({ identifier: "ClientFrame" });
303
+ /**
304
+ * Sent once, after a valid `hello`. `source` and `preset` are plain strings
305
+ * so a newer server's preset ids decode in an older CLI.
306
+ */
307
+ const ReadyFrame = Schema.Struct({
308
+ type: Schema.Literal("ready"),
309
+ protocol: Schema.Int,
310
+ sessionId: ListenerSessionId,
311
+ source: Schema.String,
312
+ preset: Schema.String,
313
+ /** The effective filter (`effectiveEventTypes`). */
314
+ eventTypes: Schema.Array(Schema.String),
315
+ /**
316
+ * The source's resolved `redactHeaders`, which `buildOutboundRequest`
317
+ * needs to build what a relay would receive (a listen token cannot read
318
+ * the source config).
319
+ */
320
+ redactHeaders: Schema.Array(Schema.String),
321
+ limits: Schema.Struct({
322
+ listenersPerSource: Count,
323
+ frameBytes: Count,
324
+ inlineBodyBytes: Count,
325
+ replayMax: Count
326
+ }),
327
+ serverTime: Millis
328
+ }).annotate({ identifier: "ReadyFrame" });
329
+ /**
330
+ * How a `request` frame carries the body: `inline` (base64 of the raw bytes,
331
+ * for bodies up to `LISTEN_LIMITS.inlineBodyBytes` whose frame fits), or
332
+ * `fetch` (read it from `GET /api/v1/sources/{key}/requests/{id}/body`,
333
+ * which a listen token may call for its source).
334
+ */
335
+ const FrameBody = Schema.Union([Schema.Struct({ inline: Schema.String }), Schema.Struct({
336
+ fetch: Schema.Literal(true),
337
+ size: Count
338
+ })]).annotate({ identifier: "FrameBody" });
339
+ /**
340
+ * One stored request for the listener. `request` is the stored record, as
341
+ * the admin API returns it (headers as stored, credentials redacted).
342
+ * `localId` is minted by the server per frame (`newLocalId`): the CLI sends it
343
+ * as `manifold-delivery-id` to every target and on every retry.
344
+ * `duplicate` requests are never sent live or on resume.
345
+ */
346
+ const RequestFrame = Schema.Struct({
347
+ type: Schema.Literal("request"),
348
+ localId: LocalId,
349
+ kind: LocalAttemptKind,
350
+ request: RequestRecord,
351
+ body: FrameBody
352
+ }).annotate({ identifier: "RequestFrame" });
353
+ const NoticeFrame = Schema.Struct({
354
+ type: Schema.Literal("notice"),
355
+ /** A `NoticeCode`, or a newer one. */
356
+ code: OpenString(64),
357
+ message: OpenString(1e3),
358
+ /** The `ref` of the `replay` frame this answers. */
359
+ ref: Schema.optionalKey(OpenString(64)),
360
+ count: Schema.optionalKey(Count)
361
+ }).annotate({ identifier: "NoticeFrame" });
362
+ const ByeFrame = Schema.Struct({
363
+ type: Schema.Literal("bye"),
364
+ /** A `ByeReason`, or a newer one. */
365
+ reason: OpenString(64),
366
+ message: Schema.optionalKey(OpenString(1e3))
367
+ }).annotate({ identifier: "ByeFrame" });
368
+ /** `LISTEN_PONG` as a frame. */
369
+ const PongFrame = Schema.Struct({ type: Schema.Literal("pong") }).annotate({ identifier: "PongFrame" });
370
+ const ServerFrame = Schema.Union([
371
+ ReadyFrame,
372
+ RequestFrame,
373
+ NoticeFrame,
374
+ ByeFrame,
375
+ PongFrame
376
+ ]).annotate({ identifier: "ServerFrame" });
377
+ /** The UTF-8 size of an encoded frame. */
378
+ const frameBytes = (text) => utf8Encode(text).byteLength;
379
+ const ParsedFrame = Data.taggedEnum();
380
+ /** What every frame has: a string `type`. */
381
+ const FrameEnvelope = Schema.Struct({ type: Schema.String });
382
+ const decodeEnvelope = Schema.decodeUnknownOption(FrameEnvelope);
383
+ /** `schema` is the union of the frames; `types` lists every `type` it knows. */
384
+ const makeParser = (schema, types) => {
385
+ const decodeFrame = Schema.decodeUnknownOption(schema);
386
+ return (data) => {
387
+ let text;
388
+ try {
389
+ text = Predicate.isString(data) ? data : new TextDecoder("utf-8", { fatal: true }).decode(data);
390
+ } catch {
391
+ return ParsedFrame.Malformed({
392
+ type: null,
393
+ reason: "not UTF-8"
394
+ });
395
+ }
396
+ if (frameBytes(text) > LISTEN_LIMITS.frameBytes) return ParsedFrame.Malformed({
397
+ type: null,
398
+ reason: "frame too large"
399
+ });
400
+ let json;
401
+ try {
402
+ json = JSON.parse(text);
403
+ } catch {
404
+ return ParsedFrame.Malformed({
405
+ type: null,
406
+ reason: "not JSON"
407
+ });
408
+ }
409
+ if (!Predicate.isObject(json)) return ParsedFrame.Malformed({
410
+ type: null,
411
+ reason: "not a JSON object"
412
+ });
413
+ const envelope = decodeEnvelope(json);
414
+ if (Option.isNone(envelope)) return ParsedFrame.Malformed({
415
+ type: null,
416
+ reason: "no string 'type'"
417
+ });
418
+ const { type } = envelope.value;
419
+ if (!Object.hasOwn(types, type)) return ParsedFrame.Unknown({ type });
420
+ const frame = decodeFrame(json);
421
+ return Option.isSome(frame) ? ParsedFrame.Frame({ frame: frame.value }) : ParsedFrame.Malformed({
422
+ type,
423
+ reason: `invalid '${type}' frame`
424
+ });
425
+ };
426
+ };
427
+ /** Reads a frame the CLI sent. Never throws. */
428
+ const parseClientFrame = makeParser(ClientFrame, {
429
+ hello: true,
430
+ result: true,
431
+ replay: true,
432
+ ping: true
433
+ });
434
+ /** Reads a frame the server sent. Never throws. */
435
+ const parseServerFrame = makeParser(ServerFrame, {
436
+ ready: true,
437
+ request: true,
438
+ notice: true,
439
+ bye: true,
440
+ pong: true
441
+ });
442
+ /** A client frame, or none when it is of an unknown type or malformed. Never throws. */
443
+ const decodeClientFrame = (data) => {
444
+ const parsed = parseClientFrame(data);
445
+ return Predicate.isTagged(parsed, "Frame") ? Option.some(parsed.frame) : Option.none();
446
+ };
447
+ /** A server frame, or none when it is of an unknown type or malformed. Never throws. */
448
+ const decodeServerFrame = (data) => {
449
+ const parsed = parseServerFrame(data);
450
+ return Predicate.isTagged(parsed, "Frame") ? Option.some(parsed.frame) : Option.none();
451
+ };
452
+ const encodeClient = Schema.encodeSync(ClientFrame);
453
+ const encodeServer = Schema.encodeSync(ServerFrame);
454
+ /** The JSON text of a client frame. Throws on a value that does not satisfy its schema (a programming error). */
455
+ const encodeClientFrame = (frame) => JSON.stringify(encodeClient(frame));
456
+ /** The JSON text of a server frame. Throws on a value that does not satisfy its schema (a programming error). */
457
+ const encodeServerFrame = (frame) => JSON.stringify(encodeServer(frame));
458
+ /**
459
+ * Builds and encodes a `request` frame, choosing how the body travels: inline
460
+ * when `body` is given, at most `LISTEN_LIMITS.inlineBodyBytes`, and the frame
461
+ * fits `LISTEN_LIMITS.frameBytes`; otherwise `fetch`. `body` is `null` when it
462
+ * is stored in R2. Answers `undefined` when even the `fetch` frame is too
463
+ * large (very large headers): send a `limit` notice instead.
464
+ */
465
+ const encodeRequestFrame = (input) => {
466
+ const base = {
467
+ type: "request",
468
+ localId: input.localId,
469
+ kind: input.kind,
470
+ request: input.request
471
+ };
472
+ if (input.body !== null && input.body.byteLength <= LISTEN_LIMITS.inlineBodyBytes) {
473
+ const frame = {
474
+ ...base,
475
+ body: { inline: toBase64(input.body) }
476
+ };
477
+ const text = encodeServerFrame(frame);
478
+ if (frameBytes(text) <= LISTEN_LIMITS.frameBytes) return {
479
+ frame,
480
+ text
481
+ };
482
+ }
483
+ const frame = {
484
+ ...base,
485
+ body: {
486
+ fetch: true,
487
+ size: input.request.bodySize
488
+ }
489
+ };
490
+ const text = encodeServerFrame(frame);
491
+ return frameBytes(text) <= LISTEN_LIMITS.frameBytes ? {
492
+ frame,
493
+ text
494
+ } : void 0;
495
+ };
496
+ /** The body of a `request` frame when it is inline; `undefined` when it must be fetched (or is not valid base64). */
497
+ const inlineBody = (frame) => "inline" in frame.body ? fromBase64(frame.body.inline) : void 0;
498
+ /**
499
+ * The globs a session filters live and resume requests with: the hello's
500
+ * `eventTypes`, or, with `likeRoute`, a copy of that route's filter as it is
501
+ * in the current snapshot. `undefined` when `likeRoute` names no route of
502
+ * this source (answer `bye: bad_hello` at hello time; send nothing later if
503
+ * the route was deleted since).
504
+ */
505
+ const effectiveEventTypes = (filter, routes) => {
506
+ if (filter.likeRoute === void 0 || filter.likeRoute === null) return filter.eventTypes;
507
+ return routes.find((route) => route.id === filter.likeRoute)?.eventTypes;
508
+ };
509
+ /**
510
+ * True when a live or resume request goes to a session with these globs:
511
+ * never a `duplicate`; `accepted` and `unrouted` ones when a glob matches
512
+ * the event type (`*` also matches a request without one), exactly as route
513
+ * filters match (src/core/filter.ts). Rejections are never sent.
514
+ */
515
+ const listenerWants = (eventTypes, request) => request.status !== "duplicate" && matchesEventTypes(eventTypes, request.eventType);
516
+ /** The WebSocket path for a source, under `API_PREFIX`. */
517
+ const listenPath = (sourceKey) => `${API_PREFIX}/sources/${sourceKey}/listen`;
518
+ /**
519
+ * The source key when `pathname` is exactly a listen path
520
+ * (`/api/v1/sources/{key}/listen`), else `undefined`. For the Worker's router.
521
+ */
522
+ const listenPathKey = (pathname) => {
523
+ const prefix = `${API_PREFIX}/sources/`;
524
+ if (!pathname.startsWith(prefix) || !pathname.endsWith("/listen")) return void 0;
525
+ const key = pathname.slice(prefix.length, pathname.length - 7);
526
+ return Schema.is(SourceKey)(key) ? key : void 0;
527
+ };
528
+ /**
529
+ * The `ws:` / `wss:` URL of a source's listen endpoint. `baseUrl` is the
530
+ * service origin as the CLI is configured with it (`http`, `https`, `ws` or
531
+ * `wss`; a path prefix is kept, as the typed client keeps it). Throws a
532
+ * `TypeError` for another protocol or an invalid source key.
533
+ */
534
+ const listenUrl = (baseUrl, sourceKey) => {
535
+ const base = new URL(baseUrl);
536
+ const protocol = base.protocol === "https:" || base.protocol === "wss:" ? "wss:" : base.protocol === "http:" || base.protocol === "ws:" ? "ws:" : void 0;
537
+ if (protocol === void 0) throw new TypeError(`expected an http or https URL, got ${base.protocol}`);
538
+ if (!Schema.is(SourceKey)(sourceKey)) throw new TypeError(`invalid source key: ${sourceKey}`);
539
+ const prefix = base.pathname.replace(/\/+$/, "");
540
+ const url = new URL(`${protocol}//${base.host}`);
541
+ url.pathname = `${prefix}${listenPath(sourceKey)}`;
542
+ return url.toString();
543
+ };
544
+ const isLoopbackLiteral = (hostname) => hostname === "localhost" || hostname === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
545
+ /**
546
+ * The label a `result` frame reports for a local target: `:{port}{path}` for
547
+ * a loopback host (`:3000/webhooks/github`), `{host}{path}` otherwise. No
548
+ * scheme, query or credentials. At most 200 characters.
549
+ */
550
+ const targetLabel = (target) => {
551
+ const url = new URL(target);
552
+ const port = url.port !== "" ? url.port : url.protocol === "https:" ? "443" : "80";
553
+ const label = isLoopbackLiteral(url.hostname) ? `:${port}${url.pathname}` : `${url.host}${url.pathname}`;
554
+ return label.length > 200 ? `${label.slice(0, 199)}…` : label;
555
+ };
556
+ const LISTEN_TOKEN_PREFIX = "mfl_";
557
+ const LISTEN_TOKEN_PATTERN = /^mfl_[A-Za-z0-9_-]{43}$/;
558
+ /** A new listen token: `mfl_` and 32 random bytes in base64url (43 characters). */
559
+ const generateListenToken = () => `${LISTEN_TOKEN_PREFIX}${toBase64Url(randomBytes(32))}`;
560
+ /** True when the value has the shape of a listen token. Says nothing about whether it is valid. */
561
+ const isListenToken = (value) => LISTEN_TOKEN_PATTERN.test(value);
562
+ /** What is stored and compared: SHA-256 of the token's UTF-8 bytes, 64 lowercase hex characters. */
563
+ const hashListenToken = (token) => sha256Hex(token);
564
+ /** The token's fingerprint (§5.5): the first 8 hex characters of its hash. */
565
+ const listenTokenFingerprint = (hash) => hash.slice(0, 8);
566
+ export { ByeFrame, ByeReason, ClientFrame, FrameBody, HelloFrame, HelloReplay, LISTEN_CLOSE, LISTEN_LIMITS, LISTEN_PING, LISTEN_PONG, LISTEN_PROTOCOL, LISTEN_TIMINGS, LISTEN_TOKEN_PREFIX, LISTEN_UPGRADE_HEADERS, LOCAL_ID_PREFIX, LocalAttemptKind, LocalId, NoticeCode, NoticeFrame, ParsedFrame, PingFrame, PongFrame, ReadyFrame, ReplayFrame, RequestFrame, ResultFrame, ServerFrame, TargetLabel, byeCloseCode, decodeClientFrame, decodeServerFrame, effectiveEventTypes, encodeClientFrame, encodeRequestFrame, encodeServerFrame, frameBytes, generateListenToken, hashListenToken, inlineBody, isFinalClose, isListenToken, isLocalId, listenPath, listenPathKey, listenTokenFingerprint, listenUrl, listenerWants, newLocalId, parseClientFrame, parseServerFrame, targetLabel };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@grovemotorco/manifold",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "description": "Verify Manifold relay signatures, sign and send test webhooks, and call the Manifold admin API with a typed client.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/grovemotorco/manifold.git",
9
+ "directory": "packages/manifold"
10
+ },
11
+ "homepage": "https://github.com/grovemotorco/manifold#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/grovemotorco/manifold/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./api": {
23
+ "types": "./dist/api.d.ts",
24
+ "default": "./dist/api.js"
25
+ },
26
+ "./client": {
27
+ "types": "./dist/client.d.ts",
28
+ "default": "./dist/client.js"
29
+ },
30
+ "./listen": {
31
+ "types": "./dist/listen.d.ts",
32
+ "default": "./dist/listen.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "peerDependencies": {
40
+ "effect": "^4.1.7"
41
+ },
42
+ "devDependencies": {
43
+ "effect": "4.1.7"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "scripts": {
50
+ "build": "vp pack"
51
+ }
6
52
  }