~james/core

core/web/src/lib/api/deliberi.ts -rw-r--r-- 2.6 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import { mintServiceAuth, serviceDidForHost } from "#lib/auth/agent.ts";
import { buildUrl, toResponseError } from "#lib/api/_request.ts";
import type { QueryValue, XrpcRequestInit } from "#lib/api/client.ts";
import type { Did, Nsid } from "#lib/api/syntax.ts";
import type { Fetch } from "#lib/fetch.ts";

// Authenticated client for deliberi's org.tangled.temp.* xrpc methods.
// Calls are authed with an atproto service-auth jwt: the browser mints a
// per-call token via the user's pds (getServiceAuth), scoped to the method
// (lxm) and deliberi's did:web (aud).
export interface DeliberiContext {
	readonly serviceUrl: string;
	readonly aud: Did;
	readonly agent: OAuthUserAgent;
	readonly fetch: Fetch;
}

export interface CreateDeliberiOptions {
	deliberiUrl: string;
	agent: OAuthUserAgent;
	fetch?: Fetch;
}

export const createDeliberiClient = ({
	deliberiUrl,
	agent,
	fetch
}: CreateDeliberiOptions): DeliberiContext => {
	const serviceUrl = deliberiUrl.replace(/\/+$/, "");
	// aud is derived from the url hostname so it can't drift from
	// deliberi's DELIBERI_HOSTNAME — both must match for service auth.
	const aud = serviceDidForHost(new URL(serviceUrl).host);
	return { serviceUrl, aud, agent, fetch: fetch ?? globalThis.fetch };
};

const authHeader = async (ctx: DeliberiContext, nsid: Nsid): Promise<string> => {
	const token = await mintServiceAuth(ctx.agent, { aud: ctx.aud, lxm: nsid });
	return `Bearer ${token}`;
};

export const authedGet = async <T>(
	ctx: DeliberiContext,
	nsid: Nsid,
	params?: Record<string, QueryValue>,
	init?: XrpcRequestInit
): Promise<T> => {
	const response = await ctx.fetch(buildUrl(ctx.serviceUrl, nsid, params), {
		headers: {
			accept: "application/json",
			authorization: await authHeader(ctx, nsid),
			...init?.headers
		},
		signal: init?.signal
	});
	if (!response.ok) throw await toResponseError(response);
	return (await response.json()) as T;
};

export const authedPost = async <T>(
	ctx: DeliberiContext,
	nsid: Nsid,
	body: unknown,
	init?: XrpcRequestInit
): Promise<T | null> => {
	const response = await ctx.fetch(buildUrl(ctx.serviceUrl, nsid), {
		method: "POST",
		headers: {
			"content-type": "application/json",
			accept: "application/json",
			authorization: await authHeader(ctx, nsid),
			...init?.headers
		},
		body: JSON.stringify(body ?? {}),
		signal: init?.signal
	});
	if (!response.ok) throw await toResponseError(response);
	// most temp procedures return no body (200 with empty payload)
	const text = await response.text();
	return text ? (JSON.parse(text) as T) : null;
};