@eminuckan/spine 0.2.2 → 0.3.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/CHANGELOG.md +42 -0
- package/CODE_OF_CONDUCT.md +39 -0
- package/CONTRIBUTING.md +78 -0
- package/MAINTAINERS.md +43 -0
- package/README.md +111 -55
- package/ROADMAP.md +58 -0
- package/SECURITY.md +37 -0
- package/dist/access/evaluator.d.ts +3 -0
- package/dist/access/evaluator.d.ts.map +1 -0
- package/dist/access/index.d.ts +3 -0
- package/dist/access/index.d.ts.map +1 -0
- package/dist/access/index.js +4 -0
- package/dist/access/types.d.ts +38 -0
- package/dist/access/types.d.ts.map +1 -0
- package/dist/access-CGrsDMwu.js +61 -0
- package/dist/access-CGrsDMwu.js.map +1 -0
- package/dist/api-client/api-config.server.d.ts +27 -0
- package/dist/api-client/api-config.server.d.ts.map +1 -1
- package/dist/api-client/error-codes.d.ts +6 -31
- package/dist/api-client/error-codes.d.ts.map +1 -1
- package/dist/api-client/index.js +3 -3
- package/dist/api-client/server.d.ts +1 -1
- package/dist/api-client/server.d.ts.map +1 -1
- package/dist/api-client/server.js +4 -4
- package/dist/{api-client-DsrxK05Z.js → api-client-CgZUMukO.js} +9 -26
- package/dist/api-client-CgZUMukO.js.map +1 -0
- package/dist/auth/auth.server.d.ts +21 -16
- package/dist/auth/auth.server.d.ts.map +1 -1
- package/dist/auth/authorization-parameters.d.ts +5 -0
- package/dist/auth/authorization-parameters.d.ts.map +1 -0
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/redis-session-storage.server.d.ts +18 -1
- package/dist/auth/redis-session-storage.server.d.ts.map +1 -1
- package/dist/auth/route-protection.server.d.ts +20 -4
- package/dist/auth/route-protection.server.d.ts.map +1 -1
- package/dist/auth/server.d.ts +1 -1
- package/dist/auth/server.d.ts.map +1 -1
- package/dist/auth/server.js +5 -5
- package/dist/auth/types.d.ts +88 -21
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth.server-D5oiz9aF.js +1066 -0
- package/dist/auth.server-D5oiz9aF.js.map +1 -0
- package/dist/auth.server-lC94lmlx.js +5 -0
- package/dist/identity/identity-context.server.d.ts +2 -0
- package/dist/identity/identity-context.server.d.ts.map +1 -1
- package/dist/identity/identity-store.d.ts +19 -2
- package/dist/identity/identity-store.d.ts.map +1 -1
- package/dist/identity/index.js +2 -2
- package/dist/identity/server.js +3 -3
- package/dist/identity/types.d.ts +3 -1
- package/dist/identity/types.d.ts.map +1 -1
- package/dist/{identity-CFa1txoj.js → identity-C5un-xAs.js} +104 -60
- package/dist/identity-C5un-xAs.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -10
- package/dist/logging/index.js +1 -1
- package/dist/{logging-_h2mi3L9.js → logging-DviiAkLx.js} +2 -2
- package/dist/{logging-_h2mi3L9.js.map → logging-DviiAkLx.js.map} +1 -1
- package/dist/permission-service-CvGpwI0d.js +95 -0
- package/dist/permission-service-CvGpwI0d.js.map +1 -0
- package/dist/permissions/constants.d.ts +3 -0
- package/dist/permissions/constants.d.ts.map +1 -1
- package/dist/permissions/index.js +2 -1
- package/dist/permissions/permission-store.d.ts +1 -1
- package/dist/permissions/types.d.ts +1 -1
- package/dist/permissions/types.d.ts.map +1 -1
- package/dist/{permissions-D5ScGGnd.js → permissions-_n1hIG7Q.js} +8 -106
- package/dist/permissions-_n1hIG7Q.js.map +1 -0
- package/dist/query-client/index.js +1 -1
- package/dist/query-client/types.d.ts +9 -9
- package/dist/query-client/types.d.ts.map +1 -1
- package/dist/{query-client-Bpe08pk9.js → query-client-Bh3TyB8W.js} +2 -2
- package/dist/query-client-Bh3TyB8W.js.map +1 -0
- package/dist/react-router/index.js +12 -10
- package/dist/react-router/server.js +19 -17
- package/dist/redis-session-storage.server-v2VcpFsQ.js +500 -0
- package/dist/redis-session-storage.server-v2VcpFsQ.js.map +1 -0
- package/dist/{server-BHfKHKF_.js → server-B6PCxc-T.js} +39 -87
- package/dist/server-B6PCxc-T.js.map +1 -0
- package/dist/{server-DZmcd2Lr.js → server-C96NMFBy.js} +18 -10
- package/dist/server-C96NMFBy.js.map +1 -0
- package/dist/{server-BxvRxjCK.js → server-Ca-3DJf2.js} +44 -11
- package/dist/server-Ca-3DJf2.js.map +1 -0
- package/dist/{server-C3L8J7iE.js → server-Dxsww9v9.js} +6 -5
- package/dist/server-Dxsww9v9.js.map +1 -0
- package/dist/{server-CouYoZiw.js → server-hGrElJMG.js} +2 -2
- package/dist/{server-CouYoZiw.js.map → server-hGrElJMG.js.map} +1 -1
- package/dist/server.js +19 -17
- package/dist/signalr/index.js +1 -1
- package/dist/signalr/types.d.ts +1 -1
- package/dist/{signalr-SJ-1sIxw.js → signalr-k-70VHKo.js} +3 -2
- package/dist/signalr-k-70VHKo.js.map +1 -0
- package/dist/tenant/index.js +2 -2
- package/dist/tenant/server.js +4 -4
- package/dist/tenant/tenant-context.d.ts +17 -1
- package/dist/tenant/tenant-context.d.ts.map +1 -1
- package/dist/tenant/tenant-cookie.server.d.ts.map +1 -1
- package/dist/tenant/tenant-store.d.ts +54 -9
- package/dist/tenant/tenant-store.d.ts.map +1 -1
- package/dist/tenant/tenant.server.d.ts +20 -1
- package/dist/tenant/tenant.server.d.ts.map +1 -1
- package/dist/tenant/types.d.ts +29 -9
- package/dist/tenant/types.d.ts.map +1 -1
- package/dist/tenant-DfLemb6n.js +384 -0
- package/dist/tenant-DfLemb6n.js.map +1 -0
- package/dist/{types-BnKaWdfe.js → types-BaaE6wjY.js} +1 -1
- package/dist/{types-BnKaWdfe.js.map → types-BaaE6wjY.js.map} +1 -1
- package/docs/adapters.md +87 -0
- package/docs/architecture.md +193 -0
- package/docs/backend-adaptation.md +249 -0
- package/docs/codex-for-oss-application.md +31 -0
- package/docs/codex-maintenance.md +47 -0
- package/docs/installation.md +213 -0
- package/docs/module-reference.md +207 -0
- package/docs/releasing.md +92 -0
- package/package.json +27 -4
- package/dist/api-client-DsrxK05Z.js.map +0 -1
- package/dist/auth.server-BPiCtlJE.js +0 -5
- package/dist/auth.server-Cx2h2qu3.js +0 -724
- package/dist/auth.server-Cx2h2qu3.js.map +0 -1
- package/dist/identity-CFa1txoj.js.map +0 -1
- package/dist/permissions-D5ScGGnd.js.map +0 -1
- package/dist/query-client-Bpe08pk9.js.map +0 -1
- package/dist/redis-session-storage.server-BR_0y-QO.js +0 -250
- package/dist/redis-session-storage.server-BR_0y-QO.js.map +0 -1
- package/dist/server-BHfKHKF_.js.map +0 -1
- package/dist/server-BxvRxjCK.js.map +0 -1
- package/dist/server-C3L8J7iE.js.map +0 -1
- package/dist/server-DZmcd2Lr.js.map +0 -1
- package/dist/signalr-SJ-1sIxw.js.map +0 -1
- package/dist/tenant-C6KPaSCX.js +0 -256
- package/dist/tenant-C6KPaSCX.js.map +0 -1
- /package/dist/{src-CJ2RLi94.js → src-B9rDUgSb.js} +0 -0
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { logger } from "./logging-
|
|
2
|
-
import { getAuthSession } from "./redis-session-storage.server-
|
|
3
|
-
import { createRedirectResponse, getUser, login, refreshTokens, requireAuth } from "./auth.server-
|
|
1
|
+
import { logger } from "./logging-DviiAkLx.js";
|
|
2
|
+
import { getAuthSession } from "./redis-session-storage.server-v2VcpFsQ.js";
|
|
3
|
+
import { createRedirectResponse, getUser, login, refreshTokens, requireAuth } from "./auth.server-D5oiz9aF.js";
|
|
4
4
|
|
|
5
5
|
//#region src/auth/route-protection.server.ts
|
|
6
|
-
const REFRESH_THRESHOLD =
|
|
6
|
+
const REFRESH_THRESHOLD = resolveRefreshThreshold();
|
|
7
|
+
function resolveRefreshThreshold() {
|
|
8
|
+
const configured = Number(process.env.OIDC_REFRESH_THRESHOLD_MS);
|
|
9
|
+
return Number.isFinite(configured) && configured > 0 ? configured : 6e4;
|
|
10
|
+
}
|
|
7
11
|
/**
|
|
8
12
|
* Check if token needs refresh
|
|
9
13
|
*/
|
|
@@ -12,8 +16,8 @@ async function shouldRefreshToken(request) {
|
|
|
12
16
|
const sessionData = await getAuthSession(request);
|
|
13
17
|
if (!sessionData.refreshToken || sessionData.refreshToken.length === 0) {
|
|
14
18
|
if (sessionData.expiresAt && Date.now() >= sessionData.expiresAt) {
|
|
15
|
-
logger.info("Token expired and no refresh token, forcing
|
|
16
|
-
const { logout } = await import("./auth.server-
|
|
19
|
+
logger.info("Token expired and no refresh token, forcing local application logout");
|
|
20
|
+
const { logout } = await import("./auth.server-lC94lmlx.js");
|
|
17
21
|
const logoutRequest = await createAutomaticLogoutRequest(request, "expired-no-refresh-token");
|
|
18
22
|
throw await logout(logoutRequest);
|
|
19
23
|
}
|
|
@@ -50,8 +54,8 @@ async function autoRefreshTokens(request) {
|
|
|
50
54
|
else {
|
|
51
55
|
logger.error("Auto-refresh failed", void 0, { error: result.error });
|
|
52
56
|
if (result.shouldLogout) {
|
|
53
|
-
logger.error("Refresh token invalid, forcing
|
|
54
|
-
const { logout } = await import("./auth.server-
|
|
57
|
+
logger.error("Refresh token invalid, forcing local application logout");
|
|
58
|
+
const { logout } = await import("./auth.server-lC94lmlx.js");
|
|
55
59
|
const logoutRequest = await createAutomaticLogoutRequest(request, "refresh-failed");
|
|
56
60
|
throw await logout(logoutRequest);
|
|
57
61
|
}
|
|
@@ -64,7 +68,7 @@ async function autoRefreshTokens(request) {
|
|
|
64
68
|
}
|
|
65
69
|
let protectionConfig = {};
|
|
66
70
|
/**
|
|
67
|
-
* Configure route protection with identity
|
|
71
|
+
* Configure route protection with identity, tenant, and app policy checkers
|
|
68
72
|
*/
|
|
69
73
|
function configureRouteProtection(config) {
|
|
70
74
|
protectionConfig = config;
|
|
@@ -88,9 +92,9 @@ function getLoginReturnUrl(request, currentPath, protection) {
|
|
|
88
92
|
protection
|
|
89
93
|
});
|
|
90
94
|
switch (protection) {
|
|
91
|
-
case "onboarding-required":
|
|
92
|
-
case "subscription-required":
|
|
93
|
-
case "public":
|
|
95
|
+
case "onboarding-required":
|
|
96
|
+
case "subscription-required":
|
|
97
|
+
case "public":
|
|
94
98
|
case "auth":
|
|
95
99
|
default: {
|
|
96
100
|
const url = new URL(request.url);
|
|
@@ -105,7 +109,7 @@ async function createAutomaticLogoutRequest(request, reason) {
|
|
|
105
109
|
});
|
|
106
110
|
const logoutUrl = new URL(request.url);
|
|
107
111
|
logoutUrl.pathname = "/auth/logout";
|
|
108
|
-
logoutUrl.searchParams.set("
|
|
112
|
+
logoutUrl.searchParams.set("logout", "local");
|
|
109
113
|
return new Request(logoutUrl.toString(), { headers: request.headers });
|
|
110
114
|
}
|
|
111
115
|
function createRouteResolverContext(request, user, currentPath, protection) {
|
|
@@ -154,62 +158,6 @@ async function applyConfiguredRouteResolution(request, user, currentPath, protec
|
|
|
154
158
|
}
|
|
155
159
|
}
|
|
156
160
|
/**
|
|
157
|
-
* Check user status (onboarding, subscription)
|
|
158
|
-
*/
|
|
159
|
-
async function checkUserStatus(request, user, currentPath) {
|
|
160
|
-
if (!protectionConfig.identityChecker) {
|
|
161
|
-
logger.warn("Identity checker not configured, skipping status check");
|
|
162
|
-
return null;
|
|
163
|
-
}
|
|
164
|
-
try {
|
|
165
|
-
const context = await protectionConfig.identityChecker.getIdentityContext(request, user.sub);
|
|
166
|
-
logger.debug("User status check", {
|
|
167
|
-
userId: user.sub,
|
|
168
|
-
currentPath,
|
|
169
|
-
hasAnyMembership: context.hasAnyMembership,
|
|
170
|
-
isOnboarded: context.isOnboarded,
|
|
171
|
-
hasSubscription: context.hasSubscription
|
|
172
|
-
});
|
|
173
|
-
if (!context.hasAnyMembership) {
|
|
174
|
-
if (currentPath !== "/onboarding") {
|
|
175
|
-
logger.info("User has no memberships, redirecting to onboarding");
|
|
176
|
-
throw createRedirectResponse("/onboarding");
|
|
177
|
-
}
|
|
178
|
-
return null;
|
|
179
|
-
}
|
|
180
|
-
if (context.hasAnyMembership) {
|
|
181
|
-
if (currentPath === "/onboarding") {
|
|
182
|
-
logger.info("User has memberships, redirecting from onboarding to subscription");
|
|
183
|
-
throw createRedirectResponse("/subscription");
|
|
184
|
-
}
|
|
185
|
-
if (currentPath === "/subscription") return null;
|
|
186
|
-
if (protectionConfig.tenantChecker && protectionConfig.subscriptionChecker) {
|
|
187
|
-
let currentTenant = await protectionConfig.tenantChecker.getCurrentTenant(request);
|
|
188
|
-
if (!currentTenant) {
|
|
189
|
-
const initResult = await protectionConfig.tenantChecker.initializeTenant(request);
|
|
190
|
-
if (initResult) currentTenant = initResult.tenantId;
|
|
191
|
-
}
|
|
192
|
-
if (currentTenant) {
|
|
193
|
-
const hasSubscription = await protectionConfig.subscriptionChecker.checkTenantSubscriptionStatus(request, currentTenant);
|
|
194
|
-
if (!hasSubscription) {
|
|
195
|
-
logger.info("Tenant has no subscription, redirecting to subscription");
|
|
196
|
-
throw createRedirectResponse("/subscription");
|
|
197
|
-
}
|
|
198
|
-
} else {
|
|
199
|
-
logger.info("Could not initialize tenant, redirecting to subscription");
|
|
200
|
-
throw createRedirectResponse("/subscription");
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
return null;
|
|
205
|
-
} catch (error) {
|
|
206
|
-
if (error instanceof Response && error.status >= 300 && error.status < 400) throw error;
|
|
207
|
-
logger.error("Error checking user status", error instanceof Error ? error : void 0);
|
|
208
|
-
if (currentPath !== "/onboarding") throw createRedirectResponse("/onboarding");
|
|
209
|
-
return null;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
161
|
* Main route protection function
|
|
214
162
|
*/
|
|
215
163
|
async function protectRoute(request, protection, loaderFn) {
|
|
@@ -222,24 +170,20 @@ async function protectRoute(request, protection, loaderFn) {
|
|
|
222
170
|
} catch {
|
|
223
171
|
return loaderFn(void 0);
|
|
224
172
|
}
|
|
225
|
-
case "auth":
|
|
173
|
+
case "auth":
|
|
174
|
+
case "policy": try {
|
|
226
175
|
await autoRefreshTokens(request);
|
|
227
176
|
const user = await requireAuth(request);
|
|
228
|
-
|
|
229
|
-
if (!handledByConfig) await checkUserStatus(request, user, url.pathname);
|
|
177
|
+
await applyConfiguredRouteResolution(request, user, url.pathname, protection);
|
|
230
178
|
return loaderFn(user);
|
|
231
179
|
} catch (error) {
|
|
232
180
|
if (error instanceof Response && error.status >= 300 && error.status < 400) throw error;
|
|
233
|
-
throw await login(request, getLoginReturnUrl(request, url.pathname,
|
|
181
|
+
throw await login(request, getLoginReturnUrl(request, url.pathname, protection));
|
|
234
182
|
}
|
|
235
183
|
case "onboarding-required": try {
|
|
236
184
|
await autoRefreshTokens(request);
|
|
237
185
|
const user = await requireAuth(request);
|
|
238
|
-
|
|
239
|
-
if (!handledByConfig && protectionConfig.identityChecker) {
|
|
240
|
-
const context = await protectionConfig.identityChecker.getIdentityContext(request, user.sub);
|
|
241
|
-
if (context.hasAnyMembership) throw createRedirectResponse("/subscription");
|
|
242
|
-
}
|
|
186
|
+
await applyConfiguredRouteResolution(request, user, url.pathname, "onboarding-required");
|
|
243
187
|
return loaderFn(user);
|
|
244
188
|
} catch (error) {
|
|
245
189
|
if (error instanceof Response && error.status >= 300 && error.status < 400) throw error;
|
|
@@ -248,11 +192,7 @@ async function protectRoute(request, protection, loaderFn) {
|
|
|
248
192
|
case "subscription-required": try {
|
|
249
193
|
await autoRefreshTokens(request);
|
|
250
194
|
const user = await requireAuth(request);
|
|
251
|
-
|
|
252
|
-
if (!handledByConfig && protectionConfig.identityChecker) {
|
|
253
|
-
const context = await protectionConfig.identityChecker.getIdentityContext(request, user.sub);
|
|
254
|
-
if (!context.hasAnyMembership) throw createRedirectResponse("/onboarding");
|
|
255
|
-
}
|
|
195
|
+
await applyConfiguredRouteResolution(request, user, url.pathname, "subscription-required");
|
|
256
196
|
if (protectionConfig.tenantChecker) {
|
|
257
197
|
const currentTenant = await protectionConfig.tenantChecker.getCurrentTenant(request);
|
|
258
198
|
if (!currentTenant) await protectionConfig.tenantChecker.initializeTenant(request);
|
|
@@ -274,11 +214,23 @@ const publicRoute = (request, loaderFn) => protectRoute(request, "public", loade
|
|
|
274
214
|
*/
|
|
275
215
|
const authRoute = (request, loaderFn) => protectRoute(request, "auth", loaderFn);
|
|
276
216
|
/**
|
|
277
|
-
*
|
|
217
|
+
* Generic policy-protected route. Apps define policy in configureRouteProtection.
|
|
218
|
+
*/
|
|
219
|
+
const policyRoute = (request, loaderFn) => protectRoute(request, "policy", loaderFn);
|
|
220
|
+
/**
|
|
221
|
+
* Alias for auth-protected routes.
|
|
222
|
+
*/
|
|
223
|
+
const protectedRoute = authRoute;
|
|
224
|
+
/**
|
|
225
|
+
* Setup policy route
|
|
226
|
+
*
|
|
227
|
+
* @deprecated Use policyRoute with configureRouteProtection instead.
|
|
278
228
|
*/
|
|
279
229
|
const onboardingRoute = (request, loaderFn) => protectRoute(request, "onboarding-required", loaderFn);
|
|
280
230
|
/**
|
|
281
|
-
*
|
|
231
|
+
* Entitlement policy route
|
|
232
|
+
*
|
|
233
|
+
* @deprecated Use policyRoute with configureRouteProtection instead.
|
|
282
234
|
*/
|
|
283
235
|
const subscriptionRoute = (request, loaderFn) => protectRoute(request, "subscription-required", loaderFn);
|
|
284
236
|
|
|
@@ -348,5 +300,5 @@ function shouldAttemptTokenRefresh(response, hasAuth) {
|
|
|
348
300
|
}
|
|
349
301
|
|
|
350
302
|
//#endregion
|
|
351
|
-
export { attemptTokenRefresh, authRoute, configureRouteProtection, isTokenExpiredResponse, onboardingRoute, protectRoute, publicRoute, resetRouteProtectionConfig, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute };
|
|
352
|
-
//# sourceMappingURL=server-
|
|
303
|
+
export { attemptTokenRefresh, authRoute, configureRouteProtection, isTokenExpiredResponse, onboardingRoute, policyRoute, protectRoute, protectedRoute, publicRoute, resetRouteProtectionConfig, shouldAttemptTokenRefresh, shouldRefreshToken, subscriptionRoute };
|
|
304
|
+
//# sourceMappingURL=server-B6PCxc-T.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-B6PCxc-T.js","names":["request: Request","jwtExpiry: number | null","protectionConfig: RouteProtectionConfig<any>","config: RouteProtectionConfig<TIdentityContext>","redirect: RouteProtectionRedirect","currentPath: string","protection: ProtectionLevel","reason: AutomaticLogoutRequestContext['reason']","user: UserInfo","identityContextPromise: Promise<any | null> | null","currentTenantPromise: Promise<string | null> | null","initializeTenantPromise: Promise<{ headers: Headers; tenantId: string } | null> | null","loaderFn: (user?: UserInfo) => Promise<T> | T","loaderFn: (user: UserInfo) => Promise<T> | T","request: Request","response: Response","hasAuth: boolean"],"sources":["../src/auth/route-protection.server.ts","../src/auth/token-refresh.server.ts"],"sourcesContent":["/**\n * Route Protection Server Module\n * \n * Provides route protection utilities for different authentication levels.\n */\n\nimport { getUser, requireAuth, refreshTokens, login } from './auth.server';\nimport { getAuthSession } from './redis-session-storage.server';\nimport type { ProtectionLevel, UserInfo } from './types';\nimport { logger } from '../logging';\nimport { createRedirectResponse } from '../http/response';\n\n// Refresh shortly before expiry. Keep this below common 5-minute access-token\n// lifetimes so a freshly issued token does not refresh again immediately.\nconst REFRESH_THRESHOLD = resolveRefreshThreshold();\n\nfunction resolveRefreshThreshold(): number {\n const configured = Number(process.env.OIDC_REFRESH_THRESHOLD_MS);\n return Number.isFinite(configured) && configured > 0 ? configured : 60_000;\n}\n\n/**\n * Check if token needs refresh\n */\nexport async function shouldRefreshToken(request: Request): Promise<boolean> {\n try {\n const sessionData = await getAuthSession(request);\n\n if (!sessionData.refreshToken || sessionData.refreshToken.length === 0) {\n if (sessionData.expiresAt && Date.now() >= sessionData.expiresAt) {\n logger.info('Token expired and no refresh token, forcing local application logout');\n const { logout } = await import('./auth.server');\n const logoutRequest = await createAutomaticLogoutRequest(request, 'expired-no-refresh-token');\n throw await logout(logoutRequest);\n }\n return false;\n }\n\n if (!sessionData.expiresAt || !sessionData.accessToken) {\n return false;\n }\n\n const now = Date.now();\n\n // Check JWT expiry\n let jwtExpiry: number | null = null;\n try {\n const tokenParts = sessionData.accessToken.split('.');\n if (tokenParts.length === 3) {\n const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64').toString());\n if (payload.exp) {\n jwtExpiry = payload.exp * 1000;\n }\n }\n } catch {\n // Ignore JWT decode errors\n }\n\n const earliestExpiry = jwtExpiry && jwtExpiry < sessionData.expiresAt \n ? jwtExpiry \n : sessionData.expiresAt;\n const timeUntilEarliestExpiry = earliestExpiry - now;\n\n return timeUntilEarliestExpiry <= REFRESH_THRESHOLD;\n } catch (error) {\n logger.error('Error checking token refresh', error instanceof Error ? error : undefined);\n return false;\n }\n}\n\n/**\n * Auto-refresh tokens if needed\n */\nasync function autoRefreshTokens(request: Request): Promise<void> {\n try {\n const needsRefresh = await shouldRefreshToken(request);\n\n if (needsRefresh) {\n logger.info('Auto-refreshing tokens due to expiry');\n const result = await refreshTokens(request);\n\n if (result.success) {\n logger.info('Auto-refresh completed successfully');\n } else {\n logger.error('Auto-refresh failed', undefined, { error: result.error });\n\n if (result.shouldLogout) {\n logger.error('Refresh token invalid, forcing local application logout');\n const { logout } = await import('./auth.server');\n const logoutRequest = await createAutomaticLogoutRequest(request, 'refresh-failed');\n throw await logout(logoutRequest);\n }\n }\n }\n } catch (error) {\n if (error instanceof Response && error.status >= 300 && error.status < 400) {\n throw error;\n }\n throw error;\n }\n}\n\n/**\n * Identity context check configuration\n */\nexport interface DefaultRouteIdentityContext {\n hasAnyMembership: boolean;\n hasEntitlement?: boolean;\n /** @deprecated Use hasEntitlement or app-specific fields instead. */\n hasSubscription: boolean;\n isOnboarded: boolean;\n}\n\nexport interface IdentityContextChecker<TIdentityContext = DefaultRouteIdentityContext> {\n getIdentityContext: (\n request: Request,\n userId: string,\n forceRefresh?: boolean\n ) => Promise<DefaultRouteIdentityContext & TIdentityContext>;\n}\n\n/**\n * Tenant checker configuration\n */\nexport interface TenantChecker {\n getCurrentTenant: (request: Request) => Promise<string | null>;\n initializeTenant: (request: Request) => Promise<{ headers: Headers; tenantId: string } | null>;\n}\n\n/**\n * Legacy subscription checker configuration\n *\n * @deprecated Put entitlement policy in resolveRoute or app-level route loaders.\n */\nexport interface SubscriptionChecker {\n checkTenantSubscriptionStatus: (request: Request, tenantId: string) => Promise<boolean>;\n}\n\nexport interface RouteProtectionRedirect {\n location: string;\n headers?: HeadersInit;\n status?: number;\n}\n\nexport interface AutomaticLogoutRequestContext {\n request: Request;\n reason: 'expired-no-refresh-token' | 'refresh-failed';\n}\n\nexport interface LoginReturnUrlContext {\n request: Request;\n currentPath: string;\n protection: ProtectionLevel;\n}\n\nexport interface RouteProtectionResolverContext<TIdentityContext = DefaultRouteIdentityContext> {\n request: Request;\n user: UserInfo;\n currentPath: string;\n protection: ProtectionLevel;\n getIdentityContext: (forceRefresh?: boolean) => Promise<TIdentityContext | null>;\n getCurrentTenant: () => Promise<string | null>;\n initializeTenant: () => Promise<{ headers: Headers; tenantId: string } | null>;\n}\n\nexport interface RouteProtectionErrorHandlerContext<TIdentityContext = DefaultRouteIdentityContext>\n extends RouteProtectionResolverContext<TIdentityContext> {\n error: unknown;\n}\n\n/**\n * Route protection configuration\n */\nexport interface RouteProtectionConfig<TIdentityContext = DefaultRouteIdentityContext> {\n identityChecker?: IdentityContextChecker<TIdentityContext>;\n tenantChecker?: TenantChecker;\n subscriptionChecker?: SubscriptionChecker;\n resolveRoute?: (\n context: RouteProtectionResolverContext<TIdentityContext>\n ) => Promise<RouteProtectionRedirect | null | void> | RouteProtectionRedirect | null | void;\n handleRouteError?: (\n context: RouteProtectionErrorHandlerContext<TIdentityContext>\n ) => Promise<RouteProtectionRedirect | null | void> | RouteProtectionRedirect | null | void;\n getLoginReturnUrl?: (context: LoginReturnUrlContext) => string;\n createAutomaticLogoutRequest?: (\n context: AutomaticLogoutRequestContext\n ) => Promise<Request> | Request;\n}\n\nlet protectionConfig: RouteProtectionConfig<any> = {};\n\n/**\n * Configure route protection with identity, tenant, and app policy checkers\n */\nexport function configureRouteProtection<TIdentityContext = DefaultRouteIdentityContext>(\n config: RouteProtectionConfig<TIdentityContext>\n): void {\n protectionConfig = config;\n}\n\n/**\n * Reset route protection to its built-in defaults.\n */\nexport function resetRouteProtectionConfig(): void {\n protectionConfig = {};\n}\n\nfunction createRedirectFromConfig(redirect: RouteProtectionRedirect): Response {\n return createRedirectResponse(redirect.location, {\n headers: redirect.headers,\n status: redirect.status,\n });\n}\n\nfunction getLoginReturnUrl(\n request: Request,\n currentPath: string,\n protection: ProtectionLevel\n): string {\n if (protectionConfig.getLoginReturnUrl) {\n return protectionConfig.getLoginReturnUrl({\n request,\n currentPath,\n protection,\n });\n }\n\n switch (protection) {\n case 'onboarding-required':\n case 'subscription-required':\n case 'public':\n case 'auth':\n default: {\n const url = new URL(request.url);\n return url.pathname === '/' ? '/' : `${url.pathname}${url.search}`;\n }\n }\n}\n\nasync function createAutomaticLogoutRequest(\n request: Request,\n reason: AutomaticLogoutRequestContext['reason']\n): Promise<Request> {\n if (protectionConfig.createAutomaticLogoutRequest) {\n return protectionConfig.createAutomaticLogoutRequest({ request, reason });\n }\n\n const logoutUrl = new URL(request.url);\n logoutUrl.pathname = '/auth/logout';\n logoutUrl.searchParams.set('logout', 'local');\n\n return new Request(logoutUrl.toString(), {\n headers: request.headers,\n });\n}\n\nfunction createRouteResolverContext(\n request: Request,\n user: UserInfo,\n currentPath: string,\n protection: ProtectionLevel\n): RouteProtectionResolverContext<any> {\n let identityContextPromise: Promise<any | null> | null = null;\n let currentTenantPromise: Promise<string | null> | null = null;\n let initializeTenantPromise: Promise<{ headers: Headers; tenantId: string } | null> | null = null;\n\n return {\n request,\n user,\n currentPath,\n protection,\n getIdentityContext: async (forceRefresh = false) => {\n if (!protectionConfig.identityChecker) {\n return null;\n }\n\n if (forceRefresh) {\n return protectionConfig.identityChecker.getIdentityContext(request, user.sub, true);\n }\n\n if (!identityContextPromise) {\n identityContextPromise = protectionConfig.identityChecker.getIdentityContext(request, user.sub);\n }\n\n return identityContextPromise;\n },\n getCurrentTenant: async () => {\n if (!protectionConfig.tenantChecker) {\n return null;\n }\n\n if (!currentTenantPromise) {\n currentTenantPromise = protectionConfig.tenantChecker.getCurrentTenant(request);\n }\n\n return currentTenantPromise;\n },\n initializeTenant: async () => {\n if (!protectionConfig.tenantChecker) {\n return null;\n }\n\n if (!initializeTenantPromise) {\n initializeTenantPromise = protectionConfig.tenantChecker.initializeTenant(request);\n }\n\n return initializeTenantPromise;\n },\n };\n}\n\nasync function applyConfiguredRouteResolution(\n request: Request,\n user: UserInfo,\n currentPath: string,\n protection: ProtectionLevel\n): Promise<boolean> {\n if (!protectionConfig.resolveRoute) {\n return false;\n }\n\n const context = createRouteResolverContext(request, user, currentPath, protection);\n\n try {\n const result = await protectionConfig.resolveRoute(context);\n if (result) {\n throw createRedirectFromConfig(result);\n }\n\n return true;\n } catch (error) {\n if (error instanceof Response && error.status >= 300 && error.status < 400) {\n throw error;\n }\n\n if (!protectionConfig.handleRouteError) {\n throw error;\n }\n\n const recovery = await protectionConfig.handleRouteError({\n ...context,\n error,\n });\n\n if (recovery) {\n throw createRedirectFromConfig(recovery);\n }\n\n throw error;\n }\n}\n\n/**\n * Main route protection function\n */\nexport async function protectRoute<T>(\n request: Request,\n protection: ProtectionLevel,\n loaderFn: (user?: UserInfo) => Promise<T> | T\n): Promise<T> {\n const url = new URL(request.url);\n\n switch (protection) {\n case 'public':\n try {\n await autoRefreshTokens(request);\n const user = await getUser(request);\n return loaderFn(user ?? undefined);\n } catch {\n return loaderFn(undefined);\n }\n\n case 'auth':\n case 'policy':\n try {\n await autoRefreshTokens(request);\n const user = await requireAuth(request);\n await applyConfiguredRouteResolution(request, user, url.pathname, protection);\n return loaderFn(user);\n } catch (error) {\n if (error instanceof Response && error.status >= 300 && error.status < 400) {\n throw error;\n }\n throw await login(request, getLoginReturnUrl(request, url.pathname, protection));\n }\n\n case 'onboarding-required':\n try {\n await autoRefreshTokens(request);\n const user = await requireAuth(request);\n\n await applyConfiguredRouteResolution(\n request,\n user,\n url.pathname,\n 'onboarding-required'\n );\n\n return loaderFn(user);\n } catch (error) {\n if (error instanceof Response && error.status >= 300 && error.status < 400) {\n throw error;\n }\n throw await login(request, getLoginReturnUrl(request, url.pathname, 'onboarding-required'));\n }\n\n case 'subscription-required':\n try {\n await autoRefreshTokens(request);\n const user = await requireAuth(request);\n\n await applyConfiguredRouteResolution(\n request,\n user,\n url.pathname,\n 'subscription-required'\n );\n\n // Initialize tenant if needed\n if (protectionConfig.tenantChecker) {\n const currentTenant = await protectionConfig.tenantChecker.getCurrentTenant(request);\n if (!currentTenant) {\n await protectionConfig.tenantChecker.initializeTenant(request);\n }\n }\n\n return loaderFn(user);\n } catch (error) {\n if (error instanceof Response && error.status >= 300 && error.status < 400) {\n throw error;\n }\n throw await login(request, getLoginReturnUrl(request, url.pathname, 'subscription-required'));\n }\n\n default:\n throw new Error(`Unknown protection level: ${protection}`);\n }\n}\n\n// ============================================================================\n// Convenience Functions\n// ============================================================================\n\n/**\n * Public route (optional auth)\n */\nexport const publicRoute = <T>(\n request: Request,\n loaderFn: (user?: UserInfo) => Promise<T> | T\n) => protectRoute(request, 'public', loaderFn);\n\n/**\n * Auth-protected route\n */\nexport const authRoute = <T>(\n request: Request,\n loaderFn: (user: UserInfo) => Promise<T> | T\n) => protectRoute(request, 'auth', loaderFn as (user?: UserInfo) => Promise<T> | T);\n\n/**\n * Generic policy-protected route. Apps define policy in configureRouteProtection.\n */\nexport const policyRoute = <T>(\n request: Request,\n loaderFn: (user: UserInfo) => Promise<T> | T\n) => protectRoute(request, 'policy', loaderFn as (user?: UserInfo) => Promise<T> | T);\n\n/**\n * Alias for auth-protected routes.\n */\nexport const protectedRoute = authRoute;\n\n/**\n * Setup policy route\n *\n * @deprecated Use policyRoute with configureRouteProtection instead.\n */\nexport const onboardingRoute = <T>(\n request: Request,\n loaderFn: (user: UserInfo) => Promise<T> | T\n) => protectRoute(request, 'onboarding-required', loaderFn as (user?: UserInfo) => Promise<T> | T);\n\n/**\n * Entitlement policy route\n *\n * @deprecated Use policyRoute with configureRouteProtection instead.\n */\nexport const subscriptionRoute = <T>(\n request: Request,\n loaderFn: (user: UserInfo) => Promise<T> | T\n) => protectRoute(request, 'subscription-required', loaderFn as (user?: UserInfo) => Promise<T> | T);\n","/**\n * Token Refresh Server Module\n */\n\nimport { refreshTokens } from './auth.server';\nimport { getAuthSession } from './redis-session-storage.server';\nimport type { TokenRefreshResult } from './types';\nimport { logger } from '../logging';\n\n/**\n * Attempt to refresh the access token\n */\nexport async function attemptTokenRefresh(request: Request): Promise<TokenRefreshResult> {\n try {\n logger.info('Attempting token refresh due to 401 response');\n\n const sessionData = await getAuthSession(request);\n\n if (!sessionData.refreshToken) {\n logger.warn('No refresh token available in session');\n return {\n success: false,\n error: 'No refresh token available',\n shouldLogout: true,\n };\n }\n\n const refreshResult = await refreshTokens(request, sessionData.refreshToken);\n\n if (!refreshResult.success) {\n logger.error('Token refresh failed', undefined, {\n error: refreshResult.error,\n shouldLogout: refreshResult.shouldLogout,\n });\n\n return {\n success: false,\n error: refreshResult.error,\n shouldLogout: refreshResult.shouldLogout,\n };\n }\n\n const tokens = refreshResult.tokens;\n if (!tokens || !tokens.access_token) {\n logger.error('Token refresh succeeded but no access token returned');\n return {\n success: false,\n error: 'No access token in refresh response',\n shouldLogout: true,\n };\n }\n\n logger.info('Token refresh successful');\n\n return {\n success: true,\n newAccessToken: tokens.access_token,\n };\n } catch (error) {\n logger.error('Token refresh attempt failed', error instanceof Error ? error : undefined);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n shouldLogout: true,\n };\n }\n}\n\n/**\n * Check if a response indicates token expiration\n */\nexport function isTokenExpiredResponse(response: Response): boolean {\n return response.status === 401;\n}\n\n/**\n * Check if token refresh should be attempted\n */\nexport function shouldAttemptTokenRefresh(response: Response, hasAuth: boolean): boolean {\n return hasAuth && isTokenExpiredResponse(response);\n}\n"],"mappings":";;;;;AAcA,MAAM,oBAAoB,yBAAyB;AAEnD,SAAS,0BAAkC;CACzC,MAAM,aAAa,OAAO,QA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,SAAgB,0BAA0BA,UAAoBC,SAA2B;AACvF,QAAO,WAAW,uBAAuB,SAAS;AACnD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { isApiClientError } from "./types-
|
|
2
|
-
import { calculateBackoffDelay, fetchWithTimeout, isRetryableError } from "./api-client-
|
|
1
|
+
import { isApiClientError } from "./types-BaaE6wjY.js";
|
|
2
|
+
import { calculateBackoffDelay, fetchWithTimeout, isRetryableError } from "./api-client-CgZUMukO.js";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
|
|
5
5
|
//#region src/api-client/api-config.server.ts
|
|
@@ -7,7 +7,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
7
7
|
* Base URL Configuration
|
|
8
8
|
* Single unified base URL for all API operations
|
|
9
9
|
*/
|
|
10
|
-
const DEFAULT_API_BASE_URL = process.env.API_BASE_URL || "
|
|
10
|
+
const DEFAULT_API_BASE_URL = process.env.API_BASE_URL || "";
|
|
11
11
|
/**
|
|
12
12
|
* Default Headers
|
|
13
13
|
* Applied to all API requests
|
|
@@ -23,7 +23,7 @@ const DEFAULT_HEADERS = {
|
|
|
23
23
|
* with the provided auth and tenant resolvers.
|
|
24
24
|
*/
|
|
25
25
|
function createAPIConfigFactory(getAccessToken, getCurrentTenant, logger, factoryOptions = {}) {
|
|
26
|
-
const { baseURL = DEFAULT_API_BASE_URL, defaultHeaders = DEFAULT_HEADERS, userAgent = "
|
|
26
|
+
const { baseURL = DEFAULT_API_BASE_URL, defaultHeaders = DEFAULT_HEADERS, userAgent = "Spine/1.0", timeout = 3e4, authHeaderName = "Authorization", authHeaderValue = (token) => `Bearer ${token}`, tenantHeaderName = "X-Tenant-Id", buildHeaders } = factoryOptions;
|
|
27
27
|
/**
|
|
28
28
|
* Resolve tenant ID from request or options
|
|
29
29
|
*/
|
|
@@ -45,9 +45,9 @@ function createAPIConfigFactory(getAccessToken, getCurrentTenant, logger, factor
|
|
|
45
45
|
* Creates unified API configuration for all services.
|
|
46
46
|
*
|
|
47
47
|
* This function automatically:
|
|
48
|
-
* - Adds authentication token
|
|
49
|
-
* - Injects tenant context
|
|
50
|
-
* - Configures base URL from environment
|
|
48
|
+
* - Adds authentication token using the configured auth header strategy
|
|
49
|
+
* - Injects tenant context using the configured tenant header strategy
|
|
50
|
+
* - Configures base URL from options or environment
|
|
51
51
|
* - Applies default headers
|
|
52
52
|
*
|
|
53
53
|
* @param request - The incoming request object
|
|
@@ -83,7 +83,7 @@ function createAPIConfigFactory(getAccessToken, getCurrentTenant, logger, factor
|
|
|
83
83
|
throw new Error("No access token available");
|
|
84
84
|
}
|
|
85
85
|
accessToken = token;
|
|
86
|
-
headers
|
|
86
|
+
if (authHeaderName) headers[authHeaderName] = authHeaderValue(token);
|
|
87
87
|
logger?.debug?.("Added authorization header to API config");
|
|
88
88
|
}
|
|
89
89
|
const tenantId = await resolveTenantId(request, options);
|
|
@@ -92,9 +92,17 @@ function createAPIConfigFactory(getAccessToken, getCurrentTenant, logger, factor
|
|
|
92
92
|
logger?.error?.("Tenant context required but not available");
|
|
93
93
|
throw new Error("Tenant context is required for this operation");
|
|
94
94
|
}
|
|
95
|
-
headers[
|
|
95
|
+
if (tenantHeaderName) headers[tenantHeaderName] = tenantId;
|
|
96
96
|
logger?.debug?.("Added tenant context header", { tenantId });
|
|
97
97
|
}
|
|
98
|
+
if (buildHeaders) Object.assign(headers, buildHeaders({
|
|
99
|
+
request,
|
|
100
|
+
options,
|
|
101
|
+
accessToken,
|
|
102
|
+
tenantId,
|
|
103
|
+
includeAuth,
|
|
104
|
+
requireTenant
|
|
105
|
+
}));
|
|
98
106
|
logger?.debug?.("API config created", {
|
|
99
107
|
basePath: baseURL,
|
|
100
108
|
hasAuth: includeAuth,
|
|
@@ -419,4 +427,4 @@ async function createApiClient(request, ClientClass, createAPIConfig, Configurat
|
|
|
419
427
|
|
|
420
428
|
//#endregion
|
|
421
429
|
export { createAPIConfigFactory, createApiClient, createFetchMiddleware };
|
|
422
|
-
//# sourceMappingURL=server-
|
|
430
|
+
//# sourceMappingURL=server-C96NMFBy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-C96NMFBy.js","names":["DEFAULT_HEADERS: Record<string, string>","getAccessToken: GetAccessTokenFn","getCurrentTenant: GetCurrentTenantFn","logger?: APILogger","factoryOptions: APIConfigFactoryOptions","token: string","request: Request","options: CreateAPIConfigOptions","headers: Record<string, string>","accessToken: string | undefined","request: Request","sessionKey: string","refreshFn: () => Promise<TokenRefreshResult>","logger?: APILogger","init: SpineRequestInit","headersInit?: HeadersInit","init: RequestInit","timeout?: number","value: unknown","response: Response","params: {\n message: string;\n response?: APIResponse<T>;\n config?: ResponseRequestMeta;\n problemDetails?: ProblemDetails;\n shouldLogout?: boolean;\n originalError?: unknown;\n cause?: unknown;\n}","rawResponse: Response","resolvedData?: T","error: unknown","context: FetchResponseContext","retryConfig: Required<Pick<RetryConfig, 'maxRetries' | 'baseDelay' | 'maxDelay'>>","context: FetchErrorContext","options: FetchSetupOptions","client: T","ClientClass: new (configuration?: unknown) => T","createAPIConfig: (request: Request, options?: CreateAPIConfigOptions) => Promise<APIConfig>","ConfigurationClass: new (params?: Record<string, unknown>) => unknown","options: CreateApiClientOptions"],"sources":["../src/api-client/api-config.server.ts","../src/api-client/fetch-client.server.ts"],"sourcesContent":["/**\n * API Configuration Server Module\n *\n * Centralized configuration for all API clients,\n * automatically handling authentication tokens and tenant context.\n */\n\nimport type { APIConfig, CreateAPIConfigOptions, GetAccessTokenFn, GetCurrentTenantFn, APILogger } from './types';\n\n/**\n * Base URL Configuration\n * Single unified base URL for all API operations\n */\nconst DEFAULT_API_BASE_URL = process.env.API_BASE_URL || '';\n\n/**\n * Default Headers\n * Applied to all API requests\n */\nconst DEFAULT_HEADERS: Record<string, string> = {\n Accept: 'application/json, application/problem+json',\n 'Content-Type': 'application/json',\n};\n\n/**\n * API Config Factory Options\n */\nexport interface APIConfigFactoryOptions {\n /**\n * Base URL for API requests\n */\n baseURL?: string;\n /**\n * Default headers applied to all requests\n */\n defaultHeaders?: Record<string, string>;\n /**\n * User agent string\n */\n userAgent?: string;\n /**\n * Default timeout in milliseconds\n */\n timeout?: number;\n /**\n * Header name used for bearer-style auth. Set to null when buildHeaders owns auth.\n * @default 'Authorization'\n */\n authHeaderName?: string | null;\n /**\n * Build an auth header value from the resolved access token.\n * @default token => `Bearer ${token}`\n */\n authHeaderValue?: (accessToken: string) => string;\n /**\n * Header name used for tenant context. Set to null when buildHeaders owns tenancy.\n * @default 'X-Tenant-Id'\n */\n tenantHeaderName?: string | null;\n /**\n * Final app-specific header hook. Returned headers are merged last.\n */\n buildHeaders?: (context: APIHeaderStrategyContext) => Record<string, string>;\n}\n\nexport interface APIHeaderStrategyContext {\n request: Request;\n options: CreateAPIConfigOptions;\n accessToken?: string;\n tenantId: string | null;\n includeAuth: boolean;\n requireTenant: boolean;\n}\n\n/**\n * Create API Config Factory\n *\n * Creates a factory function that generates API configurations\n * with the provided auth and tenant resolvers.\n */\nexport function createAPIConfigFactory(\n getAccessToken: GetAccessTokenFn,\n getCurrentTenant: GetCurrentTenantFn,\n logger?: APILogger,\n factoryOptions: APIConfigFactoryOptions = {}\n) {\n const {\n baseURL = DEFAULT_API_BASE_URL,\n defaultHeaders = DEFAULT_HEADERS,\n userAgent = 'Spine/1.0',\n timeout = 30000,\n authHeaderName = 'Authorization',\n authHeaderValue = (token: string) => `Bearer ${token}`,\n tenantHeaderName = 'X-Tenant-Id',\n buildHeaders,\n } = factoryOptions;\n\n /**\n * Resolve tenant ID from request or options\n */\n async function resolveTenantId(\n request: Request,\n options: CreateAPIConfigOptions\n ): Promise<string | null> {\n // Use explicit tenant ID if provided\n if (options.tenantId) {\n logger?.debug?.('Using explicit tenant ID', { tenantId: options.tenantId });\n return options.tenantId;\n }\n\n // Resolve from current tenant context\n try {\n const tenantId = await getCurrentTenant(request);\n if (tenantId) {\n logger?.debug?.('Resolved tenant from context', { tenantId });\n }\n return tenantId;\n } catch (error) {\n logger?.warn?.('Failed to resolve current tenant', error instanceof Error ? error : undefined);\n return null;\n }\n }\n\n /**\n * Creates unified API configuration for all services.\n *\n * This function automatically:\n * - Adds authentication token using the configured auth header strategy\n * - Injects tenant context using the configured tenant header strategy\n * - Configures base URL from options or environment\n * - Applies default headers\n *\n * @param request - The incoming request object\n * @param options - Configuration options\n * @returns API configuration object\n * @throws Error if required authentication or tenant context is missing\n *\n * @example\n * `\typescript\n * // Standard usage with auth and tenant\n * const config = await createAPIConfig(request);\n * const api = new IdentityApi(config);\n *\n * // Without tenant requirement\n * const config = await createAPIConfig(request, { requireTenant: false });\n *\n * // With explicit tenant override\n * const config = await createAPIConfig(request, { tenantId: 'specific-tenant-id' });\n * `\n */\n async function createAPIConfig(\n request: Request,\n options: CreateAPIConfigOptions = {}\n ): Promise<APIConfig> {\n const {\n requireTenant = true,\n includeAuth = true,\n customHeaders = {},\n } = options;\n\n // Start with default headers\n const headers: Record<string, string> = {\n ...defaultHeaders,\n 'User-Agent': userAgent,\n ...customHeaders,\n };\n\n let accessToken: string | undefined;\n\n // Add authentication if required\n if (includeAuth) {\n const token = await getAccessToken(request);\n if (!token) {\n logger?.error?.('No access token available for API request');\n throw new Error('No access token available');\n }\n\n accessToken = token;\n if (authHeaderName) {\n headers[authHeaderName] = authHeaderValue(token);\n }\n logger?.debug?.('Added authorization header to API config');\n }\n\n // Resolve tenant context\n const tenantId = await resolveTenantId(request, options);\n\n // Add tenant header if required\n if (requireTenant) {\n if (!tenantId) {\n logger?.error?.('Tenant context required but not available');\n throw new Error('Tenant context is required for this operation');\n }\n\n if (tenantHeaderName) {\n headers[tenantHeaderName] = tenantId;\n }\n logger?.debug?.('Added tenant context header', { tenantId });\n }\n\n if (buildHeaders) {\n Object.assign(headers, buildHeaders({\n request,\n options,\n accessToken,\n tenantId,\n includeAuth,\n requireTenant,\n }));\n }\n\n logger?.debug?.('API config created', {\n basePath: baseURL,\n hasAuth: includeAuth,\n hasTenant: !!tenantId,\n requireTenant,\n });\n\n return {\n basePath: baseURL,\n accessToken,\n headers,\n tenantId: tenantId || '',\n baseOptions: {\n timeout,\n },\n };\n }\n\n /**\n * Get the configured API base URL\n */\n function getAPIBaseURL(): string {\n return baseURL;\n }\n\n return {\n createAPIConfig,\n getAPIBaseURL,\n };\n}\n\nexport type APIConfigFactory = ReturnType<typeof createAPIConfigFactory>;\n","/**\n * Fetch-native API client setup for generated OpenAPI clients.\n *\n * This module preserves the shared request behaviors we need around fetch:\n * - request ID enrichment\n * - serialized token refresh on 401\n * - retry with exponential backoff\n * - ProblemDetails-aware error shaping\n *\n * It gives downstream apps a single fetch-native entry point for generated clients.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type {\n APIClientError,\n APIConfig,\n APIResponse,\n APILogger,\n CreateAPIConfigOptions,\n EnhancedAPIClient,\n FetchErrorContext,\n FetchMiddleware,\n FetchResponseContext,\n ProblemDetails,\n RetryConfig,\n TokenRefreshFn,\n TokenRefreshResult,\n} from './types';\nimport { isApiClientError } from './types';\nimport { calculateBackoffDelay, fetchWithTimeout, isRetryableError } from './retry-handler';\n\ntype RuntimeApiResponse<T> = {\n raw: Response;\n value(): Promise<T>;\n};\n\ntype GeneratedFetchClient = object;\n\ntype SpineRequestInit = RequestInit & {\n __spineMeta?: {\n requestId?: string;\n retryCount?: number;\n refreshed?: boolean;\n };\n};\n\ntype ResponseRequestMeta = {\n url: string;\n method: string;\n headers: Record<string, string>;\n};\n\nconst refreshPromiseMap = new Map<string, Promise<TokenRefreshResult>>();\nconst responseRequestMeta = new WeakMap<Response, ResponseRequestMeta>();\nconst rawResponseStore = new AsyncLocalStorage<Map<string, RuntimeApiResponse<unknown>>>();\n\nfunction getSessionKeyFromRequest(request: Request): string {\n const cookie = request.headers.get('cookie') || '';\n return `session:${cookie.slice(0, 50)}`;\n}\n\nfunction getOrCreateRefreshPromise(\n sessionKey: string,\n refreshFn: () => Promise<TokenRefreshResult>,\n logger?: APILogger\n): Promise<TokenRefreshResult> {\n const existingPromise = refreshPromiseMap.get(sessionKey);\n if (existingPromise) {\n logger?.info?.('Token refresh already in progress, waiting for existing refresh');\n return existingPromise;\n }\n\n logger?.info?.('Starting new token refresh');\n\n const refreshPromise = refreshFn().finally(() => {\n refreshPromiseMap.delete(sessionKey);\n });\n\n refreshPromiseMap.set(sessionKey, refreshPromise);\n return refreshPromise;\n}\n\nfunction ensureRequestMeta(init: SpineRequestInit): NonNullable<SpineRequestInit['__spineMeta']> {\n if (!init.__spineMeta) {\n init.__spineMeta = {};\n }\n\n return init.__spineMeta;\n}\n\nfunction headersToRecord(headersInit?: HeadersInit): Record<string, string> {\n return Object.fromEntries(new Headers(headersInit).entries());\n}\n\nfunction cloneInit(init: RequestInit): SpineRequestInit {\n const source = init as SpineRequestInit;\n\n return {\n ...source,\n headers: headersToRecord(source.headers),\n __spineMeta: source.__spineMeta ? { ...source.__spineMeta } : undefined,\n };\n}\n\nfunction createTimeoutFetch(timeout?: number): typeof fetch | undefined {\n if (!timeout) {\n return undefined;\n }\n\n return (input, init) => fetchWithTimeout(input, { ...init, timeout });\n}\n\nfunction isProblemDetails(value: unknown): value is ProblemDetails {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'title' in value &&\n 'status' in value &&\n 'detail' in value\n );\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const clone = response.clone();\n const contentType = clone.headers.get('content-type') || '';\n\n if (contentType.includes('application/json') || contentType.includes('+json')) {\n try {\n return await clone.json();\n } catch {\n return undefined;\n }\n }\n\n try {\n const text = await clone.text();\n return text || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction createClientError<T = unknown>(params: {\n message: string;\n response?: APIResponse<T>;\n config?: ResponseRequestMeta;\n problemDetails?: ProblemDetails;\n shouldLogout?: boolean;\n originalError?: unknown;\n cause?: unknown;\n}): APIClientError<T> {\n const error = new Error(params.message) as APIClientError<T>;\n\n error.name = 'APIClientError';\n error.isApiClientError = true;\n error.response = params.response;\n error.config = params.config;\n error.problemDetails = params.problemDetails;\n error.shouldLogout = params.shouldLogout;\n error.originalError = params.originalError;\n error.cause = params.cause;\n\n return error;\n}\n\nasync function toAPIResponse<T>(\n rawResponse: Response,\n resolvedData?: T\n): Promise<APIResponse<T>> {\n const data = resolvedData === undefined ? ((await parseResponseBody(rawResponse)) as T) : resolvedData;\n\n return {\n data,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: headersToRecord(rawResponse.headers),\n raw: rawResponse,\n };\n}\n\nasync function normalizeClientError(error: unknown): Promise<APIClientError> {\n if (isApiClientError(error)) {\n return error;\n }\n\n if (error && typeof error === 'object' && 'response' in error && (error as { response?: unknown }).response instanceof Response) {\n const response = (error as { response: Response }).response;\n const responseData = await parseResponseBody(response);\n const problemDetails = isProblemDetails(responseData) ? responseData : undefined;\n\n return createClientError({\n message:\n problemDetails?.detail ||\n problemDetails?.title ||\n response.statusText ||\n 'API request failed',\n response: await toAPIResponse(response, responseData),\n config: responseRequestMeta.get(response),\n problemDetails,\n cause: error,\n });\n }\n\n return createClientError({\n message: error instanceof Error ? error.message : 'API request failed',\n cause: error,\n });\n}\n\nfunction isRetryableFetchError(error: unknown): boolean {\n if (isRetryableError(error)) {\n return true;\n }\n\n if (error && typeof error === 'object' && 'cause' in error) {\n return isRetryableError((error as { cause?: unknown }).cause);\n }\n\n return false;\n}\n\nasync function maybeRetryResponse(\n context: FetchResponseContext,\n retryConfig: Required<Pick<RetryConfig, 'maxRetries' | 'baseDelay' | 'maxDelay'>>,\n logger?: APILogger\n): Promise<Response | undefined> {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n\n if (context.response.status === 401 || context.response.status === 409) {\n return undefined;\n }\n\n if (!isRetryableError(context.response)) {\n return undefined;\n }\n\n const retryCount = meta.retryCount ?? 0;\n if (retryCount >= retryConfig.maxRetries) {\n return undefined;\n }\n\n meta.retryCount = retryCount + 1;\n\n const delay = calculateBackoffDelay(meta.retryCount, retryConfig.baseDelay, retryConfig.maxDelay);\n logger?.info?.('Retrying request', {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n attempt: meta.retryCount,\n maxRetries: retryConfig.maxRetries,\n delay,\n status: context.response.status,\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return context.fetch(context.url, init);\n}\n\nasync function maybeRetryError(\n context: FetchErrorContext,\n retryConfig: Required<Pick<RetryConfig, 'maxRetries' | 'baseDelay' | 'maxDelay'>>,\n logger?: APILogger\n): Promise<Response | undefined> {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n const retryCount = meta.retryCount ?? 0;\n\n if (!isRetryableFetchError(context.error) || retryCount >= retryConfig.maxRetries) {\n return undefined;\n }\n\n meta.retryCount = retryCount + 1;\n\n const delay = calculateBackoffDelay(meta.retryCount, retryConfig.baseDelay, retryConfig.maxDelay);\n logger?.info?.('Retrying request after fetch failure', {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n attempt: meta.retryCount,\n maxRetries: retryConfig.maxRetries,\n delay,\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return context.fetch(context.url, init);\n}\n\nexport interface FetchSetupOptions {\n logger?: APILogger;\n attemptTokenRefresh?: TokenRefreshFn;\n retryConfig?: RetryConfig;\n addRequestId?: boolean;\n}\n\nexport function createFetchMiddleware(\n request: Request,\n options: FetchSetupOptions = {}\n): FetchMiddleware[] {\n const {\n logger,\n attemptTokenRefresh,\n retryConfig = {},\n addRequestId = true,\n } = options;\n\n const normalizedRetryConfig = {\n maxRetries: retryConfig.maxRetries ?? 3,\n baseDelay: retryConfig.baseDelay ?? 1000,\n maxDelay: retryConfig.maxDelay ?? 10000,\n };\n\n return [\n {\n async pre(context) {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n const headers = new Headers(init.headers);\n\n if (addRequestId) {\n const requestId = headers.get('X-Request-Id') || crypto.randomUUID();\n headers.set('X-Request-Id', requestId);\n meta.requestId = requestId;\n }\n\n init.headers = headersToRecord(headers);\n\n logger?.debug?.('API request initiated', {\n method: (init.method ?? 'GET').toUpperCase(),\n url: context.url,\n requestId: meta.requestId,\n });\n\n return {\n url: context.url,\n init,\n };\n },\n\n async post(context) {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n\n responseRequestMeta.set(context.response, {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n headers: headersToRecord(init.headers),\n });\n\n if (context.response.status === 401 && attemptTokenRefresh && !meta.refreshed) {\n meta.refreshed = true;\n\n logger?.info?.('Received 401 from backend, attempting token refresh', {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n });\n\n const refreshResult = await getOrCreateRefreshPromise(\n getSessionKeyFromRequest(request),\n () => attemptTokenRefresh(request),\n logger\n );\n\n if (refreshResult.success && refreshResult.newAccessToken) {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${refreshResult.newAccessToken}`);\n init.headers = headersToRecord(headers);\n\n logger?.info?.('Token refresh successful, retrying original request');\n\n return context.fetch(context.url, init);\n }\n\n if (refreshResult.shouldLogout) {\n throw createClientError({\n message: 'REFRESH_TOKEN_EXPIRED',\n response: await toAPIResponse(context.response),\n config: responseRequestMeta.get(context.response),\n shouldLogout: true,\n originalError: refreshResult,\n cause: refreshResult,\n });\n }\n }\n\n const retryResponse = await maybeRetryResponse(context, normalizedRetryConfig, logger);\n if (retryResponse) {\n return retryResponse;\n }\n\n if (context.response.status >= 400) {\n const responseData = await parseResponseBody(context.response);\n const problemDetails = isProblemDetails(responseData) ? responseData : undefined;\n\n logger?.error?.('API error response received', undefined, {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n status: context.response.status,\n code: problemDetails?.title,\n detail: problemDetails?.detail,\n traceId: problemDetails?.traceId,\n });\n }\n\n return context.response;\n },\n\n async onError(context) {\n const retryResponse = await maybeRetryError(context, normalizedRetryConfig, logger);\n if (retryResponse) {\n return retryResponse;\n }\n\n return undefined;\n },\n },\n ];\n}\n\nexport interface CreateApiClientOptions extends FetchSetupOptions, CreateAPIConfigOptions {\n credentials?: RequestCredentials;\n}\n\nfunction instrumentRawMethods<T extends GeneratedFetchClient>(client: T): void {\n if ((client as { __spineRawMethodsInstrumented?: boolean }).__spineRawMethodsInstrumented) {\n return;\n }\n\n const prototype = Object.getPrototypeOf(client) as Record<string, unknown>;\n\n for (const key of Object.getOwnPropertyNames(prototype)) {\n if (!key.endsWith('Raw')) {\n continue;\n }\n\n const original = prototype[key];\n if (typeof original !== 'function') {\n continue;\n }\n\n Object.defineProperty(client, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: async (...args: unknown[]) => {\n const result = await (original as (...innerArgs: unknown[]) => Promise<RuntimeApiResponse<unknown>>).apply(client, args);\n rawResponseStore.getStore()?.set(key, result);\n return result;\n },\n });\n }\n\n (client as { __spineRawMethodsInstrumented?: boolean }).__spineRawMethodsInstrumented = true;\n}\n\nfunction wrapClient<T extends GeneratedFetchClient>(client: T): EnhancedAPIClient<T> {\n instrumentRawMethods(client);\n\n const methodCache = new Map<PropertyKey, unknown>();\n\n return new Proxy(client, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop.endsWith('Raw')) {\n return typeof value === 'function' ? value.bind(target) : value;\n }\n\n if (methodCache.has(prop)) {\n return methodCache.get(prop);\n }\n\n const wrapped = async (...args: unknown[]) =>\n rawResponseStore.run(new Map(), async () => {\n try {\n const resolvedData = await (value as (...innerArgs: unknown[]) => Promise<unknown>).apply(target, args);\n const rawResponse = rawResponseStore.getStore()?.get(`${prop}Raw`);\n\n if (rawResponse) {\n return toAPIResponse(rawResponse.raw, resolvedData);\n }\n\n return {\n data: resolvedData,\n status: 200,\n statusText: 'OK',\n headers: {},\n };\n } catch (error) {\n throw await normalizeClientError(error);\n }\n });\n\n methodCache.set(prop, wrapped);\n return wrapped;\n },\n }) as EnhancedAPIClient<T>;\n}\n\nexport async function createApiClient<T extends GeneratedFetchClient>(\n request: Request,\n ClientClass: new (configuration?: unknown) => T,\n createAPIConfig: (request: Request, options?: CreateAPIConfigOptions) => Promise<APIConfig>,\n ConfigurationClass: new (params?: Record<string, unknown>) => unknown,\n options: CreateApiClientOptions = {}\n): Promise<{ client: EnhancedAPIClient<T>; tenantId: string }> {\n const {\n requireTenant,\n includeAuth,\n tenantId,\n customHeaders,\n credentials,\n ...fetchOptions\n } = options;\n\n const config = await createAPIConfig(request, {\n requireTenant,\n includeAuth,\n tenantId,\n customHeaders,\n });\n\n const configuration = new ConfigurationClass({\n basePath: config.basePath,\n accessToken: config.accessToken,\n headers: config.headers,\n credentials: credentials ?? config.credentials,\n middleware: createFetchMiddleware(request, fetchOptions),\n fetchApi: createTimeoutFetch(config.baseOptions?.timeout),\n });\n\n const client = new ClientClass(configuration);\n\n return {\n client: wrapClient(client),\n tenantId: config.tenantId,\n };\n}\n"],"mappings":";;;;;;;;;AAaA,MAAM,uBAAuB,QAAQ,IAAI,gBAAgB;;;;;AAMzD,MAAMA,kBAA0C;CAC9C,QAAQ;CACR,gBAAgB;AACjB;;;;;;;AA0DD,SAAgB,uBACdC,gBACAC,kBACAC,QACAC,iBAA0C,CAAE,GAC5C;CACA,MAAM,EACJ,UAAU,sBACV,iBAAiB,iBACjB,YAAY,aACZ,UAAU,KACV,iBAAiB,iBACjB,kBAAkB,CAACC,WAAmB,SAAS,MAAM,GACrD,mBAAmB,eACnB,cACD,GAAG;;;;CAKJ,eAAe,gBACbC,SACAC,SACwB;AAExB,MAAI,QAAQ,UAAU;AACpB,WAAQ,QAAQ,4BAA4B,EAAE,UAAU,QAAQ,SAAU,EAAC;AAC3E,UAAO,QAAQ;EAChB;AAGD,MAAI;GACF,MAAM,WAAW,MAAM,iBAAiB,QAAQ;AAChD,OAAI,SACF,SAAQ,QAAQ,gCAAgC,EAAE,SAAU,EAAC;AAE/D,UAAO;EACR,SAAQ,OAAO;AACd,WAAQ,OAAO,oCAAoC,iBAAiB,QAAQ,eAAkB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AAO;EACL,QAAQ,WAAW,OAAO;EAC1B,UAAU,OAAO;CAClB;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { getAuthSession } from "./redis-session-storage.server-
|
|
1
|
+
import { getAuthSession } from "./redis-session-storage.server-v2VcpFsQ.js";
|
|
2
2
|
|
|
3
3
|
//#region src/tenant/tenant-cookie.server.ts
|
|
4
4
|
const DEFAULT_TENANT_COOKIE_CONFIG = {
|
|
5
|
-
name: "
|
|
5
|
+
name: "__spine_tenant",
|
|
6
6
|
maxAge: 60 * 60 * 24 * 365,
|
|
7
7
|
path: "/",
|
|
8
8
|
secure: process.env.NODE_ENV === "production",
|
|
@@ -13,6 +13,14 @@ let tenantCookieConfig = { ...DEFAULT_TENANT_COOKIE_CONFIG };
|
|
|
13
13
|
function getTenantCookieConfig() {
|
|
14
14
|
return tenantCookieConfig;
|
|
15
15
|
}
|
|
16
|
+
function readCookieValue(cookieHeader, name) {
|
|
17
|
+
for (const segment of cookieHeader.split(";")) {
|
|
18
|
+
const [rawName, ...rawValue] = segment.split("=");
|
|
19
|
+
if (rawName?.trim() !== name || rawValue.length === 0) continue;
|
|
20
|
+
return decodeURIComponent(rawValue.join("="));
|
|
21
|
+
}
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
16
24
|
/**
|
|
17
25
|
* Get active tenant from cookie
|
|
18
26
|
*/
|
|
@@ -20,9 +28,7 @@ async function getActiveTenant(request) {
|
|
|
20
28
|
const config = getTenantCookieConfig();
|
|
21
29
|
const cookies = request.headers.get("Cookie");
|
|
22
30
|
if (!cookies) return null;
|
|
23
|
-
|
|
24
|
-
if (!match) return null;
|
|
25
|
-
return decodeURIComponent(match[1]);
|
|
31
|
+
return readCookieValue(cookies, config.name);
|
|
26
32
|
}
|
|
27
33
|
/**
|
|
28
34
|
* Set active tenant cookie value
|
|
@@ -61,6 +67,11 @@ function resetTenantCookieConfig() {
|
|
|
61
67
|
//#endregion
|
|
62
68
|
//#region src/tenant/tenant.server.ts
|
|
63
69
|
let identityContextFetcher = null;
|
|
70
|
+
let resolveInitialTenant = ({ identityContext }) => {
|
|
71
|
+
const membership = identityContext?.memberships?.[0];
|
|
72
|
+
return membership?.tenantId ?? membership?.id ?? null;
|
|
73
|
+
};
|
|
74
|
+
let resolveAvailableTenants = ({ identityContext }) => identityContext?.memberships?.map((membership) => membership.tenantId ?? membership.id).filter((tenantId) => Boolean(tenantId)) ?? [];
|
|
64
75
|
/**
|
|
65
76
|
* Configure identity context fetcher
|
|
66
77
|
*/
|
|
@@ -68,6 +79,22 @@ function configureIdentityContextFetcher(fetcher) {
|
|
|
68
79
|
identityContextFetcher = fetcher;
|
|
69
80
|
}
|
|
70
81
|
/**
|
|
82
|
+
* Configure tenant resolution for custom backend identity contracts.
|
|
83
|
+
*/
|
|
84
|
+
function configureTenantResolution(config) {
|
|
85
|
+
if (config.identityContextFetcher) identityContextFetcher = config.identityContextFetcher;
|
|
86
|
+
if (config.resolveInitialTenant) resolveInitialTenant = config.resolveInitialTenant;
|
|
87
|
+
if (config.resolveAvailableTenants) resolveAvailableTenants = config.resolveAvailableTenants;
|
|
88
|
+
}
|
|
89
|
+
function resetTenantResolutionConfig() {
|
|
90
|
+
identityContextFetcher = null;
|
|
91
|
+
resolveInitialTenant = ({ identityContext }) => {
|
|
92
|
+
const membership = identityContext?.memberships?.[0];
|
|
93
|
+
return membership?.tenantId ?? membership?.id ?? null;
|
|
94
|
+
};
|
|
95
|
+
resolveAvailableTenants = ({ identityContext }) => identityContext?.memberships?.map((membership) => membership.tenantId ?? membership.id).filter((tenantId) => Boolean(tenantId)) ?? [];
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
71
98
|
* Get current active tenant from cookie
|
|
72
99
|
*/
|
|
73
100
|
async function getCurrentTenant(request) {
|
|
@@ -92,8 +119,11 @@ async function getTenantFromIdentityContext(request) {
|
|
|
92
119
|
return null;
|
|
93
120
|
}
|
|
94
121
|
const context = await identityContextFetcher(request);
|
|
95
|
-
|
|
96
|
-
|
|
122
|
+
return resolveInitialTenant({
|
|
123
|
+
request,
|
|
124
|
+
session: sessionData,
|
|
125
|
+
identityContext: context
|
|
126
|
+
});
|
|
97
127
|
} catch (error) {
|
|
98
128
|
console.error("Error getting tenant from identity context:", error);
|
|
99
129
|
return null;
|
|
@@ -111,8 +141,11 @@ async function getAvailableTenants(request) {
|
|
|
111
141
|
return [];
|
|
112
142
|
}
|
|
113
143
|
const context = await identityContextFetcher(request);
|
|
114
|
-
|
|
115
|
-
|
|
144
|
+
return resolveAvailableTenants({
|
|
145
|
+
request,
|
|
146
|
+
session: sessionData,
|
|
147
|
+
identityContext: context
|
|
148
|
+
});
|
|
116
149
|
} catch (error) {
|
|
117
150
|
console.error("Error getting available tenants:", error);
|
|
118
151
|
return [];
|
|
@@ -181,5 +214,5 @@ async function clearCurrentTenant() {
|
|
|
181
214
|
}
|
|
182
215
|
|
|
183
216
|
//#endregion
|
|
184
|
-
export { clearActiveTenant, clearCurrentTenant, configureIdentityContextFetcher, configureTenantCookie, getActiveTenant, getAvailableTenants, getCurrentTenant, getTenantFromIdentityContext, initializeTenant, resetTenantCookieConfig, setActiveTenant, setCurrentTenant };
|
|
185
|
-
//# sourceMappingURL=server-
|
|
217
|
+
export { clearActiveTenant, clearCurrentTenant, configureIdentityContextFetcher, configureTenantCookie, configureTenantResolution, getActiveTenant, getAvailableTenants, getCurrentTenant, getTenantFromIdentityContext, initializeTenant, resetTenantCookieConfig, resetTenantResolutionConfig, setActiveTenant, setCurrentTenant };
|
|
218
|
+
//# sourceMappingURL=server-Ca-3DJf2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-Ca-3DJf2.js","names":["DEFAULT_TENANT_COOKIE_CONFIG: Required<TenantCookieConfig>","tenantCookieConfig: Required<TenantCookieConfig>","cookieHeader: string","name: string","request: Request","tenantId: string","config: TenantCookieConfig","identityContextFetcher: IdentityContextFetcher | null","resolveInitialTenant: NonNullable<TenantResolutionConfig['resolveInitialTenant']>","resolveAvailableTenants: NonNullable<TenantResolutionConfig['resolveAvailableTenants']>","fetcher: IdentityContextFetcher","config: TenantResolutionConfig","request: Request","tenantId: string"],"sources":["../src/tenant/tenant-cookie.server.ts","../src/tenant/tenant.server.ts"],"sourcesContent":["/**\n * Tenant Cookie Server Module\n * \n * Cookie-based tenant storage.\n */\n\nexport type TenantCookieSameSite = 'Strict' | 'Lax' | 'None';\n\nexport interface TenantCookieConfig {\n name?: string;\n maxAge?: number;\n path?: string;\n secure?: boolean;\n httpOnly?: boolean;\n sameSite?: TenantCookieSameSite;\n}\n\nconst DEFAULT_TENANT_COOKIE_CONFIG: Required<TenantCookieConfig> = {\n name: '__spine_tenant',\n maxAge: 60 * 60 * 24 * 365,\n path: '/',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: false,\n sameSite: 'Lax',\n};\n\nlet tenantCookieConfig: Required<TenantCookieConfig> = {\n ...DEFAULT_TENANT_COOKIE_CONFIG,\n};\n\nfunction getTenantCookieConfig(): Required<TenantCookieConfig> {\n return tenantCookieConfig;\n}\n\nfunction readCookieValue(cookieHeader: string, name: string): string | null {\n for (const segment of cookieHeader.split(';')) {\n const [rawName, ...rawValue] = segment.split('=');\n if (rawName?.trim() !== name || rawValue.length === 0) {\n continue;\n }\n\n return decodeURIComponent(rawValue.join('='));\n }\n\n return null;\n}\n\n/**\n * Get active tenant from cookie\n */\nexport async function getActiveTenant(request: Request): Promise<string | null> {\n const config = getTenantCookieConfig();\n const cookies = request.headers.get('Cookie');\n if (!cookies) return null;\n\n return readCookieValue(cookies, config.name);\n}\n\n/**\n * Set active tenant cookie value\n */\nexport async function setActiveTenant(tenantId: string): Promise<string> {\n const config = getTenantCookieConfig();\n const secure = config.secure ? '; Secure' : '';\n const httpOnly = config.httpOnly ? '; HttpOnly' : '';\n return `${config.name}=${encodeURIComponent(tenantId)}; Path=${config.path}${httpOnly}; SameSite=${config.sameSite}; Max-Age=${config.maxAge}${secure}`;\n}\n\n/**\n * Clear active tenant cookie value\n */\nexport async function clearActiveTenant(): Promise<string> {\n const config = getTenantCookieConfig();\n const secure = config.secure ? '; Secure' : '';\n const httpOnly = config.httpOnly ? '; HttpOnly' : '';\n return `${config.name}=; Path=${config.path}${httpOnly}; SameSite=${config.sameSite}; Max-Age=0${secure}`;\n}\n\n/**\n * Configure tenant cookie name\n */\nexport function configureTenantCookie(config: TenantCookieConfig): void {\n tenantCookieConfig = {\n ...tenantCookieConfig,\n ...config,\n };\n}\n\n/**\n * Reset tenant cookie config back to defaults.\n */\nexport function resetTenantCookieConfig(): void {\n tenantCookieConfig = {\n ...DEFAULT_TENANT_COOKIE_CONFIG,\n };\n}\n","/**\n * Tenant Server Module\n * \n * Server-side tenant management.\n */\n\nimport { getAuthSession } from '../auth/redis-session-storage.server';\nimport { getActiveTenant, setActiveTenant, clearActiveTenant } from './tenant-cookie.server';\nimport type { SessionData } from '../auth/types';\n\n/**\n * Identity context fetcher type (to avoid circular dependency)\n */\nexport type IdentityContextFetcher = (request: Request) => Promise<{\n memberships?: Array<{ tenantId?: string; id?: string; [key: string]: unknown }>;\n [key: string]: unknown;\n} | null>;\n\nexport interface TenantResolutionContext {\n request: Request;\n session: SessionData;\n identityContext: Awaited<ReturnType<IdentityContextFetcher>>;\n}\n\nexport interface TenantResolutionConfig {\n identityContextFetcher?: IdentityContextFetcher;\n resolveInitialTenant?: (context: TenantResolutionContext) => Promise<string | null> | string | null;\n resolveAvailableTenants?: (context: TenantResolutionContext) => Promise<string[]> | string[];\n}\n\nlet identityContextFetcher: IdentityContextFetcher | null = null;\nlet resolveInitialTenant: NonNullable<TenantResolutionConfig['resolveInitialTenant']> =\n ({ identityContext }) => {\n const membership = identityContext?.memberships?.[0];\n return membership?.tenantId ?? membership?.id ?? null;\n };\nlet resolveAvailableTenants: NonNullable<TenantResolutionConfig['resolveAvailableTenants']> =\n ({ identityContext }) =>\n identityContext?.memberships\n ?.map((membership) => membership.tenantId ?? membership.id)\n .filter((tenantId): tenantId is string => Boolean(tenantId)) ?? [];\n\n/**\n * Configure identity context fetcher\n */\nexport function configureIdentityContextFetcher(fetcher: IdentityContextFetcher): void {\n identityContextFetcher = fetcher;\n}\n\n/**\n * Configure tenant resolution for custom backend identity contracts.\n */\nexport function configureTenantResolution(config: TenantResolutionConfig): void {\n if (config.identityContextFetcher) {\n identityContextFetcher = config.identityContextFetcher;\n }\n if (config.resolveInitialTenant) {\n resolveInitialTenant = config.resolveInitialTenant;\n }\n if (config.resolveAvailableTenants) {\n resolveAvailableTenants = config.resolveAvailableTenants;\n }\n}\n\nexport function resetTenantResolutionConfig(): void {\n identityContextFetcher = null;\n resolveInitialTenant = ({ identityContext }) => {\n const membership = identityContext?.memberships?.[0];\n return membership?.tenantId ?? membership?.id ?? null;\n };\n resolveAvailableTenants = ({ identityContext }) =>\n identityContext?.memberships\n ?.map((membership) => membership.tenantId ?? membership.id)\n .filter((tenantId): tenantId is string => Boolean(tenantId)) ?? [];\n}\n\n/**\n * Get current active tenant from cookie\n */\nexport async function getCurrentTenant(request: Request): Promise<string | null> {\n try {\n const tenantFromCookie = await getActiveTenant(request);\n if (tenantFromCookie) {\n return tenantFromCookie;\n }\n return null;\n } catch (error) {\n console.error('Error getting current tenant:', error);\n return null;\n }\n}\n\n/**\n * Get tenant from identity context\n */\nexport async function getTenantFromIdentityContext(request: Request): Promise<string | null> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user?.sub) {\n return null;\n }\n\n if (!identityContextFetcher) {\n console.warn('Identity context fetcher not configured');\n return null;\n }\n\n const context = await identityContextFetcher(request);\n return resolveInitialTenant({ request, session: sessionData, identityContext: context });\n } catch (error) {\n console.error('Error getting tenant from identity context:', error);\n return null;\n }\n}\n\n/**\n * Get available tenants from identity context\n */\nexport async function getAvailableTenants(request: Request): Promise<string[]> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user?.sub) {\n return [];\n }\n\n if (!identityContextFetcher) {\n console.warn('Identity context fetcher not configured');\n return [];\n }\n\n const context = await identityContextFetcher(request);\n return resolveAvailableTenants({ request, session: sessionData, identityContext: context });\n } catch (error) {\n console.error('Error getting available tenants:', error);\n return [];\n }\n}\n\n/**\n * Set current active tenant\n */\nexport async function setCurrentTenant(\n request: Request,\n tenantId: string\n): Promise<{ headers: Headers; success: boolean; error?: string }> {\n try {\n const sessionData = await getAuthSession(request);\n\n if (!sessionData.user) {\n return { headers: new Headers(), success: false, error: 'No active session' };\n }\n\n const cookieValue = await setActiveTenant(tenantId);\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n\n return { headers, success: true };\n } catch (error) {\n console.error('Failed to set current tenant:', error);\n return {\n headers: new Headers(),\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n}\n\n/**\n * Initialize tenant on first login\n */\nexport async function initializeTenant(\n request: Request\n): Promise<{ headers: Headers; tenantId: string } | null> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user) {\n return null;\n }\n\n // Check if tenant is already set in cookie\n const currentTenant = await getCurrentTenant(request);\n if (currentTenant) {\n return null;\n }\n\n // Get tenant from identity context\n const tenantId = await getTenantFromIdentityContext(request);\n\n if (tenantId) {\n const cookieValue = await setActiveTenant(tenantId);\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n return { headers, tenantId };\n }\n\n return null;\n } catch (error) {\n console.error('Failed to initialize tenant:', error);\n return null;\n }\n}\n\n/**\n * Clear current tenant\n */\nexport async function clearCurrentTenant(): Promise<Headers> {\n const cookieValue = await clearActiveTenant();\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n return headers;\n}\n"],"mappings":";;;AAiBA,MAAMA,+BAA6D;CACjE,MAAM;CACN,QAAQ,KAAK,KAAK,KAAK;CACvB,MAAM;CACN,QAAQ,QAAQ,IAAI,aAAa;CACjC,UAAU;CACV,UAAU;AACX;AAED,IAAIC,qBAAmD,EACrD,GAAG,6BACJ;AAED,SAAS,wBAAsD;AAC7D,QAAO;AACR;AAED,SAAS,gBAAg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AAM,gCAAgC,MAAM;AACpD,SAAO;CACR;AACF;;;;AAKD,eAAsB,qBAAuC;CAC3D,MAAM,cAAc,MAAM,mBAAmB;CAC7C,MAAM,UAAU,IAAI;AACpB,SAAQ,OAAO,cAAc,YAAY;AACzC,QAAO;AACR"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { logger } from "./logging-
|
|
2
|
-
import { isApiClientError } from "./types-
|
|
1
|
+
import { logger } from "./logging-DviiAkLx.js";
|
|
2
|
+
import { isApiClientError } from "./types-BaaE6wjY.js";
|
|
3
3
|
|
|
4
4
|
//#region src/identity/identity-context.server.ts
|
|
5
5
|
let identityAPIFetcher = null;
|
|
@@ -21,7 +21,7 @@ async function fetchIdentityContext(request) {
|
|
|
21
21
|
const context = await identityAPIFetcher(request);
|
|
22
22
|
logger.debug("Identity context fetched", {
|
|
23
23
|
hasAnyMembership: context.hasAnyMembership,
|
|
24
|
-
|
|
24
|
+
hasEntitlement: context.hasEntitlement ?? context.hasSubscription,
|
|
25
25
|
isOnboarded: context.isOnboarded,
|
|
26
26
|
membershipCount: context.memberships?.length || 0
|
|
27
27
|
});
|
|
@@ -107,7 +107,8 @@ async function contextToUserInfo(context, options = {}) {
|
|
|
107
107
|
currentTenant: resolvedCurrentTenant,
|
|
108
108
|
isOnboarded: context.isOnboarded ?? false,
|
|
109
109
|
permissions,
|
|
110
|
-
|
|
110
|
+
hasEntitlement: context.hasEntitlement ?? context.hasSubscription ?? false,
|
|
111
|
+
hasSubscription: context.hasSubscription ?? context.hasEntitlement ?? false,
|
|
111
112
|
userId: context.userId,
|
|
112
113
|
email: context.email,
|
|
113
114
|
firstName: context.firstName,
|
|
@@ -143,4 +144,4 @@ function updateContextVersion(userId, newVersion) {
|
|
|
143
144
|
|
|
144
145
|
//#endregion
|
|
145
146
|
export { clearIdentityContextCache, configureIdentityAPIFetcher, configurePermissionFetcher, contextToUserInfo, fetchIdentityContext, fetchUserPermissions, getIdentityContext, hasContextVersionChanged, updateContextVersion };
|
|
146
|
-
//# sourceMappingURL=server-
|
|
147
|
+
//# sourceMappingURL=server-Dxsww9v9.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-Dxsww9v9.js","names":["identityAPIFetcher: IdentityAPIFetcher | null","fetcher: IdentityAPIFetcher","request: Request","error: unknown","userId: string","userId?: string","permissionFetcher: PermissionFetcher | null","fetcher: PermissionFetcher","tenantId: string","context: IdentityContextData","options: ContextToUserInfoOptions","permissions: string[]","newVersion: number"],"sources":["../src/identity/identity-context.server.ts"],"sourcesContent":["/**\n * Identity Context Server Module\n * \n * Server-side identity context management.\n */\n\nimport type { AddressData, IdentityContextData, TenantMembership } from './types';\nimport { isApiClientError } from '../api-client/types';\nimport { logger } from '../logging';\n\n/**\n * Identity API fetcher type (to avoid coupling with specific API client)\n */\nexport type IdentityAPIFetcher = (request: Request) => Promise<IdentityContextData>;\n\nlet identityAPIFetcher: IdentityAPIFetcher | null = null;\n\n/**\n * Configure identity API fetcher\n */\nexport function configureIdentityAPIFetcher(fetcher: IdentityAPIFetcher): void {\n identityAPIFetcher = fetcher;\n}\n\n// In-memory cache for identity context\nconst contextCache = new Map<\n string,\n {\n context: IdentityContextData;\n timestamp: number;\n version: number;\n }\n>();\n\nconst CONTEXT_CACHE_TTL = 5 * 60 * 1000; // 5 minutes\n\n/**\n * Fetch identity context from backend\n */\nexport async function fetchIdentityContext(request: Request): Promise<IdentityContextData> {\n if (!identityAPIFetcher) {\n throw new Error('Identity API fetcher not configured. Call configureIdentityAPIFetcher first.');\n }\n\n try {\n logger.info('Fetching identity context');\n const context = await identityAPIFetcher(request);\n \n logger.debug('Identity context fetched', {\n hasAnyMembership: context.hasAnyMembership,\n hasEntitlement: context.hasEntitlement ?? context.hasSubscription,\n isOnboarded: context.isOnboarded,\n membershipCount: context.memberships?.length || 0,\n });\n\n return context;\n } catch (error: unknown) {\n logger.error('Failed to fetch identity context', error instanceof Error ? error : undefined);\n\n // Check if this is a CurrentUserMissing error\n if (isApiClientError(error) && error.response?.status === 404 && error.problemDetails?.title === 'CurrentUserMissing') {\n logger.error('CurrentUserMissing error detected - session is invalid');\n const invalidSessionError = new Error('INVALID_SESSION');\n (invalidSessionError as Error & { isInvalidSession: boolean }).isInvalidSession = true;\n throw invalidSessionError;\n }\n\n throw error;\n }\n}\n\n/**\n * Get cached identity context or fetch fresh if needed\n */\nexport async function getIdentityContext(\n request: Request,\n userId: string,\n forceRefresh = false\n): Promise<IdentityContextData> {\n const cacheKey = userId;\n const cached = contextCache.get(cacheKey);\n const now = Date.now();\n\n // Return cached if valid and not forcing refresh\n if (!forceRefresh && cached && now - cached.timestamp < CONTEXT_CACHE_TTL) {\n logger.debug('Using cached identity context for user', { userId });\n return cached.context;\n }\n\n // Fetch fresh context\n const context = await fetchIdentityContext(request);\n\n // Cache the result\n contextCache.set(cacheKey, {\n context,\n timestamp: now,\n version: context.contextVersion ?? 0,\n });\n\n logger.debug('Cached fresh identity context for user', { userId });\n return context;\n}\n\n/**\n * Clear identity context cache for user\n */\nexport function clearIdentityContextCache(userId?: string): void {\n if (userId) {\n contextCache.delete(userId);\n logger.debug('Cleared identity context cache for user', { userId });\n } else {\n contextCache.clear();\n logger.debug('Cleared all identity context cache');\n }\n}\n\n/**\n * Permission fetcher type\n */\nexport type PermissionFetcher = (request: Request, tenantId: string) => Promise<string[]>;\n\nlet permissionFetcher: PermissionFetcher | null = null;\n\n/**\n * Configure permission fetcher\n */\nexport function configurePermissionFetcher(fetcher: PermissionFetcher): void {\n permissionFetcher = fetcher;\n}\n\n/**\n * Fetch user permissions for a specific tenant\n */\nexport async function fetchUserPermissions(request: Request, tenantId: string): Promise<string[]> {\n if (!tenantId) {\n logger.warn('No tenant ID provided, skipping permission fetch');\n return [];\n }\n\n if (!permissionFetcher) {\n throw new Error('Permission fetcher not configured. Call configurePermissionFetcher first.');\n }\n\n try {\n return await permissionFetcher(request, tenantId);\n } catch (error) {\n logger.error('Failed to fetch user permissions', error instanceof Error ? error : undefined);\n return [];\n }\n}\n\nexport interface UserContextInfo {\n tenants: string[];\n memberships: TenantMembership[];\n currentTenant?: string;\n isOnboarded: boolean;\n permissions: string[];\n hasEntitlement: boolean;\n /** @deprecated Use hasEntitlement or app-specific fields instead. */\n hasSubscription: boolean;\n userId?: string;\n email?: string;\n firstName?: string | null;\n lastName?: string | null;\n displayName?: string | null;\n profileImageUrl?: string | null;\n phoneNumber?: string | null;\n timeZone?: string;\n addresses?: AddressData[];\n hasOwnerMembership: boolean;\n}\n\nexport interface ContextToUserInfoOptions {\n currentTenant?: string | null;\n request?: Request;\n}\n\n/**\n * Convert raw identity context into a tenant-aware user info shape.\n */\nexport async function contextToUserInfo(\n context: IdentityContextData,\n options: ContextToUserInfoOptions = {}\n): Promise<UserContextInfo> {\n const memberships = context.memberships || [];\n const tenants = memberships.map((membership) => membership.tenantId);\n const resolvedCurrentTenant =\n options.currentTenant && tenants.includes(options.currentTenant)\n ? options.currentTenant\n : tenants[0] || undefined;\n\n let permissions: string[] = [];\n if (resolvedCurrentTenant && options.request) {\n permissions = await fetchUserPermissions(options.request, resolvedCurrentTenant);\n }\n\n return {\n tenants,\n memberships,\n currentTenant: resolvedCurrentTenant,\n isOnboarded: context.isOnboarded ?? false,\n permissions,\n hasEntitlement: context.hasEntitlement ?? context.hasSubscription ?? false,\n hasSubscription: context.hasSubscription ?? context.hasEntitlement ?? false,\n userId: context.userId,\n email: context.email,\n firstName: context.firstName,\n lastName: context.lastName,\n displayName: context.displayName,\n profileImageUrl: context.profileImageUrl,\n phoneNumber: context.phoneNumber,\n timeZone: context.timeZone,\n addresses: context.addresses,\n hasOwnerMembership: context.hasOwnerMembership ?? false,\n };\n}\n\n/**\n * Check if a cached context version differs from the latest version.\n */\nexport function hasContextVersionChanged(userId: string, newVersion: number): boolean {\n const cached = contextCache.get(userId);\n return !cached || cached.version !== newVersion;\n}\n\n/**\n * Mark a cached identity context as stale after a version change.\n */\nexport function updateContextVersion(userId: string, newVersion: number): void {\n const cached = contextCache.get(userId);\n if (!cached) return;\n\n cached.version = newVersion;\n cached.timestamp = 0;\n logger.debug('Marked identity context as stale for user', {\n userId,\n version: newVersion,\n });\n}\n"],"mappings":";;;;AAeA,IAAIA,qBAAgD;;;;AAKpD,SAAgB,4BAA4BC,SAAmC;AAC7E,sBAAqB;AACtB;AAGD,MAAM,eAAe,IAAI;AASzB,MAAM,oBAAoB,IAAI,KAAK;;;;AAKnC,eAAsB,qBAAqBC,SAAgD;AACzF,MAAK,mBACH,OAAM,IAAI,MAAM;AAGlB,KAAI;AACF,SAAO,KAAK,4BAA4B;EACxC,MAAM,UAAU,MAAM,mBAAmB,QAAQ;AAEjD,SAAO,MAAM,4BAA4B;GACvC,kBAAkB,QAAQ;GAC1B,gBAAgB,QAAQ,kBAAkB,QAAQ;GAClD,aAAa,QAAQ;GACrB,iBAAiB,QAAQ,aAAa,UAAU;EACjD,EAAC;AAEF,SAAO;CACR,SAAQC,OAAgB;AACvB,SAAO,MAAM,oCAAoC,iBAAiB,QAAQ,eAAkB;AAG5F,MAAI,iBAAiB,MAAM,IAAI,MAAM,UAAU,WAAW,OAAO,MAAM,gBAAgB,UAAU,sBAAsB;AACrH,UAAO,MAAM,yDAAyD;GACtE,MAAM,sBAAsB,IAAI,MAAM;AACtC,GAAC,oBAA8D,mBAAmB;AAClF,SAAM;EACP;AAED,QAAM;CACP;AACF;;;;AAKD,eAAsB,mBACpBD,SACAE,QACA,eAAe,OACe;CAC9B,MAAM,WAAW;CACjB,MAAM,SAAS,aAAa,IAAI,SAAS;CACzC,MAAM,MAAM,KAAK,KAAK;AAGtB,MAAK,gBAAgB,UAAU,MAAM,OAAO,YAAY,mBAAmB;AACzE,SAAO,MAAM,0CAA0C,EAAE,OAAQ,EAAC;AAClE,SAAO,OAAO;CACf;CAGD,MAAM,UAAU,MAAM,qBAAqB,QAAQ;AAGnD,cAAa,IAAI,UAAU;EACzB;EACA,WAAW;EACX,SAAS,QAAQ,kBAAkB;CACpC,EAAC;AAEF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,aAAa,QAAQ;EACrB,UAAU,QAAQ;EAClB,WAAW,QAAQ;EACnB,oBAAoB,QAAQ,sBAAsB;CACnD;AACF;;;;AAKD,SAAgB,yBAAyBP,QAAgBQ,YAA6B;CACpF,MAAM,SAAS,aAAa,IAAI,OAAO;AACvC,SAAQ,UAAU,OAAO,YAAY;AACtC;;;;AAKD,SAAgB,qBAAqBR,QAAgBQ,YAA0B;CAC7E,MAAM,SAAS,aAAa,IAAI,OAAO;AACvC,MAAK,OAAQ;AAEb,QAAO,UAAU;AACjB,QAAO,YAAY;AACnB,QAAO,MAAM,6CAA6C;EACxD;EACA,SAAS;CACV,EAAC;AACH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PermissionChecker } from "./
|
|
1
|
+
import { PermissionChecker } from "./permission-service-CvGpwI0d.js";
|
|
2
2
|
|
|
3
3
|
//#region src/permissions/route-protection.server.ts
|
|
4
4
|
const DEFAULT_UNAUTHORIZED_RESPONSE = () => new Response("Unauthorized", {
|
|
@@ -75,4 +75,4 @@ function withPermission(permission, loader, options) {
|
|
|
75
75
|
|
|
76
76
|
//#endregion
|
|
77
77
|
export { checkPermission, configurePermissionRouteProtection, requirePermission, resetPermissionRouteProtection, withPermission };
|
|
78
|
-
//# sourceMappingURL=server-
|
|
78
|
+
//# sourceMappingURL=server-hGrElJMG.js.map
|