@guren/server 2.10.0 → 2.11.0
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/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
- package/dist/Hash-CzrwKeDp.js +133 -0
- package/dist/HttpException-BkS3euNG.js +161 -0
- package/dist/Job-BVT813DO.js +441 -0
- package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
- package/dist/MessageSigner-Bd25ZJAV.js +93 -0
- package/dist/Random-DbIJ22KQ.js +191 -0
- package/dist/address-D0Iq-XIH.js +20 -0
- package/dist/auth/index.js +2 -122
- package/dist/auth-C7sVmYgc.js +1954 -0
- package/dist/authorization/index.js +2 -38
- package/dist/authorization-Dbcuc5ZK.js +610 -0
- package/dist/broadcasting/index.js +2 -26
- package/dist/broadcasting-Dw-FhyjN.js +1055 -0
- package/dist/cache/index.js +2 -17
- package/dist/cache/types.d.ts +4 -4
- package/dist/cache-BYnZf2FR.js +812 -0
- package/dist/client-Dd7vLcqp.js +27 -0
- package/dist/console/Output.d.ts +18 -18
- package/dist/encryption/index.js +5 -96
- package/dist/encryption-fOWQaKqX.js +250 -0
- package/dist/endpoint-D-20PiHY.js +46 -0
- package/dist/endpoint-D6GIqOpe.js +31 -0
- package/dist/errors-quJOkkCn.js +81 -0
- package/dist/events/index.js +2 -28
- package/dist/events-aIH_bWRx.js +410 -0
- package/dist/health/index.js +2 -24
- package/dist/health-VWdWXRwh.js +345 -0
- package/dist/hot-disposables-WsTX2ySN.js +281 -0
- package/dist/hot-reload/testing.d.ts +1 -1
- package/dist/http/resources/Resource.d.ts +23 -3
- package/dist/i18n/index.js +2 -30
- package/dist/i18n-mcWi7LCd.js +617 -0
- package/dist/index.js +7515 -7276
- package/dist/lambda/index.js +114 -71
- package/dist/logging/index.js +2 -24
- package/dist/logging-CPaRMuPP.js +518 -0
- package/dist/loopback-guard-D0Kc7-xc.js +224 -0
- package/dist/mail/index.js +2 -27
- package/dist/mail-DfEfSQEr.js +699 -0
- package/dist/mcp/index.js +2 -10
- package/dist/notifications/index.js +2 -33
- package/dist/notifications-BGqmUNZ8.js +759 -0
- package/dist/queue/index.js +3 -42
- package/dist/queue-CXrRK85G.js +948 -0
- package/dist/redis/index.js +672 -642
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime/index.js +472 -616
- package/dist/scheduling/index.js +2 -29
- package/dist/scheduling-CPiEdtQd.js +839 -0
- package/dist/storage/index.js +2 -15
- package/dist/storage-tWHMv2H_.js +841 -0
- package/dist/support/expiry.js +69 -12
- package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
- package/dist/vite/index.js +118 -181
- package/dist/vite/plugin.d.ts +1 -1
- package/dist/vite-dev-server-BSJkduhZ.js +131 -0
- package/package.json +6 -5
- package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
- package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
- package/dist/chunk-2SC566CD.js +0 -376
- package/dist/chunk-2V3YID4H.js +0 -20
- package/dist/chunk-3KV5X2FL.js +0 -31
- package/dist/chunk-63SKW5PS.js +0 -457
- package/dist/chunk-6J6B5KOB.js +0 -425
- package/dist/chunk-A5JJ7XTH.js +0 -24
- package/dist/chunk-AZOYI43J.js +0 -18
- package/dist/chunk-B5E5VBDI.js +0 -115
- package/dist/chunk-DAQKYKLH.js +0 -182
- package/dist/chunk-DRNPVBAA.js +0 -1002
- package/dist/chunk-EI5GYMAT.js +0 -853
- package/dist/chunk-H3B23O6T.js +0 -271
- package/dist/chunk-HPET6XY5.js +0 -853
- package/dist/chunk-HR2KZ3WL.js +0 -616
- package/dist/chunk-IOTWFHZU.js +0 -558
- package/dist/chunk-K6CUBJX6.js +0 -642
- package/dist/chunk-KTNJG7R7.js +0 -911
- package/dist/chunk-LAJQCSSF.js +0 -355
- package/dist/chunk-LHR6OHI7.js +0 -189
- package/dist/chunk-N7PLD7MB.js +0 -729
- package/dist/chunk-Q2P6YLRR.js +0 -24
- package/dist/chunk-QQKTH5KX.js +0 -114
- package/dist/chunk-SFQP6O52.js +0 -126
- package/dist/chunk-SQR7277M.js +0 -911
- package/dist/chunk-T2FFUU6J.js +0 -484
- package/dist/chunk-TVV5YNEC.js +0 -1842
- package/dist/chunk-UY3AZSYL.js +0 -14
- package/dist/chunk-V4DNC2ER.js +0 -114
- package/dist/chunk-VSA3QY5Q.js +0 -274
- package/dist/chunk-YSOJKAAU.js +0 -427
- package/dist/errors-PUNHAFL2.js +0 -34
|
@@ -0,0 +1,1954 @@
|
|
|
1
|
+
import { t as HttpException } from "./HttpException-BkS3euNG.js";
|
|
2
|
+
import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
|
|
3
|
+
import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-CzrwKeDp.js";
|
|
4
|
+
import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
|
|
5
|
+
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
6
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
7
|
+
import { Model } from "@guren/orm";
|
|
8
|
+
//#region src/http/middleware/session.ts
|
|
9
|
+
var MemorySessionStore = class {
|
|
10
|
+
now;
|
|
11
|
+
store = /* @__PURE__ */ new Map();
|
|
12
|
+
constructor(now = () => Date.now()) {
|
|
13
|
+
this.now = now;
|
|
14
|
+
}
|
|
15
|
+
async read(id) {
|
|
16
|
+
const entry = this.store.get(id);
|
|
17
|
+
if (!entry) return;
|
|
18
|
+
if (entry.expiresAt <= this.now()) {
|
|
19
|
+
this.store.delete(id);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
return { ...entry.data };
|
|
23
|
+
}
|
|
24
|
+
async write(id, data, ttlSeconds) {
|
|
25
|
+
const expiresAt = this.now() + ttlSeconds * 1e3;
|
|
26
|
+
this.store.set(id, {
|
|
27
|
+
data: { ...data },
|
|
28
|
+
expiresAt
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async destroy(id) {
|
|
32
|
+
this.store.delete(id);
|
|
33
|
+
}
|
|
34
|
+
async touch(id, ttlSeconds) {
|
|
35
|
+
const entry = this.store.get(id);
|
|
36
|
+
if (!entry || entry.expiresAt <= this.now()) return;
|
|
37
|
+
entry.expiresAt = this.now() + ttlSeconds * 1e3;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const DEFAULT_COOKIE_NAME = "guren.session";
|
|
41
|
+
const DEFAULT_TTL_SECONDS = 7200;
|
|
42
|
+
const DEFAULT_COOKIE_SECURE = typeof process !== "undefined" ? process.env.NODE_ENV === "production" : true;
|
|
43
|
+
const SESSION_CONTEXT_KEY = "guren:session";
|
|
44
|
+
var SessionImpl = class {
|
|
45
|
+
isNew;
|
|
46
|
+
currentId;
|
|
47
|
+
originalId;
|
|
48
|
+
data;
|
|
49
|
+
dirty = false;
|
|
50
|
+
destroyed = false;
|
|
51
|
+
regenerated = false;
|
|
52
|
+
_flash = {
|
|
53
|
+
new: {},
|
|
54
|
+
old: {}
|
|
55
|
+
};
|
|
56
|
+
constructor(id, initialData, isNew) {
|
|
57
|
+
this.isNew = isNew;
|
|
58
|
+
this.currentId = id;
|
|
59
|
+
this.originalId = id;
|
|
60
|
+
const { _flash, ...rest } = initialData;
|
|
61
|
+
this.data = { ...rest };
|
|
62
|
+
if (_flash && typeof _flash === "object") {
|
|
63
|
+
const bag = _flash;
|
|
64
|
+
this._flash = {
|
|
65
|
+
new: bag.new && typeof bag.new === "object" ? { ...bag.new } : {},
|
|
66
|
+
old: bag.old && typeof bag.old === "object" ? { ...bag.old } : {}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
get id() {
|
|
71
|
+
return this.currentId;
|
|
72
|
+
}
|
|
73
|
+
get(key) {
|
|
74
|
+
return this.data[key];
|
|
75
|
+
}
|
|
76
|
+
set(key, value) {
|
|
77
|
+
this.data[key] = value;
|
|
78
|
+
this.dirty = true;
|
|
79
|
+
}
|
|
80
|
+
has(key) {
|
|
81
|
+
return Object.prototype.hasOwnProperty.call(this.data, key);
|
|
82
|
+
}
|
|
83
|
+
forget(key) {
|
|
84
|
+
if (this.has(key)) {
|
|
85
|
+
delete this.data[key];
|
|
86
|
+
this.dirty = true;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
flush() {
|
|
90
|
+
if (Object.keys(this.data).length > 0) {
|
|
91
|
+
this.data = {};
|
|
92
|
+
this.dirty = true;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
all() {
|
|
96
|
+
return { ...this.data };
|
|
97
|
+
}
|
|
98
|
+
regenerate() {
|
|
99
|
+
this.currentId = globalThis.crypto.randomUUID();
|
|
100
|
+
this.regenerated = true;
|
|
101
|
+
this.dirty = true;
|
|
102
|
+
}
|
|
103
|
+
invalidate() {
|
|
104
|
+
this.flush();
|
|
105
|
+
this.destroyed = true;
|
|
106
|
+
}
|
|
107
|
+
flash(key, value) {
|
|
108
|
+
this._flash.new[key] = value;
|
|
109
|
+
this.dirty = true;
|
|
110
|
+
}
|
|
111
|
+
getFlash(key) {
|
|
112
|
+
return this._flash.old[key];
|
|
113
|
+
}
|
|
114
|
+
reflash() {
|
|
115
|
+
for (const [key, value] of Object.entries(this._flash.old)) this._flash.new[key] = value;
|
|
116
|
+
this.dirty = true;
|
|
117
|
+
}
|
|
118
|
+
keep(...keys) {
|
|
119
|
+
for (const key of keys) if (key in this._flash.old) this._flash.new[key] = this._flash.old[key];
|
|
120
|
+
this.dirty = true;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Age flash data: move `new` → `old`, clear previous `old`.
|
|
124
|
+
* Called at the start of each request by the session middleware.
|
|
125
|
+
* Only dirties the session when there was flash data to age — otherwise
|
|
126
|
+
* every request carrying a session would persist unconditionally.
|
|
127
|
+
*/
|
|
128
|
+
ageFlashData() {
|
|
129
|
+
const hadFlash = this.hasFlash();
|
|
130
|
+
this._flash.old = { ...this._flash.new };
|
|
131
|
+
this._flash.new = {};
|
|
132
|
+
if (hadFlash) this.dirty = true;
|
|
133
|
+
}
|
|
134
|
+
markTouched() {
|
|
135
|
+
this.dirty = true;
|
|
136
|
+
}
|
|
137
|
+
wasDestroyed() {
|
|
138
|
+
return this.destroyed;
|
|
139
|
+
}
|
|
140
|
+
wasRegenerated() {
|
|
141
|
+
return this.regenerated;
|
|
142
|
+
}
|
|
143
|
+
shouldPersist() {
|
|
144
|
+
return this.dirty || this.isNew && this.hasContent();
|
|
145
|
+
}
|
|
146
|
+
willPersist() {
|
|
147
|
+
if (this.destroyed) return false;
|
|
148
|
+
return !this.isNew || this.shouldPersist();
|
|
149
|
+
}
|
|
150
|
+
hasContent() {
|
|
151
|
+
return Object.keys(this.data).length > 0 || this.hasFlash();
|
|
152
|
+
}
|
|
153
|
+
hasFlash() {
|
|
154
|
+
return Object.keys(this._flash.new).length > 0 || Object.keys(this._flash.old).length > 0;
|
|
155
|
+
}
|
|
156
|
+
snapshot() {
|
|
157
|
+
const hasFlash = this.hasFlash();
|
|
158
|
+
return {
|
|
159
|
+
...this.data,
|
|
160
|
+
...hasFlash ? { _flash: {
|
|
161
|
+
new: { ...this._flash.new },
|
|
162
|
+
old: { ...this._flash.old }
|
|
163
|
+
} } : {}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
originalSessionId() {
|
|
167
|
+
return this.originalId;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const TESTING_SESSION_HEADER = "x-testing-session";
|
|
171
|
+
function resolveTestingSession(ctx) {
|
|
172
|
+
if (!process.env.GUREN_TESTING) return null;
|
|
173
|
+
const rawSession = ctx.req.header(TESTING_SESSION_HEADER);
|
|
174
|
+
if (!rawSession) return null;
|
|
175
|
+
try {
|
|
176
|
+
const parsed = JSON.parse(rawSession);
|
|
177
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
178
|
+
return parsed;
|
|
179
|
+
} catch {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function encodeBase64Url(value) {
|
|
184
|
+
return Buffer.from(value, "utf8").toString("base64url");
|
|
185
|
+
}
|
|
186
|
+
function decodeBase64Url(value) {
|
|
187
|
+
return Buffer.from(value, "base64url").toString("utf8");
|
|
188
|
+
}
|
|
189
|
+
function createCookieSigner(cookieName, cookiePath) {
|
|
190
|
+
const keyring = deriveAppKeyring(getAppKeyringFromEnv(), "cookie-signing");
|
|
191
|
+
const keys = [keyring.current, ...keyring.previous];
|
|
192
|
+
const canonicalize = (encodedId) => `${cookieName}|${cookiePath}|${encodedId}`;
|
|
193
|
+
const sign = (sessionId) => {
|
|
194
|
+
const encodedId = encodeBase64Url(sessionId);
|
|
195
|
+
return `${encodedId}.${createHmac("sha256", keyring.current).update(canonicalize(encodedId)).digest("base64url")}`;
|
|
196
|
+
};
|
|
197
|
+
const verify = (cookieValue) => {
|
|
198
|
+
if (!cookieValue) return null;
|
|
199
|
+
const [encodedId, signature, extra] = cookieValue.split(".");
|
|
200
|
+
if (!encodedId || !signature || extra) return null;
|
|
201
|
+
const canonical = canonicalize(encodedId);
|
|
202
|
+
if (!keys.some((key) => {
|
|
203
|
+
const expected = createHmac("sha256", key).update(canonical).digest("base64url");
|
|
204
|
+
const actualBuffer = Buffer.from(signature, "utf8");
|
|
205
|
+
const expectedBuffer = Buffer.from(expected, "utf8");
|
|
206
|
+
if (actualBuffer.length !== expectedBuffer.length) return false;
|
|
207
|
+
return timingSafeEqual(actualBuffer, expectedBuffer);
|
|
208
|
+
})) return null;
|
|
209
|
+
try {
|
|
210
|
+
return decodeBase64Url(encodedId);
|
|
211
|
+
} catch {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
return {
|
|
216
|
+
sign,
|
|
217
|
+
verify
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
function createSessionMiddleware(options = {}) {
|
|
221
|
+
const { cookieName = DEFAULT_COOKIE_NAME, cookiePath = "/", cookieDomain, cookieSecure = DEFAULT_COOKIE_SECURE, cookieSameSite = "Lax", cookieHttpOnly = true, cookieMaxAgeSeconds, ttlSeconds = DEFAULT_TTL_SECONDS, store = new MemorySessionStore() } = options;
|
|
222
|
+
const signer = createCookieSigner(cookieName, cookiePath);
|
|
223
|
+
return async (ctx, next) => {
|
|
224
|
+
const existingId = signer.verify(getCookie(ctx, cookieName));
|
|
225
|
+
const sessionId = existingId ?? globalThis.crypto.randomUUID();
|
|
226
|
+
const isNew = !existingId;
|
|
227
|
+
const storedData = existingId ? await store.read(existingId) ?? {} : {};
|
|
228
|
+
const testingData = resolveTestingSession(ctx);
|
|
229
|
+
const session = new SessionImpl(sessionId, testingData ? {
|
|
230
|
+
...storedData,
|
|
231
|
+
...testingData
|
|
232
|
+
} : storedData, isNew);
|
|
233
|
+
session.ageFlashData();
|
|
234
|
+
ctx.set(SESSION_CONTEXT_KEY, session);
|
|
235
|
+
try {
|
|
236
|
+
await next();
|
|
237
|
+
} finally {
|
|
238
|
+
if (session.wasDestroyed()) {
|
|
239
|
+
await store.destroy(session.originalSessionId());
|
|
240
|
+
deleteCookie(ctx, cookieName, {
|
|
241
|
+
path: cookiePath,
|
|
242
|
+
domain: cookieDomain,
|
|
243
|
+
secure: cookieSecure,
|
|
244
|
+
sameSite: cookieSameSite,
|
|
245
|
+
httpOnly: cookieHttpOnly
|
|
246
|
+
});
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (!session.shouldPersist()) {
|
|
250
|
+
if (existingId) {
|
|
251
|
+
if (store.touch) await store.touch(existingId, ttlSeconds);
|
|
252
|
+
else await store.write(existingId, session.snapshot(), ttlSeconds);
|
|
253
|
+
setCookie(ctx, cookieName, signer.sign(existingId), {
|
|
254
|
+
path: cookiePath,
|
|
255
|
+
domain: cookieDomain,
|
|
256
|
+
secure: cookieSecure,
|
|
257
|
+
sameSite: cookieSameSite,
|
|
258
|
+
httpOnly: cookieHttpOnly,
|
|
259
|
+
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const nextId = session.id;
|
|
265
|
+
await store.write(nextId, session.snapshot(), ttlSeconds);
|
|
266
|
+
if (session.wasRegenerated() && session.originalSessionId() !== nextId) await store.destroy(session.originalSessionId());
|
|
267
|
+
setCookie(ctx, cookieName, signer.sign(nextId), {
|
|
268
|
+
path: cookiePath,
|
|
269
|
+
domain: cookieDomain,
|
|
270
|
+
secure: cookieSecure,
|
|
271
|
+
sameSite: cookieSameSite,
|
|
272
|
+
httpOnly: cookieHttpOnly,
|
|
273
|
+
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function getSessionFromContext(ctx) {
|
|
279
|
+
return ctx.get(SESSION_CONTEXT_KEY);
|
|
280
|
+
}
|
|
281
|
+
//#endregion
|
|
282
|
+
//#region src/errors/exceptions/AuthenticationException.ts
|
|
283
|
+
/**
|
|
284
|
+
* Authentication exception.
|
|
285
|
+
*
|
|
286
|
+
* Thrown when a user is not authenticated or credentials are invalid.
|
|
287
|
+
*
|
|
288
|
+
* @example
|
|
289
|
+
* ```typescript
|
|
290
|
+
* throw new AuthenticationException()
|
|
291
|
+
* throw new AuthenticationException('Invalid token')
|
|
292
|
+
* throw new AuthenticationException('Session expired', 'login')
|
|
293
|
+
* ```
|
|
294
|
+
*/
|
|
295
|
+
var AuthenticationException = class AuthenticationException extends HttpException {
|
|
296
|
+
/**
|
|
297
|
+
* The guard that threw the exception.
|
|
298
|
+
*/
|
|
299
|
+
guard;
|
|
300
|
+
/**
|
|
301
|
+
* URL to redirect to for authentication.
|
|
302
|
+
*/
|
|
303
|
+
redirectTo;
|
|
304
|
+
constructor(message = "Unauthenticated.", guard, redirectTo) {
|
|
305
|
+
super(401, message);
|
|
306
|
+
this.name = "AuthenticationException";
|
|
307
|
+
this.guard = guard;
|
|
308
|
+
this.redirectTo = redirectTo;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Create exception with redirect URL.
|
|
312
|
+
*/
|
|
313
|
+
static withRedirect(redirectTo, message) {
|
|
314
|
+
return new AuthenticationException(message, void 0, redirectTo);
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Create exception for a specific guard.
|
|
318
|
+
*/
|
|
319
|
+
static forGuard(guard, message) {
|
|
320
|
+
return new AuthenticationException(message, guard);
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
//#endregion
|
|
324
|
+
//#region src/auth/RequestAuthContext.ts
|
|
325
|
+
var RequestAuthContext = class {
|
|
326
|
+
manager;
|
|
327
|
+
ctx;
|
|
328
|
+
resolveSession;
|
|
329
|
+
resolveGuard;
|
|
330
|
+
guardCache = /* @__PURE__ */ new Map();
|
|
331
|
+
constructor(manager, ctx, resolveSession, resolveGuard) {
|
|
332
|
+
this.manager = manager;
|
|
333
|
+
this.ctx = ctx;
|
|
334
|
+
this.resolveSession = resolveSession;
|
|
335
|
+
this.resolveGuard = resolveGuard;
|
|
336
|
+
}
|
|
337
|
+
guard(name) {
|
|
338
|
+
const key = name ?? this.manager.getDefaultGuard();
|
|
339
|
+
if (!this.guardCache.has(key)) {
|
|
340
|
+
const guard = this.resolveGuard(name);
|
|
341
|
+
this.guardCache.set(key, guard);
|
|
342
|
+
}
|
|
343
|
+
return this.guardCache.get(key);
|
|
344
|
+
}
|
|
345
|
+
session() {
|
|
346
|
+
return this.resolveSession();
|
|
347
|
+
}
|
|
348
|
+
async check() {
|
|
349
|
+
return this.guard().check();
|
|
350
|
+
}
|
|
351
|
+
async guest() {
|
|
352
|
+
return this.guard().guest();
|
|
353
|
+
}
|
|
354
|
+
async user() {
|
|
355
|
+
return this.guard().user();
|
|
356
|
+
}
|
|
357
|
+
async userOrFail() {
|
|
358
|
+
const u = await this.user();
|
|
359
|
+
if (!u) throw new AuthenticationException();
|
|
360
|
+
return u;
|
|
361
|
+
}
|
|
362
|
+
async id() {
|
|
363
|
+
return this.guard().id();
|
|
364
|
+
}
|
|
365
|
+
async login(user, remember) {
|
|
366
|
+
await this.guard().login(user, remember);
|
|
367
|
+
}
|
|
368
|
+
async attempt(credentials, remember) {
|
|
369
|
+
return this.guard().attempt(credentials, remember);
|
|
370
|
+
}
|
|
371
|
+
async logout() {
|
|
372
|
+
await this.guard().logout();
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/auth/password/ScryptHasher.ts
|
|
377
|
+
var ScryptHasher = class {
|
|
378
|
+
algorithm;
|
|
379
|
+
memoryCost;
|
|
380
|
+
timeCost;
|
|
381
|
+
cost;
|
|
382
|
+
constructor(options = {}) {
|
|
383
|
+
this.algorithm = options.algorithm ?? "argon2id";
|
|
384
|
+
this.memoryCost = options.memoryCost;
|
|
385
|
+
this.timeCost = options.timeCost;
|
|
386
|
+
this.cost = options.cost;
|
|
387
|
+
}
|
|
388
|
+
async hash(plain) {
|
|
389
|
+
if (this.algorithm === "bcrypt") return Bun.password.hash(plain, {
|
|
390
|
+
algorithm: "bcrypt",
|
|
391
|
+
cost: this.cost
|
|
392
|
+
});
|
|
393
|
+
return Bun.password.hash(plain, {
|
|
394
|
+
algorithm: this.algorithm,
|
|
395
|
+
memoryCost: this.memoryCost,
|
|
396
|
+
timeCost: this.timeCost
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
async verify(hashed, plain) {
|
|
400
|
+
return Bun.password.verify(plain, hashed);
|
|
401
|
+
}
|
|
402
|
+
needsRehash(hashed) {
|
|
403
|
+
if (this.algorithm === "bcrypt") {
|
|
404
|
+
if (!hashed.startsWith("$2")) return true;
|
|
405
|
+
if (this.cost != null) {
|
|
406
|
+
const costSegment = hashed.slice(4, 6);
|
|
407
|
+
const parsedCost = Number.parseInt(costSegment, 10);
|
|
408
|
+
if (!Number.isNaN(parsedCost) && parsedCost !== this.cost) return true;
|
|
409
|
+
}
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
if (!hashed.startsWith(`$${this.algorithm}$`)) return true;
|
|
413
|
+
const [, , , parameterSegment] = hashed.split("$");
|
|
414
|
+
if (!parameterSegment) return false;
|
|
415
|
+
const params = Object.fromEntries(parameterSegment.split(",").map((pair) => pair.split("=")).filter((parts) => parts.length === 2));
|
|
416
|
+
if (this.memoryCost != null) {
|
|
417
|
+
const memory = Number(params.m);
|
|
418
|
+
if (!Number.isNaN(memory) && memory !== this.memoryCost) return true;
|
|
419
|
+
}
|
|
420
|
+
if (this.timeCost != null) {
|
|
421
|
+
const time = Number(params.t);
|
|
422
|
+
if (!Number.isNaN(time) && time !== this.timeCost) return true;
|
|
423
|
+
}
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
//#endregion
|
|
428
|
+
//#region src/auth/providers/UserProvider.ts
|
|
429
|
+
var BaseUserProvider = class {
|
|
430
|
+
async setRememberToken(user, token) {
|
|
431
|
+
if (typeof user.setRememberToken === "function") await user.setRememberToken(token);
|
|
432
|
+
}
|
|
433
|
+
async getRememberToken(user) {
|
|
434
|
+
if (typeof user.getRememberToken === "function") return await user.getRememberToken() ?? null;
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
//#endregion
|
|
439
|
+
//#region src/auth/providers/ModelUserProvider.ts
|
|
440
|
+
/**
|
|
441
|
+
* Capability check, not `instanceof AuthenticatableModel`: a nominal check
|
|
442
|
+
* silently fails when two copies of @guren/server are loaded (src and dist
|
|
443
|
+
* coexist through workspace symlinks), which would ignore a renamed
|
|
444
|
+
* passwordHashField without any signal. Same duck-typing idiom as
|
|
445
|
+
* BaseUserProvider's remember-token support.
|
|
446
|
+
*/
|
|
447
|
+
function credentialColumnSource(model) {
|
|
448
|
+
const candidate = model;
|
|
449
|
+
return typeof candidate.resolvePasswordHashField === "function" && typeof candidate.resolveRememberTokenField === "function" ? candidate : null;
|
|
450
|
+
}
|
|
451
|
+
var ModelUserProvider = class extends BaseUserProvider {
|
|
452
|
+
model;
|
|
453
|
+
idColumn;
|
|
454
|
+
usernameColumn;
|
|
455
|
+
passwordColumn;
|
|
456
|
+
rememberTokenColumn;
|
|
457
|
+
hasher;
|
|
458
|
+
credentialsPasswordField;
|
|
459
|
+
constructor(model, options = {}) {
|
|
460
|
+
super();
|
|
461
|
+
this.model = model;
|
|
462
|
+
const authModel = credentialColumnSource(model);
|
|
463
|
+
this.idColumn = options.idColumn ?? "id";
|
|
464
|
+
this.usernameColumn = options.usernameColumn ?? "email";
|
|
465
|
+
this.passwordColumn = options.passwordColumn ?? authModel?.resolvePasswordHashField() ?? "passwordHash";
|
|
466
|
+
this.rememberTokenColumn = options.rememberTokenColumn ?? authModel?.resolveRememberTokenField() ?? "rememberToken";
|
|
467
|
+
this.hasher = options.hasher ?? new ScryptHasher();
|
|
468
|
+
this.credentialsPasswordField = options.credentialsPasswordField ?? "password";
|
|
469
|
+
}
|
|
470
|
+
cast(record) {
|
|
471
|
+
if (record && typeof record === "object") return record;
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
async retrieveById(identifier) {
|
|
475
|
+
const record = await this.model.find(identifier, this.idColumn);
|
|
476
|
+
return this.cast(record);
|
|
477
|
+
}
|
|
478
|
+
async retrieveByCredentials(credentials) {
|
|
479
|
+
const rememberToken = credentials["rememberToken"] ?? credentials["remember_token"];
|
|
480
|
+
if (rememberToken != null) {
|
|
481
|
+
const records = await this.model.where({ [this.rememberTokenColumn]: rememberToken });
|
|
482
|
+
return this.cast(records[0] ?? null);
|
|
483
|
+
}
|
|
484
|
+
const username = credentials[this.usernameColumn];
|
|
485
|
+
if (username == null) return null;
|
|
486
|
+
const records = await this.model.where({ [this.usernameColumn]: username });
|
|
487
|
+
return this.cast(records[0] ?? null);
|
|
488
|
+
}
|
|
489
|
+
async validateCredentials(user, credentials) {
|
|
490
|
+
const plain = credentials[this.credentialsPasswordField];
|
|
491
|
+
if (typeof plain !== "string") return false;
|
|
492
|
+
const hashed = user[this.passwordColumn];
|
|
493
|
+
if (typeof hashed !== "string") {
|
|
494
|
+
await this.hasher.hash("dummy-timing-equalization");
|
|
495
|
+
return false;
|
|
496
|
+
}
|
|
497
|
+
return this.hasher.verify(hashed, plain);
|
|
498
|
+
}
|
|
499
|
+
getId(user) {
|
|
500
|
+
return user[this.idColumn];
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Strip the password hash, remember token, and the model's `hidden`
|
|
504
|
+
* fields before the record leaves the auth layer. Credential
|
|
505
|
+
* validation happens on the raw record before sanitizing, so this
|
|
506
|
+
* never affects login — only what `auth.user()` exposes.
|
|
507
|
+
*/
|
|
508
|
+
sanitize(user) {
|
|
509
|
+
const authModel = credentialColumnSource(this.model);
|
|
510
|
+
const blocked = /* @__PURE__ */ new Set([
|
|
511
|
+
this.passwordColumn,
|
|
512
|
+
this.rememberTokenColumn,
|
|
513
|
+
...authModel ? [authModel.resolvePasswordHashField(), authModel.resolveRememberTokenField()] : [],
|
|
514
|
+
...this.model.hidden ?? []
|
|
515
|
+
]);
|
|
516
|
+
const clean = {};
|
|
517
|
+
for (const [key, value] of Object.entries(user)) if (!blocked.has(key)) clean[key] = value;
|
|
518
|
+
return clean;
|
|
519
|
+
}
|
|
520
|
+
async setRememberToken(user, token) {
|
|
521
|
+
if (typeof user[this.rememberTokenColumn] !== "undefined") {
|
|
522
|
+
user[this.rememberTokenColumn] = token;
|
|
523
|
+
await this.model.forceUpdate({ [this.idColumn]: this.getId(user) }, { [this.rememberTokenColumn]: token });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async getRememberToken(user) {
|
|
527
|
+
const token = user[this.rememberTokenColumn];
|
|
528
|
+
if (token == null) return null;
|
|
529
|
+
return String(token);
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
//#endregion
|
|
533
|
+
//#region src/auth/utils.ts
|
|
534
|
+
/**
|
|
535
|
+
* Hash a token using SHA-256 or SHA-512.
|
|
536
|
+
*/
|
|
537
|
+
function hashToken(token, algorithm = "sha256") {
|
|
538
|
+
return createHash(algorithm).update(token).digest("hex");
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Generate a secure random token.
|
|
542
|
+
*/
|
|
543
|
+
function generateToken(length = 32) {
|
|
544
|
+
return randomBytes(length).toString("hex");
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Generate a random ID (16 bytes = 32 hex chars).
|
|
548
|
+
*/
|
|
549
|
+
function generateId() {
|
|
550
|
+
return randomBytes(16).toString("hex");
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Securely compare two hex strings using timing-safe comparison.
|
|
554
|
+
*
|
|
555
|
+
* Input that is not strict, even-length hex is rejected rather than compared:
|
|
556
|
+
* `Buffer.from(value, 'hex')` stops at the first invalid pair, so 'zzzz' and
|
|
557
|
+
* 'yyyy' both decode to nothing — and 'abcz' and 'abdz' both decode to the
|
|
558
|
+
* one byte they share — and would compare equal. A short decode is how the
|
|
559
|
+
* decoder reports that, which beats restating its grammar in a regex here.
|
|
560
|
+
* Use `secureStringCompare` for values that are not hex.
|
|
561
|
+
*/
|
|
562
|
+
function secureCompare(a, b) {
|
|
563
|
+
if (a.length !== b.length) return false;
|
|
564
|
+
const bufA = Buffer.from(a, "hex");
|
|
565
|
+
const bufB = Buffer.from(b, "hex");
|
|
566
|
+
if (bufA.length !== a.length / 2 || bufB.length !== b.length / 2) return false;
|
|
567
|
+
return timingSafeEqual(bufA, bufB);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Securely compare two arbitrary strings using timing-safe comparison.
|
|
571
|
+
* Unlike secureCompare, this works with any string encoding (UUIDs, tokens, etc.).
|
|
572
|
+
*/
|
|
573
|
+
function secureStringCompare(a, b) {
|
|
574
|
+
const bufA = Buffer.from(a, "utf8");
|
|
575
|
+
const bufB = Buffer.from(b, "utf8");
|
|
576
|
+
if (bufA.length !== bufB.length) return false;
|
|
577
|
+
return timingSafeEqual(bufA, bufB);
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Build a URL with token and optional email parameters.
|
|
581
|
+
*/
|
|
582
|
+
function buildTokenUrl(baseUrl, token, email) {
|
|
583
|
+
const url = new URL(baseUrl);
|
|
584
|
+
url.searchParams.set("token", token);
|
|
585
|
+
if (email) url.searchParams.set("email", email);
|
|
586
|
+
return url.toString();
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Parse a URL to extract token and email parameters.
|
|
590
|
+
*/
|
|
591
|
+
function parseTokenUrl(url) {
|
|
592
|
+
try {
|
|
593
|
+
const parsed = new URL(url);
|
|
594
|
+
return {
|
|
595
|
+
token: parsed.searchParams.get("token"),
|
|
596
|
+
email: parsed.searchParams.get("email")
|
|
597
|
+
};
|
|
598
|
+
} catch {
|
|
599
|
+
return {
|
|
600
|
+
token: null,
|
|
601
|
+
email: null
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region src/auth/SessionGuard.ts
|
|
607
|
+
const DEFAULT_SESSION_KEY = "auth:user_id";
|
|
608
|
+
const DEFAULT_REMEMBER_KEY = "auth:remember_token";
|
|
609
|
+
var SessionGuard = class {
|
|
610
|
+
options;
|
|
611
|
+
cachedUser;
|
|
612
|
+
constructor(options) {
|
|
613
|
+
this.options = options;
|
|
614
|
+
}
|
|
615
|
+
get currentSession() {
|
|
616
|
+
return this.options.session;
|
|
617
|
+
}
|
|
618
|
+
get provider() {
|
|
619
|
+
return this.options.provider;
|
|
620
|
+
}
|
|
621
|
+
sessionKey() {
|
|
622
|
+
return this.options.sessionKey ?? DEFAULT_SESSION_KEY;
|
|
623
|
+
}
|
|
624
|
+
rememberSessionKey() {
|
|
625
|
+
return this.options.rememberSessionKey ?? DEFAULT_REMEMBER_KEY;
|
|
626
|
+
}
|
|
627
|
+
async loadRememberedUser() {
|
|
628
|
+
if (!this.currentSession || !this.provider.getRememberToken) return null;
|
|
629
|
+
const rememberToken = this.currentSession.get(this.rememberSessionKey());
|
|
630
|
+
if (!rememberToken) return null;
|
|
631
|
+
const user = await this.provider.retrieveByCredentials({ rememberToken });
|
|
632
|
+
if (!user) {
|
|
633
|
+
this.currentSession.forget(this.rememberSessionKey());
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
const providerToken = await this.provider.getRememberToken?.(user);
|
|
637
|
+
if (!providerToken || !secureStringCompare(providerToken, rememberToken)) {
|
|
638
|
+
this.currentSession.forget(this.rememberSessionKey());
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
641
|
+
await this.provider.setRememberToken?.(user, rememberToken);
|
|
642
|
+
const sanitized = this.sanitizeUser(user);
|
|
643
|
+
this.cachedUser = sanitized;
|
|
644
|
+
return sanitized;
|
|
645
|
+
}
|
|
646
|
+
/** Strip auth-internal fields before a record is cached or exposed. */
|
|
647
|
+
sanitizeUser(user) {
|
|
648
|
+
return this.provider.sanitize ? this.provider.sanitize(user) : user;
|
|
649
|
+
}
|
|
650
|
+
async resolveUser() {
|
|
651
|
+
if (this.cachedUser !== void 0) return this.cachedUser;
|
|
652
|
+
const session = this.currentSession;
|
|
653
|
+
if (!session) {
|
|
654
|
+
this.cachedUser = null;
|
|
655
|
+
return null;
|
|
656
|
+
}
|
|
657
|
+
const identifier = session.get(this.sessionKey());
|
|
658
|
+
if (identifier == null) {
|
|
659
|
+
const remembered = await this.loadRememberedUser();
|
|
660
|
+
this.cachedUser = remembered;
|
|
661
|
+
return remembered;
|
|
662
|
+
}
|
|
663
|
+
const user = await this.provider.retrieveById(identifier);
|
|
664
|
+
if (!user) {
|
|
665
|
+
session.forget(this.sessionKey());
|
|
666
|
+
this.cachedUser = null;
|
|
667
|
+
return null;
|
|
668
|
+
}
|
|
669
|
+
const sanitized = this.sanitizeUser(user);
|
|
670
|
+
this.cachedUser = sanitized;
|
|
671
|
+
return sanitized;
|
|
672
|
+
}
|
|
673
|
+
async check() {
|
|
674
|
+
return await this.resolveUser() !== null;
|
|
675
|
+
}
|
|
676
|
+
async guest() {
|
|
677
|
+
return !await this.check();
|
|
678
|
+
}
|
|
679
|
+
async user() {
|
|
680
|
+
return await this.resolveUser() ?? null;
|
|
681
|
+
}
|
|
682
|
+
async id() {
|
|
683
|
+
const session = this.currentSession;
|
|
684
|
+
if (!session) return null;
|
|
685
|
+
return session.get(this.sessionKey()) ?? null;
|
|
686
|
+
}
|
|
687
|
+
async remember(user) {
|
|
688
|
+
if (!this.currentSession || !this.provider.setRememberToken) return;
|
|
689
|
+
const token = generateToken(32);
|
|
690
|
+
await this.provider.setRememberToken?.(user, token);
|
|
691
|
+
this.currentSession.set(this.rememberSessionKey(), token);
|
|
692
|
+
}
|
|
693
|
+
async login(user, remember = false) {
|
|
694
|
+
const castUser = user;
|
|
695
|
+
const session = this.currentSession;
|
|
696
|
+
if (!session) throw new Error("SessionGuard: session middleware is required to use the session guard.");
|
|
697
|
+
session.regenerate();
|
|
698
|
+
const identifier = this.provider.getId(castUser);
|
|
699
|
+
session.set(this.sessionKey(), identifier);
|
|
700
|
+
this.cachedUser = this.sanitizeUser(castUser);
|
|
701
|
+
if (remember) await this.remember(castUser);
|
|
702
|
+
else session.forget(this.rememberSessionKey());
|
|
703
|
+
}
|
|
704
|
+
async logout() {
|
|
705
|
+
const session = this.currentSession;
|
|
706
|
+
if (!session) return;
|
|
707
|
+
session.forget(this.sessionKey());
|
|
708
|
+
session.forget(this.rememberSessionKey());
|
|
709
|
+
this.cachedUser = null;
|
|
710
|
+
}
|
|
711
|
+
async attempt(credentials, remember = false) {
|
|
712
|
+
const user = await this.validate(credentials);
|
|
713
|
+
if (!user) return false;
|
|
714
|
+
await this.login(user, remember);
|
|
715
|
+
return true;
|
|
716
|
+
}
|
|
717
|
+
async validate(credentials) {
|
|
718
|
+
const user = await this.provider.retrieveByCredentials(credentials);
|
|
719
|
+
if (!user) {
|
|
720
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
721
|
+
return null;
|
|
722
|
+
}
|
|
723
|
+
if (!await this.provider.validateCredentials(user, credentials)) return null;
|
|
724
|
+
return user;
|
|
725
|
+
}
|
|
726
|
+
session() {
|
|
727
|
+
return this.currentSession;
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
//#endregion
|
|
731
|
+
//#region src/auth/AuthManager.ts
|
|
732
|
+
const DEFAULT_GUARD = "web";
|
|
733
|
+
var AuthManager = class {
|
|
734
|
+
guards = /* @__PURE__ */ new Map();
|
|
735
|
+
providers = /* @__PURE__ */ new Map();
|
|
736
|
+
defaultGuard;
|
|
737
|
+
constructor(options = {}) {
|
|
738
|
+
this.defaultGuard = options.defaultGuard ?? DEFAULT_GUARD;
|
|
739
|
+
}
|
|
740
|
+
registerGuard(name, factory) {
|
|
741
|
+
this.guards.set(name, { factory });
|
|
742
|
+
}
|
|
743
|
+
registerProvider(name, factory) {
|
|
744
|
+
this.providers.set(name, { factory });
|
|
745
|
+
}
|
|
746
|
+
getProvider(name) {
|
|
747
|
+
const entry = this.providers.get(name);
|
|
748
|
+
if (!entry) throw new Error(`AuthManager: provider "${name}" has not been registered.`);
|
|
749
|
+
if (!entry.instance) {
|
|
750
|
+
entry.instance = entry.factory(this);
|
|
751
|
+
this.providers.set(name, entry);
|
|
752
|
+
}
|
|
753
|
+
return entry.instance;
|
|
754
|
+
}
|
|
755
|
+
createGuard(name, context) {
|
|
756
|
+
const entry = this.guards.get(name);
|
|
757
|
+
if (!entry) throw new Error(`AuthManager: guard "${name}" has not been registered.`);
|
|
758
|
+
return entry.factory(context);
|
|
759
|
+
}
|
|
760
|
+
guardNames() {
|
|
761
|
+
return Array.from(this.guards.keys());
|
|
762
|
+
}
|
|
763
|
+
setDefaultGuard(name) {
|
|
764
|
+
if (!this.guards.has(name)) throw new Error(`AuthManager: cannot set default guard to unregistered guard "${name}".`);
|
|
765
|
+
this.defaultGuard = name;
|
|
766
|
+
}
|
|
767
|
+
getDefaultGuard() {
|
|
768
|
+
return this.defaultGuard;
|
|
769
|
+
}
|
|
770
|
+
createAuthContext(ctx, options = {}) {
|
|
771
|
+
const guardName = options.guard ?? this.defaultGuard;
|
|
772
|
+
const resolveSession = () => getSessionFromContext(ctx);
|
|
773
|
+
const guardFactory = (name) => {
|
|
774
|
+
const targetName = name ?? guardName;
|
|
775
|
+
return this.createGuard(targetName, {
|
|
776
|
+
ctx,
|
|
777
|
+
session: resolveSession(),
|
|
778
|
+
manager: this
|
|
779
|
+
});
|
|
780
|
+
};
|
|
781
|
+
return new RequestAuthContext(this, ctx, resolveSession, guardFactory);
|
|
782
|
+
}
|
|
783
|
+
async attempt(name, ctx, credentials, remember) {
|
|
784
|
+
return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Shorthand method to register a model-based authentication provider and session guard.
|
|
788
|
+
* This simplifies the common case of authenticating users via a database model.
|
|
789
|
+
*
|
|
790
|
+
* @param model - The model class to use for user authentication
|
|
791
|
+
* @param options - Options for the ModelUserProvider (partial, with defaults)
|
|
792
|
+
* @param providerName - Name for the provider (defaults to 'users')
|
|
793
|
+
* @param guardName - Name for the guard (defaults to 'web')
|
|
794
|
+
*/
|
|
795
|
+
useModel(model, options = {}, providerName = "users", guardName = "web") {
|
|
796
|
+
const defaultOptions = {
|
|
797
|
+
usernameColumn: "email",
|
|
798
|
+
credentialsPasswordField: "password",
|
|
799
|
+
hasher: new ScryptHasher(),
|
|
800
|
+
...options
|
|
801
|
+
};
|
|
802
|
+
this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
|
|
803
|
+
this.registerGuard(guardName, ({ session, manager }) => {
|
|
804
|
+
return new SessionGuard({
|
|
805
|
+
provider: manager.getProvider(providerName),
|
|
806
|
+
session
|
|
807
|
+
});
|
|
808
|
+
});
|
|
809
|
+
this.setDefaultGuard(guardName);
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
//#endregion
|
|
813
|
+
//#region src/support/redirect-target.ts
|
|
814
|
+
/**
|
|
815
|
+
* Shared open-redirect classification primitives, used by both the
|
|
816
|
+
* redirect-safety middleware and the OAuth `redirectTo` sanitizer. Keep every
|
|
817
|
+
* hardening fix here so the two layers cannot drift.
|
|
818
|
+
*/
|
|
819
|
+
/** Normalize backslash tricks (e.g. `/\evil.com`) before classifying. */
|
|
820
|
+
function normalizeRedirectTarget(value) {
|
|
821
|
+
return value.replace(/\\/g, "/");
|
|
822
|
+
}
|
|
823
|
+
/** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
|
|
824
|
+
function isAppRelativePath(value) {
|
|
825
|
+
return value.startsWith("/") && !value.startsWith("//");
|
|
826
|
+
}
|
|
827
|
+
/** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
|
|
828
|
+
function hostMatchesAllowlist(target, allowedHosts) {
|
|
829
|
+
const hostname = target.hostname.toLowerCase();
|
|
830
|
+
const host = target.host.toLowerCase();
|
|
831
|
+
for (const allowed of allowedHosts) if (allowed.startsWith("*.")) {
|
|
832
|
+
const suffix = allowed.slice(1).toLowerCase();
|
|
833
|
+
if (hostname.endsWith(suffix) && hostname.length > suffix.length) return true;
|
|
834
|
+
} else if (host === allowed.toLowerCase()) return true;
|
|
835
|
+
return false;
|
|
836
|
+
}
|
|
837
|
+
//#endregion
|
|
838
|
+
//#region src/auth/api-token.ts
|
|
839
|
+
/**
|
|
840
|
+
* In-memory token store for testing.
|
|
841
|
+
* Do NOT use in production - tokens will be lost on restart.
|
|
842
|
+
*/
|
|
843
|
+
var MemoryApiTokenStore = class {
|
|
844
|
+
tokens = /* @__PURE__ */ new Map();
|
|
845
|
+
byHash = /* @__PURE__ */ new Map();
|
|
846
|
+
async store(token) {
|
|
847
|
+
this.tokens.set(token.id, token);
|
|
848
|
+
this.byHash.set(token.hashedToken, token.id);
|
|
849
|
+
}
|
|
850
|
+
async findByHashedToken(hashedToken) {
|
|
851
|
+
const id = this.byHash.get(hashedToken);
|
|
852
|
+
if (!id) return null;
|
|
853
|
+
return this.tokens.get(id) ?? null;
|
|
854
|
+
}
|
|
855
|
+
async findByUserId(userId) {
|
|
856
|
+
const userIdStr = String(userId);
|
|
857
|
+
return Array.from(this.tokens.values()).filter((t) => String(t.userId) === userIdStr);
|
|
858
|
+
}
|
|
859
|
+
async delete(id) {
|
|
860
|
+
const token = this.tokens.get(id);
|
|
861
|
+
if (token) {
|
|
862
|
+
this.byHash.delete(token.hashedToken);
|
|
863
|
+
this.tokens.delete(id);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
async deleteForUser(userId) {
|
|
867
|
+
const userIdStr = String(userId);
|
|
868
|
+
for (const [id, token] of this.tokens.entries()) if (String(token.userId) === userIdStr) {
|
|
869
|
+
this.byHash.delete(token.hashedToken);
|
|
870
|
+
this.tokens.delete(id);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
async updateLastUsed(id, timestamp) {
|
|
874
|
+
const token = this.tokens.get(id);
|
|
875
|
+
if (token) token.lastUsedAt = timestamp;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Clear all tokens (useful for testing).
|
|
879
|
+
*/
|
|
880
|
+
clear() {
|
|
881
|
+
this.tokens.clear();
|
|
882
|
+
this.byHash.clear();
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Get the number of stored tokens.
|
|
886
|
+
*/
|
|
887
|
+
get size() {
|
|
888
|
+
return this.tokens.size;
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
/**
|
|
892
|
+
* Create a new API token.
|
|
893
|
+
*
|
|
894
|
+
* @example
|
|
895
|
+
* ```ts
|
|
896
|
+
* const { plainTextToken, token } = await createApiToken(store, {
|
|
897
|
+
* name: 'My App Token',
|
|
898
|
+
* userId: user.id,
|
|
899
|
+
* abilities: ['read', 'write'],
|
|
900
|
+
* expiresIn: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
901
|
+
* })
|
|
902
|
+
*
|
|
903
|
+
* // Return plainTextToken to user - this is the only time it's available
|
|
904
|
+
* return ctx.json({ token: plainTextToken })
|
|
905
|
+
* ```
|
|
906
|
+
*/
|
|
907
|
+
async function createApiToken(store, options) {
|
|
908
|
+
const { name, userId, abilities = ["*"], expiresIn = null, tokenLength = 32 } = options;
|
|
909
|
+
const id = generateId();
|
|
910
|
+
const plainToken = generateToken(tokenLength);
|
|
911
|
+
const hashedToken = hashToken(plainToken);
|
|
912
|
+
const now = /* @__PURE__ */ new Date();
|
|
913
|
+
const token = {
|
|
914
|
+
id,
|
|
915
|
+
name,
|
|
916
|
+
hashedToken,
|
|
917
|
+
userId,
|
|
918
|
+
abilities,
|
|
919
|
+
lastUsedAt: null,
|
|
920
|
+
expiresAt: expiresIn == null ? null : new Date(now.getTime() + expiresIn),
|
|
921
|
+
createdAt: now
|
|
922
|
+
};
|
|
923
|
+
await store.store(token);
|
|
924
|
+
return {
|
|
925
|
+
plainTextToken: `${id}|${plainToken}`,
|
|
926
|
+
token
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Parse a plain text token into its components.
|
|
931
|
+
*/
|
|
932
|
+
function parseApiToken(plainTextToken) {
|
|
933
|
+
const parts = plainTextToken.split("|");
|
|
934
|
+
if (parts.length !== 2) return null;
|
|
935
|
+
const [id, token] = parts;
|
|
936
|
+
if (!id || !token) return null;
|
|
937
|
+
return {
|
|
938
|
+
id,
|
|
939
|
+
token
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Verify an API token and return the associated user ID.
|
|
944
|
+
*
|
|
945
|
+
* @example
|
|
946
|
+
* ```ts
|
|
947
|
+
* const result = await verifyApiToken(plainTextToken, store)
|
|
948
|
+
*
|
|
949
|
+
* if (!result) {
|
|
950
|
+
* return ctx.json({ error: 'Invalid token' }, 401)
|
|
951
|
+
* }
|
|
952
|
+
*
|
|
953
|
+
* console.log(`User ${result.userId} authenticated with abilities:`, result.abilities)
|
|
954
|
+
* ```
|
|
955
|
+
*/
|
|
956
|
+
async function verifyApiToken(plainTextToken, store, options = {}) {
|
|
957
|
+
const { updateLastUsed = true } = options;
|
|
958
|
+
const parsed = parseApiToken(plainTextToken);
|
|
959
|
+
if (!parsed) return null;
|
|
960
|
+
const hashedToken = hashToken(parsed.token);
|
|
961
|
+
const token = await store.findByHashedToken(hashedToken);
|
|
962
|
+
if (!token) return null;
|
|
963
|
+
if (token.id !== parsed.id) return null;
|
|
964
|
+
if (isOptionalExpiryPast(token.expiresAt)) return null;
|
|
965
|
+
if (!secureCompare(token.hashedToken, hashedToken)) return null;
|
|
966
|
+
if (updateLastUsed) await store.updateLastUsed(token.id, /* @__PURE__ */ new Date());
|
|
967
|
+
return {
|
|
968
|
+
token,
|
|
969
|
+
userId: token.userId,
|
|
970
|
+
abilities: token.abilities
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* Check if a token has a specific ability.
|
|
975
|
+
*/
|
|
976
|
+
function tokenCan(token, ability) {
|
|
977
|
+
if (token.abilities.includes("*")) return true;
|
|
978
|
+
return token.abilities.includes(ability);
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* Check if a token has all specified abilities.
|
|
982
|
+
*/
|
|
983
|
+
function tokenCanAll(token, abilities) {
|
|
984
|
+
if (token.abilities.includes("*")) return true;
|
|
985
|
+
return abilities.every((ability) => token.abilities.includes(ability));
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* Check if a token has any of the specified abilities.
|
|
989
|
+
*/
|
|
990
|
+
function tokenCanAny(token, abilities) {
|
|
991
|
+
if (token.abilities.includes("*")) return true;
|
|
992
|
+
return abilities.some((ability) => token.abilities.includes(ability));
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Revoke (delete) an API token.
|
|
996
|
+
*
|
|
997
|
+
* @example
|
|
998
|
+
* ```ts
|
|
999
|
+
* await revokeApiToken(tokenId, store)
|
|
1000
|
+
* ```
|
|
1001
|
+
*/
|
|
1002
|
+
async function revokeApiToken(id, store) {
|
|
1003
|
+
await store.delete(id);
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Revoke all API tokens for a user.
|
|
1007
|
+
*
|
|
1008
|
+
* @example
|
|
1009
|
+
* ```ts
|
|
1010
|
+
* // Revoke all tokens when user changes password
|
|
1011
|
+
* await revokeAllApiTokens(user.id, store)
|
|
1012
|
+
* ```
|
|
1013
|
+
*/
|
|
1014
|
+
async function revokeAllApiTokens(userId, store) {
|
|
1015
|
+
await store.deleteForUser(userId);
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* Get all API tokens for a user.
|
|
1019
|
+
*
|
|
1020
|
+
* @example
|
|
1021
|
+
* ```ts
|
|
1022
|
+
* const tokens = await getUserApiTokens(user.id, store)
|
|
1023
|
+
* // Returns tokens without the plain text (only metadata)
|
|
1024
|
+
* ```
|
|
1025
|
+
*/
|
|
1026
|
+
async function getUserApiTokens(userId, store) {
|
|
1027
|
+
return store.findByUserId(userId);
|
|
1028
|
+
}
|
|
1029
|
+
/**
|
|
1030
|
+
* Context key for storing the authenticated token.
|
|
1031
|
+
*/
|
|
1032
|
+
const API_TOKEN_KEY = "guren:api-token";
|
|
1033
|
+
/**
|
|
1034
|
+
* Create middleware that authenticates requests using Bearer tokens.
|
|
1035
|
+
*
|
|
1036
|
+
* @example
|
|
1037
|
+
* ```ts
|
|
1038
|
+
* // Basic usage
|
|
1039
|
+
* app.use('/api/*', createBearerTokenMiddleware({ store }))
|
|
1040
|
+
*
|
|
1041
|
+
* // With ability requirement
|
|
1042
|
+
* router.delete('/api/posts/:id', [PostController, 'destroy'],
|
|
1043
|
+
* createBearerTokenMiddleware({
|
|
1044
|
+
* store,
|
|
1045
|
+
* abilities: ['posts:delete'],
|
|
1046
|
+
* })
|
|
1047
|
+
* )
|
|
1048
|
+
*
|
|
1049
|
+
* // With user loading
|
|
1050
|
+
* app.use('/api/*', createBearerTokenMiddleware({
|
|
1051
|
+
* store,
|
|
1052
|
+
* loadUser: async (userId) => User.find(userId),
|
|
1053
|
+
* }))
|
|
1054
|
+
* ```
|
|
1055
|
+
*/
|
|
1056
|
+
function createBearerTokenMiddleware(options) {
|
|
1057
|
+
const { store, loadUser, abilities, onUnauthorized, onForbidden, headerName = "Authorization", updateLastUsed = true } = options;
|
|
1058
|
+
return async (ctx, next) => {
|
|
1059
|
+
const authHeader = ctx.req.header(headerName);
|
|
1060
|
+
if (!authHeader) {
|
|
1061
|
+
if (onUnauthorized) return onUnauthorized(ctx);
|
|
1062
|
+
return ctx.json({ error: "Authentication required" }, 401);
|
|
1063
|
+
}
|
|
1064
|
+
const match = authHeader.match(/^Bearer\s+(.+)$/i);
|
|
1065
|
+
if (!match) {
|
|
1066
|
+
if (onUnauthorized) return onUnauthorized(ctx);
|
|
1067
|
+
return ctx.json({ error: "Invalid authorization format" }, 401);
|
|
1068
|
+
}
|
|
1069
|
+
const plainTextToken = match[1];
|
|
1070
|
+
const result = await verifyApiToken(plainTextToken, store, { updateLastUsed });
|
|
1071
|
+
if (!result) {
|
|
1072
|
+
if (onUnauthorized) return onUnauthorized(ctx);
|
|
1073
|
+
return ctx.json({ error: "Invalid or expired token" }, 401);
|
|
1074
|
+
}
|
|
1075
|
+
if (abilities && abilities.length > 0) {
|
|
1076
|
+
if (!tokenCanAll(result.token, abilities)) {
|
|
1077
|
+
if (onForbidden) return onForbidden(ctx, abilities);
|
|
1078
|
+
return ctx.json({
|
|
1079
|
+
error: "Token lacks required abilities",
|
|
1080
|
+
required: abilities
|
|
1081
|
+
}, 403);
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
ctx.set(API_TOKEN_KEY, result);
|
|
1085
|
+
if (loadUser) {
|
|
1086
|
+
const user = await loadUser(result.userId);
|
|
1087
|
+
ctx.set("guren:user", user);
|
|
1088
|
+
}
|
|
1089
|
+
return next();
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
/**
|
|
1093
|
+
* Get the authenticated API token from the request context.
|
|
1094
|
+
*
|
|
1095
|
+
* @example
|
|
1096
|
+
* ```ts
|
|
1097
|
+
* router.get('/api/me', async (ctx) => {
|
|
1098
|
+
* const { token, userId, abilities } = getApiToken(ctx)!
|
|
1099
|
+
* return ctx.json({ userId, tokenName: token.name, abilities })
|
|
1100
|
+
* })
|
|
1101
|
+
* ```
|
|
1102
|
+
*/
|
|
1103
|
+
function getApiToken(ctx) {
|
|
1104
|
+
return ctx.get(API_TOKEN_KEY);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Get the authenticated API token from the request context, or throw.
|
|
1108
|
+
*
|
|
1109
|
+
* @throws {AuthenticationException} When no token is present in the context.
|
|
1110
|
+
*
|
|
1111
|
+
* @example
|
|
1112
|
+
* ```ts
|
|
1113
|
+
* router.get('/api/me', async (ctx) => {
|
|
1114
|
+
* const { token, userId, abilities } = getApiTokenOrFail(ctx)
|
|
1115
|
+
* return ctx.json({ userId, tokenName: token.name, abilities })
|
|
1116
|
+
* })
|
|
1117
|
+
* ```
|
|
1118
|
+
*/
|
|
1119
|
+
function getApiTokenOrFail(ctx) {
|
|
1120
|
+
const result = getApiToken(ctx);
|
|
1121
|
+
if (!result) throw new AuthenticationException("Unauthenticated.");
|
|
1122
|
+
return result;
|
|
1123
|
+
}
|
|
1124
|
+
//#endregion
|
|
1125
|
+
//#region src/auth/oauth/index.ts
|
|
1126
|
+
/** Session key holding the per-browser bindings between authorize and callback. */
|
|
1127
|
+
const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
|
|
1128
|
+
/**
|
|
1129
|
+
* How many unfinished flows one browser may have bindings for.
|
|
1130
|
+
*
|
|
1131
|
+
* Every `authorize()` parks one entry, and an abandoned flow leaves it behind
|
|
1132
|
+
* until it expires, so the list is capped. Beyond the cap the oldest entry is
|
|
1133
|
+
* dropped — that flow's callback then fails, which is the same outcome it had
|
|
1134
|
+
* before any of this existed.
|
|
1135
|
+
*/
|
|
1136
|
+
const MAX_PENDING_SESSION_BINDINGS = 5;
|
|
1137
|
+
let warnedAboutUnboundState = false;
|
|
1138
|
+
/**
|
|
1139
|
+
* An unbound `state` is transferable between browsers, which is exactly the
|
|
1140
|
+
* attack `state` exists to stop. Verification stays permissive so apps written
|
|
1141
|
+
* against the previous API keep working, so this is the only thing that tells
|
|
1142
|
+
* them they are exposed.
|
|
1143
|
+
*/
|
|
1144
|
+
function warnOnceAboutUnboundState() {
|
|
1145
|
+
if (warnedAboutUnboundState) return;
|
|
1146
|
+
warnedAboutUnboundState = true;
|
|
1147
|
+
console.warn("[guren] OAuth authorize() was called without `session` or `bindTo`, so `state` is not tied to the browser that started the flow. An attacker can then complete their own authorization in a victim's browser and log the victim into the attacker's account. Pass the current session (`this.auth.session()`) as `session` to both authorize() and handleCallback(), or manage a per-browser value yourself via `bindTo`. See: https://guren.dev/docs/guides/oauth");
|
|
1148
|
+
}
|
|
1149
|
+
let warnedAboutDroppedBinding = false;
|
|
1150
|
+
/**
|
|
1151
|
+
* The flow was bound at authorize time but the state came back without one,
|
|
1152
|
+
* so the configured `OAuthStateStore` is not persisting `binding` — which
|
|
1153
|
+
* silently reverts the protection to the transferable state it replaced.
|
|
1154
|
+
*/
|
|
1155
|
+
function warnOnceAboutDroppedBinding() {
|
|
1156
|
+
if (warnedAboutDroppedBinding) return;
|
|
1157
|
+
warnedAboutDroppedBinding = true;
|
|
1158
|
+
console.warn("[guren] An OAuth state was created with `bindTo` but came back from the state store without its binding, so the callback could not be tied to the browser that started the flow. The configured OAuthStateStore is dropping `OAuthStatePayload.binding` — for DatabaseOAuthStateStore this usually means the `oauth_states` table has no `binding` column. See: https://guren.dev/docs/guides/oauth");
|
|
1159
|
+
}
|
|
1160
|
+
function readPendingBindings(session) {
|
|
1161
|
+
const stored = session.get(OAUTH_SESSION_BINDING_KEY);
|
|
1162
|
+
if (!Array.isArray(stored)) return [];
|
|
1163
|
+
const now = Date.now();
|
|
1164
|
+
return stored.filter((entry) => typeof entry === "object" && entry !== null && typeof entry.stateHash === "string" && typeof entry.binding === "string" && typeof entry.expiresAt === "number" && entry.expiresAt > now);
|
|
1165
|
+
}
|
|
1166
|
+
function issueSessionBinding(session) {
|
|
1167
|
+
if (!session) return void 0;
|
|
1168
|
+
return generateToken(DEFAULT_STATE_LENGTH);
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Park a minted binding against the state it belongs to.
|
|
1172
|
+
*
|
|
1173
|
+
* Keyed by state rather than kept in one slot, so a browser can have several
|
|
1174
|
+
* flows in flight — two tabs, or a visitor who picks a different provider —
|
|
1175
|
+
* without each `authorize()` invalidating the one before it.
|
|
1176
|
+
*/
|
|
1177
|
+
function rememberSessionBinding(session, stateHash, binding, expiresAt) {
|
|
1178
|
+
const pending = readPendingBindings(session);
|
|
1179
|
+
pending.push({
|
|
1180
|
+
stateHash,
|
|
1181
|
+
binding,
|
|
1182
|
+
expiresAt: expiresAt.getTime()
|
|
1183
|
+
});
|
|
1184
|
+
session.set(OAUTH_SESSION_BINDING_KEY, pending.slice(Math.max(0, pending.length - MAX_PENDING_SESSION_BINDINGS)));
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* Take the binding belonging to this callback's state, leaving the rest.
|
|
1188
|
+
*
|
|
1189
|
+
* Only the matching entry is removed: a forged callback carrying an unknown
|
|
1190
|
+
* state must not be able to strip a real flow's binding and lock the visitor
|
|
1191
|
+
* out of the login they actually started.
|
|
1192
|
+
*/
|
|
1193
|
+
function consumeSessionBinding(session, stateHash) {
|
|
1194
|
+
if (!session) return void 0;
|
|
1195
|
+
const pending = readPendingBindings(session);
|
|
1196
|
+
if (pending.length === 0) return void 0;
|
|
1197
|
+
const match = pending.find((entry) => entry.stateHash === stateHash);
|
|
1198
|
+
session.set(OAUTH_SESSION_BINDING_KEY, pending.filter((entry) => entry.stateHash !== stateHash));
|
|
1199
|
+
return match?.binding;
|
|
1200
|
+
}
|
|
1201
|
+
const DEFAULT_STATE_EXPIRES_IN = 6e5;
|
|
1202
|
+
const DEFAULT_STATE_LENGTH = 24;
|
|
1203
|
+
const DEFAULT_STATE_HASH_ALGORITHM = "sha256";
|
|
1204
|
+
var MemoryOAuthStateStore = class {
|
|
1205
|
+
states = /* @__PURE__ */ new Map();
|
|
1206
|
+
maxEntries;
|
|
1207
|
+
constructor(options = {}) {
|
|
1208
|
+
this.maxEntries = options.maxEntries ?? 1e4;
|
|
1209
|
+
}
|
|
1210
|
+
async store(stateHash, payload) {
|
|
1211
|
+
if (this.states.size >= this.maxEntries) this.sweepExpired();
|
|
1212
|
+
while (this.states.size >= this.maxEntries) {
|
|
1213
|
+
const oldest = this.states.keys().next().value;
|
|
1214
|
+
if (oldest === void 0) break;
|
|
1215
|
+
this.states.delete(oldest);
|
|
1216
|
+
}
|
|
1217
|
+
this.states.set(stateHash, payload);
|
|
1218
|
+
}
|
|
1219
|
+
sweepExpired() {
|
|
1220
|
+
const now = Date.now();
|
|
1221
|
+
for (const [hash, payload] of this.states) if (isExpired(payload.expiresAt, now)) this.states.delete(hash);
|
|
1222
|
+
}
|
|
1223
|
+
async find(stateHash) {
|
|
1224
|
+
const payload = this.states.get(stateHash);
|
|
1225
|
+
if (!payload) return null;
|
|
1226
|
+
if (isExpired(payload.expiresAt)) {
|
|
1227
|
+
this.states.delete(stateHash);
|
|
1228
|
+
return null;
|
|
1229
|
+
}
|
|
1230
|
+
return payload;
|
|
1231
|
+
}
|
|
1232
|
+
async delete(stateHash) {
|
|
1233
|
+
this.states.delete(stateHash);
|
|
1234
|
+
}
|
|
1235
|
+
async consume(stateHash) {
|
|
1236
|
+
const payload = this.states.get(stateHash);
|
|
1237
|
+
if (!payload) return null;
|
|
1238
|
+
this.states.delete(stateHash);
|
|
1239
|
+
if (isExpired(payload.expiresAt)) return null;
|
|
1240
|
+
return payload;
|
|
1241
|
+
}
|
|
1242
|
+
clear() {
|
|
1243
|
+
this.states.clear();
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
var OAuthManager = class {
|
|
1247
|
+
providers = /* @__PURE__ */ new Map();
|
|
1248
|
+
stateStore;
|
|
1249
|
+
stateConfig;
|
|
1250
|
+
constructor(options = {}) {
|
|
1251
|
+
this.stateStore = options.stateStore ?? new MemoryOAuthStateStore();
|
|
1252
|
+
this.stateConfig = {
|
|
1253
|
+
expiresIn: options.stateConfig?.expiresIn ?? DEFAULT_STATE_EXPIRES_IN,
|
|
1254
|
+
stateLength: options.stateConfig?.stateLength ?? DEFAULT_STATE_LENGTH,
|
|
1255
|
+
hashAlgorithm: options.stateConfig?.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM,
|
|
1256
|
+
allowedRedirectHosts: options.stateConfig?.allowedRedirectHosts ?? []
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
registerProvider(name, config) {
|
|
1260
|
+
this.providers.set(name, config);
|
|
1261
|
+
}
|
|
1262
|
+
providerNames() {
|
|
1263
|
+
return Array.from(this.providers.keys()).sort((a, b) => a.localeCompare(b));
|
|
1264
|
+
}
|
|
1265
|
+
getProvider(name) {
|
|
1266
|
+
const provider = this.providers.get(name);
|
|
1267
|
+
if (!provider) throw new AuthenticationException(`OAuth provider "${name}" is not configured.`);
|
|
1268
|
+
return provider;
|
|
1269
|
+
}
|
|
1270
|
+
async authorize(providerName, options = {}) {
|
|
1271
|
+
const provider = this.getProvider(providerName);
|
|
1272
|
+
const sessionBinding = options.bindTo ? void 0 : issueSessionBinding(options.session);
|
|
1273
|
+
const bindTo = options.bindTo ?? sessionBinding;
|
|
1274
|
+
if (!bindTo) warnOnceAboutUnboundState();
|
|
1275
|
+
const { state, expiresAt } = await createOAuthState(providerName, this.stateStore, this.stateConfig, options.redirectTo, options.state, bindTo);
|
|
1276
|
+
if (sessionBinding && options.session) rememberSessionBinding(options.session, hashToken(state, this.stateConfig.hashAlgorithm), sessionBinding, expiresAt);
|
|
1277
|
+
return {
|
|
1278
|
+
url: buildOAuthAuthorizeUrl(provider, state, {
|
|
1279
|
+
scope: options.scope ?? provider.scopes,
|
|
1280
|
+
extraParams: options.extraParams
|
|
1281
|
+
}),
|
|
1282
|
+
state,
|
|
1283
|
+
expiresAt
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
async user(providerName, payload) {
|
|
1287
|
+
const { profile } = await this.handleCallback(providerName, payload);
|
|
1288
|
+
return profile;
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* Verify the callback and return the user profile together with the
|
|
1292
|
+
* sanitized `redirectTo` stored at authorize time. `redirectTo` is safe to
|
|
1293
|
+
* pass to a redirect response: app-relative paths and allowlisted hosts
|
|
1294
|
+
* only.
|
|
1295
|
+
*/
|
|
1296
|
+
async handleCallback(providerName, payload) {
|
|
1297
|
+
const provider = this.getProvider(providerName);
|
|
1298
|
+
const verified = await verifyOAuthState(payload.state, providerName, this.stateStore, this.stateConfig, payload.bindTo ?? consumeSessionBinding(payload.session, hashToken(payload.state, this.stateConfig.hashAlgorithm)));
|
|
1299
|
+
if (!verified) throw new AuthenticationException("Invalid or expired OAuth state.");
|
|
1300
|
+
return {
|
|
1301
|
+
profile: await fetchOAuthUserProfile(provider, await exchangeOAuthCode(provider, payload.code)),
|
|
1302
|
+
redirectTo: verified.redirectTo
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
function createOAuthManager(options = {}) {
|
|
1307
|
+
return new OAuthManager(options);
|
|
1308
|
+
}
|
|
1309
|
+
async function createOAuthState(provider, store, config = {}, redirectTo, fixedState, bindTo) {
|
|
1310
|
+
const state = fixedState ?? generateToken(config.stateLength ?? DEFAULT_STATE_LENGTH);
|
|
1311
|
+
const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
|
|
1312
|
+
const expiresAt = new Date(Date.now() + (config.expiresIn ?? DEFAULT_STATE_EXPIRES_IN));
|
|
1313
|
+
const stateHash = hashToken(state, hashAlgorithm);
|
|
1314
|
+
await store.store(stateHash, {
|
|
1315
|
+
provider,
|
|
1316
|
+
redirectTo: sanitizeOAuthRedirect(redirectTo, config.allowedRedirectHosts),
|
|
1317
|
+
expiresAt,
|
|
1318
|
+
binding: bindTo ? hashToken(bindTo, hashAlgorithm) : void 0
|
|
1319
|
+
});
|
|
1320
|
+
return {
|
|
1321
|
+
state,
|
|
1322
|
+
expiresAt
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
async function verifyOAuthState(state, provider, store, config = {}, bindTo) {
|
|
1326
|
+
const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
|
|
1327
|
+
const stateHash = hashToken(state, hashAlgorithm);
|
|
1328
|
+
const payload = typeof store.consume === "function" ? await store.consume(stateHash) : await findAndDeleteState(store, stateHash);
|
|
1329
|
+
if (!payload) return null;
|
|
1330
|
+
if (payload.provider !== provider) return null;
|
|
1331
|
+
if (!bindingMatches(payload.binding, bindTo, hashAlgorithm)) return null;
|
|
1332
|
+
return {
|
|
1333
|
+
...payload,
|
|
1334
|
+
redirectTo: sanitizeOAuthRedirect(payload.redirectTo, config.allowedRedirectHosts)
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* Whether the presented value matches the binding recorded at authorize time.
|
|
1339
|
+
*
|
|
1340
|
+
* A state created without a binding still verifies, so an app that has not
|
|
1341
|
+
* adopted `bindTo` keeps working. A state created *with* one is useless to a
|
|
1342
|
+
* browser that cannot present it, which is the whole point — so a missing or
|
|
1343
|
+
* wrong value fails.
|
|
1344
|
+
*/
|
|
1345
|
+
function bindingMatches(stored, presented, hashAlgorithm) {
|
|
1346
|
+
if (!stored) {
|
|
1347
|
+
if (presented) warnOnceAboutDroppedBinding();
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
if (!presented) return false;
|
|
1351
|
+
return secureCompare(stored, hashToken(presented, hashAlgorithm));
|
|
1352
|
+
}
|
|
1353
|
+
async function findAndDeleteState(store, stateHash) {
|
|
1354
|
+
const payload = await store.find(stateHash);
|
|
1355
|
+
if (!payload) return null;
|
|
1356
|
+
await store.delete(stateHash);
|
|
1357
|
+
return payload;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Reduce a `redirectTo` value to a safe target: app-relative paths always
|
|
1361
|
+
* pass; absolute http(s) URLs pass only when their host is in the allowlist
|
|
1362
|
+
* (supports `*.example.com` wildcards). Everything else — protocol-relative
|
|
1363
|
+
* URLs, backslash tricks, `javascript:` and other schemes — returns
|
|
1364
|
+
* `undefined`.
|
|
1365
|
+
*/
|
|
1366
|
+
function sanitizeOAuthRedirect(redirectTo, allowedHosts = []) {
|
|
1367
|
+
const value = redirectTo?.trim();
|
|
1368
|
+
if (!value) return;
|
|
1369
|
+
const normalized = normalizeRedirectTarget(value);
|
|
1370
|
+
if (isAppRelativePath(normalized)) return normalized;
|
|
1371
|
+
try {
|
|
1372
|
+
const target = new URL(normalized);
|
|
1373
|
+
if (target.protocol !== "http:" && target.protocol !== "https:") return;
|
|
1374
|
+
return hostMatchesAllowlist(target, allowedHosts) ? normalized : void 0;
|
|
1375
|
+
} catch {
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
function buildOAuthAuthorizeUrl(provider, state, options = {}) {
|
|
1380
|
+
const url = new URL(provider.authorizeUrl);
|
|
1381
|
+
url.searchParams.set("response_type", "code");
|
|
1382
|
+
url.searchParams.set("client_id", provider.clientId);
|
|
1383
|
+
url.searchParams.set("redirect_uri", provider.redirectUri);
|
|
1384
|
+
url.searchParams.set("state", state);
|
|
1385
|
+
const scopes = options.scope ?? provider.scopes;
|
|
1386
|
+
if (scopes && scopes.length > 0) url.searchParams.set("scope", scopes.join(" "));
|
|
1387
|
+
for (const [key, value] of Object.entries(options.extraParams ?? {})) url.searchParams.set(key, value);
|
|
1388
|
+
return url.toString();
|
|
1389
|
+
}
|
|
1390
|
+
async function exchangeOAuthCode(provider, code) {
|
|
1391
|
+
const params = new URLSearchParams({
|
|
1392
|
+
grant_type: "authorization_code",
|
|
1393
|
+
code,
|
|
1394
|
+
redirect_uri: provider.redirectUri,
|
|
1395
|
+
client_id: provider.clientId
|
|
1396
|
+
});
|
|
1397
|
+
const headers = {
|
|
1398
|
+
Accept: "application/json",
|
|
1399
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
1400
|
+
};
|
|
1401
|
+
if (provider.tokenAuthMethod === "client_secret_basic") headers.Authorization = `Basic ${Buffer.from(`${provider.clientId}:${provider.clientSecret}`).toString("base64")}`;
|
|
1402
|
+
else params.set("client_secret", provider.clientSecret);
|
|
1403
|
+
const response = await fetch(provider.tokenUrl, {
|
|
1404
|
+
method: "POST",
|
|
1405
|
+
headers,
|
|
1406
|
+
body: params.toString()
|
|
1407
|
+
});
|
|
1408
|
+
if (!response.ok) throw new AuthenticationException(`OAuth token exchange failed (${response.status}).`);
|
|
1409
|
+
const raw = await response.json();
|
|
1410
|
+
const accessToken = typeof raw.access_token === "string" ? raw.access_token : "";
|
|
1411
|
+
if (!accessToken) throw new AuthenticationException("OAuth token exchange did not return an access token.");
|
|
1412
|
+
return {
|
|
1413
|
+
accessToken,
|
|
1414
|
+
tokenType: typeof raw.token_type === "string" ? raw.token_type : void 0,
|
|
1415
|
+
refreshToken: typeof raw.refresh_token === "string" ? raw.refresh_token : void 0,
|
|
1416
|
+
expiresIn: typeof raw.expires_in === "number" ? raw.expires_in : void 0,
|
|
1417
|
+
scope: typeof raw.scope === "string" ? raw.scope : void 0,
|
|
1418
|
+
raw
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
async function fetchOAuthUserProfile(provider, token) {
|
|
1422
|
+
const response = await fetch(provider.userInfoUrl, {
|
|
1423
|
+
method: provider.userInfoMethod ?? "GET",
|
|
1424
|
+
headers: {
|
|
1425
|
+
Accept: "application/json",
|
|
1426
|
+
Authorization: `Bearer ${token.accessToken}`,
|
|
1427
|
+
"User-Agent": "guren-oauth"
|
|
1428
|
+
}
|
|
1429
|
+
});
|
|
1430
|
+
if (!response.ok) throw new AuthenticationException(`OAuth user fetch failed (${response.status}).`);
|
|
1431
|
+
const raw = await response.json();
|
|
1432
|
+
const profile = provider.mapProfile ? provider.mapProfile(raw, token) : defaultProfileFromUserInfo(raw, token, provider.emailVerifiedKey);
|
|
1433
|
+
if (!profile.email && provider.fetchFallbackEmail) {
|
|
1434
|
+
const fallback = await provider.fetchFallbackEmail(token);
|
|
1435
|
+
const email = typeof fallback === "string" ? fallback : fallback?.email;
|
|
1436
|
+
if (email) {
|
|
1437
|
+
const emailVerified = typeof fallback === "string" ? void 0 : fallback?.emailVerified;
|
|
1438
|
+
return {
|
|
1439
|
+
...profile,
|
|
1440
|
+
email,
|
|
1441
|
+
emailVerified
|
|
1442
|
+
};
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
return profile;
|
|
1446
|
+
}
|
|
1447
|
+
const DEFAULT_EMAIL_VERIFIED_KEY = "email_verified";
|
|
1448
|
+
function readEmailVerified(raw, key = DEFAULT_EMAIL_VERIFIED_KEY) {
|
|
1449
|
+
const value = raw[key];
|
|
1450
|
+
return typeof value === "boolean" ? value : void 0;
|
|
1451
|
+
}
|
|
1452
|
+
function defaultProfileFromUserInfo(raw, token, emailVerifiedKey) {
|
|
1453
|
+
const idCandidate = raw.id ?? raw.sub;
|
|
1454
|
+
const id = typeof idCandidate === "string" || typeof idCandidate === "number" ? String(idCandidate) : "";
|
|
1455
|
+
if (!id) throw new AuthenticationException("OAuth user profile is missing an identifier.");
|
|
1456
|
+
return {
|
|
1457
|
+
id,
|
|
1458
|
+
email: typeof raw.email === "string" ? raw.email : void 0,
|
|
1459
|
+
emailVerified: readEmailVerified(raw, emailVerifiedKey),
|
|
1460
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
1461
|
+
avatar: typeof raw.avatar_url === "string" ? raw.avatar_url : typeof raw.picture === "string" ? raw.picture : typeof raw.avatar === "string" ? raw.avatar : void 0,
|
|
1462
|
+
token,
|
|
1463
|
+
raw
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
async function fetchGitHubPrimaryEmail(token) {
|
|
1467
|
+
const response = await fetch("https://api.github.com/user/emails", { headers: {
|
|
1468
|
+
Accept: "application/vnd.github+json",
|
|
1469
|
+
Authorization: `Bearer ${token.accessToken}`,
|
|
1470
|
+
"User-Agent": "guren-oauth"
|
|
1471
|
+
} });
|
|
1472
|
+
if (!response.ok) return;
|
|
1473
|
+
const emails = await response.json();
|
|
1474
|
+
if (!Array.isArray(emails)) return;
|
|
1475
|
+
const primary = emails.find((entry) => typeof entry === "object" && entry !== null && entry.primary === true && entry.verified === true && typeof entry.email === "string");
|
|
1476
|
+
return primary ? {
|
|
1477
|
+
email: primary.email,
|
|
1478
|
+
emailVerified: true
|
|
1479
|
+
} : void 0;
|
|
1480
|
+
}
|
|
1481
|
+
function createGitHubOAuthProviderConfig(input) {
|
|
1482
|
+
return {
|
|
1483
|
+
...input,
|
|
1484
|
+
authorizeUrl: "https://github.com/login/oauth/authorize",
|
|
1485
|
+
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
1486
|
+
userInfoUrl: "https://api.github.com/user",
|
|
1487
|
+
scopes: input.scopes ?? ["read:user", "user:email"],
|
|
1488
|
+
fetchFallbackEmail: fetchGitHubPrimaryEmail
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
function createGoogleOAuthProviderConfig(input) {
|
|
1492
|
+
return {
|
|
1493
|
+
...input,
|
|
1494
|
+
authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
1495
|
+
tokenUrl: "https://oauth2.googleapis.com/token",
|
|
1496
|
+
userInfoUrl: "https://openidconnect.googleapis.com/v1/userinfo",
|
|
1497
|
+
scopes: input.scopes ?? [
|
|
1498
|
+
"openid",
|
|
1499
|
+
"profile",
|
|
1500
|
+
"email"
|
|
1501
|
+
],
|
|
1502
|
+
emailVerifiedKey: "email_verified"
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
function createDiscordOAuthProviderConfig(input) {
|
|
1506
|
+
return {
|
|
1507
|
+
...input,
|
|
1508
|
+
authorizeUrl: "https://discord.com/api/oauth2/authorize",
|
|
1509
|
+
tokenUrl: "https://discord.com/api/oauth2/token",
|
|
1510
|
+
userInfoUrl: "https://discord.com/api/users/@me",
|
|
1511
|
+
scopes: input.scopes ?? ["identify", "email"],
|
|
1512
|
+
emailVerifiedKey: "verified"
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
function buildOAuthRedirectUrl(baseUrl, token, email) {
|
|
1516
|
+
return buildTokenUrl(baseUrl, token, email);
|
|
1517
|
+
}
|
|
1518
|
+
function parseOAuthRedirectUrl(url) {
|
|
1519
|
+
return parseTokenUrl(url);
|
|
1520
|
+
}
|
|
1521
|
+
//#endregion
|
|
1522
|
+
//#region src/auth/password/NodeHasher.ts
|
|
1523
|
+
/**
|
|
1524
|
+
* Node.js-compatible password hasher using crypto.scrypt.
|
|
1525
|
+
* Use this instead of ScryptHasher when deploying to non-Bun runtimes (e.g. AWS Lambda).
|
|
1526
|
+
*/
|
|
1527
|
+
var NodeHasher = class {
|
|
1528
|
+
options;
|
|
1529
|
+
constructor(options = {}) {
|
|
1530
|
+
this.options = {
|
|
1531
|
+
cost: options.cost,
|
|
1532
|
+
memory: options.memory,
|
|
1533
|
+
saltLength: options.saltLength,
|
|
1534
|
+
keyLength: options.keyLength
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
async hash(plain) {
|
|
1538
|
+
return hashPassword(plain, this.options);
|
|
1539
|
+
}
|
|
1540
|
+
async verify(hashed, plain) {
|
|
1541
|
+
return verifyPassword(plain, hashed);
|
|
1542
|
+
}
|
|
1543
|
+
needsRehash(hashed) {
|
|
1544
|
+
return needsRehash(hashed, this.options);
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
//#endregion
|
|
1548
|
+
//#region src/auth/AuthenticatableModel.ts
|
|
1549
|
+
var AuthenticatableModel = class extends Model {
|
|
1550
|
+
static createType = void 0;
|
|
1551
|
+
static passwordField = "password";
|
|
1552
|
+
static passwordHashField = "passwordHash";
|
|
1553
|
+
static rememberTokenField = "rememberToken";
|
|
1554
|
+
static passwordHasher = null;
|
|
1555
|
+
static resolvePasswordField() {
|
|
1556
|
+
return this.passwordField ?? "password";
|
|
1557
|
+
}
|
|
1558
|
+
static resolvePasswordHashField() {
|
|
1559
|
+
return this.passwordHashField ?? "passwordHash";
|
|
1560
|
+
}
|
|
1561
|
+
static resolveRememberTokenField() {
|
|
1562
|
+
return this.rememberTokenField ?? "rememberToken";
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Credential columns can never be mass-assigned: the resolved password-hash
|
|
1566
|
+
* column (unless the model hashes in place into the password field itself)
|
|
1567
|
+
* and the remember-token column. Resolved at call time so a renamed column
|
|
1568
|
+
* stays covered. Use `forceCreate()`/`forceUpdate()` for trusted
|
|
1569
|
+
* server-side values such as `passwordHash: 'oauth:...'`.
|
|
1570
|
+
*/
|
|
1571
|
+
static deniedFields() {
|
|
1572
|
+
const denied = [...super.deniedFields()];
|
|
1573
|
+
const hashField = this.resolvePasswordHashField();
|
|
1574
|
+
if (hashField !== this.resolvePasswordField()) denied.push(hashField);
|
|
1575
|
+
denied.push(this.resolveRememberTokenField());
|
|
1576
|
+
return denied;
|
|
1577
|
+
}
|
|
1578
|
+
static resolvePasswordHasher() {
|
|
1579
|
+
if (this.passwordHasher) return this.passwordHasher;
|
|
1580
|
+
const hasher = new ScryptHasher();
|
|
1581
|
+
this.passwordHasher = hasher;
|
|
1582
|
+
return hasher;
|
|
1583
|
+
}
|
|
1584
|
+
static async preparePersistencePayload(data) {
|
|
1585
|
+
const basePayload = await super.preparePersistencePayload(data);
|
|
1586
|
+
const passwordField = this.resolvePasswordField();
|
|
1587
|
+
if (!(passwordField in basePayload)) return basePayload;
|
|
1588
|
+
const payload = { ...basePayload };
|
|
1589
|
+
const plainPassword = payload[passwordField];
|
|
1590
|
+
const hashField = this.resolvePasswordHashField();
|
|
1591
|
+
if (typeof plainPassword === "string" && plainPassword.length > 0) payload[hashField] = await this.resolvePasswordHasher().hash(plainPassword);
|
|
1592
|
+
if (passwordField !== hashField) delete payload[passwordField];
|
|
1593
|
+
return payload;
|
|
1594
|
+
}
|
|
1595
|
+
};
|
|
1596
|
+
//#endregion
|
|
1597
|
+
//#region src/auth/password-reset.ts
|
|
1598
|
+
/**
|
|
1599
|
+
* In-memory token store for testing and development.
|
|
1600
|
+
*/
|
|
1601
|
+
var MemoryPasswordResetStore = class {
|
|
1602
|
+
tokens = /* @__PURE__ */ new Map();
|
|
1603
|
+
async store(tokenId, email, expiresAt) {
|
|
1604
|
+
this.tokens.set(tokenId, {
|
|
1605
|
+
email,
|
|
1606
|
+
expiresAt
|
|
1607
|
+
});
|
|
1608
|
+
}
|
|
1609
|
+
async find(tokenId) {
|
|
1610
|
+
const record = this.tokens.get(tokenId);
|
|
1611
|
+
if (!record) return null;
|
|
1612
|
+
if (record.expiresAt < /* @__PURE__ */ new Date()) {
|
|
1613
|
+
this.tokens.delete(tokenId);
|
|
1614
|
+
return null;
|
|
1615
|
+
}
|
|
1616
|
+
return record;
|
|
1617
|
+
}
|
|
1618
|
+
async delete(tokenId) {
|
|
1619
|
+
this.tokens.delete(tokenId);
|
|
1620
|
+
}
|
|
1621
|
+
async deleteForEmail(email) {
|
|
1622
|
+
for (const [hash, record] of this.tokens) if (record.email === email) this.tokens.delete(hash);
|
|
1623
|
+
}
|
|
1624
|
+
/** Clear all tokens (useful for testing) */
|
|
1625
|
+
clear() {
|
|
1626
|
+
this.tokens.clear();
|
|
1627
|
+
}
|
|
1628
|
+
};
|
|
1629
|
+
const DEFAULT_EXPIRES_IN = 36e5;
|
|
1630
|
+
const DEFAULT_TOKEN_LENGTH = 32;
|
|
1631
|
+
const PASSWORD_RESET_PURPOSE = "password-reset";
|
|
1632
|
+
function createPasswordResetSigner() {
|
|
1633
|
+
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "password-reset-signing"));
|
|
1634
|
+
}
|
|
1635
|
+
/**
|
|
1636
|
+
* Create a password reset token for a user.
|
|
1637
|
+
*
|
|
1638
|
+
* @param email - The user's email address
|
|
1639
|
+
* @param store - The token storage implementation
|
|
1640
|
+
* @param config - Optional configuration
|
|
1641
|
+
* @returns The token result containing plain token and hash
|
|
1642
|
+
*/
|
|
1643
|
+
async function createPasswordResetToken(email, store, config = {}) {
|
|
1644
|
+
const expiresIn = config.expiresIn ?? DEFAULT_EXPIRES_IN;
|
|
1645
|
+
const tokenLength = config.tokenLength ?? DEFAULT_TOKEN_LENGTH;
|
|
1646
|
+
await store.deleteForEmail(email);
|
|
1647
|
+
const tokenId = generateId();
|
|
1648
|
+
const expiresAt = new Date(Date.now() + expiresIn);
|
|
1649
|
+
const token = createPasswordResetSigner().sign({
|
|
1650
|
+
id: tokenId,
|
|
1651
|
+
email: email.toLowerCase(),
|
|
1652
|
+
bytes: tokenLength
|
|
1653
|
+
}, {
|
|
1654
|
+
purpose: PASSWORD_RESET_PURPOSE,
|
|
1655
|
+
expiresIn
|
|
1656
|
+
});
|
|
1657
|
+
await store.store(tokenId, email.toLowerCase(), expiresAt);
|
|
1658
|
+
return {
|
|
1659
|
+
token,
|
|
1660
|
+
tokenId,
|
|
1661
|
+
expiresAt
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Verify a password reset token.
|
|
1666
|
+
*
|
|
1667
|
+
* @param token - The plain-text token from the reset URL
|
|
1668
|
+
* @param store - The token storage implementation
|
|
1669
|
+
* @param config - Optional configuration (must match createPasswordResetToken config)
|
|
1670
|
+
* @returns The email if token is valid, null otherwise
|
|
1671
|
+
*/
|
|
1672
|
+
async function verifyPasswordResetToken(token, store, _config = {}) {
|
|
1673
|
+
const payload = createPasswordResetSigner().verify(token, {
|
|
1674
|
+
purpose: PASSWORD_RESET_PURPOSE,
|
|
1675
|
+
allowExpired: true
|
|
1676
|
+
});
|
|
1677
|
+
if (!payload?.id || !payload.email) return null;
|
|
1678
|
+
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1679
|
+
await store.delete(payload.id);
|
|
1680
|
+
return null;
|
|
1681
|
+
}
|
|
1682
|
+
const record = await store.find(payload.id);
|
|
1683
|
+
if (!record) return null;
|
|
1684
|
+
return record.email.toLowerCase() === payload.email.toLowerCase() ? record.email : null;
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Complete a password reset by updating the user's password and invalidating the token.
|
|
1688
|
+
*
|
|
1689
|
+
* @param token - The plain-text token from the reset URL
|
|
1690
|
+
* @param newPassword - The new password (should be validated by caller)
|
|
1691
|
+
* @param store - The token storage implementation
|
|
1692
|
+
* @param provider - The user provider to look up and update the user
|
|
1693
|
+
* @param updatePassword - Function to update the user's password
|
|
1694
|
+
* @param config - Optional configuration
|
|
1695
|
+
* @returns The user if reset was successful, null if token is invalid
|
|
1696
|
+
*/
|
|
1697
|
+
async function completePasswordReset(token, newPassword, store, provider, updatePassword, _config = {}) {
|
|
1698
|
+
const payload = createPasswordResetSigner().verify(token, {
|
|
1699
|
+
purpose: PASSWORD_RESET_PURPOSE,
|
|
1700
|
+
allowExpired: true
|
|
1701
|
+
});
|
|
1702
|
+
if (!payload?.id || !payload.email) return null;
|
|
1703
|
+
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1704
|
+
await store.delete(payload.id);
|
|
1705
|
+
return null;
|
|
1706
|
+
}
|
|
1707
|
+
const record = await store.find(payload.id);
|
|
1708
|
+
if (!record) return null;
|
|
1709
|
+
if (record.email.toLowerCase() !== payload.email.toLowerCase()) return null;
|
|
1710
|
+
const user = await provider.retrieveByCredentials({ email: record.email });
|
|
1711
|
+
if (!user) {
|
|
1712
|
+
await store.delete(payload.id);
|
|
1713
|
+
return null;
|
|
1714
|
+
}
|
|
1715
|
+
await updatePassword(user, newPassword);
|
|
1716
|
+
await store.delete(payload.id);
|
|
1717
|
+
return user;
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Build a password reset URL from a base URL and token.
|
|
1721
|
+
*/
|
|
1722
|
+
const buildPasswordResetUrl = buildTokenUrl;
|
|
1723
|
+
/**
|
|
1724
|
+
* Parse a password reset URL to extract the token and optional email.
|
|
1725
|
+
*/
|
|
1726
|
+
const parsePasswordResetUrl = parseTokenUrl;
|
|
1727
|
+
//#endregion
|
|
1728
|
+
//#region src/auth/email-verification.ts
|
|
1729
|
+
/**
|
|
1730
|
+
* In-memory store for testing purposes.
|
|
1731
|
+
* Do NOT use in production - tokens will be lost on restart.
|
|
1732
|
+
*/
|
|
1733
|
+
var MemoryEmailVerificationStore = class {
|
|
1734
|
+
tokens = /* @__PURE__ */ new Map();
|
|
1735
|
+
async store(token) {
|
|
1736
|
+
this.tokens.set(token.tokenId, token);
|
|
1737
|
+
}
|
|
1738
|
+
async findByTokenId(tokenId) {
|
|
1739
|
+
return this.tokens.get(tokenId) ?? null;
|
|
1740
|
+
}
|
|
1741
|
+
async delete(tokenId) {
|
|
1742
|
+
this.tokens.delete(tokenId);
|
|
1743
|
+
}
|
|
1744
|
+
async deleteForEmail(email) {
|
|
1745
|
+
const normalizedEmail = email.toLowerCase();
|
|
1746
|
+
for (const [key, token] of this.tokens.entries()) if (token.email.toLowerCase() === normalizedEmail) this.tokens.delete(key);
|
|
1747
|
+
}
|
|
1748
|
+
/**
|
|
1749
|
+
* Clear all tokens (useful for testing).
|
|
1750
|
+
*/
|
|
1751
|
+
clear() {
|
|
1752
|
+
this.tokens.clear();
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Get the count of stored tokens (useful for testing).
|
|
1756
|
+
*/
|
|
1757
|
+
get size() {
|
|
1758
|
+
return this.tokens.size;
|
|
1759
|
+
}
|
|
1760
|
+
};
|
|
1761
|
+
const DEFAULT_CONFIG = {
|
|
1762
|
+
expiresIn: 864e5,
|
|
1763
|
+
tokenLength: 32
|
|
1764
|
+
};
|
|
1765
|
+
const EMAIL_VERIFICATION_PURPOSE = "email-verification";
|
|
1766
|
+
function createEmailVerificationSigner() {
|
|
1767
|
+
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "email-verification-signing"));
|
|
1768
|
+
}
|
|
1769
|
+
/**
|
|
1770
|
+
* Create a new email verification token.
|
|
1771
|
+
*
|
|
1772
|
+
* @param email - The email address to verify
|
|
1773
|
+
* @param store - Token store implementation
|
|
1774
|
+
* @param config - Optional configuration
|
|
1775
|
+
* @returns The raw token to send via email
|
|
1776
|
+
*
|
|
1777
|
+
* @example
|
|
1778
|
+
* ```ts
|
|
1779
|
+
* const { token, expiresAt } = await createEmailVerificationToken(
|
|
1780
|
+
* user.email,
|
|
1781
|
+
* verificationStore
|
|
1782
|
+
* )
|
|
1783
|
+
*
|
|
1784
|
+
* // Send email with verification link
|
|
1785
|
+
* await sendEmail({
|
|
1786
|
+
* to: user.email,
|
|
1787
|
+
* subject: 'Verify your email',
|
|
1788
|
+
* html: `<a href="${buildVerificationUrl(baseUrl, token)}">Verify Email</a>`,
|
|
1789
|
+
* })
|
|
1790
|
+
* ```
|
|
1791
|
+
*/
|
|
1792
|
+
async function createEmailVerificationToken(email, store, config = {}) {
|
|
1793
|
+
const { expiresIn, tokenLength } = {
|
|
1794
|
+
...DEFAULT_CONFIG,
|
|
1795
|
+
...config
|
|
1796
|
+
};
|
|
1797
|
+
await store.deleteForEmail(email);
|
|
1798
|
+
const tokenId = generateId();
|
|
1799
|
+
const now = /* @__PURE__ */ new Date();
|
|
1800
|
+
const expiresAt = new Date(now.getTime() + expiresIn);
|
|
1801
|
+
const token = createEmailVerificationSigner().sign({
|
|
1802
|
+
id: tokenId,
|
|
1803
|
+
email: email.toLowerCase(),
|
|
1804
|
+
bytes: tokenLength
|
|
1805
|
+
}, {
|
|
1806
|
+
purpose: EMAIL_VERIFICATION_PURPOSE,
|
|
1807
|
+
expiresIn
|
|
1808
|
+
});
|
|
1809
|
+
await store.store({
|
|
1810
|
+
email: email.toLowerCase(),
|
|
1811
|
+
tokenId,
|
|
1812
|
+
expiresAt,
|
|
1813
|
+
createdAt: now
|
|
1814
|
+
});
|
|
1815
|
+
return {
|
|
1816
|
+
token,
|
|
1817
|
+
expiresAt
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
/**
|
|
1821
|
+
* Verify an email verification token.
|
|
1822
|
+
*
|
|
1823
|
+
* @param token - The raw token from the verification link
|
|
1824
|
+
* @param store - Token store implementation
|
|
1825
|
+
* @param config - Optional configuration (not currently used, reserved for future)
|
|
1826
|
+
* @returns The email address if valid, null if invalid or expired
|
|
1827
|
+
*
|
|
1828
|
+
* @example
|
|
1829
|
+
* ```ts
|
|
1830
|
+
* const email = await verifyEmailToken(token, verificationStore)
|
|
1831
|
+
*
|
|
1832
|
+
* if (!email) {
|
|
1833
|
+
* return ctx.json({ error: 'Invalid or expired token' }, 400)
|
|
1834
|
+
* }
|
|
1835
|
+
*
|
|
1836
|
+
* // Mark user as verified
|
|
1837
|
+
* await User.update({ email }, { emailVerifiedAt: new Date() })
|
|
1838
|
+
* ```
|
|
1839
|
+
*/
|
|
1840
|
+
async function verifyEmailToken(token, store, _config = {}) {
|
|
1841
|
+
const payload = createEmailVerificationSigner().verify(token, {
|
|
1842
|
+
purpose: EMAIL_VERIFICATION_PURPOSE,
|
|
1843
|
+
allowExpired: true
|
|
1844
|
+
});
|
|
1845
|
+
if (!payload?.id || !payload.email) return null;
|
|
1846
|
+
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1847
|
+
await store.delete(payload.id);
|
|
1848
|
+
return null;
|
|
1849
|
+
}
|
|
1850
|
+
const storedToken = await store.findByTokenId(payload.id);
|
|
1851
|
+
if (!storedToken) return null;
|
|
1852
|
+
if (/* @__PURE__ */ new Date() > storedToken.expiresAt) {
|
|
1853
|
+
await store.delete(payload.id);
|
|
1854
|
+
return null;
|
|
1855
|
+
}
|
|
1856
|
+
return storedToken.email.toLowerCase() === payload.email.toLowerCase() ? storedToken.email : null;
|
|
1857
|
+
}
|
|
1858
|
+
/**
|
|
1859
|
+
* Complete email verification by consuming the token.
|
|
1860
|
+
*
|
|
1861
|
+
* @param token - The raw token from the verification link
|
|
1862
|
+
* @param store - Token store implementation
|
|
1863
|
+
* @param markVerified - Function to mark the user as verified
|
|
1864
|
+
* @returns The result of markVerified if successful, null if token invalid
|
|
1865
|
+
*
|
|
1866
|
+
* @example
|
|
1867
|
+
* ```ts
|
|
1868
|
+
* const result = await completeEmailVerification(
|
|
1869
|
+
* token,
|
|
1870
|
+
* verificationStore,
|
|
1871
|
+
* async (email) => {
|
|
1872
|
+
* await User.update({ email }, { emailVerifiedAt: new Date() })
|
|
1873
|
+
* return User.findByEmail(email)
|
|
1874
|
+
* }
|
|
1875
|
+
* )
|
|
1876
|
+
*
|
|
1877
|
+
* if (!result) {
|
|
1878
|
+
* return ctx.json({ error: 'Invalid or expired token' }, 400)
|
|
1879
|
+
* }
|
|
1880
|
+
*
|
|
1881
|
+
* return ctx.redirect('/dashboard')
|
|
1882
|
+
* ```
|
|
1883
|
+
*/
|
|
1884
|
+
async function completeEmailVerification(token, store, markVerified) {
|
|
1885
|
+
const payload = createEmailVerificationSigner().verify(token, {
|
|
1886
|
+
purpose: EMAIL_VERIFICATION_PURPOSE,
|
|
1887
|
+
allowExpired: true
|
|
1888
|
+
});
|
|
1889
|
+
if (!payload?.id || !payload.email) return null;
|
|
1890
|
+
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1891
|
+
await store.delete(payload.id);
|
|
1892
|
+
return null;
|
|
1893
|
+
}
|
|
1894
|
+
const storedToken = await store.findByTokenId(payload.id);
|
|
1895
|
+
if (!storedToken) return null;
|
|
1896
|
+
if (/* @__PURE__ */ new Date() > storedToken.expiresAt) {
|
|
1897
|
+
await store.delete(payload.id);
|
|
1898
|
+
return null;
|
|
1899
|
+
}
|
|
1900
|
+
if (storedToken.email.toLowerCase() !== payload.email.toLowerCase()) return null;
|
|
1901
|
+
const result = await markVerified(storedToken.email);
|
|
1902
|
+
await store.delete(payload.id);
|
|
1903
|
+
return result;
|
|
1904
|
+
}
|
|
1905
|
+
/**
|
|
1906
|
+
* Build a verification URL.
|
|
1907
|
+
*/
|
|
1908
|
+
const buildVerificationUrl = buildTokenUrl;
|
|
1909
|
+
/**
|
|
1910
|
+
* Parse a verification URL to extract token and email.
|
|
1911
|
+
*/
|
|
1912
|
+
const parseVerificationUrl = parseTokenUrl;
|
|
1913
|
+
/**
|
|
1914
|
+
* Check if a user's email is verified.
|
|
1915
|
+
* Helper function for use with User models.
|
|
1916
|
+
*
|
|
1917
|
+
* @param user - User object with emailVerifiedAt field
|
|
1918
|
+
* @returns true if verified, false otherwise
|
|
1919
|
+
*
|
|
1920
|
+
* @example
|
|
1921
|
+
* ```ts
|
|
1922
|
+
* if (!isEmailVerified(user)) {
|
|
1923
|
+
* return ctx.redirect('/verify-email')
|
|
1924
|
+
* }
|
|
1925
|
+
* ```
|
|
1926
|
+
*/
|
|
1927
|
+
function isEmailVerified(user) {
|
|
1928
|
+
return user?.emailVerifiedAt != null;
|
|
1929
|
+
}
|
|
1930
|
+
/**
|
|
1931
|
+
* Middleware factory to require verified email.
|
|
1932
|
+
*
|
|
1933
|
+
* @param options - Configuration options
|
|
1934
|
+
* @returns Middleware function
|
|
1935
|
+
*
|
|
1936
|
+
* @example
|
|
1937
|
+
* ```ts
|
|
1938
|
+
* router.get('/dashboard', [DashboardController, 'index'],
|
|
1939
|
+
* requireAuthenticated(),
|
|
1940
|
+
* requireVerifiedEmail({ redirectTo: '/verify-email' })
|
|
1941
|
+
* )
|
|
1942
|
+
* ```
|
|
1943
|
+
*/
|
|
1944
|
+
function requireVerifiedEmail(options = {}) {
|
|
1945
|
+
const { redirectTo = "/verify-email" } = options;
|
|
1946
|
+
return async (ctx, next) => {
|
|
1947
|
+
if (!isEmailVerified(await (options.getUser ?? (async (c) => {
|
|
1948
|
+
return c.get("guren:auth")?.user?.() ?? null;
|
|
1949
|
+
}))(ctx))) return ctx.redirect(redirectTo);
|
|
1950
|
+
await next();
|
|
1951
|
+
};
|
|
1952
|
+
}
|
|
1953
|
+
//#endregion
|
|
1954
|
+
export { generateToken as $, sanitizeOAuthRedirect as A, revokeAllApiTokens as B, createGitHubOAuthProviderConfig as C, exchangeOAuthCode as D, createOAuthState as E, createBearerTokenMiddleware as F, verifyApiToken as G, tokenCan as H, getApiToken as I, normalizeRedirectTarget as J, hostMatchesAllowlist as K, getApiTokenOrFail as L, API_TOKEN_KEY as M, MemoryApiTokenStore as N, fetchOAuthUserProfile as O, createApiToken as P, generateId as Q, getUserApiTokens as R, createDiscordOAuthProviderConfig as S, createOAuthManager as T, tokenCanAll as U, revokeApiToken as V, tokenCanAny as W, SessionGuard as X, AuthManager as Y, buildTokenUrl as Z, MemoryOAuthStateStore as _, isEmailVerified as a, BaseUserProvider as at, buildOAuthAuthorizeUrl as b, verifyEmailToken as c, MemorySessionStore as ct, completePasswordReset as d, hashToken as et, createPasswordResetToken as f, NodeHasher as g, AuthenticatableModel as h, createEmailVerificationToken as i, ModelUserProvider as it, verifyOAuthState as j, parseOAuthRedirectUrl as k, MemoryPasswordResetStore as l, createSessionMiddleware as lt, verifyPasswordResetToken as m, buildVerificationUrl as n, secureCompare as nt, parseVerificationUrl as o, ScryptHasher as ot, parsePasswordResetUrl as p, isAppRelativePath as q, completeEmailVerification as r, secureStringCompare as rt, requireVerifiedEmail as s, AuthenticationException as st, MemoryEmailVerificationStore as t, parseTokenUrl as tt, buildPasswordResetUrl as u, getSessionFromContext as ut, OAUTH_SESSION_BINDING_KEY as v, createGoogleOAuthProviderConfig as w, buildOAuthRedirectUrl as x, OAuthManager as y, parseApiToken as z };
|