@guren/server 2.18.0 → 2.20.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/{Job-DxQK8h3P.js → Job-CvDwk2Gj.js} +14 -6
- package/dist/Logger-DFifRAtc.js +114 -0
- package/dist/auth/index.js +1 -1
- package/dist/{auth-Gg54ppQi.js → auth-BXcHQwHf.js} +123 -40
- package/dist/cache/index.js +1 -1
- package/dist/cache/types.d.ts +5 -1
- package/dist/{cache-BOOIr324.js → cache-DUhlolkJ.js} +18 -3
- package/dist/client-C5Wj9P9o.js +70 -0
- package/dist/console/Command.d.ts +2 -0
- package/dist/container/Container.d.ts +9 -0
- package/dist/container/bindings.d.ts +3 -0
- package/dist/http/Application.d.ts +2 -0
- package/dist/http/middleware/cookie-session-store.d.ts +38 -0
- package/dist/http/middleware/index.d.ts +6 -0
- package/dist/http/middleware/session-manager.d.ts +86 -0
- package/dist/http/middleware/session.d.ts +40 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +236 -23
- package/dist/lambda/index.js +6 -5
- package/dist/logging/index.js +2 -1
- package/dist/{logging-zOY1XCtq.js → logging-DXmqqUl4.js} +2 -114
- package/dist/mail/index.js +1 -1
- package/dist/{mail-76DWy9lj.js → mail-9CrvJyBZ.js} +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/{notifications-okWFs9ly.js → notifications-D0VXkFLF.js} +1 -1
- package/dist/providers/AuthServiceProvider.d.ts +18 -1
- package/dist/queue/index.js +2 -2
- package/dist/{queue-CcXCjuJI.js → queue-zPPYZdif.js} +1 -1
- package/dist/redis/index.js +1 -62
- package/dist/redis/lazy-client.d.ts +8 -0
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/serverless.d.ts +15 -0
- package/dist/serverless-D96rJb6x.js +22 -0
- package/dist/{vite-manifest-DhbXfFct.js → vite-manifest-BZQ-75hf.js} +2 -2
- package/package.json +2 -2
- package/dist/client-C4TEr_Dd.js +0 -9
|
@@ -47,12 +47,7 @@ var Container = class Container {
|
|
|
47
47
|
if (this.fakes.has(key)) return this.fakes.get(key);
|
|
48
48
|
const resolvedKey = this.resolveAlias(key);
|
|
49
49
|
if (resolvedKey !== key && this.fakes.has(resolvedKey)) return this.fakes.get(resolvedKey);
|
|
50
|
-
|
|
51
|
-
if (!binding && this.deferredProviderLoader) {
|
|
52
|
-
const loading = this.deferredProviderLoader(resolvedKey);
|
|
53
|
-
binding = this.bindings.get(resolvedKey);
|
|
54
|
-
if (loading && !binding) throw new Error(`Deferred provider for "${key}" did not bind "${resolvedKey}" synchronously in register(). Container.make() cannot await an async register(); bind the service synchronously, or await ProviderManager.loadDeferredProvider() before resolving it.`);
|
|
55
|
-
}
|
|
50
|
+
const binding = this.bindings.get(resolvedKey) ?? this.loadDeferred(key, resolvedKey);
|
|
56
51
|
if (!binding) throw new Error(`Service "${key}" not found in container`);
|
|
57
52
|
if (binding.singleton && binding.instance !== void 0) return binding.instance;
|
|
58
53
|
if (this.scopedInstances.length > 0) {
|
|
@@ -83,6 +78,19 @@ var Container = class Container {
|
|
|
83
78
|
const resolvedKey = this.resolveAlias(key);
|
|
84
79
|
return this.bindings.has(resolvedKey);
|
|
85
80
|
}
|
|
81
|
+
makeOptional(key) {
|
|
82
|
+
const resolvedKey = this.resolveAlias(key);
|
|
83
|
+
if (this.fakes.has(key) || this.fakes.has(resolvedKey)) return this.make(key);
|
|
84
|
+
return this.bindings.get(resolvedKey) ?? this.loadDeferred(key, resolvedKey) ? this.make(key) : void 0;
|
|
85
|
+
}
|
|
86
|
+
/** The binding a deferred provider makes for `resolvedKey`, once its register() has run; undefined when none provides it. */
|
|
87
|
+
loadDeferred(key, resolvedKey) {
|
|
88
|
+
if (!this.deferredProviderLoader) return;
|
|
89
|
+
const loading = this.deferredProviderLoader(resolvedKey);
|
|
90
|
+
const binding = this.bindings.get(resolvedKey);
|
|
91
|
+
if (loading && !binding) throw new Error(`Deferred provider for "${key}" did not bind "${resolvedKey}" synchronously in register(). Container.make() cannot await an async register(); bind the service synchronously, or await ProviderManager.loadDeferredProvider() before resolving it.`);
|
|
92
|
+
return binding;
|
|
93
|
+
}
|
|
86
94
|
alias(alias, key) {
|
|
87
95
|
if (alias === key) throw new Error("Alias cannot be the same as the key");
|
|
88
96
|
this.aliases.set(alias, key);
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
//#region src/logging/Logger.ts
|
|
2
|
+
const DEFAULT_FILTER_KEYS = [
|
|
3
|
+
"password",
|
|
4
|
+
"password_confirmation",
|
|
5
|
+
"token",
|
|
6
|
+
"secret",
|
|
7
|
+
"credit_card",
|
|
8
|
+
"creditCard",
|
|
9
|
+
"card_number",
|
|
10
|
+
"cardNumber",
|
|
11
|
+
"cvv",
|
|
12
|
+
"ssn",
|
|
13
|
+
"authorization"
|
|
14
|
+
];
|
|
15
|
+
/** Recursively replace values of sensitive keys in a log context object. */
|
|
16
|
+
function filterSensitiveData(data, filterKeys, replacement = "[FILTERED]") {
|
|
17
|
+
if (filterKeys.length === 0) return data;
|
|
18
|
+
return filterObject(data, new Set(filterKeys.map((k) => k.toLowerCase())), replacement);
|
|
19
|
+
}
|
|
20
|
+
function filterObject(obj, keySet, replacement) {
|
|
21
|
+
const result = {};
|
|
22
|
+
for (const [key, value] of Object.entries(obj)) if (keySet.has(key.toLowerCase())) result[key] = replacement;
|
|
23
|
+
else if (value !== null && typeof value === "object" && !Array.isArray(value)) result[key] = filterObject(value, keySet, replacement);
|
|
24
|
+
else if (Array.isArray(value)) result[key] = value.map((item) => item !== null && typeof item === "object" && !Array.isArray(item) ? filterObject(item, keySet, replacement) : item);
|
|
25
|
+
else result[key] = value;
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
const reportLoggingError = (error) => {
|
|
29
|
+
console.error("Logging error:", error);
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Whether a channel's `log()` handed back something to wait on. A duck-typed
|
|
33
|
+
* check rather than `instanceof Promise`: a promise created in another realm
|
|
34
|
+
* (a `node:vm` context, a worker's module graph) satisfies the channel
|
|
35
|
+
* contract and would otherwise slip past the reporter as an unhandled rejection.
|
|
36
|
+
*/
|
|
37
|
+
function isPromiseLike(value) {
|
|
38
|
+
return typeof value === "object" && value !== null && typeof value.then === "function";
|
|
39
|
+
}
|
|
40
|
+
/** Logger instance for writing log entries. */
|
|
41
|
+
var Logger = class Logger {
|
|
42
|
+
channels;
|
|
43
|
+
baseContext;
|
|
44
|
+
filterKeys;
|
|
45
|
+
replacement;
|
|
46
|
+
constructor(channels, context = {}, options = {}) {
|
|
47
|
+
this.channels = channels;
|
|
48
|
+
this.baseContext = context;
|
|
49
|
+
this.filterKeys = options.filterKeys ?? DEFAULT_FILTER_KEYS;
|
|
50
|
+
this.replacement = options.replacement ?? "[FILTERED]";
|
|
51
|
+
}
|
|
52
|
+
emergency(message, context = {}) {
|
|
53
|
+
this.log("emergency", message, context);
|
|
54
|
+
}
|
|
55
|
+
alert(message, context = {}) {
|
|
56
|
+
this.log("alert", message, context);
|
|
57
|
+
}
|
|
58
|
+
critical(message, context = {}) {
|
|
59
|
+
this.log("critical", message, context);
|
|
60
|
+
}
|
|
61
|
+
error(message, context = {}) {
|
|
62
|
+
this.log("error", message, context);
|
|
63
|
+
}
|
|
64
|
+
warning(message, context = {}) {
|
|
65
|
+
this.log("warning", message, context);
|
|
66
|
+
}
|
|
67
|
+
warn(message, context = {}) {
|
|
68
|
+
this.warning(message, context);
|
|
69
|
+
}
|
|
70
|
+
notice(message, context = {}) {
|
|
71
|
+
this.log("notice", message, context);
|
|
72
|
+
}
|
|
73
|
+
info(message, context = {}) {
|
|
74
|
+
this.log("info", message, context);
|
|
75
|
+
}
|
|
76
|
+
debug(message, context = {}) {
|
|
77
|
+
this.log("debug", message, context);
|
|
78
|
+
}
|
|
79
|
+
log(level, message, context = {}) {
|
|
80
|
+
const merged = {
|
|
81
|
+
...this.baseContext,
|
|
82
|
+
...context
|
|
83
|
+
};
|
|
84
|
+
const entry = {
|
|
85
|
+
level,
|
|
86
|
+
message,
|
|
87
|
+
context: this.filterKeys.length > 0 ? filterSensitiveData(merged, this.filterKeys, this.replacement) : merged,
|
|
88
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
89
|
+
};
|
|
90
|
+
for (const channel of this.channels) try {
|
|
91
|
+
const pending = channel.log(entry);
|
|
92
|
+
if (isPromiseLike(pending)) Promise.resolve(pending).catch(reportLoggingError);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
reportLoggingError(error);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
withContext(context) {
|
|
98
|
+
return new Logger(this.channels, {
|
|
99
|
+
...this.baseContext,
|
|
100
|
+
...context
|
|
101
|
+
}, {
|
|
102
|
+
filterKeys: this.filterKeys,
|
|
103
|
+
replacement: this.replacement
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
child(context) {
|
|
107
|
+
return this.withContext(context);
|
|
108
|
+
}
|
|
109
|
+
async close() {
|
|
110
|
+
for (const channel of this.channels) if (channel.close) await channel.close();
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
//#endregion
|
|
114
|
+
export { filterSensitiveData as n, isPromiseLike as r, Logger as t };
|
package/dist/auth/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as buildTokenUrl, A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-
|
|
1
|
+
import { $ as buildTokenUrl, A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-BXcHQwHf.js";
|
|
2
2
|
export { API_TOKEN_KEY, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, ScryptHasher, SessionGuard, TokenGuard, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildTokenUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createApiToken, createBearerTokenMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createOAuthManager, createOAuthState, createPasswordResetToken, exchangeOAuthCode, fetchOAuthUserProfile, generateId, generateToken, getApiToken, getApiTokenOrFail, getUserApiTokens, hashToken, isEmailVerified, parseApiToken, parseOAuthRedirectUrl, parsePasswordResetUrl, parseTokenUrl, parseVerificationUrl, readBearerToken, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
|
|
2
2
|
import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
|
|
3
|
+
import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
|
|
3
4
|
import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
|
|
4
5
|
import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
|
|
5
6
|
import { n as getAuthContext } from "./context-CXk_umpT.js";
|
|
@@ -40,7 +41,17 @@ var MemorySessionStore = class {
|
|
|
40
41
|
};
|
|
41
42
|
const DEFAULT_COOKIE_NAME = "guren.session";
|
|
42
43
|
const DEFAULT_TTL_SECONDS = 7200;
|
|
43
|
-
|
|
44
|
+
/** What browsers keep per cookie; a larger one is dropped, which reads as a logout. */
|
|
45
|
+
const DEFAULT_MAX_COOKIE_BYTES = 4096;
|
|
46
|
+
/**
|
|
47
|
+
* Read when a middleware is built, not when this module loads: an app that
|
|
48
|
+
* sets NODE_ENV after importing the framework (tests, some serverless
|
|
49
|
+
* bootstraps) must still get a Secure cookie. Spelled `process.env.NODE_ENV`
|
|
50
|
+
* exactly, so the deploy plugins' `--define` settles it at bundle time.
|
|
51
|
+
*/
|
|
52
|
+
function defaultCookieSecure() {
|
|
53
|
+
return typeof process !== "undefined" ? process.env.NODE_ENV === "production" : true;
|
|
54
|
+
}
|
|
44
55
|
const SESSION_CONTEXT_KEY = "guren:session";
|
|
45
56
|
var SessionImpl = class {
|
|
46
57
|
isNew;
|
|
@@ -217,14 +228,89 @@ function createCookieSigner(cookieName, cookiePath) {
|
|
|
217
228
|
verify
|
|
218
229
|
};
|
|
219
230
|
}
|
|
231
|
+
/**
|
|
232
|
+
* The static checks can be skipped; this runs in the deploy log of exactly the
|
|
233
|
+
* app they would have warned about (RFC 0020 §1). Decided once per middleware,
|
|
234
|
+
* on its first request. `vercel dev` is one process, so there the warning
|
|
235
|
+
* would be noise; `sam local` starts a container per invocation by default,
|
|
236
|
+
* so there it is true.
|
|
237
|
+
*/
|
|
238
|
+
function warnAboutMemoryStore(store) {
|
|
239
|
+
if (!(store instanceof MemorySessionStore)) return;
|
|
240
|
+
const runtime = detectServerlessRuntime();
|
|
241
|
+
if (!runtime || runtime.emulator === "vercel-dev") return;
|
|
242
|
+
console.warn(`[guren] Sessions use MemorySessionStore on ${SERVERLESS_RUNTIME_LABELS[runtime.id]}, which shares no memory between requests, so a login is lost on the very next request. Configure a persistent store: DatabaseSessionStore from @guren/core, or a SessionManager whose default store is database- or Redis-backed.`);
|
|
243
|
+
}
|
|
244
|
+
function keyedTransport(store, signer, ttlSeconds) {
|
|
245
|
+
return {
|
|
246
|
+
async load(cookieValue) {
|
|
247
|
+
const id = signer.verify(cookieValue);
|
|
248
|
+
return id === null ? null : {
|
|
249
|
+
id,
|
|
250
|
+
data: await store.read(id) ?? {}
|
|
251
|
+
};
|
|
252
|
+
},
|
|
253
|
+
async refresh(id, session) {
|
|
254
|
+
if (store.touch) await store.touch(id, ttlSeconds);
|
|
255
|
+
else await store.write(id, session.snapshot(), ttlSeconds);
|
|
256
|
+
return signer.sign(id);
|
|
257
|
+
},
|
|
258
|
+
async persist(id, data, { regeneratedFrom }) {
|
|
259
|
+
await store.write(id, data, ttlSeconds);
|
|
260
|
+
if (regeneratedFrom !== null && regeneratedFrom !== id) await store.destroy(regeneratedFrom);
|
|
261
|
+
return signer.sign(id);
|
|
262
|
+
},
|
|
263
|
+
async discard(id) {
|
|
264
|
+
await store.destroy(id);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
function inlineTransport(codec, ttlSeconds) {
|
|
269
|
+
return {
|
|
270
|
+
async load(cookieValue) {
|
|
271
|
+
return codec.decode(cookieValue);
|
|
272
|
+
},
|
|
273
|
+
async refresh(id, session) {
|
|
274
|
+
return codec.encode(id, session.snapshot(), ttlSeconds);
|
|
275
|
+
},
|
|
276
|
+
async persist(id, data) {
|
|
277
|
+
return codec.encode(id, data, ttlSeconds);
|
|
278
|
+
},
|
|
279
|
+
async discard() {}
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* What the `Set-Cookie` header will cost, name and attributes included. The
|
|
284
|
+
* browser limit applies to the whole thing, so measuring only the value is how
|
|
285
|
+
* a session passes its own check and is then dropped without a word.
|
|
286
|
+
*/
|
|
287
|
+
function assembledCookieBytes(name, value, options, maxAge) {
|
|
288
|
+
const attributes = [
|
|
289
|
+
options.path ? `; Path=${options.path}` : "",
|
|
290
|
+
options.domain ? `; Domain=${options.domain}` : "",
|
|
291
|
+
`; Max-Age=${maxAge}`,
|
|
292
|
+
options.httpOnly ? "; HttpOnly" : "",
|
|
293
|
+
options.secure ? "; Secure" : "",
|
|
294
|
+
options.sameSite ? `; SameSite=${options.sameSite}` : ""
|
|
295
|
+
].join("");
|
|
296
|
+
return Buffer.byteLength(`${name}=${encodeURIComponent(value)}${attributes}`, "utf8");
|
|
297
|
+
}
|
|
220
298
|
function createSessionMiddleware(options = {}) {
|
|
221
|
-
const { cookieName = DEFAULT_COOKIE_NAME, cookiePath = "/", cookieDomain, cookieSecure =
|
|
299
|
+
const { cookieName = DEFAULT_COOKIE_NAME, cookiePath = "/", cookieDomain, cookieSecure = defaultCookieSecure(), cookieSameSite = "Lax", cookieHttpOnly = true, cookieMaxAgeSeconds, ttlSeconds = DEFAULT_TTL_SECONDS, maxCookieBytes = DEFAULT_MAX_COOKIE_BYTES, store: storeOrFactory = new MemorySessionStore() } = options;
|
|
222
300
|
const signer = createCookieSigner(cookieName, cookiePath);
|
|
301
|
+
let checkedStore = false;
|
|
223
302
|
return async (ctx, next) => {
|
|
224
|
-
const
|
|
303
|
+
const store = typeof storeOrFactory === "function" ? storeOrFactory() : storeOrFactory;
|
|
304
|
+
if (!checkedStore) {
|
|
305
|
+
checkedStore = true;
|
|
306
|
+
warnAboutMemoryStore(store);
|
|
307
|
+
}
|
|
308
|
+
const transport = store.inline ? inlineTransport(store.inline, ttlSeconds) : keyedTransport(store, signer, ttlSeconds);
|
|
309
|
+
const loaded = await transport.load(getCookie(ctx, cookieName));
|
|
310
|
+
const existingId = loaded?.id ?? null;
|
|
225
311
|
const sessionId = existingId ?? globalThis.crypto.randomUUID();
|
|
226
312
|
const isNew = !existingId;
|
|
227
|
-
const storedData =
|
|
313
|
+
const storedData = loaded?.data ?? {};
|
|
228
314
|
const testingData = resolveTestingSession(ctx);
|
|
229
315
|
const session = new SessionImpl(sessionId, testingData ? {
|
|
230
316
|
...storedData,
|
|
@@ -232,45 +318,42 @@ function createSessionMiddleware(options = {}) {
|
|
|
232
318
|
} : storedData, isNew);
|
|
233
319
|
session.ageFlashData();
|
|
234
320
|
ctx.set(SESSION_CONTEXT_KEY, session);
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
321
|
+
await next();
|
|
322
|
+
const cookieOptions = {
|
|
323
|
+
path: cookiePath,
|
|
324
|
+
domain: cookieDomain,
|
|
325
|
+
secure: cookieSecure,
|
|
326
|
+
sameSite: cookieSameSite,
|
|
327
|
+
httpOnly: cookieHttpOnly
|
|
328
|
+
};
|
|
329
|
+
const persistSession = async () => {
|
|
238
330
|
if (session.wasDestroyed()) {
|
|
239
|
-
await
|
|
240
|
-
deleteCookie(ctx, cookieName,
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
});
|
|
247
|
-
} else if (!session.shouldPersist()) {
|
|
248
|
-
if (existingId) {
|
|
249
|
-
if (store.touch) await store.touch(existingId, ttlSeconds);
|
|
250
|
-
else await store.write(existingId, session.snapshot(), ttlSeconds);
|
|
251
|
-
setCookie(ctx, cookieName, signer.sign(existingId), {
|
|
252
|
-
path: cookiePath,
|
|
253
|
-
domain: cookieDomain,
|
|
254
|
-
secure: cookieSecure,
|
|
255
|
-
sameSite: cookieSameSite,
|
|
256
|
-
httpOnly: cookieHttpOnly,
|
|
257
|
-
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
|
-
} else {
|
|
261
|
-
const nextId = session.id;
|
|
262
|
-
await store.write(nextId, session.snapshot(), ttlSeconds);
|
|
263
|
-
if (session.wasRegenerated() && session.originalSessionId() !== nextId) await store.destroy(session.originalSessionId());
|
|
264
|
-
setCookie(ctx, cookieName, signer.sign(nextId), {
|
|
265
|
-
path: cookiePath,
|
|
266
|
-
domain: cookieDomain,
|
|
267
|
-
secure: cookieSecure,
|
|
268
|
-
sameSite: cookieSameSite,
|
|
269
|
-
httpOnly: cookieHttpOnly,
|
|
331
|
+
await transport.discard(session.originalSessionId());
|
|
332
|
+
deleteCookie(ctx, cookieName, cookieOptions);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (!session.shouldPersist()) {
|
|
336
|
+
if (existingId) setCookie(ctx, cookieName, await write(transport.refresh(existingId, session)), {
|
|
337
|
+
...cookieOptions,
|
|
270
338
|
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
271
339
|
});
|
|
340
|
+
return;
|
|
272
341
|
}
|
|
273
|
-
|
|
342
|
+
const nextId = session.id;
|
|
343
|
+
const value = await transport.persist(nextId, session.snapshot(), { regeneratedFrom: session.wasRegenerated() ? session.originalSessionId() : null });
|
|
344
|
+
setCookie(ctx, cookieName, await write(value), {
|
|
345
|
+
...cookieOptions,
|
|
346
|
+
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
347
|
+
});
|
|
348
|
+
};
|
|
349
|
+
/** Refuses a value whose `Set-Cookie` would exceed what a browser keeps. */
|
|
350
|
+
const write = async (value) => {
|
|
351
|
+
const resolved = await value;
|
|
352
|
+
const bytes = assembledCookieBytes(cookieName, resolved, cookieOptions, cookieMaxAgeSeconds ?? ttlSeconds);
|
|
353
|
+
if (bytes > maxCookieBytes) throw new Error(`The session cookie would be ${bytes} bytes, over the ${maxCookieBytes}-byte limit browsers keep. A cookie session carries the whole session — keep large or revocable values in the database and only their ids in the session, or raise \`maxCookieBytes\`.`);
|
|
354
|
+
return resolved;
|
|
355
|
+
};
|
|
356
|
+
await persistSession();
|
|
274
357
|
};
|
|
275
358
|
}
|
|
276
359
|
function getSessionFromContext(ctx) {
|
|
@@ -1991,4 +2074,4 @@ function requireVerifiedEmail(options = {}) {
|
|
|
1991
2074
|
};
|
|
1992
2075
|
}
|
|
1993
2076
|
//#endregion
|
|
1994
|
-
export { buildTokenUrl as $, verifyOAuthState as A, getApiToken as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, TokenGuard as F, readBearerToken as G, getUserApiTokens as H, API_TOKEN_KEY as I, tokenCan as J, revokeAllApiTokens as K, MemoryApiTokenStore as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, SessionGuard as Q, createApiToken as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, hasBearerHeader as U, getApiTokenOrFail as V, parseApiToken as W, tokenCanAny as X, tokenCanAll as Y, verifyApiToken as Z, OAUTH_SESSION_BINDING_KEY as _, isEmailVerified as a, secureStringCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c, NodeHasher as ct, completePasswordReset as d, BaseUserProvider as dt, generateId as et, createPasswordResetToken as f, installAgentPrincipal as ft, MemoryOAuthStateStore as g,
|
|
2077
|
+
export { buildTokenUrl as $, verifyOAuthState as A, getApiToken as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, TokenGuard as F, readBearerToken as G, getUserApiTokens as H, API_TOKEN_KEY as I, tokenCan as J, revokeAllApiTokens as K, MemoryApiTokenStore as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, SessionGuard as Q, createApiToken as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, hasBearerHeader as U, getApiTokenOrFail as V, parseApiToken as W, tokenCanAny as X, tokenCanAll as Y, verifyApiToken as Z, OAUTH_SESSION_BINDING_KEY as _, getSessionFromContext as _t, isEmailVerified as a, secureStringCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c, NodeHasher as ct, completePasswordReset as d, BaseUserProvider as dt, generateId as et, createPasswordResetToken as f, installAgentPrincipal as ft, MemoryOAuthStateStore as g, defaultCookieSecure as gt, AuthenticatableModel as h, createSessionMiddleware as ht, createEmailVerificationToken as i, secureCompare as it, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, ScryptHasher as lt, verifyPasswordResetToken as m, MemorySessionStore as mt, buildVerificationUrl as n, hashToken as nt, parseVerificationUrl as o, ModelUserProvider as ot, parsePasswordResetUrl as p, readAgentPrincipal as pt, revokeApiToken as q, completeEmailVerification as r, parseTokenUrl as rt, requireVerifiedEmail as s, DefaultHasher as st, MemoryEmailVerificationStore as t, generateToken as tt, buildPasswordResetUrl as u, AuthenticationException as ut, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, createBearerTokenMiddleware as z };
|
package/dist/cache/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-
|
|
1
|
+
import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-DUhlolkJ.js";
|
|
2
2
|
export { CacheManager, FileStore, MemoryStore, RedisStore, TaggedCache, createCacheManager };
|
package/dist/cache/types.d.ts
CHANGED
|
@@ -45,7 +45,11 @@ export interface MemoryStoreOptions {
|
|
|
45
45
|
now?: () => number;
|
|
46
46
|
}
|
|
47
47
|
export interface RedisStoreOptions {
|
|
48
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* An ioredis client, or a function returning one *synchronously* (ioredis
|
|
50
|
+
* connects lazily on its own). A function runs when the store is first
|
|
51
|
+
* built, so a store declared in `stores` but never selected opens no socket.
|
|
52
|
+
*/
|
|
49
53
|
client: unknown;
|
|
50
54
|
/** @default 'cache:' */
|
|
51
55
|
prefix?: string;
|
|
@@ -1,8 +1,23 @@
|
|
|
1
|
+
import { r as isPromiseLike } from "./Logger-DFifRAtc.js";
|
|
1
2
|
import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
4
|
import { mkdir, readFile, readdir, rm, unlink, writeFile } from "node:fs/promises";
|
|
4
5
|
import { dirname, join } from "node:path";
|
|
5
6
|
import { existsSync } from "node:fs";
|
|
7
|
+
//#region src/redis/lazy-client.ts
|
|
8
|
+
/**
|
|
9
|
+
* The one rule for a `client` option that may be an ioredis instance or a
|
|
10
|
+
* function returning one: the function runs here, not where the config object
|
|
11
|
+
* was declared, so a declared-but-unselected store never dials. Cache and
|
|
12
|
+
* session both resolve through it — a second copy is how the two subsystems
|
|
13
|
+
* come to disagree about what `client` accepts.
|
|
14
|
+
*/
|
|
15
|
+
function resolveLazyRedisClient(client, label) {
|
|
16
|
+
const resolved = typeof client === "function" ? client() : client;
|
|
17
|
+
if (isPromiseLike(resolved)) throw new Error(`${label}: \`client\` returned a Promise. Return the ioredis client synchronously; it connects lazily on first use.`);
|
|
18
|
+
return resolved;
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
6
21
|
//#region src/cache/stores/MemoryStore.ts
|
|
7
22
|
/** In-memory cache store. */
|
|
8
23
|
var MemoryStore = class {
|
|
@@ -131,7 +146,7 @@ var RedisStore = class {
|
|
|
131
146
|
client;
|
|
132
147
|
prefix;
|
|
133
148
|
constructor(options) {
|
|
134
|
-
this.client = options.client;
|
|
149
|
+
this.client = resolveLazyRedisClient(options.client, "Redis cache store");
|
|
135
150
|
this.prefix = options.prefix ?? "cache:";
|
|
136
151
|
}
|
|
137
152
|
prefixKey(key) {
|
|
@@ -592,7 +607,7 @@ var CacheManager = class {
|
|
|
592
607
|
const cached = this.resolvedStores.get(storeName);
|
|
593
608
|
if (cached) return cached;
|
|
594
609
|
const factory = this.storeFactories.get(storeName);
|
|
595
|
-
if (!factory) throw new Error(`Cache store not found: ${storeName}`);
|
|
610
|
+
if (!factory) throw new Error(`Cache store not found: ${storeName} (declared: ${this.getStoreNames().join(", ")})`);
|
|
596
611
|
const raw = factory();
|
|
597
612
|
this.stopPreviousStore(storeName, raw);
|
|
598
613
|
const store = new TaggableCacheStoreWrapper(raw);
|
|
@@ -630,4 +645,4 @@ function createCacheManager(config) {
|
|
|
630
645
|
return new CacheManager(config);
|
|
631
646
|
}
|
|
632
647
|
//#endregion
|
|
633
|
-
export { RedisStore as a, FileStore as i, createCacheManager as n, MemoryStore as o, TaggedCache as r, CacheManager as t };
|
|
648
|
+
export { RedisStore as a, FileStore as i, createCacheManager as n, MemoryStore as o, TaggedCache as r, resolveLazyRedisClient as s, CacheManager as t };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import Redis from "ioredis";
|
|
2
|
+
//#region src/redis/scan-keys.ts
|
|
3
|
+
/** Cursor-based SCAN rather than the O(N), server-blocking KEYS. */
|
|
4
|
+
async function scanKeys(redis, pattern) {
|
|
5
|
+
const keys = [];
|
|
6
|
+
let cursor = "0";
|
|
7
|
+
do {
|
|
8
|
+
const [newCursor, foundKeys] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
9
|
+
cursor = newCursor;
|
|
10
|
+
keys.push(...foundKeys);
|
|
11
|
+
} while (cursor !== "0");
|
|
12
|
+
return keys;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/redis/RedisSessionStore.ts
|
|
16
|
+
var RedisSessionStore = class {
|
|
17
|
+
redis;
|
|
18
|
+
prefix;
|
|
19
|
+
constructor(redis, options = {}) {
|
|
20
|
+
this.redis = redis;
|
|
21
|
+
this.prefix = options.prefix ?? "session:";
|
|
22
|
+
}
|
|
23
|
+
async read(id) {
|
|
24
|
+
const key = this.prefix + id;
|
|
25
|
+
const data = await this.redis.get(key);
|
|
26
|
+
if (!data) return;
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(data);
|
|
29
|
+
} catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async write(id, data, ttlSeconds) {
|
|
34
|
+
const key = this.prefix + id;
|
|
35
|
+
const serialized = JSON.stringify(data);
|
|
36
|
+
await this.redis.setex(key, ttlSeconds, serialized);
|
|
37
|
+
}
|
|
38
|
+
async destroy(id) {
|
|
39
|
+
const key = this.prefix + id;
|
|
40
|
+
await this.redis.del(key);
|
|
41
|
+
}
|
|
42
|
+
/** EXPIRE on a missing key is a no-op, never a resurrection. */
|
|
43
|
+
async touch(id, ttlSeconds) {
|
|
44
|
+
const key = this.prefix + id;
|
|
45
|
+
await this.redis.expire(key, ttlSeconds);
|
|
46
|
+
}
|
|
47
|
+
/** Debugging/admin. */
|
|
48
|
+
async keys() {
|
|
49
|
+
return (await scanKeys(this.redis, this.prefix + "*")).map((key) => key.slice(this.prefix.length));
|
|
50
|
+
}
|
|
51
|
+
async size() {
|
|
52
|
+
return (await this.keys()).length;
|
|
53
|
+
}
|
|
54
|
+
async clear() {
|
|
55
|
+
const keys = await this.keys();
|
|
56
|
+
if (keys.length > 0) {
|
|
57
|
+
const prefixedKeys = keys.map((key) => this.prefix + key);
|
|
58
|
+
await this.redis.del(...prefixedKeys);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/redis/client.ts
|
|
64
|
+
function createRedisClient(options = {}) {
|
|
65
|
+
const { url, ...redisOptions } = options;
|
|
66
|
+
if (url) return new Redis(url, redisOptions);
|
|
67
|
+
return new Redis(redisOptions);
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
export { scanKeys as i, createRedisClient as n, RedisSessionStore as r, Redis as t };
|
|
@@ -64,6 +64,8 @@ export declare abstract class Command implements CommandInstance {
|
|
|
64
64
|
}): void;
|
|
65
65
|
call(command: string, args?: string[]): Promise<number>;
|
|
66
66
|
protected resolve<T>(key: string): T;
|
|
67
|
+
/** `resolve()` for a service a command tolerates being absent; fakes and deferred providers count. */
|
|
68
|
+
protected resolveOptional<T>(key: string): T | undefined;
|
|
67
69
|
getSignature(): string;
|
|
68
70
|
getDescription(): string;
|
|
69
71
|
getName(): string;
|
|
@@ -28,6 +28,15 @@ export declare class Container {
|
|
|
28
28
|
make<T>(key: string): T;
|
|
29
29
|
makeWith<T>(key: string, params: Record<string, unknown>): T;
|
|
30
30
|
has(key: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* `make()` for a service that may be absent: undefined when nothing provides
|
|
33
|
+
* it. Unlike `has()`, a fake counts and a deferred provider is activated, so
|
|
34
|
+
* an optional dependency bound either way is found rather than skipped.
|
|
35
|
+
*/
|
|
36
|
+
makeOptional<K extends keyof ServiceBindings>(key: K): ServiceBindings[K] | undefined;
|
|
37
|
+
makeOptional<T>(key: string): T | undefined;
|
|
38
|
+
/** The binding a deferred provider makes for `resolvedKey`, once its register() has run; undefined when none provides it. */
|
|
39
|
+
private loadDeferred;
|
|
31
40
|
alias(alias: string, key: string): this;
|
|
32
41
|
tag(keys: string[], tagName: string): this;
|
|
33
42
|
tagged<T = unknown>(tagName: string): T[];
|
|
@@ -19,6 +19,7 @@ import type { Gate } from '../authorization/Gate.js';
|
|
|
19
19
|
import type { ExceptionHandler } from '../errors/index.js';
|
|
20
20
|
import type { SharedInertiaPropsRegistry } from '../mvc/inertia/shared.js';
|
|
21
21
|
import type { AgentAuditEmitter } from '../agent/audit-emitter.js';
|
|
22
|
+
import type { SessionManager } from '../http/middleware/session-manager.js';
|
|
22
23
|
/** Maps service keys to their concrete types, for `container.make('key')`. */
|
|
23
24
|
export interface ServiceBindings {
|
|
24
25
|
app: Application;
|
|
@@ -34,6 +35,8 @@ export interface ServiceBindings {
|
|
|
34
35
|
encrypter: Encrypter;
|
|
35
36
|
'app.keyring': AppKeyring;
|
|
36
37
|
auth: AuthManager;
|
|
38
|
+
/** Bound by an app's SessionProvider; AuthServiceProvider resolves the store through it (RFC 0020). */
|
|
39
|
+
session: SessionManager;
|
|
37
40
|
oauth: OAuthManager;
|
|
38
41
|
storage: StorageManager;
|
|
39
42
|
health: HealthManager;
|
|
@@ -150,6 +150,8 @@ export declare class Application {
|
|
|
150
150
|
get authOptions(): AuthPluginOptions | undefined;
|
|
151
151
|
get i18nOptions(): I18nPluginOptions | undefined;
|
|
152
152
|
markAutoSessionAttached(): void;
|
|
153
|
+
/** Whether `key` is supplied by a deferred provider, which only activates on a `make()` after boot. */
|
|
154
|
+
isDeferredService(key: string): boolean;
|
|
153
155
|
hasAutoSessionAttached(): boolean;
|
|
154
156
|
/**
|
|
155
157
|
* Asserts that `path` resolves its principal without ever reading a session
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type AppKeyring } from '../../encryption/app-key.js';
|
|
2
|
+
import type { SessionData, SessionStore } from './session.js';
|
|
3
|
+
export interface CookieSessionStoreOptions {
|
|
4
|
+
/** Clock for expiry, injectable for tests. @default Date.now */
|
|
5
|
+
now?: () => number;
|
|
6
|
+
/** Overrides the keyring derived from `APP_KEY` / `APP_PREVIOUS_KEYS`; for tests and direct construction. */
|
|
7
|
+
keyring?: AppKeyring;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The whole session, encrypted inside the cookie under the app key: the one
|
|
11
|
+
* store needing no server-side resource (RFC 0020 §3). Two limits the docs
|
|
12
|
+
* state outright — everything in the session travels in the cookie, so the
|
|
13
|
+
* middleware caps it; and a logout cannot revoke a copy the client already
|
|
14
|
+
* has, so anything revocable belongs in the database with only its id here.
|
|
15
|
+
*/
|
|
16
|
+
export declare class CookieSessionStore implements SessionStore {
|
|
17
|
+
private readonly keyring;
|
|
18
|
+
private readonly now;
|
|
19
|
+
constructor(options?: CookieSessionStoreOptions);
|
|
20
|
+
readonly inline: {
|
|
21
|
+
/**
|
|
22
|
+
* `base64url(iv ‖ tag ‖ ciphertext)` rather than `Encrypter`'s envelope,
|
|
23
|
+
* which base64s the ciphertext into JSON and base64s that again: measured
|
|
24
|
+
* 2.27x the plaintext against 1.52x here, and a cookie's budget is this
|
|
25
|
+
* store's whole constraint. Same primitives, same 12-byte IV and 16-byte tag.
|
|
26
|
+
*/
|
|
27
|
+
encode: (id: string, data: SessionData, ttlSeconds: number) => string;
|
|
28
|
+
decode: (cookieValue: string | undefined) => {
|
|
29
|
+
id: string;
|
|
30
|
+
data: SessionData;
|
|
31
|
+
} | null;
|
|
32
|
+
};
|
|
33
|
+
private open;
|
|
34
|
+
read(): Promise<SessionData | undefined>;
|
|
35
|
+
write(): Promise<void>;
|
|
36
|
+
destroy(): Promise<void>;
|
|
37
|
+
private keyedStoreError;
|
|
38
|
+
}
|
|
@@ -3,6 +3,12 @@ export type Middleware = MiddlewareHandler;
|
|
|
3
3
|
export declare function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler;
|
|
4
4
|
export declare function jsonResponse(data: unknown, status?: number): Response;
|
|
5
5
|
export { createSessionMiddleware, MemorySessionStore, getSessionFromContext } from './session.js';
|
|
6
|
+
export { DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, SessionManager } from './session-manager.js';
|
|
7
|
+
export { CookieSessionStore } from './cookie-session-store.js';
|
|
8
|
+
export type { CookieSessionStoreOptions } from './cookie-session-store.js';
|
|
9
|
+
export type { CookieSessionDriverOptions, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, MemorySessionDriverOptions, RedisSessionDriverOptions, } from './session-manager.js';
|
|
10
|
+
export type { SessionCookieOptions, SessionInlineCodec } from './session.js';
|
|
11
|
+
export { defaultCookieSecure } from './session.js';
|
|
6
12
|
export type { Session, SessionData, SessionStore } from './session.js';
|
|
7
13
|
export { requireAuthenticated, requireGuest, attachAuthContext, type AuthContext, type RequireAuthOptions, } from './auth.js';
|
|
8
14
|
export { createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, XSRF_HEADER_NAME, XSRF_COOKIE_NAME, type CsrfOptions, type CookielessAuthEndpoints, } from './csrf.js';
|