@bbthorson/atproto-cf-auth 0.2.1 → 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.
- package/README.md +152 -15
- package/dist/accounts.d.ts +91 -0
- package/dist/accounts.js +179 -0
- package/dist/accounts.js.map +1 -0
- package/dist/client.d.ts +3 -16
- package/dist/client.js +3 -28
- package/dist/client.js.map +1 -1
- package/dist/controller.d.ts +86 -0
- package/dist/controller.js +154 -0
- package/dist/controller.js.map +1 -0
- package/dist/element.css +254 -0
- package/dist/element.js +246 -56
- package/dist/element.js.map +1 -1
- package/dist/search.d.ts +16 -0
- package/dist/search.js +38 -0
- package/dist/search.js.map +1 -0
- package/dist/server/auth.d.ts +60 -1
- package/dist/server/auth.js +159 -11
- package/dist/server/auth.js.map +1 -1
- package/dist/server/handoff.d.ts +49 -0
- package/dist/server/handoff.js +97 -0
- package/dist/server/handoff.js.map +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +2 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/scopes.d.ts +57 -0
- package/dist/server/scopes.js +84 -0
- package/dist/server/scopes.js.map +1 -0
- package/package.json +8 -5
package/README.md
CHANGED
|
@@ -39,10 +39,11 @@ With Astro: call `auth.handle(context.request)` from middleware or from an
|
|
|
39
39
|
`src/pages/auth/[...route].ts` endpoint.
|
|
40
40
|
|
|
41
41
|
**Options:** `basePath` (default `/auth`), `redirectTo` (default `/`), `scope`
|
|
42
|
-
(default `atproto`, which proves identity only;
|
|
43
|
-
|
|
44
|
-
`
|
|
45
|
-
|
|
42
|
+
(default `atproto`, which proves identity only; see [Scopes](#scopes)),
|
|
43
|
+
`conditionalScopes`, `privateKeys` (see [Confidential client](#confidential-client)),
|
|
44
|
+
`origin` (see [Outside a request](#outside-a-request)), `sessionTtlSeconds`
|
|
45
|
+
(default 30 days), `cookieName`, `metadata` (logo, terms and privacy URLs for the
|
|
46
|
+
consent screen), `onSignIn`, `handleResolver` and `requestLock` (see [Lock](#lock)).
|
|
46
47
|
|
|
47
48
|
**Identity lookups on Workers.** Workers refuse `redirect: "error"`, in `fetch()`
|
|
48
49
|
and in `new Request()`, and AT-Proto's stock resolvers ask for it when they load
|
|
@@ -58,6 +59,88 @@ then `new Agent(session)` from `@atproto/api`. Tokens refresh on demand. Before
|
|
|
58
59
|
you do this from concurrent requests (two `fetch`es from one page is enough),
|
|
59
60
|
add the lock below.
|
|
60
61
|
|
|
62
|
+
### Scopes
|
|
63
|
+
|
|
64
|
+
`scope` is asked for at every sign-in. To act on someone's PDS, add granular
|
|
65
|
+
scopes: `repo:com.example.post` to write a collection, `rpc:com.example.method?aud=*`
|
|
66
|
+
to call another service with auth their PDS signs, `space:…` for permissioned
|
|
67
|
+
spaces. (`transition:generic` still works, and grants everything.)
|
|
68
|
+
|
|
69
|
+
Some scopes only work on some PDSes. Space scopes asked of a PDS without spaces
|
|
70
|
+
fail the whole sign-in with `invalid_scope`, not just the feature. List those as
|
|
71
|
+
`conditionalScopes`: each is asked for only when its test passes for the PDS
|
|
72
|
+
signing that person in.
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { pdsServesMethod } from "@bbthorson/atproto-cf-auth/server";
|
|
76
|
+
|
|
77
|
+
createBlueskyAuth({
|
|
78
|
+
// ...
|
|
79
|
+
scope: "atproto repo:com.example.post",
|
|
80
|
+
conditionalScopes: [
|
|
81
|
+
{
|
|
82
|
+
scope: "space:com.example.notes?authority=*&skey=*&action=read&action=create",
|
|
83
|
+
when: pdsServesMethod("com.atproto.space.getDelegationToken"),
|
|
84
|
+
},
|
|
85
|
+
],
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`pdsServesMethod` asks the PDS's `community.lexicon.service.describe`, a
|
|
90
|
+
community convention for listing the methods a service serves, and fails the
|
|
91
|
+
test (leaving the scope off) when the PDS doesn't answer. `when` can be any
|
|
92
|
+
function of `{ did, pds, issuer }`.
|
|
93
|
+
|
|
94
|
+
The client metadata publishes `scope` and every conditional scope, whichever a
|
|
95
|
+
given sign-in asks for. That `scope` is the most the client may ever ask for, and
|
|
96
|
+
some authorization servers reject a request for anything beyond it.
|
|
97
|
+
|
|
98
|
+
### Confidential client
|
|
99
|
+
|
|
100
|
+
Pass `privateKeys` (ES256 private JWKs, each with a `kid`) to authenticate token
|
|
101
|
+
requests with `private_key_jwt`. Authorization servers give confidential clients
|
|
102
|
+
much longer sessions than public ones, which matters when an app acts for people
|
|
103
|
+
between their visits. The public halves are served at `{basePath}/jwks.json` and
|
|
104
|
+
named in the metadata. Loopback development stays a public client.
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
// 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] });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
To rotate, put the new key first and keep the old one until its sessions have
|
|
112
|
+
refreshed.
|
|
113
|
+
|
|
114
|
+
### Outside a request
|
|
115
|
+
|
|
116
|
+
`getOAuthSession(request)` finds the signed-in person from their cookie. For
|
|
117
|
+
work with no request (a queue consumer, a scheduled job), use
|
|
118
|
+
`await auth.restore(did)`, which returns the stored session for that DID, or
|
|
119
|
+
`null`. The client identity is named for an origin, so set the `origin` option
|
|
120
|
+
(`https://app.example`) or pass `{ origin }`.
|
|
121
|
+
|
|
122
|
+
### Sessions handed over
|
|
123
|
+
|
|
124
|
+
Some authorization servers hand an app a session for another account outside
|
|
125
|
+
the redirect flow: a group host creating a group account for the app, say.
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
const { did, session, response } = await auth.obtainSession(
|
|
129
|
+
"https://groups.example/xrpc/fyi.opensocial.provisionGroup",
|
|
130
|
+
{ handle: "thornwood", displayName: "Thornwood" },
|
|
131
|
+
{ headers: { authorization: `Bearer ${serviceAuthFromTheFounder}` } },
|
|
132
|
+
);
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
It POSTs the body as JSON the way a token request is made: with the app's
|
|
136
|
+
`client_id` (and a client assertion when confidential) and a DPoP proof for a
|
|
137
|
+
fresh key, answering one nonce challenge. The response must hold an OAuth token
|
|
138
|
+
response at `session` or as its whole body. The session is kept only if the
|
|
139
|
+
endpoint belongs to the account's own authorization server, then stored like a
|
|
140
|
+
sign-in's, so `restore(did)` returns it from then on. Otherwise it throws
|
|
141
|
+
`ObtainSessionError`, whose `error` is the endpoint's code or `NoSession`,
|
|
142
|
+
`WrongAuthServer` or `UnresolvableAccount`.
|
|
143
|
+
|
|
61
144
|
### Lock
|
|
62
145
|
|
|
63
146
|
A refresh token can be used once. When two requests for the same user land on
|
|
@@ -155,27 +238,81 @@ the handle before calling the server. Errors are `AuthError`s whose `message` is
|
|
|
155
238
|
ready to show and whose `code` you can map to your own copy (`AUTH_ERROR_MESSAGES`
|
|
156
239
|
holds the defaults). Spread `HANDLE_INPUT_ATTRIBUTES` onto your own `<input>` so
|
|
157
240
|
phones don't capitalise the handle and password managers offer it.
|
|
158
|
-
`searchHandles(query)` is
|
|
241
|
+
`searchHandles(query)` is the typeahead search on its own, against Bluesky's public API.
|
|
242
|
+
|
|
243
|
+
### Remembered accounts and typeahead
|
|
244
|
+
|
|
245
|
+
The pieces behind a "Continue as @alice" sign-in screen, for any framework:
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
import { createRecentAccounts, createSignInController } from "@bbthorson/atproto-cf-auth/client";
|
|
249
|
+
|
|
250
|
+
const accounts = createRecentAccounts(); // localStorage; pass `storage` for React Native
|
|
251
|
+
|
|
252
|
+
// Once a sign-in has worked (the page the callback lands on):
|
|
253
|
+
const user = await auth.getUser();
|
|
254
|
+
if (user) await accounts.remember(user); // fills name and avatar from Bluesky's public API
|
|
255
|
+
|
|
256
|
+
// On the sign-in screen:
|
|
257
|
+
const controller = createSignInController({
|
|
258
|
+
signIn: (handle) => auth.signIn(handle), // or your own redirect; navigate away or throw
|
|
259
|
+
accounts,
|
|
260
|
+
typeahead: true, // off by default: it sends keystrokes to Bluesky
|
|
261
|
+
});
|
|
262
|
+
controller.subscribe(() => render(controller.getState()));
|
|
263
|
+
// state: { query, suggestions, activeIndex, accounts, status, error, pending }
|
|
264
|
+
// actions: setQuery, moveActive, closeSuggestions, submit, choose(account), forget(did), setError
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
The controller owns everything that isn't markup: debounced, cancelled
|
|
268
|
+
searches that ignore late answers; handle normalisation and checking before
|
|
269
|
+
anything is sent; one sign-in at a time; and leaving the "loading" state when
|
|
270
|
+
the page comes back from the back/forward cache. In React, read it with
|
|
271
|
+
`useSyncExternalStore(controller.subscribe, controller.getState)` and draw it
|
|
272
|
+
with your own components.
|
|
273
|
+
|
|
274
|
+
Remembered accounts stay on the device and hold no tokens: DID, handle,
|
|
275
|
+
display name and an https avatar URL. Signing out doesn't forget them; the ✕
|
|
276
|
+
on a card does (`forget`). `lookupProfile(actor)` is the profile lookup on its
|
|
277
|
+
own.
|
|
159
278
|
|
|
160
279
|
### `<bsky-sign-in>`
|
|
161
280
|
|
|
162
281
|
```html
|
|
163
282
|
<script type="module">import "@bbthorson/atproto-cf-auth/element";</script>
|
|
164
283
|
|
|
165
|
-
<bsky-sign-in return-to="/campaigns" button-label="Continue
|
|
284
|
+
<bsky-sign-in return-to="/campaigns" button-label="Continue" typeahead remember-accounts></bsky-sign-in>
|
|
166
285
|
```
|
|
167
286
|
|
|
168
|
-
It renders into the light DOM with plain classes
|
|
169
|
-
`
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
`
|
|
173
|
-
|
|
174
|
-
|
|
287
|
+
It renders into the light DOM with plain classes and sets
|
|
288
|
+
`data-state="idle|loading|error"`, so your own CSS or Tailwind styles it:
|
|
289
|
+
`bsky-sign-in__form`, `__accounts`, `__account`, `__account-choose`,
|
|
290
|
+
`__account-forget`, `__divider`, `__label`, `__field`, `__input`,
|
|
291
|
+
`__suggestions`, `__suggestion`, `__avatar` (`__avatar--empty` without a
|
|
292
|
+
picture), `__identity`, `__name`, `__handle`, `__button`, `__error`.
|
|
293
|
+
|
|
294
|
+
For a starting point, import `@bbthorson/atproto-cf-auth/element.css`. It
|
|
295
|
+
inherits the page's font and text colour, and takes its other choices from
|
|
296
|
+
custom properties (`--bsky-sign-in-accent`, `-surface`, `-border`, `-muted`,
|
|
297
|
+
`-hover`, `-error`, `-radius`, `-card-radius`, `-avatar-size`, `-gap`), so a
|
|
298
|
+
few lines make it match the site.
|
|
299
|
+
|
|
300
|
+
To use your own markup, put a `<form>` containing `<input name="handle">`, a
|
|
301
|
+
button and an element with `data-bsky-error` inside the element; it adds
|
|
302
|
+
behaviour and leaves your markup alone. Add an element with
|
|
303
|
+
`data-bsky-suggestions` for the typeahead list, `data-bsky-accounts` for the
|
|
304
|
+
remembered accounts, and `data-bsky-divider` to show only when there are any.
|
|
305
|
+
The form still works with JavaScript off, because it posts to `/auth/login`.
|
|
175
306
|
|
|
176
307
|
Attributes: `base-path`, `return-to`, `label`, `placeholder`, `button-label`,
|
|
177
|
-
`loading-label`, `
|
|
178
|
-
`
|
|
308
|
+
`loading-label`, `divider-label`, `typeahead`, `remember-accounts`,
|
|
309
|
+
`ignore-redirect-errors`. Event: `bsky-sign-in:error` with `{ code, message }`.
|
|
310
|
+
Call `preventDefault()` on it to show the error yourself. The input is an ARIA
|
|
311
|
+
combobox when `typeahead` is on: arrow keys move through suggestions, Enter
|
|
312
|
+
signs in as the highlighted one, Escape closes the list.
|
|
313
|
+
|
|
314
|
+
`remember-accounts` only shows accounts; remembering one is the call to
|
|
315
|
+
`accounts.remember(user)` above, on a page where you know the sign-in worked.
|
|
179
316
|
|
|
180
317
|
In React, render `<bsky-sign-in>` like any element. Importing the module in a
|
|
181
318
|
client component registers it, and the import is a no-op during SSR.
|
|
@@ -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;
|
package/dist/accounts.js
ADDED
|
@@ -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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_ERROR_MESSAGES, AUTH_ERROR_PARAM, AuthError, isAuthErrorCode, isValidHandle, normalizeHandle, 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;
|
|
@@ -50,19 +53,3 @@ export declare const HANDLE_INPUT_ATTRIBUTES: {
|
|
|
50
53
|
readonly enterkeyhint: "go";
|
|
51
54
|
readonly placeholder: "you.bsky.social";
|
|
52
55
|
};
|
|
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[]>;
|
package/dist/client.js
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { AUTH_ERROR_PARAM, AuthError, isAuthErrorCode, isValidHandle, normalizeHandle, } from "./shared.js";
|
|
7
7
|
export { AUTH_ERROR_MESSAGES, AUTH_ERROR_PARAM, AuthError, isAuthErrorCode, isValidHandle, normalizeHandle, } from "./shared.js";
|
|
8
|
+
export { createRecentAccounts, lookupProfile, RECENT_ACCOUNTS_KEY, } from "./accounts.js";
|
|
9
|
+
export { searchHandles } from "./search.js";
|
|
10
|
+
export { createSignInController, } from "./controller.js";
|
|
8
11
|
export function createAuthClient(options = {}) {
|
|
9
12
|
const base = (options.basePath ?? "/auth").replace(/\/+$/, "");
|
|
10
13
|
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
@@ -78,32 +81,4 @@ export const HANDLE_INPUT_ATTRIBUTES = {
|
|
|
78
81
|
enterkeyhint: "go",
|
|
79
82
|
placeholder: "you.bsky.social",
|
|
80
83
|
};
|
|
81
|
-
/**
|
|
82
|
-
* Handle typeahead from Bluesky's public AppView. Optional, and it sends what
|
|
83
|
-
* the person types to Bluesky as they type, so only use it where that's fine.
|
|
84
|
-
* Pass an `AbortSignal` and abort the previous call on each keystroke.
|
|
85
|
-
*/
|
|
86
|
-
export async function searchHandles(query, options = {}) {
|
|
87
|
-
const q = query.trim().replace(/^@/, "");
|
|
88
|
-
if (q.length < 2)
|
|
89
|
-
return [];
|
|
90
|
-
const url = new URL("https://public.api.bsky.app/xrpc/app.bsky.actor.searchActorsTypeahead");
|
|
91
|
-
url.searchParams.set("q", q);
|
|
92
|
-
url.searchParams.set("limit", String(options.limit ?? 5));
|
|
93
|
-
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
94
|
-
const res = await doFetch(url, options.signal ? { signal: options.signal } : {});
|
|
95
|
-
if (!res.ok)
|
|
96
|
-
return [];
|
|
97
|
-
const body = (await res.json());
|
|
98
|
-
return (body.actors ?? []).flatMap((a) => typeof a["did"] === "string" && typeof a["handle"] === "string"
|
|
99
|
-
? [
|
|
100
|
-
{
|
|
101
|
-
did: a["did"],
|
|
102
|
-
handle: a["handle"],
|
|
103
|
-
...(typeof a["displayName"] === "string" && a["displayName"] ? { displayName: a["displayName"] } : {}),
|
|
104
|
-
...(typeof a["avatar"] === "string" ? { avatar: a["avatar"] } : {}),
|
|
105
|
-
},
|
|
106
|
-
]
|
|
107
|
-
: []);
|
|
108
|
-
}
|
|
109
84
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,eAAe,EACf,aAAa,EACb,eAAe,GAEhB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,SAAS,EACT,eAAe,EACf,aAAa,EACb,eAAe,GAGhB,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,eAAe,EACf,aAAa,EACb,eAAe,GAEhB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,SAAS,EACT,eAAe,EACf,aAAa,EACb,eAAe,GAGhB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,oBAAoB,EACpB,aAAa,EACb,mBAAmB,GAOpB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAyB,MAAM,aAAa,CAAC;AACnE,OAAO,EACL,sBAAsB,GAKvB,MAAM,iBAAiB,CAAC;AA2BzB,MAAM,UAAU,gBAAgB,CAAC,UAA6B,EAAE;IAC9D,MAAM,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC/D,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC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AAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,GAAG,CAAC,QAAQ,GAAG,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;IAC5F,OAAO,IAAI,SAAS,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC;AACzE,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,IAAI,EAAE,QAAQ;IACd,IAAI,EAAE,MAAM;IACZ,YAAY,EAAE,UAAU;IACxB,cAAc,EAAE,MAAM;IACtB,WAAW,EAAE,KAAK;IAClB,UAAU,EAAE,OAAO;IACnB,SAAS,EAAE,KAAK;IAChB,YAAY,EAAE,IAAI;IAClB,WAAW,EAAE,iBAAiB;CACtB,CAAC"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The state behind a sign-in screen, without the screen: what's typed, the
|
|
3
|
+
* typeahead suggestions and which one is highlighted, the remembered
|
|
4
|
+
* accounts, and whether a sign-in is under way or has failed.
|
|
5
|
+
*
|
|
6
|
+
* Every UI wraps the same controller: `<bsky-sign-in>` does, and a React
|
|
7
|
+
* component can with `useSyncExternalStore(controller.subscribe,
|
|
8
|
+
* controller.getState)`. State objects are immutable snapshots, replaced on
|
|
9
|
+
* every change.
|
|
10
|
+
*
|
|
11
|
+
* const controller = createSignInController({
|
|
12
|
+
* signIn: (handle) => auth.signIn(handle), // or your own redirect
|
|
13
|
+
* accounts: createRecentAccounts(),
|
|
14
|
+
* typeahead: true,
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* `signIn` gets a normalised, checked handle or DID. It should navigate away
|
|
18
|
+
* (the controller then stays `loading` until the page goes) or throw; an
|
|
19
|
+
* `AuthError` it throws is shown as it is, anything else as `authorize_failed`.
|
|
20
|
+
*/
|
|
21
|
+
import type { RecentAccount, RecentAccounts } from "./accounts.js";
|
|
22
|
+
import { type HandleSuggestion } from "./search.js";
|
|
23
|
+
import { AuthError } from "./shared.js";
|
|
24
|
+
export type SignInStatus = "idle" | "loading" | "error";
|
|
25
|
+
export interface SignInState {
|
|
26
|
+
/** What's in the field, as typed. */
|
|
27
|
+
query: string;
|
|
28
|
+
/** Typeahead results for `query`; empty when closed. */
|
|
29
|
+
suggestions: readonly HandleSuggestion[];
|
|
30
|
+
/** Index into `suggestions` of the highlighted one, or -1. */
|
|
31
|
+
activeIndex: number;
|
|
32
|
+
/** Remembered accounts, newest first. */
|
|
33
|
+
accounts: readonly RecentAccount[];
|
|
34
|
+
status: SignInStatus;
|
|
35
|
+
/** Set when `status` is `error`. */
|
|
36
|
+
error: AuthError | null;
|
|
37
|
+
/** The handle or DID a sign-in is under way for, while `loading`. */
|
|
38
|
+
pending: string | null;
|
|
39
|
+
}
|
|
40
|
+
export interface SignInControllerOptions {
|
|
41
|
+
/** Start the sign-in for a normalised, valid handle or DID. Navigate away, or throw. */
|
|
42
|
+
signIn: (identifier: string) => Promise<void>;
|
|
43
|
+
/** Remembered accounts to offer above the field. */
|
|
44
|
+
accounts?: RecentAccounts | null;
|
|
45
|
+
/**
|
|
46
|
+
* Suggest accounts as the person types. `true` uses `searchHandles`
|
|
47
|
+
* (Bluesky's public AppView, which sees every keystroke); pass your own
|
|
48
|
+
* function to search elsewhere. Default off.
|
|
49
|
+
*/
|
|
50
|
+
typeahead?: boolean | ((query: string, options: {
|
|
51
|
+
signal: AbortSignal;
|
|
52
|
+
}) => Promise<HandleSuggestion[]>);
|
|
53
|
+
/** Wait this long after the last keystroke before searching. Default 150 ms. */
|
|
54
|
+
debounceMs?: number;
|
|
55
|
+
/** Shortest query searched. Default 2. */
|
|
56
|
+
minQueryLength?: number;
|
|
57
|
+
/** Suggestions shown. Default 5. */
|
|
58
|
+
limit?: number;
|
|
59
|
+
/** Passed to `normalizeHandle`: what a bare name gets appended. Default `bsky.social`; `null` for none. */
|
|
60
|
+
defaultDomain?: string | null;
|
|
61
|
+
/** Map what `signIn` threw to the error to show. Default: `AuthError`s as they are, else `authorize_failed`. */
|
|
62
|
+
toError?: (error: unknown) => AuthError;
|
|
63
|
+
}
|
|
64
|
+
export interface SignInController {
|
|
65
|
+
getState(): SignInState;
|
|
66
|
+
/** Called after every state change. Returns the unsubscribe function. */
|
|
67
|
+
subscribe(listener: () => void): () => void;
|
|
68
|
+
/** The field changed. Clears an error and, with typeahead on, searches. */
|
|
69
|
+
setQuery(query: string): void;
|
|
70
|
+
/** Move the highlight by `delta` (wrapping), e.g. from arrow keys. Opens nothing on its own. */
|
|
71
|
+
moveActive(delta: number): void;
|
|
72
|
+
setActive(index: number): void;
|
|
73
|
+
/** Close the suggestions (Escape, or the field losing focus). */
|
|
74
|
+
closeSuggestions(): void;
|
|
75
|
+
/** Sign in as the highlighted suggestion if there is one, else as what's typed. */
|
|
76
|
+
submit(): Promise<void>;
|
|
77
|
+
/** Sign in as a suggestion or remembered account. */
|
|
78
|
+
choose(account: HandleSuggestion | RecentAccount): Promise<void>;
|
|
79
|
+
/** Drop a remembered account. */
|
|
80
|
+
forget(did: string): Promise<void>;
|
|
81
|
+
/** Show an error from elsewhere, such as `takeAuthError()` after a failed redirect. `null` clears it. */
|
|
82
|
+
setError(error: AuthError | null): void;
|
|
83
|
+
/** Stop listening and cancel any search. */
|
|
84
|
+
destroy(): void;
|
|
85
|
+
}
|
|
86
|
+
export declare function createSignInController(options: SignInControllerOptions): SignInController;
|