@bbthorson/atproto-cf-auth 0.1.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/LICENSE +21 -0
- package/README.md +133 -0
- package/dist/client.d.ts +68 -0
- package/dist/client.js +109 -0
- package/dist/client.js.map +1 -0
- package/dist/element.d.ts +5 -0
- package/dist/element.js +205 -0
- package/dist/element.js.map +1 -0
- package/dist/server/auth.d.ts +62 -0
- package/dist/server/auth.js +285 -0
- package/dist/server/auth.js.map +1 -0
- package/dist/server/cookies.d.ts +10 -0
- package/dist/server/cookies.js +30 -0
- package/dist/server/cookies.js.map +1 -0
- package/dist/server/index.d.ts +7 -0
- package/dist/server/index.js +6 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/runtime.d.ts +16 -0
- package/dist/server/runtime.js +53 -0
- package/dist/server/runtime.js.map +1 -0
- package/dist/server/seal.d.ts +16 -0
- package/dist/server/seal.js +51 -0
- package/dist/server/seal.js.map +1 -0
- package/dist/server/stores/d1.d.ts +22 -0
- package/dist/server/stores/d1.js +49 -0
- package/dist/server/stores/d1.js.map +1 -0
- package/dist/server/stores/kv.d.ts +18 -0
- package/dist/server/stores/kv.js +22 -0
- package/dist/server/stores/kv.js.map +1 -0
- package/dist/server/stores/memory.d.ts +6 -0
- package/dist/server/stores/memory.js +26 -0
- package/dist/server/stores/memory.js.map +1 -0
- package/dist/server/stores/types.d.ts +13 -0
- package/dist/server/stores/types.js +2 -0
- package/dist/server/stores/types.js.map +1 -0
- package/dist/shared.d.ts +41 -0
- package/dist/shared.js +74 -0
- package/dist/shared.js.map +1 -0
- package/package.json +63 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Brad Thorson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# @bbthorson/atproto-cf-auth
|
|
2
|
+
|
|
3
|
+
Bluesky sign-in (AT-Proto OAuth) for apps on Cloudflare Workers. It has a
|
|
4
|
+
server half that runs the OAuth flow and keeps sessions, and a framework-free
|
|
5
|
+
browser half: a headless client and a `<bsky-sign-in>` element.
|
|
6
|
+
|
|
7
|
+
It runs on Web Crypto and `fetch` only. You don't need the `nodejs_compat`
|
|
8
|
+
flag or `@atproto/oauth-client-node`, and it adds about 95 KiB gzipped to a
|
|
9
|
+
Worker.
|
|
10
|
+
|
|
11
|
+
## Server
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createBlueskyAuth, d1Store } from "@bbthorson/atproto-cf-auth/server";
|
|
15
|
+
|
|
16
|
+
let auth: ReturnType<typeof createBlueskyAuth> | undefined;
|
|
17
|
+
|
|
18
|
+
export default {
|
|
19
|
+
async fetch(request: Request, env: Env) {
|
|
20
|
+
auth ??= createBlueskyAuth({
|
|
21
|
+
appName: "Bardcast",
|
|
22
|
+
store: d1Store(env.DB), // or kvStore(env.KV)
|
|
23
|
+
secret: env.SESSION_SECRET, // Worker secret, 32+ random characters
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// Handles /auth/login, /auth/callback, /auth/logout, /auth/session and
|
|
27
|
+
// /auth/client-metadata.json. Returns null for anything else.
|
|
28
|
+
const authResponse = await auth.handle(request);
|
|
29
|
+
if (authResponse) return authResponse;
|
|
30
|
+
|
|
31
|
+
const user = await auth.getUser(request); // { did, handle?, signedInAt } | null
|
|
32
|
+
// ...your routes
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
With Hono: `app.all("/auth/*", async (c) => (await auth.handle(c.req.raw)) ?? c.notFound())`.
|
|
38
|
+
With Astro: call `auth.handle(context.request)` from middleware or from an
|
|
39
|
+
`src/pages/auth/[...route].ts` endpoint.
|
|
40
|
+
|
|
41
|
+
**Options:** `basePath` (default `/auth`), `redirectTo` (default `/`), `scope`
|
|
42
|
+
(default `atproto`, which proves identity only; add `transition:generic` to write
|
|
43
|
+
to the user's PDS), `sessionTtlSeconds` (default 30 days), `cookieName`,
|
|
44
|
+
`metadata` (logo, terms and privacy URLs for the consent screen), `onSignIn`,
|
|
45
|
+
`handleResolver` and `requestLock`.
|
|
46
|
+
|
|
47
|
+
**To call the user's PDS:** `const session = await auth.getOAuthSession(request)`,
|
|
48
|
+
then `new Agent(session)` from `@atproto/api`. Tokens refresh on demand. The
|
|
49
|
+
default lock only covers one isolate, so pass a Durable Object-backed
|
|
50
|
+
`requestLock` before you do this from concurrent requests.
|
|
51
|
+
|
|
52
|
+
### Storage
|
|
53
|
+
|
|
54
|
+
| Store | Use when |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `d1Store(env.DB)` | You have D1. Strongly consistent; creates a `bsky_auth` table on first use. |
|
|
57
|
+
| `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. |
|
|
58
|
+
| `memoryStore()` | Tests only. |
|
|
59
|
+
|
|
60
|
+
Everything written to a store is sealed with AES-GCM under `secret`, including
|
|
61
|
+
the DPoP keys and refresh tokens. Reading the table alone doesn't let anyone act
|
|
62
|
+
as a user. Changing the secret signs everyone out.
|
|
63
|
+
|
|
64
|
+
### Security
|
|
65
|
+
|
|
66
|
+
- The session cookie is an opaque random id (`HttpOnly`, `SameSite=Lax`, `Secure`
|
|
67
|
+
on https). The DID never sits in a cookie.
|
|
68
|
+
- A short-lived nonce cookie ties each callback to the browser that started it,
|
|
69
|
+
which blocks login CSRF.
|
|
70
|
+
- `/login` and `/logout` refuse cross-site POSTs.
|
|
71
|
+
- `returnTo` only accepts same-site paths, so it can't become an open redirect.
|
|
72
|
+
- The client_id is derived from the request origin, so one deploy works on
|
|
73
|
+
workers.dev, a custom domain and `127.0.0.1` in development.
|
|
74
|
+
|
|
75
|
+
In development, open the app at `http://127.0.0.1:<port>`, not `localhost`.
|
|
76
|
+
Bluesky redirects back to the loopback IP, and cookies set on `localhost` don't
|
|
77
|
+
follow.
|
|
78
|
+
|
|
79
|
+
## Browser
|
|
80
|
+
|
|
81
|
+
### Headless client
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { createAuthClient, takeAuthError, HANDLE_INPUT_ATTRIBUTES } from "@bbthorson/atproto-cf-auth/client";
|
|
85
|
+
|
|
86
|
+
const auth = createAuthClient(); // { basePath: "/auth" }
|
|
87
|
+
const user = await auth.getUser(); // null when signed out
|
|
88
|
+
await auth.signIn(handle, { returnTo: "/campaigns" }); // navigates to Bluesky; throws AuthError on failure
|
|
89
|
+
await auth.signOut();
|
|
90
|
+
|
|
91
|
+
// After a failed redirect, read ?auth_error= once (it's removed from the URL):
|
|
92
|
+
const error = takeAuthError(); // AuthError | null, .code and .message
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`signIn` normalises the handle first: it strips `@`, whitespace and characters
|
|
96
|
+
picked up when pasting, and appends `.bsky.social` to a bare name. It then checks
|
|
97
|
+
the handle before calling the server. Errors are `AuthError`s whose `message` is
|
|
98
|
+
ready to show and whose `code` you can map to your own copy (`AUTH_ERROR_MESSAGES`
|
|
99
|
+
holds the defaults). Spread `HANDLE_INPUT_ATTRIBUTES` onto your own `<input>` so
|
|
100
|
+
phones don't capitalise the handle and password managers offer it.
|
|
101
|
+
`searchHandles(query)` is an optional typeahead against Bluesky's public API.
|
|
102
|
+
|
|
103
|
+
### `<bsky-sign-in>`
|
|
104
|
+
|
|
105
|
+
```html
|
|
106
|
+
<script type="module">import "@bbthorson/atproto-cf-auth/element";</script>
|
|
107
|
+
|
|
108
|
+
<bsky-sign-in return-to="/campaigns" button-label="Continue with Bluesky"></bsky-sign-in>
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
It renders into the light DOM with plain classes (`bsky-sign-in__form`,
|
|
112
|
+
`__label`, `__input`, `__button`, `__error`) and sets `data-state="idle|loading|error"`,
|
|
113
|
+
so your own CSS or Tailwind styles it. To use your own markup, put a `<form>`
|
|
114
|
+
containing `<input name="handle">`, a button and an element with
|
|
115
|
+
`data-bsky-error` inside the element; it adds behaviour and leaves your markup
|
|
116
|
+
alone. The form still works with JavaScript off, because it posts to
|
|
117
|
+
`/auth/login`.
|
|
118
|
+
|
|
119
|
+
Attributes: `base-path`, `return-to`, `label`, `placeholder`, `button-label`,
|
|
120
|
+
`loading-label`, `ignore-redirect-errors`. Event: `bsky-sign-in:error` with
|
|
121
|
+
`{ code, message }`. Call `preventDefault()` on it to show the error yourself.
|
|
122
|
+
|
|
123
|
+
In React, render `<bsky-sign-in>` like any element. Importing the module in a
|
|
124
|
+
client component registers it, and the import is a no-op during SSR.
|
|
125
|
+
|
|
126
|
+
## Develop
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
npm install
|
|
130
|
+
npm test # vitest; node:sqlite stands in for D1, happy-dom for the browser
|
|
131
|
+
npm run typecheck
|
|
132
|
+
npm run build
|
|
133
|
+
```
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-free browser half. Everything here is plain functions over
|
|
3
|
+
* `fetch` and `location`, so React, Astro, Svelte or a bare `<script>` can
|
|
4
|
+
* wrap it in whatever state model they use.
|
|
5
|
+
*/
|
|
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";
|
|
8
|
+
export interface AuthClientOptions {
|
|
9
|
+
/** Must match the server's `basePath`. Default `/auth`. */
|
|
10
|
+
basePath?: string;
|
|
11
|
+
fetch?: typeof fetch;
|
|
12
|
+
/** Where to send the browser; overridable for tests. Default `location.assign`. */
|
|
13
|
+
navigate?: (url: string) => void;
|
|
14
|
+
}
|
|
15
|
+
export interface SignInOptions {
|
|
16
|
+
/** Same-site path to land on after sign-in. Default: the server's `redirectTo`. */
|
|
17
|
+
returnTo?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface AuthClient {
|
|
20
|
+
/** The signed-in user, or `null`. Throws `AuthError("network_error")` if the server is unreachable. */
|
|
21
|
+
getUser(): Promise<User | null>;
|
|
22
|
+
/**
|
|
23
|
+
* Normalises and checks the handle, asks the server for the authorization
|
|
24
|
+
* URL, then navigates there. Resolves only if navigation is suppressed; on
|
|
25
|
+
* failure throws an `AuthError` whose `message` is ready to show.
|
|
26
|
+
*/
|
|
27
|
+
signIn(handle: string, options?: SignInOptions): Promise<void>;
|
|
28
|
+
signOut(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare function createAuthClient(options?: AuthClientOptions): AuthClient;
|
|
31
|
+
/**
|
|
32
|
+
* A failed sign-in comes back as `?auth_error=<code>` on the redirect. This
|
|
33
|
+
* reads it and removes it from the address bar (so a reload doesn't show it
|
|
34
|
+
* again). Call once on page load.
|
|
35
|
+
*/
|
|
36
|
+
export declare function takeAuthError(): AuthError | null;
|
|
37
|
+
/**
|
|
38
|
+
* Attributes for a handle `<input>` so phones don't capitalise or "correct"
|
|
39
|
+
* it and password managers offer the saved handle. Spread them onto the
|
|
40
|
+
* element in whatever way your framework sets attributes.
|
|
41
|
+
*/
|
|
42
|
+
export declare const HANDLE_INPUT_ATTRIBUTES: {
|
|
43
|
+
readonly name: "handle";
|
|
44
|
+
readonly type: "text";
|
|
45
|
+
readonly autocomplete: "username";
|
|
46
|
+
readonly autocapitalize: "none";
|
|
47
|
+
readonly autocorrect: "off";
|
|
48
|
+
readonly spellcheck: "false";
|
|
49
|
+
readonly inputmode: "url";
|
|
50
|
+
readonly enterkeyhint: "go";
|
|
51
|
+
readonly placeholder: "you.bsky.social";
|
|
52
|
+
};
|
|
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
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-free browser half. Everything here is plain functions over
|
|
3
|
+
* `fetch` and `location`, so React, Astro, Svelte or a bare `<script>` can
|
|
4
|
+
* wrap it in whatever state model they use.
|
|
5
|
+
*/
|
|
6
|
+
import { AUTH_ERROR_PARAM, AuthError, isAuthErrorCode, isValidHandle, normalizeHandle, } from "./shared.js";
|
|
7
|
+
export { AUTH_ERROR_MESSAGES, AUTH_ERROR_PARAM, AuthError, isAuthErrorCode, isValidHandle, normalizeHandle, } from "./shared.js";
|
|
8
|
+
export function createAuthClient(options = {}) {
|
|
9
|
+
const base = (options.basePath ?? "/auth").replace(/\/+$/, "");
|
|
10
|
+
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
11
|
+
const navigate = options.navigate ?? ((url) => window.location.assign(url));
|
|
12
|
+
async function call(path, init) {
|
|
13
|
+
try {
|
|
14
|
+
return await doFetch(`${base}${path}`, { credentials: "same-origin", ...init });
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new AuthError("network_error");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
async getUser() {
|
|
22
|
+
const res = await call("/session");
|
|
23
|
+
if (!res.ok)
|
|
24
|
+
return null;
|
|
25
|
+
const body = (await res.json().catch(() => null));
|
|
26
|
+
return body?.authenticated && body.user ? body.user : null;
|
|
27
|
+
},
|
|
28
|
+
async signIn(input, signInOptions = {}) {
|
|
29
|
+
const handle = normalizeHandle(input);
|
|
30
|
+
if (!isValidHandle(handle))
|
|
31
|
+
throw new AuthError("invalid_handle");
|
|
32
|
+
const res = await call("/login", {
|
|
33
|
+
method: "POST",
|
|
34
|
+
headers: { "content-type": "application/json" },
|
|
35
|
+
body: JSON.stringify({ handle, ...(signInOptions.returnTo ? { returnTo: signInOptions.returnTo } : {}) }),
|
|
36
|
+
});
|
|
37
|
+
const body = (await res.json().catch(() => null));
|
|
38
|
+
if (res.ok && body?.url) {
|
|
39
|
+
navigate(body.url);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
throw new AuthError(isAuthErrorCode(body?.error) ? body.error : res.status === 503 ? "not_configured" : "authorize_failed");
|
|
43
|
+
},
|
|
44
|
+
async signOut() {
|
|
45
|
+
await call("/logout", { method: "POST" });
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A failed sign-in comes back as `?auth_error=<code>` on the redirect. This
|
|
51
|
+
* reads it and removes it from the address bar (so a reload doesn't show it
|
|
52
|
+
* again). Call once on page load.
|
|
53
|
+
*/
|
|
54
|
+
export function takeAuthError() {
|
|
55
|
+
if (typeof window === "undefined")
|
|
56
|
+
return null;
|
|
57
|
+
const url = new URL(window.location.href);
|
|
58
|
+
const code = url.searchParams.get(AUTH_ERROR_PARAM);
|
|
59
|
+
if (code === null)
|
|
60
|
+
return null;
|
|
61
|
+
url.searchParams.delete(AUTH_ERROR_PARAM);
|
|
62
|
+
window.history.replaceState(window.history.state, "", url.pathname + url.search + url.hash);
|
|
63
|
+
return new AuthError(isAuthErrorCode(code) ? code : "callback_failed");
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Attributes for a handle `<input>` so phones don't capitalise or "correct"
|
|
67
|
+
* it and password managers offer the saved handle. Spread them onto the
|
|
68
|
+
* element in whatever way your framework sets attributes.
|
|
69
|
+
*/
|
|
70
|
+
export const HANDLE_INPUT_ATTRIBUTES = {
|
|
71
|
+
name: "handle",
|
|
72
|
+
type: "text",
|
|
73
|
+
autocomplete: "username",
|
|
74
|
+
autocapitalize: "none",
|
|
75
|
+
autocorrect: "off",
|
|
76
|
+
spellcheck: "false",
|
|
77
|
+
inputmode: "url",
|
|
78
|
+
enterkeyhint: "go",
|
|
79
|
+
placeholder: "you.bsky.social",
|
|
80
|
+
};
|
|
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
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +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;AA2BrB,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,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,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAClF,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACjF,IAAI,CAAC,GAAG,CAAC,EAAE;QAAE,OAAO,EAAE,CAAC;IACvB,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAgD,CAAC;IAC/E,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CACvC,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,QAAQ,CAAC,KAAK,QAAQ;QAC7D,CAAC,CAAC;YACE;gBACE,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC;gBACb,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC;gBACnB,GAAG,CAAC,OAAO,CAAC,CAAC,aAAa,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACtG,GAAG,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACpE;SACF;QACH,CAAC,CAAC,EAAE,CACP,CAAC;AACJ,CAAC"}
|
package/dist/element.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<bsky-sign-in>`: a handle field and a button that run the whole sign-in,
|
|
3
|
+
* usable from any framework (or none). Importing this module registers it.
|
|
4
|
+
*
|
|
5
|
+
* <bsky-sign-in base-path="/auth" return-to="/campaigns"></bsky-sign-in>
|
|
6
|
+
*
|
|
7
|
+
* It renders into the light DOM with plain class names
|
|
8
|
+
* (`bsky-sign-in__form`, `__label`, `__input`, `__button`, `__error`) and a
|
|
9
|
+
* `data-state` of `idle | loading | error`, so the app's own CSS styles it.
|
|
10
|
+
*
|
|
11
|
+
* Or bring your own markup and it only adds behaviour. It looks for a
|
|
12
|
+
* `<form>`, an `<input name="handle">`, a submit button and an element with
|
|
13
|
+
* `data-bsky-error`:
|
|
14
|
+
*
|
|
15
|
+
* <bsky-sign-in>
|
|
16
|
+
* <form class="my-form">
|
|
17
|
+
* <input name="handle" class="my-input" />
|
|
18
|
+
* <button class="my-button">Continue with Bluesky</button>
|
|
19
|
+
* <p data-bsky-error></p>
|
|
20
|
+
* </form>
|
|
21
|
+
* </bsky-sign-in>
|
|
22
|
+
*
|
|
23
|
+
* Without JavaScript the form still works: it posts to `{base-path}/login`,
|
|
24
|
+
* which redirects to the Bluesky consent page.
|
|
25
|
+
*
|
|
26
|
+
* Events (bubbling): `bsky-sign-in:error` with `{ code, message }`. Call
|
|
27
|
+
* `preventDefault()` on it to show the error yourself.
|
|
28
|
+
*/
|
|
29
|
+
import { AuthError, HANDLE_INPUT_ATTRIBUTES, createAuthClient, takeAuthError, } from "./client.js";
|
|
30
|
+
let uid = 0;
|
|
31
|
+
export function defineSignInElement(tagName = "bsky-sign-in") {
|
|
32
|
+
if (typeof customElements === "undefined" || customElements.get(tagName))
|
|
33
|
+
return;
|
|
34
|
+
class BskySignIn extends HTMLElement {
|
|
35
|
+
static observedAttributes = ["label", "placeholder", "button-label"];
|
|
36
|
+
client;
|
|
37
|
+
form = null;
|
|
38
|
+
input = null;
|
|
39
|
+
button = null;
|
|
40
|
+
errorEl = null;
|
|
41
|
+
buttonText = "";
|
|
42
|
+
get basePath() {
|
|
43
|
+
return (this.getAttribute("base-path") ?? "/auth").replace(/\/+$/, "");
|
|
44
|
+
}
|
|
45
|
+
connectedCallback() {
|
|
46
|
+
// When the element is defined before the page is parsed, or created via
|
|
47
|
+
// innerHTML, this runs before its children exist. Wait for them, so
|
|
48
|
+
// app-provided markup is enhanced rather than duplicated.
|
|
49
|
+
queueMicrotask(() => {
|
|
50
|
+
if (!this.isConnected)
|
|
51
|
+
return;
|
|
52
|
+
if (!this.firstElementChild && document.readyState === "loading") {
|
|
53
|
+
document.addEventListener("DOMContentLoaded", () => this.isConnected && this.setUp(), { once: true });
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
this.setUp();
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
setUp() {
|
|
61
|
+
if (this.form)
|
|
62
|
+
return;
|
|
63
|
+
if (!this.querySelector("form"))
|
|
64
|
+
this.renderDefault();
|
|
65
|
+
this.form = this.querySelector("form");
|
|
66
|
+
this.input = this.querySelector('input[name="handle"]');
|
|
67
|
+
this.button = this.form?.querySelector('button:not([type="button"]), input[type="submit"]') ?? null;
|
|
68
|
+
this.errorEl = this.querySelector("[data-bsky-error]");
|
|
69
|
+
if (!this.form || !this.input)
|
|
70
|
+
return;
|
|
71
|
+
// No-JS fallback and the attributes phones need.
|
|
72
|
+
if (!this.form.getAttribute("action"))
|
|
73
|
+
this.form.setAttribute("action", `${this.basePath}/login`);
|
|
74
|
+
if (!this.form.getAttribute("method"))
|
|
75
|
+
this.form.setAttribute("method", "post");
|
|
76
|
+
for (const [name, value] of Object.entries(HANDLE_INPUT_ATTRIBUTES)) {
|
|
77
|
+
if (!this.input.hasAttribute(name))
|
|
78
|
+
this.input.setAttribute(name, value);
|
|
79
|
+
}
|
|
80
|
+
const returnTo = this.getAttribute("return-to");
|
|
81
|
+
if (returnTo && !this.form.querySelector('input[name="returnTo"]')) {
|
|
82
|
+
const hidden = document.createElement("input");
|
|
83
|
+
hidden.type = "hidden";
|
|
84
|
+
hidden.name = "returnTo";
|
|
85
|
+
hidden.value = returnTo;
|
|
86
|
+
this.form.append(hidden);
|
|
87
|
+
}
|
|
88
|
+
this.client = createAuthClient({ basePath: this.basePath });
|
|
89
|
+
this.dataset["state"] = "idle";
|
|
90
|
+
this.buttonText = this.button?.textContent ?? "";
|
|
91
|
+
this.form.addEventListener("submit", this.onSubmit);
|
|
92
|
+
this.input.addEventListener("input", this.onInput);
|
|
93
|
+
// A failed redirect lands back here with ?auth_error=.
|
|
94
|
+
if (!this.hasAttribute("ignore-redirect-errors")) {
|
|
95
|
+
const error = takeAuthError();
|
|
96
|
+
if (error)
|
|
97
|
+
this.showError(error);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
disconnectedCallback() {
|
|
101
|
+
this.form?.removeEventListener("submit", this.onSubmit);
|
|
102
|
+
this.input?.removeEventListener("input", this.onInput);
|
|
103
|
+
this.form = null;
|
|
104
|
+
}
|
|
105
|
+
attributeChangedCallback() {
|
|
106
|
+
if (!this.form)
|
|
107
|
+
return;
|
|
108
|
+
const label = this.querySelector(".bsky-sign-in__label");
|
|
109
|
+
if (label)
|
|
110
|
+
label.textContent = this.getAttribute("label") ?? "Bluesky handle";
|
|
111
|
+
if (this.input && this.hasAttribute("placeholder"))
|
|
112
|
+
this.input.placeholder = this.getAttribute("placeholder");
|
|
113
|
+
if (this.button?.classList.contains("bsky-sign-in__button")) {
|
|
114
|
+
this.buttonText = this.getAttribute("button-label") ?? "Sign in with Bluesky";
|
|
115
|
+
if (this.dataset["state"] !== "loading")
|
|
116
|
+
this.button.textContent = this.buttonText;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
renderDefault() {
|
|
120
|
+
const id = `bsky-sign-in-${++uid}`;
|
|
121
|
+
const form = document.createElement("form");
|
|
122
|
+
form.className = "bsky-sign-in__form";
|
|
123
|
+
form.noValidate = true;
|
|
124
|
+
const label = document.createElement("label");
|
|
125
|
+
label.className = "bsky-sign-in__label";
|
|
126
|
+
label.htmlFor = id;
|
|
127
|
+
label.textContent = this.getAttribute("label") ?? "Bluesky handle";
|
|
128
|
+
const input = document.createElement("input");
|
|
129
|
+
input.className = "bsky-sign-in__input";
|
|
130
|
+
input.id = id;
|
|
131
|
+
input.name = "handle";
|
|
132
|
+
input.required = true;
|
|
133
|
+
const placeholder = this.getAttribute("placeholder");
|
|
134
|
+
if (placeholder)
|
|
135
|
+
input.placeholder = placeholder;
|
|
136
|
+
const button = document.createElement("button");
|
|
137
|
+
button.className = "bsky-sign-in__button";
|
|
138
|
+
button.type = "submit";
|
|
139
|
+
button.textContent = this.getAttribute("button-label") ?? "Sign in with Bluesky";
|
|
140
|
+
const error = document.createElement("p");
|
|
141
|
+
error.className = "bsky-sign-in__error";
|
|
142
|
+
error.id = `${id}-error`;
|
|
143
|
+
error.setAttribute("data-bsky-error", "");
|
|
144
|
+
error.setAttribute("role", "alert");
|
|
145
|
+
error.hidden = true;
|
|
146
|
+
form.append(label, input, button, error);
|
|
147
|
+
this.append(form);
|
|
148
|
+
}
|
|
149
|
+
onInput = () => {
|
|
150
|
+
if (this.dataset["state"] === "error")
|
|
151
|
+
this.clearError();
|
|
152
|
+
};
|
|
153
|
+
onSubmit = async (event) => {
|
|
154
|
+
event.preventDefault();
|
|
155
|
+
if (!this.client || !this.input || this.dataset["state"] === "loading")
|
|
156
|
+
return;
|
|
157
|
+
this.clearError();
|
|
158
|
+
this.setLoading(true);
|
|
159
|
+
try {
|
|
160
|
+
const returnTo = this.getAttribute("return-to");
|
|
161
|
+
await this.client.signIn(this.input.value, returnTo ? { returnTo } : {});
|
|
162
|
+
// Navigation is under way; stay in the loading state.
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
this.setLoading(false);
|
|
166
|
+
this.showError(err instanceof AuthError ? err : new AuthError("authorize_failed"));
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
setLoading(loading) {
|
|
170
|
+
this.dataset["state"] = loading ? "loading" : "idle";
|
|
171
|
+
this.toggleAttribute("aria-busy", loading);
|
|
172
|
+
if (this.input)
|
|
173
|
+
this.input.readOnly = loading;
|
|
174
|
+
if (!this.button)
|
|
175
|
+
return;
|
|
176
|
+
this.button.disabled = loading;
|
|
177
|
+
const loadingLabel = this.getAttribute("loading-label");
|
|
178
|
+
if (loadingLabel)
|
|
179
|
+
this.button.textContent = loading ? loadingLabel : this.buttonText;
|
|
180
|
+
}
|
|
181
|
+
showError(error) {
|
|
182
|
+
const detail = { code: error.code, message: error.message };
|
|
183
|
+
const proceed = this.dispatchEvent(new CustomEvent("bsky-sign-in:error", { detail, bubbles: true, cancelable: true }));
|
|
184
|
+
this.dataset["state"] = "error";
|
|
185
|
+
this.input?.setAttribute("aria-invalid", "true");
|
|
186
|
+
if (proceed && this.errorEl) {
|
|
187
|
+
this.errorEl.textContent = error.message;
|
|
188
|
+
this.errorEl.hidden = false;
|
|
189
|
+
if (this.errorEl.id && this.input)
|
|
190
|
+
this.input.setAttribute("aria-describedby", this.errorEl.id);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
clearError() {
|
|
194
|
+
this.dataset["state"] = "idle";
|
|
195
|
+
this.input?.removeAttribute("aria-invalid");
|
|
196
|
+
if (this.errorEl) {
|
|
197
|
+
this.errorEl.textContent = "";
|
|
198
|
+
this.errorEl.hidden = true;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
customElements.define(tagName, BskySignIn);
|
|
203
|
+
}
|
|
204
|
+
defineSignInElement();
|
|
205
|
+
//# sourceMappingURL=element.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"element.js","sourceRoot":"","sources":["../src/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EACL,SAAS,EACT,uBAAuB,EACvB,gBAAgB,EAChB,aAAa,GAEd,MAAM,aAAa,CAAC;AAOrB,IAAI,GAAG,GAAG,CAAC,CAAC;AAEZ,MAAM,UAAU,mBAAmB,CAAC,OAAO,GAAG,cAAc;IAC1D,IAAI,OAAO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imeLock } from "@atproto/oauth-client";
|
|
2
|
+
import { type User } from "../shared.js";
|
|
3
|
+
import type { AuthStore } from "./stores/types.js";
|
|
4
|
+
export interface BlueskyAuthOptions {
|
|
5
|
+
/** Shown on the Bluesky consent screen. */
|
|
6
|
+
appName: string;
|
|
7
|
+
/** Where sessions and in-flight sign-ins live: `d1Store`, `kvStore` or `memoryStore`. */
|
|
8
|
+
store: AuthStore;
|
|
9
|
+
/** Seals everything written to `store`. A Worker secret of 32+ random characters. */
|
|
10
|
+
secret: string;
|
|
11
|
+
/** Mount point for the routes below. Default `/auth`. */
|
|
12
|
+
basePath?: string;
|
|
13
|
+
/** Where the browser lands after sign-in or sign-out, unless the sign-in named a `returnTo`. Default `/`. */
|
|
14
|
+
redirectTo?: string;
|
|
15
|
+
/** OAuth scope. Default `atproto` (identity only). Add e.g. `transition:generic` to write to the PDS. */
|
|
16
|
+
scope?: string;
|
|
17
|
+
/** How long a sign-in lasts, in seconds. Default 30 days. */
|
|
18
|
+
sessionTtlSeconds?: number;
|
|
19
|
+
/** Name of the session cookie. Default `bsky_sid`. */
|
|
20
|
+
cookieName?: string;
|
|
21
|
+
/**
|
|
22
|
+
* Handle → DID resolution. Default: DNS-over-HTTPS through Cloudflare's
|
|
23
|
+
* resolver plus the `/.well-known/atproto-did` check, which works on Workers.
|
|
24
|
+
*/
|
|
25
|
+
handleResolver?: HandleResolver | string | URL;
|
|
26
|
+
/**
|
|
27
|
+
* Serialises token refreshes for one DID. The default only covers one
|
|
28
|
+
* isolate; that is enough until you call the PDS with `getOAuthSession`
|
|
29
|
+
* from concurrent requests, at which point pass a Durable Object-backed lock.
|
|
30
|
+
*/
|
|
31
|
+
requestLock?: RuntimeLock;
|
|
32
|
+
/** Extra client metadata shown on the consent screen. */
|
|
33
|
+
metadata?: Pick<OAuthClientMetadataInput, "logo_uri" | "tos_uri" | "policy_uri">;
|
|
34
|
+
/** Called once per successful sign-in, before the redirect. */
|
|
35
|
+
onSignIn?: (user: User, request: Request) => void | Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
export interface BlueskyAuth {
|
|
38
|
+
/**
|
|
39
|
+
* Handles `GET {basePath}/client-metadata.json`, `GET {basePath}/session`,
|
|
40
|
+
* `POST {basePath}/login`, `GET {basePath}/callback` and
|
|
41
|
+
* `POST {basePath}/logout`. Returns `null` for anything else, so it can sit
|
|
42
|
+
* in front of an app's own router.
|
|
43
|
+
*/
|
|
44
|
+
handle(request: Request): Promise<Response | null>;
|
|
45
|
+
/** The signed-in user for this request, or `null`. This is the check to gate routes on. */
|
|
46
|
+
getUser(request: Request): Promise<User | null>;
|
|
47
|
+
/**
|
|
48
|
+
* The OAuth session for the signed-in user, for calling their PDS
|
|
49
|
+
* (`new Agent(session)` from `@atproto/api`). Refreshes tokens as needed.
|
|
50
|
+
*/
|
|
51
|
+
getOAuthSession(request: Request): Promise<OAuthSession | null>;
|
|
52
|
+
/** The client metadata document served for an origin. */
|
|
53
|
+
clientMetadata(origin: string): OAuthClientMetadataInput;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Bluesky sign-in for a Worker (or anything with Web Crypto and `fetch`).
|
|
57
|
+
*
|
|
58
|
+
* One instance serves every origin the app answers on (workers.dev, a custom
|
|
59
|
+
* domain, 127.0.0.1 in development): the OAuth client_id and redirect_uri are
|
|
60
|
+
* derived from the request's origin, so each origin names itself correctly.
|
|
61
|
+
*/
|
|
62
|
+
export declare function createBlueskyAuth(options: BlueskyAuthOptions): BlueskyAuth;
|