Open History to see the last commit
1/**
2 * `<img>`, `EventSource`, and `WebSocket` cannot set bearer or DPoP headers, so bearer and DPoP
3 * connections mint a short-lived WebSocket ticket and pass it as `wsTicket`, the same way the
4 * app's own `/ws` upgrade authenticates. Callers fetch a fresh one each time they (re)connect a
5 * stream.
6 */
7import * as Effect from "effect/Effect";
8import * as Redacted from "effect/Redacted";
9import type { HttpClient } from "effect/http";
10
11import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
12import type { PreparedConnection } from "../connection/model.ts";
13import { environmentEndpointUrl } from "../environment/endpoint.ts";
14import * as ManagedRelay from "../relay/managedRelay.ts";
15import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
16import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
17import type { DeviceHubAccess } from "../device/hubAccess.ts";
18
19export { type DeviceHubAccess, withDeviceHubQuery } from "../device/hubAccess.ts";
20
21const TICKET_TIMEOUT_MS = 8_000;
22
23export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDeviceHubAccess")(
24 function* (input: {
25 readonly prepared: PreparedConnection;
26 readonly hubBasePath: string;
27 }): Effect.fn.Return<DeviceHubAccess, RemoteEnvironmentRequestError, HttpClient.HttpClient> {
28 const httpBase = environmentEndpointUrl(input.prepared.httpBaseUrl, input.hubBasePath);
29 const wsBase = httpBase.replace(/^http/, "ws");
30 if (input.prepared.httpAuthorization === null) {
31 return { httpBase, wsBase, query: {}, credentials: true };
32 }
33 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
34 const remoteAuthorization = yield* Effect.serviceOption(
35 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
36 );
37 const ticket = yield* executeAuthenticatedEnvironmentHttpRequest({
38 prepared: input.prepared,
39 signer,
40 remoteAuthorization,
41 group: "auth",
42 method: "POST",
43 url: (urls) => urls.webSocketTicketFor({ params: { use: "media" } }),
44 timeoutMs: TICKET_TIMEOUT_MS,
45 request: ({ client, headers }) =>
46 client.webSocketTicketFor({ headers, params: { use: "media" } }),
47 });
48 return {
49 httpBase,
50 wsBase,
51 query: { wsTicket: Redacted.value(ticket.ticket) },
52 credentials: false,
53 };
54 },
55);