Something went wrong. Try again.
Monorepo for Tangled forked from tangled.org/core
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import { Client, simpleFetchHandler } from "@atcute/client";import type { OAuthUserAgent } from "@atcute/oauth-browser-client";import { isNsid, type Did } from "@atcute/lexicons/syntax";import { mintServiceAuth, serviceDidForHost } from "#lib/auth/agent.ts";import { hasPinnedRpc } from "#lib/auth/scopes.ts";import { DEFAULT_POCKET_DID, rpcServices, serviceAudience } from "#lib/auth/services.ts";import { didOf, nsidOf, type Nsid } from "#lib/api/syntax.ts";import { normalizeHandle } from "#lib/handle.ts";import type { Fetch } from "#lib/fetch.ts";
export { ClientResponseError, isXRPCErrorPayload, ok } from "@atcute/client";export type { XRPCErrorPayload } from "@atcute/client";
// generated lexicons register ambient types; don't import the barrel at runtime.
export interface BobbinContext { readonly xrpc: Client; readonly serviceUrl: string; readonly fetch: Fetch;}
export interface CreateBobbinOptions { serviceUrl: string; fetch?: Fetch; agent?: OAuthUserAgent; fixedService?: "bobbin" | "deliberi" | "migrator" | "sites"; pocketServiceDid?: Did; /** off for bodies with no handles that must keep streaming, see withNormalizedHandles */ normalizeHandles?: boolean;}
export const nsidFromUrl = (input: RequestInfo | URL): Nsid | null => { const href = input instanceof Request ? input.url : String(input); let pathname: string; try { pathname = new URL(href).pathname; } catch { return null; } const [, prefix, nsid, ...rest] = pathname.split("/"); return prefix === "xrpc" && nsid && rest.length === 0 && isNsid(nsid) ? nsidOf(nsid) : null;};
// pocket keys stored preferences by the token's `aud`export const PREFERENCES_LXMS = Object.keys(rpcServices) .filter((lxm) => rpcServices[lxm] === "pocket") .map(nsidOf);
export const withServiceAuth = ( base: Fetch, agent: OAuthUserAgent, origin: string, fixedService?: CreateBobbinOptions["fixedService"], pocketServiceDid = DEFAULT_POCKET_DID): Fetch => { return async (input, init) => { const lxm = nsidFromUrl(input); if (!lxm) return base(input, init);
const service = rpcServices[lxm]; const isPocket = service === "pocket"; if ( fixedService && (!service || (service !== fixedService && !(fixedService === "bobbin" && isPocket))) ) return base(input, init); const aud = isPocket ? didOf(pocketServiceDid) : serviceDidForHost(origin); const proxy = fixedService && service ? serviceAudience(service, aud) : undefined; const headers = new Headers(init?.headers); // old and loopback sessions have wildcard grants and keep calling services directly if (proxy && hasPinnedRpc(agent.session?.token.scope ?? "", lxm, proxy)) { const url = new URL(input instanceof Request ? input.url : input); headers.set("atproto-proxy", proxy); return agent.handle(url.pathname + url.search, { ...init, headers }); } const token = await mintServiceAuth(agent, { aud, lxm, ...(init?.signal && { signal: init.signal }) }); headers.set("authorization", `Bearer ${token}`); return base(input, { ...init, headers }); };};
// the handles the ui shows come out of bobbin as a `handle` field somewhere in a json// body, so normalizing them here covers the views at once. it buffers the body, so// non-json (patches, archives, blobs) passes through, and git reads opt outexport const withNormalizedHandles = (base: Fetch): Fetch => { return async (input, init) => { const response = await base(input, init); if (!response.headers.get("content-type")?.includes("application/json")) return response; const text = await response.text(); if (!text.includes('"handle"')) return new Response(text, response); const body = JSON.stringify( JSON.parse(text, (key, value: unknown) => key === "handle" && typeof value === "string" ? normalizeHandle(value) : value ) ); // the body is decoded and rewritten, so the wire's encoding and length no longer apply const headers = new Headers(response.headers); headers.delete("content-encoding"); headers.delete("content-length"); return new Response(body, { status: response.status, statusText: response.statusText, headers }); };};
export const createBobbinClient = ({ serviceUrl, fetch, agent, fixedService, pocketServiceDid, normalizeHandles = true}: CreateBobbinOptions): BobbinContext => { const origin = serviceUrl.replace(/\/+$/, ""); const rawFetch = fetch ?? globalThis.fetch; const authenticated = agent ? withServiceAuth(rawFetch, agent, origin, fixedService, pocketServiceDid) : rawFetch; const boundFetch = normalizeHandles ? withNormalizedHandles(authenticated) : authenticated; const xrpc = new Client({ handler: simpleFetchHandler({ service: origin, fetch: boundFetch as typeof globalThis.fetch }) }); return { xrpc, serviceUrl: origin, fetch: boundFetch };};
export const createAuthenticatedBobbinClient = ( { bobbinUrl, pocketServiceDid }: { bobbinUrl: string; pocketServiceDid?: Did }, agent: OAuthUserAgent): BobbinContext => createBobbinClient({ serviceUrl: bobbinUrl, agent, fixedService: "bobbin", pocketServiceDid });
export type QueryValue = string | number | boolean | readonly (string | number)[] | undefined;
export interface XrpcRequestInit { signal?: AbortSignal; headers?: HeadersInit;}