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.
Files changed (47) hide show
  1. package/CHANGELOG.md +48 -5
  2. package/README.md +51 -1
  3. package/dist/auth/index.d.ts +2 -2
  4. package/dist/auth/index.js +5 -3
  5. package/dist/auth/placement.gen.d.ts +1 -1
  6. package/dist/auth/placement.gen.js +4 -0
  7. package/dist/catalog/catalog.gen.d.ts +2 -2
  8. package/dist/catalog/catalog.gen.js +1394 -130
  9. package/dist/generated/index.d.ts +129 -0
  10. package/dist/generated/index.js +170 -0
  11. package/dist/generated/lexicons.d.ts +954 -134
  12. package/dist/generated/lexicons.js +511 -61
  13. package/dist/generated/nsid.d.ts +16 -1
  14. package/dist/generated/nsid.js +16 -1
  15. package/dist/generated/nsid.json +16 -1
  16. package/dist/generated/records.d.ts +148 -140
  17. package/dist/generated/types/app/certified/defs.d.ts +20 -0
  18. package/dist/generated/types/app/certified/defs.js +18 -0
  19. package/dist/generated/types/app/certified/signature/defs.d.ts +29 -0
  20. package/dist/generated/types/app/certified/signature/defs.js +18 -0
  21. package/dist/generated/types/org/hypercerts/funding/receipt.d.ts +56 -0
  22. package/dist/generated/types/org/hypercerts/funding/receipt.js +19 -0
  23. package/dist/generated/types/pub/techne/draft/financials.d.ts +26 -0
  24. package/dist/generated/types/pub/techne/draft/financials.js +12 -0
  25. package/dist/generated/types/pub/techne/draft/identity/createCollective.d.ts +5 -0
  26. package/dist/generated/types/pub/techne/draft/identity/createCollective.js +7 -0
  27. package/dist/generated/types/pub/techne/draft/identity/defs.d.ts +1 -1
  28. package/dist/generated/types/pub/techne/draft/identity/manageMethods.d.ts +4 -1
  29. package/dist/generated/types/pub/techne/draft/org.d.ts +55 -25
  30. package/dist/generated/types/pub/techne/draft/org.js +12 -5
  31. package/dist/generated/types/pub/techne/draft/orgAtPlace.d.ts +17 -0
  32. package/dist/generated/types/pub/techne/draft/orgAtPlace.js +12 -0
  33. package/dist/generated/types/pub/techne/draft/statement.d.ts +19 -0
  34. package/dist/generated/types/pub/techne/draft/statement.js +12 -0
  35. package/dist/session/dpop.d.ts +49 -0
  36. package/dist/session/dpop.js +105 -0
  37. package/dist/session/index.d.ts +22 -0
  38. package/dist/session/index.js +22 -0
  39. package/dist/session/own-session.d.ts +169 -0
  40. package/dist/session/own-session.js +364 -0
  41. package/dist/session/phone.d.ts +79 -0
  42. package/dist/session/phone.js +179 -0
  43. package/dist/session/relay.d.ts +69 -0
  44. package/dist/session/relay.js +120 -0
  45. package/dist/wasm/techne-wasm.gen.js +1 -1
  46. package/dist/wasm/techne-wasm2js.gen.js +23340 -23255
  47. package/package.json +10 -3
