// The sync server: discovery, a token, and a socket. // // Same shape as `scn-obsidian`'s setup, minus the parts a browser cannot do. // The relay says who its authorization server is, the server says where to get a // token, and the socket carries that token in the query string because a browser // WebSocket cannot set an `Authorization` header. export interface Discovery { /** The relay, e.g. https://notes.sharedcomputer.network */ resource: string; /** Corliss, e.g. https://sharedcomputer.network */ issuer: string; authorizationEndpoint: string; tokenEndpoint: string; /** Whether the server can be its own client metadata document (CIMD). */ clientMetadataDocument: boolean; } export function normalise(input: string): string { const trimmed = input.trim().replace(/\/+$/, ""); if (!trimmed) throw new Error("a sync server URL is required"); return /^https?:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`; } /** * The dev-server's stand-in for a host that sends no CORS headers. * * The SCN relay and Corliss answer without `Access-Control-Allow-Origin`, so a * browser cannot read them from `127.0.0.1` — `fetch` rejects with "Failed to * fetch" and says nothing about why. Vite proxies the two hosts we know about; * anything else goes direct and will fail the same way until the server is fixed. */ export function via(url: string): string { if (!import.meta.env.DEV) return url; const known: [RegExp, string][] = [ [/^https:\/\/notes\.sharedcomputer\.network/, "/relay"], [/^https:\/\/sharedcomputer\.network/, "/issuer"], ]; for (const [pattern, prefix] of known) { if (pattern.test(url)) return url.replace(pattern, prefix); } return url; } async function json(url: string): Promise> { const response = await fetch(via(url), { headers: { accept: "application/json" } }); if (!response.ok) throw new Error(`${url} answered ${response.status}`); return (await response.json()) as Record; } /** * Ask the relay who it trusts, then ask that server where its endpoints are. * * Two fetches, both standard: `/.well-known/oauth-protected-resource` on the * resource, and `/.well-known/oauth-authorization-server` on the issuer it names. * Doing it this way means a different deployment needs no code change — which is * the point of the well-known documents. */ export async function discover(syncUrl: string): Promise { const resource = normalise(syncUrl); const protectedResource = await json(`${resource}/.well-known/oauth-protected-resource`); const servers = protectedResource.authorization_servers; const issuer = Array.isArray(servers) ? String(servers[0] ?? "") : ""; if (!issuer) throw new Error(`${resource} names no authorization server`); const metadata = await json(`${issuer}/.well-known/oauth-authorization-server`); const authorizationEndpoint = String(metadata.authorization_endpoint ?? ""); const tokenEndpoint = String(metadata.token_endpoint ?? ""); if (!authorizationEndpoint || !tokenEndpoint) { throw new Error(`${issuer} publishes no authorization or token endpoint`); } return { resource, issuer, authorizationEndpoint, tokenEndpoint, clientMetadataDocument: metadata.client_id_metadata_document_supported === true, }; } /** * The client id, which for this estate is a document the authorization server * hosts itself. * * `scn-obsidian` uses `https://sharedcomputer.network/clients/scn-obsidian.json`, * served by Corliss, whose `redirect_uris` is the plugin's own scheme * `obsidian://scn-obsidian`. So a "registered client" here is a JSON document on * the server, not an OAuth dynamic registration — and a browser client needs one * the same way, with a loopback redirect in it: * * https://sharedcomputer.network/clients/scn-local.json * { "redirect_uris": ["http://127.0.0.1:5173/"] } * * The authorization request also carries `resource=` (RFC 8707), which * is what makes the token's audience the relay rather than the issuer. The plugin * sends it; a browser flow must too. */ export function clientIdFor(issuer: string, name = "scn-local"): string { return `${issuer.replace(/\/+$/, "")}/clients/${name}.json`; } /** What the relay says this token may open. Throws with the relay's words. */ export async function probe(syncUrl: string, token: string): Promise { const response = await fetch(via(`${normalise(syncUrl)}/v1/workspaces`), { headers: { Authorization: `Bearer ${token}`, accept: "application/json" }, }); if (!response.ok) { const body = await response.text().catch(() => ""); throw new Error(`${response.status} ${body.slice(0, 200)}`.trim()); } return response.json(); }