techne-sdk 0.10.0 → 0.11.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 CHANGED
@@ -3,6 +3,28 @@
3
3
  `techne-sdk` on npm and the `techne-sdk` crate share a version. Each entry names what changes for an app or
4
4
  a crate user.
5
5
 
6
+ ## 0.11.0 (2026-11-22)
7
+
8
+ npm 0.11.0 changes `techne-sdk/session` only; no export is removed or renamed. Nothing under `crates/` changed
9
+ since 0.10.0, so the crate stays 0.10.0.
10
+
11
+ - **`adoptHeldSession` does not lose the session it takes over** (deprecated, as before). New option `store`:
12
+ the checked session is saved there before the issuer's metadata is fetched (with the atproto endpoints
13
+ `/oauth/token` and `/oauth/revoke`, and only when the store holds no session), so an app killed during that
14
+ fetch restores it on its next launch; when the metadata names other endpoints the saved set is corrected
15
+ while the store still holds it. With `store`, open the session with `OwnSession.restore` (the store may hold
16
+ a newer set by then: a refresh or a sign-in made meanwhile), not `signedIn`. A request that got no answer (the network failed, a send took over 15 s, a
17
+ gateway answered 502/504) is sent again, the same request, for up to 50 s, each send given up 5 s before the
18
+ platform's 60 s answer window; a platform that keeps the adopt answer for the same device credential gives it
19
+ again. No answer in that window rejects `NetworkError` (before, a send had no time limit). A 503, a 429 or a
20
+ refusal is not sent again.
21
+ - **A session that ends signs its device credential out.** When the PDS refuses a refresh (the grant was
22
+ revoked, for example on the account page), the refresh answers tokens the device cannot use, or there is no
23
+ refresh token, the session now also calls `signOutDevice` with its device proof (best effort, not awaited),
24
+ so the platform drops the phone's push token then instead of when the device session expires. A session
25
+ that ends because the store holds another key's set (signed out and in again in another process) does not,
26
+ and neither clears nor signs out while the store holds a set another process rotated meanwhile.
27
+
6
28
  ## 0.10.0 (2026-11-21)
7
29
 
8
30
  npm 0.10.0 and crate 0.10.0 are built from the same commit. Additions only; no export is removed or renamed.
package/README.md CHANGED
@@ -141,7 +141,8 @@ const techne = connect(session, TECHNE_PLATFORM_DID)
141
141
  to 50 seconds, which the platform answers from its 60-second window (each send is given up 5 seconds before
142
142
  that window closes). A store that holds a set under another DPoP key (the person signed out and in again in
143
143
  another process) ends this session without touching the store. `onEnded` is called when the session is
144
- over (`SessionEnded`: sign in again).
144
+ over (`SessionEnded`: sign in again); a session that ends that way (say the grant was revoked on the account
145
+ page) also signs its device credential out, best effort, so the platform drops the phone's push token.
145
146
  - **The device credential** (push registration, the device list, `signOutDevice`, the change stream) goes only
146
147
  with a proof of the session's key: `new AtpBaseClient(session.deviceFetchHandler)` for the calls,
147
148
  `session.deviceHeaders('GET', wssUrl)` for the WebSocket's headers.
@@ -149,9 +150,15 @@ const techne = connect(session, TECHNE_PLATFORM_DID)
149
150
  seconds) and clears the store, whatever the network says; when the store holds another key's set it leaves
150
151
  that set and the store alone.
151
152
  - **Moving an older install** (deprecated, removed when the platform stops holding sessions):
