@guren/server 2.23.3 → 2.25.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.
Files changed (72) hide show
  1. package/dist/DailyFileChannel-CTTPA0EF.js +114 -0
  2. package/dist/{DocsViewerServiceProvider-DWnlXx_y.js → DocsViewerServiceProvider-CIRNHQ2I.js} +2 -2
  3. package/dist/{authorization-0mCGUFoI.js → Gate-YOt54xGF.js} +2 -217
  4. package/dist/{Job-BVvaY-7p.js → Job-COMzBNOL.js} +3 -10
  5. package/dist/McpServiceProvider-B-LioPSz.js +43 -0
  6. package/dist/Resource-BdYd4J9a.js +1035 -0
  7. package/dist/{loopback-guard-DT9gHF0F.js → ServiceProvider-DDW3MqQJ.js} +10 -68
  8. package/dist/agent/audit-file.d.ts +3 -0
  9. package/dist/agent/audit-sink.d.ts +16 -0
  10. package/dist/agent/call-budget.d.ts +22 -0
  11. package/dist/agent/events.d.ts +6 -6
  12. package/dist/api-token-BbgDEd6j.js +298 -0
  13. package/dist/audit-file-DocumbCr.js +29 -0
  14. package/dist/auth/index.js +2 -1
  15. package/dist/auth/oauth/index.d.ts +7 -0
  16. package/dist/{auth-Jp_MB8Il.js → auth-vFeem6uM.js} +8 -298
  17. package/dist/authorization/index.js +2 -1
  18. package/dist/authorization-BLhwA2Yh.js +217 -0
  19. package/dist/broadcasting/index.js +1 -1
  20. package/dist/{broadcasting-DVfG2vgN.js → broadcasting-BUBCPCnu.js} +1 -1
  21. package/dist/config/define.d.ts +49 -0
  22. package/dist/config/env-reads.d.ts +12 -0
  23. package/dist/config/env.d.ts +122 -0
  24. package/dist/container/Container.d.ts +13 -2
  25. package/dist/container/ServiceProvider.d.ts +7 -0
  26. package/dist/container/bindings.d.ts +8 -0
  27. package/dist/{default-application-Chbrul_m.js → default-application-D5ezhhiV.js} +18 -1
  28. package/dist/encryption/index.js +1 -1
  29. package/dist/{encryption-BRjZnshr.js → encryption-D1dxfMqD.js} +1 -1
  30. package/dist/{endpoint-BXipU2Jj.js → endpoint-CTIzcagh.js} +1 -1
  31. package/dist/{endpoint-Dsw3Acvq.js → endpoint-Coq0K_6I.js} +1 -1
  32. package/dist/events/index.js +1 -1
  33. package/dist/{events-CaJKZ2qk.js → events-c94CdUFc.js} +1 -1
  34. package/dist/http/Application.d.ts +22 -0
  35. package/dist/http/vite-manifest.d.ts +5 -1
  36. package/dist/i18n/index.js +1 -1
  37. package/dist/i18n/injected-translations.d.ts +8 -0
  38. package/dist/i18n/loaders/JsonLoader.d.ts +3 -2
  39. package/dist/{i18n-DRo1g0AN.js → i18n-DqcRD4qL.js} +4 -3
  40. package/dist/index.d.ts +11 -0
  41. package/dist/index.js +525 -1075
  42. package/dist/inertia-defaults-BjrcT7za.js +30 -0
  43. package/dist/internal/request.d.ts +4 -3
  44. package/dist/internal/request.js +2 -1
  45. package/dist/internal/testing.d.ts +17 -0
  46. package/dist/internal/testing.js +6 -0
  47. package/dist/lambda/index.js +1 -1
  48. package/dist/logging/index.js +2 -1
  49. package/dist/{logging-CXotojgW.js → logging-YbKmbAd7.js} +3 -113
  50. package/dist/loopback-guard-CG8xB4v0.js +68 -0
  51. package/dist/mail/index.js +1 -1
  52. package/dist/{mail-zMjQimaJ.js → mail-uRBrUl9q.js} +3 -2
  53. package/dist/mcp/McpServiceProvider.d.ts +21 -4
  54. package/dist/mcp/endpoint.d.ts +3 -3
  55. package/dist/mcp/index.d.ts +0 -2
  56. package/dist/mcp/index.js +2 -2
  57. package/dist/mvc/Controller.d.ts +11 -1
  58. package/dist/mvc/Router.d.ts +6 -0
  59. package/dist/mvc/inertia/InertiaEngine.d.ts +2 -0
  60. package/dist/mvc/validated-input.d.ts +55 -0
  61. package/dist/notifications/index.js +1 -1
  62. package/dist/{notifications-BLid0Y6M.js → notifications-LHuujttf.js} +2 -2
  63. package/dist/providers/ConfigServiceProvider.d.ts +19 -0
  64. package/dist/queue/index.js +2 -2
  65. package/dist/{queue-IdJjqbyJ.js → queue-BiBn5Sff.js} +1 -1
  66. package/dist/resolve-optional-ax6gPWTp.js +9 -0
  67. package/dist/runtime/index.js +2 -1
  68. package/dist/validated-input-D84J8wcC.js +25 -0
  69. package/dist/{vite-manifest-DeWRFXTm.js → vite-manifest-C5kqRoBV.js} +7 -32
  70. package/package.json +6 -3
  71. package/dist/McpServiceProvider-BvJRcDOm.js +0 -458
  72. package/dist/mcp/create-mcp-server.d.ts +0 -180
