~james/core

core/web/src/lib/api/appview.ts -rw-r--r-- 2.7 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
82
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 the go appview's org.tangled.temp.* xrpc methods.
// Unlike bobbin (public reads) and the pds (record writes), these 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 the appview's did
// (aud). The appview verifies the issuer's signature and the aud/lxm claims.
export interface AppviewContext {
	readonly serviceUrl: string;
	readonly aud: Did;
	readonly agent: OAuthUserAgent;
	readonly fetch: Fetch;
}

export interface CreateAppviewOptions {
	apiUrl: string;
	agent: OAuthUserAgent;
	fetch?: Fetch;
}

export const createAppviewClient = ({
	apiUrl,
	agent,
	fetch
}: CreateAppviewOptions): AppviewContext => {
	const serviceUrl = apiUrl.replace(/\/+$/, "");
	// aud host must match the appview's TANGLED_APPVIEW_HOST, which is the host
	// it's reached at; derive both from the same url so they can't drift.
	const aud = serviceDidForHost(new URL(serviceUrl).host);
	return { serviceUrl, aud, agent, fetch: fetch ?? globalThis.fetch };
};

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

export const authedGet = async <T>(
	ctx: AppviewContext,
	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: AppviewContext,
	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;
};