@happyvertical/smrt-users 0.69.0 → 0.70.1

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.
Files changed (43) hide show
  1. package/README.md +7 -0
  2. package/agents/oauth-authorization.md +13 -3
  3. package/agents/permissions.md +17 -0
  4. package/dist/chunks/{PasswordCredentialService-Dec3bz4G.js → PasswordCredentialService-BjobA5uG.js} +22 -731
  5. package/dist/chunks/PasswordCredentialService-BjobA5uG.js.map +1 -0
  6. package/dist/chunks/PermissionCatalogService-DcmTn38P.js +716 -0
  7. package/dist/chunks/PermissionCatalogService-DcmTn38P.js.map +1 -0
  8. package/dist/chunks/PostgresPermissionPolicies-RzCLuARk.js +314 -0
  9. package/dist/chunks/PostgresPermissionPolicies-RzCLuARk.js.map +1 -0
  10. package/dist/chunks/{TerminalAuthService-Bf90h-rh.js → TerminalAuthService-CIdx-ed9.js} +48 -30
  11. package/dist/chunks/TerminalAuthService-CIdx-ed9.js.map +1 -0
  12. package/dist/index.d.ts +2 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +43 -289
  15. package/dist/index.js.map +1 -1
  16. package/dist/manifest.json +1 -1
  17. package/dist/operator.js +1 -1
  18. package/dist/postgres-policies.d.ts +8 -0
  19. package/dist/postgres-policies.d.ts.map +1 -0
  20. package/dist/postgres-policies.js +2 -0
  21. package/dist/postgres-settings.d.ts +26 -0
  22. package/dist/postgres-settings.d.ts.map +1 -0
  23. package/dist/postgres-settings.js +18 -0
  24. package/dist/postgres-settings.js.map +1 -0
  25. package/dist/services/OAuthAuthorizationService.d.ts +27 -1
  26. package/dist/services/OAuthAuthorizationService.d.ts.map +1 -1
  27. package/dist/services/OperationPermissionService.d.ts +7 -2
  28. package/dist/services/OperationPermissionService.d.ts.map +1 -1
  29. package/dist/services/PostgresPermissionPolicies.d.ts +40 -1
  30. package/dist/services/PostgresPermissionPolicies.d.ts.map +1 -1
  31. package/dist/services/SessionPermissionContext.d.ts +2 -8
  32. package/dist/services/SessionPermissionContext.d.ts.map +1 -1
  33. package/dist/services/index.d.ts +2 -2
  34. package/dist/services/index.d.ts.map +1 -1
  35. package/dist/smrt-knowledge.json +9 -7
  36. package/dist/smrt-knowledge.okf.md +4 -2
  37. package/dist/sveltekit/oauth-handlers.d.ts +1 -1
  38. package/dist/sveltekit/oauth-handlers.d.ts.map +1 -1
  39. package/dist/sveltekit.js +10 -4
  40. package/dist/sveltekit.js.map +1 -1
  41. package/package.json +17 -9
  42. package/dist/chunks/PasswordCredentialService-Dec3bz4G.js.map +0 -1
  43. package/dist/chunks/TerminalAuthService-Bf90h-rh.js.map +0 -1
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-users",
5
- "packageVersion": "0.69.0",
5
+ "packageVersion": "0.70.1",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-users:AccessRequestCollection": {
8
8
  "name": "accessrequestcollection",
package/dist/operator.js CHANGED
@@ -1,4 +1,4 @@
1
- import { At as normalizeEmail, I as UserCollection, P as verifySecretHash, U as TenantCollection, _ as PermissionResolver, ct as UsersPasswordCredentialCollection, f as PasswordCredentialService, ft as MembershipCollection, jt as normalizeUsername, kt as isValidEmail, ot as RoleCollection } from "./chunks/PasswordCredentialService-Dec3bz4G.js";
1
+ import { Ct as normalizeEmail, I as UserCollection, P as verifySecretHash, St as isValidEmail, U as TenantCollection, _ as PermissionResolver, at as MembershipCollection, et as RoleCollection, f as PasswordCredentialService, tt as UsersPasswordCredentialCollection, wt as normalizeUsername } from "./chunks/PasswordCredentialService-BjobA5uG.js";
2
2
  import { a as MembershipStatus, l as TenantStatus, u as UserStatus } from "./chunks/types-DqUZxluX.js";