@@ -1,10 +1,11 @@
1
1
  import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
2
2
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
3
- import { a as setResolvedPrincipal, i as getResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-af2n5abO.js";
3
+ import { a as setResolvedPrincipal, i as getResolvedPrincipal, o as AuthenticationException, r as getAuthContext } from "./context-af2n5abO.js";
4
4
  import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
5
- import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
5
+ import { C as secureCompare, S as parseTokenUrl, _ as verifyApiToken, b as generateToken, c as hasBearerHeader, l as parseApiToken, p as revokePresentedToken, t as API_TOKEN_KEY, u as readBearerToken, v as buildTokenUrl, w as secureStringCompare, x as hashToken, y as generateId } from "./api-token-BbgDEd6j.js";
6
+ import { isExpired } from "./support/expiry.js";
6
7
  import { deleteCookie, getCookie, setCookie } from "hono/cookie";
7
- import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
8
+ import { createHmac, timingSafeEqual } from "node:crypto";
8
9
  import { Model } from "@guren/orm";
9
10
  //#region src/http/middleware/session.ts
10
11
  var MemorySessionStore = class {
@@ -862,58 +863,6 @@ var ModelUserProvider = class extends BaseUserProvider {
862
863
  }
863
864
  };
864
865
  //#endregion
865
- //#region src/auth/utils.ts
866
- function hashToken(token, algorithm = "sha256") {
867
- return createHash(algorithm).update(token).digest("hex");
868
- }
869
- function generateToken(length = 32) {
870
- return randomBytes(length).toString("hex");
871
- }
872
- /** Generate a random ID (16 bytes = 32 hex chars). */
873
- function generateId() {
874
- return randomBytes(16).toString("hex");
875
- }
876
- /**
877
- * Timing-safe comparison of two hex strings. Non-hex or odd-length input is
878
- * rejected rather than compared: `Buffer.from(x, 'hex')` stops at the first
879
- * invalid pair, so 'zzzz' and 'yyyy' would both decode to nothing and compare
880
- * equal. Use `secureStringCompare` for values that are not hex.
881
- */
882
- function secureCompare(a, b) {
883
- if (a.length !== b.length) return false;
884
- const bufA = Buffer.from(a, "hex");
885
- const bufB = Buffer.from(b, "hex");
886
- if (bufA.length !== a.length / 2 || bufB.length !== b.length / 2) return false;
887
- return timingSafeEqual(bufA, bufB);
888
- }
889
- /** Timing-safe comparison for arbitrary strings — unlike secureCompare, not hex-only. */
890
- function secureStringCompare(a, b) {
891
- const bufA = Buffer.from(a, "utf8");
892
- const bufB = Buffer.from(b, "utf8");
893
- if (bufA.length !== bufB.length) return false;
894
- return timingSafeEqual(bufA, bufB);
895
- }
896
- function buildTokenUrl(baseUrl, token, email) {
897
- const url = new URL(baseUrl);
898
- url.searchParams.set("token", token);
899
- if (email) url.searchParams.set("email", email);
900
- return url.toString();
901
- }
902
- function parseTokenUrl(url) {
903
- try {
904
- const parsed = new URL(url);
905
- return {
906
- token: parsed.searchParams.get("token"),
907
- email: parsed.searchParams.get("email")
908
- };
909
- } catch {
910
- return {
911
- token: null,
912
- email: null
913
- };
914
- }
915
- }
916
- //#endregion
917
866
  //#region src/auth/SessionGuard.ts
918
867
  const DEFAULT_SESSION_KEY = "auth:user_id";
919
868
  const DEFAULT_REMEMBER_KEY = "auth:remember_token";
@@ -1051,248 +1000,6 @@ var SessionGuard = class {
1051
1000
  }
1052
1001
  };
1053
1002
  //#endregion
