@terreno/api 57.19.2 → 57.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +393 -0
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +39 -7
- package/src/betterAuthSetup.ts +457 -38
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
|
@@ -54,6 +54,10 @@ const mcpOAuthTokenSchema = new mongoose_1.default.Schema({
|
|
|
54
54
|
required: true,
|
|
55
55
|
type: String,
|
|
56
56
|
},
|
|
57
|
+
hasRefreshToken: {
|
|
58
|
+
description: "False when this document is an access-only client_credentials token. The refresh hash is then of a discarded secret and cannot be exchanged",
|
|
59
|
+
type: Boolean,
|
|
60
|
+
},
|
|
57
61
|
refreshExpiresAt: {
|
|
58
62
|
description: "When the refresh token stops being exchangeable; the document is removed then",
|
|
59
63
|
required: true,
|
|
@@ -104,16 +108,25 @@ mcpOAuthTokenSchema.statics = {
|
|
|
104
108
|
if (await isFamilyRevoked(familyId)) {
|
|
105
109
|
throw new McpOAuthFamilyRevokedError(familyId);
|
|
106
110
|
}
|
|
111
|
+
const includeRefreshToken = options.includeRefreshToken !== false;
|
|
107
112
|
const accessToken = (0, exports.generateMcpOAuthSecret)(exports.MCP_OAUTH_ACCESS_TOKEN_PREFIX);
|
|
108
|
-
|
|
113
|
+
// Access-only grants still store a unique hash so the refreshTokenHash index stays unique.
|
|
114
|
+
// The preimage is discarded, and hasRefreshToken false makes it unusable for refresh.
|
|
115
|
+
const refreshSecret = includeRefreshToken
|
|
116
|
+
? (0, exports.generateMcpOAuthSecret)(MCP_OAUTH_REFRESH_TOKEN_PREFIX)
|
|
117
|
+
: (0, exports.generateMcpOAuthSecret)("discarded_");
|
|
109
118
|
const now = luxon_1.DateTime.now();
|
|
119
|
+
const refreshTtlSeconds = includeRefreshToken
|
|
120
|
+
? options.refreshTokenTtlSeconds
|
|
121
|
+
: options.accessTokenTtlSeconds;
|
|
110
122
|
const mcpOAuthToken = await this.create({
|
|
111
123
|
accessExpiresAt: now.plus({ seconds: options.accessTokenTtlSeconds }).toJSDate(),
|
|
112
124
|
accessTokenHash: (0, exports.hashMcpOAuthSecret)(accessToken),
|
|
113
125
|
clientId: options.clientId,
|
|
114
126
|
familyId,
|
|
115
|
-
|
|
116
|
-
|
|
127
|
+
hasRefreshToken: includeRefreshToken,
|
|
128
|
+
refreshExpiresAt: now.plus({ seconds: refreshTtlSeconds }).toJSDate(),
|
|
129
|
+
refreshTokenHash: (0, exports.hashMcpOAuthSecret)(refreshSecret),
|
|
117
130
|
resource: options.resource,
|
|
118
131
|
scope: options.scope,
|
|
119
132
|
tokenEpoch: options.tokenEpoch ?? 0,
|
|
@@ -125,7 +138,18 @@ mcpOAuthTokenSchema.statics = {
|
|
|
125
138
|
await this.updateOne({ _id: mcpOAuthToken._id, revokedAt: { $exists: false } }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
|
|
126
139
|
throw new McpOAuthFamilyRevokedError(familyId);
|
|
127
140
|
}
|
|
128
|
-
return {
|
|
141
|
+
return {
|
|
142
|
+
accessToken,
|
|
143
|
+
mcpOAuthToken,
|
|
144
|
+
refreshToken: includeRefreshToken ? refreshSecret : undefined,
|
|
145
|
+
};
|
|
146
|
+
},
|
|
147
|
+
async revokeClient(clientId) {
|
|
148
|
+
const tokens = await this.find({ clientId, revokedAt: { $exists: false } }).select({ familyId: 1 });
|
|
149
|
+
const familyIds = new Set(tokens.map((token) => token.familyId));
|
|
150
|
+
for (const familyId of familyIds) {
|
|
151
|
+
await this.revokeFamily(familyId);
|
|
152
|
+
}
|
|
129
153
|
},
|
|
130
154
|
async revokeFamily(familyId) {
|
|
131
155
|
const now = luxon_1.DateTime.now();
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { MembershipDocument } from "../types/membership";
|
|
2
|
+
export declare const LAST_ORG_ADMIN_TITLE = "Cannot remove the last org-admin";
|
|
3
|
+
/**
|
|
4
|
+
* Refuses (400) a membership change that would leave the organization with no active org-admin,
|
|
5
|
+
* so an org can never lose every administrator through a role change, suspension, or removal.
|
|
6
|
+
*/
|
|
7
|
+
export declare const assertNotLastOrgAdmin: (membership: MembershipDocument, nextRoleName?: string, nextStatus?: string) => Promise<void>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertNotLastOrgAdmin = exports.LAST_ORG_ADMIN_TITLE = void 0;
|
|
4
|
+
const errors_1 = require("../errors");
|
|
5
|
+
const organizationModel_1 = require("./organizationModel");
|
|
6
|
+
exports.LAST_ORG_ADMIN_TITLE = "Cannot remove the last org-admin";
|
|
7
|
+
const countActiveOrgAdmins = async (organizationId) => {
|
|
8
|
+
return organizationModel_1.Membership.countDocuments({
|
|
9
|
+
organizationId,
|
|
10
|
+
roleName: "org-admin",
|
|
11
|
+
status: "active",
|
|
12
|
+
});
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Refuses (400) a membership change that would leave the organization with no active org-admin,
|
|
16
|
+
* so an org can never lose every administrator through a role change, suspension, or removal.
|
|
17
|
+
*/
|
|
18
|
+
const assertNotLastOrgAdmin = async (membership, nextRoleName, nextStatus) => {
|
|
19
|
+
const remainsOrgAdmin = (nextRoleName ?? membership.roleName) === "org-admin" &&
|
|
20
|
+
(nextStatus ?? membership.status) === "active";
|
|
21
|
+
if (remainsOrgAdmin) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (membership.roleName !== "org-admin" || membership.status !== "active") {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const activeAdmins = await countActiveOrgAdmins(membership.organizationId);
|
|
28
|
+
if (activeAdmins <= 1) {
|
|
29
|
+
throw new errors_1.APIError({ status: 400, title: exports.LAST_ORG_ADMIN_TITLE });
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
exports.assertNotLastOrgAdmin = assertNotLastOrgAdmin;
|
package/dist/orgs/orgsApp.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import type express from "express";
|
|
2
2
|
import { type Application } from "express";
|
|
3
3
|
import type mongoose from "mongoose";
|
|
4
|
+
import type { AccountSecurityApp } from "../accountSecurity/accountSecurityApp";
|
|
5
|
+
import { type OrgRecoveryOptions } from "../accountSecurity/orgSecurityRoutes";
|
|
4
6
|
import { type UserModel } from "../auth";
|
|
5
7
|
import type { AnyTerrenoAccess } from "../rbac/types";
|
|
8
|
+
import type { TerrenoApp } from "../terrenoApp";
|
|
6
9
|
import type { TerrenoPlugin } from "../terrenoPlugin";
|
|
7
10
|
export interface OrgAuditEvent {
|
|
8
11
|
actorId?: string;
|
|
@@ -12,17 +15,32 @@ export interface OrgAuditEvent {
|
|
|
12
15
|
}
|
|
13
16
|
export interface OrgsAppOptions {
|
|
14
17
|
access: AnyTerrenoAccess;
|
|
18
|
+
/**
|
|
19
|
+
* The app's AccountSecurityApp. When set, org-admins get the member recovery routes at
|
|
20
|
+
* `{basePath}/:orgId/members/:userId/security/*`. TerrenoApp passes the registered one.
|
|
21
|
+
*/
|
|
22
|
+
accountSecurity?: AccountSecurityApp;
|
|
15
23
|
basePath?: string;
|
|
16
24
|
onOrgAudit?: (event: OrgAuditEvent, req: express.Request) => void | Promise<void>;
|
|
25
|
+
/** Hardening for the org-admin recovery routes, such as `{minMembershipDays: 7}`. */
|
|
26
|
+
orgRecovery?: OrgRecoveryOptions;
|
|
17
27
|
/** Nested schema for `Organization.settings`. Same as `registerOrganizationSettings`. */
|
|
18
28
|
settingsSchema?: mongoose.Schema;
|
|
19
29
|
userModel: UserModel;
|
|
20
30
|
}
|
|
21
31
|
export declare class OrgsApp implements TerrenoPlugin {
|
|
22
32
|
private readonly access;
|
|
33
|
+
private readonly accountSecurity?;
|
|
23
34
|
private readonly basePath;
|
|
24
35
|
private readonly onOrgAudit?;
|
|
36
|
+
private readonly orgRecovery?;
|
|
25
37
|
private readonly userModel;
|
|
26
38
|
constructor(options: OrgsAppOptions);
|
|
27
|
-
register(app: Application, openApi?: unknown): void;
|
|
39
|
+
register(app: Application, openApi?: unknown, terrenoApp?: TerrenoApp): void;
|
|
40
|
+
/**
|
|
41
|
+
* The org recovery routes reuse AccountSecurityApp's pipeline, which only registration wires
|
|
42
|
+
* up: the AuditApp check, access control for the D9 reach check, and the user model. Refuse an
|
|
43
|
+
* instance that is neither registered nor about to be on the same TerrenoApp.
|
|
44
|
+
*/
|
|
45
|
+
private assertAccountSecurityRegistered;
|
|
28
46
|
}
|
package/dist/orgs/orgsApp.js
CHANGED
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.OrgsApp = void 0;
|
|
4
4
|
const express_1 = require("express");
|
|
5
|
+
const orgSecurityRoutes_1 = require("../accountSecurity/orgSecurityRoutes");
|
|
5
6
|
const api_1 = require("../api");
|
|
6
7
|
const auth_1 = require("../auth");
|
|
7
8
|
const errors_1 = require("../errors");
|
|
8
9
|
const logger_1 = require("../logger");
|
|
9
10
|
const openApiBuilder_1 = require("../openApiBuilder");
|
|
10
11
|
const plugins_1 = require("../plugins");
|
|
12
|
+
const membershipGuards_1 = require("./membershipGuards");
|
|
11
13
|
const organizationModel_1 = require("./organizationModel");
|
|
12
14
|
const organizationSettings_1 = require("./organizationSettings");
|
|
13
15
|
const orgContext_1 = require("./orgContext");
|
|
@@ -71,25 +73,17 @@ const loadActiveMembership = async (user, organizationId) => {
|
|
|
71
73
|
});
|
|
72
74
|
return membership ?? undefined;
|
|
73
75
|
};
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
if (membership.roleName !== "org-admin" || membership.status !== "active") {
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
const activeAdmins = await countActiveOrgAdmins(membership.organizationId);
|
|
91
|
-
if (activeAdmins <= 1) {
|
|
92
|
-
throw new errors_1.APIError({ status: 400, title: "Cannot remove the last org-admin" });
|
|
76
|
+
/**
|
|
77
|
+
* Suspend every membership in the organization and clear each member's cached permissions, so an
|
|
78
|
+
* org-admin of a disabled or deleted organization loses its grants on the next request instead of
|
|
79
|
+
* after the permission cache TTL. The members are read after the update so a membership added
|
|
80
|
+
* meanwhile is covered too.
|
|
81
|
+
*/
|
|
82
|
+
const suspendOrganizationMemberships = async (access, organizationId) => {
|
|
83
|
+
await organizationModel_1.Membership.updateMany({ organizationId }, { status: "suspended" });
|
|
84
|
+
const userIds = await organizationModel_1.Membership.distinct("userId", { organizationId });
|
|
85
|
+
for (const userId of userIds) {
|
|
86
|
+
access.invalidateCache({ userId: String(userId) });
|
|
93
87
|
}
|
|
94
88
|
};
|
|
95
89
|
const assertCan = async (args) => {
|
|
@@ -105,19 +99,24 @@ const assertCan = async (args) => {
|
|
|
105
99
|
};
|
|
106
100
|
class OrgsApp {
|
|
107
101
|
access;
|
|
102
|
+
accountSecurity;
|
|
108
103
|
basePath;
|
|
109
104
|
onOrgAudit;
|
|
105
|
+
orgRecovery;
|
|
110
106
|
userModel;
|
|
111
107
|
constructor(options) {
|
|
112
108
|
this.access = options.access;
|
|
109
|
+
this.accountSecurity = options.accountSecurity;
|
|
113
110
|
this.basePath = options.basePath ?? "/orgs";
|
|
114
111
|
this.onOrgAudit = options.onOrgAudit;
|
|
112
|
+
this.orgRecovery = options.orgRecovery;
|
|
115
113
|
this.userModel = options.userModel;
|
|
116
114
|
if (options.settingsSchema) {
|
|
117
115
|
(0, organizationSettings_1.registerOrganizationSettings)(options.settingsSchema);
|
|
118
116
|
}
|
|
119
117
|
}
|
|
120
|
-
register(app, openApi) {
|
|
118
|
+
register(app, openApi, terrenoApp) {
|
|
119
|
+
this.assertAccountSecurityRegistered(terrenoApp);
|
|
121
120
|
const router = (0, express_1.Router)();
|
|
122
121
|
const openApiMiddleware = openApi;
|
|
123
122
|
const docs = (summary, requestBody) => {
|
|
@@ -233,7 +232,7 @@ class OrgsApp {
|
|
|
233
232
|
}
|
|
234
233
|
await organization.save();
|
|
235
234
|
if (wantsDisable) {
|
|
236
|
-
await
|
|
235
|
+
await suspendOrganizationMemberships(this.access, organization._id);
|
|
237
236
|
}
|
|
238
237
|
await emitOrgAudit({
|
|
239
238
|
event: {
|
|
@@ -252,7 +251,7 @@ class OrgsApp {
|
|
|
252
251
|
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
253
252
|
organization.deleted = true;
|
|
254
253
|
await organization.save();
|
|
255
|
-
await
|
|
254
|
+
await suspendOrganizationMemberships(this.access, organization._id);
|
|
256
255
|
await emitOrgAudit({
|
|
257
256
|
event: {
|
|
258
257
|
actorId: user.id,
|
|
@@ -317,6 +316,8 @@ class OrgsApp {
|
|
|
317
316
|
roleName,
|
|
318
317
|
userId: userIdOf(target),
|
|
319
318
|
});
|
|
319
|
+
// Membership grants (an org-admin's admin:access) apply at once, not after the cache TTL.
|
|
320
|
+
this.access.invalidateCache({ userId: String(created.userId) });
|
|
320
321
|
await emitOrgAudit({
|
|
321
322
|
event: {
|
|
322
323
|
actorId: user.id,
|
|
@@ -358,7 +359,7 @@ class OrgsApp {
|
|
|
358
359
|
}
|
|
359
360
|
const nextRoleName = typeof req.body?.roleName === "string" ? req.body.roleName : member.roleName;
|
|
360
361
|
const nextStatus = typeof req.body?.status === "string" ? req.body.status : member.status;
|
|
361
|
-
await assertNotLastOrgAdmin(member, nextRoleName, nextStatus);
|
|
362
|
+
await (0, membershipGuards_1.assertNotLastOrgAdmin)(member, nextRoleName, nextStatus);
|
|
362
363
|
if (typeof req.body?.roleName === "string") {
|
|
363
364
|
member.roleName = req.body.roleName === "org-admin" ? "org-admin" : "member";
|
|
364
365
|
}
|
|
@@ -366,6 +367,7 @@ class OrgsApp {
|
|
|
366
367
|
member.status = req.body.status === "suspended" ? "suspended" : "active";
|
|
367
368
|
}
|
|
368
369
|
await member.save();
|
|
370
|
+
this.access.invalidateCache({ userId: String(member.userId) });
|
|
369
371
|
await emitOrgAudit({
|
|
370
372
|
event: {
|
|
371
373
|
actorId: user.id,
|
|
@@ -396,8 +398,9 @@ class OrgsApp {
|
|
|
396
398
|
if (!member) {
|
|
397
399
|
throw new errors_1.NotFoundError("Membership not found");
|
|
398
400
|
}
|
|
399
|
-
await assertNotLastOrgAdmin(member, "member", "suspended");
|
|
401
|
+
await (0, membershipGuards_1.assertNotLastOrgAdmin)(member, "member", "suspended");
|
|
400
402
|
await member.deleteOne();
|
|
403
|
+
this.access.invalidateCache({ userId: String(member.userId) });
|
|
401
404
|
await emitOrgAudit({
|
|
402
405
|
event: {
|
|
403
406
|
actorId: user.id,
|
|
@@ -410,7 +413,35 @@ class OrgsApp {
|
|
|
410
413
|
});
|
|
411
414
|
return res.status(204).send();
|
|
412
415
|
}));
|
|
416
|
+
if (this.accountSecurity) {
|
|
417
|
+
(0, orgSecurityRoutes_1.mountOrgSecurityRoutes)({
|
|
418
|
+
access: this.access,
|
|
419
|
+
accountSecurity: this.accountSecurity,
|
|
420
|
+
orgRecovery: this.orgRecovery,
|
|
421
|
+
router,
|
|
422
|
+
userModel: this.userModel,
|
|
423
|
+
});
|
|
424
|
+
}
|
|
413
425
|
app.use(this.basePath, router);
|
|
414
426
|
}
|
|
427
|
+
/**
|
|
428
|
+
* The org recovery routes reuse AccountSecurityApp's pipeline, which only registration wires
|
|
429
|
+
* up: the AuditApp check, access control for the D9 reach check, and the user model. Refuse an
|
|
430
|
+
* instance that is neither registered nor about to be on the same TerrenoApp.
|
|
431
|
+
*/
|
|
432
|
+
assertAccountSecurityRegistered = (terrenoApp) => {
|
|
433
|
+
const accountSecurity = this.accountSecurity;
|
|
434
|
+
if (!accountSecurity || accountSecurity.isRegistered()) {
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (terrenoApp?.getRegistrations().includes(accountSecurity)) {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
throw new errors_1.APIError({
|
|
441
|
+
detail: "Register the AccountSecurityApp you pass to OrgsApp (app.register(accountSecurity)) so its audit check, access control, and user model apply to the org routes.",
|
|
442
|
+
status: 500,
|
|
443
|
+
title: "OrgsApp accountSecurity is not registered",
|
|
444
|
+
});
|
|
445
|
+
};
|
|
415
446
|
}
|
|
416
447
|
exports.OrgsApp = OrgsApp;
|
|
@@ -111,6 +111,14 @@ const betterAuthAuthPrefixes = (basePath) => {
|
|
|
111
111
|
`${base}/callback`,
|
|
112
112
|
`${base}/oauth-handoff`,
|
|
113
113
|
`${base}/one-time-token`,
|
|
114
|
+
`${base}/two-factor`,
|
|
115
|
+
`${base}/passkey`,
|
|
116
|
+
`${base}/link-social`,
|
|
117
|
+
`${base}/unlink-account`,
|
|
118
|
+
`${base}/multi-session`,
|
|
119
|
+
`${base}/oauth-proxy-callback`,
|
|
120
|
+
`${base}/expo-authorization-proxy`,
|
|
121
|
+
`${base}/terreno/set-password`,
|
|
114
122
|
];
|
|
115
123
|
};
|
|
116
124
|
const isAuthPath = (path, betterAuthBasePath) => {
|
package/dist/rbac/access.js
CHANGED
|
@@ -50,6 +50,7 @@ const createAccess = (options) => {
|
|
|
50
50
|
defaultRoles: extraRoles,
|
|
51
51
|
getActorPermissions: (user) => resolver.resolvePermissionsForUser(user),
|
|
52
52
|
getPreviewPermissions: (user) => resolver.resolvePermissionsForUserUncached(user),
|
|
53
|
+
getTargetPermissions: (user) => resolver.resolvePermissionsForUser(user, { requireComplete: true }),
|
|
53
54
|
invalidateCache: resolver.invalidateCache,
|
|
54
55
|
persistAudit,
|
|
55
56
|
statements: mergedStatements,
|
|
@@ -155,7 +156,7 @@ const createAccess = (options) => {
|
|
|
155
156
|
ac: resolver.ac,
|
|
156
157
|
can,
|
|
157
158
|
fieldMask,
|
|
158
|
-
getPermissions: ({ user }) => resolver.resolvePermissionsForUser(user),
|
|
159
|
+
getPermissions: ({ requireComplete, user }) => resolver.resolvePermissionsForUser(user, { requireComplete }),
|
|
159
160
|
invalidateCache: resolver.invalidateCache,
|
|
160
161
|
middleware: (0, middleware_1.createRequireAccess)({ can }),
|
|
161
162
|
permission: (0, middleware_1.createIsPermitted)({ can }),
|
package/dist/rbac/resolve.d.ts
CHANGED
|
@@ -2,6 +2,14 @@ import type { User } from "../auth";
|
|
|
2
2
|
import type { RbacRoleModel } from "./roleModel";
|
|
3
3
|
import type { PermissionSet, Statements } from "./statements";
|
|
4
4
|
import type { PermissionSource } from "./types";
|
|
5
|
+
/** Options for {@link createPermissionResolver}'s `resolvePermissionsForUser`. */
|
|
6
|
+
export interface ResolvePermissionsOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Throw 503 instead of returning a set missing a failed source's grants. Use it where fewer
|
|
9
|
+
* permissions would loosen a check, such as comparing a target's permissions to an actor's.
|
|
10
|
+
*/
|
|
11
|
+
requireComplete?: boolean;
|
|
12
|
+
}
|
|
5
13
|
export declare const createPermissionResolver: <S extends Statements>(args: {
|
|
6
14
|
statements: S;
|
|
7
15
|
rbacRoleModel: RbacRoleModel;
|
|
@@ -23,6 +31,6 @@ export declare const createPermissionResolver: <S extends Statements>(args: {
|
|
|
23
31
|
invalidateCache: (invalidateArgs?: {
|
|
24
32
|
userId?: string;
|
|
25
33
|
}) => void;
|
|
26
|
-
resolvePermissionsForUser: (user: User) => Promise<PermissionSet>;
|
|
34
|
+
resolvePermissionsForUser: (user: User, options?: ResolvePermissionsOptions) => Promise<PermissionSet>;
|
|
27
35
|
resolvePermissionsForUserUncached: (user: User) => Promise<PermissionSet>;
|
|
28
36
|
};
|
package/dist/rbac/resolve.js
CHANGED
|
@@ -145,15 +145,15 @@ const createPermissionResolver = (args) => {
|
|
|
145
145
|
const grantsAfterSourceFailure = (user, source, cached, now) => {
|
|
146
146
|
const stale = grantsFromStaleCache(source, cached, now);
|
|
147
147
|
if (stale) {
|
|
148
|
-
return stale;
|
|
148
|
+
return { failed: true, grants: stale, incomplete: false };
|
|
149
149
|
}
|
|
150
150
|
if (cached) {
|
|
151
|
-
return denyOnlyFromCache(cached);
|
|
151
|
+
return { failed: true, grants: denyOnlyFromCache(cached), incomplete: true };
|
|
152
152
|
}
|
|
153
153
|
const userPosture = denyPosture.get(user.id);
|
|
154
154
|
if (userPosture?.has(source.name)) {
|
|
155
155
|
const deny = userPosture.get(source.name);
|
|
156
|
-
return deny ? { deny } : null;
|
|
156
|
+
return { failed: true, grants: deny ? { deny } : null, incomplete: true };
|
|
157
157
|
}
|
|
158
158
|
if (failsClosedWhenDenyUnknown(source)) {
|
|
159
159
|
throw new errors_1.APIError({
|
|
@@ -162,7 +162,7 @@ const createPermissionResolver = (args) => {
|
|
|
162
162
|
title: "Permission source unavailable",
|
|
163
163
|
});
|
|
164
164
|
}
|
|
165
|
-
return null;
|
|
165
|
+
return { failed: true, grants: null, incomplete: true };
|
|
166
166
|
};
|
|
167
167
|
const fetchSourceGrants = async (user, source, shouldCache = true) => {
|
|
168
168
|
const now = luxon_1.DateTime.now().toMillis();
|
|
@@ -171,7 +171,7 @@ const createPermissionResolver = (args) => {
|
|
|
171
171
|
try {
|
|
172
172
|
const grants = await source.getGrants({ user });
|
|
173
173
|
recordDenyPosture(user.id, source, grants);
|
|
174
|
-
return { failed: false, grants };
|
|
174
|
+
return { failed: false, grants, incomplete: false };
|
|
175
175
|
}
|
|
176
176
|
catch (error) {
|
|
177
177
|
logger_1.logger.warn("Permission source refresh failed during uncached resolution", {
|
|
@@ -179,7 +179,7 @@ const createPermissionResolver = (args) => {
|
|
|
179
179
|
policy: source.staleOnFailure ?? "deny",
|
|
180
180
|
source: source.name,
|
|
181
181
|
});
|
|
182
|
-
return
|
|
182
|
+
return grantsAfterSourceFailure(user, source, cached, now);
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
const userSources = sourceCache.get(user.id) ?? new Map();
|
|
@@ -188,13 +188,13 @@ const createPermissionResolver = (args) => {
|
|
|
188
188
|
const ttlMs = source.ttlMs ?? cacheTtlMs;
|
|
189
189
|
const cachedAfterTouch = userSources.get(source.name);
|
|
190
190
|
if (cachedAfterTouch && now - cachedAfterTouch.fetchedAt < ttlMs) {
|
|
191
|
-
return { failed: false, grants: cachedAfterTouch.grants };
|
|
191
|
+
return { failed: false, grants: cachedAfterTouch.grants, incomplete: false };
|
|
192
192
|
}
|
|
193
193
|
try {
|
|
194
194
|
const grants = await source.getGrants({ user });
|
|
195
195
|
userSources.set(source.name, { fetchedAt: now, grants });
|
|
196
196
|
recordDenyPosture(user.id, source, grants);
|
|
197
|
-
return { failed: false, grants };
|
|
197
|
+
return { failed: false, grants, incomplete: false };
|
|
198
198
|
}
|
|
199
199
|
catch (error) {
|
|
200
200
|
logger_1.logger.warn("Permission source refresh failed", {
|
|
@@ -202,14 +202,12 @@ const createPermissionResolver = (args) => {
|
|
|
202
202
|
policy: source.staleOnFailure ?? "deny",
|
|
203
203
|
source: source.name,
|
|
204
204
|
});
|
|
205
|
-
return
|
|
206
|
-
failed: true,
|
|
207
|
-
grants: grantsAfterSourceFailure(user, source, cachedAfterTouch, now),
|
|
208
|
-
};
|
|
205
|
+
return grantsAfterSourceFailure(user, source, cachedAfterTouch, now);
|
|
209
206
|
}
|
|
210
207
|
};
|
|
211
|
-
const resolveEffectivePermissions = async (user, shouldCache) => {
|
|
208
|
+
const resolveEffectivePermissions = async (user, shouldCache, requireComplete = false) => {
|
|
212
209
|
const cacheKey = permissionCacheKey(user);
|
|
210
|
+
// A cached set is always complete: a set computed during a source outage is never cached.
|
|
213
211
|
if (shouldCache) {
|
|
214
212
|
const cached = permissionCache.get(cacheKey);
|
|
215
213
|
if (cached && cached.expiresAt > luxon_1.DateTime.now().toMillis()) {
|
|
@@ -222,8 +220,15 @@ const createPermissionResolver = (args) => {
|
|
|
222
220
|
const sourceResults = new Map();
|
|
223
221
|
let anySourceFailed = false;
|
|
224
222
|
for (const source of sources) {
|
|
225
|
-
const { failed, grants } = await fetchSourceGrants(user, source, shouldCache);
|
|
223
|
+
const { failed, grants, incomplete } = await fetchSourceGrants(user, source, shouldCache);
|
|
226
224
|
anySourceFailed = anySourceFailed || failed;
|
|
225
|
+
if (incomplete && requireComplete) {
|
|
226
|
+
throw new errors_1.APIError({
|
|
227
|
+
detail: `Permission source ${source.name} failed, so its grants are unknown`,
|
|
228
|
+
status: 503,
|
|
229
|
+
title: "Permission source unavailable",
|
|
230
|
+
});
|
|
231
|
+
}
|
|
227
232
|
sourceResults.set(source.name, grants);
|
|
228
233
|
if (!grants) {
|
|
229
234
|
continue;
|
|
@@ -259,8 +264,8 @@ const createPermissionResolver = (args) => {
|
|
|
259
264
|
}
|
|
260
265
|
return permissions;
|
|
261
266
|
};
|
|
262
|
-
const resolvePermissionsForUser = async (user) => {
|
|
263
|
-
return resolveEffectivePermissions(user, true);
|
|
267
|
+
const resolvePermissionsForUser = async (user, options = {}) => {
|
|
268
|
+
return resolveEffectivePermissions(user, true, options.requireComplete === true);
|
|
264
269
|
};
|
|
265
270
|
const resolvePermissionsForUserUncached = async (user) => {
|
|
266
271
|
return resolveEffectivePermissions(user, false);
|
|
@@ -8,6 +8,12 @@ export declare const createRoleManager: (args: {
|
|
|
8
8
|
defaultRoles?: RoleDefinition[];
|
|
9
9
|
getActorPermissions: (user: User) => Promise<PermissionSet>;
|
|
10
10
|
getPreviewPermissions: (user: User) => Promise<PermissionSet>;
|
|
11
|
+
/**
|
|
12
|
+
* Resolves the user a role change acts on. It must return the complete set or throw (the
|
|
13
|
+
* access instance passes `requireComplete: true`), since a target missing a failed source's
|
|
14
|
+
* grants looks less privileged than it is. Defaults to `getActorPermissions`.
|
|
15
|
+
*/
|
|
16
|
+
getTargetPermissions?: (user: User) => Promise<PermissionSet>;
|
|
11
17
|
invalidateCache: (invalidateArgs?: {
|
|
12
18
|
userId?: string;
|
|
13
19
|
}) => void;
|
package/dist/rbac/roleManager.js
CHANGED
|
@@ -53,9 +53,10 @@ const assertNoEscalation = async (actor, permissions, getActorPermissions) => {
|
|
|
53
53
|
});
|
|
54
54
|
}
|
|
55
55
|
};
|
|
56
|
-
const assertCanModifyTargetUser = async (actor, target, getActorPermissions) => {
|
|
56
|
+
const assertCanModifyTargetUser = async (actor, target, getActorPermissions, getTargetPermissions) => {
|
|
57
57
|
const actorPermissions = await getActorPermissions(actor);
|
|
58
|
-
|
|
58
|
+
// A target missing a failed source's grants would look less privileged than it is.
|
|
59
|
+
const targetPermissions = await getTargetPermissions(target);
|
|
59
60
|
if (!(0, permissionUtils_1.isPermissionSubset)(actorPermissions, targetPermissions)) {
|
|
60
61
|
logger_1.logger.warn("RBAC privileged-user mutation denied", {
|
|
61
62
|
actorId: actor.id,
|
|
@@ -68,7 +69,7 @@ const assertCanModifyTargetUser = async (actor, target, getActorPermissions) =>
|
|
|
68
69
|
}
|
|
69
70
|
};
|
|
70
71
|
const createRoleManager = (args) => {
|
|
71
|
-
const { connection, statements, defaultRoles = roleModel_1.terrenoDefaultRoles, getActorPermissions, getPreviewPermissions, invalidateCache, userModel, persistAudit = true, auditSinks = [], } = args;
|
|
72
|
+
const { connection, statements, defaultRoles = roleModel_1.terrenoDefaultRoles, getActorPermissions, getPreviewPermissions, getTargetPermissions = getActorPermissions, invalidateCache, userModel, persistAudit = true, auditSinks = [], } = args;
|
|
72
73
|
const rbacRoleModel = (0, roleModel_1.createRbacRoleModel)(connection);
|
|
73
74
|
const rbacAuditModel = persistAudit ? (0, auditModel_1.createRbacAuditModel)(connection) : undefined;
|
|
74
75
|
const emitAudit = async (record) => {
|
|
@@ -170,7 +171,7 @@ const createRoleManager = (args) => {
|
|
|
170
171
|
if (!targetUser) {
|
|
171
172
|
throw new errors_1.APIError({ status: 404, title: "User not found" });
|
|
172
173
|
}
|
|
173
|
-
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions);
|
|
174
|
+
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions, getTargetPermissions);
|
|
174
175
|
},
|
|
175
176
|
assign: async ({ actor, userId, roleNames }) => {
|
|
176
177
|
await assertCanAssignRoles(actor, getActorPermissions);
|
|
@@ -181,7 +182,7 @@ const createRoleManager = (args) => {
|
|
|
181
182
|
if (!targetUser) {
|
|
182
183
|
throw new errors_1.APIError({ status: 404, title: "User not found" });
|
|
183
184
|
}
|
|
184
|
-
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions);
|
|
185
|
+
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions, getTargetPermissions);
|
|
185
186
|
const uniqueRoleNames = [...new Set(roleNames)];
|
|
186
187
|
for (let i = 0; i < uniqueRoleNames.length; i++) {
|
|
187
188
|
for (let j = i + 1; j < uniqueRoleNames.length; j++) {
|
|
@@ -254,7 +255,7 @@ const createRoleManager = (args) => {
|
|
|
254
255
|
if (!targetUser) {
|
|
255
256
|
throw new errors_1.APIError({ status: 404, title: "User not found" });
|
|
256
257
|
}
|
|
257
|
-
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions);
|
|
258
|
+
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions, getTargetPermissions);
|
|
258
259
|
const uniqueRoleNames = [...new Set(roleNames)];
|
|
259
260
|
for (const roleName of uniqueRoleNames) {
|
|
260
261
|
const role = await rbacRoleModel.findExactlyOne({ name: roleName });
|
|
@@ -316,7 +317,7 @@ const createRoleManager = (args) => {
|
|
|
316
317
|
if (!targetUser) {
|
|
317
318
|
throw new errors_1.APIError({ status: 404, title: "User not found" });
|
|
318
319
|
}
|
|
319
|
-
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions);
|
|
320
|
+
await assertCanModifyTargetUser(actor, targetUser, getActorPermissions, getTargetPermissions);
|
|
320
321
|
assertUserSaveAvailable(targetUser);
|
|
321
322
|
const before = await getPreviewPermissions(targetUser);
|
|
322
323
|
const rbacUser = targetUser;
|