@madauth/server 0.3.0-beta.2 → 0.4.0-beta.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/README.md +3 -2
- package/dist/bin.js +104 -42
- package/dist/chunk-3PACOYTG.js +1185 -0
- package/dist/{chunk-DCDTO5LG.js → chunk-A7UYZRBL.js} +1 -0
- package/dist/{chunk-CD7Y4T66.js → chunk-GA4TF7EI.js} +24 -2
- package/dist/{chunk-TI35AZ2U.js → chunk-ISJGOCF3.js} +250 -83
- package/dist/{chunk-56MOVFO4.js → chunk-OMIX3ERC.js} +11 -2
- package/dist/{chunk-3QRKWLR7.js → chunk-Y7ZSUROX.js} +4 -1
- package/dist/{config-Dg2fZuWR.d.ts → config-DkE_2D3-.d.ts} +5 -2
- package/dist/dynamodb.js +1 -1
- package/dist/entry/azure.d.ts +3 -3
- package/dist/entry/azure.js +4 -4
- package/dist/entry/lambda.d.ts +3 -3
- package/dist/entry/lambda.js +4 -4
- package/dist/entry/node.d.ts +3 -3
- package/dist/entry/node.js +4 -4
- package/dist/index.d.ts +29 -14
- package/dist/index.js +10 -6
- package/dist/{schema-3yhCc2jH.d.ts → schema-DTeiSuQB.d.ts} +39 -2
- package/dist/sqlite.js +2 -2
- package/dist/standalone/azure.mjs +1316 -676
- package/dist/standalone/lambda.mjs +1311 -671
- package/dist/standalone/main.mjs +1142 -502
- package/dist/store/dynamodb.d.ts +1 -1
- package/dist/store/sqlite.d.ts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -0
- package/dist/{user-BMWEWREH.d.ts → user-BZs84sui.d.ts} +5 -0
- package/dist/verify.d.ts +1 -1
- package/dist/verify.js +1 -1
- package/dist/{webhook-j5u9Kv9l.d.ts → webhook-B6P50ocX.d.ts} +1 -1
- package/dist/webhook.d.ts +1 -1
- package/dist/webhook.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-DVVBIFIV.js +0 -718
|
@@ -0,0 +1,1185 @@
|
|
|
1
|
+
import {
|
|
2
|
+
EXPIRY_COOKIE,
|
|
3
|
+
RENEWAL_COOKIE,
|
|
4
|
+
RENEWAL_TYP,
|
|
5
|
+
SESSION_COOKIE,
|
|
6
|
+
SESSION_TYP,
|
|
7
|
+
randomString,
|
|
8
|
+
readToken,
|
|
9
|
+
signRenewal,
|
|
10
|
+
signSession,
|
|
11
|
+
signToken,
|
|
12
|
+
userFromClaims
|
|
13
|
+
} from "./chunk-A7UYZRBL.js";
|
|
14
|
+
import {
|
|
15
|
+
ADMIN_ROLE,
|
|
16
|
+
MAX_PASSWORD_LENGTH,
|
|
17
|
+
METHODS_WITH_SECOND_FACTOR,
|
|
18
|
+
SIGN_IN_METHODS,
|
|
19
|
+
Settings,
|
|
20
|
+
Users,
|
|
21
|
+
anyOn,
|
|
22
|
+
authenticatorOn,
|
|
23
|
+
canSignUp,
|
|
24
|
+
checkPasswordPolicy,
|
|
25
|
+
claimsFromJson,
|
|
26
|
+
deriveCodeKey,
|
|
27
|
+
googleAccountKey,
|
|
28
|
+
hashCode,
|
|
29
|
+
hashPassword,
|
|
30
|
+
initialMethods,
|
|
31
|
+
isAdmin,
|
|
32
|
+
isConfigured,
|
|
33
|
+
isOn,
|
|
34
|
+
isValidEmail,
|
|
35
|
+
methodConfig,
|
|
36
|
+
newId,
|
|
37
|
+
normalizeEmail,
|
|
38
|
+
parseClaims,
|
|
39
|
+
parseMethodSettings,
|
|
40
|
+
passwordAccountKey,
|
|
41
|
+
policyOf,
|
|
42
|
+
safeEqual,
|
|
43
|
+
sameClaims,
|
|
44
|
+
sendsVerificationEmails,
|
|
45
|
+
toMadauthUser,
|
|
46
|
+
totpAccountKey,
|
|
47
|
+
verifyAgainstDummy,
|
|
48
|
+
verifyPassword
|
|
49
|
+
} from "./chunk-ISJGOCF3.js";
|
|
50
|
+
import {
|
|
51
|
+
importSigningKeys
|
|
52
|
+
} from "./chunk-JDQLSL36.js";
|
|
53
|
+
import {
|
|
54
|
+
WEBHOOK_TIMEOUT_MS,
|
|
55
|
+
createWebhookClient,
|
|
56
|
+
localeOf
|
|
57
|
+
} from "./chunk-Y7ZSUROX.js";
|
|
58
|
+
|
|
59
|
+
// src/routes/google.ts
|
|
60
|
+
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
61
|
+
import { base64url } from "jose";
|
|
62
|
+
|
|
63
|
+
// src/google.ts
|
|
64
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
65
|
+
var GOOGLE_ISSUERS = ["https://accounts.google.com", "accounts.google.com"];
|
|
66
|
+
var googleJwks;
|
|
67
|
+
function googleKeys() {
|
|
68
|
+
googleJwks ??= createRemoteJWKSet(new URL("https://www.googleapis.com/oauth2/v3/certs"));
|
|
69
|
+
return googleJwks;
|
|
70
|
+
}
|
|
71
|
+
async function verifyGoogleIdToken(idToken, opts) {
|
|
72
|
+
let payload;
|
|
73
|
+
try {
|
|
74
|
+
({ payload } = await jwtVerify(idToken, opts.keys ?? googleKeys(), {
|
|
75
|
+
issuer: GOOGLE_ISSUERS,
|
|
76
|
+
audience: opts.clientId,
|
|
77
|
+
algorithms: ["RS256", "ES256"]
|
|
78
|
+
}));
|
|
79
|
+
} catch (e) {
|
|
80
|
+
return { ok: false, error: "verification_failed", reason: e.message };
|
|
81
|
+
}
|
|
82
|
+
if (typeof payload.sub !== "string" || !payload.sub) {
|
|
83
|
+
return { ok: false, error: "verification_failed", reason: "missing sub" };
|
|
84
|
+
}
|
|
85
|
+
if (payload.nonce !== opts.nonce) {
|
|
86
|
+
return { ok: false, error: "verification_failed", reason: "nonce mismatch" };
|
|
87
|
+
}
|
|
88
|
+
if (typeof payload.email !== "string" || !payload.email || payload.email_verified !== true) {
|
|
89
|
+
return { ok: false, error: "email_unverified", reason: "e-mail address not verified" };
|
|
90
|
+
}
|
|
91
|
+
const profile = { sub: payload.sub, email: payload.email };
|
|
92
|
+
if (typeof payload.name === "string") profile.name = payload.name;
|
|
93
|
+
if (typeof payload.picture === "string") profile.picture = payload.picture;
|
|
94
|
+
return { ok: true, profile };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/routes/helpers.ts
|
|
98
|
+
async function body(c) {
|
|
99
|
+
const data = await c.req.json().catch(() => null);
|
|
100
|
+
return data && typeof data === "object" ? data : {};
|
|
101
|
+
}
|
|
102
|
+
function error(c, status, code, message) {
|
|
103
|
+
return c.json({ error: code, message }, status);
|
|
104
|
+
}
|
|
105
|
+
var unavailable = (c) => error(c, 503, "temporarily_unavailable", "E-mails can not be sent right now. Please try again later.");
|
|
106
|
+
var accepted = (c) => c.json({}, 202);
|
|
107
|
+
var noSession = (c) => error(c, 401, "no_session", "Please sign in first.");
|
|
108
|
+
function redirectTarget(ctx, c, value) {
|
|
109
|
+
const url = ctx.allowedUrl(value);
|
|
110
|
+
return url ?? error(c, 400, "invalid_options", "redirectTo must be an absolute URL whose origin is in ALLOWED_ORIGINS.");
|
|
111
|
+
}
|
|
112
|
+
var MAX_NAME_LENGTH = 100;
|
|
113
|
+
function nameOf(value) {
|
|
114
|
+
return typeof value === "string" && value.trim() ? value.trim().slice(0, MAX_NAME_LENGTH) : null;
|
|
115
|
+
}
|
|
116
|
+
function signInAnswer(c, step) {
|
|
117
|
+
if ("disabled" in step) return error(c, 403, "method_disabled", "This way of signing in is switched off.");
|
|
118
|
+
if ("next" in step) {
|
|
119
|
+
return step.next === "totp" ? c.json({ error: "totp_required", message: "Enter the code from your authenticator app to finish signing in.", method: step.method }, 401) : c.json({ error: "totp_setup_required", message: "Set up an authenticator app to finish signing in.", method: step.method }, 401);
|
|
120
|
+
}
|
|
121
|
+
return c.json({ user: step.user });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/routes/google.ts
|
|
125
|
+
var NONCE_COOKIE = "madauth_nonce";
|
|
126
|
+
var NONCE_TYP = "madauth-nonce+jwt";
|
|
127
|
+
var NONCE_TTL = 5 * 60;
|
|
128
|
+
var OAUTH_COOKIE = "madauth_oauth";
|
|
129
|
+
var OAUTH_TYP = "madauth-oauth-state+jwt";
|
|
130
|
+
var OAUTH_TTL = 10 * 60;
|
|
131
|
+
var GOOGLE_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth";
|
|
132
|
+
var GOOGLE_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
|
|
133
|
+
var REDIRECT_ERROR_PARAM = "madauth_error";
|
|
134
|
+
var REDIRECT_NEXT_PARAM = "madauth_next";
|
|
135
|
+
async function pkceChallenge(verifier) {
|
|
136
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
137
|
+
return base64url.encode(new Uint8Array(digest));
|
|
138
|
+
}
|
|
139
|
+
function googleRoutes(app, ctx, google) {
|
|
140
|
+
const { config, keys, secure, users } = ctx;
|
|
141
|
+
const { issuer } = config;
|
|
142
|
+
const callbackUrl = `${issuer}/auth/google/callback`;
|
|
143
|
+
const resolveUser = async (profile, locale) => {
|
|
144
|
+
const key = googleAccountKey(profile.sub);
|
|
145
|
+
const emailNormalized = normalizeEmail(profile.email);
|
|
146
|
+
const signedIn = (user) => ({ ok: true, user });
|
|
147
|
+
const account = await users.findAccountByKey(key);
|
|
148
|
+
if (account) {
|
|
149
|
+
const user = await users.findById(account.userId);
|
|
150
|
+
if (user) {
|
|
151
|
+
if (account.email !== profile.email) await users.updateAccount(account.id, { email: profile.email });
|
|
152
|
+
return signedIn(user);
|
|
153
|
+
}
|
|
154
|
+
await users.deleteAccount(account.id);
|
|
155
|
+
}
|
|
156
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
157
|
+
const existing = await users.findByEmail(emailNormalized);
|
|
158
|
+
if (existing) {
|
|
159
|
+
if (existing.emailVerified && await users.hasAccounts(existing.id)) {
|
|
160
|
+
const methods = await users.signInMethods(existing.id, await ctx.settings.methods());
|
|
161
|
+
const how = methods.map((method) => ({ password: "a password", totp: "an authenticator app", google: "Google" })[method]).join(" or ");
|
|
162
|
+
return { ok: false, error: "other_method", message: `This e-mail address signs in with ${how || "another method"}. Use that instead of Google.`, methods };
|
|
163
|
+
}
|
|
164
|
+
await users.verifyByProvider(existing);
|
|
165
|
+
if (!await users.linkAccount(existing.id, { key, email: profile.email })) {
|
|
166
|
+
const linked = await users.findAccountByKey(key);
|
|
167
|
+
const owner = linked && await users.findById(linked.userId);
|
|
168
|
+
if (!owner) return { ok: false, error: "temporarily_unavailable", message: "Please try again." };
|
|
169
|
+
return signedIn(owner);
|
|
170
|
+
}
|
|
171
|
+
return signedIn(existing);
|
|
172
|
+
}
|
|
173
|
+
if (attempt === 0) {
|
|
174
|
+
const check = await ctx.checkSignup({ email: profile.email, name: profile.name, locale, method: "google" });
|
|
175
|
+
if (!check.ok) {
|
|
176
|
+
return check.reason === "rejected" ? { ok: false, error: "signup_rejected", message: check.message } : { ok: false, error: "temporarily_unavailable", message: "Signing up is not possible right now. Please try again later." };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const user = await users.createUser({
|
|
180
|
+
email: profile.email,
|
|
181
|
+
emailNormalized,
|
|
182
|
+
name: profile.name ?? null,
|
|
183
|
+
emailVerified: true,
|
|
184
|
+
account: { key, email: profile.email }
|
|
185
|
+
});
|
|
186
|
+
if (user) {
|
|
187
|
+
await ctx.emit("user.created", { user: toMadauthUser(user), method: "google" });
|
|
188
|
+
return signedIn(user);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return { ok: false, error: "temporarily_unavailable", message: "Please try again." };
|
|
192
|
+
};
|
|
193
|
+
const disabled = (c) => c.json({ error: "method_disabled", message: "Google sign-in is switched off." }, 403);
|
|
194
|
+
app.post("/auth/google/nonce", async (c) => {
|
|
195
|
+
if (!await ctx.enabled(c, "google")) return disabled(c);
|
|
196
|
+
const nonce = randomString();
|
|
197
|
+
const token = await signToken(await keys, issuer, NONCE_TYP, { nonce }, NONCE_TTL);
|
|
198
|
+
setCookie(c, NONCE_COOKIE, token, {
|
|
199
|
+
path: "/auth/google",
|
|
200
|
+
httpOnly: true,
|
|
201
|
+
secure,
|
|
202
|
+
sameSite: "Strict",
|
|
203
|
+
maxAge: NONCE_TTL
|
|
204
|
+
});
|
|
205
|
+
return c.json({ nonce });
|
|
206
|
+
});
|
|
207
|
+
app.post("/auth/google/verify", async (c) => {
|
|
208
|
+
if (!await ctx.enabled(c, "google")) return disabled(c);
|
|
209
|
+
const body2 = await c.req.json().catch(() => ({}));
|
|
210
|
+
if (typeof body2.credential !== "string" || !body2.credential) {
|
|
211
|
+
return c.json({ error: "verification_failed", message: "credential is missing" }, 400);
|
|
212
|
+
}
|
|
213
|
+
const nonceClaims = await readToken(await keys, issuer, NONCE_TYP, getCookie(c, NONCE_COOKIE));
|
|
214
|
+
if (!nonceClaims) {
|
|
215
|
+
return c.json({ error: "verification_failed", message: "nonce cookie missing or expired" }, 401);
|
|
216
|
+
}
|
|
217
|
+
const result = await verifyGoogleIdToken(body2.credential, {
|
|
218
|
+
clientId: google.clientId,
|
|
219
|
+
nonce: nonceClaims.nonce,
|
|
220
|
+
keys: config.jwksResolver
|
|
221
|
+
});
|
|
222
|
+
if (!result.ok) {
|
|
223
|
+
return c.json({ error: result.error, message: result.reason }, result.error === "email_unverified" ? 403 : 401);
|
|
224
|
+
}
|
|
225
|
+
deleteCookie(c, NONCE_COOKIE, { path: "/auth/google", secure });
|
|
226
|
+
const resolved = await resolveUser(result.profile, localeOf(body2.locale));
|
|
227
|
+
if (!resolved.ok) {
|
|
228
|
+
if (resolved.error === "other_method") return c.json({ error: resolved.error, message: resolved.message, methods: resolved.methods }, 403);
|
|
229
|
+
return c.json({ error: resolved.error, message: resolved.message }, resolved.error === "signup_rejected" ? 403 : 503);
|
|
230
|
+
}
|
|
231
|
+
return signInAnswer(c, await ctx.secondStep(c, resolved.user, ["google"], "google", result.profile));
|
|
232
|
+
});
|
|
233
|
+
const requireCodeFlow = async (c, next) => {
|
|
234
|
+
if (!google.clientSecret) return c.json({ error: "not_found" }, 404);
|
|
235
|
+
if (!await ctx.enabled(c, "google")) return disabled(c);
|
|
236
|
+
await next();
|
|
237
|
+
};
|
|
238
|
+
app.get("/auth/google/start", requireCodeFlow, async (c) => {
|
|
239
|
+
const returnUrl = ctx.allowedUrl(c.req.query("return_to"));
|
|
240
|
+
if (!returnUrl) return c.text("return_to must be an absolute URL whose origin is in ALLOWED_ORIGINS", 400);
|
|
241
|
+
const oauth = {
|
|
242
|
+
state: randomString(),
|
|
243
|
+
nonce: randomString(),
|
|
244
|
+
verifier: randomString(),
|
|
245
|
+
returnTo: returnUrl.href,
|
|
246
|
+
locale: localeOf(c.req.query("locale"))
|
|
247
|
+
};
|
|
248
|
+
const token = await signToken(await keys, issuer, OAUTH_TYP, { ...oauth }, OAUTH_TTL);
|
|
249
|
+
setCookie(c, OAUTH_COOKIE, token, {
|
|
250
|
+
path: "/auth/google",
|
|
251
|
+
httpOnly: true,
|
|
252
|
+
secure,
|
|
253
|
+
sameSite: "Lax",
|
|
254
|
+
maxAge: OAUTH_TTL
|
|
255
|
+
});
|
|
256
|
+
const url = new URL(GOOGLE_AUTH_ENDPOINT);
|
|
257
|
+
url.search = new URLSearchParams({
|
|
258
|
+
client_id: google.clientId,
|
|
259
|
+
redirect_uri: callbackUrl,
|
|
260
|
+
response_type: "code",
|
|
261
|
+
scope: "openid email profile",
|
|
262
|
+
state: oauth.state,
|
|
263
|
+
nonce: oauth.nonce,
|
|
264
|
+
code_challenge: await pkceChallenge(oauth.verifier),
|
|
265
|
+
code_challenge_method: "S256"
|
|
266
|
+
}).toString();
|
|
267
|
+
return c.redirect(url.href, 302);
|
|
268
|
+
});
|
|
269
|
+
app.get("/auth/google/callback", requireCodeFlow, async (c) => {
|
|
270
|
+
const oauth = await readToken(await keys, issuer, OAUTH_TYP, getCookie(c, OAUTH_COOKIE));
|
|
271
|
+
if (!oauth) return c.text("Sign-in expired or was started in another browser. Please try again.", 400);
|
|
272
|
+
deleteCookie(c, OAUTH_COOKIE, { path: "/auth/google", secure });
|
|
273
|
+
const back = (error2, next) => {
|
|
274
|
+
const url = new URL(oauth.returnTo);
|
|
275
|
+
if (error2) url.hash = `${REDIRECT_ERROR_PARAM}=${error2}`;
|
|
276
|
+
if (next) url.hash = `${REDIRECT_NEXT_PARAM}=${next}`;
|
|
277
|
+
return c.redirect(url.href, 302);
|
|
278
|
+
};
|
|
279
|
+
if (c.req.query("error")) return back(c.req.query("error") === "access_denied" ? "cancelled" : "verification_failed");
|
|
280
|
+
const code = c.req.query("code");
|
|
281
|
+
if (!code || c.req.query("state") !== oauth.state) return back("verification_failed");
|
|
282
|
+
let idToken;
|
|
283
|
+
try {
|
|
284
|
+
const res = await fetch(GOOGLE_TOKEN_ENDPOINT, {
|
|
285
|
+
method: "POST",
|
|
286
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
287
|
+
body: new URLSearchParams({
|
|
288
|
+
code,
|
|
289
|
+
client_id: google.clientId,
|
|
290
|
+
client_secret: google.clientSecret,
|
|
291
|
+
redirect_uri: callbackUrl,
|
|
292
|
+
grant_type: "authorization_code",
|
|
293
|
+
code_verifier: oauth.verifier
|
|
294
|
+
})
|
|
295
|
+
});
|
|
296
|
+
if (!res.ok) return back("verification_failed");
|
|
297
|
+
({ id_token: idToken } = await res.json());
|
|
298
|
+
} catch {
|
|
299
|
+
return back("verification_failed");
|
|
300
|
+
}
|
|
301
|
+
if (typeof idToken !== "string") return back("verification_failed");
|
|
302
|
+
const result = await verifyGoogleIdToken(idToken, {
|
|
303
|
+
clientId: google.clientId,
|
|
304
|
+
nonce: oauth.nonce,
|
|
305
|
+
keys: config.jwksResolver
|
|
306
|
+
});
|
|
307
|
+
if (!result.ok) return back(result.error);
|
|
308
|
+
const resolved = await resolveUser(result.profile, typeof oauth.locale === "string" ? oauth.locale : void 0);
|
|
309
|
+
if (!resolved.ok) return back(resolved.error);
|
|
310
|
+
const step = await ctx.secondStep(c, resolved.user, ["google"], "google", result.profile);
|
|
311
|
+
if ("disabled" in step) return back("method_disabled");
|
|
312
|
+
if ("next" in step) return back(void 0, step.next);
|
|
313
|
+
return back();
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/app.ts
|
|
318
|
+
import { Hono } from "hono";
|
|
319
|
+
import { deleteCookie as deleteCookie3, getCookie as getCookie3, setCookie as setCookie3 } from "hono/cookie";
|
|
320
|
+
import { cors } from "hono/cors";
|
|
321
|
+
|
|
322
|
+
// src/routes/emails.ts
|
|
323
|
+
var MAIL_INTERVAL_MS = 60 * 1e3;
|
|
324
|
+
var VERIFY_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
325
|
+
var RESET_TTL_MS = 30 * 60 * 1e3;
|
|
326
|
+
var VERIFY_LINK_PARAM = "madauth_verify";
|
|
327
|
+
var RESET_LINK_PARAM = "madauth_reset";
|
|
328
|
+
function createEmails(ctx, users, webhook) {
|
|
329
|
+
const sendEmail = async (user, type, data) => {
|
|
330
|
+
if (Date.now() - user.lastMailAt < MAIL_INTERVAL_MS) return true;
|
|
331
|
+
const result = await webhook.call(type, { to: user.email, user: { id: user.id, name: user.name ?? void 0 }, ...data }, WEBHOOK_TIMEOUT_MS);
|
|
332
|
+
if (!result.ok) {
|
|
333
|
+
console.error(`[madauth] Webhook "${type}" for ${user.email} failed: ${result.reason}`);
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
await users.updateUser(user.id, { lastMailAt: Date.now() });
|
|
337
|
+
return true;
|
|
338
|
+
};
|
|
339
|
+
return {
|
|
340
|
+
sendEmail,
|
|
341
|
+
async sendLinkEmail(user, purpose, target, locale) {
|
|
342
|
+
if (Date.now() - user.lastMailAt < MAIL_INTERVAL_MS) return true;
|
|
343
|
+
const ttl = purpose === "verify" ? VERIFY_TTL_MS : RESET_TTL_MS;
|
|
344
|
+
const { token, code } = await users.issueVerification(user.id, purpose, ttl);
|
|
345
|
+
const link = new URL(target);
|
|
346
|
+
link.hash = `${purpose === "verify" ? VERIFY_LINK_PARAM : RESET_LINK_PARAM}=${token}`;
|
|
347
|
+
return sendEmail(user, purpose === "verify" ? "email.verify" : "email.reset", {
|
|
348
|
+
link: link.href,
|
|
349
|
+
code,
|
|
350
|
+
expiresAt: Date.now() + ttl,
|
|
351
|
+
site: target.host,
|
|
352
|
+
locale
|
|
353
|
+
});
|
|
354
|
+
},
|
|
355
|
+
async sendAccountEmail(user, type, target, locale) {
|
|
356
|
+
if (!webhook.wants(type)) return true;
|
|
357
|
+
const methods = await users.signInMethods(user.id, await ctx.settings.methods());
|
|
358
|
+
return sendEmail(user, type, { link: target.href, site: target.host, locale, methods });
|
|
359
|
+
},
|
|
360
|
+
async consume(data, purpose) {
|
|
361
|
+
if (typeof data.token === "string" && data.token) {
|
|
362
|
+
return { userId: await users.consumeLinkToken(data.token, purpose), via: "link" };
|
|
363
|
+
}
|
|
364
|
+
if (isValidEmail(data.email) && typeof data.code === "string") {
|
|
365
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
366
|
+
if (!user) return { userId: null, via: "code" };
|
|
367
|
+
return { ...await users.consumeCode(user, purpose, data.code.replace(/\s/g, "")), via: "code" };
|
|
368
|
+
}
|
|
369
|
+
return { userId: null, via: "code" };
|
|
370
|
+
},
|
|
371
|
+
invalidVerification(c, { via, locked }) {
|
|
372
|
+
if (locked) {
|
|
373
|
+
return error(c, 429, "codes_locked", "Too many wrong codes. Please ask for a new e-mail and use the link in it.");
|
|
374
|
+
}
|
|
375
|
+
return via === "link" ? error(c, 400, "link_invalid", "The link is invalid, expired or was already used.") : error(c, 400, "code_invalid", "The code is wrong or expired.");
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// src/routes/email.ts
|
|
381
|
+
function emailRoutes(app, ctx, users, webhook) {
|
|
382
|
+
const emails = createEmails(ctx, users, webhook);
|
|
383
|
+
const signUpMethod = async (userId) => await users.passwordAccount(userId) ? "password" : "totp";
|
|
384
|
+
app.post("/auth/email/send-verification", async (c) => {
|
|
385
|
+
const data = await body(c);
|
|
386
|
+
const target = redirectTarget(ctx, c, data.redirectTo);
|
|
387
|
+
if (target instanceof Response) return target;
|
|
388
|
+
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
389
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
390
|
+
if (user && !user.emailVerified && await ctx.enabled(c, await signUpMethod(user.id))) {
|
|
391
|
+
if (!await emails.sendLinkEmail(user, "verify", target, localeOf(data.locale))) return unavailable(c);
|
|
392
|
+
}
|
|
393
|
+
return accepted(c);
|
|
394
|
+
});
|
|
395
|
+
const disabled = (c) => error(c, 403, "method_disabled", "This way of signing in is switched off.");
|
|
396
|
+
app.post("/auth/email/verify", async (c) => {
|
|
397
|
+
const data = await body(c);
|
|
398
|
+
const waiting = typeof data.token === "string" && data.token ? await users.peekLinkToken(data.token, "verify") : isValidEmail(data.email) ? (await users.findByEmail(normalizeEmail(data.email)))?.id ?? null : null;
|
|
399
|
+
if (waiting && !await ctx.enabled(c, await signUpMethod(waiting))) return disabled(c);
|
|
400
|
+
const consumed = await emails.consume(data, "verify");
|
|
401
|
+
const { userId, via } = consumed;
|
|
402
|
+
const user = userId ? await users.findById(userId) : null;
|
|
403
|
+
if (!user) return emails.invalidVerification(c, consumed);
|
|
404
|
+
const method = await signUpMethod(user.id);
|
|
405
|
+
if (!await ctx.enabled(c, method)) return disabled(c);
|
|
406
|
+
await users.updateUser(user.id, { emailVerified: true, wrongCodes: 0 });
|
|
407
|
+
const verified = { ...user, emailVerified: true, wrongCodes: 0 };
|
|
408
|
+
await ctx.emit("email.verified", { user: toMadauthUser(verified), via });
|
|
409
|
+
return signInAnswer(c, await ctx.secondStep(c, verified, method === "password" ? ["pwd"] : [], method));
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// src/routes/lockout.ts
|
|
414
|
+
var FREE_ATTEMPTS = 5;
|
|
415
|
+
var MAX_LOCK_MS = 15 * 60 * 1e3;
|
|
416
|
+
async function countSignInAttempt(c, users, account, now = Date.now()) {
|
|
417
|
+
const tooMany = (message) => c.json({ error: "too_many_attempts", message }, 429);
|
|
418
|
+
if (account.lockedUntil > now) {
|
|
419
|
+
const seconds = Math.ceil((account.lockedUntil - now) / 1e3);
|
|
420
|
+
return tooMany(`Too many failed attempts. Try again in ${seconds} seconds.`);
|
|
421
|
+
}
|
|
422
|
+
const failed = account.failedAttempts + 1;
|
|
423
|
+
const lockedUntil = failed >= FREE_ATTEMPTS ? now + Math.min(2 ** (failed - FREE_ATTEMPTS) * 1e3, MAX_LOCK_MS) : 0;
|
|
424
|
+
if (!await users.countAttempt(account, { failedAttempts: failed, lockedUntil })) {
|
|
425
|
+
return tooMany("Too many attempts at once. Please try again.");
|
|
426
|
+
}
|
|
427
|
+
return null;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// src/routes/password.ts
|
|
431
|
+
function passwordRoutes(app, ctx, password, users, webhook) {
|
|
432
|
+
const { minLength } = password;
|
|
433
|
+
const emails = createEmails(ctx, users, webhook);
|
|
434
|
+
app.use("/auth/password/*", async (c, next) => {
|
|
435
|
+
if (!await ctx.enabled(c, "password")) return error(c, 403, "method_disabled", "E-mail & password sign-in is switched off.");
|
|
436
|
+
await next();
|
|
437
|
+
});
|
|
438
|
+
app.post("/auth/password/signin", async (c) => {
|
|
439
|
+
const data = await body(c);
|
|
440
|
+
const wrong = () => error(c, 401, "invalid_credentials", "E-mail or password is wrong.");
|
|
441
|
+
const pw = typeof data.password === "string" ? data.password : "";
|
|
442
|
+
if (!isValidEmail(data.email) || !pw || pw.length > MAX_PASSWORD_LENGTH * 4) return wrong();
|
|
443
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
444
|
+
const account = user ? await users.passwordAccount(user.id) : null;
|
|
445
|
+
if (!user || !account?.secret) {
|
|
446
|
+
await verifyAgainstDummy(pw);
|
|
447
|
+
return wrong();
|
|
448
|
+
}
|
|
449
|
+
const refused = await countSignInAttempt(c, users, account);
|
|
450
|
+
if (refused) return refused;
|
|
451
|
+
const { ok, needsRehash } = await verifyPassword(pw, account.secret);
|
|
452
|
+
if (!ok) return wrong();
|
|
453
|
+
await users.updateAccount(account.id, {
|
|
454
|
+
failedAttempts: 0,
|
|
455
|
+
lockedUntil: 0,
|
|
456
|
+
...needsRehash ? { secret: await hashPassword(pw) } : {}
|
|
457
|
+
});
|
|
458
|
+
if (!user.emailVerified) {
|
|
459
|
+
return error(c, 403, "email_unverified", "Please confirm your e-mail address first. We can send the e-mail again.");
|
|
460
|
+
}
|
|
461
|
+
return signInAnswer(c, await ctx.secondStep(c, user, ["pwd"], "password"));
|
|
462
|
+
});
|
|
463
|
+
app.post("/auth/password/signup", async (c) => {
|
|
464
|
+
const data = await body(c);
|
|
465
|
+
const target = redirectTarget(ctx, c, data.redirectTo);
|
|
466
|
+
if (target instanceof Response) return target;
|
|
467
|
+
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
468
|
+
const policy = checkPasswordPolicy(data.password, minLength);
|
|
469
|
+
if (policy) return error(c, 400, "weak_password", policy);
|
|
470
|
+
const name = nameOf(data.name);
|
|
471
|
+
const email = data.email.trim();
|
|
472
|
+
const locale = localeOf(data.locale);
|
|
473
|
+
const check = await ctx.checkSignup({ email, name: name ?? void 0, locale, method: "password" });
|
|
474
|
+
if (!check.ok) return check.reason === "rejected" ? error(c, 403, "signup_rejected", check.message) : unavailable(c);
|
|
475
|
+
const passwordHash = await hashPassword(data.password);
|
|
476
|
+
const existing = await users.findByEmail(normalizeEmail(email));
|
|
477
|
+
if (existing?.emailVerified && await users.hasAccounts(existing.id)) {
|
|
478
|
+
return await emails.sendAccountEmail(existing, "email.already_registered", target, locale) ? accepted(c) : unavailable(c);
|
|
479
|
+
}
|
|
480
|
+
if (existing) {
|
|
481
|
+
if (Date.now() - existing.lastMailAt < MAIL_INTERVAL_MS) return accepted(c);
|
|
482
|
+
const account = await users.passwordAccount(existing.id);
|
|
483
|
+
if (account) await users.updateAccount(account.id, { secret: passwordHash, failedAttempts: 0, lockedUntil: 0 });
|
|
484
|
+
else await users.linkAccount(existing.id, { key: passwordAccountKey(existing.id), secret: passwordHash });
|
|
485
|
+
await users.updateUser(existing.id, { name });
|
|
486
|
+
return await emails.sendLinkEmail({ ...existing, name }, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
487
|
+
}
|
|
488
|
+
const user = await users.createUser({
|
|
489
|
+
email,
|
|
490
|
+
emailNormalized: normalizeEmail(email),
|
|
491
|
+
name,
|
|
492
|
+
emailVerified: false,
|
|
493
|
+
account: (userId) => ({ key: passwordAccountKey(userId), secret: passwordHash })
|
|
494
|
+
});
|
|
495
|
+
if (!user) return accepted(c);
|
|
496
|
+
await ctx.emit("user.created", { user: toMadauthUser(user), method: "password" });
|
|
497
|
+
return await emails.sendLinkEmail(user, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
498
|
+
});
|
|
499
|
+
app.post("/auth/password/send-reset", async (c) => {
|
|
500
|
+
const data = await body(c);
|
|
501
|
+
const target = redirectTarget(ctx, c, data.redirectTo);
|
|
502
|
+
if (target instanceof Response) return target;
|
|
503
|
+
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
504
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
505
|
+
const locale = localeOf(data.locale);
|
|
506
|
+
if (user && await users.passwordAccount(user.id)) {
|
|
507
|
+
if (!await emails.sendLinkEmail(user, "reset", target, locale)) return unavailable(c);
|
|
508
|
+
} else if (user) {
|
|
509
|
+
if (!await emails.sendAccountEmail(user, "email.no_password", target, locale)) return unavailable(c);
|
|
510
|
+
}
|
|
511
|
+
return accepted(c);
|
|
512
|
+
});
|
|
513
|
+
app.post("/auth/password/reset", async (c) => {
|
|
514
|
+
const data = await body(c);
|
|
515
|
+
const policy = checkPasswordPolicy(data.password, minLength);
|
|
516
|
+
if (policy) return error(c, 400, "weak_password", policy);
|
|
517
|
+
const consumed = await emails.consume(data, "reset");
|
|
518
|
+
const user = consumed.userId ? await users.findById(consumed.userId) : null;
|
|
519
|
+
const account = user ? await users.passwordAccount(user.id) : null;
|
|
520
|
+
if (!user || !account) return emails.invalidVerification(c, consumed);
|
|
521
|
+
const secret = await hashPassword(data.password);
|
|
522
|
+
if (!await users.updateAccount(account.id, { secret, failedAttempts: 0, lockedUntil: 0 })) return emails.invalidVerification(c, consumed);
|
|
523
|
+
const sessionVersion = user.sessionVersion + 1;
|
|
524
|
+
await users.updateUser(user.id, { emailVerified: true, sessionVersion, wrongCodes: 0 });
|
|
525
|
+
await users.clearVerifications(user.id);
|
|
526
|
+
const reset = { ...user, emailVerified: true, sessionVersion, wrongCodes: 0 };
|
|
527
|
+
await ctx.emit("email.password_reset", { user: toMadauthUser(reset) });
|
|
528
|
+
return signInAnswer(c, await ctx.secondStep(c, reset, ["pwd"], "password"));
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// src/routes/totp.ts
|
|
533
|
+
import { deleteCookie as deleteCookie2, getCookie as getCookie2, setCookie as setCookie2 } from "hono/cookie";
|
|
534
|
+
|
|
535
|
+
// src/totp.ts
|
|
536
|
+
import { createCipheriv, createDecipheriv, createHmac, hkdfSync, randomBytes, randomInt } from "crypto";
|
|
537
|
+
var TOTP_STEP_SECONDS = 30;
|
|
538
|
+
var TOTP_DIGITS = 6;
|
|
539
|
+
var TOTP_WINDOW = 1;
|
|
540
|
+
var RECOVERY_CODES = 10;
|
|
541
|
+
var SECRET_BYTES = 20;
|
|
542
|
+
var BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
543
|
+
var RECOVERY_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
|
|
544
|
+
var RECOVERY_CODE_LENGTH = 10;
|
|
545
|
+
var ENCRYPTION_VERSION = "v1";
|
|
546
|
+
var IV_BYTES = 12;
|
|
547
|
+
var TAG_BYTES = 16;
|
|
548
|
+
function base32Encode(bytes) {
|
|
549
|
+
let bits = 0;
|
|
550
|
+
let value = 0;
|
|
551
|
+
let out = "";
|
|
552
|
+
for (const byte of bytes) {
|
|
553
|
+
value = (value << 8 | byte) & 65535;
|
|
554
|
+
bits += 8;
|
|
555
|
+
while (bits >= 5) {
|
|
556
|
+
out += BASE32[value >>> bits - 5 & 31];
|
|
557
|
+
bits -= 5;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (bits > 0) out += BASE32[value << 5 - bits & 31];
|
|
561
|
+
return out;
|
|
562
|
+
}
|
|
563
|
+
function hotp(secret, counter, digits = TOTP_DIGITS) {
|
|
564
|
+
const message = Buffer.alloc(8);
|
|
565
|
+
message.writeBigUInt64BE(BigInt(counter));
|
|
566
|
+
const digest = createHmac("sha1", secret).update(message).digest();
|
|
567
|
+
const offset = digest[digest.length - 1] & 15;
|
|
568
|
+
const binary = (digest[offset] & 127) << 24 | digest[offset + 1] << 16 | digest[offset + 2] << 8 | digest[offset + 3];
|
|
569
|
+
return (binary % 10 ** digits).toString().padStart(digits, "0");
|
|
570
|
+
}
|
|
571
|
+
function stepOf(nowMs) {
|
|
572
|
+
return Math.floor(nowMs / 1e3 / TOTP_STEP_SECONDS);
|
|
573
|
+
}
|
|
574
|
+
function totp(secret, step, digits = TOTP_DIGITS) {
|
|
575
|
+
return hotp(secret, step, digits);
|
|
576
|
+
}
|
|
577
|
+
function verifyTotp(secret, code, nowMs, window = TOTP_WINDOW) {
|
|
578
|
+
const given = code.replace(/\s/g, "");
|
|
579
|
+
if (!new RegExp(`^\\d{${TOTP_DIGITS}}$`).test(given)) return null;
|
|
580
|
+
const now = stepOf(nowMs);
|
|
581
|
+
let found = null;
|
|
582
|
+
for (let step = now - window; step <= now + window; step++) {
|
|
583
|
+
if (safeEqual(totp(secret, step), given) && found === null) found = step;
|
|
584
|
+
}
|
|
585
|
+
return found;
|
|
586
|
+
}
|
|
587
|
+
function generateTotpSecret() {
|
|
588
|
+
return randomBytes(SECRET_BYTES);
|
|
589
|
+
}
|
|
590
|
+
function otpauthUri(options) {
|
|
591
|
+
const issuer = encodeURIComponent(options.issuer);
|
|
592
|
+
const account = encodeURIComponent(options.account);
|
|
593
|
+
const secret = base32Encode(options.secret);
|
|
594
|
+
return `otpauth://totp/${issuer}:${account}?secret=${secret}&issuer=${issuer}&algorithm=SHA1&digits=${TOTP_DIGITS}&period=${TOTP_STEP_SECONDS}`;
|
|
595
|
+
}
|
|
596
|
+
function deriveTotpKey(signingKeyD) {
|
|
597
|
+
return Buffer.from(hkdfSync("sha256", Buffer.from(signingKeyD, "base64url"), "", "madauth totp secret", 32));
|
|
598
|
+
}
|
|
599
|
+
function encryptSecret(key, secret) {
|
|
600
|
+
const iv = randomBytes(IV_BYTES);
|
|
601
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
602
|
+
const encrypted = Buffer.concat([cipher.update(secret), cipher.final()]);
|
|
603
|
+
const parts = [iv, encrypted, cipher.getAuthTag()].map((part) => part.toString("base64url"));
|
|
604
|
+
return [ENCRYPTION_VERSION, ...parts].join(".");
|
|
605
|
+
}
|
|
606
|
+
function decryptSecret(key, stored) {
|
|
607
|
+
const [version, iv, encrypted, tag, ...rest] = stored.split(".");
|
|
608
|
+
if (version !== ENCRYPTION_VERSION || !iv || !encrypted || !tag || rest.length) return null;
|
|
609
|
+
const ivBytes = Buffer.from(iv, "base64url");
|
|
610
|
+
const tagBytes = Buffer.from(tag, "base64url");
|
|
611
|
+
if (ivBytes.length !== IV_BYTES || tagBytes.length !== TAG_BYTES) return null;
|
|
612
|
+
try {
|
|
613
|
+
const decipher = createDecipheriv("aes-256-gcm", key, ivBytes);
|
|
614
|
+
decipher.setAuthTag(tagBytes);
|
|
615
|
+
return Buffer.concat([decipher.update(Buffer.from(encrypted, "base64url")), decipher.final()]);
|
|
616
|
+
} catch {
|
|
617
|
+
return null;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
function generateRecoveryCodes() {
|
|
621
|
+
const codes = /* @__PURE__ */ new Set();
|
|
622
|
+
while (codes.size < RECOVERY_CODES) {
|
|
623
|
+
let code = "";
|
|
624
|
+
for (let i = 0; i < RECOVERY_CODE_LENGTH; i++) code += RECOVERY_ALPHABET[randomInt(RECOVERY_ALPHABET.length)];
|
|
625
|
+
codes.add(`${code.slice(0, 5)}-${code.slice(5)}`);
|
|
626
|
+
}
|
|
627
|
+
return [...codes];
|
|
628
|
+
}
|
|
629
|
+
function normalizeRecoveryCode(text) {
|
|
630
|
+
if (typeof text !== "string") return null;
|
|
631
|
+
const code = text.toLowerCase().replace(/[\s-]/g, "");
|
|
632
|
+
return code.length === RECOVERY_CODE_LENGTH && [...code].every((char) => RECOVERY_ALPHABET.includes(char)) ? code : null;
|
|
633
|
+
}
|
|
634
|
+
function hashRecoveryCode(codeKey, code) {
|
|
635
|
+
return hashCode(codeKey, `recovery:${code}`);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// src/routes/totp.ts
|
|
639
|
+
var CHALLENGE_COOKIE = "madauth_challenge";
|
|
640
|
+
var CHALLENGE_TYP = "madauth-challenge+jwt";
|
|
641
|
+
var CHALLENGE_TTL = 10 * 60;
|
|
642
|
+
var SETUP_COOKIE = "madauth_totp_setup";
|
|
643
|
+
var SETUP_TYP = "madauth-totp-setup+jwt";
|
|
644
|
+
var SETUP_TTL = 10 * 60;
|
|
645
|
+
var COOKIE_PATH = "/auth/totp";
|
|
646
|
+
var cookieOptions = (secure) => ({ path: COOKIE_PATH, httpOnly: true, secure, sameSite: "Strict" });
|
|
647
|
+
async function setChallenge(c, ctx, challenge) {
|
|
648
|
+
const token = await signToken(await ctx.keys, ctx.config.issuer, CHALLENGE_TYP, { ...challenge }, CHALLENGE_TTL);
|
|
649
|
+
setCookie2(c, CHALLENGE_COOKIE, token, { ...cookieOptions(ctx.secure), maxAge: CHALLENGE_TTL });
|
|
650
|
+
}
|
|
651
|
+
function clearChallenge(c, secure) {
|
|
652
|
+
deleteCookie2(c, CHALLENGE_COOKIE, cookieOptions(secure));
|
|
653
|
+
}
|
|
654
|
+
async function readChallenge(c, ctx, next) {
|
|
655
|
+
const claims = await readToken(await ctx.keys, ctx.config.issuer, CHALLENGE_TYP, getCookie2(c, CHALLENGE_COOKIE));
|
|
656
|
+
return claims && claims.next === next && typeof claims.sub === "string" && Array.isArray(claims.amr) ? claims : null;
|
|
657
|
+
}
|
|
658
|
+
async function checkCode(c, ctx, keys, user, account, data, wrong = () => error(c, 401, "code_invalid", "The code is wrong or was already used.")) {
|
|
659
|
+
const { users } = ctx;
|
|
660
|
+
const refused = await countSignInAttempt(c, users, account);
|
|
661
|
+
if (refused) return refused;
|
|
662
|
+
if (typeof data.recoveryCode === "string") {
|
|
663
|
+
const code = normalizeRecoveryCode(data.recoveryCode);
|
|
664
|
+
if (!code || !await users.consumeRecoveryCode(account, hashRecoveryCode(keys.codeKey, code))) return wrong();
|
|
665
|
+
await users.updateAccount(account.id, { failedAttempts: 0, lockedUntil: 0 });
|
|
666
|
+
const remaining = await users.countRecoveryCodes(account);
|
|
667
|
+
await ctx.emit("totp.recovery_code_used", { user: toMadauthUser(user), remaining });
|
|
668
|
+
return "recovery_code";
|
|
669
|
+
}
|
|
670
|
+
if (typeof data.code !== "string" || !account.secret) return wrong();
|
|
671
|
+
const secret = decryptSecret(keys.totpKey, account.secret);
|
|
672
|
+
if (!secret) {
|
|
673
|
+
console.error(`[madauth] The authenticator secret of user ${user.id} can't be read: was MADAUTH_SIGNING_KEY changed?`);
|
|
674
|
+
return wrong();
|
|
675
|
+
}
|
|
676
|
+
const step = verifyTotp(secret, data.code, Date.now(), TOTP_WINDOW);
|
|
677
|
+
if (step === null || step <= (account.lastUsedStep ?? 0) || !await users.useTotpStep(account, step)) return wrong();
|
|
678
|
+
return "totp";
|
|
679
|
+
}
|
|
680
|
+
function totpRoutes(app, ctx, keys) {
|
|
681
|
+
const { config, secure, users } = ctx;
|
|
682
|
+
const { issuer } = config;
|
|
683
|
+
const cookie = cookieOptions(secure);
|
|
684
|
+
const methodsNow = (c) => ctx.methods(c);
|
|
685
|
+
app.use(`${COOKIE_PATH}/*`, async (c, next) => {
|
|
686
|
+
if (!authenticatorOn(ctx.configured, await methodsNow(c))) {
|
|
687
|
+
return error(c, 403, "method_disabled", "The authenticator app is switched off.");
|
|
688
|
+
}
|
|
689
|
+
await next();
|
|
690
|
+
});
|
|
691
|
+
const standalone = async (c) => isOn("totp", ctx.configured, await methodsNow(c));
|
|
692
|
+
const notStandalone = (c) => error(c, 403, "method_disabled", "Signing in with the authenticator app alone is switched off.");
|
|
693
|
+
const methodStillOn = async (c, challenge) => isOn(challenge.method, ctx.configured, await methodsNow(c));
|
|
694
|
+
const methodOff = (c) => error(c, 403, "method_disabled", "This way of signing in is switched off.");
|
|
695
|
+
const signedIn = async (c) => {
|
|
696
|
+
const user = await ctx.currentUser(c);
|
|
697
|
+
return user ? users.findById(user.id) : null;
|
|
698
|
+
};
|
|
699
|
+
const whoSetsUp = async (c) => {
|
|
700
|
+
const challenge = await readChallenge(c, ctx, "totp-setup");
|
|
701
|
+
const waiting = challenge ? await users.findById(challenge.sub) : null;
|
|
702
|
+
if (challenge && waiting && waiting.sessionVersion === challenge.sv) return { user: waiting, challenge };
|
|
703
|
+
const user = await signedIn(c);
|
|
704
|
+
return user ? { user, challenge: null } : null;
|
|
705
|
+
};
|
|
706
|
+
const newRecoveryCodes = () => {
|
|
707
|
+
const recoveryCodes = generateRecoveryCodes();
|
|
708
|
+
return { recoveryCodes, hashes: recoveryCodes.map((code) => hashRecoveryCode(keys.codeKey, normalizeRecoveryCode(code))) };
|
|
709
|
+
};
|
|
710
|
+
const issuerLabel = (c) => {
|
|
711
|
+
if (config.totpIssuer) return config.totpIssuer;
|
|
712
|
+
const origin = c.req.header("origin");
|
|
713
|
+
return URL.canParse(origin ?? "") ? new URL(origin).hostname : new URL(issuer).hostname;
|
|
714
|
+
};
|
|
715
|
+
const finishSignIn = async (c, user, challenge, via) => {
|
|
716
|
+
const result = await ctx.startSession(c, toMadauthUser(user, challenge.profile), [...challenge.amr, "otp"], { sv: user.sessionVersion });
|
|
717
|
+
await ctx.emit("user.signed_in", { user: result, method: challenge.method, ...challenge.amr.length ? { secondFactor: via } : {} });
|
|
718
|
+
return result;
|
|
719
|
+
};
|
|
720
|
+
app.post(`${COOKIE_PATH}/setup`, async (c) => {
|
|
721
|
+
const who = await whoSetsUp(c);
|
|
722
|
+
if (!who) return noSession(c);
|
|
723
|
+
if (who.challenge && !await methodStillOn(c, who.challenge)) return methodOff(c);
|
|
724
|
+
const existing = await users.totpAccount(who.user.id);
|
|
725
|
+
let approved;
|
|
726
|
+
if (existing) {
|
|
727
|
+
const previous = await readToken(await ctx.keys, issuer, SETUP_TYP, getCookie2(c, SETUP_COOKIE));
|
|
728
|
+
const holds = previous?.sub === who.user.id && typeof previous.approved === "number" && Date.now() - previous.approved < SETUP_TTL * 1e3;
|
|
729
|
+
if (holds) {
|
|
730
|
+
approved = previous.approved;
|
|
731
|
+
} else {
|
|
732
|
+
const data = await body(c);
|
|
733
|
+
if (data.code === void 0 && data.recoveryCode === void 0) {
|
|
734
|
+
return error(c, 401, "code_required", "Enter a code from your current authenticator app (or a recovery code) to replace it.");
|
|
735
|
+
}
|
|
736
|
+
const via = await checkCode(c, ctx, keys, who.user, existing, data);
|
|
737
|
+
if (via instanceof Response) return via;
|
|
738
|
+
approved = Date.now();
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
const secret = generateTotpSecret();
|
|
742
|
+
const claims = {
|
|
743
|
+
sub: who.user.id,
|
|
744
|
+
setup: newId("tsu"),
|
|
745
|
+
secret: encryptSecret(keys.totpKey, secret),
|
|
746
|
+
...existing ? { replaces: existing.setupId } : {},
|
|
747
|
+
...approved ? { approved } : {}
|
|
748
|
+
};
|
|
749
|
+
const token = await signToken(await ctx.keys, issuer, SETUP_TYP, claims, SETUP_TTL);
|
|
750
|
+
setCookie2(c, SETUP_COOKIE, token, { ...cookie, maxAge: SETUP_TTL });
|
|
751
|
+
return c.json({ secret: base32Encode(secret), uri: otpauthUri({ issuer: issuerLabel(c), account: who.user.email, secret }) });
|
|
752
|
+
});
|
|
753
|
+
app.post(`${COOKIE_PATH}/confirm`, async (c) => {
|
|
754
|
+
const who = await whoSetsUp(c);
|
|
755
|
+
if (!who) return noSession(c);
|
|
756
|
+
const { user, challenge } = who;
|
|
757
|
+
if (challenge && !await methodStillOn(c, challenge)) return methodOff(c);
|
|
758
|
+
const data = await body(c);
|
|
759
|
+
const setup = await readToken(await ctx.keys, issuer, SETUP_TYP, getCookie2(c, SETUP_COOKIE));
|
|
760
|
+
const secret = setup && setup.sub === user.id && typeof setup.secret === "string" && typeof setup.setup === "string" ? decryptSecret(keys.totpKey, setup.secret) : null;
|
|
761
|
+
if (!setup || !secret) return error(c, 400, "setup_expired", "The setup has expired or was started in another browser. Please start again.");
|
|
762
|
+
const step = typeof data.code === "string" ? verifyTotp(secret, data.code, Date.now(), TOTP_WINDOW) : null;
|
|
763
|
+
if (step === null) return error(c, 400, "code_invalid", "The code is wrong. Enter the current code from the app.");
|
|
764
|
+
const { recoveryCodes, hashes } = newRecoveryCodes();
|
|
765
|
+
await users.addRecoveryCodes(user.id, setup.setup, hashes);
|
|
766
|
+
const patch = { secret: setup.secret, setupId: setup.setup, failedAttempts: 0, lockedUntil: 0, lastUsedStep: step };
|
|
767
|
+
const current = setup.replaces === void 0 ? null : await users.totpAccount(user.id);
|
|
768
|
+
const written = setup.replaces === void 0 ? !!await users.linkAccount(user.id, { key: totpAccountKey(user.id), ...patch }) : !!current && await users.confirmTotpSetup(current.id, setup.replaces, patch);
|
|
769
|
+
if (!written) {
|
|
770
|
+
await users.clearRecoveryCodes(user.id, { only: setup.setup });
|
|
771
|
+
deleteCookie2(c, SETUP_COOKIE, cookie);
|
|
772
|
+
return error(c, 400, "setup_expired", "Your authenticator app was set up or removed elsewhere meanwhile. Please start again.");
|
|
773
|
+
}
|
|
774
|
+
await users.clearRecoveryCodes(user.id, { except: setup.setup });
|
|
775
|
+
deleteCookie2(c, SETUP_COOKIE, cookie);
|
|
776
|
+
await ctx.emit("totp.enabled", { user: toMadauthUser(user) });
|
|
777
|
+
if (!challenge) return c.json({ recoveryCodes });
|
|
778
|
+
const result = await finishSignIn(c, user, challenge, "totp");
|
|
779
|
+
return c.json({ user: result, recoveryCodes });
|
|
780
|
+
});
|
|
781
|
+
app.post(`${COOKIE_PATH}/verify`, async (c) => {
|
|
782
|
+
const expired = () => error(c, 401, "challenge_expired", "The sign-in has expired. Please sign in again.");
|
|
783
|
+
const challenge = await readChallenge(c, ctx, "totp");
|
|
784
|
+
if (!challenge) return expired();
|
|
785
|
+
if (!await methodStillOn(c, challenge)) return methodOff(c);
|
|
786
|
+
const user = await users.findById(challenge.sub);
|
|
787
|
+
const account = user && user.sessionVersion === challenge.sv ? await users.totpAccount(user.id) : null;
|
|
788
|
+
if (!user || !account) return expired();
|
|
789
|
+
const via = await checkCode(c, ctx, keys, user, account, await body(c));
|
|
790
|
+
if (via instanceof Response) return via;
|
|
791
|
+
return c.json({ user: await finishSignIn(c, user, challenge, via) });
|
|
792
|
+
});
|
|
793
|
+
app.post(`${COOKIE_PATH}/signin`, async (c) => {
|
|
794
|
+
if (!await standalone(c)) return notStandalone(c);
|
|
795
|
+
const data = await body(c);
|
|
796
|
+
const wrong = () => error(c, 401, "invalid_credentials", "E-mail or code is wrong.");
|
|
797
|
+
if (!isValidEmail(data.email)) return wrong();
|
|
798
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
799
|
+
const account = user ? await users.totpAccount(user.id) : null;
|
|
800
|
+
if (!user || !user.emailVerified || !account?.secret) return wrong();
|
|
801
|
+
const via = await checkCode(c, ctx, keys, user, account, data, wrong);
|
|
802
|
+
if (via instanceof Response) return via;
|
|
803
|
+
const result = await ctx.startSession(c, toMadauthUser(user), ["otp"], { sv: user.sessionVersion });
|
|
804
|
+
await ctx.emit("user.signed_in", { user: result, method: "totp" });
|
|
805
|
+
return c.json({ user: result });
|
|
806
|
+
});
|
|
807
|
+
app.post(`${COOKIE_PATH}/remove`, async (c) => {
|
|
808
|
+
const user = await signedIn(c);
|
|
809
|
+
if (!user) return noSession(c);
|
|
810
|
+
const methods = await methodsNow(c);
|
|
811
|
+
const required = METHODS_WITH_SECOND_FACTOR.filter((method) => isOn(method, ctx.configured, methods) && policyOf(method, methods) === "required");
|
|
812
|
+
if (required.length) {
|
|
813
|
+
const names = required.map((method) => method === "google" ? "Google" : "e-mail & password");
|
|
814
|
+
return error(c, 403, "required_by_policy", `Signing in with ${names.join(" and ")} requires the authenticator app, so it can't be removed.`);
|
|
815
|
+
}
|
|
816
|
+
const account = await users.totpAccount(user.id);
|
|
817
|
+
if (!account) return c.json({});
|
|
818
|
+
if (!(await users.signInMethods(user.id, methods)).some((method) => method !== "totp" && isOn(method, ctx.configured, methods))) {
|
|
819
|
+
return error(c, 403, "only_method", "The authenticator app is the only way you sign in, so it can't be removed. Delete your account instead.");
|
|
820
|
+
}
|
|
821
|
+
const via = await checkCode(c, ctx, keys, user, account, await body(c));
|
|
822
|
+
if (via instanceof Response) return via;
|
|
823
|
+
await users.removeTotp(user.id);
|
|
824
|
+
await ctx.emit("totp.disabled", { user: toMadauthUser(user) });
|
|
825
|
+
return c.json({});
|
|
826
|
+
});
|
|
827
|
+
app.post(`${COOKIE_PATH}/recovery-codes`, async (c) => {
|
|
828
|
+
const user = await signedIn(c);
|
|
829
|
+
if (!user) return noSession(c);
|
|
830
|
+
const account = await users.totpAccount(user.id);
|
|
831
|
+
if (!account) return error(c, 400, "no_authenticator", "No authenticator app is set up.");
|
|
832
|
+
const via = await checkCode(c, ctx, keys, user, account, await body(c));
|
|
833
|
+
if (via instanceof Response) return via;
|
|
834
|
+
const { recoveryCodes, hashes } = newRecoveryCodes();
|
|
835
|
+
await users.replaceRecoveryCodes(account, hashes);
|
|
836
|
+
return c.json({ recoveryCodes });
|
|
837
|
+
});
|
|
838
|
+
app.get(`${COOKIE_PATH}/status`, async (c) => {
|
|
839
|
+
const user = await signedIn(c);
|
|
840
|
+
if (!user) return noSession(c);
|
|
841
|
+
const account = await users.totpAccount(user.id);
|
|
842
|
+
return c.json({ enabled: !!account, recoveryCodesLeft: account ? await users.countRecoveryCodes(account) : 0 });
|
|
843
|
+
});
|
|
844
|
+
if (ctx.webhook && ctx.emailVerification) {
|
|
845
|
+
const emails = createEmails(ctx, users, ctx.webhook);
|
|
846
|
+
app.post(`${COOKIE_PATH}/signup`, async (c) => {
|
|
847
|
+
if (!await standalone(c)) return notStandalone(c);
|
|
848
|
+
const data = await body(c);
|
|
849
|
+
const target = redirectTarget(ctx, c, data.redirectTo);
|
|
850
|
+
if (target instanceof Response) return target;
|
|
851
|
+
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
852
|
+
const name = nameOf(data.name);
|
|
853
|
+
const email = data.email.trim();
|
|
854
|
+
const locale = localeOf(data.locale);
|
|
855
|
+
const check = await ctx.checkSignup({ email, name: name ?? void 0, locale, method: "totp" });
|
|
856
|
+
if (!check.ok) return check.reason === "rejected" ? error(c, 403, "signup_rejected", check.message) : unavailable(c);
|
|
857
|
+
const existing = await users.findByEmail(normalizeEmail(email));
|
|
858
|
+
if (existing?.emailVerified && await users.hasAccounts(existing.id)) {
|
|
859
|
+
return await emails.sendAccountEmail(existing, "email.already_registered", target, locale) ? accepted(c) : unavailable(c);
|
|
860
|
+
}
|
|
861
|
+
if (existing) {
|
|
862
|
+
if (Date.now() - existing.lastMailAt < MAIL_INTERVAL_MS) return accepted(c);
|
|
863
|
+
if (!existing.emailVerified) await users.unlinkAccount(passwordAccountKey(existing.id));
|
|
864
|
+
await users.updateUser(existing.id, { name });
|
|
865
|
+
return await emails.sendLinkEmail({ ...existing, name }, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
866
|
+
}
|
|
867
|
+
const user = await users.createUser({ email, emailNormalized: normalizeEmail(email), name, emailVerified: false });
|
|
868
|
+
if (!user) return accepted(c);
|
|
869
|
+
await ctx.emit("user.created", { user: toMadauthUser(user), method: "totp" });
|
|
870
|
+
return await emails.sendLinkEmail(user, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// src/app.ts
|
|
876
|
+
var EVENT_TIMEOUT_MS = 5e3;
|
|
877
|
+
function createApp(config) {
|
|
878
|
+
const { issuer, allowedOrigins, sessionTtlSeconds, renewalTtlSeconds, cookieDomain } = config;
|
|
879
|
+
const keys = importSigningKeys(config.signingKey);
|
|
880
|
+
const secure = issuer.startsWith("https:");
|
|
881
|
+
const isAllowedOrigin = (origin) => !!origin && allowedOrigins.includes(origin);
|
|
882
|
+
const codeKey = deriveCodeKey(config.signingKey.d);
|
|
883
|
+
const users = new Users(config.store, codeKey);
|
|
884
|
+
const methods = methodConfig(config);
|
|
885
|
+
const settings = new Settings(config.store, initialMethods(methods));
|
|
886
|
+
const configured = (method) => isConfigured(methods, method);
|
|
887
|
+
const signsUp = (method) => canSignUp(methods, method);
|
|
888
|
+
const emailVerification = sendsVerificationEmails(config);
|
|
889
|
+
const totpKeys = { totpKey: deriveTotpKey(config.signingKey.d), codeKey };
|
|
890
|
+
const issueSession = async (c, user, amr, extra) => {
|
|
891
|
+
const signingKeys = await keys;
|
|
892
|
+
const [sessionToken, renewalToken] = await Promise.all([
|
|
893
|
+
signSession(signingKeys, issuer, sessionTtlSeconds, user, amr, extra),
|
|
894
|
+
signRenewal(signingKeys, issuer, renewalTtlSeconds, user, amr, extra)
|
|
895
|
+
]);
|
|
896
|
+
setCookie3(c, SESSION_COOKIE, sessionToken, {
|
|
897
|
+
path: "/",
|
|
898
|
+
domain: cookieDomain,
|
|
899
|
+
httpOnly: true,
|
|
900
|
+
secure,
|
|
901
|
+
sameSite: "Lax",
|
|
902
|
+
maxAge: sessionTtlSeconds
|
|
903
|
+
});
|
|
904
|
+
setCookie3(c, RENEWAL_COOKIE, renewalToken, {
|
|
905
|
+
path: "/auth",
|
|
906
|
+
httpOnly: true,
|
|
907
|
+
secure,
|
|
908
|
+
sameSite: "Lax",
|
|
909
|
+
maxAge: renewalTtlSeconds
|
|
910
|
+
});
|
|
911
|
+
setCookie3(c, EXPIRY_COOKIE, String(Math.floor(Date.now() / 1e3) + sessionTtlSeconds), {
|
|
912
|
+
path: "/",
|
|
913
|
+
domain: cookieDomain,
|
|
914
|
+
secure,
|
|
915
|
+
sameSite: "Lax",
|
|
916
|
+
maxAge: renewalTtlSeconds
|
|
917
|
+
});
|
|
918
|
+
};
|
|
919
|
+
const clearSession = (c) => {
|
|
920
|
+
deleteCookie3(c, SESSION_COOKIE, { path: "/", domain: cookieDomain, secure });
|
|
921
|
+
deleteCookie3(c, RENEWAL_COOKIE, { path: "/auth", secure });
|
|
922
|
+
deleteCookie3(c, EXPIRY_COOKIE, { path: "/", domain: cookieDomain, secure });
|
|
923
|
+
};
|
|
924
|
+
const tokenClaims = async (c, cookie, typ) => readToken(await keys, issuer, typ, getCookie3(c, cookie));
|
|
925
|
+
const checked = async (claims) => {
|
|
926
|
+
const stored = await users.findById(claims.sub);
|
|
927
|
+
if (!stored || stored.sessionVersion !== claims.sv) return null;
|
|
928
|
+
const { claims: _, ...user } = userFromClaims(claims);
|
|
929
|
+
const current = claimsFromJson(stored.claims);
|
|
930
|
+
return Object.keys(current).length ? { ...user, claims: current } : user;
|
|
931
|
+
};
|
|
932
|
+
const currentSession = async (c) => {
|
|
933
|
+
const session = await tokenClaims(c, SESSION_COOKIE, SESSION_TYP);
|
|
934
|
+
const user = session ? await checked(session) : null;
|
|
935
|
+
const upToDate = session && user && sameClaims(user.claims, session.claims) && Date.now() / 1e3 - session.iat <= sessionTtlSeconds / 2;
|
|
936
|
+
if (upToDate) return user;
|
|
937
|
+
const renewal = await tokenClaims(c, RENEWAL_COOKIE, RENEWAL_TYP);
|
|
938
|
+
const sameSignIn = session && user && renewal && renewal.sub === session.sub && renewal.sv === session.sv && renewal.email === session.email;
|
|
939
|
+
const renewed = sameSignIn ? user : renewal ? await checked(renewal) : null;
|
|
940
|
+
if (renewal && renewed) {
|
|
941
|
+
await issueSession(c, renewed, renewal.amr, { sv: renewal.sv });
|
|
942
|
+
return renewed;
|
|
943
|
+
}
|
|
944
|
+
return user;
|
|
945
|
+
};
|
|
946
|
+
const methodsOf = /* @__PURE__ */ new WeakMap();
|
|
947
|
+
const ctx = {
|
|
948
|
+
config,
|
|
949
|
+
keys,
|
|
950
|
+
secure,
|
|
951
|
+
isAllowedOrigin,
|
|
952
|
+
allowedUrl(value) {
|
|
953
|
+
let url;
|
|
954
|
+
try {
|
|
955
|
+
url = new URL(typeof value === "string" ? value : "");
|
|
956
|
+
} catch {
|
|
957
|
+
return null;
|
|
958
|
+
}
|
|
959
|
+
if (!isAllowedOrigin(url.origin)) return null;
|
|
960
|
+
url.hash = "";
|
|
961
|
+
return url;
|
|
962
|
+
},
|
|
963
|
+
async startSession(c, user, amr, extra) {
|
|
964
|
+
clearChallenge(c, secure);
|
|
965
|
+
await issueSession(c, user, amr, extra);
|
|
966
|
+
return { ...user, amr };
|
|
967
|
+
},
|
|
968
|
+
async secondStep(c, user, amr, method, profile) {
|
|
969
|
+
const methods2 = await this.methods(c);
|
|
970
|
+
if (!isOn(method, configured, methods2)) return { disabled: true };
|
|
971
|
+
const enrolled = await users.totpAccount(user.id);
|
|
972
|
+
const policy = method === "totp" ? "required" : policyOf(method, methods2);
|
|
973
|
+
const next = policy === "none" ? null : enrolled ? "totp" : policy === "required" ? "totp-setup" : null;
|
|
974
|
+
if (next) {
|
|
975
|
+
clearSession(c);
|
|
976
|
+
const known = { ...profile?.name ? { name: profile.name } : {}, ...profile?.picture ? { picture: profile.picture } : {} };
|
|
977
|
+
await setChallenge(c, this, { sub: user.id, sv: user.sessionVersion, amr, method, next, ...Object.keys(known).length ? { profile: known } : {} });
|
|
978
|
+
return { next, method };
|
|
979
|
+
}
|
|
980
|
+
const result = await this.startSession(c, toMadauthUser(user, profile), amr, { sv: user.sessionVersion });
|
|
981
|
+
await this.emit("user.signed_in", { user: result, method });
|
|
982
|
+
return { user: result };
|
|
983
|
+
},
|
|
984
|
+
currentUser: currentSession,
|
|
985
|
+
users,
|
|
986
|
+
settings,
|
|
987
|
+
webhook: config.webhook ? createWebhookClient(config.webhook, config.webhookFetch) : void 0,
|
|
988
|
+
configured,
|
|
989
|
+
emailVerification,
|
|
990
|
+
methods(c) {
|
|
991
|
+
let reading = methodsOf.get(c.req.raw);
|
|
992
|
+
if (!reading) {
|
|
993
|
+
reading = settings.methods();
|
|
994
|
+
methodsOf.set(c.req.raw, reading);
|
|
995
|
+
}
|
|
996
|
+
return reading;
|
|
997
|
+
},
|
|
998
|
+
async enabled(c, method) {
|
|
999
|
+
return isOn(method, configured, await this.methods(c));
|
|
1000
|
+
},
|
|
1001
|
+
async checkSignup(data) {
|
|
1002
|
+
if (!this.webhook?.wants("signup.before")) return { ok: true };
|
|
1003
|
+
const check = await this.webhook.call("signup.before", data, WEBHOOK_TIMEOUT_MS);
|
|
1004
|
+
if (!check.ok) {
|
|
1005
|
+
console.error(`[madauth] Webhook "signup.before" failed: ${check.reason}`);
|
|
1006
|
+
return { ok: false, reason: "unavailable" };
|
|
1007
|
+
}
|
|
1008
|
+
const answer = check.body;
|
|
1009
|
+
if (answer?.allow === false) {
|
|
1010
|
+
const message = typeof answer.message === "string" && answer.message ? answer.message : "Sign-up is not possible with this e-mail address.";
|
|
1011
|
+
return { ok: false, reason: "rejected", message };
|
|
1012
|
+
}
|
|
1013
|
+
return { ok: true };
|
|
1014
|
+
},
|
|
1015
|
+
async emit(type, data) {
|
|
1016
|
+
if (!this.webhook?.wants(type)) return;
|
|
1017
|
+
const user = data.user;
|
|
1018
|
+
const payload = user && typeof user === "object" && "amr" in user ? { ...data, user: { ...user, amr: void 0 } } : data;
|
|
1019
|
+
const result = await this.webhook.call(type, payload, EVENT_TIMEOUT_MS);
|
|
1020
|
+
if (!result.ok) console.error(`[madauth] Webhook "${type}" failed: ${result.reason}`);
|
|
1021
|
+
}
|
|
1022
|
+
};
|
|
1023
|
+
const app = new Hono();
|
|
1024
|
+
app.use(
|
|
1025
|
+
"/auth/*",
|
|
1026
|
+
cors({
|
|
1027
|
+
origin: (origin) => isAllowedOrigin(origin) ? origin : null,
|
|
1028
|
+
credentials: true,
|
|
1029
|
+
allowMethods: ["GET", "POST"],
|
|
1030
|
+
allowHeaders: ["Content-Type"],
|
|
1031
|
+
maxAge: 600
|
|
1032
|
+
})
|
|
1033
|
+
);
|
|
1034
|
+
app.use("/auth/*", async (c, next) => {
|
|
1035
|
+
if (c.req.method === "POST" && !isAllowedOrigin(c.req.header("origin"))) {
|
|
1036
|
+
return c.json({ error: "forbidden_origin" }, 403);
|
|
1037
|
+
}
|
|
1038
|
+
await next();
|
|
1039
|
+
});
|
|
1040
|
+
app.get("/health", (c) => c.text("ok"));
|
|
1041
|
+
app.get("/.well-known/jwks.json", async (c) => {
|
|
1042
|
+
const { publicJwk } = await keys;
|
|
1043
|
+
c.header("Cache-Control", "public, max-age=3600");
|
|
1044
|
+
return c.json({ keys: [publicJwk] });
|
|
1045
|
+
});
|
|
1046
|
+
app.get("/auth/config", async (c) => {
|
|
1047
|
+
const current = await ctx.methods(c);
|
|
1048
|
+
const on = (method) => isOn(method, configured, current);
|
|
1049
|
+
return c.json({
|
|
1050
|
+
google: on("google") ? { clientId: config.google.clientId, codeFlow: !!config.google.clientSecret, secondFactor: policyOf("google", current) } : null,
|
|
1051
|
+
password: on("password") ? { minLength: config.password.minLength, secondFactor: policyOf("password", current) } : null,
|
|
1052
|
+
// The app can be set up when it is in use at all; `signIn` says whether it signs in on its own.
|
|
1053
|
+
totp: authenticatorOn(configured, current) ? { signIn: on("totp"), signUp: on("totp") && emailVerification } : null,
|
|
1054
|
+
email: { verification: emailVerification }
|
|
1055
|
+
});
|
|
1056
|
+
});
|
|
1057
|
+
if (emailVerification && ctx.webhook) emailRoutes(app, ctx, users, ctx.webhook);
|
|
1058
|
+
if (config.google) googleRoutes(app, ctx, config.google);
|
|
1059
|
+
if (config.password && ctx.webhook) passwordRoutes(app, ctx, config.password, users, ctx.webhook);
|
|
1060
|
+
totpRoutes(app, ctx, totpKeys);
|
|
1061
|
+
app.get("/auth/session", async (c) => {
|
|
1062
|
+
const user = await currentSession(c);
|
|
1063
|
+
if (!user) {
|
|
1064
|
+
clearSession(c);
|
|
1065
|
+
return c.json({ error: "no_session" }, 401);
|
|
1066
|
+
}
|
|
1067
|
+
return c.json({ user });
|
|
1068
|
+
});
|
|
1069
|
+
app.post("/auth/logout", (c) => {
|
|
1070
|
+
clearSession(c);
|
|
1071
|
+
clearChallenge(c, secure);
|
|
1072
|
+
return c.body(null, 204);
|
|
1073
|
+
});
|
|
1074
|
+
app.post("/auth/account/delete", async (c) => {
|
|
1075
|
+
const user = await currentSession(c);
|
|
1076
|
+
if (!user) return c.json({ error: "no_session" }, 401);
|
|
1077
|
+
const stored = await users.findById(user.id);
|
|
1078
|
+
const protects = stored && authenticatorOn(configured, await ctx.methods(c));
|
|
1079
|
+
const authenticator = protects ? await users.totpAccount(user.id) : null;
|
|
1080
|
+
if (stored && authenticator) {
|
|
1081
|
+
const data = await body(c);
|
|
1082
|
+
if (data.code === void 0 && data.recoveryCode === void 0) {
|
|
1083
|
+
return error(c, 401, "code_required", "Enter a code from your authenticator app (or a recovery code) to delete your account.");
|
|
1084
|
+
}
|
|
1085
|
+
const via = await checkCode(c, ctx, totpKeys, stored, authenticator, data);
|
|
1086
|
+
if (via instanceof Response) return via;
|
|
1087
|
+
}
|
|
1088
|
+
await users.deleteById(user.id);
|
|
1089
|
+
clearSession(c);
|
|
1090
|
+
await ctx.emit("user.deleted", { user });
|
|
1091
|
+
return c.body(null, 204);
|
|
1092
|
+
});
|
|
1093
|
+
const admin = async (c) => {
|
|
1094
|
+
const user = await currentSession(c);
|
|
1095
|
+
if (!user) return { answer: c.json({ error: "no_session" }, 401) };
|
|
1096
|
+
const email = user.email ? normalizeEmail(user.email) : void 0;
|
|
1097
|
+
if (!email || !isAdmin(user)) {
|
|
1098
|
+
const message = `Only users with the role "${ADMIN_ROLE}" can manage claims and settings.`;
|
|
1099
|
+
return { answer: c.json({ error: "forbidden", message }, 403) };
|
|
1100
|
+
}
|
|
1101
|
+
return { email };
|
|
1102
|
+
};
|
|
1103
|
+
const invalidEmail = (c) => c.json({ error: "invalid_email", message: "This is not a valid e-mail address." }, 400);
|
|
1104
|
+
const noUser = (c) => c.json({ error: "user_not_found", message: "No user has this e-mail address." }, 404);
|
|
1105
|
+
app.post("/auth/admin/claims/get", async (c) => {
|
|
1106
|
+
const caller = await admin(c);
|
|
1107
|
+
if ("answer" in caller) return caller.answer;
|
|
1108
|
+
const data = await body(c);
|
|
1109
|
+
if (!isValidEmail(data.email)) return invalidEmail(c);
|
|
1110
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
1111
|
+
if (!user) return noUser(c);
|
|
1112
|
+
return c.json({ email: user.emailNormalized, userId: user.id, claims: claimsFromJson(user.claims) });
|
|
1113
|
+
});
|
|
1114
|
+
app.post("/auth/admin/claims/set", async (c) => {
|
|
1115
|
+
const caller = await admin(c);
|
|
1116
|
+
if ("answer" in caller) return caller.answer;
|
|
1117
|
+
const data = await body(c);
|
|
1118
|
+
if (!isValidEmail(data.email)) return invalidEmail(c);
|
|
1119
|
+
const claims = parseClaims(data.claims);
|
|
1120
|
+
if (!claims) {
|
|
1121
|
+
return c.json(
|
|
1122
|
+
{
|
|
1123
|
+
error: "invalid_claims",
|
|
1124
|
+
message: 'claims must be a JSON object of at most 2048 characters whose keys are names (letters, digits and "_", starting with a letter). "roles" must be a list of names of lower-case letters, digits, "-" and "_".'
|
|
1125
|
+
},
|
|
1126
|
+
400
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
1130
|
+
if (!user) return noUser(c);
|
|
1131
|
+
await users.updateUser(user.id, { claims: Object.keys(claims).length ? JSON.stringify(claims) : null });
|
|
1132
|
+
const email = user.emailNormalized;
|
|
1133
|
+
await ctx.emit("user.claims_changed", { userId: user.id, email, claims, by: caller.email });
|
|
1134
|
+
return c.json({ email, userId: user.id, claims });
|
|
1135
|
+
});
|
|
1136
|
+
const settingsAnswer = (methods2) => ({
|
|
1137
|
+
methods: Object.fromEntries(
|
|
1138
|
+
SIGN_IN_METHODS.map((method) => [
|
|
1139
|
+
method,
|
|
1140
|
+
{
|
|
1141
|
+
configured: configured(method),
|
|
1142
|
+
enabled: isOn(method, configured, methods2),
|
|
1143
|
+
...method === "totp" ? {} : { secondFactor: policyOf(method, methods2) }
|
|
1144
|
+
}
|
|
1145
|
+
])
|
|
1146
|
+
)
|
|
1147
|
+
});
|
|
1148
|
+
app.post("/auth/admin/settings/get", async (c) => {
|
|
1149
|
+
const caller = await admin(c);
|
|
1150
|
+
if ("answer" in caller) return caller.answer;
|
|
1151
|
+
return c.json(settingsAnswer(await settings.methods()));
|
|
1152
|
+
});
|
|
1153
|
+
app.post("/auth/admin/settings/set", async (c) => {
|
|
1154
|
+
const caller = await admin(c);
|
|
1155
|
+
if ("answer" in caller) return caller.answer;
|
|
1156
|
+
const data = await body(c);
|
|
1157
|
+
const invalid = (message) => c.json({ error: "invalid_settings", message }, 400);
|
|
1158
|
+
const next = parseMethodSettings(data.methods, { booleans: true });
|
|
1159
|
+
if (!next) {
|
|
1160
|
+
return invalid(
|
|
1161
|
+
`methods must list the sign-in methods that are on (${SIGN_IN_METHODS.join(", ")}), each as true, {} or { "secondFactor": "none" | "optional" | "required" } (google and password), e.g. { "google": {}, "password": { "secondFactor": "optional" } }. A method that is not listed is off.`
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
const methods2 = await settings.changeMethods(() => anyOn(signsUp, next) ? next : null, caller.email);
|
|
1165
|
+
if (!methods2) return invalid("At least one sign-in method that creates users must stay on: Google, e-mail & password, or the authenticator app with sign-up by e-mail.");
|
|
1166
|
+
return c.json(settingsAnswer(methods2));
|
|
1167
|
+
});
|
|
1168
|
+
app.post("/auth/admin/totp/remove", async (c) => {
|
|
1169
|
+
const caller = await admin(c);
|
|
1170
|
+
if ("answer" in caller) return caller.answer;
|
|
1171
|
+
const data = await body(c);
|
|
1172
|
+
if (!isValidEmail(data.email)) return invalidEmail(c);
|
|
1173
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
1174
|
+
if (!user) return noUser(c);
|
|
1175
|
+
const removed = await users.removeTotp(user.id);
|
|
1176
|
+
if (removed) await ctx.emit("totp.disabled", { user: toMadauthUser(user), by: caller.email });
|
|
1177
|
+
return c.json({ email: user.emailNormalized, userId: user.id, enabled: false });
|
|
1178
|
+
});
|
|
1179
|
+
return app;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
export {
|
|
1183
|
+
REDIRECT_ERROR_PARAM,
|
|
1184
|
+
createApp
|
|
1185
|
+
};
|