@madauth/server 0.2.0-beta.2 → 0.3.0-beta.2
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/dist/bin.js +99 -32
- package/dist/{chunk-6EJDVZCD.js → chunk-3QRKWLR7.js} +10 -2
- package/dist/{chunk-CNL562LZ.js → chunk-56MOVFO4.js} +24 -2
- package/dist/{chunk-XNBWZZHT.js → chunk-CD7Y4T66.js} +11 -9
- package/dist/{chunk-7CTAB3QV.js → chunk-DCDTO5LG.js} +2 -2
- package/dist/{chunk-YALS7OMV.js → chunk-DVVBIFIV.js} +222 -122
- package/dist/{chunk-5CKEMC6M.js → chunk-TI35AZ2U.js} +227 -88
- package/dist/{config-BkxADgtp.d.ts → config-Dg2fZuWR.d.ts} +7 -6
- 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 +30 -7
- package/dist/index.js +15 -7
- package/dist/{schema-BSgYVRpd.d.ts → schema-3yhCc2jH.d.ts} +17 -9
- package/dist/sqlite.js +2 -2
- package/dist/standalone/azure.mjs +847 -597
- package/dist/standalone/lambda.mjs +847 -597
- package/dist/standalone/main.mjs +594 -344
- 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 +12 -0
- package/dist/verify.d.ts +1 -1
- package/dist/verify.js +1 -1
- package/dist/{webhook-ltwulgcB.d.ts → webhook-j5u9Kv9l.d.ts} +1 -1
- package/dist/webhook.d.ts +1 -1
- package/dist/webhook.js +1 -1
- package/package.json +1 -1
- package/dist/user-C1A3BfOo.d.ts +0 -12
|
@@ -15,8 +15,9 @@ var init_schema = __esm({
|
|
|
15
15
|
"src/store/schema.ts"() {
|
|
16
16
|
"use strict";
|
|
17
17
|
madauthSchema = {
|
|
18
|
-
version:
|
|
18
|
+
version: 4,
|
|
19
19
|
models: {
|
|
20
|
+
/** Someone who signed in, whichever way: the e-mail address is the identity shared by the sign-in methods. */
|
|
20
21
|
user: {
|
|
21
22
|
fields: {
|
|
22
23
|
id: { type: "string", primaryKey: true },
|
|
@@ -28,10 +29,12 @@ var init_schema = __esm({
|
|
|
28
29
|
lastMailAt: { type: "number" },
|
|
29
30
|
/** Wrong e-mail codes in a row, counted across e-mails (since version 2). */
|
|
30
31
|
wrongCodes: { type: "number" },
|
|
32
|
+
/** What admins attached to the user, as JSON, e.g. `{"roles":["admin"]}` (since version 4). */
|
|
33
|
+
claims: { type: "string", nullable: true },
|
|
31
34
|
createdAt: { type: "number" }
|
|
32
35
|
}
|
|
33
36
|
},
|
|
34
|
-
/** How a user signs in. `key` is
|
|
37
|
+
/** How a user signs in. `key` is `password:<userId>` or `google:<sub>`; later e.g. `totp:<userId>`. */
|
|
35
38
|
account: {
|
|
36
39
|
fields: {
|
|
37
40
|
id: { type: "string", primaryKey: true },
|
|
@@ -40,6 +43,8 @@ var init_schema = __esm({
|
|
|
40
43
|
secret: { type: "string", nullable: true },
|
|
41
44
|
failedAttempts: { type: "number" },
|
|
42
45
|
lockedUntil: { type: "number" },
|
|
46
|
+
/** The address the provider reported at the last sign-in, e.g. Google's current primary address (since version 4). */
|
|
47
|
+
email: { type: "string", nullable: true },
|
|
43
48
|
createdAt: { type: "number" }
|
|
44
49
|
}
|
|
45
50
|
},
|
|
@@ -54,16 +59,13 @@ var init_schema = __esm({
|
|
|
54
59
|
expiresAt: { type: "number" }
|
|
55
60
|
}
|
|
56
61
|
},
|
|
57
|
-
/**
|
|
58
|
-
|
|
59
|
-
* apply whichever way its owner signs in. `roles` holds the names separated by spaces.
|
|
60
|
-
*/
|
|
61
|
-
role: {
|
|
62
|
+
/** A setting admins change at runtime, as JSON (since version 4), e.g. `methods`: which sign-in methods are on. */
|
|
63
|
+
setting: {
|
|
62
64
|
fields: {
|
|
63
65
|
id: { type: "string", primaryKey: true },
|
|
64
|
-
|
|
66
|
+
value: { type: "string" },
|
|
65
67
|
updatedAt: { type: "number" },
|
|
66
|
-
/** The address of the admin who set
|
|
68
|
+
/** The address of the admin who set it; empty when set from the command line. */
|
|
67
69
|
updatedBy: { type: "string", nullable: true }
|
|
68
70
|
}
|
|
69
71
|
}
|
|
@@ -118,8 +120,30 @@ var init_sql = __esm({
|
|
|
118
120
|
sql: (dialect) => `ALTER TABLE ${tableName("user")} ADD COLUMN ${columnName("wrongCodes")} ${columnTypes[dialect].number} NOT NULL DEFAULT 0;`
|
|
119
121
|
},
|
|
120
122
|
{
|
|
123
|
+
// Roles were per e-mail address in their own table; since version 4 they are one of the user's claims.
|
|
121
124
|
version: 3,
|
|
122
|
-
sql: (dialect) => createTablesSql(dialect, {
|
|
125
|
+
sql: (dialect) => createTablesSql(dialect, {
|
|
126
|
+
version: 3,
|
|
127
|
+
models: {
|
|
128
|
+
role: {
|
|
129
|
+
fields: {
|
|
130
|
+
id: { type: "string", primaryKey: true },
|
|
131
|
+
roles: { type: "string" },
|
|
132
|
+
updatedAt: { type: "number" },
|
|
133
|
+
updatedBy: { type: "string", nullable: true }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
version: 4,
|
|
141
|
+
sql: (dialect) => [
|
|
142
|
+
`ALTER TABLE ${tableName("user")} ADD COLUMN ${columnName("claims")} ${columnTypes[dialect].string};`,
|
|
143
|
+
`ALTER TABLE ${tableName("account")} ADD COLUMN ${columnName("email")} ${columnTypes[dialect].string};`,
|
|
144
|
+
`DROP TABLE ${tableName("role")};`,
|
|
145
|
+
createTablesSql(dialect, { version: 4, models: { setting: madauthSchema.models.setting } })
|
|
146
|
+
].join("\n")
|
|
123
147
|
}
|
|
124
148
|
];
|
|
125
149
|
}
|
|
@@ -2683,6 +2707,63 @@ var cors = (options) => {
|
|
|
2683
2707
|
};
|
|
2684
2708
|
};
|
|
2685
2709
|
|
|
2710
|
+
// src/claims.ts
|
|
2711
|
+
var ADMIN_ROLE = "admin";
|
|
2712
|
+
var MAX_ROLES = 20;
|
|
2713
|
+
var MAX_CLAIMS_LENGTH = 2048;
|
|
2714
|
+
var ROLE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
2715
|
+
var CLAIM_NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;
|
|
2716
|
+
function parseRoles(input) {
|
|
2717
|
+
if (!Array.isArray(input)) return null;
|
|
2718
|
+
if (!input.every((role) => typeof role === "string" && ROLE_NAME.test(role))) return null;
|
|
2719
|
+
const roles = [...new Set(input)].sort();
|
|
2720
|
+
return roles.length <= MAX_ROLES ? roles : null;
|
|
2721
|
+
}
|
|
2722
|
+
function parseClaims(input) {
|
|
2723
|
+
if (!isJsonObject(input)) return null;
|
|
2724
|
+
const claims = {};
|
|
2725
|
+
for (const key of Object.keys(input).sort()) {
|
|
2726
|
+
const value = input[key];
|
|
2727
|
+
if (!CLAIM_NAME.test(key) || !isJsonValue(value)) return null;
|
|
2728
|
+
if (key === "roles") {
|
|
2729
|
+
const roles = parseRoles(value);
|
|
2730
|
+
if (!roles) return null;
|
|
2731
|
+
claims[key] = roles;
|
|
2732
|
+
} else {
|
|
2733
|
+
claims[key] = value;
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
return JSON.stringify(claims).length <= MAX_CLAIMS_LENGTH ? claims : null;
|
|
2737
|
+
}
|
|
2738
|
+
function isJsonObject(value) {
|
|
2739
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
2740
|
+
}
|
|
2741
|
+
function isJsonValue(value) {
|
|
2742
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
2743
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
2744
|
+
if (Array.isArray(value)) return value.every(isJsonValue);
|
|
2745
|
+
return isJsonObject(value) && Object.values(value).every(isJsonValue);
|
|
2746
|
+
}
|
|
2747
|
+
function sameClaims(a, b) {
|
|
2748
|
+
return JSON.stringify(a ?? {}) === JSON.stringify(b ?? {});
|
|
2749
|
+
}
|
|
2750
|
+
function claimsFromJson(json) {
|
|
2751
|
+
if (!json) return {};
|
|
2752
|
+
try {
|
|
2753
|
+
const parsed = JSON.parse(json);
|
|
2754
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
2755
|
+
} catch {
|
|
2756
|
+
return {};
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
function rolesOf(user) {
|
|
2760
|
+
const roles = user.claims?.roles;
|
|
2761
|
+
return Array.isArray(roles) ? roles.filter((role) => typeof role === "string") : [];
|
|
2762
|
+
}
|
|
2763
|
+
function isAdmin(user) {
|
|
2764
|
+
return rolesOf(user).includes(ADMIN_ROLE);
|
|
2765
|
+
}
|
|
2766
|
+
|
|
2686
2767
|
// ../../node_modules/jose/dist/webapi/lib/buffer_utils.js
|
|
2687
2768
|
var encoder = new TextEncoder();
|
|
2688
2769
|
var decoder = new TextDecoder();
|
|
@@ -3889,45 +3970,6 @@ function safeEqual(a, b) {
|
|
|
3889
3970
|
return x.length === y.length && timingSafeEqual(x, y);
|
|
3890
3971
|
}
|
|
3891
3972
|
|
|
3892
|
-
// src/roles.ts
|
|
3893
|
-
var ADMIN_ROLE = "admin";
|
|
3894
|
-
var MAX_ROLES = 20;
|
|
3895
|
-
var ROLE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
3896
|
-
function parseRoles(input) {
|
|
3897
|
-
if (!Array.isArray(input)) return null;
|
|
3898
|
-
if (!input.every((role) => typeof role === "string" && ROLE_NAME.test(role))) return null;
|
|
3899
|
-
const roles = [...new Set(input)].sort();
|
|
3900
|
-
return roles.length <= MAX_ROLES ? roles : null;
|
|
3901
|
-
}
|
|
3902
|
-
function sameRoles(a, b) {
|
|
3903
|
-
return a.length === b.length && a.every((role, i) => role === b[i]);
|
|
3904
|
-
}
|
|
3905
|
-
var Roles = class {
|
|
3906
|
-
constructor(store) {
|
|
3907
|
-
this.store = store;
|
|
3908
|
-
}
|
|
3909
|
-
/** The address's roles, sorted; empty if it has none. */
|
|
3910
|
-
async get(emailNormalized) {
|
|
3911
|
-
const record = await this.store.findOne("role", { id: emailNormalized });
|
|
3912
|
-
return typeof record?.roles === "string" && record.roles ? record.roles.split(" ").filter(Boolean) : [];
|
|
3913
|
-
}
|
|
3914
|
-
/** Replaces the address's roles. `updatedBy` is the address of the admin, or null for the command line. */
|
|
3915
|
-
async set(emailNormalized, roles, updatedBy) {
|
|
3916
|
-
if (!roles.length) {
|
|
3917
|
-
await this.remove(emailNormalized);
|
|
3918
|
-
return;
|
|
3919
|
-
}
|
|
3920
|
-
const data = { roles: roles.join(" "), updatedAt: Date.now(), updatedBy };
|
|
3921
|
-
if (await this.store.update("role", { id: emailNormalized }, data) === 1) return;
|
|
3922
|
-
if (!await this.store.create("role", { id: emailNormalized, ...data })) {
|
|
3923
|
-
await this.store.update("role", { id: emailNormalized }, data);
|
|
3924
|
-
}
|
|
3925
|
-
}
|
|
3926
|
-
async remove(emailNormalized) {
|
|
3927
|
-
await this.store.delete("role", { id: emailNormalized });
|
|
3928
|
-
}
|
|
3929
|
-
};
|
|
3930
|
-
|
|
3931
3973
|
// src/google.ts
|
|
3932
3974
|
var GOOGLE_ISSUERS = ["https://accounts.google.com", "accounts.google.com"];
|
|
3933
3975
|
var googleJwks;
|
|
@@ -3952,14 +3994,13 @@ async function verifyGoogleIdToken(idToken, opts) {
|
|
|
3952
3994
|
if (payload.nonce !== opts.nonce) {
|
|
3953
3995
|
return { ok: false, error: "verification_failed", reason: "nonce mismatch" };
|
|
3954
3996
|
}
|
|
3955
|
-
if (payload.email_verified !== true) {
|
|
3997
|
+
if (typeof payload.email !== "string" || !payload.email || payload.email_verified !== true) {
|
|
3956
3998
|
return { ok: false, error: "email_unverified", reason: "e-mail address not verified" };
|
|
3957
3999
|
}
|
|
3958
|
-
const
|
|
3959
|
-
if (typeof payload.
|
|
3960
|
-
if (typeof payload.
|
|
3961
|
-
|
|
3962
|
-
return { ok: true, user };
|
|
4000
|
+
const profile = { sub: payload.sub, email: payload.email };
|
|
4001
|
+
if (typeof payload.name === "string") profile.name = payload.name;
|
|
4002
|
+
if (typeof payload.picture === "string") profile.picture = payload.picture;
|
|
4003
|
+
return { ok: true, profile };
|
|
3963
4004
|
}
|
|
3964
4005
|
|
|
3965
4006
|
// src/user.ts
|
|
@@ -3993,7 +4034,7 @@ function signSession(keys, issuer, ttlSeconds, user, amr, extra = {}) {
|
|
|
3993
4034
|
email_verified: user.email ? true : void 0,
|
|
3994
4035
|
name: user.name,
|
|
3995
4036
|
picture: user.picture,
|
|
3996
|
-
|
|
4037
|
+
claims: user.claims && Object.keys(user.claims).length ? user.claims : void 0,
|
|
3997
4038
|
amr
|
|
3998
4039
|
};
|
|
3999
4040
|
return signToken(keys, issuer, SESSION_TYP, claims, ttlSeconds);
|
|
@@ -4015,353 +4056,100 @@ function userFromClaims(claims) {
|
|
|
4015
4056
|
if (claims.email) user.email = claims.email;
|
|
4016
4057
|
if (claims.name) user.name = claims.name;
|
|
4017
4058
|
if (claims.picture) user.picture = claims.picture;
|
|
4018
|
-
if (
|
|
4059
|
+
if (claims.claims && typeof claims.claims === "object" && Object.keys(claims.claims).length) user.claims = claims.claims;
|
|
4019
4060
|
return user;
|
|
4020
4061
|
}
|
|
4021
4062
|
|
|
4022
|
-
// src/
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
var
|
|
4027
|
-
var
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
|
|
4043
|
-
|
|
4044
|
-
|
|
4045
|
-
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
}
|
|
4050
|
-
return c.json({ nonce });
|
|
4051
|
-
});
|
|
4052
|
-
app.post("/auth/google/verify", async (c) => {
|
|
4053
|
-
const body = await c.req.json().catch(() => ({}));
|
|
4054
|
-
if (typeof body.credential !== "string" || !body.credential) {
|
|
4055
|
-
return c.json({ error: "verification_failed", message: "credential is missing" }, 400);
|
|
4056
|
-
}
|
|
4057
|
-
const nonceClaims = await readToken(await keys, issuer, NONCE_TYP, getCookie(c, NONCE_COOKIE));
|
|
4058
|
-
if (!nonceClaims) {
|
|
4059
|
-
return c.json({ error: "verification_failed", message: "nonce cookie missing or expired" }, 401);
|
|
4060
|
-
}
|
|
4061
|
-
const result = await verifyGoogleIdToken(body.credential, {
|
|
4062
|
-
clientId: google.clientId,
|
|
4063
|
-
nonce: nonceClaims.nonce,
|
|
4064
|
-
keys: config.jwksResolver
|
|
4065
|
-
});
|
|
4066
|
-
if (!result.ok) {
|
|
4067
|
-
return c.json({ error: result.error, message: result.reason }, result.error === "email_unverified" ? 403 : 401);
|
|
4068
|
-
}
|
|
4069
|
-
deleteCookie(c, NONCE_COOKIE, { path: "/auth/google", secure });
|
|
4070
|
-
const user = await ctx.startSession(c, result.user, ["google"]);
|
|
4071
|
-
await ctx.emit("user.signed_in", { user, method: "google" });
|
|
4072
|
-
return c.json({ user });
|
|
4073
|
-
});
|
|
4074
|
-
const requireCodeFlow = async (c, next) => {
|
|
4075
|
-
if (!google.clientSecret) return c.json({ error: "not_found" }, 404);
|
|
4076
|
-
await next();
|
|
4077
|
-
};
|
|
4078
|
-
app.get("/auth/google/start", requireCodeFlow, async (c) => {
|
|
4079
|
-
const returnUrl = ctx.allowedUrl(c.req.query("return_to"));
|
|
4080
|
-
if (!returnUrl) return c.text("return_to must be an absolute URL whose origin is in ALLOWED_ORIGINS", 400);
|
|
4081
|
-
const oauth = {
|
|
4082
|
-
state: randomString(),
|
|
4083
|
-
nonce: randomString(),
|
|
4084
|
-
verifier: randomString(),
|
|
4085
|
-
returnTo: returnUrl.href
|
|
4086
|
-
};
|
|
4087
|
-
const token = await signToken(await keys, issuer, OAUTH_TYP, { ...oauth }, OAUTH_TTL);
|
|
4088
|
-
setCookie(c, OAUTH_COOKIE, token, {
|
|
4089
|
-
path: "/auth/google",
|
|
4090
|
-
httpOnly: true,
|
|
4091
|
-
secure,
|
|
4092
|
-
sameSite: "Lax",
|
|
4093
|
-
maxAge: OAUTH_TTL
|
|
4094
|
-
});
|
|
4095
|
-
const url = new URL(GOOGLE_AUTH_ENDPOINT);
|
|
4096
|
-
url.search = new URLSearchParams({
|
|
4097
|
-
client_id: google.clientId,
|
|
4098
|
-
redirect_uri: callbackUrl,
|
|
4099
|
-
response_type: "code",
|
|
4100
|
-
scope: "openid email profile",
|
|
4101
|
-
state: oauth.state,
|
|
4102
|
-
nonce: oauth.nonce,
|
|
4103
|
-
code_challenge: await pkceChallenge(oauth.verifier),
|
|
4104
|
-
code_challenge_method: "S256"
|
|
4105
|
-
}).toString();
|
|
4106
|
-
return c.redirect(url.href, 302);
|
|
4107
|
-
});
|
|
4108
|
-
app.get("/auth/google/callback", requireCodeFlow, async (c) => {
|
|
4109
|
-
const oauth = await readToken(await keys, issuer, OAUTH_TYP, getCookie(c, OAUTH_COOKIE));
|
|
4110
|
-
if (!oauth) return c.text("Sign-in expired or was started in another browser. Please try again.", 400);
|
|
4111
|
-
deleteCookie(c, OAUTH_COOKIE, { path: "/auth/google", secure });
|
|
4112
|
-
const back = (error) => {
|
|
4113
|
-
const url = new URL(oauth.returnTo);
|
|
4114
|
-
if (error) url.hash = `${REDIRECT_ERROR_PARAM}=${error}`;
|
|
4115
|
-
return c.redirect(url.href, 302);
|
|
4116
|
-
};
|
|
4117
|
-
if (c.req.query("error")) return back(c.req.query("error") === "access_denied" ? "cancelled" : "verification_failed");
|
|
4118
|
-
const code = c.req.query("code");
|
|
4119
|
-
if (!code || c.req.query("state") !== oauth.state) return back("verification_failed");
|
|
4120
|
-
let idToken;
|
|
4063
|
+
// src/users.ts
|
|
4064
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
4065
|
+
|
|
4066
|
+
// src/settings.ts
|
|
4067
|
+
var SIGN_IN_METHODS = ["google", "password"];
|
|
4068
|
+
var METHODS_SETTING = "methods";
|
|
4069
|
+
function parseMethodSettings(input) {
|
|
4070
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return null;
|
|
4071
|
+
const settings = {};
|
|
4072
|
+
for (const [key, value] of Object.entries(input)) {
|
|
4073
|
+
if (!SIGN_IN_METHODS.includes(key) || typeof value !== "boolean") return null;
|
|
4074
|
+
settings[key] = value;
|
|
4075
|
+
}
|
|
4076
|
+
return settings;
|
|
4077
|
+
}
|
|
4078
|
+
var MAX_TRIES = 3;
|
|
4079
|
+
var Settings = class {
|
|
4080
|
+
constructor(store) {
|
|
4081
|
+
this.store = store;
|
|
4082
|
+
}
|
|
4083
|
+
/** The setting's value, or undefined if it was never set. */
|
|
4084
|
+
async get(id) {
|
|
4085
|
+
return (await this.read(id)).value;
|
|
4086
|
+
}
|
|
4087
|
+
/** The stored JSON and what it holds; both undefined if the setting was never set. */
|
|
4088
|
+
async read(id) {
|
|
4089
|
+
const record = await this.store.findOne("setting", { id });
|
|
4090
|
+
if (typeof record?.value !== "string") return {};
|
|
4121
4091
|
try {
|
|
4122
|
-
|
|
4123
|
-
method: "POST",
|
|
4124
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
4125
|
-
body: new URLSearchParams({
|
|
4126
|
-
code,
|
|
4127
|
-
client_id: google.clientId,
|
|
4128
|
-
client_secret: google.clientSecret,
|
|
4129
|
-
redirect_uri: callbackUrl,
|
|
4130
|
-
grant_type: "authorization_code",
|
|
4131
|
-
code_verifier: oauth.verifier
|
|
4132
|
-
})
|
|
4133
|
-
});
|
|
4134
|
-
if (!res.ok) return back("verification_failed");
|
|
4135
|
-
({ id_token: idToken } = await res.json());
|
|
4092
|
+
return { json: record.value, value: JSON.parse(record.value) };
|
|
4136
4093
|
} catch {
|
|
4137
|
-
return
|
|
4094
|
+
return { json: record.value };
|
|
4138
4095
|
}
|
|
4139
|
-
|
|
4140
|
-
|
|
4141
|
-
|
|
4142
|
-
|
|
4143
|
-
|
|
4144
|
-
|
|
4145
|
-
|
|
4146
|
-
|
|
4147
|
-
|
|
4148
|
-
|
|
4149
|
-
|
|
4096
|
+
}
|
|
4097
|
+
/**
|
|
4098
|
+
* Changes the setting: `apply` gets the current value and returns the new one, or null to refuse the
|
|
4099
|
+
* change. The write only lands if nobody changed the setting since `apply` read it; otherwise `apply` runs
|
|
4100
|
+
* again with the newer value. Resolves to the new value, or null if `apply` refused.
|
|
4101
|
+
* `updatedBy` is the address of the admin, or null for the command line.
|
|
4102
|
+
*/
|
|
4103
|
+
async change(id, apply, updatedBy) {
|
|
4104
|
+
for (let attempt = 0; attempt < MAX_TRIES; attempt++) {
|
|
4105
|
+
const { json, value } = await this.read(id);
|
|
4106
|
+
const next = apply(value);
|
|
4107
|
+
if (next === null) return null;
|
|
4108
|
+
const patch = { value: JSON.stringify(next), updatedAt: Date.now(), updatedBy };
|
|
4109
|
+
const written = json === void 0 ? await this.store.create("setting", { id, ...patch }) : await this.store.update("setting", { id, value: json }, patch) === 1;
|
|
4110
|
+
if (written) return next;
|
|
4111
|
+
}
|
|
4112
|
+
throw new Error(`Setting "${id}" kept changing; try again.`);
|
|
4113
|
+
}
|
|
4114
|
+
/** Replaces the setting. */
|
|
4115
|
+
async set(id, value, updatedBy) {
|
|
4116
|
+
await this.change(id, () => value, updatedBy);
|
|
4117
|
+
}
|
|
4118
|
+
/** Which sign-in methods are on; a method that was never switched off is on. */
|
|
4119
|
+
async methods() {
|
|
4120
|
+
return parseMethodSettings(await this.get(METHODS_SETTING)) ?? {};
|
|
4121
|
+
}
|
|
4122
|
+
/** Changes which methods are on, see {@link change}; `apply` gets the methods as they are now. */
|
|
4123
|
+
async changeMethods(apply, updatedBy) {
|
|
4124
|
+
return this.change(METHODS_SETTING, (current) => apply(parseMethodSettings(current) ?? {}), updatedBy);
|
|
4125
|
+
}
|
|
4126
|
+
};
|
|
4127
|
+
function isOn(method, available, methods) {
|
|
4128
|
+
return available(method) && methods[method] !== false;
|
|
4129
|
+
}
|
|
4130
|
+
function anyOn(available, methods) {
|
|
4131
|
+
return SIGN_IN_METHODS.some((method) => isOn(method, available, methods));
|
|
4150
4132
|
}
|
|
4151
4133
|
|
|
4152
|
-
// src/
|
|
4153
|
-
var
|
|
4154
|
-
var
|
|
4155
|
-
var
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4161
|
-
|
|
4162
|
-
|
|
4163
|
-
function toMadauthUser(user) {
|
|
4134
|
+
// src/users.ts
|
|
4135
|
+
var MAX_CODE_ATTEMPTS = 5;
|
|
4136
|
+
var MAX_WRONG_CODES = 10;
|
|
4137
|
+
var newId = (prefix) => `${prefix}_${randomBytes2(16).toString("base64url")}`;
|
|
4138
|
+
function passwordAccountKey(userId) {
|
|
4139
|
+
return `password:${userId}`;
|
|
4140
|
+
}
|
|
4141
|
+
function googleAccountKey(sub) {
|
|
4142
|
+
return `google:${sub}`;
|
|
4143
|
+
}
|
|
4144
|
+
function toMadauthUser(user, profile = {}) {
|
|
4164
4145
|
const result = { id: user.id, email: user.email };
|
|
4165
|
-
|
|
4146
|
+
const name = user.name ?? profile.name;
|
|
4147
|
+
if (name) result.name = name;
|
|
4148
|
+
if (profile.picture) result.picture = profile.picture;
|
|
4149
|
+
const claims = claimsFromJson(user.claims);
|
|
4150
|
+
if (Object.keys(claims).length) result.claims = claims;
|
|
4166
4151
|
return result;
|
|
4167
4152
|
}
|
|
4168
|
-
function passwordRoutes(app, ctx, password, users, webhook) {
|
|
4169
|
-
const { minLength } = password;
|
|
4170
|
-
const body = async (c) => {
|
|
4171
|
-
const data = await c.req.json().catch(() => null);
|
|
4172
|
-
return data && typeof data === "object" ? data : {};
|
|
4173
|
-
};
|
|
4174
|
-
const error = (c, status, code, message2) => c.json({ error: code, message: message2 }, status);
|
|
4175
|
-
const unavailable = (c) => error(c, 503, "temporarily_unavailable", "E-mails can not be sent right now. Please try again later.");
|
|
4176
|
-
const accepted = (c) => c.json({}, 202);
|
|
4177
|
-
const redirectTarget = (c, value) => {
|
|
4178
|
-
const url = ctx.allowedUrl(value);
|
|
4179
|
-
return url ?? error(c, 400, "invalid_options", "redirectTo must be an absolute URL whose origin is in ALLOWED_ORIGINS.");
|
|
4180
|
-
};
|
|
4181
|
-
const sendEmail = async (user, type, data) => {
|
|
4182
|
-
if (Date.now() - user.lastMailAt < MAIL_INTERVAL_MS) return true;
|
|
4183
|
-
const result = await webhook.call(type, { to: user.email, user: { id: user.id, name: user.name ?? void 0 }, ...data }, WEBHOOK_TIMEOUT_MS);
|
|
4184
|
-
if (!result.ok) {
|
|
4185
|
-
console.error(`[madauth] Webhook "${type}" for ${user.email} failed: ${result.reason}`);
|
|
4186
|
-
return false;
|
|
4187
|
-
}
|
|
4188
|
-
await users.updateUser(user.id, { lastMailAt: Date.now() });
|
|
4189
|
-
return true;
|
|
4190
|
-
};
|
|
4191
|
-
const sendLinkEmail = async (user, purpose, target, locale) => {
|
|
4192
|
-
if (Date.now() - user.lastMailAt < MAIL_INTERVAL_MS) return true;
|
|
4193
|
-
const ttl = purpose === "verify" ? VERIFY_TTL_MS : RESET_TTL_MS;
|
|
4194
|
-
const { token, code } = await users.issueVerification(user.id, purpose, ttl);
|
|
4195
|
-
const link = new URL(target);
|
|
4196
|
-
link.hash = `${purpose === "verify" ? VERIFY_LINK_PARAM : RESET_LINK_PARAM}=${token}`;
|
|
4197
|
-
return sendEmail(user, purpose === "verify" ? "email.verify" : "email.reset", {
|
|
4198
|
-
link: link.href,
|
|
4199
|
-
code,
|
|
4200
|
-
expiresAt: Date.now() + ttl,
|
|
4201
|
-
site: target.host,
|
|
4202
|
-
locale
|
|
4203
|
-
});
|
|
4204
|
-
};
|
|
4205
|
-
const localeOf = (data) => typeof data.locale === "string" && data.locale.length <= MAX_LOCALE_LENGTH ? data.locale : void 0;
|
|
4206
|
-
const consume = async (data, purpose) => {
|
|
4207
|
-
if (typeof data.token === "string" && data.token) {
|
|
4208
|
-
return { userId: await users.consumeLinkToken(data.token, purpose), via: "link" };
|
|
4209
|
-
}
|
|
4210
|
-
if (isValidEmail(data.email) && typeof data.code === "string") {
|
|
4211
|
-
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4212
|
-
if (!user) return { userId: null, via: "code" };
|
|
4213
|
-
return { ...await users.consumeCode(user, purpose, data.code.replace(/\s/g, "")), via: "code" };
|
|
4214
|
-
}
|
|
4215
|
-
return { userId: null, via: "code" };
|
|
4216
|
-
};
|
|
4217
|
-
const invalidVerification = (c, { via, locked }) => {
|
|
4218
|
-
if (locked) {
|
|
4219
|
-
return error(c, 429, "codes_locked", "Too many wrong codes. Please ask for a new e-mail and use the link in it.");
|
|
4220
|
-
}
|
|
4221
|
-
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.");
|
|
4222
|
-
};
|
|
4223
|
-
app.post("/auth/password/signin", async (c) => {
|
|
4224
|
-
const data = await body(c);
|
|
4225
|
-
const wrong = () => error(c, 401, "invalid_credentials", "E-mail or password is wrong.");
|
|
4226
|
-
const pw = typeof data.password === "string" ? data.password : "";
|
|
4227
|
-
if (!isValidEmail(data.email) || !pw || pw.length > MAX_PASSWORD_LENGTH * 4) return wrong();
|
|
4228
|
-
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4229
|
-
const account = user ? await users.passwordAccount(user.id) : null;
|
|
4230
|
-
if (!user || !account?.secret) {
|
|
4231
|
-
await verifyAgainstDummy(pw);
|
|
4232
|
-
return wrong();
|
|
4233
|
-
}
|
|
4234
|
-
const now = Date.now();
|
|
4235
|
-
if (account.lockedUntil > now) {
|
|
4236
|
-
const seconds = Math.ceil((account.lockedUntil - now) / 1e3);
|
|
4237
|
-
return error(c, 429, "too_many_attempts", `Too many failed attempts. Try again in ${seconds} seconds.`);
|
|
4238
|
-
}
|
|
4239
|
-
const failed = account.failedAttempts + 1;
|
|
4240
|
-
const lockedUntil = failed >= FREE_ATTEMPTS ? now + Math.min(2 ** (failed - FREE_ATTEMPTS) * 1e3, MAX_LOCK_MS) : 0;
|
|
4241
|
-
if (!await users.countAttempt(account, { failedAttempts: failed, lockedUntil })) {
|
|
4242
|
-
return error(c, 429, "too_many_attempts", "Too many attempts at once. Please try again.");
|
|
4243
|
-
}
|
|
4244
|
-
const { ok, needsRehash } = await verifyPassword(pw, account.secret);
|
|
4245
|
-
if (!ok) return wrong();
|
|
4246
|
-
await users.updateAccount(account.id, {
|
|
4247
|
-
failedAttempts: 0,
|
|
4248
|
-
lockedUntil: 0,
|
|
4249
|
-
...needsRehash ? { secret: await hashPassword(pw) } : {}
|
|
4250
|
-
});
|
|
4251
|
-
if (!user.emailVerified) {
|
|
4252
|
-
return error(c, 403, "email_unverified", "Please confirm your e-mail address first. We can send the e-mail again.");
|
|
4253
|
-
}
|
|
4254
|
-
const result = await ctx.startSession(c, toMadauthUser(user), ["pwd"], { sv: user.sessionVersion });
|
|
4255
|
-
await ctx.emit("user.signed_in", { user: result, method: "password" });
|
|
4256
|
-
return c.json({ user: result });
|
|
4257
|
-
});
|
|
4258
|
-
app.post("/auth/password/signup", async (c) => {
|
|
4259
|
-
const data = await body(c);
|
|
4260
|
-
const target = redirectTarget(c, data.redirectTo);
|
|
4261
|
-
if (target instanceof Response) return target;
|
|
4262
|
-
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
4263
|
-
const policy = checkPasswordPolicy(data.password, minLength);
|
|
4264
|
-
if (policy) return error(c, 400, "weak_password", policy);
|
|
4265
|
-
const name = typeof data.name === "string" && data.name.trim() ? data.name.trim().slice(0, MAX_NAME_LENGTH) : null;
|
|
4266
|
-
const email = data.email.trim();
|
|
4267
|
-
const locale = localeOf(data);
|
|
4268
|
-
if (webhook.wants("signup.before")) {
|
|
4269
|
-
const check2 = await webhook.call("signup.before", { email, name: name ?? void 0, locale }, WEBHOOK_TIMEOUT_MS);
|
|
4270
|
-
if (!check2.ok) {
|
|
4271
|
-
console.error(`[madauth] Webhook "signup.before" failed: ${check2.reason}`);
|
|
4272
|
-
return unavailable(c);
|
|
4273
|
-
}
|
|
4274
|
-
const answer = check2.body;
|
|
4275
|
-
if (answer?.allow === false) {
|
|
4276
|
-
const message2 = typeof answer.message === "string" && answer.message ? answer.message : "Sign-up is not possible with this e-mail address.";
|
|
4277
|
-
return error(c, 403, "signup_rejected", message2);
|
|
4278
|
-
}
|
|
4279
|
-
}
|
|
4280
|
-
const passwordHash = await hashPassword(data.password);
|
|
4281
|
-
const existing = await users.findByEmail(normalizeEmail(email));
|
|
4282
|
-
if (existing?.emailVerified) {
|
|
4283
|
-
if (!webhook.wants("email.already_registered")) return accepted(c);
|
|
4284
|
-
const sent = await sendEmail(existing, "email.already_registered", { link: target.href, site: target.host, locale });
|
|
4285
|
-
return sent ? accepted(c) : unavailable(c);
|
|
4286
|
-
}
|
|
4287
|
-
if (existing) {
|
|
4288
|
-
if (Date.now() - existing.lastMailAt < MAIL_INTERVAL_MS) return accepted(c);
|
|
4289
|
-
const account = await users.passwordAccount(existing.id);
|
|
4290
|
-
if (account) await users.updateAccount(account.id, { secret: passwordHash, failedAttempts: 0, lockedUntil: 0 });
|
|
4291
|
-
await users.updateUser(existing.id, { name });
|
|
4292
|
-
return await sendLinkEmail({ ...existing, name }, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
4293
|
-
}
|
|
4294
|
-
const user = await users.createPasswordUser({
|
|
4295
|
-
email,
|
|
4296
|
-
emailNormalized: normalizeEmail(email),
|
|
4297
|
-
name,
|
|
4298
|
-
passwordHash,
|
|
4299
|
-
emailVerified: false
|
|
4300
|
-
});
|
|
4301
|
-
if (!user) return accepted(c);
|
|
4302
|
-
await ctx.emit("user.created", { user: toMadauthUser(user) });
|
|
4303
|
-
return await sendLinkEmail(user, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
4304
|
-
});
|
|
4305
|
-
app.post("/auth/password/send-verification", async (c) => {
|
|
4306
|
-
const data = await body(c);
|
|
4307
|
-
const target = redirectTarget(c, data.redirectTo);
|
|
4308
|
-
if (target instanceof Response) return target;
|
|
4309
|
-
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
4310
|
-
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4311
|
-
if (user && !user.emailVerified && await users.passwordAccount(user.id)) {
|
|
4312
|
-
if (!await sendLinkEmail(user, "verify", target, localeOf(data))) return unavailable(c);
|
|
4313
|
-
}
|
|
4314
|
-
return accepted(c);
|
|
4315
|
-
});
|
|
4316
|
-
app.post("/auth/password/verify-email", async (c) => {
|
|
4317
|
-
const consumed = await consume(await body(c), "verify");
|
|
4318
|
-
const { userId, via } = consumed;
|
|
4319
|
-
const user = userId ? await users.findById(userId) : null;
|
|
4320
|
-
if (!user) return invalidVerification(c, consumed);
|
|
4321
|
-
await users.updateUser(user.id, { emailVerified: true, wrongCodes: 0 });
|
|
4322
|
-
const result = await ctx.startSession(c, toMadauthUser(user), ["pwd"], { sv: user.sessionVersion });
|
|
4323
|
-
await ctx.emit("email.verified", { user: result, via });
|
|
4324
|
-
await ctx.emit("user.signed_in", { user: result, method: "password" });
|
|
4325
|
-
return c.json({ user: result });
|
|
4326
|
-
});
|
|
4327
|
-
app.post("/auth/password/send-reset", async (c) => {
|
|
4328
|
-
const data = await body(c);
|
|
4329
|
-
const target = redirectTarget(c, data.redirectTo);
|
|
4330
|
-
if (target instanceof Response) return target;
|
|
4331
|
-
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
4332
|
-
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4333
|
-
if (user && await users.passwordAccount(user.id)) {
|
|
4334
|
-
if (!await sendLinkEmail(user, "reset", target, localeOf(data))) return unavailable(c);
|
|
4335
|
-
}
|
|
4336
|
-
return accepted(c);
|
|
4337
|
-
});
|
|
4338
|
-
app.post("/auth/password/reset", async (c) => {
|
|
4339
|
-
const data = await body(c);
|
|
4340
|
-
const policy = checkPasswordPolicy(data.password, minLength);
|
|
4341
|
-
if (policy) return error(c, 400, "weak_password", policy);
|
|
4342
|
-
const consumed = await consume(data, "reset");
|
|
4343
|
-
const user = consumed.userId ? await users.findById(consumed.userId) : null;
|
|
4344
|
-
const account = user ? await users.passwordAccount(user.id) : null;
|
|
4345
|
-
if (!user || !account) return invalidVerification(c, consumed);
|
|
4346
|
-
await users.updateAccount(account.id, { secret: await hashPassword(data.password), failedAttempts: 0, lockedUntil: 0 });
|
|
4347
|
-
const sessionVersion = user.sessionVersion + 1;
|
|
4348
|
-
await users.updateUser(user.id, { emailVerified: true, sessionVersion, wrongCodes: 0 });
|
|
4349
|
-
await users.clearVerifications(user.id);
|
|
4350
|
-
const result = await ctx.startSession(c, toMadauthUser(user), ["pwd"], { sv: sessionVersion });
|
|
4351
|
-
await ctx.emit("password.reset", { user: result });
|
|
4352
|
-
await ctx.emit("user.signed_in", { user: result, method: "password" });
|
|
4353
|
-
return c.json({ user: result });
|
|
4354
|
-
});
|
|
4355
|
-
}
|
|
4356
|
-
|
|
4357
|
-
// src/users.ts
|
|
4358
|
-
import { randomBytes as randomBytes2 } from "crypto";
|
|
4359
|
-
var MAX_CODE_ATTEMPTS = 5;
|
|
4360
|
-
var MAX_WRONG_CODES = 10;
|
|
4361
|
-
var newId = (prefix) => `${prefix}_${randomBytes2(16).toString("base64url")}`;
|
|
4362
|
-
function passwordAccountKey(userId) {
|
|
4363
|
-
return `password:${userId}`;
|
|
4364
|
-
}
|
|
4365
4153
|
var Users = class {
|
|
4366
4154
|
/** `codeKey` keys the e-mail codes (see deriveCodeKey); only needed to issue and check them. */
|
|
4367
4155
|
constructor(store, codeKey) {
|
|
@@ -4379,11 +4167,22 @@ var Users = class {
|
|
|
4379
4167
|
return await this.store.findOne("user", { id });
|
|
4380
4168
|
}
|
|
4381
4169
|
async passwordAccount(userId) {
|
|
4382
|
-
return
|
|
4170
|
+
return this.findAccountByKey(passwordAccountKey(userId));
|
|
4383
4171
|
}
|
|
4384
|
-
/**
|
|
4385
|
-
async
|
|
4386
|
-
const
|
|
4172
|
+
/** How the user signs in, from their accounts: e.g. `['google']` for a user without a password. */
|
|
4173
|
+
async signInMethods(userId) {
|
|
4174
|
+
const accounts = await this.store.findMany("account", { userId });
|
|
4175
|
+
const methods = accounts.map((account) => String(account.key).split(":")[0]);
|
|
4176
|
+
return SIGN_IN_METHODS.filter((method) => methods.includes(method));
|
|
4177
|
+
}
|
|
4178
|
+
async findAccountByKey(key) {
|
|
4179
|
+
return await this.store.findOne("account", { key });
|
|
4180
|
+
}
|
|
4181
|
+
/**
|
|
4182
|
+
* Creates a user with their first account. Resolves to null if the e-mail address or the account key is
|
|
4183
|
+
* taken. `account.key` is `password:<userId>` for a password (its hash as `secret`), or e.g. `google:<sub>`.
|
|
4184
|
+
*/
|
|
4185
|
+
async createUser(data) {
|
|
4387
4186
|
const user = {
|
|
4388
4187
|
id: newId("usr"),
|
|
4389
4188
|
email: data.email,
|
|
@@ -4393,45 +4192,66 @@ var Users = class {
|
|
|
4393
4192
|
sessionVersion: 0,
|
|
4394
4193
|
lastMailAt: 0,
|
|
4395
4194
|
wrongCodes: 0,
|
|
4396
|
-
|
|
4195
|
+
claims: null,
|
|
4196
|
+
createdAt: Date.now()
|
|
4397
4197
|
};
|
|
4398
4198
|
if (!await this.store.create("user", user)) return null;
|
|
4399
|
-
const account =
|
|
4400
|
-
|
|
4401
|
-
userId: user.id,
|
|
4402
|
-
key: passwordAccountKey(user.id),
|
|
4403
|
-
secret: data.passwordHash,
|
|
4404
|
-
failedAttempts: 0,
|
|
4405
|
-
lockedUntil: 0,
|
|
4406
|
-
createdAt: now
|
|
4407
|
-
};
|
|
4408
|
-
if (!await this.store.create("account", account)) {
|
|
4199
|
+
const account = typeof data.account === "function" ? data.account(user.id) : data.account;
|
|
4200
|
+
if (!await this.linkAccount(user.id, account)) {
|
|
4409
4201
|
await this.store.delete("user", { id: user.id });
|
|
4410
4202
|
return null;
|
|
4411
4203
|
}
|
|
4412
4204
|
return user;
|
|
4413
4205
|
}
|
|
4414
4206
|
/**
|
|
4415
|
-
*
|
|
4416
|
-
*
|
|
4207
|
+
* A provider verified the user's address: an unconfirmed password sign-up with it, whose password nobody
|
|
4208
|
+
* has proven, is dropped (the account and its pending links and codes), and the user counts as verified.
|
|
4209
|
+
*/
|
|
4210
|
+
async verifyByProvider(user) {
|
|
4211
|
+
if (user.emailVerified) return;
|
|
4212
|
+
await this.store.delete("account", { key: passwordAccountKey(user.id) });
|
|
4213
|
+
await this.clearVerifications(user.id);
|
|
4214
|
+
await this.updateUser(user.id, { emailVerified: true, wrongCodes: 0 });
|
|
4215
|
+
}
|
|
4216
|
+
/** Removes an account record, e.g. one left behind by a deletion that did not finish. */
|
|
4217
|
+
async deleteAccount(id) {
|
|
4218
|
+
await this.store.delete("account", { id });
|
|
4219
|
+
}
|
|
4220
|
+
/** Adds a sign-in method to a user. Resolves to null if the account key is taken. */
|
|
4221
|
+
async linkAccount(userId, account) {
|
|
4222
|
+
const record = {
|
|
4223
|
+
id: newId("acc"),
|
|
4224
|
+
userId,
|
|
4225
|
+
key: account.key,
|
|
4226
|
+
secret: account.secret ?? null,
|
|
4227
|
+
failedAttempts: 0,
|
|
4228
|
+
lockedUntil: 0,
|
|
4229
|
+
email: account.email ?? null,
|
|
4230
|
+
createdAt: Date.now()
|
|
4231
|
+
};
|
|
4232
|
+
return await this.store.create("account", record) ? record : null;
|
|
4233
|
+
}
|
|
4234
|
+
/**
|
|
4235
|
+
* Deletes the user and everything stored for them. Resolves to false if there is no such user (any more).
|
|
4417
4236
|
*/
|
|
4418
|
-
async
|
|
4419
|
-
const user = await this.
|
|
4420
|
-
if (!user) return
|
|
4421
|
-
if (await this.store.delete("user", { id: user.id }) !== 1) return
|
|
4237
|
+
async deleteById(id) {
|
|
4238
|
+
const user = await this.findById(id);
|
|
4239
|
+
if (!user) return false;
|
|
4240
|
+
if (await this.store.delete("user", { id: user.id }) !== 1) return false;
|
|
4422
4241
|
try {
|
|
4423
4242
|
await this.store.delete("account", { userId: user.id });
|
|
4424
4243
|
await this.store.delete("verification", { userId: user.id });
|
|
4425
4244
|
} catch (e) {
|
|
4426
4245
|
console.error(`[madauth] Deleted user ${user.id}, but not all of their records: ${e.message}`);
|
|
4427
4246
|
}
|
|
4428
|
-
return
|
|
4247
|
+
return true;
|
|
4429
4248
|
}
|
|
4430
4249
|
async updateUser(id, patch) {
|
|
4431
4250
|
await this.store.update("user", { id }, patch);
|
|
4432
4251
|
}
|
|
4252
|
+
/** Changes an account. Resolves to false if it is gone meanwhile. */
|
|
4433
4253
|
async updateAccount(id, patch) {
|
|
4434
|
-
await this.store.update("account", { id }, patch);
|
|
4254
|
+
return await this.store.update("account", { id }, patch) === 1;
|
|
4435
4255
|
}
|
|
4436
4256
|
/**
|
|
4437
4257
|
* Counts a sign-in attempt: writes `patch` only if the account's `failedAttempts` is still the value that
|
|
@@ -4489,98 +4309,490 @@ var Users = class {
|
|
|
4489
4309
|
if (attempts >= MAX_CODE_ATTEMPTS) await this.store.delete("verification", { id: record.id });
|
|
4490
4310
|
return { userId: null, locked: wrongCodes >= MAX_WRONG_CODES };
|
|
4491
4311
|
}
|
|
4492
|
-
return { userId: await this.consume(record), locked: false };
|
|
4493
|
-
}
|
|
4494
|
-
/** Counts a code for the user and resolves to the new count; null if other requests kept changing it. */
|
|
4495
|
-
async countWrongCode(user) {
|
|
4496
|
-
let current = user;
|
|
4497
|
-
for (let attempt = 0; attempt < 3 && current; attempt++) {
|
|
4498
|
-
const wrongCodes = (current.wrongCodes ?? 0) + 1;
|
|
4499
|
-
if (await this.store.update("user", { id: user.id, wrongCodes: current.wrongCodes ?? null }, { wrongCodes }) === 1) {
|
|
4500
|
-
return wrongCodes;
|
|
4501
|
-
}
|
|
4502
|
-
current = await this.findById(user.id);
|
|
4312
|
+
return { userId: await this.consume(record), locked: false };
|
|
4313
|
+
}
|
|
4314
|
+
/** Counts a code for the user and resolves to the new count; null if other requests kept changing it. */
|
|
4315
|
+
async countWrongCode(user) {
|
|
4316
|
+
let current = user;
|
|
4317
|
+
for (let attempt = 0; attempt < 3 && current; attempt++) {
|
|
4318
|
+
const wrongCodes = (current.wrongCodes ?? 0) + 1;
|
|
4319
|
+
if (await this.store.update("user", { id: user.id, wrongCodes: current.wrongCodes ?? null }, { wrongCodes }) === 1) {
|
|
4320
|
+
return wrongCodes;
|
|
4321
|
+
}
|
|
4322
|
+
current = await this.findById(user.id);
|
|
4323
|
+
}
|
|
4324
|
+
return null;
|
|
4325
|
+
}
|
|
4326
|
+
async consume(record) {
|
|
4327
|
+
const deleted = await this.store.delete("verification", { id: record.id });
|
|
4328
|
+
if (deleted !== 1 || record.expiresAt <= Date.now()) return null;
|
|
4329
|
+
return record.userId;
|
|
4330
|
+
}
|
|
4331
|
+
};
|
|
4332
|
+
|
|
4333
|
+
// src/webhooks.ts
|
|
4334
|
+
import { createHmac as createHmac2, randomBytes as randomBytes3, randomUUID, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
4335
|
+
var WEBHOOK_TYPES = [
|
|
4336
|
+
"email.verify",
|
|
4337
|
+
"email.reset",
|
|
4338
|
+
"email.already_registered",
|
|
4339
|
+
"email.no_password",
|
|
4340
|
+
"signup.before",
|
|
4341
|
+
"user.created",
|
|
4342
|
+
"email.verified",
|
|
4343
|
+
"email.password_reset",
|
|
4344
|
+
"user.signed_in",
|
|
4345
|
+
"user.deleted",
|
|
4346
|
+
"user.claims_changed"
|
|
4347
|
+
];
|
|
4348
|
+
var WEBHOOK_TIMEOUT_MS = 1e4;
|
|
4349
|
+
var MAX_LOCALE_LENGTH = 35;
|
|
4350
|
+
function localeOf(value) {
|
|
4351
|
+
return typeof value === "string" && value.length <= MAX_LOCALE_LENGTH ? value : void 0;
|
|
4352
|
+
}
|
|
4353
|
+
var REQUIRED_EMAIL_TYPES = ["email.verify", "email.reset"];
|
|
4354
|
+
var SECRET_PREFIX = "whsec_";
|
|
4355
|
+
var DEV_WEBHOOK_RECEIVER_URL = "https://github.com/inouiw/madAuth-webhooks/tree/main/dev-receiver";
|
|
4356
|
+
var WEBHOOK_TOLERANCE_SECONDS = 5 * 60;
|
|
4357
|
+
function generateWebhookSecret() {
|
|
4358
|
+
return `${SECRET_PREFIX}${randomBytes3(32).toString("base64")}`;
|
|
4359
|
+
}
|
|
4360
|
+
function checkWebhookSecret(secret) {
|
|
4361
|
+
if (!secret.startsWith(SECRET_PREFIX)) return `must start with "${SECRET_PREFIX}"`;
|
|
4362
|
+
const key = Buffer.from(secret.slice(SECRET_PREFIX.length), "base64");
|
|
4363
|
+
if (key.length < 24 || key.length > 64) return "must contain 24 to 64 bytes in base64";
|
|
4364
|
+
return null;
|
|
4365
|
+
}
|
|
4366
|
+
function hmac2(secret, content) {
|
|
4367
|
+
const key = Buffer.from(secret.slice(SECRET_PREFIX.length), "base64");
|
|
4368
|
+
return createHmac2("sha256", key).update(content).digest("base64");
|
|
4369
|
+
}
|
|
4370
|
+
function signWebhook(secret, id, timestamp, body) {
|
|
4371
|
+
return `v1,${hmac2(secret, `${id}.${timestamp}.${body}`)}`;
|
|
4372
|
+
}
|
|
4373
|
+
function createWebhookClient(settings, fetchImpl = fetch) {
|
|
4374
|
+
const wants = (type) => settings.events.has(type);
|
|
4375
|
+
return {
|
|
4376
|
+
wants,
|
|
4377
|
+
async call(type, data, timeoutMs) {
|
|
4378
|
+
if (!wants(type)) return { ok: true, body: void 0 };
|
|
4379
|
+
const id = `msg_${randomUUID()}`;
|
|
4380
|
+
const timestamp = Math.floor(Date.now() / 1e3);
|
|
4381
|
+
const body = JSON.stringify({ type, data });
|
|
4382
|
+
let response;
|
|
4383
|
+
try {
|
|
4384
|
+
response = await fetchImpl(settings.url, {
|
|
4385
|
+
method: "POST",
|
|
4386
|
+
headers: {
|
|
4387
|
+
"Content-Type": "application/json",
|
|
4388
|
+
"webhook-id": id,
|
|
4389
|
+
"webhook-timestamp": String(timestamp),
|
|
4390
|
+
"webhook-signature": signWebhook(settings.secret, id, timestamp, body)
|
|
4391
|
+
},
|
|
4392
|
+
body,
|
|
4393
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
4394
|
+
});
|
|
4395
|
+
} catch (e) {
|
|
4396
|
+
const reason = e.name === "TimeoutError" ? `no answer within ${timeoutMs} ms` : e.message;
|
|
4397
|
+
return { ok: false, reason };
|
|
4398
|
+
}
|
|
4399
|
+
const text = await response.text().catch(() => "");
|
|
4400
|
+
if (!response.ok) return { ok: false, reason: `HTTP ${response.status}` };
|
|
4401
|
+
let parsed;
|
|
4402
|
+
try {
|
|
4403
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
4404
|
+
} catch {
|
|
4405
|
+
parsed = void 0;
|
|
4406
|
+
}
|
|
4407
|
+
return { ok: true, body: parsed };
|
|
4408
|
+
}
|
|
4409
|
+
};
|
|
4410
|
+
}
|
|
4411
|
+
|
|
4412
|
+
// src/routes/google.ts
|
|
4413
|
+
var NONCE_COOKIE = "madauth_nonce";
|
|
4414
|
+
var NONCE_TYP = "madauth-nonce+jwt";
|
|
4415
|
+
var NONCE_TTL = 5 * 60;
|
|
4416
|
+
var OAUTH_COOKIE = "madauth_oauth";
|
|
4417
|
+
var OAUTH_TYP = "madauth-oauth-state+jwt";
|
|
4418
|
+
var OAUTH_TTL = 10 * 60;
|
|
4419
|
+
var GOOGLE_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth";
|
|
4420
|
+
var GOOGLE_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
|
|
4421
|
+
var REDIRECT_ERROR_PARAM = "madauth_error";
|
|
4422
|
+
async function pkceChallenge(verifier) {
|
|
4423
|
+
const digest2 = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
4424
|
+
return base64url_exports.encode(new Uint8Array(digest2));
|
|
4425
|
+
}
|
|
4426
|
+
function googleRoutes(app, ctx, google) {
|
|
4427
|
+
const { config, keys, secure, users } = ctx;
|
|
4428
|
+
const { issuer } = config;
|
|
4429
|
+
const callbackUrl = `${issuer}/auth/google/callback`;
|
|
4430
|
+
const resolveUser = async (profile, locale) => {
|
|
4431
|
+
const key = googleAccountKey(profile.sub);
|
|
4432
|
+
const emailNormalized = normalizeEmail(profile.email);
|
|
4433
|
+
const signedIn = (user) => ({ ok: true, user: toMadauthUser(user, profile), sv: user.sessionVersion });
|
|
4434
|
+
const account = await users.findAccountByKey(key);
|
|
4435
|
+
if (account) {
|
|
4436
|
+
const user = await users.findById(account.userId);
|
|
4437
|
+
if (user) {
|
|
4438
|
+
if (account.email !== profile.email) await users.updateAccount(account.id, { email: profile.email });
|
|
4439
|
+
return signedIn(user);
|
|
4440
|
+
}
|
|
4441
|
+
await users.deleteAccount(account.id);
|
|
4442
|
+
}
|
|
4443
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
4444
|
+
const existing = await users.findByEmail(emailNormalized);
|
|
4445
|
+
if (existing) {
|
|
4446
|
+
await users.verifyByProvider(existing);
|
|
4447
|
+
if (!await users.linkAccount(existing.id, { key, email: profile.email })) {
|
|
4448
|
+
const linked = await users.findAccountByKey(key);
|
|
4449
|
+
const owner = linked && await users.findById(linked.userId);
|
|
4450
|
+
if (!owner) return { ok: false, error: "temporarily_unavailable", message: "Please try again." };
|
|
4451
|
+
return signedIn(owner);
|
|
4452
|
+
}
|
|
4453
|
+
return signedIn(existing);
|
|
4454
|
+
}
|
|
4455
|
+
if (attempt === 0) {
|
|
4456
|
+
const check2 = await ctx.checkSignup({ email: profile.email, name: profile.name, locale, method: "google" });
|
|
4457
|
+
if (!check2.ok) {
|
|
4458
|
+
return check2.reason === "rejected" ? { ok: false, error: "signup_rejected", message: check2.message } : { ok: false, error: "temporarily_unavailable", message: "Signing up is not possible right now. Please try again later." };
|
|
4459
|
+
}
|
|
4460
|
+
}
|
|
4461
|
+
const user = await users.createUser({
|
|
4462
|
+
email: profile.email,
|
|
4463
|
+
emailNormalized,
|
|
4464
|
+
name: profile.name ?? null,
|
|
4465
|
+
emailVerified: true,
|
|
4466
|
+
account: { key, email: profile.email }
|
|
4467
|
+
});
|
|
4468
|
+
if (user) {
|
|
4469
|
+
await ctx.emit("user.created", { user: toMadauthUser(user), method: "google" });
|
|
4470
|
+
return signedIn(user);
|
|
4471
|
+
}
|
|
4472
|
+
}
|
|
4473
|
+
return { ok: false, error: "temporarily_unavailable", message: "Please try again." };
|
|
4474
|
+
};
|
|
4475
|
+
const disabled = (c) => c.json({ error: "method_disabled", message: "Google sign-in is switched off." }, 403);
|
|
4476
|
+
app.post("/auth/google/nonce", async (c) => {
|
|
4477
|
+
if (!await ctx.enabled("google")) return disabled(c);
|
|
4478
|
+
const nonce = randomString();
|
|
4479
|
+
const token = await signToken(await keys, issuer, NONCE_TYP, { nonce }, NONCE_TTL);
|
|
4480
|
+
setCookie(c, NONCE_COOKIE, token, {
|
|
4481
|
+
path: "/auth/google",
|
|
4482
|
+
httpOnly: true,
|
|
4483
|
+
secure,
|
|
4484
|
+
sameSite: "Strict",
|
|
4485
|
+
maxAge: NONCE_TTL
|
|
4486
|
+
});
|
|
4487
|
+
return c.json({ nonce });
|
|
4488
|
+
});
|
|
4489
|
+
app.post("/auth/google/verify", async (c) => {
|
|
4490
|
+
if (!await ctx.enabled("google")) return disabled(c);
|
|
4491
|
+
const body = await c.req.json().catch(() => ({}));
|
|
4492
|
+
if (typeof body.credential !== "string" || !body.credential) {
|
|
4493
|
+
return c.json({ error: "verification_failed", message: "credential is missing" }, 400);
|
|
4494
|
+
}
|
|
4495
|
+
const nonceClaims = await readToken(await keys, issuer, NONCE_TYP, getCookie(c, NONCE_COOKIE));
|
|
4496
|
+
if (!nonceClaims) {
|
|
4497
|
+
return c.json({ error: "verification_failed", message: "nonce cookie missing or expired" }, 401);
|
|
4498
|
+
}
|
|
4499
|
+
const result = await verifyGoogleIdToken(body.credential, {
|
|
4500
|
+
clientId: google.clientId,
|
|
4501
|
+
nonce: nonceClaims.nonce,
|
|
4502
|
+
keys: config.jwksResolver
|
|
4503
|
+
});
|
|
4504
|
+
if (!result.ok) {
|
|
4505
|
+
return c.json({ error: result.error, message: result.reason }, result.error === "email_unverified" ? 403 : 401);
|
|
4506
|
+
}
|
|
4507
|
+
deleteCookie(c, NONCE_COOKIE, { path: "/auth/google", secure });
|
|
4508
|
+
const resolved = await resolveUser(result.profile, localeOf(body.locale));
|
|
4509
|
+
if (!resolved.ok) {
|
|
4510
|
+
return c.json({ error: resolved.error, message: resolved.message }, resolved.error === "signup_rejected" ? 403 : 503);
|
|
4511
|
+
}
|
|
4512
|
+
const user = await ctx.startSession(c, resolved.user, ["google"], { sv: resolved.sv });
|
|
4513
|
+
await ctx.emit("user.signed_in", { user, method: "google" });
|
|
4514
|
+
return c.json({ user });
|
|
4515
|
+
});
|
|
4516
|
+
const requireCodeFlow = async (c, next) => {
|
|
4517
|
+
if (!google.clientSecret) return c.json({ error: "not_found" }, 404);
|
|
4518
|
+
if (!await ctx.enabled("google")) return disabled(c);
|
|
4519
|
+
await next();
|
|
4520
|
+
};
|
|
4521
|
+
app.get("/auth/google/start", requireCodeFlow, async (c) => {
|
|
4522
|
+
const returnUrl = ctx.allowedUrl(c.req.query("return_to"));
|
|
4523
|
+
if (!returnUrl) return c.text("return_to must be an absolute URL whose origin is in ALLOWED_ORIGINS", 400);
|
|
4524
|
+
const oauth = {
|
|
4525
|
+
state: randomString(),
|
|
4526
|
+
nonce: randomString(),
|
|
4527
|
+
verifier: randomString(),
|
|
4528
|
+
returnTo: returnUrl.href,
|
|
4529
|
+
locale: localeOf(c.req.query("locale"))
|
|
4530
|
+
};
|
|
4531
|
+
const token = await signToken(await keys, issuer, OAUTH_TYP, { ...oauth }, OAUTH_TTL);
|
|
4532
|
+
setCookie(c, OAUTH_COOKIE, token, {
|
|
4533
|
+
path: "/auth/google",
|
|
4534
|
+
httpOnly: true,
|
|
4535
|
+
secure,
|
|
4536
|
+
sameSite: "Lax",
|
|
4537
|
+
maxAge: OAUTH_TTL
|
|
4538
|
+
});
|
|
4539
|
+
const url = new URL(GOOGLE_AUTH_ENDPOINT);
|
|
4540
|
+
url.search = new URLSearchParams({
|
|
4541
|
+
client_id: google.clientId,
|
|
4542
|
+
redirect_uri: callbackUrl,
|
|
4543
|
+
response_type: "code",
|
|
4544
|
+
scope: "openid email profile",
|
|
4545
|
+
state: oauth.state,
|
|
4546
|
+
nonce: oauth.nonce,
|
|
4547
|
+
code_challenge: await pkceChallenge(oauth.verifier),
|
|
4548
|
+
code_challenge_method: "S256"
|
|
4549
|
+
}).toString();
|
|
4550
|
+
return c.redirect(url.href, 302);
|
|
4551
|
+
});
|
|
4552
|
+
app.get("/auth/google/callback", requireCodeFlow, async (c) => {
|
|
4553
|
+
const oauth = await readToken(await keys, issuer, OAUTH_TYP, getCookie(c, OAUTH_COOKIE));
|
|
4554
|
+
if (!oauth) return c.text("Sign-in expired or was started in another browser. Please try again.", 400);
|
|
4555
|
+
deleteCookie(c, OAUTH_COOKIE, { path: "/auth/google", secure });
|
|
4556
|
+
const back = (error) => {
|
|
4557
|
+
const url = new URL(oauth.returnTo);
|
|
4558
|
+
if (error) url.hash = `${REDIRECT_ERROR_PARAM}=${error}`;
|
|
4559
|
+
return c.redirect(url.href, 302);
|
|
4560
|
+
};
|
|
4561
|
+
if (c.req.query("error")) return back(c.req.query("error") === "access_denied" ? "cancelled" : "verification_failed");
|
|
4562
|
+
const code = c.req.query("code");
|
|
4563
|
+
if (!code || c.req.query("state") !== oauth.state) return back("verification_failed");
|
|
4564
|
+
let idToken;
|
|
4565
|
+
try {
|
|
4566
|
+
const res = await fetch(GOOGLE_TOKEN_ENDPOINT, {
|
|
4567
|
+
method: "POST",
|
|
4568
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
4569
|
+
body: new URLSearchParams({
|
|
4570
|
+
code,
|
|
4571
|
+
client_id: google.clientId,
|
|
4572
|
+
client_secret: google.clientSecret,
|
|
4573
|
+
redirect_uri: callbackUrl,
|
|
4574
|
+
grant_type: "authorization_code",
|
|
4575
|
+
code_verifier: oauth.verifier
|
|
4576
|
+
})
|
|
4577
|
+
});
|
|
4578
|
+
if (!res.ok) return back("verification_failed");
|
|
4579
|
+
({ id_token: idToken } = await res.json());
|
|
4580
|
+
} catch {
|
|
4581
|
+
return back("verification_failed");
|
|
4582
|
+
}
|
|
4583
|
+
if (typeof idToken !== "string") return back("verification_failed");
|
|
4584
|
+
const result = await verifyGoogleIdToken(idToken, {
|
|
4585
|
+
clientId: google.clientId,
|
|
4586
|
+
nonce: oauth.nonce,
|
|
4587
|
+
keys: config.jwksResolver
|
|
4588
|
+
});
|
|
4589
|
+
if (!result.ok) return back(result.error);
|
|
4590
|
+
const resolved = await resolveUser(result.profile, typeof oauth.locale === "string" ? oauth.locale : void 0);
|
|
4591
|
+
if (!resolved.ok) return back(resolved.error);
|
|
4592
|
+
const user = await ctx.startSession(c, resolved.user, ["google"], { sv: resolved.sv });
|
|
4593
|
+
await ctx.emit("user.signed_in", { user, method: "google" });
|
|
4594
|
+
return back();
|
|
4595
|
+
});
|
|
4596
|
+
}
|
|
4597
|
+
|
|
4598
|
+
// src/routes/password.ts
|
|
4599
|
+
var FREE_ATTEMPTS = 5;
|
|
4600
|
+
var MAX_LOCK_MS = 15 * 60 * 1e3;
|
|
4601
|
+
var MAIL_INTERVAL_MS = 60 * 1e3;
|
|
4602
|
+
var VERIFY_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
4603
|
+
var RESET_TTL_MS = 30 * 60 * 1e3;
|
|
4604
|
+
var VERIFY_LINK_PARAM = "madauth_verify";
|
|
4605
|
+
var RESET_LINK_PARAM = "madauth_reset";
|
|
4606
|
+
var MAX_NAME_LENGTH = 100;
|
|
4607
|
+
function passwordRoutes(app, ctx, password, users, webhook) {
|
|
4608
|
+
const { minLength } = password;
|
|
4609
|
+
const disabled = (c) => c.json({ error: "method_disabled", message: "E-mail & password sign-in is switched off." }, 403);
|
|
4610
|
+
app.use("/auth/password/*", async (c, next) => {
|
|
4611
|
+
if (!await ctx.enabled("password")) return disabled(c);
|
|
4612
|
+
await next();
|
|
4613
|
+
});
|
|
4614
|
+
const body = async (c) => {
|
|
4615
|
+
const data = await c.req.json().catch(() => null);
|
|
4616
|
+
return data && typeof data === "object" ? data : {};
|
|
4617
|
+
};
|
|
4618
|
+
const error = (c, status, code, message2) => c.json({ error: code, message: message2 }, status);
|
|
4619
|
+
const unavailable = (c) => error(c, 503, "temporarily_unavailable", "E-mails can not be sent right now. Please try again later.");
|
|
4620
|
+
const accepted = (c) => c.json({}, 202);
|
|
4621
|
+
const redirectTarget = (c, value) => {
|
|
4622
|
+
const url = ctx.allowedUrl(value);
|
|
4623
|
+
return url ?? error(c, 400, "invalid_options", "redirectTo must be an absolute URL whose origin is in ALLOWED_ORIGINS.");
|
|
4624
|
+
};
|
|
4625
|
+
const sendEmail = async (user, type, data) => {
|
|
4626
|
+
if (Date.now() - user.lastMailAt < MAIL_INTERVAL_MS) return true;
|
|
4627
|
+
const result = await webhook.call(type, { to: user.email, user: { id: user.id, name: user.name ?? void 0 }, ...data }, WEBHOOK_TIMEOUT_MS);
|
|
4628
|
+
if (!result.ok) {
|
|
4629
|
+
console.error(`[madauth] Webhook "${type}" for ${user.email} failed: ${result.reason}`);
|
|
4630
|
+
return false;
|
|
4631
|
+
}
|
|
4632
|
+
await users.updateUser(user.id, { lastMailAt: Date.now() });
|
|
4633
|
+
return true;
|
|
4634
|
+
};
|
|
4635
|
+
const sendLinkEmail = async (user, purpose, target, locale) => {
|
|
4636
|
+
if (Date.now() - user.lastMailAt < MAIL_INTERVAL_MS) return true;
|
|
4637
|
+
const ttl = purpose === "verify" ? VERIFY_TTL_MS : RESET_TTL_MS;
|
|
4638
|
+
const { token, code } = await users.issueVerification(user.id, purpose, ttl);
|
|
4639
|
+
const link = new URL(target);
|
|
4640
|
+
link.hash = `${purpose === "verify" ? VERIFY_LINK_PARAM : RESET_LINK_PARAM}=${token}`;
|
|
4641
|
+
return sendEmail(user, purpose === "verify" ? "email.verify" : "email.reset", {
|
|
4642
|
+
link: link.href,
|
|
4643
|
+
code,
|
|
4644
|
+
expiresAt: Date.now() + ttl,
|
|
4645
|
+
site: target.host,
|
|
4646
|
+
locale
|
|
4647
|
+
});
|
|
4648
|
+
};
|
|
4649
|
+
const sendAccountEmail = async (user, type, target, locale) => {
|
|
4650
|
+
if (!webhook.wants(type)) return true;
|
|
4651
|
+
const methods = await users.signInMethods(user.id);
|
|
4652
|
+
return sendEmail(user, type, { link: target.href, site: target.host, locale, methods });
|
|
4653
|
+
};
|
|
4654
|
+
const consume = async (data, purpose) => {
|
|
4655
|
+
if (typeof data.token === "string" && data.token) {
|
|
4656
|
+
return { userId: await users.consumeLinkToken(data.token, purpose), via: "link" };
|
|
4657
|
+
}
|
|
4658
|
+
if (isValidEmail(data.email) && typeof data.code === "string") {
|
|
4659
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4660
|
+
if (!user) return { userId: null, via: "code" };
|
|
4661
|
+
return { ...await users.consumeCode(user, purpose, data.code.replace(/\s/g, "")), via: "code" };
|
|
4503
4662
|
}
|
|
4504
|
-
return null;
|
|
4505
|
-
}
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
return record.userId;
|
|
4510
|
-
}
|
|
4511
|
-
};
|
|
4512
|
-
|
|
4513
|
-
// src/webhooks.ts
|
|
4514
|
-
import { createHmac as createHmac2, randomBytes as randomBytes3, randomUUID, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
4515
|
-
var WEBHOOK_TYPES = [
|
|
4516
|
-
"email.verify",
|
|
4517
|
-
"email.reset",
|
|
4518
|
-
"email.already_registered",
|
|
4519
|
-
"signup.before",
|
|
4520
|
-
"user.created",
|
|
4521
|
-
"email.verified",
|
|
4522
|
-
"password.reset",
|
|
4523
|
-
"user.signed_in",
|
|
4524
|
-
"user.deleted",
|
|
4525
|
-
"roles.changed"
|
|
4526
|
-
];
|
|
4527
|
-
var REQUIRED_EMAIL_TYPES = ["email.verify", "email.reset"];
|
|
4528
|
-
var SECRET_PREFIX = "whsec_";
|
|
4529
|
-
var DEV_WEBHOOK_RECEIVER_URL = "https://github.com/inouiw/madAuth-webhooks/tree/main/dev-receiver";
|
|
4530
|
-
var WEBHOOK_TOLERANCE_SECONDS = 5 * 60;
|
|
4531
|
-
function generateWebhookSecret() {
|
|
4532
|
-
return `${SECRET_PREFIX}${randomBytes3(32).toString("base64")}`;
|
|
4533
|
-
}
|
|
4534
|
-
function checkWebhookSecret(secret) {
|
|
4535
|
-
if (!secret.startsWith(SECRET_PREFIX)) return `must start with "${SECRET_PREFIX}"`;
|
|
4536
|
-
const key = Buffer.from(secret.slice(SECRET_PREFIX.length), "base64");
|
|
4537
|
-
if (key.length < 24 || key.length > 64) return "must contain 24 to 64 bytes in base64";
|
|
4538
|
-
return null;
|
|
4539
|
-
}
|
|
4540
|
-
function hmac2(secret, content) {
|
|
4541
|
-
const key = Buffer.from(secret.slice(SECRET_PREFIX.length), "base64");
|
|
4542
|
-
return createHmac2("sha256", key).update(content).digest("base64");
|
|
4543
|
-
}
|
|
4544
|
-
function signWebhook(secret, id, timestamp, body) {
|
|
4545
|
-
return `v1,${hmac2(secret, `${id}.${timestamp}.${body}`)}`;
|
|
4546
|
-
}
|
|
4547
|
-
function createWebhookClient(settings, fetchImpl = fetch) {
|
|
4548
|
-
const wants = (type) => settings.events.has(type);
|
|
4549
|
-
return {
|
|
4550
|
-
wants,
|
|
4551
|
-
async call(type, data, timeoutMs) {
|
|
4552
|
-
if (!wants(type)) return { ok: true, body: void 0 };
|
|
4553
|
-
const id = `msg_${randomUUID()}`;
|
|
4554
|
-
const timestamp = Math.floor(Date.now() / 1e3);
|
|
4555
|
-
const body = JSON.stringify({ type, data });
|
|
4556
|
-
let response;
|
|
4557
|
-
try {
|
|
4558
|
-
response = await fetchImpl(settings.url, {
|
|
4559
|
-
method: "POST",
|
|
4560
|
-
headers: {
|
|
4561
|
-
"Content-Type": "application/json",
|
|
4562
|
-
"webhook-id": id,
|
|
4563
|
-
"webhook-timestamp": String(timestamp),
|
|
4564
|
-
"webhook-signature": signWebhook(settings.secret, id, timestamp, body)
|
|
4565
|
-
},
|
|
4566
|
-
body,
|
|
4567
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
4568
|
-
});
|
|
4569
|
-
} catch (e) {
|
|
4570
|
-
const reason = e.name === "TimeoutError" ? `no answer within ${timeoutMs} ms` : e.message;
|
|
4571
|
-
return { ok: false, reason };
|
|
4572
|
-
}
|
|
4573
|
-
const text = await response.text().catch(() => "");
|
|
4574
|
-
if (!response.ok) return { ok: false, reason: `HTTP ${response.status}` };
|
|
4575
|
-
let parsed;
|
|
4576
|
-
try {
|
|
4577
|
-
parsed = text ? JSON.parse(text) : void 0;
|
|
4578
|
-
} catch {
|
|
4579
|
-
parsed = void 0;
|
|
4580
|
-
}
|
|
4581
|
-
return { ok: true, body: parsed };
|
|
4663
|
+
return { userId: null, via: "code" };
|
|
4664
|
+
};
|
|
4665
|
+
const invalidVerification = (c, { via, locked }) => {
|
|
4666
|
+
if (locked) {
|
|
4667
|
+
return error(c, 429, "codes_locked", "Too many wrong codes. Please ask for a new e-mail and use the link in it.");
|
|
4582
4668
|
}
|
|
4669
|
+
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.");
|
|
4583
4670
|
};
|
|
4671
|
+
app.post("/auth/password/signin", async (c) => {
|
|
4672
|
+
const data = await body(c);
|
|
4673
|
+
const wrong = () => error(c, 401, "invalid_credentials", "E-mail or password is wrong.");
|
|
4674
|
+
const pw = typeof data.password === "string" ? data.password : "";
|
|
4675
|
+
if (!isValidEmail(data.email) || !pw || pw.length > MAX_PASSWORD_LENGTH * 4) return wrong();
|
|
4676
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4677
|
+
const account = user ? await users.passwordAccount(user.id) : null;
|
|
4678
|
+
if (!user || !account?.secret) {
|
|
4679
|
+
await verifyAgainstDummy(pw);
|
|
4680
|
+
return wrong();
|
|
4681
|
+
}
|
|
4682
|
+
const now = Date.now();
|
|
4683
|
+
if (account.lockedUntil > now) {
|
|
4684
|
+
const seconds = Math.ceil((account.lockedUntil - now) / 1e3);
|
|
4685
|
+
return error(c, 429, "too_many_attempts", `Too many failed attempts. Try again in ${seconds} seconds.`);
|
|
4686
|
+
}
|
|
4687
|
+
const failed = account.failedAttempts + 1;
|
|
4688
|
+
const lockedUntil = failed >= FREE_ATTEMPTS ? now + Math.min(2 ** (failed - FREE_ATTEMPTS) * 1e3, MAX_LOCK_MS) : 0;
|
|
4689
|
+
if (!await users.countAttempt(account, { failedAttempts: failed, lockedUntil })) {
|
|
4690
|
+
return error(c, 429, "too_many_attempts", "Too many attempts at once. Please try again.");
|
|
4691
|
+
}
|
|
4692
|
+
const { ok, needsRehash } = await verifyPassword(pw, account.secret);
|
|
4693
|
+
if (!ok) return wrong();
|
|
4694
|
+
await users.updateAccount(account.id, {
|
|
4695
|
+
failedAttempts: 0,
|
|
4696
|
+
lockedUntil: 0,
|
|
4697
|
+
...needsRehash ? { secret: await hashPassword(pw) } : {}
|
|
4698
|
+
});
|
|
4699
|
+
if (!user.emailVerified) {
|
|
4700
|
+
return error(c, 403, "email_unverified", "Please confirm your e-mail address first. We can send the e-mail again.");
|
|
4701
|
+
}
|
|
4702
|
+
const result = await ctx.startSession(c, toMadauthUser(user), ["pwd"], { sv: user.sessionVersion });
|
|
4703
|
+
await ctx.emit("user.signed_in", { user: result, method: "password" });
|
|
4704
|
+
return c.json({ user: result });
|
|
4705
|
+
});
|
|
4706
|
+
app.post("/auth/password/signup", async (c) => {
|
|
4707
|
+
const data = await body(c);
|
|
4708
|
+
const target = redirectTarget(c, data.redirectTo);
|
|
4709
|
+
if (target instanceof Response) return target;
|
|
4710
|
+
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
4711
|
+
const policy = checkPasswordPolicy(data.password, minLength);
|
|
4712
|
+
if (policy) return error(c, 400, "weak_password", policy);
|
|
4713
|
+
const name = typeof data.name === "string" && data.name.trim() ? data.name.trim().slice(0, MAX_NAME_LENGTH) : null;
|
|
4714
|
+
const email = data.email.trim();
|
|
4715
|
+
const locale = localeOf(data.locale);
|
|
4716
|
+
const check2 = await ctx.checkSignup({ email, name: name ?? void 0, locale, method: "password" });
|
|
4717
|
+
if (!check2.ok) return check2.reason === "rejected" ? error(c, 403, "signup_rejected", check2.message) : unavailable(c);
|
|
4718
|
+
const passwordHash = await hashPassword(data.password);
|
|
4719
|
+
const existing = await users.findByEmail(normalizeEmail(email));
|
|
4720
|
+
if (existing?.emailVerified) {
|
|
4721
|
+
return await sendAccountEmail(existing, "email.already_registered", target, locale) ? accepted(c) : unavailable(c);
|
|
4722
|
+
}
|
|
4723
|
+
if (existing) {
|
|
4724
|
+
if (Date.now() - existing.lastMailAt < MAIL_INTERVAL_MS) return accepted(c);
|
|
4725
|
+
const account = await users.passwordAccount(existing.id);
|
|
4726
|
+
if (account) await users.updateAccount(account.id, { secret: passwordHash, failedAttempts: 0, lockedUntil: 0 });
|
|
4727
|
+
else await users.linkAccount(existing.id, { key: passwordAccountKey(existing.id), secret: passwordHash });
|
|
4728
|
+
await users.updateUser(existing.id, { name });
|
|
4729
|
+
return await sendLinkEmail({ ...existing, name }, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
4730
|
+
}
|
|
4731
|
+
const user = await users.createUser({
|
|
4732
|
+
email,
|
|
4733
|
+
emailNormalized: normalizeEmail(email),
|
|
4734
|
+
name,
|
|
4735
|
+
emailVerified: false,
|
|
4736
|
+
account: (userId) => ({ key: passwordAccountKey(userId), secret: passwordHash })
|
|
4737
|
+
});
|
|
4738
|
+
if (!user) return accepted(c);
|
|
4739
|
+
await ctx.emit("user.created", { user: toMadauthUser(user), method: "password" });
|
|
4740
|
+
return await sendLinkEmail(user, "verify", target, locale) ? accepted(c) : unavailable(c);
|
|
4741
|
+
});
|
|
4742
|
+
app.post("/auth/password/send-verification", async (c) => {
|
|
4743
|
+
const data = await body(c);
|
|
4744
|
+
const target = redirectTarget(c, data.redirectTo);
|
|
4745
|
+
if (target instanceof Response) return target;
|
|
4746
|
+
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
4747
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4748
|
+
if (user && !user.emailVerified && await users.passwordAccount(user.id)) {
|
|
4749
|
+
if (!await sendLinkEmail(user, "verify", target, localeOf(data.locale))) return unavailable(c);
|
|
4750
|
+
}
|
|
4751
|
+
return accepted(c);
|
|
4752
|
+
});
|
|
4753
|
+
app.post("/auth/password/verify-email", async (c) => {
|
|
4754
|
+
const consumed = await consume(await body(c), "verify");
|
|
4755
|
+
const { userId, via } = consumed;
|
|
4756
|
+
const user = userId ? await users.findById(userId) : null;
|
|
4757
|
+
if (!user) return invalidVerification(c, consumed);
|
|
4758
|
+
await users.updateUser(user.id, { emailVerified: true, wrongCodes: 0 });
|
|
4759
|
+
const result = await ctx.startSession(c, toMadauthUser(user), ["pwd"], { sv: user.sessionVersion });
|
|
4760
|
+
await ctx.emit("email.verified", { user: result, via });
|
|
4761
|
+
await ctx.emit("user.signed_in", { user: result, method: "password" });
|
|
4762
|
+
return c.json({ user: result });
|
|
4763
|
+
});
|
|
4764
|
+
app.post("/auth/password/send-reset", async (c) => {
|
|
4765
|
+
const data = await body(c);
|
|
4766
|
+
const target = redirectTarget(c, data.redirectTo);
|
|
4767
|
+
if (target instanceof Response) return target;
|
|
4768
|
+
if (!isValidEmail(data.email)) return error(c, 400, "invalid_email", "This is not a valid e-mail address.");
|
|
4769
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4770
|
+
const locale = localeOf(data.locale);
|
|
4771
|
+
if (user && await users.passwordAccount(user.id)) {
|
|
4772
|
+
if (!await sendLinkEmail(user, "reset", target, locale)) return unavailable(c);
|
|
4773
|
+
} else if (user) {
|
|
4774
|
+
if (!await sendAccountEmail(user, "email.no_password", target, locale)) return unavailable(c);
|
|
4775
|
+
}
|
|
4776
|
+
return accepted(c);
|
|
4777
|
+
});
|
|
4778
|
+
app.post("/auth/password/reset", async (c) => {
|
|
4779
|
+
const data = await body(c);
|
|
4780
|
+
const policy = checkPasswordPolicy(data.password, minLength);
|
|
4781
|
+
if (policy) return error(c, 400, "weak_password", policy);
|
|
4782
|
+
const consumed = await consume(data, "reset");
|
|
4783
|
+
const user = consumed.userId ? await users.findById(consumed.userId) : null;
|
|
4784
|
+
const account = user ? await users.passwordAccount(user.id) : null;
|
|
4785
|
+
if (!user || !account) return invalidVerification(c, consumed);
|
|
4786
|
+
const secret = await hashPassword(data.password);
|
|
4787
|
+
if (!await users.updateAccount(account.id, { secret, failedAttempts: 0, lockedUntil: 0 })) return invalidVerification(c, consumed);
|
|
4788
|
+
const sessionVersion = user.sessionVersion + 1;
|
|
4789
|
+
await users.updateUser(user.id, { emailVerified: true, sessionVersion, wrongCodes: 0 });
|
|
4790
|
+
await users.clearVerifications(user.id);
|
|
4791
|
+
const result = await ctx.startSession(c, toMadauthUser(user), ["pwd"], { sv: sessionVersion });
|
|
4792
|
+
await ctx.emit("email.password_reset", { user: result });
|
|
4793
|
+
await ctx.emit("user.signed_in", { user: result, method: "password" });
|
|
4794
|
+
return c.json({ user: result });
|
|
4795
|
+
});
|
|
4584
4796
|
}
|
|
4585
4797
|
|
|
4586
4798
|
// src/app.ts
|
|
@@ -4590,12 +4802,9 @@ function createApp(config) {
|
|
|
4590
4802
|
const keys = importSigningKeys(config.signingKey);
|
|
4591
4803
|
const secure = issuer.startsWith("https:");
|
|
4592
4804
|
const isAllowedOrigin = (origin) => !!origin && allowedOrigins.includes(origin);
|
|
4593
|
-
const
|
|
4594
|
-
const
|
|
4595
|
-
|
|
4596
|
-
const current = roles && user.email ? await roles.get(normalizeEmail(user.email)) : [];
|
|
4597
|
-
return current.length ? { ...rest, roles: current } : rest;
|
|
4598
|
-
};
|
|
4805
|
+
const users = new Users(config.store, deriveCodeKey(config.signingKey.d));
|
|
4806
|
+
const settings = new Settings(config.store);
|
|
4807
|
+
const available = (method) => method === "google" ? !!config.google : !!config.password;
|
|
4599
4808
|
const issueSession = async (c, user, amr, extra) => {
|
|
4600
4809
|
const signingKeys = await keys;
|
|
4601
4810
|
const [sessionToken, renewalToken] = await Promise.all([
|
|
@@ -4647,12 +4856,29 @@ function createApp(config) {
|
|
|
4647
4856
|
return url;
|
|
4648
4857
|
},
|
|
4649
4858
|
async startSession(c, user, amr, extra) {
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
return signedIn;
|
|
4859
|
+
await issueSession(c, user, amr, extra);
|
|
4860
|
+
return user;
|
|
4653
4861
|
},
|
|
4654
|
-
users
|
|
4862
|
+
users,
|
|
4863
|
+
settings,
|
|
4655
4864
|
webhook: config.webhook ? createWebhookClient(config.webhook, config.webhookFetch) : void 0,
|
|
4865
|
+
async enabled(method) {
|
|
4866
|
+
return isOn(method, available, await settings.methods());
|
|
4867
|
+
},
|
|
4868
|
+
async checkSignup(data) {
|
|
4869
|
+
if (!this.webhook?.wants("signup.before")) return { ok: true };
|
|
4870
|
+
const check2 = await this.webhook.call("signup.before", data, WEBHOOK_TIMEOUT_MS);
|
|
4871
|
+
if (!check2.ok) {
|
|
4872
|
+
console.error(`[madauth] Webhook "signup.before" failed: ${check2.reason}`);
|
|
4873
|
+
return { ok: false, reason: "unavailable" };
|
|
4874
|
+
}
|
|
4875
|
+
const answer = check2.body;
|
|
4876
|
+
if (answer?.allow === false) {
|
|
4877
|
+
const message2 = typeof answer.message === "string" && answer.message ? answer.message : "Sign-up is not possible with this e-mail address.";
|
|
4878
|
+
return { ok: false, reason: "rejected", message: message2 };
|
|
4879
|
+
}
|
|
4880
|
+
return { ok: true };
|
|
4881
|
+
},
|
|
4656
4882
|
async emit(type, data) {
|
|
4657
4883
|
if (!this.webhook?.wants(type)) return;
|
|
4658
4884
|
const result = await this.webhook.call(type, data, EVENT_TIMEOUT_MS);
|
|
@@ -4682,29 +4908,28 @@ function createApp(config) {
|
|
|
4682
4908
|
c.header("Cache-Control", "public, max-age=3600");
|
|
4683
4909
|
return c.json({ keys: [publicJwk] });
|
|
4684
4910
|
});
|
|
4685
|
-
app.get(
|
|
4686
|
-
|
|
4687
|
-
(
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
|
|
4691
|
-
|
|
4911
|
+
app.get("/auth/config", async (c) => {
|
|
4912
|
+
const methods = await settings.methods();
|
|
4913
|
+
const on = (method) => isOn(method, available, methods);
|
|
4914
|
+
return c.json({
|
|
4915
|
+
google: on("google") ? { clientId: config.google.clientId, codeFlow: !!config.google.clientSecret } : null,
|
|
4916
|
+
password: on("password") ? { minLength: config.password.minLength } : null
|
|
4917
|
+
});
|
|
4918
|
+
});
|
|
4692
4919
|
if (config.google) googleRoutes(app, ctx, config.google);
|
|
4693
|
-
if (config.password && ctx.
|
|
4920
|
+
if (config.password && ctx.webhook) passwordRoutes(app, ctx, config.password, users, ctx.webhook);
|
|
4694
4921
|
const tokenClaims = async (c, cookie, typ) => readToken(await keys, issuer, typ, getCookie(c, cookie));
|
|
4695
|
-
const hasEnded = async (claims) => {
|
|
4696
|
-
if (!claims.sub.startsWith("usr_")) return false;
|
|
4697
|
-
const stored = await ctx.users?.findById(claims.sub);
|
|
4698
|
-
return !stored || stored.sessionVersion !== claims.sv;
|
|
4699
|
-
};
|
|
4700
4922
|
const checked = async (claims) => {
|
|
4701
|
-
const
|
|
4702
|
-
|
|
4923
|
+
const stored = await users.findById(claims.sub);
|
|
4924
|
+
if (!stored || stored.sessionVersion !== claims.sv) return null;
|
|
4925
|
+
const { claims: _, ...user } = userFromClaims(claims);
|
|
4926
|
+
const current = claimsFromJson(stored.claims);
|
|
4927
|
+
return Object.keys(current).length ? { ...user, claims: current } : user;
|
|
4703
4928
|
};
|
|
4704
4929
|
const currentSession = async (c) => {
|
|
4705
4930
|
const session = await tokenClaims(c, SESSION_COOKIE, SESSION_TYP);
|
|
4706
4931
|
const user = session ? await checked(session) : null;
|
|
4707
|
-
const upToDate = session && user &&
|
|
4932
|
+
const upToDate = session && user && sameClaims(user.claims, session.claims) && Date.now() / 1e3 - session.iat <= sessionTtlSeconds / 2;
|
|
4708
4933
|
if (upToDate) return user;
|
|
4709
4934
|
const renewal = await tokenClaims(c, RENEWAL_COOKIE, RENEWAL_TYP);
|
|
4710
4935
|
const sameSignIn = session && user && renewal && renewal.sub === session.sub && renewal.sv === session.sv && renewal.email === session.email;
|
|
@@ -4730,56 +4955,82 @@ function createApp(config) {
|
|
|
4730
4955
|
app.post("/auth/account/delete", async (c) => {
|
|
4731
4956
|
const user = await currentSession(c);
|
|
4732
4957
|
if (!user) return c.json({ error: "no_session" }, 401);
|
|
4733
|
-
|
|
4734
|
-
const passwordUserId = ctx.users && user.email ? await ctx.users.deleteByEmail(normalizeEmail(user.email)) : null;
|
|
4958
|
+
await users.deleteById(user.id);
|
|
4735
4959
|
clearSession(c);
|
|
4736
|
-
await ctx.emit("user.deleted", { user
|
|
4960
|
+
await ctx.emit("user.deleted", { user });
|
|
4737
4961
|
return c.body(null, 204);
|
|
4738
4962
|
});
|
|
4739
|
-
|
|
4740
|
-
const
|
|
4741
|
-
|
|
4742
|
-
|
|
4743
|
-
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
4752
|
-
|
|
4753
|
-
|
|
4754
|
-
|
|
4755
|
-
|
|
4756
|
-
|
|
4757
|
-
|
|
4758
|
-
|
|
4759
|
-
|
|
4760
|
-
|
|
4761
|
-
|
|
4762
|
-
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
|
|
4769
|
-
|
|
4770
|
-
|
|
4771
|
-
|
|
4772
|
-
|
|
4773
|
-
|
|
4774
|
-
|
|
4775
|
-
|
|
4776
|
-
|
|
4777
|
-
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4781
|
-
});
|
|
4782
|
-
|
|
4963
|
+
const admin = async (c) => {
|
|
4964
|
+
const user = await currentSession(c);
|
|
4965
|
+
if (!user) return { answer: c.json({ error: "no_session" }, 401) };
|
|
4966
|
+
const email = user.email ? normalizeEmail(user.email) : void 0;
|
|
4967
|
+
if (!email || !isAdmin(user)) {
|
|
4968
|
+
const message2 = `Only users with the role "${ADMIN_ROLE}" can manage claims and settings.`;
|
|
4969
|
+
return { answer: c.json({ error: "forbidden", message: message2 }, 403) };
|
|
4970
|
+
}
|
|
4971
|
+
return { email };
|
|
4972
|
+
};
|
|
4973
|
+
const body = async (c) => {
|
|
4974
|
+
const data = await c.req.json().catch(() => null);
|
|
4975
|
+
return data && typeof data === "object" ? data : {};
|
|
4976
|
+
};
|
|
4977
|
+
const invalidEmail = (c) => c.json({ error: "invalid_email", message: "This is not a valid e-mail address." }, 400);
|
|
4978
|
+
const noUser = (c) => c.json({ error: "user_not_found", message: "No user has this e-mail address." }, 404);
|
|
4979
|
+
app.post("/auth/admin/claims/get", async (c) => {
|
|
4980
|
+
const caller = await admin(c);
|
|
4981
|
+
if ("answer" in caller) return caller.answer;
|
|
4982
|
+
const data = await body(c);
|
|
4983
|
+
if (!isValidEmail(data.email)) return invalidEmail(c);
|
|
4984
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
4985
|
+
if (!user) return noUser(c);
|
|
4986
|
+
return c.json({ email: user.emailNormalized, userId: user.id, claims: claimsFromJson(user.claims) });
|
|
4987
|
+
});
|
|
4988
|
+
app.post("/auth/admin/claims/set", async (c) => {
|
|
4989
|
+
const caller = await admin(c);
|
|
4990
|
+
if ("answer" in caller) return caller.answer;
|
|
4991
|
+
const data = await body(c);
|
|
4992
|
+
if (!isValidEmail(data.email)) return invalidEmail(c);
|
|
4993
|
+
const claims = parseClaims(data.claims);
|
|
4994
|
+
if (!claims) {
|
|
4995
|
+
return c.json(
|
|
4996
|
+
{
|
|
4997
|
+
error: "invalid_claims",
|
|
4998
|
+
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 "_".'
|
|
4999
|
+
},
|
|
5000
|
+
400
|
|
5001
|
+
);
|
|
5002
|
+
}
|
|
5003
|
+
const user = await users.findByEmail(normalizeEmail(data.email));
|
|
5004
|
+
if (!user) return noUser(c);
|
|
5005
|
+
await users.updateUser(user.id, { claims: Object.keys(claims).length ? JSON.stringify(claims) : null });
|
|
5006
|
+
const email = user.emailNormalized;
|
|
5007
|
+
await ctx.emit("user.claims_changed", { userId: user.id, email, claims, by: caller.email });
|
|
5008
|
+
return c.json({ email, userId: user.id, claims });
|
|
5009
|
+
});
|
|
5010
|
+
const settingsAnswer = (methods) => ({
|
|
5011
|
+
methods: Object.fromEntries(
|
|
5012
|
+
SIGN_IN_METHODS.map((method) => [method, { available: available(method), enabled: isOn(method, available, methods) }])
|
|
5013
|
+
)
|
|
5014
|
+
});
|
|
5015
|
+
app.post("/auth/admin/settings/get", async (c) => {
|
|
5016
|
+
const caller = await admin(c);
|
|
5017
|
+
if ("answer" in caller) return caller.answer;
|
|
5018
|
+
return c.json(settingsAnswer(await settings.methods()));
|
|
5019
|
+
});
|
|
5020
|
+
app.post("/auth/admin/settings/set", async (c) => {
|
|
5021
|
+
const caller = await admin(c);
|
|
5022
|
+
if ("answer" in caller) return caller.answer;
|
|
5023
|
+
const data = await body(c);
|
|
5024
|
+
const invalid2 = (message2) => c.json({ error: "invalid_settings", message: message2 }, 400);
|
|
5025
|
+
const changes = parseMethodSettings(data.methods);
|
|
5026
|
+
if (!changes) return invalid2(`methods must be an object with true or false for ${SIGN_IN_METHODS.join(" and/or ")}.`);
|
|
5027
|
+
const methods = await settings.changeMethods((current) => {
|
|
5028
|
+
const next = { ...current, ...changes };
|
|
5029
|
+
return anyOn(available, next) ? next : null;
|
|
5030
|
+
}, caller.email);
|
|
5031
|
+
if (!methods) return invalid2("At least one sign-in method must stay on.");
|
|
5032
|
+
return c.json(settingsAnswer(methods));
|
|
5033
|
+
});
|
|
4783
5034
|
return app;
|
|
4784
5035
|
}
|
|
4785
5036
|
|
|
@@ -4844,19 +5095,18 @@ MADAUTH_SIGNING_KEY='${JSON.stringify(key)}'
|
|
|
4844
5095
|
if (clientId && !clientId.endsWith(".apps.googleusercontent.com")) {
|
|
4845
5096
|
throw new ConfigError(`GOOGLE_CLIENT_ID must end with ".apps.googleusercontent.com" but is "${clientId}".`);
|
|
4846
5097
|
}
|
|
4847
|
-
const
|
|
4848
|
-
const
|
|
4849
|
-
|
|
5098
|
+
const webhook = webhookFromEnv(read("WEBHOOK_URL"), read("WEBHOOK_SECRET"), read("WEBHOOK_EVENTS"));
|
|
5099
|
+
const sendsEmails = !!webhook && REQUIRED_EMAIL_TYPES.every((type) => webhook.events.has(type));
|
|
5100
|
+
const password = sendsEmails ? { minLength: passwordMinLength(read("PASSWORD_MIN_LENGTH")) } : void 0;
|
|
5101
|
+
if (!clientId && !password) {
|
|
4850
5102
|
throw new ConfigError(
|
|
4851
|
-
`
|
|
5103
|
+
`No sign-in method is configured. Set GOOGLE_CLIENT_ID for Google sign-in, and/or a webhook that sends the e-mails for e-mail & password sign-in: for development, run the receiver at ${DEV_WEBHOOK_RECEIVER_URL} and set WEBHOOK_URL=http://localhost:8790/webhook and WEBHOOK_EVENTS=${REQUIRED_EMAIL_TYPES.join(",")},email.already_registered,email.no_password. See docs/server.md.`
|
|
4852
5104
|
);
|
|
4853
5105
|
}
|
|
4854
5106
|
const store = overrides.store ?? await storeFromDatabaseUrl(read("DATABASE_URL"));
|
|
4855
|
-
|
|
4856
|
-
if (store) password = { minLength: passwordMinLength(read("PASSWORD_MIN_LENGTH")), store };
|
|
4857
|
-
if (!clientId && !password) {
|
|
5107
|
+
if (!store) {
|
|
4858
5108
|
throw new ConfigError(
|
|
4859
|
-
"
|
|
5109
|
+
"DATABASE_URL is not set. madAuth stores every user, whichever way they sign in: set e.g. DATABASE_URL=sqlite:./madauth.db or DATABASE_URL=dynamodb:<table>. See docs/server.md."
|
|
4860
5110
|
);
|
|
4861
5111
|
}
|
|
4862
5112
|
const ttlValue = read("SESSION_TTL");
|
|
@@ -4879,6 +5129,7 @@ MADAUTH_SIGNING_KEY='${JSON.stringify(key)}'
|
|
|
4879
5129
|
renewalTtlSeconds,
|
|
4880
5130
|
cookieDomain: read("COOKIE_DOMAIN"),
|
|
4881
5131
|
google: clientId ? { clientId, clientSecret: read("GOOGLE_CLIENT_SECRET") } : void 0,
|
|
5132
|
+
store,
|
|
4882
5133
|
password,
|
|
4883
5134
|
webhook
|
|
4884
5135
|
};
|
|
@@ -4924,8 +5175,9 @@ async function dynamoDbStore(tableName2) {
|
|
|
4924
5175
|
const { createDynamoDbAdapter: createDynamoDbAdapter2 } = await Promise.resolve().then(() => (init_dynamodb(), dynamodb_exports));
|
|
4925
5176
|
return createDynamoDbAdapter2({ tableName: tableName2 });
|
|
4926
5177
|
}
|
|
5178
|
+
var RENAMED_TYPES = { "password.reset": "email.password_reset", "roles.changed": "user.claims_changed" };
|
|
4927
5179
|
var LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]", "host.docker.internal"];
|
|
4928
|
-
function webhookFromEnv(url, secret, events
|
|
5180
|
+
function webhookFromEnv(url, secret, events) {
|
|
4929
5181
|
if (!url) {
|
|
4930
5182
|
if (secret || events) throw new ConfigError("WEBHOOK_SECRET and WEBHOOK_EVENTS need WEBHOOK_URL.");
|
|
4931
5183
|
return void 0;
|
|
@@ -4955,24 +5207,22 @@ WEBHOOK_SECRET=${generateWebhookSecret()}
|
|
|
4955
5207
|
const allTypes = `All types: ${WEBHOOK_TYPES.join(", ")}. See "Webhooks" in docs/server.md.`;
|
|
4956
5208
|
if (!selected.size) {
|
|
4957
5209
|
throw new ConfigError(
|
|
4958
|
-
|
|
5210
|
+
`WEBHOOK_EVENTS is not set. List the types your webhook receiver handles; only these are sent. E-mail & password sign-in is on when they include ${REQUIRED_EMAIL_TYPES.join(" and ")}. For a receiver that sends the e-mails:
|
|
5211
|
+
|
|
5212
|
+
WEBHOOK_EVENTS=email.verify,email.reset,email.already_registered,email.no_password
|
|
4959
5213
|
|
|
4960
|
-
|
|
5214
|
+
For one that only wants to know who signed in:
|
|
4961
5215
|
|
|
4962
|
-
|
|
5216
|
+
WEBHOOK_EVENTS=user.signed_in
|
|
5217
|
+
|
|
5218
|
+
` + allTypes
|
|
4963
5219
|
);
|
|
4964
5220
|
}
|
|
4965
5221
|
const unknown = [...selected].filter((e) => !WEBHOOK_TYPES.includes(e));
|
|
4966
5222
|
if (unknown.length) {
|
|
4967
|
-
|
|
4968
|
-
}
|
|
4969
|
-
const missing = sendsEmails ? REQUIRED_EMAIL_TYPES.filter((type) => !selected.has(type)) : [];
|
|
4970
|
-
if (missing.length) {
|
|
5223
|
+
const renamed = unknown.filter((e) => e in RENAMED_TYPES).map((e) => `${e} is now ${RENAMED_TYPES[e]}`);
|
|
4971
5224
|
throw new ConfigError(
|
|
4972
|
-
`WEBHOOK_EVENTS
|
|
4973
|
-
|
|
4974
|
-
WEBHOOK_EVENTS=${[...selected, ...missing].join(",")}
|
|
4975
|
-
`
|
|
5225
|
+
`WEBHOOK_EVENTS: unknown type ${unknown.join(", ")}. ${renamed.length ? `${renamed.join("; ")}. ` : ""}Known types: ${WEBHOOK_TYPES.join(", ")}.`
|
|
4976
5226
|
);
|
|
4977
5227
|
}
|
|
4978
5228
|
return { url: parsed.href, secret, events: selected };
|