effect-cloudflare-webrtc 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +439 -2
- package/dist/AudioSink-BybkMP2y.d.ts +54 -0
- package/dist/Readable-CJPSx6Uq.js +65 -0
- package/dist/Readable-CJPSx6Uq.js.map +1 -0
- package/dist/Realtime-B5OIHlLR.d.ts +129 -0
- package/dist/Realtime-B6TjV8su.js +195 -0
- package/dist/Realtime-B6TjV8su.js.map +1 -0
- package/dist/RealtimeClient-Bl0Tun5r.js +2488 -0
- package/dist/RealtimeClient-Bl0Tun5r.js.map +1 -0
- package/dist/RealtimeClient-ESFO5vfF.d.ts +412 -0
- package/dist/RealtimeClient-K7oKgsB9.d.ts +1000 -0
- package/dist/chunk-pbuEa-1d.js +13 -0
- package/dist/client/index.d.ts +275 -0
- package/dist/client/index.js +493 -0
- package/dist/client/index.js.map +1 -0
- package/dist/effect/client/index.d.ts +434 -0
- package/dist/effect/client/index.js +2 -0
- package/dist/effect/server/index.d.ts +2 -0
- package/dist/effect/server/index.js +2 -0
- package/dist/react/index.d.ts +44 -0
- package/dist/react/index.js +107 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server/index.d.ts +23 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +92 -4
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import * as Effect from "effect/Effect";
|
|
2
|
+
import * as _$effect_Layer0 from "effect/Layer";
|
|
3
|
+
import * as _$effect_Cause0 from "effect/Cause";
|
|
4
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
5
|
+
import * as HttpRouter from "effect/http/HttpRouter";
|
|
6
|
+
import * as HttpServerRequest from "effect/http/HttpServerRequest";
|
|
7
|
+
import * as HttpServerResponse from "effect/http/HttpServerResponse";
|
|
8
|
+
import * as _$effect_http_HttpClientError0 from "effect/http/HttpClientError";
|
|
9
|
+
import * as _$effect_http_HttpServerError0 from "effect/http/HttpServerError";
|
|
10
|
+
|
|
11
|
+
//#region src/effect/server/Realtime.d.ts
|
|
12
|
+
declare namespace Realtime_d_exports {
|
|
13
|
+
export {
|
|
14
|
+
Options,
|
|
15
|
+
RouteRealtimeRequestOptions,
|
|
16
|
+
handler,
|
|
17
|
+
invalidPathCode,
|
|
18
|
+
layer,
|
|
19
|
+
pathEscapesSession,
|
|
20
|
+
routeRealtimeRequest,
|
|
21
|
+
sessionTokenHeader,
|
|
22
|
+
sessionTokenInvalidCode
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** The request header that carries the session token. */
|
|
26
|
+
declare const sessionTokenHeader = "x-realtime-session-token";
|
|
27
|
+
/** The `errorCode` of the response when the session token is not valid. */
|
|
28
|
+
declare const sessionTokenInvalidCode = "realtime_session_token_invalid";
|
|
29
|
+
/** The `errorCode` of the response when the path can escape its session. */
|
|
30
|
+
declare const invalidPathCode = "realtime_invalid_path";
|
|
31
|
+
interface RouteRealtimeRequestOptions {
|
|
32
|
+
/**
|
|
33
|
+
* Cloudflare Realtime SFU App ID. Get it here:
|
|
34
|
+
* https://dash.cloudflare.com/?to=/:account/realtime/sfu/create
|
|
35
|
+
*/
|
|
36
|
+
appId: string;
|
|
37
|
+
/** Cloudflare Realtime SFU App Token. Keep it on the server. */
|
|
38
|
+
token: string;
|
|
39
|
+
/** The request of the browser. */
|
|
40
|
+
request: Request;
|
|
41
|
+
/**
|
|
42
|
+
* The part of the path that is replaced. For a proxy route
|
|
43
|
+
* `/api/realtime/*`, the value is "/api/realtime".
|
|
44
|
+
* Default: "/realtime".
|
|
45
|
+
*/
|
|
46
|
+
prefix?: string;
|
|
47
|
+
/** Default: "https://rtc.live.cloudflare.com/v1". */
|
|
48
|
+
realtimeApiBaseUrl?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Only the browser that made a session can change it. The response of
|
|
51
|
+
* `sessions/new` has a `sessionToken`, and the client sends it in a
|
|
52
|
+
* request header with each later request of that session. Default: true.
|
|
53
|
+
*/
|
|
54
|
+
lockSessionToInitiator?: boolean;
|
|
55
|
+
/** The secret that signs the session token. Default: the SFU app token. */
|
|
56
|
+
sessionTokenSecret?: string;
|
|
57
|
+
/**
|
|
58
|
+
* How long a session token is valid, in seconds. After that, the client
|
|
59
|
+
* makes a new session. Default: 86400 (24 hours).
|
|
60
|
+
*/
|
|
61
|
+
sessionTokenTTL?: number;
|
|
62
|
+
/**
|
|
63
|
+
* TURN Server App ID. Get it here:
|
|
64
|
+
* https://dash.cloudflare.com/?to=/:account/realtime/turn/create
|
|
65
|
+
*/
|
|
66
|
+
turnServerAppId?: string;
|
|
67
|
+
/** TURN Server App Token. */
|
|
68
|
+
turnServerAppToken?: string;
|
|
69
|
+
/** How long the TURN credentials are valid, in seconds. Default: 86400. */
|
|
70
|
+
turnServerCredentialTTL?: number;
|
|
71
|
+
/**
|
|
72
|
+
* More request headers that are sent to the Realtime API. `Content-Type`
|
|
73
|
+
* and `Accept` are always sent. All other headers of the browser, for
|
|
74
|
+
* example `Cookie`, are not sent.
|
|
75
|
+
*/
|
|
76
|
+
forwardHeaders?: ReadonlyArray<string>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* True if the path has an encoded separator, a `;` or a dot segment. A proxy
|
|
80
|
+
* that decodes and resolves such a path can reach another session, or a path
|
|
81
|
+
* outside `/sessions/`. A `;` is refused because a proxy can remove the
|
|
82
|
+
* parameters of a segment: `..;x` becomes `..`.
|
|
83
|
+
*/
|
|
84
|
+
declare function pathEscapesSession(path: string): boolean;
|
|
85
|
+
declare const routeRealtimeRequest: (
|
|
86
|
+
options: RouteRealtimeRequestOptions
|
|
87
|
+
) => Effect.Effect<
|
|
88
|
+
Response,
|
|
89
|
+
_$effect_http_HttpClientError0.HttpClientError | _$effect_Cause0.UnknownError,
|
|
90
|
+
HttpClient.HttpClient
|
|
91
|
+
>;
|
|
92
|
+
type Options = Omit<RouteRealtimeRequestOptions, "request">;
|
|
93
|
+
/** Handle the current router request using the supplied HttpClient. */
|
|
94
|
+
declare const handler: (
|
|
95
|
+
options: Options
|
|
96
|
+
) => Effect.Effect<
|
|
97
|
+
HttpServerResponse.HttpServerResponse,
|
|
98
|
+
| _$effect_http_HttpClientError0.HttpClientError
|
|
99
|
+
| _$effect_Cause0.UnknownError
|
|
100
|
+
| _$effect_http_HttpServerError0.RequestError,
|
|
101
|
+
HttpClient.HttpClient | HttpServerRequest.HttpServerRequest
|
|
102
|
+
>;
|
|
103
|
+
/** Mount every Realtime method under the configured prefix. */
|
|
104
|
+
declare const layer: (
|
|
105
|
+
options: Options & {
|
|
106
|
+
prefix?: `/${string}`;
|
|
107
|
+
}
|
|
108
|
+
) => _$effect_Layer0.Layer<
|
|
109
|
+
never,
|
|
110
|
+
never,
|
|
111
|
+
| HttpRouter.HttpRouter
|
|
112
|
+
| HttpRouter.Request<"Requires", HttpClient.HttpClient>
|
|
113
|
+
| HttpRouter.Request<"Error", _$effect_http_HttpClientError0.HttpClientError>
|
|
114
|
+
| HttpRouter.Request<"Error", _$effect_Cause0.UnknownError>
|
|
115
|
+
| HttpRouter.Request<
|
|
116
|
+
"Error",
|
|
117
|
+
_$effect_http_HttpServerError0.RequestParseError
|
|
118
|
+
>
|
|
119
|
+
| HttpRouter.Request<"Error", _$effect_http_HttpServerError0.RouteNotFound>
|
|
120
|
+
| HttpRouter.Request<"Error", _$effect_http_HttpServerError0.InternalError>
|
|
121
|
+
>;
|
|
122
|
+
//#endregion
|
|
123
|
+
export {
|
|
124
|
+
sessionTokenInvalidCode as i,
|
|
125
|
+
RouteRealtimeRequestOptions as n,
|
|
126
|
+
sessionTokenHeader as r,
|
|
127
|
+
Realtime_d_exports as t
|
|
128
|
+
};
|
|
129
|
+
//# sourceMappingURL=Realtime-B5OIHlLR.d.ts.map
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-pbuEa-1d.js";
|
|
2
|
+
import * as Effect from "effect/Effect";
|
|
3
|
+
import * as Option from "effect/Option";
|
|
4
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
5
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
6
|
+
import * as HttpBody from "effect/http/HttpBody";
|
|
7
|
+
import * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
8
|
+
import * as HttpRouter from "effect/http/HttpRouter";
|
|
9
|
+
import * as HttpServerRequest from "effect/http/HttpServerRequest";
|
|
10
|
+
import * as HttpServerResponse from "effect/http/HttpServerResponse";
|
|
11
|
+
//#region src/effect/server/Realtime.ts
|
|
12
|
+
var Realtime_exports = /* @__PURE__ */ __exportAll({
|
|
13
|
+
handler: () => handler,
|
|
14
|
+
invalidPathCode: () => invalidPathCode,
|
|
15
|
+
layer: () => layer,
|
|
16
|
+
pathEscapesSession: () => pathEscapesSession,
|
|
17
|
+
routeRealtimeRequest: () => routeRealtimeRequest,
|
|
18
|
+
sessionTokenHeader: () => sessionTokenHeader,
|
|
19
|
+
sessionTokenInvalidCode: () => sessionTokenInvalidCode
|
|
20
|
+
});
|
|
21
|
+
/** The request header that carries the session token. */
|
|
22
|
+
const sessionTokenHeader = "x-realtime-session-token";
|
|
23
|
+
/** The `errorCode` of the response when the session token is not valid. */
|
|
24
|
+
const sessionTokenInvalidCode = "realtime_session_token_invalid";
|
|
25
|
+
/** The `errorCode` of the response when the path can escape its session. */
|
|
26
|
+
const invalidPathCode = "realtime_invalid_path";
|
|
27
|
+
const encoder = new TextEncoder();
|
|
28
|
+
const decoder = new TextDecoder();
|
|
29
|
+
function toBase64Url(bytes) {
|
|
30
|
+
let binary = "";
|
|
31
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
32
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
33
|
+
}
|
|
34
|
+
function fromBase64Url(text) {
|
|
35
|
+
try {
|
|
36
|
+
const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
|
|
37
|
+
const bytes = new Uint8Array(binary.length);
|
|
38
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
39
|
+
return bytes;
|
|
40
|
+
} catch {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const hmacKey = (secret) => crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
45
|
+
name: "HMAC",
|
|
46
|
+
hash: "SHA-256"
|
|
47
|
+
}, false, ["sign", "verify"]);
|
|
48
|
+
const jwtHeader = toBase64Url(encoder.encode(JSON.stringify({
|
|
49
|
+
alg: "HS256",
|
|
50
|
+
typ: "JWT"
|
|
51
|
+
})));
|
|
52
|
+
/** A JWT (HS256) that names the session. */
|
|
53
|
+
async function signSessionToken(sessionId, secret, ttl) {
|
|
54
|
+
const issuedAt = Math.floor(Date.now() / 1e3);
|
|
55
|
+
const payload = toBase64Url(encoder.encode(JSON.stringify({
|
|
56
|
+
sessionId,
|
|
57
|
+
iat: issuedAt,
|
|
58
|
+
exp: issuedAt + ttl
|
|
59
|
+
})));
|
|
60
|
+
const signature = await crypto.subtle.sign("HMAC", await hmacKey(secret), encoder.encode(`${jwtHeader}.${payload}`));
|
|
61
|
+
return `${jwtHeader}.${payload}.${toBase64Url(new Uint8Array(signature))}`;
|
|
62
|
+
}
|
|
63
|
+
async function sessionTokenIsValid(token, sessionId, secret) {
|
|
64
|
+
const [header, payload, signature, ...rest] = token.split(".");
|
|
65
|
+
if (header !== jwtHeader || payload === void 0 || signature === void 0 || rest.length > 0) return false;
|
|
66
|
+
const signatureBytes = fromBase64Url(signature);
|
|
67
|
+
const payloadBytes = fromBase64Url(payload);
|
|
68
|
+
if (signatureBytes === void 0 || payloadBytes === void 0) return false;
|
|
69
|
+
if (!await crypto.subtle.verify("HMAC", await hmacKey(secret), signatureBytes, encoder.encode(`${header}.${payload}`))) return false;
|
|
70
|
+
try {
|
|
71
|
+
const claims = JSON.parse(decoder.decode(payloadBytes));
|
|
72
|
+
return typeof claims === "object" && claims !== null && "sessionId" in claims && claims.sessionId === sessionId && "exp" in claims && typeof claims.exp === "number" && claims.exp > Date.now() / 1e3;
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const json = (status, body) => new Response(JSON.stringify(body), {
|
|
78
|
+
status,
|
|
79
|
+
headers: { "Content-Type": "application/json" }
|
|
80
|
+
});
|
|
81
|
+
const defaultIceServers = [{ urls: ["stun:stun.cloudflare.com:3478", "stun:stun.cloudflare.com:53"] }];
|
|
82
|
+
const encodedSeparator = /%2f|%5c|%3b/i;
|
|
83
|
+
const dotSegment = /^(?:\.|%2e){1,2}$/i;
|
|
84
|
+
/**
|
|
85
|
+
* True if the path has an encoded separator, a `;` or a dot segment. A proxy
|
|
86
|
+
* that decodes and resolves such a path can reach another session, or a path
|
|
87
|
+
* outside `/sessions/`. A `;` is refused because a proxy can remove the
|
|
88
|
+
* parameters of a segment: `..;x` becomes `..`.
|
|
89
|
+
*/
|
|
90
|
+
function pathEscapesSession(path) {
|
|
91
|
+
if (/[\\;]/.test(path) || encodedSeparator.test(path)) return true;
|
|
92
|
+
return path.split("/").some((segment) => dotSegment.test(segment));
|
|
93
|
+
}
|
|
94
|
+
const send = Effect.fnUntraced(function* (url, init) {
|
|
95
|
+
const client = yield* HttpClient.HttpClient;
|
|
96
|
+
const base = HttpClientRequest.fromWeb(new Request(url, { method: init.method }));
|
|
97
|
+
const request = init.body === void 0 ? base : HttpClientRequest.setBody(base, HttpBody.raw(init.body));
|
|
98
|
+
const response = yield* client.execute(HttpClientRequest.setHeaders(request, Object.fromEntries(new Headers(init.headers))));
|
|
99
|
+
const web = HttpClientResponse.toWeb(response);
|
|
100
|
+
if (Option.isSome(web)) return web.value;
|
|
101
|
+
const body = init.method === "HEAD" || [
|
|
102
|
+
204,
|
|
103
|
+
205,
|
|
104
|
+
304
|
|
105
|
+
].includes(response.status) ? null : yield* response.arrayBuffer;
|
|
106
|
+
return new Response(body, {
|
|
107
|
+
status: response.status,
|
|
108
|
+
headers: response.headers
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
const routeRealtimeRequest = Effect.fn("Realtime.routeRealtimeRequest")(function* (options) {
|
|
112
|
+
const { appId, token, request, prefix = "/realtime", realtimeApiBaseUrl = "https://rtc.live.cloudflare.com/v1", lockSessionToInitiator = true, sessionTokenSecret = token, sessionTokenTTL = 86400, turnServerAppId, turnServerAppToken, turnServerCredentialTTL = 86400, forwardHeaders = [] } = options;
|
|
113
|
+
const url = new URL(request.url);
|
|
114
|
+
if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)) return new Response(null, { status: 404 });
|
|
115
|
+
const path = url.pathname.slice(prefix.length);
|
|
116
|
+
if (pathEscapesSession(path)) return json(400, {
|
|
117
|
+
errorCode: invalidPathCode,
|
|
118
|
+
errorDescription: "The path of the request is not a plain path."
|
|
119
|
+
});
|
|
120
|
+
if (path === "/generate-ice-servers") {
|
|
121
|
+
if (turnServerAppId === void 0 || turnServerAppToken === void 0) return json(200, { iceServers: defaultIceServers });
|
|
122
|
+
return yield* send(`${realtimeApiBaseUrl}/turn/keys/${turnServerAppId}/credentials/generate-ice-servers`, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
body: JSON.stringify({ ttl: turnServerCredentialTTL }),
|
|
125
|
+
headers: {
|
|
126
|
+
Authorization: `Bearer ${turnServerAppToken}`,
|
|
127
|
+
"Content-Type": "application/json"
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const headers = new Headers();
|
|
132
|
+
for (const name of [
|
|
133
|
+
"content-type",
|
|
134
|
+
"accept",
|
|
135
|
+
...forwardHeaders
|
|
136
|
+
]) {
|
|
137
|
+
const value = request.headers.get(name);
|
|
138
|
+
if (value !== null) headers.set(name, value);
|
|
139
|
+
}
|
|
140
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
141
|
+
const body = request.method === "GET" || request.method === "HEAD" ? void 0 : yield* Effect.tryPromise(() => request.arrayBuffer());
|
|
142
|
+
const forward = () => send(`${realtimeApiBaseUrl}/apps/${appId}${path}${url.search}`, {
|
|
143
|
+
method: request.method,
|
|
144
|
+
headers,
|
|
145
|
+
body: body === void 0 || body.byteLength === 0 ? void 0 : body
|
|
146
|
+
});
|
|
147
|
+
if (!lockSessionToInitiator) return yield* forward();
|
|
148
|
+
if (path === "/sessions/new") {
|
|
149
|
+
const response = yield* forward();
|
|
150
|
+
const text = yield* Effect.tryPromise(() => response.text());
|
|
151
|
+
const passThrough = () => new Response(text, {
|
|
152
|
+
status: response.status,
|
|
153
|
+
statusText: response.statusText,
|
|
154
|
+
headers: response.headers
|
|
155
|
+
});
|
|
156
|
+
if (!response.ok) return passThrough();
|
|
157
|
+
let created;
|
|
158
|
+
try {
|
|
159
|
+
created = JSON.parse(text);
|
|
160
|
+
} catch {
|
|
161
|
+
return passThrough();
|
|
162
|
+
}
|
|
163
|
+
if (typeof created !== "object" || created === null || !("sessionId" in created) || typeof created.sessionId !== "string") return passThrough();
|
|
164
|
+
const id = created.sessionId;
|
|
165
|
+
return json(response.status, {
|
|
166
|
+
...created,
|
|
167
|
+
sessionToken: yield* Effect.tryPromise(() => signSessionToken(id, sessionTokenSecret, sessionTokenTTL))
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
const [, sessionId] = /^\/sessions\/([^/]+)(?:\/|$)/.exec(path) ?? [];
|
|
171
|
+
if (sessionId === void 0) return json(403, {
|
|
172
|
+
errorCode: "realtime_route_not_permitted",
|
|
173
|
+
errorDescription: "With lockSessionToInitiator, only session requests are permitted."
|
|
174
|
+
});
|
|
175
|
+
const sessionToken = request.headers.get(sessionTokenHeader);
|
|
176
|
+
if (sessionToken === null || !(yield* Effect.tryPromise(() => sessionTokenIsValid(sessionToken, sessionId, sessionTokenSecret)))) return json(401, {
|
|
177
|
+
errorCode: sessionTokenInvalidCode,
|
|
178
|
+
errorDescription: "The session token is absent, expired, or not for this session."
|
|
179
|
+
});
|
|
180
|
+
return yield* forward();
|
|
181
|
+
});
|
|
182
|
+
/** Handle the current router request using the supplied HttpClient. */
|
|
183
|
+
const handler = (options) => Effect.gen(function* () {
|
|
184
|
+
const request = yield* HttpServerRequest.toWeb(yield* HttpServerRequest.HttpServerRequest);
|
|
185
|
+
return HttpServerResponse.fromWeb(yield* routeRealtimeRequest({
|
|
186
|
+
...options,
|
|
187
|
+
request
|
|
188
|
+
}));
|
|
189
|
+
});
|
|
190
|
+
/** Mount every Realtime method under the configured prefix. */
|
|
191
|
+
const layer = (options) => HttpRouter.add("*", `${options.prefix ?? "/realtime"}/*`, handler(options));
|
|
192
|
+
//#endregion
|
|
193
|
+
export { sessionTokenInvalidCode as i, routeRealtimeRequest as n, sessionTokenHeader as r, Realtime_exports as t };
|
|
194
|
+
|
|
195
|
+
//# sourceMappingURL=Realtime-B6TjV8su.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Realtime-B6TjV8su.js","names":[],"sources":["../src/effect/server/Realtime.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as HttpBody from \"effect/http/HttpBody\";\nimport * as HttpClient from \"effect/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/http/HttpClientRequest\";\nimport * as HttpClientResponse from \"effect/http/HttpClientResponse\";\nimport * as HttpRouter from \"effect/http/HttpRouter\";\nimport * as HttpServerRequest from \"effect/http/HttpServerRequest\";\nimport * as HttpServerResponse from \"effect/http/HttpServerResponse\";\n\n/** The request header that carries the session token. */\nexport const sessionTokenHeader = \"x-realtime-session-token\";\n\n/** The `errorCode` of the response when the session token is not valid. */\nexport const sessionTokenInvalidCode = \"realtime_session_token_invalid\";\n\n/** The `errorCode` of the response when the path can escape its session. */\nexport const invalidPathCode = \"realtime_invalid_path\";\n\nexport interface RouteRealtimeRequestOptions {\n /**\n * Cloudflare Realtime SFU App ID. Get it here:\n * https://dash.cloudflare.com/?to=/:account/realtime/sfu/create\n */\n appId: string;\n /** Cloudflare Realtime SFU App Token. Keep it on the server. */\n token: string;\n /** The request of the browser. */\n request: Request;\n /**\n * The part of the path that is replaced. For a proxy route\n * `/api/realtime/*`, the value is \"/api/realtime\".\n * Default: \"/realtime\".\n */\n prefix?: string;\n /** Default: \"https://rtc.live.cloudflare.com/v1\". */\n realtimeApiBaseUrl?: string;\n /**\n * Only the browser that made a session can change it. The response of\n * `sessions/new` has a `sessionToken`, and the client sends it in a\n * request header with each later request of that session. Default: true.\n */\n lockSessionToInitiator?: boolean;\n /** The secret that signs the session token. Default: the SFU app token. */\n sessionTokenSecret?: string;\n /**\n * How long a session token is valid, in seconds. After that, the client\n * makes a new session. Default: 86400 (24 hours).\n */\n sessionTokenTTL?: number;\n /**\n * TURN Server App ID. Get it here:\n * https://dash.cloudflare.com/?to=/:account/realtime/turn/create\n */\n turnServerAppId?: string;\n /** TURN Server App Token. */\n turnServerAppToken?: string;\n /** How long the TURN credentials are valid, in seconds. Default: 86400. */\n turnServerCredentialTTL?: number;\n /**\n * More request headers that are sent to the Realtime API. `Content-Type`\n * and `Accept` are always sent. All other headers of the browser, for\n * example `Cookie`, are not sent.\n */\n forwardHeaders?: ReadonlyArray<string>;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(text: string): Uint8Array<ArrayBuffer> | undefined {\n try {\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n } catch {\n return undefined;\n }\n}\n\nconst hmacKey = (secret: string) =>\n crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\", \"verify\"]\n );\n\nconst jwtHeader = toBase64Url(\n encoder.encode(JSON.stringify({ alg: \"HS256\", typ: \"JWT\" }))\n);\n\n/** A JWT (HS256) that names the session. */\nasync function signSessionToken(\n sessionId: string,\n secret: string,\n ttl: number\n): Promise<string> {\n const issuedAt = Math.floor(Date.now() / 1000);\n const payload = toBase64Url(\n encoder.encode(\n JSON.stringify({ sessionId, iat: issuedAt, exp: issuedAt + ttl })\n )\n );\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n await hmacKey(secret),\n encoder.encode(`${jwtHeader}.${payload}`)\n );\n return `${jwtHeader}.${payload}.${toBase64Url(new Uint8Array(signature))}`;\n}\n\nasync function sessionTokenIsValid(\n token: string,\n sessionId: string,\n secret: string\n): Promise<boolean> {\n const [header, payload, signature, ...rest] = token.split(\".\");\n if (\n header !== jwtHeader ||\n payload === undefined ||\n signature === undefined ||\n rest.length > 0\n ) {\n return false;\n }\n const signatureBytes = fromBase64Url(signature);\n const payloadBytes = fromBase64Url(payload);\n if (signatureBytes === undefined || payloadBytes === undefined) return false;\n const verified = await crypto.subtle.verify(\n \"HMAC\",\n await hmacKey(secret),\n signatureBytes,\n encoder.encode(`${header}.${payload}`)\n );\n if (!verified) return false;\n try {\n const claims: unknown = JSON.parse(decoder.decode(payloadBytes));\n return (\n typeof claims === \"object\" &&\n claims !== null &&\n \"sessionId\" in claims &&\n claims.sessionId === sessionId &&\n \"exp\" in claims &&\n typeof claims.exp === \"number\" &&\n claims.exp > Date.now() / 1000\n );\n } catch {\n return false;\n }\n}\n\nconst json = (status: number, body: unknown) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\" }\n });\n\nconst defaultIceServers = [\n { urls: [\"stun:stun.cloudflare.com:3478\", \"stun:stun.cloudflare.com:53\"] }\n];\n\nconst encodedSeparator = /%2f|%5c|%3b/i;\nconst dotSegment = /^(?:\\.|%2e){1,2}$/i;\n\n/**\n * True if the path has an encoded separator, a `;` or a dot segment. A proxy\n * that decodes and resolves such a path can reach another session, or a path\n * outside `/sessions/`. A `;` is refused because a proxy can remove the\n * parameters of a segment: `..;x` becomes `..`.\n */\nexport function pathEscapesSession(path: string): boolean {\n if (/[\\\\;]/.test(path) || encodedSeparator.test(path)) return true;\n return path.split(\"/\").some((segment) => dotSegment.test(segment));\n}\n\nconst send = Effect.fnUntraced(function* (\n url: string,\n init: { method: string; headers: HeadersInit; body?: string | ArrayBuffer }\n) {\n const client = yield* HttpClient.HttpClient;\n const base = HttpClientRequest.fromWeb(\n new Request(url, { method: init.method })\n );\n const request =\n init.body === undefined\n ? base\n : HttpClientRequest.setBody(base, HttpBody.raw(init.body));\n // Setting the body can remove Content-Type. Apply the forwarded headers last.\n const response = yield* client.execute(\n HttpClientRequest.setHeaders(\n request,\n Object.fromEntries(new Headers(init.headers))\n )\n );\n const web = HttpClientResponse.toWeb(response);\n if (Option.isSome(web)) return web.value;\n const body =\n init.method === \"HEAD\" || [204, 205, 304].includes(response.status)\n ? null\n : yield* response.arrayBuffer;\n return new Response(body, {\n status: response.status,\n headers: response.headers\n });\n});\n\nexport const routeRealtimeRequest = Effect.fn(\"Realtime.routeRealtimeRequest\")(\n function* (options: RouteRealtimeRequestOptions) {\n const {\n appId,\n token,\n request,\n prefix = \"/realtime\",\n realtimeApiBaseUrl = \"https://rtc.live.cloudflare.com/v1\",\n lockSessionToInitiator = true,\n sessionTokenSecret = token,\n sessionTokenTTL = 86400,\n turnServerAppId,\n turnServerAppToken,\n turnServerCredentialTTL = 86400,\n forwardHeaders = []\n } = options;\n const url = new URL(request.url);\n if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)) {\n return new Response(null, { status: 404 });\n }\n const path = url.pathname.slice(prefix.length);\n if (pathEscapesSession(path)) {\n return json(400, {\n errorCode: invalidPathCode,\n errorDescription: \"The path of the request is not a plain path.\"\n });\n }\n\n if (path === \"/generate-ice-servers\") {\n if (turnServerAppId === undefined || turnServerAppToken === undefined) {\n return json(200, { iceServers: defaultIceServers });\n }\n return yield* send(\n `${realtimeApiBaseUrl}/turn/keys/${turnServerAppId}/credentials/generate-ice-servers`,\n {\n method: \"POST\",\n body: JSON.stringify({ ttl: turnServerCredentialTTL }),\n headers: {\n Authorization: `Bearer ${turnServerAppToken}`,\n \"Content-Type\": \"application/json\"\n }\n }\n );\n }\n\n // Only the headers of this list go to the Realtime API. The cookies and\n // the session token of the browser stay here.\n const headers = new Headers();\n for (const name of [\"content-type\", \"accept\", ...forwardHeaders]) {\n const value = request.headers.get(name);\n if (value !== null) headers.set(name, value);\n }\n headers.set(\"Authorization\", `Bearer ${token}`);\n // The body is read completely. A stream body is lost when the request has\n // no `Content-Length`, and some runtimes cannot send it.\n const body =\n request.method === \"GET\" || request.method === \"HEAD\"\n ? undefined\n : yield* Effect.tryPromise(() => request.arrayBuffer());\n const forward = () =>\n send(`${realtimeApiBaseUrl}/apps/${appId}${path}${url.search}`, {\n method: request.method,\n headers,\n body: body === undefined || body.byteLength === 0 ? undefined : body\n });\n\n if (!lockSessionToInitiator) return yield* forward();\n\n if (path === \"/sessions/new\") {\n const response = yield* forward();\n const text = yield* Effect.tryPromise(() => response.text());\n const passThrough = () =>\n new Response(text, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers\n });\n if (!response.ok) return passThrough();\n let created: unknown;\n try {\n created = JSON.parse(text);\n } catch {\n return passThrough();\n }\n if (\n typeof created !== \"object\" ||\n created === null ||\n !(\"sessionId\" in created) ||\n typeof created.sessionId !== \"string\"\n ) {\n return passThrough();\n }\n const id = created.sessionId;\n return json(response.status, {\n ...created,\n sessionToken: yield* Effect.tryPromise(() =>\n signSessionToken(id, sessionTokenSecret, sessionTokenTTL)\n )\n });\n }\n\n const [, sessionId] = /^\\/sessions\\/([^/]+)(?:\\/|$)/.exec(path) ?? [];\n if (sessionId === undefined) {\n return json(403, {\n errorCode: \"realtime_route_not_permitted\",\n errorDescription:\n \"With lockSessionToInitiator, only session requests are permitted.\"\n });\n }\n const sessionToken = request.headers.get(sessionTokenHeader);\n if (\n sessionToken === null ||\n !(yield* Effect.tryPromise(() =>\n sessionTokenIsValid(sessionToken, sessionId, sessionTokenSecret)\n ))\n ) {\n return json(401, {\n errorCode: sessionTokenInvalidCode,\n errorDescription:\n \"The session token is absent, expired, or not for this session.\"\n });\n }\n return yield* forward();\n }\n);\n\nexport type Options = Omit<RouteRealtimeRequestOptions, \"request\">;\n\n/** Handle the current router request using the supplied HttpClient. */\nexport const handler = (options: Options) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.toWeb(\n yield* HttpServerRequest.HttpServerRequest\n );\n return HttpServerResponse.fromWeb(\n yield* routeRealtimeRequest({ ...options, request })\n );\n });\n\n/** Mount every Realtime method under the configured prefix. */\nexport const layer = (options: Options & { prefix?: `/${string}` }) =>\n HttpRouter.add(\"*\", `${options.prefix ?? \"/realtime\"}/*`, handler(options));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAWA,MAAa,qBAAqB;;AAGlC,MAAa,0BAA0B;;AAGvC,MAAa,kBAAkB;AAkD/B,MAAM,UAAU,IAAI,aAAa;AACjC,MAAM,UAAU,IAAI,aAAa;AAEjC,SAAS,YAAY,OAA2B;CAC9C,IAAI,SAAS;AACb,MAAK,MAAM,QAAQ,MAAO,WAAU,OAAO,aAAa,KAAK;AAC7D,QAAO,KAAK,OAAO,CAChB,QAAQ,OAAO,IAAI,CACnB,QAAQ,OAAO,IAAI,CACnB,QAAQ,OAAO,GAAG;;AAGvB,SAAS,cAAc,MAAmD;AACxE,KAAI;EACF,MAAM,SAAS,KAAK,KAAK,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,IAAI,CAAC;EAC/D,MAAM,QAAQ,IAAI,WAAW,OAAO,OAAO;AAC3C,OAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,IAAK,OAAM,KAAK,OAAO,WAAW,EAAE;AACvE,SAAO;SACD;AACN;;;AAIJ,MAAM,WAAW,WACf,OAAO,OA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