@bbthorson/atproto-cf-auth 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,13 +11,13 @@ Worker.
11
11
  ## Server
12
12
 
13
13
  ```ts
14
- import { createBlueskyAuth, d1Store } from "@bbthorson/atproto-cf-auth/server";
14
+ import { createAtprotoAuth, d1Store } from "@bbthorson/atproto-cf-auth/server";
15
15
 
16
- let auth: ReturnType<typeof createBlueskyAuth> | undefined;
16
+ let auth: ReturnType<typeof createAtprotoAuth> | undefined;
17
17
 
18
18
  export default {
19
19
  async fetch(request: Request, env: Env) {
20
- auth ??= createBlueskyAuth({
20
+ auth ??= createAtprotoAuth({
21
21
  appName: "Bardcast",
22
22
  store: d1Store(env.DB), // or kvStore(env.KV)
23
23
  secret: env.SESSION_SECRET, // Worker secret, 32+ random characters
@@ -43,7 +43,9 @@ With Astro: call `auth.handle(context.request)` from middleware or from an
43
43
  `conditionalScopes`, `privateKeys` (see [Confidential client](#confidential-client)),
44
44
  `origin` (see [Outside a request](#outside-a-request)), `sessionTtlSeconds`
45
45
  (default 30 days), `cookieName`, `metadata` (logo, terms and privacy URLs for the
46
- consent screen), `onSignIn`, `handleResolver` and `requestLock` (see [Lock](#lock)).
46
+ consent screen), `mode`, `callbackPaths`, `onSignIn` and `onSignInError` (see
47
+ [Identity only](#identity-only)), `signUpServers` (see [Sign-up](#sign-up)),
48
+ `handleResolver` and `requestLock` (see [Lock](#lock)).
47
49
 
48
50
  **Identity lookups on Workers.** Workers refuse `redirect: "error"`, in `fetch()`
49
51
  and in `new Request()`, and AT-Proto's stock resolvers ask for it when they load
@@ -59,6 +61,111 @@ then `new Agent(session)` from `@atproto/api`. Tokens refresh on demand. Before
59
61
  you do this from concurrent requests (two `fetch`es from one page is enough),
60
62
  add the lock below.
61
63
 
64
+ ### Identity only
65
+
66
+ Apps that already have sessions of their own often need only one thing from
67
+ AT-Proto: proof that this person controls this DID. Set `mode: "identity"` and
68
+ the library proves it, then hands over. It keeps nothing: it sets no session
69
+ cookie, serves no `/session` or `/logout`, and revokes the OAuth tokens as soon
70
+ as the sign-in is verified.
71
+
72
+ ```ts
73
+ const auth = createAtprotoAuth({
74
+ appName: "Inbox",
75
+ store: postgresStore((text, params) => sql.query(text, params)),
76
+ secret: env.AUTH_SECRET,
77
+ basePath: "/api/v1/atproto",
78
+ mode: "identity",
79
+ async onSignIn({ user, flow }) {
80
+ const account = await findOrCreateAccount(user.did, user.handle);
81
+ if (account.disabled) return redirectTo("/login?error=account_disabled");
82
+ return startAppSession(account, flow.returnTo ?? "/"); // a Response that sets your cookie
83
+ },
84
+ onSignInError: ({ code, flow }) => redirectTo(`/login?error=${code}`),
85
+ });
86
+ ```
87
+
88
+ `onSignIn` (in either mode) may return a `Response` to answer the callback
89
+ itself; in the default `"session"` mode the library's session cookie is added to
90
+ it. A throw fails the sign-in as `callback_failed`. `onSignInError` gets every
91
+ failed callback (`access_denied`, `browser_mismatch`, `callback_failed`) with the
92
+ flow when it could be read, and may return a `Response` too; otherwise the
93
+ browser goes back with `?auth_error=<code>`.
94
+
95
+ ### Starting a sign-in from your own route
96
+
97
+ `POST {basePath}/login` covers the common case. For your own API shape, or to
98
+ carry something through the sign-in, call `authorize`:
99
+
100
+ ```ts
101
+ app.post("/api/v1/sign-in", async (c) => {
102
+ const { handle } = await c.req.json();
103
+ const result = await auth.authorize(c.req.raw, {
104
+ handle,
105
+ returnTo: "/inbox",
106
+ context: { flow: "creator" }, // handed back as `flow.context`
107
+ });
108
+ if (!result.ok) return c.json({ error: result.error }, result.status);
109
+ const res = c.json({ url: result.url });
110
+ for (const cookie of result.cookies) res.headers.append("set-cookie", cookie);
111
+ return res;
112
+ });
113
+ ```
114
+
115
+ `context` is any JSON value. It is kept with the OAuth state in your store,
116
+ sealed, and never travels through the browser or the authorization server, so it
117
+ may hold a secret. Keep it small.
118
+
119
+ **Callback paths.** List further paths in `callbackPaths` (`["/callback/mobile"]`)
120
+ and pick one per sign-in with `callbackPath`. Each is published as a redirect URI
121
+ and answered by `handle()`; a sign-in must come back to the path it was sent to.
122
+ Use one where flows need telling apart before their state is read, such as a
123
+ path a native app claims as a universal link.
124
+
125
+ **Unbound flows.** Every sign-in is tied to the browser that started it by a
126
+ nonce cookie, which is what stops login CSRF: someone finishing their own
127
+ sign-in in your browser. A native app that hands off to the system browser
128
+ can't keep that cookie. For that case only, `bindToBrowser: false` drops the
129
+ cookie, and the app must bind the flow itself: put a verifier only it holds in
130
+ `context`, and have `onSignIn` hand the result over only to whoever presents it.
131
+
132
+ ### Sign-up
133
+
134
+ Someone without an account can create one without leaving your sign-in flow:
135
+ the host's own sign-up page opens, and they come back signed in through the
136
+ same callback as any sign-in. This uses OAuth's `prompt=create`, which an
137
+ authorization server lists in its `prompt_values_supported` when it offers
138
+ sign-up (`https://bsky.social` does).
139
+
140
+ From the browser, `client.signUp()` or the element's `sign-up` attribute (see
141
+ [Browser](#browser)) posts `{ signUp: true }` to `/login`. The server starts at
142
+ the first of `signUpServers` (default `["https://bsky.social"]`); a request may
143
+ name another only if it's on that list, so a browser can't make your Worker
144
+ fetch an arbitrary URL. `signUpServers: []` turns sign-up off on that route.
145
+
146
+ From your own route, pass a server instead of a handle:
147
+
148
+ ```ts
149
+ const result = await auth.authorize(request, {
150
+ server: "https://bsky.social",
151
+ prompt: "create",
152
+ returnTo: "/welcome",
153
+ });
154
+ ```
155
+
156
+ Before anyone is sent away, the server's metadata is checked for `create`; a
157
+ server without it answers `sign_up_unavailable`. `authorize` takes any https
158
+ server, because the app chose it; don't pass one straight from a request.
159
+
160
+ A sign-up asks for `scope` only: `conditionalScopes` are tested against an
161
+ account's PDS, and there isn't one yet.
162
+
163
+ `server` without `prompt: "create"` also works: the host shows its own choice
164
+ between signing in and creating an account, which suits someone who knows their
165
+ host but not their handle. Other prompts pass through for any sign-in:
166
+ `"login"` to sign in again despite an existing session, `"select_account"` to
167
+ pick between accounts.
168
+
62
169
  ### Scopes
63
170
 
64
171
  `scope` is asked for at every sign-in. To act on someone's PDS, add granular
@@ -74,7 +181,7 @@ signing that person in.
74
181
  ```ts
75
182
  import { pdsServesMethod } from "@bbthorson/atproto-cf-auth/server";
76
183
 
77
- createBlueskyAuth({
184
+ createAtprotoAuth({
78
185
  // ...
79
186
  scope: "atproto repo:com.example.post",
80
187
  conditionalScopes: [
@@ -105,7 +212,7 @@ named in the metadata. Loopback development stays a public client.
105
212
 
106
213
  ```ts
107
214
  // once: node -e "import('@atproto/jwk-jose').then(async ({JoseKey}) => console.log(JSON.stringify((await JoseKey.generate(['ES256'], 'k1')).privateJwk)))"
108
- createBlueskyAuth({ /* ... */ privateKeys: [env.OAUTH_PRIVATE_KEY] });
215
+ createAtprotoAuth({ /* ... */ privateKeys: [env.OAUTH_PRIVATE_KEY] });
109
216
  ```
110
217
 
111
218
  To rotate, put the new key first and keep the old one until its sessions have
@@ -154,11 +261,11 @@ tokens in time. `durableObjectLock` closes the race: each user's restores queue
154
261
  at one Durable Object, wherever they run.
155
262
 
156
263
  ```ts
157
- import { AuthLock, createBlueskyAuth, durableObjectLock } from "@bbthorson/atproto-cf-auth/server";
264
+ import { AuthLock, createAtprotoAuth, durableObjectLock } from "@bbthorson/atproto-cf-auth/server";
158
265
 
159
266
  export { AuthLock }; // the Durable Object class, exported from your Worker's entry
160
267
 
161
- auth ??= createBlueskyAuth({
268
+ auth ??= createAtprotoAuth({
162
269
  // ...
163
270
  requestLock: durableObjectLock(env.AUTH_LOCK),
164
271
  });
@@ -194,6 +301,7 @@ request at another location may read the old tokens for up to a minute.
194
301
  | Store | Use when |
195
302
  |---|---|
196
303
  | `d1Store(env.DB)` | You have D1. Strongly consistent; creates a `bsky_auth` table on first use. |
304
+ | `postgresStore(query)` | You have Postgres: Neon (`(text, params) => sql.query(text, params)`), Hyperdrive or node-postgres (`pool.query`), PGlite. Strongly consistent. Creates a `bsky_auth` table on first use, or pass `createTable: false` and a `table` your migrations own. |
197
305
  | `kvStore(env.KV)` | You'd rather not add a database. Eventually consistent, so a sign-in that starts and finishes at different Cloudflare locations can fail. |
198
306
  | `memoryStore()` | Tests only. |
199
307
 
@@ -206,7 +314,9 @@ as a user. Changing the secret signs everyone out.
206
314
  - The session cookie is an opaque random id (`HttpOnly`, `SameSite=Lax`, `Secure`
207
315
  on https). The DID never sits in a cookie.
208
316
  - A short-lived nonce cookie ties each callback to the browser that started it,
209
- which blocks login CSRF.
317
+ which blocks login CSRF. (Unless a flow opts out with `bindToBrowser: false`;
318
+ see [Unbound flows](#starting-a-sign-in-from-your-own-route).)
319
+ - In `"identity"` mode no OAuth token outlives the callback.
210
320
  - `/login` and `/logout` refuse cross-site POSTs.
211
321
  - `returnTo` only accepts same-site paths, so it can't become an open redirect.
212
322
  - The client_id is derived from the request origin, so one deploy works on
@@ -226,6 +336,7 @@ import { createAuthClient, takeAuthError, HANDLE_INPUT_ATTRIBUTES } from "@bbtho
226
336
  const auth = createAuthClient(); // { basePath: "/auth" }
227
337
  const user = await auth.getUser(); // null when signed out
228
338
  await auth.signIn(handle, { returnTo: "/campaigns" }); // navigates to Bluesky; throws AuthError on failure
339
+ await auth.signUp({ returnTo: "/welcome" }); // someone without an account; see Sign-up
229
340
  await auth.signOut();
230
341
 
231
342
  // After a failed redirect, read ?auth_error= once (it's removed from the URL):
@@ -238,31 +349,121 @@ the handle before calling the server. Errors are `AuthError`s whose `message` is
238
349
  ready to show and whose `code` you can map to your own copy (`AUTH_ERROR_MESSAGES`
239
350
  holds the defaults). Spread `HANDLE_INPUT_ATTRIBUTES` onto your own `<input>` so
240
351
  phones don't capitalise the handle and password managers offer it.
241
- `searchHandles(query)` is an optional typeahead against Bluesky's public API.
352
+ `searchHandles(query)` is the typeahead search on its own, against Bluesky's public API.
353
+
354
+ ### Remembered accounts and typeahead
355
+
356
+ The pieces behind a "Continue as @alice" sign-in screen, for any framework:
357
+
358
+ ```ts
359
+ import { createRecentAccounts, createSignInController } from "@bbthorson/atproto-cf-auth/client";
360
+
361
+ const accounts = createRecentAccounts(); // localStorage; pass `storage` for React Native
362
+
363
+ // Once a sign-in has worked (the page the callback lands on):
364
+ const user = await auth.getUser();
365
+ if (user) await accounts.remember(user); // fills name and avatar from Bluesky's public API
366
+
367
+ // On the sign-in screen:
368
+ const controller = createSignInController({
369
+ signIn: (handle) => auth.signIn(handle), // or your own redirect; navigate away or throw
370
+ accounts,
371
+ typeahead: true, // off by default: it sends keystrokes to Bluesky
372
+ });
373
+ controller.subscribe(() => render(controller.getState()));
374
+ // state: { query, suggestions, activeIndex, accounts, status, error, pending }
375
+ // actions: setQuery, moveActive, closeSuggestions, submit, choose(account), forget(did), setError
376
+ ```
377
+
378
+ The controller owns everything that isn't markup: debounced, cancelled
379
+ searches that ignore late answers; handle normalisation and checking before
380
+ anything is sent; one sign-in at a time; and leaving the "loading" state when
381
+ the page comes back from the back/forward cache. In React, read it with
382
+ `useSyncExternalStore(controller.subscribe, controller.getState)` and draw it
383
+ with your own components.
384
+
385
+ Remembered accounts stay on the device and hold no tokens: DID, handle,
386
+ display name and an https avatar URL. Signing out doesn't forget them; the ✕
387
+ on a card does (`forget`). `lookupProfile(actor)` is the profile lookup on its
388
+ own.
242
389
 
243
390
  ### `<bsky-sign-in>`
244
391
 
245
392
  ```html
246
393
  <script type="module">import "@bbthorson/atproto-cf-auth/element";</script>
247
394
 
248
- <bsky-sign-in return-to="/campaigns" button-label="Continue with Bluesky"></bsky-sign-in>
395
+ <bsky-sign-in return-to="/campaigns" button-label="Continue" typeahead remember-accounts></bsky-sign-in>
249
396
  ```
250
397
 
251
- It renders into the light DOM with plain classes (`bsky-sign-in__form`,
252
- `__label`, `__input`, `__button`, `__error`) and sets `data-state="idle|loading|error"`,
253
- so your own CSS or Tailwind styles it. To use your own markup, put a `<form>`
254
- containing `<input name="handle">`, a button and an element with
255
- `data-bsky-error` inside the element; it adds behaviour and leaves your markup
256
- alone. The form still works with JavaScript off, because it posts to
257
- `/auth/login`.
398
+ It renders into the light DOM with plain classes and sets
399
+ `data-state="idle|loading|error"`, so your own CSS or Tailwind styles it:
400
+ `bsky-sign-in__form`, `__accounts`, `__account`, `__account-choose`,
401
+ `__account-forget`, `__divider`, `__label`, `__field`, `__input`,
402
+ `__suggestions`, `__suggestion`, `__avatar` (`__avatar--empty` without a
403
+ picture), `__identity`, `__name`, `__handle`, `__button`, `__error`.
404
+
405
+ For a starting point, import `@bbthorson/atproto-cf-auth/element.css`. It
406
+ inherits the page's font and text colour, and takes its other choices from
407
+ custom properties (`--bsky-sign-in-accent`, `-surface`, `-border`, `-muted`,
408
+ `-hover`, `-error`, `-radius`, `-card-radius`, `-avatar-size`, `-gap`), so a
409
+ few lines make it match the site.
410
+
411
+ To use your own markup, put a `<form>` containing `<input name="handle">`, a
412
+ button and an element with `data-bsky-error` inside the element; it adds
413
+ behaviour and leaves your markup alone. Add an element with
414
+ `data-bsky-suggestions` for the typeahead list, `data-bsky-accounts` for the
415
+ remembered accounts, and `data-bsky-divider` to show only when there are any.
416
+ The form still works with JavaScript off, because it posts to `/auth/login`.
258
417
 
259
418
  Attributes: `base-path`, `return-to`, `label`, `placeholder`, `button-label`,
260
- `loading-label`, `ignore-redirect-errors`. Event: `bsky-sign-in:error` with
261
- `{ code, message }`. Call `preventDefault()` on it to show the error yourself.
419
+ `loading-label`, `divider-label`, `typeahead`, `remember-accounts`, `sign-up`
420
+ (with `sign-up-prompt` and `sign-up-label`), `ignore-redirect-errors`. Event: `bsky-sign-in:error` with `{ code, message }`.
421
+ Call `preventDefault()` on it to show the error yourself. The input is an ARIA
422
+ combobox when `typeahead` is on: arrow keys move through suggestions, Enter
423
+ signs in as the highlighted one, Escape closes the list.
424
+
425
+ `sign-up` adds "Don't have an account? Create one" under the form (class
426
+ `bsky-sign-in__sign-up`, button `__sign-up-button`). Bare, it uses the server's
427
+ default sign-up host; `sign-up="https://pds.example"` names one, which must be on
428
+ the server's `signUpServers`. The button is a second submit button, so it works
429
+ without JavaScript as well. In your own markup, give a submit button
430
+ `data-bsky-sign-up name="signUp" value="1"`.
431
+
432
+ `remember-accounts` only shows accounts; remembering one is the call to
433
+ `accounts.remember(user)` above, on a page where you know the sign-in worked.
262
434
 
263
435
  In React, render `<bsky-sign-in>` like any element. Importing the module in a
264
436
  client component registers it, and the import is a no-op during SSR.
265
437
 
438
+ ## Upgrading
439
+
440
+ ### From 0.4 to 0.5
441
+
442
+ Three breaking changes, each a mechanical edit, and two new error codes:
443
+
444
+ - `createBlueskyAuth` is now `createAtprotoAuth`, and the types `BlueskyAuth`
445
+ and `BlueskyAuthOptions` are `AtprotoAuth` and `AtprotoAuthOptions`. Nothing in
446
+ the library is specific to Bluesky's servers.
447
+ - `onSignIn` takes one object: `onSignIn: (user, request) => …` becomes
448
+ `onSignIn: ({ user, request }) => …`. It also gets `flow`, and may now return a
449
+ `Response`.
450
+ - The default error copy for `invalid_handle` and `authorize_failed` no longer
451
+ says "Bluesky", and `<bsky-sign-in>`'s default label is
452
+ "Bluesky or Atmosphere handle". Apps that show `AUTH_ERROR_MESSAGES` or the
453
+ default label change wording; apps with their own copy see nothing.
454
+
455
+ `AuthErrorCode` gains `invalid_server` and `sign_up_unavailable`. A `switch`
456
+ over it that the compiler checks for exhaustiveness needs the two cases.
457
+
458
+ New, and opt-in: `mode: "identity"`, `authorize()`, `callbackPaths`,
459
+ `bindToBrowser: false`, `onSignInError`, sign-up (`server`, `prompt`,
460
+ `signUpServers`, `client.signUp()`, the element's `sign-up`), and
461
+ `postgresStore`.
462
+
463
+ Unchanged on purpose, so nobody is signed out and no stylesheet breaks: the
464
+ cookie names (`bsky_sid`, `bsky_auth_nonce`), the routes under `basePath`, the
465
+ `<bsky-sign-in>` tag and its class names, and what's in the store.
466
+
266
467
  ## Develop
267
468
 
268
469
  ```bash
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Accounts this browser has signed in with, for a "Continue as @alice" card
3
+ * above the handle field.
4
+ *
5
+ * Kept on the device only (`localStorage` by default), never sent anywhere.
6
+ * Holds what's needed to draw the card and start a sign-in: DID, handle,
7
+ * display name and avatar URL. No tokens.
8
+ *
9
+ * Remember an account once you know the sign-in worked: on the page the
10
+ * callback lands on, after `getUser()` returns someone.
11
+ *
12
+ * const accounts = createRecentAccounts();
13
+ * const user = await auth.getUser();
14
+ * if (user) await accounts.remember(user);
15
+ *
16
+ * Signing out doesn't forget the account; that is what lets the next sign-in
17
+ * take one tap. People remove it with the card's ✕ (`forget`).
18
+ */
19
+ export interface RecentAccount {
20
+ did: string;
21
+ handle: string;
22
+ displayName?: string;
23
+ /** An https URL. Anything else is dropped when the account is stored. */
24
+ avatar?: string;
25
+ /** ISO timestamp of the last time this account was remembered. */
26
+ lastUsedAt: string;
27
+ }
28
+ /** What `remember` accepts: a `User` from `getUser()` is enough. */
29
+ export interface AccountInput {
30
+ did: string;
31
+ handle?: string | undefined;
32
+ displayName?: string | undefined;
33
+ avatar?: string | undefined;
34
+ }
35
+ /**
36
+ * Where the list lives. `localStorage` fits as it is; on React Native, wrap
37
+ * SecureStore or AsyncStorage (either may return promises).
38
+ */
39
+ export interface AccountStorage {
40
+ getItem(key: string): string | null | undefined | Promise<string | null | undefined>;
41
+ setItem(key: string, value: string): void | Promise<void>;
42
+ removeItem(key: string): void | Promise<void>;
43
+ }
44
+ export interface RecentAccountsOptions {
45
+ /** Default: `localStorage`, where it exists and can be written. `null` keeps the list in memory only. */
46
+ storage?: AccountStorage | null;
47
+ /** Default `atproto-cf-auth:recent-accounts`. */
48
+ key?: string;
49
+ /** Most accounts kept, newest first. Default 3. */
50
+ max?: number;
51
+ /**
52
+ * Fill in a missing handle, display name or avatar from Bluesky's public
53
+ * profile API when remembering. Default true. This sends the DID (only) to
54
+ * `public.api.bsky.app`.
55
+ */
56
+ lookup?: boolean;
57
+ fetch?: typeof fetch;
58
+ }
59
+ export interface RecentAccounts {
60
+ /** Newest first. Never throws: unreadable storage reads as an empty list. */
61
+ list(): Promise<RecentAccount[]>;
62
+ /**
63
+ * Put the account at the top of the list, looking up whatever profile
64
+ * details are missing. Resolves to the stored entry, or `null` if no handle
65
+ * could be found for it (a card needs one).
66
+ */
67
+ remember(account: AccountInput): Promise<RecentAccount | null>;
68
+ forget(did: string): Promise<void>;
69
+ clear(): Promise<void>;
70
+ /** Called after every change made through this object. */
71
+ subscribe(listener: (accounts: RecentAccount[]) => void): () => void;
72
+ }
73
+ export declare const RECENT_ACCOUNTS_KEY = "atproto-cf-auth:recent-accounts";
74
+ export declare function createRecentAccounts(options?: RecentAccountsOptions): RecentAccounts;
75
+ export interface ProfileSummary {
76
+ did: string;
77
+ handle: string;
78
+ displayName?: string;
79
+ avatar?: string;
80
+ }
81
+ /**
82
+ * A handle, display name and avatar for a DID or handle, from Bluesky's
83
+ * public AppView. `null` when it doesn't answer or doesn't know the account
84
+ * (accounts that never used Bluesky have no profile there).
85
+ */
86
+ export declare function lookupProfile(actor: string, options?: {
87
+ fetch?: typeof fetch;
88
+ signal?: AbortSignal;
89
+ }): Promise<ProfileSummary | null>;
90
+ /** Only https URLs reach an `<img src>`. */
91
+ export declare function httpsUrl(value: unknown): string | undefined;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Accounts this browser has signed in with, for a "Continue as @alice" card
3
+ * above the handle field.
4
+ *
5
+ * Kept on the device only (`localStorage` by default), never sent anywhere.
6
+ * Holds what's needed to draw the card and start a sign-in: DID, handle,
7
+ * display name and avatar URL. No tokens.
8
+ *
9
+ * Remember an account once you know the sign-in worked: on the page the
10
+ * callback lands on, after `getUser()` returns someone.
11
+ *
12
+ * const accounts = createRecentAccounts();
13
+ * const user = await auth.getUser();
14
+ * if (user) await accounts.remember(user);
15
+ *
16
+ * Signing out doesn't forget the account; that is what lets the next sign-in
17
+ * take one tap. People remove it with the card's ✕ (`forget`).
18
+ */
19
+ export const RECENT_ACCOUNTS_KEY = "atproto-cf-auth:recent-accounts";
20
+ export function createRecentAccounts(options = {}) {
21
+ const key = options.key ?? RECENT_ACCOUNTS_KEY;
22
+ const max = Math.max(1, options.max ?? 3);
23
+ const storage = options.storage === undefined ? defaultStorage() : options.storage;
24
+ const lookup = options.lookup ?? true;
25
+ const listeners = new Set();
26
+ let memory = [];
27
+ async function read() {
28
+ if (!storage)
29
+ return memory;
30
+ try {
31
+ const raw = await storage.getItem(key);
32
+ return raw ? parseAccounts(raw) : [];
33
+ }
34
+ catch {
35
+ return [];
36
+ }
37
+ }
38
+ async function write(accounts) {
39
+ memory = accounts;
40
+ if (storage) {
41
+ try {
42
+ if (accounts.length)
43
+ await storage.setItem(key, JSON.stringify(accounts));
44
+ else
45
+ await storage.removeItem(key);
46
+ }
47
+ catch {
48
+ // Private mode or a full quota: the list just isn't kept.
49
+ }
50
+ }
51
+ for (const listener of listeners)
52
+ listener(accounts);
53
+ }
54
+ return {
55
+ list: read,
56
+ async remember(input) {
57
+ if (!input.did.startsWith("did:"))
58
+ return null;
59
+ const known = (await read()).find((a) => a.did === input.did);
60
+ let handle = input.handle ?? known?.handle;
61
+ let displayName = input.displayName ?? known?.displayName;
62
+ let avatar = input.avatar ?? known?.avatar;
63
+ if (lookup && (!input.handle || !displayName || !avatar)) {
64
+ const profile = await lookupProfile(input.did, options.fetch ? { fetch: options.fetch } : {});
65
+ if (profile) {
66
+ handle = input.handle ?? profile.handle;
67
+ displayName = input.displayName ?? profile.displayName ?? displayName;
68
+ avatar = input.avatar ?? profile.avatar ?? avatar;
69
+ }
70
+ }
71
+ if (!handle || handle === "handle.invalid")
72
+ return null;
73
+ const entry = toAccount({ did: input.did, handle, displayName, avatar, lastUsedAt: new Date().toISOString() });
74
+ if (!entry)
75
+ return null;
76
+ const rest = (await read()).filter((a) => a.did !== entry.did);
77
+ await write([entry, ...rest].slice(0, max));
78
+ return entry;
79
+ },
80
+ async forget(did) {
81
+ const accounts = await read();
82
+ const next = accounts.filter((a) => a.did !== did);
83
+ if (next.length !== accounts.length)
84
+ await write(next);
85
+ },
86
+ async clear() {
87
+ await write([]);
88
+ },
89
+ subscribe(listener) {
90
+ listeners.add(listener);
91
+ return () => listeners.delete(listener);
92
+ },
93
+ };
94
+ }
95
+ /**
96
+ * A handle, display name and avatar for a DID or handle, from Bluesky's
97
+ * public AppView. `null` when it doesn't answer or doesn't know the account
98
+ * (accounts that never used Bluesky have no profile there).
99
+ */
100
+ export async function lookupProfile(actor, options = {}) {
101
+ const url = new URL("https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile");
102
+ url.searchParams.set("actor", actor);
103
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
104
+ try {
105
+ const res = await doFetch(url, options.signal ? { signal: options.signal } : {});
106
+ if (!res.ok)
107
+ return null;
108
+ const body = await res.json();
109
+ if (!isRecord(body) || typeof body["did"] !== "string" || typeof body["handle"] !== "string")
110
+ return null;
111
+ const displayName = typeof body["displayName"] === "string" && body["displayName"].trim() ? body["displayName"] : undefined;
112
+ const avatar = httpsUrl(body["avatar"]);
113
+ return {
114
+ did: body["did"],
115
+ handle: body["handle"],
116
+ ...(displayName ? { displayName } : {}),
117
+ ...(avatar ? { avatar } : {}),
118
+ };
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ function parseAccounts(raw) {
125
+ let value;
126
+ try {
127
+ value = JSON.parse(raw);
128
+ }
129
+ catch {
130
+ return [];
131
+ }
132
+ if (!Array.isArray(value))
133
+ return [];
134
+ return value.flatMap((item) => {
135
+ const account = isRecord(item) ? toAccount(item) : null;
136
+ return account ? [account] : [];
137
+ });
138
+ }
139
+ function toAccount(item) {
140
+ const { did, handle, displayName, lastUsedAt } = item;
141
+ if (typeof did !== "string" || !did.startsWith("did:"))
142
+ return null;
143
+ if (typeof handle !== "string" || !handle)
144
+ return null;
145
+ const avatar = httpsUrl(item["avatar"]);
146
+ return {
147
+ did,
148
+ handle,
149
+ ...(typeof displayName === "string" && displayName ? { displayName } : {}),
150
+ ...(avatar ? { avatar } : {}),
151
+ lastUsedAt: typeof lastUsedAt === "string" ? lastUsedAt : new Date(0).toISOString(),
152
+ };
153
+ }
154
+ /** Only https URLs reach an `<img src>`. */
155
+ export function httpsUrl(value) {
156
+ if (typeof value !== "string")
157
+ return undefined;
158
+ try {
159
+ return new URL(value).protocol === "https:" ? value : undefined;
160
+ }
161
+ catch {
162
+ return undefined;
163
+ }
164
+ }
165
+ function isRecord(value) {
166
+ return typeof value === "object" && value !== null && !Array.isArray(value);
167
+ }
168
+ function defaultStorage() {
169
+ try {
170
+ if (typeof localStorage === "undefined")
171
+ return null;
172
+ return localStorage;
173
+ }
174
+ catch {
175
+ // Reading `localStorage` itself throws where site data is blocked.
176
+ return null;
177
+ }
178
+ }
179
+ //# sourceMappingURL=accounts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accounts.js","sourceRoot":"","sources":["../src/accounts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AA6DH,MAAM,CAAC,MAAM,mBAAmB,GAAG,iCAAiC,CAAC;AAErE,MAAM,UAAU,oBAAoB,CAAC,UAAiC,EAAE;IACtE,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,mBAAmB,CAAC;IAC/C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAC1C,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;IACnF,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC;IACtC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAuC,CAAC;IACjE,IAAI,MAAM,GAAoB,EAAE,CAAC;IAEjC,KAAK,UAAU,IAAI;QACjB,IAAI,CAAC,OAAO;YAAE,OAAO,MAAM,CAAC;QAC5B,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YACvC,OAAO,GAAG,CA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IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,cAAc;IACrB,IAAI,CAAC;QACH,IAAI,OAAO,YAAY,KAAK,WAAW;YAAE,OAAO,IAAI,CAAC;QACrD,OAAO,YAAY,CAAC;IACtB,CAAC;IAAC,MAAM,CAAC;QACP,mEAAmE;QACnE,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
package/dist/client.d.ts CHANGED
@@ -4,7 +4,10 @@
4
4
  * wrap it in whatever state model they use.
5
5
  */
6
6
  import { AuthError, type User } from "./shared.js";
7
- export { AUTH_ERROR_MESSAGES, AUTH_ERROR_PARAM, AuthError, isAuthErrorCode, isValidHandle, normalizeHandle, type AuthErrorCode, type User, } from "./shared.js";
7
+ export { AUTH_ERROR_MESSAGES, AUTH_ERROR_PARAM, AuthError, isAuthErrorCode, isValidHandle, normalizeHandle, normalizeServer, type AuthErrorCode, type User, } from "./shared.js";
8
+ export { createRecentAccounts, lookupProfile, RECENT_ACCOUNTS_KEY, type AccountInput, type AccountStorage, type ProfileSummary, type RecentAccount, type RecentAccounts, type RecentAccountsOptions, } from "./accounts.js";
9
+ export { searchHandles, type HandleSuggestion } from "./search.js";
10
+ export { createSignInController, type SignInController, type SignInControllerOptions, type SignInState, type SignInStatus, } from "./controller.js";
8
11
  export interface AuthClientOptions {
9
12
  /** Must match the server's `basePath`. Default `/auth`. */
10
13
  basePath?: string;
@@ -16,6 +19,14 @@ export interface SignInOptions {
16
19
  /** Same-site path to land on after sign-in. Default: the server's `redirectTo`. */
17
20
  returnTo?: string;
18
21
  }
22
+ export interface SignUpOptions extends SignInOptions {
23
+ /**
24
+ * The server to create the account on. It must be on the server's
25
+ * `signUpServers` list; default: the first one there (`https://bsky.social`
26
+ * unless the app changed it).
27
+ */
28
+ server?: string;
29
+ }
19
30
  export interface AuthClient {
20
31
  /** The signed-in user, or `null`. Throws `AuthError("network_error")` if the server is unreachable. */
21
32
  getUser(): Promise<User | null>;
@@ -25,6 +36,13 @@ export interface AuthClient {
25
36
  * failure throws an `AuthError` whose `message` is ready to show.
26
37
  */
27
38
  signIn(handle: string, options?: SignInOptions): Promise<void>;
39
+ /**
40
+ * For someone without an account: asks the server to start a sign-up
41
+ * (`prompt=create`) and navigates to the host's account-creation page. They
42
+ * come back signed in, through the same callback as a sign-in. Throws an
43
+ * `AuthError` (`sign_up_unavailable`, `invalid_server`, …) on failure.
44
+ */
45
+ signUp(options?: SignUpOptions): Promise<void>;
28
46
  signOut(): Promise<void>;
29
47
  }
30
48
  export declare function createAuthClient(options?: AuthClientOptions): AuthClient;
@@ -50,19 +68,3 @@ export declare const HANDLE_INPUT_ATTRIBUTES: {
50
68
  readonly enterkeyhint: "go";
51
69
  readonly placeholder: "you.bsky.social";
52
70
  };
53
- export interface HandleSuggestion {
54
- did: string;
55
- handle: string;
56
- displayName?: string;
57
- avatar?: string;
58
- }
59
- /**
60
- * Handle typeahead from Bluesky's public AppView. Optional, and it sends what
61
- * the person types to Bluesky as they type, so only use it where that's fine.
62
- * Pass an `AbortSignal` and abort the previous call on each keystroke.
63
- */
64
- export declare function searchHandles(query: string, options?: {
65
- limit?: number;
66
- signal?: AbortSignal;
67
- fetch?: typeof fetch;
68
- }): Promise<HandleSuggestion[]>;