@@ -0,0 +1,169 @@
1
+ /**
2
+ * A session the app holds itself (#redesign 659c31df): the OAuth tokens for the person's PDS, bound to a
3
+ * DPoP key the app made, plus the platform's narrow device credential. It is a {@link Session}
4
+ * (`did` + `fetchHandler`), so `connect(session, platform)` takes it as it takes a browser OAuth session.
5
+ *
6
+ * - **Calls to the PDS** carry `Authorization: DPoP <access token>` and a fresh proof (with `ath`) per
7
+ * request. A `use_dpop_nonce` answer is signed again once with the nonce it names; nonces are kept per
8
+ * origin. An `invalid_token` answer refreshes and sends once more.
9
+ * - **Refresh** goes through the platform's `refreshOwnSession` (the platform adds its client assertion; the
10
+ * proof is the device's). The PDS rotates the refresh token on every refresh and ends the whole grant if
11
+ * an old one comes back or a refresh is signed by another key, so:
12
+ * - one refresh at a time: in this process by a single flight, across processes by the `lock` option
13
+ * the app backs with its own cross-process lock; inside it the store is read again, and a token set
14
+ * another process already rotated is taken instead of refreshing again;
15
+ * - early: a call starts a refresh when the access token has less than `refreshEarlyMs` to live; while
16
+ * the token still has more than {@link STILL_VALID_MS} the call goes on with it and the refresh runs
17
+ * (or fails) behind it, so a platform that is down does not hold the call;
18
+ * - the rotated set is saved to the store before it is used;
19
+ * - a refresh that got no answer (the network failed or timed out, a gateway answered 502/504, or the
20
+ * platform answered 503/429 while the PDS call with that token was still running) is sent again, the
21
+ * same refresh token with a fresh proof by the same key, starting up to {@link LOST_ANSWER_WINDOW_MS}
22
+ * after the first: the platform keeps each refresh's answer for 60 s and gives it to the same token
23
+ * and key again, so a lost answer does not sign the person out. Each send is given up
24
+ * {@link SEND_MARGIN_MS} before those 60 s end, so no resend reaches the platform after its answer is
25
+ * gone. A phone that stays offline past that window after the PDS rotated is signed out on its next
26
+ * refresh (the window is the platform's).
27
+ * - the store holding a set under another key (the person signed out and in again in another process)
28
+ * ends this session and leaves the store alone: a refresh or a revoke signed by this key would end the
29
+ * other process's grant;
30
+ * - a rotated set whose save failed is saved by the next refresh only while the store still holds the
31
+ * set it came from; otherwise the store's (newer) set is taken.
32
+ * - an answer the device cannot use after the token rotated (no access token, another `sub`) ends the
33
+ * session: the old token is spent, so keeping it would end the grant later anyway.
34
+ * - **Sign-out** waits for a refresh in flight, revokes the grant (`revokeOwnSession`) and the device
35
+ * credential (`signOutDevice`), each given up after {@link SIGN_OUT_TIMEOUT_MS}, and clears the store,
36
+ * whatever the network says. When the store holds another key's set it touches neither that set nor the
37
+ * store.
38
+ * - **The device credential** (`rsds_`, narrowed to this key) goes only with a per-request proof:
39
+ * {@link OwnSession.deviceFetchHandler} for registerDevicePush, listDeviceSessions and signOutDevice,
40
+ * {@link OwnSession.deviceHeaders} for the change stream's WebSocket.
41
+ */
42
+ import type { FetchHandler } from '@atproto/xrpc';
43
+ import { type DpopKey } from './dpop.js';
44
+ import { OwnSessionError, type Fetch } from './relay.js';
45
+ /** What the app keeps for a signed-in device, in secure storage (every field but `did`, `pds` and the
46
+ * endpoints is a secret). Plain JSON, so a store writes it as a string. */
47
+ export interface OwnSessionData {
48
+ /** The person's DID (the tokens' `sub`). */
49
+ did: string;
50
+ /** The PDS the tokens are for (an origin). */
51
+ pds: string;
52
+ accessToken: string;
53
+ refreshToken?: string;
54
+ /** When the access token expires, in milliseconds since the epoch. */
55
+ expiresAt?: number;
56
+ scope?: string;
57
+ /** The authorization server. */
58
+ issuer?: string;
59
+ /** The `htu` of refresh proofs (`startPhoneSignup` names it). */
60
+ tokenEndpoint: string;
61
+ /** The `htu` of revoke proofs. */
62
+ revocationEndpoint: string;
63
+ /** The session's DPoP key (a P-256 private JWK). */
64
+ dpopKey: DpopKey;
65
+ /** The latest DPoP nonce the authorization server gave. */
66
+ dpopNonce?: string;
67
+ /** The platform's narrow device credential (`rsds_`), bound to `dpopKey`. */
68
+ deviceSession?: string;
69
+ /** That device's public handle (`listDeviceSessions`). */
70
+ deviceId?: string;
71
+ }
72
+ /** Where the app keeps its {@link OwnSessionData} (Beacon: expo-secure-store). `get` answers null when
73
+ * nobody is signed in. Every process of the app must see the same store. */
74
+ export interface TokenStore {
75
+ get(): Promise<OwnSessionData | null>;
76
+ set(data: OwnSessionData): Promise<void>;
77
+ delete(): Promise<void>;
78
+ }
79
+ /** Runs `fn` while holding a lock every process of the app shares (a refresh rotates the token, so two at
80
+ * once end the session). The in-process single flight is always there; this adds the cross-process part. */
81
+ export type RefreshLock = <T>(fn: () => Promise<T>) => Promise<T>;
82
+ /** {@link OwnSession}'s options. */
83
+ export interface OwnSessionOptions {
84
+ /** The platform's origin (`https://...`): where `refreshOwnSession`, `revokeOwnSession` and the device calls go. */
85
+ platformUrl: string;
86
+ store: TokenStore;
87
+ /** The cross-process lock around a refresh and a sign-out; none by default. */
88
+ lock?: RefreshLock;
89
+ /** Refresh when the access token has less than this to live; 5 minutes by default. */
90
+ refreshEarlyMs?: number;
91
+ /** Called once when the session ends (the PDS dropped the grant, or sign-out): show sign-in. */
92
+ onEnded?: (error: OwnSessionError) => void;
93
+ /** The fetch every request goes through; `globalThis.fetch` by default. */
94
+ fetch?: Fetch;
95
+ /** Clock and timer (tests). */
96
+ now?: () => number;
97
+ sleep?: (ms: number) => Promise<void>;
98
+ }
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;
105
+ /** How long sign-out waits for each of its calls (revoke, signOutDevice). */
106
+ export declare const SIGN_OUT_TIMEOUT_MS = 10000;
107
+ /** An early refresh holds the call only when the access token has less than this to live. */
108
+ export declare const STILL_VALID_MS = 30000;
109
+ /** The origin of `url` (`scheme://host[:port]`), lower-cased: what a DPoP nonce is kept under. */
110
+ export declare function nonceKey(url: string): string;
111
+ /** The proof headers for a device-credential request: `Authorization: Bearer <rsds_>` and a `DPoP` proof by
112
+ * `key` for `method` `url` with `ath` over the credential (no server nonce is asked for). */
113
+ export declare function deviceProofHeaders(key: DpopKey, deviceSession: string, method: string, url: string): Record<string, string>;
114
+ /** The device's own session (module doc). Make one with {@link OwnSession.restore} or {@link OwnSession.signedIn}.
115
+ * The tokens and the key are in `#private` fields, so logging the session prints neither. */
116
+ export declare class OwnSession {
117
+ #private;
118
+ private constructor();
119
+ /** The session in the store, or null when nobody is signed in there. */
120
+ static restore(opts: OwnSessionOptions): Promise<OwnSession | null>;
121
+ /** A session just signed in (`finishPhoneSignIn`, `adoptHeldSession`): saved to the store first. */
122
+ static signedIn(data: OwnSessionData, opts: OwnSessionOptions): Promise<OwnSession>;
123
+ /** The signed-in person's DID. */
124
+ get did(): string;
125
+ /** The device credential's public handle, when there is one. */
126
+ get deviceId(): string | undefined;
127
+ /** When the access token expires (ms since the epoch), when known. */
128
+ get expiresAt(): number | undefined;
129
+ /**
130
+ * A request to the person's PDS with the session: `url` is a path (`/xrpc/...`, how an XRPC client calls
131
+ * a fetch handler) on the PDS, or a full URL. `connect` calls this.
132
+ */
133
+ fetchHandler: FetchHandler;
134
+ /** The access token. When it has less than `refreshEarlyMs` to live a refresh starts; the call waits for
135
+ * it only when the token has less than {@link STILL_VALID_MS} left. A refresh that fails while the token
136
+ * still lives does not fail the call (the next one tries again); one that ends the session does. */
137
+ accessToken(): Promise<string>;
138
+ /**
139
+ * Refresh now (one at a time; module doc). With `seen`, the access token the caller found stale: when the
140
+ * store already holds another (another process refreshed), that one is taken and nothing is sent.
141
+ * Rejects with `SessionEnded` when the session is over (the store is cleared and `onEnded` called; when
142
+ * the store holds another key's set, it is left alone), `NetworkError` when no answer came inside the
143
+ * lost-answer window (the session is kept), or the platform's refusal.
144
+ */
145
+ refresh(seen?: string): Promise<void>;
146
+ /**
147
+ * Sign out: wait for a refresh in flight (so the newest refresh token is the one revoked), revoke the grant
148
+ * at the PDS (`revokeOwnSession` with the refresh token, so the whole grant goes), sign the device
149
+ * credential out (`signOutDevice`), clear the store. Each call is given up after
150
+ * {@link SIGN_OUT_TIMEOUT_MS}. The store is cleared and the session ends whatever the network says; the
151
+ * answer says what the server took. When the store holds no set of this session's (signed out, or signed
152
+ * in under another key, in another process), nothing is sent and the store is left alone; when the store
153
+ * cannot be read, this session's own set is revoked and the store is left alone. A second call answers
154
+ * the first one's result.
155
+ */
156
+ signOut(): Promise<{
157
+ revoked: boolean;
158
+ deviceSignedOut: boolean;
159
+ }>;
160
+ /** The headers for one device-credential request (`Authorization: Bearer <rsds_>` and its `DPoP` proof):
161
+ * for the change stream, `deviceHeaders('GET', 'wss://<platform>/xrpc/_stream/changes')` on the
162
+ * WebSocket. Each call makes a new proof; use it for one request. Null when the session has no device
163
+ * credential. */
164
+ deviceHeaders(method: string, url: string): Record<string, string> | null;
165
+ /** A fetch handler to the platform with the device credential and a fresh proof per request: for
166
+ * registerDevicePush, listDeviceSessions and signOutDevice (`new AtpBaseClient(session.deviceFetchHandler)`).
167
+ * `url` is a path on the platform (`/xrpc/...`) or a full URL. */
168
+ deviceFetchHandler: FetchHandler;
169
+ }
@@ -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>;