@happyvertical/smrt-users 0.62.3 → 0.62.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +1 -0
- package/README.md +24 -1
- package/agents/oauth-authorization.md +39 -0
- package/agents/permissions.md +13 -0
- package/dist/chunks/{TerminalAuthService-D0U2N9LK.js → TerminalAuthService-CN6XV6nH.js} +8 -5
- package/dist/chunks/{TerminalAuthService-D0U2N9LK.js.map → TerminalAuthService-CN6XV6nH.js.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +307 -5
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/services/SessionPermissionContext.d.ts +17 -0
- package/dist/services/SessionPermissionContext.d.ts.map +1 -1
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/oauth-cimd-fetch.d.ts +22 -0
- package/dist/services/oauth-cimd-fetch.d.ts.map +1 -0
- package/dist/services/oauth-cimd.d.ts +70 -0
- package/dist/services/oauth-cimd.d.ts.map +1 -0
- package/dist/smrt-knowledge.json +13 -7
- package/dist/smrt-knowledge.okf.md +9 -5
- package/dist/sveltekit.js +1 -1
- package/package.json +9 -9
package/dist/manifest.json
CHANGED
|
@@ -67,6 +67,16 @@ export interface PrincipalPermissionRuntimeOptions extends SmrtClassOptions {
|
|
|
67
67
|
postgresRls?: boolean;
|
|
68
68
|
/** Reuse an initialized resolver instead of creating one per call. */
|
|
69
69
|
resolver?: PermissionResolver;
|
|
70
|
+
/**
|
|
71
|
+
* Id of the session this principal run was bound from, when the host has
|
|
72
|
+
* one. **Server-set only** — never derive it from browser or user input.
|
|
73
|
+
* Surfaced verbatim as `context.sessionId` (default `null`); it is an
|
|
74
|
+
* UNVERIFIED label, not an authenticated session: it is never published to
|
|
75
|
+
* the `smrt.session_id` RLS GUC (which stays empty for principal runs) and
|
|
76
|
+
* never feeds permission resolution. No `session` object is
|
|
77
|
+
* loaded or fabricated: `context.session` stays `null`.
|
|
78
|
+
*/
|
|
79
|
+
sessionId?: string | null;
|
|
70
80
|
/** Tenant the principal acts within. `null` resolves to no permissions. */
|
|
71
81
|
tenantId: string | null;
|
|
72
82
|
/** The user whose live permissions bound this execution. */
|
|
@@ -77,6 +87,13 @@ declare global {
|
|
|
77
87
|
}
|
|
78
88
|
export declare function getCurrentSessionPermissionContext(): SessionPermissionRuntimeContext | undefined;
|
|
79
89
|
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;
|
|
80
97
|
export declare function withSessionPermissionContext<T>(options: SessionPermissionRuntimeOptions, fn: (context: SessionPermissionRuntimeContext) => Promise<T>): Promise<T>;
|
|
81
98
|
/**
|
|
82
99
|
* Run `fn` AS a bound principal — a `(userId, tenantId)` pair rather than a
|
|
@@ -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,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kB,CAAC;IAC9B;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,2EAA2E;IAC3E,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAC;CAChB;AAgBD,OAAO,CAAC,MAAM,CAAC;IAEb,IAAI,iCAAiC,EACjC,CAAC,MAAM,+BAA+B,GAAG,SAAS,CAAC,GACnD,SAAS,CAAC;CAMf;AAwBD,wBAAgB,kCAAkC,IAC9C,+BAA+B,GAC/B,SAAS,CAEZ;AAED,wBAAgB,wBAAwB,IAAI,iBAAiB,GAAG,SAAS,CAExE;AA2BD;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,IAAI,CAAC,+BAA+B,EAAE,SAAS,GAAG,WAAW,CAAC,GACtE,MAAM,CAER;AA6KD,wBAAsB,4BAA4B,CAAC,CAAC,EAClD,OAAO,EAAE,+BAA+B,EACxC,EAAE,EAAE,CAAC,OAAO,EAAE,+BAA+B,KAAK,OAAO,CAAC,CAAC,CAAC,GAC3D,OAAO,CAAC,CAAC,CAAC,CAmDZ;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,8BAA8B,CAAC,CAAC,EACpD,OAAO,EAAE,iCAAiC,EAC1C,EAAE,EAAE,CAAC,OAAO,EAAE,+BAA+B,KAAK,OAAO,CAAC,CAAC,CAAC,GAC3D,OAAO,CAAC,CAAC,CAAC,CAwEZ"}
|
package/dist/services/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export { SmrtOAuthAuthorizationService, type SmrtOAuthAuthorizationServiceOption
|
|
|
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';
|
|
16
|
+
export { type CimdAuthorizationServerOptions, type CimdFetcher, type CimdFetchResult, type CimdRejectionReason, type ClientIdMetadataDocumentOptions, createCimdAuthorizationServer, createSafeCimdFetcher, isBlockedAddress as isBlockedCimdAddress, isClientIdMetadataDocumentUrl, withClientIdMetadataDocuments, } from './oauth-cimd.js';
|
|
16
17
|
export { type BeginPasskeyRegistrationInput, DEFAULT_MAX_PASSKEYS_PER_USER, DEFAULT_PASSKEY_CHALLENGE_TTL_SECONDS, DEFAULT_PASSKEY_FRESH_AUTH_METHODS, DEFAULT_PASSKEY_FRESH_SESSION_SECONDS, DEFAULT_PASSKEY_MANAGE_PERMISSION, DEFAULT_PASSKEY_NAME, ensurePasskeyPermissionsRegistered, type FinishPasskeyRegistrationInput, type ListPasskeysInput, PASSKEY_CHALLENGE_TTL_CEILING_SECONDS, PASSKEY_FRESH_SESSION_CEILING_SECONDS, PASSKEY_FRESH_SESSION_FLOOR_SECONDS, PASSKEY_LOGIN_KIND, PASSKEY_MAX_PER_USER_CEILING, PASSKEY_NAME_MAX_LENGTH, PASSKEY_PERMISSION_DEFINITIONS, PASSKEY_SESSION_DATA_KEY, type PasskeyAuthenticationBegin, PasskeyCredentialError, PasskeyCredentialForbiddenError, PasskeyCredentialService, type PasskeyCredentialServiceOptions, PasskeyReauthenticationRequiredError, type PasskeyRegistrationBegin, PasskeyRegistrationError, type PasskeyRelyingPartyOptions, type PasskeySignInInput, type PasskeySignInResult, type PasskeySummary, type RemoveAllPasskeysInput, type RemovePasskeyInput, type RenamePasskeyInput, } from './PasskeyCredentialService.js';
|
|
17
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';
|
|
18
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';
|
|
@@ -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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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"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** A fully buffered, bounded response. Header names are lower-case. */
|
|
2
|
+
export interface CimdFetchResult {
|
|
3
|
+
status: number;
|
|
4
|
+
headers: Readonly<Record<string, string>>;
|
|
5
|
+
body: string;
|
|
6
|
+
}
|
|
7
|
+
/** Fetches one already syntax-validated client_id URL. Injectable for tests. */
|
|
8
|
+
export type CimdFetcher = (url: URL, limits: {
|
|
9
|
+
timeoutMs: number;
|
|
10
|
+
maxBytes: number;
|
|
11
|
+
}) => Promise<CimdFetchResult>;
|
|
12
|
+
export type ResolveHostname = (hostname: string) => Promise<{
|
|
13
|
+
address: string;
|
|
14
|
+
family?: number;
|
|
15
|
+
}[]>;
|
|
16
|
+
/** True for anything that is not a plain public unicast address. */
|
|
17
|
+
export declare function isBlockedAddress(address: string): boolean;
|
|
18
|
+
/** Default fetcher: DNS-pinned node:https, no redirects, bounded time and bytes. */
|
|
19
|
+
export declare function createSafeCimdFetcher(options?: {
|
|
20
|
+
resolveHostname?: ResolveHostname;
|
|
21
|
+
}): CimdFetcher;
|
|
22
|
+
//# sourceMappingURL=oauth-cimd-fetch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-cimd-fetch.d.ts","sourceRoot":"","sources":["../../src/services/oauth-cimd-fetch.ts"],"names":[],"mappings":"AAkBA,uEAAuE;AACvE,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC1C,IAAI,EAAE,MAAM,CAAC;CACd;AACD,gFAAgF;AAChF,MAAM,MAAM,WAAW,GAAG,CACxB,GAAG,EAAE,GAAG,EACR,MAAM,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,KAC5C,OAAO,CAAC,eAAe,CAAC,CAAC;AAC9B,MAAM,MAAM,eAAe,GAAG,CAC5B,QAAQ,EAAE,MAAM,KACb,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC,CAAC;AAkCrD,oEAAoE;AACpE,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAMzD;AAiBD,oFAAoF;AACpF,wBAAgB,qBAAqB,CACnC,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,eAAe,CAAA;CAAO,GAClD,WAAW,CA4Fb"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth Client ID Metadata Documents (CIMD, #5081): an HTTPS-URL `client_id`
|
|
3
|
+
* whose metadata the authorization server fetches instead of requiring prior
|
|
4
|
+
* registration. Opt-in like dynamic client registration; off by default.
|
|
5
|
+
*
|
|
6
|
+
* The SDK server resolves clients only through `storage.getClient`, so CIMD is
|
|
7
|
+
* a storage decorator plus a thin server subclass that advertises support in
|
|
8
|
+
* RFC 8414 metadata. Every failure resolves to "unknown client" (null) so the
|
|
9
|
+
* SDK answers uniformly and no fetch detail reaches the requester.
|
|
10
|
+
*/
|
|
11
|
+
import { OAuthAuthorizationServer, type OAuthAuthorizationServerOptions, type OAuthAuthorizationStorage } from '@happyvertical/auth/server';
|
|
12
|
+
import { type CimdFetcher } from './oauth-cimd-fetch.js';
|
|
13
|
+
export type { CimdFetcher, CimdFetchResult } from './oauth-cimd-fetch.js';
|
|
14
|
+
export { createSafeCimdFetcher, isBlockedAddress } from './oauth-cimd-fetch.js';
|
|
15
|
+
/** Why a CIMD client_id resolved to "unknown client"; for operator logging only. */
|
|
16
|
+
export type CimdRejectionReason = 'invalid_url' | 'origin_denied' | 'fetch_failed' | 'too_busy' | 'http_status' | 'content_type' | 'malformed_document' | 'invalid_document';
|
|
17
|
+
export interface ClientIdMetadataDocumentOptions {
|
|
18
|
+
/**
|
|
19
|
+
* REQUIRED app policy: which client origins may use CIMD. Called with the
|
|
20
|
+
* client_id's origin and the full URL on every request (never cached), so a
|
|
21
|
+
* policy change takes effect immediately. A throw or non-true result denies.
|
|
22
|
+
* To accept any HTTPS client, pass an explicit `() => true`; the host's
|
|
23
|
+
* consent screen is then the only gate. There is deliberately no implicit
|
|
24
|
+
* allow-all: enabling CIMD without a policy throws at construction.
|
|
25
|
+
*/
|
|
26
|
+
allowClientOrigin(origin: string, clientId: string): boolean | Promise<boolean>;
|
|
27
|
+
/** Replace the SSRF-guarded fetcher (tests, or an egress proxy). */
|
|
28
|
+
fetcher?: CimdFetcher;
|
|
29
|
+
/** Observability hook; never expose the reason to the requester. */
|
|
30
|
+
onRejected?(clientId: string, reason: CimdRejectionReason): void;
|
|
31
|
+
/** Fetch deadline. Default 5000. */
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/** Document size cap in bytes. Default 16384. */
|
|
34
|
+
maxBytes?: number;
|
|
35
|
+
/** Cache floor; also applies to no-store/no-cache/max-age=0. Default 60. */
|
|
36
|
+
minCacheSeconds?: number;
|
|
37
|
+
/** Cache ceiling. Default 86400. */
|
|
38
|
+
maxCacheSeconds?: number;
|
|
39
|
+
/** Used when the response carries no cache lifetime. Default 3600. */
|
|
40
|
+
defaultCacheSeconds?: number;
|
|
41
|
+
/** How long a failed lookup is remembered. Default 30. */
|
|
42
|
+
negativeCacheSeconds?: number;
|
|
43
|
+
/** Maximum simultaneous cache-miss fetches; excess are refused. Default 8. */
|
|
44
|
+
maxConcurrentFetches?: number;
|
|
45
|
+
/** Maximum cached documents (oldest evicted). Default 1000. */
|
|
46
|
+
maxCacheEntries?: number;
|
|
47
|
+
/** Clock seam for tests. */
|
|
48
|
+
now?: () => number;
|
|
49
|
+
}
|
|
50
|
+
/** True when a client_id should be resolved as a metadata document URL. */
|
|
51
|
+
export declare function isClientIdMetadataDocumentUrl(clientId: string): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Wrap `storage` so https:// client_ids resolve from their metadata document.
|
|
54
|
+
* Other client_ids pass through untouched; every other storage method does too.
|
|
55
|
+
*/
|
|
56
|
+
export declare function withClientIdMetadataDocuments(storage: OAuthAuthorizationStorage, settings: {
|
|
57
|
+
scopes: readonly string[];
|
|
58
|
+
allowLoopbackRedirects?: boolean;
|
|
59
|
+
} & ClientIdMetadataDocumentOptions): OAuthAuthorizationStorage;
|
|
60
|
+
/** SDK server options plus the opt-in CIMD block (absent = disabled). */
|
|
61
|
+
export interface CimdAuthorizationServerOptions extends OAuthAuthorizationServerOptions {
|
|
62
|
+
clientIdMetadataDocuments?: ClientIdMetadataDocumentOptions;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Create the SDK authorization server, optionally accepting Client ID Metadata
|
|
66
|
+
* Documents. Without `clientIdMetadataDocuments` this is exactly the SDK server:
|
|
67
|
+
* https:// client_ids stay unknown and nothing is fetched or advertised.
|
|
68
|
+
*/
|
|
69
|
+
export declare function createCimdAuthorizationServer(options: CimdAuthorizationServerOptions): OAuthAuthorizationServer;
|
|
70
|
+
//# sourceMappingURL=oauth-cimd.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-cimd.d.ts","sourceRoot":"","sources":["../../src/services/oauth-cimd.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAEL,wBAAwB,EACxB,KAAK,+BAA+B,EACpC,KAAK,yBAAyB,EAE/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,KAAK,WAAW,EAGjB,MAAM,uBAAuB,CAAC;AAE/B,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,EAAE,qB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AClC,GAAG,+BAA+B,GAClC,yBAAyB,CAoI3B;AAED,yEAAyE;AACzE,MAAM,WAAW,8BACf,SAAQ,+BAA+B;IACvC,yBAAyB,CAAC,EAAE,+BAA+B,CAAC;CAC7D;AAYD;;;;GAIG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,8BAA8B,GACtC,wBAAwB,CAY1B"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,18 +3,19 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-users",
|
|
6
|
-
"packageVersion": "0.62.
|
|
6
|
+
"packageVersion": "0.62.5",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
13
|
-
"moduleDoc:agents/permissions.md": "
|
|
10
|
+
"manifest": "63952e8dd18495c416d8ee8874e09a20e88ae010694c4aa013ce4f24f01e4e68",
|
|
11
|
+
"packageJson": "17d88ca275831ebc0d40595051d76b0301f658337dce25992d85cd2e0d3fd1c1",
|
|
12
|
+
"agents": "f78e7b59477d9fcfad466a3c2ab9cf3a541aad7ac0c5e9f8a35f66b5b22c6435",
|
|
13
|
+
"moduleDoc:agents/permissions.md": "e8c6c8aecdbac4b7371557008bbd9fae3f5ec3c86a7b4a84108012442b550068",
|
|
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
19
|
"moduleDoc:agents/retention.md": "fc6ed5443b154641bfe890a4de1213366d4b330ea1bb18ea9e0edfe605f45b02"
|
|
19
20
|
},
|
|
20
21
|
"exports": [
|
|
@@ -8335,12 +8336,12 @@
|
|
|
8335
8336
|
"polymorphicAssociations": 0,
|
|
8336
8337
|
"uuidColumns": 162
|
|
8337
8338
|
},
|
|
8338
|
-
"agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant identity, RBAC, hierarchical tenants, sessions, and SvelteKit auth.\n\n## Modules\n\nRead only the module relevant to the change; protocol and provisioning details\nare not prerequisites for unrelated user-package work.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/permission-registry.ts` | portable permission metadata registration; same root/service singleton, no authority grants | [agents/permissions.md](agents/permissions.md#portable-metadata-registry-4765) |\n| `src/services/PermissionResolver.ts` | permission precedence, inherited memberships, guards, RLS, role seeding | [agents/permissions.md](agents/permissions.md) |\n| `src/services/OidcLoginService.ts`, collections and OIDC handlers | identity reconciliation, transaction boundaries, migration readiness | [agents/oidc-provisioning.md](agents/oidc-provisioning.md) |\n| `src/services/MobileAuthService.ts` | mobile handshake, bearer sessions, bootstrap extension boundary | [agents/mobile-auth.md](agents/mobile-auth.md) |\n| `src/services/TerminalAuthService.ts`, `src/services/LoginAttemptLimiter.ts`, `src/collections/LoginAttemptCollection.ts` | terminal approval concurrency, shared login budget and lockout (#3273), retry-safe database fixtures | [agents/terminal-auth-testing.md](agents/terminal-auth-testing.md) |\n| `src/services/DeviceCredentialService.ts` | per-person PIN layered on a device session (#3276), verifier seam for other credential kinds | this file, \"Security boundaries\" |\n| `src/services/PasswordCredentialService.ts`, `src/sveltekit/password-handlers.ts` | email + password sign-in and password lifecycle (#3274); shared scrypt in `credential-hash.ts` | this file, \"Security boundaries\"; README \"Password sign-in\" |\n| `src/services/PasskeyCredentialService.ts`, `src/sveltekit/passkey-handlers.ts`, `src/svelte/passkey.ts` | passkey (WebAuthn) sign-in and passkey lifecycle (#3275); library does all verification | this file, \"Security boundaries\"; README \"Passkey sign-in\" |\n| `src/services/TenantInvitationService.ts`, `src/services/MailboxAuthenticationService.ts` | exact-role invitations, preserved identity, one-use generations and embedded transaction send budgets | [agents/family-invitations.md](agents/family-invitations.md) |\n| `src/retention.ts` | expired session/token/CLI-auth reaping and retention sweep wiring | [agents/retention.md](agents/retention.md) |\n\n## Models and authority\n\n- Users are global; tenant access comes through Membership (unique user/tenant).\n User email is normalized and globally unique through readonly nullable\n `emailKey`. `profileId` is a unique cross-package reference: at most one User\n owns each non-null Profile.\n- Tenant uses STI and a materialized hierarchy, maximum depth 10.\n `hierarchyPath`/`hierarchyLevel` are derived from `parentTenantId` by\n `Tenant.save()` on every save (any caller-supplied value is recomputed) and\n descendants are re-materialized when they change; never hand-maintain them.\n Legacy rows are backfilled with `smrt db:materialize-tenant-hierarchy`\n (`materializeTenantHierarchy()`). Tests that need a corrupt path must write it\n with raw SQL (#3036).\n- Role with `tenantId = null` is available to all tenants; `isSystem` prevents\n deletion. `inheritsToDescendants` is opt-in. Seed owner/admin/member/viewer\n through `RoleCollection.seedSystemRoles()` at application initialization.\n- Group roles apply only in their own tenant. Use `getGroupIdsForTenant()`,\n never cross-tenant `getGroupIds()`, for authorization.\n- Upward visibility is opt-in and read-only: `permissions.ancestorRead`\n ({ roles, collections, maxDepth? }) lets a DESCENDANT membership contribute\n declared `<collection>.read` at an ancestor, only when no membership resolved\n there, intersected with BOTH the role's own catalog grants and the\n principal's effective permissions in that descendant, and only for SYSTEM\n roles (a tenant-scoped role sharing a declared slug is ignored). Off by default, never\n write, never lateral, and never row visibility — sibling rows stay scoped by\n tenancy/RLS. Read the permissions module before changing it.\n- Membership DENY always wins. Direct inactive membership blocks inherited\n authority; a direct active membership pins resolution instead of unioning it\n with ancestors. Read the permissions module before changing these rules.\n- AccessRequest has no generated API/MCP/CLI operations; access it through\n `AccessRequestService`. Its JSON field is `requestContext`, not reserved\n slug-scoping `context`.\n\n## Security boundaries\n\n- Generated REST/MCP operations on identity/RBAC models are list/get only.\n Route authentication does not authorize authority mutations, and these models\n are not tenant-scoped. Use permission-gated services or explicitly checked\n consumer handlers. Generated CLI is list/get or closed (`cli: false` for\n credential/grant models) because agents shell out to it; a `cli` without\n `include` is full CRUD (#3742). Their catalog slugs stay full via\n `USERS_AUTHORITY_CATALOG_MODELS`. Preserve the registry assertions in\n `security-audit-1400.test.ts` and `issue-3742-cli-surface-lockdown.test.ts`.\n- Resource guards take the resource tenant, not the session tenant. Omit a\n session membership when targeting a different tenant; mismatches fail closed.\n `loadSessionContext().tenantAuthorization` must be checked by required-tenant\n consumers: null membership can represent inherited authority.\n- Sessions use secure UUIDs; TTL is seconds (default seven days). Access marks\n expired sessions EXPIRED. Magic-link tokens are single use.\n- `Session.authMethod` is server-set at mint time and never read from the\n client; every mint site in this package sets it. A session with\n `parentSessionId` is valid only while its parent validates\n (`loadSessionContext` enforces this; there is no FK cascade by design), may\n not switch to a tenant other than the parent's, and is revoked with its\n parent by `destroySession`.\n- Credential sign-ins reserve through `LoginAttemptLimiter` BEFORE credential\n work and key the subject on the submitted identifier, never a resolved user,\n so unknown and wrong take the same path. Reservations are fail-closed: keep\n them on failure, release on success or abort, never skip the reserve.\n Limiter writes are raw SQL and bypass the change feed; the audit sink is the\n observability seam, and it must never throw into the sign-in path.\n Subject and source budgets are sized independently (#3531); `source: false`\n ignores the source key, so a reservation then needs a subject (fail closed).\n The `source-locked` audit entry never carries a subject or caller metadata.\n- `DeviceCredentialService` accepts a person credential only from a\n first-class session whose `authMethod` is a device-enrollment method\n (`terminal` by default) and that the host's `assertEnrolledDevice` confirms.\n A layered or PIN session can never administer PINs regardless of\n permissions. PIN hashes carry a per-row salt and the configured pepper;\n treat an unset pepper as a production misconfiguration.\n- A person session carries the PERSON's authority (resolved from their own\n membership on every load), never the device account's. `Session.data` keys\n in `SESSION_DATA_KEYS` are server-set controls enforced by the model:\n `permissionCeiling` only ever intersects (malformed fails closed to none)\n and suppresses `superAdminBypass`/`systemContext`; `absoluteExpiresAt`\n bounds `extend()` and `isValid()`; `idleSeconds` overrides the resolving\n service's TTL policy. Never write them from client input. The ceiling is a\n sign-in snapshot; `singleOccupant` revokes other children only AFTER a\n successful mint. A `mustReset` sign-in mints with an empty ceiling and\n `setPin` ends that session; do not grant it authority another way.\n- `UsersPasswordCredential` is one row per person, sensitive, with no\n generated surface; `PasswordCredentialService` and its handlers are its only\n session-authorized read/write paths. The separate Node `./operator` entrypoint\n provisions new PostgreSQL owners from trusted database custody, atomically;\n never mount it in a browser/REST/MCP handler. Exact retries verify existing\n credentials without writes; partial/conflicting identities fail closed.\n See README \"Trusted deployment owner provisioning\".\n Sign-in normalizes the email like `emailKey`, reserves\n before work, always runs one scrypt verify (dummy hash when absent), never\n creates a user, and maps every non-rate-limit refusal to one\n `PasswordCredentialError`. It re-checks the credential after the mint (a\n rehash that keeps row and version is confirmed by re-verifying); the\n parameter-upgrade write is a guarded UPDATE that must never replace a\n rotated password, and verification against a weaker stored hash is padded\n to the policy's scrypt cost. Self-service writes are guarded on the proven\n credential (first set insert-only); session sweeps run before and after\n each write. Self-service needs the current password except for a first\n set; `users.password.manage` follows the PIN's single-tenant target\n rule and never resets the actor's own. Layered sessions never manage\n passwords; a `mustChange` sign-in mints an empty ceiling.\n `replaceForgottenPassword` (#3905, opt-in `recovery`) is the only\n self-service write without the current password: it decides on the stored\n session row (owner, first-class, no ceiling, listed non-password/pin\n `authMethod`, fresh `outOfBandProofAt` stamp) and ends every session,\n its own included. Never set that stamp from client input.\n- `UsersPasskeyCredential` (many per person) and `UsersPasskeyChallenge` (consumed\n challenge ledger) are sensitive with no generated surface;\n `PasskeyCredentialService` and its handlers are the only paths. Verification is\n `@simplewebauthn/server`, loaded on first use (its `reflect-metadata` polyfill is process-wide) and external in the build; never hand-roll COSE/CBOR. Sign-in reserves on\n the submitted credential id before any work, requires user verification, checks\n user handle and a strictly advancing counter (`reason: 'counter'`), mints, then\n re-checks with a guarded counter UPDATE; a ceremony is an HMAC-signed\n `ceremonyId` consumed into the unique ledger (replay = refuse; set\n `challengeSecret` for multi-process). Unique arbiters are\n `INSERT … ON CONFLICT DO NOTHING`, never a caught constraint error. Register and\n self-remove need a session authenticated within `freshSessionSeconds`, decided\n on the stored row (`Session.getAuthenticatedAt()`: server-set\n `data.authenticatedAt`, which tenant-switch rotation carries forward, else\n `created_at`; malformed fails closed; `setSessionData` refuses the key),\n first-class, no ceiling, and its STORED `authMethod` in `freshAuthMethods` (default password/passkey/oidc/magic-link; never `terminal`, whose approval mints a fresh session for any holder of a stale one, nor `pin`); self list/rename also refuse a ceiling; `users.passkey.manage` follows the PIN's\n single-tenant rule, and `removeAllPasskeys` is admin-only, never self. Sessions\n end before and after every removal; `SESSION_DATA_KEYS.passkeyCredentialId` is\n server-set (`setSessionData` refuses it). State-changing handlers require\n `application/json` (415). Challenge rows are reaped only 10 minutes past expiry\n (clock skew).\n- Step-up (#4841, `src/step-up.ts`, subpath `./step-up`): `requireRecentAuthentication`\n decides on `SessionContext.reauthenticatedAt`, derived from the stored row:\n `data.reauthenticatedAt` (server-set through `SessionCollection.markReauthenticated`\n only after a deliberate fresh authentication; `setSessionData` refuses it;\n extend/activity never move it) or the sign-in time of a password or passkey\n session only (`STEP_UP_SIGN_IN_AUTH_METHODS` = `password`, `passkey`; an OIDC\n or magic-link SIGN-IN, `terminal`, `pin`, `mobile` never count: an unlocked\n stolen device can complete them without the person). Rule: an EXISTING\n session never counts as fresh by itself; a DELIBERATE fresh authentication\n with any supported method does, so an OIDC-only or magic-link-only owner can\n still step up. Methods, all stamping the EXISTING session (never minting one),\n all refusing layered/PIN/ceilinged sessions (`Session.isStepUpEligible`):\n `PasswordCredentialService.stepUp` (limiter-guarded password check);\n `OidcLoginService.beginStepUp`/`completeStepUp` (authorization request with\n `prompt=login` + `max_age=0`; the transaction is stored on the session as\n `data.oidcStepUpIntent`, taken at the callback so it is single use; the ID\n token must verify as at sign-in AND carry `auth_time` inside the window, not\n before the intent started, not future; its issuer+subject must be an existing\n `OidcIdentity` of the session user's own profile; a provider that omits\n `auth_time` or ignores `prompt`/`max_age` is refused);\n `MagicLinkService.requestStepUp`/`consumeStepUp` (token claim `purpose:\n step_up` + session digest + user id, TTL <= 300 s, single use; `verify` and\n `inspect` refuse it so it cannot sign in; `consumeStepUp` refuses a link\n without that purpose). Every step-up refusal is one `StepUpRequiredError`\n (`step_up_required`) that does not say which check failed. A passkey owner\n re-authenticates with a fresh passkey sign-in. Keep the entry free of\n side-effect imports.\n- A layered session whose tenant differs from its parent's never loads (null\n is allowed: narrower). Limiter rows carry `retain_until`; retention must\n not fall back to a process-wide horizon.\n- `Session.parentSessionId` is the parent's bearer: sensitive, never a\n `list()` filter (raw-SQL id reads, which also keep revocation sweeps free of\n caller list bounds), never serialized to clients. `users.pin.manage` reaches\n only people whose every active membership is in the actor's tenant (the PIN\n is global per person). A sign-in re-checks the verified\n credential generation AFTER the mint (`stillValid`); keep that ordering.\n Operation guards deny outside a session's ceiling; `loadPersonSession`\n re-checks device enrollment.\n- Tenant switching verifies active membership before writing and rotates the\n session ID for non-null targets, revoking the old session. Persist the returned\n `SwitchTenantResult.sessionId`; `switchSessionTenant()` updates the cookie and\n preserves its security settings. Failed switches mutate nothing; null clears\n do not rotate, and layered sessions never rotate (a replacement would escape\n the revocation sweeps they depend on). Layers do not nest. `SessionCollection.setSessionTenant()` is unguarded and must\n never receive an untrusted tenant ID.\n- OIDC provisioning is atomic and fail-closed. Preserve exact issuer/subject\n identifiers, claim-source email verification, unique global Person ownership,\n and transaction-bound reconciliation. Read the OIDC module and canonical\n scenario matrix before changing any provisioning path.\n\n## Entry points and validation\n\n`src/sveltekit/` owns `createSessionHandler`, `createSessionCookie`,\n`destroySessionCookie`, and `switchSessionTenant`. Use README integration examples\nrather than copying application setup into these instructions.\n\nFrom the repository root:\n\n```bash\npnpm --filter @happyvertical/smrt-users test\npnpm --filter @happyvertical/smrt-users typecheck\npnpm --filter @happyvertical/smrt-users test:postgres\n```\n\nStart with the relevant test file via `test -- src/__tests__/<file>.test.ts`.\nRun `test:postgres` for RLS, principal context, OIDC, or terminal-auth database\nchanges. `typecheck` includes Svelte accessibility checks; plain `tsc` is\ninsufficient. The typecheck configs read workspace package sources, while\n`tsconfig.svelte.json` is used to package Svelte declarations. Follow root\nknowledge freshness checks before shipping.\n\n## Pending invitations\n\n`TenantInvitationService.create({ db: tx, transaction: 'caller' }).prepare({\ntenantId, email, roleSlug })` is a trusted host integration seam. The caller\nmust authorize the destination tenant and system role, serialize its invitation\nscope, and own the entire transaction. It prepares only pending User and\nMembership records, with a canonical global Person and email reservation;\nit never proves email ownership, activates access, sends email, or mints login\ncredentials. Existing canonical User/Profile links remain unchanged; unowned\nsame-email Profiles require explicit reconciliation. Pending retries reuse rows,\nactive memberships remain active with their existing role, and inactive or\nconflicting memberships fail closed. Caller failures must roll back the whole\ntransaction; retry identity uniqueness conflicts only after rollback. Run the\nprofile/user email-key backfills before using this service.\n\n`issue({ membershipId })` requires the host to authorize that exact destination\nand returns a signed single-use `{ membershipId, token, expiresAt }`; secure\ndelivery is the host’s responsibility (no email is sent). Configure `secret` and\noptional `tokenExpiry` (1–604800 seconds, default one day) at service creation.\n`accept({ membershipId, token, sessionId, expectedUserId? })` consumes the tenant\ngrant only after validating an independently authenticated, active exact User's\nstored first-class OIDC, magic-link, password or passkey session. Layered,\npermission-ceiling, terminal and unknown sessions fail closed. It activates only\nthe Membership; reuse/switch that session through canonical session APIs.\nNever mint global identity sessions from an operator-copyable invitation.\n\nFor a new pending User, wire `authorizeOidcOwner(context, { membershipId, token })`\nonly into the canonical protocol-verified OIDC `authorizeProfileOwner` callback.\nIt requires the exact caller transaction, strict `email_verified: true` and the\nexact canonical invitee email, consumes the grant and activates pending User\nand Membership atomically before returning `{ profile, user, tenantId, membershipId }`.\nArbitrary claims must never reach this trusted callback seam. The canonical\nbinder still verifies ownership and issuer/subject authority before commit.\nThe signed scope fixes user, profile, tenant, membership and role; expiration,\nreplay, changed bindings, inactive membership and suspended users fail closed.\nNonce consumption and activation roll back together. `TenantInvitationError`\nis an expected 400/403 refusal;\n`MagicLinkError` represents invalid, expired or replayed proof. Database failures\nremain distinct. Treat tokens as secrets, prefer URL fragments and POST bodies,\nand never log or persist a copy outside the canonical token ledger.\n\n\n## Independent emailed mailbox authentication\n\n`MailboxAuthenticationService.create({db:tx,transaction:'caller',secret,loginLimiter})`\nrequests and verifies returning-client login without creating identities/sessions.\n`request({email,sourceKey,deliver})` returns only `{requested:true}` for known,\nunknown, malformed, pending, inactive or unauthorized accounts. The trusted server\n`deliver({email,token,expiresAt})` callback sends only to the eligible canonical\nactive User's email; never expose a proof in HTTP responses/operator UI/logs,\nincluding development. Ten-minute one-use proofs bind immutable User/Profile ids.\n`authenticate({token,expectedUserId?,sessionId?})` rechecks canonical identity and\nactive tenant membership before consuming proof; returns only verified\n`{userId,profileId,tenantId}` for the host's canonical magic-link session mint.\nExisting signed-in identity must match; supplied sessions cannot have a parent,\npermission ceiling, terminal/PIN/unknown method, or inactive principal.\n\nFor pending invitation onboarding, `requestMailboxAuthentication({membershipId,\ntoken:projectGrant,sourceKey,deliver})` inspects but never consumes the signed\nproject grant, then delivers a DIFFERENT mailbox proof to the fixed invitee.\nOnly `{expiresAt}` is returned. `authenticateMailbox({membershipId,\ninvitationToken:projectGrant,token:mailedProof,expectedUserId?,sessionId?})` claims\nBOTH proof nonces and activates pending canonical User/exact Membership in the\nsame caller transaction. Mailbox proof issuer binds all invitation ids, role and\nSHA256 of the exact grant. A copied operator-visible grant cannot authenticate\nidentity. Repeated email requests do not burn the grant; only the first completed\nauthentication can claim it. Existing active-session/OIDC paths remain supported.\n\nAll refusals/caller failures must roll back the whole caller transaction. Mail\ntransport must reject on failure. Delivery is an external effect before commit:\na successfully delivered but rolled-back proof is unusable; retry may send another\nmail. No session/authentication is valid without committed proof claims. The host\nmust set a bounded transport timeout and never return transport payloads/secrets.\nNo generic outbox/provider is required; compose the existing SDK email transport.\n\nBoth mail request operations REQUIRE a root-executor canonical\n`LoginAttemptLimiter` passed as `loginLimiter`; missing limiters fail before\nnonce/budget writes or delivery. Completion-only operations may omit it. Supply\nthe limiter independently from the caller transaction so\ncaller rollbacks cannot release send budgets (SQLite single-connection fixtures\ncannot prove that production-pool separation). `sourceKey` is a trusted server\nclient-address key, never request-controlled forwarded headers; limiter hashes\nand peppers it, never stores raw addresses/email. Each request retains its budget\nthrough window expiry via `retainOnSuccess`, regardless of account eligibility.\nHandle `LoginRateLimitError` with the same generic request response plus retry\npolicy. Returning request has a 250ms response floor; delivery latency remains\ntransport-dependent, so do not claim constant timing. Malformed/expired/replayed\nproofs raise `MagicLinkError`; invitation binding/status refusals also use\n`TenantInvitationError`. Database/transport faults remain distinguishable server\nfailures. Never swallow an error and commit a partially consumed transaction.\n\n`MagicLinkService.inspect()` validates signed live nonce without claiming it;\nit is preparation, never authentication. `verify()` remains the atomic claim.\nOptional generated signed `subject` binds immutable identity; legacy callers\nwithout a subject retain their existing result shape.\n\nFocused matrix: `mailbox-authentication.test.ts` runs in memory SQLite by default;\n`TEST_DB_ADAPTER=postgres` plus an explicit isolated `DATABASE_URL` creates a unique\nschema per scenario and also exercises concurrent invitation/login proof claims.\nIt is registered in `test:postgres`; no shared local service fallback is used.\n",
|
|
8339
|
+
"agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant identity, RBAC, hierarchical tenants, sessions, and SvelteKit auth.\n\n## Modules\n\nRead only the module relevant to the change; protocol and provisioning details\nare not prerequisites for unrelated user-package work.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/permission-registry.ts` | portable permission metadata registration; same root/service singleton, no authority grants | [agents/permissions.md](agents/permissions.md#portable-metadata-registry-4765) |\n| `src/services/PermissionResolver.ts` | permission precedence, inherited memberships, guards, RLS, role seeding | [agents/permissions.md](agents/permissions.md) |\n| `src/services/OidcLoginService.ts`, collections and OIDC handlers | identity reconciliation, transaction boundaries, migration readiness | [agents/oidc-provisioning.md](agents/oidc-provisioning.md) |\n| `src/services/MobileAuthService.ts` | mobile handshake, bearer sessions, bootstrap extension boundary | [agents/mobile-auth.md](agents/mobile-auth.md) |\n| `src/services/TerminalAuthService.ts`, `src/services/LoginAttemptLimiter.ts`, `src/collections/LoginAttemptCollection.ts` | terminal approval concurrency, shared login budget and lockout (#3273), retry-safe database fixtures | [agents/terminal-auth-testing.md](agents/terminal-auth-testing.md) |\n| `src/services/DeviceCredentialService.ts` | per-person PIN layered on a device session (#3276), verifier seam for other credential kinds | this file, \"Security boundaries\" |\n| `src/services/PasswordCredentialService.ts`, `src/sveltekit/password-handlers.ts` | email + password sign-in and password lifecycle (#3274); shared scrypt in `credential-hash.ts` | this file, \"Security boundaries\"; README \"Password sign-in\" |\n| `src/services/PasskeyCredentialService.ts`, `src/sveltekit/passkey-handlers.ts`, `src/svelte/passkey.ts` | passkey (WebAuthn) sign-in and passkey lifecycle (#3275); library does all verification | this file, \"Security boundaries\"; README \"Passkey sign-in\" |\n| `src/services/TenantInvitationService.ts`, `src/services/MailboxAuthenticationService.ts` | exact-role invitations, preserved identity, one-use generations and embedded transaction send budgets | [agents/family-invitations.md](agents/family-invitations.md) |\n| `src/services/oauth-cimd.ts`, `src/services/oauth-cimd-fetch.ts` | opt-in Client ID Metadata Documents for the SDK OAuth server (#5081): required origin policy, SSRF-pinned fetch, cache | [agents/oauth-authorization.md](agents/oauth-authorization.md#client-id-metadata-documents-5081) |\n| `src/retention.ts` | expired session/token/CLI-auth reaping and retention sweep wiring | [agents/retention.md](agents/retention.md) |\n\n## Models and authority\n\n- Users are global; tenant access comes through Membership (unique user/tenant).\n User email is normalized and globally unique through readonly nullable\n `emailKey`. `profileId` is a unique cross-package reference: at most one User\n owns each non-null Profile.\n- Tenant uses STI and a materialized hierarchy, maximum depth 10.\n `hierarchyPath`/`hierarchyLevel` are derived from `parentTenantId` by\n `Tenant.save()` on every save (any caller-supplied value is recomputed) and\n descendants are re-materialized when they change; never hand-maintain them.\n Legacy rows are backfilled with `smrt db:materialize-tenant-hierarchy`\n (`materializeTenantHierarchy()`). Tests that need a corrupt path must write it\n with raw SQL (#3036).\n- Role with `tenantId = null` is available to all tenants; `isSystem` prevents\n deletion. `inheritsToDescendants` is opt-in. Seed owner/admin/member/viewer\n through `RoleCollection.seedSystemRoles()` at application initialization.\n- Group roles apply only in their own tenant. Use `getGroupIdsForTenant()`,\n never cross-tenant `getGroupIds()`, for authorization.\n- Upward visibility is opt-in and read-only: `permissions.ancestorRead`\n ({ roles, collections, maxDepth? }) lets a DESCENDANT membership contribute\n declared `<collection>.read` at an ancestor, only when no membership resolved\n there, intersected with BOTH the role's own catalog grants and the\n principal's effective permissions in that descendant, and only for SYSTEM\n roles (a tenant-scoped role sharing a declared slug is ignored). Off by default, never\n write, never lateral, and never row visibility — sibling rows stay scoped by\n tenancy/RLS. Read the permissions module before changing it.\n- Membership DENY always wins. Direct inactive membership blocks inherited\n authority; a direct active membership pins resolution instead of unioning it\n with ancestors. Read the permissions module before changing these rules.\n- AccessRequest has no generated API/MCP/CLI operations; access it through\n `AccessRequestService`. Its JSON field is `requestContext`, not reserved\n slug-scoping `context`.\n\n## Security boundaries\n\n- Generated REST/MCP operations on identity/RBAC models are list/get only.\n Route authentication does not authorize authority mutations, and these models\n are not tenant-scoped. Use permission-gated services or explicitly checked\n consumer handlers. Generated CLI is list/get or closed (`cli: false` for\n credential/grant models) because agents shell out to it; a `cli` without\n `include` is full CRUD (#3742). Their catalog slugs stay full via\n `USERS_AUTHORITY_CATALOG_MODELS`. Preserve the registry assertions in\n `security-audit-1400.test.ts` and `issue-3742-cli-surface-lockdown.test.ts`.\n- Resource guards take the resource tenant, not the session tenant. Omit a\n session membership when targeting a different tenant; mismatches fail closed.\n `loadSessionContext().tenantAuthorization` must be checked by required-tenant\n consumers: null membership can represent inherited authority.\n- Sessions use secure UUIDs; TTL is seconds (default seven days). Access marks\n expired sessions EXPIRED. Magic-link tokens are single use.\n- `Session.authMethod` is server-set at mint time and never read from the\n client; every mint site in this package sets it. A session with\n `parentSessionId` is valid only while its parent validates\n (`loadSessionContext` enforces this; there is no FK cascade by design), may\n not switch to a tenant other than the parent's, and is revoked with its\n parent by `destroySession`.\n- Credential sign-ins reserve through `LoginAttemptLimiter` BEFORE credential\n work and key the subject on the submitted identifier, never a resolved user,\n so unknown and wrong take the same path. Reservations are fail-closed: keep\n them on failure, release on success or abort, never skip the reserve.\n Limiter writes are raw SQL and bypass the change feed; the audit sink is the\n observability seam, and it must never throw into the sign-in path.\n Subject and source budgets are sized independently (#3531); `source: false`\n ignores the source key, so a reservation then needs a subject (fail closed).\n The `source-locked` audit entry never carries a subject or caller metadata.\n- `DeviceCredentialService` accepts a person credential only from a\n first-class session whose `authMethod` is a device-enrollment method\n (`terminal` by default) and that the host's `assertEnrolledDevice` confirms.\n A layered or PIN session can never administer PINs regardless of\n permissions. PIN hashes carry a per-row salt and the configured pepper;\n treat an unset pepper as a production misconfiguration.\n- A person session carries the PERSON's authority (resolved from their own\n membership on every load), never the device account's. `Session.data` keys\n in `SESSION_DATA_KEYS` are server-set controls enforced by the model:\n `permissionCeiling` only ever intersects (malformed fails closed to none)\n and suppresses `superAdminBypass`/`systemContext`; `absoluteExpiresAt`\n bounds `extend()` and `isValid()`; `idleSeconds` overrides the resolving\n service's TTL policy. Never write them from client input. The ceiling is a\n sign-in snapshot; `singleOccupant` revokes other children only AFTER a\n successful mint. A `mustReset` sign-in mints with an empty ceiling and\n `setPin` ends that session; do not grant it authority another way.\n- `UsersPasswordCredential` is one row per person, sensitive, with no\n generated surface; `PasswordCredentialService` and its handlers are its only\n session-authorized read/write paths. The separate Node `./operator` entrypoint\n provisions new PostgreSQL owners from trusted database custody, atomically;\n never mount it in a browser/REST/MCP handler. Exact retries verify existing\n credentials without writes; partial/conflicting identities fail closed.\n See README \"Trusted deployment owner provisioning\".\n Sign-in normalizes the email like `emailKey`, reserves\n before work, always runs one scrypt verify (dummy hash when absent), never\n creates a user, and maps every non-rate-limit refusal to one\n `PasswordCredentialError`. It re-checks the credential after the mint (a\n rehash that keeps row and version is confirmed by re-verifying); the\n parameter-upgrade write is a guarded UPDATE that must never replace a\n rotated password, and verification against a weaker stored hash is padded\n to the policy's scrypt cost. Self-service writes are guarded on the proven\n credential (first set insert-only); session sweeps run before and after\n each write. Self-service needs the current password except for a first\n set; `users.password.manage` follows the PIN's single-tenant target\n rule and never resets the actor's own. Layered sessions never manage\n passwords; a `mustChange` sign-in mints an empty ceiling.\n `replaceForgottenPassword` (#3905, opt-in `recovery`) is the only\n self-service write without the current password: it decides on the stored\n session row (owner, first-class, no ceiling, listed non-password/pin\n `authMethod`, fresh `outOfBandProofAt` stamp) and ends every session,\n its own included. Never set that stamp from client input.\n- `UsersPasskeyCredential` (many per person) and `UsersPasskeyChallenge` (consumed\n challenge ledger) are sensitive with no generated surface;\n `PasskeyCredentialService` and its handlers are the only paths. Verification is\n `@simplewebauthn/server`, loaded on first use (its `reflect-metadata` polyfill is process-wide) and external in the build; never hand-roll COSE/CBOR. Sign-in reserves on\n the submitted credential id before any work, requires user verification, checks\n user handle and a strictly advancing counter (`reason: 'counter'`), mints, then\n re-checks with a guarded counter UPDATE; a ceremony is an HMAC-signed\n `ceremonyId` consumed into the unique ledger (replay = refuse; set\n `challengeSecret` for multi-process). Unique arbiters are\n `INSERT … ON CONFLICT DO NOTHING`, never a caught constraint error. Register and\n self-remove need a session authenticated within `freshSessionSeconds`, decided\n on the stored row (`Session.getAuthenticatedAt()`: server-set\n `data.authenticatedAt`, which tenant-switch rotation carries forward, else\n `created_at`; malformed fails closed; `setSessionData` refuses the key),\n first-class, no ceiling, and its STORED `authMethod` in `freshAuthMethods` (default password/passkey/oidc/magic-link; never `terminal`, whose approval mints a fresh session for any holder of a stale one, nor `pin`); self list/rename also refuse a ceiling; `users.passkey.manage` follows the PIN's\n single-tenant rule, and `removeAllPasskeys` is admin-only, never self. Sessions\n end before and after every removal; `SESSION_DATA_KEYS.passkeyCredentialId` is\n server-set (`setSessionData` refuses it). State-changing handlers require\n `application/json` (415). Challenge rows are reaped only 10 minutes past expiry\n (clock skew).\n- Step-up (#4841, `src/step-up.ts`, subpath `./step-up`): `requireRecentAuthentication`\n decides on `SessionContext.reauthenticatedAt`, derived from the stored row:\n `data.reauthenticatedAt` (server-set through `SessionCollection.markReauthenticated`\n only after a deliberate fresh authentication; `setSessionData` refuses it;\n extend/activity never move it) or the sign-in time of a password or passkey\n session only (`STEP_UP_SIGN_IN_AUTH_METHODS` = `password`, `passkey`; an OIDC\n or magic-link SIGN-IN, `terminal`, `pin`, `mobile` never count: an unlocked\n stolen device can complete them without the person). Rule: an EXISTING\n session never counts as fresh by itself; a DELIBERATE fresh authentication\n with any supported method does, so an OIDC-only or magic-link-only owner can\n still step up. Methods, all stamping the EXISTING session (never minting one),\n all refusing layered/PIN/ceilinged sessions (`Session.isStepUpEligible`):\n `PasswordCredentialService.stepUp` (limiter-guarded password check);\n `OidcLoginService.beginStepUp`/`completeStepUp` (authorization request with\n `prompt=login` + `max_age=0`; the transaction is stored on the session as\n `data.oidcStepUpIntent`, taken at the callback so it is single use; the ID\n token must verify as at sign-in AND carry `auth_time` inside the window, not\n before the intent started, not future; its issuer+subject must be an existing\n `OidcIdentity` of the session user's own profile; a provider that omits\n `auth_time` or ignores `prompt`/`max_age` is refused);\n `MagicLinkService.requestStepUp`/`consumeStepUp` (token claim `purpose:\n step_up` + session digest + user id, TTL <= 300 s, single use; `verify` and\n `inspect` refuse it so it cannot sign in; `consumeStepUp` refuses a link\n without that purpose). Every step-up refusal is one `StepUpRequiredError`\n (`step_up_required`) that does not say which check failed. A passkey owner\n re-authenticates with a fresh passkey sign-in. Keep the entry free of\n side-effect imports.\n- A layered session whose tenant differs from its parent's never loads (null\n is allowed: narrower). Limiter rows carry `retain_until`; retention must\n not fall back to a process-wide horizon.\n- `Session.parentSessionId` is the parent's bearer: sensitive, never a\n `list()` filter (raw-SQL id reads, which also keep revocation sweeps free of\n caller list bounds), never serialized to clients. `users.pin.manage` reaches\n only people whose every active membership is in the actor's tenant (the PIN\n is global per person). A sign-in re-checks the verified\n credential generation AFTER the mint (`stillValid`); keep that ordering.\n Operation guards deny outside a session's ceiling; `loadPersonSession`\n re-checks device enrollment.\n- Tenant switching verifies active membership before writing and rotates the\n session ID for non-null targets, revoking the old session. Persist the returned\n `SwitchTenantResult.sessionId`; `switchSessionTenant()` updates the cookie and\n preserves its security settings. Failed switches mutate nothing; null clears\n do not rotate, and layered sessions never rotate (a replacement would escape\n the revocation sweeps they depend on). Layers do not nest. `SessionCollection.setSessionTenant()` is unguarded and must\n never receive an untrusted tenant ID.\n- OIDC provisioning is atomic and fail-closed. Preserve exact issuer/subject\n identifiers, claim-source email verification, unique global Person ownership,\n and transaction-bound reconciliation. Read the OIDC module and canonical\n scenario matrix before changing any provisioning path.\n\n## Entry points and validation\n\n`src/sveltekit/` owns `createSessionHandler`, `createSessionCookie`,\n`destroySessionCookie`, and `switchSessionTenant`. Use README integration examples\nrather than copying application setup into these instructions.\n\nFrom the repository root:\n\n```bash\npnpm --filter @happyvertical/smrt-users test\npnpm --filter @happyvertical/smrt-users typecheck\npnpm --filter @happyvertical/smrt-users test:postgres\n```\n\nStart with the relevant test file via `test -- src/__tests__/<file>.test.ts`.\nRun `test:postgres` for RLS, principal context, OIDC, or terminal-auth database\nchanges. `typecheck` includes Svelte accessibility checks; plain `tsc` is\ninsufficient. The typecheck configs read workspace package sources, while\n`tsconfig.svelte.json` is used to package Svelte declarations. Follow root\nknowledge freshness checks before shipping.\n\n## Pending invitations\n\n`TenantInvitationService.create({ db: tx, transaction: 'caller' }).prepare({\ntenantId, email, roleSlug })` is a trusted host integration seam. The caller\nmust authorize the destination tenant and system role, serialize its invitation\nscope, and own the entire transaction. It prepares only pending User and\nMembership records, with a canonical global Person and email reservation;\nit never proves email ownership, activates access, sends email, or mints login\ncredentials. Existing canonical User/Profile links remain unchanged; unowned\nsame-email Profiles require explicit reconciliation. Pending retries reuse rows,\nactive memberships remain active with their existing role, and inactive or\nconflicting memberships fail closed. Caller failures must roll back the whole\ntransaction; retry identity uniqueness conflicts only after rollback. Run the\nprofile/user email-key backfills before using this service.\n\n`issue({ membershipId })` requires the host to authorize that exact destination\nand returns a signed single-use `{ membershipId, token, expiresAt }`; secure\ndelivery is the host’s responsibility (no email is sent). Configure `secret` and\noptional `tokenExpiry` (1–604800 seconds, default one day) at service creation.\n`accept({ membershipId, token, sessionId, expectedUserId? })` consumes the tenant\ngrant only after validating an independently authenticated, active exact User's\nstored first-class OIDC, magic-link, password or passkey session. Layered,\npermission-ceiling, terminal and unknown sessions fail closed. It activates only\nthe Membership; reuse/switch that session through canonical session APIs.\nNever mint global identity sessions from an operator-copyable invitation.\n\nFor a new pending User, wire `authorizeOidcOwner(context, { membershipId, token })`\nonly into the canonical protocol-verified OIDC `authorizeProfileOwner` callback.\nIt requires the exact caller transaction, strict `email_verified: true` and the\nexact canonical invitee email, consumes the grant and activates pending User\nand Membership atomically before returning `{ profile, user, tenantId, membershipId }`.\nArbitrary claims must never reach this trusted callback seam. The canonical\nbinder still verifies ownership and issuer/subject authority before commit.\nThe signed scope fixes user, profile, tenant, membership and role; expiration,\nreplay, changed bindings, inactive membership and suspended users fail closed.\nNonce consumption and activation roll back together. `TenantInvitationError`\nis an expected 400/403 refusal;\n`MagicLinkError` represents invalid, expired or replayed proof. Database failures\nremain distinct. Treat tokens as secrets, prefer URL fragments and POST bodies,\nand never log or persist a copy outside the canonical token ledger.\n\n\n## Independent emailed mailbox authentication\n\n`MailboxAuthenticationService.create({db:tx,transaction:'caller',secret,loginLimiter})`\nrequests and verifies returning-client login without creating identities/sessions.\n`request({email,sourceKey,deliver})` returns only `{requested:true}` for known,\nunknown, malformed, pending, inactive or unauthorized accounts. The trusted server\n`deliver({email,token,expiresAt})` callback sends only to the eligible canonical\nactive User's email; never expose a proof in HTTP responses/operator UI/logs,\nincluding development. Ten-minute one-use proofs bind immutable User/Profile ids.\n`authenticate({token,expectedUserId?,sessionId?})` rechecks canonical identity and\nactive tenant membership before consuming proof; returns only verified\n`{userId,profileId,tenantId}` for the host's canonical magic-link session mint.\nExisting signed-in identity must match; supplied sessions cannot have a parent,\npermission ceiling, terminal/PIN/unknown method, or inactive principal.\n\nFor pending invitation onboarding, `requestMailboxAuthentication({membershipId,\ntoken:projectGrant,sourceKey,deliver})` inspects but never consumes the signed\nproject grant, then delivers a DIFFERENT mailbox proof to the fixed invitee.\nOnly `{expiresAt}` is returned. `authenticateMailbox({membershipId,\ninvitationToken:projectGrant,token:mailedProof,expectedUserId?,sessionId?})` claims\nBOTH proof nonces and activates pending canonical User/exact Membership in the\nsame caller transaction. Mailbox proof issuer binds all invitation ids, role and\nSHA256 of the exact grant. A copied operator-visible grant cannot authenticate\nidentity. Repeated email requests do not burn the grant; only the first completed\nauthentication can claim it. Existing active-session/OIDC paths remain supported.\n\nAll refusals/caller failures must roll back the whole caller transaction. Mail\ntransport must reject on failure. Delivery is an external effect before commit:\na successfully delivered but rolled-back proof is unusable; retry may send another\nmail. No session/authentication is valid without committed proof claims. The host\nmust set a bounded transport timeout and never return transport payloads/secrets.\nNo generic outbox/provider is required; compose the existing SDK email transport.\n\nBoth mail request operations REQUIRE a root-executor canonical\n`LoginAttemptLimiter` passed as `loginLimiter`; missing limiters fail before\nnonce/budget writes or delivery. Completion-only operations may omit it. Supply\nthe limiter independently from the caller transaction so\ncaller rollbacks cannot release send budgets (SQLite single-connection fixtures\ncannot prove that production-pool separation). `sourceKey` is a trusted server\nclient-address key, never request-controlled forwarded headers; limiter hashes\nand peppers it, never stores raw addresses/email. Each request retains its budget\nthrough window expiry via `retainOnSuccess`, regardless of account eligibility.\nHandle `LoginRateLimitError` with the same generic request response plus retry\npolicy. Returning request has a 250ms response floor; delivery latency remains\ntransport-dependent, so do not claim constant timing. Malformed/expired/replayed\nproofs raise `MagicLinkError`; invitation binding/status refusals also use\n`TenantInvitationError`. Database/transport faults remain distinguishable server\nfailures. Never swallow an error and commit a partially consumed transaction.\n\n`MagicLinkService.inspect()` validates signed live nonce without claiming it;\nit is preparation, never authentication. `verify()` remains the atomic claim.\nOptional generated signed `subject` binds immutable identity; legacy callers\nwithout a subject retain their existing result shape.\n\nFocused matrix: `mailbox-authentication.test.ts` runs in memory SQLite by default;\n`TEST_DB_ADAPTER=postgres` plus an explicit isolated `DATABASE_URL` creates a unique\nschema per scenario and also exercises concurrent invitation/login proof claims.\nIt is registered in `test:postgres`; no shared local service fallback is used.\n",
|
|
8339
8340
|
"moduleDocs": [
|
|
8340
8341
|
{
|
|
8341
8342
|
"path": "agents/permissions.md",
|
|
8342
8343
|
"module": "permissions",
|
|
8343
|
-
"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"
|
|
8344
|
+
"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"
|
|
8344
8345
|
},
|
|
8345
8346
|
{
|
|
8346
8347
|
"path": "agents/oidc-provisioning.md",
|
|
@@ -8362,6 +8363,11 @@
|
|
|
8362
8363
|
"module": "family-invitations",
|
|
8363
8364
|
"content": "## Family invitations and preserved Person identity\n\nTrusted hosts may use `prepare({tenantId,email,roleId})` instead of `roleSlug`\nto select an exact destination-owned role (or genuine global system role). Both\nselectors together, foreign-tenant roles and missing roles fail closed. The\nlegacy `roleSlug` path remains system-only. `existingProfilePolicy:'owned-person'`\nis an explicit service option allowing an existing ACTIVE canonical User's\nalready-owned tenant Person; exact normalized email, Person discriminator, unique\nownership and active source-family membership/tenant are required. It never\nrebinds profiles or credentials. New pending identities stay canonical global;\nOIDC owner authorization still requires canonical global Person. Returning\n`MailboxAuthenticationService` retains its existing global-only contract.\n\n`UserCollection.requireOwnedPersonForTenant(userId,tenantId)` is a bounded\nread for the exact current tenant actor, with active destination membership; it\nvalidates the same preserved owned Person. System/bypass/different actors fail.\nConsumers must use their transaction executor and treat returned profile data as\nprivate identity data, never a cross-family directory.\n\nEach `issue` rotates a random generation in canonical membership context memory\n(`smrt/tenant-invitation`, `generation`) and signs it into grant bindings, so a\nresend invalidates every earlier grant and its mailbox proofs. `revoke` affects\nonly pending membership, rotates generation and marks it inactive. `prepare`\nmay reprepare only service-revoked inactive membership with the same role;\nmanual inactive memberships stay refused. Malformed generation fails closed.\nNever edit/forget this framework-owned state. Legacy grants without generation\nremain valid until a rotation, expiry or consumption. Host scope/relationship\nwrites must follow acceptance on the same caller executor: a failure rolls back\nnonces, activation, generation and host writes. Mint the canonical magic-link\nsession only after committed mailbox identity proof; the grant alone cannot mint.\n\n### Retained send budgets with embedded caller transactions\n\nBefore opening a caller transaction, use exported\n`reserveMailboxAuthenticationRequest({limiter,scope,sourceKey})`. Scope is\n`{purpose:'returning',email}` or `{purpose:'invitation',tenantId,email}`. Pass\nits opaque `MailboxRequestReservation` as `reservation` to the corresponding\nrequest method, with the same limiter instance configured on the service and\nthe same trusted source key. The capability is a frozen empty object branded\nonly in a private WeakMap: copying/serializing/forging/reusing it does not carry\nauthority. Claim is synchronous and consumes even mismatched attempts before\nany await. It has no release/refund method; budget is settled with\n`retainOnSuccess` before the host transaction, so transport/caller rollback\ncannot refund it. Reserve outside all caller transactions; SDK versions without\nroot transaction introspection cannot prove that the host followed this rule.\n\nSQLite/DuckDB requests without a pre-reservation fail before writes or delivery.\nPostgreSQL retains its independently supplied root-limiter implicit request path\nand its legacy subject keys; do not claim those counters are pooled with the new\ncapability keys. Each host should consistently use its selected request path.\nEach capability expires at the earlier of thirty seconds or the earliest actual\nreserved key window end; allowed `LoginAttemptLease.budgetExpiresAt` reports that\nUnix-millisecond deadline. Request rechecks expiry after awaited identity work,\nbefore proof generation and before delivery. Never retain capabilities for later\nwork or carry one across processes. Capability subject budgets use purpose-separated immutable\n`['returning',normalizedEmail]` and `['invitation',tenantId,normalizedEmail]`\ntuples, so malformed returning email cannot collide with invitation scope and preparing/reissuing membership\nor grant generations does not reset the send budget. Source budget namespace is\nshared across both purposes. Returning malformed/unknown email intentionally\nconsumes normal source budget and returns no proof: a host's unknown invitation\npreflight may reserve `{purpose:'returning',email:''}`, discard the capability\nand return its uniform failure response without a service/proof call.\n"
|
|
8364
8365
|
},
|
|
8366
|
+
{
|
|
8367
|
+
"path": "agents/oauth-authorization.md",
|
|
8368
|
+
"module": "oauth-authorization",
|
|
8369
|
+
"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"
|
|
8370
|
+
},
|
|
8365
8371
|
{
|
|
8366
8372
|
"path": "agents/retention.md",
|
|
8367
8373
|
"module": "retention",
|
|
@@ -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-
|
|
8
|
+
at: "2026-11-17T20:00:22Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:c58419d063267e801c976db56801d4b3fc2735f81d676ed5c6774901b8a84a7e"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/package.json"
|
|
@@ -23,15 +23,18 @@ sources:
|
|
|
23
23
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/agents/mobile-auth.md"
|
|
24
24
|
title: "@happyvertical/smrt-users packages/users/agents/mobile-auth.md"
|
|
25
25
|
- id: "agents-4"
|
|
26
|
+
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/agents/oauth-authorization.md"
|
|
27
|
+
title: "@happyvertical/smrt-users packages/users/agents/oauth-authorization.md"
|
|
28
|
+
- id: "agents-5"
|
|
26
29
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/agents/oidc-provisioning.md"
|
|
27
30
|
title: "@happyvertical/smrt-users packages/users/agents/oidc-provisioning.md"
|
|
28
|
-
- id: "agents-
|
|
31
|
+
- id: "agents-6"
|
|
29
32
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/agents/permissions.md"
|
|
30
33
|
title: "@happyvertical/smrt-users packages/users/agents/permissions.md"
|
|
31
|
-
- id: "agents-
|
|
34
|
+
- id: "agents-7"
|
|
32
35
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/agents/retention.md"
|
|
33
36
|
title: "@happyvertical/smrt-users packages/users/agents/retention.md"
|
|
34
|
-
- id: "agents-
|
|
37
|
+
- id: "agents-8"
|
|
35
38
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/agents/terminal-auth-testing.md"
|
|
36
39
|
title: "@happyvertical/smrt-users packages/users/agents/terminal-auth-testing.md"
|
|
37
40
|
---
|
|
@@ -50,6 +53,7 @@ sources:
|
|
|
50
53
|
- `packages/users/AGENTS.md`
|
|
51
54
|
- `packages/users/agents/family-invitations.md`
|
|
52
55
|
- `packages/users/agents/mobile-auth.md`
|
|
56
|
+
- `packages/users/agents/oauth-authorization.md`
|
|
53
57
|
- `packages/users/agents/oidc-provisioning.md`
|
|
54
58
|
- `packages/users/agents/permissions.md`
|
|
55
59
|
- `packages/users/agents/retention.md`
|
package/dist/sveltekit.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { M as LoginRateLimitError, d as PasswordCredentialForbiddenError, f as PasswordCredentialService, g as SessionService, p as PasswordPolicyError, u as PasswordCredentialError } from "./chunks/PasswordCredentialService-BfYi-lfi.js";
|
|
2
|
-
import { B as OidcLoginService, C as PasskeyCredentialService, D as OperationPermissionError, F as MobileAuthError, H as encodeOidcTransaction, I as MobileAuthService, J as DeviceCredentialError, L as readMobileBearerToken, P as withSessionPermissionContext, R as validateMobileRedirectUri, S as PasskeyCredentialForbiddenError, T as PasskeyRegistrationError, U as getUsersOidcConfig, V as decodeOidcTransaction, W as resolveOidcProviderConfig, X as DeviceCredentialPolicyError, Y as DeviceCredentialForbiddenError, Z as DeviceCredentialService, a as TerminalAuthError, o as TerminalAuthRateLimitError, s as TerminalAuthService, w as PasskeyReauthenticationRequiredError, x as PasskeyCredentialError, z as OidcLoginError } from "./chunks/TerminalAuthService-
|
|
2
|
+
import { B as OidcLoginService, C as PasskeyCredentialService, D as OperationPermissionError, F as MobileAuthError, H as encodeOidcTransaction, I as MobileAuthService, J as DeviceCredentialError, L as readMobileBearerToken, P as withSessionPermissionContext, R as validateMobileRedirectUri, S as PasskeyCredentialForbiddenError, T as PasskeyRegistrationError, U as getUsersOidcConfig, V as decodeOidcTransaction, W as resolveOidcProviderConfig, X as DeviceCredentialPolicyError, Y as DeviceCredentialForbiddenError, Z as DeviceCredentialService, a as TerminalAuthError, o as TerminalAuthRateLimitError, s as TerminalAuthService, w as PasskeyReauthenticationRequiredError, x as PasskeyCredentialError, z as OidcLoginError } from "./chunks/TerminalAuthService-CN6XV6nH.js";
|
|
3
3
|
import { DiscoveryArtifactValidationError, SMRT_APP_RESULT_CONTRACT, SMRT_APP_RESULT_SCHEMA, SMRT_APP_RESULT_VERSION, SMRT_DISCOVERY_CONFORMANCE_ARTIFACT_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_SCHEMA, SMRT_DISCOVERY_CONFORMANCE_VERSION, SMRT_MCP_RESULT_METADATA_KEY, canonicalizeDiscoveryArtifact, createDiscoveryConformanceArtifact, deriveCommandRequirements, validateDiscoveryConformanceArtifact } from "./app-contract.js";
|
|
4
4
|
import { ObjectRegistry, createClassNamePredicate, resolveCustomActionMetadata, resolveEffectiveActionMetadata } from "@happyvertical/smrt-core";
|
|
5
5
|
import { createLogger } from "@happyvertical/logger";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-users",
|
|
3
|
-
"version": "0.62.
|
|
3
|
+
"version": "0.62.5",
|
|
4
4
|
"smrtJsdoc": "strict",
|
|
5
5
|
"description": "Multi-tenant user management for the SMRT framework - users, tenants, roles, permissions, groups",
|
|
6
6
|
"type": "module",
|
|
@@ -61,20 +61,20 @@
|
|
|
61
61
|
"dependencies": {
|
|
62
62
|
"@happyvertical/auth": "^0.113.0",
|
|
63
63
|
"@happyvertical/logger": "^0.113.0",
|
|
64
|
-
"@happyvertical/smrt-config": "0.62.
|
|
65
|
-
"@happyvertical/smrt-core": "0.62.
|
|
66
|
-
"@happyvertical/smrt-mobile-contract": "0.62.
|
|
67
|
-
"@happyvertical/smrt-profiles": "0.62.
|
|
68
|
-
"@happyvertical/smrt-tenancy": "0.62.
|
|
69
|
-
"@happyvertical/smrt-types": "0.62.
|
|
70
|
-
"@happyvertical/smrt-ui": "0.62.
|
|
64
|
+
"@happyvertical/smrt-config": "0.62.5",
|
|
65
|
+
"@happyvertical/smrt-core": "0.62.5",
|
|
66
|
+
"@happyvertical/smrt-mobile-contract": "0.62.5",
|
|
67
|
+
"@happyvertical/smrt-profiles": "0.62.5",
|
|
68
|
+
"@happyvertical/smrt-tenancy": "0.62.5",
|
|
69
|
+
"@happyvertical/smrt-types": "0.62.5",
|
|
70
|
+
"@happyvertical/smrt-ui": "0.62.5",
|
|
71
71
|
"@happyvertical/sql": "^0.113.0",
|
|
72
72
|
"@simplewebauthn/browser": "^14.0.0",
|
|
73
73
|
"@simplewebauthn/server": "^14.0.3",
|
|
74
74
|
"jose": "^6.2.12"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@happyvertical/smrt-vitest": "0.62.
|
|
77
|
+
"@happyvertical/smrt-vitest": "0.62.5",
|
|
78
78
|
"@sveltejs/package": "^2.5.8",
|
|
79
79
|
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
|
80
80
|
"@types/node": "24.13.6",
|