1054
- //#region src/auth/api-token.ts
1055
- /**
1056
- * In-memory token store for testing.
1057
- * Do NOT use in production - tokens will be lost on restart.
1058
- */
1059
- var MemoryApiTokenStore = class {
1060
- tokens = /* @__PURE__ */ new Map();
1061
- byHash = /* @__PURE__ */ new Map();
1062
- async store(token) {
1063
- this.tokens.set(token.id, token);
1064
- this.byHash.set(token.hashedToken, token.id);
1065
- }
1066
- async findByHashedToken(hashedToken) {
1067
- const id = this.byHash.get(hashedToken);
1068
- if (!id) return null;
1069
- return this.tokens.get(id) ?? null;
1070
- }
1071
- async findByUserId(userId) {
1072
- const userIdStr = String(userId);
1073
- return Array.from(this.tokens.values()).filter((t) => String(t.userId) === userIdStr);
1074
- }
1075
- async delete(id) {
1076
- const token = this.tokens.get(id);
1077
- if (token) {
1078
- this.byHash.delete(token.hashedToken);
1079
- this.tokens.delete(id);
1080
- }
1081
- }
1082
- async deleteForUser(userId) {
1083
- const userIdStr = String(userId);
1084
- for (const [id, token] of this.tokens.entries()) if (String(token.userId) === userIdStr) {
1085
- this.byHash.delete(token.hashedToken);
1086
- this.tokens.delete(id);
1087
- }
1088
- }
1089
- async updateLastUsed(id, timestamp) {
1090
- const token = this.tokens.get(id);
1091
- if (token) token.lastUsedAt = timestamp;
1092
- }
1093
- clear() {
1094
- this.tokens.clear();
1095
- this.byHash.clear();
1096
- }
1097
- get size() {
1098
- return this.tokens.size;
1099
- }
1100
- };
1101
- /**
1102
- * Create a new API token.
1103
- */
1104
- async function createApiToken(store, options) {
1105
- const { name, userId, abilities = ["*"], expiresIn = null, tokenLength = 32 } = options;
1106
- const id = generateId();
1107
- const plainToken = generateToken(tokenLength);
1108
- const hashedToken = hashToken(plainToken);
1109
- const now = /* @__PURE__ */ new Date();
1110
- const token = {
1111
- id,
1112
- name,
1113
- hashedToken,
1114
- userId,
1115
- abilities,
1116
- lastUsedAt: null,
1117
- expiresAt: expiresIn == null ? null : new Date(now.getTime() + expiresIn),
1118
- createdAt: now
1119
- };
1120
- await store.store(token);
1121
- return {
1122
- plainTextToken: `${id}|${plainToken}`,
1123
- token
1124
- };
1125
- }
1126
- /**
1127
- * Parse a plain text token into its components.
1128
- */
1129
- function parseApiToken(plainTextToken) {
1130
- const parts = plainTextToken.split("|");
1131
- if (parts.length !== 2) return null;
1132
- const [id, token] = parts;
1133
- if (!id || !token) return null;
1134
- return {
1135
- id,
1136
- token
1137
- };
1138
- }
1139
- /**
1140
- * Extract the bearer token from an Authorization header. The one parsing rule
1141
- * shared by `createBearerTokenMiddleware`, `TokenGuard` and `hasBearerHeader`.
1142
- * `\S` keeps the match linear — `\s+(.+)` backtracks quadratically when a
1143
- * trailing newline makes `$` unreachable, on a pre-authentication header — and
1144
- * makes an all-whitespace token "not a bearer request", so CSRF is not skipped.
1145
- */
1146
- function readBearerToken(header) {
1147
- if (!header) return null;
1148
- const match = header.match(/^Bearer\s+(\S.*)$/i);
1149
- return match ? match[1] : null;
1150
- }
1151
- /**
1152
- * The one answer to "is this request bearer-authenticated?", shared by
1153
- * `AuthManager.resolveGuardName` and the CSRF skip for cookie-less bearer
1154
- * requests, which must classify a request identically.
1155
- */
1156
- function hasBearerHeader(ctx) {
1157
- return readBearerToken(ctx.req.header("Authorization")) !== null;
1158
- }
1159
- /**
1160
- * Verify an API token and return the associated user ID.
1161
- */
1162
- async function verifyApiToken(plainTextToken, store, options = {}) {
1163
- const { updateLastUsed = true } = options;
1164
- const parsed = parseApiToken(plainTextToken);
1165
- if (!parsed) return null;
1166
- const hashedToken = hashToken(parsed.token);
1167
- const token = await store.findByHashedToken(hashedToken);
1168
- if (!token) return null;
1169
- if (token.id !== parsed.id) return null;
1170
- if (isOptionalExpiryPast(token.expiresAt)) return null;
1171
- if (!secureCompare(token.hashedToken, hashedToken)) return null;
1172
- if (updateLastUsed) await store.updateLastUsed(token.id, /* @__PURE__ */ new Date());
1173
- return {
1174
- token,
1175
- userId: token.userId,
1176
- abilities: token.abilities
1177
- };
1178
- }
1179
- /**
1180
- * Check if a token has a specific ability.
1181
- */
1182
- function tokenCan(token, ability) {
1183
- if (token.abilities.includes("*")) return true;
1184
- return token.abilities.includes(ability);
1185
- }
1186
- /**
1187
- * Check if a token has all specified abilities.
1188
- */
1189
- function tokenCanAll(token, abilities) {
1190
- if (token.abilities.includes("*")) return true;
1191
- return abilities.every((ability) => token.abilities.includes(ability));
1192
- }
1193
- /**
1194
- * Check if a token has any of the specified abilities.
1195
- */
1196
- function tokenCanAny(token, abilities) {
1197
- if (token.abilities.includes("*")) return true;
1198
- return abilities.some((ability) => token.abilities.includes(ability));
1199
- }
1200
- /**
1201
- * Revoke (delete) an API token.
1202
- */
1203
- async function revokeApiToken(id, store) {
1204
- await store.delete(id);
1205
- }
1206
- /**
1207
- * Revoke all API tokens for a user.
1208
- */
1209
- async function revokeAllApiTokens(userId, store) {
1210
- await store.deleteForUser(userId);
1211
- }
1212
- /**
1213
- * Get all API tokens for a user.
1214
- */
1215
- async function getUserApiTokens(userId, store) {
1216
- return store.findByUserId(userId);
1217
- }
1218
- /**
1219
- * Context key for storing the authenticated token.
1220
- */
1221
- const API_TOKEN_KEY = "guren:api-token";
1222
- /**
1223
- * Revoke the token a request presented, and clear it from the request context
1224
- * so `getApiToken()` / `getApiTokenOrFail()` cannot succeed after a logout on
1225
- * the same request. The slot is cleared whether or not a token still verified.
1226
- */
1227
- async function revokePresentedToken(ctx, tokenId, store) {
1228
- if (tokenId) await revokeApiToken(tokenId, store);
1229
- ctx.set(API_TOKEN_KEY, void 0);
1230
- }
1231
- /**
1232
- * Create middleware that authenticates requests using Bearer tokens.
1233
- * @example
1234
- * ```ts
1235
- * app.use('/api/*', createBearerTokenMiddleware({ store, abilities: ['posts:delete'] }))
1236
- * ```
1237
- */
1238
- function createBearerTokenMiddleware(options) {
1239
- const { store, loadUser, abilities, onUnauthorized, onForbidden, headerName = "Authorization", updateLastUsed = true } = options;
1240
- return async (ctx, next) => {
1241
- const authHeader = ctx.req.header(headerName);
1242
- if (!authHeader) {
1243
- if (onUnauthorized) return onUnauthorized(ctx);
1244
- return ctx.json({ error: "Authentication required" }, 401);
1245
- }
1246
- const plainTextToken = readBearerToken(authHeader);
1247
- if (!plainTextToken) {
1248
- if (onUnauthorized) return onUnauthorized(ctx);
1249
- return ctx.json({ error: "Invalid authorization format" }, 401);
1250
- }
1251
- const result = await verifyApiToken(plainTextToken, store, { updateLastUsed });
1252
- if (!result) {
1253
- if (onUnauthorized) return onUnauthorized(ctx);
1254
- return ctx.json({ error: "Invalid or expired token" }, 401);
1255
- }
1256
- if (abilities && abilities.length > 0) {
1257
- if (!tokenCanAll(result.token, abilities)) {
1258
- if (onForbidden) return onForbidden(ctx, abilities);
1259
- return ctx.json({
1260
- error: "Token lacks required abilities",
1261
- required: abilities
1262
- }, 403);
1263
- }
1264
- }
1265
- ctx.set(API_TOKEN_KEY, result);
1266
- if (loadUser) {
1267
- const user = await loadUser(result.userId);
1268
- ctx.set("guren:user", user);
1269
- setResolvedPrincipal(ctx, {
1270
- user,
1271
- id: result.userId,
1272
- revoke: () => revokePresentedToken(ctx, result.token.id, store)
1273
- });
1274
- if (!getAuthContext(ctx)) ctx.set(AUTH_CONTEXT_KEY, createPrincipalAuthContext(ctx));
1275
- }
1276
- return next();
1277
- };
1278
- }
1279
- /**
1280
- * Get the authenticated API token from the request context.
1281
- */
1282
- function getApiToken(ctx) {
1283
- return ctx.get(API_TOKEN_KEY);
1284
- }
1285
- /**
1286
- * Get the authenticated API token from the request context, or throw.
1287
- *
1288
- * @throws {AuthenticationException} When no token is present in the context.
1289
- */
1290
- function getApiTokenOrFail(ctx) {
1291
- const result = getApiToken(ctx);
1292
- if (!result) throw new AuthenticationException("Unauthenticated.");
1293
- return result;
1294
- }
1295
- //#endregion
1296
1003
  //#region src/auth/TokenGuard.ts
