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
23/** Reusable across media requests until it expires; only for connections that send credentials. */
24export const mintMediaTicket = Effect.fn("clientRuntime.state.mintMediaTicket")(function* (
25 prepared: PreparedConnection,
26) {
27 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
28 const remoteAuthorization = yield* Effect.serviceOption(
29 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
30 );
31 return yield* executeAuthenticatedEnvironmentHttpRequest({
32 prepared,
33 signer,
34 remoteAuthorization,
35 group: "auth",
36 method: "POST",
37 url: (urls) => urls.webSocketTicketFor({ params: { use: "media" } }),
38 timeoutMs: TICKET_TIMEOUT_MS,
39 request: ({ client, headers }) =>
40 client.webSocketTicketFor({ headers, params: { use: "media" } }),
41 });
42});
43
44export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDeviceHubAccess")(
45 function* (input: {
46 readonly prepared: PreparedConnection;
47 readonly hubBasePath: string;
48 }): Effect.fn.Return<DeviceHubAccess, RemoteEnvironmentRequestError, HttpClient.HttpClient> {
49 const httpBase = environmentEndpointUrl(input.prepared.httpBaseUrl, input.hubBasePath);
50 const wsBase = httpBase.replace(/^http/, "ws");
51 if (input.prepared.httpAuthorization === null) {
52 return { httpBase, wsBase, query: {}, credentials: true };
53 }
54 const ticket = yield* mintMediaTicket(input.prepared);
55 return {
56 httpBase,
57 wsBase,
58 query: { wsTicket: Redacted.value(ticket.ticket) },
59 credentials: false,
60 };
61 },
62);