techne-sdk 0.7.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.
@@ -0,0 +1,364 @@
1
+ import { METHOD } from '../generated/nsid.js';
2
+ import { dpopKeyFromJwk, dpopProof } from './dpop.js';
3
+ import { NETWORK_ERROR, OwnSessionError, SESSION_ENDED, fetchOr, nonceIn, postPlatform, retryAfterOf, str, trimSlash, withNonceRetry, withTimeout, } from './relay.js';
4
+ /** How long the platform keeps a refresh's answer for the same token and key. */
5
+ export const PLATFORM_ANSWER_WINDOW_MS = 60_000;
6
+ /** How long after the first send a refresh that got no answer may be sent again. */
7
+ export const LOST_ANSWER_WINDOW_MS = 50_000;
8
+ /** Every send is given up this long before {@link PLATFORM_ANSWER_WINDOW_MS} ends (clock skew, transit). */
9
+ export const SEND_MARGIN_MS = 5_000;
10
+ /** The waits between those sends, and how long one send may take at most. */
11
+ const LOST_ANSWER_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000];
12
+ const REFRESH_TIMEOUT_MS = 15_000;
13
+ /** How long sign-out waits for each of its calls (revoke, signOutDevice). */
14
+ export const SIGN_OUT_TIMEOUT_MS = 10_000;
15
+ /** An early refresh holds the call only when the access token has less than this to live. */
16
+ export const STILL_VALID_MS = 30_000;
17
+ /** Answers that say the refresh may not have finished: send it again. */
18
+ const NO_ANSWER_YET = new Set([429, 502, 503, 504]);
19
+ const REFRESH_EARLY_MS = 5 * 60_000;
20
+ const ORIGIN = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]+/i;
21
+ /** The origin of `url` (`scheme://host[:port]`), lower-cased: what a DPoP nonce is kept under. */
22
+ export function nonceKey(url) {
23
+ return (url.match(ORIGIN)?.[0] ?? url).toLowerCase();
24
+ }
25
+ /** A body that can be sent twice (not a stream). */
26
+ function replayable(body) {
27
+ return body == null || typeof body.getReader !== 'function';
28
+ }
29
+ /** The `error` in a `WWW-Authenticate: DPoP error="..."` answer. */
30
+ function wwwError(res) {
31
+ return res.headers.get('www-authenticate')?.match(/error="([^"]+)"/)?.[1];
32
+ }
33
+ /** The proof headers for a device-credential request: `Authorization: Bearer <rsds_>` and a `DPoP` proof by
34
+ * `key` for `method` `url` with `ath` over the credential (no server nonce is asked for). */
35
+ export function deviceProofHeaders(key, deviceSession, method, url) {
36
+ return { authorization: `Bearer ${deviceSession}`, dpop: dpopProof(key, { htm: method, htu: url, token: deviceSession }) };
37
+ }
38
+ /** The same token set (access and refresh token). */
39
+ function sameSet(a, b) {
40
+ return a.accessToken === b.accessToken && a.refreshToken === b.refreshToken;
41
+ }
42
+ /** The device's own session (module doc). Make one with {@link OwnSession.restore} or {@link OwnSession.signedIn}.
43
+ * The tokens and the key are in `#private` fields, so logging the session prints neither. */
44
+ export class OwnSession {
45
+ #data;
46
+ #key;
47
+ #opts;
48
+ #platformUrl;
49
+ #fetch;
50
+ #lock;
51
+ #nonces = new Map();
52
+ #refreshing;
53
+ #signingOut;
54
+ #endedWith;
55
+ /** Signing out: no new refresh starts. */
56
+ #closing = false;
57
+ /** The set the current one was rotated from, while the current one is not in the store (its save
58
+ * failed); undefined when the store holds the current set. */
59
+ #unsavedFrom;
60
+ constructor(data, opts) {
61
+ this.#key = dpopKeyFromJwk(data.dpopKey);
62
+ this.#data = data;
63
+ this.#opts = opts;
64
+ this.#platformUrl = trimSlash(opts.platformUrl);
65
+ this.#fetch = fetchOr(opts.fetch);
66
+ this.#lock = opts.lock ?? ((fn) => fn());
67
+ this.#noteNonce(data.tokenEndpoint, data.dpopNonce);
68
+ }
69
+ /** The session in the store, or null when nobody is signed in there. */
70
+ static async restore(opts) {
71
+ const data = await opts.store.get();
72
+ return data ? new OwnSession(data, opts) : null;
73
+ }
74
+ /** A session just signed in (`finishPhoneSignIn`, `adoptHeldSession`): saved to the store first. */
75
+ static async signedIn(data, opts) {
76
+ const session = new OwnSession(data, opts);
77
+ await opts.store.set(data);
78
+ return session;
79
+ }
80
+ /** The signed-in person's DID. */
81
+ get did() {
82
+ return this.#data.did;
83
+ }
84
+ /** The device credential's public handle, when there is one. */
85
+ get deviceId() {
86
+ return this.#data.deviceId;
87
+ }
88
+ /** When the access token expires (ms since the epoch), when known. */
89
+ get expiresAt() {
90
+ return this.#data.expiresAt;
91
+ }
92
+ #now() {
93
+ return (this.#opts.now ?? Date.now)();
94
+ }
95
+ #sleep(ms) {
96
+ return this.#opts.sleep ? this.#opts.sleep(ms) : new Promise((r) => setTimeout(r, ms));
97
+ }
98
+ #noteNonce(url, nonce) {
99
+ if (nonce)
100
+ this.#nonces.set(nonceKey(url), nonce);
101
+ }
102
+ #ensureLive() {
103
+ if (this.#endedWith)
104
+ throw this.#endedWith;
105
+ }
106
+ /** The stored set is this session's: the same DID and the same DPoP key (the same P-256 public point). */
107
+ #ours(stored) {
108
+ const k = stored?.dpopKey;
109
+ return !!stored && stored.did === this.#data.did && k?.x === this.#key.x && k?.y === this.#key.y;
110
+ }
111
+ /**
112
+ * A request to the person's PDS with the session: `url` is a path (`/xrpc/...`, how an XRPC client calls
113
+ * a fetch handler) on the PDS, or a full URL. `connect` calls this.
114
+ */
115
+ fetchHandler = async (url, init) => {
116
+ const full = url.startsWith('/') ? `${nonceKey(this.#data.pds)}${url}` : url;
117
+ const method = (init.method ?? 'GET').toUpperCase();
118
+ const send = async (token) => {
119
+ const headers = new Headers(init.headers);
120
+ headers.set('authorization', `DPoP ${token}`);
121
+ headers.set('dpop', dpopProof(this.#key, { htm: method, htu: full, nonce: this.#nonces.get(nonceKey(full)), token }));
122
+ const res = await this.#fetch(full, { ...init, headers });
123
+ this.#noteNonce(full, res.headers.get('dpop-nonce'));
124
+ return res;
125
+ };
126
+ const token = await this.accessToken();
127
+ let res = await send(token);
128
+ const canResend = replayable(init.body);
129
+ if (canResend && res.status === 401 && wwwError(res) === 'use_dpop_nonce' && res.headers.get('dpop-nonce'))
130
+ res = await send(token);
131
+ if (canResend && res.status === 401 && wwwError(res) === 'invalid_token' && this.#data.refreshToken) {
132
+ await this.refresh(token);
133
+ res = await send(this.#data.accessToken);
134
+ }
135
+ return res;
136
+ };
137
+ /** The access token. When it has less than `refreshEarlyMs` to live a refresh starts; the call waits for
138
+ * it only when the token has less than {@link STILL_VALID_MS} left. A refresh that fails while the token
139
+ * still lives does not fail the call (the next one tries again); one that ends the session does. */
140
+ async accessToken() {
141
+ this.#ensureLive();
142
+ const { expiresAt, refreshToken, accessToken } = this.#data;
143
+ if (expiresAt !== undefined && refreshToken && expiresAt - this.#now() < (this.#opts.refreshEarlyMs ?? REFRESH_EARLY_MS)) {
144
+ const refreshing = this.refresh(accessToken);
145
+ if (expiresAt - this.#now() > STILL_VALID_MS) {
146
+ refreshing.catch(() => { });
147
+ return accessToken;
148
+ }
149
+ try {
150
+ await refreshing;
151
+ }
152
+ catch (e) {
153
+ if (e instanceof OwnSessionError && e.code === SESSION_ENDED)
154
+ throw e;
155
+ if (expiresAt <= this.#now())
156
+ throw e;
157
+ }
158
+ }
159
+ return this.#data.accessToken;
160
+ }
161
+ /**
162
+ * Refresh now (one at a time; module doc). With `seen`, the access token the caller found stale: when the
163
+ * store already holds another (another process refreshed), that one is taken and nothing is sent.
164
+ * Rejects with `SessionEnded` when the session is over (the store is cleared and `onEnded` called; when
165
+ * the store holds another key's set, it is left alone), `NetworkError` when no answer came inside the
166
+ * lost-answer window (the session is kept), or the platform's refusal.
167
+ */
168
+ async refresh(seen) {
169
+ this.#ensureLive();
170
+ if (this.#closing)
171
+ throw new OwnSessionError(SESSION_ENDED, 'techne-sdk/session: signing out');
172
+ const token = seen ?? this.#data.accessToken;
173
+ this.#refreshing ??= this.#lock(() => this.#refreshLocked(token)).finally(() => {
174
+ this.#refreshing = undefined;
175
+ });
176
+ return this.#refreshing;
177
+ }
178
+ async #refreshLocked(seen) {
179
+ const stored = await this.#opts.store.get();
180
+ // Nobody, another account, or this account under another key (signed out and in again elsewhere): the
181
+ // store is not this session's to change, and this key must not sign for that set.
182
+ if (!this.#ours(stored))
183
+ throw this.#end(new OwnSessionError(SESSION_ENDED, 'techne-sdk/session: signed out in another process'), false);
184
+ const from = this.#unsavedFrom;
185
+ if (from && sameSet(stored, from)) {
186
+ // The last rotated set never reached the store, which still holds the set it came from: save it first.
187
+ await this.#opts.store.set(this.#data);
188
+ }
189
+ else if (!sameSet(stored, this.#data)) {
190
+ // Another process refreshed while this one waited (or wrote over a set this one could not save): take
191
+ // its set, and send nothing.
192
+ this.#unsavedFrom = undefined;
193
+ this.#data = stored;
194
+ this.#noteNonce(stored.tokenEndpoint, stored.dpopNonce);
195
+ return;
196
+ }
197
+ // The store holds the current set now.
198
+ this.#unsavedFrom = undefined;
199
+ // A refresh in this process already replaced the token the caller found stale.
200
+ if (this.#data.accessToken !== seen)
201
+ return;
202
+ const d = this.#data;
203
+ if (!d.refreshToken)
204
+ throw this.#end(new OwnSessionError(SESSION_ENDED, 'techne-sdk/session: the session has no refresh token'));
205
+ const refreshToken = d.refreshToken;
206
+ const started = this.#now();
207
+ let answer;
208
+ try {
209
+ ;
210
+ ({ answer } = await withNonceRetry(METHOD.REFRESH_OWN_SESSION, this.#nonces.get(nonceKey(d.tokenEndpoint)), (nonce) => this.#resendUntilAnswered(started, () => ({ refreshToken, dpop: dpopProof(this.#key, { htm: 'POST', htu: d.tokenEndpoint, nonce }) }))));
211
+ }
212
+ catch (e) {
213
+ if (e instanceof OwnSessionError && e.code === 'InvalidGrant')
214
+ throw this.#end(new OwnSessionError(SESSION_ENDED, e.message, { status: e.status, cause: e }));
215
+ throw e;
216
+ }
217
+ // From here the old refresh token is spent at the PDS: an answer that cannot be used ends the session.
218
+ const t = answer.json;
219
+ const accessToken = str(t, 'access_token');
220
+ if (!accessToken || str(t, 'sub') !== d.did) {
221
+ const cause = new OwnSessionError(accessToken ? 'WrongAccount' : 'InvalidResponse', `techne-sdk/session: refreshOwnSession answered ${accessToken ? `tokens for ${str(t, 'sub')}, not ${d.did}` : 'no access_token'}`);
222
+ throw this.#end(new OwnSessionError(SESSION_ENDED, cause.message, { cause }));
223
+ }
224
+ const expiresIn = t?.expires_in;
225
+ const next = {
226
+ ...d,
227
+ accessToken,
228
+ refreshToken: str(t, 'refresh_token') ?? d.refreshToken,
229
+ expiresAt: typeof expiresIn === 'number' ? this.#now() + expiresIn * 1000 : undefined,
230
+ scope: str(t, 'scope') ?? d.scope,
231
+ dpopNonce: this.#nonces.get(nonceKey(d.tokenEndpoint)) ?? d.dpopNonce,
232
+ };
233
+ // Keep the new set in memory even if the store fails (the old token is spent), and save it before the
234
+ // access token is used.
235
+ this.#data = next;
236
+ try {
237
+ await this.#opts.store.set(next);
238
+ }
239
+ catch (e) {
240
+ this.#unsavedFrom = d;
241
+ throw e;
242
+ }
243
+ }
244
+ /** One refresh request (`body()` makes it, with a fresh proof each time), sent again while no answer comes
245
+ * (module doc): a send starts up to {@link LOST_ANSWER_WINDOW_MS} after `started`, and each is given up
246
+ * {@link SEND_MARGIN_MS} before the platform's {@link PLATFORM_ANSWER_WINDOW_MS} ends. */
247
+ async #resendUntilAnswered(started, body) {
248
+ const deadline = started + PLATFORM_ANSWER_WINDOW_MS - SEND_MARGIN_MS;
249
+ for (let lost = 0;; lost++) {
250
+ let got;
251
+ let failure;
252
+ const left = deadline - this.#now();
253
+ if (left <= 0)
254
+ throw new OwnSessionError(NETWORK_ERROR, 'techne-sdk/session: refreshOwnSession got no answer in the window');
255
+ try {
256
+ got = await postPlatform(this.#fetch, this.#platformUrl, METHOD.REFRESH_OWN_SESSION, body(), { timeoutMs: Math.min(REFRESH_TIMEOUT_MS, left) });
257
+ this.#noteNonce(this.#data.tokenEndpoint, nonceIn(got));
258
+ }
259
+ catch (e) {
260
+ failure = e;
261
+ }
262
+ if (got && !NO_ANSWER_YET.has(got.status))
263
+ return got;
264
+ const wait = Math.max(LOST_ANSWER_DELAYS_MS[Math.min(lost, LOST_ANSWER_DELAYS_MS.length - 1)], ((got ? retryAfterOf(got) : undefined) ?? 0) * 1000);
265
+ if (this.#now() + wait - started > LOST_ANSWER_WINDOW_MS) {
266
+ if (got)
267
+ return got;
268
+ throw new OwnSessionError(NETWORK_ERROR, 'techne-sdk/session: refreshOwnSession got no answer', { cause: failure });
269
+ }
270
+ await this.#sleep(wait);
271
+ }
272
+ }
273
+ /** Ends the session here: clears the store (unless `clear` is false), calls `onEnded`. */
274
+ #end(error, clear = true) {
275
+ if (!this.#endedWith) {
276
+ this.#endedWith = error;
277
+ if (clear)
278
+ void this.#opts.store.delete().catch(() => { });
279
+ try {
280
+ this.#opts.onEnded?.(error);
281
+ }
282
+ catch { }
283
+ }
284
+ return this.#endedWith;
285
+ }
286
+ /**
287
+ * Sign out: wait for a refresh in flight (so the newest refresh token is the one revoked), revoke the grant
288
+ * at the PDS (`revokeOwnSession` with the refresh token, so the whole grant goes), sign the device
289
+ * credential out (`signOutDevice`), clear the store. Each call is given up after
290
+ * {@link SIGN_OUT_TIMEOUT_MS}. The store is cleared and the session ends whatever the network says; the
291
+ * answer says what the server took. When the store holds no set of this session's (signed out, or signed
292
+ * in under another key, in another process), nothing is sent and the store is left alone; when the store
293
+ * cannot be read, this session's own set is revoked and the store is left alone. A second call answers
294
+ * the first one's result.
295
+ */
296
+ signOut() {
297
+ this.#signingOut ??= this.#signOut();
298
+ return this.#signingOut;
299
+ }
300
+ async #signOut() {
301
+ this.#closing = true;
302
+ await this.#refreshing?.catch(() => { });
303
+ try {
304
+ return await this.#lock(async () => {
305
+ // undefined: the store could not be read (this session's own set is revoked; the store is not cleared,
306
+ // as it may hold another key's set).
307
+ const stored = await this.#opts.store.get().catch(() => undefined);
308
+ if (stored !== undefined && !this.#ours(stored))
309
+ return { revoked: false, deviceSignedOut: false };
310
+ // The newest set: this session's when the store still holds the set its unsaved one came from.
311
+ const from = this.#unsavedFrom;
312
+ const d = stored === undefined || (from && sameSet(stored, from)) ? this.#data : stored;
313
+ try {
314
+ const revoked = await this.#revoke(d).catch(() => false);
315
+ let deviceSignedOut = false;
316
+ if (d.deviceSession) {
317
+ const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' };
318
+ deviceSignedOut = await withTimeout(SIGN_OUT_TIMEOUT_MS, (signal) => this.#deviceFetch(d, `/xrpc/${METHOD.SIGN_OUT_DEVICE}`, { ...init, signal })).then((r) => r.ok, () => false);
319
+ }
320
+ return { revoked, deviceSignedOut };
321
+ }
322
+ finally {
323
+ if (stored !== undefined)
324
+ await this.#opts.store.delete().catch(() => { });
325
+ }
326
+ });
327
+ }
328
+ finally {
329
+ this.#end(new OwnSessionError(SESSION_ENDED, 'techne-sdk/session: signed out'), false);
330
+ }
331
+ }
332
+ async #revoke(d) {
333
+ const { answer } = await withNonceRetry(METHOD.REVOKE_OWN_SESSION, this.#nonces.get(nonceKey(d.revocationEndpoint)), async (nonce) => {
334
+ const got = await postPlatform(this.#fetch, this.#platformUrl, METHOD.REVOKE_OWN_SESSION, { token: d.refreshToken ?? d.accessToken, dpop: dpopProof(this.#key, { htm: 'POST', htu: d.revocationEndpoint, nonce }) }, { timeoutMs: SIGN_OUT_TIMEOUT_MS });
335
+ this.#noteNonce(d.revocationEndpoint, nonceIn(got));
336
+ return got;
337
+ });
338
+ return answer.json?.ok === true;
339
+ }
340
+ /** The headers for one device-credential request (`Authorization: Bearer <rsds_>` and its `DPoP` proof):
341
+ * for the change stream, `deviceHeaders('GET', 'wss://<platform>/xrpc/_stream/changes')` on the
342
+ * WebSocket. Each call makes a new proof; use it for one request. Null when the session has no device
343
+ * credential. */
344
+ deviceHeaders(method, url) {
345
+ this.#ensureLive();
346
+ return this.#data.deviceSession ? deviceProofHeaders(this.#key, this.#data.deviceSession, method, url) : null;
347
+ }
348
+ async #deviceFetch(d, url, init) {
349
+ if (!d.deviceSession)
350
+ throw new OwnSessionError('NoDeviceSession', 'techne-sdk/session: this session has no device credential');
351
+ const full = url.startsWith('/') ? `${this.#platformUrl}${url}` : url;
352
+ const headers = new Headers(init.headers);
353
+ for (const [k, v] of Object.entries(deviceProofHeaders(this.#key, d.deviceSession, init.method ?? 'GET', full)))
354
+ headers.set(k, v);
355
+ return this.#fetch(full, { ...init, headers });
356
+ }
357
+ /** A fetch handler to the platform with the device credential and a fresh proof per request: for
358
+ * registerDevicePush, listDeviceSessions and signOutDevice (`new AtpBaseClient(session.deviceFetchHandler)`).
359
+ * `url` is a path on the platform (`/xrpc/...`) or a full URL. */
360
+ deviceFetchHandler = async (url, init) => {
361
+ this.#ensureLive();
362
+ return this.#deviceFetch(this.#data, url, init);
363
+ };
364
+ }
@@ -0,0 +1,79 @@
1
+ import { type DpopKey } from './dpop.js';
2
+ import type { OwnSessionData } from './own-session.js';
3
+ import { type Fetch } from './relay.js';
4
+ /** The endpoints the door's proofs name (`startPhoneSignup` with `ownSession:{}`). */
5
+ export interface OwnSessionEndpoints {
6
+ issuer?: string;
7
+ /** The `htu` of the start and code-step proofs. */
8
+ challengeEndpoint: string;
9
+ /** The `htu` of the token and refresh proofs. */
10
+ tokenEndpoint: string;
11
+ /** The `htu` of revoke proofs. */
12
+ revocationEndpoint: string;
13
+ }
14
+ /** A sign-in between its two steps: plain JSON the app keeps until the code is entered. `dpopKey` and
15
+ * `codeVerifier` are secrets (memory or secure storage, never a log). */
16
+ export interface PendingPhoneSignIn {
17
+ phone: string;
18
+ dpopKey: DpopKey;
19
+ codeVerifier: string;
20
+ endpoints: OwnSessionEndpoints;
21
+ /** The latest DPoP nonce the door gave. */
22
+ dpopNonce?: string;
23
+ }
24
+ /** What the sign-in steps take. */
25
+ export interface PhoneSignInOptions {
26
+ /** The platform's origin (`https://...`). */
27
+ platformUrl: string;
28
+ /** `globalThis.fetch` by default. */
29
+ fetch?: Fetch;
30
+ }
31
+ /** {@link finishPhoneSignIn}'s options. */
32
+ export interface FinishPhoneSignInOptions extends PhoneSignInOptions {
33
+ /** Shown in the person's device list. */
34
+ device?: {
35
+ platform?: string;
36
+ deviceName?: string;
37
+ };
38
+ }
39
+ /**
40
+ * Step 1: ask the door for its endpoints, make the DPoP key and the PKCE pair, and start the sign-in (the
41
+ * platform texts the code). Rejects with the platform's refusal as an {@link OwnSessionError}:
42
+ * `OwnSessionUnavailable` (sign in the old way: the door is off, or a review number), `RateLimitExceeded`
43
+ * (`retryAfter`), `InvalidRequest`.
44
+ */
45
+ export declare function startPhoneSignIn(o: PhoneSignInOptions & {
46
+ phone: string;
47
+ }): Promise<PendingPhoneSignIn>;
48
+ /**
49
+ * Step 2: finish with the code the person entered. The three proofs (code step, token, and the revoke the
50
+ * platform uses only if a check refuses the sign-in) are signed with the latest nonce; a `UseDpopNonce`
51
+ * answer with a new nonce is signed again and sent with the same code (the platform has not spent it), up to
52
+ * twice (the code step and the token step may each ask). `pending.dpopNonce` keeps the latest nonce, so a
53
+ * retry by the app signs with it. Answers the session to save ({@link OwnSession.signedIn}) and whether the
54
+ * number's account was just made. Rejects with the platform's refusal: `InvalidRequest` (wrong code: try
55
+ * again), `CodeExpired` (start again), `NewCodeSent`, `MethodFrozen`, `OwnSessionUnavailable`,
56
+ * `RateLimitExceeded`, `Unavailable`.
57
+ */
58
+ export declare function finishPhoneSignIn(pending: PendingPhoneSignIn, code: string, o: FinishPhoneSignInOptions): Promise<{
59
+ session: OwnSessionData;
60
+ created: boolean;
61
+ }>;
62
+ /**
63
+ * @deprecated A one-time move for a device signed in on an older build, removed when the platform stops
64
+ * holding sessions. The device, with its full `rsds_` device session, takes over the OAuth session the
65
+ * platform holds for its account (`social.scenius.adoptHeldSession`): it gets the tokens and their DPoP key,
66
+ * and its `rsds_` narrows to that key (so from then on it goes only with a proof:
67
+ * {@link OwnSession.deviceFetchHandler}). The account's other devices on older builds sign in again. The
68
+ * token and revocation endpoints come from the issuer's metadata (tried three times; failing that, the
69
+ * atproto defaults, so the tokens are never thrown away). Save the answer at once
70
+ * ({@link OwnSession.signedIn}): the platform deleted its copy, so a lost answer means signing in again.
71
+ * Rejects with `NoHeldSession` (nothing to adopt: already adopted, or never held), `Unavailable` (try
72
+ * again), `WrongAccount` (a session for another DID than `did`), or `InvalidResponse` (no session, no
73
+ * issuer, or an issuer that is not an https origin; checked before anything is kept).
74
+ */
75
+ export declare function adoptHeldSession(o: PhoneSignInOptions & {
76
+ deviceSession: string;
77
+ /** The DID the device is signed in as: a session for another account is refused (`WrongAccount`). */
78
+ did: string;
79
+ }): Promise<OwnSessionData>;
@@ -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
+ }