@velajs/cloudflare 1.10.1 → 1.22.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/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.md +197 -322
- package/dist/durable-objects.d.ts +28 -0
- package/dist/durable-objects.js +494 -0
- package/dist/durable-objects.js.map +1 -0
- package/dist/index.d.ts +193 -376
- package/dist/index.js +412 -1034
- package/dist/index.js.map +1 -1
- package/dist/nonce-validation-LE0vFk-7.js +445 -0
- package/dist/nonce-validation-LE0vFk-7.js.map +1 -0
- package/dist/nonce.durable-object-Df3_42Sy.d.ts +141 -0
- package/package.json +34 -26
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { l as VelaDoPitrRpc, p as CloudflareRoot, t as VelaNonceDurableObject } from "./nonce.durable-object-Df3_42Sy.js";
|
|
2
|
+
import { InjectionToken } from "@velajs/vela";
|
|
3
|
+
import { BroadcastCommand } from "@velajs/vela/websocket";
|
|
4
|
+
import { CommitStamp, InvalidationCommand, LiveInspection } from "@velajs/vela/live";
|
|
5
|
+
import { DurableObject } from "cloudflare:workers";
|
|
6
|
+
//#region src/websocket/websocket.durable-object.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Base class for the WebSocket Durable Object. The user exports a named subclass
|
|
9
|
+
* (matching their `wrangler.toml` `class_name`) built from their `AppModule`:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
|
|
16
|
+
* bridge DO hibernation) and forwards every event into the runtime-agnostic
|
|
17
|
+
* `WsDispatcher` via {@link DoWebSocketHost}.
|
|
18
|
+
*/
|
|
19
|
+
export declare function VelaWebSocketDurableObject<T extends object>(rootModule: CloudflareRoot<NoInfer<T>>, options: {
|
|
20
|
+
envToken: InjectionToken<T>;
|
|
21
|
+
}): new (ctx: DurableObjectState, env: T) => DurableObject<T> & VelaDoPitrRpc & {
|
|
22
|
+
broadcast(cmd: BroadcastCommand): Promise<void>;
|
|
23
|
+
invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;
|
|
24
|
+
inspectLive(): Promise<LiveInspection>;
|
|
25
|
+
};
|
|
26
|
+
//#endregion
|
|
27
|
+
export { VelaNonceDurableObject };
|
|
28
|
+
//# sourceMappingURL=durable-objects.d.ts.map
|
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
import { S as roomTag, _ as resolveCloudflareRoot, b as connTag, d as WsServerHolder, h as readDoPitrBookmark, l as CfWsClient, n as isValidExpiry, o as initDoLive, p as armDoPitr, s as initializeDoLiveResources, t as isCanonicalBoundedText, y as registerCloudflareEnvironment } from "./nonce-validation-LE0vFk-7.js";
|
|
2
|
+
import { VelaApplication, bootstrap } from "@velajs/vela";
|
|
3
|
+
import { WS_SERVER, WsDispatcher, WsServerImpl, assertBroadcastCommandFits, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
|
|
4
|
+
import { DurableObject } from "cloudflare:workers";
|
|
5
|
+
//#region src/websocket/cf-room-registry.ts
|
|
6
|
+
/**
|
|
7
|
+
* Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room
|
|
8
|
+
* membership lives in tags (hub room, set at accept) + the attachment (dynamic
|
|
9
|
+
* `join()`), never in DO instance fields — so it survives hibernation with zero
|
|
10
|
+
* rehydration.
|
|
11
|
+
*/
|
|
12
|
+
var CfRoomRegistry = class {
|
|
13
|
+
ctx;
|
|
14
|
+
deliveryAuthorizer;
|
|
15
|
+
frameLimitForPath;
|
|
16
|
+
constructor(ctx) {
|
|
17
|
+
this.ctx = ctx;
|
|
18
|
+
}
|
|
19
|
+
setDeliveryAuthorizer(authorizer) {
|
|
20
|
+
this.deliveryAuthorizer = authorizer;
|
|
21
|
+
}
|
|
22
|
+
/** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */
|
|
23
|
+
setFrameLimitResolver(resolver) {
|
|
24
|
+
this.frameLimitForPath = resolver;
|
|
25
|
+
}
|
|
26
|
+
register(_client) {}
|
|
27
|
+
leaveAll(_client) {}
|
|
28
|
+
join(client, room) {
|
|
29
|
+
return client.join(room);
|
|
30
|
+
}
|
|
31
|
+
leave(client, room) {
|
|
32
|
+
return client.leave(room);
|
|
33
|
+
}
|
|
34
|
+
localIdsInRoom(room) {
|
|
35
|
+
return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);
|
|
36
|
+
}
|
|
37
|
+
deliverLocal(cmd) {
|
|
38
|
+
const excludeIds = new Set(cmd.exceptIds ?? []);
|
|
39
|
+
const excludeRooms = cmd.exceptRooms ?? [];
|
|
40
|
+
const targets = cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);
|
|
41
|
+
const seen = /* @__PURE__ */ new Set();
|
|
42
|
+
const selected = [];
|
|
43
|
+
for (const ws of targets) {
|
|
44
|
+
const att = this.reconcileFrameLimit(ws, this.attachmentOf(ws));
|
|
45
|
+
if (seen.has(att.connId)) continue;
|
|
46
|
+
seen.add(att.connId);
|
|
47
|
+
if (att.state !== "active" || att.expiresAtMs !== void 0 && (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now())) {
|
|
48
|
+
try {
|
|
49
|
+
att.state = "rejected";
|
|
50
|
+
ws.serializeAttachment(att);
|
|
51
|
+
ws.close(1008, "identity expired or connection rejected");
|
|
52
|
+
} catch {}
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (excludeIds.has(att.connId)) continue;
|
|
56
|
+
if (excludeRooms.some((r) => att.rooms.includes(r))) continue;
|
|
57
|
+
selected.push({
|
|
58
|
+
ws,
|
|
59
|
+
client: new CfWsClient(this.ctx, ws)
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
if (!this.deliveryAuthorizer) {
|
|
63
|
+
for (const { client } of selected) client.sendRaw(cmd.frame);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
return Promise.all(selected.map(async ({ ws, client }) => {
|
|
67
|
+
let allowed = false;
|
|
68
|
+
try {
|
|
69
|
+
allowed = await this.deliveryAuthorizer(client) === true;
|
|
70
|
+
} catch {
|
|
71
|
+
allowed = false;
|
|
72
|
+
}
|
|
73
|
+
if (allowed) client.sendRaw(cmd.frame);
|
|
74
|
+
else this.reject(ws, "delivery authorization revoked");
|
|
75
|
+
})).then(() => void 0);
|
|
76
|
+
}
|
|
77
|
+
collectRooms(rooms) {
|
|
78
|
+
const set = /* @__PURE__ */ new Set();
|
|
79
|
+
for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);
|
|
80
|
+
return [...set];
|
|
81
|
+
}
|
|
82
|
+
socketsForRoom(room) {
|
|
83
|
+
return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));
|
|
84
|
+
}
|
|
85
|
+
attachmentOf(ws) {
|
|
86
|
+
return ws.deserializeAttachment() ?? {
|
|
87
|
+
connId: "",
|
|
88
|
+
state: "rejected",
|
|
89
|
+
path: "",
|
|
90
|
+
rooms: [],
|
|
91
|
+
data: {}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */
|
|
95
|
+
clientFor(ws) {
|
|
96
|
+
this.reconcileFrameLimit(ws, this.attachmentOf(ws));
|
|
97
|
+
return new CfWsClient(this.ctx, ws);
|
|
98
|
+
}
|
|
99
|
+
reconcileFrameLimit(ws, attachment) {
|
|
100
|
+
const expected = this.frameLimitForPath?.(attachment.path);
|
|
101
|
+
if (expected !== void 0 && attachment.maxFrameBytes !== expected) {
|
|
102
|
+
attachment.maxFrameBytes = expected;
|
|
103
|
+
ws.serializeAttachment(attachment);
|
|
104
|
+
}
|
|
105
|
+
return attachment;
|
|
106
|
+
}
|
|
107
|
+
reject(ws, reason) {
|
|
108
|
+
try {
|
|
109
|
+
const attachment = this.attachmentOf(ws);
|
|
110
|
+
attachment.state = "rejected";
|
|
111
|
+
ws.serializeAttachment(attachment);
|
|
112
|
+
ws.close(1008, reason);
|
|
113
|
+
} catch {}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/websocket/do-websocket-host.ts
|
|
118
|
+
/**
|
|
119
|
+
* The socket lifecycle inside a WebSocket Durable Object, decoupled from the
|
|
120
|
+
* `cloudflare:workers` base class so it is unit-testable with fakes. The thin
|
|
121
|
+
* `VelaWebSocketDurableObject` shell forwards its hibernation callbacks here.
|
|
122
|
+
*/
|
|
123
|
+
var DoWebSocketHost = class {
|
|
124
|
+
ctx;
|
|
125
|
+
dispatcher;
|
|
126
|
+
registry;
|
|
127
|
+
gatewayPaths;
|
|
128
|
+
constructor(ctx, dispatcher, registry, gatewayPaths = []) {
|
|
129
|
+
this.ctx = ctx;
|
|
130
|
+
this.dispatcher = dispatcher;
|
|
131
|
+
this.registry = registry;
|
|
132
|
+
this.gatewayPaths = gatewayPaths;
|
|
133
|
+
}
|
|
134
|
+
/** The single registered gateway's path — a fallback when the Worker didn't forward `x-vela-path`. */
|
|
135
|
+
defaultPath() {
|
|
136
|
+
return this.gatewayPaths[0];
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Accept a hibernatable socket: tag it with its hub room + connection id,
|
|
140
|
+
* persist the attachment, then await `OnGatewayConnection` before the caller
|
|
141
|
+
* returns 101. A rejected lifecycle hook closes and fails the upgrade.
|
|
142
|
+
*/
|
|
143
|
+
async accept(ws, path, roomId, userId, expiresAtMs, principal) {
|
|
144
|
+
const maxFrameBytes = this.dispatcher.getGatewayMaxFrameBytes(path);
|
|
145
|
+
if (maxFrameBytes === void 0) return false;
|
|
146
|
+
if (expiresAtMs !== void 0 && (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now())) return false;
|
|
147
|
+
if (principal !== void 0 && (expiresAtMs === void 0 || userId !== principal.subject || !principal.issuer || !principal.tenantId) || expiresAtMs !== void 0 && principal === void 0) return false;
|
|
148
|
+
const connId = crypto.randomUUID();
|
|
149
|
+
const attachment = {
|
|
150
|
+
connId,
|
|
151
|
+
state: "pending",
|
|
152
|
+
userId,
|
|
153
|
+
principal: principal === void 0 ? void 0 : {
|
|
154
|
+
issuer: principal.issuer,
|
|
155
|
+
subject: principal.subject,
|
|
156
|
+
principalType: principal.principalType
|
|
157
|
+
},
|
|
158
|
+
tenantId: principal?.tenantId,
|
|
159
|
+
expiresAtMs,
|
|
160
|
+
path,
|
|
161
|
+
maxFrameBytes,
|
|
162
|
+
rooms: [roomId],
|
|
163
|
+
data: {
|
|
164
|
+
...userId ? { userId } : {},
|
|
165
|
+
...principal ? {
|
|
166
|
+
principal: {
|
|
167
|
+
issuer: principal.issuer,
|
|
168
|
+
subject: principal.subject,
|
|
169
|
+
principalType: principal.principalType
|
|
170
|
+
},
|
|
171
|
+
tenantId: principal.tenantId
|
|
172
|
+
} : {},
|
|
173
|
+
...expiresAtMs !== void 0 ? { expiresAtMs } : {}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
if (new TextEncoder().encode(JSON.stringify(attachment)).byteLength > 16384) return false;
|
|
177
|
+
try {
|
|
178
|
+
this.ctx.acceptWebSocket(ws, [roomTag(roomId), connTag(connId)]);
|
|
179
|
+
ws.serializeAttachment(attachment);
|
|
180
|
+
} catch {
|
|
181
|
+
try {
|
|
182
|
+
ws.close(1008, "Connection rejected");
|
|
183
|
+
} catch {}
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
const client = this.registry.clientFor(ws);
|
|
187
|
+
try {
|
|
188
|
+
await this.dispatcher.handleOpen(path, client);
|
|
189
|
+
if (!this.transition(ws, "active", "pending")) throw new Error("Unable to persist authorized WebSocket state");
|
|
190
|
+
return true;
|
|
191
|
+
} catch (err) {
|
|
192
|
+
await this.dispatcher.handleError(path, client, err).catch(() => {});
|
|
193
|
+
this.transition(ws, "rejected");
|
|
194
|
+
try {
|
|
195
|
+
ws.close(1008, "Connection rejected");
|
|
196
|
+
} catch {}
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async onMessage(ws, message) {
|
|
201
|
+
if (!this.isActive(ws)) {
|
|
202
|
+
this.reject(ws, "Connection is not authorized");
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const client = this.registry.clientFor(ws);
|
|
206
|
+
await this.dispatcher.dispatchMessage(client.path, client, message);
|
|
207
|
+
}
|
|
208
|
+
async onClose(ws, code, reason) {
|
|
209
|
+
if (!this.isActive(ws, false)) {
|
|
210
|
+
this.transition(ws, "rejected");
|
|
211
|
+
try {
|
|
212
|
+
ws.close();
|
|
213
|
+
} catch {}
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const client = this.registry.clientFor(ws);
|
|
217
|
+
await this.dispatcher.handleClose(client.path, client, code, reason);
|
|
218
|
+
try {
|
|
219
|
+
if (code === 1e3 || code >= 3e3 && code <= 4999) ws.close(code, reason);
|
|
220
|
+
else ws.close();
|
|
221
|
+
} catch {}
|
|
222
|
+
}
|
|
223
|
+
async onError(ws, err) {
|
|
224
|
+
if (!this.isActive(ws, false)) {
|
|
225
|
+
this.reject(ws, "Connection failed before authorization");
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
const client = this.registry.clientFor(ws);
|
|
229
|
+
await this.dispatcher.handleError(client.path, client, err);
|
|
230
|
+
}
|
|
231
|
+
/** Deliver a broadcast command to this DO's local sockets (RPC entry point). */
|
|
232
|
+
broadcast(cmd) {
|
|
233
|
+
assertBroadcastCommandFits(cmd, this.dispatcher.getMaximumGatewayFrameBytes());
|
|
234
|
+
return this.registry.deliverLocal(cmd);
|
|
235
|
+
}
|
|
236
|
+
transition(ws, state, expectedState) {
|
|
237
|
+
try {
|
|
238
|
+
const attachment = ws.deserializeAttachment();
|
|
239
|
+
if (!attachment) return false;
|
|
240
|
+
if (expectedState !== void 0 && attachment.state !== expectedState) return false;
|
|
241
|
+
attachment.state = state;
|
|
242
|
+
ws.serializeAttachment(attachment);
|
|
243
|
+
return true;
|
|
244
|
+
} catch {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
isActive(ws, checkExpiry = true) {
|
|
249
|
+
try {
|
|
250
|
+
const attachment = ws.deserializeAttachment();
|
|
251
|
+
if (!attachment || attachment.state !== "active") return false;
|
|
252
|
+
return !checkExpiry || attachment.expiresAtMs === void 0 || Number.isSafeInteger(attachment.expiresAtMs) && attachment.expiresAtMs > Date.now();
|
|
253
|
+
} catch {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
reject(ws, reason) {
|
|
258
|
+
this.transition(ws, "rejected");
|
|
259
|
+
try {
|
|
260
|
+
ws.close(1008, reason);
|
|
261
|
+
} catch {}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/websocket/do-bootstrap.ts
|
|
266
|
+
/**
|
|
267
|
+
* Slim DI bootstrap for the Durable Object isolate: wires the container and runs
|
|
268
|
+
* `OnModuleInit`/`OnApplicationBootstrap` (so `WsDispatcher` discovers gateways)
|
|
269
|
+
* WITHOUT building the Hono app/routes the DO never serves. Cloudflare binding
|
|
270
|
+
* refs are initialized straight from the DO's `env`, and the ctx-backed server
|
|
271
|
+
* is bound before bootstrap lifecycle so gateway `afterInit`/handlers see it.
|
|
272
|
+
*/
|
|
273
|
+
async function buildDoRuntime(rootModule, ctx, options) {
|
|
274
|
+
const { container, routeManager, loader } = await bootstrap(rootModule, { configureContainer: (container) => {
|
|
275
|
+
registerCloudflareEnvironment(container, {
|
|
276
|
+
token: options.envToken,
|
|
277
|
+
env: options.env
|
|
278
|
+
});
|
|
279
|
+
} });
|
|
280
|
+
const registry = new CfRoomRegistry(ctx);
|
|
281
|
+
const driver = local();
|
|
282
|
+
driver.bind(registry);
|
|
283
|
+
const server = new WsServerImpl(driver);
|
|
284
|
+
if (container.has(WS_SERVER)) {
|
|
285
|
+
const holder = await container.resolveAsync(WS_SERVER);
|
|
286
|
+
if (holder instanceof WsServerHolder) holder.setTarget(server);
|
|
287
|
+
}
|
|
288
|
+
const app = new VelaApplication(container, routeManager);
|
|
289
|
+
app.setInstances(await loader.resolveAllInstances());
|
|
290
|
+
initializeDoLiveResources(container, ctx);
|
|
291
|
+
await app.callOnModuleInit();
|
|
292
|
+
await app.callOnApplicationBootstrap();
|
|
293
|
+
const wsEntrypoints = app.entrypoints.ofKind("websocket", readWsEntrypointMeta);
|
|
294
|
+
const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);
|
|
295
|
+
registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));
|
|
296
|
+
registry.setDeliveryAuthorizer((client) => {
|
|
297
|
+
const path = client instanceof CfWsClient ? client.path : "";
|
|
298
|
+
return dispatcher.authorizeDelivery(path, client);
|
|
299
|
+
});
|
|
300
|
+
const live = initDoLive(app, ctx);
|
|
301
|
+
return {
|
|
302
|
+
dispatcher,
|
|
303
|
+
registry,
|
|
304
|
+
server,
|
|
305
|
+
gatewayPaths: wsEntrypoints.map((ep) => ep.meta.path),
|
|
306
|
+
live,
|
|
307
|
+
close: (signal) => app.close(signal)
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
//#endregion
|
|
311
|
+
//#region src/websocket/websocket.durable-object.ts
|
|
312
|
+
const PING = "{\"event\":\"$ping\"}";
|
|
313
|
+
const PONG = "{\"event\":\"$pong\"}";
|
|
314
|
+
const MAX_IDENTITY_FIELD_BYTES = 2048;
|
|
315
|
+
const encoder = new TextEncoder();
|
|
316
|
+
function isIdentityField(value) {
|
|
317
|
+
return value !== null && value.length > 0 && encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Base class for the WebSocket Durable Object. The user exports a named subclass
|
|
321
|
+
* (matching their `wrangler.toml` `class_name`) built from their `AppModule`:
|
|
322
|
+
*
|
|
323
|
+
* ```ts
|
|
324
|
+
* export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}
|
|
325
|
+
* ```
|
|
326
|
+
*
|
|
327
|
+
* It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
|
|
328
|
+
* bridge DO hibernation) and forwards every event into the runtime-agnostic
|
|
329
|
+
* `WsDispatcher` via {@link DoWebSocketHost}.
|
|
330
|
+
*/
|
|
331
|
+
function VelaWebSocketDurableObject(rootModule, options) {
|
|
332
|
+
return class VelaWsDurableObject extends DurableObject {
|
|
333
|
+
host;
|
|
334
|
+
liveEngine;
|
|
335
|
+
ready;
|
|
336
|
+
constructor(ctx, env) {
|
|
337
|
+
super(ctx, env);
|
|
338
|
+
try {
|
|
339
|
+
ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));
|
|
340
|
+
} catch {}
|
|
341
|
+
this.ready = ctx.blockConcurrencyWhile(async () => {
|
|
342
|
+
const runtime = await buildDoRuntime(resolveCloudflareRoot(rootModule, env), ctx, {
|
|
343
|
+
...options,
|
|
344
|
+
env
|
|
345
|
+
});
|
|
346
|
+
this.host = new DoWebSocketHost(ctx, runtime.dispatcher, runtime.registry, runtime.gatewayPaths);
|
|
347
|
+
this.liveEngine = runtime.live;
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
/** Intra-worker RPC only; HTTP fetch never exposes this admin snapshot. */
|
|
351
|
+
async inspectLive() {
|
|
352
|
+
await this.ready;
|
|
353
|
+
return this.liveEngine?.inspect() ?? {
|
|
354
|
+
subscriptions: [],
|
|
355
|
+
rooms: []
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
async fetch(request) {
|
|
359
|
+
await this.ready;
|
|
360
|
+
if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected WebSocket upgrade", { status: 426 });
|
|
361
|
+
const url = new URL(request.url);
|
|
362
|
+
const roomId = request.headers.get("x-vela-room") ?? this.ctx.id.name ?? url.pathname;
|
|
363
|
+
const path = request.headers.get("x-vela-path") ?? this.host.defaultPath() ?? url.pathname;
|
|
364
|
+
const userId = request.headers.get("x-vela-user") || void 0;
|
|
365
|
+
const rawExpiresAtMs = request.headers.get("x-vela-expires-at-ms");
|
|
366
|
+
const parsedExpiresAtMs = rawExpiresAtMs === null ? void 0 : Number(rawExpiresAtMs);
|
|
367
|
+
if (parsedExpiresAtMs !== void 0 && (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)) return new Response("Invalid WebSocket identity expiry", { status: 403 });
|
|
368
|
+
const issuer = request.headers.get("x-vela-issuer");
|
|
369
|
+
const subject = request.headers.get("x-vela-subject");
|
|
370
|
+
const principalType = request.headers.get("x-vela-principal-type");
|
|
371
|
+
const tenantId = request.headers.get("x-vela-tenant");
|
|
372
|
+
const hasPrincipalHeader = issuer !== null || subject !== null || principalType !== null || tenantId !== null;
|
|
373
|
+
let principal;
|
|
374
|
+
if (hasPrincipalHeader) {
|
|
375
|
+
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 });
|
|
376
|
+
principal = {
|
|
377
|
+
issuer,
|
|
378
|
+
subject,
|
|
379
|
+
principalType,
|
|
380
|
+
tenantId
|
|
381
|
+
};
|
|
382
|
+
} else if (parsedExpiresAtMs !== void 0) return new Response("WebSocket identity tuple is missing", { status: 403 });
|
|
383
|
+
if (parsedExpiresAtMs !== void 0 && parsedExpiresAtMs <= Date.now()) return new Response("WebSocket identity expired", { status: 403 });
|
|
384
|
+
const { 0: client, 1: server } = new WebSocketPair();
|
|
385
|
+
if (!await this.host.accept(server, path, roomId, userId, parsedExpiresAtMs, principal)) return new Response("WebSocket connection rejected", { status: 403 });
|
|
386
|
+
return new Response(null, {
|
|
387
|
+
status: 101,
|
|
388
|
+
webSocket: client
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
async webSocketMessage(ws, message) {
|
|
392
|
+
await this.ready;
|
|
393
|
+
await this.host.onMessage(ws, message);
|
|
394
|
+
}
|
|
395
|
+
async webSocketClose(ws, code, reason) {
|
|
396
|
+
await this.ready;
|
|
397
|
+
await this.host.onClose(ws, code, reason);
|
|
398
|
+
}
|
|
399
|
+
async webSocketError(ws, error) {
|
|
400
|
+
await this.ready;
|
|
401
|
+
await this.host.onError(ws, error);
|
|
402
|
+
}
|
|
403
|
+
/** DO RPC — server-initiated broadcast forwarded from a Worker (see `broadcastToRoom`). */
|
|
404
|
+
async broadcast(cmd) {
|
|
405
|
+
await this.ready;
|
|
406
|
+
await this.host.broadcast(cmd);
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* DO RPC — live tag invalidation forwarded from a Worker (durableObjectLive /
|
|
410
|
+
* liveInvalidateToRoom). Appends to THIS log scope's cursor log and returns
|
|
411
|
+
* the commit stamp (what `Vela-Commit-Cursor` carries); the subscription
|
|
412
|
+
* refreshes fan out asynchronously.
|
|
413
|
+
*/
|
|
414
|
+
async invalidate(cmd) {
|
|
415
|
+
await this.ready;
|
|
416
|
+
return this.liveEngine?.applyInvalidation(cmd);
|
|
417
|
+
}
|
|
418
|
+
/** DO RPC — the current PITR bookmark (typed-unavailable on a non-SQLite DO). */
|
|
419
|
+
async pitrCurrentBookmark() {
|
|
420
|
+
await this.ready;
|
|
421
|
+
return readDoPitrBookmark(this.ctx.storage);
|
|
422
|
+
}
|
|
423
|
+
/** DO RPC — the PITR bookmark closest to `time` (+ the current bookmark). */
|
|
424
|
+
async pitrBookmarkForTime(time) {
|
|
425
|
+
await this.ready;
|
|
426
|
+
return readDoPitrBookmark(this.ctx.storage, time);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* DO RPC — arm a PITR restore and return the undo bookmark. When `restart` is
|
|
430
|
+
* requested, `ctx.abort()` is called AFTER the undo bookmark is computed so
|
|
431
|
+
* the recovery applies on the immediately-following session; otherwise the
|
|
432
|
+
* restore applies on the next natural restart (`restarted: false`).
|
|
433
|
+
*/
|
|
434
|
+
async pitrArmRestore(opts) {
|
|
435
|
+
await this.ready;
|
|
436
|
+
const result = await armDoPitr(this.ctx.storage, opts);
|
|
437
|
+
if (opts.restart === true) this.ctx.abort("vela PITR restore");
|
|
438
|
+
return result;
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
//#endregion
|
|
443
|
+
//#region src/nonce/nonce.durable-object.ts
|
|
444
|
+
const EXPIRED_DELETE_BATCH = 1024;
|
|
445
|
+
const CREATE_TABLE = "CREATE TABLE IF NOT EXISTS __vela_nonce_claims (nonce TEXT PRIMARY KEY NOT NULL, expires_at INTEGER NOT NULL CHECK (expires_at > 0)) WITHOUT ROWID";
|
|
446
|
+
const CREATE_EXPIRY_INDEX = "CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)";
|
|
447
|
+
const DELETE_EXPIRED = "DELETE FROM __vela_nonce_claims WHERE nonce IN (SELECT nonce FROM __vela_nonce_claims WHERE expires_at < ? ORDER BY expires_at LIMIT ?)";
|
|
448
|
+
const INSERT_CLAIM = "INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at";
|
|
449
|
+
/**
|
|
450
|
+
* SQLite Durable Object that atomically consumes nonces.
|
|
451
|
+
*
|
|
452
|
+
* Export this class from the Worker entry and register it through a Wrangler
|
|
453
|
+
* `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`
|
|
454
|
+
* is the single-use decision; all SQL runs synchronously before the RPC method
|
|
455
|
+
* yields, and the nonce primary key is the final concurrency boundary.
|
|
456
|
+
*/
|
|
457
|
+
var VelaNonceDurableObject = class extends DurableObject {
|
|
458
|
+
sql;
|
|
459
|
+
constructor(ctx, env) {
|
|
460
|
+
super(ctx, env);
|
|
461
|
+
try {
|
|
462
|
+
const sql = ctx.storage?.sql;
|
|
463
|
+
if (!sql || typeof sql.exec !== "function") return;
|
|
464
|
+
sql.exec(CREATE_TABLE);
|
|
465
|
+
sql.exec(CREATE_EXPIRY_INDEX);
|
|
466
|
+
this.sql = sql;
|
|
467
|
+
} catch {
|
|
468
|
+
this.sql = void 0;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
async claim(nonce, expEpochSeconds) {
|
|
472
|
+
const sql = this.sql;
|
|
473
|
+
if (!sql) return false;
|
|
474
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
475
|
+
if (!isCanonicalBoundedText(nonce, 512) || !isValidExpiry(expEpochSeconds, now)) return false;
|
|
476
|
+
try {
|
|
477
|
+
sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);
|
|
478
|
+
const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);
|
|
479
|
+
if (!cursor || typeof cursor.toArray !== "function") return false;
|
|
480
|
+
const rows = cursor.toArray();
|
|
481
|
+
if (!Array.isArray(rows) || rows.length !== 1) return false;
|
|
482
|
+
const row = rows[0];
|
|
483
|
+
if (typeof row !== "object" || row === null) return false;
|
|
484
|
+
if (!Object.hasOwn(row, "nonce") || !Object.hasOwn(row, "expires_at") || !("nonce" in row) || !("expires_at" in row)) return false;
|
|
485
|
+
return row.nonce === nonce && row.expires_at === expEpochSeconds;
|
|
486
|
+
} catch {
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
//#endregion
|
|
492
|
+
export { VelaNonceDurableObject, VelaWebSocketDurableObject };
|
|
493
|
+
|
|
494
|
+
//# sourceMappingURL=durable-objects.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"durable-objects.js","names":[],"sources":["../src/websocket/cf-room-registry.ts","../src/websocket/do-websocket-host.ts","../src/websocket/do-bootstrap.ts","../src/websocket/websocket.durable-object.ts","../src/nonce/nonce.durable-object.ts"],"sourcesContent":["import type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const att = this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: new CfWsClient(this.ctx, ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return (\n (ws.deserializeAttachment() as WsAttachment | null) ?? {\n connId: '',\n state: 'rejected',\n path: '',\n rooms: [],\n data: {},\n }\n );\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n return new CfWsClient(this.ctx, ws);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n","import { 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 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 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 await 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('Unable to persist authorized WebSocket state');\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 const client = this.registry.clientFor(ws);\n await this.dispatcher.dispatchMessage(client.path, client, message);\n }\n\n async onClose(ws: WsLike, code: number, reason: string): Promise<void> {\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 = ws.deserializeAttachment() as WsAttachment | null;\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 = ws.deserializeAttachment() as WsAttachment | null;\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): void {\n this.transition(ws, 'rejected');\n try {\n ws.close(1008, reason);\n } catch {\n // already closed\n }\n }\n}\n","import { bootstrap, VelaApplication } from '@velajs/vela';\nimport type { InjectionToken, Type } from '@velajs/vela';\nimport {\n local,\n readWsEntrypointMeta,\n WsDispatcher,\n WsServerImpl,\n WS_SERVER,\n} from '@velajs/vela/websocket';\nimport type { WsServer } from '@velajs/vela/websocket';\nimport type { LiveEngine } from '@velajs/vela/live';\nimport { registerCloudflareEnvironment } from '../environment';\nimport { CfWsClient } from './cf-ws-client';\nimport { CfRoomRegistry } from './cf-room-registry';\nimport { initDoLive, initializeDoLiveResources } from './do-live';\nimport type { DoStateLike } from './do-state';\nimport { WsServerHolder } from './ws-server-holder';\n\nexport interface DoRuntime {\n dispatcher: WsDispatcher;\n registry: CfRoomRegistry;\n server: WsServer;\n /** Gateway paths from `app.entrypoints.ofKind('websocket')` (discovery order). */\n gatewayPaths: string[];\n /** The live-query engine (undefined when the app doesn't import LiveModule). */\n live?: LiveEngine;\n close(signal?: string): Promise<void>;\n}\n\n/**\n * Slim DI bootstrap for the Durable Object isolate: wires the container and runs\n * `OnModuleInit`/`OnApplicationBootstrap` (so `WsDispatcher` discovers gateways)\n * WITHOUT building the Hono app/routes the DO never serves. Cloudflare binding\n * refs are initialized straight from the DO's `env`, and the ctx-backed server\n * is bound before bootstrap lifecycle so gateway `afterInit`/handlers see it.\n */\nexport async function buildDoRuntime<T extends object>(\n rootModule: Type,\n ctx: DoStateLike,\n options: { env: T; envToken: InjectionToken<T> },\n): Promise<DoRuntime> {\n const { container, routeManager, loader } = await bootstrap(rootModule, {\n configureContainer: (container) => {\n registerCloudflareEnvironment(container, { token: options.envToken, env: options.env });\n },\n });\n\n const registry = new CfRoomRegistry(ctx);\n const driver = local();\n driver.bind(registry);\n const server = new WsServerImpl(driver);\n\n if (container.has(WS_SERVER)) {\n const holder = await container.resolveAsync(WS_SERVER);\n if (holder instanceof WsServerHolder) holder.setTarget(server);\n }\n\n const app = new VelaApplication(container, routeManager);\n app.setInstances(await loader.resolveAllInstances());\n initializeDoLiveResources(container, ctx);\n await app.callOnModuleInit();\n await app.callOnApplicationBootstrap();\n\n // The entrypoint registry is the transport contract: one 'websocket' entry\n // per discovered gateway ({ meta: { path, dispatcher } }). Built by\n // callOnApplicationBootstrap(), so this slim no-routes path has it too.\n const wsEntrypoints = app.entrypoints.ofKind('websocket', readWsEntrypointMeta);\n const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);\n registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));\n registry.setDeliveryAuthorizer((client) => {\n const path = client instanceof CfWsClient ? client.path : '';\n return dispatcher.authorizeDelivery(path, client);\n });\n\n // Live queries: wire the SQLite cursor log + local driver mode and replay\n // hibernation-persisted subscriptions into the fresh engine.\n const live = initDoLive(app, ctx);\n\n return {\n // Zero gateways still yields a live dispatcher (module imported, nothing\n // decorated) — fall back to resolving it directly.\n dispatcher,\n registry,\n server,\n gatewayPaths: wsEntrypoints.map((ep) => ep.meta.path),\n live,\n close: (signal?: string) => app.close(signal),\n };\n}\n","import { DurableObject } from 'cloudflare:workers';\nimport type { InjectionToken } 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 { resolveCloudflareRoot } from '../root-module';\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`:\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}.\n */\nexport function VelaWebSocketDurableObject<T extends object>(\n rootModule: CloudflareRoot<NoInfer<T>>,\n options: { envToken: InjectionToken<T> },\n): new (\n ctx: DurableObjectState,\n env: T,\n) => DurableObject<T> &\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<T> {\n private host!: DoWebSocketHost;\n private liveEngine?: LiveEngine;\n private readonly ready: Promise<void>;\n\n constructor(ctx: DurableObjectState, env: T) {\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 const runtime = await buildDoRuntime(resolveCloudflareRoot(rootModule, env), ctx, {\n ...options,\n env,\n });\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('x-vela-room') ?? this.ctx.id.name ?? url.pathname;\n const path = request.headers.get('x-vela-path') ?? this.host.defaultPath() ?? url.pathname;\n const userId = request.headers.get('x-vela-user') || undefined;\n const rawExpiresAtMs = request.headers.get('x-vela-expires-at-ms');\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('x-vela-issuer');\n const subject = request.headers.get('x-vela-subject');\n const principalType = request.headers.get('x-vela-principal-type');\n const tenantId = request.headers.get('x-vela-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 — server-initiated broadcast forwarded from a Worker (see `broadcastToRoom`). */\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","import { DurableObject } from 'cloudflare:workers';\nimport { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from './nonce-validation';\nconst EXPIRED_DELETE_BATCH = 1_024;\n\nconst CREATE_TABLE =\n 'CREATE TABLE IF NOT EXISTS __vela_nonce_claims (' +\n 'nonce TEXT PRIMARY KEY NOT NULL, ' +\n 'expires_at INTEGER NOT NULL CHECK (expires_at > 0)' +\n ') WITHOUT ROWID';\nconst CREATE_EXPIRY_INDEX =\n 'CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)';\nconst DELETE_EXPIRED =\n 'DELETE FROM __vela_nonce_claims WHERE nonce IN (' +\n 'SELECT nonce FROM __vela_nonce_claims ' +\n 'WHERE expires_at < ? ORDER BY expires_at LIMIT ?' +\n ')';\nconst INSERT_CLAIM =\n 'INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ' +\n 'ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at';\n\ninterface NonceSqlCursor {\n toArray(): Record<string, unknown>[];\n}\n\ninterface NonceSqlStorage {\n exec(query: string, ...bindings: unknown[]): NonceSqlCursor;\n}\n\n/**\n * SQLite Durable Object that atomically consumes nonces.\n *\n * Export this class from the Worker entry and register it through a Wrangler\n * `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`\n * is the single-use decision; all SQL runs synchronously before the RPC method\n * yields, and the nonce primary key is the final concurrency boundary.\n */\nexport class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {\n private sql?: NonceSqlStorage;\n\n constructor(ctx: DurableObjectState, env: Record<string, unknown>) {\n super(ctx, env);\n try {\n const sql = ctx.storage?.sql;\n if (!sql || typeof sql.exec !== 'function') return;\n sql.exec(CREATE_TABLE);\n sql.exec(CREATE_EXPIRY_INDEX);\n this.sql = sql;\n } catch {\n // A non-SQLite/misconfigured class stays fail-closed: every claim denies.\n this.sql = undefined;\n }\n }\n\n async claim(nonce: string, expEpochSeconds: number): Promise<boolean> {\n const sql = this.sql;\n if (!sql) return false;\n\n const now = Math.floor(Date.now() / 1_000);\n if (!isCanonicalBoundedText(nonce, MAX_NONCE_BYTES) || !isValidExpiry(expEpochSeconds, now)) {\n return false;\n }\n\n try {\n // Keep cleanup bounded so one claim cannot monopolize the DO. Entries at\n // exactly `now` remain: Vela's invocation verifier accepts `now === exp`.\n sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);\n\n const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);\n if (!cursor || typeof cursor.toArray !== 'function') return false;\n const rows: unknown = cursor.toArray();\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n\n const row: unknown = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n if (\n !Object.hasOwn(row, 'nonce') ||\n !Object.hasOwn(row, 'expires_at') ||\n !('nonce' in row) ||\n !('expires_at' in row)\n ) {\n return false;\n }\n return row.nonce === nonce && row.expires_at === expEpochSeconds;\n } catch {\n return false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAa,iBAAb,MAAoD;CAIrB;CAH7B;CACA;CAEA,YAAY,KAAmC;EAAlB,KAAA,MAAA;CAAmB;CAEhD,sBAAsB,YAAoE;EACxF,KAAK,qBAAqB;CAC5B;;CAGA,sBAAsB,UAAsD;EAC1E,KAAK,oBAAoB;CAC3B;CAGA,SAAS,SAAyB,CAAC;CACnC,SAAS,SAAyB,CAAC;CAEnC,KAAK,QAAkB,MAAoC;EACzD,OAAO,OAAO,KAAK,IAAI;CACzB;CAEA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