@happyvertical/smrt-users 0.40.60 → 0.40.61
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/AGENTS.md +6 -1
- package/dist/chunks/{TerminalAuthService-ntiMq2ar.js → TerminalAuthService-h7XBwJLh.js} +34 -3
- package/dist/chunks/TerminalAuthService-h7XBwJLh.js.map +1 -0
- package/dist/collections/RoleCollection.d.ts +2 -0
- package/dist/collections/RoleCollection.d.ts.map +1 -1
- package/dist/collections/RolePermissionCollection.d.ts +9 -0
- package/dist/collections/RolePermissionCollection.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/manifest.json +29 -1
- package/dist/smrt-knowledge.json +7 -5
- package/dist/sveltekit.js +1 -1
- package/package.json +9 -9
- package/dist/chunks/TerminalAuthService-ntiMq2ar.js.map +0 -1
|
@@ -36,6 +36,8 @@ export declare class RoleCollection extends SmrtCollection<Role> {
|
|
|
36
36
|
* Find role by slug within a tenant context
|
|
37
37
|
*/
|
|
38
38
|
findBySlug(slug: string, tenantId?: string): Promise<Role | null>;
|
|
39
|
+
/** Find a built-in system role only; tenant slug collisions never match. */
|
|
40
|
+
findSystemRoleBySlug(slug: string): Promise<Role | null>;
|
|
39
41
|
/**
|
|
40
42
|
* Seed default system roles
|
|
41
43
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RoleCollection.d.ts","sourceRoot":"","sources":["../../src/collections/RoleCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,OAAO,KAAK,EACV,2BAA2B,EAC3B,0BAA0B,EAC3B,MAAM,+BAA+B,CAAC;AAEvC,MAAM,WAAW,sBACf,SAAQ,IAAI,CAAC,0BAA0B,EAAE,SAAS,CAAC;IACnD,gBAAgB,CAAC,EAAE,2BAA2B,CAAC;IAC/C,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;;;OAQG;IACH,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;CAClC;AAED;;GAEG;AACH,qBAAa,cAAe,SAAQ,cAAc,CAAC,IAAI,CAAC;IACtD,MAAM,CAAC,QAAQ,CAAC,UAAU,cAAQ;IAElC;;OAEG;IACG,eAAe,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;IAOxC;;OAEG;IACG,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IASrD;;OAEG;IACG,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAOxD;;OAEG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAoBvE;;OAEG;IACG,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;CA0D7E"}
|
|
1
|
+
{"version":3,"file":"RoleCollection.d.ts","sourceRoot":"","sources":["../../src/collections/RoleCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,OAAO,KAAK,EACV,2BAA2B,EAC3B,0BAA0B,EAC3B,MAAM,+BAA+B,CAAC;AAEvC,MAAM,WAAW,sBACf,SAAQ,IAAI,CAAC,0BAA0B,EAAE,SAAS,CAAC;IACnD,gBAAgB,CAAC,EAAE,2BAA2B,CAAC;IAC/C,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;;;OAQG;IACH,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;CAClC;AAED;;GAEG;AACH,qBAAa,cAAe,SAAQ,cAAc,CAAC,IAAI,CAAC;IACtD,MAAM,CAAC,QAAQ,CAAC,UAAU,cAAQ;IAElC;;OAEG;IACG,eAAe,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;IAOxC;;OAEG;IACG,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IASrD;;OAEG;IACG,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAOxD;;OAEG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAoBvE,4EAA4E;IACtE,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAQ9D;;OAEG;IACG,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;CA0D7E"}
|
|
@@ -16,6 +16,8 @@ export interface SeedRolePermissionsOptions {
|
|
|
16
16
|
*/
|
|
17
17
|
syncCatalog?: boolean;
|
|
18
18
|
tenantId?: string;
|
|
19
|
+
/** @internal Restrict the matrix to system roles (tenantId null + isSystem). */
|
|
20
|
+
systemRolesOnly?: boolean;
|
|
19
21
|
}
|
|
20
22
|
export interface SeedRolePermissionsResult {
|
|
21
23
|
added: Record<string, string[]>;
|
|
@@ -64,5 +66,12 @@ export declare class RolePermissionCollection extends SmrtCollection<RolePermiss
|
|
|
64
66
|
* slugs are added, and stale mappings are only removed when `prune` is true.
|
|
65
67
|
*/
|
|
66
68
|
seedRolePermissions(matrix?: RolePermissionPatternMatrix, options?: SeedRolePermissionsOptions): Promise<SeedRolePermissionsResult>;
|
|
69
|
+
/**
|
|
70
|
+
* Add the catalog-registered self-personalization grant to existing built-in
|
|
71
|
+
* roles. This is the explicit, idempotent upgrade path for applications
|
|
72
|
+
* whose roles predate the Fields permission; custom role matrices are never
|
|
73
|
+
* considered here.
|
|
74
|
+
*/
|
|
75
|
+
seedDefaultRolePersonalizationPermissions(options?: Omit<SeedRolePermissionsOptions, 'prune'>): Promise<SeedRolePermissionsResult>;
|
|
67
76
|
}
|
|
68
77
|
//# sourceMappingURL=RolePermissionCollection.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RolePermissionCollection.d.ts","sourceRoot":"","sources":["../../src/collections/RolePermissionCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAEL,KAAK,iBAAiB,EAEvB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAsB,KAAK,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAI7E,MAAM,MAAM,2BAA2B,GAAG,OAAO,CAC/C,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAClC,CAAC;AAEF,MAAM,WAAW,0BAA0B;IACzC,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"RolePermissionCollection.d.ts","sourceRoot":"","sources":["../../src/collections/RolePermissionCollection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAEL,KAAK,iBAAiB,EAEvB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAsB,KAAK,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAI7E,MAAM,MAAM,2BAA2B,GAAG,OAAO,CAC/C,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAClC,CAAC;AAEF,MAAM,WAAW,0BAA0B;IACzC,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAClC,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAC7C,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACpC,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CAC7C;AAED,eAAO,MAAM,gCAAgC,EAAE,MAAM,CACnD,eAAe,EACf,SAAS,MAAM,EAAE,CAMlB,CAAC;AA4GF;;GAEG;AACH,qBAAa,wBAAyB,SAAQ,cAAc,CAAC,cAAc,CAAC;IAC1E,MAAM,CAAC,QAAQ,CAAC,UAAU,wBAAkB;IAE5C;;OAEG;IACG,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAM3D;;OAEG;IACG,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAMvE;;OAEG;IACG,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAQ3E;;OAEG;IACG,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,cAAc,CAAC;IAe1B;;OAEG;IACG,gBAAgB,CACpB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,OAAO,CAAC;IAanB;;OAEG;IACG,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAKzD;;;;;;OAMG;IACG,mBAAmB,CACvB,MAAM,GAAE,2BAA8D,EACtE,OAAO,GAAE,0BAA+B,GACvC,OAAO,CAAC,yBAAyB,CAAC;IAiHrC;;;;;OAKG;IACG,yCAAyC,CAC7C,OAAO,GAAE,IAAI,CAAC,0BAA0B,EAAE,OAAO,CAAM,GACtD,OAAO,CAAC,yBAAyB,CAAC;CAWtC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as PermissionCollection, A as UserEmailKeyBackfillError, B as Session, C as decodeOidcTransaction, Ct as TenantPermissionEffect, E as resolveOidcProviderConfig, F as TenantHierarchyError, G as deriveOperationPermissionCollectionName, H as DEFAULT_ROLE_PERMISSION_PATTERNS, I as MAX_TENANT_HIERARCHY_DEPTH, J as registerPermissionDefinitions, K as deriveOperationPermissionSlug, L as Tenant, M as TenantPermissionOverrideCollection, N as TenantPermissionOverride, O as OidcProvisioningError, P as TenantCollection, Q as Role, R as SessionCollection, S as OidcLoginService, St as SessionStatus, T as getUsersOidcConfig, Tt as UserStatus, U as RolePermissionCollection, V as generateSessionId, W as PermissionCatalogService, X as RolePermission, Y as syncPermissionCatalog, Z as RoleCollection, _ as readMobileBearerToken, _t as DEFAULT_ROLES, a as TerminalAuthRateLimitError, at as GroupRoleCollection, b as PermissionResolver, bt as MembershipStatus, c as assertOperationPermission, ct as GroupMember, d as getCurrentSessionPermissionContext, dt as UsersCliAuthRequestCollection, et as Permission, f as getRequestScopedDatabase, ft as UsersCliAuthRequest, g as MobileAuthService, gt as AccessRequestStatus, h as MobileAuthError, ht as normalizeEmail, i as TerminalAuthError, it as Membership, j as backfillUserEmailKeys, k as UserCollection, l as checkOperationPermission, lt as GroupCollection, m as withSessionPermissionContext, mt as isValidEmail, n as DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, nt as MembershipOverride, o as TerminalAuthService, ot as GroupRole, p as withPrincipalPermissionContext, pt as User, q as normalizeOperationPermissionAction, r as DEFAULT_CLI_SESSION_TTL_SECONDS, rt as MembershipCollection, s as OperationPermissionError, st as GroupMemberCollection, t as DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, tt as MembershipOverrideCollection, u as hasOperationPermission, ut as Group, v as validateMobileRedirectUri, vt as DEFAULT_ROLE_SLUGS, w as encodeOidcTransaction, wt as TenantStatus, x as OidcLoginError, xt as OverrideEffect, y as SessionService, yt as DEFAULT_TENANT_POLICY, z as DEFAULT_SESSION_TTL } from "./chunks/TerminalAuthService-
|
|
1
|
+
import { $ as PermissionCollection, A as UserEmailKeyBackfillError, B as Session, C as decodeOidcTransaction, Ct as TenantPermissionEffect, E as resolveOidcProviderConfig, F as TenantHierarchyError, G as deriveOperationPermissionCollectionName, H as DEFAULT_ROLE_PERMISSION_PATTERNS, I as MAX_TENANT_HIERARCHY_DEPTH, J as registerPermissionDefinitions, K as deriveOperationPermissionSlug, L as Tenant, M as TenantPermissionOverrideCollection, N as TenantPermissionOverride, O as OidcProvisioningError, P as TenantCollection, Q as Role, R as SessionCollection, S as OidcLoginService, St as SessionStatus, T as getUsersOidcConfig, Tt as UserStatus, U as RolePermissionCollection, V as generateSessionId, W as PermissionCatalogService, X as RolePermission, Y as syncPermissionCatalog, Z as RoleCollection, _ as readMobileBearerToken, _t as DEFAULT_ROLES, a as TerminalAuthRateLimitError, at as GroupRoleCollection, b as PermissionResolver, bt as MembershipStatus, c as assertOperationPermission, ct as GroupMember, d as getCurrentSessionPermissionContext, dt as UsersCliAuthRequestCollection, et as Permission, f as getRequestScopedDatabase, ft as UsersCliAuthRequest, g as MobileAuthService, gt as AccessRequestStatus, h as MobileAuthError, ht as normalizeEmail, i as TerminalAuthError, it as Membership, j as backfillUserEmailKeys, k as UserCollection, l as checkOperationPermission, lt as GroupCollection, m as withSessionPermissionContext, mt as isValidEmail, n as DEFAULT_CLI_AUTH_REQUEST_TTL_SECONDS, nt as MembershipOverride, o as TerminalAuthService, ot as GroupRole, p as withPrincipalPermissionContext, pt as User, q as normalizeOperationPermissionAction, r as DEFAULT_CLI_SESSION_TTL_SECONDS, rt as MembershipCollection, s as OperationPermissionError, st as GroupMemberCollection, t as DEFAULT_CLI_AUTH_POLL_INTERVAL_SECONDS, tt as MembershipOverrideCollection, u as hasOperationPermission, ut as Group, v as validateMobileRedirectUri, vt as DEFAULT_ROLE_SLUGS, w as encodeOidcTransaction, wt as TenantStatus, x as OidcLoginError, xt as OverrideEffect, y as SessionService, yt as DEFAULT_TENANT_POLICY, z as DEFAULT_SESSION_TTL } from "./chunks/TerminalAuthService-h7XBwJLh.js";
|
|
2
2
|
import { ObjectRegistry, SmrtCollection, SmrtObject, field, findManifestEntryByQualifiedName, smrt } from "@happyvertical/smrt-core";
|
|
3
3
|
import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
|
|
4
4
|
import { createLogger } from "@happyvertical/logger";
|
|
@@ -918,7 +918,7 @@ var MagicLinkService = class MagicLinkService {
|
|
|
918
918
|
* The caller is responsible for emailing the token to the user.
|
|
919
919
|
*/
|
|
920
920
|
async generate(email) {
|
|
921
|
-
const { SignJWT } = await import("./chunks/TerminalAuthService-
|
|
921
|
+
const { SignJWT } = await import("./chunks/TerminalAuthService-h7XBwJLh.js").then((n) => n.D);
|
|
922
922
|
const key = await this.getSigningKey();
|
|
923
923
|
const nonce = crypto.randomUUID();
|
|
924
924
|
const normalizedEmail = normalizeEmail(email);
|
|
@@ -947,7 +947,7 @@ var MagicLinkService = class MagicLinkService {
|
|
|
947
947
|
* @throws {MagicLinkError} If the token is invalid, expired, or already used
|
|
948
948
|
*/
|
|
949
949
|
async verify(token) {
|
|
950
|
-
const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-
|
|
950
|
+
const { jwtVerify, errors } = await import("./chunks/TerminalAuthService-h7XBwJLh.js").then((n) => n.D);
|
|
951
951
|
const key = await this.getSigningKey();
|
|
952
952
|
let payload;
|
|
953
953
|
try {
|
package/dist/manifest.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": "1.0.0",
|
|
3
3
|
"timestamp": 0,
|
|
4
4
|
"packageName": "@happyvertical/smrt-users",
|
|
5
|
-
"packageVersion": "0.40.
|
|
5
|
+
"packageVersion": "0.40.61",
|
|
6
6
|
"objects": {
|
|
7
7
|
"@happyvertical/smrt-users:AccessRequestCollection": {
|
|
8
8
|
"name": "accessrequestcollection",
|
|
@@ -1359,6 +1359,20 @@
|
|
|
1359
1359
|
"isStatic": false,
|
|
1360
1360
|
"isPublic": true
|
|
1361
1361
|
},
|
|
1362
|
+
"findSystemRoleBySlug": {
|
|
1363
|
+
"name": "findSystemRoleBySlug",
|
|
1364
|
+
"async": true,
|
|
1365
|
+
"parameters": [
|
|
1366
|
+
{
|
|
1367
|
+
"name": "slug",
|
|
1368
|
+
"type": "string",
|
|
1369
|
+
"optional": false
|
|
1370
|
+
}
|
|
1371
|
+
],
|
|
1372
|
+
"returnType": "Promise<Role | null>",
|
|
1373
|
+
"isStatic": false,
|
|
1374
|
+
"isPublic": true
|
|
1375
|
+
},
|
|
1362
1376
|
"seedSystemRoles": {
|
|
1363
1377
|
"name": "seedSystemRoles",
|
|
1364
1378
|
"async": true,
|
|
@@ -1554,6 +1568,20 @@
|
|
|
1554
1568
|
"returnType": "Promise<SeedRolePermissionsResult>",
|
|
1555
1569
|
"isStatic": false,
|
|
1556
1570
|
"isPublic": true
|
|
1571
|
+
},
|
|
1572
|
+
"seedDefaultRolePersonalizationPermissions": {
|
|
1573
|
+
"name": "seedDefaultRolePersonalizationPermissions",
|
|
1574
|
+
"async": true,
|
|
1575
|
+
"parameters": [
|
|
1576
|
+
{
|
|
1577
|
+
"name": "options",
|
|
1578
|
+
"type": "Omit<SeedRolePermissionsOptions, 'prune'>",
|
|
1579
|
+
"optional": true
|
|
1580
|
+
}
|
|
1581
|
+
],
|
|
1582
|
+
"returnType": "Promise<SeedRolePermissionsResult>",
|
|
1583
|
+
"isStatic": false,
|
|
1584
|
+
"isPublic": true
|
|
1557
1585
|
}
|
|
1558
1586
|
},
|
|
1559
1587
|
"decoratorConfig": {},
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
4
4
|
"packageName": "@happyvertical/smrt-users",
|
|
5
|
-
"packageVersion": "0.40.
|
|
5
|
+
"packageVersion": "0.40.61",
|
|
6
6
|
"sourceManifestPath": "dist/manifest.json",
|
|
7
7
|
"agentDocPath": "AGENTS.md",
|
|
8
8
|
"sourceHashes": {
|
|
9
|
-
"manifest": "
|
|
10
|
-
"packageJson": "
|
|
11
|
-
"agents": "
|
|
9
|
+
"manifest": "e76015b8be84d5ca02856ebbd1d8ae42f4c8a81e1e4cf3c6fbb76a32f8aed155",
|
|
10
|
+
"packageJson": "1a713e6070802988ea2721f9b63baccf3d11cb9f552602a487d11a1b50b297b0",
|
|
11
|
+
"agents": "0e476c050275a8d14f5dfdf70c4b07a90af1445018ed505d2c1a0d25d1f41ddd"
|
|
12
12
|
},
|
|
13
13
|
"exports": [
|
|
14
14
|
".",
|
|
@@ -279,6 +279,7 @@
|
|
|
279
279
|
"methods": [
|
|
280
280
|
"findBySlug",
|
|
281
281
|
"findByTenant",
|
|
282
|
+
"findSystemRoleBySlug",
|
|
282
283
|
"findSystemRoles",
|
|
283
284
|
"findTenantRoles",
|
|
284
285
|
"seedSystemRoles"
|
|
@@ -306,6 +307,7 @@
|
|
|
306
307
|
"getPermissionIds",
|
|
307
308
|
"hasPermission",
|
|
308
309
|
"removePermission",
|
|
310
|
+
"seedDefaultRolePersonalizationPermissions",
|
|
309
311
|
"seedRolePermissions"
|
|
310
312
|
],
|
|
311
313
|
"surfaces": [],
|
|
@@ -3080,5 +3082,5 @@
|
|
|
3080
3082
|
"polymorphicAssociations": 0,
|
|
3081
3083
|
"uuidColumns": 52
|
|
3082
3084
|
},
|
|
3083
|
-
"agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant user management with RBAC, hierarchical tenants, session handling, and SvelteKit integration.\n\n## Models (14)\n\n| Model | Key Pattern |\n|-------|-------------|\n| User | Auth identity. `profileId` is a unique cross-package reference to smrt-profiles (one User per non-null Profile). Email auto-lowercased; readonly nullable unique `emailKey` is derived on save for durable normalized uniqueness. |\n| AccessRequest | \"Request access / waitlist\" record captured before a `User` exists. CLOSED generated surface (`api`/`mcp`/`cli` = `[]`) — all access via `AccessRequestService`. Email normalized + indexed; JSON `requestContext` (NOT `context` — reserved for slug scoping). |\n| Tenant | **STI** + hierarchical parent-child. `hierarchyPath` (materialized path), `hierarchyLevel`. Max depth 10. |\n| Session | Server-side. Secure UUID. TTL in **seconds** (not ms). Status auto-updates to EXPIRED on access. |\n| MagicLinkToken | Single-use email login token. Backed by `MagicLinkService`. |\n| Role | `tenantId = null` → system role (available to all tenants). `isSystem: true` blocks deletion. `inheritsToDescendants: true` (default false) opts the role's membership authority into descendant tenants. |\n| Permission | Slug format: `resource.action`. Parsed by PermissionResolver. |\n| Membership | User + Tenant + Role junction. UNIQUE(userId, tenantId). |\n| Group | Team within a tenant. Multiple roles via GroupRole. |\n| GroupMember, GroupRole, RolePermission | Join tables. |\n| MembershipOverride | Per-user permission grant/deny. **DENY always wins.** |\n| TenantPermissionOverride | Tenant-level cascade overrides. Effect: INHERIT/GRANT/DENY. |\n\n## Permission Resolution — Precedence (broad → specific, most-specific wins)\n\n`PermissionResolver.resolvePermissions` builds the effective set in this order;\neach later layer overrides earlier ones:\n\n1. **Tenant-inherited** — walk ancestors, apply each `TenantPermissionOverride`\n down the cascade (GRANT adds, DENY removes within the hierarchy)\n2. **Membership role** — base permissions from the user's role in the tenant\n3. **Group roles** — permissions from all groups the user belongs to **in that tenant**\n4. **Tenant-level DENY** *(removes; overrides role/group grants, tenant-wide)* — a\n `TenantPermissionOverride` with effect `DENY` is a HARD, tenant-wide block: it\n subtracts the DENY'd slug even if a role or group granted it (steps 2–3). It\n sits just **above** the per-user membership overrides and **below** role/group.\n5. **Membership GRANT override** *(re-adds; most specific)* — a per-user GRANT can\n re-add a slug a tenant DENY'd in step 4, because it is more specific.\n6. **Membership DENY override** *(absolute; always wins)* — a per-user DENY removes\n the slug last and is never overridden.\n\nSo a permission a role grants but the tenant DENYs is **removed**, unless that\nexact user also has a membership-GRANT override for it. A membership-DENY always\nwins. Tenant-DENY of an inherited/cascade grant still blocks it (unchanged).\nThe hard block reflects the tenant cascade's **net** resolution, not an\nunconditional union of every DENY in the chain — so a more-specific tenant GRANT\n(e.g. a child sub-tenant re-granting a permission its parent DENYs) still wins.\n\n### Membership selection — hierarchical inheritance (opt-in, #1866)\n\nWhich membership feeds step 2 above:\n\n1. **A direct membership row in the target tenant always pins resolution to\n itself** — active rows resolve normally; an inactive (pending/suspended)\n row resolves to the **empty set**. A direct row therefore *attenuates*\n rather than unions: \"viewer here, despite being network admin\" gives\n viewer, and a suspension in the child is effective even for users holding\n inheritable authority on an ancestor.\n2. **No direct row** → the resolver walks the tenant's ancestors (nearest\n first, from `hierarchyPath`) and resolves through the **nearest ACTIVE\n ancestor membership whose role has `inheritsToDescendants: true`**.\n Unflagged or inactive ancestor memberships are skipped (they neither confer\n nor block); there is **no union across the chain** — the nearest flagged\n membership alone is used. To attenuate a specific descendant, create a\n direct membership there or use a tenant-level DENY.\n3. **No qualifying ancestor** → empty set (byte-identical to the\n pre-inheritance resolver; with no role flagged, nothing changes).\n\nAll later layers run unchanged against the **target** tenant: the tenant\ncascade and tenant-DENY hard block come from the target tenant (a child can\ncarve authority out of an inherited role), group roles stay exact-tenant (only\ntarget-tenant groups contribute; ancestor groups never flow down), and\nmembership GRANT/DENY overrides travel with the ancestor membership used.\n`PermissionResolutionResult.inheritedFromTenantId` reports the ancestor tenant\nwhen inheritance was used (`null` for direct resolution).\n\nSafety: resolution is bounded by `MAX_TENANT_HIERARCHY_DEPTH`; malformed\n`hierarchyPath` values fail closed to the empty set — too deep,\nself-referential, duplicate ancestors, or inconsistent with the actual\n`parentTenantId` chain (the path is verified link-by-link against the loaded\nancestor rows before it is trusted as an authorization source). Tenant `status` is not consulted (parity with direct\nresolution). Caching: a long-lived `(user, tenant)` permission cache must also\ninvalidate on ancestor-membership changes and on `Role.inheritsToDescendants`\nflips — request-scoped caches (the common pattern) are unaffected.\n\nFlag roles at seed time with\n`seedSystemRoles({ inheritsToDescendants: ['owner', 'admin'] })` (additive:\nlisted slugs are flagged, omitted slugs are never unflagged; unknown slugs\nthrow). The default seed leaves every role exact-tenant.\n\n## Operation Permission Guards\n\nSMRT derives a fine-grained, per-`<collection>.<action>` permission catalog **from the\nmanifest** (`PermissionCatalogService`, including custom `@smrt` actions — not just CRUD)\nand enforces it two ways: app-side via `assertOperationPermission()` / `PermissionResolver`,\nand at the database via generated **Postgres RLS** policies\n(`generatePostgresPermissionSql()` / `applyPostgresPermissionPolicies()`) that read the\nsession-injected `smrt.permissions` / `smrt.tenant_id` (set by `withSessionPermissionContext`\nvia `set_config`). Because the RLS teeth are at the data layer, enforcement is door-agnostic\n— REST, MCP, and in-process callers are all bounded once the principal's context is set.\nSetup: README → *Manifest-derived permission catalog* and *Postgres RLS enforcement*.\n\n- Use `assertOperationPermission()` for hand-written mutations in SvelteKit form\n actions, custom endpoints, CLI scripts, and jobs. It derives the same\n `<collection>.<action>` slugs as `PermissionCatalogService` (`list`/`get` →\n `read`), requires the slug to exist in the catalog, then resolves permissions\n through `PermissionResolver`.\n- `assertOperationPermission()` throws fail-closed by default. Use\n `{ onDeny: 'return' }`, `checkOperationPermission()`, or\n `hasOperationPermission()` when a structured/boolean result is needed.\n- **Resource-tenant calling convention**: for resource-anchored authorization,\n pass the **resource's** tenant id — `tenantId: resourceTenantId` — not the\n session's current tenant. With `Role.inheritsToDescendants` flagged, a\n root-tenant admin then passes for any descendant resource with no app-side\n authority logic (and no membership fan-out), while per-child delegation and\n DENY precedence keep working. Do NOT pass a session-scoped `membership`\n alongside a different resource `tenantId` — a membership/tenant mismatch\n fails closed by design; omit `membership` and let the resolver look it up.\n- System context and super-admin bypass context are honored for parity with\n Postgres RLS. Pass `{ allowSuperAdminBypass: false }` on money-class or\n separation-of-duties operations that must require an explicit permission grant.\n- **Postgres RLS and membership inheritance**: RLS policies check the\n session-injected `smrt.permissions` list (resolved app-side by\n `PermissionResolver`), so a session whose `smrt.tenant_id` IS the child\n tenant gets inherited authority in RLS automatically. But RLS row filtering\n stays bound to the session's tenant setting — a root-tenant session acting\n on child-tenant rows is authorized by the app-level guard (resource-tenant\n convention above), not by RLS. This is a documented divergence, mirroring\n how #1829 handled bypass parity.\n- Seed role mappings with `RolePermissionCollection.seedRolePermissions()` or\n `RoleCollection.seedSystemRoles({ seedPermissions: true })`. The default\n matrix maps owner/admin to all catalog permissions, member to read/create for\n ordinary app resources, and viewer to read-only. Member create grants\n intentionally exclude users/RBAC authority and security resources (`users`,\n `tenants`, `roles`, `permissions`, memberships, groups, sessions, magic-link\n tokens, and related join/override tables). Re-seeding is additive and\n idempotent; pruning stale mappings requires `{ prune: true }`.\n\n**Critical**: `getGroupIdsForTenant(userId, tenantId)` (joins with groups table to scope by tenant). Never use `getGroupIds()` — it's cross-tenant.\n\n## Hierarchical Tenants\n\n- `TenantCollection.createChild()` auto-calculates hierarchy fields, enforces depth limit\n- `moveToParent()` updates tenant + ALL descendants' paths/levels\n- `cascadePermissions` (parent pushes down) + `inheritPermissions` (child accepts) — both must be true\n- `getTree(rootId?)` returns nested structure for UI\n- Two independent downward flows: the `TenantPermissionOverride` **cascade**\n (tenant-level permission config, flags above) and **membership-role\n inheritance** (`Role.inheritsToDescendants`, per-role opt-in — see\n \"Membership selection\" above). The cascade flags do not gate membership\n inheritance.\n\n## SvelteKit Integration\n\n```typescript\n// hooks.server.ts\nexport const handle = createSessionHandler({ db, ttl: 604800, skipPaths: ['/api/public'] });\n// Populates event.locals: { user, membership, permissions: string[], tenantId, sessionId }\n\n// +page.server.ts\nawait createSessionCookie(event, userId, tenantId, { db });\nawait destroySessionCookie(event, { db });\nawait switchSessionTenant(event, tenantId, { db });\n```\n\n## Mobile `/api/mobile` Handlers (ADR 0001 Phase 3.5, #1748)\n\n`createMobileAuthHandlers(options)` (from `/sveltekit`) returns the mountable\nserver side of the KMP mobile contract: `authStart` (`POST auth/start`,\nserver-brokered PKCE via `OidcLoginService`), `authComplete`\n(`POST auth/complete`, code + echoed `state`/`codeVerifier` → bearer\nsession), `session.GET`/`session.DELETE` (bootstrap/logout), and\n`guard`/`withSession` — the bearer middleware for app-owned mobile routes.\nCore logic lives in `MobileAuthService` (framework-agnostic; exported from\nthe package root).\n\n- **Bearer = session id** (same convention as `TerminalAuthService`); 401\n bodies are `{ error, code }` and drive the mobile client's re-auth flow.\n- **Stateless handshake**: the OAuth `state` is an HMAC-signed token\n (secret: `stateSecret` ?? provider `clientSecret`) carrying\n nonce/provider/createdAt — full ID-token nonce verification with no\n server-side pending state. The `codeVerifier` never enters a URL: it is\n client-held per the frozen contract.\n- **Wire DTOs** come from `@happyvertical/smrt-mobile-contract`\n (`MobileAuthStartRequest` etc.) — one owning package for the Kotlin,\n Swift, and TypeScript shapes (compile-checked descriptors + parity test).\n- **Tenant options** honor `Role.inheritsToDescendants` (#1867): direct\n ACTIVE memberships plus descendants of flagged memberships (nearest\n flagged ancestor labels the option; any direct row pins; inactive direct\n rows exclude). Session binding defaults to the first DIRECT tenant —\n override with `resolveTenantId`.\n- **Hooks**: `resolveUser` (invite-gating; default provisions via\n `getOrCreateFromOidc`), `resolveTenantId`, `buildExtras` (bootstrap\n `extras`; model JSON must use `toPublicJSON({ permissions })` — #1822).\n `buildExtras` is the only app-domain bootstrap extension point. Never emit\n app fields such as `dashboard` at the response top level: they are outside\n `MobileSessionBootstrap` and the Kotlin decoder ignores them.\n- **Guard** wraps `withSessionPermissionContext`, so\n `assertOperationPermission`, tenancy context, and Postgres RLS all see the\n bearer caller; `OperationPermissionError` maps to 403 with a\n machine-readable `reason`.\n- **Uploads**: `resolveMobileUploadDedupKey` + the documented contract in\n `docs/content/architecture/mobile-upload-contract.md` (`clientCaptureId`\n field, `Idempotency-Key` header fallback); domain ingestion stays\n app-side. Framework-model writes ride `sync/apply`, not this path.\n- Configure `redirectUris` in production — RFC 8252 scheme rules always\n apply, but the allow list is the defense against redirecting authorization\n responses to attacker-controlled URIs.\n\n## Security (S5 #1400)\n\n- **Generated REST/MCP surface is READ-ONLY for every RBAC/identity model.**\n User, Tenant, Group, Membership, MembershipOverride, Role, Permission,\n RolePermission, GroupRole, GroupMember, and TenantPermissionOverride generate\n `list`/`get` only — `create`/`update`/`delete` are intentionally NOT\n generated. The merged `requireRouteAuth` gate (#1540) enforces *authentication*,\n not *authorization*, and these models are not `@TenantScoped`, so an\n auto-generated mutating route would let any authenticated user self-grant a\n role/permission, flip a tenant's cascade flags, or change another user's auth\n identity. Mutate them through the permission-gated services (`TenantService`,\n collection helpers) or consumer-owned, permission-checked handlers. A\n structural regression test (`security-audit-1400.test.ts`) enumerates the\n registry to assert no authority model exposes a mutating op. (`cli` stays\n enabled — local-operator surface, outside the network/agent threat model.)\n- **`switchTenant` is fail-closed AND rotates the session id.**\n `SessionService.switchTenant` / `switchSessionTenant` verify the session's user\n has an ACTIVE membership in the target tenant before any write (the tenant id\n is the isolation key for every `@TenantScoped` query). A non-member/unknown-\n session switch returns `{ switched: false, sessionId: null, ... }` and mutates\n nothing. On a successful switch into a NON-null tenant the session id is\n ROTATED: a fresh `Session` (new secure id, fresh TTL, same user, new tenant,\n device context carried over) is minted and the old session is REVOKED — so a\n captured pre-switch id immediately stops validating, shrinking the blast radius\n of a leaked id across a tenant boundary. `switchTenant` returns a\n `SwitchTenantResult` (`{ switched, sessionId, session, rotated }`); callers MUST\n persist the returned `sessionId`. `switchSessionTenant` does this for you by\n re-setting the session cookie (preserving httpOnly/secure/sameSite) to the new\n id. A `null` clear stays in place (no rotation, no cookie change). The\n low-level `SessionCollection.setSessionTenant` is the UNGUARDED primitive (used\n for the null-clear path) — never call it with an untrusted tenant id.\n- **OIDC `email_verified` is enforced.** `UserCollection.getOrCreateFromOidc`\n refuses to provision a user when the IdP explicitly returns\n `email_verified: false` (opt out with `{ allowUnverifiedEmail: true }`). An\n absent claim makes no assertion and is not enforced.\n- **RFC 9207 response issuer is exact.** OIDC callbacks validate a supplied\n `iss` against discovered metadata with exact string comparison before trusting\n a code or error. If metadata advertises issuer-response support, `iss` is\n required.\n- **Verified-email Profile reuse is fail-closed.** The typed canonical scenarios\n live in\n `packages/profiles/src/testing/oidcProvisioningDecisionMatrix.ts`; both\n package suites execute that matrix and public docs reference it rather than\n maintaining another behavioral table. Default provisioning reuses only one\n unowned, global `Person`. Tenant-scoped, non-Person, duplicate-email,\n and already-owned matches fail before User/session creation. An existing\n issuer/subject link without a User must still be the unique global Person for\n the current verified claim email; once owned, the stable issuer/subject link\n reuses its canonical Person and owner.\n Issuer and subject are opaque, case-sensitive identifiers; preserve their\n exact value and use trim only to reject blank claims.\n- **`resolveProfile` is the application reconciliation boundary.** The\n SvelteKit handlers, `OidcLoginService`, and `getOrCreateFromOidc` accept the\n same hook inside the provisioning transaction. The service/handler path\n supplies protocol-validated claims; direct collection callers must validate\n and trust their claim source before calling `getOrCreateFromOidc`.\n Token/userinfo merging keeps `email` and `email_verified` paired to the same\n claim source; verification is never borrowed across sources.\n Resolver reads/writes use the supplied `db`, and the hook must be idempotent\n because a concurrent unique-key conflict can retry it. `undefined` chooses\n the secure default and `null` rejects, including exact issuer/subject reuse.\n For a new identity, a supplied Profile is still validated as the unique,\n unowned global Person for the verified email. For an exact existing identity,\n it must be the already-linked Profile and cannot rebind identity authority;\n stable-link owner and canonical-Person checks still apply. The hook receives a\n separate frozen claims snapshot; internal retry and persistence state is not\n exposed for mutation.\n- **Owned first binding requires `authorizeProfileOwner`.** An invitation or\n approval workflow may explicitly return both its pre-provisioned canonical\n global `Person` and existing approved `User` from this transaction-bound\n hook. `undefined` keeps the secure `profile_owned` default and `null`\n rejects. SMRT treats only the selected IDs as input, reloads them in the\n provisioning transaction, and requires `email_verified === true`, the unique\n canonical global Person for the normalized claim email, exactly one owner,\n that owner as the selected User, and the same normalized User email. The\n hook runs before identity/User/session creation and may be retried, so use\n only its supplied `db` and `users` handles and keep application authorization\n idempotent. Never authorize from email matching alone. Existing exact\n identities cannot be rebound; when `resolveProfile` is also present both\n hooks must select the same Profile.\n- **OIDC first login is atomic.** The Profile, `OidcIdentity`, and User are one\n transaction. The database arbiters are `OidcIdentity.identityKey`,\n private `oidc_profile_email_reservations.email_key`, `User.emailKey`, and the\n unique `User.profileId`; local callbacks acquire exact issuer/subject and normalized\n email locks in deterministic order so changed email claims also serialize.\n SQLite and DuckDB callbacks additionally serialize transactions per database\n URL because one adapter cannot safely overlap unrelated root transactions;\n owner-authorized DuckDB callbacks use that same root-handle serialization;\n PostgreSQL deadlock and serialization errors use a bounded transaction retry.\n Newly provisioned Profiles use non-semantic per-profile slugs so equal IdP\n display names cannot trigger a natural-key upsert;\n run\n `smrt db:status`, `smrt db:migrate`, then `smrt db:status` before deployment.\n Stop or upgrade old writers first. Before migration, group\n non-null `users.profile_id` values, then reconcile duplicates. After\n migration, run public `backfillProfileEmailKeys(db)` followed by\n `backfillUserEmailKeys(db)` from one deploy process. Both use the shared\n TypeScript `normalizeIdentityEmail()` implementation transactionally and are\n idempotent; the User backfill fails before writes if normalized duplicates\n remain. Every OIDC path requires the Profile email-key readiness marker;\n creating a User or checking User email uniqueness additionally requires the\n User marker. A stable issuer/subject with an existing owning User skips only\n the User email-key lookup and marker. Full scans remain in the explicit deploy\n step; guarded runtime paths use indexed keys and validate only returned\n candidates. Multiple null links remain valid.\n Legacy race keys backfill only after canonical validation. Pass a root\n database on adapters such as DuckDB that cannot create nested savepoints.\n Root adapters must expose `beginTransaction`; transaction-only handles are\n ambiguous and fail closed before provisioning writes. Caller-owned\n transactions never run `_smrt_backfills` DDL and require that table to\n already exist; use the root database when initialization or recovery is\n needed.\n\n## Gotchas\n\n- **seedSystemRoles() required**: call `RoleCollection.seedSystemRoles()` at app init (creates owner/admin/member/viewer)\n- **PermissionResolver casts `as any`**: collections have protected constructors — known framework limitation\n- **Session TTL in seconds**: `DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60` (not milliseconds)\n- **Users are cross-tenant**: one user, many tenants via Membership. Email globally unique.\n- **Batch permission queries**: resolver fetches all permission IDs in one query, then maps to slugs (avoids N+1)\n"
|
|
3085
|
+
"agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant user management with RBAC, hierarchical tenants, session handling, and SvelteKit integration.\n\n## Models (14)\n\n| Model | Key Pattern |\n|-------|-------------|\n| User | Auth identity. `profileId` is a unique cross-package reference to smrt-profiles (one User per non-null Profile). Email auto-lowercased; readonly nullable unique `emailKey` is derived on save for durable normalized uniqueness. |\n| AccessRequest | \"Request access / waitlist\" record captured before a `User` exists. CLOSED generated surface (`api`/`mcp`/`cli` = `[]`) — all access via `AccessRequestService`. Email normalized + indexed; JSON `requestContext` (NOT `context` — reserved for slug scoping). |\n| Tenant | **STI** + hierarchical parent-child. `hierarchyPath` (materialized path), `hierarchyLevel`. Max depth 10. |\n| Session | Server-side. Secure UUID. TTL in **seconds** (not ms). Status auto-updates to EXPIRED on access. |\n| MagicLinkToken | Single-use email login token. Backed by `MagicLinkService`. |\n| Role | `tenantId = null` → system role (available to all tenants). `isSystem: true` blocks deletion. `inheritsToDescendants: true` (default false) opts the role's membership authority into descendant tenants. |\n| Permission | Slug format: `resource.action`. Parsed by PermissionResolver. |\n| Membership | User + Tenant + Role junction. UNIQUE(userId, tenantId). |\n| Group | Team within a tenant. Multiple roles via GroupRole. |\n| GroupMember, GroupRole, RolePermission | Join tables. |\n| MembershipOverride | Per-user permission grant/deny. **DENY always wins.** |\n| TenantPermissionOverride | Tenant-level cascade overrides. Effect: INHERIT/GRANT/DENY. |\n\n## Permission Resolution — Precedence (broad → specific, most-specific wins)\n\n`PermissionResolver.resolvePermissions` builds the effective set in this order;\neach later layer overrides earlier ones:\n\n1. **Tenant-inherited** — walk ancestors, apply each `TenantPermissionOverride`\n down the cascade (GRANT adds, DENY removes within the hierarchy)\n2. **Membership role** — base permissions from the user's role in the tenant\n3. **Group roles** — permissions from all groups the user belongs to **in that tenant**\n4. **Tenant-level DENY** *(removes; overrides role/group grants, tenant-wide)* — a\n `TenantPermissionOverride` with effect `DENY` is a HARD, tenant-wide block: it\n subtracts the DENY'd slug even if a role or group granted it (steps 2–3). It\n sits just **above** the per-user membership overrides and **below** role/group.\n5. **Membership GRANT override** *(re-adds; most specific)* — a per-user GRANT can\n re-add a slug a tenant DENY'd in step 4, because it is more specific.\n6. **Membership DENY override** *(absolute; always wins)* — a per-user DENY removes\n the slug last and is never overridden.\n\nSo a permission a role grants but the tenant DENYs is **removed**, unless that\nexact user also has a membership-GRANT override for it. A membership-DENY always\nwins. Tenant-DENY of an inherited/cascade grant still blocks it (unchanged).\nThe hard block reflects the tenant cascade's **net** resolution, not an\nunconditional union of every DENY in the chain — so a more-specific tenant GRANT\n(e.g. a child sub-tenant re-granting a permission its parent DENYs) still wins.\n\n### Membership selection — hierarchical inheritance (opt-in, #1866)\n\nWhich membership feeds step 2 above:\n\n1. **A direct membership row in the target tenant always pins resolution to\n itself** — active rows resolve normally; an inactive (pending/suspended)\n row resolves to the **empty set**. A direct row therefore *attenuates*\n rather than unions: \"viewer here, despite being network admin\" gives\n viewer, and a suspension in the child is effective even for users holding\n inheritable authority on an ancestor.\n2. **No direct row** → the resolver walks the tenant's ancestors (nearest\n first, from `hierarchyPath`) and resolves through the **nearest ACTIVE\n ancestor membership whose role has `inheritsToDescendants: true`**.\n Unflagged or inactive ancestor memberships are skipped (they neither confer\n nor block); there is **no union across the chain** — the nearest flagged\n membership alone is used. To attenuate a specific descendant, create a\n direct membership there or use a tenant-level DENY.\n3. **No qualifying ancestor** → empty set (byte-identical to the\n pre-inheritance resolver; with no role flagged, nothing changes).\n\nAll later layers run unchanged against the **target** tenant: the tenant\ncascade and tenant-DENY hard block come from the target tenant (a child can\ncarve authority out of an inherited role), group roles stay exact-tenant (only\ntarget-tenant groups contribute; ancestor groups never flow down), and\nmembership GRANT/DENY overrides travel with the ancestor membership used.\n`PermissionResolutionResult.inheritedFromTenantId` reports the ancestor tenant\nwhen inheritance was used (`null` for direct resolution).\n\nSafety: resolution is bounded by `MAX_TENANT_HIERARCHY_DEPTH`; malformed\n`hierarchyPath` values fail closed to the empty set — too deep,\nself-referential, duplicate ancestors, or inconsistent with the actual\n`parentTenantId` chain (the path is verified link-by-link against the loaded\nancestor rows before it is trusted as an authorization source). Tenant `status` is not consulted (parity with direct\nresolution). Caching: a long-lived `(user, tenant)` permission cache must also\ninvalidate on ancestor-membership changes and on `Role.inheritsToDescendants`\nflips — request-scoped caches (the common pattern) are unaffected.\n\nFlag roles at seed time with\n`seedSystemRoles({ inheritsToDescendants: ['owner', 'admin'] })` (additive:\nlisted slugs are flagged, omitted slugs are never unflagged; unknown slugs\nthrow). The default seed leaves every role exact-tenant.\n\n## Operation Permission Guards\n\nSMRT derives a fine-grained, per-`<collection>.<action>` permission catalog **from the\nmanifest** (`PermissionCatalogService`, including custom `@smrt` actions — not just CRUD)\nand enforces it two ways: app-side via `assertOperationPermission()` / `PermissionResolver`,\nand at the database via generated **Postgres RLS** policies\n(`generatePostgresPermissionSql()` / `applyPostgresPermissionPolicies()`) that read the\nsession-injected `smrt.permissions` / `smrt.tenant_id` (set by `withSessionPermissionContext`\nvia `set_config`). Because the RLS teeth are at the data layer, enforcement is door-agnostic\n— REST, MCP, and in-process callers are all bounded once the principal's context is set.\nSetup: README → *Manifest-derived permission catalog* and *Postgres RLS enforcement*.\n\n- Use `assertOperationPermission()` for hand-written mutations in SvelteKit form\n actions, custom endpoints, CLI scripts, and jobs. It derives the same\n `<collection>.<action>` slugs as `PermissionCatalogService` (`list`/`get` →\n `read`), requires the slug to exist in the catalog, then resolves permissions\n through `PermissionResolver`.\n- `assertOperationPermission()` throws fail-closed by default. Use\n `{ onDeny: 'return' }`, `checkOperationPermission()`, or\n `hasOperationPermission()` when a structured/boolean result is needed.\n- **Resource-tenant calling convention**: for resource-anchored authorization,\n pass the **resource's** tenant id — `tenantId: resourceTenantId` — not the\n session's current tenant. With `Role.inheritsToDescendants` flagged, a\n root-tenant admin then passes for any descendant resource with no app-side\n authority logic (and no membership fan-out), while per-child delegation and\n DENY precedence keep working. Do NOT pass a session-scoped `membership`\n alongside a different resource `tenantId` — a membership/tenant mismatch\n fails closed by design; omit `membership` and let the resolver look it up.\n- System context and super-admin bypass context are honored for parity with\n Postgres RLS. Pass `{ allowSuperAdminBypass: false }` on money-class or\n separation-of-duties operations that must require an explicit permission grant.\n- **Postgres RLS and membership inheritance**: RLS policies check the\n session-injected `smrt.permissions` list (resolved app-side by\n `PermissionResolver`), so a session whose `smrt.tenant_id` IS the child\n tenant gets inherited authority in RLS automatically. But RLS row filtering\n stays bound to the session's tenant setting — a root-tenant session acting\n on child-tenant rows is authorized by the app-level guard (resource-tenant\n convention above), not by RLS. This is a documented divergence, mirroring\n how #1829 handled bypass parity.\n- Seed role mappings with `RolePermissionCollection.seedRolePermissions()` or\n `RoleCollection.seedSystemRoles({ seedPermissions: true })`. The default\n matrix maps owner/admin to all catalog permissions, member to read/create for\n ordinary app resources, and viewer to read-only. Member create grants\n intentionally exclude users/RBAC authority and security resources (`users`,\n `tenants`, `roles`, `permissions`, memberships, groups, sessions, magic-link\n tokens, and related join/override tables). Re-seeding is additive and\n idempotent; pruning stale mappings requires `{ prune: true }`. When a\n contributing package registers a new built-in self-personalization\n permission after system roles already exist, call the explicit,\n idempotent `RolePermissionCollection.seedDefaultRolePersonalizationPermissions()`\n upgrade helper; it targets owner/admin/member/viewer only and never grants\n custom roles.\n\n**Critical**: `getGroupIdsForTenant(userId, tenantId)` (joins with groups table to scope by tenant). Never use `getGroupIds()` — it's cross-tenant.\n\n## Hierarchical Tenants\n\n- `TenantCollection.createChild()` auto-calculates hierarchy fields, enforces depth limit\n- `moveToParent()` updates tenant + ALL descendants' paths/levels\n- `cascadePermissions` (parent pushes down) + `inheritPermissions` (child accepts) — both must be true\n- `getTree(rootId?)` returns nested structure for UI\n- Two independent downward flows: the `TenantPermissionOverride` **cascade**\n (tenant-level permission config, flags above) and **membership-role\n inheritance** (`Role.inheritsToDescendants`, per-role opt-in — see\n \"Membership selection\" above). The cascade flags do not gate membership\n inheritance.\n\n## SvelteKit Integration\n\n```typescript\n// hooks.server.ts\nexport const handle = createSessionHandler({ db, ttl: 604800, skipPaths: ['/api/public'] });\n// Populates event.locals: { user, membership, permissions: string[], tenantId, sessionId }\n\n// +page.server.ts\nawait createSessionCookie(event, userId, tenantId, { db });\nawait destroySessionCookie(event, { db });\nawait switchSessionTenant(event, tenantId, { db });\n```\n\n## Mobile `/api/mobile` Handlers (ADR 0001 Phase 3.5, #1748)\n\n`createMobileAuthHandlers(options)` (from `/sveltekit`) returns the mountable\nserver side of the KMP mobile contract: `authStart` (`POST auth/start`,\nserver-brokered PKCE via `OidcLoginService`), `authComplete`\n(`POST auth/complete`, code + echoed `state`/`codeVerifier` → bearer\nsession), `session.GET`/`session.DELETE` (bootstrap/logout), and\n`guard`/`withSession` — the bearer middleware for app-owned mobile routes.\nCore logic lives in `MobileAuthService` (framework-agnostic; exported from\nthe package root).\n\n- **Bearer = session id** (same convention as `TerminalAuthService`); 401\n bodies are `{ error, code }` and drive the mobile client's re-auth flow.\n- **Stateless handshake**: the OAuth `state` is an HMAC-signed token\n (secret: `stateSecret` ?? provider `clientSecret`) carrying\n nonce/provider/createdAt — full ID-token nonce verification with no\n server-side pending state. The `codeVerifier` never enters a URL: it is\n client-held per the frozen contract.\n- **Wire DTOs** come from `@happyvertical/smrt-mobile-contract`\n (`MobileAuthStartRequest` etc.) — one owning package for the Kotlin,\n Swift, and TypeScript shapes (compile-checked descriptors + parity test).\n- **Tenant options** honor `Role.inheritsToDescendants` (#1867): direct\n ACTIVE memberships plus descendants of flagged memberships (nearest\n flagged ancestor labels the option; any direct row pins; inactive direct\n rows exclude). Session binding defaults to the first DIRECT tenant —\n override with `resolveTenantId`.\n- **Hooks**: `resolveUser` (invite-gating; default provisions via\n `getOrCreateFromOidc`), `resolveTenantId`, `buildExtras` (bootstrap\n `extras`; model JSON must use `toPublicJSON({ permissions })` — #1822).\n `buildExtras` is the only app-domain bootstrap extension point. Never emit\n app fields such as `dashboard` at the response top level: they are outside\n `MobileSessionBootstrap` and the Kotlin decoder ignores them.\n- **Guard** wraps `withSessionPermissionContext`, so\n `assertOperationPermission`, tenancy context, and Postgres RLS all see the\n bearer caller; `OperationPermissionError` maps to 403 with a\n machine-readable `reason`.\n- **Uploads**: `resolveMobileUploadDedupKey` + the documented contract in\n `docs/content/architecture/mobile-upload-contract.md` (`clientCaptureId`\n field, `Idempotency-Key` header fallback); domain ingestion stays\n app-side. Framework-model writes ride `sync/apply`, not this path.\n- Configure `redirectUris` in production — RFC 8252 scheme rules always\n apply, but the allow list is the defense against redirecting authorization\n responses to attacker-controlled URIs.\n\n## Security (S5 #1400)\n\n- **Generated REST/MCP surface is READ-ONLY for every RBAC/identity model.**\n User, Tenant, Group, Membership, MembershipOverride, Role, Permission,\n RolePermission, GroupRole, GroupMember, and TenantPermissionOverride generate\n `list`/`get` only — `create`/`update`/`delete` are intentionally NOT\n generated. The merged `requireRouteAuth` gate (#1540) enforces *authentication*,\n not *authorization*, and these models are not `@TenantScoped`, so an\n auto-generated mutating route would let any authenticated user self-grant a\n role/permission, flip a tenant's cascade flags, or change another user's auth\n identity. Mutate them through the permission-gated services (`TenantService`,\n collection helpers) or consumer-owned, permission-checked handlers. A\n structural regression test (`security-audit-1400.test.ts`) enumerates the\n registry to assert no authority model exposes a mutating op. (`cli` stays\n enabled — local-operator surface, outside the network/agent threat model.)\n- **`switchTenant` is fail-closed AND rotates the session id.**\n `SessionService.switchTenant` / `switchSessionTenant` verify the session's user\n has an ACTIVE membership in the target tenant before any write (the tenant id\n is the isolation key for every `@TenantScoped` query). A non-member/unknown-\n session switch returns `{ switched: false, sessionId: null, ... }` and mutates\n nothing. On a successful switch into a NON-null tenant the session id is\n ROTATED: a fresh `Session` (new secure id, fresh TTL, same user, new tenant,\n device context carried over) is minted and the old session is REVOKED — so a\n captured pre-switch id immediately stops validating, shrinking the blast radius\n of a leaked id across a tenant boundary. `switchTenant` returns a\n `SwitchTenantResult` (`{ switched, sessionId, session, rotated }`); callers MUST\n persist the returned `sessionId`. `switchSessionTenant` does this for you by\n re-setting the session cookie (preserving httpOnly/secure/sameSite) to the new\n id. A `null` clear stays in place (no rotation, no cookie change). The\n low-level `SessionCollection.setSessionTenant` is the UNGUARDED primitive (used\n for the null-clear path) — never call it with an untrusted tenant id.\n- **OIDC `email_verified` is enforced.** `UserCollection.getOrCreateFromOidc`\n refuses to provision a user when the IdP explicitly returns\n `email_verified: false` (opt out with `{ allowUnverifiedEmail: true }`). An\n absent claim makes no assertion and is not enforced.\n- **RFC 9207 response issuer is exact.** OIDC callbacks validate a supplied\n `iss` against discovered metadata with exact string comparison before trusting\n a code or error. If metadata advertises issuer-response support, `iss` is\n required.\n- **Verified-email Profile reuse is fail-closed.** The typed canonical scenarios\n live in\n `packages/profiles/src/testing/oidcProvisioningDecisionMatrix.ts`; both\n package suites execute that matrix and public docs reference it rather than\n maintaining another behavioral table. Default provisioning reuses only one\n unowned, global `Person`. Tenant-scoped, non-Person, duplicate-email,\n and already-owned matches fail before User/session creation. An existing\n issuer/subject link without a User must still be the unique global Person for\n the current verified claim email; once owned, the stable issuer/subject link\n reuses its canonical Person and owner.\n Issuer and subject are opaque, case-sensitive identifiers; preserve their\n exact value and use trim only to reject blank claims.\n- **`resolveProfile` is the application reconciliation boundary.** The\n SvelteKit handlers, `OidcLoginService`, and `getOrCreateFromOidc` accept the\n same hook inside the provisioning transaction. The service/handler path\n supplies protocol-validated claims; direct collection callers must validate\n and trust their claim source before calling `getOrCreateFromOidc`.\n Token/userinfo merging keeps `email` and `email_verified` paired to the same\n claim source; verification is never borrowed across sources.\n Resolver reads/writes use the supplied `db`, and the hook must be idempotent\n because a concurrent unique-key conflict can retry it. `undefined` chooses\n the secure default and `null` rejects, including exact issuer/subject reuse.\n For a new identity, a supplied Profile is still validated as the unique,\n unowned global Person for the verified email. For an exact existing identity,\n it must be the already-linked Profile and cannot rebind identity authority;\n stable-link owner and canonical-Person checks still apply. The hook receives a\n separate frozen claims snapshot; internal retry and persistence state is not\n exposed for mutation.\n- **Owned first binding requires `authorizeProfileOwner`.** An invitation or\n approval workflow may explicitly return both its pre-provisioned canonical\n global `Person` and existing approved `User` from this transaction-bound\n hook. `undefined` keeps the secure `profile_owned` default and `null`\n rejects. SMRT treats only the selected IDs as input, reloads them in the\n provisioning transaction, and requires `email_verified === true`, the unique\n canonical global Person for the normalized claim email, exactly one owner,\n that owner as the selected User, and the same normalized User email. The\n hook runs before identity/User/session creation and may be retried, so use\n only its supplied `db` and `users` handles and keep application authorization\n idempotent. Never authorize from email matching alone. Existing exact\n identities cannot be rebound; when `resolveProfile` is also present both\n hooks must select the same Profile.\n- **OIDC first login is atomic.** The Profile, `OidcIdentity`, and User are one\n transaction. The database arbiters are `OidcIdentity.identityKey`,\n private `oidc_profile_email_reservations.email_key`, `User.emailKey`, and the\n unique `User.profileId`; local callbacks acquire exact issuer/subject and normalized\n email locks in deterministic order so changed email claims also serialize.\n SQLite and DuckDB callbacks additionally serialize transactions per database\n URL because one adapter cannot safely overlap unrelated root transactions;\n owner-authorized DuckDB callbacks use that same root-handle serialization;\n PostgreSQL deadlock and serialization errors use a bounded transaction retry.\n Newly provisioned Profiles use non-semantic per-profile slugs so equal IdP\n display names cannot trigger a natural-key upsert;\n run\n `smrt db:status`, `smrt db:migrate`, then `smrt db:status` before deployment.\n Stop or upgrade old writers first. Before migration, group\n non-null `users.profile_id` values, then reconcile duplicates. After\n migration, run public `backfillProfileEmailKeys(db)` followed by\n `backfillUserEmailKeys(db)` from one deploy process. Both use the shared\n TypeScript `normalizeIdentityEmail()` implementation transactionally and are\n idempotent; the User backfill fails before writes if normalized duplicates\n remain. Every OIDC path requires the Profile email-key readiness marker;\n creating a User or checking User email uniqueness additionally requires the\n User marker. A stable issuer/subject with an existing owning User skips only\n the User email-key lookup and marker. Full scans remain in the explicit deploy\n step; guarded runtime paths use indexed keys and validate only returned\n candidates. Multiple null links remain valid.\n Legacy race keys backfill only after canonical validation. Pass a root\n database on adapters such as DuckDB that cannot create nested savepoints.\n Root adapters must expose `beginTransaction`; transaction-only handles are\n ambiguous and fail closed before provisioning writes. Caller-owned\n transactions never run `_smrt_backfills` DDL and require that table to\n already exist; use the root database when initialization or recovery is\n needed.\n\n## Gotchas\n\n- **seedSystemRoles() required**: call `RoleCollection.seedSystemRoles()` at app init (creates owner/admin/member/viewer)\n- **PermissionResolver casts `as any`**: collections have protected constructors — known framework limitation\n- **Session TTL in seconds**: `DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60` (not milliseconds)\n- **Users are cross-tenant**: one user, many tenants via Membership. Email globally unique.\n- **Batch permission queries**: resolver fetches all permission IDs in one query, then maps to slugs (avoids N+1)\n"
|
|
3084
3086
|
}
|
package/dist/sveltekit.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as decodeOidcTransaction, E as resolveOidcProviderConfig, S as OidcLoginService, T as getUsersOidcConfig, _ as readMobileBearerToken, a as TerminalAuthRateLimitError, g as MobileAuthService, h as MobileAuthError, i as TerminalAuthError, m as withSessionPermissionContext, o as TerminalAuthService, s as OperationPermissionError, v as validateMobileRedirectUri, w as encodeOidcTransaction, x as OidcLoginError, y as SessionService } from "./chunks/TerminalAuthService-
|
|
1
|
+
import { C as decodeOidcTransaction, E as resolveOidcProviderConfig, S as OidcLoginService, T as getUsersOidcConfig, _ as readMobileBearerToken, a as TerminalAuthRateLimitError, g as MobileAuthService, h as MobileAuthError, i as TerminalAuthError, m as withSessionPermissionContext, o as TerminalAuthService, s as OperationPermissionError, v as validateMobileRedirectUri, w as encodeOidcTransaction, x as OidcLoginError, y as SessionService } from "./chunks/TerminalAuthService-h7XBwJLh.js";
|
|
2
2
|
import { DiscoveryArtifactValidationError, SMRT_APP_RESULT_CONTRACT, SMRT_APP_RESULT_SCHEMA, SMRT_APP_RESULT_VERSION, SMRT_DISCOVERY_CONFORMANCE_ARTIFACT_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_VERSION, SMRT_MCP_RESULT_METADATA_KEY, canonicalizeDiscoveryArtifact, createDiscoveryConformanceArtifact, deriveCommandRequirements, validateDiscoveryConformanceArtifact } from "./app-contract.js";
|
|
3
3
|
import { ObjectRegistry } from "@happyvertical/smrt-core";
|
|
4
4
|
import { createLogger } from "@happyvertical/logger";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-users",
|
|
3
|
-
"version": "0.40.
|
|
3
|
+
"version": "0.40.61",
|
|
4
4
|
"description": "Multi-tenant user management for the SMRT framework - users, tenants, roles, permissions, groups",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"smrtRawPrimitives": "strict",
|
|
@@ -48,13 +48,13 @@
|
|
|
48
48
|
"@happyvertical/logger": "^0.85.5",
|
|
49
49
|
"@happyvertical/sql": "^0.85.5",
|
|
50
50
|
"jose": "^6.2.3",
|
|
51
|
-
"@happyvertical/smrt-config": "0.40.
|
|
52
|
-
"@happyvertical/smrt-core": "0.40.
|
|
53
|
-
"@happyvertical/smrt-
|
|
54
|
-
"@happyvertical/smrt-
|
|
55
|
-
"@happyvertical/smrt-
|
|
56
|
-
"@happyvertical/smrt-types": "0.40.
|
|
57
|
-
"@happyvertical/smrt-ui": "0.40.
|
|
51
|
+
"@happyvertical/smrt-config": "0.40.61",
|
|
52
|
+
"@happyvertical/smrt-core": "0.40.61",
|
|
53
|
+
"@happyvertical/smrt-mobile-contract": "0.40.61",
|
|
54
|
+
"@happyvertical/smrt-profiles": "0.40.61",
|
|
55
|
+
"@happyvertical/smrt-tenancy": "0.40.61",
|
|
56
|
+
"@happyvertical/smrt-types": "0.40.61",
|
|
57
|
+
"@happyvertical/smrt-ui": "0.40.61"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@sveltejs/package": "^2.5.8",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
"typescript": "5.9.3",
|
|
67
67
|
"vite": "8.1.4",
|
|
68
68
|
"vitest": "4.1.10",
|
|
69
|
-
"@happyvertical/smrt-vitest": "0.40.
|
|
69
|
+
"@happyvertical/smrt-vitest": "0.40.61"
|
|
70
70
|
},
|
|
71
71
|
"keywords": [
|
|
72
72
|
"smrt",
|