techne-sdk 0.10.0 → 0.12.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 (35) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +89 -6
  3. package/dist/auth/app-key.d.ts +2 -1
  4. package/dist/auth/app-key.js +2 -1
  5. package/dist/catalog/catalog.gen.js +320 -25
  6. package/dist/connect.d.ts +5 -2
  7. package/dist/generated/lexicons.d.ts +74 -20
  8. package/dist/generated/lexicons.js +42 -10
  9. package/dist/generated/nsid.d.ts +5 -0
  10. package/dist/generated/nsid.js +5 -0
  11. package/dist/generated/nsid.json +5 -0
  12. package/dist/generated/types/pub/techne/draft/identity/createCollective.d.ts +4 -1
  13. package/dist/generated/types/pub/techne/draft/identity/createCollective.js +7 -0
  14. package/dist/generated/types/pub/techne/draft/orgAtPlace.d.ts +2 -2
  15. package/dist/generated/types/pub/techne/draft/place.d.ts +4 -0
  16. package/dist/generated/types/pub/techne/draft/query/composeRecords.d.ts +2 -2
  17. package/dist/generated/types/pub/techne/draft/query/countRecords.d.ts +6 -0
  18. package/dist/generated/types/pub/techne/draft/query/countRecords.js +14 -0
  19. package/dist/generated/types/pub/techne/draft/query/listRecords.d.ts +7 -1
  20. package/dist/generated/types/pub/techne/draft/query/listRecords.js +14 -0
  21. package/dist/item.d.ts +3 -1
  22. package/dist/item.js +1 -1
  23. package/dist/query/hosts.d.ts +1 -1
  24. package/dist/query/hosts.js +5 -3
  25. package/dist/query/index.d.ts +32 -5
  26. package/dist/read/index.js +5 -4
  27. package/dist/session/own-session.d.ts +6 -6
  28. package/dist/session/own-session.js +45 -44
  29. package/dist/session/phone.d.ts +27 -8
  30. package/dist/session/phone.js +73 -14
  31. package/dist/session/relay.d.ts +23 -0
  32. package/dist/session/relay.js +44 -0
  33. package/dist/wasm/techne-wasm.gen.js +1 -1
  34. package/dist/wasm/techne-wasm2js.gen.js +21892 -21892
  35. package/package.json +1 -1
@@ -11,6 +11,16 @@ export class InvalidRequestError extends XRPCError {
11
11
  super(src.status, src.error, src.message, src.headers, { cause: src });
12
12
  }
13
13
  }
