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 type { HttpClient } from "effect/http";
9
10import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
11import type { PreparedConnection } from "../connection/model.ts";
12import { environmentEndpointUrl } from "../environment/endpoint.ts";
13import * as ManagedRelay from "../relay/managedRelay.ts";
14import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
15import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
16import type { DeviceHubAccess } from "../device/hubAccess.ts";
17
18export { type DeviceHubAccess, withDeviceHubQuery } from "../device/hubAccess.ts";
19
20const TICKET_TIMEOUT_MS = 8_000;
21
22export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDeviceHubAccess")(
23 function* (input: {
24 readonly prepared: PreparedConnection;
25 readonly hubBasePath: string;
26 }): Effect.fn.Return<DeviceHubAccess, RemoteEnvironmentRequestError, HttpClient.HttpClient> {
27 const httpBase = environmentEndpointUrl(input.prepared.httpBaseUrl, input.hubBasePath);
28 const wsBase = httpBase.replace(/^http/, "ws");
29 if (input.prepared.httpAuthorization === null) {
30 return { httpBase, wsBase, query: {}, credentials: true };
31 }
32 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
33 const remoteAuthorization = yield* Effect.serviceOption(
34 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
35 );
36 const ticket = yield* executeAuthenticatedEnvironmentHttpRequest({
37 prepared: input.prepared,
38 signer,
39 remoteAuthorization,
40 group: "auth",
41 method: "POST",
42 url: (urls) => urls.webSocketTicket(),
43 timeoutMs: TICKET_TIMEOUT_MS,
44 request: ({ client, headers }) => client.webSocketTicket({ headers }),
45 });
46 return {
47 httpBase,
48 wsBase,
49 query: { wsTicket: ticket.ticket },
50 credentials: false,
51 };
52 },
53);