techne-sdk 0.3.8 → 0.4.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 (49) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +3 -1
  3. package/dist/auth/account.d.ts +67 -0
  4. package/dist/auth/account.js +136 -0
  5. package/dist/auth/hosts.d.ts +4 -0
  6. package/dist/auth/hosts.js +4 -0
  7. package/dist/auth/index.d.ts +30 -5
  8. package/dist/auth/index.js +80 -12
  9. package/dist/catalog/catalog.gen.js +1067 -194
  10. package/dist/generated/index.d.ts +9 -0
  11. package/dist/generated/index.js +27 -0
  12. package/dist/generated/lexicons.d.ts +1436 -148
  13. package/dist/generated/lexicons.js +782 -23
  14. package/dist/generated/nsid.d.ts +14 -0
  15. package/dist/generated/nsid.js +14 -0
  16. package/dist/generated/nsid.json +14 -0
  17. package/dist/generated/types/pub/techne/draft/commons/moveAccountHandle.d.ts +3 -0
  18. package/dist/generated/types/pub/techne/draft/commons/moveAccountHandle.js +7 -0
  19. package/dist/generated/types/pub/techne/draft/identity/attest.d.ts +3 -0
  20. package/dist/generated/types/pub/techne/draft/identity/attest.js +7 -0
  21. package/dist/generated/types/pub/techne/draft/identity/beginAddMethod.d.ts +3 -0
  22. package/dist/generated/types/pub/techne/draft/identity/beginAddMethod.js +7 -0
  23. package/dist/generated/types/pub/techne/draft/identity/cancelPendingChange.d.ts +29 -0
  24. package/dist/generated/types/pub/techne/draft/identity/cancelPendingChange.js +27 -0
  25. package/dist/generated/types/pub/techne/draft/identity/defs.d.ts +22 -4
  26. package/dist/generated/types/pub/techne/draft/identity/defs.js +7 -0
  27. package/dist/generated/types/pub/techne/draft/identity/finishAddMethod.d.ts +6 -0
  28. package/dist/generated/types/pub/techne/draft/identity/finishAddMethod.js +14 -0
  29. package/dist/generated/types/pub/techne/draft/identity/fold.d.ts +3 -0
  30. package/dist/generated/types/pub/techne/draft/identity/fold.js +7 -0
  31. package/dist/generated/types/pub/techne/draft/identity/holdForPhone.d.ts +1 -1
  32. package/dist/generated/types/pub/techne/draft/identity/link.d.ts +3 -0
  33. package/dist/generated/types/pub/techne/draft/identity/link.js +7 -0
  34. package/dist/generated/types/pub/techne/draft/identity/listMethods.d.ts +6 -1
  35. package/dist/generated/types/pub/techne/draft/identity/manageMethods.d.ts +225 -0
  36. package/dist/generated/types/pub/techne/draft/identity/manageMethods.js +209 -0
  37. package/dist/generated/types/pub/techne/draft/identity/openAccountPage.d.ts +40 -0
  38. package/dist/generated/types/pub/techne/draft/identity/openAccountPage.js +55 -0
  39. package/dist/generated/types/pub/techne/draft/identity/resolve.d.ts +4 -0
  40. package/dist/generated/types/pub/techne/draft/identity/unlinkMethod.d.ts +6 -0
  41. package/dist/generated/types/pub/techne/draft/identity/unlinkMethod.js +7 -0
  42. package/dist/generated/types/pub/techne/draft/permissioned/putRecords.d.ts +2 -2
  43. package/dist/generated/types/pub/techne/draft/registry/blockIndex.d.ts +7 -1
  44. package/dist/generated/types/pub/techne/draft/registry/blockIndex.js +17 -3
  45. package/dist/generated/types/pub/techne/draft/registry/purgeType.d.ts +7 -1
  46. package/dist/generated/types/pub/techne/draft/registry/purgeType.js +17 -3
  47. package/dist/wasm/techne-wasm.gen.js +1 -1
  48. package/dist/wasm/techne-wasm2js.gen.js +11723 -11721
  49. package/package.json +2 -1
