@guren/server 2.13.0 → 2.14.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/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
- package/dist/agent/derive.d.ts +155 -0
- package/dist/agent/dispatch.d.ts +123 -0
- package/dist/agent/events.d.ts +80 -0
- package/dist/agent/redact.d.ts +55 -0
- package/dist/agent/scopes.d.ts +115 -0
- package/dist/auth/AuthManager.d.ts +64 -0
- package/dist/auth/RequestAuthContext.d.ts +3 -5
- package/dist/auth/TokenGuard.d.ts +61 -0
- package/dist/auth/api-token.d.ts +25 -5
- package/dist/auth/context.d.ts +24 -0
- package/dist/auth/index.d.ts +5 -2
- package/dist/auth/index.js +2 -2
- package/dist/auth/providers/UserProvider.d.ts +7 -0
- package/dist/auth/types.d.ts +6 -0
- package/dist/{auth-C7sVmYgc.js → auth-BSUc14CD.js} +313 -122
- package/dist/authorization/index.js +1 -1
- package/dist/authorization/middleware.d.ts +28 -1
- package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
- package/dist/broadcasting/index.js +1 -1
- package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BxU-LIfF.js} +2 -45
- package/dist/context-DoD0c7J_.js +26 -0
- package/dist/http/middleware/auth.d.ts +2 -2
- package/dist/http/middleware/capabilities.d.ts +57 -0
- package/dist/http/middleware/csrf.d.ts +3 -0
- package/dist/http/request.d.ts +51 -2
- package/dist/index.d.ts +12 -3
- package/dist/index.js +1015 -84
- package/dist/internal/agent-preflight.d.ts +28 -0
- package/dist/internal/request.d.ts +19 -0
- package/dist/internal/request.js +2 -0
- package/dist/internal/route-path.d.ts +28 -0
- package/dist/internal/route-path.js +33 -0
- package/dist/internal/zod-compat.d.ts +201 -0
- package/dist/internal/zod-compat.js +193 -0
- package/dist/internal/zod-json-schema.d.ts +102 -0
- package/dist/internal/zod-json-schema.js +461 -0
- package/dist/mcp/create-mcp-server.d.ts +29 -0
- package/dist/mcp/index.js +1 -1
- package/dist/mvc/Controller.d.ts +46 -0
- package/dist/mvc/Router.d.ts +53 -0
- package/dist/request-CRVuIiQr.js +78 -0
- package/dist/runtime/index.js +5 -2
- package/dist/{vite-manifest-gdONBsM3.js → vite-manifest-BGfWbPYp.js} +1 -1
- package/package.json +17 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { t as HttpException } from "./HttpException-BkS3euNG.js";
|
|
2
2
|
import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
|
|
3
|
-
import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-CzrwKeDp.js";
|
|
4
3
|
import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
|
|
4
|
+
import { n as getAuthContext } from "./context-DoD0c7J_.js";
|
|
5
|
+
import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-CzrwKeDp.js";
|
|
5
6
|
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
6
7
|
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
7
8
|
import { Model } from "@guren/orm";
|
|
@@ -323,23 +324,20 @@ var AuthenticationException = class AuthenticationException extends HttpExceptio
|
|
|
323
324
|
//#endregion
|
|
324
325
|
//#region src/auth/RequestAuthContext.ts
|
|
325
326
|
var RequestAuthContext = class {
|
|
326
|
-
|
|
327
|
+
resolveName;
|
|
327
328
|
ctx;
|
|
328
329
|
resolveSession;
|
|
329
330
|
resolveGuard;
|
|
330
331
|
guardCache = /* @__PURE__ */ new Map();
|
|
331
|
-
constructor(
|
|
332
|
-
this.
|
|
332
|
+
constructor(resolveName, ctx, resolveSession, resolveGuard) {
|
|
333
|
+
this.resolveName = resolveName;
|
|
333
334
|
this.ctx = ctx;
|
|
334
335
|
this.resolveSession = resolveSession;
|
|
335
336
|
this.resolveGuard = resolveGuard;
|
|
336
337
|
}
|
|
337
338
|
guard(name) {
|
|
338
|
-
const key =
|
|
339
|
-
if (!this.guardCache.has(key))
|
|
340
|
-
const guard = this.resolveGuard(name);
|
|
341
|
-
this.guardCache.set(key, guard);
|
|
342
|
-
}
|
|
339
|
+
const key = this.resolveName(name);
|
|
340
|
+
if (!this.guardCache.has(key)) this.guardCache.set(key, this.resolveGuard(key));
|
|
343
341
|
return this.guardCache.get(key);
|
|
344
342
|
}
|
|
345
343
|
session() {
|
|
@@ -426,6 +424,15 @@ var ScryptHasher = class {
|
|
|
426
424
|
};
|
|
427
425
|
//#endregion
|
|
428
426
|
//#region src/auth/providers/UserProvider.ts
|
|
427
|
+
/**
|
|
428
|
+
* Run a user record through the provider's optional `sanitize` before it
|
|
429
|
+
* leaves the auth layer. Every guard must call this on anything it returns
|
|
430
|
+
* from `user()` — a guard that forgets the optional-chaining ternary leaks
|
|
431
|
+
* password hashes, so the ternary lives here, once.
|
|
432
|
+
*/
|
|
433
|
+
function sanitizeUser(provider, user) {
|
|
434
|
+
return provider.sanitize ? provider.sanitize(user) : user;
|
|
435
|
+
}
|
|
429
436
|
var BaseUserProvider = class {
|
|
430
437
|
async setRememberToken(user, token) {
|
|
431
438
|
if (typeof user.setRememberToken === "function") await user.setRememberToken(token);
|
|
@@ -645,7 +652,7 @@ var SessionGuard = class {
|
|
|
645
652
|
}
|
|
646
653
|
/** Strip auth-internal fields before a record is cached or exposed. */
|
|
647
654
|
sanitizeUser(user) {
|
|
648
|
-
return this.provider
|
|
655
|
+
return sanitizeUser(this.provider, user);
|
|
649
656
|
}
|
|
650
657
|
async resolveUser() {
|
|
651
658
|
if (this.cachedUser !== void 0) return this.cachedUser;
|
|
@@ -728,113 +735,6 @@ var SessionGuard = class {
|
|
|
728
735
|
}
|
|
729
736
|
};
|
|
730
737
|
//#endregion
|
|
731
|
-
//#region src/auth/AuthManager.ts
|
|
732
|
-
const DEFAULT_GUARD = "web";
|
|
733
|
-
var AuthManager = class {
|
|
734
|
-
guards = /* @__PURE__ */ new Map();
|
|
735
|
-
providers = /* @__PURE__ */ new Map();
|
|
736
|
-
defaultGuard;
|
|
737
|
-
constructor(options = {}) {
|
|
738
|
-
this.defaultGuard = options.defaultGuard ?? DEFAULT_GUARD;
|
|
739
|
-
}
|
|
740
|
-
registerGuard(name, factory) {
|
|
741
|
-
this.guards.set(name, { factory });
|
|
742
|
-
}
|
|
743
|
-
registerProvider(name, factory) {
|
|
744
|
-
this.providers.set(name, { factory });
|
|
745
|
-
}
|
|
746
|
-
getProvider(name) {
|
|
747
|
-
const entry = this.providers.get(name);
|
|
748
|
-
if (!entry) throw new Error(`AuthManager: provider "${name}" has not been registered.`);
|
|
749
|
-
if (!entry.instance) {
|
|
750
|
-
entry.instance = entry.factory(this);
|
|
751
|
-
this.providers.set(name, entry);
|
|
752
|
-
}
|
|
753
|
-
return entry.instance;
|
|
754
|
-
}
|
|
755
|
-
createGuard(name, context) {
|
|
756
|
-
const entry = this.guards.get(name);
|
|
757
|
-
if (!entry) throw new Error(`AuthManager: guard "${name}" has not been registered.`);
|
|
758
|
-
return entry.factory(context);
|
|
759
|
-
}
|
|
760
|
-
guardNames() {
|
|
761
|
-
return Array.from(this.guards.keys());
|
|
762
|
-
}
|
|
763
|
-
setDefaultGuard(name) {
|
|
764
|
-
if (!this.guards.has(name)) throw new Error(`AuthManager: cannot set default guard to unregistered guard "${name}".`);
|
|
765
|
-
this.defaultGuard = name;
|
|
766
|
-
}
|
|
767
|
-
getDefaultGuard() {
|
|
768
|
-
return this.defaultGuard;
|
|
769
|
-
}
|
|
770
|
-
createAuthContext(ctx, options = {}) {
|
|
771
|
-
const guardName = options.guard ?? this.defaultGuard;
|
|
772
|
-
const resolveSession = () => getSessionFromContext(ctx);
|
|
773
|
-
const guardFactory = (name) => {
|
|
774
|
-
const targetName = name ?? guardName;
|
|
775
|
-
return this.createGuard(targetName, {
|
|
776
|
-
ctx,
|
|
777
|
-
session: resolveSession(),
|
|
778
|
-
manager: this
|
|
779
|
-
});
|
|
780
|
-
};
|
|
781
|
-
return new RequestAuthContext(this, ctx, resolveSession, guardFactory);
|
|
782
|
-
}
|
|
783
|
-
async attempt(name, ctx, credentials, remember) {
|
|
784
|
-
return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
|
|
785
|
-
}
|
|
786
|
-
/**
|
|
787
|
-
* Shorthand method to register a model-based authentication provider and session guard.
|
|
788
|
-
* This simplifies the common case of authenticating users via a database model.
|
|
789
|
-
*
|
|
790
|
-
* @param model - The model class to use for user authentication
|
|
791
|
-
* @param options - Options for the ModelUserProvider (partial, with defaults)
|
|
792
|
-
* @param providerName - Name for the provider (defaults to 'users')
|
|
793
|
-
* @param guardName - Name for the guard (defaults to 'web')
|
|
794
|
-
*/
|
|
795
|
-
useModel(model, options = {}, providerName = "users", guardName = "web") {
|
|
796
|
-
const defaultOptions = {
|
|
797
|
-
usernameColumn: "email",
|
|
798
|
-
credentialsPasswordField: "password",
|
|
799
|
-
hasher: new ScryptHasher(),
|
|
800
|
-
...options
|
|
801
|
-
};
|
|
802
|
-
this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
|
|
803
|
-
this.registerGuard(guardName, ({ session, manager }) => {
|
|
804
|
-
return new SessionGuard({
|
|
805
|
-
provider: manager.getProvider(providerName),
|
|
806
|
-
session
|
|
807
|
-
});
|
|
808
|
-
});
|
|
809
|
-
this.setDefaultGuard(guardName);
|
|
810
|
-
}
|
|
811
|
-
};
|
|
812
|
-
//#endregion
|
|
813
|
-
//#region src/support/redirect-target.ts
|
|
814
|
-
/**
|
|
815
|
-
* Shared open-redirect classification primitives, used by both the
|
|
816
|
-
* redirect-safety middleware and the OAuth `redirectTo` sanitizer. Keep every
|
|
817
|
-
* hardening fix here so the two layers cannot drift.
|
|
818
|
-
*/
|
|
819
|
-
/** Normalize backslash tricks (e.g. `/\evil.com`) before classifying. */
|
|
820
|
-
function normalizeRedirectTarget(value) {
|
|
821
|
-
return value.replace(/\\/g, "/");
|
|
822
|
-
}
|
|
823
|
-
/** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
|
|
824
|
-
function isAppRelativePath(value) {
|
|
825
|
-
return value.startsWith("/") && !value.startsWith("//");
|
|
826
|
-
}
|
|
827
|
-
/** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
|
|
828
|
-
function hostMatchesAllowlist(target, allowedHosts) {
|
|
829
|
-
const hostname = target.hostname.toLowerCase();
|
|
830
|
-
const host = target.host.toLowerCase();
|
|
831
|
-
for (const allowed of allowedHosts) if (allowed.startsWith("*.")) {
|
|
832
|
-
const suffix = allowed.slice(1).toLowerCase();
|
|
833
|
-
if (hostname.endsWith(suffix) && hostname.length > suffix.length) return true;
|
|
834
|
-
} else if (host === allowed.toLowerCase()) return true;
|
|
835
|
-
return false;
|
|
836
|
-
}
|
|
837
|
-
//#endregion
|
|
838
738
|
//#region src/auth/api-token.ts
|
|
839
739
|
/**
|
|
840
740
|
* In-memory token store for testing.
|
|
@@ -940,6 +840,27 @@ function parseApiToken(plainTextToken) {
|
|
|
940
840
|
};
|
|
941
841
|
}
|
|
942
842
|
/**
|
|
843
|
+
* Extract the bearer token from an Authorization header value. The one
|
|
844
|
+
* parsing rule shared by `createBearerTokenMiddleware`, `TokenGuard`, and
|
|
845
|
+
* `hasBearerHeader` below — three readers of the same header must not
|
|
846
|
+
* disagree about what a bearer request is.
|
|
847
|
+
*/
|
|
848
|
+
function readBearerToken(header) {
|
|
849
|
+
if (!header) return null;
|
|
850
|
+
const match = header.match(/^Bearer\s+(.+)$/i);
|
|
851
|
+
return match ? match[1] : null;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* The one answer to "is this request bearer-authenticated?" — the parsing
|
|
855
|
+
* rule above applied to the header it is read from. Shared by guard selection
|
|
856
|
+
* (`AuthManager.resolveGuardName`) and the CSRF skip for cookie-less bearer
|
|
857
|
+
* requests: both must classify a request identically, and a second copy of
|
|
858
|
+
* the header name is how they would drift apart.
|
|
859
|
+
*/
|
|
860
|
+
function hasBearerHeader(ctx) {
|
|
861
|
+
return readBearerToken(ctx.req.header("Authorization")) !== null;
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
943
864
|
* Verify an API token and return the associated user ID.
|
|
944
865
|
*
|
|
945
866
|
* @example
|
|
@@ -1061,12 +982,11 @@ function createBearerTokenMiddleware(options) {
|
|
|
1061
982
|
if (onUnauthorized) return onUnauthorized(ctx);
|
|
1062
983
|
return ctx.json({ error: "Authentication required" }, 401);
|
|
1063
984
|
}
|
|
1064
|
-
const
|
|
1065
|
-
if (!
|
|
985
|
+
const plainTextToken = readBearerToken(authHeader);
|
|
986
|
+
if (!plainTextToken) {
|
|
1066
987
|
if (onUnauthorized) return onUnauthorized(ctx);
|
|
1067
988
|
return ctx.json({ error: "Invalid authorization format" }, 401);
|
|
1068
989
|
}
|
|
1069
|
-
const plainTextToken = match[1];
|
|
1070
990
|
const result = await verifyApiToken(plainTextToken, store, { updateLastUsed });
|
|
1071
991
|
if (!result) {
|
|
1072
992
|
if (onUnauthorized) return onUnauthorized(ctx);
|
|
@@ -1122,6 +1042,277 @@ function getApiTokenOrFail(ctx) {
|
|
|
1122
1042
|
return result;
|
|
1123
1043
|
}
|
|
1124
1044
|
//#endregion
|
|
1045
|
+
//#region src/auth/TokenGuard.ts
|
|
1046
|
+
/**
|
|
1047
|
+
* Bearer-token implementation of the Guard contract (RFC 0016 Phase 0).
|
|
1048
|
+
*
|
|
1049
|
+
* Reads `Authorization: Bearer <token>`, verifies it against the configured
|
|
1050
|
+
* ApiTokenStore, and exposes the result through the same Guard surface the
|
|
1051
|
+
* SessionGuard implements — so `requireAuthenticated()`, `Controller.auth`,
|
|
1052
|
+
* and Gate resolution treat session- and token-authenticated requests
|
|
1053
|
+
* identically. On successful verification the result is also written to
|
|
1054
|
+
* `ctx[API_TOKEN_KEY]`, keeping `getApiToken(ctx)` and `tokenCan*` working
|
|
1055
|
+
* exactly as they do behind `createBearerTokenMiddleware` — and when that
|
|
1056
|
+
* middleware already verified this request's token, the guard reuses its
|
|
1057
|
+
* result instead of paying a second store read and lastUsedAt write.
|
|
1058
|
+
*
|
|
1059
|
+
* Credential flows do not apply to bearer tokens: `attempt()`, `login()` and
|
|
1060
|
+
* `validate()` throw. `logout()` is not a no-op — it revokes the presented
|
|
1061
|
+
* token, the closest meaningful analogue to ending a session. On a request
|
|
1062
|
+
* that carries a session cookie *and* a Bearer header, only the token is
|
|
1063
|
+
* revoked; end the session explicitly via `auth.guard('web').logout()`.
|
|
1064
|
+
*
|
|
1065
|
+
* This guard answers authentication only. Token *abilities* are not
|
|
1066
|
+
* consulted here or by Gate/policies — enforce them where the operation is
|
|
1067
|
+
* dispatched (`tokenCan*`, `createBearerTokenMiddleware({ abilities })`, or
|
|
1068
|
+
* the RFC 0016 scope gate), per the RFC's scope-before-policy layering.
|
|
1069
|
+
*/
|
|
1070
|
+
var TokenGuard = class {
|
|
1071
|
+
ctx;
|
|
1072
|
+
store;
|
|
1073
|
+
provider;
|
|
1074
|
+
updateLastUsed;
|
|
1075
|
+
verification;
|
|
1076
|
+
resolvedUser;
|
|
1077
|
+
constructor(options) {
|
|
1078
|
+
this.ctx = options.ctx;
|
|
1079
|
+
this.store = options.store;
|
|
1080
|
+
this.provider = options.provider;
|
|
1081
|
+
this.updateLastUsed = options.updateLastUsed ?? true;
|
|
1082
|
+
}
|
|
1083
|
+
verify() {
|
|
1084
|
+
if (!this.verification) this.verification = (async () => {
|
|
1085
|
+
const plainTextToken = readBearerToken(this.ctx.req.header("Authorization"));
|
|
1086
|
+
if (!plainTextToken) return null;
|
|
1087
|
+
const existing = this.ctx.get(API_TOKEN_KEY);
|
|
1088
|
+
if (existing && existing.token.id === parseApiToken(plainTextToken)?.id) return existing;
|
|
1089
|
+
const result = await verifyApiToken(plainTextToken, this.store, { updateLastUsed: this.updateLastUsed });
|
|
1090
|
+
if (result) this.ctx.set(API_TOKEN_KEY, result);
|
|
1091
|
+
return result;
|
|
1092
|
+
})();
|
|
1093
|
+
return this.verification;
|
|
1094
|
+
}
|
|
1095
|
+
async check() {
|
|
1096
|
+
return await this.user() !== null;
|
|
1097
|
+
}
|
|
1098
|
+
async guest() {
|
|
1099
|
+
return !await this.check();
|
|
1100
|
+
}
|
|
1101
|
+
user() {
|
|
1102
|
+
if (!this.resolvedUser) this.resolvedUser = (async () => {
|
|
1103
|
+
const result = await this.verify();
|
|
1104
|
+
if (!result) return null;
|
|
1105
|
+
if (!this.provider) return { id: result.userId };
|
|
1106
|
+
const record = await this.provider.retrieveById(result.userId);
|
|
1107
|
+
return record ? sanitizeUser(this.provider, record) : null;
|
|
1108
|
+
})();
|
|
1109
|
+
return this.resolvedUser;
|
|
1110
|
+
}
|
|
1111
|
+
async id() {
|
|
1112
|
+
return (await this.verify())?.userId ?? null;
|
|
1113
|
+
}
|
|
1114
|
+
async login() {
|
|
1115
|
+
throw new Error("TokenGuard does not support login(); issue a token with createApiToken() instead.");
|
|
1116
|
+
}
|
|
1117
|
+
async attempt(_credentials, _remember) {
|
|
1118
|
+
throw new Error("TokenGuard does not support attempt(); bearer tokens are not credential-based.");
|
|
1119
|
+
}
|
|
1120
|
+
async validate(_credentials) {
|
|
1121
|
+
throw new Error("TokenGuard does not support validate(); bearer tokens are not credential-based.");
|
|
1122
|
+
}
|
|
1123
|
+
/** Revokes the presented token. Subsequent requests with it fail verification. */
|
|
1124
|
+
async logout() {
|
|
1125
|
+
const result = await this.verify();
|
|
1126
|
+
if (result) await revokeApiToken(result.token.id, this.store);
|
|
1127
|
+
this.verification = Promise.resolve(null);
|
|
1128
|
+
this.resolvedUser = Promise.resolve(null);
|
|
1129
|
+
this.ctx.set(API_TOKEN_KEY, void 0);
|
|
1130
|
+
}
|
|
1131
|
+
session() {}
|
|
1132
|
+
};
|
|
1133
|
+
//#endregion
|
|
1134
|
+
//#region src/auth/AuthManager.ts
|
|
1135
|
+
const DEFAULT_GUARD = "web";
|
|
1136
|
+
var AuthManager = class {
|
|
1137
|
+
guards = /* @__PURE__ */ new Map();
|
|
1138
|
+
providers = /* @__PURE__ */ new Map();
|
|
1139
|
+
defaultGuard;
|
|
1140
|
+
tokenGuard = null;
|
|
1141
|
+
apiTokenStore = null;
|
|
1142
|
+
apiTokenOptions = {};
|
|
1143
|
+
constructor(options = {}) {
|
|
1144
|
+
this.defaultGuard = options.defaultGuard ?? DEFAULT_GUARD;
|
|
1145
|
+
}
|
|
1146
|
+
registerGuard(name, factory) {
|
|
1147
|
+
this.guards.set(name, { factory });
|
|
1148
|
+
}
|
|
1149
|
+
registerProvider(name, factory) {
|
|
1150
|
+
this.providers.set(name, { factory });
|
|
1151
|
+
}
|
|
1152
|
+
getProvider(name) {
|
|
1153
|
+
const entry = this.providers.get(name);
|
|
1154
|
+
if (!entry) throw new Error(`AuthManager: provider "${name}" has not been registered.`);
|
|
1155
|
+
if (!entry.instance) {
|
|
1156
|
+
entry.instance = entry.factory(this);
|
|
1157
|
+
this.providers.set(name, entry);
|
|
1158
|
+
}
|
|
1159
|
+
return entry.instance;
|
|
1160
|
+
}
|
|
1161
|
+
createGuard(name, context) {
|
|
1162
|
+
const entry = this.guards.get(name);
|
|
1163
|
+
if (!entry) throw new Error(`AuthManager: guard "${name}" has not been registered.`);
|
|
1164
|
+
return entry.factory(context);
|
|
1165
|
+
}
|
|
1166
|
+
guardNames() {
|
|
1167
|
+
return Array.from(this.guards.keys());
|
|
1168
|
+
}
|
|
1169
|
+
setDefaultGuard(name) {
|
|
1170
|
+
if (!this.guards.has(name)) throw new Error(`AuthManager: cannot set default guard to unregistered guard "${name}".`);
|
|
1171
|
+
this.defaultGuard = name;
|
|
1172
|
+
}
|
|
1173
|
+
getDefaultGuard() {
|
|
1174
|
+
return this.defaultGuard;
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* The guard name an unqualified `auth.guard()` / `auth.user()` call resolves
|
|
1178
|
+
* to for this request. Explicit names always win; otherwise a registered
|
|
1179
|
+
* token guard is selected when the request carries a Bearer Authorization
|
|
1180
|
+
* header, falling back to the default (session) guard. This is the
|
|
1181
|
+
* composite-guard rule from RFC 0016: session- and token-authenticated
|
|
1182
|
+
* requests flow through the same auth surface without configuration.
|
|
1183
|
+
*/
|
|
1184
|
+
resolveGuardName(ctx, name) {
|
|
1185
|
+
if (name) return name;
|
|
1186
|
+
if (this.tokenGuard && hasBearerHeader(ctx)) return this.tokenGuard;
|
|
1187
|
+
return this.defaultGuard;
|
|
1188
|
+
}
|
|
1189
|
+
createAuthContext(ctx, options = {}) {
|
|
1190
|
+
const resolveSession = () => getSessionFromContext(ctx);
|
|
1191
|
+
const resolveName = (name) => this.resolveGuardName(ctx, name ?? options.guard);
|
|
1192
|
+
const guardFactory = (resolvedName) => {
|
|
1193
|
+
return this.createGuard(resolvedName, {
|
|
1194
|
+
ctx,
|
|
1195
|
+
session: resolveSession(),
|
|
1196
|
+
manager: this
|
|
1197
|
+
});
|
|
1198
|
+
};
|
|
1199
|
+
return new RequestAuthContext(resolveName, ctx, resolveSession, guardFactory);
|
|
1200
|
+
}
|
|
1201
|
+
async attempt(name, ctx, credentials, remember) {
|
|
1202
|
+
return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
|
|
1203
|
+
}
|
|
1204
|
+
/**
|
|
1205
|
+
* Shorthand method to register a model-based authentication provider and session guard.
|
|
1206
|
+
* This simplifies the common case of authenticating users via a database model.
|
|
1207
|
+
*
|
|
1208
|
+
* @param model - The model class to use for user authentication
|
|
1209
|
+
* @param options - Options for the ModelUserProvider (partial, with defaults)
|
|
1210
|
+
* @param providerName - Name for the provider (defaults to 'users')
|
|
1211
|
+
* @param guardName - Name for the guard (defaults to 'web')
|
|
1212
|
+
*/
|
|
1213
|
+
useModel(model, options = {}, providerName = "users", guardName = "web") {
|
|
1214
|
+
const defaultOptions = {
|
|
1215
|
+
usernameColumn: "email",
|
|
1216
|
+
credentialsPasswordField: "password",
|
|
1217
|
+
hasher: new ScryptHasher(),
|
|
1218
|
+
...options
|
|
1219
|
+
};
|
|
1220
|
+
this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
|
|
1221
|
+
this.registerGuard(guardName, ({ session, manager }) => {
|
|
1222
|
+
return new SessionGuard({
|
|
1223
|
+
provider: manager.getProvider(providerName),
|
|
1224
|
+
session
|
|
1225
|
+
});
|
|
1226
|
+
});
|
|
1227
|
+
this.setDefaultGuard(guardName);
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Register a bearer-token guard backed by an ApiTokenStore and enable
|
|
1231
|
+
* header-based guard selection: requests carrying `Authorization: Bearer`
|
|
1232
|
+
* resolve to this guard, everything else keeps the default (session)
|
|
1233
|
+
* guard. The default guard itself is unchanged — session apps keep
|
|
1234
|
+
* working exactly as before.
|
|
1235
|
+
*
|
|
1236
|
+
* @param store - Where issued tokens live (see createApiToken)
|
|
1237
|
+
* @param options.provider - Registered provider name used to load the full
|
|
1238
|
+
* user record from the token's userId. Without it, `auth.user()` resolves
|
|
1239
|
+
* to a minimal `{ id }` record (enough for Gate/policy evaluation).
|
|
1240
|
+
* @param options.guardName - Guard registry name (defaults to 'token')
|
|
1241
|
+
*/
|
|
1242
|
+
useTokens(store, options = {}) {
|
|
1243
|
+
const guardName = options.guardName ?? "token";
|
|
1244
|
+
if (this.guards.has(guardName) && this.tokenGuard !== guardName) throw new Error(`AuthManager: guard "${guardName}" is already registered. Pass a different guardName to useTokens() instead of shadowing it.`);
|
|
1245
|
+
this.registerGuard(guardName, ({ ctx, manager }) => {
|
|
1246
|
+
return new TokenGuard({
|
|
1247
|
+
store,
|
|
1248
|
+
ctx,
|
|
1249
|
+
provider: options.provider ? manager.getProvider(options.provider) : void 0,
|
|
1250
|
+
updateLastUsed: options.updateLastUsed
|
|
1251
|
+
});
|
|
1252
|
+
});
|
|
1253
|
+
this.tokenGuard = guardName;
|
|
1254
|
+
this.apiTokenStore = store;
|
|
1255
|
+
this.apiTokenOptions = { ...options };
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* The options the last `useTokens()` call configured its guard with.
|
|
1259
|
+
*
|
|
1260
|
+
* Read by machinery that has to *replace* the store without changing
|
|
1261
|
+
* anything else about how tokens authenticate — `guren tool:dev` installs an
|
|
1262
|
+
* ephemeral store over the app's, and doing that with a bare `useTokens(store)`
|
|
1263
|
+
* silently dropped the app's `provider`, so a token resolved to a bare
|
|
1264
|
+
* `{ id }` instead of the real user record and every policy reading a user
|
|
1265
|
+
* field behaved differently for no stated reason.
|
|
1266
|
+
*/
|
|
1267
|
+
getApiTokenOptions() {
|
|
1268
|
+
return { ...this.apiTokenOptions };
|
|
1269
|
+
}
|
|
1270
|
+
/**
|
|
1271
|
+
* The token store {@link useTokens} was configured with, or `undefined`
|
|
1272
|
+
* when this app never called it.
|
|
1273
|
+
*
|
|
1274
|
+
* This is the one path by which out-of-request machinery — `guren
|
|
1275
|
+
* token:issue`, the App MCP adapter's principal lookup — reaches the same
|
|
1276
|
+
* store the guard verifies against. `useTokens` otherwise closes over
|
|
1277
|
+
* `store` inside the guard factory, where nothing outside a live request
|
|
1278
|
+
* can see it, so an issuance command could only write tokens into a store
|
|
1279
|
+
* of its own making, which no running app would ever read.
|
|
1280
|
+
*
|
|
1281
|
+
* Deliberately on this class rather than on `AuthManagerContract`: the
|
|
1282
|
+
* contract describes what a *request* needs from auth, and handing out the
|
|
1283
|
+
* raw store is not part of that. Callers reach it through the concrete
|
|
1284
|
+
* manager (`Application.auth`).
|
|
1285
|
+
*/
|
|
1286
|
+
getApiTokenStore() {
|
|
1287
|
+
return this.apiTokenStore ?? void 0;
|
|
1288
|
+
}
|
|
1289
|
+
};
|
|
1290
|
+
//#endregion
|
|
1291
|
+
//#region src/support/redirect-target.ts
|
|
1292
|
+
/**
|
|
1293
|
+
* Shared open-redirect classification primitives, used by both the
|
|
1294
|
+
* redirect-safety middleware and the OAuth `redirectTo` sanitizer. Keep every
|
|
1295
|
+
* hardening fix here so the two layers cannot drift.
|
|
1296
|
+
*/
|
|
1297
|
+
/** Normalize backslash tricks (e.g. `/\evil.com`) before classifying. */
|
|
1298
|
+
function normalizeRedirectTarget(value) {
|
|
1299
|
+
return value.replace(/\\/g, "/");
|
|
1300
|
+
}
|
|
1301
|
+
/** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
|
|
1302
|
+
function isAppRelativePath(value) {
|
|
1303
|
+
return value.startsWith("/") && !value.startsWith("//");
|
|
1304
|
+
}
|
|
1305
|
+
/** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
|
|
1306
|
+
function hostMatchesAllowlist(target, allowedHosts) {
|
|
1307
|
+
const hostname = target.hostname.toLowerCase();
|
|
1308
|
+
const host = target.host.toLowerCase();
|
|
1309
|
+
for (const allowed of allowedHosts) if (allowed.startsWith("*.")) {
|
|
1310
|
+
const suffix = allowed.slice(1).toLowerCase();
|
|
1311
|
+
if (hostname.endsWith(suffix) && hostname.length > suffix.length) return true;
|
|
1312
|
+
} else if (host === allowed.toLowerCase()) return true;
|
|
1313
|
+
return false;
|
|
1314
|
+
}
|
|
1315
|
+
//#endregion
|
|
1125
1316
|
//#region src/auth/oauth/index.ts
|
|
1126
1317
|
/** Session key holding the per-browser bindings between authorize and callback. */
|
|
1127
1318
|
const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
|
|
@@ -1945,10 +2136,10 @@ function requireVerifiedEmail(options = {}) {
|
|
|
1945
2136
|
const { redirectTo = "/verify-email" } = options;
|
|
1946
2137
|
return async (ctx, next) => {
|
|
1947
2138
|
if (!isEmailVerified(await (options.getUser ?? (async (c) => {
|
|
1948
|
-
return c
|
|
2139
|
+
return await getAuthContext(c)?.user() ?? null;
|
|
1949
2140
|
}))(ctx))) return ctx.redirect(redirectTo);
|
|
1950
2141
|
await next();
|
|
1951
2142
|
};
|
|
1952
2143
|
}
|
|
1953
2144
|
//#endregion
|
|
1954
|
-
export {
|
|
2145
|
+
export { SessionGuard as $, sanitizeOAuthRedirect as A, createBearerTokenMiddleware as B, createGitHubOAuthProviderConfig as C, exchangeOAuthCode as D, createOAuthState as E, AuthManager as F, parseApiToken as G, getApiTokenOrFail as H, TokenGuard as I, revokeApiToken as J, readBearerToken as K, API_TOKEN_KEY as L, hostMatchesAllowlist as M, isAppRelativePath as N, fetchOAuthUserProfile as O, normalizeRedirectTarget as P, verifyApiToken as Q, MemoryApiTokenStore as R, createDiscordOAuthProviderConfig as S, createOAuthManager as T, getUserApiTokens as U, getApiToken as V, hasBearerHeader as W, tokenCanAll as X, tokenCan as Y, tokenCanAny as Z, MemoryOAuthStateStore as _, isEmailVerified as a, secureCompare as at, buildOAuthAuthorizeUrl as b, verifyEmailToken as c, BaseUserProvider as ct, completePasswordReset as d, MemorySessionStore as dt, buildTokenUrl as et, createPasswordResetToken as f, createSessionMiddleware as ft, NodeHasher as g, AuthenticatableModel as h, createEmailVerificationToken as i, parseTokenUrl as it, verifyOAuthState as j, parseOAuthRedirectUrl as k, MemoryPasswordResetStore as l, ScryptHasher as lt, verifyPasswordResetToken as m, buildVerificationUrl as n, generateToken as nt, parseVerificationUrl as o, secureStringCompare as ot, parsePasswordResetUrl as p, getSessionFromContext 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, AuthenticationException as ut, OAUTH_SESSION_BINDING_KEY as v, createGoogleOAuthProviderConfig as w, buildOAuthRedirectUrl as x, OAuthManager as y, createApiToken as z };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { _ as setGate, 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 } from "../authorization-CdfbCj8J.js";
|
|
2
2
|
export { Gate, Policy, Response, authorize, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, can, cannot, createGate, defineGate, definePolicy, getGate, isAuthorizationResponse, setGate, withAuthorization };
|
|
@@ -16,12 +16,39 @@ import { Gate } from './Gate.js';
|
|
|
16
16
|
* // Multiple abilities (any)
|
|
17
17
|
* app.get('/dashboard', authorizeMiddleware(['admin', 'moderator']), dashboardHandler)
|
|
18
18
|
* ```
|
|
19
|
+
*
|
|
20
|
+
* An array argument is snapshotted at creation: mutating it afterwards
|
|
21
|
+
* changes neither what the middleware checks nor what it reports. A
|
|
22
|
+
* one-element array is treated exactly like the bare ability, denial message
|
|
23
|
+
* and status included. An empty array denies every request (`Gate.any([])` is
|
|
24
|
+
* false) and names no ability — fail-closed, so it is left to run rather than
|
|
25
|
+
* rejected.
|
|
19
26
|
*/
|
|
20
27
|
export declare function authorizeMiddleware(ability: string | string[], modelResolver?: (ctx: Context) => unknown | Promise<unknown>, options?: AuthorizeOptions): Middleware;
|
|
21
28
|
/**
|
|
22
29
|
* Middleware to authorize all given abilities.
|
|
30
|
+
*
|
|
31
|
+
* The array is snapshotted at creation, so mutating it afterwards changes
|
|
32
|
+
* neither what the middleware checks nor what it reports.
|
|
33
|
+
*
|
|
34
|
+
* @throws if no ability is given. `Gate.all([])` is vacuously true, so an
|
|
35
|
+
* empty list would mount a route that advertises authorization and enforces
|
|
36
|
+
* none — the fail-open shape RFC 0016's "authn is not authz" rule exists to
|
|
37
|
+
* catch. Refusing at creation surfaces it at boot rather than per request.
|
|
38
|
+
*/
|
|
39
|
+
export declare function authorizeAllMiddleware(input: string[], modelResolver?: (ctx: Context) => unknown | Promise<unknown>, options?: AuthorizeOptions): Middleware;
|
|
40
|
+
/**
|
|
41
|
+
* The ability `authorizeResourceMiddleware` checks for an HTTP method, or
|
|
42
|
+
* `undefined` for a method it refuses to guess at (which the middleware
|
|
43
|
+
* denies). This is the single source of the verb → ability mapping: a
|
|
44
|
+
* consumer resolving a route's ability from its stamped
|
|
45
|
+
* `authorization.resource` capability calls this rather than restating the
|
|
46
|
+
* table, and may only do so when `resource.fromMethodMap` is true.
|
|
47
|
+
*
|
|
48
|
+
* Not re-exported from the package root — like the capability stamp itself
|
|
49
|
+
* (RFC 0007), this is an internal contract until a public consumer needs it.
|
|
23
50
|
*/
|
|
24
|
-
export declare function
|
|
51
|
+
export declare function resourceAbilityForMethod(method: string): string | undefined;
|
|
25
52
|
/**
|
|
26
53
|
* Middleware factory for resource authorization.
|
|
27
54
|
* Automatically maps HTTP methods to policy abilities.
|