1297
1004
  /**
1298
1005
  * Bearer-token Guard (RFC 0016 Phase 0). Credential flows (`attempt`,
@@ -1729,6 +1436,9 @@ var OAuthManager = class {
1729
1436
  providerNames() {
1730
1437
  return Array.from(this.providers.keys()).sort((a, b) => a.localeCompare(b));
1731
1438
  }
1439
+ async pruneExpiredStates(now = /* @__PURE__ */ new Date()) {
1440
+ await this.stateStore.deleteExpired?.(now);
1441
+ }
1732
1442
  getProvider(name) {
1733
1443
  const provider = this.providers.get(name);
1734
1444
  if (!provider) throw new AuthenticationException(`OAuth provider "${name}" is not configured.`);
@@ -2292,4 +2002,4 @@ function requireVerifiedEmail(options = {}) {
2292
2002
  };
2293
2003
  }
2294
2004
  //#endregion
2295
- export { SessionGuard as $, verifyOAuthState as A, createBearerTokenMiddleware as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, DEFAULT_PROVIDER as F, parseApiToken as G, getApiTokenOrFail as H, TokenGuard as I, revokeApiToken as J, readBearerToken as K, API_TOKEN_KEY as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, verifyApiToken as Q, MemoryApiTokenStore as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, getUserApiTokens as U, getApiToken as V, hasBearerHeader as W, tokenCanAll as X, tokenCan as Y, tokenCanAny as Z, OAUTH_SESSION_BINDING_KEY as _, getSessionFromContext as _t, isEmailVerified as a, secureCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c, DefaultHasher as ct, completePasswordReset as d, BaseUserProvider as dt, buildTokenUrl as et, createPasswordResetToken as f, installAgentPrincipal as ft, MemoryOAuthStateStore as g, defaultCookieSecure as gt, AuthenticatableModel as h, createSessionMiddleware as ht, createEmailVerificationToken as i, parseTokenUrl as it, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, NodeHasher as lt, verifyPasswordResetToken as m, MemorySessionStore as mt, buildVerificationUrl as n, generateToken as nt, parseVerificationUrl as o, secureStringCompare as ot, parsePasswordResetUrl as p, readAgentPrincipal as pt, revokeAllApiTokens as q, completeEmailVerification as r, hashToken as rt, requireVerifiedEmail as s, ModelUserProvider as st, MemoryEmailVerificationStore as t, generateId as tt, buildPasswordResetUrl as u, ScryptHasher as ut, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, createApiToken as z };
2005
+ export { verifyOAuthState as A, NodeHasher as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, DEFAULT_PROVIDER as F, MemorySessionStore as G, BaseUserProvider as H, TokenGuard as I, getSessionFromContext as J, createSessionMiddleware as K, SessionGuard as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, ModelUserProvider as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, installAgentPrincipal as U, ScryptHasher as V, readAgentPrincipal as W, OAUTH_SESSION_BINDING_KEY as _, isEmailVerified as a, buildOAuthRedirectUrl as b, verifyEmailToken as c, completePasswordReset as d, createPasswordResetToken as f, MemoryOAuthStateStore as g, AuthenticatableModel as h, createEmailVerificationToken as i, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, verifyPasswordResetToken as m, buildVerificationUrl as n, parseVerificationUrl as o, parsePasswordResetUrl as p, defaultCookieSecure as q, completeEmailVerification as r, requireVerifiedEmail as s, MemoryEmailVerificationStore as t, buildPasswordResetUrl as u, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, DefaultHasher as z };
@@ -1,2 +1,3 @@
1
- import { a as withAuthorization, c as Gate, d as can, f as cannot, g as isAuthorizationResponse, h as getGate, l as Response, m as defineGate, n as authorizeMiddleware, o as Policy, p as createGate, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as authorize, v as setGate } from "../authorization-0mCGUFoI.js";
1
+ import { a as withAuthorization, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware } from "../authorization-BLhwA2Yh.js";
2
+ import { a as cannot, f as setGate, i as can, l as getGate, n as Response, o as createGate, r as authorize, s as defineGate, t as Gate, u as isAuthorizationResponse } from "../Gate-YOt54xGF.js";
2
3
  export { Gate, Policy, Response, authorize, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, can, cannot, createGate, defineGate, definePolicy, getGate, isAuthorizationResponse, setGate, withAuthorization };
