~james/core

core/web/src/lib/api/invite.ts -rw-r--r-- 1.2 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
import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import { mintServiceAuth, serviceDidForHost } from "#lib/auth/agent.ts";
import type { XRPCProcedures } from "@atcute/lexicons/ambient";
import { serviceUrlFor, toResponseError } from "#lib/api/_request.ts";
import { nsidOf } from "#lib/api/syntax.ts";
import type { Fetch } from "#lib/fetch.ts";

// spelled out rather than read off the lexicon's schema: the generated module sits in a
// `server/` directory (its nsid's path), which sveltekit refuses to ship to the browser
const REDEEM: keyof XRPCProcedures = "org.tangled.temp.server.redeemInviteCode";

export const REDEEM_NSID = nsidOf(REDEEM);

export const redeemInviteCode = async (
	agent: OAuthUserAgent,
	knot: string,
	code: string,
	fetch: Fetch = globalThis.fetch
): Promise<void> => {
	const token = await mintServiceAuth(agent, {
		aud: serviceDidForHost(knot),
		lxm: REDEEM_NSID
	});
	const response = await fetch(new URL(`/xrpc/${REDEEM_NSID}`, `${serviceUrlFor(knot)}/`), {
		method: "POST",
		headers: {
			"content-type": "application/json",
			accept: "application/json",
			authorization: `Bearer ${token}`
		},
		body: JSON.stringify({ code })
	});
	if (!response.ok) throw await toResponseError(response);
};