techne-sdk 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -5
- package/README.md +51 -1
- package/dist/auth/index.d.ts +2 -2
- package/dist/auth/index.js +5 -3
- package/dist/auth/placement.gen.d.ts +1 -1
- package/dist/auth/placement.gen.js +4 -0
- package/dist/catalog/catalog.gen.d.ts +2 -2
- package/dist/catalog/catalog.gen.js +1394 -130
- package/dist/generated/index.d.ts +129 -0
- package/dist/generated/index.js +170 -0
- package/dist/generated/lexicons.d.ts +954 -134
- package/dist/generated/lexicons.js +511 -61
- package/dist/generated/nsid.d.ts +16 -1
- package/dist/generated/nsid.js +16 -1
- package/dist/generated/nsid.json +16 -1
- package/dist/generated/records.d.ts +148 -140
- package/dist/generated/types/app/certified/defs.d.ts +20 -0
- package/dist/generated/types/app/certified/defs.js +18 -0
- package/dist/generated/types/app/certified/signature/defs.d.ts +29 -0
- package/dist/generated/types/app/certified/signature/defs.js +18 -0
- package/dist/generated/types/org/hypercerts/funding/receipt.d.ts +56 -0
- package/dist/generated/types/org/hypercerts/funding/receipt.js +19 -0
- package/dist/generated/types/pub/techne/draft/financials.d.ts +26 -0
- package/dist/generated/types/pub/techne/draft/financials.js +12 -0
- package/dist/generated/types/pub/techne/draft/identity/createCollective.d.ts +5 -0
- package/dist/generated/types/pub/techne/draft/identity/createCollective.js +7 -0
- package/dist/generated/types/pub/techne/draft/identity/defs.d.ts +1 -1
- package/dist/generated/types/pub/techne/draft/identity/manageMethods.d.ts +4 -1
- package/dist/generated/types/pub/techne/draft/org.d.ts +55 -25
- package/dist/generated/types/pub/techne/draft/org.js +12 -5
- package/dist/generated/types/pub/techne/draft/orgAtPlace.d.ts +17 -0
- package/dist/generated/types/pub/techne/draft/orgAtPlace.js +12 -0
- package/dist/generated/types/pub/techne/draft/statement.d.ts +19 -0
- package/dist/generated/types/pub/techne/draft/statement.js +12 -0
- package/dist/session/dpop.d.ts +49 -0
- package/dist/session/dpop.js +105 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +22 -0
- package/dist/session/own-session.d.ts +169 -0
- package/dist/session/own-session.js +364 -0
- package/dist/session/phone.d.ts +79 -0
- package/dist/session/phone.js +179 -0
- package/dist/session/relay.d.ts +69 -0
- package/dist/session/relay.js +120 -0
- package/dist/wasm/techne-wasm.gen.js +1 -1
- package/dist/wasm/techne-wasm2js.gen.js +23340 -23255
- package/package.json +10 -3
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in through the platform's phone door in own-session mode: the device makes the DPoP key and the PKCE
|
|
3
|
+
* pair and signs every proof; the platform runs the door (and adds its client assertion) and answers the
|
|
4
|
+
* token set bound to the device's key, plus a narrow device credential. The platform keeps no session.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* const pending = await startPhoneSignIn({ platformUrl, phone }) // texts the code
|
|
8
|
+
* const { session: data, created } = await finishPhoneSignIn(pending, code, { platformUrl })
|
|
9
|
+
* const session = await OwnSession.signedIn(data, { platformUrl, store })
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* And {@link adoptHeldSession}, the one-time move of a session the platform holds for a device that signed
|
|
13
|
+
* in on an older build (deprecated: removed when the platform stops holding sessions).
|
|
14
|
+
*/
|
|
15
|
+
import { METHOD } from '../generated/nsid.js';
|
|
16
|
+
import { dpopKeyFromJwk, dpopProof, generateDpopKey, pkcePair } from './dpop.js';
|
|
17
|
+
import { OwnSessionError, fetchOr, nonceIn, obj, postPlatform, refusal, str, trimSlash, withNonceRetry, withTimeout } from './relay.js';
|
|
18
|
+
/** The fields every own-session answer must carry (beyond the lexicon's `required`, the SDK needs `pds`, where
|
|
19
|
+
* the tokens go, and `sub`). */
|
|
20
|
+
function ownAnswer(nsid, own) {
|
|
21
|
+
if (!str(own, 'accessToken') || !str(own, 'pds') || !str(own, 'sub')?.startsWith('did:')) {
|
|
22
|
+
throw new OwnSessionError('InvalidResponse', `techne-sdk/session: ${nsid} answered no session (accessToken, pds and sub)`);
|
|
23
|
+
}
|
|
24
|
+
return own;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Step 1: ask the door for its endpoints, make the DPoP key and the PKCE pair, and start the sign-in (the
|
|
28
|
+
* platform texts the code). Rejects with the platform's refusal as an {@link OwnSessionError}:
|
|
29
|
+
* `OwnSessionUnavailable` (sign in the old way: the door is off, or a review number), `RateLimitExceeded`
|
|
30
|
+
* (`retryAfter`), `InvalidRequest`.
|
|
31
|
+
*/
|
|
32
|
+
export async function startPhoneSignIn(o) {
|
|
33
|
+
const fetch = fetchOr(o.fetch);
|
|
34
|
+
const nsid = METHOD.START_PHONE_SIGNUP;
|
|
35
|
+
const first = await postPlatform(fetch, o.platformUrl, nsid, { phone: o.phone, ownSession: {} });
|
|
36
|
+
if (first.status !== 200)
|
|
37
|
+
throw refusal(nsid, first);
|
|
38
|
+
const own = obj(first.json, 'ownSession');
|
|
39
|
+
const [challengeEndpoint, tokenEndpoint, revocationEndpoint] = [str(own, 'challengeEndpoint'), str(own, 'tokenEndpoint'), str(own, 'revocationEndpoint')];
|
|
40
|
+
if (!challengeEndpoint || !tokenEndpoint || !revocationEndpoint)
|
|
41
|
+
throw new OwnSessionError('InvalidResponse', `techne-sdk/session: ${nsid} answered no endpoints`);
|
|
42
|
+
const endpoints = { issuer: str(own, 'issuer'), challengeEndpoint, tokenEndpoint, revocationEndpoint };
|
|
43
|
+
const dpopKey = generateDpopKey();
|
|
44
|
+
const { verifier, challenge } = pkcePair();
|
|
45
|
+
const { nonce } = await withNonceRetry(nsid, nonceIn(first), (nonce) => postPlatform(fetch, o.platformUrl, nsid, {
|
|
46
|
+
phone: o.phone,
|
|
47
|
+
ownSession: { codeChallenge: challenge, dpop: dpopProof(dpopKey, { htm: 'POST', htu: challengeEndpoint, nonce }) },
|
|
48
|
+
}));
|
|
49
|
+
return { phone: o.phone, dpopKey, codeVerifier: verifier, endpoints, dpopNonce: nonce };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Step 2: finish with the code the person entered. The three proofs (code step, token, and the revoke the
|
|
53
|
+
* platform uses only if a check refuses the sign-in) are signed with the latest nonce; a `UseDpopNonce`
|
|
54
|
+
* answer with a new nonce is signed again and sent with the same code (the platform has not spent it), up to
|
|
55
|
+
* twice (the code step and the token step may each ask). `pending.dpopNonce` keeps the latest nonce, so a
|
|
56
|
+
* retry by the app signs with it. Answers the session to save ({@link OwnSession.signedIn}) and whether the
|
|
57
|
+
* number's account was just made. Rejects with the platform's refusal: `InvalidRequest` (wrong code: try
|
|
58
|
+
* again), `CodeExpired` (start again), `NewCodeSent`, `MethodFrozen`, `OwnSessionUnavailable`,
|
|
59
|
+
* `RateLimitExceeded`, `Unavailable`.
|
|
60
|
+
*/
|
|
61
|
+
export async function finishPhoneSignIn(pending, code, o) {
|
|
62
|
+
const fetch = fetchOr(o.fetch);
|
|
63
|
+
const nsid = METHOD.FINISH_PHONE_SIGNUP;
|
|
64
|
+
const key = dpopKeyFromJwk(pending.dpopKey);
|
|
65
|
+
const e = pending.endpoints;
|
|
66
|
+
const send = (nonce) => postPlatform(fetch, o.platformUrl, nsid, {
|
|
67
|
+
phone: pending.phone,
|
|
68
|
+
code,
|
|
69
|
+
...(o.device && { device: o.device }),
|
|
70
|
+
ownSession: {
|
|
71
|
+
challengeDpop: dpopProof(key, { htm: 'POST', htu: e.challengeEndpoint, nonce }),
|
|
72
|
+
tokenDpop: dpopProof(key, { htm: 'POST', htu: e.tokenEndpoint, nonce }),
|
|
73
|
+
revokeDpop: dpopProof(key, { htm: 'POST', htu: e.revocationEndpoint, nonce }),
|
|
74
|
+
codeVerifier: pending.codeVerifier,
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
let done;
|
|
78
|
+
try {
|
|
79
|
+
done = await withNonceRetry(nsid, pending.dpopNonce, send, 2);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
if (err instanceof OwnSessionError && err.nonce)
|
|
83
|
+
pending.dpopNonce = err.nonce;
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
const { answer, nonce } = done;
|
|
87
|
+
pending.dpopNonce = nonce;
|
|
88
|
+
const own = ownAnswer(nsid, obj(answer.json, 'ownSession'));
|
|
89
|
+
const did = str(answer.json, 'did');
|
|
90
|
+
if (own.sub !== did)
|
|
91
|
+
throw new OwnSessionError('WrongAccount', `techne-sdk/session: the tokens are for ${own.sub}, the sign-in for ${did}`);
|
|
92
|
+
return { session: sessionData(own, key, e, nonce, answer.json), created: answer.json?.created === true };
|
|
93
|
+
}
|
|
94
|
+
function sessionData(own, key, e, nonce, device) {
|
|
95
|
+
const expires = Date.parse(str(own, 'expiresAt') ?? '');
|
|
96
|
+
return {
|
|
97
|
+
did: own.sub,
|
|
98
|
+
pds: own.pds,
|
|
99
|
+
accessToken: own.accessToken,
|
|
100
|
+
refreshToken: str(own, 'refreshToken'),
|
|
101
|
+
expiresAt: Number.isFinite(expires) ? expires : undefined,
|
|
102
|
+
scope: str(own, 'scope'),
|
|
103
|
+
issuer: str(own, 'issuer'),
|
|
104
|
+
tokenEndpoint: e.tokenEndpoint,
|
|
105
|
+
revocationEndpoint: e.revocationEndpoint,
|
|
106
|
+
dpopKey: key,
|
|
107
|
+
dpopNonce: str(own, 'dpopNonce') ?? nonce,
|
|
108
|
+
deviceSession: str(device, 'deviceSession'),
|
|
109
|
+
deviceId: str(device, 'deviceId'),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** How long one fetch of the issuer's metadata may take, and the waits between tries. */
|
|
113
|
+
const METADATA_TIMEOUT_MS = 10_000;
|
|
114
|
+
const METADATA_RETRY_DELAYS_MS = [1_000, 3_000];
|
|
115
|
+
const HTTPS_ORIGIN = /^https:\/\/[^/?#]+\/?$/i;
|
|
116
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
117
|
+
/** The token and revocation endpoints of authorization server `issuer` (its RFC 8414 metadata). */
|
|
118
|
+
async function authorizationServerEndpoints(issuer, fetch) {
|
|
119
|
+
const base = trimSlash(issuer);
|
|
120
|
+
// The body is read inside the timeout too: an issuer that sends its headers and then stalls is given up.
|
|
121
|
+
const meta = await withTimeout(METADATA_TIMEOUT_MS, async (signal) => {
|
|
122
|
+
const res = await fetch(`${base}/.well-known/oauth-authorization-server`, { headers: { accept: 'application/json' }, signal });
|
|
123
|
+
if (!res.ok)
|
|
124
|
+
throw new OwnSessionError('Unavailable', `techne-sdk/session: ${base} metadata answered ${res.status}`, { status: res.status });
|
|
125
|
+
return (await res.json());
|
|
126
|
+
});
|
|
127
|
+
const [tokenEndpoint, revocationEndpoint] = [str(meta, 'token_endpoint'), str(meta, 'revocation_endpoint')];
|
|
128
|
+
if (trimSlash(str(meta, 'issuer') ?? '') !== base || !tokenEndpoint || !revocationEndpoint) {
|
|
129
|
+
throw new OwnSessionError('InvalidResponse', `techne-sdk/session: ${base} metadata names another issuer, or no token or revocation endpoint`);
|
|
130
|
+
}
|
|
131
|
+
return { tokenEndpoint, revocationEndpoint };
|
|
132
|
+
}
|
|
133
|
+
/** {@link authorizationServerEndpoints}, tried three times; when no try answers, the endpoints every atproto
|
|
134
|
+
* authorization server (`@atproto/oauth-provider`, the ePDS) serves: `/oauth/token` and `/oauth/revoke`.
|
|
135
|
+
* Used after the platform handed its session over and deleted its copy, so the tokens are kept either way
|
|
136
|
+
* (if those endpoints were wrong, the next refresh is refused and the person signs in again, which is what
|
|
137
|
+
* throwing the tokens away would have meant at once). */
|
|
138
|
+
async function endpointsKeepingTokens(issuer, fetch) {
|
|
139
|
+
for (let i = 0;; i++) {
|
|
140
|
+
try {
|
|
141
|
+
return await authorizationServerEndpoints(issuer, fetch);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
if (i >= METADATA_RETRY_DELAYS_MS.length)
|
|
145
|
+
break;
|
|
146
|
+
await sleep(METADATA_RETRY_DELAYS_MS[i]);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const base = trimSlash(issuer);
|
|
150
|
+
return { tokenEndpoint: `${base}/oauth/token`, revocationEndpoint: `${base}/oauth/revoke` };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* @deprecated A one-time move for a device signed in on an older build, removed when the platform stops
|
|
154
|
+
* holding sessions. The device, with its full `rsds_` device session, takes over the OAuth session the
|
|
155
|
+
* platform holds for its account (`social.scenius.adoptHeldSession`): it gets the tokens and their DPoP key,
|
|
156
|
+
* and its `rsds_` narrows to that key (so from then on it goes only with a proof:
|
|
157
|
+
* {@link OwnSession.deviceFetchHandler}). The account's other devices on older builds sign in again. The
|
|
158
|
+
* token and revocation endpoints come from the issuer's metadata (tried three times; failing that, the
|
|
159
|
+
* atproto defaults, so the tokens are never thrown away). Save the answer at once
|
|
160
|
+
* ({@link OwnSession.signedIn}): the platform deleted its copy, so a lost answer means signing in again.
|
|
161
|
+
* Rejects with `NoHeldSession` (nothing to adopt: already adopted, or never held), `Unavailable` (try
|
|
162
|
+
* again), `WrongAccount` (a session for another DID than `did`), or `InvalidResponse` (no session, no
|
|
163
|
+
* issuer, or an issuer that is not an https origin; checked before anything is kept).
|
|
164
|
+
*/
|
|
165
|
+
export async function adoptHeldSession(o) {
|
|
166
|
+
const fetch = fetchOr(o.fetch);
|
|
167
|
+
const nsid = METHOD.ADOPT_HELD_SESSION;
|
|
168
|
+
const answer = await postPlatform(fetch, o.platformUrl, nsid, {}, { headers: { authorization: `Bearer ${o.deviceSession}` } });
|
|
169
|
+
if (answer.status !== 200)
|
|
170
|
+
throw refusal(nsid, answer);
|
|
171
|
+
const own = ownAnswer(nsid, obj(answer.json, 'ownSession'));
|
|
172
|
+
if (own.sub !== o.did)
|
|
173
|
+
throw new OwnSessionError('WrongAccount', `techne-sdk/session: ${nsid} answered a session for ${own.sub}, not ${o.did}`);
|
|
174
|
+
const key = dpopKeyFromJwk(own.dpopKey);
|
|
175
|
+
const issuer = str(own, 'issuer');
|
|
176
|
+
if (!issuer || !HTTPS_ORIGIN.test(issuer))
|
|
177
|
+
throw new OwnSessionError('InvalidResponse', `techne-sdk/session: ${nsid} named no https issuer origin (${issuer})`);
|
|
178
|
+
return sessionData(own, key, await endpointsKeepingTokens(issuer, fetch), undefined, { deviceSession: o.deviceSession });
|
|
179
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The platform's own-session methods as the device calls them: a JSON POST to the platform's `/xrpc/`, its
|
|
3
|
+
* refusals as {@link OwnSessionError}, and the one DPoP-nonce retry every proof-carrying call shares.
|
|
4
|
+
* Shared by the sign-in steps and the session.
|
|
5
|
+
*/
|
|
6
|
+
/** A refusal from the platform (its XRPC `error` as `code`), or one of the SDK's own:
|
|
7
|
+
* `SessionEnded` (sign in again), `NetworkError` (no answer), `WrongAccount` (the tokens name another DID),
|
|
8
|
+
* `InvalidResponse` (an answer without what the lexicon promises). */
|
|
9
|
+
export declare class OwnSessionError extends Error {
|
|
10
|
+
/** The XRPC error name (`UseDpopNonce`, `InvalidGrant`, `OwnSessionUnavailable`, `RateLimitExceeded`, ...) or the SDK's. */
|
|
11
|
+
readonly code: string;
|
|
12
|
+
/** The HTTP status, when there was an answer. */
|
|
13
|
+
readonly status?: number;
|
|
14
|
+
/** Seconds to wait (`Retry-After`), on `RateLimitExceeded`. */
|
|
15
|
+
readonly retryAfter?: number;
|
|
16
|
+
/** The nonce to sign with, on `UseDpopNonce`. */
|
|
17
|
+
readonly nonce?: string;
|
|
18
|
+
constructor(code: string, message: string, extra?: {
|
|
19
|
+
status?: number;
|
|
20
|
+
retryAfter?: number;
|
|
21
|
+
nonce?: string;
|
|
22
|
+
cause?: unknown;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/** The session is over (the PDS dropped the grant, or it was signed out): sign in again. */
|
|
26
|
+
export declare const SESSION_ENDED = "SessionEnded";
|
|
27
|
+
/** A request got no answer (the network failed). */
|
|
28
|
+
export declare const NETWORK_ERROR = "NetworkError";
|
|
29
|
+
export type Fetch = typeof globalThis.fetch;
|
|
30
|
+
/** A JSON object as it came: every field is read through {@link str} (or checked) before use. */
|
|
31
|
+
export type Json = Readonly<Record<string, unknown>>;
|
|
32
|
+
/** `o[k]` when it is a string. */
|
|
33
|
+
export declare function str(o: Json | null | undefined, k: string): string | undefined;
|
|
34
|
+
/** `o[k]` when it is an object. */
|
|
35
|
+
export declare function obj(o: Json | null | undefined, k: string): Json | undefined;
|
|
36
|
+
/** One answer from the platform. */
|
|
37
|
+
export interface PlatformAnswer {
|
|
38
|
+
status: number;
|
|
39
|
+
json: Json | null;
|
|
40
|
+
headers: Headers;
|
|
41
|
+
}
|
|
42
|
+
/** `fetch`, or `globalThis.fetch` looked up at call time (a test or a polyfill may set it later). */
|
|
43
|
+
export declare const fetchOr: (fetch?: Fetch) => Fetch;
|
|
44
|
+
/** `url` without trailing slashes. */
|
|
45
|
+
export declare const trimSlash: (url: string) => string;
|
|
46
|
+
/** `fn(signal)`, given up after `ms` (no limit when `ms` is undefined): the signal aborts and the promise
|
|
47
|
+
* rejects with `NetworkError` at `ms` even if `fn` ignores the signal, so a caller never waits longer. */
|
|
48
|
+
export declare function withTimeout<T>(ms: number | undefined, fn: (signal?: AbortSignal) => Promise<T>): Promise<T>;
|
|
49
|
+
/** `<platformUrl>/xrpc/<nsid>` with `body` as JSON. A fetch that throws (or takes longer than `timeoutMs`)
|
|
50
|
+
* throws: no answer. */
|
|
51
|
+
export declare function postPlatform(fetch: Fetch, platformUrl: string, nsid: string, body: unknown, { headers, timeoutMs }?: {
|
|
52
|
+
headers?: Record<string, string>;
|
|
53
|
+
timeoutMs?: number;
|
|
54
|
+
}): Promise<PlatformAnswer>;
|
|
55
|
+
/** Seconds in the answer's `Retry-After`, when it names some. */
|
|
56
|
+
export declare function retryAfterOf(answer: PlatformAnswer): number | undefined;
|
|
57
|
+
/** The refusal in `answer`. */
|
|
58
|
+
export declare function refusal(nsid: string, answer: PlatformAnswer): OwnSessionError;
|
|
59
|
+
/** The latest DPoP nonce an answer carries (`dpopNonce` in the body or its `ownSession`, or the `DPoP-Nonce` header). */
|
|
60
|
+
export declare function nonceIn(answer: PlatformAnswer): string | undefined;
|
|
61
|
+
/**
|
|
62
|
+
* `send(nonce)` until it answers 200: a `UseDpopNonce` refusal naming a new nonce is signed again with it, up
|
|
63
|
+
* to `retries` times (the door's code step and its token step may each ask once). Answers the 200 and the
|
|
64
|
+
* latest nonce; any other refusal is thrown, carrying the latest nonce in `nonce` when it was `UseDpopNonce`.
|
|
65
|
+
*/
|
|
66
|
+
export declare function withNonceRetry(nsid: string, nonce: string | undefined, send: (nonce: string | undefined) => Promise<PlatformAnswer>, retries?: number): Promise<{
|
|
67
|
+
answer: PlatformAnswer;
|
|
68
|
+
nonce?: string;
|
|
69
|
+
}>;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The platform's own-session methods as the device calls them: a JSON POST to the platform's `/xrpc/`, its
|
|
3
|
+
* refusals as {@link OwnSessionError}, and the one DPoP-nonce retry every proof-carrying call shares.
|
|
4
|
+
* Shared by the sign-in steps and the session.
|
|
5
|
+
*/
|
|
6
|
+
/** A refusal from the platform (its XRPC `error` as `code`), or one of the SDK's own:
|
|
7
|
+
* `SessionEnded` (sign in again), `NetworkError` (no answer), `WrongAccount` (the tokens name another DID),
|
|
8
|
+
* `InvalidResponse` (an answer without what the lexicon promises). */
|
|
9
|
+
export class OwnSessionError extends Error {
|
|
10
|
+
/** The XRPC error name (`UseDpopNonce`, `InvalidGrant`, `OwnSessionUnavailable`, `RateLimitExceeded`, ...) or the SDK's. */
|
|
11
|
+
code;
|
|
12
|
+
/** The HTTP status, when there was an answer. */
|
|
13
|
+
status;
|
|
14
|
+
/** Seconds to wait (`Retry-After`), on `RateLimitExceeded`. */
|
|
15
|
+
retryAfter;
|
|
16
|
+
/** The nonce to sign with, on `UseDpopNonce`. */
|
|
17
|
+
nonce;
|
|
18
|
+
constructor(code, message, extra = {}) {
|
|
19
|
+
super(message, extra.cause === undefined ? undefined : { cause: extra.cause });
|
|
20
|
+
this.name = 'OwnSessionError';
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.status = extra.status;
|
|
23
|
+
this.retryAfter = extra.retryAfter;
|
|
24
|
+
this.nonce = extra.nonce;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** The session is over (the PDS dropped the grant, or it was signed out): sign in again. */
|
|
28
|
+
export const SESSION_ENDED = 'SessionEnded';
|
|
29
|
+
/** A request got no answer (the network failed). */
|
|
30
|
+
export const NETWORK_ERROR = 'NetworkError';
|
|
31
|
+
/** `o[k]` when it is a string. */
|
|
32
|
+
export function str(o, k) {
|
|
33
|
+
const v = o?.[k];
|
|
34
|
+
return typeof v === 'string' ? v : undefined;
|
|
35
|
+
}
|
|
36
|
+
/** `o[k]` when it is an object. */
|
|
37
|
+
export function obj(o, k) {
|
|
38
|
+
const v = o?.[k];
|
|
39
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
|
|
40
|
+
}
|
|
41
|
+
/** `fetch`, or `globalThis.fetch` looked up at call time (a test or a polyfill may set it later). */
|
|
42
|
+
export const fetchOr = (fetch) => (input, init) => (fetch ?? globalThis.fetch)(input, init);
|
|
43
|
+
/** `url` without trailing slashes. */
|
|
44
|
+
export const trimSlash = (url) => url.replace(/\/+$/, '');
|
|
45
|
+
/** `fn(signal)`, given up after `ms` (no limit when `ms` is undefined): the signal aborts and the promise
|
|
46
|
+
* rejects with `NetworkError` at `ms` even if `fn` ignores the signal, so a caller never waits longer. */
|
|
47
|
+
export async function withTimeout(ms, fn) {
|
|
48
|
+
if (ms === undefined)
|
|
49
|
+
return fn(undefined);
|
|
50
|
+
const abort = new AbortController();
|
|
51
|
+
let timer;
|
|
52
|
+
const late = new Promise((_, reject) => {
|
|
53
|
+
timer = setTimeout(() => {
|
|
54
|
+
abort.abort();
|
|
55
|
+
reject(new OwnSessionError(NETWORK_ERROR, `techne-sdk/session: no answer in ${ms} ms`));
|
|
56
|
+
}, Math.max(0, ms));
|
|
57
|
+
});
|
|
58
|
+
try {
|
|
59
|
+
return await Promise.race([fn(abort.signal), late]);
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** `<platformUrl>/xrpc/<nsid>` with `body` as JSON. A fetch that throws (or takes longer than `timeoutMs`)
|
|
66
|
+
* throws: no answer. */
|
|
67
|
+
export async function postPlatform(fetch, platformUrl, nsid, body, { headers = {}, timeoutMs } = {}) {
|
|
68
|
+
return withTimeout(timeoutMs, async (signal) => {
|
|
69
|
+
const res = await fetch(`${trimSlash(platformUrl)}/xrpc/${nsid}`, {
|
|
70
|
+
method: 'POST',
|
|
71
|
+
headers: { accept: 'application/json', 'content-type': 'application/json', ...headers },
|
|
72
|
+
body: JSON.stringify(body ?? {}),
|
|
73
|
+
signal,
|
|
74
|
+
});
|
|
75
|
+
const text = await res.text();
|
|
76
|
+
let json = null;
|
|
77
|
+
try {
|
|
78
|
+
const parsed = text ? JSON.parse(text) : null;
|
|
79
|
+
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed))
|
|
80
|
+
json = parsed;
|
|
81
|
+
}
|
|
82
|
+
catch { }
|
|
83
|
+
return { status: res.status, json, headers: res.headers };
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
/** Seconds in the answer's `Retry-After`, when it names some. */
|
|
87
|
+
export function retryAfterOf(answer) {
|
|
88
|
+
const s = Number(answer.headers.get('retry-after'));
|
|
89
|
+
return Number.isFinite(s) && s > 0 ? s : undefined;
|
|
90
|
+
}
|
|
91
|
+
/** The refusal in `answer`. */
|
|
92
|
+
export function refusal(nsid, answer) {
|
|
93
|
+
const code = str(answer.json, 'error') ?? `Http${answer.status}`;
|
|
94
|
+
const nonce = str(answer.json, 'nonce') ?? answer.headers.get('dpop-nonce') ?? undefined;
|
|
95
|
+
return new OwnSessionError(code, `techne-sdk/session: ${nsid}: ${str(answer.json, 'message') ?? `answered ${answer.status}`}`, {
|
|
96
|
+
status: answer.status,
|
|
97
|
+
retryAfter: retryAfterOf(answer),
|
|
98
|
+
nonce: code === 'UseDpopNonce' ? nonce : undefined,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** The latest DPoP nonce an answer carries (`dpopNonce` in the body or its `ownSession`, or the `DPoP-Nonce` header). */
|
|
102
|
+
export function nonceIn(answer) {
|
|
103
|
+
return str(answer.json, 'dpopNonce') ?? str(obj(answer.json, 'ownSession'), 'dpopNonce') ?? answer.headers.get('dpop-nonce') ?? undefined;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* `send(nonce)` until it answers 200: a `UseDpopNonce` refusal naming a new nonce is signed again with it, up
|
|
107
|
+
* to `retries` times (the door's code step and its token step may each ask once). Answers the 200 and the
|
|
108
|
+
* latest nonce; any other refusal is thrown, carrying the latest nonce in `nonce` when it was `UseDpopNonce`.
|
|
109
|
+
*/
|
|
110
|
+
export async function withNonceRetry(nsid, nonce, send, retries = 1) {
|
|
111
|
+
for (let attempt = 0;; attempt++) {
|
|
112
|
+
const answer = await send(nonce);
|
|
113
|
+
if (answer.status === 200)
|
|
114
|
+
return { answer, nonce: nonceIn(answer) ?? nonce };
|
|
115
|
+
const err = refusal(nsid, answer);
|
|
116
|
+
if (err.code !== 'UseDpopNonce' || !err.nonce || err.nonce === nonce || attempt >= retries)
|
|
117
|
+
throw err;
|
|
118
|
+
nonce = err.nonce;
|
|
119
|
+
}
|
|
120
|
+
}
|