14
+ export class ViewRequiredError extends XRPCError {
15
+ constructor(src) {
16
+ super(src.status, src.error, src.message, src.headers, { cause: src });
17
+ }
18
+ }
19
+ export class NotCuratedError extends XRPCError {
20
+ constructor(src) {
21
+ super(src.status, src.error, src.message, src.headers, { cause: src });
22
+ }
23
+ }
14
24
  export class NotFoundError extends XRPCError {
15
25
  constructor(src) {
16
26
  super(src.status, src.error, src.message, src.headers, { cause: src });
@@ -20,6 +30,10 @@ export function toKnownErr(e) {
20
30
  if (e instanceof XRPCError) {
21
31
  if (e.error === 'InvalidRequest')
22
32
  return new InvalidRequestError(e);
33
+ if (e.error === 'ViewRequired')
34
+ return new ViewRequiredError(e);
35
+ if (e.error === 'NotCurated')
36
+ return new NotCuratedError(e);
23
37
  if (e.error === 'NotFound')
24
38
  return new NotFoundError(e);
25
39
  }
@@ -40,6 +40,12 @@ export interface Response {
40
40
  export declare class InvalidRequestError extends XRPCError {
41
41
  constructor(src: XRPCError);
42
42
  }
43
+ export declare class ViewRequiredError extends XRPCError {
44
+ constructor(src: XRPCError);
45
+ }
46
+ export declare class NotCuratedError extends XRPCError {
47
+ constructor(src: XRPCError);
48
+ }
43
49
  export declare class NotFoundError extends XRPCError {
44
50
  constructor(src: XRPCError);
45
51
  }
@@ -62,7 +68,7 @@ export interface Record {
62
68
  space?: string;
63
69
  /** Whether the record is public (on the firehose) or permissioned. */
64
70
  source: 'public' | 'permissioned' | (string & {});
65
- /** A public record that is a live curated record: a curator the commons root trusts merged it from its sources, and it is not superseded. Its `pub.techne.draft.provenance` (same author, subject this record) names who it is from. Absent otherwise. */
71
+ /** A public record that is a live curated record: a curator the commons root trusts merged it from its sources, and it is not superseded. Its `pub.techne.draft.provenance` (same author, subject this record) names who it is from. Always answered: false for every other record (a source copy, a superseded one, a permissioned one). */
66
72
  curated?: boolean;
67
73
  /** The caller's own permissioned record that the reach limit holds back from the people it would reach: a withheld act (a share or a circle add), answered to its author alone (to anyone else it is not found) until the limit admits it. Absent otherwise. A query with `held: true` answers only these. */
68
74
  held?: boolean;
@@ -11,6 +11,16 @@ export class InvalidRequestError extends XRPCError {
11
11
  super(src.status, src.error, src.message, src.headers, { cause: src });
12
12
  }
13
13
  }
14
+ export class ViewRequiredError extends XRPCError {
15
+ constructor(src) {
16
+ super(src.status, src.error, src.message, src.headers, { cause: src });
17
+ }
18
+ }
19
+ export class NotCuratedError extends XRPCError {
20
+ constructor(src) {
21
+ super(src.status, src.error, src.message, src.headers, { cause: src });
22
+ }
23
+ }
14
24
  export class NotFoundError extends XRPCError {
15
25
  constructor(src) {
16
26
  super(src.status, src.error, src.message, src.headers, { cause: src });
@@ -20,6 +30,10 @@ export function toKnownErr(e) {
20
30
  if (e instanceof XRPCError) {
21
31
  if (e.error === 'InvalidRequest')
22
32
  return new InvalidRequestError(e);
33
+ if (e.error === 'ViewRequired')
34
+ return new ViewRequiredError(e);
35
+ if (e.error === 'NotCurated')
36
+ return new NotCuratedError(e);
23
37
  if (e.error === 'NotFound')
24
38
  return new NotFoundError(e);
25
39
  }
package/dist/item.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * the one shape every read answers (`Item<T>`), typed URIs, and the check that
4
4
  * gives each item its verdict.
5
5
  *
6
- * An item is `{ uri, cid, record, verdict, problems, curated, byline }`:
6
+ * An item is `{ uri, cid, author, record, verdict, problems, curated, byline }`:
7
7
  *
8
8
  * - `uri` is typed (`Uri<Place>`), so a hook handed `item.uri` comes back typed. A bare string is no
9
9
  * `Uri<Place>` (only an item, or `Place.uri(s)`, makes one); a read taking a bare string answers
@@ -59,6 +59,8 @@ export interface Byline extends BylineRef {
59
59
  interface ItemBase<T> {
60
60
  uri: Uri<T>;
61
61
  cid: string;
62
+ /** The DID whose repo holds the record: its author (a curated record's is the curator's). */
63
+ author: string;
62
64
  /** Why it is not valid: the check's reasons when invalid, what it waits for when pending. */
63
65
  problems: string[];
64
66
  /** A live curated record (the commons composed it from versions). */
package/dist/item.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * the one shape every read answers (`Item<T>`), typed URIs, and the check that
4
4
  * gives each item its verdict.
5
5
  *
6
- * An item is `{ uri, cid, record, verdict, problems, curated, byline }`:
6
+ * An item is `{ uri, cid, author, record, verdict, problems, curated, byline }`:
7
7
  *
8
8
  * - `uri` is typed (`Uri<Place>`), so a hook handed `item.uri` comes back typed. A bare string is no
9
9
  * `Uri<Place>` (only an item, or `Place.uri(s)`, makes one); a read taking a bare string answers
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { type Binding, type EnvelopeField, type Composed, type Composition, type Reader, type StepRecord, type StepRef } from './compose.js';
25
25
  import { type Query, type QueryReader, type QueryRecord } from './index.js';
26
- /** The provenance records written about `$uris` (as written: a read scoped to subjects). */
26
+ /** The provenance records written about `$uris` (as written). */
27
27
  export declare const PROVENANCE_OF_QUERY: Query;
28
28
  /** The mirror sidecars written about `$uris` (`source`, and the frozen old-Almanac `sourceRef`). */
29
29
  export declare const MIRROR_SIDECARS_QUERY: Query;
@@ -24,12 +24,14 @@
24
24
  import { NSID } from '../generated/nsid.js';
25
25
  import { compose, ENVELOPE_ONLY, MAX_STEP_LIMIT } from './compose.js';
26
26
  import { getRecords, listAllRecordsFor } from './index.js';
27
- /** The provenance records written about `$uris` (as written: a read scoped to subjects). */
27
+ /** The provenance records written about `$uris` (as written). */
28
28
  export const PROVENANCE_OF_QUERY = {
29
+ view: 'asWritten',
29
30
  where: { all: [{ type: { is: NSID.PROVENANCE } }, { subject: { in: ['$uris'] } }] },
30
31
  };
31
32
  /** The mirror sidecars written about `$uris` (`source`, and the frozen old-Almanac `sourceRef`). */
32
33
  export const MIRROR_SIDECARS_QUERY = {
34
+ view: 'asWritten',
33
35
  where: { all: [{ type: { in: [NSID.SOURCE, NSID.SOURCE_REF] } }, { subject: { in: ['$uris'] } }] },
34
36
  };
35
37
  const authority = (uri) => uri.split('/')[2] ?? '';
@@ -130,7 +132,7 @@ export const HOST_SOURCES_QUERY = {
130
132
  { not: [{ has: { via: 'subject', by: 'author', where: { type: { in: [NSID.SOURCE, NSID.SOURCE_REF] } } } }] },
131
133
  ],
132
134
  },
133
- curated: false,
135
+ view: 'asWritten',
134
136
  };
135
137
  /** The record fields {@link hostsFrom} reads of the host steps' records: a page that hands the provenances to no
136
138
  * other rule asks {@link hostSteps} for exactly these. */
@@ -285,8 +287,8 @@ export async function listedOnOf(read, record) {
285
287
  /** The provenances naming any of `$uris` among their sources (the `references` role): a source copy finds
286
288
  * the curated record made from it. As written, so a provenance is found whatever lists. */
287
289
  export const CURATED_FROM_QUERY = {
290
+ view: 'asWritten',
288
291
  where: { all: [{ type: { is: NSID.PROVENANCE } }, { references: { in: ['$uris'] } }] },
289
- curated: false,
290
292
  };
291
293
  /**
292
294
  * The live curated record that stands for `uri` now, when `uri` itself is not one a reader is shown (the
@@ -39,19 +39,45 @@ export type QueryNode = {
39
39
  } | {
40
40
  readonly [role: string]: Condition | readonly QueryNode[];
41
41
  };
42
- /** A `pub.techne.draft.query`, as data (the platform validates it). */
43
- export interface Query {
42
+ /**
43
+ * Which public records a branch reads; every list names one, there is no default (the `view` property of `pub.techne.draft.query` and its `#branch`):
44
+ * - `curated`: the commons' listed records, one curated record per thing (merged from its sources by a curator
45
+ * the commons root trusts), moderated, not hidden; an event only inside the supported areas. A type no curator
46
+ * covers is refused with `NotCurated`, naming the type, never answered as an empty list.
47
+ * - `asWritten`: every public record as its author wrote it, each source copy and the curated record, not hidden,
48
+ * not superseded. Totals in this view count both copies of a curated thing.
49
+ * A permissioned record reads the same in both (it is never curated).
50
+ */
51
+ export type View = 'curated' | 'asWritten';
52
+ /** One branch of a query in the `any` form: its own view and `where`. */
53
+ export interface QueryBranch {
54
+ readonly view: View;
44
55
  readonly where: QueryNode;
45
- /** A role, a measure's `as` name, or `shuffle` (one deterministic order per {@link Query.seed}). */
56
+ }
57
+ /** What every query document carries besides its branches. */
58
+ export interface QueryOptions {
59
+ /** A role, a measure's `as` name, or `shuffle` (one deterministic order per `seed`). */
46
60
  readonly order?: string;
47
61
  /** The seed of `order: "shuffle"`: a literal or a `$param`; required with it, refused without it. */
48
62
  readonly seed?: string;
49
63
  readonly limit?: number;
50
64
  readonly signals?: readonly Readonly<Record<string, unknown>>[];
51
- readonly curated?: boolean;
52
65
  /** Only the caller's own permissioned records the reach limit is holding back (each marked `held`). */
53
66
  readonly held?: boolean;
54
67
  }
68
+ /** A `pub.techne.draft.query`, as data (the platform validates it). Every branch names its {@link View}: `view`
69
+ * beside `where` names it for every branch of the `where` (each child of a top-level `any` too), and the `any`
70
+ * form, `{ any: [{ view, where }, …] }`, one per branch (an app's feed: curated events and its own records as
71
+ * written, in one list). A query naming no view is refused with `ViewRequired`. */
72
+ export type Query = QueryOptions & ({
73
+ readonly view: View;
74
+ readonly where: QueryNode;
75
+ readonly any?: never;
76
+ } | {
77
+ readonly any: readonly [QueryBranch, ...QueryBranch[]];
78
+ readonly view?: never;
79
+ readonly where?: never;
80
+ });
55
81
  /** One record a query answered (`pub.techne.draft.query.listRecords#record`). */
56
82
  export interface QueryRecord<V = Record<string, unknown>> {
57
83
  uri: string;
@@ -65,7 +91,8 @@ export interface QueryRecord<V = Record<string, unknown>> {
65
91
  space?: string;
66
92
  source: 'public' | 'permissioned';
67
93
  /** A public record that is a live curated record (a curator the commons root trusts merged it); its
68
- * provenance names who it is from ({@link hostsOf}). Absent otherwise. */
94
+ * provenance names who it is from ({@link hostsOf}). Always answered, false otherwise (a platform from before
95
+ * views left it out when false). */
69
96
  curated?: boolean;
70
97
  /** The caller's own permissioned record the reach limit holds back from the people it would reach:
71
98
  * answered to its author alone (anyone else does not see it) until the limit admits it. */
@@ -3,8 +3,8 @@
3
3
  * {@link Item}s, and their options forms (`{ queryKey, queryFn }`, for TanStack Query). Internal: an app
4
4
  * calls them on what `connect` returns, which binds them to its session and the claims it holds.
5
5
  *
6
- * - `query(q, opts)`: one page of a query document (`pub.techne.draft.query.listRecords`). A list across
7
- * authors answers curated records (the query's `curated`, on the platform). `count` is a read option
6
+ * - `query(q, opts)`: one page of a query document (`pub.techne.draft.query.listRecords`). Every list reads
7
+ * the view the query names (`view`: `curated` or `asWritten`, on the platform). `count` is a read option
8
8
  * (the document has no count field); the page's `count` is what the platform counted, before `include`.
9
9
  * - `get(uri, opts)`: one record. By default the curated view: `commons.getVersions` resolves any copy to
10
10
  * its curated record, and a type nobody curates answers the record itself. `prefer: 'mine'` answers the
@@ -28,9 +28,10 @@ export const readerOf = (techne) => async (nsid, params) => (await techne.platfo
28
28
  export const posterOf = (techne) => async (nsid, body) => (await techne.platform.call(nsid, {}, body, { encoding: 'application/json' })).data;
29
29
  /** `r` as an item, with `byline` from its curated record's composition. */
30
30
  function itemOf(techne, r, curated, composition) {
31
- const { verdict, problems } = check({ uri: r.uri, collection: r.collection ?? collectionOf(r.uri), author: r.author ?? authorOf(r.uri), value: r.value, space: r.space, time: r.time, held: r.held }, techne.claims);
31
+ const author = r.author ?? authorOf(r.uri);
32
+ const { verdict, problems } = check({ uri: r.uri, collection: r.collection ?? collectionOf(r.uri), author, value: r.value, space: r.space, time: r.time, held: r.held }, techne.claims);
32
33
  // The check is what makes the record a `T`: valid and pending records passed its lexicon check.
33
- return { uri: r.uri, cid: r.cid, record: r.value, verdict, problems, curated, byline: curated ? bylineOf(composition) : null };
34
+ return { uri: r.uri, cid: r.cid, author, record: r.value, verdict, problems, curated, byline: curated ? bylineOf(composition) : null };
34
35
  }
35
36
  const fromQueryRecord = (techne, r, composition) => itemOf(techne, r, r.curated === true, composition);
36
37
  export async function query(techne, q, opts = {}) {
@@ -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>;