@hamur/auth 0.0.0-stage → 0.0.1
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 +22 -0
- package/README.md +14 -2
- package/dist/chunks/bun-index-0grce57w.js +47 -0
- package/dist/chunks/bun-index-nn9z2k40.js +92 -0
- package/dist/chunks/bun-index-pmpez2a8.js +10 -0
- package/dist/chunks/bun-index-r6757s88.js +206 -0
- package/dist/src/adapters/angular.js +63 -0
- package/dist/src/adapters/html.js +29 -0
- package/dist/src/adapters/preact.js +37 -0
- package/dist/src/adapters/react.js +32 -0
- package/dist/src/adapters/solid.js +45 -0
- package/dist/src/adapters/svelte.js +44 -0
- package/dist/src/adapters/vue.js +55 -0
- package/dist/src/index.js +688 -0
- package/dist/src/middleware.js +45 -0
- package/dist/src/route-middleware.js +42 -0
- package/dist/src/server/index.js +2971 -0
- package/dist/types/src/adapters/angular.d.ts +32 -0
- package/dist/types/src/adapters/html.d.ts +15 -0
- package/dist/types/src/adapters/preact.d.ts +19 -0
- package/dist/types/src/adapters/react.d.ts +19 -0
- package/dist/types/src/adapters/solid.d.ts +25 -0
- package/dist/types/src/adapters/svelte-session.d.ts +8 -0
- package/dist/types/src/adapters/svelte-webauthn.d.ts +8 -0
- package/dist/types/src/adapters/svelte.d.ts +5 -0
- package/dist/types/src/adapters/vue.d.ts +25 -0
- package/dist/types/src/build/access-tokens.d.ts +4 -0
- package/dist/types/src/build/client.d.ts +4 -0
- package/dist/types/src/build/dev-key.d.ts +6 -0
- package/dist/types/src/build/email.d.ts +4 -0
- package/dist/types/src/build/guards.d.ts +4 -0
- package/dist/types/src/build/module-entry.d.ts +3 -0
- package/dist/types/src/build/oauth.d.ts +8 -0
- package/dist/types/src/build/session.d.ts +6 -0
- package/dist/types/src/build/single-use.d.ts +15 -0
- package/dist/types/src/build/webauthn.d.ts +7 -0
- package/dist/types/src/client/webauthn.d.ts +37 -0
- package/dist/types/src/index.d.ts +43 -0
- package/dist/types/src/middleware.d.ts +4 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +4 -0
- package/dist/types/src/route-middleware.d.ts +2 -0
- package/dist/types/src/runtime/middleware/auth.d.ts +3 -0
- package/dist/types/src/runtime/middleware/guest.d.ts +3 -0
- package/dist/types/src/runtime/payload.d.ts +2 -0
- package/dist/types/src/runtime/plugin.d.ts +2 -0
- package/dist/types/src/runtime/store.d.ts +28 -0
- package/dist/types/src/runtime/targets.d.ts +4 -0
- package/dist/types/src/server/access-token.d.ts +27 -0
- package/dist/types/src/server/auth-link.d.ts +15 -0
- package/dist/types/src/server/door.d.ts +4 -0
- package/dist/types/src/server/endpoint.d.ts +8 -0
- package/dist/types/src/server/guard.d.ts +12 -0
- package/dist/types/src/server/hooks.d.ts +5 -0
- package/dist/types/src/server/index.d.ts +88 -0
- package/dist/types/src/server/oauth/atproto-dns.d.ts +1 -0
- package/dist/types/src/server/oauth/atproto-fetch.d.ts +13 -0
- package/dist/types/src/server/oauth/atproto-metadata.d.ts +1 -0
- package/dist/types/src/server/oauth/atproto.d.ts +36 -0
- package/dist/types/src/server/oauth/cookie.d.ts +17 -0
- package/dist/types/src/server/oauth/dpop.d.ts +4 -0
- package/dist/types/src/server/oauth/handler.d.ts +101 -0
- package/dist/types/src/server/oauth/oidc.d.ts +20 -0
- package/dist/types/src/server/oauth/providers/apple.d.ts +26 -0
- package/dist/types/src/server/oauth/providers/atlassian.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/auth0.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/authentik.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/azureb2c.d.ts +11 -0
- package/dist/types/src/server/oauth/providers/battledotnet.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/box.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/catalog.d.ts +12 -0
- package/dist/types/src/server/oauth/providers/cloudflare.d.ts +11 -0
- package/dist/types/src/server/oauth/providers/cognito.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/discord.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/dropbox.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/facebook.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/gitea.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/github.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/gitlab.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/google.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/heroku.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/hubspot.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/instagram.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/keycloak.d.ts +11 -0
- package/dist/types/src/server/oauth/providers/kick.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/line.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/linear.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/linkedin.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/livechat.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/mastodon.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/microsoft.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/okta.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/ory.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/osu.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/paypal.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/polar.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/preset.d.ts +74 -0
- package/dist/types/src/server/oauth/providers/riotgames.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/roblox.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/salesforce.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/seznam.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/shopifyCustomer.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/slack.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/spotify.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/steam.d.ts +23 -0
- package/dist/types/src/server/oauth/providers/strava.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/tiktok.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/twitch.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/vk.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/wechat.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/workos.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/x.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/xsuaa.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/yandex.d.ts +5 -0
- package/dist/types/src/server/oauth/providers/zendesk.d.ts +9 -0
- package/dist/types/src/server/oauth/providers/zitadel.d.ts +9 -0
- package/dist/types/src/server/personal.d.ts +5 -0
- package/dist/types/src/server/session.d.ts +20 -0
- package/dist/types/src/server/token-requests.d.ts +5 -0
- package/dist/types/src/server/token.d.ts +17 -0
- package/dist/types/src/server/totp.d.ts +28 -0
- package/dist/types/src/server/webauthn/cbor.d.ts +16 -0
- package/dist/types/src/server/webauthn/cose.d.ts +17 -0
- package/dist/types/src/server/webauthn/data.d.ts +20 -0
- package/dist/types/src/server/webauthn/handler.d.ts +63 -0
- package/dist/types/src/single-use.d.ts +17 -0
- package/dist/types/src/types.d.ts +88 -0
- package/package.json +122 -4
- package/src/adapters/AuthState.svelte +14 -0
- package/src/adapters/angular.ts +80 -0
- package/src/adapters/html.ts +39 -0
- package/src/adapters/preact.ts +53 -0
- package/src/adapters/react.ts +49 -0
- package/src/adapters/solid.ts +64 -0
- package/src/adapters/svelte-session.ts +21 -0
- package/src/adapters/svelte-webauthn.ts +20 -0
- package/src/adapters/svelte.ts +5 -0
- package/src/adapters/vue.ts +70 -0
- package/src/build/access-tokens.ts +44 -0
- package/src/build/client.ts +16 -0
- package/src/build/dev-key.ts +29 -0
- package/src/build/email.ts +32 -0
- package/src/build/guards.ts +12 -0
- package/src/build/module-entry.ts +8 -0
- package/src/build/oauth.ts +54 -0
- package/src/build/session.ts +54 -0
- package/src/build/single-use.ts +104 -0
- package/src/build/webauthn.ts +28 -0
- package/src/client/webauthn.ts +129 -0
- package/src/env.d.ts +84 -0
- package/src/index.ts +44 -0
- package/src/middleware.ts +9 -0
- package/src/module.ts +26 -0
- package/src/options.ts +241 -0
- package/src/route-middleware.ts +2 -0
- package/src/runtime/middleware/auth.ts +16 -0
- package/src/runtime/middleware/guest.ts +17 -0
- package/src/runtime/payload.ts +40 -0
- package/src/runtime/plugin.ts +12 -0
- package/src/runtime/store.ts +72 -0
- package/src/runtime/targets.ts +9 -0
- package/src/server/access-token.ts +130 -0
- package/src/server/auth-link.ts +95 -0
- package/src/server/door.ts +33 -0
- package/src/server/endpoint.ts +33 -0
- package/src/server/guard.ts +41 -0
- package/src/server/hooks.ts +13 -0
- package/src/server/index.ts +96 -0
- package/src/server/oauth/atproto-dns.ts +3 -0
- package/src/server/oauth/atproto-fetch.ts +67 -0
- package/src/server/oauth/atproto-metadata.ts +20 -0
- package/src/server/oauth/atproto.ts +292 -0
- package/src/server/oauth/cookie.ts +38 -0
- package/src/server/oauth/dpop.ts +32 -0
- package/src/server/oauth/handler.ts +377 -0
- package/src/server/oauth/oidc.ts +283 -0
- package/src/server/oauth/providers/apple.ts +108 -0
- package/src/server/oauth/providers/atlassian.ts +20 -0
- package/src/server/oauth/providers/auth0.ts +29 -0
- package/src/server/oauth/providers/authentik.ts +29 -0
- package/src/server/oauth/providers/azureb2c.ts +41 -0
- package/src/server/oauth/providers/battledotnet.ts +21 -0
- package/src/server/oauth/providers/box.ts +19 -0
- package/src/server/oauth/providers/catalog.ts +73 -0
- package/src/server/oauth/providers/cloudflare.ts +34 -0
- package/src/server/oauth/providers/cognito.ts +29 -0
- package/src/server/oauth/providers/discord.ts +19 -0
- package/src/server/oauth/providers/dropbox.ts +26 -0
- package/src/server/oauth/providers/facebook.ts +19 -0
- package/src/server/oauth/providers/gitea.ts +29 -0
- package/src/server/oauth/providers/github.ts +33 -0
- package/src/server/oauth/providers/gitlab.ts +29 -0
- package/src/server/oauth/providers/google.ts +19 -0
- package/src/server/oauth/providers/heroku.ts +28 -0
- package/src/server/oauth/providers/hubspot.ts +27 -0
- package/src/server/oauth/providers/instagram.ts +32 -0
- package/src/server/oauth/providers/keycloak.ts +31 -0
- package/src/server/oauth/providers/kick.ts +26 -0
- package/src/server/oauth/providers/line.ts +19 -0
- package/src/server/oauth/providers/linear.ts +34 -0
- package/src/server/oauth/providers/linkedin.ts +20 -0
- package/src/server/oauth/providers/livechat.ts +19 -0
- package/src/server/oauth/providers/mastodon.ts +29 -0
- package/src/server/oauth/providers/microsoft.ts +29 -0
- package/src/server/oauth/providers/okta.ts +29 -0
- package/src/server/oauth/providers/ory.ts +29 -0
- package/src/server/oauth/providers/osu.ts +19 -0
- package/src/server/oauth/providers/paypal.ts +19 -0
- package/src/server/oauth/providers/polar.ts +19 -0
- package/src/server/oauth/providers/preset.ts +206 -0
- package/src/server/oauth/providers/riotgames.ts +19 -0
- package/src/server/oauth/providers/roblox.ts +19 -0
- package/src/server/oauth/providers/salesforce.ts +29 -0
- package/src/server/oauth/providers/seznam.ts +19 -0
- package/src/server/oauth/providers/shopifyCustomer.ts +47 -0
- package/src/server/oauth/providers/slack.ts +27 -0
- package/src/server/oauth/providers/spotify.ts +19 -0
- package/src/server/oauth/providers/steam.ts +162 -0
- package/src/server/oauth/providers/strava.ts +20 -0
- package/src/server/oauth/providers/tiktok.ts +22 -0
- package/src/server/oauth/providers/twitch.ts +32 -0
- package/src/server/oauth/providers/vk.ts +36 -0
- package/src/server/oauth/providers/wechat.ts +39 -0
- package/src/server/oauth/providers/workos.ts +19 -0
- package/src/server/oauth/providers/x.ts +19 -0
- package/src/server/oauth/providers/xsuaa.ts +29 -0
- package/src/server/oauth/providers/yandex.ts +26 -0
- package/src/server/oauth/providers/zendesk.ts +29 -0
- package/src/server/oauth/providers/zitadel.ts +29 -0
- package/src/server/personal.ts +17 -0
- package/src/server/session.ts +150 -0
- package/src/server/token-requests.ts +13 -0
- package/src/server/token.ts +81 -0
- package/src/server/totp.ts +165 -0
- package/src/server/webauthn/cbor.ts +154 -0
- package/src/server/webauthn/cose.ts +95 -0
- package/src/server/webauthn/data.ts +50 -0
- package/src/server/webauthn/handler.ts +510 -0
- package/src/single-use.ts +41 -0
- package/src/types.ts +91 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/// <reference path="../../env.d.ts" />
|
|
2
|
+
import { hostFetch } from "#hamur/auth/atproto"
|
|
3
|
+
import { urlProblem } from "hamur/server/internal"
|
|
4
|
+
|
|
5
|
+
export { hostProblem, urlProblem } from "hamur/server/internal"
|
|
6
|
+
|
|
7
|
+
export const FETCH_TIMEOUT = 5_000
|
|
8
|
+
export const MAX_BODY = 65_536
|
|
9
|
+
|
|
10
|
+
/** `message` is the reason, logged and never sent. */
|
|
11
|
+
export class AtprotoResolveError extends Error {}
|
|
12
|
+
|
|
13
|
+
export interface AtprotoAnswer {
|
|
14
|
+
status: number
|
|
15
|
+
ok: boolean
|
|
16
|
+
headers: Headers
|
|
17
|
+
text: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function readBody(response: Response, url: string): Promise<string> {
|
|
21
|
+
const length = Number(response.headers.get("content-length"))
|
|
22
|
+
if (length > MAX_BODY) {
|
|
23
|
+
await response.body?.cancel().catch(() => {})
|
|
24
|
+
throw new AtprotoResolveError(`${url} answered more than ${MAX_BODY} bytes`)
|
|
25
|
+
}
|
|
26
|
+
if (!response.body) return ""
|
|
27
|
+
const reader = response.body.getReader()
|
|
28
|
+
const chunks: Uint8Array[] = []
|
|
29
|
+
let size = 0
|
|
30
|
+
for (;;) {
|
|
31
|
+
const { done, value } = await reader.read()
|
|
32
|
+
if (done) break
|
|
33
|
+
size += value.byteLength
|
|
34
|
+
if (size > MAX_BODY) {
|
|
35
|
+
await reader.cancel().catch(() => {})
|
|
36
|
+
throw new AtprotoResolveError(`${url} answered more than ${MAX_BODY} bytes`)
|
|
37
|
+
}
|
|
38
|
+
chunks.push(value)
|
|
39
|
+
}
|
|
40
|
+
const bytes = new Uint8Array(size)
|
|
41
|
+
let at = 0
|
|
42
|
+
for (const chunk of chunks) {
|
|
43
|
+
bytes.set(chunk, at)
|
|
44
|
+
at += chunk.byteLength
|
|
45
|
+
}
|
|
46
|
+
return new TextDecoder().decode(bytes)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function atprotoFetch(url: string, init: RequestInit = {}): Promise<AtprotoAnswer> {
|
|
50
|
+
const problem = urlProblem(url)
|
|
51
|
+
if (problem !== undefined) throw new AtprotoResolveError(`${url}: ${problem}`)
|
|
52
|
+
const sent: RequestInit = { ...init, redirect: "manual", signal: AbortSignal.timeout(FETCH_TIMEOUT) }
|
|
53
|
+
let response: Response
|
|
54
|
+
let text: string
|
|
55
|
+
try {
|
|
56
|
+
response = hostFetch ? await hostFetch(url, sent) : await fetch(url, sent)
|
|
57
|
+
if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
|
|
58
|
+
await response.body?.cancel().catch(() => {})
|
|
59
|
+
throw new AtprotoResolveError(`${url} answered a redirect`)
|
|
60
|
+
}
|
|
61
|
+
text = await readBody(response, url)
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof AtprotoResolveError) throw error
|
|
64
|
+
throw new AtprotoResolveError(`${url}: ${(error as Error).message}`)
|
|
65
|
+
}
|
|
66
|
+
return { status: response.status, ok: response.ok, headers: response.headers, text }
|
|
67
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/// <reference path="../../env.d.ts" />
|
|
2
|
+
import { routes } from "#hamur/auth/atproto"
|
|
3
|
+
import { defineHandler, getRequestURL } from "hamur/server"
|
|
4
|
+
import { atprotoClientMetadata as metadataFor } from "./atproto.ts"
|
|
5
|
+
|
|
6
|
+
export const atprotoClientMetadata = defineHandler({
|
|
7
|
+
route: "/_hamur/auth/atproto/client-metadata.json",
|
|
8
|
+
method: "GET",
|
|
9
|
+
raw: true,
|
|
10
|
+
async handler(_, { event }) {
|
|
11
|
+
await Promise.all(routes.map((route) => route.load()))
|
|
12
|
+
return Response.json(
|
|
13
|
+
metadataFor(
|
|
14
|
+
getRequestURL(event).origin,
|
|
15
|
+
routes.map((route) => route.path),
|
|
16
|
+
),
|
|
17
|
+
{ headers: { "cache-control": "no-cache" } },
|
|
18
|
+
)
|
|
19
|
+
},
|
|
20
|
+
})
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/// <reference path="../../env.d.ts" />
|
|
2
|
+
import { baseURL } from "#hamur/auth/guards"
|
|
3
|
+
import { createError, getRequestURL, type HandlerContext, type HamurEvent } from "hamur/server"
|
|
4
|
+
import { AtprotoResolveError, atprotoFetch, hostProblem, urlProblem, type AtprotoAnswer } from "./atproto-fetch.ts"
|
|
5
|
+
import { createDPoPKey, dpopProof } from "./dpop.ts"
|
|
6
|
+
import { createOAuthHandler, errorCode, type OAuthError, type OAuthTokens } from "./handler.ts"
|
|
7
|
+
import { ATPROTO_METADATA_ROUTE } from "./providers/catalog.ts"
|
|
8
|
+
|
|
9
|
+
/** The client metadata document of an AT Protocol OAuth client (atproto OAuth, "Client ID Metadata Document"). */
|
|
10
|
+
export interface AtprotoClientMetadata {
|
|
11
|
+
client_id: string
|
|
12
|
+
client_name?: string
|
|
13
|
+
client_uri?: string
|
|
14
|
+
logo_uri?: string
|
|
15
|
+
tos_uri?: string
|
|
16
|
+
policy_uri?: string
|
|
17
|
+
redirect_uris: string[]
|
|
18
|
+
scope: string
|
|
19
|
+
grant_types: string[]
|
|
20
|
+
response_types: string[]
|
|
21
|
+
application_type: "web" | "native"
|
|
22
|
+
token_endpoint_auth_method: "none"
|
|
23
|
+
dpop_bound_access_tokens: true
|
|
24
|
+
[key: string]: unknown
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface AtprotoResult {
|
|
28
|
+
did: string
|
|
29
|
+
handle: string
|
|
30
|
+
tokens: OAuthTokens
|
|
31
|
+
/** The private ES256 key the tokens are bound to (DPoP); a request with them needs a proof signed with it. */
|
|
32
|
+
dpopKey: JsonWebKey
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface OAuthAtprotoOptions {
|
|
36
|
+
/** Fields of the served client metadata; `client_id`, `token_endpoint_auth_method` and `dpop_bound_access_tokens` stay Hamur's. */
|
|
37
|
+
clientMetadata?: Partial<AtprotoClientMetadata>
|
|
38
|
+
/** Default `["atproto"]`; `atproto` is added when missing. */
|
|
39
|
+
scope?: string[]
|
|
40
|
+
onSuccess(event: HamurEvent, result: AtprotoResult): unknown
|
|
41
|
+
onError?(event: HamurEvent, error: OAuthError): unknown
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface Resolved {
|
|
45
|
+
did: string
|
|
46
|
+
handle: string
|
|
47
|
+
issuer: string
|
|
48
|
+
par: string
|
|
49
|
+
authorize: string
|
|
50
|
+
token: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface FlowData {
|
|
54
|
+
did: string
|
|
55
|
+
handle: string
|
|
56
|
+
token: string
|
|
57
|
+
dpopKey: JsonWebKey
|
|
58
|
+
nonce?: string
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const PROVIDER = "atproto"
|
|
62
|
+
const UNRESOLVED = "AT Protocol handle could not be resolved"
|
|
63
|
+
const MISMATCH = "AT Protocol handle does not match its DID"
|
|
64
|
+
const DID = /^did:(?:plc:[a-z2-7]{24}|web:[a-z0-9.-]+)$/
|
|
65
|
+
// The token endpoint, the DID and the nonce are sealed in the flow cookie, which must stay under 4 KB.
|
|
66
|
+
const MAX_URL = 2048
|
|
67
|
+
const MAX_NONCE = 256
|
|
68
|
+
|
|
69
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
70
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
71
|
+
const isStrings = (value: unknown): value is string[] =>
|
|
72
|
+
Array.isArray(value) && value.every((entry) => typeof entry === "string")
|
|
73
|
+
function fail(reason: string): never {
|
|
74
|
+
throw new AtprotoResolveError(reason)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** What every `oauthAtproto` call of the app asked for, merged into the one client metadata document. */
|
|
78
|
+
const registered: { clientMetadata: Partial<AtprotoClientMetadata>; scope: string[] }[] = []
|
|
79
|
+
|
|
80
|
+
const appBase = (): string => baseURL.replace(/\/+$/, "")
|
|
81
|
+
const clientIdOf = (origin: string): string => `${origin}${appBase()}${ATPROTO_METADATA_ROUTE}`
|
|
82
|
+
|
|
83
|
+
export function atprotoClientMetadata(origin: string, paths: string[]): AtprotoClientMetadata {
|
|
84
|
+
const given = Object.assign(
|
|
85
|
+
{},
|
|
86
|
+
...registered.map(({ clientMetadata }) => clientMetadata).reverse(),
|
|
87
|
+
) as Partial<AtprotoClientMetadata>
|
|
88
|
+
const scope = [...new Set(registered.flatMap((entry) => entry.scope))]
|
|
89
|
+
return {
|
|
90
|
+
client_name: origin,
|
|
91
|
+
client_uri: origin,
|
|
92
|
+
redirect_uris: paths.map((path) => `${origin}${appBase()}${path}`),
|
|
93
|
+
scope: (scope.length ? scope : ["atproto"]).join(" "),
|
|
94
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
95
|
+
response_types: ["code"],
|
|
96
|
+
application_type: "web",
|
|
97
|
+
...given,
|
|
98
|
+
client_id: clientIdOf(origin),
|
|
99
|
+
token_endpoint_auth_method: "none",
|
|
100
|
+
dpop_bound_access_tokens: true,
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function json(url: string): Promise<Record<string, unknown>> {
|
|
105
|
+
const answer = await atprotoFetch(url, { headers: { accept: "application/json" } })
|
|
106
|
+
if (!answer.ok) fail(`${url} answered ${answer.status}`)
|
|
107
|
+
return parsed(answer) ?? fail(`${url} did not answer a JSON object`)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function parsed(answer: AtprotoAnswer): Record<string, unknown> | undefined {
|
|
111
|
+
try {
|
|
112
|
+
const value: unknown = JSON.parse(answer.text)
|
|
113
|
+
return isRecord(value) ? value : undefined
|
|
114
|
+
} catch {
|
|
115
|
+
return undefined
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function httpsURL(value: unknown, what: string): string {
|
|
120
|
+
if (typeof value !== "string") return fail(`${what} is missing`)
|
|
121
|
+
if (value.length > MAX_URL) return fail(`${what} is longer than ${MAX_URL} characters`)
|
|
122
|
+
const problem = urlProblem(value)
|
|
123
|
+
return problem === undefined ? value : fail(`${what} ${value}: ${problem}`)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function resolve(given: string | null): Promise<Resolved> {
|
|
127
|
+
const handle = (given ?? "").toLowerCase()
|
|
128
|
+
if (!handle) fail("no handle")
|
|
129
|
+
const syntax = hostProblem(handle)
|
|
130
|
+
if (syntax !== undefined) fail(`handle ${JSON.stringify(handle)}: ${syntax}`)
|
|
131
|
+
|
|
132
|
+
const named = await atprotoFetch(`https://${handle}/.well-known/atproto-did`, { headers: { accept: "text/plain" } })
|
|
133
|
+
if (!named.ok) fail(`https://${handle}/.well-known/atproto-did answered ${named.status}`)
|
|
134
|
+
const did = named.text.trim()
|
|
135
|
+
if (!DID.test(did)) fail(`https://${handle}/.well-known/atproto-did did not answer a did:plc or did:web`)
|
|
136
|
+
|
|
137
|
+
const document = await json(
|
|
138
|
+
did.startsWith("did:plc:")
|
|
139
|
+
? `https://plc.directory/${did}`
|
|
140
|
+
: `https://${did.slice("did:web:".length)}/.well-known/did.json`,
|
|
141
|
+
)
|
|
142
|
+
if (document.id !== did) fail(`the DID document of ${did} names another id`)
|
|
143
|
+
const aliases = isStrings(document.alsoKnownAs) ? document.alsoKnownAs : []
|
|
144
|
+
if (!aliases.some((alias) => alias.toLowerCase() === `at://${handle}`))
|
|
145
|
+
throw createError({ status: 401, message: MISMATCH })
|
|
146
|
+
|
|
147
|
+
const services = Array.isArray(document.service) ? document.service.filter(isRecord) : []
|
|
148
|
+
const pds = services.find(
|
|
149
|
+
(service) =>
|
|
150
|
+
(service.id === "#atproto_pds" || service.id === `${did}#atproto_pds`) &&
|
|
151
|
+
service.type === "AtprotoPersonalDataServer",
|
|
152
|
+
)
|
|
153
|
+
const pdsOrigin = new URL(httpsURL(pds?.serviceEndpoint, "the PDS")).origin
|
|
154
|
+
|
|
155
|
+
const resource = await json(`${pdsOrigin}/.well-known/oauth-protected-resource`)
|
|
156
|
+
const servers = isStrings(resource.authorization_servers) ? resource.authorization_servers : []
|
|
157
|
+
const issuer = new URL(httpsURL(servers[0], "the authorization server")).origin
|
|
158
|
+
|
|
159
|
+
const metadata = await json(`${issuer}/.well-known/oauth-authorization-server`)
|
|
160
|
+
if (metadata.issuer !== issuer) fail(`the authorization server metadata's issuer is not ${issuer}`)
|
|
161
|
+
return {
|
|
162
|
+
did,
|
|
163
|
+
handle,
|
|
164
|
+
issuer,
|
|
165
|
+
par: httpsURL(metadata.pushed_authorization_request_endpoint, "pushed_authorization_request_endpoint"),
|
|
166
|
+
authorize: httpsURL(metadata.authorization_endpoint, "authorization_endpoint"),
|
|
167
|
+
token: httpsURL(metadata.token_endpoint, "token_endpoint"),
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** A form `POST` with a DPoP proof; a `use_dpop_nonce` error is sent again once with the server's `DPoP-Nonce` (RFC 9449 §8). */
|
|
172
|
+
async function dpopPost(
|
|
173
|
+
url: string,
|
|
174
|
+
body: URLSearchParams,
|
|
175
|
+
key: JsonWebKey,
|
|
176
|
+
nonce: string | undefined,
|
|
177
|
+
): Promise<{ answer: AtprotoAnswer; json: Record<string, unknown> | undefined; nonce: string | undefined }> {
|
|
178
|
+
for (let attempt = 0; ; attempt++) {
|
|
179
|
+
const headers = {
|
|
180
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
181
|
+
accept: "application/json",
|
|
182
|
+
dpop: await dpopProof(key, "POST", url, nonce),
|
|
183
|
+
}
|
|
184
|
+
const answer = await atprotoFetch(url, { method: "POST", headers, body: body.toString() })
|
|
185
|
+
const fresh = answer.headers.get("dpop-nonce") ?? nonce
|
|
186
|
+
if (fresh !== undefined && fresh.length > MAX_NONCE)
|
|
187
|
+
fail(`${url} sent a DPoP-Nonce longer than ${MAX_NONCE} characters`)
|
|
188
|
+
const json = parsed(answer)
|
|
189
|
+
if (attempt === 0 && !answer.ok && json?.error === "use_dpop_nonce" && fresh !== undefined && fresh !== nonce) {
|
|
190
|
+
nonce = fresh
|
|
191
|
+
continue
|
|
192
|
+
}
|
|
193
|
+
return { answer, json, nonce: fresh }
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function unresolved(event: HamurEvent, error: unknown): never {
|
|
198
|
+
if (!(error instanceof AtprotoResolveError)) throw error
|
|
199
|
+
event.log.child({ name: "hamur" }).debug(UNRESOLVED, { reason: error.message })
|
|
200
|
+
throw createError({ status: 400, message: UNRESOLVED })
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const isFlowData = (value: unknown): value is FlowData =>
|
|
204
|
+
isRecord(value) &&
|
|
205
|
+
typeof value.did === "string" &&
|
|
206
|
+
typeof value.handle === "string" &&
|
|
207
|
+
typeof value.token === "string" &&
|
|
208
|
+
isRecord(value.dpopKey) &&
|
|
209
|
+
(value.nonce === undefined || typeof value.nonce === "string")
|
|
210
|
+
|
|
211
|
+
export function oauthAtproto(options: OAuthAtprotoOptions): (input: unknown, ctx: HandlerContext) => Promise<unknown> {
|
|
212
|
+
if (options.scope !== undefined && !isStrings(options.scope))
|
|
213
|
+
throw new TypeError("oauthAtproto scope must be an array of strings")
|
|
214
|
+
if (options.clientMetadata !== undefined && !isRecord(options.clientMetadata))
|
|
215
|
+
throw new TypeError("oauthAtproto clientMetadata must be an object")
|
|
216
|
+
const given = options.scope ?? ["atproto"]
|
|
217
|
+
const scope = given.includes("atproto") ? given : ["atproto", ...given]
|
|
218
|
+
registered.push({ clientMetadata: options.clientMetadata ?? {}, scope })
|
|
219
|
+
|
|
220
|
+
return createOAuthHandler(
|
|
221
|
+
{
|
|
222
|
+
authorizationURL: "https://atproto.invalid/",
|
|
223
|
+
tokenURL: "https://atproto.invalid/",
|
|
224
|
+
clientId: "",
|
|
225
|
+
scope,
|
|
226
|
+
tokenAuth: "none",
|
|
227
|
+
onSuccess: (event, { user, tokens }) =>
|
|
228
|
+
options.onSuccess(event, { ...(user as Omit<AtprotoResult, "tokens">), tokens }),
|
|
229
|
+
...(options.onError ? { onError: options.onError } : {}),
|
|
230
|
+
},
|
|
231
|
+
{
|
|
232
|
+
provider: PROVIDER,
|
|
233
|
+
clientId: (event) => clientIdOf(getRequestURL(event).origin),
|
|
234
|
+
clientSecret: () => "",
|
|
235
|
+
async authorize({ event, params }) {
|
|
236
|
+
try {
|
|
237
|
+
const target = await resolve(getRequestURL(event).searchParams.get("handle"))
|
|
238
|
+
const dpopKey = await createDPoPKey()
|
|
239
|
+
params.set("login_hint", target.handle)
|
|
240
|
+
const pushed = await dpopPost(target.par, params, dpopKey, undefined)
|
|
241
|
+
const requestURI = pushed.json?.request_uri
|
|
242
|
+
if (!pushed.answer.ok || typeof requestURI !== "string" || requestURI.length > MAX_URL) {
|
|
243
|
+
const error = typeof pushed.json?.error === "string" ? `: ${errorCode(pushed.json.error)}` : ""
|
|
244
|
+
fail(`the pushed authorization request answered ${pushed.answer.status}${error}`)
|
|
245
|
+
}
|
|
246
|
+
const location = new URL(target.authorize)
|
|
247
|
+
location.searchParams.set("client_id", params.get("client_id")!)
|
|
248
|
+
location.searchParams.set("request_uri", requestURI)
|
|
249
|
+
const data: FlowData = {
|
|
250
|
+
did: target.did,
|
|
251
|
+
handle: target.handle,
|
|
252
|
+
token: target.token,
|
|
253
|
+
dpopKey,
|
|
254
|
+
...(pushed.nonce === undefined ? {} : { nonce: pushed.nonce }),
|
|
255
|
+
}
|
|
256
|
+
return { location: location.href, issuer: target.issuer, data: { ...data } }
|
|
257
|
+
} catch (error) {
|
|
258
|
+
return unresolved(event, error)
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
async tokenRequest({ event, body, data }) {
|
|
262
|
+
if (!isFlowData(data)) throw createError({ status: 400, message: "Invalid OAuth state" })
|
|
263
|
+
let sent: Awaited<ReturnType<typeof dpopPost>>
|
|
264
|
+
try {
|
|
265
|
+
sent = await dpopPost(data.token, body, data.dpopKey, data.nonce)
|
|
266
|
+
} catch (error) {
|
|
267
|
+
return unresolved(event, error)
|
|
268
|
+
}
|
|
269
|
+
const granted = typeof sent.json?.scope === "string" ? sent.json.scope.split(" ") : []
|
|
270
|
+
const dpop = typeof sent.json?.token_type === "string" && sent.json.token_type.toLowerCase() === "dpop"
|
|
271
|
+
if (!sent.answer.ok || !sent.json || !dpop || !granted.includes("atproto")) {
|
|
272
|
+
const error =
|
|
273
|
+
typeof sent.json?.error === "string"
|
|
274
|
+
? { error: errorCode(sent.json.error) }
|
|
275
|
+
: sent.answer.ok
|
|
276
|
+
? { reason: "not a DPoP token with the atproto scope" }
|
|
277
|
+
: {}
|
|
278
|
+
event.log
|
|
279
|
+
.child({ name: "hamur" })
|
|
280
|
+
.warn("OAuth token request failed", { status: sent.answer.status, ...error })
|
|
281
|
+
throw createError({ status: 401, message: "OAuth token request failed" })
|
|
282
|
+
}
|
|
283
|
+
return sent.json
|
|
284
|
+
},
|
|
285
|
+
async profile({ tokens, data }) {
|
|
286
|
+
if (!isFlowData(data)) throw createError({ status: 400, message: "Invalid OAuth state" })
|
|
287
|
+
if (tokens.sub !== data.did) throw createError({ status: 401, message: MISMATCH })
|
|
288
|
+
return { did: data.did, handle: data.handle, dpopKey: data.dpopKey }
|
|
289
|
+
},
|
|
290
|
+
},
|
|
291
|
+
)
|
|
292
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { CookieOptions } from "hamur/server"
|
|
2
|
+
|
|
3
|
+
export interface FlowCookie {
|
|
4
|
+
name: string
|
|
5
|
+
options: Omit<CookieOptions, "maxAge" | "expires">
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The flow cookie of `route`, `__Host-hamur-<flow>-<first 16 hex of SHA-256(route)>` on `Path=/`, so a sibling
|
|
10
|
+
* subdomain cannot plant it; under `hamur dev` on plain http it is `hamur-<flow>-<h>` without `Secure`, which a `form_post` flow cannot use.
|
|
11
|
+
* An OAuth flow is `SameSite=Lax` (`None` for `form_post`), a WebAuthn one `Strict`.
|
|
12
|
+
*/
|
|
13
|
+
export async function flowCookie(options: {
|
|
14
|
+
dev: boolean
|
|
15
|
+
protocol: string
|
|
16
|
+
route: string
|
|
17
|
+
formPost: boolean
|
|
18
|
+
flow?: "oauth" | "webauthn"
|
|
19
|
+
}): Promise<FlowCookie> {
|
|
20
|
+
const flow = options.flow ?? "oauth"
|
|
21
|
+
const plainDev = options.dev && options.protocol === "http:"
|
|
22
|
+
if (options.formPost && plainDev) {
|
|
23
|
+
throw new TypeError(
|
|
24
|
+
'@hamur/auth: oauthHandler with responseMode "form_post" needs https under hamur dev: its flow cookie is SameSite=None, which a browser drops without Secure; set devServer.https',
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(options.route)))
|
|
28
|
+
const hash = Array.from(digest.subarray(0, 8), (byte) => byte.toString(16).padStart(2, "0")).join("")
|
|
29
|
+
return {
|
|
30
|
+
name: `${plainDev ? "" : "__Host-"}hamur-${flow}-${hash}`,
|
|
31
|
+
options: {
|
|
32
|
+
path: "/",
|
|
33
|
+
httpOnly: true,
|
|
34
|
+
secure: !plainDev,
|
|
35
|
+
sameSite: flow === "webauthn" ? "strict" : options.formPost ? "none" : "lax",
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { toBase64Url } from "hamur/server/internal"
|
|
2
|
+
|
|
3
|
+
const ALGORITHM = { name: "ECDSA", namedCurve: "P-256" } as const
|
|
4
|
+
const encoder = new TextEncoder()
|
|
5
|
+
const part = (value: unknown): string => toBase64Url(encoder.encode(JSON.stringify(value)))
|
|
6
|
+
|
|
7
|
+
/** A new ES256 key for one flow's DPoP proofs (RFC 9449), as its private JWK. */
|
|
8
|
+
export async function createDPoPKey(): Promise<JsonWebKey> {
|
|
9
|
+
const pair = (await crypto.subtle.generateKey(ALGORITHM, true, ["sign", "verify"])) as CryptoKeyPair
|
|
10
|
+
const { kty, crv, x, y, d } = await crypto.subtle.exportKey("jwk", pair.privateKey)
|
|
11
|
+
return { kty, crv, x, y, d }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** RFC 9449 §4.2: a `dpop+jwt` proof for `method` and `url` (its query and fragment dropped), signed with `key`, with the server's `nonce` when it gave one. */
|
|
15
|
+
export async function dpopProof(key: JsonWebKey, method: string, url: string, nonce?: string): Promise<string> {
|
|
16
|
+
const { kty, crv, x, y } = key
|
|
17
|
+
const target = new URL(url)
|
|
18
|
+
const header = { typ: "dpop+jwt", alg: "ES256", jwk: { kty, crv, x, y } }
|
|
19
|
+
const payload = {
|
|
20
|
+
jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16))),
|
|
21
|
+
htm: method,
|
|
22
|
+
htu: `${target.origin}${target.pathname}`,
|
|
23
|
+
iat: Math.floor(Date.now() / 1000),
|
|
24
|
+
...(nonce === undefined ? {} : { nonce }),
|
|
25
|
+
}
|
|
26
|
+
const input = `${part(header)}.${part(payload)}`
|
|
27
|
+
const signing = await crypto.subtle.importKey("jwk", { kty, crv, x, y, d: key.d }, ALGORITHM, false, ["sign"])
|
|
28
|
+
const signature = new Uint8Array(
|
|
29
|
+
await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, signing, encoder.encode(input)),
|
|
30
|
+
)
|
|
31
|
+
return `${input}.${toBase64Url(signature)}`
|
|
32
|
+
}
|