@@ -0,0 +1,217 @@
1
+ import { c as denialToException, d as resolveGate, g as tryGetRequestContainer, n as Response, p as AuthorizationException } from "./Gate-YOt54xGF.js";
2
+ //#region src/http/middleware/capabilities.ts
3
+ /**
4
+ * Internal security-capability marker (RFC 0007): built-in middleware
5
+ * factories stamp their handlers so tooling can read what a chain enforces
6
+ * without name heuristics. `Symbol.for()` keeps the key identical across
7
+ * duplicated `@guren/server` copies in one process. Not public API — the
8
+ * shape may change in any release.
9
+ */
10
+ const CAPABILITIES = Symbol.for("guren.capabilities");
11
+ /**
12
+ * Folds one middleware's stamp into an accumulating aggregate. Mutates `into`
13
+ * and never `stamp`. Every call counts as an independent check, so folding the
14
+ * *same* stamp twice degrades an `'any'` to `'mixed'` — de-duplicating handlers
15
+ * that appear more than once in a chain is the caller's job.
16
+ */
17
+ function mergeCapabilities(into, stamp) {
18
+ const auth = stamp.authentication;
19
+ if (auth && (!into.authentication || auth.mode === "required")) into.authentication = { ...auth };
20
+ const authz = stamp.authorization;
21
+ if (!authz) return;
22
+ const current = into.authorization;
23
+ if (!current) {
24
+ into.authorization = {
25
+ abilities: [...authz.abilities],
26
+ mode: authz.mode,
27
+ ...authz.resource ? { resource: { ...authz.resource } } : {}
28
+ };
29
+ return;
30
+ }
31
+ for (const ability of authz.abilities) if (!current.abilities.includes(ability)) current.abilities.push(ability);
32
+ current.mode = current.mode === "all" && authz.mode === "all" ? "all" : "mixed";
33
+ if (authz.resource) current.resource = { fromMethodMap: (current.resource?.fromMethodMap ?? true) && authz.resource.fromMethodMap };
34
+ }
35
+ function stampCapabilities(handler, capabilities) {
36
+ Object.defineProperty(handler, CAPABILITIES, {
37
+ value: capabilities,
38
+ enumerable: false
39
+ });
40
+ return handler;
41
+ }
42
+ function capabilitiesOf(handler) {
43
+ if (typeof handler !== "function") return void 0;
44
+ return handler[CAPABILITIES];
45
+ }
46
+ //#endregion
47
+ //#region src/authorization/Policy.ts
48
+ /**
49
+ * Base policy class for model authorization. Ability methods are looked up on
50
+ * the subclass by name (`viewAny`, `view`, `create`, `update`, `delete`,
51
+ * `restore`, `forceDelete`, or any custom ability), each taking
52
+ * `(user, model?, ...args)`.
53
+ */
54
+ var Policy = class {
55
+ allow(message) {
56
+ return Response.allow(message);
57
+ }
58
+ deny(message, code) {
59
+ return Response.deny(message, code);
60
+ }
61
+ denyWithStatus(status, message) {
62
+ return Response.denyWithStatus(status, message);
63
+ }
64
+ denyAsNotFound(message) {
65
+ return Response.denyAsNotFound(message);
66
+ }
67
+ };
68
+ /** Create a policy class from an object of ability functions. */
69
+ function definePolicy(definition) {
70
+ return class extends Policy {
71
+ before = definition.before;
72
+ viewAny(user) {
73
+ return definition.viewAny?.(user) ?? false;
74
+ }
75
+ view(user, model) {
76
+ return definition.view?.(user, model) ?? false;
77
+ }
78
+ create(user) {
79
+ return definition.create?.(user) ?? false;
80
+ }
81
+ update(user, model) {
82
+ return definition.update?.(user, model) ?? false;
83
+ }
84
+ delete(user, model) {
85
+ return definition.delete?.(user, model) ?? false;
86
+ }
87
+ restore(user, model) {
88
+ return definition.restore?.(user, model) ?? false;
89
+ }
90
+ forceDelete(user, model) {
91
+ return definition.forceDelete?.(user, model) ?? false;
92
+ }
93
+ };
94
+ }
95
+ //#endregion
96
+ //#region src/authorization/middleware.ts
97
+ /** The gate of the app serving `ctx` (RFC 0023 §2); the ambient one on a bare Hono app. */
98
+ function gateFor(ctx) {
99
+ return tryGetRequestContainer(ctx)?.makeOptional("gate") ?? resolveGate();
100
+ }
101
+ /**
102
+ * Middleware to authorize an ability. An array argument is snapshotted at
103
+ * creation, and a one-element array behaves exactly like the bare ability.
104
+ * An empty array denies every request (`Gate.any([])` is false) — fail-closed,
105
+ * so it is left to run rather than rejected.
106
+ */
107
+ function authorizeMiddleware(ability, modelResolver, options = {}) {
108
+ const abilities = Array.isArray(ability) ? [...ability] : [ability];
109
+ const anyOf = abilities.length !== 1;
110
+ return stampCapabilities(async (ctx, next) => {
111
+ const gate = gateFor(ctx);
112
+ const user = await gate.resolveUser(ctx);
113
+ const gateForUser = gate.forUser(user);
114
+ const model = modelResolver ? await modelResolver(ctx) : void 0;
115
+ if (anyOf) {
116
+ if (!await gateForUser.any(abilities, model)) throw new AuthorizationException(options.message ?? "This action is unauthorized.");
117
+ } else {
118
+ const response = await gateForUser.checkResponse(abilities[0], user, model);
119
+ if (!response.allowed) throw denialToException(options.message ? {
120
+ ...response,
121
+ message: options.message
122
+ } : response);
123
+ }
124
+ await next();
125
+ }, { authorization: {
126
+ abilities,
127
+ mode: anyOf ? "any" : "all"
128
+ } });
129
+ }
130
+ /**
131
+ * Middleware to authorize all given abilities. The array is snapshotted at creation.
132
+ *
133
+ * @throws if no ability is given: `Gate.all([])` is vacuously true, so an empty
134
+ * list would advertise authorization and enforce none (RFC 0016).
135
+ */
136
+ function authorizeAllMiddleware(input, modelResolver, options = {}) {
137
+ const abilities = [...input];
138
+ if (abilities.length === 0) throw new Error("authorizeAllMiddleware() requires at least one ability: an empty list authorizes every request while claiming to authorize.");
139
+ return stampCapabilities(async (ctx, next) => {
140
+ const gate = gateFor(ctx);
141
+ const user = await gate.resolveUser(ctx);
142
+ const gateForUser = gate.forUser(user);
143
+ const model = modelResolver ? await modelResolver(ctx) : void 0;
144
+ if (!await gateForUser.all(abilities, model)) throw new AuthorizationException(options.message ?? "This action is unauthorized.");
145
+ await next();
146
+ }, { authorization: {
147
+ abilities,
148
+ mode: "all"
149
+ } });
150
+ }
151
+ const RESOURCE_ABILITY_BY_METHOD = {
152
+ GET: "view",
153
+ HEAD: "view",
154
+ QUERY: "view",
155
+ POST: "create",
156
+ PUT: "update",
157
+ PATCH: "update",
158
+ DELETE: "delete"
159
+ };
160
+ /**
161
+ * The single source of the verb → ability mapping; `undefined` for a method it
162
+ * refuses to guess at. A consumer resolving a route's ability from its stamped
163
+ * `authorization.resource` capability calls this rather than restating the
164
+ * table, and may only do so when `resource.fromMethodMap` is true. Internal
165
+ * contract (RFC 0007): not re-exported from the package root.
166
+ */
167
+ function resourceAbilityForMethod(method) {
168
+ return RESOURCE_ABILITY_BY_METHOD[method.toUpperCase()];
169
+ }
170
+ /**
171
+ * Maps HTTP methods to policy abilities. A method outside the built-in mapping
172
+ * (a custom verb via `router.on()`) is denied with a 403 rather than downgraded
173
+ * to `view`: guessing would let a view-only user reach a mutating handler. Map
174
+ * custom verbs explicitly with `options.abilityFor`.
175
+ */
176
+ function authorizeResourceMiddleware(modelResolver, options = {}) {
177
+ const abilityFor = options.abilityFor;
178
+ return stampCapabilities(async (ctx, next) => {
179
+ const method = ctx.req.method.toUpperCase();
180
+ const ability = abilityFor?.(method) ?? resourceAbilityForMethod(method);
181
+ if (ability === void 0) throw new AuthorizationException(options.message ?? "This action is unauthorized.");
182
+ const gate = gateFor(ctx);
183
+ const user = await gate.resolveUser(ctx);
184
+ const gateForUser = gate.forUser(user);
185
+ const model = await modelResolver(ctx);
186
+ const response = await gateForUser.checkResponse(ability, user, model);
187
+ if (!response.allowed) throw denialToException(options.message ? {
188
+ ...response,
189
+ message: options.message
190
+ } : response);
191
+ await next();
192
+ }, { authorization: {
193
+ abilities: [],
194
+ mode: "all",
195
+ resource: { fromMethodMap: abilityFor === void 0 }
196
+ } });
197
+ }
198
+ /** Create a gate-aware context with authorization helpers. */
199
+ function withAuthorization(gate) {
200
+ return async (ctx, next) => {
201
+ const user = await gate.resolveUser(ctx);
202
+ const gateForUser = gate.forUser(user);
203
+ ctx.set("gate", gateForUser);
204
+ ctx.set("can", async (ability, ...args) => {
205
+ return gateForUser.allows(ability, ...args);
206
+ });
207
+ ctx.set("cannot", async (ability, ...args) => {
208
+ return gateForUser.denies(ability, ...args);
209
+ });
210
+ ctx.set("authorize", async (ability, ...args) => {
211
+ return gateForUser.authorize(ability, ...args);
212
+ });
213
+ await next();
214
+ };
215
+ }
216
+ //#endregion
217
+ export { withAuthorization as a, capabilitiesOf as c, resourceAbilityForMethod as i, mergeCapabilities as l, authorizeMiddleware as n, Policy as o, authorizeResourceMiddleware as r, definePolicy as s, authorizeAllMiddleware as t, stampCapabilities as u };
@@ -1,2 +1,2 @@
1
- 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-DVfG2vgN.js";
1
+ 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-BUBCPCnu.js";
2
2
  export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
