@lowdefy/api 6.1.0 → 7.0.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/context/applySystemTrust.js +45 -0
- package/dist/context/createApiContext.js +18 -3
- package/dist/context/createAuthorizeOutcome.js +91 -0
- package/dist/context/createBoundSystemContext.js +33 -0
- package/dist/context/createEvaluateOperators.js +8 -3
- package/dist/context/createRequestSignal.js +47 -0
- package/dist/context/createSystemContext.js +80 -0
- package/dist/context/getCanonicalUrl.js +27 -0
- package/dist/context/isSameOriginRequest.js +85 -0
- package/dist/context/isWebSocketOriginAllowed.js +63 -0
- package/dist/context/normalizeInjectedCaller.js +58 -0
- package/dist/context/parseRequestBody.js +32 -0
- package/dist/context/readMemberships.js +71 -0
- package/dist/context/resolveAuthentication.js +758 -0
- package/dist/context/resolveStrategyCaller.js +7 -3
- package/dist/csp/addNonceToElements.js +23 -0
- package/dist/csp/createContentSecurityPolicy.js +45 -0
- package/dist/csp/getWebSocketSources.js +36 -0
- package/dist/email/renderAuthEmail.js +99 -0
- package/dist/index.js +21 -5
- package/dist/response/formatErrorForAgent.js +35 -0
- package/dist/response/redactResponse.js +8 -1
- package/dist/routes/agent/authorizeAgent.js +17 -5
- package/dist/routes/agent/callAgent.js +12 -2
- package/dist/routes/agent/collectChatFiles.js +39 -0
- package/dist/routes/agent/prepareAgent.js +23 -4
- package/dist/routes/auth/buildAdminPlugin.js +33 -0
- package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
- package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
- package/dist/routes/auth/buildOauthPostLogin.js +73 -0
- package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
- package/dist/routes/auth/buildProviders.js +61 -0
- package/dist/routes/auth/createAsMetadataHandler.js +27 -0
- package/dist/routes/auth/createAuthLogger.js +31 -0
- package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
- package/dist/routes/auth/createOnAPIError.js +41 -0
- package/dist/routes/auth/createSendEmail.js +54 -0
- package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
- package/dist/routes/auth/getAuthEnforcement.js +41 -0
- package/dist/routes/auth/getBetterAuth.js +107 -0
- package/dist/routes/auth/getBetterAuthConfig.js +767 -0
- package/dist/routes/auth/handleAuthRequest.js +43 -0
- package/dist/routes/auth/hooks/authHookPoints.js +204 -0
- package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
- package/dist/routes/auth/hooks/buildHooks.js +112 -0
- package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
- package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
- package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
- package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
- package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
- package/dist/routes/auth/hooks/findHookUser.js +27 -0
- package/dist/routes/auth/modelNames.js +30 -0
- package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
- package/dist/routes/auth/organizations/authorizeRole.js +27 -0
- package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
- package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
- package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
- package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
- package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
- package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
- package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
- package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
- package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
- package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
- package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
- package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
- package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
- package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
- package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
- package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
- package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
- package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
- package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
- package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
- package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
- package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
- package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
- package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
- package/dist/routes/auth/resolveCookiePrefix.js +30 -0
- package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
- package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
- package/dist/routes/connections/checkUnwalledReach.js +37 -0
- package/dist/routes/connections/getConnectionConfig.js +6 -1
- package/dist/routes/connections/resolveTenantPreflight.js +226 -0
- package/dist/routes/connections/resolveUnwalledReach.js +144 -0
- package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
- package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
- package/dist/routes/endpoints/callEndpoint.js +22 -7
- package/dist/routes/endpoints/control/controlParallelFor.js +61 -22
- package/dist/routes/endpoints/control/controlReject.js +23 -1
- package/dist/routes/endpoints/control/controlReturn.js +29 -1
- package/dist/routes/endpoints/control/controlThrow.js +3 -2
- package/dist/routes/endpoints/control/controlTry.js +10 -1
- package/dist/routes/endpoints/control/controlWhile.js +55 -0
- package/dist/routes/endpoints/control/handleControl.js +3 -1
- package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
- package/dist/routes/endpoints/evaluateRoutineOperators.js +2 -1
- package/dist/routes/endpoints/forwardScheduledEndpoint.js +3 -2
- package/dist/routes/endpoints/getEndpointConfig.js +18 -8
- package/dist/routes/endpoints/getSchemaValidator.js +39 -0
- package/dist/routes/endpoints/handleAgentCall.js +21 -2
- package/dist/routes/endpoints/handleAuthStep.js +214 -0
- package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
- package/dist/routes/endpoints/handleEndpointCall.js +43 -6
- package/dist/routes/endpoints/handleRenderNotification.js +14 -4
- package/dist/routes/endpoints/handleRequest.js +12 -1
- package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
- package/dist/routes/endpoints/handleValidateSchema.js +13 -15
- package/dist/routes/endpoints/invokeEndpoint.js +26 -3
- package/dist/routes/endpoints/operatorScope.js +2 -1
- package/dist/routes/{auth/callbacks/createCallbackPlugins.js → endpoints/parseWebhookBody.js} +10 -6
- package/dist/routes/endpoints/resolveCallBinding.js +91 -0
- package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
- package/dist/routes/endpoints/runDetachedEndpoint.js +63 -18
- package/dist/routes/endpoints/runRoutine.js +64 -5
- package/dist/routes/endpoints/runScheduledEndpoint.js +18 -11
- package/dist/routes/endpoints/runWebhookEndpoint.js +69 -23
- package/dist/routes/endpoints/runWebhookVerify.js +129 -0
- package/dist/routes/endpoints/scheduleBackground.js +10 -0
- package/dist/routes/endpoints/test/runTest.js +31 -9
- package/dist/routes/endpoints/validatePayload.js +144 -0
- package/dist/routes/log/logClientError.js +7 -4
- package/dist/routes/mcp/createMcpServer.js +143 -82
- package/dist/routes/mcp/getMcpJwks.js +93 -0
- package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
- package/dist/routes/mcp/getMcpUri.js +69 -0
- package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
- package/dist/routes/mcp/runAfterToolCall.js +50 -0
- package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
- package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
- package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
- package/dist/routes/page/dynamic/createContentError.js +34 -0
- package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
- package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
- package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
- package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
- package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
- package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
- package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
- package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
- package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
- package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
- package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
- package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
- package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
- package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
- package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
- package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
- package/dist/routes/page/dynamic/validateFragment.js +17 -58
- package/dist/routes/page/getPageConfig.js +76 -6
- package/dist/routes/request/authorizeRequest.js +21 -6
- package/dist/routes/request/callRequest.js +22 -10
- package/dist/routes/request/callRequestResolver.js +49 -6
- package/dist/routes/request/checkConnectionRead.js +1 -1
- package/dist/routes/request/checkConnectionWrite.js +1 -1
- package/dist/routes/request/createWalledResolver.js +75 -0
- package/dist/routes/request/getRequestConfig.js +19 -3
- package/dist/routes/request/maskCredentialProperties.js +34 -0
- package/dist/routes/request/resolveTenancy.js +223 -0
- package/dist/routes/request/validateSchemas.js +7 -6
- package/dist/routes/{auth/events/createEventPlugins.js → rootConfig/getAppEvents.js} +7 -6
- package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
- package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
- package/dist/routes/rootConfig/getRootConfig.js +9 -3
- package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
- package/dist/routes/websocket/authorizeWebsocket.js +19 -4
- package/dist/routes/websocket/createChannelRegistry.js +20 -9
- package/dist/routes/websocket/createWebSocketConnection.js +150 -28
- package/dist/routes/websocket/getCallerFingerprint.js +31 -0
- package/dist/routes/websocket/prepareChannel.js +29 -1
- package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
- package/dist/test/testContext.js +13 -10
- package/package.json +28 -12
- package/dist/context/createAuthorize.js +0 -45
- package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
- package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
- package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
- package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
- package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
- package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
- package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
- package/dist/routes/auth/createLogger.js +0 -35
- package/dist/routes/auth/createPrefixedCookies.js +0 -52
- package/dist/routes/auth/createProviders.js +0 -25
- package/dist/routes/auth/defaultAuthUrl.js +0 -31
- package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
- package/dist/routes/auth/events/createEvents.js +0 -56
- package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
- package/dist/routes/auth/events/createSignInEvent.js +0 -46
- package/dist/routes/auth/events/createSignOutEvent.js +0 -43
- package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
- package/dist/routes/auth/getAuthConfig.js +0 -90
- package/dist/routes/auth/resolveCookies.js +0 -37
- package/dist/routes/log/formatValidationError.js +0 -31
- /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
|
@@ -0,0 +1,758 @@
|
|
|
1
|
+
/* eslint-disable no-param-reassign */ /*
|
|
2
|
+
Copyright 2020-2026 Lowdefy, Inc
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/ import { createHash } from 'node:crypto';
|
|
16
|
+
import { decodeJwt, jwtVerify } from 'jose';
|
|
17
|
+
import { normalizeCaller, type } from '@lowdefy/helpers';
|
|
18
|
+
import findPendingInvitation from '../routes/auth/organizations/findPendingInvitation.js';
|
|
19
|
+
import { getRegisteredOrganization } from '../routes/auth/organizations/getOrganizationBinding.js';
|
|
20
|
+
import { getAsIssuer, getMcpResourceUri } from '../routes/mcp/getMcpUri.js';
|
|
21
|
+
import getMcpJwks from '../routes/mcp/getMcpJwks.js';
|
|
22
|
+
import readMemberships from './readMemberships.js';
|
|
23
|
+
import resolveStrategyCaller from './resolveStrategyCaller.js';
|
|
24
|
+
// resolveAuthentication is the single writer of context.user - nothing
|
|
25
|
+
// downstream rewrites it. The session and strategy branches are disjoint
|
|
26
|
+
// ways to become a caller: a resolved session is terminal - it never falls
|
|
27
|
+
// through to strategies, so a walled-out member cannot be silently
|
|
28
|
+
// re-admitted by an apiKey/jwt strategy carrying config-granted roles. API
|
|
29
|
+
// strategies are tried, in config order, only when no session resolves.
|
|
30
|
+
//
|
|
31
|
+
// The third branch is the MCP bearer branch, gated on the mcp option only
|
|
32
|
+
// the /api/mcp route passes - see resolveMcpCaller below. It is disjoint the
|
|
33
|
+
// same way: an MCP request never resolves a session or a strategy caller, and
|
|
34
|
+
// the general path refuses any bearer whose audience is the MCP resource URI
|
|
35
|
+
// before the strategies run.
|
|
36
|
+
//
|
|
37
|
+
// The active member row is the hard membership wall and the role source in
|
|
38
|
+
// one indexed read on the { userId, organizationId } member index, live on
|
|
39
|
+
// every request so membership removal and role changes take effect
|
|
40
|
+
// immediately - roles are deliberately not stamped onto the session. For a
|
|
41
|
+
// session the read returns every member row the person holds (readMemberships),
|
|
42
|
+
// so the same round trip names every organization they belong to, recorded on
|
|
43
|
+
// context.authSession with the session id for the response's caller stamp
|
|
44
|
+
// (callerStamp). A session whose user holds no member row in the active org
|
|
45
|
+
// resolves to unauthenticated: a stale cookie from another app's deployment
|
|
46
|
+
// and a member removed mid-session are treated as logged out, not logged-in
|
|
47
|
+
// with no roles.
|
|
48
|
+
// Under policy: pinned, a session whose active organization is not this app's
|
|
49
|
+
// organization is treated the same way, member row there or not.
|
|
50
|
+
//
|
|
51
|
+
// A session carrying no active organization at all differs by policy. Under
|
|
52
|
+
// pinned it resolves to unauthenticated on the same reasoning. Under tenant it
|
|
53
|
+
// resolves to a caller carrying identity, no membership and no roles, marked
|
|
54
|
+
// awaitingOrganization - the invited user before they accept.
|
|
55
|
+
// createAuthorizeOutcome refuses that caller wherever auth.public is false, so
|
|
56
|
+
// the marker widens no access; it exists so the always-public accept page can
|
|
57
|
+
// tell an invited user from a stranger.
|
|
58
|
+
//
|
|
59
|
+
// The resolved caller is a record, so its keys are snake_case like every other
|
|
60
|
+
// column an app reads - normalizeCaller applies that once over the whole
|
|
61
|
+
// assembled object. The transform is not the adapter's: BetterAuth hands back
|
|
62
|
+
// camelCase JS keys (emailVerified, twoFactorEnabled) whatever the columns are
|
|
63
|
+
// named, so without it session.user would reintroduce camelCase beside the
|
|
64
|
+
// Lowdefy-resolved keys on the same object.
|
|
65
|
+
//
|
|
66
|
+
// The member row carries two unrelated authorities and they stay apart.
|
|
67
|
+
// context.user.roles is member.appRoles - the app's own role strings, and the
|
|
68
|
+
// only source createAuthorizeOutcome matches against auth.roles page and endpoint
|
|
69
|
+
// gates. context.user.org_roles is the split of member.role - BetterAuth's
|
|
70
|
+
// owner/admin/member tier, an administrative fact about this organization that
|
|
71
|
+
// no gate reads. context.user.attributes is
|
|
72
|
+
// the one merged bag of authorization inputs: user.attributes (global) and
|
|
73
|
+
// the active member's attributes (per-org), shallow per-key merge where the
|
|
74
|
+
// member value wins - nested objects replace, never deep-merge.
|
|
75
|
+
//
|
|
76
|
+
// user.profile - the opaque display-and-app-data bag - rides the
|
|
77
|
+
// session.user spread onto the resolved caller (denormalization, not a join:
|
|
78
|
+
// no extra lookup). A user with no profile writes carries no profile key, so
|
|
79
|
+
// _user.profile is undefined - never a synthesized {}. Strategy callers lack
|
|
80
|
+
// profile exactly as they lack name and image.
|
|
81
|
+
//
|
|
82
|
+
// user.contactId - the link to the app's canonical record for this person -
|
|
83
|
+
// rides the same spread on the same argument, and is absent the same way for a
|
|
84
|
+
// user with no link (never synthesized to null). The platform projects it and
|
|
85
|
+
// stops there: nothing here reads it, and nothing resolves what it points at.
|
|
86
|
+
// It needs no special casing handling: normalizeCaller's all-keys rule snakes
|
|
87
|
+
// it to _user.contact_id like every other field, and the adapter's schema-wide
|
|
88
|
+
// derive stores it as the contact_id column.
|
|
89
|
+
//
|
|
90
|
+
// context.user.two_factor_enrolled is the one caller fact no session field
|
|
91
|
+
// carries: whether this person holds a factor that satisfies
|
|
92
|
+
// auth.twoFactor.required. It is set only on session callers - strategy,
|
|
93
|
+
// injected and system callers omit the key entirely, so the enrolment gate,
|
|
94
|
+
// which tests === false, lets every non-session caller through untouched.
|
|
95
|
+
// The passkey plugin is configured iff it is registered on the instance -
|
|
96
|
+
// getBetterAuthConfig only pushes it when auth.passkey.enabled is true.
|
|
97
|
+
function passkeyConfigured({ auth }) {
|
|
98
|
+
return (auth.options?.plugins ?? []).some((plugin)=>plugin?.id === 'passkey');
|
|
99
|
+
}
|
|
100
|
+
// The membership wall and the caller assembly, shared verbatim by the session
|
|
101
|
+
// and MCP bearer branches so the two ways to become a member caller cannot
|
|
102
|
+
// drift - one role source, one caller shape. member is the caller's row in the
|
|
103
|
+
// active organization, or null when they hold none. The session branch reads it
|
|
104
|
+
// with every other row the person holds (readMemberships), since its response
|
|
105
|
+
// is stamped with their memberships; the bearer branches read the one row.
|
|
106
|
+
//
|
|
107
|
+
// memberId is passed only by the member token branch: a token works for the
|
|
108
|
+
// member row it was made for, so a member who left and rejoined - a new row -
|
|
109
|
+
// holds no old tokens.
|
|
110
|
+
async function resolveMemberCaller(context, { adapter, auth, member, memberId, organizationId, user }) {
|
|
111
|
+
if (type.isNone(member)) {
|
|
112
|
+
context.logger.debug(`User "${user.id}" has no member row in organization "${organizationId}" - resolved unauthenticated.`);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
if (!type.isUndefined(memberId) && member.id !== memberId) {
|
|
116
|
+
context.logger.debug(`User "${user.id}" holds member row "${member.id}" in organization "${organizationId}", not the row "${memberId}" the token was made for - resolved unauthenticated.`);
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
// member.role is a CSV BetterAuth writes over a closed three-name set the
|
|
120
|
+
// platform itself writes, so no comma can appear inside a name.
|
|
121
|
+
const orgRoles = (member.role ?? '').split(',').map((role)=>role.trim()).filter(Boolean);
|
|
122
|
+
// twoFactorEnrolled - holds a factor that satisfies auth.twoFactor.required
|
|
123
|
+
// (Decision 4). Short-circuits on twoFactorEnabled, which rides the user
|
|
124
|
+
// record both branches hand in (session.user projects it - the plugin
|
|
125
|
+
// declares input: false but not returned: false), so only an UNENROLLED
|
|
126
|
+
// caller costs the passkey read - and once required is on, that is the
|
|
127
|
+
// shrinking minority by design.
|
|
128
|
+
//
|
|
129
|
+
// The passkey read is gated on the plugin being CONFIGURED, not on
|
|
130
|
+
// required === true: gating on required would make this field mean "has
|
|
131
|
+
// enrolled" in one deployment and "has enrolled TOTP" in another, a value that
|
|
132
|
+
// lies depending on config. A passkey counts because it is a phishing-resistant
|
|
133
|
+
// possession factor with user verification bound to it - the reason Entra and
|
|
134
|
+
// Okta accept one outright. (It is not the ONLY route a passwordless user has:
|
|
135
|
+
// Lowdefy sets allowPasswordless: true, so TOTP is reachable by them too -
|
|
136
|
+
// Decision 4. The passkey still counts here on its own merit.)
|
|
137
|
+
//
|
|
138
|
+
// Needs the platform-owned user-passkeys { userId: 1 } index - without it this
|
|
139
|
+
// is a collection scan on every request from an unenrolled caller.
|
|
140
|
+
let twoFactorEnrolled = user.twoFactorEnabled === true;
|
|
141
|
+
if (!twoFactorEnrolled && passkeyConfigured({
|
|
142
|
+
auth
|
|
143
|
+
})) {
|
|
144
|
+
const passkeyCount = await adapter.count({
|
|
145
|
+
model: 'passkey',
|
|
146
|
+
where: [
|
|
147
|
+
{
|
|
148
|
+
field: 'userId',
|
|
149
|
+
value: user.id
|
|
150
|
+
}
|
|
151
|
+
]
|
|
152
|
+
});
|
|
153
|
+
twoFactorEnrolled = passkeyCount > 0;
|
|
154
|
+
}
|
|
155
|
+
// normalizeCaller is shallow, so the attributes bag it carries through is the
|
|
156
|
+
// merge below verbatim - app-owned keys inside it are never renamed.
|
|
157
|
+
return normalizeCaller({
|
|
158
|
+
...user,
|
|
159
|
+
// Per-organization display copies, denormalized onto the member row by
|
|
160
|
+
// UpdateUserProfile. The user row's name/image are deployment-global and
|
|
161
|
+
// last-edit-wins across workspaces, so a caller acting in organization A
|
|
162
|
+
// would otherwise be stamped and rendered with the identity last saved in
|
|
163
|
+
// organization B (T18). Nullish-coalesced: a member who has never saved a
|
|
164
|
+
// profile in this organization falls back to the global copies.
|
|
165
|
+
name: member.name ?? user.name,
|
|
166
|
+
image: member.image ?? user.image,
|
|
167
|
+
// Absent on a member row minted with no app roles - never falls back to
|
|
168
|
+
// member.role, which would make the two fields one dual-storage scheme.
|
|
169
|
+
roles: member.appRoles ?? [],
|
|
170
|
+
orgRoles,
|
|
171
|
+
attributes: {
|
|
172
|
+
...user.attributes ?? {},
|
|
173
|
+
...member.attributes ?? {}
|
|
174
|
+
},
|
|
175
|
+
activeOrganizationId: organizationId,
|
|
176
|
+
twoFactorEnrolled,
|
|
177
|
+
// organization_id is the caller's active org in its serialized string form -
|
|
178
|
+
// the value the tenant wall stamps onto and filters walled collections with,
|
|
179
|
+
// and the one operators read as _user: organization_id. It resolves under
|
|
180
|
+
// both organizations policies (under pinned it always equals the pinned
|
|
181
|
+
// org, since set-active-organization is disabled there).
|
|
182
|
+
organizationId
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
// The HTTP call sites hand over Fetch Headers; direct callers pass plain
|
|
186
|
+
// objects - read both so neither shape silently reads as "no bearer".
|
|
187
|
+
function readBearerToken({ headers }) {
|
|
188
|
+
const authorization = typeof headers?.get === 'function' ? headers.get('authorization') : headers?.authorization;
|
|
189
|
+
if (!authorization || !authorization.startsWith('Bearer ')) {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
return authorization.slice('Bearer '.length).trim();
|
|
193
|
+
}
|
|
194
|
+
// The closed MCP scope vocabulary - the AS grants nothing outside it, and
|
|
195
|
+
// grantedScopes never carries a foreign scope string downstream.
|
|
196
|
+
const MCP_SCOPES = [
|
|
197
|
+
'mcp:read',
|
|
198
|
+
'mcp:write'
|
|
199
|
+
];
|
|
200
|
+
// An access token minted for the MCP resource must never re-enter the general
|
|
201
|
+
// /api/* surface as a strategy caller - even a jwt strategy misconfigured to
|
|
202
|
+
// point at the app's own JWKS would otherwise accept it with the strategy's
|
|
203
|
+
// config-granted roles. Tested on the decoded aud alone, unverified:
|
|
204
|
+
// rejection needs no key material, and a forged aud only denies its forger.
|
|
205
|
+
// A non-JWT bearer or a decode failure is not this check's concern - opaque
|
|
206
|
+
// strategy credentials fall through to the strategies unchanged.
|
|
207
|
+
function hasMcpAudienceBearer({ context, headers }) {
|
|
208
|
+
const token = readBearerToken({
|
|
209
|
+
headers
|
|
210
|
+
});
|
|
211
|
+
if (token === null) {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
const resourceUri = getMcpResourceUri({
|
|
215
|
+
config: context.config
|
|
216
|
+
});
|
|
217
|
+
if (resourceUri === null) {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
let aud;
|
|
221
|
+
try {
|
|
222
|
+
({ aud } = decodeJwt(token));
|
|
223
|
+
} catch (error) {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
const audiences = type.isArray(aud) ? aud : [
|
|
227
|
+
aud
|
|
228
|
+
];
|
|
229
|
+
const rejected = audiences.some((value)=>value === resourceUri);
|
|
230
|
+
if (rejected) {
|
|
231
|
+
context.logger.debug({
|
|
232
|
+
event: 'auth_mcp_audience_bearer_rejected'
|
|
233
|
+
}, 'Bearer token carrying the MCP resource audience rejected on the general API surface - resolved unauthenticated.');
|
|
234
|
+
}
|
|
235
|
+
return rejected;
|
|
236
|
+
}
|
|
237
|
+
// A banned user is refused on every MCP bearer, OAuth or member token: a ban
|
|
238
|
+
// deletes the user's sessions, but nothing else on the bearer path would read
|
|
239
|
+
// it. A ban with an expiry in the past no longer applies.
|
|
240
|
+
function isBanned({ user }) {
|
|
241
|
+
if (user.banned !== true) {
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
return type.isNone(user.banExpires) || new Date(user.banExpires) > new Date();
|
|
245
|
+
}
|
|
246
|
+
// The user read, ban check and membership wall both MCP bearers share once
|
|
247
|
+
// each has settled which user and organization it acts for. Returns the
|
|
248
|
+
// resolved caller, or null when the user is gone, banned or not a member.
|
|
249
|
+
async function resolveBearerMember(context, { adapter, auth, memberId, organizationId, userId }) {
|
|
250
|
+
// The bearer carries only the user id - the caller's user fields are read live.
|
|
251
|
+
const user = await adapter.findOne({
|
|
252
|
+
model: 'user',
|
|
253
|
+
where: [
|
|
254
|
+
{
|
|
255
|
+
field: 'id',
|
|
256
|
+
value: userId
|
|
257
|
+
}
|
|
258
|
+
]
|
|
259
|
+
});
|
|
260
|
+
if (type.isNone(user)) {
|
|
261
|
+
context.logger.debug({
|
|
262
|
+
event: 'auth_mcp_no_user',
|
|
263
|
+
organizationId
|
|
264
|
+
}, `MCP bearer rejected: user "${userId}" has no user row.`);
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
if (isBanned({
|
|
268
|
+
user
|
|
269
|
+
})) {
|
|
270
|
+
context.logger.debug({
|
|
271
|
+
event: 'auth_mcp_user_banned',
|
|
272
|
+
organizationId
|
|
273
|
+
}, `MCP bearer rejected: user "${userId}" is banned.`);
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
const memberRow = await adapter.findOne({
|
|
277
|
+
model: 'member',
|
|
278
|
+
where: [
|
|
279
|
+
{
|
|
280
|
+
field: 'userId',
|
|
281
|
+
value: user.id
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
field: 'organizationId',
|
|
285
|
+
value: organizationId
|
|
286
|
+
}
|
|
287
|
+
]
|
|
288
|
+
});
|
|
289
|
+
const member = await resolveMemberCaller(context, {
|
|
290
|
+
adapter,
|
|
291
|
+
auth,
|
|
292
|
+
member: memberRow,
|
|
293
|
+
memberId,
|
|
294
|
+
organizationId,
|
|
295
|
+
user
|
|
296
|
+
});
|
|
297
|
+
if (type.isNone(member)) {
|
|
298
|
+
context.logger.debug({
|
|
299
|
+
event: 'auth_mcp_no_membership',
|
|
300
|
+
organizationId
|
|
301
|
+
}, `MCP bearer rejected: user "${userId}" is not a member of organization "${organizationId}".`);
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
return member;
|
|
305
|
+
}
|
|
306
|
+
// Member tokens are the long-lived bearer a script sends in place of an OAuth
|
|
307
|
+
// access token. The prefix tells them apart from a JWT without parsing, and
|
|
308
|
+
// lets secret scanners and people recognise a leaked one.
|
|
309
|
+
const MEMBER_TOKEN_PREFIX = 'ldf_mcp_';
|
|
310
|
+
// lastUsedAt is display data, not an audit trail: written at most once an hour
|
|
311
|
+
// per token so a script calling several times a minute costs no write per call.
|
|
312
|
+
const LAST_USED_INTERVAL_MS = 60 * 60 * 1000;
|
|
313
|
+
function refuseMemberToken(context, { description }) {
|
|
314
|
+
context.user = null;
|
|
315
|
+
context.mcpAuth = {
|
|
316
|
+
tokenStatus: 'invalid',
|
|
317
|
+
memberToken: true,
|
|
318
|
+
description
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
const MEMBER_GONE = "This token's member can no longer use it.";
|
|
322
|
+
async function touchMemberToken(context, { adapter, row }) {
|
|
323
|
+
const lastUsedAt = type.isNone(row.lastUsedAt) ? 0 : new Date(row.lastUsedAt).getTime();
|
|
324
|
+
if (Date.now() - lastUsedAt < LAST_USED_INTERVAL_MS) {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
await adapter.update({
|
|
329
|
+
model: 'mcpToken',
|
|
330
|
+
where: [
|
|
331
|
+
{
|
|
332
|
+
field: 'id',
|
|
333
|
+
value: row.id
|
|
334
|
+
}
|
|
335
|
+
],
|
|
336
|
+
update: {
|
|
337
|
+
lastUsedAt: new Date()
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
} catch (error) {
|
|
341
|
+
context.logger.warn({
|
|
342
|
+
event: 'auth_mcp_token_last_used_failed',
|
|
343
|
+
err: error,
|
|
344
|
+
tokenId: row.id
|
|
345
|
+
}, `Could not record when member token "${row.id}" was last used: ${error.message}`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
// The member token branch. The token is looked up by its SHA-256 - the token
|
|
349
|
+
// itself is never stored - and acts as the member row it was made for, in the
|
|
350
|
+
// organization it was made in. Every refusal carries a description the route
|
|
351
|
+
// returns in the challenge, since a script cannot sign in and needs to know
|
|
352
|
+
// why: switched off, expired, or its member can no longer use it.
|
|
353
|
+
async function resolveMemberTokenCaller(context, { auth, token }) {
|
|
354
|
+
const { adapter } = await auth.$context;
|
|
355
|
+
const row = await adapter.findOne({
|
|
356
|
+
model: 'mcpToken',
|
|
357
|
+
where: [
|
|
358
|
+
{
|
|
359
|
+
field: 'hash',
|
|
360
|
+
value: createHash('sha256').update(token).digest('hex')
|
|
361
|
+
}
|
|
362
|
+
]
|
|
363
|
+
});
|
|
364
|
+
if (type.isNone(row)) {
|
|
365
|
+
context.logger.debug({
|
|
366
|
+
event: 'auth_mcp_member_token_rejected'
|
|
367
|
+
}, 'MCP member token rejected: no token matches.');
|
|
368
|
+
refuseMemberToken(context, {
|
|
369
|
+
description: 'This token was switched off or does not exist.'
|
|
370
|
+
});
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
if (!type.isNone(row.expiresAt) && new Date(row.expiresAt) <= new Date()) {
|
|
374
|
+
context.logger.debug({
|
|
375
|
+
event: 'auth_mcp_member_token_rejected',
|
|
376
|
+
tokenId: row.id
|
|
377
|
+
}, `MCP member token "${row.id}" rejected: it expired at ${new Date(row.expiresAt).toISOString()}.`);
|
|
378
|
+
refuseMemberToken(context, {
|
|
379
|
+
description: 'This token has expired.'
|
|
380
|
+
});
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const registered = getRegisteredOrganization({
|
|
384
|
+
auth
|
|
385
|
+
});
|
|
386
|
+
if (registered?.policy === 'pinned' && row.organizationId !== registered.slug) {
|
|
387
|
+
context.logger.debug({
|
|
388
|
+
event: 'auth_mcp_member_token_rejected',
|
|
389
|
+
tokenId: row.id
|
|
390
|
+
}, `MCP member token "${row.id}" rejected: its organization "${row.organizationId}" is not this app's pinned organization "${registered.slug}".`);
|
|
391
|
+
refuseMemberToken(context, {
|
|
392
|
+
description: MEMBER_GONE
|
|
393
|
+
});
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const member = await resolveBearerMember(context, {
|
|
397
|
+
adapter,
|
|
398
|
+
auth,
|
|
399
|
+
memberId: row.memberId,
|
|
400
|
+
organizationId: row.organizationId,
|
|
401
|
+
userId: row.userId
|
|
402
|
+
});
|
|
403
|
+
if (type.isNone(member)) {
|
|
404
|
+
refuseMemberToken(context, {
|
|
405
|
+
description: MEMBER_GONE
|
|
406
|
+
});
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
await touchMemberToken(context, {
|
|
410
|
+
adapter,
|
|
411
|
+
row
|
|
412
|
+
});
|
|
413
|
+
context.mcpAuth = {
|
|
414
|
+
tokenStatus: 'valid',
|
|
415
|
+
tokenId: row.id,
|
|
416
|
+
organizationId: row.organizationId,
|
|
417
|
+
// Every MCP scope: the token acts as the member who made it, and the
|
|
418
|
+
// member's roles still gate every tool.
|
|
419
|
+
grantedScopes: MCP_SCOPES
|
|
420
|
+
};
|
|
421
|
+
context.user = {
|
|
422
|
+
...member,
|
|
423
|
+
auth_method: 'mcp'
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
// The MCP bearer branch. The route accepts two credential kinds: an access
|
|
427
|
+
// token this app's authorization server minted for the MCP resource, and a
|
|
428
|
+
// member token (see resolveMemberTokenCaller) - a session cookie or a strategy
|
|
429
|
+
// credential never authenticates here. The access token is verified in-process
|
|
430
|
+
// with jose against the AS's own signing keys.
|
|
431
|
+
// The organization the token acts in is its organization_id claim - the
|
|
432
|
+
// consent referenceId the member chose at authorization, stamped by the AS
|
|
433
|
+
// (buildOauthPostLogin) - never a path segment or a request parameter. The
|
|
434
|
+
// claim alone is not enough: the consent row for (client, user, organization)
|
|
435
|
+
// must still exist, so a grant the member gave up (RevokeMcpGrant, a consent
|
|
436
|
+
// deleted in the app) stops working at once instead of at the token's expiry.
|
|
437
|
+
// context.mcpAuth records the token outcome for the route layer's challenge
|
|
438
|
+
// decisions; context.user stays the only caller surface.
|
|
439
|
+
async function resolveMcpCaller(context, { auth, headers }) {
|
|
440
|
+
const token = readBearerToken({
|
|
441
|
+
headers
|
|
442
|
+
});
|
|
443
|
+
if (token === null) {
|
|
444
|
+
// The anonymous caller - public tools only, never a challenge here.
|
|
445
|
+
context.user = null;
|
|
446
|
+
context.mcpAuth = {
|
|
447
|
+
tokenStatus: 'none',
|
|
448
|
+
parseableJwt: true
|
|
449
|
+
};
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
if (token.startsWith(MEMBER_TOKEN_PREFIX)) {
|
|
453
|
+
await resolveMemberTokenCaller(context, {
|
|
454
|
+
auth,
|
|
455
|
+
token
|
|
456
|
+
});
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
let payload;
|
|
460
|
+
try {
|
|
461
|
+
({ payload } = await jwtVerify(token, getMcpJwks({
|
|
462
|
+
auth
|
|
463
|
+
}), {
|
|
464
|
+
issuer: getAsIssuer({
|
|
465
|
+
config: context.config
|
|
466
|
+
}),
|
|
467
|
+
// jose matches an array aud containing the value, so RFC 8707
|
|
468
|
+
// multi-resource grants verify against the canonical resource URI.
|
|
469
|
+
audience: getMcpResourceUri({
|
|
470
|
+
config: context.config
|
|
471
|
+
}),
|
|
472
|
+
// A token without a subject cannot source a caller, and one without an
|
|
473
|
+
// organization has nothing to be a member of - both are rejected as
|
|
474
|
+
// invalid rather than half-resolved.
|
|
475
|
+
requiredClaims: [
|
|
476
|
+
'sub',
|
|
477
|
+
'organization_id'
|
|
478
|
+
]
|
|
479
|
+
}));
|
|
480
|
+
} catch (error) {
|
|
481
|
+
let parseableJwt = true;
|
|
482
|
+
try {
|
|
483
|
+
decodeJwt(token);
|
|
484
|
+
} catch (decodeError) {
|
|
485
|
+
parseableJwt = false;
|
|
486
|
+
}
|
|
487
|
+
context.logger.debug({
|
|
488
|
+
event: 'auth_mcp_token_rejected',
|
|
489
|
+
err: error
|
|
490
|
+
}, `MCP bearer token rejected: ${error.message}`);
|
|
491
|
+
context.user = null;
|
|
492
|
+
context.mcpAuth = {
|
|
493
|
+
tokenStatus: 'invalid',
|
|
494
|
+
parseableJwt
|
|
495
|
+
};
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const organizationId = payload.organization_id;
|
|
499
|
+
// client_id and azp are both stamped by the AS on every access token it
|
|
500
|
+
// mints; azp is the fallback for a token minted before client_id was.
|
|
501
|
+
const clientId = payload.client_id ?? payload.azp;
|
|
502
|
+
if (!type.isString(organizationId) || !type.isString(clientId)) {
|
|
503
|
+
context.logger.debug({
|
|
504
|
+
event: 'auth_mcp_token_rejected'
|
|
505
|
+
}, 'MCP bearer token rejected: organization_id or client_id claim is not a string.');
|
|
506
|
+
context.user = null;
|
|
507
|
+
context.mcpAuth = {
|
|
508
|
+
tokenStatus: 'invalid',
|
|
509
|
+
parseableJwt: true
|
|
510
|
+
};
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
const { adapter } = await auth.$context;
|
|
514
|
+
// The live grant. The AS keys consent per (client, user, organization) -
|
|
515
|
+
// the referenceId - so this one indexed read answers whether the grant the
|
|
516
|
+
// token was minted under still stands.
|
|
517
|
+
const consent = await adapter.findOne({
|
|
518
|
+
model: 'oauthConsent',
|
|
519
|
+
where: [
|
|
520
|
+
{
|
|
521
|
+
field: 'clientId',
|
|
522
|
+
value: clientId
|
|
523
|
+
},
|
|
524
|
+
{
|
|
525
|
+
field: 'userId',
|
|
526
|
+
value: payload.sub
|
|
527
|
+
},
|
|
528
|
+
{
|
|
529
|
+
field: 'referenceId',
|
|
530
|
+
value: organizationId
|
|
531
|
+
}
|
|
532
|
+
]
|
|
533
|
+
});
|
|
534
|
+
if (type.isNone(consent)) {
|
|
535
|
+
context.logger.debug({
|
|
536
|
+
event: 'auth_mcp_grant_revoked',
|
|
537
|
+
clientId,
|
|
538
|
+
organizationId
|
|
539
|
+
}, `MCP bearer token rejected: no consent stands for client "${clientId}" in organization "${organizationId}" - the grant was revoked.`);
|
|
540
|
+
context.user = null;
|
|
541
|
+
context.mcpAuth = {
|
|
542
|
+
clientId,
|
|
543
|
+
organizationId,
|
|
544
|
+
tokenStatus: 'invalid',
|
|
545
|
+
parseableJwt: true,
|
|
546
|
+
revoked: true
|
|
547
|
+
};
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
// The scope claim reduced to the closed MCP vocabulary.
|
|
551
|
+
const grantedScopes = (type.isString(payload.scope) ? payload.scope : '').split(' ').filter((scope)=>MCP_SCOPES.includes(scope));
|
|
552
|
+
const validMcpAuth = {
|
|
553
|
+
clientId,
|
|
554
|
+
organizationId,
|
|
555
|
+
tokenStatus: 'valid',
|
|
556
|
+
parseableJwt: true,
|
|
557
|
+
grantedScopes
|
|
558
|
+
};
|
|
559
|
+
// The same pinned wall the session branch applies: a pinned app serves one
|
|
560
|
+
// organization, so a token referencing any other - verifiable or not -
|
|
561
|
+
// never reaches the member read.
|
|
562
|
+
const registered = getRegisteredOrganization({
|
|
563
|
+
auth
|
|
564
|
+
});
|
|
565
|
+
if (registered?.policy === 'pinned' && organizationId !== registered.slug) {
|
|
566
|
+
context.logger.debug(`MCP token for organization "${organizationId}", which is not this app's pinned organization "${registered.slug}" - resolved unauthenticated.`);
|
|
567
|
+
context.user = null;
|
|
568
|
+
context.mcpAuth = validMcpAuth;
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
const member = await resolveBearerMember(context, {
|
|
572
|
+
adapter,
|
|
573
|
+
auth,
|
|
574
|
+
organizationId,
|
|
575
|
+
userId: payload.sub
|
|
576
|
+
});
|
|
577
|
+
if (type.isNone(member)) {
|
|
578
|
+
// A token whose subject is no longer a member of its organization -
|
|
579
|
+
// removed, left, banned, or the user deleted - resolves invalid, not to the
|
|
580
|
+
// anonymous caller: the route answers invalid with the sign-in challenge,
|
|
581
|
+
// so the client re-runs authorization and its organization choice instead
|
|
582
|
+
// of holding a token that works for nothing.
|
|
583
|
+
context.user = null;
|
|
584
|
+
context.mcpAuth = {
|
|
585
|
+
clientId,
|
|
586
|
+
organizationId,
|
|
587
|
+
tokenStatus: 'invalid',
|
|
588
|
+
parseableJwt: true,
|
|
589
|
+
noMembership: true
|
|
590
|
+
};
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
context.mcpAuth = validMcpAuth;
|
|
594
|
+
// auth_method names the surface the caller arrived on, symmetric with
|
|
595
|
+
// strategy callers - app config reads it to label MCP-authored writes.
|
|
596
|
+
context.user = {
|
|
597
|
+
...member,
|
|
598
|
+
auth_method: 'mcp'
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
// context.authSession is the session the caller was resolved from, for the
|
|
602
|
+
// response's caller stamp: { id, memberOrganizationIds }. memberOrganizationIds
|
|
603
|
+
// is every organization the person belongs to under tenant, this app's
|
|
604
|
+
// organization alone under pinned, and null when the member rows were not read
|
|
605
|
+
// (a session with no active organization) or did not fit one read. null for
|
|
606
|
+
// every caller that is not a session caller.
|
|
607
|
+
async function resolveAuthentication(context, { auth, headers, strategies, mcp }) {
|
|
608
|
+
context.authSession = null;
|
|
609
|
+
if (type.isNone(auth)) {
|
|
610
|
+
context.user = null;
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
// Only the /api/mcp route passes mcp - its callers authenticate by access
|
|
614
|
+
// token alone, so the session and strategy branches are skipped outright
|
|
615
|
+
// rather than tried and out-prioritized.
|
|
616
|
+
if (mcp === true) {
|
|
617
|
+
await resolveMcpCaller(context, {
|
|
618
|
+
auth,
|
|
619
|
+
headers
|
|
620
|
+
});
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const session = await auth.api.getSession({
|
|
624
|
+
headers
|
|
625
|
+
});
|
|
626
|
+
if (type.isNone(session)) {
|
|
627
|
+
if (hasMcpAudienceBearer({
|
|
628
|
+
context,
|
|
629
|
+
headers
|
|
630
|
+
})) {
|
|
631
|
+
context.user = null;
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
context.user = await resolveStrategyCaller({
|
|
635
|
+
headers,
|
|
636
|
+
logger: context.logger,
|
|
637
|
+
strategies
|
|
638
|
+
});
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
const activeOrganizationId = session.session.activeOrganizationId;
|
|
642
|
+
if (type.isNone(activeOrganizationId)) {
|
|
643
|
+
// A session with no active organization differs by policy. Under tenant it
|
|
644
|
+
// is the invited user before they accept - their pre-accept session carries
|
|
645
|
+
// no organization by design, because they are about to join someone else's.
|
|
646
|
+
// Resolving them to null leaves the always-public accept page unable to
|
|
647
|
+
// tell them from a stranger, and that page is the one page they can reach.
|
|
648
|
+
// They become a caller carrying identity, no membership and no roles,
|
|
649
|
+
// marked awaitingOrganization - createAuthorizeOutcome refuses that caller
|
|
650
|
+
// wherever auth.public is false, so the marker widens no access. Under
|
|
651
|
+
// pinned the state has no meaning: one organization exists, and someone
|
|
652
|
+
// outside it has no reason to be known to the app.
|
|
653
|
+
if (getRegisteredOrganization({
|
|
654
|
+
auth
|
|
655
|
+
})?.policy !== 'tenant') {
|
|
656
|
+
context.logger.debug(`Session for user "${session.user.id}" has no active organization - resolved unauthenticated.`);
|
|
657
|
+
context.user = null;
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
context.logger.debug(`Session for user "${session.user.id}" has no active organization under tenant - resolved awaiting organization.`);
|
|
661
|
+
// Why they are awaiting matters to the app: an invited user who signed up
|
|
662
|
+
// directly (instead of via the invitation link) holds a pending invitation
|
|
663
|
+
// and no member row, and without a marker the public pages cannot tell
|
|
664
|
+
// them from a caller awaiting operator provisioning - the invited user is
|
|
665
|
+
// stranded the moment they lose the invitation email. The pending
|
|
666
|
+
// invitation is read here (only for this rare caller, one indexed read) so
|
|
667
|
+
// the app can route them to the accept page and hand it the invitation id.
|
|
668
|
+
// Diagnosis only - accepting stays the caller's own, explicit act.
|
|
669
|
+
const pendingInvitation = type.isString(session.user.email) ? await findPendingInvitation({
|
|
670
|
+
adapter: (await auth.$context).adapter,
|
|
671
|
+
email: session.user.email
|
|
672
|
+
}) : null;
|
|
673
|
+
// No member row, so no per-organization attributes and no roles of either
|
|
674
|
+
// kind - the global attributes ride alone.
|
|
675
|
+
context.authSession = {
|
|
676
|
+
id: session.session.id,
|
|
677
|
+
memberOrganizationIds: null
|
|
678
|
+
};
|
|
679
|
+
context.user = normalizeCaller({
|
|
680
|
+
...session.user,
|
|
681
|
+
roles: [],
|
|
682
|
+
orgRoles: [],
|
|
683
|
+
attributes: session.user.attributes ?? {},
|
|
684
|
+
awaitingOrganization: true,
|
|
685
|
+
// Always present on the awaiting caller (true or false) so app config
|
|
686
|
+
// can branch on it without an absent-key case. The invitation id rides
|
|
687
|
+
// only when one exists - never synthesized to null - and is safe to hand
|
|
688
|
+
// to its own invitee: the accept route re-verifies that the session's
|
|
689
|
+
// email matches the invitation before minting anything.
|
|
690
|
+
hasPendingInvitation: !type.isNone(pendingInvitation),
|
|
691
|
+
...type.isNone(pendingInvitation) ? {} : {
|
|
692
|
+
pendingInvitationId: pendingInvitation.id
|
|
693
|
+
}
|
|
694
|
+
});
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
// Under pinned, the active organization must be this app's organization.
|
|
698
|
+
// Without this, a session pinned elsewhere - accept-time drift from an
|
|
699
|
+
// invitation another app sent, a stale cookie, a session shared between two
|
|
700
|
+
// pinned apps on one host - resolves as an authenticated caller here
|
|
701
|
+
// carrying the other organization's roles, so every role name the two
|
|
702
|
+
// catalogs share becomes a page they can open. Ahead of the member read: a
|
|
703
|
+
// foreign session costs no database round trip.
|
|
704
|
+
//
|
|
705
|
+
// The comparison target is the configured slug, not getOrganizationBinding's
|
|
706
|
+
// pinned.id, because pinned can legitimately be absent on a live request -
|
|
707
|
+
// resolvePinnedOrganization swallows a failed ensure so the _organization
|
|
708
|
+
// operator and step organizationId defaulting fail with their own clear
|
|
709
|
+
// errors instead of every request failing in the middleware. Comparing
|
|
710
|
+
// against an unresolved binding would either log the whole deployment out on
|
|
711
|
+
// a transient database error or skip the check exactly when the database is
|
|
712
|
+
// unhealthy. Under pinned the organization's id is its slug, so the check
|
|
713
|
+
// needs no database read and an unhealthy ensure cannot defeat it.
|
|
714
|
+
//
|
|
715
|
+
// Recovery is one re-login at this app: applyPinnedPolicy runs at every
|
|
716
|
+
// session.create and re-pins the session whenever the caller holds a member
|
|
717
|
+
// row here. Never send the person to the other app - the production cookie
|
|
718
|
+
// prefix is shared across apps on one host, so signing in there flips the
|
|
719
|
+
// shared session the other way and breaks the app they came from.
|
|
720
|
+
//
|
|
721
|
+
// Under tenant there is no pinned organization and the check does not apply.
|
|
722
|
+
const registered = getRegisteredOrganization({
|
|
723
|
+
auth
|
|
724
|
+
});
|
|
725
|
+
if (registered?.policy === 'pinned' && activeOrganizationId !== registered.slug) {
|
|
726
|
+
context.logger.debug(`Session for user "${session.user.id}" has active organization "${activeOrganizationId}", which is not this app's pinned organization "${registered.slug}" - resolved unauthenticated.`);
|
|
727
|
+
context.user = null;
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
const { adapter } = await auth.$context;
|
|
731
|
+
const { member, organizationIds } = await readMemberships({
|
|
732
|
+
adapter,
|
|
733
|
+
organizationId: activeOrganizationId,
|
|
734
|
+
userId: session.user.id
|
|
735
|
+
});
|
|
736
|
+
context.user = await resolveMemberCaller(context, {
|
|
737
|
+
adapter,
|
|
738
|
+
auth,
|
|
739
|
+
member,
|
|
740
|
+
organizationId: activeOrganizationId,
|
|
741
|
+
user: session.user
|
|
742
|
+
});
|
|
743
|
+
if (type.isNone(context.user)) {
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
// A pinned app serves one organization, and this caller reached here as a
|
|
747
|
+
// member of it, so that is the one membership its stamp names: rows the same
|
|
748
|
+
// auth database holds for other apps' organizations never change this app's
|
|
749
|
+
// stamp. Under tenant every organization the person belongs to counts.
|
|
750
|
+
const memberOrganizationIds = registered?.policy === 'pinned' ? [
|
|
751
|
+
registered.slug
|
|
752
|
+
] : organizationIds;
|
|
753
|
+
context.authSession = {
|
|
754
|
+
id: session.session.id,
|
|
755
|
+
memberOrganizationIds
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
export default resolveAuthentication;
|