@velajs/cloudflare 1.29.0 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/README.md +262 -75
  3. package/dist/bindings.js +77 -0
  4. package/dist/bindings.js.map +1 -0
  5. package/dist/cloudflare-application.js +282 -0
  6. package/dist/cloudflare-application.js.map +1 -0
  7. package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
  8. package/dist/cloudflare-factory.js +165 -0
  9. package/dist/cloudflare-factory.js.map +1 -0
  10. package/dist/decorators/queue-consumer.js +39 -0
  11. package/dist/decorators/queue-consumer.js.map +1 -0
  12. package/dist/diagnostics.js +18 -0
  13. package/dist/diagnostics.js.map +1 -0
  14. package/dist/durable-objects.d.ts +8 -5
  15. package/dist/durable-objects.js +2 -524
  16. package/dist/environment.js +19 -0
  17. package/dist/environment.js.map +1 -0
  18. package/dist/index.d.ts +163 -456
  19. package/dist/index.js +15 -1276
  20. package/dist/nonce/durable-object-nonce.store.js +33 -0
  21. package/dist/nonce/durable-object-nonce.store.js.map +1 -0
  22. package/dist/nonce/nonce-validation.js +18 -0
  23. package/dist/nonce/nonce-validation.js.map +1 -0
  24. package/dist/nonce/nonce.durable-object.js +54 -0
  25. package/dist/nonce/nonce.durable-object.js.map +1 -0
  26. package/dist/{nonce.durable-object-Df4CZi-0.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -12
  27. package/dist/platform.js +22 -0
  28. package/dist/platform.js.map +1 -0
  29. package/dist/queue/cloudflare-queues.js +215 -0
  30. package/dist/queue/cloudflare-queues.js.map +1 -0
  31. package/dist/queues.d.ts +1 -2
  32. package/dist/queues.js +1 -214
  33. package/dist/rate-limit/cloudflare-rate-limit.store.js +79 -0
  34. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -0
  35. package/dist/root-module-C23bUwt_.d.ts +11 -0
  36. package/dist/schedule-diagnostics.js +44 -0
  37. package/dist/schedule-diagnostics.js.map +1 -0
  38. package/dist/scheduled-event.js +68 -0
  39. package/dist/scheduled-event.js.map +1 -0
  40. package/dist/services/flagship-flag.driver.js +52 -0
  41. package/dist/services/flagship-flag.driver.js.map +1 -0
  42. package/dist/services/kv-cache.store.js +108 -0
  43. package/dist/services/kv-cache.store.js.map +1 -0
  44. package/dist/services/kv-flag.driver.js +62 -0
  45. package/dist/services/kv-flag.driver.js.map +1 -0
  46. package/dist/storage/r2-storage.js +30 -0
  47. package/dist/storage/r2-storage.js.map +1 -0
  48. package/dist/storage.d.ts +28 -0
  49. package/dist/storage.js +2 -0
  50. package/dist/testing.d.ts +96 -0
  51. package/dist/testing.js +111 -0
  52. package/dist/testing.js.map +1 -0
  53. package/dist/vela-env-DFvyoNT3.d.ts +1 -2
  54. package/dist/websocket/binding-gateways.js +33 -0
  55. package/dist/websocket/binding-gateways.js.map +1 -0
  56. package/dist/websocket/cf-room-registry.js +139 -0
  57. package/dist/websocket/cf-room-registry.js.map +1 -0
  58. package/dist/websocket/cf-ws-client.js +94 -0
  59. package/dist/websocket/cf-ws-client.js.map +1 -0
  60. package/dist/websocket/do-bootstrap.js +77 -0
  61. package/dist/websocket/do-bootstrap.js.map +1 -0
  62. package/dist/websocket/do-live.js +143 -0
  63. package/dist/websocket/do-live.js.map +1 -0
  64. package/dist/websocket/do-pitr.js +81 -0
  65. package/dist/websocket/do-pitr.js.map +1 -0
  66. package/dist/websocket/do-state.js +7 -0
  67. package/dist/websocket/do-state.js.map +1 -0
  68. package/dist/websocket/do-websocket-host.js +169 -0
  69. package/dist/websocket/do-websocket-host.js.map +1 -0
  70. package/dist/websocket/live-driver.js +149 -0
  71. package/dist/websocket/live-driver.js.map +1 -0
  72. package/dist/websocket/room-id.js +37 -0
  73. package/dist/websocket/room-id.js.map +1 -0
  74. package/dist/websocket/websocket.durable-object.js +142 -0
  75. package/dist/websocket/websocket.durable-object.js.map +1 -0
  76. package/dist/websocket/worker-transport.js +80 -0
  77. package/dist/websocket/worker-transport.js.map +1 -0
  78. package/dist/websocket/ws-attachment.js +79 -0
  79. package/dist/websocket/ws-attachment.js.map +1 -0
  80. package/package.json +26 -7
  81. package/dist/durable-objects.js.map +0 -1
  82. package/dist/index.js.map +0 -1
  83. package/dist/nonce-validation-Dy8z05A9.js +0 -522
  84. package/dist/nonce-validation-Dy8z05A9.js.map +0 -1
  85. package/dist/queues.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do-websocket-host.js","names":[],"sources":["../../src/websocket/do-websocket-host.ts"],"sourcesContent":["import { socketAttachment } from './ws-attachment';\nimport { WsMessageQueue, assertBroadcastCommandFits } from '@velajs/vela/websocket';\nimport type { BroadcastCommand, WsDispatcher } from '@velajs/vela/websocket';\nimport type { CfRoomRegistry } from './cf-room-registry';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nimport { connTag, roomTag } from './room-id';\n\nexport interface WsConnectionPrincipal {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n tenantId: string;\n}\n\n/**\n * The socket lifecycle inside a WebSocket Durable Object, decoupled from the\n * `cloudflare:workers` base class so it is unit-testable with fakes. The thin\n * `VelaWebSocketDurableObject` shell forwards its hibernation callbacks here.\n */\nexport class DoWebSocketHost {\n readonly #messages = new WeakMap<WsLike, WsMessageQueue>();\n constructor(\n private readonly ctx: DoStateLike,\n private readonly dispatcher: WsDispatcher,\n private readonly registry: CfRoomRegistry,\n private readonly gatewayPaths: readonly string[] = [],\n ) {}\n\n /** The single registered gateway's path — a fallback when the Worker didn't forward `x-vela-path`. */\n defaultPath(): string | undefined {\n return this.gatewayPaths[0];\n }\n\n /**\n * Accept a hibernatable socket: tag it with its hub room + connection id,\n * persist the attachment, then await `OnGatewayConnection` before the caller\n * returns 101. A rejected lifecycle hook closes and fails the upgrade.\n */\n async accept(\n ws: WsLike,\n path: string,\n roomId: string,\n userId?: string,\n expiresAtMs?: number,\n principal?: WsConnectionPrincipal,\n ): Promise<boolean> {\n const maxFrameBytes = this.dispatcher.getGatewayMaxFrameBytes(path);\n if (maxFrameBytes === undefined) return false;\n if (\n expiresAtMs !== undefined &&\n (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now())\n ) {\n return false;\n }\n if (\n (principal !== undefined &&\n (expiresAtMs === undefined ||\n userId !== principal.subject ||\n !principal.issuer ||\n !principal.tenantId)) ||\n (expiresAtMs !== undefined && principal === undefined)\n ) {\n return false;\n }\n\n const connId = crypto.randomUUID();\n const attachment: WsAttachment = {\n version: 1,\n connId,\n state: 'pending',\n userId,\n principal:\n principal === undefined\n ? undefined\n : {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal?.tenantId,\n expiresAtMs,\n path,\n maxFrameBytes,\n rooms: [roomId],\n data: {\n ...(userId ? { userId } : {}),\n ...(principal\n ? {\n principal: {\n issuer: principal.issuer,\n subject: principal.subject,\n principalType: principal.principalType,\n },\n tenantId: principal.tenantId,\n }\n : {}),\n ...(expiresAtMs !== undefined ? { expiresAtMs } : {}),\n },\n };\n if (new TextEncoder().encode(JSON.stringify(attachment)).byteLength > MAX_WS_ATTACHMENT_BYTES) {\n return false;\n }\n try {\n this.ctx.acceptWebSocket(ws, [roomTag(roomId), connTag(connId)]);\n ws.serializeAttachment(attachment);\n } catch {\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n\n const client = this.registry.clientFor(ws);\n try {\n // Broadcasts the hook issues skip this still-pending socket.\n await this.registry.admitting(ws, () => this.dispatcher.handleOpen(path, client));\n // Another callback may have rejected the socket while the asynchronous\n // connection hook was still pending. Never resurrect that terminal state\n // after the hook resolves.\n if (!this.transition(ws, 'active', 'pending')) {\n throw new Error(\n socketAttachment(ws)?.state === 'rejected'\n ? 'WebSocket was rejected while OnGatewayConnection was running: a frame ' +\n 'arrived before the connection hook completed, or the connection closed or failed'\n : 'Unable to persist authorized WebSocket state',\n );\n }\n return true;\n } catch (err) {\n await this.dispatcher.handleError(path, client, err).catch(() => {});\n this.transition(ws, 'rejected');\n try {\n ws.close(1008, 'Connection rejected');\n } catch {\n // already closed\n }\n return false;\n }\n }\n\n async onMessage(ws: WsLike, message: string | ArrayBuffer): Promise<void> {\n if (!this.isActive(ws)) {\n this.reject(ws, 'Connection is not authorized');\n return;\n }\n let queue = this.#messages.get(ws);\n if (!queue) {\n const path = socketAttachment(ws)?.path;\n const options = this.dispatcher.collectEntrypoints().find((entry) => entry.meta.path === path)\n ?.meta.options;\n queue = new WsMessageQueue(\n () => this.reject(ws, 'WebSocket message budget exceeded', 1013),\n options?.maxPendingMessages,\n options?.maxPendingBytes,\n );\n this.#messages.set(ws, queue);\n }\n await queue.run(message, async () => {\n if (!this.isActive(ws)) return;\n const client = this.registry.clientFor(ws);\n await this.dispatcher.dispatchMessage(client.path, client, message);\n });\n }\n\n async onClose(ws: WsLike, code: number, reason: string): Promise<void> {\n this.#messages.get(ws)?.stop();\n if (!this.isActive(ws, false)) {\n this.transition(ws, 'rejected');\n try {\n ws.close();\n } catch {\n // already closed\n }\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleClose(client.path, client, code, reason);\n // Complete the closing handshake. Only 1000 and 3000-4999 are valid for\n // close(); reserved/abnormal codes (1005/1006/1015, etc.) throw a RangeError,\n // so fall back to a codeless close on those.\n try {\n if (code === 1000 || (code >= 3000 && code <= 4999)) ws.close(code, reason);\n else ws.close();\n } catch {\n // socket already closed\n }\n }\n\n async onError(ws: WsLike, err: unknown): Promise<void> {\n if (!this.isActive(ws, false)) {\n this.reject(ws, 'Connection failed before authorization');\n return;\n }\n const client = this.registry.clientFor(ws);\n await this.dispatcher.handleError(client.path, client, err);\n }\n\n /** Deliver a broadcast command to this DO's local sockets (RPC entry point). */\n broadcast(cmd: BroadcastCommand): void | Promise<void> {\n assertBroadcastCommandFits(cmd, this.dispatcher.getMaximumGatewayFrameBytes());\n return this.registry.deliverLocal(cmd);\n }\n\n private transition(\n ws: WsLike,\n state: WsAttachment['state'],\n expectedState?: WsAttachment['state'],\n ): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment) return false;\n if (expectedState !== undefined && attachment.state !== expectedState) return false;\n attachment.state = state;\n ws.serializeAttachment(attachment);\n return true;\n } catch {\n return false;\n }\n }\n\n private isActive(ws: WsLike, checkExpiry = true): boolean {\n try {\n const attachment = socketAttachment(ws);\n if (!attachment || attachment.state !== 'active') return false;\n return (\n !checkExpiry ||\n attachment.expiresAtMs === undefined ||\n (Number.isSafeInteger(attachment.expiresAtMs) && attachment.expiresAtMs > Date.now())\n );\n } catch {\n return false;\n }\n }\n\n private reject(ws: WsLike, reason: string, code = 1008): void {\n this.#messages.get(ws)?.stop();\n this.transition(ws, 'rejected');\n try {\n ws.close(code, reason);\n } catch {\n // already closed\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,kBAAb,MAA6B;CAGR;CACA;CACA;CACA;CALnB,4BAAqB,IAAI,QAAgC;CACzD,YACE,KACA,YACA,UACA,eAAmD,CAAC,GACpD;EAJiB,KAAA,MAAA;EACA,KAAA,aAAA;EACA,KAAA,WAAA;EACA,KAAA,eAAA;CAChB;;CAGH,cAAkC;EAChC,OAAO,KAAK,aAAa;CAC3B;;;;;;CAOA,MAAM,OACJ,IACA,MACA,QACA,QACA,aACA,WACkB;EAClB,MAAM,gBAAgB,KAAK,WAAW,wBAAwB,IAAI;EAClE,IAAI,kBAAkB,KAAA,GAAW,OAAO;EACxC,IACE,gBAAgB,KAAA,MACf,CAAC,OAAO,cAAc,WAAW,KAAK,eAAe,KAAK,IAAI,IAE/D,OAAO;EAET,IACG,cAAc,KAAA,MACZ,gBAAgB,KAAA,KACf,WAAW,UAAU,WACrB,CAAC,UAAU,UACX,CAAC,UAAU,aACd,gBAAgB,KAAA,KAAa,cAAc,KAAA,GAE5C,OAAO;EAGT,MAAM,SAAS,OAAO,WAAW;EACjC,MAA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M,SAAS,KAAK,SAAS,UAAU,EAAE;EACzC,MAAM,KAAK,WAAW,YAAY,OAAO,MAAM,QAAQ,GAAG;CAC5D;;CAGA,UAAU,KAA6C;EACrD,2BAA2B,KAAK,KAAK,WAAW,4BAA4B,CAAC;EAC7E,OAAO,KAAK,SAAS,aAAa,GAAG;CACvC;CAEA,WACE,IACA,OACA,eACS;EACT,IAAI;GACF,MAAM,aAAa,iBAAiB,EAAE;GACtC,IAAI,CAAC,YAAY,OAAO;GACxB,IAAI,kBAAkB,KAAA,KAAa,WAAW,UAAU,eAAe,OAAO;GAC9E,WAAW,QAAQ;GACnB,GAAG,oBAAoB,UAAU;GACjC,OAAO;EACT,QAAQ;GACN,OAAO;EACT;CACF;CAEA,SAAiB,IAAY,cAAc,MAAe;EACxD,IAAI;GACF,MAAM,aAAa,iBAAiB,EAAE;GACtC,IAAI,CAAC,cAAc,WAAW,UAAU,UAAU,OAAO;GACzD,OACE,CAAC,eACD,WAAW,gBAAgB,KAAA,KAC1B,OAAO,cAAc,WAAW,WAAW,KAAK,WAAW,cAAc,KAAK,IAAI;EAEvF,QAAQ;GACN,OAAO;EACT;CACF;CAEA,OAAe,IAAY,QAAgB,OAAO,MAAY;EAC5D,KAAK,UAAU,IAAI,EAAE,CAAC,EAAE,KAAK;EAC7B,KAAK,WAAW,IAAI,UAAU;EAC9B,IAAI;GACF,GAAG,MAAM,MAAM,MAAM;EACvB,QAAQ,CAER;CACF;AACF"}
@@ -0,0 +1,149 @@
1
+ import { gatewayObjectRoom } from "./room-id.js";
2
+ import { bindingGateways } from "./binding-gateways.js";
3
+ import { gatewayRoomObject } from "./worker-transport.js";
4
+ import { DiscoveryService } from "@velajs/vela/module-kit";
5
+ //#region src/websocket/live-driver.ts
6
+ const DEFAULT_ROOM = "default";
7
+ function describeFilter({ binding, gatewayPath }) {
8
+ return [...binding === void 0 ? [] : [`binding '${binding}'`], ...gatewayPath === void 0 ? [] : [`path '${gatewayPath}'`]].join(" and ");
9
+ }
10
+ /** A commit stamp a room object returned, validated before it reaches headers. */
11
+ function commitStamp(value) {
12
+ if (value === void 0) return void 0;
13
+ const cursor = typeof value === "object" && value !== null ? Reflect.get(value, "cursor") : void 0;
14
+ const epoch = typeof value === "object" && value !== null ? Reflect.get(value, "epoch") : void 0;
15
+ if (typeof cursor !== "number" || typeof epoch !== "string") throw new Error("Durable Object invalidate() returned an invalid commit stamp");
16
+ return {
17
+ cursor,
18
+ epoch
19
+ };
20
+ }
21
+ /**
22
+ * Delivers live invalidations to the room Durable Object of a
23
+ * `@WebSocketGateway({ binding })`, whose SQLite log stamps the commit. Inside
24
+ * that Durable Object the same driver applies invalidations locally.
25
+ */
26
+ var CfLiveDriver = class {
27
+ options;
28
+ kind = "durable-object";
29
+ #sink;
30
+ #local = false;
31
+ #context;
32
+ #target;
33
+ constructor(options = {}) {
34
+ this.options = options;
35
+ }
36
+ bind(sink) {
37
+ this.#sink = sink;
38
+ }
39
+ /** @internal The Worker's live platform supplies its environment and gateways. */
40
+ _attach(context) {
41
+ this.#context = context;
42
+ this.#target = void 0;
43
+ }
44
+ /** @internal A Durable Object dispatches to its own engine and SQLite log. */
45
+ _setLocalMode() {
46
+ this.#local = true;
47
+ }
48
+ /**
49
+ * @internal The Durable Object that holds one room's subscriptions. As for
50
+ * upgrades and `Gateways` pushes, a gateway without `roomParam` keeps every
51
+ * socket in one room, its path, so each of its rooms is in that object.
52
+ */
53
+ _room(room) {
54
+ const { env, binding, gatewayPath } = this.#resolveTarget();
55
+ return gatewayRoomObject(env, gatewayPath, binding, gatewayObjectRoom(gatewayPath, room));
56
+ }
57
+ dispatch(cmd) {
58
+ if (this.#local) return this.#sink?.applyInvalidation(cmd);
59
+ const room = cmd.room ?? this.options.defaultRoom ?? DEFAULT_ROOM;
60
+ return this._room(room).call("invalidate", {
61
+ ...cmd,
62
+ room
63
+ }).then(commitStamp);
64
+ }
65
+ #resolveTarget() {
66
+ if (this.#target) return this.#target;
67
+ const context = this.#context;
68
+ if (!context) throw new Error("durableObjectLive() needs the Cloudflare adapter: create the application with createCloudflareWorker(), createCloudflareApp() or cloudflareAdapter().");
69
+ let { binding, gatewayPath } = this.options;
70
+ const gateways = context.gateways();
71
+ if (binding === void 0 || gatewayPath === void 0) {
72
+ const candidates = gateways.filter((gateway) => (binding === void 0 || gateway.binding === binding) && (gatewayPath === void 0 || gateway.path === gatewayPath));
73
+ const [chosen, ...others] = candidates;
74
+ if (!chosen) {
75
+ const filter = describeFilter(this.options);
76
+ throw new Error(filter ? `durableObjectLive() found no @WebSocketGateway with ${filter}. Name the gateway that holds the subscriptions, with its binding.` : "LiveModule delivers Worker invalidations to the room Durable Object of a gateway, but no @WebSocketGateway names a binding. Declare one with { binding }, or pass driver: () => durableObjectLive({ binding, gatewayPath }).");
77
+ }
78
+ if (others.length > 0) {
79
+ const paths = candidates.map((gateway) => `'${gateway.path}'`).join(", ");
80
+ throw new Error(`LiveModule must choose where Worker invalidations go, but several binding-backed gateways (${paths}) could hold the subscriptions. Pass driver: () => durableObjectLive({ gatewayPath }) to LiveModule.`);
81
+ }
82
+ binding ??= chosen.binding;
83
+ gatewayPath ??= chosen.path;
84
+ }
85
+ const target = {
86
+ env: context.env,
87
+ binding,
88
+ gatewayPath
89
+ };
90
+ this.#target = target;
91
+ return target;
92
+ }
93
+ };
94
+ /**
95
+ * The Cloudflare live driver, for `LiveModule.forRoot({ driver })`. It is the
96
+ * default on Cloudflare, so name it only to choose a gateway, binding or
97
+ * default room:
98
+ *
99
+ * ```ts
100
+ * LiveModule.forRoot({ driver: () => durableObjectLive({ gatewayPath: '/rooms/:id/ws' }) })
101
+ * ```
102
+ */
103
+ function durableObjectLive(options = {}) {
104
+ return new CfLiveDriver(options);
105
+ }
106
+ let workerLocalLiveWarned = false;
107
+ /**
108
+ * The Worker isolate's live platform: invalidations default to the room
109
+ * Durable Object of the application's binding-backed gateway, chosen and read
110
+ * from `ENV` when first needed, and `LiveInspector` reads each room from that
111
+ * object. A configured local driver is warned about once per isolate:
112
+ * subscriptions live in the Durable Object, so it would reach none.
113
+ */
114
+ function workerLivePlatform(env, container) {
115
+ const context = {
116
+ env,
117
+ gateways: () => bindingGateways(container.resolve(DiscoveryService))
118
+ };
119
+ let bound;
120
+ return {
121
+ liveDriver: () => durableObjectLive(),
122
+ async inspect(room) {
123
+ if (!bound) throw new Error("LiveModule delivers locally in this Worker: no room to inspect");
124
+ const value = await bound._room(room).call("inspectLive");
125
+ const subscriptions = typeof value === "object" && value !== null ? Reflect.get(value, "subscriptions") : void 0;
126
+ const rooms = typeof value === "object" && value !== null ? Reflect.get(value, "rooms") : void 0;
127
+ if (!Array.isArray(subscriptions) || !Array.isArray(rooms)) throw new Error("Durable Object inspectLive() returned an invalid snapshot");
128
+ return {
129
+ subscriptions,
130
+ rooms
131
+ };
132
+ },
133
+ bindDriver(driver) {
134
+ if (driver instanceof CfLiveDriver) {
135
+ driver._attach(context);
136
+ bound = driver;
137
+ return;
138
+ }
139
+ if (driver.kind !== "local" || workerLocalLiveWarned) return;
140
+ if (container.getDiagnostics() === "silent") return;
141
+ workerLocalLiveWarned = true;
142
+ console.warn("[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live in the WebSocket Durable Object, so invalidations sent from the Worker never reach them. Remove the driver option to deliver through the gateway room Durable Object.");
143
+ }
144
+ };
145
+ }
146
+ //#endregion
147
+ export { CfLiveDriver, durableObjectLive, workerLivePlatform };
148
+
149
+ //# sourceMappingURL=live-driver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-driver.js","names":[],"sources":["../../src/websocket/live-driver.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport { DiscoveryService, type Container } from '@velajs/vela/module-kit';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveDriver,\n LiveInvalidationSink,\n LivePlatform,\n} from '@velajs/vela/live';\nimport { bindingGateways, type BindingGateway } from './binding-gateways';\nimport { gatewayObjectRoom } from './room-id';\nimport { gatewayRoomObject, type GatewayRoomObject } from './worker-transport';\n\nconst DEFAULT_ROOM = 'default';\n\nexport interface DurableObjectLiveOptions {\n /**\n * Durable Object namespace binding that holds the gateway's rooms, read from\n * the application's `ENV` when an invalidation first needs it. Defaults to\n * the `binding` of the chosen gateway.\n */\n binding?: string;\n /**\n * Exact `@WebSocketGateway()` path whose rooms hold the subscriptions.\n * Defaults to the single gateway backed by `binding` (or by any binding).\n */\n gatewayPath?: string;\n /**\n * Room used when an invalidation names none. Matches the client default. A\n * gateway without `roomParam` has one room, its path, which every\n * invalidation reaches.\n */\n defaultRoom?: string;\n}\n\nexport interface LiveInvalidateStub {\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n}\n\n/** Only the native namespace operations required for live invalidation. */\nexport interface LiveNamespace {\n idFromName(name: string): DurableObjectId;\n get(id: DurableObjectId): LiveInvalidateStub;\n}\n\n/** @internal What the Worker's live platform hands a driver. */\ninterface WorkerLiveContext {\n env: VelaEnv;\n gateways(): readonly Pick<BindingGateway, 'path' | 'binding'>[];\n}\n\n/** Where the Worker delivers invalidations: one gateway's room objects. */\ninterface LiveTarget {\n env: VelaEnv;\n binding: string;\n gatewayPath: string;\n}\n\nfunction describeFilter({ binding, gatewayPath }: DurableObjectLiveOptions): string {\n const parts = [\n ...(binding === undefined ? [] : [`binding '${binding}'`]),\n ...(gatewayPath === undefined ? [] : [`path '${gatewayPath}'`]),\n ];\n return parts.join(' and ');\n}\n\n/** A commit stamp a room object returned, validated before it reaches headers. */\nfunction commitStamp(value: unknown): CommitStamp | undefined {\n if (value === undefined) return undefined;\n const cursor: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'cursor') : undefined;\n const epoch: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'epoch') : undefined;\n if (typeof cursor !== 'number' || typeof epoch !== 'string') {\n throw new Error('Durable Object invalidate() returned an invalid commit stamp');\n }\n return { cursor, epoch };\n}\n\n/**\n * Delivers live invalidations to the room Durable Object of a\n * `@WebSocketGateway({ binding })`, whose SQLite log stamps the commit. Inside\n * that Durable Object the same driver applies invalidations locally.\n */\nexport class CfLiveDriver implements LiveDriver {\n readonly kind = 'durable-object';\n #sink: LiveInvalidationSink | undefined;\n #local = false;\n #context: WorkerLiveContext | undefined;\n #target: LiveTarget | undefined;\n\n constructor(private readonly options: DurableObjectLiveOptions = {}) {}\n\n bind(sink: LiveInvalidationSink): void {\n this.#sink = sink;\n }\n\n /** @internal The Worker's live platform supplies its environment and gateways. */\n _attach(context: WorkerLiveContext): void {\n this.#context = context;\n this.#target = undefined;\n }\n\n /** @internal A Durable Object dispatches to its own engine and SQLite log. */\n _setLocalMode(): void {\n this.#local = true;\n }\n\n /**\n * @internal The Durable Object that holds one room's subscriptions. As for\n * upgrades and `Gateways` pushes, a gateway without `roomParam` keeps every\n * socket in one room, its path, so each of its rooms is in that object.\n */\n _room(room: string): GatewayRoomObject {\n const { env, binding, gatewayPath } = this.#resolveTarget();\n return gatewayRoomObject(env, gatewayPath, binding, gatewayObjectRoom(gatewayPath, room));\n }\n\n dispatch(cmd: InvalidationCommand): Promise<CommitStamp | undefined> | CommitStamp | undefined {\n if (this.#local) return this.#sink?.applyInvalidation(cmd);\n const room = cmd.room ?? this.options.defaultRoom ?? DEFAULT_ROOM;\n return this._room(room)\n .call('invalidate', { ...cmd, room })\n .then(commitStamp);\n }\n\n #resolveTarget(): LiveTarget {\n if (this.#target) return this.#target;\n const context = this.#context;\n if (!context) {\n throw new Error(\n 'durableObjectLive() needs the Cloudflare adapter: create the application with ' +\n 'createCloudflareWorker(), createCloudflareApp() or cloudflareAdapter().',\n );\n }\n let { binding, gatewayPath } = this.options;\n const gateways = context.gateways();\n if (binding === undefined || gatewayPath === undefined) {\n const candidates = gateways.filter(\n (gateway) =>\n (binding === undefined || gateway.binding === binding) &&\n (gatewayPath === undefined || gateway.path === gatewayPath),\n );\n const [chosen, ...others] = candidates;\n if (!chosen) {\n const filter = describeFilter(this.options);\n throw new Error(\n filter\n ? `durableObjectLive() found no @WebSocketGateway with ${filter}. Name the gateway ` +\n 'that holds the subscriptions, with its binding.'\n : 'LiveModule delivers Worker invalidations to the room Durable Object of a ' +\n 'gateway, but no @WebSocketGateway names a binding. Declare one with ' +\n '{ binding }, or pass driver: () => durableObjectLive({ binding, gatewayPath }).',\n );\n }\n if (others.length > 0) {\n const paths = candidates.map((gateway) => `'${gateway.path}'`).join(', ');\n throw new Error(\n `LiveModule must choose where Worker invalidations go, but several binding-backed ` +\n `gateways (${paths}) could hold the subscriptions. Pass ` +\n 'driver: () => durableObjectLive({ gatewayPath }) to LiveModule.',\n );\n }\n binding ??= chosen.binding;\n gatewayPath ??= chosen.path;\n }\n const target: LiveTarget = { env: context.env, binding, gatewayPath };\n this.#target = target;\n return target;\n }\n}\n\n/**\n * The Cloudflare live driver, for `LiveModule.forRoot({ driver })`. It is the\n * default on Cloudflare, so name it only to choose a gateway, binding or\n * default room:\n *\n * ```ts\n * LiveModule.forRoot({ driver: () => durableObjectLive({ gatewayPath: '/rooms/:id/ws' }) })\n * ```\n */\nexport function durableObjectLive(options: DurableObjectLiveOptions = {}): CfLiveDriver {\n return new CfLiveDriver(options);\n}\n\nlet workerLocalLiveWarned = false;\n\n/**\n * The Worker isolate's live platform: invalidations default to the room\n * Durable Object of the application's binding-backed gateway, chosen and read\n * from `ENV` when first needed, and `LiveInspector` reads each room from that\n * object. A configured local driver is warned about once per isolate:\n * subscriptions live in the Durable Object, so it would reach none.\n */\nexport function workerLivePlatform(env: VelaEnv, container: Container): LivePlatform {\n const context: WorkerLiveContext = {\n env,\n gateways: () => bindingGateways(container.resolve(DiscoveryService)),\n };\n let bound: CfLiveDriver | undefined;\n return {\n liveDriver: () => durableObjectLive(),\n async inspect(room) {\n if (!bound) throw new Error('LiveModule delivers locally in this Worker: no room to inspect');\n const value: unknown = await bound._room(room).call('inspectLive');\n const subscriptions: unknown =\n typeof value === 'object' && value !== null\n ? Reflect.get(value, 'subscriptions')\n : undefined;\n const rooms: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'rooms') : undefined;\n if (!Array.isArray(subscriptions) || !Array.isArray(rooms)) {\n throw new Error('Durable Object inspectLive() returned an invalid snapshot');\n }\n return { subscriptions, rooms };\n },\n bindDriver(driver) {\n if (driver instanceof CfLiveDriver) {\n driver._attach(context);\n bound = driver;\n return;\n }\n if (driver.kind !== 'local' || workerLocalLiveWarned) return;\n if (container.getDiagnostics() === 'silent') return;\n workerLocalLiveWarned = true;\n console.warn(\n '[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live ' +\n 'in the WebSocket Durable Object, so invalidations sent from the Worker never reach ' +\n 'them. Remove the driver option to deliver through the gateway room Durable Object.',\n );\n },\n };\n}\n"],"mappings":";;;;;AAaA,MAAM,eAAe;AA6CrB,SAAS,eAAe,EAAE,SAAS,eAAiD;CAKlF,OAAO,CAHL,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,CAAC,YAAY,QAAQ,EAAE,GACxD,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,CAAC,SAAS,YAAY,EAAE,CAEpD,CAAC,CAAC,KAAK,OAAO;AAC3B;;AAGA,SAAS,YAAY,OAAyC;CAC5D,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,SACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,QAAQ,IAAI,KAAA;CAC/E,MAAM,QACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,OAAO,IAAI,KAAA;CAC9E,IAAI,OAAO,WAAW,YAAY,OAAO,UAAU,UACjD,MAAM,IAAI,MAAM,8DAA8D;CAEhF,OAAO;EAAE;EAAQ;CAAM;AACzB;;;;;;AAOA,IAAa,eAAb,MAAgD;CAOjB;CAN7B,OAAgB;CAChB;CACA,SAAS;CACT;CACA;CAEA,YAAY,UAAqD,CAAC,GAAG;EAAxC,KAAA,UAAA;CAAyC;CAEtE,KAAK,MAAkC;EACrC,KAAK,QAAQ;CACf;;CAGA,QAAQ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;GAAE,KAAK,QAAQ;GAAK;GAAS;EAAY;EACpE,KAAK,UAAU;EACf,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAgB,kBAAkB,UAAoC,CAAC,GAAiB;CACtF,OAAO,IAAI,aAAa,OAAO;AACjC;AAEA,IAAI,wBAAwB;;;;;;;;AAS5B,SAAgB,mBAAmB,KAAc,WAAoC;CACnF,MAAM,UAA6B;EACjC;EACA,gBAAgB,gBAAgB,UAAU,QAAQ,gBAAgB,CAAC;CACrE;CACA,IAAI;CACJ,OAAO;EACL,kBAAkB,kBAAkB;EACpC,MAAM,QAAQ,MAAM;GAClB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,gEAAgE;GAC5F,MAAM,QAAiB,MAAM,MAAM,MAAM,IAAI,CAAC,CAAC,KAAK,aAAa;GACjE,MAAM,gBACJ,OAAO,UAAU,YAAY,UAAU,OACnC,QAAQ,IAAI,OAAO,eAAe,IAClC,KAAA;GACN,MAAM,QACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,OAAO,IAAI,KAAA;GAC9E,IAAI,CAAC,MAAM,QAAQ,aAAa,KAAK,CAAC,MAAM,QAAQ,KAAK,GACvD,MAAM,IAAI,MAAM,2DAA2D;GAE7E,OAAO;IAAE;IAAe;GAAM;EAChC;EACA,WAAW,QAAQ;GACjB,IAAI,kBAAkB,cAAc;IAClC,OAAO,QAAQ,OAAO;IACtB,QAAQ;IACR;GACF;GACA,IAAI,OAAO,SAAS,WAAW,uBAAuB;GACtD,IAAI,UAAU,eAAe,MAAM,UAAU;GAC7C,wBAAwB;GACxB,QAAQ,KACN,8PAGF;EACF;CACF;AACF"}
@@ -0,0 +1,37 @@
1
+ //#region src/websocket/room-id.ts
2
+ /** Hibernation tag marking a socket's hub room (set at accept; immutable after). */
3
+ function roomTag(roomId) {
4
+ return `room:${roomId}`;
5
+ }
6
+ /** Hibernation tag addressing one connection directly. */
7
+ function connTag(connId) {
8
+ return `conn:${connId}`;
9
+ }
10
+ const DO_ROOM_NAME_PREFIX = "vela:ws:v2:";
11
+ const MAX_DO_ROOM_NAME_BYTES = 1024;
12
+ const encoder = new TextEncoder();
13
+ /** Stable, collision-free Durable Object name for one gateway's room. */
14
+ function durableObjectRoomName(gatewayPath, roomId) {
15
+ if (typeof gatewayPath !== "string" || gatewayPath.length === 0 || typeof roomId !== "string" || roomId.length === 0 || /[\u0000-\u001f\u007f]/.test(gatewayPath) || /[\u0000-\u001f\u007f]/.test(roomId)) throw new Error("A non-empty, control-free gateway path and room id are required");
16
+ const name = `${DO_ROOM_NAME_PREFIX}${encodeURIComponent(gatewayPath)}:${encodeURIComponent(roomId)}`;
17
+ if (encoder.encode(name).byteLength > MAX_DO_ROOM_NAME_BYTES) throw new Error("The gateway/room Durable Object name exceeds 1024 bytes");
18
+ return name;
19
+ }
20
+ const PATH_PARAM = /:[A-Za-z_]/;
21
+ /**
22
+ * The room whose Durable Object holds `room` of the gateway at `gatewayPath`.
23
+ * A gateway without roomParam (its path has no parameters) admits every
24
+ * upgrade into one room, its path, so each room it names lives in that object;
25
+ * upgrades, `Gateways` pushes and live invalidations resolve the same way.
26
+ */
27
+ function gatewayObjectRoom(gatewayPath, room) {
28
+ return PATH_PARAM.test(gatewayPath) ? room : gatewayPath;
29
+ }
30
+ /** One Durable Object instance per gateway + room, addressed by name. */
31
+ function roomToDurableId(ns, gatewayPath, roomId) {
32
+ return ns.idFromName(durableObjectRoomName(gatewayPath, roomId));
33
+ }
34
+ //#endregion
35
+ export { connTag, durableObjectRoomName, gatewayObjectRoom, roomTag, roomToDurableId };
36
+
37
+ //# sourceMappingURL=room-id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room-id.js","names":[],"sources":["../../src/websocket/room-id.ts"],"sourcesContent":["// Canonical room ↔ Durable Object mappings. The SAME functions are used by the\n// Worker upgrade route (to pick the DO) and by every server-initiated emit — so\n// a connection and a later broadcast always resolve to the same DO instance.\n\n/** Hibernation tag marking a socket's hub room (set at accept; immutable after). */\nexport function roomTag(roomId: string): string {\n return `room:${roomId}`;\n}\n\n/** Hibernation tag addressing one connection directly. */\nexport function connTag(connId: string): string {\n return `conn:${connId}`;\n}\n\nconst DO_ROOM_NAME_PREFIX = 'vela:ws:v2:';\nconst MAX_DO_ROOM_NAME_BYTES = 1_024;\nconst encoder = new TextEncoder();\n\n/** Stable, collision-free Durable Object name for one gateway's room. */\nexport function durableObjectRoomName(gatewayPath: string, roomId: string): string {\n if (\n typeof gatewayPath !== 'string' ||\n gatewayPath.length === 0 ||\n typeof roomId !== 'string' ||\n roomId.length === 0 ||\n /[\\u0000-\\u001f\\u007f]/.test(gatewayPath) ||\n /[\\u0000-\\u001f\\u007f]/.test(roomId)\n ) {\n throw new Error('A non-empty, control-free gateway path and room id are required');\n }\n const name = `${DO_ROOM_NAME_PREFIX}${encodeURIComponent(gatewayPath)}:${encodeURIComponent(roomId)}`;\n if (encoder.encode(name).byteLength > MAX_DO_ROOM_NAME_BYTES) {\n throw new Error('The gateway/room Durable Object name exceeds 1024 bytes');\n }\n return name;\n}\n\n// A path parameter (`:name`): a gateway declares roomParam exactly when its\n// path has one, which WsDispatcher validates at bootstrap.\nconst PATH_PARAM = /:[A-Za-z_]/;\n\n/**\n * The room whose Durable Object holds `room` of the gateway at `gatewayPath`.\n * A gateway without roomParam (its path has no parameters) admits every\n * upgrade into one room, its path, so each room it names lives in that object;\n * upgrades, `Gateways` pushes and live invalidations resolve the same way.\n */\nexport function gatewayObjectRoom(gatewayPath: string, room: string): string {\n return PATH_PARAM.test(gatewayPath) ? room : gatewayPath;\n}\n\n/** One Durable Object instance per gateway + room, addressed by name. */\nexport function roomToDurableId(\n ns: Pick<DurableObjectNamespace, 'idFromName'>,\n gatewayPath: string,\n roomId: string,\n): DurableObjectId {\n return ns.idFromName(durableObjectRoomName(gatewayPath, roomId));\n}\n"],"mappings":";;AAKA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;;AAGA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;AAEA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,UAAU,IAAI,YAAY;;AAGhC,SAAgB,sBAAsB,aAAqB,QAAwB;CACjF,IACE,OAAO,gBAAgB,YACvB,YAAY,WAAW,KACvB,OAAO,WAAW,YAClB,OAAO,WAAW,KAClB,wBAAwB,KAAK,WAAW,KACxC,wBAAwB,KAAK,MAAM,GAEnC,MAAM,IAAI,MAAM,iEAAiE;CAEnF,MAAM,OAAO,GAAG,sBAAsB,mBAAmB,WAAW,EAAE,GAAG,mBAAmB,MAAM;CAClG,IAAI,QAAQ,OAAO,IAAI,CAAC,CAAC,aAAa,wBACpC,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;AACT;AAIA,MAAM,aAAa;;;;;;;AAQnB,SAAgB,kBAAkB,aAAqB,MAAsB;CAC3E,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO;AAC/C;;AAGA,SAAgB,gBACd,IACA,aACA,QACiB;CACjB,OAAO,GAAG,WAAW,sBAAsB,aAAa,MAAM,CAAC;AACjE"}
@@ -0,0 +1,142 @@
1
+ import { FORWARDED_UPGRADE_HEADERS } from "./worker-transport.js";
2
+ import { armDoPitr, readDoPitrBookmark } from "./do-pitr.js";
3
+ import { DoWebSocketHost } from "./do-websocket-host.js";
4
+ import { buildDoRuntime } from "./do-bootstrap.js";
5
+ import { DurableObject } from "cloudflare:workers";
6
+ //#region src/websocket/websocket.durable-object.ts
7
+ const PING = "{\"event\":\"$ping\"}";
8
+ const PONG = "{\"event\":\"$pong\"}";
9
+ const MAX_IDENTITY_FIELD_BYTES = 2048;
10
+ const encoder = new TextEncoder();
11
+ function isIdentityField(value) {
12
+ return value !== null && value.length > 0 && encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES;
13
+ }
14
+ /**
15
+ * Base class for the WebSocket Durable Object. The user exports a named subclass
16
+ * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, or
17
+ * from a `DynamicModule` declared at module scope:
18
+ *
19
+ * ```ts
20
+ * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}
21
+ * ```
22
+ *
23
+ * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
24
+ * bridge DO hibernation) and forwards every event into the runtime-agnostic
25
+ * `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core
26
+ * `WebSocketModule.forRoot()`: this object registers the platform that binds
27
+ * its server to these sockets, delivers live invalidations locally and keeps
28
+ * the live cursor log in its SQLite storage. The DO's `env` is the
29
+ * application's ENV, as in the Worker.
30
+ */
31
+ function VelaWebSocketDurableObject(rootModule) {
32
+ return class VelaWsDurableObject extends DurableObject {
33
+ host;
34
+ liveEngine;
35
+ ready;
36
+ constructor(ctx, env) {
37
+ super(ctx, env);
38
+ try {
39
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));
40
+ } catch {}
41
+ this.ready = ctx.blockConcurrencyWhile(async () => {
42
+ const runtime = await buildDoRuntime(rootModule, ctx, { env });
43
+ this.host = new DoWebSocketHost(ctx, runtime.dispatcher, runtime.registry, runtime.gatewayPaths);
44
+ this.liveEngine = runtime.live;
45
+ });
46
+ }
47
+ /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */
48
+ async inspectLive() {
49
+ await this.ready;
50
+ return this.liveEngine?.inspect() ?? {
51
+ subscriptions: [],
52
+ rooms: []
53
+ };
54
+ }
55
+ async fetch(request) {
56
+ await this.ready;
57
+ if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected WebSocket upgrade", { status: 426 });
58
+ const url = new URL(request.url);
59
+ const roomId = request.headers.get(FORWARDED_UPGRADE_HEADERS.room) ?? this.ctx.id.name ?? url.pathname;
60
+ const path = request.headers.get(FORWARDED_UPGRADE_HEADERS.path) ?? this.host.defaultPath() ?? url.pathname;
61
+ const userId = request.headers.get(FORWARDED_UPGRADE_HEADERS.user) || void 0;
62
+ const rawExpiresAtMs = request.headers.get(FORWARDED_UPGRADE_HEADERS.expiresAtMs);
63
+ const parsedExpiresAtMs = rawExpiresAtMs === null ? void 0 : Number(rawExpiresAtMs);
64
+ if (parsedExpiresAtMs !== void 0 && (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)) return new Response("Invalid WebSocket identity expiry", { status: 403 });
65
+ const issuer = request.headers.get(FORWARDED_UPGRADE_HEADERS.issuer);
66
+ const subject = request.headers.get(FORWARDED_UPGRADE_HEADERS.subject);
67
+ const principalType = request.headers.get(FORWARDED_UPGRADE_HEADERS.principalType);
68
+ const tenantId = request.headers.get(FORWARDED_UPGRADE_HEADERS.tenant);
69
+ const hasPrincipalHeader = issuer !== null || subject !== null || principalType !== null || tenantId !== null;
70
+ let principal;
71
+ if (hasPrincipalHeader) {
72
+ if (!isIdentityField(issuer) || !isIdentityField(subject) || principalType !== "user" && principalType !== "service" || !isIdentityField(tenantId) || parsedExpiresAtMs === void 0 || userId !== void 0 && userId !== subject) return new Response("Invalid WebSocket principal", { status: 403 });
73
+ principal = {
74
+ issuer,
75
+ subject,
76
+ principalType,
77
+ tenantId
78
+ };
79
+ } else if (parsedExpiresAtMs !== void 0) return new Response("WebSocket identity tuple is missing", { status: 403 });
80
+ if (parsedExpiresAtMs !== void 0 && parsedExpiresAtMs <= Date.now()) return new Response("WebSocket identity expired", { status: 403 });
81
+ const { 0: client, 1: server } = new WebSocketPair();
82
+ if (!await this.host.accept(server, path, roomId, userId, parsedExpiresAtMs, principal)) return new Response("WebSocket connection rejected", { status: 403 });
83
+ return new Response(null, {
84
+ status: 101,
85
+ webSocket: client
86
+ });
87
+ }
88
+ async webSocketMessage(ws, message) {
89
+ await this.ready;
90
+ await this.host.onMessage(ws, message);
91
+ }
92
+ async webSocketClose(ws, code, reason) {
93
+ await this.ready;
94
+ await this.host.onClose(ws, code, reason);
95
+ }
96
+ async webSocketError(ws, error) {
97
+ await this.ready;
98
+ await this.host.onError(ws, error);
99
+ }
100
+ /** DO RPC — a `Gateways` push forwarded from the Worker or another room's object. */
101
+ async broadcast(cmd) {
102
+ await this.ready;
103
+ await this.host.broadcast(cmd);
104
+ }
105
+ /**
106
+ * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /
107
+ * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns
108
+ * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription
109
+ * refreshes fan out asynchronously.
110
+ */
111
+ async invalidate(cmd) {
112
+ await this.ready;
113
+ return this.liveEngine?.applyInvalidation(cmd);
114
+ }
115
+ /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */
116
+ async pitrCurrentBookmark() {
117
+ await this.ready;
118
+ return readDoPitrBookmark(this.ctx.storage);
119
+ }
120
+ /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */
121
+ async pitrBookmarkForTime(time) {
122
+ await this.ready;
123
+ return readDoPitrBookmark(this.ctx.storage, time);
124
+ }
125
+ /**
126
+ * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is
127
+ * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so
128
+ * the recovery applies on the immediately-following session; otherwise the
129
+ * restore applies on the next natural restart (`restarted: false`).
130
+ */
131
+ async pitrArmRestore(opts) {
132
+ await this.ready;
133
+ const result = await armDoPitr(this.ctx.storage, opts);
134
+ if (opts.restart === true) this.ctx.abort("vela PITR restore");
135
+ return result;
136
+ }
137
+ };
138
+ }
139
+ //#endregion
140
+ export { VelaWebSocketDurableObject };
141
+
142
+ //# sourceMappingURL=websocket.durable-object.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.durable-object.js","names":["FORWARDED"],"sources":["../../src/websocket/websocket.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveEngine,\n LiveInspection,\n} from '@velajs/vela/live';\nimport { buildDoRuntime } from './do-bootstrap';\nimport { DoWebSocketHost, type WsConnectionPrincipal } from './do-websocket-host';\nimport { armDoPitr, readDoPitrBookmark } from './do-pitr';\nimport { FORWARDED_UPGRADE_HEADERS as FORWARDED } from './worker-transport';\nimport type { CloudflareRoot } from '../root-module';\nimport type {\n DoPitrArmOptions,\n DoPitrArmResult,\n DoPitrBookmarkRead,\n VelaDoPitrRpc,\n} from './do-pitr';\n\nconst PING = '{\"event\":\"$ping\"}';\nconst PONG = '{\"event\":\"$pong\"}';\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\nfunction isIdentityField(value: string | null): value is string {\n return (\n value !== null &&\n value.length > 0 &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/**\n * Base class for the WebSocket Durable Object. The user exports a named subclass\n * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, or\n * from a `DynamicModule` declared at module scope:\n *\n * ```ts\n * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}\n * ```\n *\n * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot\n * bridge DO hibernation) and forwards every event into the runtime-agnostic\n * `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core\n * `WebSocketModule.forRoot()`: this object registers the platform that binds\n * its server to these sockets, delivers live invalidations locally and keeps\n * the live cursor log in its SQLite storage. The DO's `env` is the\n * application's ENV, as in the Worker.\n */\nexport function VelaWebSocketDurableObject(rootModule: CloudflareRoot): new (\n ctx: DurableObjectState,\n env: VelaEnv,\n) => DurableObject<VelaEnv> &\n VelaDoPitrRpc & {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n inspectLive(): Promise<LiveInspection>;\n } {\n return class VelaWsDurableObject extends DurableObject<VelaEnv> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: VelaEnv) {\n super(ctx, env);\n // Application-level ping/pong answered WITHOUT waking a hibernated DO.\n try {\n ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));\n } catch {\n // Older runtimes without auto-response — fine, protocol pings still work.\n }\n this.ready = ctx.blockConcurrencyWhile(async () => {\n // The root is static, so constructing another instance declares no new\n // classes in the isolate-global metadata registry.\n const runtime = await buildDoRuntime(rootModule, ctx, { env });\n this.host = new DoWebSocketHost(\n ctx,\n runtime.dispatcher,\n runtime.registry,\n runtime.gatewayPaths,\n );\n this.liveEngine = runtime.live;\n });\n }\n\n /** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */\n async inspectLive(): Promise<LiveInspection> {\n await this.ready;\n return this.liveEngine?.inspect() ?? { subscriptions: [], rooms: [] };\n }\n\n override async fetch(request: Request): Promise<Response> {\n await this.ready;\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected WebSocket upgrade', { status: 426 });\n }\n\n const url = new URL(request.url);\n // Headers are primary (carry auth + multi-gateway routing); fall back to the\n // DO's own name (set via idFromName(room)) and the single gateway path so a\n // plain `stub.fetch(request)` forward still works.\n const roomId = request.headers.get(FORWARDED.room) ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get(FORWARDED.path) ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get(FORWARDED.user) || undefined;\n const rawExpiresAtMs = request.headers.get(FORWARDED.expiresAtMs);\n const parsedExpiresAtMs = rawExpiresAtMs === null ? undefined : Number(rawExpiresAtMs);\n if (\n parsedExpiresAtMs !== undefined &&\n (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)\n ) {\n return new Response('Invalid WebSocket identity expiry', { status: 403 });\n }\n\n const issuer = request.headers.get(FORWARDED.issuer);\n const subject = request.headers.get(FORWARDED.subject);\n const principalType = request.headers.get(FORWARDED.principalType);\n const tenantId = request.headers.get(FORWARDED.tenant);\n const hasPrincipalHeader =\n issuer !== null || subject !== null || principalType !== null || tenantId !== null;\n let principal: WsConnectionPrincipal | undefined;\n if (hasPrincipalHeader) {\n if (\n !isIdentityField(issuer) ||\n !isIdentityField(subject) ||\n (principalType !== 'user' && principalType !== 'service') ||\n !isIdentityField(tenantId) ||\n parsedExpiresAtMs === undefined ||\n (userId !== undefined && userId !== subject)\n ) {\n return new Response('Invalid WebSocket principal', { status: 403 });\n }\n principal = { issuer, subject, principalType, tenantId };\n } else if (parsedExpiresAtMs !== undefined) {\n return new Response('WebSocket identity tuple is missing', { status: 403 });\n }\n\n if (parsedExpiresAtMs !== undefined && parsedExpiresAtMs <= Date.now()) {\n return new Response('WebSocket identity expired', { status: 403 });\n }\n\n const { 0: client, 1: server } = new WebSocketPair();\n const accepted = await this.host.accept(\n server,\n path,\n roomId,\n userId,\n parsedExpiresAtMs,\n principal,\n );\n if (!accepted) return new Response('WebSocket connection rejected', { status: 403 });\n return new Response(null, { status: 101, webSocket: client });\n }\n\n override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {\n await this.ready;\n await this.host.onMessage(ws, message);\n }\n\n override async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {\n await this.ready;\n await this.host.onClose(ws, code, reason);\n }\n\n override async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n await this.ready;\n await this.host.onError(ws, error);\n }\n\n /** DO RPC — a `Gateways` push forwarded from the Worker or another room's object. */\n async broadcast(cmd: BroadcastCommand): Promise<void> {\n await this.ready;\n await this.host.broadcast(cmd);\n }\n\n /**\n * DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /\n * liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns\n * the commit stamp (what `Vela-Commit-Cursor` carries); the subscription\n * refreshes fan out asynchronously.\n */\n async invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined> {\n await this.ready;\n return this.liveEngine?.applyInvalidation(cmd);\n }\n\n // -- Durable Object PITR (point-in-time recovery) RPC ---------------------\n //\n // GUARD / reachability: these are admin-privileged operations (a restore can\n // roll the DO's SQLite state back up to 30 days and, with `restart`, abort\n // the DO to apply it now). They are safe to expose here because a Durable\n // Object's RPC methods are NOT network-reachable: a `DurableObjectStub` is\n // obtainable ONLY from a Worker that binds this DO namespace, and RPC calls\n // travel Cloudflare's internal capability channel — never the public\n // internet. A WebSocket/HTTP client reaches only `fetch()` above, never these\n // methods. The security boundary is therefore the WORKER-SIDE studio admin\n // gate that fronts the `CloudflareDoTimeTravelPort` (master admin token + the\n // 428 confirm challenge) — the identical trust model as `broadcast()` /\n // `invalidate()` on this same DO. See `do-pitr.ts` for the storage wrappers.\n\n /** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */\n async pitrCurrentBookmark(): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage);\n }\n\n /** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */\n async pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead> {\n await this.ready;\n return readDoPitrBookmark(this.ctx.storage, time);\n }\n\n /**\n * DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is\n * requested, `ctx.abort()` is called AFTER the undo bookmark is computed so\n * the recovery applies on the immediately-following session; otherwise the\n * restore applies on the next natural restart (`restarted: false`).\n */\n async pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult> {\n await this.ready;\n const result = await armDoPitr(this.ctx.storage, opts);\n if (opts.restart === true) this.ctx.abort('vela PITR restore');\n return result;\n }\n };\n}\n"],"mappings":";;;;;;AAqBA,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,2BAA2B;AACjC,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,gBAAgB,OAAuC;CAC9D,OACE,UAAU,QACV,MAAM,SAAS,KACf,QAAQ,OAAO,KAAK,CAAC,CAAC,cAAc;AAExC;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,2BAA2B,YAQvC;CACF,OAAO,MAAM,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A,MAAe,eAAe,IAAe,OAA+B;GAC1E,MAAM,KAAK;GACX,MAAM,KAAK,KAAK,QAAQ,IAAI,KAAK;EACnC;;EAGA,MAAM,UAAU,KAAsC;GACpD,MAAM,KAAK;GACX,MAAM,KAAK,KAAK,UAAU,GAAG;EAC/B;;;;;;;EAQA,MAAM,WAAW,KAA4D;GAC3E,MAAM,KAAK;GACX,OAAO,KAAK,YAAY,kBAAkB,GAAG;EAC/C;;EAiBA,MAAM,sBAAmD;GACvD,MAAM,KAAK;GACX,OAAO,mBAAmB,KAAK,IAAI,OAAO;EAC5C;;EAGA,MAAM,oBAAoB,MAAoD;GAC5E,MAAM,KAAK;GACX,OAAO,mBAAmB,KAAK,IAAI,SAAS,IAAI;EAClD;;;;;;;EAQA,MAAM,eAAe,MAAkD;GACrE,MAAM,KAAK;GACX,MAAM,SAAS,MAAM,UAAU,KAAK,IAAI,SAAS,IAAI;GACrD,IAAI,KAAK,YAAY,MAAM,KAAK,IAAI,MAAM,mBAAmB;GAC7D,OAAO;EACT;CACF;AACF"}
@@ -0,0 +1,80 @@
1
+ import { durableObjectRoomName } from "./room-id.js";
2
+ import { DURABLE_OBJECT_NAMESPACE } from "../bindings.js";
3
+ import { resolveBinding } from "@velajs/vela/module-kit";
4
+ //#region src/websocket/worker-transport.ts
5
+ /**
6
+ * Headers that carry trusted upgrade values from the Worker's upgrade route to
7
+ * the room's Durable Object. The route removes client copies before any
8
+ * application hook runs; the Durable Object reads only these.
9
+ */
10
+ const FORWARDED_UPGRADE_HEADERS = {
11
+ room: "x-vela-room",
12
+ path: "x-vela-path",
13
+ user: "x-vela-user",
14
+ issuer: "x-vela-issuer",
15
+ subject: "x-vela-subject",
16
+ principalType: "x-vela-principal-type",
17
+ tenant: "x-vela-tenant",
18
+ expiresAtMs: "x-vela-expires-at-ms"
19
+ };
20
+ const FORWARDING_HEADERS = [...Object.values(FORWARDED_UPGRADE_HEADERS), "x-vela-expires-at"];
21
+ function operation(target, name) {
22
+ const value = Reflect.get(target, name);
23
+ if (typeof value !== "function") throw new Error(`Durable Object ${name}() is unavailable`);
24
+ return value;
25
+ }
26
+ /**
27
+ * The Durable Object that holds one gateway room, one object per gateway and
28
+ * room, in the namespace the gateway's `binding` names in ENV, resolved through
29
+ * the binding seam. Room objects are application classes, so validate only
30
+ * the stub operations called here.
31
+ */
32
+ function gatewayRoomObject(env, gatewayPath, binding, room) {
33
+ if (binding === void 0) throw new Error(`Gateway '${gatewayPath}' names no binding: declare @WebSocketGateway({ binding })`);
34
+ const namespace = resolveBinding(env, { binding }, DURABLE_OBJECT_NAMESPACE);
35
+ const id = namespace.idFromName(durableObjectRoomName(gatewayPath, room));
36
+ return {
37
+ id,
38
+ async call(method, ...args) {
39
+ const stub = namespace.get(id);
40
+ if (typeof stub !== "object" || stub === null) throw new Error("Invalid Durable Object stub");
41
+ return Reflect.apply(operation(stub, method), stub, args);
42
+ }
43
+ };
44
+ }
45
+ /**
46
+ * The Worker isolate's WebSocket transport. Sockets live in each gateway
47
+ * room's Durable Object, so the Worker keeps none: `Gateways` pushes become a
48
+ * `broadcast` RPC to the room's object (the server gateways inject refuses
49
+ * pushes with guidance to `Gateways`), and each authenticated upgrade goes to
50
+ * the object named by the gateway's `binding`, carrying the verified identity
51
+ * in {@link FORWARDED_UPGRADE_HEADERS}. The Durable Object returns the `101`
52
+ * with the client socket.
53
+ */
54
+ function workerWebSocketTransport(env) {
55
+ return {
56
+ forwardingHeaders: FORWARDING_HEADERS,
57
+ async deliver({ gatewayPath, binding, room, command }) {
58
+ await gatewayRoomObject(env, gatewayPath, binding, room).call("broadcast", command);
59
+ },
60
+ async forwardUpgrade({ request, gatewayPath, room, binding, identity }) {
61
+ const headers = new Headers(request.headers);
62
+ const names = FORWARDED_UPGRADE_HEADERS;
63
+ headers.set(names.room, room);
64
+ headers.set(names.path, gatewayPath);
65
+ headers.set(names.user, identity.principal.subject);
66
+ headers.set(names.issuer, identity.principal.issuer);
67
+ headers.set(names.subject, identity.principal.subject);
68
+ headers.set(names.principalType, identity.principal.principalType);
69
+ headers.set(names.tenant, identity.tenantId);
70
+ headers.set(names.expiresAtMs, String(identity.expiresAtMs));
71
+ const response = await gatewayRoomObject(env, gatewayPath, binding, room).call("fetch", new Request(request, { headers }));
72
+ if (!(response instanceof Response)) throw new Error("Durable Object returned an invalid response");
73
+ return response;
74
+ }
75
+ };
76
+ }
77
+ //#endregion
78
+ export { FORWARDED_UPGRADE_HEADERS, gatewayRoomObject, workerWebSocketTransport };
79
+
80
+ //# sourceMappingURL=worker-transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-transport.js","names":[],"sources":["../../src/websocket/worker-transport.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport type { ForwardedWebSocketUpgrade, WebSocketTransport } from '@velajs/vela/websocket';\nimport { resolveBinding } from '@velajs/vela/module-kit';\nimport { DURABLE_OBJECT_NAMESPACE } from '../bindings';\nimport { durableObjectRoomName } from './room-id';\n\n/**\n * Headers that carry trusted upgrade values from the Worker's upgrade route to\n * the room's Durable Object. The route removes client copies before any\n * application hook runs; the Durable Object reads only these.\n */\nexport const FORWARDED_UPGRADE_HEADERS = {\n room: 'x-vela-room',\n path: 'x-vela-path',\n user: 'x-vela-user',\n issuer: 'x-vela-issuer',\n subject: 'x-vela-subject',\n principalType: 'x-vela-principal-type',\n tenant: 'x-vela-tenant',\n expiresAtMs: 'x-vela-expires-at-ms',\n} as const;\n\nconst FORWARDING_HEADERS: readonly string[] = [\n ...Object.values(FORWARDED_UPGRADE_HEADERS),\n // Retired header name: still removed so a client can never supply it.\n 'x-vela-expires-at',\n];\n\nfunction operation(target: object, name: string): Function {\n const value: unknown = Reflect.get(target, name);\n if (typeof value !== 'function') throw new Error(`Durable Object ${name}() is unavailable`);\n return value;\n}\n\n/** One gateway room's Durable Object: its id, and calls to its operations. */\nexport interface GatewayRoomObject {\n readonly id: unknown;\n call(method: string, ...args: unknown[]): Promise<unknown>;\n}\n\n/**\n * The Durable Object that holds one gateway room, one object per gateway and\n * room, in the namespace the gateway's `binding` names in ENV, resolved through\n * the binding seam. Room objects are application classes, so validate only\n * the stub operations called here.\n */\nexport function gatewayRoomObject(\n env: VelaEnv,\n gatewayPath: string,\n binding: string | undefined,\n room: string,\n): GatewayRoomObject {\n if (binding === undefined) {\n throw new Error(\n `Gateway '${gatewayPath}' names no binding: declare @WebSocketGateway({ binding })`,\n );\n }\n const namespace = resolveBinding(env, { binding }, DURABLE_OBJECT_NAMESPACE);\n const id = namespace.idFromName(durableObjectRoomName(gatewayPath, room));\n return {\n id,\n async call(method, ...args) {\n const stub: unknown = namespace.get(id);\n if (typeof stub !== 'object' || stub === null) throw new Error('Invalid Durable Object stub');\n return Reflect.apply(operation(stub, method), stub, args);\n },\n };\n}\n\n/**\n * The Worker isolate's WebSocket transport. Sockets live in each gateway\n * room's Durable Object, so the Worker keeps none: `Gateways` pushes become a\n * `broadcast` RPC to the room's object (the server gateways inject refuses\n * pushes with guidance to `Gateways`), and each authenticated upgrade goes to\n * the object named by the gateway's `binding`, carrying the verified identity\n * in {@link FORWARDED_UPGRADE_HEADERS}. The Durable Object returns the `101`\n * with the client socket.\n */\nexport function workerWebSocketTransport(env: VelaEnv): WebSocketTransport {\n return {\n forwardingHeaders: FORWARDING_HEADERS,\n async deliver({ gatewayPath, binding, room, command }) {\n await gatewayRoomObject(env, gatewayPath, binding, room).call('broadcast', command);\n },\n async forwardUpgrade({\n request,\n gatewayPath,\n room,\n binding,\n identity,\n }: ForwardedWebSocketUpgrade) {\n const headers = new Headers(request.headers);\n const names = FORWARDED_UPGRADE_HEADERS;\n headers.set(names.room, room);\n headers.set(names.path, gatewayPath);\n headers.set(names.user, identity.principal.subject);\n headers.set(names.issuer, identity.principal.issuer);\n headers.set(names.subject, identity.principal.subject);\n headers.set(names.principalType, identity.principal.principalType);\n headers.set(names.tenant, identity.tenantId);\n headers.set(names.expiresAtMs, String(identity.expiresAtMs));\n const response: unknown = await gatewayRoomObject(env, gatewayPath, binding, room).call(\n 'fetch',\n new Request(request, { headers }),\n );\n if (!(response instanceof Response)) {\n throw new Error('Durable Object returned an invalid response');\n }\n return response;\n },\n };\n}\n"],"mappings":";;;;;;;;;AAWA,MAAa,4BAA4B;CACvC,MAAM;CACN,MAAM;CACN,MAAM;CACN,QAAQ;CACR,SAAS;CACT,eAAe;CACf,QAAQ;CACR,aAAa;AACf;AAEA,MAAM,qBAAwC,CAC5C,GAAG,OAAO,OAAO,yBAAyB,GAE1C,mBACF;AAEA,SAAS,UAAU,QAAgB,MAAwB;CACzD,MAAM,QAAiB,QAAQ,IAAI,QAAQ,IAAI;CAC/C,IAAI,OAAO,UAAU,YAAY,MAAM,IAAI,MAAM,kBAAkB,KAAK,kBAAkB;CAC1F,OAAO;AACT;;;;;;;AAcA,SAAgB,kBACd,KACA,aACA,SACA,MACmB;CACnB,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MACR,YAAY,YAAY,2DAC1B;CAEF,MAAM,YAAY,eAAe,KAAK,EAAE,QAAQ,GAAG,wBAAwB;CAC3E,MAAM,KAAK,UAAU,WAAW,sBAAsB,aAAa,IAAI,CAAC;CACxE,OAAO;EACL;EACA,MAAM,KAAK,QAAQ,GAAG,MAAM;GAC1B,MAAM,OAAgB,UAAU,IAAI,EAAE;GACtC,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,MAAM,IAAI,MAAM,6BAA6B;GAC5F,OAAO,QAAQ,MAAM,UAAU,MAAM,MAAM,GAAG,MAAM,IAAI;EAC1D;CACF;AACF;;;;;;;;;;AAWA,SAAgB,yBAAyB,KAAkC;CACzE,OAAO;EACL,mBAAmB;EACnB,MAAM,QAAQ,EAAE,aAAa,SAAS,MAAM,WAAW;GACrD,MAAM,kBAAkB,KAAK,aAAa,SAAS,IAAI,CAAC,CAAC,KAAK,aAAa,OAAO;EACpF;EACA,MAAM,eAAe,EACnB,SACA,aACA,MACA,SACA,YAC4B;GAC5B,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;GAC3C,MAAM,QAAQ;GACd,QAAQ,IAAI,MAAM,MAAM,IAAI;GAC5B,QAAQ,IAAI,MAAM,MAAM,WAAW;GACnC,QAAQ,IAAI,MAAM,MAAM,SAAS,UAAU,OAAO;GAClD,QAAQ,IAAI,MAAM,QAAQ,SAAS,UAAU,MAAM;GACnD,QAAQ,IAAI,MAAM,SAAS,SAAS,UAAU,OAAO;GACrD,QAAQ,IAAI,MAAM,eAAe,SAAS,UAAU,aAAa;GACjE,QAAQ,IAAI,MAAM,QAAQ,SAAS,QAAQ;GAC3C,QAAQ,IAAI,MAAM,aAAa,OAAO,SAAS,WAAW,CAAC;GAC3D,MAAM,WAAoB,MAAM,kBAAkB,KAAK,aAAa,SAAS,IAAI,CAAC,CAAC,KACjF,SACA,IAAI,QAAQ,SAAS,EAAE,QAAQ,CAAC,CAClC;GACA,IAAI,EAAE,oBAAoB,WACxB,MAAM,IAAI,MAAM,6CAA6C;GAE/D,OAAO;EACT;CACF;AACF"}
@@ -0,0 +1,79 @@
1
+ import { DEFAULT_WS_MAX_JOINED_ROOMS, assertWebSocketRoomId } from "@velajs/vela/websocket";
2
+ //#region src/websocket/ws-attachment.ts
3
+ const record = (value) => {
4
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
5
+ const prototype = Object.getPrototypeOf(value);
6
+ return (prototype === Object.prototype || prototype === null) && Reflect.ownKeys(value).every((key) => {
7
+ const property = Object.getOwnPropertyDescriptor(value, key);
8
+ return property !== void 0 && "value" in property;
9
+ });
10
+ };
11
+ const positive = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
12
+ const text = (value) => typeof value === "string" && value.length > 0 && new TextEncoder().encode(value).byteLength <= 2048;
13
+ /** Versionless 1.x records remain readable; malformed/future versions fail closed. */
14
+ function readWsAttachment(value) {
15
+ if (!record(value) || value.version !== void 0 && value.version !== 1) return void 0;
16
+ if (!text(value.connId) || typeof value.path !== "string" || value.path.length > 8192 || value.state !== "pending" && value.state !== "active" && value.state !== "rejected" || !Array.isArray(value.rooms) || value.rooms.length > DEFAULT_WS_MAX_JOINED_ROOMS || !record(value.data)) return void 0;
17
+ const rooms = [];
18
+ for (let index = 0; index < value.rooms.length; index++) {
19
+ const descriptor = Object.getOwnPropertyDescriptor(value.rooms, index);
20
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "string") return void 0;
21
+ const room = descriptor.value;
22
+ try {
23
+ assertWebSocketRoomId(room);
24
+ } catch {
25
+ return;
26
+ }
27
+ if (rooms.includes(room)) return void 0;
28
+ rooms.push(room);
29
+ }
30
+ if (value.maxFrameBytes !== void 0 && !positive(value.maxFrameBytes)) return void 0;
31
+ if (value.expiresAtMs !== void 0 && !positive(value.expiresAtMs)) return void 0;
32
+ if (value.userId !== void 0 && !text(value.userId)) return void 0;
33
+ if (value.tenantId !== void 0 && !text(value.tenantId)) return void 0;
34
+ let principal;
35
+ if (value.principal !== void 0) {
36
+ const p = value.principal;
37
+ if (!record(p) || !text(p.issuer) || !text(p.subject) || p.principalType !== "user" && p.principalType !== "service") return void 0;
38
+ principal = {
39
+ issuer: p.issuer,
40
+ subject: p.subject,
41
+ principalType: p.principalType
42
+ };
43
+ if (value.userId !== void 0 && value.userId !== p.subject) return void 0;
44
+ }
45
+ return {
46
+ version: 1,
47
+ connId: value.connId,
48
+ state: value.state,
49
+ path: value.path,
50
+ rooms,
51
+ data: { ...value.data },
52
+ ...principal ? { principal } : {},
53
+ ...typeof value.userId === "string" ? { userId: value.userId } : {},
54
+ ...typeof value.tenantId === "string" ? { tenantId: value.tenantId } : {},
55
+ ...typeof value.expiresAtMs === "number" ? { expiresAtMs: value.expiresAtMs } : {},
56
+ ...typeof value.maxFrameBytes === "number" ? { maxFrameBytes: value.maxFrameBytes } : {}
57
+ };
58
+ }
59
+ function socketAttachment(ws) {
60
+ try {
61
+ return readWsAttachment(ws.deserializeAttachment());
62
+ } catch {
63
+ return;
64
+ }
65
+ }
66
+ function rejectedAttachment() {
67
+ return {
68
+ version: 1,
69
+ connId: "",
70
+ state: "rejected",
71
+ path: "",
72
+ rooms: [],
73
+ data: {}
74
+ };
75
+ }
76
+ //#endregion
77
+ export { readWsAttachment, rejectedAttachment, socketAttachment };
78
+
79
+ //# sourceMappingURL=ws-attachment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ws-attachment.js","names":[],"sources":["../../src/websocket/ws-attachment.ts"],"sourcesContent":["import { assertWebSocketRoomId, DEFAULT_WS_MAX_JOINED_ROOMS } from '@velajs/vela/websocket';\nimport type { WsAttachment, WsLike } from './do-state';\n\nconst record = (value: unknown): value is Record<string, unknown> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === Object.prototype || prototype === null) &&\n Reflect.ownKeys(value).every((key) => {\n const property = Object.getOwnPropertyDescriptor(value, key);\n return property !== undefined && 'value' in property;\n })\n );\n};\nconst positive = (value: unknown): value is number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\nconst text = (value: unknown): value is string =>\n typeof value === 'string' &&\n value.length > 0 &&\n new TextEncoder().encode(value).byteLength <= 2048;\n\n/** Versionless 1.x records remain readable; malformed/future versions fail closed. */\nexport function readWsAttachment(value: unknown): WsAttachment | undefined {\n if (!record(value) || (value.version !== undefined && value.version !== 1)) return undefined;\n if (\n !text(value.connId) ||\n typeof value.path !== 'string' ||\n value.path.length > 8192 ||\n (value.state !== 'pending' && value.state !== 'active' && value.state !== 'rejected') ||\n !Array.isArray(value.rooms) ||\n value.rooms.length > DEFAULT_WS_MAX_JOINED_ROOMS ||\n !record(value.data)\n )\n return undefined;\n const rooms: string[] = [];\n for (let index = 0; index < value.rooms.length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(value.rooms, index);\n if (!descriptor || !('value' in descriptor) || typeof descriptor.value !== 'string')\n return undefined;\n const room: string = descriptor.value;\n try {\n assertWebSocketRoomId(room);\n } catch {\n return undefined;\n }\n if (rooms.includes(room)) return undefined;\n rooms.push(room);\n }\n if (value.maxFrameBytes !== undefined && !positive(value.maxFrameBytes)) return undefined;\n if (value.expiresAtMs !== undefined && !positive(value.expiresAtMs)) return undefined;\n if (value.userId !== undefined && !text(value.userId)) return undefined;\n if (value.tenantId !== undefined && !text(value.tenantId)) return undefined;\n let principal: WsAttachment['principal'];\n if (value.principal !== undefined) {\n const p = value.principal;\n if (\n !record(p) ||\n !text(p.issuer) ||\n !text(p.subject) ||\n (p.principalType !== 'user' && p.principalType !== 'service')\n )\n return undefined;\n principal = { issuer: p.issuer, subject: p.subject, principalType: p.principalType };\n if (value.userId !== undefined && value.userId !== p.subject) return undefined;\n }\n return {\n version: 1,\n connId: value.connId,\n state: value.state,\n path: value.path,\n rooms,\n data: { ...value.data },\n ...(principal ? { principal } : {}),\n ...(typeof value.userId === 'string' ? { userId: value.userId } : {}),\n ...(typeof value.tenantId === 'string' ? { tenantId: value.tenantId } : {}),\n ...(typeof value.expiresAtMs === 'number' ? { expiresAtMs: value.expiresAtMs } : {}),\n ...(typeof value.maxFrameBytes === 'number' ? { maxFrameBytes: value.maxFrameBytes } : {}),\n };\n}\n\nexport function socketAttachment(ws: WsLike): WsAttachment | undefined {\n try {\n return readWsAttachment(ws.deserializeAttachment());\n } catch {\n return undefined;\n }\n}\n\nexport function rejectedAttachment(): WsAttachment {\n return { version: 1, connId: '', state: 'rejected', path: '', rooms: [], data: {} };\n}\n"],"mappings":";;AAGA,MAAM,UAAU,UAAqD;CACnE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CACxE,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,QACG,cAAc,OAAO,aAAa,cAAc,SACjD,QAAQ,QAAQ,KAAK,CAAC,CAAC,OAAO,QAAQ;EACpC,MAAM,WAAW,OAAO,yBAAyB,OAAO,GAAG;EAC3D,OAAO,aAAa,KAAA,KAAa,WAAW;CAC9C,CAAC;AAEL;AACA,MAAM,YAAY,UAChB,OAAO,UAAU,YA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