@@ -1,5 +1,5 @@
1
1
  import { a as parseRequestPayload } from "./request-CLOYytGP.js";
2
- import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-Chbrul_m.js";
2
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-D5ezhhiV.js";
3
3
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
4
4
  import { c as randomHex } from "./Random-S0OvCuR8.js";
5
5
  //#region src/broadcasting/channels/Channel.ts
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Configuration as data (RFC 0027 §2). A definition resolves its config from the
3
+ * validated env and binds the manager that config builds; ConfigServiceProvider
4
+ * runs `bind` in its register() and `boot` in its boot(), ahead of every other
5
+ * provider. Importing a definition has no side effect.
6
+ */
7
+ import type { Container } from '../container/Container.js';
8
+ import type { CacheConfig } from '../cache/types.js';
9
+ import type { MailConfig } from '../mail/types.js';
10
+ import { type QueueConfig } from '../queue/QueueManager.js';
11
+ import type { StorageConfig } from '../storage/types.js';
12
+ import { type OAuthManagerOptions, type OAuthProviderConfig } from '../auth/oauth/index.js';
13
+ import type { HostAuthorizationOptions } from '../http/middleware/host-authorization.js';
14
+ import type { AppEnv } from './env.js';
15
+ export interface HttpConfig {
16
+ /** DNS rebinding protection, mounted ahead of every app middleware. Absent or `false` disables it. */
17
+ readonly hostAuthorization?: HostAuthorizationOptions | false;
18
+ }
19
+ /** `stateStore` and `stateConfig` are the manager's own options, passed through unchanged. */
20
+ export interface OAuthConfig extends Readonly<OAuthManagerOptions> {
21
+ /** Each entry is registered with `OAuthManager.registerProvider(name, config)`. */
22
+ readonly providers?: Readonly<Record<string, OAuthProviderConfig>>;
23
+ }
24
+ /** What each key configures. Augmentable, like `SessionDrivers`: `@guren/core` adds `session` and `database`. */
25
+ export interface ConfigDefinitions {
26
+ cache: CacheConfig;
27
+ http: HttpConfig;
28
+ mail: MailConfig;
29
+ oauth: OAuthConfig;
30
+ queue: QueueConfig;
31
+ storage: StorageConfig;
32
+ }
33
+ export interface ConfigDefinition<K extends keyof ConfigDefinitions = keyof ConfigDefinitions> {
34
+ readonly key: K;
35
+ resolve(env: AppEnv): ConfigDefinitions[K];
36
+ /** Runs in ConfigServiceProvider.register(). Binds; never connects. */
37
+ bind(container: Container, config: ConfigDefinitions[K]): void;
38
+ /** Runs in ConfigServiceProvider.boot(), before every other provider's boot. */
39
+ boot?(container: Container, config: ConfigDefinitions[K], env: AppEnv): Promise<void> | void;
40
+ }
41
+ export declare function defineConfig<K extends keyof ConfigDefinitions>(definition: ConfigDefinition<K>): ConfigDefinition<K>;
42
+ type Resolve<K extends keyof ConfigDefinitions> = (env: AppEnv) => ConfigDefinitions[K];
43
+ export declare function defineCacheConfig(resolve: Resolve<'cache'>): ConfigDefinition<'cache'>;
44
+ export declare function defineHttpConfig(resolve: Resolve<'http'>): ConfigDefinition<'http'>;
45
+ export declare function defineMailConfig(resolve: Resolve<'mail'>): ConfigDefinition<'mail'>;
46
+ export declare function defineOAuthConfig(resolve: Resolve<'oauth'>): ConfigDefinition<'oauth'>;
47
+ export declare function defineQueueConfig(resolve: Resolve<'queue'>): ConfigDefinition<'queue'>;
48
+ export declare function defineStorageConfig(resolve: Resolve<'storage'>): ConfigDefinition<'storage'>;
49
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Which environment keys a definition's `resolve()` read (RFC 0027 §2).
3
+ * ConfigServiceProvider leaves a definition unbound when it read a key the
4
+ * environment does not set, rather than handing a manager the redacted
5
+ * placeholder; the CLI reads the same record to know which config it may trust.
6
+ */
7
+ export interface RecordedEnv<T> {
8
+ readonly env: T;
9
+ /** Filled while `resolve()` runs, so read it after the call. */
10
+ readonly read: ReadonlySet<string>;
11
+ }
12
+ export declare function recordEnvReads<T extends object>(values: T): RecordedEnv<T>;