package/CHANGELOG.md CHANGED
@@ -3,6 +3,62 @@
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.4.0 (2026-11-14)
7
+
8
+ npm 0.4.0 and crate 0.4.0 are built from the same commit. Lexicons `v0.1.22-techne.69` to `v0.1.22-techne.80`
9
+ (commit `8bad036c`) with `techne-lexicon-check` `=0.3.8` to `=0.3.18` from crates.io, and the platform's published
10
+ API from platform `main` `ff01ca02c` to `5c4f180ba`. Codegen, the catalog and the WebAssembly are regenerated. Two
11
+ generated error classes are removed (below), so this is a major version (RELEASING.md). What changes for an app:
12
+
13
+ ### Removed (breaking)
14
+
15
+ - `ForbiddenError` from the generated `registry.purgeType` and `registry.blockIndex` types (techne-sdk/types/...,
16
+ and the root re-exports): the server never sent `Forbidden`; use `NotAuthorizedError`. No consumer imports
17
+ them (beacon, commons, sites checked 2026-11-14).
18
+
19
+ ### Changed
20
+
21
+ - Lexicons techne.79 and .80: error names now match what the platform sends. `registry.purgeType` and
22
+ `registry.blockIndex` declare `NotAuthorized`, `ProgramRefused` and `InvalidRequest` (the server answered
23
+ `NotAuthorized`, never `Forbidden`). `identity.openAccountPage` declares `NotAuthorized` (a bearer token that is
24
+ neither a device session nor an agent token, such as an app's OAuth token) and `ProgramRefused` (an agent
25
+ token or a program's token) in place of `Forbidden`. `commons.moveAccountHandle` gains `ProgramRefused`. The
26
+ operator methods' descriptions say they need the moderate scope.
27
+ - Lexicons techne.76 to .78: new `identity.openAccountPage` (`NSID.IDENTITY_OPEN_ACCOUNT_PAGE`, a one-time link
28
+ that opens the account page signed in; a browser or device session only). `identity.defs#methodView` gains
29
+ `programs`. `identity.manageMethods` (the identity PDS's signed hook; apps do not call it) gains the
30
+ `setPrograms`, `findKey` and `operator` ops and the `program` flag. New permission set `pub.techne.draft.authModerate` (the operator methods; our
31
+ sign-in page offers it to operators only, apps never ask for it).
32
+
33
+ - `identity.createLinkToken` and `identity.holdForPhone`: a held write's record may carry `"$name"` slots as well
34
+ as `"$subject"` and `"$now"`; the platform fills each with the proving account's name.
35
+ - `permissioned.putRecords`: a roster batch (one with any `pub.techne.draft.membership` write) is checked whole
36
+ first (a write putRecord would refuse before reading anything refuses the call, 400 `InvalidRequest`, nothing
37
+ written), then stops at its first refused write and reports every later write as `Conflict`, not written. As a
38
+ circle, every prefix of its membership writes must keep a manager (`LastManager`). A write's result can now be
39
+ `RateLimitExceeded` or `Forbidden`.
40
+ - Sign-in method rules (lexicons techne.70 to .74): new `identity.cancelPendingChange` and `identity.manageMethods`
41
+ (the identity PDS's signed hook; apps do not call it). `identity.defs#methodView` gains `passkey`, `nostr` and
42
+ `recoveryCodes` types, `recovery` and `frozenUntil`; new `identity.defs#pendingChange`. `listMethods` takes
43
+ `allTypes` and answers `pending`. `unlinkMethod` now waits 7 days (`status: pending`, `pending`) and can refuse
44
+ with `RecoveryProtected`. `identity.resolve` answers `frozen` and `frozenUntil`. `MethodFrozen` on `attest`,
45
+ `beginAddMethod`, `finishAddMethod`, and the platform's `completeMobileEmailSignIn`, `deleteAccount` and
46
+ `finishPhoneSignup`; `ProtectedAccount` (409) on `finishAddMethod`, `fold` and `link`. `deleteAccount` can
47
+ answer `scheduledFor` and `pending` when the deletion waits.
48
+ - `techne-sdk/auth`, sign-in at another server: when the Techne sign-in page hands an account on another server back
49
+ (`error=login_required&login_hint=<handle>`), `restore` starts the sign-in again at that handle's server (at most
50
+ `MAX_HANDBACKS`, 2, times) with the app's `state` and the scope the client metadata declares. `signIn` now always
51
+ sends a `state` of its own (`techne-sdk:<n>[:<the app's>]`); `redirectState`, and the `state` of an error
52
+ `restore` rejects with, still answer the app's. A restart that fails rejects with the hand-back error, the
53
+ failure as its `restartError`.
54
+ - `techne-sdk/auth`: new `openAccountSettings({ section })` and `accountSettingsUrl` open (or give) the account page,
55
+ `<the PDS's sign-in host>/me`, at `'profile'`, `'methods'` or `'delete'`. `section: 'delete'` is the link for
56
+ Apple's account-deletion rule; there is no delete API. With a platform-session client (`techne`), the page opens
57
+ signed in through `identity.openAccountPage`; on any refusal (an OAuth app's `connect` token always is), the
58
+ plain page. New exports only.
59
+ - Query: a calendar event with no stated end that starts at midnight in its own offset runs to the next midnight
60
+ (a day), not two hours.
61
+
6
62
  ## 0.3.8 (2026-11-12)
7
63
 
8
64
  npm catches up with the crate: npm 0.3.8 and crate 0.3.8 are built from the same commit, lexicons
@@ -19,6 +75,9 @@ removed or renamed. What an app on npm 0.3.4 gets (the details are in the crate
19
75
  `beginAddMethod` `SendFailed` (502); `finishAddMethod` `RateLimitExceeded` (429) and `UpstreamFailure` (502).
20
76
  - `permissioned.putRecord`, `putRecords`, `deleteRecord`, and the kept circle methods (`createGroup`, `leaveGroup`,
21
77
  `removeGroupMember`, `renameGroup`) can refuse with `LastManager` (409).
78
+ - `renameGroup` and `removeGroupMember` are now manager-only (role 40): a plain member, who could call them
79
+ before, gets 403 `NotAuthorized` (`removeGroupMember` also 403 `Forbidden` for a membership above the caller's
80
+ role, and 404 `NotFound` for no such circle).
22
81
  - `pub.techne.draft.heldAt.query`, and `summary.json` `emoji`.
23
82
 
24
83
  Since platform `main` `cebe9efcb` (the scopes branch, already in the platform `main` pinned here), for an app writing
package/README.md CHANGED
@@ -26,7 +26,7 @@ Every import goes through the package's `exports`, so the resolver has to read t
26
26
  | `techne-sdk/react` | `TechneProvider` / `useTechne` (the client in React), and `useEvent(uri)`: one commons event or place as its versions, with the check's verdict (React only) |
27
27
  | `techne-sdk/react/query` | the client's reads as hooks over TanStack Query (`useRecordQuery`, `useRecord`, `useVersions`, `defaultQueryClient`); needs `@tanstack/react-query` |
28
28
  | `techne-sdk/versions` | the same state without React: `eventState`, `verifyAnswer`, version labels |
29
- | `techne-sdk/auth` | sign-in ("Sign in with Techne"): `signIn`, `signUp`, `restore`, `signOut`, `clientMetadata`, `scopes`, `appKey`, `appSpace` (browser OAuth) |
29
+ | `techne-sdk/auth` | sign-in ("Sign in with Techne"): `signIn`, `signUp`, `restore`, `signOut`, `clientMetadata`, `scopes`, `appKey`, `appSpace` (browser OAuth); the account page: `openAccountSettings`, `accountSettingsUrl` |
30
30
  | `techne-sdk/connect` | `connect(session, platform?)` / `connectHosted(did, fetchHandler)` / `connectAnonymous(platform?)`: the client over one session, with its reads (`query`, `get`, `versions`, their options forms) and `put`; `bind(clients)` over clients made elsewhere |
31
31
  | `techne-sdk/put` | `put(techne, records, { deletes })`: the one write, deletes included (public deletes hinted to the platform); `put(techne, [], { deletes })` for deletes alone |
32
32
  | `techne-sdk/query` | the platform's generic queries: `listRecords`, `getRecords`, `compose` (several steps in one `composeRecords` call), hosts (`hostsOf`, `hostSteps`/`hostsFrom`) |
@@ -97,6 +97,8 @@ else {
97
97
  - **The app's private space:** `appSpace(session.did, clientId)` is `at://{did}/pub.techne.draft.space.private/{appKey}`, where `appKey(clientId)` is the client id hashed (base32, lowercase, no padding, of its SHA-256; the platform's `sidecar_rkey`). Write there with `put(techne, [{ record, space: appSpace(did, clientId) }])` and read with `permissioned.listRecords({ space })`. Only that person reads it, and only through this app. In development the client id is the loopback client's, `resolveClientId(options)` with the same options `signIn` took: it carries the scope, so it changes with the port, `types` and `everything`, and so does the space. Its scope names the space type without a key (an id cannot carry its own hash); Techne's PDS reads that keyless scope from a loopback client as its own space, adds the key when it calls the platform, and shows the own-space line on the consent page. The browser keeps one stored session per origin, so a page that switches between client ids (other `types`, another port's id) signs out first; `restore` hands back whichever session the origin holds.
98
98
  - **Development:** on `localhost` or `127.0.0.1` you can leave `clientId` out. The SDK then uses atproto's loopback client, so you don't need to host anything.
99
99
  - **Sessions:** the library refreshes tokens itself. `restore` returns the session, `null` when nobody is signed in, and rejects when a sign-in or refresh failed. `signOut({ clientId, session })` revokes the session. `onSessionDeleted` tells you when the library drops a session. A `state` passed to `signIn` comes back from `redirectState({ clientId })` on the page the redirect lands on.
100
+ - **Accounts on another server:** the Techne sign-in page also takes a handle from any server. When the account lives elsewhere, the page sends the person back to your redirect URI with `error=login_required&login_hint=<handle>`, and `restore` starts the sign-in again at that handle's server, with your `state` and the scope your client metadata declares; `restore` does not settle while the page navigates there. You write nothing for it; it is one reason to sign in through `signIn` and not hand-roll the OAuth. (The SDK sends its own `state`, `techne-sdk:<n>:<yours>`; `redirectState`, and the error `restore` rejects with, hand back yours.)
101
+ - **The account page and Delete account:** people manage their account (profile, ways to sign in, devices and apps, Delete account) on the account page at their PDS's sign-in host, never inside an app. `openAccountSettings()` opens it in a new tab; call it from the tap's handler. `openAccountSettings({ section: 'delete' })` opens it at Delete account: that is the link for Apple's account-deletion rule (the app still deletes its own data itself). There is no API that deletes an account. Sections are `'profile'`, `'methods'` and `'delete'`. Pass `session` (from `restore`) and it answers `false` without opening anything when the person signed in at another server, which has no Techne account page. Pass `open: (url) => …` to open it elsewhere (an in-app browser sheet in React Native). `accountSettingsUrl(options)` is the address alone. The host comes from the PDS's OAuth metadata, so a move of the sign-in host changes nothing for you. An app on a platform session (`connectHosted`) passes `techne` too, and the page opens already signed in through the platform's one-time link (`identity.openAccountPage`) where the platform and this SDK carry it; otherwise the page asks for a code.
100
102
  - **Another deployment:** `platform` names the platform's DID (`TECHNE_PLATFORM_DID` by default). `pds`, `plcUrl` and `handleDomain` name the PDS people sign in at, its PLC directory and its handle domain. Pass them the same way to every call.
101
103
 
102
104
  **Before the Techne release:** the techne.town defaults (`TECHNE_PLATFORM_DID`, the techne.town PDS and handle domain) go live at the Techne release. Until then, `signIn()` without `pds` fails: pass `pds`, `plcUrl`, `handleDomain` and `platform` explicitly, and ask the Techne team for the current staging values.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The account page: where a person manages their Techne account (profile, ways to sign in, devices and apps,
3
+ * Delete account). It lives on the PDS's sign-in host, at `<authorization server>/me`; the host is read from
4
+ * the PDS's OAuth metadata (`/.well-known/oauth-protected-resource`, its `authorization_servers`), never
5
+ * spelled here, so a move of the sign-in host changes nothing for an app.
6
+ *
7
+ * Apps never change sign-in methods or delete an account themselves: they link here, where the browser shows
8
+ * our address. For Apple's account-deletion rule an app offers "Delete account" as
9
+ * `openAccountSettings({ section: 'delete' })`, which opens the page at its Delete section (and deletes the
10
+ * app's own data itself). There is no delete API.
11
+ *
12
+ * Signed in already. Given a client holding a platform session (`techne`, from `connectHosted`), the page opens
13
+ * through the platform's one-time link (`pub.techne.draft.identity.openAccountPage`, `<account page>?handoff=`),
14
+ * so the person sees "Continue as @handle" instead of a code. The platform gives that link only to a browser
15
+ * or device session: a token minted through the PDS (an OAuth app's `connect`) is refused, and so is a
16
+ * platform without the method. Every refusal, failure or answer that is not exactly a link to this
17
+ * account page opens the plain page, which asks for a code. Security actions there still ask for a code or a
18
+ * passkey either way.
19
+ */
20
+ import type { OAuthSession } from '@atproto/oauth-client-browser';
21
+ import type { Clients } from '../connect.js';
22
+ /** The page's sections an app may open it at, and the anchor each is on the page. */
23
+ export declare const ACCOUNT_SECTIONS: {
24
+ /** Name, avatar, bio, handle. */
25
+ readonly profile: "profile";
26
+ /** Ways to sign in (and recovery). */
27
+ readonly methods: "ways";
28
+ /** Delete account: what an app links to for Apple's deletion rule. */
29
+ readonly delete: "delete";
30
+ };
31
+ export type AccountSection = keyof typeof ACCOUNT_SECTIONS;
32
+ /** What {@link accountSettingsUrl} takes. */
33
+ export interface AccountSettingsOptions {
34
+ /** Open the page at this section; the top when absent. */
35
+ section?: AccountSection;
36
+ /** The PDS whose account page it is; {@link TECHNE_TOWN_PDS} by default (as `signIn`'s `pds`). */
37
+ pds?: string;
38
+ /** The signed-in OAuth session (`restore`'s): when its sign-in server is not the PDS's, the account lives
39
+ * on another server, which has no Techne account page, and the answer is `null`. */
40
+ session?: Pick<OAuthSession, 'serverMetadata'>;
41
+ /** A client on a platform session (`connectHosted`): asks the platform for a one-time link that opens the
42
+ * page signed in. Without it (or when the platform refuses) the plain page. */
43
+ techne?: Pick<Clients, 'platform'>;
44
+ /** The fetch the PDS's metadata is read with; `globalThis.fetch` by default. */
45
+ fetch?: typeof globalThis.fetch;
46
+ }
47
+ /**
48
+ * The account page's address for these options: `<sign-in host>/me`, then `#<section>`; through the
49
+ * platform's one-time link when `techne` gets one. `null` when `session` signed in at another server (no
50
+ * Techne account page there). Rejects only when the PDS's metadata cannot be read.
51
+ */
52
+ export declare function accountSettingsUrl(o?: AccountSettingsOptions): Promise<string | null>;
53
+ /** What {@link openAccountSettings} takes. */
54
+ export interface OpenAccountSettingsOptions extends AccountSettingsOptions {
55
+ /** Opens the URL: an in-app browser sheet on a phone (Expo's `WebBrowser.openBrowserAsync`, say). Absent,
56
+ * a new browser tab. */
57
+ open?: (url: string) => unknown;
58
+ }
59
+ /**
60
+ * Open the account page (see {@link accountSettingsUrl}), at `section` when given:
61
+ * `openAccountSettings({ section: 'delete' })` is the link for Apple's account-deletion rule. Call it from the
62
+ * tap's handler: in a browser the tab is opened blank at once, inside the tap (a tab opened after awaiting
63
+ * the address is lost to popup blockers), then pointed at the page; a blocked tab opens the page here
64
+ * instead. With `open`, the address goes to it (required outside a browser). Answers `false`, opening nothing, when `session` signed in at
65
+ * another server (no Techne account page there); rejects when the PDS's metadata cannot be read.
66
+ */
67
+ export declare function openAccountSettings(o?: OpenAccountSettingsOptions): Promise<boolean>;
@@ -0,0 +1,136 @@
1
+ import { isLoopbackHost } from '@atproto/oauth-types';
2
+ import { TECHNE_TOWN_PDS } from './hosts.js';
3
+ /** The page's sections an app may open it at, and the anchor each is on the page. */
4
+ export const ACCOUNT_SECTIONS = {
5
+ /** Name, avatar, bio, handle. */
6
+ profile: 'profile',
7
+ /** Ways to sign in (and recovery). */
8
+ methods: 'ways',
9
+ /** Delete account: what an app links to for Apple's deletion rule. */
10
+ delete: 'delete',
11
+ };
12
+ /** How long to wait for the one-time link before opening the plain page. */
13
+ const LINK_WAIT_MS = 5000;
14
+ /** The sign-in server per PDS, read once (a failed read is not kept). */
15
+ const issuers = new Map();
16
+ /** `pds`'s OAuth authorization server: the first of its protected-resource metadata's
17
+ * `authorization_servers`, an origin (https, or http on a loopback host for development). */
18
+ async function issuerOf(pds, fetch) {
19
+ const base = pds.replace(/\/+$/, '');
20
+ let pending = issuers.get(base);
21
+ if (!pending) {
22
+ pending = (async () => {
23
+ const url = `${base}/.well-known/oauth-protected-resource`;
24
+ const res = await fetch(url);
25
+ if (!res.ok)
26
+ throw new Error(`techne-sdk/auth: ${url} answered ${res.status}`);
27
+ const doc = (await res.json());
28
+ const first = Array.isArray(doc?.authorization_servers) ? doc.authorization_servers[0] : undefined;
29
+ const issuer = typeof first === 'string' ? originOf(first) : null;
30
+ if (!issuer)
31
+ throw new Error(`techne-sdk/auth: ${url} names no usable authorization server`);
32
+ return issuer;
33
+ })();
34
+ pending.catch(() => issuers.delete(base));
35
+ issuers.set(base, pending);
36
+ }
37
+ return pending;
38
+ }
39
+ /** `url` as a bare origin when it is one (https, or http on localhost, 127.0.0.1 or [::1]), else `null`. */
40
+ function originOf(url) {
41
+ let u;
42
+ try {
43
+ u = new URL(url);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ if (!(u.protocol === 'https:' || (u.protocol === 'http:' && isLoopbackHost(u.hostname))))
49
+ return null;
50
+ if (u.username || u.password || u.search || u.hash || (u.pathname !== '/' && u.pathname !== ''))
51
+ return null;
52
+ return u.origin;
53
+ }
54
+ /**
55
+ * The account page's address for these options: `<sign-in host>/me`, then `#<section>`; through the
56
+ * platform's one-time link when `techne` gets one. `null` when `session` signed in at another server (no
57
+ * Techne account page there). Rejects only when the PDS's metadata cannot be read.
58
+ */
59
+ export async function accountSettingsUrl(o = {}) {
60
+ checkSection(o.section);
61
+ const issuer = await issuerOf(o.pds ?? TECHNE_TOWN_PDS, o.fetch ?? ((input, init) => globalThis.fetch(input, init)));
62
+ if (o.session && originOf(o.session.serverMetadata.issuer) !== issuer)
63
+ return null;
64
+ const page = `${issuer}/me`;
65
+ const hash = o.section ? `#${ACCOUNT_SECTIONS[o.section]}` : '';
66
+ const link = o.techne ? await oneTimeLink(o.techne, page) : null;
67
+ return `${link ?? page}${hash}`;
68
+ }
69
+ function checkSection(section) {
70
+ if (section !== undefined && !(typeof section === 'string' && Object.hasOwn(ACCOUNT_SECTIONS, section))) {
71
+ throw new TypeError(`techne-sdk/auth: section is one of ${Object.keys(ACCOUNT_SECTIONS).join(', ')} (got ${JSON.stringify(section)})`);
72
+ }
73
+ }
74
+ /** The platform's one-time link into `page`, or `null` (a refusal, a timeout, or an
75
+ * answer that is not `<page>?handoff=<base64url token>` exactly). Never throws. */
76
+ async function oneTimeLink(techne, page) {
77
+ let timer;
78
+ try {
79
+ const res = await Promise.race([
80
+ techne.platform.pub.techne.draft.identity.openAccountPage(),
81
+ new Promise((_, reject) => {
82
+ timer = setTimeout(() => reject(new Error('timeout')), LINK_WAIT_MS);
83
+ }),
84
+ ]);
85
+ // Checked at run time too: the answer comes off the wire.
86
+ const url = res.data.url;
87
+ const prefix = `${page}?handoff=`;
88
+ return typeof url === 'string' && url.startsWith(prefix) && /^[A-Za-z0-9_-]{1,128}$/.test(url.slice(prefix.length)) ? url : null;
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ finally {
94
+ if (timer !== undefined)
95
+ clearTimeout(timer);
96
+ }
97
+ }
98
+ /**
99
+ * Open the account page (see {@link accountSettingsUrl}), at `section` when given:
100
+ * `openAccountSettings({ section: 'delete' })` is the link for Apple's account-deletion rule. Call it from the
101
+ * tap's handler: in a browser the tab is opened blank at once, inside the tap (a tab opened after awaiting
102
+ * the address is lost to popup blockers), then pointed at the page; a blocked tab opens the page here
103
+ * instead. With `open`, the address goes to it (required outside a browser). Answers `false`, opening nothing, when `session` signed in at
104
+ * another server (no Techne account page there); rejects when the PDS's metadata cannot be read.
105
+ */
106
+ export async function openAccountSettings(o = {}) {
107
+ checkSection(o.section);
108
+ const w = o.open ? null : openBlankTab();
109
+ if (w)
110
+ w.opener = null;
111
+ let url;
112
+ try {
113
+ url = await accountSettingsUrl(o);
114
+ }
115
+ catch (e) {
116
+ w?.close();
117
+ throw e;
118
+ }
119
+ if (!url) {
120
+ w?.close();
121
+ return false;
122
+ }
123
+ if (o.open)
124
+ await o.open(url);
125
+ else if (w)
126
+ w.location.href = url;
127
+ else if (typeof globalThis.location?.assign === 'function')
128
+ globalThis.location.assign(url);
129
+ else
130
+ throw new TypeError('techne-sdk/auth: no browser window here; pass open (an in-app browser, say)');
131
+ return true;
132
+ }
133
+ /** A blank tab, opened synchronously; null when there is no window or the browser blocks it. */
134
+ function openBlankTab() {
135
+ return globalThis.open?.('about:blank', '_blank') ?? null;
136
+ }
@@ -0,0 +1,4 @@
1
+ /** The techne.town handle domain: a bare name signs in as `<name>.techne.town`. */
2
+ export declare const TECHNE_TOWN = "techne.town";
3
+ /** The techne.town PDS: where a sign-in with no handle, and every sign-up, starts. */
4
+ export declare const TECHNE_TOWN_PDS = "https://pds.techne.town";
@@ -0,0 +1,4 @@
1
+ /** The techne.town handle domain: a bare name signs in as `<name>.techne.town`. */
2
+ export const TECHNE_TOWN = 'techne.town';
3
+ /** The techne.town PDS: where a sign-in with no handle, and every sign-up, starts. */
4
+ export const TECHNE_TOWN_PDS = 'https://pds.techne.town';
@@ -56,19 +56,30 @@
56
56
  * refresh token revoked) is announced to {@link onSessionDeleted} listeners. The `state` a {@link signIn}
57
57
  * sent comes back from {@link redirectState} on the page the redirect lands on (the same `init()`).
58
58
  *
59
+ * Another server. The Techne sign-in page offers "your handle" for an account on any server; a handle it does
60
+ * not host comes back to the app's redirect URI as `error=login_required&login_hint=<handle>`, and
61
+ * {@link restore} then starts the sign-in again at that handle's PDS (at most {@link MAX_HANDBACKS} times),
62
+ * with the same `state` and the scope the client's metadata declares (the most it may ask for: a {@link signIn}
63
+ * with the same options as {@link clientMetadata} asks for exactly that). Meanwhile `restore` does not settle
64
+ * (the page is navigating). So an app never handles it, and never hand-rolls the OAuth. The SDK sends its own
65
+ * `state` (`techne-sdk:<n>[:<the app's>]`) to tell its requests apart; {@link redirectState} answers the app's.
66
+ *
67
+ * The account page. {@link openAccountSettings} opens the person's account page on their Techne PDS (profile,
68
+ * ways to sign in, devices, Delete account), at a section such as `'delete'`; {@link accountSettingsUrl} is its
69
+ * address. There is no API that deletes an account: an app links there.
70
+ *
59
71
  * One BrowserOAuthClient per client id, made on first use. Tests (and other runtimes) inject their own
60
72
  * with {@link setOAuthClientFactory}.
61
73
  */
62
74
  import type { AuthorizeOptions, OAuthSession } from '@atproto/oauth-client-browser';
63
75
  import { type OAuthClientMetadataInput } from '@atproto/oauth-types';
64
76
  import { TECHNE_PLATFORM_DID } from '../platform.js';
77
+ import { TECHNE_TOWN, TECHNE_TOWN_PDS } from './hosts.js';
65
78
  export { appKey, appSpace } from './app-key.js';
79
+ export { accountSettingsUrl, openAccountSettings, type AccountSection, type AccountSettingsOptions, type OpenAccountSettingsOptions } from './account.js';
66
80
  export { TECHNE_PLATFORM_DID };
67
81
  export type { OAuthSession };
68
- /** The techne.town handle domain: a bare name signs in as `<name>.techne.town`. */
69
- export declare const TECHNE_TOWN = "techne.town";
70
- /** The techne.town PDS: where a sign-in with no handle, and every sign-up, starts. */
71
- export declare const TECHNE_TOWN_PDS = "https://pds.techne.town";
82
+ export { TECHNE_TOWN, TECHNE_TOWN_PDS };
72
83
  /** The OAuth client the module drives: what it uses of BrowserOAuthClient. */
73
84
  export interface OAuthClientLike {
74
85
  init(refresh?: boolean): Promise<{
@@ -77,6 +88,10 @@ export interface OAuthClientLike {
77
88
  } | undefined>;
78
89
  signInRedirect(input: string, options?: AuthorizeOptions): Promise<unknown>;
79
90
  revoke(sub: string): Promise<void>;
91
+ /** The metadata the client signs in with (BrowserOAuthClient's): its `scope` is what a restarted sign-in asks for. */
92
+ readonly clientMetadata?: {
93
+ readonly scope?: string;
94
+ };
80
95
  }
81
96
  /** What a factory is given to make a client. */
82
97
  export interface ClientConfig {
@@ -184,8 +199,18 @@ export interface SignInOptions extends ClientOptions {
184
199
  /** Handed back by the redirect: {@link redirectState} answers it there. */
185
200
  state?: string;
186
201
  }
187
- /** Sign in: redirects to the person's PDS, and comes back to the app's redirect URI (then {@link restore}). */
202
+ /** Sign in: redirects to the person's PDS, and comes back to the app's redirect URI (then {@link restore}).
203
+ * When the sign-in page hands the person back because their account is on another server, {@link restore}
204
+ * starts this sign-in again there (see {@link MAX_HANDBACKS}). */
188
205
  export declare function signIn(o?: SignInOptions): Promise<void>;
206
+ /**
207
+ * How many times one sign-in is started again at another server. The Techne sign-in page (ePDS) hands a
208
+ * person whose account lives elsewhere back to the app's redirect URI as an OAuth error,
209
+ * `error=login_required&login_hint=<handle or DID>` with the request's `state` (ePDS pds-core
210
+ * `lib/handle-handback.ts`); {@link restore} then signs in again at that handle's PDS, which the library
211
+ * resolves. Two, so a second server that hands back once more still works and a loop of servers stops.
212
+ */
213
+ export declare const MAX_HANDBACKS = 2;
189
214
  /** {@link signIn} with `signUp: true`. */
190
215
  export declare function signUp(o?: Omit<SignInOptions, 'signUp'>): Promise<void>;
191
216
  /** The signed-in session, or `null` (see the module doc for the redirect, refresh and errors). */
@@ -1,15 +1,14 @@
1
1
  import { buildAtprotoLoopbackClientId, isLoopbackHost } from '@atproto/oauth-types';
2
- import { isValidNsid } from '@atproto/syntax';
2
+ import { isValidDid, isValidHandle, isValidNsid } from '@atproto/syntax';
3
3
  import { NSID } from '../generated/nsid.js';
4
4
  import { appviewRef, TECHNE_PLATFORM_DID } from '../platform.js';
5
5
  import { appKey } from './app-key.js';
6
+ import { TECHNE_TOWN, TECHNE_TOWN_PDS } from './hosts.js';
6
7
  import { PUBLIC_HOMES } from './placement.gen.js';
7
8
  export { appKey, appSpace } from './app-key.js';
9
+ export { accountSettingsUrl, openAccountSettings } from './account.js';
8
10
  export { TECHNE_PLATFORM_DID };
9
- /** The techne.town handle domain: a bare name signs in as `<name>.techne.town`. */
10
- export const TECHNE_TOWN = 'techne.town';
11
- /** The techne.town PDS: where a sign-in with no handle, and every sign-up, starts. */
12
- export const TECHNE_TOWN_PDS = 'https://pds.techne.town';
11
+ export { TECHNE_TOWN, TECHNE_TOWN_PDS };
13
12
  /** The default: a BrowserOAuthClient, loaded on first use (so the module imports under node). For an https
14
13
  * client id the library fetches the metadata the app serves; for a loopback id it builds it. */
15
14
  const browserFactory = async (config) => {
@@ -179,19 +178,67 @@ function signInTarget(handle, o = {}) {
179
178
  return h;
180
179
  return `${h}.${o.handleDomain ?? TECHNE_TOWN}`;
181
180
  }
182
- /** Sign in: redirects to the person's PDS, and comes back to the app's redirect URI (then {@link restore}). */
181
+ /** Sign in: redirects to the person's PDS, and comes back to the app's redirect URI (then {@link restore}).
182
+ * When the sign-in page hands the person back because their account is on another server, {@link restore}
183
+ * starts this sign-in again there (see {@link MAX_HANDBACKS}). */
183
184
  export async function signIn(o = {}) {
184
185
  const { scope } = resolveClient(o);
185
186
  const client = await oauthClient(o);
186
187
  // A sign-up is at the home PDS unless the app names another PDS by its URL.
187
188
  const input = o.signUp ? (o.handle && /^https:\/\//.test(o.handle) ? o.handle : homePds(o)) : signInTarget(o.handle, o);
188
- const options = { scope };
189
+ const options = { scope, state: wrapState(0, o.state) };
189
190
  if (o.signUp)
190
191
  options.prompt = 'create';
191
- if (o.state !== undefined)
192
- options.state = o.state;
193
192
  await client.signInRedirect(input, options);
194
193
  }
194
+ /**
195
+ * How many times one sign-in is started again at another server. The Techne sign-in page (ePDS) hands a
196
+ * person whose account lives elsewhere back to the app's redirect URI as an OAuth error,
197
+ * `error=login_required&login_hint=<handle or DID>` with the request's `state` (ePDS pds-core
198
+ * `lib/handle-handback.ts`); {@link restore} then signs in again at that handle's PDS, which the library
199
+ * resolves. Two, so a second server that hands back once more still works and a loop of servers stops.
200
+ */
201
+ export const MAX_HANDBACKS = 2;
202
+ /** The `state` the SDK sends: `techne-sdk:<hand-backs so far>`, then `:<the app's state>` when it gave one.
203
+ * Coming back with it shows the library found the request in its state store (so the error answers a
204
+ * sign-in this app started, from the server it went to; the library checks no `iss` on an error), and
205
+ * counts the restarts. Errors {@link restore} rejects with carry the app's state again. */
206
+ const STATE_PREFIX = 'techne-sdk:';
207
+ const wrapState = (hops, appState) => `${STATE_PREFIX}${hops}${appState === undefined ? '' : `:${appState}`}`;
208
+ /** The SDK's `state` read back: the hand-backs so far and the app's own state (`null`: none). A state not
209
+ * in the SDK's shape (a sign-in started before it wrapped states) is the app's as it is. */
210
+ function unwrapState(state) {
211
+ const m = state == null ? null : /^techne-sdk:(\d+)(?::([\s\S]*))?$/.exec(state);
212
+ if (!m)
213
+ return { hops: null, appState: state ?? null };
214
+ return { hops: Number(m[1]), appState: m[2] ?? null };
215
+ }
216
+ function hasState(e) {
217
+ return typeof e === 'object' && e !== null && typeof e.state === 'string';
218
+ }
219
+ /** `err` with the app's own `state` in place of the SDK's (an OAuthCallbackError carries the state sent). */
220
+ function appStateOn(err) {
221
+ if (hasState(err))
222
+ err.state = unwrapState(err.state).appState;
223
+ return err;
224
+ }
225
+ /** A hand-back to start again, read off what `init()` threw: an OAuthCallbackError (duck-typed: the library
226
+ * is loaded lazily) for a request of ours with `error=login_required` and a handle or DID in `login_hint`.
227
+ * Anything else is `null`, and the error stands. */
228
+ function handback(err) {
229
+ const e = err;
230
+ if (typeof e?.params?.get !== 'function')
231
+ return null;
232
+ const { hops, appState } = unwrapState(e.state);
233
+ if (hops === null || hops >= MAX_HANDBACKS)
234
+ return null;
235
+ if (e.params.get('error') !== 'login_required')
236
+ return null;
237
+ const hint = e.params.get('login_hint')?.trim();
238
+ if (!hint || !(isValidHandle(hint) || isValidDid(hint)))
239
+ return null;
240
+ return { hint, hops, appState };
241
+ }
195
242
  /** {@link signIn} with `signUp: true`. */
196
243
  export function signUp(o = {}) {
197
244
  return signIn({ ...o, signUp: true });
@@ -207,9 +254,30 @@ function restored(o) {
207
254
  }
208
255
  let pending = restoring.get(clientId);
209
256
  if (!pending) {
210
- pending = oauthClient(o)
211
- .then((c) => c.init())
212
- .then((r) => (r ? { session: r.session, state: r.state ?? null } : null));
257
+ pending = oauthClient(o).then(async (c) => {
258
+ let r;
259
+ try {
260
+ r = await c.init();
261
+ }
262
+ catch (err) {
263
+ const back = handback(err);
264
+ if (!back)
265
+ throw appStateOn(err);
266
+ // Start again at the handle's PDS, asking for what the client's metadata declares (the options
267
+ // restore was given need not name the types signIn asked for). In a browser this navigates away
268
+ // and never settles (the library rejects after 5 s if the person comes back).
269
+ const scope = c.clientMetadata?.scope ?? resolveClient(o).scope;
270
+ try {
271
+ await c.signInRedirect(back.hint, { scope, state: wrapState(back.hops + 1, back.appState ?? undefined) });
272
+ }
273
+ catch (cause) {
274
+ // The hand-back stands (its error and description), with why the restart failed.
275
+ throw Object.assign(appStateOn(err), { restartError: cause });
276
+ }
277
+ return null;
278
+ }
279
+ return r ? { session: r.session, state: unwrapState(r.state).appState } : null;
280
+ });
213
281
  pending.catch(() => restoring.delete(clientId));
214
282
  restoring.set(clientId, pending);
215
283
  }