@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,2971 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
getUserSession2,
|
|
4
|
+
setUserSession2,
|
|
5
|
+
replaceUserSession2,
|
|
6
|
+
clearUserSession2,
|
|
7
|
+
requireUserSession2,
|
|
8
|
+
createAccessToken2,
|
|
9
|
+
revokeAccessToken2
|
|
10
|
+
} from "../../chunks/bun-index-r6757s88.js";
|
|
11
|
+
import {
|
|
12
|
+
isAppPath
|
|
13
|
+
} from "../../chunks/bun-index-pmpez2a8.js";
|
|
14
|
+
// packages/auth/src/server/auth-link.ts
|
|
15
|
+
import { email as configured, loadMail, siteUrl, templates } from "#hamur/auth/email";
|
|
16
|
+
import { baseURL } from "#hamur/auth/guards";
|
|
17
|
+
import { useSiteConfig } from "hamur/server";
|
|
18
|
+
import { absoluteUrl, escapeXml } from "hamur/server/internal";
|
|
19
|
+
|
|
20
|
+
// packages/auth/src/server/token.ts
|
|
21
|
+
import { singleUse } from "#hamur/auth/single-use";
|
|
22
|
+
import { createError, useStorage } from "hamur/server";
|
|
23
|
+
import { sealFor, storageMountDriver, unsealFor } from "hamur/server/internal";
|
|
24
|
+
|
|
25
|
+
// packages/auth/src/single-use.ts
|
|
26
|
+
var ATOMIC = ["redis", "db", "sqlite"];
|
|
27
|
+
var IN_PROCESS = ["memory", "fs"];
|
|
28
|
+
var ONE_PROCESS_PRESETS = ["bun", "node"];
|
|
29
|
+
var FIX = "mount storage.session on redis, db or sqlite";
|
|
30
|
+
var WHAT = {
|
|
31
|
+
webAuthnRegister: "challenges",
|
|
32
|
+
webAuthnAuthenticate: "challenges",
|
|
33
|
+
consumeAuthToken: "tokens",
|
|
34
|
+
verifyTotp: "TOTP codes"
|
|
35
|
+
};
|
|
36
|
+
function singleUseProblem(mount, at) {
|
|
37
|
+
const what = WHAT[at.name];
|
|
38
|
+
if (!mount)
|
|
39
|
+
return `@hamur/auth: ${at.name} needs the session storage mount for single-use ${what}; set storage.session`;
|
|
40
|
+
if (mount.encrypt)
|
|
41
|
+
return `@hamur/auth: single-use ${what} need an atomic increment; the "session" mount has encrypt, whose increment is not atomic; ${FIX}`;
|
|
42
|
+
if (ATOMIC.includes(mount.driver))
|
|
43
|
+
return;
|
|
44
|
+
if (IN_PROCESS.includes(mount.driver) && (at.dev || ONE_PROCESS_PRESETS.includes(at.preset)))
|
|
45
|
+
return;
|
|
46
|
+
return `@hamur/auth: single-use ${what} need an atomic increment; the "session" mount uses ${mount.driver} on the ${at.preset} preset; ${FIX}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// packages/auth/src/server/token.ts
|
|
50
|
+
var DEFAULT_TTL = 900;
|
|
51
|
+
var PURPOSE = /^[\x21-\x7e]{1,111}$/;
|
|
52
|
+
var ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
53
|
+
var shown = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
|
|
54
|
+
var spent = () => createError({ status: 400, message: "Token expired or already used" });
|
|
55
|
+
function sealPurpose(purpose, name) {
|
|
56
|
+
if (typeof purpose !== "string" || !PURPOSE.test(purpose))
|
|
57
|
+
throw new TypeError(`${name} purpose must be 1 to 111 visible ASCII characters (got ${shown(purpose)})`);
|
|
58
|
+
return `hamur-auth-token:${purpose}`;
|
|
59
|
+
}
|
|
60
|
+
var isSealed = (value) => typeof value === "object" && value !== null && typeof value.id === "string" && ID.test(value.id) && Number.isSafeInteger(value.ttl) && value.ttl > 0;
|
|
61
|
+
var singleUseChecked = false;
|
|
62
|
+
async function checkSingleUse() {
|
|
63
|
+
if (singleUseChecked)
|
|
64
|
+
return;
|
|
65
|
+
const problem = singleUseProblem(await storageMountDriver("session"), {
|
|
66
|
+
name: "consumeAuthToken",
|
|
67
|
+
preset: singleUse.preset,
|
|
68
|
+
dev: Boolean(import.meta.dev)
|
|
69
|
+
});
|
|
70
|
+
if (problem)
|
|
71
|
+
throw new Error(problem);
|
|
72
|
+
singleUseChecked = true;
|
|
73
|
+
}
|
|
74
|
+
async function createAuthToken(event, options) {
|
|
75
|
+
const purpose = sealPurpose(options?.purpose, "createAuthToken");
|
|
76
|
+
const ttl = options.ttl ?? DEFAULT_TTL;
|
|
77
|
+
if (!Number.isSafeInteger(ttl) || ttl <= 0)
|
|
78
|
+
throw new TypeError(`createAuthToken ttl must be a positive integer of seconds (got ${shown(ttl)})`);
|
|
79
|
+
const value = { id: crypto.randomUUID(), ttl, data: options.data };
|
|
80
|
+
return sealFor(value, { purpose, ttl });
|
|
81
|
+
}
|
|
82
|
+
async function consumeAuthToken(event, token, purpose) {
|
|
83
|
+
const sealedFor = sealPurpose(purpose, "consumeAuthToken");
|
|
84
|
+
await checkSingleUse();
|
|
85
|
+
const sealed = typeof token === "string" ? await unsealFor(token, { purpose: sealedFor }) : undefined;
|
|
86
|
+
if (!isSealed(sealed))
|
|
87
|
+
throw spent();
|
|
88
|
+
if (await useStorage("session").increment(`auth-token:${sealed.id}`, 1, { ttl: sealed.ttl }) !== 1)
|
|
89
|
+
throw spent();
|
|
90
|
+
return sealed.data;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// packages/auth/src/server/auth-link.ts
|
|
94
|
+
var TEXT = {
|
|
95
|
+
"magic-link": {
|
|
96
|
+
subject: (site) => `Sign in to ${site}`,
|
|
97
|
+
intro: (site) => `Use this link to sign in to ${site}:`,
|
|
98
|
+
action: "Sign in"
|
|
99
|
+
},
|
|
100
|
+
"verify-email": {
|
|
101
|
+
subject: () => "Confirm your email",
|
|
102
|
+
intro: (site) => `Use this link to confirm your email address for ${site}:`,
|
|
103
|
+
action: "Confirm your email"
|
|
104
|
+
},
|
|
105
|
+
"password-reset": {
|
|
106
|
+
subject: () => "Reset your password",
|
|
107
|
+
intro: (site) => `Use this link to set a new password for ${site}:`,
|
|
108
|
+
action: "Reset your password"
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
var ADDRESS = /^[^\s@"\\\x00-\x1f\x7f]+@[^\s@"\\\x00-\x1f\x7f]+$/;
|
|
112
|
+
function body(purpose, site, url, expiresAt) {
|
|
113
|
+
const { intro, action } = TEXT[purpose];
|
|
114
|
+
const until = expiresAt.toISOString().slice(0, 16).replace("T", " ");
|
|
115
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head><body><p>${escapeXml(intro(site))}</p><p><a href="${escapeXml(url)}">${action}</a></p><p>The link works once, until ${until} UTC. If you did not ask for it, ignore this email.</p></body></html>`;
|
|
116
|
+
}
|
|
117
|
+
function redacted(error, token, email) {
|
|
118
|
+
for (let at = error;at instanceof Error; at = at.cause) {
|
|
119
|
+
const text = `${at.message}
|
|
120
|
+
${at.stack}`;
|
|
121
|
+
if (text.includes(token) || text.includes(email))
|
|
122
|
+
return new Error(error.message.replaceAll(token, "<token>").replaceAll(email, "<email>"));
|
|
123
|
+
}
|
|
124
|
+
return error;
|
|
125
|
+
}
|
|
126
|
+
async function sendAuthLink(event, options) {
|
|
127
|
+
const { purpose, email, data, next } = options;
|
|
128
|
+
if (!Object.hasOwn(TEXT, purpose))
|
|
129
|
+
throw new TypeError(`sendAuthLink purpose must be "magic-link", "verify-email" or "password-reset" (got ${JSON.stringify(purpose)})`);
|
|
130
|
+
if (typeof email !== "string" || !email.isWellFormed() || !ADDRESS.test(email))
|
|
131
|
+
throw new TypeError("sendAuthLink email must be one bare address");
|
|
132
|
+
if (next !== undefined && !isAppPath(next))
|
|
133
|
+
throw new TypeError(`sendAuthLink next must be an app path such as "/account" (got ${JSON.stringify(next)})`);
|
|
134
|
+
if (!loadMail)
|
|
135
|
+
throw new Error("@hamur/auth: sendAuthLink needs @hamur/mail in modules");
|
|
136
|
+
const site = useSiteConfig(event);
|
|
137
|
+
const origin = site.url ?? siteUrl;
|
|
138
|
+
if (!origin)
|
|
139
|
+
throw new Error("@hamur/auth: sendAuthLink needs site.url: a mail holds absolute links");
|
|
140
|
+
const { page, template, subject, ttl } = configured[purpose];
|
|
141
|
+
const expiresAt = new Date(Date.now() + ttl * 1000);
|
|
142
|
+
const token = await createAuthToken(event, { purpose, data: { email, data, next }, ttl });
|
|
143
|
+
const url = `${absoluteUrl(origin, baseURL, page)}?token=${token}`;
|
|
144
|
+
const name = site.name ?? new URL(origin).host;
|
|
145
|
+
const { sendMail } = await loadMail();
|
|
146
|
+
try {
|
|
147
|
+
await sendMail({
|
|
148
|
+
to: { address: email },
|
|
149
|
+
subject: subject ?? TEXT[purpose].subject(name),
|
|
150
|
+
...templates.includes(template) ? { template, props: { url, email, expiresAt } } : { html: body(purpose, name, url, expiresAt) }
|
|
151
|
+
});
|
|
152
|
+
} catch (error) {
|
|
153
|
+
throw redacted(error, token, email);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// packages/auth/src/server/totp.ts
|
|
157
|
+
import { singleUse as singleUse2 } from "#hamur/auth/single-use";
|
|
158
|
+
import { hashPassword, useSiteConfig as useSiteConfig2, useStorage as useStorage2, verifyPassword } from "hamur/server";
|
|
159
|
+
import { storageMountDriver as storageMountDriver2, timingSafeEqual, toBase64Url } from "hamur/server/internal";
|
|
160
|
+
var BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
161
|
+
var SECRET_BYTES = 20;
|
|
162
|
+
var STEP = 30;
|
|
163
|
+
var DIGITS = 6;
|
|
164
|
+
var DEFAULT_WINDOW = 1;
|
|
165
|
+
var MAX_WINDOW = 10;
|
|
166
|
+
var MARK_TTL = (2 * MAX_WINDOW + 2) * STEP;
|
|
167
|
+
var CODE = /^\d{6}$/;
|
|
168
|
+
var RECOVERY_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
|
|
169
|
+
var RECOVERY_LENGTH = 10;
|
|
170
|
+
var DEFAULT_RECOVERY_COUNT = 10;
|
|
171
|
+
var MAX_RECOVERY_COUNT = 100;
|
|
172
|
+
var RECOVERY_CODE = /^[0-9a-hjkmnp-tv-z]{10}$/;
|
|
173
|
+
var shown2 = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
|
|
174
|
+
function base32Encode(bytes) {
|
|
175
|
+
let out = "";
|
|
176
|
+
let buffer = 0;
|
|
177
|
+
let bits = 0;
|
|
178
|
+
for (const byte of bytes) {
|
|
179
|
+
buffer = buffer << 8 | byte;
|
|
180
|
+
bits += 8;
|
|
181
|
+
while (bits >= 5) {
|
|
182
|
+
bits -= 5;
|
|
183
|
+
out += BASE32[buffer >> bits & 31];
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (bits > 0)
|
|
187
|
+
out += BASE32[buffer << 5 - bits & 31];
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
function base32Decode(text) {
|
|
191
|
+
const clean = text.replace(/\s+/g, "").replace(/=+$/, "").toUpperCase();
|
|
192
|
+
if (clean.length === 0)
|
|
193
|
+
return;
|
|
194
|
+
const out = new Uint8Array(Math.floor(clean.length * 5 / 8));
|
|
195
|
+
let buffer = 0;
|
|
196
|
+
let bits = 0;
|
|
197
|
+
let at = 0;
|
|
198
|
+
for (const char of clean) {
|
|
199
|
+
const value = BASE32.indexOf(char);
|
|
200
|
+
if (value < 0)
|
|
201
|
+
return;
|
|
202
|
+
buffer = (buffer << 5 | value) & 65535;
|
|
203
|
+
bits += 5;
|
|
204
|
+
if (bits >= 8) {
|
|
205
|
+
bits -= 8;
|
|
206
|
+
out[at++] = buffer >> bits & 255;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return out.length > 0 ? out : undefined;
|
|
210
|
+
}
|
|
211
|
+
async function hotp(key, counter) {
|
|
212
|
+
const message = new Uint8Array(8);
|
|
213
|
+
new DataView(message.buffer).setBigUint64(0, BigInt(counter));
|
|
214
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, message));
|
|
215
|
+
const offset = mac[19] & 15;
|
|
216
|
+
const binary = (mac[offset] & 127) << 24 | mac[offset + 1] << 16 | mac[offset + 2] << 8 | mac[offset + 3];
|
|
217
|
+
return String(binary % 10 ** DIGITS).padStart(DIGITS, "0");
|
|
218
|
+
}
|
|
219
|
+
var singleUseChecked2 = false;
|
|
220
|
+
async function checkSingleUse2() {
|
|
221
|
+
if (singleUseChecked2)
|
|
222
|
+
return;
|
|
223
|
+
const problem = singleUseProblem(await storageMountDriver2("session"), {
|
|
224
|
+
name: "verifyTotp",
|
|
225
|
+
preset: singleUse2.preset,
|
|
226
|
+
dev: Boolean(import.meta.dev)
|
|
227
|
+
});
|
|
228
|
+
if (problem)
|
|
229
|
+
throw new Error(problem);
|
|
230
|
+
singleUseChecked2 = true;
|
|
231
|
+
}
|
|
232
|
+
function createTotp(options) {
|
|
233
|
+
const label = options?.label;
|
|
234
|
+
if (typeof label !== "string" || label.length === 0)
|
|
235
|
+
throw new TypeError(`createTotp label must be a non-empty string (got ${shown2(label)})`);
|
|
236
|
+
if (options.issuer !== undefined && (typeof options.issuer !== "string" || options.issuer.length === 0))
|
|
237
|
+
throw new TypeError(`createTotp issuer must be a non-empty string (got ${shown2(options.issuer)})`);
|
|
238
|
+
const issuer = options.issuer ?? useSiteConfig2().name;
|
|
239
|
+
const secret = base32Encode(crypto.getRandomValues(new Uint8Array(SECRET_BYTES)));
|
|
240
|
+
const account = issuer ? `${encodeURIComponent(issuer)}:${encodeURIComponent(label)}` : encodeURIComponent(label);
|
|
241
|
+
const query = `secret=${secret}${issuer ? `&issuer=${encodeURIComponent(issuer)}` : ""}&algorithm=SHA1&digits=${DIGITS}&period=${STEP}`;
|
|
242
|
+
return { secret, uri: `otpauth://totp/${account}?${query}` };
|
|
243
|
+
}
|
|
244
|
+
async function verifyTotp(event, secret, code, options) {
|
|
245
|
+
const window = options?.window ?? DEFAULT_WINDOW;
|
|
246
|
+
if (!Number.isInteger(window) || window < 0 || window > MAX_WINDOW)
|
|
247
|
+
throw new TypeError(`verifyTotp window must be an integer from 0 to ${MAX_WINDOW} (got ${shown2(window)})`);
|
|
248
|
+
const keyBytes = typeof secret === "string" ? base32Decode(secret) : undefined;
|
|
249
|
+
if (!keyBytes)
|
|
250
|
+
throw new TypeError("verifyTotp secret must be base32, as createTotp returns it");
|
|
251
|
+
await checkSingleUse2();
|
|
252
|
+
if (typeof code !== "string" || !CODE.test(code))
|
|
253
|
+
return false;
|
|
254
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-1" }, false, ["sign"]);
|
|
255
|
+
const now = Math.floor(Date.now() / 1000 / STEP);
|
|
256
|
+
let matched;
|
|
257
|
+
for (let offset = -window;offset <= window; offset++) {
|
|
258
|
+
const step = now + offset;
|
|
259
|
+
if (timingSafeEqual(await hotp(key, step), code) && matched === undefined)
|
|
260
|
+
matched = step;
|
|
261
|
+
}
|
|
262
|
+
if (matched === undefined)
|
|
263
|
+
return false;
|
|
264
|
+
const id = toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", keyBytes)));
|
|
265
|
+
return await useStorage2("session").increment(`totp:${id}:${matched}`, 1, { ttl: MARK_TTL }) === 1;
|
|
266
|
+
}
|
|
267
|
+
async function createRecoveryCodes(count = DEFAULT_RECOVERY_COUNT) {
|
|
268
|
+
if (!Number.isInteger(count) || count < 1 || count > MAX_RECOVERY_COUNT)
|
|
269
|
+
throw new TypeError(`createRecoveryCodes count must be an integer from 1 to ${MAX_RECOVERY_COUNT} (got ${shown2(count)})`);
|
|
270
|
+
const codes = Array.from({ length: count }, () => Array.from(crypto.getRandomValues(new Uint8Array(RECOVERY_LENGTH)), (byte) => RECOVERY_ALPHABET[byte & 31]).join(""));
|
|
271
|
+
return { codes, hashes: await Promise.all(codes.map((code) => hashPassword(code))) };
|
|
272
|
+
}
|
|
273
|
+
async function matchRecoveryCode(code, hashes) {
|
|
274
|
+
const normalized = typeof code === "string" ? code.replace(/[\s-]+/g, "").toLowerCase() : "";
|
|
275
|
+
if (!RECOVERY_CODE.test(normalized))
|
|
276
|
+
return -1;
|
|
277
|
+
for (const [index, hash] of hashes.entries()) {
|
|
278
|
+
if (await verifyPassword(hash, normalized))
|
|
279
|
+
return index;
|
|
280
|
+
}
|
|
281
|
+
return -1;
|
|
282
|
+
}
|
|
283
|
+
// packages/auth/src/server/oauth/handler.ts
|
|
284
|
+
import { baseURL as baseURL2, redirect as targets } from "#hamur/auth/guards";
|
|
285
|
+
import {
|
|
286
|
+
createError as createError2,
|
|
287
|
+
deleteCookie,
|
|
288
|
+
getCookie,
|
|
289
|
+
getRequestURL,
|
|
290
|
+
getRouteRules,
|
|
291
|
+
readFormData,
|
|
292
|
+
setCookie
|
|
293
|
+
} from "hamur/server";
|
|
294
|
+
import { originCheckPasses, readSecret, sealFor as sealFor2, timingSafeEqual as timingSafeEqual2, toBase64Url as toBase64Url2, unsealFor as unsealFor2 } from "hamur/server/internal";
|
|
295
|
+
|
|
296
|
+
// packages/auth/src/server/oauth/cookie.ts
|
|
297
|
+
async function flowCookie(options) {
|
|
298
|
+
const flow = options.flow ?? "oauth";
|
|
299
|
+
const plainDev = options.dev && options.protocol === "http:";
|
|
300
|
+
if (options.formPost && plainDev) {
|
|
301
|
+
throw new TypeError('@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');
|
|
302
|
+
}
|
|
303
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(options.route)));
|
|
304
|
+
const hash = Array.from(digest.subarray(0, 8), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
305
|
+
return {
|
|
306
|
+
name: `${plainDev ? "" : "__Host-"}hamur-${flow}-${hash}`,
|
|
307
|
+
options: {
|
|
308
|
+
path: "/",
|
|
309
|
+
httpOnly: true,
|
|
310
|
+
secure: !plainDev,
|
|
311
|
+
sameSite: flow === "webauthn" ? "strict" : options.formPost ? "none" : "lax"
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// packages/auth/src/server/oauth/handler.ts
|
|
317
|
+
var PURPOSE2 = "hamur-oauth";
|
|
318
|
+
var TTL = 600;
|
|
319
|
+
var TIMEOUT = 1e4;
|
|
320
|
+
var PROVIDER = "custom";
|
|
321
|
+
var randomToken = () => toBase64Url2(crypto.getRandomValues(new Uint8Array(32)));
|
|
322
|
+
var challengeOf = async (verifier) => toBase64Url2(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
|
|
323
|
+
var formEncoded = (value) => new URLSearchParams([["", value]]).toString().slice(1);
|
|
324
|
+
var errorCode = (value) => value.replace(/[^A-Za-z0-9_.-]/g, "").slice(0, 64) || "unknown";
|
|
325
|
+
var errorDescription = (value) => value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").slice(0, 256);
|
|
326
|
+
var readOAuthSecret = (secret, name, caller = "oauthHandler") => readSecret(secret, `${caller} ${name}`);
|
|
327
|
+
function appPath(pathname) {
|
|
328
|
+
const base = baseURL2.replace(/\/+$/, "");
|
|
329
|
+
return base && (pathname === base || pathname.startsWith(`${base}/`)) ? pathname.slice(base.length) || "/" : pathname;
|
|
330
|
+
}
|
|
331
|
+
var isFlow = (value) => typeof value === "object" && value !== null && ["state", "redirectURI", "provider", "route"].every((key) => typeof value[key] === "string") && (value.data === undefined || typeof value.data === "object" && value.data !== null);
|
|
332
|
+
var noAnswer = () => createError2({ status: 502, message: "OAuth provider did not answer" });
|
|
333
|
+
var refused = () => createError2({ status: 401, message: "OAuth token request failed" });
|
|
334
|
+
async function providerJSON(event, url, init, what) {
|
|
335
|
+
let response;
|
|
336
|
+
let text;
|
|
337
|
+
try {
|
|
338
|
+
response = await fetch(url, { ...init, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT) });
|
|
339
|
+
text = await response.text();
|
|
340
|
+
} catch {
|
|
341
|
+
throw noAnswer();
|
|
342
|
+
}
|
|
343
|
+
let body;
|
|
344
|
+
try {
|
|
345
|
+
body = JSON.parse(text);
|
|
346
|
+
} catch {
|
|
347
|
+
body = undefined;
|
|
348
|
+
}
|
|
349
|
+
const record = typeof body === "object" && body !== null && !Array.isArray(body) ? body : undefined;
|
|
350
|
+
if (!response.ok || !record) {
|
|
351
|
+
const error = typeof record?.error === "string" ? errorCode(record.error) : undefined;
|
|
352
|
+
event.log.child({ name: "hamur" }).warn(`OAuth ${what} failed`, { status: response.status, ...error ? { error } : {} });
|
|
353
|
+
throw refused();
|
|
354
|
+
}
|
|
355
|
+
return record;
|
|
356
|
+
}
|
|
357
|
+
function oauthHandler(options) {
|
|
358
|
+
return createOAuthHandler(options);
|
|
359
|
+
}
|
|
360
|
+
function createOAuthHandler(options, hooks) {
|
|
361
|
+
const provider = hooks?.provider ?? PROVIDER;
|
|
362
|
+
const clientIdParam = hooks?.clientIdParam ?? "client_id";
|
|
363
|
+
const readClientId = (event) => hooks ? hooks.clientId(event) : readOAuthSecret(options.clientId, "clientId");
|
|
364
|
+
const readClientSecret = (event, clientId) => hooks ? hooks.clientSecret(event, clientId) : readOAuthSecret(options.clientSecret, "clientSecret");
|
|
365
|
+
const pkce = options.pkce ?? true;
|
|
366
|
+
const configuredTokenAuth = options.tokenAuth ?? "client_secret_basic";
|
|
367
|
+
const formPost = options.responseMode === "form_post";
|
|
368
|
+
if (!["client_secret_basic", "client_secret_post", "none"].includes(configuredTokenAuth))
|
|
369
|
+
throw new TypeError(`oauthHandler tokenAuth must be "client_secret_basic", "client_secret_post" or "none" (got ${JSON.stringify(configuredTokenAuth)})`);
|
|
370
|
+
if (options.responseMode !== undefined && !["query", "form_post"].includes(options.responseMode))
|
|
371
|
+
throw new TypeError(`oauthHandler responseMode must be "query" or "form_post" (got ${JSON.stringify(options.responseMode)})`);
|
|
372
|
+
if (configuredTokenAuth === "none" && !pkce)
|
|
373
|
+
throw new TypeError('oauthHandler tokenAuth "none" needs pkce');
|
|
374
|
+
if (configuredTokenAuth !== "none" && options.clientSecret === undefined)
|
|
375
|
+
throw new TypeError(`oauthHandler tokenAuth "${configuredTokenAuth}" needs clientSecret`);
|
|
376
|
+
if (!Array.isArray(options.scope) || !options.scope.every((entry) => typeof entry === "string"))
|
|
377
|
+
throw new TypeError("oauthHandler scope must be an array of strings");
|
|
378
|
+
return async (_input, { event }) => {
|
|
379
|
+
const url = getRequestURL(event);
|
|
380
|
+
const route = appPath(url.pathname);
|
|
381
|
+
const cookie = await flowCookie({ dev: Boolean(import.meta.dev), protocol: url.protocol, route, formPost });
|
|
382
|
+
const method = event.request.method;
|
|
383
|
+
let params;
|
|
384
|
+
let callback;
|
|
385
|
+
if (method === "GET") {
|
|
386
|
+
params = url.searchParams;
|
|
387
|
+
callback = !formPost && (params.has("code") || params.has("error"));
|
|
388
|
+
} else if (formPost && method === "POST") {
|
|
389
|
+
params = new URLSearchParams;
|
|
390
|
+
for (const [key, value] of await readFormData(event))
|
|
391
|
+
if (typeof value === "string")
|
|
392
|
+
params.append(key, value);
|
|
393
|
+
callback = true;
|
|
394
|
+
} else {
|
|
395
|
+
event.response.headers.set("allow", formPost ? "GET, POST" : "GET");
|
|
396
|
+
throw createError2({ status: 405, message: "Method Not Allowed" });
|
|
397
|
+
}
|
|
398
|
+
event.response.headers.set("cache-control", "no-store");
|
|
399
|
+
const redirectURI = options.redirectURL ?? `${url.origin}${url.pathname}`;
|
|
400
|
+
if (!callback) {
|
|
401
|
+
const endpoints = hooks?.endpoints ? await hooks.endpoints(event) : undefined;
|
|
402
|
+
const authorizationURL = endpoints?.authorizationURL ?? options.authorizationURL;
|
|
403
|
+
if (formPost && !originCheckPasses(event, getRouteRules(event), new URL(authorizationURL).origin)) {
|
|
404
|
+
throw new Error(`@hamur/auth: oauthHandler with responseMode "form_post" needs routeRules[${JSON.stringify(route)}].originCheck.allow to list the provider's origin`);
|
|
405
|
+
}
|
|
406
|
+
const clientId = readClientId(event);
|
|
407
|
+
const state = randomToken();
|
|
408
|
+
const verifier = pkce ? randomToken() : undefined;
|
|
409
|
+
const nonce = hooks?.nonce ? randomToken() : undefined;
|
|
410
|
+
const sent = new URLSearchParams(options.authorizationParams ?? {});
|
|
411
|
+
sent.set("response_type", "code");
|
|
412
|
+
sent.set(clientIdParam, clientId);
|
|
413
|
+
sent.set("redirect_uri", redirectURI);
|
|
414
|
+
const scope = hooks?.scope ? hooks.scope(clientId) : options.scope;
|
|
415
|
+
if (scope.length)
|
|
416
|
+
sent.set("scope", scope.join(" "));
|
|
417
|
+
sent.set("state", state);
|
|
418
|
+
if (nonce)
|
|
419
|
+
sent.set("nonce", nonce);
|
|
420
|
+
if (verifier) {
|
|
421
|
+
sent.set("code_challenge", await challengeOf(verifier));
|
|
422
|
+
sent.set("code_challenge_method", "S256");
|
|
423
|
+
}
|
|
424
|
+
if (formPost)
|
|
425
|
+
sent.set("response_mode", "form_post");
|
|
426
|
+
let location;
|
|
427
|
+
let issuer = endpoints?.issuer;
|
|
428
|
+
let data;
|
|
429
|
+
if (hooks?.authorize) {
|
|
430
|
+
const pushed = await hooks.authorize({ event, params: sent });
|
|
431
|
+
({ location, issuer, data } = pushed);
|
|
432
|
+
} else {
|
|
433
|
+
const target = new URL(authorizationURL);
|
|
434
|
+
for (const [key, value] of sent)
|
|
435
|
+
target.searchParams.set(key, value);
|
|
436
|
+
location = target.href;
|
|
437
|
+
}
|
|
438
|
+
const flow = {
|
|
439
|
+
state,
|
|
440
|
+
...verifier ? { verifier } : {},
|
|
441
|
+
...nonce ? { nonce } : {},
|
|
442
|
+
...issuer === undefined ? {} : { issuer },
|
|
443
|
+
redirectURI,
|
|
444
|
+
provider,
|
|
445
|
+
route,
|
|
446
|
+
...data ? { data } : {}
|
|
447
|
+
};
|
|
448
|
+
setCookie(event, cookie.name, await sealFor2(flow, { purpose: PURPOSE2, ttl: TTL }), {
|
|
449
|
+
...cookie.options,
|
|
450
|
+
maxAge: TTL
|
|
451
|
+
});
|
|
452
|
+
return new Response(null, { status: 302, headers: { location } });
|
|
453
|
+
}
|
|
454
|
+
deleteCookie(event, cookie.name, cookie.options);
|
|
455
|
+
const given = params.get("state") ?? "";
|
|
456
|
+
const sealed = getCookie(event, cookie.name);
|
|
457
|
+
const flow = sealed === undefined ? undefined : await unsealFor2(sealed, { purpose: PURPOSE2 });
|
|
458
|
+
if (!isFlow(flow) || flow.route !== route || flow.provider !== provider || flow.redirectURI !== redirectURI || !given || !timingSafeEqual2(flow.state, given) || hooks?.nonce && typeof flow.nonce !== "string") {
|
|
459
|
+
throw createError2({ status: 400, message: "Invalid OAuth state" });
|
|
460
|
+
}
|
|
461
|
+
const issuer = options.issuer ?? flow.issuer;
|
|
462
|
+
if (issuer !== undefined && params.get("iss") !== issuer)
|
|
463
|
+
throw createError2({ status: 400, message: "OAuth issuer mismatch" });
|
|
464
|
+
const error = params.get("error");
|
|
465
|
+
if (error !== null) {
|
|
466
|
+
const code = errorCode(error);
|
|
467
|
+
const given = params.get("error_description");
|
|
468
|
+
const description = given === null ? undefined : errorDescription(given);
|
|
469
|
+
event.log.child({ name: "hamur" }).warn(`OAuth provider answered error ${code}`, description === undefined ? {} : { description });
|
|
470
|
+
if (options.onError)
|
|
471
|
+
return options.onError(event, { error: code, ...description === undefined ? {} : { description } });
|
|
472
|
+
throw createError2({ status: 401, message: `OAuth error: ${code}` });
|
|
473
|
+
}
|
|
474
|
+
const code = params.get("code");
|
|
475
|
+
if (!code)
|
|
476
|
+
throw refused();
|
|
477
|
+
const endpoints = hooks?.endpoints ? await hooks.endpoints(event) : undefined;
|
|
478
|
+
const tokenURL = endpoints?.tokenURL ?? options.tokenURL;
|
|
479
|
+
const tokenAuth = endpoints?.tokenAuth ?? configuredTokenAuth;
|
|
480
|
+
const clientId = readClientId(event);
|
|
481
|
+
const body = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: flow.redirectURI });
|
|
482
|
+
if (flow.verifier)
|
|
483
|
+
body.set("code_verifier", flow.verifier);
|
|
484
|
+
const headers = {
|
|
485
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
486
|
+
accept: "application/json"
|
|
487
|
+
};
|
|
488
|
+
if (tokenAuth === "client_secret_basic") {
|
|
489
|
+
const secret = await readClientSecret(event, clientId);
|
|
490
|
+
headers.authorization = `Basic ${btoa(`${formEncoded(clientId)}:${formEncoded(secret)}`)}`;
|
|
491
|
+
} else {
|
|
492
|
+
body.set(clientIdParam, clientId);
|
|
493
|
+
if (tokenAuth === "client_secret_post")
|
|
494
|
+
body.set("client_secret", await readClientSecret(event, clientId));
|
|
495
|
+
}
|
|
496
|
+
const answer = hooks?.tokenRequest ? await hooks.tokenRequest({
|
|
497
|
+
event,
|
|
498
|
+
url: tokenURL,
|
|
499
|
+
headers,
|
|
500
|
+
body,
|
|
501
|
+
params,
|
|
502
|
+
...flow.data ? { data: flow.data } : {}
|
|
503
|
+
}) : await providerJSON(event, tokenURL, { method: "POST", headers, body }, "token request");
|
|
504
|
+
if (typeof answer.access_token !== "string" || answer.access_token === "") {
|
|
505
|
+
event.log.child({ name: "hamur" }).warn("OAuth token request failed", {
|
|
506
|
+
status: 200,
|
|
507
|
+
...typeof answer.error === "string" ? { error: errorCode(answer.error) } : {}
|
|
508
|
+
});
|
|
509
|
+
throw refused();
|
|
510
|
+
}
|
|
511
|
+
const tokens = answer;
|
|
512
|
+
let profile;
|
|
513
|
+
if (hooks?.profile)
|
|
514
|
+
profile = await hooks.profile({
|
|
515
|
+
event,
|
|
516
|
+
tokens,
|
|
517
|
+
params,
|
|
518
|
+
clientId,
|
|
519
|
+
...flow.nonce === undefined ? {} : { nonce: flow.nonce },
|
|
520
|
+
...flow.data ? { data: flow.data } : {}
|
|
521
|
+
});
|
|
522
|
+
else if (options.userURL !== undefined) {
|
|
523
|
+
profile = await providerJSON(event, options.userURL, { headers: { authorization: `Bearer ${tokens.access_token}`, accept: "application/json" } }, "user request");
|
|
524
|
+
}
|
|
525
|
+
const user = options.mapUser ? await options.mapUser(profile, tokens) : profile;
|
|
526
|
+
const value = await options.onSuccess(event, { user, tokens });
|
|
527
|
+
if (value !== undefined)
|
|
528
|
+
return value;
|
|
529
|
+
return new Response(null, { status: 302, headers: { location: `${baseURL2.replace(/\/+$/, "")}${targets.home}` } });
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
// packages/auth/src/server/oauth/oidc.ts
|
|
533
|
+
import {
|
|
534
|
+
createError as createError4,
|
|
535
|
+
useStorage as useStorage3
|
|
536
|
+
} from "hamur/server";
|
|
537
|
+
import { timingSafeEqual as timingSafeEqual3 } from "hamur/server/internal";
|
|
538
|
+
|
|
539
|
+
// packages/auth/src/server/oauth/providers/preset.ts
|
|
540
|
+
import { oauth as configured2 } from "#hamur/auth/oauth";
|
|
541
|
+
import {
|
|
542
|
+
createError as createError3,
|
|
543
|
+
JWTError,
|
|
544
|
+
verifyJWT
|
|
545
|
+
} from "hamur/server";
|
|
546
|
+
import { isEnvRef, readSecret as readSecret2 } from "hamur/server/internal";
|
|
547
|
+
|
|
548
|
+
// packages/auth/src/server/oauth/providers/catalog.ts
|
|
549
|
+
var client = ["clientId", "clientSecret"];
|
|
550
|
+
var APPLE_ORIGIN = "https://appleid.apple.com";
|
|
551
|
+
var ATPROTO_METADATA_ROUTE = "/_hamur/auth/atproto/client-metadata.json";
|
|
552
|
+
var OAUTH_PROVIDERS = {
|
|
553
|
+
github: { label: "GitHub", secrets: client, keys: [] },
|
|
554
|
+
google: { label: "Google", secrets: client, keys: [] },
|
|
555
|
+
microsoft: { label: "Microsoft", secrets: client, keys: ["tenant"] },
|
|
556
|
+
apple: { label: "Apple", secrets: ["clientId", "privateKey"], keys: ["teamId", "keyId"] },
|
|
557
|
+
discord: { label: "Discord", secrets: client, keys: [] },
|
|
558
|
+
gitlab: { label: "GitLab", secrets: client, keys: ["baseURL"] },
|
|
559
|
+
steam: { label: "Steam", secrets: [], keys: [] },
|
|
560
|
+
atlassian: { label: "Atlassian", secrets: client, keys: [] },
|
|
561
|
+
auth0: { label: "Auth0", secrets: client, keys: ["domain"] },
|
|
562
|
+
authentik: { label: "Authentik", secrets: client, keys: ["domain"] },
|
|
563
|
+
battledotnet: { label: "BattleDotNet", secrets: client, keys: [] },
|
|
564
|
+
box: { label: "Box", secrets: client, keys: [] },
|
|
565
|
+
dropbox: { label: "Dropbox", secrets: client, keys: [] },
|
|
566
|
+
facebook: { label: "Facebook", secrets: client, keys: [] },
|
|
567
|
+
gitea: { label: "Gitea", secrets: client, keys: ["baseURL"] },
|
|
568
|
+
heroku: { label: "Heroku", secrets: client, keys: [] },
|
|
569
|
+
keycloak: { label: "Keycloak", secrets: client, keys: ["serverURL", "realm"] },
|
|
570
|
+
kick: { label: "Kick", secrets: client, keys: [] },
|
|
571
|
+
line: { label: "Line", secrets: client, keys: [] },
|
|
572
|
+
linear: { label: "Linear", secrets: client, keys: [] },
|
|
573
|
+
linkedin: { label: "LinkedIn", secrets: client, keys: [] },
|
|
574
|
+
mastodon: { label: "Mastodon", secrets: client, keys: ["baseURL"] },
|
|
575
|
+
okta: { label: "Okta", secrets: client, keys: ["domain"] },
|
|
576
|
+
ory: { label: "Ory", secrets: client, keys: ["domain"] },
|
|
577
|
+
osu: { label: "Osu", secrets: client, keys: [] },
|
|
578
|
+
paypal: { label: "PayPal", secrets: client, keys: [] },
|
|
579
|
+
polar: { label: "Polar", secrets: client, keys: [] },
|
|
580
|
+
riotgames: { label: "RiotGames", secrets: client, keys: [] },
|
|
581
|
+
roblox: { label: "Roblox", secrets: client, keys: [] },
|
|
582
|
+
salesforce: { label: "Salesforce", secrets: client, keys: ["baseURL"] },
|
|
583
|
+
seznam: { label: "Seznam", secrets: client, keys: [] },
|
|
584
|
+
slack: { label: "Slack", secrets: client, keys: [] },
|
|
585
|
+
spotify: { label: "Spotify", secrets: client, keys: [] },
|
|
586
|
+
twitch: { label: "Twitch", secrets: client, keys: [] },
|
|
587
|
+
x: { label: "X", secrets: client, keys: [] },
|
|
588
|
+
yandex: { label: "Yandex", secrets: client, keys: [] },
|
|
589
|
+
zendesk: { label: "Zendesk", secrets: client, keys: ["subdomain"] },
|
|
590
|
+
zitadel: { label: "Zitadel", secrets: client, keys: ["domain"] },
|
|
591
|
+
azureb2c: { label: "AzureB2C", secrets: client, keys: ["tenant", "policy"] },
|
|
592
|
+
cloudflare: { label: "Cloudflare", secrets: ["clientSecret"], keys: ["clientId", "teamName"] },
|
|
593
|
+
cognito: { label: "Cognito", secrets: client, keys: ["domain"] },
|
|
594
|
+
hubspot: { label: "HubSpot", secrets: client, keys: [] },
|
|
595
|
+
instagram: { label: "Instagram", secrets: client, keys: [] },
|
|
596
|
+
livechat: { label: "LiveChat", secrets: client, keys: [] },
|
|
597
|
+
shopifyCustomer: { label: "ShopifyCustomer", secrets: client, keys: ["shopId"] },
|
|
598
|
+
strava: { label: "Strava", secrets: client, keys: [] },
|
|
599
|
+
tiktok: { label: "TikTok", secrets: client, keys: [] },
|
|
600
|
+
vk: { label: "VK", secrets: ["clientId"], keys: [] },
|
|
601
|
+
wechat: { label: "WeChat", secrets: client, keys: [] },
|
|
602
|
+
workos: { label: "WorkOS", secrets: client, keys: [] },
|
|
603
|
+
xsuaa: { label: "Xsuaa", secrets: client, keys: ["domain"] }
|
|
604
|
+
};
|
|
605
|
+
function providerKeys(provider) {
|
|
606
|
+
const { secrets, keys } = OAUTH_PROVIDERS[provider];
|
|
607
|
+
return [...secrets, "redirectURL", ...keys];
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// packages/auth/src/server/oauth/providers/preset.ts
|
|
611
|
+
var CALL_KEYS = new Set(["onSuccess", "onError", "scope", "authorizationParams"]);
|
|
612
|
+
var exportName = (name) => `oauth${OAUTH_PROVIDERS[name].label}`;
|
|
613
|
+
function presetConfig(name, options) {
|
|
614
|
+
const config = { ...configured2[name] };
|
|
615
|
+
const keys = providerKeys(name);
|
|
616
|
+
for (const [key, value] of Object.entries(options)) {
|
|
617
|
+
if (CALL_KEYS.has(key))
|
|
618
|
+
continue;
|
|
619
|
+
if (!keys.includes(key))
|
|
620
|
+
throw new TypeError(`@hamur/auth: ${exportName(name)} has no ${JSON.stringify(key)} (it takes: ${keys.join(", ")})`);
|
|
621
|
+
if (value !== undefined && value !== "")
|
|
622
|
+
config[key] = value;
|
|
623
|
+
}
|
|
624
|
+
return config;
|
|
625
|
+
}
|
|
626
|
+
function userOf(value) {
|
|
627
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value))
|
|
628
|
+
return value;
|
|
629
|
+
throw createError3({ status: 401, message: "OAuth token request failed" });
|
|
630
|
+
}
|
|
631
|
+
var CLAIMS = {
|
|
632
|
+
algorithm: "alg",
|
|
633
|
+
key: "signature",
|
|
634
|
+
signature: "signature",
|
|
635
|
+
expired: "exp",
|
|
636
|
+
not_before: "nbf",
|
|
637
|
+
issuer: "iss",
|
|
638
|
+
audience: "aud"
|
|
639
|
+
};
|
|
640
|
+
async function idTokenClaims(token, jwksUri, options) {
|
|
641
|
+
let claims;
|
|
642
|
+
try {
|
|
643
|
+
claims = await verifyJWT(typeof token === "string" ? token : "", { jwksUri }, {
|
|
644
|
+
algorithms: options.algorithms ?? ["RS256"],
|
|
645
|
+
...options.issuer === undefined ? {} : { issuer: options.issuer },
|
|
646
|
+
audience: options.audience,
|
|
647
|
+
...options.clockTolerance === undefined ? {} : { clockTolerance: options.clockTolerance }
|
|
648
|
+
});
|
|
649
|
+
} catch (error) {
|
|
650
|
+
if (!(error instanceof JWTError))
|
|
651
|
+
throw error;
|
|
652
|
+
throw createError3({ status: 401, message: `Invalid ID token: ${CLAIMS[error.code] ?? error.code}` });
|
|
653
|
+
}
|
|
654
|
+
if (typeof claims.sub !== "string" || claims.sub === "")
|
|
655
|
+
throw createError3({ status: 401, message: "Invalid ID token: sub" });
|
|
656
|
+
return claims;
|
|
657
|
+
}
|
|
658
|
+
function originOf(value) {
|
|
659
|
+
return (/^https?:\/\//i.test(value) ? value : `https://${value}`).replace(/\/+$/, "");
|
|
660
|
+
}
|
|
661
|
+
function requireKey(name, config, key) {
|
|
662
|
+
const value = config[key];
|
|
663
|
+
if (typeof value !== "string" || value === "")
|
|
664
|
+
throw new TypeError(`@hamur/auth: ${exportName(name)} needs auth.oauth.${name}.${key}`);
|
|
665
|
+
return value;
|
|
666
|
+
}
|
|
667
|
+
function reader(name, config) {
|
|
668
|
+
return (_event, key) => {
|
|
669
|
+
const given = config[key];
|
|
670
|
+
const where = `auth.oauth.${name}.${key}`;
|
|
671
|
+
if (isEnvRef(given))
|
|
672
|
+
return readSecret2(given, `@hamur/auth: ${exportName(name)} ${where}`);
|
|
673
|
+
if (typeof given === "string" && given !== "")
|
|
674
|
+
return given;
|
|
675
|
+
throw new Error(`@hamur/auth: ${exportName(name)} needs ${where}`);
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
function presetHandler(preset, options) {
|
|
679
|
+
const { name } = preset;
|
|
680
|
+
const config = presetConfig(name, options);
|
|
681
|
+
const record = preset.record(config);
|
|
682
|
+
const read = reader(name, config);
|
|
683
|
+
const tokenAuth = record.tokenAuth ?? "client_secret_basic";
|
|
684
|
+
const scopes = options.scope ?? record.scope;
|
|
685
|
+
return createOAuthHandler({
|
|
686
|
+
authorizationURL: record.authorizationURL,
|
|
687
|
+
tokenURL: record.tokenURL,
|
|
688
|
+
...record.userURL === undefined ? {} : { userURL: record.userURL },
|
|
689
|
+
clientId: "",
|
|
690
|
+
...tokenAuth === "none" ? {} : { clientSecret: "" },
|
|
691
|
+
scope: record.scopeSeparator === undefined ? scopes : [],
|
|
692
|
+
...record.issuer === undefined ? {} : { issuer: record.issuer },
|
|
693
|
+
tokenAuth,
|
|
694
|
+
...record.responseMode === undefined ? {} : { responseMode: record.responseMode },
|
|
695
|
+
...record.pkce === undefined ? {} : { pkce: record.pkce },
|
|
696
|
+
authorizationParams: {
|
|
697
|
+
...record.authorizationParams,
|
|
698
|
+
...record.scopeSeparator !== undefined && scopes.length ? { scope: scopes.join(record.scopeSeparator) } : {},
|
|
699
|
+
...options.authorizationParams
|
|
700
|
+
},
|
|
701
|
+
...typeof config.redirectURL === "string" ? { redirectURL: config.redirectURL } : {},
|
|
702
|
+
mapUser: record.mapUser,
|
|
703
|
+
onSuccess: options.onSuccess,
|
|
704
|
+
...options.onError ? { onError: options.onError } : {}
|
|
705
|
+
}, {
|
|
706
|
+
provider: name,
|
|
707
|
+
clientId: (event) => read(event, "clientId"),
|
|
708
|
+
clientSecret: (event, clientId) => record.clientSecret ? record.clientSecret({ event, clientId, read }) : read(event, "clientSecret"),
|
|
709
|
+
...record.profile ? { profile: record.profile } : {},
|
|
710
|
+
...record.clientIdScope && options.scope === undefined ? { scope: (clientId) => [...record.scope, clientId] } : {},
|
|
711
|
+
...record.clientIdParam ? { clientIdParam: record.clientIdParam } : {},
|
|
712
|
+
...record.tokenRequest ? { tokenRequest: record.tokenRequest } : {}
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// packages/auth/src/server/oauth/oidc.ts
|
|
717
|
+
var DISCOVERY_TTL = 3600;
|
|
718
|
+
var CLOCK_TOLERANCE = 60;
|
|
719
|
+
var PROVIDER2 = "oidc";
|
|
720
|
+
var ENDPOINTS = ["authorization_endpoint", "token_endpoint", "jwks_uri"];
|
|
721
|
+
var STRING_LISTS = [
|
|
722
|
+
"id_token_signing_alg_values_supported",
|
|
723
|
+
"token_endpoint_auth_methods_supported",
|
|
724
|
+
"response_modes_supported"
|
|
725
|
+
];
|
|
726
|
+
var ID_TOKEN_ALGORITHMS = [
|
|
727
|
+
"RS256",
|
|
728
|
+
"RS384",
|
|
729
|
+
"RS512",
|
|
730
|
+
"PS256",
|
|
731
|
+
"PS384",
|
|
732
|
+
"PS512",
|
|
733
|
+
"ES256",
|
|
734
|
+
"ES384",
|
|
735
|
+
"Ed25519",
|
|
736
|
+
"EdDSA"
|
|
737
|
+
];
|
|
738
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
739
|
+
function isHttps(value) {
|
|
740
|
+
if (typeof value !== "string")
|
|
741
|
+
return false;
|
|
742
|
+
try {
|
|
743
|
+
return new URL(value).protocol === "https:";
|
|
744
|
+
} catch {
|
|
745
|
+
return false;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
var isStrings = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
749
|
+
var invalid = (claim) => createError4({ status: 401, message: `Invalid ID token: ${claim}` });
|
|
750
|
+
var discoveryFailed = () => createError4({ status: 502, message: "OIDC discovery failed" });
|
|
751
|
+
async function storageKey(issuer) {
|
|
752
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(issuer)));
|
|
753
|
+
return `oidc:${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
754
|
+
}
|
|
755
|
+
function metadataOf(document, issuer) {
|
|
756
|
+
if (document.issuer !== issuer)
|
|
757
|
+
return { invalid: "issuer" };
|
|
758
|
+
const endpoint = ENDPOINTS.find((field) => !isHttps(document[field]));
|
|
759
|
+
if (endpoint)
|
|
760
|
+
return { invalid: `${endpoint} is not an https URL` };
|
|
761
|
+
const list = STRING_LISTS.find((field) => document[field] !== undefined && !isStrings(document[field]));
|
|
762
|
+
if (list)
|
|
763
|
+
return { invalid: `${list} is not a list of strings` };
|
|
764
|
+
const iss = document.authorization_response_iss_parameter_supported;
|
|
765
|
+
if (iss !== undefined && typeof iss !== "boolean")
|
|
766
|
+
return { invalid: "authorization_response_iss_parameter_supported is not a boolean" };
|
|
767
|
+
const advertised = document.id_token_signing_alg_values_supported;
|
|
768
|
+
const algorithms = advertised ? ID_TOKEN_ALGORITHMS.filter((alg) => advertised.includes(alg)) : ["RS256"];
|
|
769
|
+
if (!algorithms.length)
|
|
770
|
+
return { invalid: "id_token_signing_alg_values_supported names no algorithm Hamur verifies" };
|
|
771
|
+
return {
|
|
772
|
+
issuer,
|
|
773
|
+
authorization_endpoint: document.authorization_endpoint,
|
|
774
|
+
token_endpoint: document.token_endpoint,
|
|
775
|
+
jwks_uri: document.jwks_uri,
|
|
776
|
+
algorithms,
|
|
777
|
+
...document.token_endpoint_auth_methods_supported === undefined ? {} : { token_endpoint_auth_methods_supported: document.token_endpoint_auth_methods_supported },
|
|
778
|
+
...iss === undefined ? {} : { authorization_response_iss_parameter_supported: iss }
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
var known = new Map;
|
|
782
|
+
var inFlight = new Map;
|
|
783
|
+
async function discover(event, issuer) {
|
|
784
|
+
const held = known.get(issuer);
|
|
785
|
+
if (held && Date.now() < held.fetchedAt + DISCOVERY_TTL * 1000)
|
|
786
|
+
return held.metadata;
|
|
787
|
+
let pending = inFlight.get(issuer);
|
|
788
|
+
if (!pending) {
|
|
789
|
+
pending = load(event, issuer).finally(() => inFlight.delete(issuer));
|
|
790
|
+
inFlight.set(issuer, pending);
|
|
791
|
+
}
|
|
792
|
+
return pending;
|
|
793
|
+
}
|
|
794
|
+
async function load(event, issuer) {
|
|
795
|
+
const key = await storageKey(issuer);
|
|
796
|
+
const storage = useStorage3("cache");
|
|
797
|
+
const stored = await storage.getItem(key).catch(() => {
|
|
798
|
+
return;
|
|
799
|
+
});
|
|
800
|
+
if (isRecord(stored) && typeof stored.fetchedAt === "number" && Date.now() < stored.fetchedAt + DISCOVERY_TTL * 1000 && isRecord(stored.document)) {
|
|
801
|
+
const metadata = metadataOf(stored.document, issuer);
|
|
802
|
+
if (!("invalid" in metadata)) {
|
|
803
|
+
known.set(issuer, { fetchedAt: stored.fetchedAt, metadata });
|
|
804
|
+
return metadata;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
const url = `${issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
|
|
808
|
+
let response;
|
|
809
|
+
let text;
|
|
810
|
+
try {
|
|
811
|
+
response = await fetch(url, {
|
|
812
|
+
headers: { accept: "application/json" },
|
|
813
|
+
redirect: "manual",
|
|
814
|
+
signal: AbortSignal.timeout(TIMEOUT)
|
|
815
|
+
});
|
|
816
|
+
text = await response.text();
|
|
817
|
+
} catch {
|
|
818
|
+
throw noAnswer();
|
|
819
|
+
}
|
|
820
|
+
let document;
|
|
821
|
+
try {
|
|
822
|
+
document = JSON.parse(text);
|
|
823
|
+
} catch {
|
|
824
|
+
document = undefined;
|
|
825
|
+
}
|
|
826
|
+
const log = event.log.child({ name: "hamur" });
|
|
827
|
+
if (!response.ok || !isRecord(document)) {
|
|
828
|
+
log.warn("OIDC discovery failed", { status: response.status });
|
|
829
|
+
throw discoveryFailed();
|
|
830
|
+
}
|
|
831
|
+
const metadata = metadataOf(document, issuer);
|
|
832
|
+
if ("invalid" in metadata) {
|
|
833
|
+
if (metadata.invalid === "issuer")
|
|
834
|
+
throw createError4({ status: 502, message: "OIDC discovery issuer mismatch" });
|
|
835
|
+
log.warn(`OIDC discovery failed: ${metadata.invalid}`);
|
|
836
|
+
throw discoveryFailed();
|
|
837
|
+
}
|
|
838
|
+
const fetchedAt = Date.now();
|
|
839
|
+
known.set(issuer, { fetchedAt, metadata });
|
|
840
|
+
await storage.setItem(key, { fetchedAt, document }, { ttl: DISCOVERY_TTL }).catch(() => {});
|
|
841
|
+
return metadata;
|
|
842
|
+
}
|
|
843
|
+
function clientAuth(methods, confidential) {
|
|
844
|
+
if (!confidential) {
|
|
845
|
+
if (methods === undefined || methods.includes("none"))
|
|
846
|
+
return "none";
|
|
847
|
+
} else {
|
|
848
|
+
if (methods === undefined || methods.includes("client_secret_basic"))
|
|
849
|
+
return "client_secret_basic";
|
|
850
|
+
if (methods.includes("client_secret_post"))
|
|
851
|
+
return "client_secret_post";
|
|
852
|
+
}
|
|
853
|
+
throw createError4({ status: 502, message: "OIDC provider supports no client authentication Hamur offers" });
|
|
854
|
+
}
|
|
855
|
+
async function verifyIDToken(token, check) {
|
|
856
|
+
const claims = await idTokenClaims(token, check.jwksUri, {
|
|
857
|
+
issuer: check.issuer,
|
|
858
|
+
audience: check.clientId,
|
|
859
|
+
algorithms: check.algorithms,
|
|
860
|
+
clockTolerance: CLOCK_TOLERANCE
|
|
861
|
+
});
|
|
862
|
+
if (claims.exp === undefined)
|
|
863
|
+
throw invalid("exp");
|
|
864
|
+
if (claims.iat === undefined)
|
|
865
|
+
throw invalid("iat");
|
|
866
|
+
const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
867
|
+
if (!audience.every((aud) => aud === check.clientId || typeof aud === "string" && check.audiences.includes(aud)))
|
|
868
|
+
throw invalid("aud");
|
|
869
|
+
if (claims.azp === undefined ? audience.length > 1 : claims.azp !== check.clientId)
|
|
870
|
+
throw invalid("azp");
|
|
871
|
+
if (typeof claims.nonce !== "string" || check.nonce === undefined || !timingSafeEqual3(claims.nonce, check.nonce))
|
|
872
|
+
throw invalid("nonce");
|
|
873
|
+
return claims;
|
|
874
|
+
}
|
|
875
|
+
function oauthOIDC(options) {
|
|
876
|
+
const { issuer } = options;
|
|
877
|
+
if (!isHttps(issuer))
|
|
878
|
+
throw new TypeError(`oauthOIDC issuer must be an https URL (got ${JSON.stringify(issuer)})`);
|
|
879
|
+
if (options.scope !== undefined && !isStrings(options.scope))
|
|
880
|
+
throw new TypeError("oauthOIDC scope must be an array of strings");
|
|
881
|
+
if (options.audiences !== undefined && !isStrings(options.audiences))
|
|
882
|
+
throw new TypeError("oauthOIDC audiences must be an array of strings");
|
|
883
|
+
const given = options.scope ?? ["openid", "profile", "email"];
|
|
884
|
+
const scope = given.includes("openid") ? given : ["openid", ...given];
|
|
885
|
+
const audiences = options.audiences ?? [];
|
|
886
|
+
const confidential = options.clientSecret !== undefined;
|
|
887
|
+
return createOAuthHandler({
|
|
888
|
+
authorizationURL: issuer,
|
|
889
|
+
tokenURL: issuer,
|
|
890
|
+
clientId: options.clientId,
|
|
891
|
+
...confidential ? { clientSecret: options.clientSecret } : {},
|
|
892
|
+
scope,
|
|
893
|
+
tokenAuth: confidential ? "client_secret_basic" : "none",
|
|
894
|
+
onSuccess: (event, result) => options.onSuccess(event, result),
|
|
895
|
+
...options.onError ? { onError: options.onError } : {}
|
|
896
|
+
}, {
|
|
897
|
+
provider: PROVIDER2,
|
|
898
|
+
nonce: true,
|
|
899
|
+
async endpoints(event) {
|
|
900
|
+
const metadata = await discover(event, issuer);
|
|
901
|
+
return {
|
|
902
|
+
authorizationURL: metadata.authorization_endpoint,
|
|
903
|
+
tokenURL: metadata.token_endpoint,
|
|
904
|
+
...metadata.authorization_response_iss_parameter_supported === true ? { issuer } : {},
|
|
905
|
+
tokenAuth: clientAuth(metadata.token_endpoint_auth_methods_supported, confidential)
|
|
906
|
+
};
|
|
907
|
+
},
|
|
908
|
+
clientId: () => readOAuthSecret(options.clientId, "clientId", "oauthOIDC"),
|
|
909
|
+
clientSecret: () => readOAuthSecret(options.clientSecret, "clientSecret", "oauthOIDC"),
|
|
910
|
+
async profile({ event, tokens, clientId, nonce }) {
|
|
911
|
+
const metadata = await discover(event, issuer);
|
|
912
|
+
return verifyIDToken(tokens.id_token, {
|
|
913
|
+
jwksUri: metadata.jwks_uri,
|
|
914
|
+
algorithms: metadata.algorithms,
|
|
915
|
+
issuer,
|
|
916
|
+
clientId,
|
|
917
|
+
audiences,
|
|
918
|
+
nonce
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
// packages/auth/src/server/oauth/atproto.ts
|
|
924
|
+
import { baseURL as baseURL3 } from "#hamur/auth/guards";
|
|
925
|
+
import { createError as createError5, getRequestURL as getRequestURL2 } from "hamur/server";
|
|
926
|
+
|
|
927
|
+
// packages/auth/src/server/oauth/atproto-fetch.ts
|
|
928
|
+
import { hostFetch } from "#hamur/auth/atproto";
|
|
929
|
+
import { urlProblem } from "hamur/server/internal";
|
|
930
|
+
import { hostProblem, urlProblem as urlProblem2 } from "hamur/server/internal";
|
|
931
|
+
var FETCH_TIMEOUT = 5000;
|
|
932
|
+
var MAX_BODY = 65536;
|
|
933
|
+
|
|
934
|
+
class AtprotoResolveError extends Error {
|
|
935
|
+
}
|
|
936
|
+
async function readBody(response, url) {
|
|
937
|
+
const length = Number(response.headers.get("content-length"));
|
|
938
|
+
if (length > MAX_BODY) {
|
|
939
|
+
await response.body?.cancel().catch(() => {});
|
|
940
|
+
throw new AtprotoResolveError(`${url} answered more than ${MAX_BODY} bytes`);
|
|
941
|
+
}
|
|
942
|
+
if (!response.body)
|
|
943
|
+
return "";
|
|
944
|
+
const reader = response.body.getReader();
|
|
945
|
+
const chunks = [];
|
|
946
|
+
let size = 0;
|
|
947
|
+
for (;; ) {
|
|
948
|
+
const { done, value } = await reader.read();
|
|
949
|
+
if (done)
|
|
950
|
+
break;
|
|
951
|
+
size += value.byteLength;
|
|
952
|
+
if (size > MAX_BODY) {
|
|
953
|
+
await reader.cancel().catch(() => {});
|
|
954
|
+
throw new AtprotoResolveError(`${url} answered more than ${MAX_BODY} bytes`);
|
|
955
|
+
}
|
|
956
|
+
chunks.push(value);
|
|
957
|
+
}
|
|
958
|
+
const bytes = new Uint8Array(size);
|
|
959
|
+
let at = 0;
|
|
960
|
+
for (const chunk of chunks) {
|
|
961
|
+
bytes.set(chunk, at);
|
|
962
|
+
at += chunk.byteLength;
|
|
963
|
+
}
|
|
964
|
+
return new TextDecoder().decode(bytes);
|
|
965
|
+
}
|
|
966
|
+
async function atprotoFetch(url, init = {}) {
|
|
967
|
+
const problem = urlProblem(url);
|
|
968
|
+
if (problem !== undefined)
|
|
969
|
+
throw new AtprotoResolveError(`${url}: ${problem}`);
|
|
970
|
+
const sent = { ...init, redirect: "manual", signal: AbortSignal.timeout(FETCH_TIMEOUT) };
|
|
971
|
+
let response;
|
|
972
|
+
let text;
|
|
973
|
+
try {
|
|
974
|
+
response = hostFetch ? await hostFetch(url, sent) : await fetch(url, sent);
|
|
975
|
+
if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
|
|
976
|
+
await response.body?.cancel().catch(() => {});
|
|
977
|
+
throw new AtprotoResolveError(`${url} answered a redirect`);
|
|
978
|
+
}
|
|
979
|
+
text = await readBody(response, url);
|
|
980
|
+
} catch (error) {
|
|
981
|
+
if (error instanceof AtprotoResolveError)
|
|
982
|
+
throw error;
|
|
983
|
+
throw new AtprotoResolveError(`${url}: ${error.message}`);
|
|
984
|
+
}
|
|
985
|
+
return { status: response.status, ok: response.ok, headers: response.headers, text };
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// packages/auth/src/server/oauth/dpop.ts
|
|
989
|
+
import { toBase64Url as toBase64Url3 } from "hamur/server/internal";
|
|
990
|
+
var ALGORITHM = { name: "ECDSA", namedCurve: "P-256" };
|
|
991
|
+
var encoder = new TextEncoder;
|
|
992
|
+
var part = (value) => toBase64Url3(encoder.encode(JSON.stringify(value)));
|
|
993
|
+
async function createDPoPKey() {
|
|
994
|
+
const pair = await crypto.subtle.generateKey(ALGORITHM, true, ["sign", "verify"]);
|
|
995
|
+
const { kty, crv, x, y, d } = await crypto.subtle.exportKey("jwk", pair.privateKey);
|
|
996
|
+
return { kty, crv, x, y, d };
|
|
997
|
+
}
|
|
998
|
+
async function dpopProof(key, method, url, nonce) {
|
|
999
|
+
const { kty, crv, x, y } = key;
|
|
1000
|
+
const target = new URL(url);
|
|
1001
|
+
const header = { typ: "dpop+jwt", alg: "ES256", jwk: { kty, crv, x, y } };
|
|
1002
|
+
const payload = {
|
|
1003
|
+
jti: toBase64Url3(crypto.getRandomValues(new Uint8Array(16))),
|
|
1004
|
+
htm: method,
|
|
1005
|
+
htu: `${target.origin}${target.pathname}`,
|
|
1006
|
+
iat: Math.floor(Date.now() / 1000),
|
|
1007
|
+
...nonce === undefined ? {} : { nonce }
|
|
1008
|
+
};
|
|
1009
|
+
const input = `${part(header)}.${part(payload)}`;
|
|
1010
|
+
const signing = await crypto.subtle.importKey("jwk", { kty, crv, x, y, d: key.d }, ALGORITHM, false, ["sign"]);
|
|
1011
|
+
const signature = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, signing, encoder.encode(input)));
|
|
1012
|
+
return `${input}.${toBase64Url3(signature)}`;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// packages/auth/src/server/oauth/atproto.ts
|
|
1016
|
+
var PROVIDER3 = "atproto";
|
|
1017
|
+
var UNRESOLVED = "AT Protocol handle could not be resolved";
|
|
1018
|
+
var MISMATCH = "AT Protocol handle does not match its DID";
|
|
1019
|
+
var DID = /^did:(?:plc:[a-z2-7]{24}|web:[a-z0-9.-]+)$/;
|
|
1020
|
+
var MAX_URL = 2048;
|
|
1021
|
+
var MAX_NONCE = 256;
|
|
1022
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1023
|
+
var isStrings2 = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
1024
|
+
function fail(reason) {
|
|
1025
|
+
throw new AtprotoResolveError(reason);
|
|
1026
|
+
}
|
|
1027
|
+
var registered = [];
|
|
1028
|
+
var appBase = () => baseURL3.replace(/\/+$/, "");
|
|
1029
|
+
var clientIdOf = (origin) => `${origin}${appBase()}${ATPROTO_METADATA_ROUTE}`;
|
|
1030
|
+
async function json(url) {
|
|
1031
|
+
const answer = await atprotoFetch(url, { headers: { accept: "application/json" } });
|
|
1032
|
+
if (!answer.ok)
|
|
1033
|
+
fail(`${url} answered ${answer.status}`);
|
|
1034
|
+
return parsed(answer) ?? fail(`${url} did not answer a JSON object`);
|
|
1035
|
+
}
|
|
1036
|
+
function parsed(answer) {
|
|
1037
|
+
try {
|
|
1038
|
+
const value = JSON.parse(answer.text);
|
|
1039
|
+
return isRecord2(value) ? value : undefined;
|
|
1040
|
+
} catch {
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
function httpsURL(value, what) {
|
|
1045
|
+
if (typeof value !== "string")
|
|
1046
|
+
return fail(`${what} is missing`);
|
|
1047
|
+
if (value.length > MAX_URL)
|
|
1048
|
+
return fail(`${what} is longer than ${MAX_URL} characters`);
|
|
1049
|
+
const problem = urlProblem2(value);
|
|
1050
|
+
return problem === undefined ? value : fail(`${what} ${value}: ${problem}`);
|
|
1051
|
+
}
|
|
1052
|
+
async function resolve(given) {
|
|
1053
|
+
const handle = (given ?? "").toLowerCase();
|
|
1054
|
+
if (!handle)
|
|
1055
|
+
fail("no handle");
|
|
1056
|
+
const syntax = hostProblem(handle);
|
|
1057
|
+
if (syntax !== undefined)
|
|
1058
|
+
fail(`handle ${JSON.stringify(handle)}: ${syntax}`);
|
|
1059
|
+
const named = await atprotoFetch(`https://${handle}/.well-known/atproto-did`, { headers: { accept: "text/plain" } });
|
|
1060
|
+
if (!named.ok)
|
|
1061
|
+
fail(`https://${handle}/.well-known/atproto-did answered ${named.status}`);
|
|
1062
|
+
const did = named.text.trim();
|
|
1063
|
+
if (!DID.test(did))
|
|
1064
|
+
fail(`https://${handle}/.well-known/atproto-did did not answer a did:plc or did:web`);
|
|
1065
|
+
const document = await json(did.startsWith("did:plc:") ? `https://plc.directory/${did}` : `https://${did.slice("did:web:".length)}/.well-known/did.json`);
|
|
1066
|
+
if (document.id !== did)
|
|
1067
|
+
fail(`the DID document of ${did} names another id`);
|
|
1068
|
+
const aliases = isStrings2(document.alsoKnownAs) ? document.alsoKnownAs : [];
|
|
1069
|
+
if (!aliases.some((alias) => alias.toLowerCase() === `at://${handle}`))
|
|
1070
|
+
throw createError5({ status: 401, message: MISMATCH });
|
|
1071
|
+
const services = Array.isArray(document.service) ? document.service.filter(isRecord2) : [];
|
|
1072
|
+
const pds = services.find((service) => (service.id === "#atproto_pds" || service.id === `${did}#atproto_pds`) && service.type === "AtprotoPersonalDataServer");
|
|
1073
|
+
const pdsOrigin = new URL(httpsURL(pds?.serviceEndpoint, "the PDS")).origin;
|
|
1074
|
+
const resource = await json(`${pdsOrigin}/.well-known/oauth-protected-resource`);
|
|
1075
|
+
const servers = isStrings2(resource.authorization_servers) ? resource.authorization_servers : [];
|
|
1076
|
+
const issuer = new URL(httpsURL(servers[0], "the authorization server")).origin;
|
|
1077
|
+
const metadata = await json(`${issuer}/.well-known/oauth-authorization-server`);
|
|
1078
|
+
if (metadata.issuer !== issuer)
|
|
1079
|
+
fail(`the authorization server metadata's issuer is not ${issuer}`);
|
|
1080
|
+
return {
|
|
1081
|
+
did,
|
|
1082
|
+
handle,
|
|
1083
|
+
issuer,
|
|
1084
|
+
par: httpsURL(metadata.pushed_authorization_request_endpoint, "pushed_authorization_request_endpoint"),
|
|
1085
|
+
authorize: httpsURL(metadata.authorization_endpoint, "authorization_endpoint"),
|
|
1086
|
+
token: httpsURL(metadata.token_endpoint, "token_endpoint")
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
async function dpopPost(url, body, key, nonce) {
|
|
1090
|
+
for (let attempt = 0;; attempt++) {
|
|
1091
|
+
const headers = {
|
|
1092
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
1093
|
+
accept: "application/json",
|
|
1094
|
+
dpop: await dpopProof(key, "POST", url, nonce)
|
|
1095
|
+
};
|
|
1096
|
+
const answer = await atprotoFetch(url, { method: "POST", headers, body: body.toString() });
|
|
1097
|
+
const fresh = answer.headers.get("dpop-nonce") ?? nonce;
|
|
1098
|
+
if (fresh !== undefined && fresh.length > MAX_NONCE)
|
|
1099
|
+
fail(`${url} sent a DPoP-Nonce longer than ${MAX_NONCE} characters`);
|
|
1100
|
+
const json = parsed(answer);
|
|
1101
|
+
if (attempt === 0 && !answer.ok && json?.error === "use_dpop_nonce" && fresh !== undefined && fresh !== nonce) {
|
|
1102
|
+
nonce = fresh;
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
return { answer, json, nonce: fresh };
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
function unresolved(event, error) {
|
|
1109
|
+
if (!(error instanceof AtprotoResolveError))
|
|
1110
|
+
throw error;
|
|
1111
|
+
event.log.child({ name: "hamur" }).debug(UNRESOLVED, { reason: error.message });
|
|
1112
|
+
throw createError5({ status: 400, message: UNRESOLVED });
|
|
1113
|
+
}
|
|
1114
|
+
var isFlowData = (value) => isRecord2(value) && typeof value.did === "string" && typeof value.handle === "string" && typeof value.token === "string" && isRecord2(value.dpopKey) && (value.nonce === undefined || typeof value.nonce === "string");
|
|
1115
|
+
function oauthAtproto(options) {
|
|
1116
|
+
if (options.scope !== undefined && !isStrings2(options.scope))
|
|
1117
|
+
throw new TypeError("oauthAtproto scope must be an array of strings");
|
|
1118
|
+
if (options.clientMetadata !== undefined && !isRecord2(options.clientMetadata))
|
|
1119
|
+
throw new TypeError("oauthAtproto clientMetadata must be an object");
|
|
1120
|
+
const given = options.scope ?? ["atproto"];
|
|
1121
|
+
const scope = given.includes("atproto") ? given : ["atproto", ...given];
|
|
1122
|
+
registered.push({ clientMetadata: options.clientMetadata ?? {}, scope });
|
|
1123
|
+
return createOAuthHandler({
|
|
1124
|
+
authorizationURL: "https://atproto.invalid/",
|
|
1125
|
+
tokenURL: "https://atproto.invalid/",
|
|
1126
|
+
clientId: "",
|
|
1127
|
+
scope,
|
|
1128
|
+
tokenAuth: "none",
|
|
1129
|
+
onSuccess: (event, { user, tokens }) => options.onSuccess(event, { ...user, tokens }),
|
|
1130
|
+
...options.onError ? { onError: options.onError } : {}
|
|
1131
|
+
}, {
|
|
1132
|
+
provider: PROVIDER3,
|
|
1133
|
+
clientId: (event) => clientIdOf(getRequestURL2(event).origin),
|
|
1134
|
+
clientSecret: () => "",
|
|
1135
|
+
async authorize({ event, params }) {
|
|
1136
|
+
try {
|
|
1137
|
+
const target = await resolve(getRequestURL2(event).searchParams.get("handle"));
|
|
1138
|
+
const dpopKey = await createDPoPKey();
|
|
1139
|
+
params.set("login_hint", target.handle);
|
|
1140
|
+
const pushed = await dpopPost(target.par, params, dpopKey, undefined);
|
|
1141
|
+
const requestURI = pushed.json?.request_uri;
|
|
1142
|
+
if (!pushed.answer.ok || typeof requestURI !== "string" || requestURI.length > MAX_URL) {
|
|
1143
|
+
const error = typeof pushed.json?.error === "string" ? `: ${errorCode(pushed.json.error)}` : "";
|
|
1144
|
+
fail(`the pushed authorization request answered ${pushed.answer.status}${error}`);
|
|
1145
|
+
}
|
|
1146
|
+
const location = new URL(target.authorize);
|
|
1147
|
+
location.searchParams.set("client_id", params.get("client_id"));
|
|
1148
|
+
location.searchParams.set("request_uri", requestURI);
|
|
1149
|
+
const data = {
|
|
1150
|
+
did: target.did,
|
|
1151
|
+
handle: target.handle,
|
|
1152
|
+
token: target.token,
|
|
1153
|
+
dpopKey,
|
|
1154
|
+
...pushed.nonce === undefined ? {} : { nonce: pushed.nonce }
|
|
1155
|
+
};
|
|
1156
|
+
return { location: location.href, issuer: target.issuer, data: { ...data } };
|
|
1157
|
+
} catch (error) {
|
|
1158
|
+
return unresolved(event, error);
|
|
1159
|
+
}
|
|
1160
|
+
},
|
|
1161
|
+
async tokenRequest({ event, body, data }) {
|
|
1162
|
+
if (!isFlowData(data))
|
|
1163
|
+
throw createError5({ status: 400, message: "Invalid OAuth state" });
|
|
1164
|
+
let sent;
|
|
1165
|
+
try {
|
|
1166
|
+
sent = await dpopPost(data.token, body, data.dpopKey, data.nonce);
|
|
1167
|
+
} catch (error) {
|
|
1168
|
+
return unresolved(event, error);
|
|
1169
|
+
}
|
|
1170
|
+
const granted = typeof sent.json?.scope === "string" ? sent.json.scope.split(" ") : [];
|
|
1171
|
+
const dpop = typeof sent.json?.token_type === "string" && sent.json.token_type.toLowerCase() === "dpop";
|
|
1172
|
+
if (!sent.answer.ok || !sent.json || !dpop || !granted.includes("atproto")) {
|
|
1173
|
+
const error = typeof sent.json?.error === "string" ? { error: errorCode(sent.json.error) } : sent.answer.ok ? { reason: "not a DPoP token with the atproto scope" } : {};
|
|
1174
|
+
event.log.child({ name: "hamur" }).warn("OAuth token request failed", { status: sent.answer.status, ...error });
|
|
1175
|
+
throw createError5({ status: 401, message: "OAuth token request failed" });
|
|
1176
|
+
}
|
|
1177
|
+
return sent.json;
|
|
1178
|
+
},
|
|
1179
|
+
async profile({ tokens, data }) {
|
|
1180
|
+
if (!isFlowData(data))
|
|
1181
|
+
throw createError5({ status: 400, message: "Invalid OAuth state" });
|
|
1182
|
+
if (tokens.sub !== data.did)
|
|
1183
|
+
throw createError5({ status: 401, message: MISMATCH });
|
|
1184
|
+
return { did: data.did, handle: data.handle, dpopKey: data.dpopKey };
|
|
1185
|
+
}
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
// packages/auth/src/server/oauth/providers/apple.ts
|
|
1189
|
+
import { signJWT } from "hamur/server";
|
|
1190
|
+
var SECRET_TTL = 3600;
|
|
1191
|
+
var RENEW_BEFORE = 300;
|
|
1192
|
+
async function importPrivateKey(pem) {
|
|
1193
|
+
const body = pem.replace(/\\n/g, `
|
|
1194
|
+
`).replace(/-----(BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, "");
|
|
1195
|
+
let der;
|
|
1196
|
+
try {
|
|
1197
|
+
der = Uint8Array.from(atob(body), (char) => char.charCodeAt(0));
|
|
1198
|
+
} catch {
|
|
1199
|
+
throw new TypeError("@hamur/auth: oauthApple privateKey must be a PKCS #8 PEM key (the .p8 file)");
|
|
1200
|
+
}
|
|
1201
|
+
return crypto.subtle.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
|
|
1202
|
+
}
|
|
1203
|
+
var text = (value) => typeof value === "string" && value !== "" ? value.slice(0, 256) : undefined;
|
|
1204
|
+
function nameOf(field) {
|
|
1205
|
+
if (field === null)
|
|
1206
|
+
return;
|
|
1207
|
+
let value;
|
|
1208
|
+
try {
|
|
1209
|
+
value = JSON.parse(field);
|
|
1210
|
+
} catch {
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
const name = value?.name;
|
|
1214
|
+
if (typeof name !== "object" || name === null)
|
|
1215
|
+
return;
|
|
1216
|
+
const firstName = text(name.firstName);
|
|
1217
|
+
const lastName = text(name.lastName);
|
|
1218
|
+
return firstName || lastName ? { ...firstName ? { firstName } : {}, ...lastName ? { lastName } : {} } : undefined;
|
|
1219
|
+
}
|
|
1220
|
+
function appleRecord() {
|
|
1221
|
+
let key;
|
|
1222
|
+
let secret;
|
|
1223
|
+
return () => ({
|
|
1224
|
+
authorizationURL: `${APPLE_ORIGIN}/auth/authorize`,
|
|
1225
|
+
tokenURL: `${APPLE_ORIGIN}/auth/token`,
|
|
1226
|
+
scope: ["name", "email"],
|
|
1227
|
+
tokenAuth: "client_secret_post",
|
|
1228
|
+
responseMode: "form_post",
|
|
1229
|
+
pkce: false,
|
|
1230
|
+
async clientSecret({ event, clientId, read }) {
|
|
1231
|
+
const teamId = read(event, "teamId");
|
|
1232
|
+
const keyId = read(event, "keyId");
|
|
1233
|
+
const pem = read(event, "privateKey");
|
|
1234
|
+
const id = `${teamId}
|
|
1235
|
+
${keyId}
|
|
1236
|
+
${clientId}
|
|
1237
|
+
${pem}`;
|
|
1238
|
+
const now = Math.floor(Date.now() / 1000);
|
|
1239
|
+
if (secret?.id === id && now < secret.until)
|
|
1240
|
+
return secret.value;
|
|
1241
|
+
if (key?.pem !== pem)
|
|
1242
|
+
key = { pem, value: importPrivateKey(pem) };
|
|
1243
|
+
const value = await signJWT({}, await key.value, {
|
|
1244
|
+
alg: "ES256",
|
|
1245
|
+
kid: keyId,
|
|
1246
|
+
issuer: teamId,
|
|
1247
|
+
subject: clientId,
|
|
1248
|
+
audience: APPLE_ORIGIN,
|
|
1249
|
+
expiresIn: SECRET_TTL
|
|
1250
|
+
});
|
|
1251
|
+
secret = { id, value, until: now + SECRET_TTL - RENEW_BEFORE };
|
|
1252
|
+
return value;
|
|
1253
|
+
},
|
|
1254
|
+
async profile({ tokens, params, clientId }) {
|
|
1255
|
+
const claims = await idTokenClaims(tokens.id_token, `${APPLE_ORIGIN}/auth/keys`, {
|
|
1256
|
+
issuer: APPLE_ORIGIN,
|
|
1257
|
+
audience: clientId
|
|
1258
|
+
});
|
|
1259
|
+
const name = nameOf(params.get("user"));
|
|
1260
|
+
return { ...claims, ...name ? { name } : {} };
|
|
1261
|
+
},
|
|
1262
|
+
mapUser: (profile) => profile
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
var apple = { name: "apple", record: appleRecord() };
|
|
1266
|
+
function oauthApple(options) {
|
|
1267
|
+
return presetHandler({ name: "apple", record: appleRecord() }, options);
|
|
1268
|
+
}
|
|
1269
|
+
// packages/auth/src/server/oauth/providers/discord.ts
|
|
1270
|
+
var discord = {
|
|
1271
|
+
name: "discord",
|
|
1272
|
+
record: () => ({
|
|
1273
|
+
authorizationURL: "https://discord.com/oauth2/authorize",
|
|
1274
|
+
tokenURL: "https://discord.com/api/oauth2/token",
|
|
1275
|
+
userURL: "https://discord.com/api/users/@me",
|
|
1276
|
+
scope: ["identify", "email"],
|
|
1277
|
+
tokenAuth: "client_secret_post",
|
|
1278
|
+
mapUser: (profile) => profile
|
|
1279
|
+
})
|
|
1280
|
+
};
|
|
1281
|
+
function oauthDiscord(options) {
|
|
1282
|
+
return presetHandler(discord, options);
|
|
1283
|
+
}
|
|
1284
|
+
// packages/auth/src/server/oauth/providers/github.ts
|
|
1285
|
+
var github = {
|
|
1286
|
+
name: "github",
|
|
1287
|
+
record: () => ({
|
|
1288
|
+
authorizationURL: "https://github.com/login/oauth/authorize",
|
|
1289
|
+
tokenURL: "https://github.com/login/oauth/access_token",
|
|
1290
|
+
scope: [],
|
|
1291
|
+
tokenAuth: "client_secret_post",
|
|
1292
|
+
profile: ({ event, tokens }) => providerJSON(event, "https://api.github.com/user", {
|
|
1293
|
+
headers: {
|
|
1294
|
+
authorization: `Bearer ${tokens.access_token}`,
|
|
1295
|
+
accept: "application/vnd.github+json",
|
|
1296
|
+
"user-agent": "hamur-auth"
|
|
1297
|
+
}
|
|
1298
|
+
}, "user request"),
|
|
1299
|
+
mapUser: (profile) => profile
|
|
1300
|
+
})
|
|
1301
|
+
};
|
|
1302
|
+
function oauthGitHub(options) {
|
|
1303
|
+
return presetHandler(github, options);
|
|
1304
|
+
}
|
|
1305
|
+
// packages/auth/src/server/oauth/providers/gitlab.ts
|
|
1306
|
+
var gitlab = {
|
|
1307
|
+
name: "gitlab",
|
|
1308
|
+
record: ({ baseURL = "https://gitlab.com" }) => {
|
|
1309
|
+
const base = baseURL.replace(/\/+$/, "");
|
|
1310
|
+
return {
|
|
1311
|
+
authorizationURL: `${base}/oauth/authorize`,
|
|
1312
|
+
tokenURL: `${base}/oauth/token`,
|
|
1313
|
+
userURL: `${base}/api/v4/user`,
|
|
1314
|
+
scope: ["read_user"],
|
|
1315
|
+
tokenAuth: "client_secret_post",
|
|
1316
|
+
mapUser: (profile) => profile
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
function oauthGitLab(options) {
|
|
1321
|
+
return presetHandler(gitlab, options);
|
|
1322
|
+
}
|
|
1323
|
+
// packages/auth/src/server/oauth/providers/google.ts
|
|
1324
|
+
var google = {
|
|
1325
|
+
name: "google",
|
|
1326
|
+
record: () => ({
|
|
1327
|
+
authorizationURL: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
1328
|
+
tokenURL: "https://oauth2.googleapis.com/token",
|
|
1329
|
+
userURL: "https://openidconnect.googleapis.com/v1/userinfo",
|
|
1330
|
+
scope: ["openid", "email", "profile"],
|
|
1331
|
+
tokenAuth: "client_secret_post",
|
|
1332
|
+
mapUser: (profile) => profile
|
|
1333
|
+
})
|
|
1334
|
+
};
|
|
1335
|
+
function oauthGoogle(options) {
|
|
1336
|
+
return presetHandler(google, options);
|
|
1337
|
+
}
|
|
1338
|
+
// packages/auth/src/server/oauth/providers/microsoft.ts
|
|
1339
|
+
var microsoft = {
|
|
1340
|
+
name: "microsoft",
|
|
1341
|
+
record: ({ tenant = "common" }) => {
|
|
1342
|
+
const base = `https://login.microsoftonline.com/${encodeURIComponent(tenant)}/oauth2/v2.0`;
|
|
1343
|
+
return {
|
|
1344
|
+
authorizationURL: `${base}/authorize`,
|
|
1345
|
+
tokenURL: `${base}/token`,
|
|
1346
|
+
userURL: "https://graph.microsoft.com/v1.0/me",
|
|
1347
|
+
scope: ["User.Read"],
|
|
1348
|
+
tokenAuth: "client_secret_post",
|
|
1349
|
+
mapUser: (profile) => profile
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
};
|
|
1353
|
+
function oauthMicrosoft(options) {
|
|
1354
|
+
return presetHandler(microsoft, options);
|
|
1355
|
+
}
|
|
1356
|
+
// packages/auth/src/server/oauth/providers/steam.ts
|
|
1357
|
+
import { baseURL as baseURL4, redirect as targets2 } from "#hamur/auth/guards";
|
|
1358
|
+
import {
|
|
1359
|
+
createError as createError6,
|
|
1360
|
+
deleteCookie as deleteCookie2,
|
|
1361
|
+
getCookie as getCookie2,
|
|
1362
|
+
getRequestURL as getRequestURL3,
|
|
1363
|
+
setCookie as setCookie2
|
|
1364
|
+
} from "hamur/server";
|
|
1365
|
+
import { sealFor as sealFor3, timingSafeEqual as timingSafeEqual4, unsealFor as unsealFor3 } from "hamur/server/internal";
|
|
1366
|
+
var STEAM_ENDPOINT = "https://steamcommunity.com/openid/login";
|
|
1367
|
+
var NS = "http://specs.openid.net/auth/2.0";
|
|
1368
|
+
var SELECT = `${NS}/identifier_select`;
|
|
1369
|
+
var CLAIMED = /^https:\/\/steamcommunity\.com\/openid\/id\/(\d+)$/;
|
|
1370
|
+
var MUST_SIGN = ["op_endpoint", "claimed_id", "identity", "return_to", "response_nonce", "assoc_handle"];
|
|
1371
|
+
var PROVIDER4 = "steam";
|
|
1372
|
+
var isFlow2 = (value) => typeof value === "object" && value !== null && ["state", "provider", "route", "redirectURI"].every((key) => typeof value[key] === "string");
|
|
1373
|
+
var failed = () => createError6({ status: 401, message: "Steam OpenID check failed" });
|
|
1374
|
+
var returnTo = (redirectURI, state) => {
|
|
1375
|
+
const url = new URL(redirectURI);
|
|
1376
|
+
url.searchParams.set("hamur_state", state);
|
|
1377
|
+
return url.href;
|
|
1378
|
+
};
|
|
1379
|
+
function checkAssertion(params, expectedReturnTo) {
|
|
1380
|
+
if (params.get("openid.mode") !== "id_res")
|
|
1381
|
+
throw failed();
|
|
1382
|
+
if (params.get("openid.ns") !== NS)
|
|
1383
|
+
throw failed();
|
|
1384
|
+
if (params.get("openid.op_endpoint") !== STEAM_ENDPOINT)
|
|
1385
|
+
throw failed();
|
|
1386
|
+
if (params.get("openid.return_to") !== expectedReturnTo)
|
|
1387
|
+
throw failed();
|
|
1388
|
+
const claimedId = params.get("openid.claimed_id");
|
|
1389
|
+
const match = claimedId === null ? null : CLAIMED.exec(claimedId);
|
|
1390
|
+
if (!match || params.get("openid.identity") !== claimedId)
|
|
1391
|
+
throw failed();
|
|
1392
|
+
const signed = (params.get("openid.signed") ?? "").split(",");
|
|
1393
|
+
if (!MUST_SIGN.every((field) => signed.includes(field)))
|
|
1394
|
+
throw failed();
|
|
1395
|
+
if (!params.get("openid.sig") || !params.get("openid.assoc_handle") || !params.get("openid.response_nonce"))
|
|
1396
|
+
throw failed();
|
|
1397
|
+
return { steamId: match[1], claimedId };
|
|
1398
|
+
}
|
|
1399
|
+
function verificationBody(params) {
|
|
1400
|
+
const body = new URLSearchParams;
|
|
1401
|
+
for (const [key, value] of params)
|
|
1402
|
+
if (key.startsWith("openid."))
|
|
1403
|
+
body.append(key, key === "openid.mode" ? "check_authentication" : value);
|
|
1404
|
+
return body;
|
|
1405
|
+
}
|
|
1406
|
+
async function verified(event, params) {
|
|
1407
|
+
let response;
|
|
1408
|
+
let text;
|
|
1409
|
+
try {
|
|
1410
|
+
response = await fetch(STEAM_ENDPOINT, {
|
|
1411
|
+
method: "POST",
|
|
1412
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "text/plain" },
|
|
1413
|
+
body: verificationBody(params),
|
|
1414
|
+
redirect: "manual",
|
|
1415
|
+
signal: AbortSignal.timeout(TIMEOUT)
|
|
1416
|
+
});
|
|
1417
|
+
text = await response.text();
|
|
1418
|
+
} catch {
|
|
1419
|
+
throw noAnswer();
|
|
1420
|
+
}
|
|
1421
|
+
if (!response.ok) {
|
|
1422
|
+
event.log.child({ name: "hamur" }).warn("Steam check_authentication failed", { status: response.status });
|
|
1423
|
+
return false;
|
|
1424
|
+
}
|
|
1425
|
+
return text.split(/\r?\n/).includes("is_valid:true");
|
|
1426
|
+
}
|
|
1427
|
+
function oauthSteam(options) {
|
|
1428
|
+
const config = presetConfig(PROVIDER4, options);
|
|
1429
|
+
const redirectURL = typeof config.redirectURL === "string" ? config.redirectURL : undefined;
|
|
1430
|
+
return async (_input, { event }) => {
|
|
1431
|
+
const url = getRequestURL3(event);
|
|
1432
|
+
if (event.request.method !== "GET") {
|
|
1433
|
+
event.response.headers.set("allow", "GET");
|
|
1434
|
+
throw createError6({ status: 405, message: "Method Not Allowed" });
|
|
1435
|
+
}
|
|
1436
|
+
event.response.headers.set("cache-control", "no-store");
|
|
1437
|
+
const route = appPath(url.pathname);
|
|
1438
|
+
const cookie = await flowCookie({ dev: Boolean(import.meta.dev), protocol: url.protocol, route, formPost: false });
|
|
1439
|
+
const redirectURI = redirectURL ?? `${url.origin}${url.pathname}`;
|
|
1440
|
+
const params = url.searchParams;
|
|
1441
|
+
if (!params.has("openid.mode") && !params.has("hamur_state")) {
|
|
1442
|
+
const state = randomToken();
|
|
1443
|
+
const flow = { state, provider: PROVIDER4, route, redirectURI };
|
|
1444
|
+
setCookie2(event, cookie.name, await sealFor3(flow, { purpose: PURPOSE2, ttl: TTL }), {
|
|
1445
|
+
...cookie.options,
|
|
1446
|
+
maxAge: TTL
|
|
1447
|
+
});
|
|
1448
|
+
const target = new URL(STEAM_ENDPOINT);
|
|
1449
|
+
target.searchParams.set("openid.ns", NS);
|
|
1450
|
+
target.searchParams.set("openid.mode", "checkid_setup");
|
|
1451
|
+
target.searchParams.set("openid.return_to", returnTo(redirectURI, state));
|
|
1452
|
+
target.searchParams.set("openid.realm", new URL(redirectURI).origin);
|
|
1453
|
+
target.searchParams.set("openid.identity", SELECT);
|
|
1454
|
+
target.searchParams.set("openid.claimed_id", SELECT);
|
|
1455
|
+
return new Response(null, { status: 302, headers: { location: target.href } });
|
|
1456
|
+
}
|
|
1457
|
+
deleteCookie2(event, cookie.name, cookie.options);
|
|
1458
|
+
const given = params.get("hamur_state") ?? "";
|
|
1459
|
+
const sealed = getCookie2(event, cookie.name);
|
|
1460
|
+
const flow = sealed === undefined ? undefined : await unsealFor3(sealed, { purpose: PURPOSE2 });
|
|
1461
|
+
if (!isFlow2(flow) || flow.route !== route || flow.provider !== PROVIDER4 || flow.redirectURI !== redirectURI || !given || !timingSafeEqual4(flow.state, given)) {
|
|
1462
|
+
throw createError6({ status: 400, message: "Invalid OAuth state" });
|
|
1463
|
+
}
|
|
1464
|
+
if (params.get("openid.mode") === "cancel" && options.onError)
|
|
1465
|
+
return options.onError(event, { error: "cancel" });
|
|
1466
|
+
const user = checkAssertion(params, returnTo(flow.redirectURI, flow.state));
|
|
1467
|
+
if (!await verified(event, params))
|
|
1468
|
+
throw failed();
|
|
1469
|
+
const value = await options.onSuccess(event, { user });
|
|
1470
|
+
if (value !== undefined)
|
|
1471
|
+
return value;
|
|
1472
|
+
return new Response(null, { status: 302, headers: { location: `${baseURL4.replace(/\/+$/, "")}${targets2.home}` } });
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
// packages/auth/src/server/oauth/providers/atlassian.ts
|
|
1476
|
+
var atlassian = {
|
|
1477
|
+
name: "atlassian",
|
|
1478
|
+
record: () => ({
|
|
1479
|
+
authorizationURL: "https://auth.atlassian.com/authorize",
|
|
1480
|
+
tokenURL: "https://auth.atlassian.com/oauth/token",
|
|
1481
|
+
userURL: "https://api.atlassian.com/me",
|
|
1482
|
+
scope: ["read:me"],
|
|
1483
|
+
tokenAuth: "client_secret_post",
|
|
1484
|
+
authorizationParams: { audience: "api.atlassian.com", prompt: "consent" },
|
|
1485
|
+
mapUser: (profile) => profile
|
|
1486
|
+
})
|
|
1487
|
+
};
|
|
1488
|
+
function oauthAtlassian(options) {
|
|
1489
|
+
return presetHandler(atlassian, options);
|
|
1490
|
+
}
|
|
1491
|
+
// packages/auth/src/server/oauth/providers/auth0.ts
|
|
1492
|
+
var auth0 = {
|
|
1493
|
+
name: "auth0",
|
|
1494
|
+
record: (config) => {
|
|
1495
|
+
const base = originOf(requireKey("auth0", config, "domain"));
|
|
1496
|
+
return {
|
|
1497
|
+
authorizationURL: `${base}/authorize`,
|
|
1498
|
+
tokenURL: `${base}/oauth/token`,
|
|
1499
|
+
userURL: `${base}/userinfo`,
|
|
1500
|
+
scope: ["openid", "profile", "email"],
|
|
1501
|
+
tokenAuth: "client_secret_post",
|
|
1502
|
+
mapUser: (profile) => profile
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
};
|
|
1506
|
+
function oauthAuth0(options) {
|
|
1507
|
+
return presetHandler(auth0, options);
|
|
1508
|
+
}
|
|
1509
|
+
// packages/auth/src/server/oauth/providers/authentik.ts
|
|
1510
|
+
var authentik = {
|
|
1511
|
+
name: "authentik",
|
|
1512
|
+
record: (config) => {
|
|
1513
|
+
const base = originOf(requireKey("authentik", config, "domain"));
|
|
1514
|
+
return {
|
|
1515
|
+
authorizationURL: `${base}/application/o/authorize/`,
|
|
1516
|
+
tokenURL: `${base}/application/o/token/`,
|
|
1517
|
+
userURL: `${base}/application/o/userinfo/`,
|
|
1518
|
+
scope: ["openid", "profile", "email"],
|
|
1519
|
+
tokenAuth: "client_secret_post",
|
|
1520
|
+
mapUser: (profile) => profile
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
};
|
|
1524
|
+
function oauthAuthentik(options) {
|
|
1525
|
+
return presetHandler(authentik, options);
|
|
1526
|
+
}
|
|
1527
|
+
// packages/auth/src/server/oauth/providers/battledotnet.ts
|
|
1528
|
+
var battledotnet = {
|
|
1529
|
+
name: "battledotnet",
|
|
1530
|
+
record: () => ({
|
|
1531
|
+
authorizationURL: "https://oauth.battle.net/authorize",
|
|
1532
|
+
tokenURL: "https://oauth.battle.net/token",
|
|
1533
|
+
userURL: "https://oauth.battle.net/userinfo",
|
|
1534
|
+
scope: ["openid"],
|
|
1535
|
+
tokenAuth: "client_secret_basic",
|
|
1536
|
+
mapUser: (profile) => profile
|
|
1537
|
+
})
|
|
1538
|
+
};
|
|
1539
|
+
function oauthBattleDotNet(options) {
|
|
1540
|
+
return presetHandler(battledotnet, options);
|
|
1541
|
+
}
|
|
1542
|
+
// packages/auth/src/server/oauth/providers/box.ts
|
|
1543
|
+
var box = {
|
|
1544
|
+
name: "box",
|
|
1545
|
+
record: () => ({
|
|
1546
|
+
authorizationURL: "https://account.box.com/api/oauth2/authorize",
|
|
1547
|
+
tokenURL: "https://api.box.com/oauth2/token",
|
|
1548
|
+
userURL: "https://api.box.com/2.0/users/me",
|
|
1549
|
+
scope: [],
|
|
1550
|
+
tokenAuth: "client_secret_post",
|
|
1551
|
+
mapUser: (profile) => profile
|
|
1552
|
+
})
|
|
1553
|
+
};
|
|
1554
|
+
function oauthBox(options) {
|
|
1555
|
+
return presetHandler(box, options);
|
|
1556
|
+
}
|
|
1557
|
+
// packages/auth/src/server/oauth/providers/dropbox.ts
|
|
1558
|
+
var dropbox = {
|
|
1559
|
+
name: "dropbox",
|
|
1560
|
+
record: () => ({
|
|
1561
|
+
authorizationURL: "https://www.dropbox.com/oauth2/authorize",
|
|
1562
|
+
tokenURL: "https://api.dropboxapi.com/oauth2/token",
|
|
1563
|
+
scope: ["account_info.read"],
|
|
1564
|
+
tokenAuth: "client_secret_post",
|
|
1565
|
+
profile: ({ event, tokens }) => providerJSON(event, "https://api.dropboxapi.com/2/users/get_current_account", { method: "POST", headers: { authorization: `Bearer ${tokens.access_token}`, accept: "application/json" } }, "user request"),
|
|
1566
|
+
mapUser: (profile) => profile
|
|
1567
|
+
})
|
|
1568
|
+
};
|
|
1569
|
+
function oauthDropbox(options) {
|
|
1570
|
+
return presetHandler(dropbox, options);
|
|
1571
|
+
}
|
|
1572
|
+
// packages/auth/src/server/oauth/providers/facebook.ts
|
|
1573
|
+
var facebook = {
|
|
1574
|
+
name: "facebook",
|
|
1575
|
+
record: () => ({
|
|
1576
|
+
authorizationURL: "https://www.facebook.com/dialog/oauth",
|
|
1577
|
+
tokenURL: "https://graph.facebook.com/oauth/access_token",
|
|
1578
|
+
userURL: "https://graph.facebook.com/me?fields=id,name,email,picture",
|
|
1579
|
+
scope: ["public_profile", "email"],
|
|
1580
|
+
tokenAuth: "client_secret_post",
|
|
1581
|
+
mapUser: (profile) => profile
|
|
1582
|
+
})
|
|
1583
|
+
};
|
|
1584
|
+
function oauthFacebook(options) {
|
|
1585
|
+
return presetHandler(facebook, options);
|
|
1586
|
+
}
|
|
1587
|
+
// packages/auth/src/server/oauth/providers/gitea.ts
|
|
1588
|
+
var gitea = {
|
|
1589
|
+
name: "gitea",
|
|
1590
|
+
record: ({ baseURL = "https://gitea.com" }) => {
|
|
1591
|
+
const base = originOf(baseURL);
|
|
1592
|
+
return {
|
|
1593
|
+
authorizationURL: `${base}/login/oauth/authorize`,
|
|
1594
|
+
tokenURL: `${base}/login/oauth/access_token`,
|
|
1595
|
+
userURL: `${base}/api/v1/user`,
|
|
1596
|
+
scope: ["read:user"],
|
|
1597
|
+
tokenAuth: "client_secret_post",
|
|
1598
|
+
mapUser: (profile) => profile
|
|
1599
|
+
};
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
function oauthGitea(options) {
|
|
1603
|
+
return presetHandler(gitea, options);
|
|
1604
|
+
}
|
|
1605
|
+
// packages/auth/src/server/oauth/providers/heroku.ts
|
|
1606
|
+
var heroku = {
|
|
1607
|
+
name: "heroku",
|
|
1608
|
+
record: () => ({
|
|
1609
|
+
authorizationURL: "https://id.heroku.com/oauth/authorize",
|
|
1610
|
+
tokenURL: "https://id.heroku.com/oauth/token",
|
|
1611
|
+
scope: ["identity"],
|
|
1612
|
+
tokenAuth: "client_secret_post",
|
|
1613
|
+
profile: ({ event, tokens }) => providerJSON(event, "https://api.heroku.com/account", {
|
|
1614
|
+
headers: { authorization: `Bearer ${tokens.access_token}`, accept: "application/vnd.heroku+json; version=3" }
|
|
1615
|
+
}, "user request"),
|
|
1616
|
+
mapUser: (profile) => profile
|
|
1617
|
+
})
|
|
1618
|
+
};
|
|
1619
|
+
function oauthHeroku(options) {
|
|
1620
|
+
return presetHandler(heroku, options);
|
|
1621
|
+
}
|
|
1622
|
+
// packages/auth/src/server/oauth/providers/keycloak.ts
|
|
1623
|
+
var keycloak = {
|
|
1624
|
+
name: "keycloak",
|
|
1625
|
+
record: (config) => {
|
|
1626
|
+
const base = `${originOf(requireKey("keycloak", config, "serverURL"))}/realms/${encodeURIComponent(requireKey("keycloak", config, "realm"))}/protocol/openid-connect`;
|
|
1627
|
+
return {
|
|
1628
|
+
authorizationURL: `${base}/auth`,
|
|
1629
|
+
tokenURL: `${base}/token`,
|
|
1630
|
+
userURL: `${base}/userinfo`,
|
|
1631
|
+
scope: ["openid"],
|
|
1632
|
+
tokenAuth: "client_secret_basic",
|
|
1633
|
+
mapUser: (profile) => profile
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
};
|
|
1637
|
+
function oauthKeycloak(options) {
|
|
1638
|
+
return presetHandler(keycloak, options);
|
|
1639
|
+
}
|
|
1640
|
+
// packages/auth/src/server/oauth/providers/kick.ts
|
|
1641
|
+
var kick = {
|
|
1642
|
+
name: "kick",
|
|
1643
|
+
record: () => ({
|
|
1644
|
+
authorizationURL: "https://id.kick.com/oauth/authorize",
|
|
1645
|
+
tokenURL: "https://id.kick.com/oauth/token",
|
|
1646
|
+
scope: ["user:read"],
|
|
1647
|
+
tokenAuth: "client_secret_post",
|
|
1648
|
+
profile: ({ event, tokens }) => providerJSON(event, "https://api.kick.com/public/v1/users", { headers: { authorization: `Bearer ${tokens.access_token}`, accept: "application/json" } }, "user request"),
|
|
1649
|
+
mapUser: (profile) => userOf(profile.data?.[0])
|
|
1650
|
+
})
|
|
1651
|
+
};
|
|
1652
|
+
function oauthKick(options) {
|
|
1653
|
+
return presetHandler(kick, options);
|
|
1654
|
+
}
|
|
1655
|
+
// packages/auth/src/server/oauth/providers/line.ts
|
|
1656
|
+
var line = {
|
|
1657
|
+
name: "line",
|
|
1658
|
+
record: () => ({
|
|
1659
|
+
authorizationURL: "https://access.line.me/oauth2/v2.1/authorize",
|
|
1660
|
+
tokenURL: "https://api.line.me/oauth2/v2.1/token",
|
|
1661
|
+
userURL: "https://api.line.me/v2/profile",
|
|
1662
|
+
scope: ["openid", "profile"],
|
|
1663
|
+
tokenAuth: "client_secret_post",
|
|
1664
|
+
mapUser: (profile) => profile
|
|
1665
|
+
})
|
|
1666
|
+
};
|
|
1667
|
+
function oauthLine(options) {
|
|
1668
|
+
return presetHandler(line, options);
|
|
1669
|
+
}
|
|
1670
|
+
// packages/auth/src/server/oauth/providers/linear.ts
|
|
1671
|
+
var linear = {
|
|
1672
|
+
name: "linear",
|
|
1673
|
+
record: () => ({
|
|
1674
|
+
authorizationURL: "https://linear.app/oauth/authorize",
|
|
1675
|
+
tokenURL: "https://api.linear.app/oauth/token",
|
|
1676
|
+
scope: ["read"],
|
|
1677
|
+
tokenAuth: "client_secret_post",
|
|
1678
|
+
profile: ({ event, tokens }) => providerJSON(event, "https://api.linear.app/graphql", {
|
|
1679
|
+
method: "POST",
|
|
1680
|
+
headers: {
|
|
1681
|
+
authorization: `Bearer ${tokens.access_token}`,
|
|
1682
|
+
accept: "application/json",
|
|
1683
|
+
"content-type": "application/json"
|
|
1684
|
+
},
|
|
1685
|
+
body: JSON.stringify({ query: "{ viewer { id name displayName email avatarUrl } }" })
|
|
1686
|
+
}, "user request"),
|
|
1687
|
+
mapUser: (profile) => userOf(profile.data?.viewer)
|
|
1688
|
+
})
|
|
1689
|
+
};
|
|
1690
|
+
function oauthLinear(options) {
|
|
1691
|
+
return presetHandler(linear, options);
|
|
1692
|
+
}
|
|
1693
|
+
// packages/auth/src/server/oauth/providers/linkedin.ts
|
|
1694
|
+
var linkedin = {
|
|
1695
|
+
name: "linkedin",
|
|
1696
|
+
record: () => ({
|
|
1697
|
+
authorizationURL: "https://www.linkedin.com/oauth/v2/authorization",
|
|
1698
|
+
tokenURL: "https://www.linkedin.com/oauth/v2/accessToken",
|
|
1699
|
+
userURL: "https://api.linkedin.com/v2/userinfo",
|
|
1700
|
+
scope: ["openid", "profile", "email"],
|
|
1701
|
+
tokenAuth: "client_secret_post",
|
|
1702
|
+
pkce: false,
|
|
1703
|
+
mapUser: (profile) => profile
|
|
1704
|
+
})
|
|
1705
|
+
};
|
|
1706
|
+
function oauthLinkedIn(options) {
|
|
1707
|
+
return presetHandler(linkedin, options);
|
|
1708
|
+
}
|
|
1709
|
+
// packages/auth/src/server/oauth/providers/mastodon.ts
|
|
1710
|
+
var mastodon = {
|
|
1711
|
+
name: "mastodon",
|
|
1712
|
+
record: ({ baseURL = "https://mastodon.social" }) => {
|
|
1713
|
+
const base = originOf(baseURL);
|
|
1714
|
+
return {
|
|
1715
|
+
authorizationURL: `${base}/oauth/authorize`,
|
|
1716
|
+
tokenURL: `${base}/oauth/token`,
|
|
1717
|
+
userURL: `${base}/api/v1/accounts/verify_credentials`,
|
|
1718
|
+
scope: ["read:accounts"],
|
|
1719
|
+
tokenAuth: "client_secret_post",
|
|
1720
|
+
mapUser: (profile) => profile
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
};
|
|
1724
|
+
function oauthMastodon(options) {
|
|
1725
|
+
return presetHandler(mastodon, options);
|
|
1726
|
+
}
|
|
1727
|
+
// packages/auth/src/server/oauth/providers/okta.ts
|
|
1728
|
+
var okta = {
|
|
1729
|
+
name: "okta",
|
|
1730
|
+
record: (config) => {
|
|
1731
|
+
const base = originOf(requireKey("okta", config, "domain"));
|
|
1732
|
+
return {
|
|
1733
|
+
authorizationURL: `${base}/oauth2/v1/authorize`,
|
|
1734
|
+
tokenURL: `${base}/oauth2/v1/token`,
|
|
1735
|
+
userURL: `${base}/oauth2/v1/userinfo`,
|
|
1736
|
+
scope: ["openid", "profile", "email"],
|
|
1737
|
+
tokenAuth: "client_secret_basic",
|
|
1738
|
+
mapUser: (profile) => profile
|
|
1739
|
+
};
|
|
1740
|
+
}
|
|
1741
|
+
};
|
|
1742
|
+
function oauthOkta(options) {
|
|
1743
|
+
return presetHandler(okta, options);
|
|
1744
|
+
}
|
|
1745
|
+
// packages/auth/src/server/oauth/providers/ory.ts
|
|
1746
|
+
var ory = {
|
|
1747
|
+
name: "ory",
|
|
1748
|
+
record: (config) => {
|
|
1749
|
+
const base = originOf(requireKey("ory", config, "domain"));
|
|
1750
|
+
return {
|
|
1751
|
+
authorizationURL: `${base}/oauth2/auth`,
|
|
1752
|
+
tokenURL: `${base}/oauth2/token`,
|
|
1753
|
+
userURL: `${base}/userinfo`,
|
|
1754
|
+
scope: ["openid", "email"],
|
|
1755
|
+
tokenAuth: "client_secret_basic",
|
|
1756
|
+
mapUser: (profile) => profile
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
};
|
|
1760
|
+
function oauthOry(options) {
|
|
1761
|
+
return presetHandler(ory, options);
|
|
1762
|
+
}
|
|
1763
|
+
// packages/auth/src/server/oauth/providers/osu.ts
|
|
1764
|
+
var osu = {
|
|
1765
|
+
name: "osu",
|
|
1766
|
+
record: () => ({
|
|
1767
|
+
authorizationURL: "https://osu.ppy.sh/oauth/authorize",
|
|
1768
|
+
tokenURL: "https://osu.ppy.sh/oauth/token",
|
|
1769
|
+
userURL: "https://osu.ppy.sh/api/v2/me",
|
|
1770
|
+
scope: ["identify"],
|
|
1771
|
+
tokenAuth: "client_secret_post",
|
|
1772
|
+
mapUser: (profile) => profile
|
|
1773
|
+
})
|
|
1774
|
+
};
|
|
1775
|
+
function oauthOsu(options) {
|
|
1776
|
+
return presetHandler(osu, options);
|
|
1777
|
+
}
|
|
1778
|
+
// packages/auth/src/server/oauth/providers/paypal.ts
|
|
1779
|
+
var paypal = {
|
|
1780
|
+
name: "paypal",
|
|
1781
|
+
record: () => ({
|
|
1782
|
+
authorizationURL: "https://www.paypal.com/signin/authorize",
|
|
1783
|
+
tokenURL: "https://api-m.paypal.com/v1/oauth2/token",
|
|
1784
|
+
userURL: "https://api-m.paypal.com/v1/identity/openidconnect/userinfo?schema=openid",
|
|
1785
|
+
scope: ["openid", "profile", "email"],
|
|
1786
|
+
tokenAuth: "client_secret_basic",
|
|
1787
|
+
mapUser: (profile) => profile
|
|
1788
|
+
})
|
|
1789
|
+
};
|
|
1790
|
+
function oauthPayPal(options) {
|
|
1791
|
+
return presetHandler(paypal, options);
|
|
1792
|
+
}
|
|
1793
|
+
// packages/auth/src/server/oauth/providers/polar.ts
|
|
1794
|
+
var polar = {
|
|
1795
|
+
name: "polar",
|
|
1796
|
+
record: () => ({
|
|
1797
|
+
authorizationURL: "https://polar.sh/oauth2/authorize",
|
|
1798
|
+
tokenURL: "https://api.polar.sh/v1/oauth2/token",
|
|
1799
|
+
userURL: "https://api.polar.sh/v1/oauth2/userinfo",
|
|
1800
|
+
scope: ["openid", "email"],
|
|
1801
|
+
tokenAuth: "client_secret_post",
|
|
1802
|
+
mapUser: (profile) => profile
|
|
1803
|
+
})
|
|
1804
|
+
};
|
|
1805
|
+
function oauthPolar(options) {
|
|
1806
|
+
return presetHandler(polar, options);
|
|
1807
|
+
}
|
|
1808
|
+
// packages/auth/src/server/oauth/providers/riotgames.ts
|
|
1809
|
+
var riotgames = {
|
|
1810
|
+
name: "riotgames",
|
|
1811
|
+
record: () => ({
|
|
1812
|
+
authorizationURL: "https://auth.riotgames.com/authorize",
|
|
1813
|
+
tokenURL: "https://auth.riotgames.com/token",
|
|
1814
|
+
userURL: "https://americas.api.riotgames.com/riot/account/v1/accounts/me",
|
|
1815
|
+
scope: ["openid"],
|
|
1816
|
+
tokenAuth: "client_secret_basic",
|
|
1817
|
+
mapUser: (profile) => profile
|
|
1818
|
+
})
|
|
1819
|
+
};
|
|
1820
|
+
function oauthRiotGames(options) {
|
|
1821
|
+
return presetHandler(riotgames, options);
|
|
1822
|
+
}
|
|
1823
|
+
// packages/auth/src/server/oauth/providers/roblox.ts
|
|
1824
|
+
var roblox = {
|
|
1825
|
+
name: "roblox",
|
|
1826
|
+
record: () => ({
|
|
1827
|
+
authorizationURL: "https://apis.roblox.com/oauth/v1/authorize",
|
|
1828
|
+
tokenURL: "https://apis.roblox.com/oauth/v1/token",
|
|
1829
|
+
userURL: "https://apis.roblox.com/oauth/v1/userinfo",
|
|
1830
|
+
scope: ["openid", "profile"],
|
|
1831
|
+
tokenAuth: "client_secret_post",
|
|
1832
|
+
mapUser: (profile) => profile
|
|
1833
|
+
})
|
|
1834
|
+
};
|
|
1835
|
+
function oauthRoblox(options) {
|
|
1836
|
+
return presetHandler(roblox, options);
|
|
1837
|
+
}
|
|
1838
|
+
// packages/auth/src/server/oauth/providers/salesforce.ts
|
|
1839
|
+
var salesforce = {
|
|
1840
|
+
name: "salesforce",
|
|
1841
|
+
record: ({ baseURL = "https://login.salesforce.com" }) => {
|
|
1842
|
+
const base = originOf(baseURL);
|
|
1843
|
+
return {
|
|
1844
|
+
authorizationURL: `${base}/services/oauth2/authorize`,
|
|
1845
|
+
tokenURL: `${base}/services/oauth2/token`,
|
|
1846
|
+
userURL: `${base}/services/oauth2/userinfo`,
|
|
1847
|
+
scope: ["openid", "profile", "email"],
|
|
1848
|
+
tokenAuth: "client_secret_post",
|
|
1849
|
+
mapUser: (profile) => profile
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
};
|
|
1853
|
+
function oauthSalesforce(options) {
|
|
1854
|
+
return presetHandler(salesforce, options);
|
|
1855
|
+
}
|
|
1856
|
+
// packages/auth/src/server/oauth/providers/seznam.ts
|
|
1857
|
+
var seznam = {
|
|
1858
|
+
name: "seznam",
|
|
1859
|
+
record: () => ({
|
|
1860
|
+
authorizationURL: "https://login.szn.cz/api/v1/oauth/auth",
|
|
1861
|
+
tokenURL: "https://login.szn.cz/api/v1/oauth/token",
|
|
1862
|
+
userURL: "https://login.szn.cz/api/v1/user",
|
|
1863
|
+
scope: ["identity"],
|
|
1864
|
+
tokenAuth: "client_secret_post",
|
|
1865
|
+
mapUser: (profile) => profile
|
|
1866
|
+
})
|
|
1867
|
+
};
|
|
1868
|
+
function oauthSeznam(options) {
|
|
1869
|
+
return presetHandler(seznam, options);
|
|
1870
|
+
}
|
|
1871
|
+
// packages/auth/src/server/oauth/providers/slack.ts
|
|
1872
|
+
var slack = {
|
|
1873
|
+
name: "slack",
|
|
1874
|
+
record: () => ({
|
|
1875
|
+
authorizationURL: "https://slack.com/openid/connect/authorize",
|
|
1876
|
+
tokenURL: "https://slack.com/api/openid.connect.token",
|
|
1877
|
+
scope: ["openid", "email", "profile"],
|
|
1878
|
+
tokenAuth: "client_secret_post",
|
|
1879
|
+
profile: ({ event, tokens }) => providerJSON(event, "https://slack.com/api/openid.connect.userInfo", { method: "POST", headers: { authorization: `Bearer ${tokens.access_token}`, accept: "application/json" } }, "user request"),
|
|
1880
|
+
mapUser: (profile) => userOf(profile.ok === true ? profile : undefined)
|
|
1881
|
+
})
|
|
1882
|
+
};
|
|
1883
|
+
function oauthSlack(options) {
|
|
1884
|
+
return presetHandler(slack, options);
|
|
1885
|
+
}
|
|
1886
|
+
// packages/auth/src/server/oauth/providers/spotify.ts
|
|
1887
|
+
var spotify = {
|
|
1888
|
+
name: "spotify",
|
|
1889
|
+
record: () => ({
|
|
1890
|
+
authorizationURL: "https://accounts.spotify.com/authorize",
|
|
1891
|
+
tokenURL: "https://accounts.spotify.com/api/token",
|
|
1892
|
+
userURL: "https://api.spotify.com/v1/me",
|
|
1893
|
+
scope: ["user-read-email"],
|
|
1894
|
+
tokenAuth: "client_secret_basic",
|
|
1895
|
+
mapUser: (profile) => profile
|
|
1896
|
+
})
|
|
1897
|
+
};
|
|
1898
|
+
function oauthSpotify(options) {
|
|
1899
|
+
return presetHandler(spotify, options);
|
|
1900
|
+
}
|
|
1901
|
+
// packages/auth/src/server/oauth/providers/twitch.ts
|
|
1902
|
+
var twitch = {
|
|
1903
|
+
name: "twitch",
|
|
1904
|
+
record: () => ({
|
|
1905
|
+
authorizationURL: "https://id.twitch.tv/oauth2/authorize",
|
|
1906
|
+
tokenURL: "https://id.twitch.tv/oauth2/token",
|
|
1907
|
+
scope: ["user:read:email"],
|
|
1908
|
+
tokenAuth: "client_secret_post",
|
|
1909
|
+
profile: ({ event, tokens, clientId }) => providerJSON(event, "https://api.twitch.tv/helix/users", {
|
|
1910
|
+
headers: {
|
|
1911
|
+
authorization: `Bearer ${tokens.access_token}`,
|
|
1912
|
+
"client-id": clientId,
|
|
1913
|
+
accept: "application/json"
|
|
1914
|
+
}
|
|
1915
|
+
}, "user request"),
|
|
1916
|
+
mapUser: (profile) => userOf(profile.data?.[0])
|
|
1917
|
+
})
|
|
1918
|
+
};
|
|
1919
|
+
function oauthTwitch(options) {
|
|
1920
|
+
return presetHandler(twitch, options);
|
|
1921
|
+
}
|
|
1922
|
+
// packages/auth/src/server/oauth/providers/x.ts
|
|
1923
|
+
var x = {
|
|
1924
|
+
name: "x",
|
|
1925
|
+
record: () => ({
|
|
1926
|
+
authorizationURL: "https://x.com/i/oauth2/authorize",
|
|
1927
|
+
tokenURL: "https://api.x.com/2/oauth2/token",
|
|
1928
|
+
userURL: "https://api.x.com/2/users/me?user.fields=profile_image_url,verified",
|
|
1929
|
+
scope: ["users.read", "tweet.read"],
|
|
1930
|
+
tokenAuth: "client_secret_basic",
|
|
1931
|
+
mapUser: (profile) => userOf(profile.data)
|
|
1932
|
+
})
|
|
1933
|
+
};
|
|
1934
|
+
function oauthX(options) {
|
|
1935
|
+
return presetHandler(x, options);
|
|
1936
|
+
}
|
|
1937
|
+
// packages/auth/src/server/oauth/providers/yandex.ts
|
|
1938
|
+
var yandex = {
|
|
1939
|
+
name: "yandex",
|
|
1940
|
+
record: () => ({
|
|
1941
|
+
authorizationURL: "https://oauth.yandex.com/authorize",
|
|
1942
|
+
tokenURL: "https://oauth.yandex.com/token",
|
|
1943
|
+
scope: ["login:info", "login:email"],
|
|
1944
|
+
tokenAuth: "client_secret_post",
|
|
1945
|
+
profile: ({ event, tokens }) => providerJSON(event, "https://login.yandex.ru/info?format=json", { headers: { authorization: `OAuth ${tokens.access_token}`, accept: "application/json" } }, "user request"),
|
|
1946
|
+
mapUser: (profile) => profile
|
|
1947
|
+
})
|
|
1948
|
+
};
|
|
1949
|
+
function oauthYandex(options) {
|
|
1950
|
+
return presetHandler(yandex, options);
|
|
1951
|
+
}
|
|
1952
|
+
// packages/auth/src/server/oauth/providers/zendesk.ts
|
|
1953
|
+
var zendesk = {
|
|
1954
|
+
name: "zendesk",
|
|
1955
|
+
record: (config) => {
|
|
1956
|
+
const base = `https://${encodeURIComponent(requireKey("zendesk", config, "subdomain"))}.zendesk.com`;
|
|
1957
|
+
return {
|
|
1958
|
+
authorizationURL: `${base}/oauth/authorizations/new`,
|
|
1959
|
+
tokenURL: `${base}/oauth/tokens`,
|
|
1960
|
+
userURL: `${base}/api/v2/users/me`,
|
|
1961
|
+
scope: ["read"],
|
|
1962
|
+
tokenAuth: "client_secret_post",
|
|
1963
|
+
mapUser: (profile) => userOf(profile.user)
|
|
1964
|
+
};
|
|
1965
|
+
}
|
|
1966
|
+
};
|
|
1967
|
+
function oauthZendesk(options) {
|
|
1968
|
+
return presetHandler(zendesk, options);
|
|
1969
|
+
}
|
|
1970
|
+
// packages/auth/src/server/oauth/providers/zitadel.ts
|
|
1971
|
+
var zitadel = {
|
|
1972
|
+
name: "zitadel",
|
|
1973
|
+
record: (config) => {
|
|
1974
|
+
const base = originOf(requireKey("zitadel", config, "domain"));
|
|
1975
|
+
return {
|
|
1976
|
+
authorizationURL: `${base}/oauth/v2/authorize`,
|
|
1977
|
+
tokenURL: `${base}/oauth/v2/token`,
|
|
1978
|
+
userURL: `${base}/oidc/v1/userinfo`,
|
|
1979
|
+
scope: ["openid", "profile", "email"],
|
|
1980
|
+
tokenAuth: "client_secret_basic",
|
|
1981
|
+
mapUser: (profile) => profile
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
};
|
|
1985
|
+
function oauthZitadel(options) {
|
|
1986
|
+
return presetHandler(zitadel, options);
|
|
1987
|
+
}
|
|
1988
|
+
// packages/auth/src/server/oauth/providers/azureb2c.ts
|
|
1989
|
+
import { createError as createError7 } from "hamur/server";
|
|
1990
|
+
var azureb2c = {
|
|
1991
|
+
name: "azureb2c",
|
|
1992
|
+
record: (config) => {
|
|
1993
|
+
const tenant = encodeURIComponent(requireKey("azureb2c", config, "tenant"));
|
|
1994
|
+
const host = `https://${tenant}.b2clogin.com`;
|
|
1995
|
+
const base = `${host}/${tenant}.onmicrosoft.com/${encodeURIComponent(requireKey("azureb2c", config, "policy"))}`;
|
|
1996
|
+
return {
|
|
1997
|
+
authorizationURL: `${base}/oauth2/v2.0/authorize`,
|
|
1998
|
+
tokenURL: `${base}/oauth2/v2.0/token`,
|
|
1999
|
+
scope: ["openid", "offline_access"],
|
|
2000
|
+
clientIdScope: true,
|
|
2001
|
+
tokenAuth: "client_secret_post",
|
|
2002
|
+
async profile({ tokens, clientId }) {
|
|
2003
|
+
const claims = await idTokenClaims(tokens.id_token, `${base}/discovery/v2.0/keys`, { audience: clientId });
|
|
2004
|
+
if (typeof claims.iss !== "string" || !claims.iss.startsWith(`${host}/`))
|
|
2005
|
+
throw createError7({ status: 401, message: "Invalid ID token: iss" });
|
|
2006
|
+
return claims;
|
|
2007
|
+
},
|
|
2008
|
+
mapUser: (profile) => profile
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
};
|
|
2012
|
+
function oauthAzureB2C(options) {
|
|
2013
|
+
return presetHandler(azureb2c, options);
|
|
2014
|
+
}
|
|
2015
|
+
// packages/auth/src/server/oauth/providers/cloudflare.ts
|
|
2016
|
+
var cloudflare = {
|
|
2017
|
+
name: "cloudflare",
|
|
2018
|
+
record: (config) => {
|
|
2019
|
+
if (typeof config.clientId !== "string" || config.clientId === "") {
|
|
2020
|
+
throw new TypeError("@hamur/auth: oauthCloudflare needs auth.oauth.cloudflare.clientId as text: Cloudflare Access puts it in its URLs");
|
|
2021
|
+
}
|
|
2022
|
+
const base = `https://${encodeURIComponent(requireKey("cloudflare", config, "teamName"))}.cloudflareaccess.com/cdn-cgi/access/sso/oidc/${encodeURIComponent(config.clientId)}`;
|
|
2023
|
+
return {
|
|
2024
|
+
authorizationURL: `${base}/authorization`,
|
|
2025
|
+
tokenURL: `${base}/token`,
|
|
2026
|
+
userURL: `${base}/userinfo`,
|
|
2027
|
+
scope: ["openid", "email", "profile"],
|
|
2028
|
+
tokenAuth: "client_secret_post",
|
|
2029
|
+
mapUser: (profile) => profile
|
|
2030
|
+
};
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
function oauthCloudflare(options) {
|
|
2034
|
+
return presetHandler(cloudflare, options);
|
|
2035
|
+
}
|
|
2036
|
+
// packages/auth/src/server/oauth/providers/cognito.ts
|
|
2037
|
+
var cognito = {
|
|
2038
|
+
name: "cognito",
|
|
2039
|
+
record: (config) => {
|
|
2040
|
+
const base = originOf(requireKey("cognito", config, "domain"));
|
|
2041
|
+
return {
|
|
2042
|
+
authorizationURL: `${base}/oauth2/authorize`,
|
|
2043
|
+
tokenURL: `${base}/oauth2/token`,
|
|
2044
|
+
userURL: `${base}/oauth2/userInfo`,
|
|
2045
|
+
scope: ["openid", "email", "profile"],
|
|
2046
|
+
tokenAuth: "client_secret_basic",
|
|
2047
|
+
mapUser: (profile) => profile
|
|
2048
|
+
};
|
|
2049
|
+
}
|
|
2050
|
+
};
|
|
2051
|
+
function oauthCognito(options) {
|
|
2052
|
+
return presetHandler(cognito, options);
|
|
2053
|
+
}
|
|
2054
|
+
// packages/auth/src/server/oauth/providers/hubspot.ts
|
|
2055
|
+
var hubspot = {
|
|
2056
|
+
name: "hubspot",
|
|
2057
|
+
record: () => ({
|
|
2058
|
+
authorizationURL: "https://app.hubspot.com/oauth/authorize",
|
|
2059
|
+
tokenURL: "https://api.hubapi.com/oauth/v1/token",
|
|
2060
|
+
scope: ["oauth"],
|
|
2061
|
+
tokenAuth: "client_secret_post",
|
|
2062
|
+
pkce: false,
|
|
2063
|
+
profile: ({ event, tokens }) => providerJSON(event, `https://api.hubapi.com/oauth/v1/access-tokens/${encodeURIComponent(tokens.access_token)}`, { headers: { accept: "application/json" } }, "user request"),
|
|
2064
|
+
mapUser: (profile) => profile
|
|
2065
|
+
})
|
|
2066
|
+
};
|
|
2067
|
+
function oauthHubSpot(options) {
|
|
2068
|
+
return presetHandler(hubspot, options);
|
|
2069
|
+
}
|
|
2070
|
+
// packages/auth/src/server/oauth/providers/instagram.ts
|
|
2071
|
+
var unwrap = (answer) => Array.isArray(answer.data) ? answer.data[0] : answer;
|
|
2072
|
+
var instagram = {
|
|
2073
|
+
name: "instagram",
|
|
2074
|
+
record: () => ({
|
|
2075
|
+
authorizationURL: "https://www.instagram.com/oauth/authorize",
|
|
2076
|
+
tokenURL: "https://api.instagram.com/oauth/access_token",
|
|
2077
|
+
scope: ["instagram_business_basic"],
|
|
2078
|
+
tokenAuth: "client_secret_post",
|
|
2079
|
+
pkce: false,
|
|
2080
|
+
tokenRequest: async ({ event, url, headers, body }) => userOf(unwrap(await providerJSON(event, url, { method: "POST", headers, body }, "token request"))),
|
|
2081
|
+
profile: ({ event, tokens }) => {
|
|
2082
|
+
const target = new URL("https://graph.instagram.com/me");
|
|
2083
|
+
target.searchParams.set("fields", "user_id,username,name,account_type,profile_picture_url");
|
|
2084
|
+
target.searchParams.set("access_token", tokens.access_token);
|
|
2085
|
+
return providerJSON(event, target.href, { headers: { accept: "application/json" } }, "user request");
|
|
2086
|
+
},
|
|
2087
|
+
mapUser: (profile) => userOf(unwrap(profile))
|
|
2088
|
+
})
|
|
2089
|
+
};
|
|
2090
|
+
function oauthInstagram(options) {
|
|
2091
|
+
return presetHandler(instagram, options);
|
|
2092
|
+
}
|
|
2093
|
+
// packages/auth/src/server/oauth/providers/livechat.ts
|
|
2094
|
+
var livechat = {
|
|
2095
|
+
name: "livechat",
|
|
2096
|
+
record: () => ({
|
|
2097
|
+
authorizationURL: "https://accounts.livechat.com/",
|
|
2098
|
+
tokenURL: "https://accounts.livechat.com/v2/token",
|
|
2099
|
+
userURL: "https://accounts.livechat.com/v2/accounts/me",
|
|
2100
|
+
scope: [],
|
|
2101
|
+
tokenAuth: "client_secret_post",
|
|
2102
|
+
mapUser: (profile) => profile
|
|
2103
|
+
})
|
|
2104
|
+
};
|
|
2105
|
+
function oauthLiveChat(options) {
|
|
2106
|
+
return presetHandler(livechat, options);
|
|
2107
|
+
}
|
|
2108
|
+
// packages/auth/src/server/oauth/providers/shopifyCustomer.ts
|
|
2109
|
+
var QUERY = "{ customer { id firstName lastName displayName emailAddress { emailAddress } } }";
|
|
2110
|
+
var shopifyCustomer = {
|
|
2111
|
+
name: "shopifyCustomer",
|
|
2112
|
+
record: (config) => {
|
|
2113
|
+
const shop = encodeURIComponent(requireKey("shopifyCustomer", config, "shopId"));
|
|
2114
|
+
return {
|
|
2115
|
+
authorizationURL: `https://shopify.com/authentication/${shop}/oauth/authorize`,
|
|
2116
|
+
tokenURL: `https://shopify.com/authentication/${shop}/oauth/token`,
|
|
2117
|
+
scope: ["openid", "email", "customer-account-api:full"],
|
|
2118
|
+
tokenAuth: "client_secret_basic",
|
|
2119
|
+
profile: ({ event, tokens }) => providerJSON(event, `https://shopify.com/${shop}/account/customer/api/2025-01/graphql`, {
|
|
2120
|
+
method: "POST",
|
|
2121
|
+
headers: {
|
|
2122
|
+
authorization: tokens.access_token,
|
|
2123
|
+
accept: "application/json",
|
|
2124
|
+
"content-type": "application/json"
|
|
2125
|
+
},
|
|
2126
|
+
body: JSON.stringify({ query: QUERY })
|
|
2127
|
+
}, "user request"),
|
|
2128
|
+
mapUser: (profile) => userOf(profile.data?.customer)
|
|
2129
|
+
};
|
|
2130
|
+
}
|
|
2131
|
+
};
|
|
2132
|
+
function oauthShopifyCustomer(options) {
|
|
2133
|
+
return presetHandler(shopifyCustomer, options);
|
|
2134
|
+
}
|
|
2135
|
+
// packages/auth/src/server/oauth/providers/strava.ts
|
|
2136
|
+
var strava = {
|
|
2137
|
+
name: "strava",
|
|
2138
|
+
record: () => ({
|
|
2139
|
+
authorizationURL: "https://www.strava.com/oauth/authorize",
|
|
2140
|
+
tokenURL: "https://www.strava.com/oauth/token",
|
|
2141
|
+
userURL: "https://www.strava.com/api/v3/athlete",
|
|
2142
|
+
scope: ["read"],
|
|
2143
|
+
scopeSeparator: ",",
|
|
2144
|
+
tokenAuth: "client_secret_post",
|
|
2145
|
+
mapUser: (profile) => profile
|
|
2146
|
+
})
|
|
2147
|
+
};
|
|
2148
|
+
function oauthStrava(options) {
|
|
2149
|
+
return presetHandler(strava, options);
|
|
2150
|
+
}
|
|
2151
|
+
// packages/auth/src/server/oauth/providers/tiktok.ts
|
|
2152
|
+
var tiktok = {
|
|
2153
|
+
name: "tiktok",
|
|
2154
|
+
record: () => ({
|
|
2155
|
+
authorizationURL: "https://www.tiktok.com/v2/auth/authorize/",
|
|
2156
|
+
tokenURL: "https://open.tiktokapis.com/v2/oauth/token/",
|
|
2157
|
+
userURL: "https://open.tiktokapis.com/v2/user/info/?fields=open_id,union_id,avatar_url,display_name",
|
|
2158
|
+
scope: ["user.info.basic"],
|
|
2159
|
+
scopeSeparator: ",",
|
|
2160
|
+
clientIdParam: "client_key",
|
|
2161
|
+
tokenAuth: "client_secret_post",
|
|
2162
|
+
pkce: false,
|
|
2163
|
+
mapUser: (profile) => userOf(profile.data?.user)
|
|
2164
|
+
})
|
|
2165
|
+
};
|
|
2166
|
+
function oauthTikTok(options) {
|
|
2167
|
+
return presetHandler(tiktok, options);
|
|
2168
|
+
}
|
|
2169
|
+
// packages/auth/src/server/oauth/providers/vk.ts
|
|
2170
|
+
var vk = {
|
|
2171
|
+
name: "vk",
|
|
2172
|
+
record: () => ({
|
|
2173
|
+
authorizationURL: "https://id.vk.com/authorize",
|
|
2174
|
+
tokenURL: "https://id.vk.com/oauth2/auth",
|
|
2175
|
+
scope: ["vkid.personal_info", "email"],
|
|
2176
|
+
tokenAuth: "none",
|
|
2177
|
+
tokenRequest: ({ event, url, headers, body, params }) => {
|
|
2178
|
+
body.set("device_id", params.get("device_id") ?? "");
|
|
2179
|
+
body.set("state", params.get("state") ?? "");
|
|
2180
|
+
return providerJSON(event, url, { method: "POST", headers, body }, "token request");
|
|
2181
|
+
},
|
|
2182
|
+
profile: ({ event, tokens, clientId }) => providerJSON(event, "https://id.vk.com/oauth2/user_info", {
|
|
2183
|
+
method: "POST",
|
|
2184
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
2185
|
+
body: new URLSearchParams({ client_id: clientId, access_token: tokens.access_token })
|
|
2186
|
+
}, "user request"),
|
|
2187
|
+
mapUser: (profile) => userOf(profile.user)
|
|
2188
|
+
})
|
|
2189
|
+
};
|
|
2190
|
+
function oauthVK(options) {
|
|
2191
|
+
return presetHandler(vk, options);
|
|
2192
|
+
}
|
|
2193
|
+
// packages/auth/src/server/oauth/providers/wechat.ts
|
|
2194
|
+
var wechat = {
|
|
2195
|
+
name: "wechat",
|
|
2196
|
+
record: () => ({
|
|
2197
|
+
authorizationURL: "https://open.weixin.qq.com/connect/qrconnect#wechat_redirect",
|
|
2198
|
+
tokenURL: "https://api.weixin.qq.com/sns/oauth2/access_token",
|
|
2199
|
+
scope: ["snsapi_login"],
|
|
2200
|
+
clientIdParam: "appid",
|
|
2201
|
+
tokenAuth: "client_secret_post",
|
|
2202
|
+
pkce: false,
|
|
2203
|
+
tokenRequest: ({ event, url, body }) => {
|
|
2204
|
+
const target = new URL(url);
|
|
2205
|
+
for (const [key, value] of [
|
|
2206
|
+
["appid", body.get("appid")],
|
|
2207
|
+
["secret", body.get("client_secret")],
|
|
2208
|
+
["code", body.get("code")],
|
|
2209
|
+
["grant_type", "authorization_code"]
|
|
2210
|
+
])
|
|
2211
|
+
target.searchParams.set(key, value ?? "");
|
|
2212
|
+
return providerJSON(event, target.href, { headers: { accept: "application/json" } }, "token request");
|
|
2213
|
+
},
|
|
2214
|
+
profile: ({ event, tokens }) => {
|
|
2215
|
+
const target = new URL("https://api.weixin.qq.com/sns/userinfo");
|
|
2216
|
+
target.searchParams.set("access_token", tokens.access_token);
|
|
2217
|
+
target.searchParams.set("openid", typeof tokens.openid === "string" ? tokens.openid : "");
|
|
2218
|
+
return providerJSON(event, target.href, { headers: { accept: "application/json" } }, "user request");
|
|
2219
|
+
},
|
|
2220
|
+
mapUser: (profile) => userOf(typeof profile.openid === "string" ? profile : undefined)
|
|
2221
|
+
})
|
|
2222
|
+
};
|
|
2223
|
+
function oauthWeChat(options) {
|
|
2224
|
+
return presetHandler(wechat, options);
|
|
2225
|
+
}
|
|
2226
|
+
// packages/auth/src/server/oauth/providers/workos.ts
|
|
2227
|
+
var workos = {
|
|
2228
|
+
name: "workos",
|
|
2229
|
+
record: () => ({
|
|
2230
|
+
authorizationURL: "https://api.workos.com/user_management/authorize",
|
|
2231
|
+
tokenURL: "https://api.workos.com/user_management/authenticate",
|
|
2232
|
+
scope: [],
|
|
2233
|
+
tokenAuth: "client_secret_post",
|
|
2234
|
+
authorizationParams: { provider: "authkit" },
|
|
2235
|
+
mapUser: (_profile, tokens) => userOf(tokens.user)
|
|
2236
|
+
})
|
|
2237
|
+
};
|
|
2238
|
+
function oauthWorkOS(options) {
|
|
2239
|
+
return presetHandler(workos, options);
|
|
2240
|
+
}
|
|
2241
|
+
// packages/auth/src/server/oauth/providers/xsuaa.ts
|
|
2242
|
+
var xsuaa = {
|
|
2243
|
+
name: "xsuaa",
|
|
2244
|
+
record: (config) => {
|
|
2245
|
+
const base = originOf(requireKey("xsuaa", config, "domain"));
|
|
2246
|
+
return {
|
|
2247
|
+
authorizationURL: `${base}/oauth/authorize`,
|
|
2248
|
+
tokenURL: `${base}/oauth/token`,
|
|
2249
|
+
userURL: `${base}/userinfo`,
|
|
2250
|
+
scope: ["openid"],
|
|
2251
|
+
tokenAuth: "client_secret_basic",
|
|
2252
|
+
mapUser: (profile) => profile
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
function oauthXsuaa(options) {
|
|
2257
|
+
return presetHandler(xsuaa, options);
|
|
2258
|
+
}
|
|
2259
|
+
// packages/auth/src/server/webauthn/handler.ts
|
|
2260
|
+
import { singleUse as singleUse3 } from "#hamur/auth/single-use";
|
|
2261
|
+
import { webauthn as config } from "#hamur/auth/webauthn";
|
|
2262
|
+
import {
|
|
2263
|
+
createError as createError8,
|
|
2264
|
+
deleteCookie as deleteCookie3,
|
|
2265
|
+
getCookie as getCookie3,
|
|
2266
|
+
getRequestURL as getRequestURL4,
|
|
2267
|
+
readBodyBytes,
|
|
2268
|
+
setCookie as setCookie3,
|
|
2269
|
+
useStorage as useStorage4
|
|
2270
|
+
} from "hamur/server";
|
|
2271
|
+
import {
|
|
2272
|
+
fromBase64Url as decodeBase64Url,
|
|
2273
|
+
listedRequestHost,
|
|
2274
|
+
sealFor as sealFor4,
|
|
2275
|
+
storageMountDriver as storageMountDriver3,
|
|
2276
|
+
timingSafeEqual as timingSafeEqual5,
|
|
2277
|
+
toBase64Url as toBase64Url5,
|
|
2278
|
+
unsealFor as unsealFor4
|
|
2279
|
+
} from "hamur/server/internal";
|
|
2280
|
+
|
|
2281
|
+
// packages/auth/src/server/webauthn/cbor.ts
|
|
2282
|
+
var MAX_CBOR_BYTES = 65536;
|
|
2283
|
+
var MAX_DEPTH = 16;
|
|
2284
|
+
var text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
2285
|
+
function half(bits) {
|
|
2286
|
+
const sign = bits & 32768 ? -1 : 1;
|
|
2287
|
+
const exponent = bits >> 10 & 31;
|
|
2288
|
+
const fraction = bits & 1023;
|
|
2289
|
+
if (exponent === 0)
|
|
2290
|
+
return sign * fraction * 2 ** -24;
|
|
2291
|
+
if (exponent === 31)
|
|
2292
|
+
return fraction ? NaN : sign * Infinity;
|
|
2293
|
+
return sign * (1 + fraction / 1024) * 2 ** (exponent - 15);
|
|
2294
|
+
}
|
|
2295
|
+
function decodeCBORItem(bytes, offset = 0) {
|
|
2296
|
+
if (bytes.length > MAX_CBOR_BYTES)
|
|
2297
|
+
throw new RangeError(`CBOR input is over ${MAX_CBOR_BYTES} bytes`);
|
|
2298
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
2299
|
+
let at = offset;
|
|
2300
|
+
const need = (count) => {
|
|
2301
|
+
if (at + count > bytes.length)
|
|
2302
|
+
throw new RangeError("CBOR input ends inside an item");
|
|
2303
|
+
};
|
|
2304
|
+
const argument = (info) => {
|
|
2305
|
+
if (info < 24)
|
|
2306
|
+
return info;
|
|
2307
|
+
if (info === 24) {
|
|
2308
|
+
need(1);
|
|
2309
|
+
return bytes[at++];
|
|
2310
|
+
}
|
|
2311
|
+
if (info === 25) {
|
|
2312
|
+
need(2);
|
|
2313
|
+
const value = view.getUint16(at);
|
|
2314
|
+
at += 2;
|
|
2315
|
+
return value;
|
|
2316
|
+
}
|
|
2317
|
+
if (info === 26) {
|
|
2318
|
+
need(4);
|
|
2319
|
+
const value = view.getUint32(at);
|
|
2320
|
+
at += 4;
|
|
2321
|
+
return value;
|
|
2322
|
+
}
|
|
2323
|
+
if (info === 27) {
|
|
2324
|
+
need(8);
|
|
2325
|
+
const value = view.getBigUint64(at);
|
|
2326
|
+
at += 8;
|
|
2327
|
+
return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value;
|
|
2328
|
+
}
|
|
2329
|
+
throw new TypeError(info === 31 ? "CBOR indefinite lengths are refused" : `CBOR additional information ${info} is reserved`);
|
|
2330
|
+
};
|
|
2331
|
+
const length = (info) => {
|
|
2332
|
+
const value = argument(info);
|
|
2333
|
+
if (typeof value === "bigint" || value > bytes.length - at)
|
|
2334
|
+
throw new RangeError("CBOR length runs past the input");
|
|
2335
|
+
return value;
|
|
2336
|
+
};
|
|
2337
|
+
const item = (depth) => {
|
|
2338
|
+
need(1);
|
|
2339
|
+
const head = bytes[at++];
|
|
2340
|
+
const major = head >> 5;
|
|
2341
|
+
const info = head & 31;
|
|
2342
|
+
switch (major) {
|
|
2343
|
+
case 0:
|
|
2344
|
+
return argument(info);
|
|
2345
|
+
case 1: {
|
|
2346
|
+
const value = argument(info);
|
|
2347
|
+
return typeof value === "number" && value < Number.MAX_SAFE_INTEGER ? -1 - value : -1n - BigInt(value);
|
|
2348
|
+
}
|
|
2349
|
+
case 2: {
|
|
2350
|
+
const size = length(info);
|
|
2351
|
+
return bytes.slice(at, at += size);
|
|
2352
|
+
}
|
|
2353
|
+
case 3: {
|
|
2354
|
+
const size = length(info);
|
|
2355
|
+
return text2.decode(bytes.subarray(at, at += size));
|
|
2356
|
+
}
|
|
2357
|
+
case 4: {
|
|
2358
|
+
if (depth >= MAX_DEPTH)
|
|
2359
|
+
throw new RangeError(`CBOR nests deeper than ${MAX_DEPTH}`);
|
|
2360
|
+
const size = length(info);
|
|
2361
|
+
const list = [];
|
|
2362
|
+
for (let i = 0;i < size; i++)
|
|
2363
|
+
list.push(item(depth + 1));
|
|
2364
|
+
return list;
|
|
2365
|
+
}
|
|
2366
|
+
case 5: {
|
|
2367
|
+
if (depth >= MAX_DEPTH)
|
|
2368
|
+
throw new RangeError(`CBOR nests deeper than ${MAX_DEPTH}`);
|
|
2369
|
+
const size = length(info);
|
|
2370
|
+
const map = new Map;
|
|
2371
|
+
for (let i = 0;i < size; i++) {
|
|
2372
|
+
const key = item(depth + 1);
|
|
2373
|
+
if (map.has(key))
|
|
2374
|
+
throw new TypeError("CBOR map repeats a key");
|
|
2375
|
+
map.set(key, item(depth + 1));
|
|
2376
|
+
}
|
|
2377
|
+
return map;
|
|
2378
|
+
}
|
|
2379
|
+
case 6:
|
|
2380
|
+
throw new TypeError("CBOR tags are refused");
|
|
2381
|
+
default: {
|
|
2382
|
+
if (info === 20)
|
|
2383
|
+
return false;
|
|
2384
|
+
if (info === 21)
|
|
2385
|
+
return true;
|
|
2386
|
+
if (info === 22)
|
|
2387
|
+
return null;
|
|
2388
|
+
if (info === 23)
|
|
2389
|
+
return;
|
|
2390
|
+
if (info < 20)
|
|
2391
|
+
return { simple: info };
|
|
2392
|
+
if (info === 24) {
|
|
2393
|
+
need(1);
|
|
2394
|
+
const value = bytes[at++];
|
|
2395
|
+
if (value < 32)
|
|
2396
|
+
throw new TypeError("CBOR simple value in two bytes must be 32 or more");
|
|
2397
|
+
return { simple: value };
|
|
2398
|
+
}
|
|
2399
|
+
if (info === 25) {
|
|
2400
|
+
need(2);
|
|
2401
|
+
const value = half(view.getUint16(at));
|
|
2402
|
+
at += 2;
|
|
2403
|
+
return value;
|
|
2404
|
+
}
|
|
2405
|
+
if (info === 26) {
|
|
2406
|
+
need(4);
|
|
2407
|
+
const value = view.getFloat32(at);
|
|
2408
|
+
at += 4;
|
|
2409
|
+
return value;
|
|
2410
|
+
}
|
|
2411
|
+
if (info === 27) {
|
|
2412
|
+
need(8);
|
|
2413
|
+
const value = view.getFloat64(at);
|
|
2414
|
+
at += 8;
|
|
2415
|
+
return value;
|
|
2416
|
+
}
|
|
2417
|
+
throw new TypeError(info === 31 ? "CBOR break outside an indefinite item" : `CBOR additional information ${info} is reserved`);
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
};
|
|
2421
|
+
const value = item(0);
|
|
2422
|
+
return { value, end: at };
|
|
2423
|
+
}
|
|
2424
|
+
function decodeCBOR(bytes) {
|
|
2425
|
+
const { value, end } = decodeCBORItem(bytes);
|
|
2426
|
+
if (end !== bytes.length)
|
|
2427
|
+
throw new TypeError("CBOR input has bytes after its item");
|
|
2428
|
+
return value;
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
// packages/auth/src/server/webauthn/cose.ts
|
|
2432
|
+
import { toBase64Url as toBase64Url4 } from "hamur/server/internal";
|
|
2433
|
+
var ALGORITHMS = [-8, -19, -7, -257];
|
|
2434
|
+
var MIN_RSA_BYTES = 256;
|
|
2435
|
+
var bytesOf = (value, size) => value instanceof Uint8Array && (size === undefined || value.length === size) ? value : undefined;
|
|
2436
|
+
function coseToJWK(key) {
|
|
2437
|
+
if (!(key instanceof Map))
|
|
2438
|
+
return;
|
|
2439
|
+
const algorithm = key.get(3);
|
|
2440
|
+
const kty = key.get(1);
|
|
2441
|
+
if (algorithm === -7) {
|
|
2442
|
+
const x = bytesOf(key.get(-2), 32);
|
|
2443
|
+
const y = bytesOf(key.get(-3), 32);
|
|
2444
|
+
if (kty !== 2 || key.get(-1) !== 1 || !x || !y)
|
|
2445
|
+
return;
|
|
2446
|
+
return { algorithm, jwk: { kty: "EC", crv: "P-256", x: toBase64Url4(x), y: toBase64Url4(y) } };
|
|
2447
|
+
}
|
|
2448
|
+
if (algorithm === -8 || algorithm === -19) {
|
|
2449
|
+
const x = bytesOf(key.get(-2), 32);
|
|
2450
|
+
if (kty !== 1 || key.get(-1) !== 6 || !x)
|
|
2451
|
+
return;
|
|
2452
|
+
return { algorithm, jwk: { kty: "OKP", crv: "Ed25519", x: toBase64Url4(x) } };
|
|
2453
|
+
}
|
|
2454
|
+
if (algorithm === -257) {
|
|
2455
|
+
const n = bytesOf(key.get(-1));
|
|
2456
|
+
const e = bytesOf(key.get(-2));
|
|
2457
|
+
if (kty !== 3 || !n || !e || n.length < MIN_RSA_BYTES || n[0] === 0 || e.length === 0 || e.length > 8)
|
|
2458
|
+
return;
|
|
2459
|
+
return { algorithm, jwk: { kty: "RSA", n: toBase64Url4(n), e: toBase64Url4(e) } };
|
|
2460
|
+
}
|
|
2461
|
+
return;
|
|
2462
|
+
}
|
|
2463
|
+
function importParams(algorithm) {
|
|
2464
|
+
if (algorithm === -7)
|
|
2465
|
+
return { name: "ECDSA", namedCurve: "P-256" };
|
|
2466
|
+
if (algorithm === -257)
|
|
2467
|
+
return { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
|
|
2468
|
+
return { name: "Ed25519" };
|
|
2469
|
+
}
|
|
2470
|
+
function verifyParams(algorithm) {
|
|
2471
|
+
if (algorithm === -7)
|
|
2472
|
+
return { name: "ECDSA", hash: "SHA-256" };
|
|
2473
|
+
if (algorithm === -257)
|
|
2474
|
+
return { name: "RSASSA-PKCS1-v1_5" };
|
|
2475
|
+
return { name: "Ed25519" };
|
|
2476
|
+
}
|
|
2477
|
+
function importJWK(jwk, algorithm) {
|
|
2478
|
+
return crypto.subtle.importKey("jwk", jwk, importParams(algorithm), false, ["verify"]);
|
|
2479
|
+
}
|
|
2480
|
+
function derToRaw(der) {
|
|
2481
|
+
if (der.length < 8 || der[0] !== 48 || der[1] !== der.length - 2)
|
|
2482
|
+
return;
|
|
2483
|
+
const raw = new Uint8Array(64);
|
|
2484
|
+
let at = 2;
|
|
2485
|
+
for (const half of [0, 1]) {
|
|
2486
|
+
if (der[at] !== 2)
|
|
2487
|
+
return;
|
|
2488
|
+
const size = der[at + 1];
|
|
2489
|
+
at += 2;
|
|
2490
|
+
if (size === undefined || size < 1 || size > 33 || at + size > der.length)
|
|
2491
|
+
return;
|
|
2492
|
+
let integer = der.subarray(at, at + size);
|
|
2493
|
+
at += size;
|
|
2494
|
+
if (integer[0] & 128)
|
|
2495
|
+
return;
|
|
2496
|
+
if (integer.length > 1 && integer[0] === 0 && !(integer[1] & 128))
|
|
2497
|
+
return;
|
|
2498
|
+
if (integer.length === 33) {
|
|
2499
|
+
if (integer[0] !== 0)
|
|
2500
|
+
return;
|
|
2501
|
+
integer = integer.subarray(1);
|
|
2502
|
+
}
|
|
2503
|
+
raw.set(integer, half * 32 + 32 - integer.length);
|
|
2504
|
+
}
|
|
2505
|
+
return at === der.length ? raw : undefined;
|
|
2506
|
+
}
|
|
2507
|
+
async function verifySignature(key, algorithm, signature, data) {
|
|
2508
|
+
const given = algorithm === -7 ? derToRaw(signature) : new Uint8Array(signature);
|
|
2509
|
+
if (!given)
|
|
2510
|
+
return false;
|
|
2511
|
+
try {
|
|
2512
|
+
return await crypto.subtle.verify(verifyParams(algorithm), key, given, data);
|
|
2513
|
+
} catch {
|
|
2514
|
+
return false;
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
// packages/auth/src/server/webauthn/data.ts
|
|
2519
|
+
var UP = 1;
|
|
2520
|
+
var UV = 4;
|
|
2521
|
+
var BE = 8;
|
|
2522
|
+
var BS = 16;
|
|
2523
|
+
var AT = 64;
|
|
2524
|
+
var ED = 128;
|
|
2525
|
+
var HEADER = 37;
|
|
2526
|
+
function readHeader(bytes) {
|
|
2527
|
+
if (bytes.length < HEADER)
|
|
2528
|
+
return;
|
|
2529
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
2530
|
+
return { rpIdHash: bytes.subarray(0, 32), flags: bytes[32], signCount: view.getUint32(33) };
|
|
2531
|
+
}
|
|
2532
|
+
function parseAuthenticatorData(bytes) {
|
|
2533
|
+
const data = readHeader(bytes);
|
|
2534
|
+
if (!data)
|
|
2535
|
+
throw new RangeError("authenticator data is shorter than 37 bytes");
|
|
2536
|
+
let at = HEADER;
|
|
2537
|
+
if (data.flags & AT) {
|
|
2538
|
+
if (at + 18 > bytes.length)
|
|
2539
|
+
throw new RangeError("attested credential data is cut short");
|
|
2540
|
+
const size = bytes[at + 16] << 8 | bytes[at + 17];
|
|
2541
|
+
at += 18;
|
|
2542
|
+
if (at + size > bytes.length)
|
|
2543
|
+
throw new RangeError("credential id runs past the authenticator data");
|
|
2544
|
+
const id = bytes.slice(at, at + size);
|
|
2545
|
+
at += size;
|
|
2546
|
+
const key = decodeCBORItem(bytes, at);
|
|
2547
|
+
at = key.end;
|
|
2548
|
+
data.credential = { id, publicKey: key.value };
|
|
2549
|
+
}
|
|
2550
|
+
if (data.flags & ED) {
|
|
2551
|
+
const extensions = decodeCBORItem(bytes, at);
|
|
2552
|
+
if (!(extensions.value instanceof Map))
|
|
2553
|
+
throw new TypeError("authenticator extensions are not a map");
|
|
2554
|
+
at = extensions.end;
|
|
2555
|
+
}
|
|
2556
|
+
if (at !== bytes.length)
|
|
2557
|
+
throw new RangeError("authenticator data has bytes after its fields");
|
|
2558
|
+
return data;
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// packages/auth/src/server/webauthn/handler.ts
|
|
2562
|
+
var PURPOSE3 = "hamur-webauthn";
|
|
2563
|
+
var TTL2 = 300;
|
|
2564
|
+
var TIMEOUT2 = 60000;
|
|
2565
|
+
var MAX_NAME = 256;
|
|
2566
|
+
var MAX_HANDLE = 64;
|
|
2567
|
+
var MAX_CREDENTIAL_ID = 1023;
|
|
2568
|
+
var VERIFICATIONS = ["required", "preferred", "discouraged"];
|
|
2569
|
+
var TRANSPORTS = ["usb", "nfc", "ble", "smart-card", "hybrid", "internal"];
|
|
2570
|
+
function fromBase64Url(text) {
|
|
2571
|
+
const bytes = decodeBase64Url(text);
|
|
2572
|
+
return bytes && bytes.length > 0 && toBase64Url5(bytes) === text ? bytes : undefined;
|
|
2573
|
+
}
|
|
2574
|
+
function transportsOf(value) {
|
|
2575
|
+
if (!Array.isArray(value))
|
|
2576
|
+
return;
|
|
2577
|
+
return TRANSPORTS.filter((name) => value.includes(name));
|
|
2578
|
+
}
|
|
2579
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2580
|
+
var isName = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_NAME;
|
|
2581
|
+
var randomText = (size) => toBase64Url5(crypto.getRandomValues(new Uint8Array(size)));
|
|
2582
|
+
var sha256 = async (bytes) => new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
|
2583
|
+
var concat = (a, b) => {
|
|
2584
|
+
const joined = new Uint8Array(a.length + b.length);
|
|
2585
|
+
joined.set(a);
|
|
2586
|
+
joined.set(b, a.length);
|
|
2587
|
+
return joined;
|
|
2588
|
+
};
|
|
2589
|
+
var failed2 = (check) => createError8({ status: 400, message: `WebAuthn verification failed: ${check}` });
|
|
2590
|
+
var invalid2 = () => createError8({ status: 400, message: "Invalid WebAuthn request" });
|
|
2591
|
+
var isChallenge = (value, kind, route) => isRecord3(value) && value.kind === kind && value.route === route && typeof value.challenge === "string" && typeof value.id === "string";
|
|
2592
|
+
function relyingParty(event) {
|
|
2593
|
+
const url = getRequestURL4(event);
|
|
2594
|
+
if (config.rpID !== undefined)
|
|
2595
|
+
return {
|
|
2596
|
+
id: config.rpID,
|
|
2597
|
+
name: config.rpName ?? config.rpID,
|
|
2598
|
+
origins: expectedOrigins(config.rpID, config.origins, url, Boolean(import.meta.dev))
|
|
2599
|
+
};
|
|
2600
|
+
if (!import.meta.dev && !listedRequestHost(event, url.hostname))
|
|
2601
|
+
throw failed2("origin");
|
|
2602
|
+
return { id: url.hostname, name: config.rpName ?? url.hostname, origins: config.origins ?? [url.origin] };
|
|
2603
|
+
}
|
|
2604
|
+
function expectedOrigins(rpID, origins, url, dev) {
|
|
2605
|
+
const configured = origins ?? [`https://${rpID}`];
|
|
2606
|
+
const own = url.hostname === rpID || url.hostname.endsWith(`.${rpID}`);
|
|
2607
|
+
return dev && own && !configured.includes(url.origin) ? [...configured, url.origin] : configured;
|
|
2608
|
+
}
|
|
2609
|
+
var singleUseChecked3 = false;
|
|
2610
|
+
async function checkSingleUse3(name) {
|
|
2611
|
+
if (singleUseChecked3)
|
|
2612
|
+
return;
|
|
2613
|
+
const problem = singleUseProblem(await storageMountDriver3("session"), {
|
|
2614
|
+
name,
|
|
2615
|
+
preset: singleUse3.preset,
|
|
2616
|
+
dev: Boolean(import.meta.dev)
|
|
2617
|
+
});
|
|
2618
|
+
if (problem)
|
|
2619
|
+
throw new Error(problem);
|
|
2620
|
+
singleUseChecked3 = true;
|
|
2621
|
+
}
|
|
2622
|
+
async function readStep(event) {
|
|
2623
|
+
const bytes = await readBodyBytes(event);
|
|
2624
|
+
let body;
|
|
2625
|
+
try {
|
|
2626
|
+
body = JSON.parse(new TextDecoder().decode(bytes ?? new Uint8Array));
|
|
2627
|
+
} catch {
|
|
2628
|
+
throw invalid2();
|
|
2629
|
+
}
|
|
2630
|
+
if (!isRecord3(body) || body.step !== "options" && body.step !== "verify")
|
|
2631
|
+
throw invalid2();
|
|
2632
|
+
return body;
|
|
2633
|
+
}
|
|
2634
|
+
function descriptors(list, from) {
|
|
2635
|
+
if (!Array.isArray(list))
|
|
2636
|
+
throw new TypeError(`${from} must return an array of { id, transports? }`);
|
|
2637
|
+
return list.map((entry) => {
|
|
2638
|
+
if (!isRecord3(entry) || typeof entry.id !== "string" || !fromBase64Url(entry.id))
|
|
2639
|
+
throw new TypeError(`${from} must return an array of { id, transports? } with a base64url id`);
|
|
2640
|
+
const transports = transportsOf(entry.transports);
|
|
2641
|
+
return { type: "public-key", id: entry.id, ...transports ? { transports } : {} };
|
|
2642
|
+
});
|
|
2643
|
+
}
|
|
2644
|
+
async function start(event, cookie, value) {
|
|
2645
|
+
setCookie3(event, cookie.name, await sealFor4(value, { purpose: PURPOSE3, ttl: TTL2 }), {
|
|
2646
|
+
...cookie.options,
|
|
2647
|
+
maxAge: TTL2
|
|
2648
|
+
});
|
|
2649
|
+
}
|
|
2650
|
+
async function openChallenge(event, cookie, kind, route) {
|
|
2651
|
+
const sealed = getCookie3(event, cookie.name);
|
|
2652
|
+
deleteCookie3(event, cookie.name, cookie.options);
|
|
2653
|
+
const value = sealed === undefined ? undefined : await unsealFor4(sealed, { purpose: PURPOSE3 });
|
|
2654
|
+
if (!isChallenge(value, kind, route))
|
|
2655
|
+
throw failed2("challenge");
|
|
2656
|
+
if (await useStorage4("session").increment(`webauthn:${value.id}`, 1, { ttl: TTL2 }) !== 1)
|
|
2657
|
+
throw failed2("challenge");
|
|
2658
|
+
return value;
|
|
2659
|
+
}
|
|
2660
|
+
function checkClientData(bytes, type, sealed, party) {
|
|
2661
|
+
let data;
|
|
2662
|
+
try {
|
|
2663
|
+
data = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
2664
|
+
} catch {
|
|
2665
|
+
throw failed2("type");
|
|
2666
|
+
}
|
|
2667
|
+
if (!isRecord3(data) || data.type !== type)
|
|
2668
|
+
throw failed2("type");
|
|
2669
|
+
if (typeof data.challenge !== "string" || !timingSafeEqual5(data.challenge, sealed.challenge))
|
|
2670
|
+
throw failed2("challenge");
|
|
2671
|
+
if (typeof data.origin !== "string" || !party.origins.includes(data.origin))
|
|
2672
|
+
throw failed2("origin");
|
|
2673
|
+
if (data.crossOrigin === true || data.topOrigin !== undefined)
|
|
2674
|
+
throw failed2("origin");
|
|
2675
|
+
}
|
|
2676
|
+
async function checkAuthenticatorData(data, party, userVerification) {
|
|
2677
|
+
if (!timingSafeEqual5(data.rpIdHash, await sha256(new TextEncoder().encode(party.id))))
|
|
2678
|
+
throw failed2("rpIdHash");
|
|
2679
|
+
if (!(data.flags & UP))
|
|
2680
|
+
throw failed2("userPresence");
|
|
2681
|
+
if (userVerification === "required" && !(data.flags & UV))
|
|
2682
|
+
throw failed2("userVerification");
|
|
2683
|
+
if (data.flags & BS && !(data.flags & BE))
|
|
2684
|
+
throw failed2("backupState");
|
|
2685
|
+
}
|
|
2686
|
+
function credentialResponse(value) {
|
|
2687
|
+
if (!isRecord3(value) || value.type !== "public-key" || typeof value.id !== "string" || typeof value.rawId !== "string" || !isRecord3(value.response))
|
|
2688
|
+
throw invalid2();
|
|
2689
|
+
const raw = fromBase64Url(value.rawId);
|
|
2690
|
+
const clientData = typeof value.response.clientDataJSON === "string" ? fromBase64Url(value.response.clientDataJSON) : undefined;
|
|
2691
|
+
if (!raw || !clientData)
|
|
2692
|
+
throw invalid2();
|
|
2693
|
+
return { id: value.id, raw, fields: value.response, clientData };
|
|
2694
|
+
}
|
|
2695
|
+
var bytesField = (fields, key) => {
|
|
2696
|
+
const value = fields[key];
|
|
2697
|
+
const bytes = typeof value === "string" ? fromBase64Url(value) : undefined;
|
|
2698
|
+
if (!bytes)
|
|
2699
|
+
throw invalid2();
|
|
2700
|
+
return bytes;
|
|
2701
|
+
};
|
|
2702
|
+
function verificationOf(given, name) {
|
|
2703
|
+
const value = given ?? "preferred";
|
|
2704
|
+
if (!VERIFICATIONS.includes(value))
|
|
2705
|
+
throw new TypeError(`${name} userVerification must be "required", "preferred" or "discouraged" (got ${JSON.stringify(value)})`);
|
|
2706
|
+
return value;
|
|
2707
|
+
}
|
|
2708
|
+
async function stepContext(event, name) {
|
|
2709
|
+
await checkSingleUse3(name);
|
|
2710
|
+
const url = getRequestURL4(event);
|
|
2711
|
+
const route = appPath(url.pathname);
|
|
2712
|
+
const cookie = await flowCookie({
|
|
2713
|
+
dev: Boolean(import.meta.dev),
|
|
2714
|
+
protocol: url.protocol,
|
|
2715
|
+
route,
|
|
2716
|
+
formPost: false,
|
|
2717
|
+
flow: "webauthn"
|
|
2718
|
+
});
|
|
2719
|
+
event.response.headers.set("cache-control", "no-store");
|
|
2720
|
+
return { route, cookie, body: await readStep(event) };
|
|
2721
|
+
}
|
|
2722
|
+
function webAuthnRegister(options) {
|
|
2723
|
+
const userVerification = verificationOf(options.userVerification, "webAuthnRegister");
|
|
2724
|
+
if (typeof options.onSuccess !== "function")
|
|
2725
|
+
throw new TypeError("webAuthnRegister needs onSuccess");
|
|
2726
|
+
if (options.getUserHandle && !options.validateUser)
|
|
2727
|
+
throw new TypeError("webAuthnRegister getUserHandle needs validateUser: a user handle is looked up only for a userName validateUser accepted");
|
|
2728
|
+
if (options.excludeCredentials && !options.validateUser)
|
|
2729
|
+
throw new TypeError("webAuthnRegister excludeCredentials needs validateUser: an account's credentials are listed only for a userName validateUser accepted");
|
|
2730
|
+
return async (_input, { event }) => {
|
|
2731
|
+
const { route, cookie, body } = await stepContext(event, "webAuthnRegister");
|
|
2732
|
+
const party = relyingParty(event);
|
|
2733
|
+
if (body.step === "options") {
|
|
2734
|
+
const user = body.user;
|
|
2735
|
+
if (!isRecord3(user) || !isName(user.userName) || user.displayName !== undefined && !isName(user.displayName))
|
|
2736
|
+
throw invalid2();
|
|
2737
|
+
const given = {
|
|
2738
|
+
userName: user.userName,
|
|
2739
|
+
...user.displayName === undefined ? {} : { displayName: user.displayName }
|
|
2740
|
+
};
|
|
2741
|
+
let userHandle;
|
|
2742
|
+
let exclude = [];
|
|
2743
|
+
if (options.validateUser) {
|
|
2744
|
+
await options.validateUser(given, event);
|
|
2745
|
+
if (options.getUserHandle) {
|
|
2746
|
+
userHandle = await options.getUserHandle(event, given.userName);
|
|
2747
|
+
const bytes = userHandle === undefined ? undefined : fromBase64Url(userHandle);
|
|
2748
|
+
if (userHandle !== undefined && !(bytes && bytes.length > 0 && bytes.length <= MAX_HANDLE))
|
|
2749
|
+
throw new TypeError(`webAuthnRegister getUserHandle must return a base64url user handle of 1 to ${MAX_HANDLE} bytes, or undefined`);
|
|
2750
|
+
}
|
|
2751
|
+
if (options.excludeCredentials)
|
|
2752
|
+
exclude = descriptors(await options.excludeCredentials(event, given.userName), "webAuthnRegister excludeCredentials");
|
|
2753
|
+
}
|
|
2754
|
+
userHandle ??= randomText(32);
|
|
2755
|
+
const challenge = randomText(32);
|
|
2756
|
+
await start(event, cookie, { kind: "register", route, challenge, id: randomText(16), ...given, userHandle });
|
|
2757
|
+
return {
|
|
2758
|
+
rp: { id: party.id, name: party.name },
|
|
2759
|
+
user: { id: userHandle, name: given.userName, displayName: given.displayName ?? given.userName },
|
|
2760
|
+
challenge,
|
|
2761
|
+
pubKeyCredParams: ALGORITHMS.map((alg) => ({ type: "public-key", alg })),
|
|
2762
|
+
timeout: TIMEOUT2,
|
|
2763
|
+
excludeCredentials: exclude,
|
|
2764
|
+
authenticatorSelection: { residentKey: "preferred", userVerification },
|
|
2765
|
+
attestation: "none"
|
|
2766
|
+
};
|
|
2767
|
+
}
|
|
2768
|
+
const response = credentialResponse(body.response);
|
|
2769
|
+
const attestationBytes = bytesField(response.fields, "attestationObject");
|
|
2770
|
+
const sealed = await openChallenge(event, cookie, "register", route);
|
|
2771
|
+
checkClientData(response.clientData, "webauthn.create", sealed, party);
|
|
2772
|
+
let attestation;
|
|
2773
|
+
try {
|
|
2774
|
+
attestation = decodeCBOR(attestationBytes);
|
|
2775
|
+
} catch {
|
|
2776
|
+
throw failed2("attestation");
|
|
2777
|
+
}
|
|
2778
|
+
const fmt = attestation instanceof Map ? attestation.get("fmt") : undefined;
|
|
2779
|
+
const statement = attestation instanceof Map ? attestation.get("attStmt") : undefined;
|
|
2780
|
+
const authData = attestation instanceof Map ? attestation.get("authData") : undefined;
|
|
2781
|
+
if (typeof fmt !== "string" || !(statement instanceof Map) || !(authData instanceof Uint8Array))
|
|
2782
|
+
throw failed2("attestation");
|
|
2783
|
+
let data;
|
|
2784
|
+
try {
|
|
2785
|
+
data = parseAuthenticatorData(authData);
|
|
2786
|
+
} catch {
|
|
2787
|
+
throw failed2("attestation");
|
|
2788
|
+
}
|
|
2789
|
+
await checkAuthenticatorData(data, party, userVerification);
|
|
2790
|
+
const attested = data.credential;
|
|
2791
|
+
if (!(data.flags & AT) || !attested)
|
|
2792
|
+
throw failed2("credentialId");
|
|
2793
|
+
if (response.id !== toBase64Url5(response.raw) || attested.id.length > MAX_CREDENTIAL_ID || !timingSafeEqual5(attested.id, response.raw))
|
|
2794
|
+
throw failed2("credentialId");
|
|
2795
|
+
const key = coseToJWK(attested.publicKey);
|
|
2796
|
+
if (!key)
|
|
2797
|
+
throw failed2("algorithm");
|
|
2798
|
+
let verifier;
|
|
2799
|
+
try {
|
|
2800
|
+
verifier = await importJWK(key.jwk, key.algorithm);
|
|
2801
|
+
} catch {
|
|
2802
|
+
throw failed2("algorithm");
|
|
2803
|
+
}
|
|
2804
|
+
if (fmt === "none" && statement.size !== 0)
|
|
2805
|
+
throw failed2("attestation");
|
|
2806
|
+
if (fmt === "packed" && !statement.has("x5c")) {
|
|
2807
|
+
const signature = statement.get("sig");
|
|
2808
|
+
if (statement.get("alg") !== key.algorithm || !(signature instanceof Uint8Array))
|
|
2809
|
+
throw failed2("attestation");
|
|
2810
|
+
const signed = concat(authData, await sha256(response.clientData));
|
|
2811
|
+
if (!await verifySignature(verifier, key.algorithm, signature, signed))
|
|
2812
|
+
throw failed2("attestation");
|
|
2813
|
+
}
|
|
2814
|
+
const transports = transportsOf(response.fields.transports);
|
|
2815
|
+
const credential = {
|
|
2816
|
+
id: response.id,
|
|
2817
|
+
userHandle: sealed.userHandle,
|
|
2818
|
+
publicKey: key.jwk,
|
|
2819
|
+
algorithm: key.algorithm,
|
|
2820
|
+
counter: data.signCount,
|
|
2821
|
+
...transports ? { transports } : {},
|
|
2822
|
+
backupEligible: Boolean(data.flags & BE),
|
|
2823
|
+
backedUp: Boolean(data.flags & BS),
|
|
2824
|
+
userVerified: Boolean(data.flags & UV)
|
|
2825
|
+
};
|
|
2826
|
+
const user = {
|
|
2827
|
+
userName: sealed.userName,
|
|
2828
|
+
...sealed.displayName === undefined ? {} : { displayName: sealed.displayName },
|
|
2829
|
+
userHandle: sealed.userHandle
|
|
2830
|
+
};
|
|
2831
|
+
const value = await options.onSuccess(event, { credential, user });
|
|
2832
|
+
return value === undefined ? { verified: true } : value;
|
|
2833
|
+
};
|
|
2834
|
+
}
|
|
2835
|
+
function webAuthnAuthenticate(options) {
|
|
2836
|
+
const userVerification = verificationOf(options.userVerification, "webAuthnAuthenticate");
|
|
2837
|
+
if (typeof options.getCredential !== "function")
|
|
2838
|
+
throw new TypeError("webAuthnAuthenticate needs getCredential");
|
|
2839
|
+
if (typeof options.onSuccess !== "function")
|
|
2840
|
+
throw new TypeError("webAuthnAuthenticate needs onSuccess");
|
|
2841
|
+
return async (_input, { event }) => {
|
|
2842
|
+
const { route, cookie, body } = await stepContext(event, "webAuthnAuthenticate");
|
|
2843
|
+
const party = relyingParty(event);
|
|
2844
|
+
if (body.step === "options") {
|
|
2845
|
+
const user = body.user;
|
|
2846
|
+
if (user !== undefined && !(isRecord3(user) && isName(user.userName)))
|
|
2847
|
+
throw invalid2();
|
|
2848
|
+
const userName = isRecord3(user) ? user.userName : undefined;
|
|
2849
|
+
const allow = userName !== undefined && options.allowCredentials ? descriptors(await options.allowCredentials(event, userName), "webAuthnAuthenticate allowCredentials") : [];
|
|
2850
|
+
const challenge = randomText(32);
|
|
2851
|
+
await start(event, cookie, {
|
|
2852
|
+
kind: "authenticate",
|
|
2853
|
+
route,
|
|
2854
|
+
challenge,
|
|
2855
|
+
id: randomText(16),
|
|
2856
|
+
...userName === undefined ? {} : { userName },
|
|
2857
|
+
...allow.length ? { allow: allow.map((entry) => entry.id) } : {}
|
|
2858
|
+
});
|
|
2859
|
+
return { challenge, timeout: TIMEOUT2, rpId: party.id, allowCredentials: allow, userVerification };
|
|
2860
|
+
}
|
|
2861
|
+
const response = credentialResponse(body.response);
|
|
2862
|
+
const authData = bytesField(response.fields, "authenticatorData");
|
|
2863
|
+
const signature = bytesField(response.fields, "signature");
|
|
2864
|
+
const handle = response.fields.userHandle;
|
|
2865
|
+
if (handle !== undefined && handle !== null && typeof handle !== "string")
|
|
2866
|
+
throw invalid2();
|
|
2867
|
+
const sealed = await openChallenge(event, cookie, "authenticate", route);
|
|
2868
|
+
checkClientData(response.clientData, "webauthn.get", sealed, party);
|
|
2869
|
+
const data = readHeader(authData);
|
|
2870
|
+
if (!data)
|
|
2871
|
+
throw failed2("rpIdHash");
|
|
2872
|
+
await checkAuthenticatorData(data, party, userVerification);
|
|
2873
|
+
if (response.id !== toBase64Url5(response.raw))
|
|
2874
|
+
throw failed2("credential");
|
|
2875
|
+
if (sealed.allow && !sealed.allow.includes(response.id))
|
|
2876
|
+
throw failed2("credential");
|
|
2877
|
+
const credential = await options.getCredential(event, response.id);
|
|
2878
|
+
if (!credential)
|
|
2879
|
+
throw failed2("credential");
|
|
2880
|
+
const userHandle = typeof handle === "string" && handle !== "" ? handle : undefined;
|
|
2881
|
+
if (userHandle === undefined ? !sealed.allow : !timingSafeEqual5(userHandle, credential.userHandle))
|
|
2882
|
+
throw failed2("userHandle");
|
|
2883
|
+
if (Boolean(data.flags & BE) !== credential.backupEligible)
|
|
2884
|
+
throw failed2("backupState");
|
|
2885
|
+
let verifier;
|
|
2886
|
+
try {
|
|
2887
|
+
verifier = await importJWK(credential.publicKey, credential.algorithm);
|
|
2888
|
+
} catch {
|
|
2889
|
+
throw failed2("signature");
|
|
2890
|
+
}
|
|
2891
|
+
if (!await verifySignature(verifier, credential.algorithm, signature, concat(authData, await sha256(response.clientData))))
|
|
2892
|
+
throw failed2("signature");
|
|
2893
|
+
const counter = data.signCount;
|
|
2894
|
+
if ((credential.counter !== 0 || counter !== 0) && counter <= credential.counter)
|
|
2895
|
+
throw failed2("signCount");
|
|
2896
|
+
const value = await options.onSuccess(event, { credential, counter, backedUp: Boolean(data.flags & BS) });
|
|
2897
|
+
return value === undefined ? { verified: true } : value;
|
|
2898
|
+
};
|
|
2899
|
+
}
|
|
2900
|
+
export {
|
|
2901
|
+
clearUserSession2 as clearUserSession,
|
|
2902
|
+
consumeAuthToken,
|
|
2903
|
+
createAccessToken2 as createAccessToken,
|
|
2904
|
+
createAuthToken,
|
|
2905
|
+
createRecoveryCodes,
|
|
2906
|
+
createTotp,
|
|
2907
|
+
getUserSession2 as getUserSession,
|
|
2908
|
+
matchRecoveryCode,
|
|
2909
|
+
oauthApple,
|
|
2910
|
+
oauthAtlassian,
|
|
2911
|
+
oauthAtproto,
|
|
2912
|
+
oauthAuth0,
|
|
2913
|
+
oauthAuthentik,
|
|
2914
|
+
oauthAzureB2C,
|
|
2915
|
+
oauthBattleDotNet,
|
|
2916
|
+
oauthBox,
|
|
2917
|
+
oauthCloudflare,
|
|
2918
|
+
oauthCognito,
|
|
2919
|
+
oauthDiscord,
|
|
2920
|
+
oauthDropbox,
|
|
2921
|
+
oauthFacebook,
|
|
2922
|
+
oauthGitHub,
|
|
2923
|
+
oauthGitLab,
|
|
2924
|
+
oauthGitea,
|
|
2925
|
+
oauthGoogle,
|
|
2926
|
+
oauthHandler,
|
|
2927
|
+
oauthHeroku,
|
|
2928
|
+
oauthHubSpot,
|
|
2929
|
+
oauthInstagram,
|
|
2930
|
+
oauthKeycloak,
|
|
2931
|
+
oauthKick,
|
|
2932
|
+
oauthLine,
|
|
2933
|
+
oauthLinear,
|
|
2934
|
+
oauthLinkedIn,
|
|
2935
|
+
oauthLiveChat,
|
|
2936
|
+
oauthMastodon,
|
|
2937
|
+
oauthMicrosoft,
|
|
2938
|
+
oauthOIDC,
|
|
2939
|
+
oauthOkta,
|
|
2940
|
+
oauthOry,
|
|
2941
|
+
oauthOsu,
|
|
2942
|
+
oauthPayPal,
|
|
2943
|
+
oauthPolar,
|
|
2944
|
+
oauthRiotGames,
|
|
2945
|
+
oauthRoblox,
|
|
2946
|
+
oauthSalesforce,
|
|
2947
|
+
oauthSeznam,
|
|
2948
|
+
oauthShopifyCustomer,
|
|
2949
|
+
oauthSlack,
|
|
2950
|
+
oauthSpotify,
|
|
2951
|
+
oauthSteam,
|
|
2952
|
+
oauthStrava,
|
|
2953
|
+
oauthTikTok,
|
|
2954
|
+
oauthTwitch,
|
|
2955
|
+
oauthVK,
|
|
2956
|
+
oauthWeChat,
|
|
2957
|
+
oauthWorkOS,
|
|
2958
|
+
oauthX,
|
|
2959
|
+
oauthXsuaa,
|
|
2960
|
+
oauthYandex,
|
|
2961
|
+
oauthZendesk,
|
|
2962
|
+
oauthZitadel,
|
|
2963
|
+
replaceUserSession2 as replaceUserSession,
|
|
2964
|
+
requireUserSession2 as requireUserSession,
|
|
2965
|
+
revokeAccessToken2 as revokeAccessToken,
|
|
2966
|
+
sendAuthLink,
|
|
2967
|
+
setUserSession2 as setUserSession,
|
|
2968
|
+
verifyTotp,
|
|
2969
|
+
webAuthnAuthenticate,
|
|
2970
|
+
webAuthnRegister
|
|
2971
|
+
};
|