@berdyh/bridge-server-cf 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ bridge
2
+ Copyright 2026 Shokhrukh Berdikobilov (Shoh Berdy)
3
+
4
+ This product includes software from bridge (https://github.com/berdyh/bridge),
5
+ licensed under the Apache License, Version 2.0.
package/README.md CHANGED
@@ -1,3 +1,102 @@
1
- # Temporary Holding Version
1
+ # @berdyh/bridge-server-cf
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Cloudflare Workers adapter for the bridge server kit: a Worker that serves the core's HTTP routes, and a Durable Object per user that holds the relay's sockets. It is for apps deployed on Cloudflare. It takes a device store (Neon or D1) and an `AuthVerifier` (Clerk) from the other adapter packages, and ships a Worker template to copy.
4
+
5
+ Copy `templates/worker.ts` and `wrangler.toml.example` into the app's own Worker
6
+ project. Each app needs its own namespace, database and Clerk secret. Apply the
7
+ Neon migration before use; for D1, use `createD1DeviceStore(env.DB)` and copy its
8
+ migration into the app's D1 migrations directory. Secrets belong in Worker secret
9
+ bindings. Source templates and migrations live beside their respective packages;
10
+ copy them from this repository (the package manifests publish dist only).
11
+
12
+ The template sets `enrollPage: "/bridge/enroll"`, advertised in discovery. Serve
13
+ the app's enrollment page at that path or change it to another path on the app
14
+ origin. It is optional; omit it when the app has no enrollment page. The core
15
+ validates discovery when the Worker constructs its app: the path must start with
16
+ a single `/` and contain no query, fragment, backslash, space or control character.
17
+ Absolute and off-origin URLs are rejected.
18
+
19
+ Rate limit `/relay/*` and `/bridge/devices*` with a Cloudflare rate-limiting rule: the
20
+ Worker does not throttle, and each unauthenticated request can cost a Clerk Backend API
21
+ call. Set the optional `CLERK_JWT_KEY` (PEM public key) so browser JWTs verify locally;
22
+ see [Add the bridge to an app](../../docs/guides/add-to-an-app.md#rate-limit-the-public-routes).
23
+
24
+ The Worker template advertises Clerk's device flow and enables OAuth verification
25
+ with the same CLERK_CLIENT_ID and explicit
26
+ `oauth: { clientId: env.CLERK_CLIENT_ID, allowWithoutCredentialId: true }`.
27
+ This opts into device-id-only
28
+ revocation: **a revoked machine can reconnect under a new runnerId and use its
29
+ refresh token to keep obtaining new access tokens for as long as the refresh
30
+ token/grant remains valid, or until the grant is manually revoked in Clerk**.
31
+ Access-token expiry alone does not end this window (`offline_access` enables
32
+ refresh). To revoke the grant manually, call
33
+ `clerkClient.oauthApplications.revokeToken({ oauthApplicationId, token })` from a
34
+ trusted backend using this app's Clerk secret key and an opaque access or refresh
35
+ token from that grant; Clerk revokes both tokens. Device-id revocation does not
36
+ make this call automatically. See the [Clerk verifier README](../server-clerk/README.md)
37
+ for the required inputs and limitations.
38
+
39
+ The Clerk verifier remains strict by default. For whole-grant revocation, supply
40
+ both `resolveGrant` and `revokeGrant` hooks backed by an authoritative,
41
+ refresh-stable grant mapping; see the Clerk verifier README. Token
42
+ id/jti, userId and clientId are not stable grant identifiers. Each app owns its
43
+ grant data and provider credentials.
44
+
45
+ The Worker caches one core Hono app per env object in a WeakMap; only the per-user DO owns sockets.
46
+ The gateway derives `idFromName(userId)` from the verified principal and forwards
47
+ no bearer token. The DO independently checks accept/disconnect user ids against
48
+ its namespace-derived id (or its name for a custom gateway). Attachments contain
49
+ peer, negotiated state, inbound timestamps, hello deadlines and close
50
+ markers and must be smaller than 16 KB. A fresh DO instance reconstructs routing
51
+ from attachments. In-flight Promise chains serialize each socket's handler calls;
52
+ they are disposable and prevent eviction until settled, not persistent state.
53
+ The relay persists only a `boundedHostname`-validated name (1–255 printable
54
+ characters) beside the bounded agents list. Online presence repeats that name for
55
+ current and later browsers after hibernation; offline presence omits it. Invalid
56
+ names are dropped from presence and stored as `"unknown"` in the device record.
57
+
58
+ Each user's Durable Object refuses an upgrade with 429 once the user holds
59
+ `maxSocketsPerUser` sockets of that role (defaults 16 browsers, 8 runners), before the
60
+ core's `onOpen` and before replacing a same-key browser tab.
61
+
62
+ Liveness uses WebSocket auto-response and the DO alarm API, never JavaScript
63
+ timers. Peers send the text frame `bridge:ping` after 20 seconds without outbound
64
+ traffic and reconnect if no `bridge:pong` arrives within 10 seconds. The DO
65
+ registers `WebSocketRequestResponsePair('bridge:ping', 'bridge:pong')`, so incoming
66
+ pings are answered without waking the DO. Neither heartbeat string reaches the
67
+ relay core; unsolicited pongs are ignored and servers never initiate text pings.
68
+
69
+ Any inbound frame proves liveness. The latest inbound time is the maximum of the
70
+ attachment timestamp and `getWebSocketAutoResponseTimestamp(ws)`, so it survives
71
+ hibernation, including auto-responses. A sparse alarm sweep (at most 30 seconds
72
+ apart while sockets exist) closes sockets with no inbound frame for 60 seconds;
73
+ sweep timing can delay that close by up to 30 seconds. A runner must greet within
74
+ 10 seconds; an earlier alarm enforces that fixed deadline and pre-hello traffic
75
+ cannot extend it. The sweep refreshes an active runner's lastSeen through the
76
+ store's 5-minute throttle; failures are best effort and do not block the socket's
77
+ event chain. Ordinary relayed frames update attachments without reading or
78
+ writing alarm storage. No alarms remain when there are no live sockets.
79
+
80
+ A socket older than `maxSocketAgeMs` (default 12 hours, 0 disables it; measured from
81
+ `state.connectedAt`) is closed by the same sweep with 1012 (`RELAY_CLOSE_MAX_AGE`), so
82
+ the client or runner reconnects and presents a fresh token. Only the device API's
83
+ revocation is seen live; identity-provider revocation takes effect within one max age.
84
+
85
+ Workers' WebSocket API has no bufferedAmount or terminate. **maxQueuedBytes is
86
+ inert on Workers**: the adapter owns no outbound queue and skips byte encoding on
87
+ send when bufferedAmount is absent. If a runtime exposes bufferedAmount, the
88
+ adapter honors maxQueuedBytes. Runtime send failures close the socket; the
89
+ platform's hidden aggregate buffer cannot be bounded through this option.
90
+ Closing immediately persists a discard marker so queued inbound events never
91
+ route after server termination.
92
+
93
+ The package typecheck includes `templates/worker.ts` against the owned adapter
94
+ sources, so copied-template API drift fails the normal check.
95
+
96
+ Tests use the installed Wrangler Miniflare runtime for Hono, actual WebSocket
97
+ hibernation acceptance, D1, replacement, routing and credential revocation, plus
98
+ fakes for deterministic eviction, deadlines and send failures. A real `wrangler dev` run is covered by the `e2e-cf` suite.
99
+
100
+ ## Guides
101
+
102
+ Deploying a server: [Add the bridge to an app](../../docs/guides/add-to-an-app.md). Writing your own adapter: [Write an adapter](../../docs/guides/write-an-adapter.md).
@@ -0,0 +1,7 @@
1
+ import { type BridgeServerConfig, type RelayGateway } from "@berdyh/bridge-server";
2
+ export declare const CF_HEARTBEAT_PING = "bridge:ping";
3
+ export declare const CF_HEARTBEAT_PONG = "bridge:pong";
4
+ /** Only the authenticated peer is forwarded; bearer tokens never enter attachments. */
5
+ export declare function createDoRelayGateway(namespace: DurableObjectNamespace): RelayGateway;
6
+ /** All durable connection state is in attachments; only in-flight event chains live in memory. */
7
+ export declare function createRelayDurableObject<Env>(configFor: (env: Env) => BridgeServerConfig): new (state: DurableObjectState, env: Env) => DurableObject;
@@ -0,0 +1,280 @@
1
+ import { RELAY_CLOSE_REPLACED, RELAY_CLOSE_REVOKED, RELAY_SUBPROTOCOL } from "@berdyh/bridge-protocol";
2
+ import { createDeviceService, createRelayCore, RELAY_CLOSE_MAX_AGE, resolveSocketLimits, revokedVerdictFrame } from "@berdyh/bridge-server";
3
+ const PEER_HEADER = "x-bridge-internal-peer";
4
+ const INTERNAL = "https://bridge.internal";
5
+ export const CF_HEARTBEAT_PING = "bridge:ping";
6
+ export const CF_HEARTBEAT_PONG = "bridge:pong";
7
+ const HELLO_MS = 10_000;
8
+ const SWEEP_MS = 30_000;
9
+ const IDLE_MS = 60_000;
10
+ const namespaces = new WeakMap();
11
+ const bytes = (s) => new TextEncoder().encode(s).byteLength;
12
+ function save(ws, value) {
13
+ if (bytes(JSON.stringify(value)) >= 16 * 1024)
14
+ throw new Error("relay attachment exceeds 16 KB");
15
+ ws.serializeAttachment(value);
16
+ }
17
+ function matches(p, f) {
18
+ return (f.role === undefined || f.role === p.role) &&
19
+ (f.runnerId === undefined || (p.role === "runner" && f.runnerId === p.runnerId)) &&
20
+ (f.browserKeyId === undefined || (p.role === "browser" && f.browserKeyId === p.browserKeyId)) &&
21
+ (f.credentialId === undefined || (p.role === "runner" && f.credentialId === p.credentialId));
22
+ }
23
+ /** Only the authenticated peer is forwarded; bearer tokens never enter attachments. */
24
+ export function createDoRelayGateway(namespace) {
25
+ const stub = (u) => namespace.get(namespace.idFromName(u));
26
+ const gateway = {
27
+ accept(request, peer) {
28
+ const headers = new Headers({ upgrade: "websocket", [PEER_HEADER]: JSON.stringify(peer) });
29
+ if (request.headers.get("sec-websocket-protocol")?.split(",").some((p) => p.trim() === RELAY_SUBPROTOCOL))
30
+ headers.set("sec-websocket-protocol", RELAY_SUBPROTOCOL);
31
+ return stub(peer.userId).fetch(new Request(`${INTERNAL}/accept`, { headers }));
32
+ },
33
+ // Runs in the Worker and never calls the user's Durable Object: the verdict socket is a plain
34
+ // (non-hibernating) WebSocket that no relay registry knows, so it cannot displace or reach anything.
35
+ async acceptVerdict(request, verdict) {
36
+ if (request.headers.get("upgrade")?.toLowerCase() !== "websocket")
37
+ return new Response("Upgrade Required", { status: 426 });
38
+ const pair = new WebSocketPair();
39
+ const server = pair[1];
40
+ server.accept();
41
+ server.send(revokedVerdictFrame(verdict.runnerId));
42
+ server.close(RELAY_CLOSE_REVOKED, "revoked");
43
+ const offered = request.headers.get("sec-websocket-protocol")?.split(",").some((p) => p.trim() === RELAY_SUBPROTOCOL);
44
+ return new Response(null, { status: 101, webSocket: pair[0], ...(offered ? { headers: { "sec-websocket-protocol": RELAY_SUBPROTOCOL } } : {}) });
45
+ },
46
+ async disconnect(userId, filter, code, reason) {
47
+ const response = await stub(userId).fetch(new Request(`${INTERNAL}/disconnect`, { method: "POST", body: JSON.stringify({ userId, filter, code, reason }) }));
48
+ if (!response.ok)
49
+ throw new Error("relay disconnect failed");
50
+ return response.json();
51
+ },
52
+ };
53
+ namespaces.set(gateway, namespace);
54
+ return gateway;
55
+ }
56
+ /** All durable connection state is in attachments; only in-flight event chains live in memory. */
57
+ export function createRelayDurableObject(configFor) {
58
+ return class RelayDurableObject {
59
+ ctx;
60
+ transport;
61
+ handler;
62
+ // A pending handler prevents hibernation. No correctness state depends on these chains after eviction.
63
+ chains = new WeakMap();
64
+ config;
65
+ devices;
66
+ alarmChain = Promise.resolve();
67
+ constructor(ctx, env) {
68
+ this.ctx = ctx;
69
+ this.config = configFor(env);
70
+ this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(CF_HEARTBEAT_PING, CF_HEARTBEAT_PONG));
71
+ this.devices = createDeviceService({ store: this.config.adapters.store, now: () => new Date(this.now()), lastSeenIntervalMs: this.config.lastSeenIntervalMs });
72
+ const find = (id) => this.sockets().find((ws) => this.attachment(ws).id === id);
73
+ this.transport = {
74
+ bind: (h) => { if (this.handler)
75
+ throw new Error("relay handler already bound"); this.handler = h; },
76
+ accept: (request, peer) => this.accept(request, peer),
77
+ disconnect: async (u, filter, code, reason) => {
78
+ const targets = this.transport.connections(u, filter);
79
+ for (const c of targets)
80
+ this.transport.close(c.id, code, reason);
81
+ await this.schedule();
82
+ return targets.length;
83
+ },
84
+ connections: (u, f = {}) => this.sockets().map((ws) => this.attachment(ws)).filter((a) => a.peer.userId === u && matches(a.peer, f)),
85
+ setState: (id, state) => {
86
+ const ws = find(id);
87
+ if (!ws)
88
+ return;
89
+ const a = this.attachment(ws);
90
+ save(ws, { ...a, state });
91
+ },
92
+ send: (id, data) => {
93
+ const ws = find(id);
94
+ if (!ws)
95
+ return "closed";
96
+ // Workers currently exposes no bufferedAmount. If present on a runtime, honor it;
97
+ // otherwise platform send failures and the per-message cap bound our own queue (zero).
98
+ const buffered = ws.bufferedAmount;
99
+ if (buffered !== undefined && buffered + bytes(data) > (this.config.maxQueuedBytes ?? 4 * 1024 * 1024)) {
100
+ this.transport.close(id, 1013, "backpressure");
101
+ return "dropped_backpressure";
102
+ }
103
+ try {
104
+ ws.send(data);
105
+ return (buffered ?? 0) > 0 ? "queued" : "sent";
106
+ }
107
+ catch {
108
+ this.terminate(ws, 1013, "send failed");
109
+ return "dropped_backpressure";
110
+ }
111
+ },
112
+ close: (id, code, reason) => {
113
+ const ws = find(id);
114
+ if (!ws)
115
+ return;
116
+ this.terminate(ws, code, reason);
117
+ },
118
+ };
119
+ this.transport.bind(createRelayCore({ ...this.config, adapters: { ...this.config.adapters, relay: this.transport } }, this.transport));
120
+ }
121
+ terminate(ws, code, reason) {
122
+ const a = this.attachment(ws);
123
+ if (a.closed)
124
+ return;
125
+ // Use the socket directly: a failing send can already have removed it from
126
+ // getWebSockets()/OPEN state. Its queued inbound events still need discarding.
127
+ save(ws, { ...a, closed: true, discard: true });
128
+ try {
129
+ ws.close(code, reason.slice(0, 30));
130
+ }
131
+ catch { /* runtime already closed it */ }
132
+ this.ctx.waitUntil(this.enqueue(ws, () => this.handler.onClose(a, code, reason), true).then(() => this.schedule()));
133
+ }
134
+ now() { return (this.config.now?.() ?? new Date()).getTime(); }
135
+ ownsUser(userId) {
136
+ // state.id.name is not available on every Workers runtime. Compare the
137
+ // deterministic namespace id when using the kit's gateway, including on wake.
138
+ const namespace = namespaces.get(this.config.adapters.relay);
139
+ return namespace ? namespace.idFromName(userId).equals(this.ctx.id) : this.ctx.id.name === userId;
140
+ }
141
+ lastInbound(ws) {
142
+ return Math.max(this.attachment(ws).lastInbound, this.ctx.getWebSocketAutoResponseTimestamp(ws)?.getTime() ?? 0);
143
+ }
144
+ attachment(ws) { return ws.deserializeAttachment(); }
145
+ sockets() { return this.ctx.getWebSockets().filter((ws) => { const a = this.attachment(ws); return a && !a.closed && ws.readyState === 1; }); }
146
+ enqueue(ws, fn, always = false) {
147
+ const chain = (this.chains.get(ws) ?? Promise.resolve()).then(async () => {
148
+ if (always || !this.attachment(ws).discard)
149
+ await fn();
150
+ }).catch(() => { this.transport.close(this.attachment(ws).id, 1011, "internal error"); });
151
+ this.chains.set(ws, chain);
152
+ return chain;
153
+ }
154
+ schedule() {
155
+ // Serialize read/compare/write so concurrent sockets cannot install a stale
156
+ // deadline. Read durable storage rather than caching alarm state across eviction.
157
+ const next = this.alarmChain.catch(() => { }).then(async () => {
158
+ const sockets = this.sockets();
159
+ const now = this.now();
160
+ const deadline = sockets.length ? Math.min(now + SWEEP_MS, ...sockets.flatMap((ws) => {
161
+ const a = this.attachment(ws);
162
+ return a.peer.role === "runner" && !a.state.greeted ? [a.helloDeadline] : [];
163
+ })) : null;
164
+ const current = await this.ctx.storage.getAlarm();
165
+ if (deadline === null ? current === null : current !== null && current > now && current <= deadline)
166
+ return;
167
+ if (deadline === null)
168
+ await this.ctx.storage.deleteAlarm();
169
+ else
170
+ await this.ctx.storage.setAlarm(deadline);
171
+ });
172
+ this.alarmChain = next;
173
+ return next;
174
+ }
175
+ async accept(request, peer) {
176
+ if (!this.ownsUser(peer.userId))
177
+ return new Response("Wrong relay user", { status: 403 });
178
+ if (request.headers.get("upgrade")?.toLowerCase() !== "websocket")
179
+ return new Response("Upgrade Required", { status: 426 });
180
+ // Refuse before replacing anything, so a refused upgrade never kicks a live tab.
181
+ const limits = resolveSocketLimits(this.config);
182
+ const held = this.transport.connections(peer.userId, { role: peer.role }).filter((c) => !(peer.role === "browser" && c.peer.role === "browser" && c.peer.browserKeyId === peer.browserKeyId));
183
+ if (held.length >= (peer.role === "browser" ? limits.maxBrowserSockets : limits.maxRunnerSockets))
184
+ return new Response("Too many connections", { status: 429, headers: { "retry-after": "30" } });
185
+ if (peer.role === "browser") {
186
+ for (const old of this.transport.connections(peer.userId, { role: "browser", browserKeyId: peer.browserKeyId }))
187
+ this.transport.close(old.id, RELAY_CLOSE_REPLACED, "replaced");
188
+ }
189
+ const pair = new WebSocketPair();
190
+ const ws = pair[1];
191
+ const latest = Math.max(0, ...this.sockets().map((s) => Date.parse(this.attachment(s).state.connectedAt)));
192
+ const now = this.now();
193
+ const a = { id: crypto.randomUUID(), peer, state: { connectedAt: new Date(Math.max(now, latest + 1)).toISOString() }, helloDeadline: now + HELLO_MS, lastInbound: now };
194
+ save(ws, a);
195
+ this.ctx.acceptWebSocket(ws);
196
+ await this.enqueue(ws, () => this.handler.onOpen(a));
197
+ await this.schedule();
198
+ const headers = request.headers.get("sec-websocket-protocol") === RELAY_SUBPROTOCOL ? { "sec-websocket-protocol": RELAY_SUBPROTOCOL } : undefined;
199
+ return new Response(null, { status: 101, webSocket: pair[0], headers });
200
+ }
201
+ async fetch(request) {
202
+ const path = new URL(request.url).pathname;
203
+ if (path === "/accept" && request.method === "GET") {
204
+ const peer = JSON.parse(request.headers.get(PEER_HEADER) ?? "null");
205
+ if (!peer || !peer.userId || (peer.role !== "runner" && peer.role !== "browser"))
206
+ return new Response("Invalid peer", { status: 400 });
207
+ return this.transport.accept(request, peer);
208
+ }
209
+ if (path === "/disconnect" && request.method === "POST") {
210
+ const { userId, filter, code, reason } = await request.json();
211
+ if (typeof userId !== "string" || !this.ownsUser(userId))
212
+ return new Response("Wrong relay user", { status: 403 });
213
+ return Response.json(await this.transport.disconnect(userId, filter, code, reason));
214
+ }
215
+ return new Response("Not found", { status: 404 });
216
+ }
217
+ async webSocketMessage(ws, message) {
218
+ if (this.attachment(ws).closed)
219
+ return;
220
+ // Record receipt before an async core handler; its work cannot make a live
221
+ // socket look idle. Auto-responded pings are tracked by the runtime instead.
222
+ save(ws, { ...this.attachment(ws), lastInbound: this.now() });
223
+ if (typeof message !== "string") {
224
+ this.transport.close(this.attachment(ws).id, 1003, "text only");
225
+ return;
226
+ }
227
+ await this.enqueue(ws, async () => {
228
+ // The runtime normally consumes pings without waking the DO. Keep the
229
+ // event path symmetric as well; neither heartbeat string reaches core.
230
+ if (message === CF_HEARTBEAT_PING) {
231
+ this.transport.send(this.attachment(ws).id, CF_HEARTBEAT_PONG);
232
+ return;
233
+ }
234
+ if (message === CF_HEARTBEAT_PONG)
235
+ return;
236
+ await this.handler.onMessage(this.attachment(ws), message);
237
+ });
238
+ }
239
+ async webSocketClose(ws, code, reason, _wasClean) {
240
+ const a = this.attachment(ws);
241
+ // Hibernating sockets require the close callback to complete the handshake,
242
+ // including sockets we already marked closed on server termination.
243
+ try {
244
+ ws.close([1005, 1006, 1015].includes(code) ? 1000 : code, reason.slice(0, 30));
245
+ }
246
+ catch { /* closed */ }
247
+ if (!a || a.closed)
248
+ return;
249
+ save(ws, { ...a, closed: true });
250
+ await this.enqueue(ws, () => this.handler.onClose(this.attachment(ws), code, reason), true);
251
+ await this.schedule();
252
+ }
253
+ async webSocketError(ws, _error) { this.terminate(ws, 1011, "socket error"); }
254
+ async alarm() {
255
+ for (const ws of this.sockets()) {
256
+ const a = this.attachment(ws);
257
+ if (a.peer.role === "runner" && !a.state.greeted && a.helloDeadline <= this.now()) {
258
+ this.transport.close(a.id, 1008, "hello timeout");
259
+ continue;
260
+ }
261
+ // Tokens are checked only at upgrade: bound how long a socket outlives its credential.
262
+ const { maxSocketAgeMs: maxAge } = resolveSocketLimits(this.config);
263
+ if (maxAge > 0 && this.now() - Date.parse(a.state.connectedAt) >= maxAge) {
264
+ this.transport.close(a.id, RELAY_CLOSE_MAX_AGE, "max age");
265
+ continue;
266
+ }
267
+ const lastInbound = this.lastInbound(ws);
268
+ if (this.now() - lastInbound >= IDLE_MS) {
269
+ this.transport.close(a.id, 1001, "heartbeat timeout");
270
+ continue;
271
+ }
272
+ if (a.peer.role === "runner" && a.state.greeted && lastInbound > (a.lastSeenAttempt ?? 0) && this.now() - (a.lastSeenAttempt ?? 0) >= (this.config.lastSeenIntervalMs ?? 300_000)) {
273
+ save(ws, { ...a, lastSeenAttempt: this.now() });
274
+ this.ctx.waitUntil(this.devices.recordSeen(a.peer.userId, a.peer.runnerId).catch(() => { }));
275
+ }
276
+ }
277
+ await this.schedule();
278
+ }
279
+ };
280
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./do-transport.js";
2
+ export * from "./worker.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./do-transport.js";
2
+ export * from "./worker.js";
@@ -0,0 +1,4 @@
1
+ import { type BridgeServerConfig } from "@berdyh/bridge-server";
2
+ export type WorkerConfigFactory<Env> = (env: Env) => BridgeServerConfig;
3
+ /** Mount the core's Hono HttpHost; the Worker never owns relay sockets. */
4
+ export declare function createBridgeWorker<Env>(configFor: WorkerConfigFactory<Env>): ExportedHandler<Env>;
package/dist/worker.js ADDED
@@ -0,0 +1,14 @@
1
+ import { createBridgeApp } from "@berdyh/bridge-server";
2
+ /** Mount the core's Hono HttpHost; the Worker never owns relay sockets. */
3
+ export function createBridgeWorker(configFor) {
4
+ const apps = new WeakMap();
5
+ return { fetch: (request, env) => {
6
+ const key = env;
7
+ let app = apps.get(key);
8
+ if (!app) {
9
+ app = createBridgeApp(configFor(env));
10
+ apps.set(key, app);
11
+ }
12
+ return app.fetch(request);
13
+ } };
14
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@berdyh/bridge-server-cf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.1",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/berdyh/bridge.git",
8
+ "directory": "packages/server-cf"
9
+ },
10
+ "homepage": "https://github.com/berdyh/bridge/tree/main/packages/server-cf#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/berdyh/bridge/issues"
13
+ },
14
+ "type": "module",
15
+ "description": "Cloudflare Workers + Durable Object adapter",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "NOTICE"
25
+ ],
26
+ "dependencies": {
27
+ "@berdyh/bridge-protocol": "0.2.1",
28
+ "@berdyh/bridge-server": "0.2.1",
29
+ "hono": "4.13.13"
30
+ },
31
+ "devDependencies": {
32
+ "@cloudflare/workers-types": "5.20261012.1",
33
+ "wrangler": "4.149.0"
34
+ },
35
+ "scripts": {
36
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
37
+ "pretypecheck": "pnpm --filter \"@berdyh/bridge-server-cf^...\" build",
38
+ "typecheck": "tsc -p tsconfig.json",
39
+ "pretest": "pnpm --filter \"@berdyh/bridge-server-cf^...\" build",
40
+ "test": "vitest run --passWithNoTests"
41
+ }
6
42
  }