@happyvertical/smrt-users 0.60.14 → 0.60.16
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 +28 -0
- package/README.md +66 -0
- package/agents/permissions.md +18 -0
- package/dist/chunks/{PasswordCredentialService-BSSP_kyT.js → PasswordCredentialService-D_evcc-I.js} +144 -17
- package/dist/chunks/PasswordCredentialService-D_evcc-I.js.map +1 -0
- package/dist/chunks/{TerminalAuthService-BGeqNZU_.js → TerminalAuthService-CKw_Aoy1.js} +133 -8
- package/dist/chunks/TerminalAuthService-CKw_Aoy1.js.map +1 -0
- package/dist/chunks/permission-registry-PhcdZvKe.js +19 -0
- package/dist/chunks/permission-registry-PhcdZvKe.js.map +1 -0
- package/dist/collections/SessionCollection.d.ts +30 -0
- package/dist/collections/SessionCollection.d.ts.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +111 -11
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +89 -1
- package/dist/models/Session.d.ts +45 -0
- package/dist/models/Session.d.ts.map +1 -1
- package/dist/models/index.d.ts +1 -1
- package/dist/models/index.d.ts.map +1 -1
- package/dist/operator.js +1 -1
- package/dist/permission-registry-state.d.ts +8 -0
- package/dist/permission-registry-state.d.ts.map +1 -0
- package/dist/permission-registry.d.ts +24 -0
- package/dist/permission-registry.d.ts.map +1 -0
- package/dist/permission-registry.js +2 -0
- package/dist/services/MagicLinkService.d.ts +55 -0
- package/dist/services/MagicLinkService.d.ts.map +1 -1
- package/dist/services/OidcLoginService.d.ts +63 -0
- package/dist/services/OidcLoginService.d.ts.map +1 -1
- package/dist/services/PasswordCredentialService.d.ts +23 -0
- package/dist/services/PasswordCredentialService.d.ts.map +1 -1
- package/dist/services/PermissionCatalogService.d.ts +2 -27
- package/dist/services/PermissionCatalogService.d.ts.map +1 -1
- package/dist/services/SessionService.d.ts +8 -0
- package/dist/services/SessionService.d.ts.map +1 -1
- package/dist/services/index.d.ts +3 -3
- package/dist/services/index.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +85 -7
- package/dist/smrt-knowledge.okf.md +4 -2
- package/dist/step-up.d.ts +57 -0
- package/dist/step-up.d.ts.map +1 -0
- package/dist/step-up.js +36 -0
- package/dist/step-up.js.map +1 -0
- package/dist/sveltekit.js +2 -2
- package/package.json +20 -12
- package/dist/chunks/PasswordCredentialService-BSSP_kyT.js.map +0 -1
- package/dist/chunks/TerminalAuthService-BGeqNZU_.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SessionService.d.ts","sourceRoot":"","sources":["../../src/services/SessionService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,OAAO,EACL,KAAK,oBAAoB,EAE1B,MAAM,qCAAqC,CAAC;AAE7C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAGL,KAAK,OAAO,EACZ,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAG9C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,sBAAsB;IACtB,IAAI,EAAE,IAAI,CAAC;IACX,oEAAoE;IACpE,UAAU,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IAC/B,gCAAgC;IAChC,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE;QACpB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;QAC5B,qBAAqB,EAAE,MAAM,GAAG,IAAI,CAAC;KACtC,GAAG,IAAI,CAAC;IACT,sCAAsC;IACtC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,iBAAiB;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;;;OAQG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O,CAAC,OAAO,CAAC;IAM5E;;OAEG;IACG,cAAc,CAAC,CAAC,EACpB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAIzB;;OAEG;IACG,cAAc,CAClB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,OAAO,CAAC;IAInB;;OAEG;WACU,MAAM,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,cAAc,CAAC;CAK7E"}
|
package/dist/services/index.d.ts
CHANGED
|
@@ -6,15 +6,15 @@ export { ACCESS_REQUEST_CAPABILITIES, type AccessRequestAuthorizationContext, ty
|
|
|
6
6
|
export { ANCESTOR_READ_ACTION, type AncestorReadPackageConfig, type AncestorReadPolicy, DEFAULT_ANCESTOR_READ_MAX_DEPTH, getConfiguredAncestorReadPolicy, isAncestorReadableSlug, type NormalizedAncestorReadPolicy, normalizeAncestorReadPolicy, } from './AncestorReadPolicy.js';
|
|
7
7
|
export { type ClearPinInput, DEFAULT_DEVICE_PERSON_IDLE_SECONDS, DEFAULT_PIN_MANAGE_PERMISSION, DeviceCredentialError, DeviceCredentialForbiddenError, DeviceCredentialPolicyError, DeviceCredentialService, type DeviceCredentialServiceOptions, type DeviceCredentialVerification, type DeviceCredentialVerifier, type DeviceSignInContext, type DeviceSignInInput, type DeviceSignInResult, ensurePinPermissionsRegistered, PIN_LOGIN_KIND, PIN_PERMISSION_DEFINITIONS, type PinPolicyOptions, type PinSignInInput, PinVerifier, type ResetPinInput, type SetPinInput, } from './DeviceCredentialService.js';
|
|
8
8
|
export { DEFAULT_LOGIN_ATTEMPT_WINDOW_SECONDS, DEFAULT_LOGIN_LOCKOUT_BASE_SECONDS, DEFAULT_LOGIN_LOCKOUT_FACTOR, DEFAULT_LOGIN_LOCKOUT_MAX_SECONDS, DEFAULT_LOGIN_MAX_ATTEMPTS, DEFAULT_SOURCE_LOCKOUT_AUDIT_SECONDS, DurableLoginAuditSink, InvalidCredentialsError, type LoginAttemptDecision, type LoginAttemptDenied, type LoginAttemptLease, LoginAttemptLimiter, type LoginAttemptLimiterOptions, type LoginAuditEntry, type LoginAuditSink, type LoginBudgetOptions, type LoginFailureOutcome, type LoginLockoutOptions, LoginRateLimitError, type ReserveLoginAttemptOptions, } from './LoginAttemptLimiter.js';
|
|
9
|
-
export { MagicLinkError, type MagicLinkResult, MagicLinkService, type MagicLinkServiceOptions, type MagicLinkVerifyResult, } from './MagicLinkService.js';
|
|
9
|
+
export { MagicLinkError, type MagicLinkResult, MagicLinkService, type MagicLinkServiceOptions, type MagicLinkStepUpRequest, type MagicLinkStepUpResult, type MagicLinkVerifyResult, } from './MagicLinkService.js';
|
|
10
10
|
export { type AuthenticatedMailbox, type MailboxAuthenticationDelivery, type MailboxAuthenticationRequestScope, MailboxAuthenticationService, type MailboxAuthenticationServiceOptions, type MailboxRequestReservation, reserveMailboxAuthenticationRequest, } from './MailboxAuthenticationService.js';
|
|
11
11
|
export { MobileAuthError, type MobileAuthErrorCode, MobileAuthService, type MobileAuthServiceOptions, type MobileBootstrapContext, type MobileLoginContext, type MobileLogoutResult, type MobileRequestMeta, type MobileResolvedUser, type MobileTenantContext, readMobileBearerToken, validateMobileRedirectUri, } from './MobileAuthService.js';
|
|
12
12
|
export { SmrtOAuthAuthorizationService, type SmrtOAuthAuthorizationServiceOptions, type SmrtOAuthGrantSummary, } from './OAuthAuthorizationService.js';
|
|
13
13
|
export { SMRT_OAUTH_GRANT_CLAIM, SmrtOAuthAuthorizationStorage, type SmrtOAuthAuthorizationStorageOptions, } from './OAuthAuthorizationStorage.js';
|
|
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 OidcTokenEndpointAuthMethod, type OidcTokenSet, type OidcTransaction, type ResolvedOidcProviderConfig, resolveOidcProviderConfig, type UsersOidcConfig, } from './OidcLoginService.js';
|
|
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
16
|
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
|
-
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 ReplaceForgottenPasswordInput, type ResetPasswordInput, type SetPasswordInput, } from './PasswordCredentialService.js';
|
|
17
|
+
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
18
|
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';
|
|
19
19
|
export { type PermissionResolutionOptions, type PermissionResolutionResult, PermissionResolver, type PermissionResolverOptions, type TenantPermissionInheritanceResult, } from './PermissionResolver.js';
|
|
20
20
|
export { applyPostgresPermissionPolicies, type GeneratePostgresPermissionSqlResult, generatePostgresPermissionSql, type PostgresPermissionPolicyReportItem, type PostgresPermissionPolicyTarget, } from './PostgresPermissionPolicies.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,2BAA2B,EAC3B,KAAK,iCAAiC,EACtC,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAC5B,kBAAkB,EAClB,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,KAAK,sBAAsB,EAC3B,oBAAoB,EACpB,KAAK,2BAA2B,EAChC,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAC7B,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,EAChC,KAAK,4BAA4B,EACjC,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,GAC9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,oBAAoB,EACpB,KAAK,yBAAyB,EAC9B,KAAK,kBAAkB,EACvB,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,CAAC;AACvC,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,oBAAoB,EACzB,cAAc,EACd,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,KAAK,wBAAwB,EAC7B,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,4BAA4B,EACjC,qBAAqB,EACrB,uBAAuB,EACvB,KAAK,8BAA8B,GACpC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,KAAK,kBAAkB,EACvB,aAAa,EACb,KAAK,yBAAyB,GAC/B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,KAAK,0BAA0B,EAC/B,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,+CAA+C,EAC/C,qCAAqC,EACrC,sCAAsC,EACtC,oCAAoC,EACpC,+BAA+B,EAC/B,2BAA2B,EAC3B,iBAAiB,EACjB,0BAA0B,EAC1B,mBAAmB,EACnB,KAAK,0BAA0B,GAChC,MAAM,0BAA0B,CAAC"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-users",
|
|
6
|
-
"packageVersion": "0.60.
|
|
6
|
+
"packageVersion": "0.60.16",
|
|
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": "4f11c693668878436d17f30ff495e1bab63d22f5161f2028b8cb49b52b810fb8",
|
|
11
|
+
"packageJson": "1c0ba4eef6cf92b9f56159ac100914a3c7837307d61bc0a82c6123a3276f80c7",
|
|
12
|
+
"agents": "30b71cb25de701433b9b10de8968eaafb6f30e4dd933dc1328feac416c439d70",
|
|
13
|
+
"moduleDoc:agents/permissions.md": "08a83623a45ef11b2d8596fff2c88cbfbb10bb71188e12e796037b61278bbe56",
|
|
14
14
|
"moduleDoc:agents/oidc-provisioning.md": "b73f3fdaf61136720132a614c7e14237b7bd35f7bf5d43eabb29f565485803b9",
|
|
15
15
|
"moduleDoc:agents/mobile-auth.md": "25e85e83f43e3a46383a92fa809f3a003b4545c3026e78dbe1bccbbc35161e18",
|
|
16
16
|
"moduleDoc:agents/terminal-auth-testing.md": "ca6bdf325fe4edc3c875e6da38e3f5b4ae287bc0e7035002d275cf15de36e906",
|
|
@@ -23,7 +23,9 @@
|
|
|
23
23
|
"./manifest",
|
|
24
24
|
"./manifest.json",
|
|
25
25
|
"./operator",
|
|
26
|
+
"./permission-registry",
|
|
26
27
|
"./playground",
|
|
28
|
+
"./step-up",
|
|
27
29
|
"./svelte",
|
|
28
30
|
"./sveltekit"
|
|
29
31
|
],
|
|
@@ -2322,12 +2324,15 @@
|
|
|
2322
2324
|
"findChildren",
|
|
2323
2325
|
"findValidSession",
|
|
2324
2326
|
"getSessionData",
|
|
2327
|
+
"markReauthenticated",
|
|
2328
|
+
"recordStepUpIntent",
|
|
2325
2329
|
"revokeChildren",
|
|
2326
2330
|
"revokeSession",
|
|
2327
2331
|
"revokeUserSessions",
|
|
2328
2332
|
"revokeUserSessionsByAuthMethod",
|
|
2329
2333
|
"setSessionData",
|
|
2330
2334
|
"setSessionTenant",
|
|
2335
|
+
"takeStepUpIntent",
|
|
2331
2336
|
"touch"
|
|
2332
2337
|
],
|
|
2333
2338
|
"methodSignatures": [
|
|
@@ -2396,6 +2401,25 @@
|
|
|
2396
2401
|
],
|
|
2397
2402
|
"returns": "Promise<T | undefined>"
|
|
2398
2403
|
},
|
|
2404
|
+
{
|
|
2405
|
+
"name": "markReauthenticated",
|
|
2406
|
+
"async": true,
|
|
2407
|
+
"params": [
|
|
2408
|
+
"sessionId: string",
|
|
2409
|
+
"options?: object"
|
|
2410
|
+
],
|
|
2411
|
+
"returns": "Promise<Date | null>"
|
|
2412
|
+
},
|
|
2413
|
+
{
|
|
2414
|
+
"name": "recordStepUpIntent",
|
|
2415
|
+
"async": true,
|
|
2416
|
+
"params": [
|
|
2417
|
+
"sessionId: string",
|
|
2418
|
+
"intent: Record<string, unknown>",
|
|
2419
|
+
"options?: object"
|
|
2420
|
+
],
|
|
2421
|
+
"returns": "Promise<boolean>"
|
|
2422
|
+
},
|
|
2399
2423
|
{
|
|
2400
2424
|
"name": "revokeChildren",
|
|
2401
2425
|
"async": true,
|
|
@@ -2451,6 +2475,15 @@
|
|
|
2451
2475
|
],
|
|
2452
2476
|
"returns": "Promise<boolean>"
|
|
2453
2477
|
},
|
|
2478
|
+
{
|
|
2479
|
+
"name": "takeStepUpIntent",
|
|
2480
|
+
"async": true,
|
|
2481
|
+
"params": [
|
|
2482
|
+
"sessionId: string",
|
|
2483
|
+
"options?: object"
|
|
2484
|
+
],
|
|
2485
|
+
"returns": "Promise<Record<string, unknown> | null>"
|
|
2486
|
+
},
|
|
2454
2487
|
{
|
|
2455
2488
|
"name": "touch",
|
|
2456
2489
|
"async": true,
|
|
@@ -2520,6 +2553,20 @@
|
|
|
2520
2553
|
"reason": "not listed in api.include",
|
|
2521
2554
|
"objectName": "@happyvertical/smrt-users:SessionCollection"
|
|
2522
2555
|
},
|
|
2556
|
+
{
|
|
2557
|
+
"kind": "api",
|
|
2558
|
+
"operation": "markReauthenticated",
|
|
2559
|
+
"code": "not-included",
|
|
2560
|
+
"reason": "not listed in api.include",
|
|
2561
|
+
"objectName": "@happyvertical/smrt-users:SessionCollection"
|
|
2562
|
+
},
|
|
2563
|
+
{
|
|
2564
|
+
"kind": "api",
|
|
2565
|
+
"operation": "recordStepUpIntent",
|
|
2566
|
+
"code": "not-included",
|
|
2567
|
+
"reason": "not listed in api.include",
|
|
2568
|
+
"objectName": "@happyvertical/smrt-users:SessionCollection"
|
|
2569
|
+
},
|
|
2523
2570
|
{
|
|
2524
2571
|
"kind": "api",
|
|
2525
2572
|
"operation": "revokeChildren",
|
|
@@ -2562,6 +2609,13 @@
|
|
|
2562
2609
|
"reason": "not listed in api.include",
|
|
2563
2610
|
"objectName": "@happyvertical/smrt-users:SessionCollection"
|
|
2564
2611
|
},
|
|
2612
|
+
{
|
|
2613
|
+
"kind": "api",
|
|
2614
|
+
"operation": "takeStepUpIntent",
|
|
2615
|
+
"code": "not-included",
|
|
2616
|
+
"reason": "not listed in api.include",
|
|
2617
|
+
"objectName": "@happyvertical/smrt-users:SessionCollection"
|
|
2618
|
+
},
|
|
2565
2619
|
{
|
|
2566
2620
|
"kind": "api",
|
|
2567
2621
|
"operation": "touch",
|
|
@@ -6674,9 +6728,11 @@
|
|
|
6674
6728
|
"getData",
|
|
6675
6729
|
"getIdleSeconds",
|
|
6676
6730
|
"getPermissionCeiling",
|
|
6731
|
+
"getReauthenticatedAt",
|
|
6677
6732
|
"isExpired",
|
|
6678
6733
|
"isLayered",
|
|
6679
6734
|
"isRevoked",
|
|
6735
|
+
"isStepUpEligible",
|
|
6680
6736
|
"isValid",
|
|
6681
6737
|
"recordActivity",
|
|
6682
6738
|
"removeData",
|
|
@@ -6716,6 +6772,10 @@
|
|
|
6716
6772
|
"name": "getPermissionCeiling",
|
|
6717
6773
|
"returns": "string[] | null"
|
|
6718
6774
|
},
|
|
6775
|
+
{
|
|
6776
|
+
"name": "getReauthenticatedAt",
|
|
6777
|
+
"returns": "Date | null"
|
|
6778
|
+
},
|
|
6719
6779
|
{
|
|
6720
6780
|
"name": "isExpired",
|
|
6721
6781
|
"returns": "boolean"
|
|
@@ -6728,6 +6788,10 @@
|
|
|
6728
6788
|
"name": "isRevoked",
|
|
6729
6789
|
"returns": "boolean"
|
|
6730
6790
|
},
|
|
6791
|
+
{
|
|
6792
|
+
"name": "isStepUpEligible",
|
|
6793
|
+
"returns": "boolean"
|
|
6794
|
+
},
|
|
6731
6795
|
{
|
|
6732
6796
|
"name": "isValid",
|
|
6733
6797
|
"returns": "boolean"
|
|
@@ -6838,6 +6902,13 @@
|
|
|
6838
6902
|
"reason": "not listed in api.include",
|
|
6839
6903
|
"objectName": "@happyvertical/smrt-users:Session"
|
|
6840
6904
|
},
|
|
6905
|
+
{
|
|
6906
|
+
"kind": "api",
|
|
6907
|
+
"operation": "getReauthenticatedAt",
|
|
6908
|
+
"code": "not-included",
|
|
6909
|
+
"reason": "not listed in api.include",
|
|
6910
|
+
"objectName": "@happyvertical/smrt-users:Session"
|
|
6911
|
+
},
|
|
6841
6912
|
{
|
|
6842
6913
|
"kind": "api",
|
|
6843
6914
|
"operation": "isExpired",
|
|
@@ -6859,6 +6930,13 @@
|
|
|
6859
6930
|
"reason": "not listed in api.include",
|
|
6860
6931
|
"objectName": "@happyvertical/smrt-users:Session"
|
|
6861
6932
|
},
|
|
6933
|
+
{
|
|
6934
|
+
"kind": "api",
|
|
6935
|
+
"operation": "isStepUpEligible",
|
|
6936
|
+
"code": "not-included",
|
|
6937
|
+
"reason": "not listed in api.include",
|
|
6938
|
+
"objectName": "@happyvertical/smrt-users:Session"
|
|
6939
|
+
},
|
|
6862
6940
|
{
|
|
6863
6941
|
"kind": "api",
|
|
6864
6942
|
"operation": "isValid",
|
|
@@ -8241,12 +8319,12 @@
|
|
|
8241
8319
|
"polymorphicAssociations": 0,
|
|
8242
8320
|
"uuidColumns": 162
|
|
8243
8321
|
},
|
|
8244
|
-
"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/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- 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. Follow root knowledge 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",
|
|
8322
|
+
"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. Follow root knowledge 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",
|
|
8245
8323
|
"moduleDocs": [
|
|
8246
8324
|
{
|
|
8247
8325
|
"path": "agents/permissions.md",
|
|
8248
8326
|
"module": "permissions",
|
|
8249
|
-
"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.\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"
|
|
8327
|
+
"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.\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"
|
|
8250
8328
|
},
|
|
8251
8329
|
{
|
|
8252
8330
|
"path": "agents/oidc-provisioning.md",
|
|
@@ -5,10 +5,10 @@ description: "Multi-tenant user management for the SMRT framework - users, tenan
|
|
|
5
5
|
status: "stable"
|
|
6
6
|
generated:
|
|
7
7
|
by: "smrt/scripts/generate-knowledge-okf.ts"
|
|
8
|
-
at: "2026-11-
|
|
8
|
+
at: "2026-11-09T18:41:34Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:85c5ed7ca0925f6bc5251da5c5d77a57cf9e9f4fe725d1ad38fc236ef9ca5ab0"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/users/package.json"
|
|
@@ -78,7 +78,9 @@ sources:
|
|
|
78
78
|
- `./manifest`
|
|
79
79
|
- `./manifest.json`
|
|
80
80
|
- `./operator`
|
|
81
|
+
- `./permission-registry`
|
|
81
82
|
- `./playground`
|
|
83
|
+
- `./step-up`
|
|
82
84
|
- `./svelte`
|
|
83
85
|
- `./sveltekit`
|
|
84
86
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Step-up (recent authentication) check (#4841).
|
|
3
|
+
*
|
|
4
|
+
* A session proves who signed in at some point; a sensitive action (replacing
|
|
5
|
+
* a vault account, for instance) needs proof the person is at the keyboard
|
|
6
|
+
* NOW. The proof is server-side session state: the sign-in time of an
|
|
7
|
+
* interactive session, or the stamp `PasswordCredentialService.stepUp` writes
|
|
8
|
+
* after a fresh password check. This module only decides; it never writes.
|
|
9
|
+
*
|
|
10
|
+
* @packageDocumentation
|
|
11
|
+
*/
|
|
12
|
+
import type { SessionContext } from './services/SessionService.js';
|
|
13
|
+
/** The slice of a session context the step-up and owner checks read. */
|
|
14
|
+
export type StepUpSession = Pick<SessionContext, 'sessionId' | 'user' | 'reauthenticatedAt' | 'membership' | 'tenantId' | 'authMethod' | 'parent' | 'permissionCeiling' | 'tenantAuthorization'>;
|
|
15
|
+
/** Stable machine code carried by {@link StepUpRequiredError}. */
|
|
16
|
+
export declare const STEP_UP_REQUIRED_CODE = "step_up_required";
|
|
17
|
+
/** Default age (5 minutes) a step-up may have when an action runs. */
|
|
18
|
+
export declare const DEFAULT_STEP_UP_MAX_AGE_SECONDS = 300;
|
|
19
|
+
/** Largest accepted `maxAgeSeconds` (1 hour). */
|
|
20
|
+
export declare const STEP_UP_MAX_AGE_CEILING_SECONDS: number;
|
|
21
|
+
/**
|
|
22
|
+
* The session has no sufficiently recent authentication. One message and one
|
|
23
|
+
* code for every reason (missing, stale, malformed, wrong session or user), so
|
|
24
|
+
* a caller learns only that it must re-authenticate.
|
|
25
|
+
*/
|
|
26
|
+
export declare class StepUpRequiredError extends Error {
|
|
27
|
+
readonly code = "step_up_required";
|
|
28
|
+
constructor(message?: string);
|
|
29
|
+
}
|
|
30
|
+
export interface RequireRecentAuthenticationOptions {
|
|
31
|
+
/** Longest acceptable age in seconds. Default 300; capped at one hour. */
|
|
32
|
+
maxAgeSeconds?: number;
|
|
33
|
+
/** Clock, injectable for tests. Default `() => new Date()`. */
|
|
34
|
+
now?: () => Date;
|
|
35
|
+
/** The session the caller authenticated; a different session is refused. */
|
|
36
|
+
expectedSessionId?: string;
|
|
37
|
+
/** The user the action is for; a different user's session is refused. */
|
|
38
|
+
expectedUserId?: string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Throw {@link StepUpRequiredError} unless `session` (a context from
|
|
42
|
+
* `SessionService.loadSessionContext`) was authenticated within
|
|
43
|
+
* `maxAgeSeconds`. Fails closed: a missing, malformed, future-dated or stale
|
|
44
|
+
* timestamp, a session or user other than the expected ones, or an invalid
|
|
45
|
+
* `maxAgeSeconds` all refuse.
|
|
46
|
+
*/
|
|
47
|
+
export declare function requireRecentAuthentication(session: Pick<StepUpSession, 'sessionId' | 'user' | 'reauthenticatedAt'>, options?: RequireRecentAuthenticationOptions): void;
|
|
48
|
+
/**
|
|
49
|
+
* Whether `session` is a first-class session of the OWNER of its tenant: a
|
|
50
|
+
* direct, active membership in the system `owner` role (not an inherited or
|
|
51
|
+
* ancestor one), with no device or layered channel (`terminal`, `pin`, a
|
|
52
|
+
* parent session) and no permission ceiling. A member, a device-only session
|
|
53
|
+
* and a missing session are all false. Hosts with a custom owner role decide
|
|
54
|
+
* for themselves and pass their own check where this one is injected.
|
|
55
|
+
*/
|
|
56
|
+
export declare function isTenantOwnerSession(session: StepUpSession | null | undefined): boolean;
|
|
57
|
+
//# sourceMappingURL=step-up.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"step-up.d.ts","sourceRoot":"","sources":["../src/step-up.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,IAAI,CAC9B,cAAc,EACZ,WAAW,GACX,MAAM,GACN,mBAAmB,GACnB,YAAY,GACZ,UAAU,GACV,YAAY,GACZ,QAAQ,GACR,mBAAmB,GACnB,qBAAqB,CACxB,CAAC;AAOF,kEAAkE;AAClE,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD,sEAAsE;AACtE,eAAO,MAAM,+BAA+B,MAAM,CAAC;AAEnD,iDAAiD;AACjD,eAAO,MAAM,+BAA+B,QAAU,CAAC;AAKvD;;;;GAIG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,IAAI,sBAAyB;gBAE1B,OAAO,SAAuC;CAI3D;AAED,MAAM,WAAW,kCAAkC;IACjD,0EAA0E;IAC1E,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+DAA+D;IAC/D,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,4EAA4E;IAC5E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,yEAAyE;IACzE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,IAAI,CAAC,aAAa,EAAE,WAAW,GAAG,MAAM,GAAG,mBAAmB,CAAC,EACxE,OAAO,GAAE,kCAAuC,GAC/C,IAAI,CA8BN;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,GACxC,OAAO,CAkBT"}
|
package/dist/step-up.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { n as DEFAULT_ROLES } from "./chunks/types-DqUZxluX.js";
|
|
2
|
+
//#region src/step-up.ts
|
|
3
|
+
var OWNER_ROLE_ID = DEFAULT_ROLES[0].id;
|
|
4
|
+
var DEVICE_AUTH_METHODS = /* @__PURE__ */ new Set(["terminal", "pin"]);
|
|
5
|
+
var STEP_UP_REQUIRED_CODE = "step_up_required";
|
|
6
|
+
var DEFAULT_STEP_UP_MAX_AGE_SECONDS = 300;
|
|
7
|
+
var STEP_UP_MAX_AGE_CEILING_SECONDS = 3600;
|
|
8
|
+
var StepUpRequiredError = class extends Error {
|
|
9
|
+
code = STEP_UP_REQUIRED_CODE;
|
|
10
|
+
constructor(message = "Recent authentication is required.") {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "StepUpRequiredError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
function requireRecentAuthentication(session, options = {}) {
|
|
16
|
+
const maxAge = options.maxAgeSeconds ?? 300;
|
|
17
|
+
if (!Number.isFinite(maxAge) || maxAge <= 0 || maxAge > 3600) throw new StepUpRequiredError();
|
|
18
|
+
if (options.expectedSessionId !== void 0 && session.sessionId !== options.expectedSessionId) throw new StepUpRequiredError();
|
|
19
|
+
if (options.expectedUserId !== void 0 && session.user?.id !== options.expectedUserId) throw new StepUpRequiredError();
|
|
20
|
+
const at = session.reauthenticatedAt;
|
|
21
|
+
if (!(at instanceof Date) || Number.isNaN(at.getTime())) throw new StepUpRequiredError();
|
|
22
|
+
const age = (options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() - at.getTime();
|
|
23
|
+
if (age < -3e4 || age > maxAge * 1e3) throw new StepUpRequiredError();
|
|
24
|
+
}
|
|
25
|
+
function isTenantOwnerSession(session) {
|
|
26
|
+
if (!session?.user?.id || !session.tenantId) return false;
|
|
27
|
+
const membership = session.membership;
|
|
28
|
+
if (!membership || membership.roleId !== OWNER_ROLE_ID || membership.tenantId !== session.tenantId || membership.userId !== session.user.id || typeof membership.isActive === "function" && !membership.isActive()) return false;
|
|
29
|
+
if (session.tenantAuthorization?.inheritedFromTenantId) return false;
|
|
30
|
+
if (session.parent || session.permissionCeiling) return false;
|
|
31
|
+
return !(typeof session.authMethod === "string" && DEVICE_AUTH_METHODS.has(session.authMethod));
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { DEFAULT_STEP_UP_MAX_AGE_SECONDS, STEP_UP_MAX_AGE_CEILING_SECONDS, STEP_UP_REQUIRED_CODE, StepUpRequiredError, isTenantOwnerSession, requireRecentAuthentication };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=step-up.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"step-up.js","names":[],"sources":["../src/step-up.ts"],"sourcesContent":["/**\n * Step-up (recent authentication) check (#4841).\n *\n * A session proves who signed in at some point; a sensitive action (replacing\n * a vault account, for instance) needs proof the person is at the keyboard\n * NOW. The proof is server-side session state: the sign-in time of an\n * interactive session, or the stamp `PasswordCredentialService.stepUp` writes\n * after a fresh password check. This module only decides; it never writes.\n *\n * @packageDocumentation\n */\n\nimport type { SessionContext } from './services/SessionService.js';\nimport { DEFAULT_ROLES } from './types/index.js';\n\n/** The slice of a session context the step-up and owner checks read. */\nexport type StepUpSession = Pick<\n SessionContext,\n | 'sessionId'\n | 'user'\n | 'reauthenticatedAt'\n | 'membership'\n | 'tenantId'\n | 'authMethod'\n | 'parent'\n | 'permissionCeiling'\n | 'tenantAuthorization'\n>;\n\nconst OWNER_ROLE_ID: string = DEFAULT_ROLES[0].id;\n\n/** Session channels that are a device, never the person at the keyboard. */\nconst DEVICE_AUTH_METHODS: ReadonlySet<string> = new Set(['terminal', 'pin']);\n\n/** Stable machine code carried by {@link StepUpRequiredError}. */\nexport const STEP_UP_REQUIRED_CODE = 'step_up_required';\n\n/** Default age (5 minutes) a step-up may have when an action runs. */\nexport const DEFAULT_STEP_UP_MAX_AGE_SECONDS = 300;\n\n/** Largest accepted `maxAgeSeconds` (1 hour). */\nexport const STEP_UP_MAX_AGE_CEILING_SECONDS = 60 * 60;\n\n/** Clock skew tolerated before a future stamp is treated as forged. */\nconst FUTURE_SKEW_MS = 30_000;\n\n/**\n * The session has no sufficiently recent authentication. One message and one\n * code for every reason (missing, stale, malformed, wrong session or user), so\n * a caller learns only that it must re-authenticate.\n */\nexport class StepUpRequiredError extends Error {\n readonly code = STEP_UP_REQUIRED_CODE;\n\n constructor(message = 'Recent authentication is required.') {\n super(message);\n this.name = 'StepUpRequiredError';\n }\n}\n\nexport interface RequireRecentAuthenticationOptions {\n /** Longest acceptable age in seconds. Default 300; capped at one hour. */\n maxAgeSeconds?: number;\n /** Clock, injectable for tests. Default `() => new Date()`. */\n now?: () => Date;\n /** The session the caller authenticated; a different session is refused. */\n expectedSessionId?: string;\n /** The user the action is for; a different user's session is refused. */\n expectedUserId?: string;\n}\n\n/**\n * Throw {@link StepUpRequiredError} unless `session` (a context from\n * `SessionService.loadSessionContext`) was authenticated within\n * `maxAgeSeconds`. Fails closed: a missing, malformed, future-dated or stale\n * timestamp, a session or user other than the expected ones, or an invalid\n * `maxAgeSeconds` all refuse.\n */\nexport function requireRecentAuthentication(\n session: Pick<StepUpSession, 'sessionId' | 'user' | 'reauthenticatedAt'>,\n options: RequireRecentAuthenticationOptions = {},\n): void {\n const maxAge = options.maxAgeSeconds ?? DEFAULT_STEP_UP_MAX_AGE_SECONDS;\n if (\n !Number.isFinite(maxAge) ||\n maxAge <= 0 ||\n maxAge > STEP_UP_MAX_AGE_CEILING_SECONDS\n ) {\n throw new StepUpRequiredError();\n }\n if (\n options.expectedSessionId !== undefined &&\n session.sessionId !== options.expectedSessionId\n ) {\n throw new StepUpRequiredError();\n }\n if (\n options.expectedUserId !== undefined &&\n session.user?.id !== options.expectedUserId\n ) {\n throw new StepUpRequiredError();\n }\n const at = session.reauthenticatedAt;\n if (!(at instanceof Date) || Number.isNaN(at.getTime())) {\n throw new StepUpRequiredError();\n }\n const nowMs = (options.now ?? (() => new Date()))().getTime();\n const age = nowMs - at.getTime();\n if (age < -FUTURE_SKEW_MS || age > maxAge * 1000) {\n throw new StepUpRequiredError();\n }\n}\n\n/**\n * Whether `session` is a first-class session of the OWNER of its tenant: a\n * direct, active membership in the system `owner` role (not an inherited or\n * ancestor one), with no device or layered channel (`terminal`, `pin`, a\n * parent session) and no permission ceiling. A member, a device-only session\n * and a missing session are all false. Hosts with a custom owner role decide\n * for themselves and pass their own check where this one is injected.\n */\nexport function isTenantOwnerSession(\n session: StepUpSession | null | undefined,\n): boolean {\n if (!session?.user?.id || !session.tenantId) return false;\n const membership = session.membership;\n if (\n !membership ||\n membership.roleId !== OWNER_ROLE_ID ||\n membership.tenantId !== session.tenantId ||\n membership.userId !== session.user.id ||\n (typeof membership.isActive === 'function' && !membership.isActive())\n ) {\n return false;\n }\n if (session.tenantAuthorization?.inheritedFromTenantId) return false;\n if (session.parent || session.permissionCeiling) return false;\n return !(\n typeof session.authMethod === 'string' &&\n DEVICE_AUTH_METHODS.has(session.authMethod)\n );\n}\n"],"mappings":";;AA6BA,IAAM,gBAAwB,cAAc,EAAC,CAAE;AAG/C,IAAM,sCAA2C,IAAI,IAAI,CAAC,YAAY,KAAK,CAAC;AAGrE,IAAM,wBAAwB;AAG9B,IAAM,kCAAkC;AAGxC,IAAM,kCAAkC;AAUxC,IAAM,sBAAN,cAAkC,MAAM;CACpC,OAAO;CAEhB,YAAY,UAAU,sCAAsC;EAC1D,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAoBO,SAAS,4BACd,SACA,UAA8C,CAAC,GACzC;CACN,MAAM,SAAS,QAAQ,iBAAA;CACvB,IACE,CAAC,OAAO,SAAS,MAAM,KACvB,UAAU,KACV,SAAA,MAEA,MAAM,IAAI,oBAAoB;CAEhC,IACE,QAAQ,sBAAsB,KAAA,KAC9B,QAAQ,cAAc,QAAQ,mBAE9B,MAAM,IAAI,oBAAoB;CAEhC,IACE,QAAQ,mBAAmB,KAAA,KAC3B,QAAQ,MAAM,OAAO,QAAQ,gBAE7B,MAAM,IAAI,oBAAoB;CAEhC,MAAM,KAAK,QAAQ;CACnB,IAAI,EAAE,cAAc,SAAS,OAAO,MAAM,GAAG,QAAQ,CAAC,GACpD,MAAM,IAAI,oBAAoB;CAGhC,MAAM,OADS,QAAQ,8BAAc,IAAI,KAAK,GAAA,CAAI,CAAA,CAAE,QACxC,IAAQ,GAAG,QAAQ;CAC/B,IAAI,MAAM,QAAmB,MAAM,SAAS,KAC1C,MAAM,IAAI,oBAAoB;AAElC;AAUO,SAAS,qBACd,SACS;CACT,IAAI,CAAC,SAAS,MAAM,MAAM,CAAC,QAAQ,UAAU,OAAO;CACpD,MAAM,aAAa,QAAQ;CAC3B,IACE,CAAC,cACD,WAAW,WAAW,iBACtB,WAAW,aAAa,QAAQ,YAChC,WAAW,WAAW,QAAQ,KAAK,MAClC,OAAO,WAAW,aAAa,cAAc,CAAC,WAAW,SAAS,GAEnE,OAAO;CAET,IAAI,QAAQ,qBAAqB,uBAAuB,OAAO;CAC/D,IAAI,QAAQ,UAAU,QAAQ,mBAAmB,OAAO;CACxD,OAAO,EACL,OAAO,QAAQ,eAAe,YAC9B,oBAAoB,IAAI,QAAQ,UAAU;AAE9C"}
|
package/dist/sveltekit.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { M as LoginRateLimitError, d as PasswordCredentialForbiddenError, f as PasswordCredentialService, g as SessionService, p as PasswordPolicyError, u as PasswordCredentialError } from "./chunks/PasswordCredentialService-
|
|
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-
|
|
1
|
+
import { M as LoginRateLimitError, d as PasswordCredentialForbiddenError, f as PasswordCredentialService, g as SessionService, p as PasswordPolicyError, u as PasswordCredentialError } from "./chunks/PasswordCredentialService-D_evcc-I.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-CKw_Aoy1.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";
|