3
3
  import { isPostgresDatabase, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
4
4
  import { withSystemContext } from "@happyvertical/smrt-tenancy";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Postgres policy generation, without the rest of the package. A host that
3
+ * keeps run-time models in an app schema loads this subpath to generate and
4
+ * apply their row-level-security policies.
5
+ * @packageDocumentation
6
+ */
7
+ export { applyScopedPostgresPermissionPolicies, type GeneratePostgresPermissionSqlResult, generatePostgresPermissionSql, type PostgresPolicyScope, } from './services/PostgresPermissionPolicies.js';
8
+ //# sourceMappingURL=postgres-policies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-policies.d.ts","sourceRoot":"","sources":["../src/postgres-policies.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,qCAAqC,EACrC,KAAK,mCAAmC,EACxC,6BAA6B,EAC7B,KAAK,mBAAmB,GACzB,MAAM,0CAA0C,CAAC"}
@@ -0,0 +1,2 @@
1
+ import { n as applyScopedPostgresPermissionPolicies, r as generatePostgresPermissionSql } from "./chunks/PostgresPermissionPolicies-RzCLuARk.js";
2
+ export { applyScopedPostgresPermissionPolicies, generatePostgresPermissionSql };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The six transaction-local `smrt.*` settings a PostgreSQL row-level-security
3
+ * policy reads. Pure and dependency-free so a host that owns the connection
4
+ * (a broker, a pool) can write them without loading the rest of the package.
5
+ * Callers bind them with `set_config(name, value, true)`.
6
+ * @packageDocumentation
7
+ */
8
+ /** What the settings are derived from. */
9
+ export interface PostgresPrincipalSettingsInput {
10
+ tenantId: string | null;
11
+ userId: string | null;
12
+ /** A loaded session; only then is its id published. */
13
+ session: unknown | null;
14
+ sessionId: string | null;
15
+ permissions: readonly string[];
16
+ superAdminBypass: boolean;
17
+ systemContext: boolean;
18
+ }
19
+ /**
20
+ * Value published to `smrt.session_id`. Only a session that was actually
21
+ * loaded is published; an unverified label keeps it empty (fail closed).
22
+ */
23
+ export declare function resolvePostgresSessionIdValue(context: Pick<PostgresPrincipalSettingsInput, 'session' | 'sessionId'>): string;
24
+ /** `[name, value]` for each of the six `smrt.*` settings, in a fixed order. */
25
+ export declare function postgresPrincipalSettings(context: PostgresPrincipalSettingsInput): Array<[string, string]>;
26
+ //# sourceMappingURL=postgres-settings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-settings.d.ts","sourceRoot":"","sources":["../src/postgres-settings.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,0CAA0C;AAC1C,MAAM,WAAW,8BAA8B;IAC7C,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,uDAAuD;IACvD,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IACxB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,WAAW,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,gBAAgB,EAAE,OAAO,CAAC;IAC1B,aAAa,EAAE,OAAO,CAAC;CACxB;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,IAAI,CAAC,8BAA8B,EAAE,SAAS,GAAG,WAAW,CAAC,GACrE,MAAM,CAER;AAED,+EAA+E;AAC/E,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,8BAA8B,GACtC,KAAK,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CASzB"}
@@ -0,0 +1,18 @@
1
+ //#region src/postgres-settings.ts
2
+ function resolvePostgresSessionIdValue(context) {
3
+ return context.session ? context.sessionId ?? "" : "";
4
+ }
5
+ function postgresPrincipalSettings(context) {
6
+ return [
7
+ ["smrt.tenant_id", context.tenantId ?? ""],
8
+ ["smrt.user_id", context.userId ?? ""],
9
+ ["smrt.session_id", resolvePostgresSessionIdValue(context)],
10
+ ["smrt.permissions", JSON.stringify(context.permissions)],
11
+ ["smrt.super_admin_bypass", context.superAdminBypass ? "true" : "false"],
12
+ ["smrt.system_context", context.systemContext ? "true" : "false"]
13
+ ];
14
+ }
15
+ //#endregion
16
+ export { postgresPrincipalSettings, resolvePostgresSessionIdValue };
17
+
18
+ //# sourceMappingURL=postgres-settings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-settings.js","names":[],"sources":["../src/postgres-settings.ts"],"sourcesContent":["/**\n * The six transaction-local `smrt.*` settings a PostgreSQL row-level-security\n * policy reads. Pure and dependency-free so a host that owns the connection\n * (a broker, a pool) can write them without loading the rest of the package.\n * Callers bind them with `set_config(name, value, true)`.\n * @packageDocumentation\n */\n\n/** What the settings are derived from. */\nexport interface PostgresPrincipalSettingsInput {\n tenantId: string | null;\n userId: string | null;\n /** A loaded session; only then is its id published. */\n session: unknown | null;\n sessionId: string | null;\n permissions: readonly string[];\n superAdminBypass: boolean;\n systemContext: boolean;\n}\n\n/**\n * Value published to `smrt.session_id`. Only a session that was actually\n * loaded is published; an unverified label keeps it empty (fail closed).\n */\nexport function resolvePostgresSessionIdValue(\n context: Pick<PostgresPrincipalSettingsInput, 'session' | 'sessionId'>,\n): string {\n return context.session ? (context.sessionId ?? '') : '';\n}\n\n/** `[name, value]` for each of the six `smrt.*` settings, in a fixed order. */\nexport function postgresPrincipalSettings(\n context: PostgresPrincipalSettingsInput,\n): Array<[string, string]> {\n return [\n ['smrt.tenant_id', context.tenantId ?? ''],\n ['smrt.user_id', context.userId ?? ''],\n ['smrt.session_id', resolvePostgresSessionIdValue(context)],\n ['smrt.permissions', JSON.stringify(context.permissions)],\n ['smrt.super_admin_bypass', context.superAdminBypass ? 'true' : 'false'],\n ['smrt.system_context', context.systemContext ? 'true' : 'false'],\n ];\n}\n"],"mappings":";AAwBO,SAAS,8BACd,SACQ;CACR,OAAO,QAAQ,UAAW,QAAQ,aAAa,KAAM;AACvD;AAGO,SAAS,0BACd,SACyB;CACzB,OAAO;EACL,CAAC,kBAAkB,QAAQ,YAAY,EAAE;EACzC,CAAC,gBAAgB,QAAQ,UAAU,EAAE;EACrC,CAAC,mBAAmB,8BAA8B,OAAO,CAAC;EAC1D,CAAC,oBAAoB,KAAK,UAAU,QAAQ,WAAW,CAAC;EACxD,CAAC,2BAA2B,QAAQ,mBAAmB,SAAS,OAAO;EACvE,CAAC,uBAAuB,QAAQ,gBAAgB,SAAS,OAAO;CAClE;AACF"}
@@ -6,6 +6,18 @@ import { type SessionContext } from './SessionService.js';
6
6
  /** Every scope needs an explicit permission mapping; empty mappings allow any live session. */
7
7
  export interface SmrtOAuthAuthorizationServiceOptions extends SmrtClassOptions {
8
8
  scopePermissions: Readonly<Record<string, readonly string[]>>;
9
+ /**
10
+ * Default `false`: consent grants the requested scopes the user holds
11
+ * (requested ∩ held) and refuses only when none remain. `true` restores
12
+ * all-or-nothing consent: a request for any scope the user cannot hold is
13
+ * refused with `access_denied`.
14
+ */
15
+ refuseUnheldScopes?: boolean;
16
+ }
17
+ /** What consent would grant for a request: the requested scopes the user holds. */
18
+ export interface SmrtOAuthConsentScopes {
19
+ requested: string[];
20
+ granted: string[];
9
21
  }
10
22
  /** Safe account-settings projection; excludes session credentials and token hashes. */
11
23
  export interface SmrtOAuthGrantSummary {
@@ -36,7 +48,21 @@ export declare class SmrtOAuthAuthorizationService {
36
48
  };
37
49
  private liveSession;
38
50
  private permits;
39
- /** Call only after an explicit user consent action; the session is loaded again. */
51
+ /**
52
+ * Requested scopes the session may be granted: those whose mapped permissions
53
+ * it holds (unmapped scopes never), or all-or-nothing with `refuseUnheldScopes`.
54
+ */
55
+ private grantable;
56
+ /**
57
+ * The scopes consent would grant, for the host's consent screen. Throws
58
+ * `access_denied` for a dead session or when nothing can be granted.
59
+ */
60
+ consentScopes(request: OAuthAuthorizationRequest, sessionId: string): Promise<SmrtOAuthConsentScopes>;
61
+ /**
62
+ * Call only after an explicit user consent action; the session is loaded
63
+ * again. Grants requested ∩ held, so the stored grant, the code, the tokens
64
+ * and the token response `scope` (RFC 6749 §3.3) carry only the narrowed set.
65
+ */
40
66
  approve(server: OAuthAuthorizationServer, request: OAuthAuthorizationRequest, sessionId: string): Promise<import("@happyvertical/auth/server").OAuthAuthorizationRedirect>;
41
67
  private resolve;
42
68
  private revalidateConsent;
@@ -1 +1 @@
1
- {"version":3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GG;IACH,OAAO,CAAC,SAAS;IASjB;;;OAGG;IACG,aAAa,CACjB,OAAO,EAAE,yBAAyB,EAClC,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,sBAAsB,CAAC;IASlC;;;;OAIG;IACG,OAAO,CACX,MAAM,EAAE,wBAAwB,EAChC,OAAO,EAAE,yBAAyB,EAClC,SAAS,EAAE,MAAM;YAgCL,OAAO;YAiDP,iBAAiB;IAwB/B,6FAA6F;IACvF,yBAAyB,CAC7B,OAAO,EAAE,UAAU,GAClB,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IAWjC,qEAAqE;IAC/D,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC;IAiBrE,0EAA0E;IACpE,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;YAMzD,WAAW;IAmCzB,OAAO,CAAC,OAAO;CAWhB"}
@@ -2,10 +2,15 @@
2
2
  * Reusable operation-level permission guard for hand-written server surfaces.
3
3
  * @packageDocumentation
4
4
  */
5
- import type { SmrtClassOptions } from '@happyvertical/smrt-core';
5
+ import { type SmrtClassOptions } from '@happyvertical/smrt-core';
6
6
  import { type OperationPermissionCollectionInput, type PermissionCatalog } from './PermissionCatalogService.js';
7
7
  import { type PermissionResolutionOptions, PermissionResolver } from './PermissionResolver.js';
8
- export type OperationPermissionDenyReason = 'invalid_operation' | 'missing_principal' | 'resolution_error' | 'unknown_permission' | 'permission_denied';
8
+ export type OperationPermissionDenyReason = 'invalid_operation' | 'missing_principal' | 'resolution_error' | 'unknown_permission' | 'permission_denied'
9
+ /**
10
+ * Inside a transaction-scoped REST request (#5195), a check for a user or
11
+ * tenant other than the request's principal.
12
+ */
13
+ | 'subject_mismatch';
9
14
  export type OperationPermissionAllowReason = 'permission_granted' | 'super_admin_bypass' | 'system_context_bypass';
10
15
  export interface OperationPermissionDecision {
11
16
  allowed: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"OperationPermissionService.d.ts","sourceRoot":"","sources":["../../src/services/OperationPermissionService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAEL,KAAK,kCAAkC,EACvC,KAAK,iBAAiB,EAEvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,KAAK,2BAA2B,EAChC,kBAAkB,EACnB,MAAM,yBAAyB,CAAC;AAGjC,MAAM,MAAM,6BAA6B,GACrC,mBAAmB,GACnB,mBAAmB,GACnB,kBAAkB,GAClB,oBAAoB,GACpB,mBAAmB,CAAC;AAExB,MAAM,MAAM,8BAA8B,GACtC,oBAAoB,GACpB,oBAAoB,GACpB,uBAAuB,CAAC;AAE5B,MAAM,WAAW,2BAA2B;IAC1C,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,MAAM,EAAE,8BAA8B,GAAG,6BAA6B,CAAC;IACvE,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,0BACf,SAAQ,gBAAgB,EACtB,2BAA2B;IAC7B;;OAEG;IACH,UAAU,EAAE,kCAAkC,CAAC;IAC/C;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;OAEG;IACH,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B,MAAM,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;IAC5B,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB;;;;;;;;OAQG;IACH,aAAa,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,MAAM,EAAE,CAAC;CACzD;AAED,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,QAAQ,CAAC,QAAQ,EAAE,2BAA2B,CAAC;IAC/C,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,QAAQ,CAAC,MAAM,OAAO;gBAEV,QAAQ,EAAE,2BAA2B;CAUlD;AAmED,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,2BAA2B,CAAC,CA0FtC;AAED,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,OAAO,CAAC,CAElB;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,2BAA2B,CAAC,CAOtC"}
1
+ {"version":3,"file":"OperationPermissionService.d.ts","sourceRoot":"","sources":["../../src/services/OperationPermissionService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAGL,KAAK,gBAAgB,EACtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAEL,KAAK,kCAAkC,EACvC,KAAK,iBAAiB,EAEvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,KAAK,2BAA2B,EAChC,kBAAkB,EACnB,MAAM,yBAAyB,CAAC;AAGjC,MAAM,MAAM,6BAA6B,GACrC,mBAAmB,GACnB,mBAAmB,GACnB,kBAAkB,GAClB,oBAAoB,GACpB,mBAAmB;AACrB;;;GAGG;GACD,kBAAkB,CAAC;AAEvB,MAAM,MAAM,8BAA8B,GACtC,oBAAoB,GACpB,oBAAoB,GACpB,uBAAuB,CAAC;AAE5B,MAAM,WAAW,2BAA2B;IAC1C,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,MAAM,EAAE,8BAA8B,GAAG,6BAA6B,CAAC;IACvE,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,0BACf,SAAQ,gBAAgB,EACtB,2BAA2B;IAC7B;;OAEG;IACH,UAAU,EAAE,kCAAkC,CAAC;IAC/C;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;OAEG;IACH,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B,MAAM,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;IAC5B,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB;;;;;;;;OAQG;IACH,aAAa,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,MAAM,EAAE,CAAC;CACzD;AAED,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,QAAQ,CAAC,QAAQ,EAAE,2BAA2B,CAAC;IAC/C,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,QAAQ,CAAC,MAAM,OAAO;gBAEV,QAAQ,EAAE,2BAA2B;CAUlD;AAmED,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,2BAA2B,CAAC,CAkGtC;AA+DD,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,OAAO,CAAC,CAElB;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,2BAA2B,CAAC,CAOtC"}
@@ -4,6 +4,36 @@
4
4
  */
5
5
  import { type SmrtClassOptions } from '@happyvertical/smrt-core';
6
6
  import { type PostgresPermissionAction, type PostgresPermissionBinding } from './PermissionCatalogService.js';
7
+ /**
8
+ * Narrows policy generation to one application schema, for a host that holds
9
+ * a registry of run-time models (an app's tables are addressed unqualified
10
+ * through a transaction-local `search_path`).
11
+ *
12
+ * With a scope the generator never falls back to `public`: every table is
13
+ * addressed in `schemaName`, the `smrt_*` helper functions are created there
14
+ * (policies call them unqualified, through that same `search_path`, so a
15
+ * schema copied or renamed whole keeps its own helpers), only the registered classes
16
+ * `includeClass` accepts get policies, and explicit catalog or config bindings
17
+ * (which name tables of the deployment's own schema) are not applied.
18
+ */
19
+ export interface PostgresPolicyScope {
20
+ /** The schema the scoped tables and helper functions live in. */
21
+ schemaName: string;
22
+ /** Which registered classes get policies (default: none). */
23
+ includeClass: (info: {
24
+ className: string;
25
+ qualifiedName?: string;
26
+ }) => boolean;
27
+ /**
28
+ * The permission slugs that allow each action on a table, for a host whose
29
+ * slugs are not the `<collection>.read|create|update|delete` default.
30
+ */
31
+ permissionsFor?: (info: {
32
+ className: string;
33
+ collection: string;
34
+ tableName: string;
35
+ }) => Partial<Record<PostgresPermissionAction, string[]>> | undefined;
36
+ }
7
37
  export interface PostgresPermissionPolicyReportItem {
8
38
  className?: string;
9
39
  collection?: string;
@@ -28,6 +58,15 @@ export interface GeneratePostgresPermissionSqlResult {
28
58
  statements: string[];
29
59
  targets: PostgresPermissionPolicyTarget[];
30
60
  }
31
- export declare function generatePostgresPermissionSql(options?: SmrtClassOptions): GeneratePostgresPermissionSqlResult;
61
+ export declare function generatePostgresPermissionSql(options?: SmrtClassOptions, scope?: PostgresPolicyScope): GeneratePostgresPermissionSqlResult;
32
62
  export declare function applyPostgresPermissionPolicies(options?: SmrtClassOptions): Promise<GeneratePostgresPermissionSqlResult>;
63
+ /**
64
+ * Apply the policies of one scoped schema through a handle the caller already
65
+ * holds, so they commit or roll back with the caller's own DDL (an app's
66
+ * tables are created in the same transaction). The scope is required: nothing
67
+ * here falls back to `public`. The handle must be a PostgreSQL one.
68
+ */
69
+ export declare function applyScopedPostgresPermissionPolicies(db: {
70
+ query: (sql: string, ...params: unknown[]) => Promise<unknown>;
71
+ }, scope: PostgresPolicyScope, options?: SmrtClassOptions): Promise<GeneratePostgresPermissionSqlResult>;
33
72
  //# sourceMappingURL=PostgresPermissionPolicies.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"PostgresPermissionPolicies.d.ts","sourceRoot":"","sources":["../../src/services/PostgresPermissionPolicies.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAGL,KAAK,gBAAgB,EACtB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAEL,KAAK,wBAAwB,EAC7B,KAAK,yBAAyB,EAC/B,MAAM,+BAA+B,CAAC;AAmBvC,MAAM,WAAW,kCAAkC;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,8BAA8B;IAC7C,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,wBAAwB,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,mCAAmC;IAClD,QAAQ,EAAE,yBAAyB,EAAE,CAAC;IACtC,OAAO,EAAE,kCAAkC,EAAE,CAAC;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,EAAE,8BAA8B,EAAE,CAAC;CAC3C;AAuQD,wBAAgB,6BAA6B,CAC3C,OAAO,GAAE,gBAAqB,GAC7B,mCAAmC,CAgOrC;AAED,wBAAsB,+BAA+B,CACnD,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,mCAAmC,CAAC,CA0B9C"}
1
+ {"version":3,"file":"PostgresPermissionPolicies.d.ts","sourceRoot":"","sources":["../../src/services/PostgresPermissionPolicies.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAGL,KAAK,gBAAgB,EACtB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAEL,KAAK,wBAAwB,EAC7B,KAAK,yBAAyB,EAC/B,MAAM,+BAA+B,CAAC;AASvC;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,mBAAmB;IAClC,iEAAiE;IACjE,UAAU,EAAE,MAAM,CAAC;IACnB,6DAA6D;IAC7D,YAAY,EAAE,CAAC,IAAI,EAAE;QACnB,SAAS,EAAE,MAAM,CAAC;QAClB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,KAAK,OAAO,CAAC;IACd;;;OAGG;IACH,cAAc,CAAC,EAAE,CAAC,IAAI,EAAE;QACtB,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;QACnB,SAAS,EAAE,MAAM,CAAC;KACnB,KAAK,OAAO,CAAC,MAAM,CAAC,wBAAwB,EAAE,MAAM,EAAE,CAAC,CAAC,GAAG,SAAS,CAAC;CACvE;AAYD,MAAM,WAAW,kCAAkC;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,8BAA8B;IAC7C,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,wBAAwB,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,mCAAmC;IAClD,QAAQ,EAAE,yBAAyB,EAAE,CAAC;IACtC,OAAO,EAAE,kCAAkC,EAAE,CAAC;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,EAAE,8BAA8B,EAAE,CAAC;CAC3C;AAiTD,wBAAgB,6BAA6B,CAC3C,OAAO,GAAE,gBAAqB,EAC9B,KAAK,CAAC,EAAE,mBAAmB,GAC1B,mCAAmC,CAuOrC;AAED,wBAAsB,+BAA+B,CACnD,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,mCAAmC,CAAC,CA0B9C;AAED;;;;;GAKG;AACH,wBAAsB,qCAAqC,CACzD,EAAE,EAAE;IAAE,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;CAAE,EACtE,KAAK,EAAE,mBAAmB,EAC1B,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,mCAAmC,CAAC,CAa9C"}
@@ -5,6 +5,7 @@
5
5
  import type { SmrtClassOptions } from '@happyvertical/smrt-core';
6
6
  import type { DatabaseInterface } from '@happyvertical/sql';
7
7
  import type { Membership } from '../models/Membership.js';
8
+ import { resolvePostgresSessionIdValue } from '../postgres-settings.js';
8
9
  import { PermissionResolver } from './PermissionResolver.js';
9
10
  import { type SessionContext, SessionService } from './SessionService.js';
10
11
  interface QueryableDatabase extends DatabaseInterface {
@@ -87,13 +88,7 @@ declare global {
87
88
  }
88
89
  export declare function getCurrentSessionPermissionContext(): SessionPermissionRuntimeContext | undefined;
89
90
  export declare function getRequestScopedDatabase(): QueryableDatabase | undefined;
90
- /**
91
- * Value published to the `smrt.session_id` RLS GUC. Only a session that was
92
- * actually loaded (`context.session` non-null) is published; a principal run's
93
- * `sessionId` is an unverified server-set label and keeps the GUC empty
94
- * (fail closed).
95
- */
96
- export declare function resolvePostgresSessionIdValue(context: Pick<SessionPermissionRuntimeContext, 'session' | 'sessionId'>): string;
91
+ export { resolvePostgresSessionIdValue };
97
92
  export declare function withSessionPermissionContext<T>(options: SessionPermissionRuntimeOptions, fn: (context: SessionPermissionRuntimeContext) => Promise<T>): Promise<T>;
98
93
  /**
99
94
  * Run `fn` AS a bound principal — a `(userId, tenantId)` pair rather than a
@@ -120,5 +115,4 @@ export declare function withSessionPermissionContext<T>(options: SessionPermissi
120
115
  * `assertOperationPermission`).
121
116
  */
122
117
  export declare function withPrincipalPermissionContext<T>(options: PrincipalPermissionRuntimeOptions, fn: (context: SessionPermissionRuntimeContext) => Promise<T>): Promise<T>;
123
- export {};
124
118
  //# sourceMappingURL=SessionPermissionContext.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"SessionPermissionContext.d.ts","sourceRoot":"","sources":["../../src/services/SessionPermissionContext.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EACL,KAAK,cAAc,EACnB,cAAc,EAEf,MAAM,qBAAqB,CAAC;AAE7B,UAAU,iBAAkB,SAAQ,iBAAiB;IACnD,gBAAgB,CAAC,EAAE,MAAM,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACtD,GAAG,EAAE,MAAM,CAAC;CACb;AAED,UAAU,mBAAoB,SAAQ,iBAAiB;IACrD,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IA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CAAC,CAAC,GAC3D,OAAO,CAAC,CAAC,CAAC,CAwEZ"}
@@ -9,7 +9,7 @@ export { DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS, DEFAULT_LOGIN_LOCKOUT_BASE_SECOND
9
9
  export { MagicLinkError, type MagicLinkResult, MagicLinkService, type MagicLinkServiceOptions, type MagicLinkStepUpRequest, type MagicLinkStepUpResult, type MagicLinkVerifyResult, } from './MagicLinkService.js';
10
10
  export { type AuthenticatedMailbox, type MailboxAuthenticationDelivery, type MailboxAuthenticationRequestScope, MailboxAuthenticationService, type MailboxAuthenticationServiceOptions, type MailboxRequestReservation, reserveMailboxAuthenticationRequest, } from './MailboxAuthenticationService.js';
11
11
  export { MobileAuthError, type MobileAuthErrorCode, MobileAuthService, type MobileAuthServiceOptions, type MobileBootstrapContext, type MobileLoginContext, type MobileLogoutResult, type MobileRequestMeta, type MobileResolvedUser, type MobileTenantContext, readMobileBearerToken, validateMobileRedirectUri, } from './MobileAuthService.js';
12
- export { SmrtOAuthAuthorizationService, type SmrtOAuthAuthorizationServiceOptions, type SmrtOAuthGrantSummary, } from './OAuthAuthorizationService.js';
12
+ export { SmrtOAuthAuthorizationService, type SmrtOAuthAuthorizationServiceOptions, type SmrtOAuthConsentScopes, type SmrtOAuthGrantSummary, } from './OAuthAuthorizationService.js';
13
13
  export { SMRT_OAUTH_GRANT_CLAIM, SmrtOAuthAuthorizationStorage, type SmrtOAuthAuthorizationStorageOptions, } from './OAuthAuthorizationStorage.js';
14
14
  export { type CreateAuthorizationUrlOptions, decodeOidcTransaction, encodeOidcTransaction, getUsersOidcConfig, type OidcCallbackResult, OidcLoginError, type OidcLoginResult, OidcLoginService, type OidcLoginServiceOptions, type OidcProviderConfig, type OidcProviderKind, type OidcProviderMetadata, type OidcProviderResolution, type OidcProviderResolutionOptions, type OidcStepUpResult, type OidcStepUpStart, type OidcTokenEndpointAuthMethod, type OidcTokenSet, type OidcTransaction, type ResolvedOidcProviderConfig, resolveOidcProviderConfig, type UsersOidcConfig, } from './OidcLoginService.js';
15
15
  export { assertOperationPermission, checkOperationPermission, hasOperationPermission, type OperationPermissionAllowReason, type OperationPermissionDecision, type OperationPermissionDenyReason, OperationPermissionError, type OperationPermissionOptions, } from './OperationPermissionService.js';
@@ -18,7 +18,7 @@ export { type BeginPasskeyRegistrationInput, DEFAULT_MAX_PASSKEYS_PER_USER, DEFA
18
18
  export { type ChangePasswordInput, type ClearPasswordInput, DEFAULT_PASSWORD_DENYLIST, DEFAULT_PASSWORD_MANAGE_PERMISSION, DEFAULT_PASSWORD_MAX_LENGTH, DEFAULT_PASSWORD_MIN_LENGTH, DEFAULT_PASSWORD_RECOVERY_MAX_AGE_SECONDS, ensurePasswordPermissionsRegistered, outOfBandProofSessionData, PASSWORD_LOGIN_KIND, PASSWORD_MAX_LENGTH_CEILING, PASSWORD_PERMISSION_DEFINITIONS, PASSWORD_RECOVERY_MAX_AGE_CEILING_SECONDS, PasswordCredentialError, PasswordCredentialForbiddenError, PasswordCredentialService, type PasswordCredentialServiceOptions, type PasswordPolicyContext, PasswordPolicyError, type PasswordPolicyOptions, type PasswordRecoveryOptions, type PasswordRecoveryProofContext, type PasswordSignInInput, type PasswordSignInResult, type PasswordStepUpInput, type PasswordStepUpResult, type ReplaceForgottenPasswordInput, type ResetPasswordInput, type SetPasswordInput, } from './PasswordCredentialService.js';
19
19
  export { deriveOperationPermissionCollectionName, deriveOperationPermissionSlug, normalizeOperationPermissionAction, type OperationPermissionCollectionInput, type PermissionCatalog, PermissionCatalogService, type PermissionCatalogSource, type PermissionCatalogSyncResult, type PermissionDefinition, type PostgresPermissionAction, type PostgresPermissionBinding, registerPermissionDefinitions, syncPermissionCatalog, type UsersConfig, } from './PermissionCatalogService.js';
20
20
  export { type PermissionResolutionOptions, type PermissionResolutionResult, PermissionResolver, type PermissionResolverOptions, type TenantPermissionInheritanceResult, } from './PermissionResolver.js';
21
- export { applyPostgresPermissionPolicies, type GeneratePostgresPermissionSqlResult, generatePostgresPermissionSql, type PostgresPermissionPolicyReportItem, type PostgresPermissionPolicyTarget, } from './PostgresPermissionPolicies.js';
21
+ export { applyPostgresPermissionPolicies, applyScopedPostgresPermissionPolicies, type GeneratePostgresPermissionSqlResult, generatePostgresPermissionSql, type PostgresPermissionPolicyReportItem, type PostgresPermissionPolicyTarget, type PostgresPolicyScope, } from './PostgresPermissionPolicies.js';
22
22
  export { type CreateResourceGrantOptions, checkResourceOperationPermission, MAX_RESOURCE_GRANT_DELEGATION_DEPTH, type ResourceGrantDecision, ResourceGrantService, type ResourceIdentity, type ResourceIdentityVerifier, type ResourceOperationPermissionOptions, type RevokeResourceGrantOptions, } from './ResourceGrantService.js';
23
23
  export { type CreatedServicePrincipal, type CreateServicePrincipalInput, type ServicePrincipalRecord, ServicePrincipalService, type ServicePrincipalServiceOptions, } from './ServicePrincipalService.js';
24
24
  export { getCurrentSessionPermissionContext, getRequestScopedDatabase, type PrincipalPermissionRuntimeOptions, type SessionPermissionRuntimeContext, type SessionPermissionRuntimeOptions, withPrincipalPermissionContext, withSessionPermissionContext, } from './SessionPermissionContext.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,2BAA2B,EAC3B,KAAK,iCAAiC,EACtC,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAC5B,kBAAkB,EAClB,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,KAAK,sBAAsB,EAC3B,oBAAoB,EACpB,KAAK,2BAA2B,EAChC,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,GAC9B,MAAM,2BAA2B,C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B,EACvB,KAAK,8BAA8B,GACpC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,KAAK,kBAAkB,EACvB,aAAa,EACb,KAAK,yBAAyB,GAC/B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,KAAK,0BAA0B,EAC/B,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,+CAA+C,EAC/C,qCAAqC,EACrC,sCAAsC,EACtC,oCAAoC,EACpC,+BAA+B,EAC/B,2BAA2B,EAC3B,iBAAiB,EACjB,0BAA0B,EAC1B,mBAAmB,EACnB,KAAK,0BAA0B,GAChC,MAAM,0BAA0B,CAAC"}
@@ -3,19 +3,19 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-users",
6
- "packageVersion": "0.69.0",
6
+ "packageVersion": "0.70.1",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "e5a87ded3adb06027059be3cd1d76e578bcc74cea5364f35118ee1fd8ba367cf",
11
- "packageJson": "0b1bb6b2fcfc8af82978ce9a664c56288d2eeec43f54253a2aa02de7f2127c68",
10
+ "manifest": "9065120c8d85f23622b13fd8e6bc924c5fd41d1aa26aeee293020fabf3155cfc",
11
+ "packageJson": "57eb3ded0e217050dbad73f26cbade2d54b073ad7fd52e0940179b21851c8634",
12
12
  "agents": "b6ae65770f9d085554ccb058f5f87f88132df9dfba3a80f311cb6bb029de9c23",
13
- "moduleDoc:agents/permissions.md": "e8c6c8aecdbac4b7371557008bbd9fae3f5ec3c86a7b4a84108012442b550068",
13
+ "moduleDoc:agents/permissions.md": "12514e331691ea98c7f6b0e6a7596cd4beee7a784cba16927959056565cfad78",
14
14
  "moduleDoc:agents/oidc-provisioning.md": "8408153424b22c6648f062151e261fe4b72271d5c0812b55e6d09a558a4386fd",
15
15
  "moduleDoc:agents/mobile-auth.md": "25e85e83f43e3a46383a92fa809f3a003b4545c3026e78dbe1bccbbc35161e18",
16
16
  "moduleDoc:agents/terminal-auth-testing.md": "ca6bdf325fe4edc3c875e6da38e3f5b4ae287bc0e7035002d275cf15de36e906",
17
17
  "moduleDoc:agents/family-invitations.md": "8598bfc3540b4c5ee2aef611db55dc2a8f6b6993fce9619f84a8ce32608a2954",
18
- "moduleDoc:agents/oauth-authorization.md": "ab2c07927e72a0ac47953052aebb48d0df42a34b9b6cf77db2de73933103e17d",
18
+ "moduleDoc:agents/oauth-authorization.md": "3264ccc679d3f64db2aa768c4c79627483278216e06f850cce4164f5e6ae7189",
19
19
  "moduleDoc:agents/service-principals.md": "ae11f9b0d05e7c77a0a9a827f35422c161e250e3338616337991a636a83f5859",
20
20
  "moduleDoc:agents/retention.md": "fc6ed5443b154641bfe890a4de1213366d4b330ea1bb18ea9e0edfe605f45b02"
21
21
  },
@@ -27,6 +27,8 @@
27
27
  "./operator",
28
28
  "./permission-registry",
29
29
  "./playground",
30
+ "./postgres-policies",
31
+ "./postgres-settings",
30
32
  "./step-up",
31
33
  "./svelte",
32
34
  "./sveltekit"
@@ -8450,7 +8452,7 @@
8450
8452
  {
8451
8453
  "path": "agents/permissions.md",
8452
8454
  "module": "permissions",
8453
- "content": "# Permissions and tenant inheritance\n\nRead for `src/services/PermissionResolver.ts`, operation guards, role seeding,\nRLS, and tenant-hierarchy changes. Integration examples live in README's\nmanifest-derived permission catalog and PostgreSQL RLS sections.\n\n## Membership selection\n\n1. A direct target-tenant membership pins resolution: active resolves normally;\n pending/suspended returns empty. Never union direct and ancestor roles.\n2. Otherwise walk hierarchyPath nearest-first for the nearest active ancestor\n membership whose role has inheritsToDescendants. Skip inactive/unflagged\n ancestors; they neither grant nor block. No qualifying ancestor means empty.\n3. Run later layers against the target tenant. Only target-tenant groups apply;\n membership overrides travel with the chosen ancestor membership.\n inheritedFromTenantId reports that ancestor, null for direct resolution.\n\nVerify hierarchyPath link-by-link against loaded parentTenantId rows before\ntrusting it: excess depth, self-reference, duplicates or inconsistent paths\nfail closed. Bound traversal by MAX_TENANT_HIERARCHY_DEPTH. Tenant status is not\nconsulted, matching direct resolution. Long-lived user/tenant caches must\ninvalidate ancestor membership changes and inheritsToDescendants flips;\nrequest-scoped caches do not survive those requests.\n\n`loadSessionContext().tenantAuthorization` is authoritative for required-tenant\nconsumers; membership null can mean inherited authority.\n\n4. If no membership resolved at all, apply the opt-in ancestor-read policy\n (smrt#2939): the user's ACTIVE memberships on VERIFIED DESCENDANTS of the\n target, whose role slug is declared in `permissions.ancestorRead.roles` and\n within `maxDepth` hops, contribute `<collection>.read` for declared\n collections, intersected with BOTH that role's own catalog grants (so a\n descendant-side tenant GRANT, group role, or membership GRANT cannot widen\n it) AND the principal's effective permissions in that descendant (so its\n DENY cascade and membership DENY apply). Only a SYSTEM\n role (`tenantId` null, `isSystem: true`) matches a declared slug: slugs are\n not unique across a hierarchy, so a tenant-scoped custom role of the same\n name must not opt its tenant in. Off by default;\n read-only; never lateral; never reached when a direct or inherited\n membership already decided. The target tenant's DENY still subtracts.\n `ancestorReadFromTenantIds` reports the contributing descendants. The grant\n carries no membership, so `membershipId`/`tenantAuthorization.membershipId`\n stay null and a consumer requiring a non-empty membership still refuses.\n\n## Permission precedence\n\nApply these layers in order, later layers overriding earlier ones:\n\n1. Ancestor TenantPermissionOverride cascade (GRANT adds, DENY removes).\n2. Selected membership role permissions.\n3. Target-tenant group-role permissions.\n4. Tenant cascade's net DENY removes role/group grants.\n5. Membership GRANT may re-add a tenant-denied slug.\n6. Membership DENY removes last and always wins.\n\nThe tenant block is the cascade's net result, not the union of historical DENYs:\na child's more-specific GRANT can override a parent DENY. Use a direct child\nmembership or tenant DENY to attenuate inherited role authority.\n`getGroupIdsForTenant(userId, tenantId)` is required; getGroupIds is cross-tenant.\n\n## Hierarchies and seeding\n\n- `Tenant.save()` derives hierarchyPath/hierarchyLevel from the REAL\n parentTenantId chain on every save (never from an ancestor's stored path),\n refuses missing parents, cycles and over-depth before writing, and\n re-materializes descendants by raw column update (so STI subclass columns\n are never clobbered). createChild/moveToParent/makeRoot are thin wrappers.\n `materializeTenantHierarchy(db, { dryRun })` / `smrt\n db:materialize-tenant-hierarchy` backfills legacy rows: idempotent, one\n transaction, refuses a broken chain without writing (#3036). A NEW or\n CHANGED parent link is authority-bearing, so `Tenant.save()` first loads the\n parent through TenantCollection (the caller's tenancy scope) and refuses an\n invisible one on every path — helpers, `create({ parentTenantId })`, or a\n plain assignment + save; system context bypasses as usual, and an unchanged\n link is never re-checked. getTree(rootId?)\n returns UI structure. Maximum depth is 10.\n- Tenant override cascade requires parent cascadePermissions and child\n inheritPermissions. These flags do not gate the independent, per-role\n inheritsToDescendants membership flow.\n- `permissions.ancestorRead` in the `users` package config declares upward,\n read-only visibility: `{ roles, collections, maxDepth? }`. Both lists are\n required and non-empty and `maxDepth >= 1`, else the policy is OFF — there is\n no partially valid declaration. `isAncestorReadableSlug()` is the single place\n the read-only bound is enforced; only a two-segment `<collection>.<action>`\n slug whose action normalizes to `read` on a declared collection passes.\n `PermissionResolver.create(options, { ancestorReadPolicy })` binds one\n resolver; `null` forces it off. It grants the OPERATION at the ancestor, never\n row visibility — sibling rows stay scoped by the tenancy interceptor and RLS.\n- seedSystemRoles({ inheritsToDescendants: ['owner', 'admin'] }) flags listed\n slugs additively, never unflags omitted ones, and rejects unknown slugs.\n Default seeds are exact-tenant.\n- RolePermissionCollection.seedRolePermissions() or\n seedSystemRoles({ seedPermissions: true }) maps owner/admin to all catalog\n permissions, member to ordinary-resource read/create, viewer to read. Member\n create excludes identity/RBAC/security resources and their joins/overrides.\n Seeding is additive/idempotent; removal requires prune: true. Catalog sync\n and grants plan from one read, then commit in `SEEDING_BATCH_SIZE` batches\n (#3323): never one durable commit per row (an fsync each on local SQLite),\n and never one catalog-wide transaction (`@happyvertical/sql` transaction\n scopes cost superlinearly per statement). Pass a caller transaction's handle.\n- When a package adds built-in self-personalization permissions after role\n creation, explicitly call seedDefaultRolePersonalizationPermissions(). It\n upgrades owner/admin/member/viewer idempotently and never grants custom roles.\n The built-in self-personalization slugs are `fields.policy.personalize`,\n `overviews.personalize` and `shell.personalize`, each seeded only once its\n package registered it.\n\n## Guards and RLS\n\nPermissionCatalogService derives collection.action slugs from manifests,\nincluding custom actions; list/get map to read. Guards derive a class's slug\nthrough the same resolution (explicit `collection`, manifest entry, then its\nSTI base's), so an STI subtype resolves its STI base's collection\n(`Network extends Tenant` -> `tenants.update`) in every build, including a\nbundle decorated before its manifest loads (#3125). Hand-written mutations in form\nhandlers, endpoints, CLI and jobs use assertOperationPermission(). It requires\ncatalog presence then resolves permissions, throwing fail-closed by default.\nShared STI CRUD catalog entries name the effective base model, independent of\nregistration order. Subtypes cannot overwrite `profiles.create` (formerly Bot\nwhen Bot registered last). An explicit child collection keeps its own CRUD,\nand deeper descendants sharing that namespace cannot replace its owner;\nchild custom actions and field permissions are still catalogued. Same-name app\nreplacements supply the effective base identity through the public registry.\n`sti-create-dispatch.test.ts` exercises real Profile/Bot and a generic family\nthrough REST, MCP, CLI's create handler and assistant manifest dispatch on SQLite;\n`permission-catalog.test.ts` checks reversed order and app replacement metadata.\nUse onDeny: 'return', checkOperationPermission or hasOperationPermission only\nwhen the caller handles a structured/boolean denial.\n\nGenerated SvelteKit write routes (POST/PUT/PATCH/DELETE CRUD and mutating\ncustom actions) enforce the same `collection.action` slug (custom actions use\n`collection.<method>`; actions hosted on a collection class use the item collection, which the catalog now emits) after authentication: the slug must be in the request's\nsession permission snapshot (`locals.permissions`/`permissionSet`/\n`smrtPermissions` or `locals.tenantContext.permissions`), otherwise 403. Only\n`locals.tenantContext.superAdminBypass` skips it; `api.public: true` stays open.\n\nResource-anchored guards receive the resource tenant ID. When it differs from\nthe session tenant, omit the session membership so the resolver selects the\nappropriate authority; mismatched supplied membership/tenant fails closed.\nInherited root-admin authority can then authorize descendant resources without\napplication-side membership fan-out.\n\nResolution cost must not scale with catalog size in objects (#3047): role →\npermission ids and ids → slugs are `list({ select })` projection reads (the\ncollections' beforeList interceptors still run; no RolePermission/Permission\nis hydrated), so an owner mapped to the whole catalog costs two queries and\nno per-permission objects. Keep new resolver reads projections when only ids\nor slugs are needed, and do not add public collection methods for them — each\nbecomes a custom-action slug in the manifest-derived catalog. The resolver's\ncollections never inherit `defaultListLimit`/`maxListLimit` from the caller's\noptions, and id-list reads chunk at `IN_LIST_CHUNK_SIZE` with an explicit\nlimit: a truncated authorization read would narrow the result silently.\n`issue-3047-permission-resolution-cost-postgres.test.ts` pins the hydration\nbudget and a golden equivalence matrix recorded on the hydrating resolver.\n\nThe same rule holds for every framework-internal authorization read (#3048):\ncollections that back a decision — the resolver's, the ResourceGrant exact-tuple\nread in `checkResourceOperationPermission()` (DENY wins only if every row is\nread), and TenantService's owned-tenant quota count — are created through\n`withoutListBounds()` (`src/services/authorization-read-options.ts`), which\nstrips only the caller's list bounds. Use it for any new decision read;\n`issue-3048-authorization-list-bounds-postgres.test.ts` pins it.\n\nPermissionResolver runs every resolution inside smrt-tenancy's system context\n(#3036). Its reads are deliberately cross-tenant and framework-owned — the\nancestor TenantPermissionOverride batch, ancestor memberships for\ninheritsToDescendants, descendant memberships for ancestor-read — and are keyed\nby the explicit (userId, tenantId); with those classes registered tenant-scoped\n(`autoFilter`) the consumer's filter otherwise threw TenantIsolationError or\nsilently narrowed them. It returns slugs and ids only, never rows, and the\ncaller's own reads stay filtered. Do not move a resolver read back under the\nambient tenant; the Postgres regression suite\n`issue-3036-hierarchy-resolution-postgres.test.ts` pins this. Because nothing\nbackstops those reads any more, the tenant-override cascade verifies its chain\ntoo: it uses hierarchyPath only when it agrees link-by-link with\nparentTenantId, otherwise walks the real parent links (so a forged path cannot\ncascade an unrelated tenant in, and a never-materialized row still gets its real\nancestors' DENYs — and GRANTs), and throws TenantHierarchyError on a broken\nreal chain: a per-request failure for that tenant's whole subtree, which\n`smrt db:materialize-tenant-hierarchy --dry-run` reports ahead of time (see\nREADME \"Upgrading an existing fleet\").\n`getTenantInheritanceChain()` returns Tenant rows, so it is NOT run in system\ncontext; it reports the same verified chain the cascade applies when the\ncaller can read every ancestor. Otherwise it never reports PARENT_NOT_FOUND\nfor a row the caller simply cannot see: an interceptor refusal surfaces as\nTenantIsolationError, and a silently filtered row (e.g. RLS) ends the chain at\nthe nearest readable ancestor. Descendant path rewrites are raw column updates recorded through\n`bumpChangeFeed`; `updated_at` is intentionally not bumped (derived columns;\nevery save recomputes them). They are not atomic with the moving row's save —\nan interrupted subtree fails closed until re-saved or backfilled.\n\nSystem context and super-admin bypass are honored. Pass\nallowSuperAdminBypass: false for money or separation-of-duties operations that\nrequire an explicit grant.\n\ngeneratePostgresPermissionSql/applyPostgresPermissionPolicies enforce generated\nRLS using smrt.permissions and smrt.tenant_id, installed with set_config by\nwithSessionPermissionContext. This bounds REST, MCP and in-process database\naccess once principal context is set. Child-tenant sessions receive resolved\ninherited permissions automatically, but RLS row filtering remains bound to the\nsession tenant: a root session's app-level guard authorization does not itself\npermit child rows through RLS. Preserve this distinction.\n\nRolePermission's natural key is `(role_id, permission_id)` (#3329); repeated or\nconcurrent inserts converge without changing the grant ID. Existing deployments\nmust run `deduplicateRolePermissions()` with stopped writers before ordinary\nschema migration; see README's \"Upgrade duplicate role grants\". It keeps the\noldest row and installs uniqueness atomically. Runtime seeding never performs\nthis schema repair.\n\nMembershipOverride `(membership_id, permission_id)`, TenantPermissionOverride\n`(tenant_id, permission_id)` and GroupMember `(group_id, user_id)` are natural\nkeys too (#3375): `setOverride()` upserts (last effect wins), removal deletes by\nthe pair, and their FKs declare `onDelete: 'NO ACTION'` so the natural key does\nnot turn them into CASCADE. Existing deployments run\n`deduplicateAuthorityPairs()` in the same stopped-writer window; it keeps the\neffective override (DENY > GRANT > INHERIT) so authority never widens.\n\nCustom methods can declare `operationPermissions` aliases to the same\ncollection's CRUD grants (#3878); `deriveOperationPermissionSlug()` resolves\nthem for class and catalog-slug callers. Catalog generation merges optional\n`databaseActions` into the target grant's PostgreSQL bindings. CRUD grants\ncannot themselves be aliased. See core's [generator contract](../../core/agents/generators.md#custom-action-permission-aliases-3878).\n\n## Portable metadata registry (#4765)\n\nBrowser-safe packages import `registerPermissionDefinitions` and its existing\n`PermissionDefinition` / PostgreSQL binding types from\n`@happyvertical/smrt-users/permission-registry`. This entry imports only shared\nmetadata storage. It does not load Users models, catalog database sync, operator\nservices, PostgreSQL policy generation or Core filesystem discovery.\n\nThe old package-root and PermissionCatalogService exports re-export the exact\nsame function. Both paths share the existing process-global Map/counter; each\nreturned disposer removes only its own registration and may be called repeatedly.\nDefinitions retain their original references and normalization/conflict rules\nremain in the server catalog. No second catalog or no-op browser registration is\nintroduced. Metadata registration and catalog sync do not grant a user, role,\ntenant or resource permission. Existing persisted grants/current authority checks\nremain required. Use the public portable entry rather than private service paths\nwhen a model package needs declarations without the server runtime.\n\n### Runtime resource discovery imports\n\n`src/sveltekit/resource-list-handler.ts` imports shared action/name policy from\n`@happyvertical/smrt-core/api-actions`, not the Vite-plugin barrel. This is the\nsame implementation re-exported by the route generator; permissions, wireability,\ncustom-action receiver resolution and paths are unchanged. The existing resource\nhandler suite retains positive and refusal coverage, and its fresh-Node published\nentry guard rejects Vite route-emitter/activation-generator loads. No SQL executor,\ntransaction, authentication or tenant-boundary behavior changes in this import fix.\n\n## Agent users (#5086)\n\nThere is no agent column on `User`. A user is an agent when its linked\n`Profile` has the `bot` profile type (`resolveAgentProfile` /\n`AGENT_PROFILE_TYPE_SLUG` in `@happyvertical/smrt-profiles`); give it a\nmembership with a limited custom role like any member. MCP classifies the\nprincipal from that live profile (`kind: 'agent'`), the default MCP policy\naccepts the kind only when `principalKinds` lists it, and the role's\npermissions cap what its tokens can do on every request. The profile models\nrefuse an unprivileged principal changing whether a profile is `bot` typed\n(including by create or natural-key upsert) or creating/renaming the type, so an agent cannot relabel itself. See\n`packages/app-runtime/agents/self-issuer-mcp.md`.\n"
8455
+ "content": "# Permissions and tenant inheritance\n\nRead for `src/services/PermissionResolver.ts`, operation guards, role seeding,\nRLS, and tenant-hierarchy changes. Integration examples live in README's\nmanifest-derived permission catalog and PostgreSQL RLS sections.\n\n## Membership selection\n\n1. A direct target-tenant membership pins resolution: active resolves normally;\n pending/suspended returns empty. Never union direct and ancestor roles.\n2. Otherwise walk hierarchyPath nearest-first for the nearest active ancestor\n membership whose role has inheritsToDescendants. Skip inactive/unflagged\n ancestors; they neither grant nor block. No qualifying ancestor means empty.\n3. Run later layers against the target tenant. Only target-tenant groups apply;\n membership overrides travel with the chosen ancestor membership.\n inheritedFromTenantId reports that ancestor, null for direct resolution.\n\nVerify hierarchyPath link-by-link against loaded parentTenantId rows before\ntrusting it: excess depth, self-reference, duplicates or inconsistent paths\nfail closed. Bound traversal by MAX_TENANT_HIERARCHY_DEPTH. Tenant status is not\nconsulted, matching direct resolution. Long-lived user/tenant caches must\ninvalidate ancestor membership changes and inheritsToDescendants flips;\nrequest-scoped caches do not survive those requests.\n\n`loadSessionContext().tenantAuthorization` is authoritative for required-tenant\nconsumers; membership null can mean inherited authority.\n\n4. If no membership resolved at all, apply the opt-in ancestor-read policy\n (smrt#2939): the user's ACTIVE memberships on VERIFIED DESCENDANTS of the\n target, whose role slug is declared in `permissions.ancestorRead.roles` and\n within `maxDepth` hops, contribute `<collection>.read` for declared\n collections, intersected with BOTH that role's own catalog grants (so a\n descendant-side tenant GRANT, group role, or membership GRANT cannot widen\n it) AND the principal's effective permissions in that descendant (so its\n DENY cascade and membership DENY apply). Only a SYSTEM\n role (`tenantId` null, `isSystem: true`) matches a declared slug: slugs are\n not unique across a hierarchy, so a tenant-scoped custom role of the same\n name must not opt its tenant in. Off by default;\n read-only; never lateral; never reached when a direct or inherited\n membership already decided. The target tenant's DENY still subtracts.\n `ancestorReadFromTenantIds` reports the contributing descendants. The grant\n carries no membership, so `membershipId`/`tenantAuthorization.membershipId`\n stay null and a consumer requiring a non-empty membership still refuses.\n\n## Permission precedence\n\nApply these layers in order, later layers overriding earlier ones:\n\n1. Ancestor TenantPermissionOverride cascade (GRANT adds, DENY removes).\n2. Selected membership role permissions.\n3. Target-tenant group-role permissions.\n4. Tenant cascade's net DENY removes role/group grants.\n5. Membership GRANT may re-add a tenant-denied slug.\n6. Membership DENY removes last and always wins.\n\nThe tenant block is the cascade's net result, not the union of historical DENYs:\na child's more-specific GRANT can override a parent DENY. Use a direct child\nmembership or tenant DENY to attenuate inherited role authority.\n`getGroupIdsForTenant(userId, tenantId)` is required; getGroupIds is cross-tenant.\n\n## Hierarchies and seeding\n\n- `Tenant.save()` derives hierarchyPath/hierarchyLevel from the REAL\n parentTenantId chain on every save (never from an ancestor's stored path),\n refuses missing parents, cycles and over-depth before writing, and\n re-materializes descendants by raw column update (so STI subclass columns\n are never clobbered). createChild/moveToParent/makeRoot are thin wrappers.\n `materializeTenantHierarchy(db, { dryRun })` / `smrt\n db:materialize-tenant-hierarchy` backfills legacy rows: idempotent, one\n transaction, refuses a broken chain without writing (#3036). A NEW or\n CHANGED parent link is authority-bearing, so `Tenant.save()` first loads the\n parent through TenantCollection (the caller's tenancy scope) and refuses an\n invisible one on every path — helpers, `create({ parentTenantId })`, or a\n plain assignment + save; system context bypasses as usual, and an unchanged\n link is never re-checked. getTree(rootId?)\n returns UI structure. Maximum depth is 10.\n- Tenant override cascade requires parent cascadePermissions and child\n inheritPermissions. These flags do not gate the independent, per-role\n inheritsToDescendants membership flow.\n- `permissions.ancestorRead` in the `users` package config declares upward,\n read-only visibility: `{ roles, collections, maxDepth? }`. Both lists are\n required and non-empty and `maxDepth >= 1`, else the policy is OFF — there is\n no partially valid declaration. `isAncestorReadableSlug()` is the single place\n the read-only bound is enforced; only a two-segment `<collection>.<action>`\n slug whose action normalizes to `read` on a declared collection passes.\n `PermissionResolver.create(options, { ancestorReadPolicy })` binds one\n resolver; `null` forces it off. It grants the OPERATION at the ancestor, never\n row visibility — sibling rows stay scoped by the tenancy interceptor and RLS.\n- seedSystemRoles({ inheritsToDescendants: ['owner', 'admin'] }) flags listed\n slugs additively, never unflags omitted ones, and rejects unknown slugs.\n Default seeds are exact-tenant.\n- RolePermissionCollection.seedRolePermissions() or\n seedSystemRoles({ seedPermissions: true }) maps owner/admin to all catalog\n permissions, member to ordinary-resource read/create, viewer to read. Member\n create excludes identity/RBAC/security resources and their joins/overrides.\n Seeding is additive/idempotent; removal requires prune: true. Catalog sync\n and grants plan from one read, then commit in `SEEDING_BATCH_SIZE` batches\n (#3323): never one durable commit per row (an fsync each on local SQLite),\n and never one catalog-wide transaction (`@happyvertical/sql` transaction\n scopes cost superlinearly per statement). Pass a caller transaction's handle.\n- When a package adds built-in self-personalization permissions after role\n creation, explicitly call seedDefaultRolePersonalizationPermissions(). It\n upgrades owner/admin/member/viewer idempotently and never grants custom roles.\n The built-in self-personalization slugs are `fields.policy.personalize`,\n `overviews.personalize` and `shell.personalize`, each seeded only once its\n package registered it.\n\n## Guards and RLS\n\nPermissionCatalogService derives collection.action slugs from manifests,\nincluding custom actions; list/get map to read. Guards derive a class's slug\nthrough the same resolution (explicit `collection`, manifest entry, then its\nSTI base's), so an STI subtype resolves its STI base's collection\n(`Network extends Tenant` -> `tenants.update`) in every build, including a\nbundle decorated before its manifest loads (#3125). Hand-written mutations in form\nhandlers, endpoints, CLI and jobs use assertOperationPermission(). It requires\ncatalog presence then resolves permissions, throwing fail-closed by default.\nShared STI CRUD catalog entries name the effective base model, independent of\nregistration order. Subtypes cannot overwrite `profiles.create` (formerly Bot\nwhen Bot registered last). An explicit child collection keeps its own CRUD,\nand deeper descendants sharing that namespace cannot replace its owner;\nchild custom actions and field permissions are still catalogued. Same-name app\nreplacements supply the effective base identity through the public registry.\n`sti-create-dispatch.test.ts` exercises real Profile/Bot and a generic family\nthrough REST, MCP, CLI's create handler and assistant manifest dispatch on SQLite;\n`permission-catalog.test.ts` checks reversed order and app replacement metadata.\nUse onDeny: 'return', checkOperationPermission or hasOperationPermission only\nwhen the caller handles a structured/boolean denial.\n\nInside a runtime REST request acting for a host-resolved principal\n(`getRequestPrincipal()` from core, #5195), `checkOperationPermission` and\nits siblings are capped by that principal: a slug it lacks is denied\nwhichever branch would grant it (system context, super-admin bypass, live\nrole, explicit `permissionSet`). For the principal's own user and tenant its\npermissions stand in for resolution (an explicit set is intersected); for\nanother subject a transaction-scoped request denies with `subject_mismatch`\nand any other request resolves that subject live, still capped. Outside such\na request the gate is unchanged. Test: `src/__tests__/rest-request-scope.test.ts`.\n\nGenerated SvelteKit write routes (POST/PUT/PATCH/DELETE CRUD and mutating\ncustom actions) enforce the same `collection.action` slug (custom actions use\n`collection.<method>`; actions hosted on a collection class use the item collection, which the catalog now emits) after authentication: the slug must be in the request's\nsession permission snapshot (`locals.permissions`/`permissionSet`/\n`smrtPermissions` or `locals.tenantContext.permissions`), otherwise 403. Only\n`locals.tenantContext.superAdminBypass` skips it; `api.public: true` stays open.\n\nResource-anchored guards receive the resource tenant ID. When it differs from\nthe session tenant, omit the session membership so the resolver selects the\nappropriate authority; mismatched supplied membership/tenant fails closed.\nInherited root-admin authority can then authorize descendant resources without\napplication-side membership fan-out.\n\nResolution cost must not scale with catalog size in objects (#3047): role →\npermission ids and ids → slugs are `list({ select })` projection reads (the\ncollections' beforeList interceptors still run; no RolePermission/Permission\nis hydrated), so an owner mapped to the whole catalog costs two queries and\nno per-permission objects. Keep new resolver reads projections when only ids\nor slugs are needed, and do not add public collection methods for them — each\nbecomes a custom-action slug in the manifest-derived catalog. The resolver's\ncollections never inherit `defaultListLimit`/`maxListLimit` from the caller's\noptions, and id-list reads chunk at `IN_LIST_CHUNK_SIZE` with an explicit\nlimit: a truncated authorization read would narrow the result silently.\n`issue-3047-permission-resolution-cost-postgres.test.ts` pins the hydration\nbudget and a golden equivalence matrix recorded on the hydrating resolver.\n\nThe same rule holds for every framework-internal authorization read (#3048):\ncollections that back a decision — the resolver's, the ResourceGrant exact-tuple\nread in `checkResourceOperationPermission()` (DENY wins only if every row is\nread), and TenantService's owned-tenant quota count — are created through\n`withoutListBounds()` (`src/services/authorization-read-options.ts`), which\nstrips only the caller's list bounds. Use it for any new decision read;\n`issue-3048-authorization-list-bounds-postgres.test.ts` pins it.\n\nPermissionResolver runs every resolution inside smrt-tenancy's system context\n(#3036). Its reads are deliberately cross-tenant and framework-owned — the\nancestor TenantPermissionOverride batch, ancestor memberships for\ninheritsToDescendants, descendant memberships for ancestor-read — and are keyed\nby the explicit (userId, tenantId); with those classes registered tenant-scoped\n(`autoFilter`) the consumer's filter otherwise threw TenantIsolationError or\nsilently narrowed them. It returns slugs and ids only, never rows, and the\ncaller's own reads stay filtered. Do not move a resolver read back under the\nambient tenant; the Postgres regression suite\n`issue-3036-hierarchy-resolution-postgres.test.ts` pins this. Because nothing\nbackstops those reads any more, the tenant-override cascade verifies its chain\ntoo: it uses hierarchyPath only when it agrees link-by-link with\nparentTenantId, otherwise walks the real parent links (so a forged path cannot\ncascade an unrelated tenant in, and a never-materialized row still gets its real\nancestors' DENYs — and GRANTs), and throws TenantHierarchyError on a broken\nreal chain: a per-request failure for that tenant's whole subtree, which\n`smrt db:materialize-tenant-hierarchy --dry-run` reports ahead of time (see\nREADME \"Upgrading an existing fleet\").\n`getTenantInheritanceChain()` returns Tenant rows, so it is NOT run in system\ncontext; it reports the same verified chain the cascade applies when the\ncaller can read every ancestor. Otherwise it never reports PARENT_NOT_FOUND\nfor a row the caller simply cannot see: an interceptor refusal surfaces as\nTenantIsolationError, and a silently filtered row (e.g. RLS) ends the chain at\nthe nearest readable ancestor. Descendant path rewrites are raw column updates recorded through\n`bumpChangeFeed`; `updated_at` is intentionally not bumped (derived columns;\nevery save recomputes them). They are not atomic with the moving row's save —\nan interrupted subtree fails closed until re-saved or backfilled.\n\nSystem context and super-admin bypass are honored. Pass\nallowSuperAdminBypass: false for money or separation-of-duties operations that\nrequire an explicit grant.\n\ngeneratePostgresPermissionSql/applyPostgresPermissionPolicies enforce generated\nRLS using smrt.permissions and smrt.tenant_id, installed with set_config by\nwithSessionPermissionContext. This bounds REST, MCP and in-process database\naccess once principal context is set. Child-tenant sessions receive resolved\ninherited permissions automatically, but RLS row filtering remains bound to the\nsession tenant: a root session's app-level guard authorization does not itself\npermit child rows through RLS. Preserve this distinction.\n\nA host with run-time models in an app schema passes a `PostgresPolicyScope` (second\nargument; `@happyvertical/smrt-users/postgres-policies`, `applyScopedPostgresPermissionPolicies`\non a handle it already holds): tables and the `smrt_*` helpers live in\n`schemaName`, never `public`; only `includeClass` classes get policies;\n`permissionsFor` names the slugs; explicit bindings are not applied. Helper bodies\nnever call each other (a schema copied whole creates functions in name order).\n\nRolePermission's natural key is `(role_id, permission_id)` (#3329); repeated or\nconcurrent inserts converge without changing the grant ID. Existing deployments\nmust run `deduplicateRolePermissions()` with stopped writers before ordinary\nschema migration; see README's \"Upgrade duplicate role grants\". It keeps the\noldest row and installs uniqueness atomically. Runtime seeding never performs\nthis schema repair.\n\nMembershipOverride `(membership_id, permission_id)`, TenantPermissionOverride\n`(tenant_id, permission_id)` and GroupMember `(group_id, user_id)` are natural\nkeys too (#3375): `setOverride()` upserts (last effect wins), removal deletes by\nthe pair, and their FKs declare `onDelete: 'NO ACTION'` so the natural key does\nnot turn them into CASCADE. Existing deployments run\n`deduplicateAuthorityPairs()` in the same stopped-writer window; it keeps the\neffective override (DENY > GRANT > INHERIT) so authority never widens.\n\nCustom methods can declare `operationPermissions` aliases to the same\ncollection's CRUD grants (#3878); `deriveOperationPermissionSlug()` resolves\nthem for class and catalog-slug callers. Catalog generation merges optional\n`databaseActions` into the target grant's PostgreSQL bindings. CRUD grants\ncannot themselves be aliased. See core's [generator contract](../../core/agents/generators.md#custom-action-permission-aliases-3878).\n\n## Portable metadata registry (#4765)\n\nBrowser-safe packages import `registerPermissionDefinitions` and its existing\n`PermissionDefinition` / PostgreSQL binding types from\n`@happyvertical/smrt-users/permission-registry`. This entry imports only shared\nmetadata storage. It does not load Users models, catalog database sync, operator\nservices, PostgreSQL policy generation or Core filesystem discovery.\n\nThe old package-root and PermissionCatalogService exports re-export the exact\nsame function. Both paths share the existing process-global Map/counter; each\nreturned disposer removes only its own registration and may be called repeatedly.\nDefinitions retain their original references and normalization/conflict rules\nremain in the server catalog. No second catalog or no-op browser registration is\nintroduced. Metadata registration and catalog sync do not grant a user, role,\ntenant or resource permission. Existing persisted grants/current authority checks\nremain required. Use the public portable entry rather than private service paths\nwhen a model package needs declarations without the server runtime.\n\n### Runtime resource discovery imports\n\n`src/sveltekit/resource-list-handler.ts` imports shared action/name policy from\n`@happyvertical/smrt-core/api-actions`, not the Vite-plugin barrel. This is the\nsame implementation re-exported by the route generator; permissions, wireability,\ncustom-action receiver resolution and paths are unchanged. The existing resource\nhandler suite retains positive and refusal coverage, and its fresh-Node published\nentry guard rejects Vite route-emitter/activation-generator loads. No SQL executor,\ntransaction, authentication or tenant-boundary behavior changes in this import fix.\n\n## Agent users (#5086)\n\nThere is no agent column on `User`. A user is an agent when its linked\n`Profile` has the `bot` profile type (`resolveAgentProfile` /\n`AGENT_PROFILE_TYPE_SLUG` in `@happyvertical/smrt-profiles`); give it a\nmembership with a limited custom role like any member. MCP classifies the\nprincipal from that live profile (`kind: 'agent'`), the default MCP policy\naccepts the kind only when `principalKinds` lists it, and the role's\npermissions cap what its tokens can do on every request. The profile models\nrefuse an unprivileged principal changing whether a profile is `bot` typed\n(including by create or natural-key upsert) or creating/renaming the type, so an agent cannot relabel itself. See\n`packages/app-runtime/agents/self-issuer-mcp.md`.\n"
8454
8456
  },
8455
8457
  {
8456
8458
  "path": "agents/oidc-provisioning.md",
@@ -8475,7 +8477,7 @@
8475
8477
  {
8476
8478
  "path": "agents/oauth-authorization.md",
8477
8479
  "module": "oauth-authorization",
8478
- "content": "# Hosted OAuth authorization\n\n`SmrtOAuthAuthorizationStorage` implements the protocol-neutral storage contract\nfrom `@happyvertical/auth/server`. Apply normal SMRT migrations before starting\nthe server. The six `users_oauth_*` models are sensitive and have no generated\nREST, MCP or CLI operations. Keep their tables on the private application\nconnection; public catalog roles must not read them.\n\n`SmrtOAuthAuthorizationService.create({ db, scopePermissions })` supplies the\nsession boundary. `approve(server, parsedRequest, sessionId)` loads the existing\nsession again, checks its active user and tenant membership, verifies every\nscope's configured permissions, and records consent. Existing magic-link,\npassword and OIDC sessions work without a separate identity mapping. Parent\nsession validity and session permission ceilings are enforced by SessionService.\nUnknown scopes fail closed. An empty permission mapping explicitly permits a\nscope for any valid session. OAuth does not grant super-admin bypass.\n\nPass `service.identity` to the SDK server. It revalidates the stored consent on\nboth code exchange and refresh. A permission loss denies the grant rather than\nsilently expanding or partially authorizing it. The consent-time permission\nsnapshot is an upper bound even if the host later changes its scope mapping.\n\nAfter `server.verifyAccessToken(token, resource)`, always call\n`service.validateAccessTokenClaims(payload)`. A non-null result is a server-only\nSessionContext whose permissions and permissionCeiling are limited to the\nverified token's mapped scopes. Do not serialize that context: it contains the\nsession credential. The JWT carries only a non-secret `smrt_grant_id`, subject,\nclient, tenant and scopes. JWT signature verification alone does not check live\nsession, user, tenant or consent revocation.\n\n`listGrants(sessionId)` returns safe account-settings projections.\n`revokeGrant(sessionId, grantId)` checks ownership and atomically revokes the\nconsent, outstanding codes, and all refresh descendants. Revoking or replaying a\nmanaged refresh token also revokes its consent, so existing access tokens fail\nthe live grant check. Repeating revocation is safe. A foreign grant returns false.\n\nThe `/sveltekit` export `createOAuthHandlers({ server, authorization,\ngetSessionId })` provides Fetch-compatible `authorize`, `consent`, `grants` and\n`protocol` handlers. The host renders consent, supplies its existing cookie\nlookup, and preserves a validated local return path through magic-link login.\nConsent POST requires an exact same-origin Origin header and `decision=approve`;\nrequested OAuth parameters remain on the authorization URL and are revalidated\nby the SDK. Grant revocation POST has the same origin check and takes `grantId`.\nAll account/consent responses use private, no-store. No handler authenticates a\nsession from OAuth client identity or accepts a browser-submitted user/tenant.\n\n## Client ID Metadata Documents (#5081)\n\nOpt-in, off by default, like `dynamicClientRegistration`. The SDK server\nresolves clients only through `storage.getClient`, so\n`createCimdAuthorizationServer({ ...sdkOptions, clientIdMetadataDocuments })`\n(`src/services/oauth-cimd.ts`) wraps the storage and subclasses the server to\nadd `client_id_metadata_document_supported: true` to RFC 8414 metadata. Without\nthe option it returns the plain SDK server: https client_ids stay unknown,\nnothing is fetched, nothing is advertised. `withClientIdMetadataDocuments`\ncomposes the same decorator onto a storage directly.\n\n- `allowClientOrigin(origin, clientId)` is REQUIRED; construction throws\n without it (there is no implicit allow-all; pass `() => true` explicitly).\n It runs on every request before the cache, so a policy change is immediate;\n a throw or non-`true` result denies.\n- client_id must be the canonical `https://` URL with a path, default port, no\n credentials/fragment/query/dot segments, and a public DNS-style host (literal IPs,\n single-label and `.local/.internal/.localhost`-style names are refused before\n any network I/O).\n- Fetch (`oauth-cimd-fetch.ts`): DNS resolved once, every address must be\n public (non-global-unicast IPv6, private/loopback/link-local/CGNAT/metadata\n IPv4 refused), connection pinned to the vetted address, redirects never\n followed, 5 s deadline covering DNS and the request (also enforced around any injected fetcher), 16 KiB cap, at most 8 concurrent cache-miss fetches (`maxConcurrentFetches`; excess is refused as unknown client, not failure-cached), `application/json` or `+json` only,\n identity encoding. content's `safe-remote-url` is not reused: users cannot\n depend on content (heavy graph, content dev-depends on users).\n- Document: `client_id` equals the URL; `redirect_uris` 1-10 https (loopback\n http only with `allowLoopbackRedirects`); the authorization request's\n `redirect_uri` must equal one entry exactly; `token_endpoint_auth_method`\n absent or `none`; any `client_secret*` rejects; grant/response types limited\n to `authorization_code`/`refresh_token`/`code`. Allowed scopes are the\n document's `scope` intersected with the server's (all server scopes if\n absent).\n- Cache: in-memory, honours `s-maxage`/`max-age`/`Age`, clamped to 60 s..24 h\n (so `no-store` still gets the floor, bounding outbound fetches), 1 h default,\n 30 s negative cache, 1000 entries, concurrent lookups share one fetch. It is\n per-process; replicas fetch independently.\n- Every failure is \"unknown client\" to the requester; `onRejected(clientId,\n reason)` is for operator logs only. Tests: `src/__tests__/oauth-cimd.test.ts`.\n\n## Transaction invariants\n\nCode consume uses a conditional write. Refresh rotation and revocation lock a\nstable family row before reading token state; locking the token being replaced\nalone would allow a concurrent revocation to miss an inserted descendant.\nManaged operations lock the consent row first, then the family. Replacement\ninsertion, old-token consume and replay revocation share one database executor.\nA failed insert rolls back consume. Revalidated scopes and claims are persisted\natomically before the SDK exposes the replacement. Undefined claims clear prior\nclaims. Narrowing cannot expand scopes, revive or modify a consumed token.\n\nRetry only transaction failures classified as SQLite contention or PostgreSQL\nserialization/deadlock, after adapter rollback, at most six retries. Never retry\nprotocol callbacks or other external effects. The database adapter must clean up\nfailed statements and support independent connections; a process-local mutex is\nnot a replica-safety mechanism.\n\n## Behavior-to-test contract (#3659)\n\nEvery row runs in `src/__tests__/oauth-authorization.test.ts` on Node >=26 with\nSQLite and real PostgreSQL. Commands:\n\n```sh\npnpm --filter @happyvertical/smrt-users exec vitest run src/__tests__/oauth-authorization.test.ts\nDATABASE_URL=postgres://postgres@127.0.0.1:55597/smrt_oauth pnpm --filter @happyvertical/smrt-users exec vitest run src/__tests__/oauth-authorization.test.ts\npnpm --filter @happyvertical/smrt-users typecheck\n```\n\n| Invariant / trigger | Positive | Negative / failure | Actor / context | Executor / external edge | Level |\n| --- | --- | --- | --- | --- | --- |\n| Register and consume code | Metadata survives new adapter; one concurrent winner | Wrong client, redirect, resource; expiry and replay | Registered client / subject | Independent DB connections; SDK code contract | Integration |\n| Rotate / replay refresh | One replacement | Reuse revokes every descendant | Same family across replicas | Stable family lock, same transaction | Integration |\n| Rotation rollback / revoke race | Retry after insertion failure works | Duplicate replacement aborts consume; revoke cannot miss descendant | Same family, simultaneous operations | Real rollback and independent executors | Integration |\n| Narrow replacement | Subset and replacement claims persist through subsequent rotation; undefined claims clear old claims | Expansion, hash mismatch, consumed/revoked token | Authenticated client / original family | SDK fail-closed narrowing contract, atomic locked update | Integration |\n| Explicit recovery factory | Recreates configured connection after invalidation | Instance-only fails closed; ordinary storage failure propagates | Storage owner / configured database | Injected failure boundary plus real independent-connection races | Unit + integration |\n| Access revocation | Another adapter sees it; repeats safe | Expired revocation no longer effective | Possessor of verified access token | Unique insert with conflict handling | Integration |\n| Consent/grant ownership | Own grant can list/revoke | Other subject, tenant, scope deny; no session bearer in projection | Owner A/B × grant A/B | Live session + consent reads; atomic cascade | Integration |\n| Live identity and ceiling | Current permission allows | Inactive user/membership, changed session ceiling, destroyed session | Active vs revoked context | SessionService and current RBAC | Integration |\n| Code/live revoke cascade | Valid code exchanges | Membership loss before exchange; refresh revoke kills access | Original subject/tenant | SDK revalidateConsent callback | Integration |\n| Consent snapshot / tenant | Original mapped scope | Later permission mapping expansion; inactive tenant | Owner × current tenant | Stored upper bound plus live permission checks | Integration |\n| Layered session / expiry | Parent and child valid | Parent destroyed or child expired | Person session on device parent | Existing session controls | Integration |\n| Consent route | Same-origin explicit approval | Missing/foreign Origin, denial, revoked session | Browser session / untrusted POST | Fetch request and SDK parsing | Route + DB |\n\nThis is new functionality, so a base-regression comparison is N/A: base has no\nOAuth authorization storage or session grant API. Positive/negative contract\ncases exercise real persistence rather than mocked SQL. Remote-provider outage\nis N/A: the service has no external identity/provider call. SDK owns malformed\nOAuth protocol, signature, PKCE and redirect parsing tests; hosts own their\nconsent UI, login return path and application-specific workspace policy.\n\n### Recoverable local SQLite connections\n\nLocal libsql connections may be invalidated by the SQL adapter after a native\n`SQLITE_BUSY` failure. An instance-only storage adapter fails closed in this\ncase; it does not silently reconnect and discard connection settings.\nFor recoverable local multi-replica operation, supply `recoverDatabase`:\n\n```typescript\nconst storage = await SmrtOAuthAuthorizationStorage.create({\n db,\n recoverDatabase: async () => {\n const connection = await getDatabase({\n type: 'sqlite', url: configuredFileUrl, dbid: randomUUID(),\n });\n await connection.query('PRAGMA foreign_keys = ON');\n // Reapply any other application-required connection settings here.\n return connection;\n },\n});\n```\n\nThe factory is also used for the initial dedicated storage connection, keeping\nstorage recovery independent of a shared application/session connection. It\nmust return a migrated connection to the same database and restore every\nrequired PRAGMA, attachment, temporary table or other per-connection setting.\nIt must not create application schema. Known invalidated failures may be retried\nat most six times; ordinary storage failures propagate. PostgreSQL does not\nneed this factory. Connection ownership/disposal remains with the host factory.\n"
8480
+ "content": "# Hosted OAuth authorization\n\n`SmrtOAuthAuthorizationStorage` implements the protocol-neutral storage contract\nfrom `@happyvertical/auth/server`. Apply normal SMRT migrations before starting\nthe server. The six `users_oauth_*` models are sensitive and have no generated\nREST, MCP or CLI operations. Keep their tables on the private application\nconnection; public catalog roles must not read them.\n\n`SmrtOAuthAuthorizationService.create({ db, scopePermissions })` supplies the\nsession boundary. `approve(server, parsedRequest, sessionId)` loads the existing\nsession again, checks its active user and tenant membership, and records\nconsent for the requested scopes whose configured permissions the session holds\n(requested ∩ held, #5110). The stored grant, the SDK code, the token response\n`scope` (RFC 6749 section 3.3) and both tokens carry only that subset, passed by\napproving `{ ...request, scopes: granted }`; the SDK refresh path refuses any\nscope beyond the grant (`invalid_scope`); a role that lost a mapped permission\ngets the whole refresh refused (no partial clamp), so refresh never widens. A\nrequest with no `scope` parameter now yields `access_denied` (it used to store\nan empty grant). No held scope: `access_denied`. `refuseUnheldScopes: true`\nrestores all-or-nothing consent. `consentScopes()` and the `authorize` handler\nreport the narrowed `scopes` (and `requestedScopes` when different). Existing magic-link,\npassword and OIDC sessions work without a separate identity mapping. Parent\nsession validity and session permission ceilings are enforced by SessionService.\nUnmapped scopes are never granted. An empty permission mapping explicitly permits a\nscope for any valid session. OAuth does not grant super-admin bypass.\n\nPass `service.identity` to the SDK server. It revalidates the stored consent on\nboth code exchange and refresh. A permission loss denies the grant rather than\nsilently expanding or partially authorizing it. The consent-time permission\nsnapshot is an upper bound even if the host later changes its scope mapping.\n\nAfter `server.verifyAccessToken(token, resource)`, always call\n`service.validateAccessTokenClaims(payload)`. A non-null result is a server-only\nSessionContext whose permissions and permissionCeiling are limited to the\nverified token's mapped scopes. Do not serialize that context: it contains the\nsession credential. The JWT carries only a non-secret `smrt_grant_id`, subject,\nclient, tenant and scopes. JWT signature verification alone does not check live\nsession, user, tenant or consent revocation.\n\n`listGrants(sessionId)` returns safe account-settings projections.\n`revokeGrant(sessionId, grantId)` checks ownership and atomically revokes the\nconsent, outstanding codes, and all refresh descendants. Revoking or replaying a\nmanaged refresh token also revokes its consent, so existing access tokens fail\nthe live grant check. Repeating revocation is safe. A foreign grant returns false.\n\nThe `/sveltekit` export `createOAuthHandlers({ server, authorization,\ngetSessionId })` provides Fetch-compatible `authorize`, `consent`, `grants` and\n`protocol` handlers. The host renders consent, supplies its existing cookie\nlookup, and preserves a validated local return path through magic-link login.\nConsent POST requires an exact same-origin Origin header and `decision=approve`;\nrequested OAuth parameters remain on the authorization URL and are revalidated\nby the SDK. Grant revocation POST has the same origin check and takes `grantId`.\nAll account/consent responses use private, no-store. No handler authenticates a\nsession from OAuth client identity or accepts a browser-submitted user/tenant.\n\n## Client ID Metadata Documents (#5081)\n\nOpt-in, off by default, like `dynamicClientRegistration`. The SDK server\nresolves clients only through `storage.getClient`, so\n`createCimdAuthorizationServer({ ...sdkOptions, clientIdMetadataDocuments })`\n(`src/services/oauth-cimd.ts`) wraps the storage and subclasses the server to\nadd `client_id_metadata_document_supported: true` to RFC 8414 metadata. Without\nthe option it returns the plain SDK server: https client_ids stay unknown,\nnothing is fetched, nothing is advertised. `withClientIdMetadataDocuments`\ncomposes the same decorator onto a storage directly.\n\n- `allowClientOrigin(origin, clientId)` is REQUIRED; construction throws\n without it (there is no implicit allow-all; pass `() => true` explicitly).\n It runs on every request before the cache, so a policy change is immediate;\n a throw or non-`true` result denies.\n- client_id must be the canonical `https://` URL with a path, default port, no\n credentials/fragment/query/dot segments, and a public DNS-style host (literal IPs,\n single-label and `.local/.internal/.localhost`-style names are refused before\n any network I/O).\n- Fetch (`oauth-cimd-fetch.ts`): DNS resolved once, every address must be\n public (non-global-unicast IPv6, private/loopback/link-local/CGNAT/metadata\n IPv4 refused), connection pinned to the vetted address, redirects never\n followed, 5 s deadline covering DNS and the request (also enforced around any injected fetcher), 16 KiB cap, at most 8 concurrent cache-miss fetches (`maxConcurrentFetches`; excess is refused as unknown client, not failure-cached), `application/json` or `+json` only,\n identity encoding. content's `safe-remote-url` is not reused: users cannot\n depend on content (heavy graph, content dev-depends on users).\n- Document: `client_id` equals the URL; `redirect_uris` 1-10 https (loopback\n http only with `allowLoopbackRedirects`); the authorization request's\n `redirect_uri` must equal one entry exactly; `token_endpoint_auth_method`\n absent or `none`; any `client_secret*` rejects; grant/response types limited\n to `authorization_code`/`refresh_token`/`code`. Allowed scopes are the\n document's `scope` intersected with the server's (all server scopes if\n absent).\n- Cache: in-memory, honours `s-maxage`/`max-age`/`Age`, clamped to 60 s..24 h\n (so `no-store` still gets the floor, bounding outbound fetches), 1 h default,\n 30 s negative cache, 1000 entries, concurrent lookups share one fetch. It is\n per-process; replicas fetch independently.\n- Every failure is \"unknown client\" to the requester; `onRejected(clientId,\n reason)` is for operator logs only. Tests: `src/__tests__/oauth-cimd.test.ts`.\n\n## Transaction invariants\n\nCode consume uses a conditional write. Refresh rotation and revocation lock a\nstable family row before reading token state; locking the token being replaced\nalone would allow a concurrent revocation to miss an inserted descendant.\nManaged operations lock the consent row first, then the family. Replacement\ninsertion, old-token consume and replay revocation share one database executor.\nA failed insert rolls back consume. Revalidated scopes and claims are persisted\natomically before the SDK exposes the replacement. Undefined claims clear prior\nclaims. Narrowing cannot expand scopes, revive or modify a consumed token.\n\nRetry only transaction failures classified as SQLite contention or PostgreSQL\nserialization/deadlock, after adapter rollback, at most six retries. Never retry\nprotocol callbacks or other external effects. The database adapter must clean up\nfailed statements and support independent connections; a process-local mutex is\nnot a replica-safety mechanism.\n\n## Behavior-to-test contract (#3659)\n\nEvery row runs in `src/__tests__/oauth-authorization.test.ts` on Node >=26 with\nSQLite and real PostgreSQL. Commands:\n\n```sh\npnpm --filter @happyvertical/smrt-users exec vitest run src/__tests__/oauth-authorization.test.ts\nDATABASE_URL=postgres://postgres@127.0.0.1:55597/smrt_oauth pnpm --filter @happyvertical/smrt-users exec vitest run src/__tests__/oauth-authorization.test.ts\npnpm --filter @happyvertical/smrt-users typecheck\n```\n\n| Invariant / trigger | Positive | Negative / failure | Actor / context | Executor / external edge | Level |\n| --- | --- | --- | --- | --- | --- |\n| Register and consume code | Metadata survives new adapter; one concurrent winner | Wrong client, redirect, resource; expiry and replay | Registered client / subject | Independent DB connections; SDK code contract | Integration |\n| Rotate / replay refresh | One replacement | Reuse revokes every descendant | Same family across replicas | Stable family lock, same transaction | Integration |\n| Rotation rollback / revoke race | Retry after insertion failure works | Duplicate replacement aborts consume; revoke cannot miss descendant | Same family, simultaneous operations | Real rollback and independent executors | Integration |\n| Narrow replacement | Subset and replacement claims persist through subsequent rotation; undefined claims clear old claims | Expansion, hash mismatch, consumed/revoked token | Authenticated client / original family | SDK fail-closed narrowing contract, atomic locked update | Integration |\n| Explicit recovery factory | Recreates configured connection after invalidation | Instance-only fails closed; ordinary storage failure propagates | Storage owner / configured database | Injected failure boundary plus real independent-connection races | Unit + integration |\n| Access revocation | Another adapter sees it; repeats safe | Expired revocation no longer effective | Possessor of verified access token | Unique insert with conflict handling | Integration |\n| Consent/grant ownership | Own grant can list/revoke | Other subject, tenant, scope deny; no session bearer in projection | Owner A/B × grant A/B | Live session + consent reads; atomic cascade | Integration |\n| Live identity and ceiling | Current permission allows | Inactive user/membership, changed session ceiling, destroyed session | Active vs revoked context | SessionService and current RBAC | Integration |\n| Code/live revoke cascade | Valid code exchanges | Membership loss before exchange; refresh revoke kills access | Original subject/tenant | SDK revalidateConsent callback | Integration |\n| Scope narrowing (#5110) | Held subset in grant, token `scope`, consent data; full holder gets all; strict option refuses | Nothing held `access_denied`; refresh expansion `invalid_scope`; revoked grant | Role holding fewer permissions than requested | SDK `approve` with narrowed request | Integration |\n| Consent snapshot / tenant | Original mapped scope | Later permission mapping expansion; inactive tenant | Owner × current tenant | Stored upper bound plus live permission checks | Integration |\n| Layered session / expiry | Parent and child valid | Parent destroyed or child expired | Person session on device parent | Existing session controls | Integration |\n| Consent route | Same-origin explicit approval | Missing/foreign Origin, denial, revoked session | Browser session / untrusted POST | Fetch request and SDK parsing | Route + DB |\n\nThis is new functionality, so a base-regression comparison is N/A: base has no\nOAuth authorization storage or session grant API. Positive/negative contract\ncases exercise real persistence rather than mocked SQL. Remote-provider outage\nis N/A: the service has no external identity/provider call. SDK owns malformed\nOAuth protocol, signature, PKCE and redirect parsing tests; hosts own their\nconsent UI, login return path and application-specific workspace policy.\n\n### Recoverable local SQLite connections\n\nLocal libsql connections may be invalidated by the SQL adapter after a native\n`SQLITE_BUSY` failure. An instance-only storage adapter fails closed in this\ncase; it does not silently reconnect and discard connection settings.\nFor recoverable local multi-replica operation, supply `recoverDatabase`:\n\n```typescript\nconst storage = await SmrtOAuthAuthorizationStorage.create({\n db,\n recoverDatabase: async () => {\n const connection = await getDatabase({\n type: 'sqlite', url: configuredFileUrl, dbid: randomUUID(),\n });\n await connection.query('PRAGMA foreign_keys = ON');\n // Reapply any other application-required connection settings here.\n return connection;\n },\n});\n```\n\nThe factory is also used for the initial dedicated storage connection, keeping\nstorage recovery independent of a shared application/session connection. It\nmust return a migrated connection to the same database and restore every\nrequired PRAGMA, attachment, temporary table or other per-connection setting.\nIt must not create application schema. Known invalidated failures may be retried\nat most six times; ordinary storage failures propagate. PostgreSQL does not\nneed this factory. Connection ownership/disposal remains with the host factory.\n"
8479
8481
  },
8480
8482
  {
8481
8483
  "path": "agents/service-principals.md",
@@ -5,10 +5,10 @@ description: "Multi-tenant user management for the SMRT framework - users, tenan
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-20T00:35:42Z"
8
+ at: "2026-11-23T17:57:32Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:3f79fe2561160036e71872b5450f3ee8663848f0faed84f17aa1fc3ec690be4d"
11
+ source_revision: "sha256:a66a4907c7ceadf06c8039bb2a04a786e77ccc3ecf50aa596de3b2c4b46fcbf8"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/package.json"
@@ -88,6 +88,8 @@ sources:
88
88
  - `./operator`
89
89
  - `./permission-registry`
90
90
  - `./playground`
91
+ - `./postgres-policies`
92
+ - `./postgres-settings`
91
93
  - `./step-up`
92
94
  - `./svelte`
93
95
  - `./sveltekit`
@@ -14,7 +14,7 @@ export interface OAuthHandlerOptions<Event extends OAuthHandlerEvent> {
14
14
  }
15
15
  /** Helpers for /authorize, consent POST and account grant management; no UI assumptions. */
16
16
  export declare function createOAuthHandlers<Event extends OAuthHandlerEvent>(options: OAuthHandlerOptions<Event>): {
17
- /** Return validated scope/client information for the host's consent page. */
17
+ /** Validated client info for the consent page; `scopes` is what consent would grant. */
18
18
  authorize: (event: Event) => Promise<Response>;
19
19
  /** A successful POST requires same-origin explicit approval and a fresh session. */
20
20
  consent: (event: Event) => Promise<Response>;
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-handlers.d.ts","sourceRoot":"","sources":["../../src/sveltekit/oauth-handlers.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,OAAO,EACL,KAAK,wBAAwB,EAE9B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,0CAA0C,CAAC;AAE9F,uFAAuF;AACvF,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,CAAC;IACjB,GAAG,EAAE,GAAG,CAAC;CACV;AACD,yEAAyE;AACzE,MAAM,WAAW,mBAAmB,CAAC,KAAK,SAAS,iBAAiB;IAClE,MAAM,EAAE,wBAAwB,CAAC;IACjC,aAAa,EAAE,6BAA6B,CAAC;IAC7C,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;CACpE;AA8BD,4FAA4F;AAC5F,wBAAgB,mBAAmB,CAAC,KAAK,SAAS,iBAAiB,EACjE,OAAO,EAAE,mBAAmB,CAAC,KAAK,CAAC;IASjC,6EAA6E;uBAC1D,KAAK;IAUxB,oFAAoF;qBACnE,KAAK;oBA6BN,KAAK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