techne-sdk 0.7.0 → 0.9.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.
@@ -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
+ }