@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,104 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import { DiagnosticError, addTemplate, hasStorageMount, type HamurContext } from "hamur/kit"
|
|
4
|
+
import { inProcessDriver, singleUseProblem, type SingleUseMount, type SingleUseName } from "../single-use.ts"
|
|
5
|
+
import { usedHandlers } from "./webauthn.ts"
|
|
6
|
+
|
|
7
|
+
const SERVER = "@hamur/auth/server"
|
|
8
|
+
const SOURCE = /\.(?:[cm]?[jt]s|[jt]sx)$/
|
|
9
|
+
const IGNORED_FILE = /\.(test|spec)\.[^/]+$|\.d\.[cm]?ts$/
|
|
10
|
+
// Matched against the transpiler's printed output: one canonical form, comments gone, type-only imports dropped.
|
|
11
|
+
const NAMED_IMPORT = /^import\s+(?:[\w$]+\s*,\s*)?\{([^}]*)\}\s*from\s*"@hamur\/auth\/server"/gm
|
|
12
|
+
const NAMESPACE_IMPORT = /^import\s+(?:[\w$]+\s*,\s*)?\*\s*as\s+([\w$]+)\s+from\s*"@hamur\/auth\/server"/gm
|
|
13
|
+
|
|
14
|
+
/** The app source files under `dir`, without tests, declaration files, `node_modules` and dot folders. */
|
|
15
|
+
export function sourceFiles(dir: string): string[] {
|
|
16
|
+
if (!existsSync(dir)) return []
|
|
17
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((entry): string[] => {
|
|
18
|
+
const path = join(dir, entry.name)
|
|
19
|
+
if (entry.isDirectory()) return entry.name === "node_modules" || entry.name.startsWith(".") ? [] : sourceFiles(path)
|
|
20
|
+
return SOURCE.test(entry.name) && !IGNORED_FILE.test(entry.name) ? [path] : []
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const TRANSPILERS = {
|
|
25
|
+
ts: new Bun.Transpiler({ loader: "ts" }),
|
|
26
|
+
tsx: new Bun.Transpiler({ loader: "tsx" }),
|
|
27
|
+
jsx: new Bun.Transpiler({ loader: "jsx" }),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The server names whose import the build looks for, after the passkey handlers it finds by their handler files. */
|
|
31
|
+
const IMPORTED = ["consumeAuthToken", "verifyTotp"] as const satisfies readonly SingleUseName[]
|
|
32
|
+
|
|
33
|
+
/** `text` imports `name` from `@hamur/auth/server` as a value: by name, or through a namespace it reads it from; comments and strings do not count. `kind` is the file's loader. */
|
|
34
|
+
export function importsAuthName(name: string, text: string, kind: keyof typeof TRANSPILERS = "ts"): boolean {
|
|
35
|
+
const transpiler = TRANSPILERS[kind]
|
|
36
|
+
let source: string
|
|
37
|
+
try {
|
|
38
|
+
if (!transpiler.scanImports(text).some((entry) => entry.kind === "import-statement" && entry.path === SERVER))
|
|
39
|
+
return false
|
|
40
|
+
source = transpiler.transformSync(text)
|
|
41
|
+
} catch {
|
|
42
|
+
return false
|
|
43
|
+
}
|
|
44
|
+
const named = new RegExp(`^${name}\\b`)
|
|
45
|
+
for (const [, names] of source.matchAll(NAMED_IMPORT)) {
|
|
46
|
+
if (names!.split(",").some((part) => named.test(part.trim()))) return true
|
|
47
|
+
}
|
|
48
|
+
for (const [, space] of source.matchAll(NAMESPACE_IMPORT)) {
|
|
49
|
+
if (new RegExp(`\\b${space!.replace(/\$/g, "\\$")}\\s*\\.\\s*${name}\\b`).test(source)) return true
|
|
50
|
+
}
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const loaderOf = (file: string): keyof typeof TRANSPILERS =>
|
|
55
|
+
file.endsWith("x") ? (file.endsWith("tsx") ? "tsx" : "jsx") : "ts"
|
|
56
|
+
|
|
57
|
+
/** `name` is imported from `@hamur/auth/server` in a server file of the app or of a layer. */
|
|
58
|
+
export function serverImports(hamur: HamurContext): (name: string) => boolean {
|
|
59
|
+
const dirs = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)]
|
|
60
|
+
const files = dirs.flatMap((dir) =>
|
|
61
|
+
sourceFiles(dir).map((file) => ({ text: readFileSync(file, "utf8"), kind: loaderOf(file) })),
|
|
62
|
+
)
|
|
63
|
+
return (name) => files.some((file) => importsAuthName(name, file.text, file.kind))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The single-use names the app uses: the passkey handlers, then `consumeAuthToken` and `verifyTotp` imported in a server file. */
|
|
67
|
+
function usedNames(hamur: HamurContext): SingleUseName[] {
|
|
68
|
+
return [...usedHandlers(hamur), ...IMPORTED.filter(serverImports(hamur))]
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The build's `session` mount: `storage.session`, else the preset's default; `null` for a driver that is not built in, which the first call checks by the name it gives itself. */
|
|
72
|
+
function sessionMount(hamur: HamurContext): SingleUseMount | null {
|
|
73
|
+
const configured = hamur.options.storage.session
|
|
74
|
+
if (configured) {
|
|
75
|
+
if (typeof configured.builtIn !== "string") return null
|
|
76
|
+
const options = (configured.options ?? {}) as { encrypt?: unknown }
|
|
77
|
+
return { driver: configured.builtIn, encrypt: options.encrypt !== undefined }
|
|
78
|
+
}
|
|
79
|
+
if (!hasStorageMount("session")) return undefined
|
|
80
|
+
return {
|
|
81
|
+
driver: hamur.options.preset === "cloudflare" && !hamur.options.dev ? "cloudflare-kv" : "fs",
|
|
82
|
+
encrypt: false,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The build check of the `session` mount for single-use challenges and tokens, and what the first call and the start read. */
|
|
87
|
+
export function setupSingleUse(hamur: HamurContext): void {
|
|
88
|
+
let inProcess: string | undefined
|
|
89
|
+
addTemplate({
|
|
90
|
+
filename: "auth/single-use",
|
|
91
|
+
getContents: (ctx) =>
|
|
92
|
+
`export const singleUse = ${JSON.stringify({ preset: ctx.options.preset, ...(inProcess === undefined ? {} : { inProcess }) })};\n`,
|
|
93
|
+
})
|
|
94
|
+
hamur.hooks.hook("build:before", () => {
|
|
95
|
+
inProcess = undefined
|
|
96
|
+
const [name] = usedNames(hamur)
|
|
97
|
+
if (name === undefined) return
|
|
98
|
+
const mount = sessionMount(hamur)
|
|
99
|
+
if (mount === null) return
|
|
100
|
+
const problem = singleUseProblem(mount, { name, preset: hamur.options.preset, dev: hamur.options.dev })
|
|
101
|
+
if (problem) throw new DiagnosticError("HAMUR_E5103", problem)
|
|
102
|
+
inProcess = inProcessDriver(mount)
|
|
103
|
+
})
|
|
104
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { addTemplate, type HamurContext } from "hamur/kit"
|
|
2
|
+
import type { SingleUseName } from "../single-use.ts"
|
|
3
|
+
import type { ResolvedAuthOptions } from "../types.ts"
|
|
4
|
+
|
|
5
|
+
const SERVER = "@hamur/auth/server"
|
|
6
|
+
const HANDLERS = ["webAuthnRegister", "webAuthnAuthenticate"] as const satisfies readonly SingleUseName[]
|
|
7
|
+
|
|
8
|
+
/** The passkey helpers the app's handlers are written as a call of (`handler: webAuthnRegister({ … })`). */
|
|
9
|
+
export function usedHandlers(hamur: HamurContext): SingleUseName[] {
|
|
10
|
+
return HANDLERS.filter((name) =>
|
|
11
|
+
hamur.serverRoutes.some(({ fn }) => fn.handlerImport?.from === SERVER && fn.handlerImport.name === name),
|
|
12
|
+
)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The relying party the handlers read and the start checks' inputs; the `session` mount's check is `setupSingleUse`'s. */
|
|
16
|
+
export function setupWebAuthn(options: ResolvedAuthOptions, hamur: HamurContext): void {
|
|
17
|
+
addTemplate({
|
|
18
|
+
filename: "auth/webauthn",
|
|
19
|
+
getContents: (ctx) => {
|
|
20
|
+
const value = {
|
|
21
|
+
...options.webauthn,
|
|
22
|
+
used: usedHandlers(ctx).length > 0,
|
|
23
|
+
listedHosts: Array.isArray(ctx.options.server.allowedHosts),
|
|
24
|
+
}
|
|
25
|
+
return `export const webauthn = ${JSON.stringify(value)};\n`
|
|
26
|
+
},
|
|
27
|
+
})
|
|
28
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { $fetch } from "hamur/app"
|
|
2
|
+
|
|
3
|
+
export interface WebAuthnOptions {
|
|
4
|
+
registerEndpoint: string
|
|
5
|
+
authenticateEndpoint: string
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface WebAuthnUser {
|
|
9
|
+
userName: string
|
|
10
|
+
displayName?: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** What every adapter's `useWebAuthn` calls; `isSupported` is the adapter's own reactive value. */
|
|
14
|
+
export interface WebAuthnCalls {
|
|
15
|
+
register(user: WebAuthnUser): Promise<unknown>
|
|
16
|
+
authenticate(userName?: string): Promise<unknown>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type Json = Record<string, any>
|
|
20
|
+
|
|
21
|
+
interface Statics {
|
|
22
|
+
parseCreationOptionsFromJSON?(json: Json): unknown
|
|
23
|
+
parseRequestOptionsFromJSON?(json: Json): unknown
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface WebAuthnEnv {
|
|
27
|
+
post(url: string, body: unknown): Promise<unknown>
|
|
28
|
+
credentials: {
|
|
29
|
+
create(options: { publicKey: unknown }): Promise<unknown>
|
|
30
|
+
get(options: { publicKey: unknown }): Promise<unknown>
|
|
31
|
+
}
|
|
32
|
+
PublicKeyCredential?: Statics
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A secure context that has `PublicKeyCredential`. */
|
|
36
|
+
export function webAuthnSupported(): boolean {
|
|
37
|
+
return typeof window !== "undefined" && window.isSecureContext === true && typeof PublicKeyCredential === "function"
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function toBase64Url(bytes: ArrayBuffer | ArrayBufferView): string {
|
|
41
|
+
const view = ArrayBuffer.isView(bytes)
|
|
42
|
+
? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
43
|
+
: new Uint8Array(bytes)
|
|
44
|
+
let text = ""
|
|
45
|
+
for (const byte of view) text += String.fromCharCode(byte)
|
|
46
|
+
return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function fromBase64Url(text: string): Uint8Array<ArrayBuffer> {
|
|
50
|
+
const base64 = text.replace(/-/g, "+").replace(/_/g, "/")
|
|
51
|
+
const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4))
|
|
52
|
+
const bytes = new Uint8Array(binary.length)
|
|
53
|
+
for (let at = 0; at < binary.length; at++) bytes[at] = binary.charCodeAt(at)
|
|
54
|
+
return bytes
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const withIds = (list: unknown): unknown =>
|
|
58
|
+
Array.isArray(list) ? list.map((entry: Json) => ({ ...entry, id: fromBase64Url(entry.id) })) : list
|
|
59
|
+
|
|
60
|
+
/** `PublicKeyCredential.parseCreationOptionsFromJSON` where the browser has it, else the same conversion of `challenge`, `user.id` and the excluded ids. */
|
|
61
|
+
function creationOptions(json: Json, statics: Statics | undefined): unknown {
|
|
62
|
+
if (typeof statics?.parseCreationOptionsFromJSON === "function") return statics.parseCreationOptionsFromJSON(json)
|
|
63
|
+
return {
|
|
64
|
+
...json,
|
|
65
|
+
challenge: fromBase64Url(json.challenge),
|
|
66
|
+
user: { ...json.user, id: fromBase64Url(json.user.id) },
|
|
67
|
+
excludeCredentials: withIds(json.excludeCredentials),
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** `PublicKeyCredential.parseRequestOptionsFromJSON` where the browser has it, else the same conversion of `challenge` and the allowed ids. */
|
|
72
|
+
function requestOptions(json: Json, statics: Statics | undefined): unknown {
|
|
73
|
+
if (typeof statics?.parseRequestOptionsFromJSON === "function") return statics.parseRequestOptionsFromJSON(json)
|
|
74
|
+
return { ...json, challenge: fromBase64Url(json.challenge), allowCredentials: withIds(json.allowCredentials) }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** `credential.toJSON()` where the browser has it, else its fields in base64url, the shape `PublicKeyCredential.toJSON()` gives. */
|
|
78
|
+
function credentialJSON(credential: Json): unknown {
|
|
79
|
+
if (typeof credential.toJSON === "function") return credential.toJSON()
|
|
80
|
+
const response = credential.response as Json
|
|
81
|
+
const fields: Json = { clientDataJSON: toBase64Url(response.clientDataJSON) }
|
|
82
|
+
if (response.attestationObject) {
|
|
83
|
+
fields.attestationObject = toBase64Url(response.attestationObject)
|
|
84
|
+
if (typeof response.getTransports === "function") fields.transports = response.getTransports()
|
|
85
|
+
} else {
|
|
86
|
+
fields.authenticatorData = toBase64Url(response.authenticatorData)
|
|
87
|
+
fields.signature = toBase64Url(response.signature)
|
|
88
|
+
if (response.userHandle) fields.userHandle = toBase64Url(response.userHandle)
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
id: credential.id,
|
|
92
|
+
rawId: toBase64Url(credential.rawId),
|
|
93
|
+
type: credential.type,
|
|
94
|
+
...(credential.authenticatorAttachment ? { authenticatorAttachment: credential.authenticatorAttachment } : {}),
|
|
95
|
+
response: fields,
|
|
96
|
+
clientExtensionResults:
|
|
97
|
+
typeof credential.getClientExtensionResults === "function" ? credential.getClientExtensionResults() : {},
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const browserEnv = (): WebAuthnEnv => ({
|
|
102
|
+
post: (url, body) => $fetch(url, { method: "POST", body }),
|
|
103
|
+
credentials: navigator.credentials as unknown as WebAuthnEnv["credentials"],
|
|
104
|
+
PublicKeyCredential: PublicKeyCredential as unknown as Statics,
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
/** The two steps of `webAuthnRegister` and `webAuthnAuthenticate`, `options` then `verify`. A refused step rejects with the `FetchError` of its answer. */
|
|
108
|
+
export function webAuthn(options: WebAuthnOptions, env?: WebAuthnEnv): WebAuthnCalls {
|
|
109
|
+
const use = (): WebAuthnEnv => (env ??= browserEnv())
|
|
110
|
+
return {
|
|
111
|
+
async register(user) {
|
|
112
|
+
const { post, credentials, PublicKeyCredential } = use()
|
|
113
|
+
const json = (await post(options.registerEndpoint, { step: "options", user })) as Json
|
|
114
|
+
const credential = await credentials.create({ publicKey: creationOptions(json, PublicKeyCredential) })
|
|
115
|
+
if (!credential) throw new Error("WebAuthn registration returned no credential")
|
|
116
|
+
return post(options.registerEndpoint, { step: "verify", response: credentialJSON(credential as Json) })
|
|
117
|
+
},
|
|
118
|
+
async authenticate(userName) {
|
|
119
|
+
const { post, credentials, PublicKeyCredential } = use()
|
|
120
|
+
const json = (await post(options.authenticateEndpoint, {
|
|
121
|
+
step: "options",
|
|
122
|
+
...(userName === undefined ? {} : { user: { userName } }),
|
|
123
|
+
})) as Json
|
|
124
|
+
const credential = await credentials.get({ publicKey: requestOptions(json, PublicKeyCredential) })
|
|
125
|
+
if (!credential) throw new Error("WebAuthn sign-in returned no credential")
|
|
126
|
+
return post(options.authenticateEndpoint, { step: "verify", response: credentialJSON(credential as Json) })
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
}
|
package/src/env.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
declare module "#hamur/auth/options" {
|
|
2
|
+
export const session: import("./types.ts").ResolvedAuthOptions["session"]
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
interface ImportMeta {
|
|
6
|
+
readonly dev?: boolean
|
|
7
|
+
readonly prerender?: boolean
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
declare module "#hamur/auth/client" {
|
|
11
|
+
export const loadStrategy: import("./types.ts").AuthLoadStrategy
|
|
12
|
+
/** False for `"none"` and for html, whose pages do not re-render on the client. */
|
|
13
|
+
export const fetchAfterMount: boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
declare module "#hamur/auth/guards" {
|
|
17
|
+
export const redirect: import("./types.ts").ResolvedAuthOptions["redirect"]
|
|
18
|
+
export const baseURL: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
declare module "#hamur/auth/oauth" {
|
|
22
|
+
/** `auth.oauth` of the config, by provider. */
|
|
23
|
+
export const oauth: Record<string, Record<string, unknown>>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
declare module "#hamur/auth/webauthn" {
|
|
27
|
+
/** `auth.webauthn` of the config, and what the start checks and the single-use check read. */
|
|
28
|
+
export const webauthn: import("./types.ts").WebAuthnConfig & {
|
|
29
|
+
/** An app handler is written as a call of `webAuthnRegister` or `webAuthnAuthenticate`. */
|
|
30
|
+
used: boolean
|
|
31
|
+
/** `server.allowedHosts` is a list. */
|
|
32
|
+
listedHosts: boolean
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
declare module "#hamur/auth/single-use" {
|
|
37
|
+
/** What the first call's and the start's single-use checks read. */
|
|
38
|
+
export const singleUse: {
|
|
39
|
+
preset: string
|
|
40
|
+
/** The `session` mount's driver when the app uses a single-use name and the mount counts in one process only (`memory`, `fs`). */
|
|
41
|
+
inProcess?: string
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
declare module "#hamur/auth/email" {
|
|
46
|
+
export const email: import("./types.ts").ResolvedAuthOptions["email"]
|
|
47
|
+
/** `site.url` of the config; the server's resolved site is read first. */
|
|
48
|
+
export const siteUrl: string | null
|
|
49
|
+
/** The names of the `app/mail/` templates. */
|
|
50
|
+
export const templates: readonly string[]
|
|
51
|
+
/** `@hamur/mail/server`, declared here since `@hamur/auth` does not depend on it; `undefined` when `@hamur/mail` is not in `modules`. */
|
|
52
|
+
export const loadMail:
|
|
53
|
+
| (() => Promise<{
|
|
54
|
+
sendMail(message: {
|
|
55
|
+
to: { address: string }
|
|
56
|
+
subject: string
|
|
57
|
+
html?: string
|
|
58
|
+
template?: string
|
|
59
|
+
props?: Record<string, unknown>
|
|
60
|
+
}): Promise<unknown>
|
|
61
|
+
}>)
|
|
62
|
+
| undefined
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
declare module "#hamur/auth/access-tokens" {
|
|
66
|
+
interface TokenDatabase {
|
|
67
|
+
first<T>(strings: TemplateStringsArray, ...values: Array<string | null>): PromiseLike<T | undefined>
|
|
68
|
+
run(strings: TemplateStringsArray, ...values: Array<string | null>): PromiseLike<unknown>
|
|
69
|
+
}
|
|
70
|
+
/** `undefined` without `auth.accessTokens`; `loadDb` is `@hamur/db/server`, declared here since `@hamur/auth` does not depend on it. */
|
|
71
|
+
export const accessTokens:
|
|
72
|
+
| {
|
|
73
|
+
loadDb(): Promise<{ useDatabase(): TokenDatabase }>
|
|
74
|
+
loadUser(): Promise<{ default(userId: string): Promise<import("./index.ts").User | null> }>
|
|
75
|
+
}
|
|
76
|
+
| undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
declare module "#hamur/auth/atproto" {
|
|
80
|
+
/** The app's `oauthAtproto` routes without a parameter, below `app.baseURL`; `load` imports the module that defines each */
|
|
81
|
+
export const routes: { path: string; load(): Promise<unknown> }[]
|
|
82
|
+
/** node and bun presets: a fetch that refuses a host resolving to a blocked address and connects to the address it checked; else `undefined`. */
|
|
83
|
+
export const hostFetch: ((url: string, init: RequestInit) => Promise<Response>) | undefined
|
|
84
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { HamurEvent } from "hamur/server"
|
|
2
|
+
import type { AuthConfig } from "./types.ts"
|
|
3
|
+
|
|
4
|
+
export { default } from "./module.ts"
|
|
5
|
+
export type { AuthConfig, AuthLoadStrategy, AuthSessionConfig } from "./types.ts"
|
|
6
|
+
|
|
7
|
+
/** The signed-in user; an app adds its fields with `declare module "@hamur/auth" { interface User { … } }`. */
|
|
8
|
+
export interface User {}
|
|
9
|
+
|
|
10
|
+
/** Fields of the user session besides `user` and `secure`, added the same way. */
|
|
11
|
+
export interface UserSession {}
|
|
12
|
+
|
|
13
|
+
/** Fields kept in the session that never leave the server: not in the session endpoint, not in the payload. */
|
|
14
|
+
export interface SecureSessionData {}
|
|
15
|
+
|
|
16
|
+
export type UserSessionData = UserSession & { user?: User; secure?: SecureSessionData }
|
|
17
|
+
|
|
18
|
+
/** The user session as the session endpoint answers it: without `id` and `secure`. */
|
|
19
|
+
export type PublicUserSession = Omit<UserSessionData, "secure">
|
|
20
|
+
|
|
21
|
+
/** The access token of the request, as `requireAccessToken` puts it on `event.context`. */
|
|
22
|
+
export interface AccessToken {
|
|
23
|
+
id: string
|
|
24
|
+
scopes: string[]
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
declare module "hamur" {
|
|
28
|
+
interface HamurModuleOptions {
|
|
29
|
+
auth?: AuthConfig
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
declare module "hamur/server" {
|
|
34
|
+
interface HamurEventContext {
|
|
35
|
+
/** Set by `requireAccessToken`, with the token's user as `user`. */
|
|
36
|
+
accessToken?: AccessToken
|
|
37
|
+
}
|
|
38
|
+
interface ServerHooks {
|
|
39
|
+
/** Before `GET <baseURL>_hamur/auth/session` answers a session with keys; may add fields, and a throw is the answer. */
|
|
40
|
+
"auth:session:fetch": (session: PublicUserSession, event: HamurEvent) => void | Promise<void>
|
|
41
|
+
/** Before `clearUserSession` (and `DELETE <baseURL>_hamur/auth/session`) clears the session. */
|
|
42
|
+
"auth:session:clear": (session: UserSessionData & { id: string }, event: HamurEvent) => void | Promise<void>
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { defineMiddleware } from "hamur/app"
|
|
2
|
+
import { accessTokenGuard } from "./server/access-token.ts"
|
|
3
|
+
import { guard } from "./server/guard.ts"
|
|
4
|
+
|
|
5
|
+
/** The user session or the 401, and `{ user, session }` on the context; in a request list a document request goes to `auth.redirect.login` instead. */
|
|
6
|
+
export const requireUser = defineMiddleware({ server: guard })
|
|
7
|
+
|
|
8
|
+
/** The user and the scopes of the request's access token, or the 401; a session cookie does not stand in for the token. */
|
|
9
|
+
export const requireAccessToken = defineMiddleware({ server: accessTokenGuard })
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { defineModule } from "hamur/kit"
|
|
2
|
+
import { setupAccessTokens } from "./build/access-tokens.ts"
|
|
3
|
+
import { setupClient } from "./build/client.ts"
|
|
4
|
+
import { setupEmail } from "./build/email.ts"
|
|
5
|
+
import { setupGuards } from "./build/guards.ts"
|
|
6
|
+
import { setupOAuth } from "./build/oauth.ts"
|
|
7
|
+
import { setupSession } from "./build/session.ts"
|
|
8
|
+
import { setupSingleUse } from "./build/single-use.ts"
|
|
9
|
+
import { setupWebAuthn } from "./build/webauthn.ts"
|
|
10
|
+
import { resolveOptions } from "./options.ts"
|
|
11
|
+
import type { AuthConfig } from "./types.ts"
|
|
12
|
+
|
|
13
|
+
export default defineModule<AuthConfig>({
|
|
14
|
+
meta: { name: "auth", configKey: "auth" },
|
|
15
|
+
setup(input, hamur) {
|
|
16
|
+
const options = resolveOptions(input)
|
|
17
|
+
setupSession(options, hamur)
|
|
18
|
+
setupClient(options, hamur)
|
|
19
|
+
setupGuards(options, hamur)
|
|
20
|
+
setupOAuth(options, hamur)
|
|
21
|
+
setupWebAuthn(options, hamur)
|
|
22
|
+
setupSingleUse(hamur)
|
|
23
|
+
setupEmail(options, hamur)
|
|
24
|
+
setupAccessTokens(options, hamur)
|
|
25
|
+
},
|
|
26
|
+
})
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { isAppPath } from "./runtime/targets.ts"
|
|
2
|
+
import { OAUTH_PROVIDERS, providerKeys } from "./server/oauth/providers/catalog.ts"
|
|
3
|
+
import type { AuthLinkPurpose, ResolvedAuthOptions } from "./types.ts"
|
|
4
|
+
import { DiagnosticError, isEnvRef } from "hamur/kit"
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_MAX_AGE = 604_800
|
|
7
|
+
|
|
8
|
+
const TOP_KEYS = ["session", "loadStrategy", "redirect", "oauth", "webauthn", "email", "accessTokens"]
|
|
9
|
+
const WEBAUTHN_KEYS = ["rpID", "rpName", "origins"]
|
|
10
|
+
const EMAIL_KEYS = ["page", "template", "subject", "ttl"]
|
|
11
|
+
const EMAIL: ResolvedAuthOptions["email"] = {
|
|
12
|
+
"magic-link": { page: "/auth/magic-link", template: "AuthMagicLink", ttl: 900 },
|
|
13
|
+
"verify-email": { page: "/auth/verify-email", template: "AuthVerifyEmail", ttl: 86_400 },
|
|
14
|
+
"password-reset": { page: "/auth/reset-password", template: "AuthPasswordReset", ttl: 3600 },
|
|
15
|
+
}
|
|
16
|
+
const HOST_NAME = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/
|
|
17
|
+
const REDIRECT_KEYS = ["login", "home"]
|
|
18
|
+
const LOAD_STRATEGIES = ["server-first", "client-only", "none"]
|
|
19
|
+
const SESSION_KEYS = ["name", "password", "maxAge", "idleTimeout", "storage", "cookie"]
|
|
20
|
+
const COOKIE_KEYS = ["domain", "path", "httpOnly", "secure", "sameSite", "partitioned"]
|
|
21
|
+
const SAME_SITE = ["lax", "strict", "none"]
|
|
22
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
|
|
23
|
+
const MIN_PASSWORD = 32
|
|
24
|
+
|
|
25
|
+
function fail(message: string): never {
|
|
26
|
+
throw new DiagnosticError("HAMUR_E5101", message)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function shown(value: unknown): string {
|
|
30
|
+
if (Array.isArray(value)) return "an array"
|
|
31
|
+
if (typeof value === "function") return "a function"
|
|
32
|
+
if (value === undefined) return "undefined"
|
|
33
|
+
return JSON.stringify(value)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
37
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
38
|
+
|
|
39
|
+
function onlyKeys(at: string, value: Record<string, unknown>, keys: string[]): void {
|
|
40
|
+
for (const key of Object.keys(value))
|
|
41
|
+
if (!keys.includes(key)) fail(`${at} has no ${JSON.stringify(key)} (it takes: ${keys.join(", ")})`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function seconds(at: string, value: unknown): number | undefined {
|
|
45
|
+
if (value === undefined) return undefined
|
|
46
|
+
if (!(typeof value === "number" && Number.isSafeInteger(value) && value >= 1))
|
|
47
|
+
fail(`${at} must be a positive integer of seconds (got ${shown(value)})`)
|
|
48
|
+
return value
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `auth.oauth`, one object of config keys per provider preset; secret keys take the text or `env("NAME")`, and `""` is unset. */
|
|
52
|
+
function resolveOAuth(input: unknown): Record<string, Record<string, unknown>> {
|
|
53
|
+
if (input === undefined) return {}
|
|
54
|
+
if (!isObject(input)) fail(`auth.oauth must be an object (got ${shown(input)})`)
|
|
55
|
+
onlyKeys("auth.oauth", input, Object.keys(OAUTH_PROVIDERS))
|
|
56
|
+
const resolved: Record<string, Record<string, unknown>> = {}
|
|
57
|
+
for (const [name, config] of Object.entries(input)) {
|
|
58
|
+
const at = `auth.oauth.${name}`
|
|
59
|
+
if (!isObject(config)) fail(`${at} must be an object (got ${shown(config)})`)
|
|
60
|
+
const { secrets } = OAUTH_PROVIDERS[name]!
|
|
61
|
+
onlyKeys(at, config, providerKeys(name))
|
|
62
|
+
const kept: Record<string, unknown> = {}
|
|
63
|
+
for (const [key, value] of Object.entries(config)) {
|
|
64
|
+
if (value === undefined || value === "") continue
|
|
65
|
+
kept[key] = value
|
|
66
|
+
if (secrets.includes(key)) {
|
|
67
|
+
if (typeof value !== "string" && !isEnvRef(value)) fail(`${at}.${key} must be a string or env("NAME")`)
|
|
68
|
+
} else if (typeof value !== "string") fail(`${at}.${key} must be a string (got ${shown(value)})`)
|
|
69
|
+
}
|
|
70
|
+
resolved[name] = kept
|
|
71
|
+
}
|
|
72
|
+
return resolved
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isOrigin(value: unknown): value is string {
|
|
76
|
+
if (typeof value !== "string") return false
|
|
77
|
+
try {
|
|
78
|
+
const url = new URL(value)
|
|
79
|
+
return (url.protocol === "https:" || url.protocol === "http:") && url.origin === value
|
|
80
|
+
} catch {
|
|
81
|
+
return false
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `auth.webauthn`; `rpID` must be each origin's host or a parent domain of it. */
|
|
86
|
+
function resolveWebAuthn(input: unknown): ResolvedAuthOptions["webauthn"] {
|
|
87
|
+
if (input === undefined) return {}
|
|
88
|
+
if (!isObject(input)) fail(`auth.webauthn must be an object (got ${shown(input)})`)
|
|
89
|
+
onlyKeys("auth.webauthn", input, WEBAUTHN_KEYS)
|
|
90
|
+
const { rpID, rpName, origins } = input
|
|
91
|
+
if (rpID !== undefined && !(typeof rpID === "string" && HOST_NAME.test(rpID)))
|
|
92
|
+
fail(`auth.webauthn.rpID must be a lowercase host name such as "example.com" (got ${shown(rpID)})`)
|
|
93
|
+
if (rpName !== undefined && !(typeof rpName === "string" && rpName !== ""))
|
|
94
|
+
fail(`auth.webauthn.rpName must be a non-empty string (got ${shown(rpName)})`)
|
|
95
|
+
if (origins !== undefined) {
|
|
96
|
+
if (!Array.isArray(origins) || !origins.length)
|
|
97
|
+
fail(
|
|
98
|
+
`auth.webauthn.origins must be a non-empty array of origins such as "https://example.com" (got ${shown(origins)})`,
|
|
99
|
+
)
|
|
100
|
+
for (const origin of origins) {
|
|
101
|
+
if (!isOrigin(origin))
|
|
102
|
+
fail(`auth.webauthn.origins entry ${shown(origin)} must be an origin such as "https://example.com"`)
|
|
103
|
+
const host = new URL(origin).hostname
|
|
104
|
+
if (typeof rpID === "string" && host !== rpID && !host.endsWith(`.${rpID}`))
|
|
105
|
+
fail(
|
|
106
|
+
`auth.webauthn.rpID ${JSON.stringify(rpID)} is not the host or a parent domain of origin ${JSON.stringify(origin)}`,
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
...(rpID === undefined ? {} : { rpID: rpID as string }),
|
|
112
|
+
...(rpName === undefined ? {} : { rpName: rpName as string }),
|
|
113
|
+
...(origins === undefined ? {} : { origins: [...(origins as string[])] }),
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** `auth.email` with the defaults; a purpose's `subject` defaults where `site.name` is known. */
|
|
118
|
+
function resolveEmail(input: unknown): ResolvedAuthOptions["email"] {
|
|
119
|
+
const email = input === undefined ? {} : input
|
|
120
|
+
if (!isObject(email)) fail(`auth.email must be an object (got ${shown(email)})`)
|
|
121
|
+
onlyKeys("auth.email", email, Object.keys(EMAIL))
|
|
122
|
+
const resolved = structuredClone(EMAIL)
|
|
123
|
+
for (const purpose of Object.keys(EMAIL) as AuthLinkPurpose[]) {
|
|
124
|
+
const given = email[purpose]
|
|
125
|
+
if (given === undefined) continue
|
|
126
|
+
const at = `auth.email.${purpose}`
|
|
127
|
+
if (!isObject(given)) fail(`${at} must be an object (got ${shown(given)})`)
|
|
128
|
+
onlyKeys(at, given, EMAIL_KEYS)
|
|
129
|
+
const { page } = given
|
|
130
|
+
if (page !== undefined) {
|
|
131
|
+
if (!isAppPath(page)) fail(`${at}.page must be an app path such as "/auth/magic-link" (got ${shown(page)})`)
|
|
132
|
+
if (/[?#]/.test(page)) fail(`${at}.page must be a path without a query or a hash (got ${shown(page)})`)
|
|
133
|
+
resolved[purpose].page = page
|
|
134
|
+
}
|
|
135
|
+
for (const key of ["template", "subject"] as const) {
|
|
136
|
+
const value = given[key]
|
|
137
|
+
if (value === undefined) continue
|
|
138
|
+
if (typeof value !== "string" || value === "")
|
|
139
|
+
fail(`${at}.${key} must be a non-empty string (got ${shown(value)})`)
|
|
140
|
+
resolved[purpose][key] = value
|
|
141
|
+
}
|
|
142
|
+
resolved[purpose].ttl = seconds(`${at}.ttl`, given.ttl) ?? resolved[purpose].ttl
|
|
143
|
+
}
|
|
144
|
+
return resolved
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** `auth.accessTokens`; whether its file exists is checked once the modules ran. */
|
|
148
|
+
function resolveAccessTokens(input: unknown): ResolvedAuthOptions["accessTokens"] {
|
|
149
|
+
if (input === undefined) return undefined
|
|
150
|
+
if (!isObject(input)) fail(`auth.accessTokens must be an object (got ${shown(input)})`)
|
|
151
|
+
onlyKeys("auth.accessTokens", input, ["user"])
|
|
152
|
+
const { user } = input
|
|
153
|
+
if (typeof user !== "string" || user === "")
|
|
154
|
+
fail(`auth.accessTokens.user must be the path of a file (got ${shown(user)})`)
|
|
155
|
+
return { user }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The `auth` key checked, with the defaults; a password is never printed in a message. */
|
|
159
|
+
export function resolveOptions(input: unknown): ResolvedAuthOptions {
|
|
160
|
+
if (input !== undefined && !isObject(input)) fail(`auth must be an object (got ${shown(input)})`)
|
|
161
|
+
const auth = input ?? {}
|
|
162
|
+
onlyKeys("auth", auth, TOP_KEYS)
|
|
163
|
+
const session = auth.session ?? {}
|
|
164
|
+
if (!isObject(session)) fail(`auth.session must be an object (got ${shown(session)})`)
|
|
165
|
+
onlyKeys("auth.session", session, SESSION_KEYS)
|
|
166
|
+
|
|
167
|
+
const { password } = session
|
|
168
|
+
if (password !== undefined) {
|
|
169
|
+
const literal = typeof password === "string" && password.length >= MIN_PASSWORD
|
|
170
|
+
if (!literal && !isEnvRef(password))
|
|
171
|
+
fail(`auth.session.password must be a string of at least ${MIN_PASSWORD} characters or env("NAME")`)
|
|
172
|
+
}
|
|
173
|
+
const maxAge = seconds("auth.session.maxAge", session.maxAge) ?? DEFAULT_MAX_AGE
|
|
174
|
+
const idleTimeout = seconds("auth.session.idleTimeout", session.idleTimeout)
|
|
175
|
+
const storage = session.storage ?? false
|
|
176
|
+
if (storage !== false && !(typeof storage === "string" && storage !== ""))
|
|
177
|
+
fail(`auth.session.storage must be a storage mount name or false (got ${shown(storage)})`)
|
|
178
|
+
const cookie = session.cookie ?? {}
|
|
179
|
+
if (!isObject(cookie)) fail(`auth.session.cookie must be an object (got ${shown(cookie)})`)
|
|
180
|
+
for (const key of ["maxAge", "expires"])
|
|
181
|
+
if (Object.hasOwn(cookie, key)) fail(`auth.session.cookie cannot set ${key}; use auth.session.maxAge`)
|
|
182
|
+
onlyKeys("auth.session.cookie", cookie, COOKIE_KEYS)
|
|
183
|
+
for (const key of ["path", "domain"]) {
|
|
184
|
+
if (cookie[key] !== undefined && typeof cookie[key] !== "string")
|
|
185
|
+
fail(`auth.session.cookie.${key} must be a string (got ${shown(cookie[key])})`)
|
|
186
|
+
}
|
|
187
|
+
for (const key of ["httpOnly", "secure", "partitioned"]) {
|
|
188
|
+
if (cookie[key] !== undefined && typeof cookie[key] !== "boolean")
|
|
189
|
+
fail(`auth.session.cookie.${key} must be true or false (got ${shown(cookie[key])})`)
|
|
190
|
+
}
|
|
191
|
+
const { sameSite } = cookie
|
|
192
|
+
if (sameSite !== undefined && !SAME_SITE.includes(sameSite as string))
|
|
193
|
+
fail(`auth.session.cookie.sameSite must be "lax", "strict" or "none" (got ${shown(sameSite)})`)
|
|
194
|
+
if (sameSite === "none" && cookie.secure === false)
|
|
195
|
+
fail(
|
|
196
|
+
'auth.session.cookie.sameSite "none" needs secure: true; a browser drops a SameSite=None cookie without Secure',
|
|
197
|
+
)
|
|
198
|
+
const hostOnly = cookie.secure !== false && (cookie.path ?? "/") === "/" && cookie.domain === undefined
|
|
199
|
+
const name = session.name ?? (hostOnly ? "__Host-hamur-auth" : "hamur-auth")
|
|
200
|
+
if (typeof name !== "string" || !TOKEN.test(name))
|
|
201
|
+
fail(`auth.session.name must be a cookie name (got ${shown(name)})`)
|
|
202
|
+
if (/^__host-/i.test(name) && !hostOnly)
|
|
203
|
+
fail(`auth.session.name ${JSON.stringify(name)} needs auth.session.cookie with secure, path "/" and no domain`)
|
|
204
|
+
|
|
205
|
+
const loadStrategy = auth.loadStrategy ?? "server-first"
|
|
206
|
+
if (!LOAD_STRATEGIES.includes(loadStrategy as string))
|
|
207
|
+
fail(`auth.loadStrategy must be "server-first", "client-only" or "none" (got ${shown(loadStrategy)})`)
|
|
208
|
+
|
|
209
|
+
const redirect = auth.redirect === undefined ? {} : auth.redirect
|
|
210
|
+
if (!isObject(redirect)) fail(`auth.redirect must be an object (got ${shown(redirect)})`)
|
|
211
|
+
onlyKeys("auth.redirect", redirect, REDIRECT_KEYS)
|
|
212
|
+
const target = (key: string, fallback: string): string => {
|
|
213
|
+
const value = redirect[key] === undefined ? fallback : redirect[key]
|
|
214
|
+
if (!isAppPath(value))
|
|
215
|
+
fail(`auth.redirect.${key} must be an app path such as ${JSON.stringify(fallback)} (got ${shown(value)})`)
|
|
216
|
+
if (/[?#]/.test(value)) fail(`auth.redirect.${key} must be a path without a query or a hash (got ${shown(value)})`)
|
|
217
|
+
return value
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const oauth = resolveOAuth(auth.oauth)
|
|
221
|
+
const webauthn = resolveWebAuthn(auth.webauthn)
|
|
222
|
+
const email = resolveEmail(auth.email)
|
|
223
|
+
const accessTokens = resolveAccessTokens(auth.accessTokens)
|
|
224
|
+
|
|
225
|
+
return {
|
|
226
|
+
redirect: { login: target("login", "/login"), home: target("home", "/") },
|
|
227
|
+
oauth,
|
|
228
|
+
webauthn,
|
|
229
|
+
email,
|
|
230
|
+
...(accessTokens === undefined ? {} : { accessTokens }),
|
|
231
|
+
loadStrategy: loadStrategy as ResolvedAuthOptions["loadStrategy"],
|
|
232
|
+
session: {
|
|
233
|
+
name,
|
|
234
|
+
...(password === undefined ? {} : { password: password as ResolvedAuthOptions["session"]["password"] }),
|
|
235
|
+
maxAge,
|
|
236
|
+
...(idleTimeout === undefined ? {} : { idleTimeout }),
|
|
237
|
+
...(storage === false ? {} : { storage }),
|
|
238
|
+
cookie: cookie as ResolvedAuthOptions["session"]["cookie"],
|
|
239
|
+
},
|
|
240
|
+
}
|
|
241
|
+
}
|