152
- `adoptHeldSession({ platformUrl, deviceSession, did })` takes over the session the platform holds for a
153
- device signed in with a full `rsds_` credential (`WrongAccount` when it is not `did`'s); save its answer with
154
- `OwnSession.signedIn` at once. The tokens are kept even when the issuer's metadata does not answer.
153
+ `adoptHeldSession({ platformUrl, deviceSession, did, store })` takes over the session the platform holds for
154
+ a device signed in with a full `rsds_` credential (`WrongAccount` when it is not `did`'s); save its answer
155
+ with `OwnSession.signedIn` at once. The tokens are kept even when the issuer's metadata does not answer. With
156
+ `store`, the session is saved there (only when the store is empty) before the issuer's metadata is fetched,
157
+ so an app killed meanwhile restores it on its next launch; then open it with `OwnSession.restore`, not
158
+ `signedIn` (the store may hold a newer set by then), and `signedIn` the answer only when `restore` finds
159
+ nothing. A request that got no answer (network, a send
160
+ over 15 seconds, 502/504) is sent again for up to 50 seconds, for a platform that keeps the answer for the
161
+ same device credential; `NetworkError` after that.
155
162
 
156
163
  ## Do it the atproto way
157
164
 
@@ -31,6 +31,9 @@
31
31
  * set it came from; otherwise the store's (newer) set is taken.
32
32
  * - an answer the device cannot use after the token rotated (no access token, another `sub`) ends the
33
33
  * session: the old token is spent, so keeping it would end the grant later anyway.
34
+ * - **A session that ends** (the PDS refused a refresh: the grant was revoked, say on the account page) clears
35
+ * the store and signs the device credential out too (best effort), so the platform drops the phone's push
36
+ * token then rather than when the device session expires.
34
37
  * - **Sign-out** waits for a refresh in flight, revokes the grant (`revokeOwnSession`) and the device
35
38
  * credential (`signOutDevice`), each given up after {@link SIGN_OUT_TIMEOUT_MS}, and clears the store,
36
39
  * whatever the network says. When the store holds another key's set it touches neither that set nor the
@@ -96,12 +99,7 @@ export interface OwnSessionOptions {
96
99
  now?: () => number;
97
100
  sleep?: (ms: number) => Promise<void>;
98
101
  }
99
- /** How long the platform keeps a refresh's answer for the same token and key. */
100
- export declare const PLATFORM_ANSWER_WINDOW_MS = 60000;
101
- /** How long after the first send a refresh that got no answer may be sent again. */
102
- export declare const LOST_ANSWER_WINDOW_MS = 50000;
103
- /** Every send is given up this long before {@link PLATFORM_ANSWER_WINDOW_MS} ends (clock skew, transit). */
104
- export declare const SEND_MARGIN_MS = 5000;
102
+ export { LOST_ANSWER_WINDOW_MS, PLATFORM_ANSWER_WINDOW_MS, SEND_MARGIN_MS } from './relay.js';
105
103
  /** How long sign-out waits for each of its calls (revoke, signOutDevice). */
106
104
  export declare const SIGN_OUT_TIMEOUT_MS = 10000;
107
105
  /** An early refresh holds the call only when the access token has less than this to live. */
@@ -111,6 +109,8 @@ export declare function nonceKey(url: string): string;
111
109
  /** The proof headers for a device-credential request: `Authorization: Bearer <rsds_>` and a `DPoP` proof by
112
110
  * `key` for `method` `url` with `ath` over the credential (no server nonce is asked for). */
113
111
  export declare function deviceProofHeaders(key: DpopKey, deviceSession: string, method: string, url: string): Record<string, string>;
112
+ /** The same token set (access and refresh token). */
113
+ export declare function sameSet(a: Pick<OwnSessionData, 'accessToken' | 'refreshToken'>, b: Pick<OwnSessionData, 'accessToken' | 'refreshToken'>): boolean;
114
114
  /** The device's own session (module doc). Make one with {@link OwnSession.restore} or {@link OwnSession.signedIn}.
115
115
  * The tokens and the key are in `#private` fields, so logging the session prints neither. */
116
116
  export declare class OwnSession {
@@ -1,15 +1,7 @@
1
1
  import { METHOD } from '../generated/nsid.js';
2
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;
3
+ import { OwnSessionError, SESSION_ENDED, fetchOr, nonceIn, postPlatform, resendUntilAnswered, str, trimSlash, withNonceRetry, withTimeout, } from './relay.js';
4
+ export { LOST_ANSWER_WINDOW_MS, PLATFORM_ANSWER_WINDOW_MS, SEND_MARGIN_MS } from './relay.js';
13
5
  /** How long sign-out waits for each of its calls (revoke, signOutDevice). */
14
6
  export const SIGN_OUT_TIMEOUT_MS = 10_000;
15
7
  /** An early refresh holds the call only when the access token has less than this to live. */
@@ -36,7 +28,7 @@ export function deviceProofHeaders(key, deviceSession, method, url) {
36
28
  return { authorization: `Bearer ${deviceSession}`, dpop: dpopProof(key, { htm: method, htu: url, token: deviceSession }) };
37
29
  }
38
30
  /** The same token set (access and refresh token). */
39
- function sameSet(a, b) {
31
+ export function sameSet(a, b) {
40
32
  return a.accessToken === b.accessToken && a.refreshToken === b.refreshToken;
41
33
  }
42
34
  /** The device's own session (module doc). Make one with {@link OwnSession.restore} or {@link OwnSession.signedIn}.
@@ -242,40 +234,30 @@ export class OwnSession {
242
234
  }
243
235
  }
244
236
  /** 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) });
237
+ * (module doc, {@link resendUntilAnswered}). */
238
+ #resendUntilAnswered(started, body) {
239
+ return resendUntilAnswered({
240
+ nsid: METHOD.REFRESH_OWN_SESSION,
241
+ started,
242
+ now: () => this.#now(),
243
+ sleep: (ms) => this.#sleep(ms),
244
+ noAnswerYet: (status) => NO_ANSWER_YET.has(status),
245
+ send: async (timeoutMs) => {
246
+ const got = await postPlatform(this.#fetch, this.#platformUrl, METHOD.REFRESH_OWN_SESSION, body(), { timeoutMs });
257
247
  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
248
  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
- }
249
+ },
250
+ });
272
251
  }
273
- /** Ends the session here: clears the store (unless `clear` is false), calls `onEnded`. */
252
+ /** Ends the session here: calls `onEnded`, and unless `clear` is false (the store holds no set of this
253
+ * session's) clears the store and signs the device credential out (best effort, not awaited): the grant
254
+ * is gone, and the device session would otherwise keep the phone's push token on the platform until it
255
+ * expires. */
274
256
  #end(error, clear = true) {
275
257
  if (!this.#endedWith) {
276
258
  this.#endedWith = error;
277
259
  if (clear)
278
- void this.#opts.store.delete().catch(() => { });
260
+ void this.#clearIfStillOurs();
279
261
  try {
280
262
  this.#opts.onEnded?.(error);
281
263
  }
@@ -283,6 +265,22 @@ export class OwnSession {
283
265
  }
284
266
  return this.#endedWith;
285
267
  }
268
+ /** The store and the device credential, cleared only while the store holds this session's set (or none):
269
+ * a set another process rotated meanwhile (no shared `lock`) is a live session, not this ended one. */
270
+ async #clearIfStillOurs() {
271
+ try {
272
+ const stored = await this.#opts.store.get();
273
+ const from = this.#unsavedFrom;
274
+ if (stored && !(this.#ours(stored) && (sameSet(stored, this.#data) || (from && sameSet(stored, from)))))
275
+ return;
276
+ if (stored)
277
+ await this.#opts.store.delete().catch(() => { });
278
+ }
279
+ catch {
280
+ return;
281
+ }
282
+ await this.#signOutDevice(this.#data);
283
+ }
286
284
  /**
287
285
  * Sign out: wait for a refresh in flight (so the newest refresh token is the one revoked), revoke the grant
288
286
  * at the PDS (`revokeOwnSession` with the refresh token, so the whole grant goes), sign the device
@@ -312,12 +310,7 @@ export class OwnSession {
312
310
  const d = stored === undefined || (from && sameSet(stored, from)) ? this.#data : stored;
313
311
  try {
314
312
  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 };
313
+ return { revoked, deviceSignedOut: await this.#signOutDevice(d) };
321
314
  }
322
315
  finally {
323
316
  if (stored !== undefined)
@@ -329,6 +322,14 @@ export class OwnSession {
329
322
  this.#end(new OwnSessionError(SESSION_ENDED, 'techne-sdk/session: signed out'), false);
330
323
  }
331
324
  }
325
+ /** `signOutDevice` with `d`'s device credential, given up after {@link SIGN_OUT_TIMEOUT_MS}: whether the
326
+ * platform took it. Never throws; false when there is no device credential. */
327
+ async #signOutDevice(d) {
328
+ if (!d.deviceSession)
329
+ return false;
330
+ const init = { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' };
331
+ return withTimeout(SIGN_OUT_TIMEOUT_MS, (signal) => this.#deviceFetch(d, `/xrpc/${METHOD.SIGN_OUT_DEVICE}`, { ...init, signal })).then((r) => r.ok, () => false);
332
+ }
332
333
  async #revoke(d) {
333
334
  const { answer } = await withNonceRetry(METHOD.REVOKE_OWN_SESSION, this.#nonces.get(nonceKey(d.revocationEndpoint)), async (nonce) => {
334
335
  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 });
@@ -1,5 +1,5 @@
1
1
  import { type DpopKey } from './dpop.js';
2
- import type { OwnSessionData } from './own-session.js';
2
+ import { type OwnSessionData, type TokenStore } from './own-session.js';
3
3
  import { type Fetch } from './relay.js';
4
4
  /** The endpoints the door's proofs name (`startPhoneSignup` with `ownSession:{}`). */
5
5
  export interface OwnSessionEndpoints {
@@ -64,16 +64,35 @@ export declare function finishPhoneSignIn(pending: PendingPhoneSignIn, code: str
64
64
  * holding sessions. The device, with its full `rsds_` device session, takes over the OAuth session the
65
65
  * platform holds for its account (`social.scenius.adoptHeldSession`): it gets the tokens and their DPoP key,
66
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).
67
+ * {@link OwnSession.deviceFetchHandler}). The account's other devices on older builds sign in again.
68
+ *
69
+ * The platform deletes its copy when it answers, so the answer must not be lost:
70
+ * - **On the wire**: a request that got no answer (the network failed, a send took longer than 15 s, a
71
+ * gateway answered 502/504) is sent again, the same request, starting up to
72
+ * {@link LOST_ANSWER_WINDOW_MS} after the first, each send given up before the platform's
73
+ * {@link PLATFORM_ANSWER_WINDOW_MS}: a platform that keeps the answer for the same device credential
74
+ * gives it again (one that does not refuses the retry, and the person signs in once). Past that window it
75
+ * rejects `NetworkError`.
76
+ * - **On the phone**: with `store`, the session is saved there as soon as it is checked, before the issuer's
77
+ * metadata is fetched (with the atproto endpoints, `/oauth/token` and `/oauth/revoke`), so an app killed
78
+ * meanwhile finds it in the store on its next launch ({@link OwnSession.restore}). It is saved only when
79
+ * the store holds no session when it looks, and its endpoints are corrected there afterwards only while the
80
+ * store still holds that set.
81
+ *
82
+ * The token and revocation endpoints come from the issuer's metadata (tried three times; failing that, the
83
+ * atproto defaults, so the tokens are never thrown away). Without `store`, save the answer at once
84
+ * ({@link OwnSession.signedIn}). With `store`, open the session with {@link OwnSession.restore}, not
85
+ * `signedIn`: the store holds this set, or a newer one that landed during the metadata fetch (a refresh, a
86
+ * sign-in), which `signedIn` would write over with spent tokens; only when `restore` finds nothing (the store
87
+ * could not be written) `signedIn` the answer. Rejects with `NoHeldSession` (nothing to
88
+ * adopt: already adopted, or never held), `Unavailable` (try again), `NetworkError` (no answer: try again),
89
+ * `WrongAccount` (a session for another DID than `did`), or `InvalidResponse` (no session, no issuer, or an
90
+ * issuer that is not an https origin; checked before anything is kept).
74
91
  */
75
92
  export declare function adoptHeldSession(o: PhoneSignInOptions & {
76
93
  deviceSession: string;
77
94
  /** The DID the device is signed in as: a session for another account is refused (`WrongAccount`). */
78
95
  did: string;
96
+ /** The app's session store: the session is saved there before the metadata fetch (above). */
97
+ store?: TokenStore;
79
98
  }): Promise<OwnSessionData>;
@@ -14,7 +14,8 @@
14
14
  */
15
15
  import { METHOD } from '../generated/nsid.js';
16
16
  import { dpopKeyFromJwk, dpopProof, generateDpopKey, pkcePair } from './dpop.js';
17
- import { OwnSessionError, fetchOr, nonceIn, obj, postPlatform, refusal, str, trimSlash, withNonceRetry, withTimeout } from './relay.js';
17
+ import { sameSet } from './own-session.js';
18
+ import { OwnSessionError, fetchOr, nonceIn, obj, postPlatform, refusal, resendUntilAnswered, str, trimSlash, withNonceRetry, withTimeout, } from './relay.js';
18
19
  /** The fields every own-session answer must carry (beyond the lexicon's `required`, the SDK needs `pds`, where
19
20
  * the tokens go, and `sub`). */
20
21
  function ownAnswer(nsid, own) {
@@ -130,8 +131,13 @@ async function authorizationServerEndpoints(issuer, fetch) {
130
131
  }
131
132
  return { tokenEndpoint, revocationEndpoint };
132
133
  }
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`.
134
+ /** The token and revocation endpoints every atproto authorization server (`@atproto/oauth-provider`, the
135
+ * ePDS) serves: `/oauth/token` and `/oauth/revoke` on the issuer. */
136
+ function atprotoEndpoints(issuer) {
137
+ const base = trimSlash(issuer);
138
+ return { tokenEndpoint: `${base}/oauth/token`, revocationEndpoint: `${base}/oauth/revoke` };
139
+ }
140
+ /** {@link authorizationServerEndpoints}, tried three times; when no try answers, {@link atprotoEndpoints}.
135
141
  * Used after the platform handed its session over and deleted its copy, so the tokens are kept either way
136
142
  * (if those endpoints were wrong, the next refresh is refused and the person signs in again, which is what
137
143
  * throwing the tokens away would have meant at once). */
@@ -146,26 +152,65 @@ async function endpointsKeepingTokens(issuer, fetch) {
146
152
  await sleep(METADATA_RETRY_DELAYS_MS[i]);
147
153
  }
148
154
  }
149
- const base = trimSlash(issuer);
150
- return { tokenEndpoint: `${base}/oauth/token`, revocationEndpoint: `${base}/oauth/revoke` };
155
+ return atprotoEndpoints(issuer);
151
156
  }
157
+ /** Save `data` when `store` holds no session when it looks (a session already there is not written over):
158
+ * whether it did. Never throws. */
159
+ async function saveIfEmpty(store, data) {
160
+ try {
161
+ if ((await store.get()) !== null)
162
+ return false;
163
+ await store.set(data);
164
+ return true;
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ }
170
+ /** An adopt answer lost on the way (a gateway that got no answer from the platform): send it again. A 503 or
171
+ * a 429 is the platform's answer (nothing was handed over: try later), not a lost one. */
172
+ const ADOPT_NO_ANSWER = new Set([502, 504]);
152
173
  /**
153
174
  * @deprecated A one-time move for a device signed in on an older build, removed when the platform stops
154
175
  * holding sessions. The device, with its full `rsds_` device session, takes over the OAuth session the
155
176
  * platform holds for its account (`social.scenius.adoptHeldSession`): it gets the tokens and their DPoP key,
156
177
  * 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).
178
+ * {@link OwnSession.deviceFetchHandler}). The account's other devices on older builds sign in again.
179
+ *
180
+ * The platform deletes its copy when it answers, so the answer must not be lost:
181
+ * - **On the wire**: a request that got no answer (the network failed, a send took longer than 15 s, a
182
+ * gateway answered 502/504) is sent again, the same request, starting up to
183
+ * {@link LOST_ANSWER_WINDOW_MS} after the first, each send given up before the platform's
184
+ * {@link PLATFORM_ANSWER_WINDOW_MS}: a platform that keeps the answer for the same device credential
185
+ * gives it again (one that does not refuses the retry, and the person signs in once). Past that window it
186
+ * rejects `NetworkError`.
187
+ * - **On the phone**: with `store`, the session is saved there as soon as it is checked, before the issuer's
188
+ * metadata is fetched (with the atproto endpoints, `/oauth/token` and `/oauth/revoke`), so an app killed
189
+ * meanwhile finds it in the store on its next launch ({@link OwnSession.restore}). It is saved only when
190
+ * the store holds no session when it looks, and its endpoints are corrected there afterwards only while the
191
+ * store still holds that set.
192
+ *
193
+ * The token and revocation endpoints come from the issuer's metadata (tried three times; failing that, the
194
+ * atproto defaults, so the tokens are never thrown away). Without `store`, save the answer at once
195
+ * ({@link OwnSession.signedIn}). With `store`, open the session with {@link OwnSession.restore}, not
196
+ * `signedIn`: the store holds this set, or a newer one that landed during the metadata fetch (a refresh, a
197
+ * sign-in), which `signedIn` would write over with spent tokens; only when `restore` finds nothing (the store
198
+ * could not be written) `signedIn` the answer. Rejects with `NoHeldSession` (nothing to
199
+ * adopt: already adopted, or never held), `Unavailable` (try again), `NetworkError` (no answer: try again),
200
+ * `WrongAccount` (a session for another DID than `did`), or `InvalidResponse` (no session, no issuer, or an
201
+ * issuer that is not an https origin; checked before anything is kept).
164
202
  */
165
203
  export async function adoptHeldSession(o) {
166
204
  const fetch = fetchOr(o.fetch);
167
205
  const nsid = METHOD.ADOPT_HELD_SESSION;
168
- const answer = await postPlatform(fetch, o.platformUrl, nsid, {}, { headers: { authorization: `Bearer ${o.deviceSession}` } });
206
+ const answer = await resendUntilAnswered({
207
+ nsid,
208
+ started: Date.now(),
209
+ now: () => Date.now(),
210
+ sleep,
211
+ noAnswerYet: (status) => ADOPT_NO_ANSWER.has(status),
212
+ send: (timeoutMs) => postPlatform(fetch, o.platformUrl, nsid, {}, { headers: { authorization: `Bearer ${o.deviceSession}` }, timeoutMs }),
213
+ });
169
214
  if (answer.status !== 200)
170
215
  throw refusal(nsid, answer);
171
216
  const own = ownAnswer(nsid, obj(answer.json, 'ownSession'));
@@ -175,5 +220,19 @@ export async function adoptHeldSession(o) {
175
220
  const issuer = str(own, 'issuer');
176
221
  if (!issuer || !HTTPS_ORIGIN.test(issuer))
177
222
  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 });
223
+ const first = sessionData(own, key, atprotoEndpoints(issuer), undefined, { deviceSession: o.deviceSession });
224
+ const saved = o.store ? await saveIfEmpty(o.store, first) : false;
225
+ const endpoints = await endpointsKeepingTokens(issuer, fetch);
226
+ if (endpoints.tokenEndpoint === first.tokenEndpoint && endpoints.revocationEndpoint === first.revocationEndpoint)
227
+ return first;
228
+ const data = { ...first, ...endpoints };
229
+ if (saved && o.store) {
230
+ try {
231
+ const now = await o.store.get();
232
+ if (now && sameSet(now, first))
233
+ await o.store.set(data);
234
+ }
235
+ catch { }
236
+ }
237
+ return data;
179
238
  }
@@ -67,3 +67,26 @@ export declare function withNonceRetry(nsid: string, nonce: string | undefined,
67
67
  answer: PlatformAnswer;
68
68
  nonce?: string;
69
69
  }>;
70
+ /** How long the platform keeps an answer for the same request (a refresh's for the same token and key, an
71
+ * adopt's for the same device credential). */
72
+ export declare const PLATFORM_ANSWER_WINDOW_MS = 60000;
73
+ /** How long after the first send a request that got no answer may be sent again. */
74
+ export declare const LOST_ANSWER_WINDOW_MS = 50000;
75
+ /** Every send is given up this long before {@link PLATFORM_ANSWER_WINDOW_MS} ends (clock skew, transit). */
76
+ export declare const SEND_MARGIN_MS = 5000;
77
+ /**
78
+ * One platform request whose answer the platform keeps for {@link PLATFORM_ANSWER_WINDOW_MS}, sent again
79
+ * while no answer comes: `send(timeoutMs)` makes it (afresh each time, e.g. with a new proof). A send that
80
+ * throws (no answer, or no answer in its time) or an answer `noAnswerYet` names counts as none. A send starts
81
+ * up to {@link LOST_ANSWER_WINDOW_MS} after `started`, and each is given up {@link SEND_MARGIN_MS} before
82
+ * the platform's window ends, so no resend reaches the platform after its kept answer is gone. Past that,
83
+ * the last answer, or `NetworkError`.
84
+ */
85
+ export declare function resendUntilAnswered(o: {
86
+ nsid: string;
87
+ started: number;
88
+ now: () => number;
89
+ sleep: (ms: number) => Promise<void>;
90
+ noAnswerYet: (status: number) => boolean;
91
+ send: (timeoutMs: number) => Promise<PlatformAnswer>;
92
+ }): Promise<PlatformAnswer>;
@@ -118,3 +118,47 @@ export async function withNonceRetry(nsid, nonce, send, retries = 1) {
118
118
  nonce = err.nonce;
119
119
  }
120
120
  }
121
+ /** How long the platform keeps an answer for the same request (a refresh's for the same token and key, an
122
+ * adopt's for the same device credential). */
123
+ export const PLATFORM_ANSWER_WINDOW_MS = 60_000;
124
+ /** How long after the first send a request that got no answer may be sent again. */
125
+ export const LOST_ANSWER_WINDOW_MS = 50_000;
126
+ /** Every send is given up this long before {@link PLATFORM_ANSWER_WINDOW_MS} ends (clock skew, transit). */
127
+ export const SEND_MARGIN_MS = 5_000;
128
+ /** The waits between those sends, and how long one send may take at most. */
129
+ const LOST_ANSWER_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000];
130
+ const SEND_TIMEOUT_MS = 15_000;
131
+ /**
132
+ * One platform request whose answer the platform keeps for {@link PLATFORM_ANSWER_WINDOW_MS}, sent again
133
+ * while no answer comes: `send(timeoutMs)` makes it (afresh each time, e.g. with a new proof). A send that
134
+ * throws (no answer, or no answer in its time) or an answer `noAnswerYet` names counts as none. A send starts
135
+ * up to {@link LOST_ANSWER_WINDOW_MS} after `started`, and each is given up {@link SEND_MARGIN_MS} before
136
+ * the platform's window ends, so no resend reaches the platform after its kept answer is gone. Past that,
137
+ * the last answer, or `NetworkError`.
138
+ */
139
+ export async function resendUntilAnswered(o) {
140
+ const deadline = o.started + PLATFORM_ANSWER_WINDOW_MS - SEND_MARGIN_MS;
141
+ let failure;
142
+ for (let lost = 0;; lost++) {
143
+ let got;
144
+ const left = deadline - o.now();
145
+ if (left <= 0)
146
+ throw new OwnSessionError(NETWORK_ERROR, `techne-sdk/session: ${o.nsid} got no answer in the window`, { cause: failure });
147
+ try {
148
+ got = await o.send(Math.min(SEND_TIMEOUT_MS, left));
149
+ failure = undefined;
150
+ }
151
+ catch (e) {
152
+ failure = e;
153
+ }
154
+ if (got && !o.noAnswerYet(got.status))
155
+ return got;
156
+ const wait = Math.max(LOST_ANSWER_DELAYS_MS[Math.min(lost, LOST_ANSWER_DELAYS_MS.length - 1)], ((got ? retryAfterOf(got) : undefined) ?? 0) * 1000);
157
+ if (o.now() + wait - o.started > LOST_ANSWER_WINDOW_MS) {
158
+ if (got)
159
+ return got;
160
+ throw new OwnSessionError(NETWORK_ERROR, `techne-sdk/session: ${o.nsid} got no answer`, { cause: failure });
161
+ }
162
+ await o.sleep(wait);
163
+ }
164
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "techne-sdk",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "TechneSDK: sign in (\"Sign in with Techne\", browser OAuth), put, query, useEvent and the read-time check for apps on the Techne platform. Types and clients are generated from the published lexicons; the logic that must match the platform exactly (the check, version ranking, put's order) is Rust compiled to WebAssembly (wasm2js on hosts without it). Datetime fields are plain strings: send Date.prototype.toISOString() (UTC, trailing Z).",
5
5
  "license": "MIT",
6
6
  "repository": {