@guren/server 2.19.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/Logger-DFifRAtc.js +114 -0
- package/dist/auth/index.js +1 -1
- package/dist/{auth-DrbFuxoW.js → auth-BXcHQwHf.js} +93 -38
- 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/http/middleware/cookie-session-store.d.ts +38 -0
- package/dist/http/middleware/index.d.ts +4 -2
- package/dist/http/middleware/session-manager.d.ts +9 -0
- package/dist/http/middleware/session.d.ts +22 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +104 -8
- package/dist/lambda/index.js +3 -3
- package/dist/logging/index.js +2 -1
- package/dist/{logging-DcvkE5Dh.js → logging-DXmqqUl4.js} +2 -114
- package/dist/redis/lazy-client.d.ts +8 -0
- package/dist/runtime/index.js +3 -3
- package/dist/{vite-manifest-C57vi7J9.js → vite-manifest-BZQ-75hf.js} +2 -2
- package/package.json +2 -2
|
@@ -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 };
|
|
@@ -41,6 +41,8 @@ var MemorySessionStore = class {
|
|
|
41
41
|
};
|
|
42
42
|
const DEFAULT_COOKIE_NAME = "guren.session";
|
|
43
43
|
const DEFAULT_TTL_SECONDS = 7200;
|
|
44
|
+
/** What browsers keep per cookie; a larger one is dropped, which reads as a logout. */
|
|
45
|
+
const DEFAULT_MAX_COOKIE_BYTES = 4096;
|
|
44
46
|
/**
|
|
45
47
|
* Read when a middleware is built, not when this module loads: an app that
|
|
46
48
|
* sets NODE_ENV after importing the framework (tests, some serverless
|
|
@@ -239,8 +241,62 @@ function warnAboutMemoryStore(store) {
|
|
|
239
241
|
if (!runtime || runtime.emulator === "vercel-dev") return;
|
|
240
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.`);
|
|
241
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
|
+
}
|
|
242
298
|
function createSessionMiddleware(options = {}) {
|
|
243
|
-
const { cookieName = DEFAULT_COOKIE_NAME, cookiePath = "/", cookieDomain, cookieSecure = defaultCookieSecure(), cookieSameSite = "Lax", cookieHttpOnly = true, cookieMaxAgeSeconds, ttlSeconds = DEFAULT_TTL_SECONDS, store: storeOrFactory = new MemorySessionStore() } = options;
|
|
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;
|
|
244
300
|
const signer = createCookieSigner(cookieName, cookiePath);
|
|
245
301
|
let checkedStore = false;
|
|
246
302
|
return async (ctx, next) => {
|
|
@@ -249,10 +305,12 @@ function createSessionMiddleware(options = {}) {
|
|
|
249
305
|
checkedStore = true;
|
|
250
306
|
warnAboutMemoryStore(store);
|
|
251
307
|
}
|
|
252
|
-
const
|
|
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;
|
|
253
311
|
const sessionId = existingId ?? globalThis.crypto.randomUUID();
|
|
254
312
|
const isNew = !existingId;
|
|
255
|
-
const storedData =
|
|
313
|
+
const storedData = loaded?.data ?? {};
|
|
256
314
|
const testingData = resolveTestingSession(ctx);
|
|
257
315
|
const session = new SessionImpl(sessionId, testingData ? {
|
|
258
316
|
...storedData,
|
|
@@ -260,45 +318,42 @@ function createSessionMiddleware(options = {}) {
|
|
|
260
318
|
} : storedData, isNew);
|
|
261
319
|
session.ageFlashData();
|
|
262
320
|
ctx.set(SESSION_CONTEXT_KEY, session);
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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 () => {
|
|
266
330
|
if (session.wasDestroyed()) {
|
|
267
|
-
await
|
|
268
|
-
deleteCookie(ctx, cookieName,
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
});
|
|
275
|
-
} else if (!session.shouldPersist()) {
|
|
276
|
-
if (existingId) {
|
|
277
|
-
if (store.touch) await store.touch(existingId, ttlSeconds);
|
|
278
|
-
else await store.write(existingId, session.snapshot(), ttlSeconds);
|
|
279
|
-
setCookie(ctx, cookieName, signer.sign(existingId), {
|
|
280
|
-
path: cookiePath,
|
|
281
|
-
domain: cookieDomain,
|
|
282
|
-
secure: cookieSecure,
|
|
283
|
-
sameSite: cookieSameSite,
|
|
284
|
-
httpOnly: cookieHttpOnly,
|
|
285
|
-
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
286
|
-
});
|
|
287
|
-
}
|
|
288
|
-
} else {
|
|
289
|
-
const nextId = session.id;
|
|
290
|
-
await store.write(nextId, session.snapshot(), ttlSeconds);
|
|
291
|
-
if (session.wasRegenerated() && session.originalSessionId() !== nextId) await store.destroy(session.originalSessionId());
|
|
292
|
-
setCookie(ctx, cookieName, signer.sign(nextId), {
|
|
293
|
-
path: cookiePath,
|
|
294
|
-
domain: cookieDomain,
|
|
295
|
-
secure: cookieSecure,
|
|
296
|
-
sameSite: cookieSameSite,
|
|
297
|
-
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,
|
|
298
338
|
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
299
339
|
});
|
|
340
|
+
return;
|
|
300
341
|
}
|
|
301
|
-
|
|
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();
|
|
302
357
|
};
|
|
303
358
|
}
|
|
304
359
|
function getSessionFromContext(ctx) {
|
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,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
|
+
}
|
|
@@ -4,8 +4,10 @@ export declare function defineMiddleware(handler: MiddlewareHandler): Middleware
|
|
|
4
4
|
export declare function jsonResponse(data: unknown, status?: number): Response;
|
|
5
5
|
export { createSessionMiddleware, MemorySessionStore, getSessionFromContext } from './session.js';
|
|
6
6
|
export { DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, SessionManager } from './session-manager.js';
|
|
7
|
-
export
|
|
8
|
-
export type {
|
|
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';
|
|
9
11
|
export { defaultCookieSecure } from './session.js';
|
|
10
12
|
export type { Session, SessionData, SessionStore } from './session.js';
|
|
11
13
|
export { requireAuthenticated, requireGuest, attachAuthContext, type AuthContext, type RequireAuthOptions, } from './auth.js';
|
|
@@ -23,6 +23,15 @@ export interface RedisSessionDriverOptions {
|
|
|
23
23
|
export interface SessionDrivers {
|
|
24
24
|
memory: MemorySessionDriverOptions;
|
|
25
25
|
redis: RedisSessionDriverOptions;
|
|
26
|
+
cookie: CookieSessionDriverOptions;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The cookie driver takes no app-facing options: its key comes from `APP_KEY`
|
|
30
|
+
* and its size budget from the middleware. `keyring` and `now` stay on
|
|
31
|
+
* {@link CookieSessionStoreOptions}, for direct construction in tests — a
|
|
32
|
+
* committed `config/session.ts` is the wrong home for key material.
|
|
33
|
+
*/
|
|
34
|
+
export interface CookieSessionDriverOptions {
|
|
26
35
|
}
|
|
27
36
|
export type SessionStoreConfig = {
|
|
28
37
|
[K in keyof SessionDrivers]: {
|
|
@@ -13,6 +13,22 @@ export interface SessionStore {
|
|
|
13
13
|
* session that does not exist must be a no-op, not a resurrection.
|
|
14
14
|
*/
|
|
15
15
|
touch?(id: string, ttlSeconds: number): Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Present on stores that keep the session *inside* the cookie (RFC 0020 §3).
|
|
18
|
+
* The middleware then writes `encode()`'s value as the cookie instead of a
|
|
19
|
+
* signed id and reads the next request's back through `decode()`, so
|
|
20
|
+
* `read`/`write`/`destroy` are never called: there is no keyed store behind it.
|
|
21
|
+
*/
|
|
22
|
+
inline?: SessionInlineCodec;
|
|
23
|
+
}
|
|
24
|
+
export interface SessionInlineCodec {
|
|
25
|
+
/** Throws when the session cannot fit the cookie, rather than emitting one a browser drops. */
|
|
26
|
+
encode(id: string, data: SessionData, ttlSeconds: number): string;
|
|
27
|
+
/** Null for a missing, expired, tampered, or undecryptable cookie. */
|
|
28
|
+
decode(cookieValue: string | undefined): {
|
|
29
|
+
id: string;
|
|
30
|
+
data: SessionData;
|
|
31
|
+
} | null;
|
|
16
32
|
}
|
|
17
33
|
export declare class MemorySessionStore implements SessionStore {
|
|
18
34
|
private readonly now;
|
|
@@ -35,6 +51,12 @@ export interface SessionCookieOptions {
|
|
|
35
51
|
ttlSeconds?: number;
|
|
36
52
|
}
|
|
37
53
|
export interface SessionOptions extends SessionCookieOptions {
|
|
54
|
+
/**
|
|
55
|
+
* Bytes the whole `Set-Cookie` may occupy before the middleware refuses it.
|
|
56
|
+
* Browsers drop a larger one, and a dropped session cookie is a silent logout.
|
|
57
|
+
* @default 4096
|
|
58
|
+
*/
|
|
59
|
+
maxCookieBytes?: number;
|
|
38
60
|
/**
|
|
39
61
|
* The store, or a function returning it, called on every request and never
|
|
40
62
|
* at construction: a Workers binding does not exist before the first request
|
package/dist/index.d.ts
CHANGED
|
@@ -43,9 +43,9 @@ export { InertiaServiceProvider, AuthServiceProvider, OAuthServiceProvider, Even
|
|
|
43
43
|
export { FormRequest } from './http/FormRequest.js';
|
|
44
44
|
export { AuthManager, SessionGuard, TokenGuard, ModelUserProvider, BaseUserProvider, AuthenticatableModel, ScryptHasher, createPasswordResetToken, verifyPasswordResetToken, completePasswordReset, buildPasswordResetUrl, parsePasswordResetUrl, MemoryPasswordResetStore, createEmailVerificationToken, verifyEmailToken, completeEmailVerification, buildVerificationUrl, parseVerificationUrl, isEmailVerified, requireVerifiedEmail, MemoryEmailVerificationStore, createApiToken, parseApiToken, readBearerToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, OAuthManager, MemoryOAuthStateStore, createOAuthManager, createOAuthState, verifyOAuthState, sanitizeOAuthRedirect, OAUTH_SESSION_BINDING_KEY, buildOAuthAuthorizeUrl, exchangeOAuthCode, fetchOAuthUserProfile, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createDiscordOAuthProviderConfig, buildOAuthRedirectUrl, parseOAuthRedirectUrl, } from './auth/index.js';
|
|
45
45
|
export type { AuthContext as AuthRuntimeContext, AuthCredentials, AuthManagerOptions, Authenticatable, Guard, GuardContext, GuardFactory, UserProvider, ProviderFactory, DefaultSanitizedKeys, Sanitized, PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, ApiToken, ApiTokenGuardOptions, ApiTokenStore, CreateApiTokenOptions, CreateApiTokenResult, BearerTokenMiddlewareOptions, VerifiedApiToken, TokenGuardOptions, OAuthProviderConfig, OAuthTokenResult, OAuthUserProfile, OAuthFallbackEmail, OAuthStatePayload, OAuthStateStore, OAuthStateConfig, OAuthAuthorizeOptions, OAuthCallbackPayload, OAuthManagerOptions, OAuthProviderFactoryInput, OAuthBindingSession, } from './auth/index.js';
|
|
46
|
-
export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, getSessionFromContext, requireAuthenticated, requireGuest, attachAuthContext, createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
|
|
46
|
+
export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, CookieSessionStore, DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, getSessionFromContext, requireAuthenticated, requireGuest, attachAuthContext, createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
|
|
47
47
|
export { AUTH_CONTEXT_KEY } from './http/middleware/auth.js';
|
|
48
|
-
export type { Middleware, Session, SessionData, SessionStore, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, SessionCookieOptions, MemorySessionDriverOptions, RedisSessionDriverOptions, AuthContext, RequireAuthOptions, CsrfOptions, CookielessAuthEndpoints, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';
|
|
48
|
+
export type { Middleware, Session, SessionData, SessionStore, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, SessionCookieOptions, SessionInlineCodec, CookieSessionStoreOptions, CookieSessionDriverOptions, MemorySessionDriverOptions, RedisSessionDriverOptions, AuthContext, RequireAuthOptions, CsrfOptions, CookielessAuthEndpoints, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';
|
|
49
49
|
export { Validator, FieldValidator, createValidator, quickValidate, quickValidateOrThrow, required, nullable, requiredIf, requiredUnless, requiredWith, requiredWithout, string as stringRule, numeric, integer, boolean as booleanRule, array as arrayRule, object as objectRule, email as emailRule, url as urlRule, uuid as uuidRule, ip, ipv4, ipv6, json as jsonRule, alpha, alphaNum, alphaDash, regex, min, max, between, size, inValues, notIn, confirmed, same, different, date as dateRule, dateFormat, after, afterOrEqual, before, beforeOrEqual, startsWith, endsWith, file as fileRule, image as imageRule, mimes, maxFileSize, minFileSize, custom, unique, exists, } from './http/validation/index.js';
|
|
50
50
|
export type { ValidationRule, RuleDefinition, ValidationResult, FileValidationOptions, ImageValidationOptions, ValidatorOptions, FileLike, } from './http/validation/index.js';
|
|
51
51
|
export { Event, EventManager, createEventManager, Listener, RequestReceived, RequestFinished, UserAuthenticated, UserLoggedOut, JobProcessed, JobFailed, ApplicationStarted, ApplicationShutdown, } from './events/index.js';
|
package/dist/index.js
CHANGED
|
@@ -9,23 +9,24 @@ import { a as getRegisteredJobs, c as setQueueDriver, d as getContainer, f as re
|
|
|
9
9
|
import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-DT9gHF0F.js";
|
|
10
10
|
import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
|
|
11
11
|
import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
|
|
12
|
-
import { 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, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, _t as getSessionFromContext, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, f as createPasswordResetToken, ft as installAgentPrincipal, g as MemoryOAuthStateStore, gt as defaultCookieSecure, h as AuthenticatableModel, ht as createSessionMiddleware, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, mt as MemorySessionStore, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as readAgentPrincipal, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as DefaultHasher, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-
|
|
12
|
+
import { 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, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, _t as getSessionFromContext, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, f as createPasswordResetToken, ft as installAgentPrincipal, g as MemoryOAuthStateStore, gt as defaultCookieSecure, h as AuthenticatableModel, ht as createSessionMiddleware, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, mt as MemorySessionStore, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as readAgentPrincipal, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as DefaultHasher, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-BXcHQwHf.js";
|
|
13
13
|
import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "./Hash-D2DFd8xX.js";
|
|
14
14
|
import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-CXk_umpT.js";
|
|
15
|
-
import {
|
|
15
|
+
import { n as filterSensitiveData, t as Logger } from "./Logger-DFifRAtc.js";
|
|
16
|
+
import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-DUhlolkJ.js";
|
|
16
17
|
import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
|
|
17
18
|
import { r as isMcpEndpointEnabled } from "./endpoint-Dsw3Acvq.js";
|
|
18
19
|
import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
|
|
19
20
|
import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "./i18n-Cg1aajRP.js";
|
|
20
|
-
import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-
|
|
21
|
+
import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-BZQ-75hf.js";
|
|
21
22
|
import { r as isDocsViewerEnabled } from "./endpoint-BXipU2Jj.js";
|
|
22
23
|
import { t as jsx_runtime_exports } from "./jsx-runtime.js";
|
|
23
24
|
import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
|
|
24
25
|
import { a as RequestFinished, c as UserLoggedOut, d as createEventManager, f as Event, i as JobProcessed, l as Listener, n as ApplicationStarted, o as RequestReceived, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as EventManager } from "./events-DOmAHDeP.js";
|
|
25
26
|
import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-D0VXkFLF.js";
|
|
26
|
-
import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "./cache-BOOIr324.js";
|
|
27
27
|
import { a as processJob, c as RedisDriver$1, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver$1 } from "./queue-zPPYZdif.js";
|
|
28
28
|
import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "./mail-9CrvJyBZ.js";
|
|
29
|
+
import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "./logging-DXmqqUl4.js";
|
|
29
30
|
import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-B5RzB0A2.js";
|
|
30
31
|
import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "./Random-S0OvCuR8.js";
|
|
31
32
|
import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-uwP3Di4D.js";
|
|
@@ -34,6 +35,7 @@ import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHeal
|
|
|
34
35
|
import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "./scheduling-C6tcOtUl.js";
|
|
35
36
|
import { Hono } from "hono";
|
|
36
37
|
import { deleteCookie, getCookie } from "hono/cookie";
|
|
38
|
+
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
|
37
39
|
import { cors } from "hono/cors";
|
|
38
40
|
import { createMiddleware } from "hono/factory";
|
|
39
41
|
import { parseAccept } from "hono/utils/accept";
|
|
@@ -816,6 +818,100 @@ async function mountModuleRoutes(router, gurenModule) {
|
|
|
816
818
|
await pending;
|
|
817
819
|
}
|
|
818
820
|
//#endregion
|
|
821
|
+
//#region src/http/middleware/cookie-session-store.ts
|
|
822
|
+
const IV_BYTES = 12;
|
|
823
|
+
const TAG_BYTES = 16;
|
|
824
|
+
function isPlainObject(value) {
|
|
825
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* The whole session, encrypted inside the cookie under the app key: the one
|
|
829
|
+
* store needing no server-side resource (RFC 0020 §3). Two limits the docs
|
|
830
|
+
* state outright — everything in the session travels in the cookie, so the
|
|
831
|
+
* middleware caps it; and a logout cannot revoke a copy the client already
|
|
832
|
+
* has, so anything revocable belongs in the database with only its id here.
|
|
833
|
+
*/
|
|
834
|
+
var CookieSessionStore = class {
|
|
835
|
+
keyring;
|
|
836
|
+
now;
|
|
837
|
+
constructor(options = {}) {
|
|
838
|
+
this.keyring = options.keyring ?? deriveAppKeyring(getAppKeyringFromEnv(), "cookie-session");
|
|
839
|
+
this.now = options.now ?? (() => Date.now());
|
|
840
|
+
}
|
|
841
|
+
inline = {
|
|
842
|
+
/**
|
|
843
|
+
* `base64url(iv ‖ tag ‖ ciphertext)` rather than `Encrypter`'s envelope,
|
|
844
|
+
* which base64s the ciphertext into JSON and base64s that again: measured
|
|
845
|
+
* 2.27x the plaintext against 1.52x here, and a cookie's budget is this
|
|
846
|
+
* store's whole constraint. Same primitives, same 12-byte IV and 16-byte tag.
|
|
847
|
+
*/
|
|
848
|
+
encode: (id, data, ttlSeconds) => {
|
|
849
|
+
const payload = {
|
|
850
|
+
id,
|
|
851
|
+
data,
|
|
852
|
+
expiresAt: this.now() + ttlSeconds * 1e3
|
|
853
|
+
};
|
|
854
|
+
const iv = randomBytes(IV_BYTES);
|
|
855
|
+
const cipher = createCipheriv("aes-256-gcm", this.keyring.current, iv, { authTagLength: TAG_BYTES });
|
|
856
|
+
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final()]);
|
|
857
|
+
return Buffer.concat([
|
|
858
|
+
iv,
|
|
859
|
+
cipher.getAuthTag(),
|
|
860
|
+
ciphertext
|
|
861
|
+
]).toString("base64url");
|
|
862
|
+
},
|
|
863
|
+
decode: (cookieValue) => {
|
|
864
|
+
if (!cookieValue) return null;
|
|
865
|
+
const raw = Buffer.from(cookieValue, "base64url");
|
|
866
|
+
if (raw.length <= 28) return null;
|
|
867
|
+
const iv = raw.subarray(0, IV_BYTES);
|
|
868
|
+
const tag = raw.subarray(IV_BYTES, 28);
|
|
869
|
+
const ciphertext = raw.subarray(28);
|
|
870
|
+
for (const key of [this.keyring.current, ...this.keyring.previous]) {
|
|
871
|
+
const payload = this.open(key, iv, tag, ciphertext);
|
|
872
|
+
if (payload) return payload;
|
|
873
|
+
}
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
open(key, iv, tag, ciphertext) {
|
|
878
|
+
let plaintext;
|
|
879
|
+
try {
|
|
880
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
|
|
881
|
+
decipher.setAuthTag(tag);
|
|
882
|
+
plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
|
|
883
|
+
} catch {
|
|
884
|
+
return null;
|
|
885
|
+
}
|
|
886
|
+
let payload;
|
|
887
|
+
try {
|
|
888
|
+
payload = JSON.parse(plaintext);
|
|
889
|
+
} catch {
|
|
890
|
+
return null;
|
|
891
|
+
}
|
|
892
|
+
if (!isPlainObject(payload)) return null;
|
|
893
|
+
const { id, data, expiresAt } = payload;
|
|
894
|
+
if (typeof id !== "string" || typeof expiresAt !== "number" || !isPlainObject(data)) return null;
|
|
895
|
+
if (expiresAt <= this.now()) return null;
|
|
896
|
+
return {
|
|
897
|
+
id,
|
|
898
|
+
data
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
async read() {
|
|
902
|
+
throw new Error(this.keyedStoreError("read"));
|
|
903
|
+
}
|
|
904
|
+
async write() {
|
|
905
|
+
throw new Error(this.keyedStoreError("write"));
|
|
906
|
+
}
|
|
907
|
+
async destroy() {
|
|
908
|
+
throw new Error(this.keyedStoreError("destroy"));
|
|
909
|
+
}
|
|
910
|
+
keyedStoreError(method) {
|
|
911
|
+
return `CookieSessionStore has no keyed store to ${method}: the session lives in the cookie, which the session middleware reads and writes through \`inline\`. Use a database- or Redis-backed store to look a session up by id.`;
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
//#endregion
|
|
819
915
|
//#region src/http/middleware/session-manager.ts
|
|
820
916
|
/** The store `SessionConfig.default` names when it names none, and the one driver that shares no state between requests. */
|
|
821
917
|
const DEFAULT_SESSION_STORE_NAME = "memory";
|
|
@@ -842,9 +938,9 @@ var SessionManager = class {
|
|
|
842
938
|
this.options = options;
|
|
843
939
|
this.defaultStoreName = defaultName;
|
|
844
940
|
this.registerDriver("memory", ({ now }) => new MemorySessionStore(now));
|
|
941
|
+
this.registerDriver("cookie", () => new CookieSessionStore());
|
|
845
942
|
this.registerDriver("redis", ({ client, prefix }) => {
|
|
846
|
-
const redis =
|
|
847
|
-
if (isPromiseLike(redis)) throw new Error("Session store \"redis\": `client` returned a Promise. Return the ioredis client synchronously; it connects lazily on first use.");
|
|
943
|
+
const redis = resolveLazyRedisClient(client, "Session store \"redis\"");
|
|
848
944
|
return new RedisSessionStore(redis, { prefix });
|
|
849
945
|
});
|
|
850
946
|
this.configs.set(DEFAULT_SESSION_STORE_NAME, { driver: "memory" });
|
|
@@ -2448,7 +2544,7 @@ function inertiaPageUrl(request) {
|
|
|
2448
2544
|
return `${pathname}${search}`;
|
|
2449
2545
|
}
|
|
2450
2546
|
async function renderDocument$1(page, options) {
|
|
2451
|
-
const defaultEntry = process.env.GUREN_INERTIA_ENTRY
|
|
2547
|
+
const defaultEntry = process.env.GUREN_INERTIA_ENTRY || "/resources/js/app.tsx";
|
|
2452
2548
|
const entry = options.entry ?? defaultEntry;
|
|
2453
2549
|
const title = escapeHtml$1(options.title ?? DEFAULT_TITLE);
|
|
2454
2550
|
const isProduction = process.env.NODE_ENV === "production";
|
|
@@ -7620,4 +7716,4 @@ function renderEnvironmentSection() {
|
|
|
7620
7716
|
//#region src/index.ts
|
|
7621
7717
|
ensureErrorStackTracePolyfill();
|
|
7622
7718
|
//#endregion
|
|
7623
|
-
export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
|
|
7719
|
+
export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
|
package/dist/lambda/index.js
CHANGED
|
@@ -60,9 +60,9 @@ function getLambdaContext() {
|
|
|
60
60
|
if (!isLambda()) return null;
|
|
61
61
|
return {
|
|
62
62
|
functionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
|
|
63
|
-
functionVersion: process.env.AWS_LAMBDA_FUNCTION_VERSION
|
|
64
|
-
memorySize: parseInt(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE
|
|
65
|
-
region: process.env.AWS_REGION
|
|
63
|
+
functionVersion: process.env.AWS_LAMBDA_FUNCTION_VERSION || "$LATEST",
|
|
64
|
+
memorySize: parseInt(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE || "128", 10),
|
|
65
|
+
region: process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || "us-east-1",
|
|
66
66
|
logGroup: process.env.AWS_LAMBDA_LOG_GROUP_NAME,
|
|
67
67
|
logStream: process.env.AWS_LAMBDA_LOG_STREAM_NAME,
|
|
68
68
|
tmpDir: "/tmp"
|
package/dist/logging/index.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as filterSensitiveData, t as Logger } from "../Logger-DFifRAtc.js";
|
|
2
|
+
import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "../logging-DXmqqUl4.js";
|
|
2
3
|
export { ConsoleChannel, DailyFileChannel, FileChannel, LOG_LEVEL_PRIORITY, LogManager, Logger, createLogManager, dailyFileDateStamp, dailyFilePath, filterSensitiveData, getLogManager, matchDailyFileDate, setLogManager };
|
|
@@ -1,118 +1,6 @@
|
|
|
1
|
+
import { r as isPromiseLike, t as Logger } from "./Logger-DFifRAtc.js";
|
|
1
2
|
import * as path$1 from "node:path";
|
|
2
3
|
import * as fs from "node:fs";
|
|
3
|
-
//#region src/logging/Logger.ts
|
|
4
|
-
const DEFAULT_FILTER_KEYS = [
|
|
5
|
-
"password",
|
|
6
|
-
"password_confirmation",
|
|
7
|
-
"token",
|
|
8
|
-
"secret",
|
|
9
|
-
"credit_card",
|
|
10
|
-
"creditCard",
|
|
11
|
-
"card_number",
|
|
12
|
-
"cardNumber",
|
|
13
|
-
"cvv",
|
|
14
|
-
"ssn",
|
|
15
|
-
"authorization"
|
|
16
|
-
];
|
|
17
|
-
/** Recursively replace values of sensitive keys in a log context object. */
|
|
18
|
-
function filterSensitiveData(data, filterKeys, replacement = "[FILTERED]") {
|
|
19
|
-
if (filterKeys.length === 0) return data;
|
|
20
|
-
return filterObject(data, new Set(filterKeys.map((k) => k.toLowerCase())), replacement);
|
|
21
|
-
}
|
|
22
|
-
function filterObject(obj, keySet, replacement) {
|
|
23
|
-
const result = {};
|
|
24
|
-
for (const [key, value] of Object.entries(obj)) if (keySet.has(key.toLowerCase())) result[key] = replacement;
|
|
25
|
-
else if (value !== null && typeof value === "object" && !Array.isArray(value)) result[key] = filterObject(value, keySet, replacement);
|
|
26
|
-
else if (Array.isArray(value)) result[key] = value.map((item) => item !== null && typeof item === "object" && !Array.isArray(item) ? filterObject(item, keySet, replacement) : item);
|
|
27
|
-
else result[key] = value;
|
|
28
|
-
return result;
|
|
29
|
-
}
|
|
30
|
-
const reportLoggingError = (error) => {
|
|
31
|
-
console.error("Logging error:", error);
|
|
32
|
-
};
|
|
33
|
-
/**
|
|
34
|
-
* Whether a channel's `log()` handed back something to wait on. A duck-typed
|
|
35
|
-
* check rather than `instanceof Promise`: a promise created in another realm
|
|
36
|
-
* (a `node:vm` context, a worker's module graph) satisfies the channel
|
|
37
|
-
* contract and would otherwise slip past the reporter as an unhandled rejection.
|
|
38
|
-
*/
|
|
39
|
-
function isPromiseLike(value) {
|
|
40
|
-
return typeof value === "object" && value !== null && typeof value.then === "function";
|
|
41
|
-
}
|
|
42
|
-
/** Logger instance for writing log entries. */
|
|
43
|
-
var Logger = class Logger {
|
|
44
|
-
channels;
|
|
45
|
-
baseContext;
|
|
46
|
-
filterKeys;
|
|
47
|
-
replacement;
|
|
48
|
-
constructor(channels, context = {}, options = {}) {
|
|
49
|
-
this.channels = channels;
|
|
50
|
-
this.baseContext = context;
|
|
51
|
-
this.filterKeys = options.filterKeys ?? DEFAULT_FILTER_KEYS;
|
|
52
|
-
this.replacement = options.replacement ?? "[FILTERED]";
|
|
53
|
-
}
|
|
54
|
-
emergency(message, context = {}) {
|
|
55
|
-
this.log("emergency", message, context);
|
|
56
|
-
}
|
|
57
|
-
alert(message, context = {}) {
|
|
58
|
-
this.log("alert", message, context);
|
|
59
|
-
}
|
|
60
|
-
critical(message, context = {}) {
|
|
61
|
-
this.log("critical", message, context);
|
|
62
|
-
}
|
|
63
|
-
error(message, context = {}) {
|
|
64
|
-
this.log("error", message, context);
|
|
65
|
-
}
|
|
66
|
-
warning(message, context = {}) {
|
|
67
|
-
this.log("warning", message, context);
|
|
68
|
-
}
|
|
69
|
-
warn(message, context = {}) {
|
|
70
|
-
this.warning(message, context);
|
|
71
|
-
}
|
|
72
|
-
notice(message, context = {}) {
|
|
73
|
-
this.log("notice", message, context);
|
|
74
|
-
}
|
|
75
|
-
info(message, context = {}) {
|
|
76
|
-
this.log("info", message, context);
|
|
77
|
-
}
|
|
78
|
-
debug(message, context = {}) {
|
|
79
|
-
this.log("debug", message, context);
|
|
80
|
-
}
|
|
81
|
-
log(level, message, context = {}) {
|
|
82
|
-
const merged = {
|
|
83
|
-
...this.baseContext,
|
|
84
|
-
...context
|
|
85
|
-
};
|
|
86
|
-
const entry = {
|
|
87
|
-
level,
|
|
88
|
-
message,
|
|
89
|
-
context: this.filterKeys.length > 0 ? filterSensitiveData(merged, this.filterKeys, this.replacement) : merged,
|
|
90
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
91
|
-
};
|
|
92
|
-
for (const channel of this.channels) try {
|
|
93
|
-
const pending = channel.log(entry);
|
|
94
|
-
if (isPromiseLike(pending)) Promise.resolve(pending).catch(reportLoggingError);
|
|
95
|
-
} catch (error) {
|
|
96
|
-
reportLoggingError(error);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
withContext(context) {
|
|
100
|
-
return new Logger(this.channels, {
|
|
101
|
-
...this.baseContext,
|
|
102
|
-
...context
|
|
103
|
-
}, {
|
|
104
|
-
filterKeys: this.filterKeys,
|
|
105
|
-
replacement: this.replacement
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
child(context) {
|
|
109
|
-
return this.withContext(context);
|
|
110
|
-
}
|
|
111
|
-
async close() {
|
|
112
|
-
for (const channel of this.channels) if (channel.close) await channel.close();
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
//#endregion
|
|
116
4
|
//#region src/logging/types.ts
|
|
117
5
|
/** Log level priority (lower = more severe). */
|
|
118
6
|
const LOG_LEVEL_PRIORITY = {
|
|
@@ -469,4 +357,4 @@ function getLogManager() {
|
|
|
469
357
|
return globalLogManager;
|
|
470
358
|
}
|
|
471
359
|
//#endregion
|
|
472
|
-
export { DailyFileChannel as a, matchDailyFileDate as c, LOG_LEVEL_PRIORITY as d,
|
|
360
|
+
export { DailyFileChannel as a, matchDailyFileDate as c, LOG_LEVEL_PRIORITY as d, setLogManager as i, FileChannel as l, createLogManager as n, dailyFileDateStamp as o, getLogManager as r, dailyFilePath as s, LogManager as t, ConsoleChannel as u };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one rule for a `client` option that may be an ioredis instance or a
|
|
3
|
+
* function returning one: the function runs here, not where the config object
|
|
4
|
+
* was declared, so a declared-but-unselected store never dials. Cache and
|
|
5
|
+
* session both resolve through it — a second copy is how the two subsystems
|
|
6
|
+
* come to disagree about what `client` accepts.
|
|
7
|
+
*/
|
|
8
|
+
export declare function resolveLazyRedisClient(client: unknown, label: string): unknown;
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as trimTrailingSlashes } from "../trim-slashes-BLY9hKAa.js";
|
|
2
2
|
import { n as hash } from "../Hash-D2DFd8xX.js";
|
|
3
|
-
import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-
|
|
3
|
+
import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-BZQ-75hf.js";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { realpath } from "node:fs/promises";
|
|
6
6
|
import { dirname, extname, join, resolve, sep } from "node:path";
|
|
@@ -220,7 +220,7 @@ function registerDevAssets(app, options) {
|
|
|
220
220
|
jsx: "transform",
|
|
221
221
|
jsxFactory: "React.createElement",
|
|
222
222
|
jsxFragment: "React.Fragment",
|
|
223
|
-
define: { "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV
|
|
223
|
+
define: { "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "development") }
|
|
224
224
|
};
|
|
225
225
|
const transpile = {
|
|
226
226
|
tsx: new Bun.Transpiler({
|
|
@@ -351,7 +351,7 @@ function createJsxRuntimeShim(helpers, runtimeUrl) {
|
|
|
351
351
|
}).join("\n")}\n`;
|
|
352
352
|
}
|
|
353
353
|
function isDev() {
|
|
354
|
-
return
|
|
354
|
+
return process.env.NODE_ENV !== "production";
|
|
355
355
|
}
|
|
356
356
|
function deriveCssRoute(prefix) {
|
|
357
357
|
const base = prefix.endsWith("/js") ? prefix.slice(0, -3) : prefix;
|
|
@@ -34,7 +34,7 @@ function parseImportMap(value, options = {}) {
|
|
|
34
34
|
const DEFAULT_DEV_STYLES_ENTRY = "/resources/css/app.css";
|
|
35
35
|
//#endregion
|
|
36
36
|
//#region package.json
|
|
37
|
-
var version = "2.
|
|
37
|
+
var version = "2.20.0";
|
|
38
38
|
//#endregion
|
|
39
39
|
//#region src/http/dev-banner.ts
|
|
40
40
|
figlet.parseFont("Standard", standard);
|
|
@@ -138,7 +138,7 @@ const DEFAULT_DEV_SERVER_URL = "http://localhost:5173";
|
|
|
138
138
|
* `NODE_ENV` is `production` (E2E runs do exactly this).
|
|
139
139
|
*/
|
|
140
140
|
function isViteProduction(devServerUrl = process.env.VITE_DEV_SERVER_URL) {
|
|
141
|
-
return
|
|
141
|
+
return process.env.NODE_ENV === "production" && typeof devServerUrl !== "string";
|
|
142
142
|
}
|
|
143
143
|
function normalizeDevServerUrl(value) {
|
|
144
144
|
if (!value) return value;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@guren/server",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.20.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"license": "MIT",
|
|
@@ -142,7 +142,7 @@
|
|
|
142
142
|
"test": "bun test"
|
|
143
143
|
},
|
|
144
144
|
"dependencies": {
|
|
145
|
-
"@guren/orm": "^2.
|
|
145
|
+
"@guren/orm": "^2.7.0",
|
|
146
146
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
147
147
|
"chalk": "^5.3.0",
|
|
148
148
|
"consola": "^3.4.2",
|