@shivaedev/identity 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -0
- package/README.md +208 -91
- package/dist/PermissionSession.d.ts +11 -0
- package/dist/PermissionSession.d.ts.map +1 -0
- package/dist/PermissionSession.js +6 -0
- package/dist/PermissionSession.js.map +1 -0
- package/dist/authRefusal.d.ts +18 -0
- package/dist/authRefusal.d.ts.map +1 -0
- package/dist/authRefusal.js +11 -0
- package/dist/authRefusal.js.map +1 -0
- package/dist/client/AuthFailure.d.ts +18 -0
- package/dist/client/AuthFailure.d.ts.map +1 -0
- package/dist/client/AuthFailure.js +15 -0
- package/dist/client/AuthFailure.js.map +1 -0
- package/dist/client/AuthFailureCode.d.ts +4 -0
- package/dist/client/AuthFailureCode.d.ts.map +1 -0
- package/dist/client/AuthFailureCode.js +57 -0
- package/dist/client/AuthFailureCode.js.map +1 -0
- package/dist/client/adapters/authCall.d.ts +8 -0
- package/dist/client/adapters/authCall.d.ts.map +1 -0
- package/dist/client/adapters/authCall.js +31 -0
- package/dist/client/adapters/authCall.js.map +1 -0
- package/dist/client/adapters/authQuery.d.ts +5 -0
- package/dist/client/adapters/authQuery.d.ts.map +1 -0
- package/dist/client/adapters/authQuery.js +9 -0
- package/dist/client/adapters/authQuery.js.map +1 -0
- package/dist/client/adapters/authSession.d.ts +9 -0
- package/dist/client/adapters/authSession.d.ts.map +1 -0
- package/dist/client/adapters/authSession.js +20 -0
- package/dist/client/adapters/authSession.js.map +1 -0
- package/dist/client/adapters/changeEmail.d.ts +12 -0
- package/dist/client/adapters/changeEmail.d.ts.map +1 -0
- package/dist/client/adapters/changeEmail.js +5 -0
- package/dist/client/adapters/changeEmail.js.map +1 -0
- package/dist/roles.d.ts +16 -0
- package/dist/roles.d.ts.map +1 -0
- package/dist/roles.js +6 -0
- package/dist/roles.js.map +1 -0
- package/dist/server/UserDirectory.d.ts +14 -0
- package/dist/server/UserDirectory.d.ts.map +1 -0
- package/dist/server/UserDirectory.js +4 -0
- package/dist/server/UserDirectory.js.map +1 -0
- package/dist/server/{local.d.ts → adapters/local.d.ts} +1 -1
- package/dist/server/adapters/local.d.ts.map +1 -0
- package/dist/server/{local.js → adapters/local.js} +7 -6
- package/dist/server/adapters/local.js.map +1 -0
- package/dist/server/adapters/proxyRanges.d.ts.map +1 -0
- package/dist/server/adapters/proxyRanges.js.map +1 -0
- package/dist/server/adapters/trustedOrigins.d.ts +3 -0
- package/dist/server/adapters/trustedOrigins.d.ts.map +1 -0
- package/dist/server/adapters/trustedOrigins.js +10 -0
- package/dist/server/adapters/trustedOrigins.js.map +1 -0
- package/dist/server/adapters/trustedProxy.d.ts.map +1 -0
- package/dist/server/{trustedProxy.js → adapters/trustedProxy.js} +1 -1
- package/dist/server/adapters/trustedProxy.js.map +1 -0
- package/dist/server/adapters/trustedProxyRanges.d.ts.map +1 -0
- package/dist/server/{trustedProxyRanges.js → adapters/trustedProxyRanges.js} +1 -1
- package/dist/server/adapters/trustedProxyRanges.js.map +1 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.d.ts +9 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.d.ts.map +1 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.js +9 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.js.map +1 -0
- package/dist/server/better-auth/accountRoleSeed.d.ts +3 -3
- package/dist/server/better-auth/accountRoleSeed.d.ts.map +1 -1
- package/dist/server/better-auth/accountRoleSeed.js +1 -1
- package/dist/server/better-auth/accountRoleSeed.js.map +1 -1
- package/dist/server/better-auth/adapters/acquire.d.ts +7 -0
- package/dist/server/better-auth/adapters/acquire.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/acquire.js +14 -0
- package/dist/server/better-auth/adapters/acquire.js.map +1 -0
- package/dist/server/better-auth/adapters/assertSchema.d.ts.map +1 -0
- package/dist/server/better-auth/{assertSchema.js → adapters/assertSchema.js} +2 -2
- package/dist/server/better-auth/adapters/assertSchema.js.map +1 -0
- package/dist/server/better-auth/adapters/bearerSessions.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/bearerSessions.js.map +1 -0
- package/dist/server/better-auth/{clientIp.d.ts → adapters/clientIp.d.ts} +4 -3
- package/dist/server/better-auth/adapters/clientIp.d.ts.map +1 -0
- package/dist/server/better-auth/{clientIp.js → adapters/clientIp.js} +7 -5
- package/dist/server/better-auth/adapters/clientIp.js.map +1 -0
- package/dist/server/better-auth/adapters/closeRoleEndpoints.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/closeRoleEndpoints.js.map +1 -0
- package/dist/server/better-auth/adapters/columnDrift.d.ts.map +1 -0
- package/dist/server/better-auth/{columnDrift.js → adapters/columnDrift.js} +1 -1
- package/dist/server/better-auth/adapters/columnDrift.js.map +1 -0
- package/dist/server/better-auth/adapters/emailOptions.d.ts +2 -2
- package/dist/server/better-auth/adapters/emailOptions.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/emailOptions.js +13 -9
- package/dist/server/better-auth/adapters/emailOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/hookRuntime.d.ts +7 -1
- package/dist/server/better-auth/adapters/hookRuntime.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/hookRuntime.js +9 -1
- package/dist/server/better-auth/adapters/hookRuntime.js.map +1 -1
- package/dist/server/better-auth/adapters/migrate.d.ts.map +1 -0
- package/dist/server/better-auth/{migrate.js → adapters/migrate.js} +1 -1
- package/dist/server/better-auth/adapters/migrate.js.map +1 -0
- package/dist/server/better-auth/adapters/migrationPlan.d.ts.map +1 -0
- package/dist/server/better-auth/{migrationPlan.js → adapters/migrationPlan.js} +1 -1
- package/dist/server/better-auth/adapters/migrationPlan.js.map +1 -0
- package/dist/server/better-auth/adapters/migrations/generate.d.ts.map +1 -0
- package/dist/server/better-auth/{migrations → adapters/migrations}/generate.js +1 -1
- package/dist/server/better-auth/adapters/migrations/generate.js.map +1 -0
- package/dist/server/better-auth/{mount.d.ts → adapters/mount.d.ts} +61 -50
- package/dist/server/better-auth/adapters/mount.d.ts.map +1 -0
- package/dist/server/better-auth/{mount.js → adapters/mount.js} +40 -24
- package/dist/server/better-auth/adapters/mount.js.map +1 -0
- package/dist/server/better-auth/adapters/mountedSessions.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/mountedSessions.js.map +1 -0
- package/dist/server/better-auth/adapters/oauthGrants.d.ts +17 -0
- package/dist/server/better-auth/adapters/oauthGrants.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/oauthGrants.js +78 -0
- package/dist/server/better-auth/adapters/oauthGrants.js.map +1 -0
- package/dist/server/better-auth/adapters/oauthProvider.d.ts +18 -0
- package/dist/server/better-auth/adapters/oauthProvider.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/oauthProvider.js +36 -0
- package/dist/server/better-auth/adapters/oauthProvider.js.map +1 -0
- package/dist/server/better-auth/adapters/profileStorage.d.ts +6 -0
- package/dist/server/better-auth/adapters/profileStorage.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/profileStorage.js +13 -0
- package/dist/server/better-auth/adapters/profileStorage.js.map +1 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.d.ts +3 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.js +56 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.js.map +1 -0
- package/dist/server/better-auth/adapters/rateLimitStorage.d.ts +4 -0
- package/dist/server/better-auth/adapters/rateLimitStorage.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/rateLimitStorage.js +14 -0
- package/dist/server/better-auth/adapters/rateLimitStorage.js.map +1 -0
- package/dist/server/better-auth/adapters/response.d.ts +4 -2
- package/dist/server/better-auth/adapters/response.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/response.js +9 -7
- package/dist/server/better-auth/adapters/response.js.map +1 -1
- package/dist/server/better-auth/adapters/roleSeedOptions.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/roleSeedOptions.js +2 -1
- package/dist/server/better-auth/adapters/roleSeedOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/routeHandler.d.ts +5 -0
- package/dist/server/better-auth/adapters/routeHandler.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/routeHandler.js +20 -0
- package/dist/server/better-auth/adapters/routeHandler.js.map +1 -0
- package/dist/server/better-auth/adapters/signInPolicyOptions.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/signInPolicyOptions.js +3 -2
- package/dist/server/better-auth/adapters/signInPolicyOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/storedRoleOptions.js +1 -1
- package/dist/server/better-auth/adapters/storedRoleOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/tables.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/tables.js.map +1 -0
- package/dist/server/better-auth/adapters/testingCredentials.d.ts +4 -0
- package/dist/server/better-auth/adapters/testingCredentials.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/testingCredentials.js +8 -0
- package/dist/server/better-auth/adapters/testingCredentials.js.map +1 -0
- package/dist/server/better-auth/adapters/userDirectory.d.ts +7 -0
- package/dist/server/better-auth/adapters/userDirectory.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/userDirectory.js +20 -0
- package/dist/server/better-auth/adapters/userDirectory.js.map +1 -0
- package/dist/server/better-auth/admittedSessions.d.ts +1 -1
- package/dist/server/better-auth/admittedSessions.d.ts.map +1 -1
- package/dist/server/better-auth/admittedSessions.js +1 -1
- package/dist/server/better-auth/admittedSessions.js.map +1 -1
- package/dist/server/better-auth/assignRole.d.ts +2 -2
- package/dist/server/better-auth/assignRole.d.ts.map +1 -1
- package/dist/server/better-auth/assignRole.js +5 -3
- package/dist/server/better-auth/assignRole.js.map +1 -1
- package/dist/server/better-auth/emails.d.ts +11 -8
- package/dist/server/better-auth/emails.d.ts.map +1 -1
- package/dist/server/better-auth/mountRoutes.d.ts +10 -3
- package/dist/server/better-auth/mountRoutes.d.ts.map +1 -1
- package/dist/server/better-auth/mountRoutes.js +7 -17
- package/dist/server/better-auth/mountRoutes.js.map +1 -1
- package/dist/server/better-auth/testDatabase.js +1 -1
- package/dist/server/better-auth/testDatabase.js.map +1 -1
- package/dist/server/better-auth/testing.d.ts +13 -39
- package/dist/server/better-auth/testing.d.ts.map +1 -1
- package/dist/server/better-auth/testing.js +44 -12
- package/dist/server/better-auth/testing.js.map +1 -1
- package/dist/server/better-auth/userDirectoryReads.d.ts +26 -0
- package/dist/server/better-auth/userDirectoryReads.d.ts.map +1 -0
- package/dist/server/better-auth/userDirectoryReads.js +42 -0
- package/dist/server/better-auth/userDirectoryReads.js.map +1 -0
- package/dist/server/better-auth/userProfiles.d.ts +4 -6
- package/dist/server/better-auth/userProfiles.d.ts.map +1 -1
- package/dist/server/better-auth/userProfiles.js +2 -11
- package/dist/server/better-auth/userProfiles.js.map +1 -1
- package/dist/server/currentSessionContext.d.ts +5 -0
- package/dist/server/currentSessionContext.d.ts.map +1 -0
- package/dist/server/currentSessionContext.js +19 -0
- package/dist/server/currentSessionContext.js.map +1 -0
- package/dist/server/oauthGrants.d.ts +24 -0
- package/dist/server/oauthGrants.d.ts.map +1 -0
- package/dist/server/oauthGrants.js +5 -0
- package/dist/server/oauthGrants.js.map +1 -0
- package/dist/server/origin.d.ts +0 -1
- package/dist/server/origin.d.ts.map +1 -1
- package/dist/server/origin.js +0 -8
- package/dist/server/origin.js.map +1 -1
- package/dist/server/permissions.d.ts.map +1 -1
- package/dist/server/permissions.js +2 -4
- package/dist/server/permissions.js.map +1 -1
- package/dist/server/resolveChanges.d.ts +8 -0
- package/dist/server/resolveChanges.d.ts.map +1 -0
- package/dist/server/resolveChanges.js +13 -0
- package/dist/server/resolveChanges.js.map +1 -0
- package/dist/server/revalidateStream.d.ts +3 -3
- package/dist/server/revalidateStream.d.ts.map +1 -1
- package/dist/server/revalidateStream.js +3 -8
- package/dist/server/revalidateStream.js.map +1 -1
- package/dist/server/session.d.ts +1 -1
- package/dist/server/session.d.ts.map +1 -1
- package/dist/server/session.js +10 -11
- package/dist/server/session.js.map +1 -1
- package/dist/server/tracing.d.ts.map +1 -1
- package/dist/server/tracing.js +3 -7
- package/dist/server/tracing.js.map +1 -1
- package/dist/sessions.d.ts +19 -3
- package/dist/sessions.d.ts.map +1 -1
- package/dist/users.d.ts +29 -0
- package/dist/users.d.ts.map +1 -0
- package/dist/users.js +18 -0
- package/dist/users.js.map +1 -0
- package/package.json +19 -14
- package/src/PermissionSession.ts +7 -0
- package/src/authRefusal.ts +13 -0
- package/src/client/AuthFailure.ts +19 -0
- package/src/client/AuthFailureCode.ts +58 -0
- package/src/client/adapters/authCall.ts +44 -0
- package/src/client/adapters/authQuery.ts +13 -0
- package/src/client/adapters/authSession.ts +30 -0
- package/src/client/adapters/changeEmail.ts +13 -0
- package/src/roles.ts +5 -0
- package/src/server/UserDirectory.ts +14 -0
- package/src/server/{local.ts → adapters/local.ts} +7 -9
- package/src/server/adapters/trustedOrigins.ts +13 -0
- package/src/server/{trustedProxy.ts → adapters/trustedProxy.ts} +1 -1
- package/src/server/{trustedProxyRanges.ts → adapters/trustedProxyRanges.ts} +1 -1
- package/src/server/better-auth/UndeclaredDefaultRole.ts +9 -0
- package/src/server/better-auth/accountRoleSeed.ts +1 -1
- package/src/server/better-auth/adapters/acquire.ts +17 -0
- package/src/server/better-auth/{assertSchema.ts → adapters/assertSchema.ts} +2 -2
- package/src/server/better-auth/{clientIp.ts → adapters/clientIp.ts} +7 -6
- package/src/server/better-auth/{columnDrift.ts → adapters/columnDrift.ts} +1 -1
- package/src/server/better-auth/adapters/emailOptions.ts +21 -9
- package/src/server/better-auth/adapters/hookRuntime.ts +17 -3
- package/src/server/better-auth/{migrate.ts → adapters/migrate.ts} +1 -1
- package/src/server/better-auth/{migrationPlan.ts → adapters/migrationPlan.ts} +1 -1
- package/src/server/better-auth/{migrations → adapters/migrations}/generate.ts +1 -1
- package/src/server/better-auth/{mount.ts → adapters/mount.ts} +66 -29
- package/src/server/better-auth/adapters/oauthGrants.ts +92 -0
- package/src/server/better-auth/adapters/oauthProvider.ts +49 -0
- package/src/server/better-auth/adapters/profileStorage.ts +18 -0
- package/src/server/better-auth/adapters/providerOnlyOptions.ts +63 -0
- package/src/server/better-auth/adapters/rateLimitStorage.ts +23 -0
- package/src/server/better-auth/adapters/response.ts +16 -8
- package/src/server/better-auth/adapters/roleSeedOptions.ts +2 -1
- package/src/server/better-auth/adapters/routeHandler.ts +31 -0
- package/src/server/better-auth/adapters/signInPolicyOptions.ts +3 -2
- package/src/server/better-auth/adapters/storedRoleOptions.ts +1 -1
- package/src/server/better-auth/adapters/testingCredentials.ts +9 -0
- package/src/server/better-auth/adapters/userDirectory.ts +33 -0
- package/src/server/better-auth/admittedSessions.ts +1 -1
- package/src/server/better-auth/assignRole.ts +5 -3
- package/src/server/better-auth/emails.ts +11 -8
- package/src/server/better-auth/mountRoutes.ts +16 -35
- package/src/server/better-auth/testDatabase.ts +1 -1
- package/src/server/better-auth/testing.ts +68 -18
- package/src/server/better-auth/userDirectoryReads.ts +47 -0
- package/src/server/better-auth/userProfiles.ts +6 -12
- package/src/server/currentSessionContext.ts +23 -0
- package/src/server/oauthGrants.ts +23 -0
- package/src/server/origin.ts +0 -10
- package/src/server/permissions.ts +2 -4
- package/src/server/resolveChanges.ts +24 -0
- package/src/server/revalidateStream.ts +4 -8
- package/src/server/session.ts +14 -11
- package/src/server/tracing.ts +4 -9
- package/src/users.ts +19 -0
- package/dist/server/better-auth/assertSchema.d.ts.map +0 -1
- package/dist/server/better-auth/assertSchema.js.map +0 -1
- package/dist/server/better-auth/bearerSessions.d.ts.map +0 -1
- package/dist/server/better-auth/bearerSessions.js.map +0 -1
- package/dist/server/better-auth/clientIp.d.ts.map +0 -1
- package/dist/server/better-auth/clientIp.js.map +0 -1
- package/dist/server/better-auth/closeRoleEndpoints.d.ts.map +0 -1
- package/dist/server/better-auth/closeRoleEndpoints.js.map +0 -1
- package/dist/server/better-auth/columnDrift.d.ts.map +0 -1
- package/dist/server/better-auth/columnDrift.js.map +0 -1
- package/dist/server/better-auth/emailWindow.d.ts +0 -3
- package/dist/server/better-auth/emailWindow.d.ts.map +0 -1
- package/dist/server/better-auth/emailWindow.js +0 -23
- package/dist/server/better-auth/emailWindow.js.map +0 -1
- package/dist/server/better-auth/memoryRateLimit.d.ts +0 -3
- package/dist/server/better-auth/memoryRateLimit.d.ts.map +0 -1
- package/dist/server/better-auth/memoryRateLimit.js +0 -46
- package/dist/server/better-auth/memoryRateLimit.js.map +0 -1
- package/dist/server/better-auth/migrate.d.ts.map +0 -1
- package/dist/server/better-auth/migrate.js.map +0 -1
- package/dist/server/better-auth/migrationPlan.d.ts.map +0 -1
- package/dist/server/better-auth/migrationPlan.js.map +0 -1
- package/dist/server/better-auth/migrations/generate.d.ts.map +0 -1
- package/dist/server/better-auth/migrations/generate.js.map +0 -1
- package/dist/server/better-auth/mount.d.ts.map +0 -1
- package/dist/server/better-auth/mount.js.map +0 -1
- package/dist/server/better-auth/mountedSessions.d.ts.map +0 -1
- package/dist/server/better-auth/mountedSessions.js.map +0 -1
- package/dist/server/better-auth/tables.d.ts.map +0 -1
- package/dist/server/better-auth/tables.js.map +0 -1
- package/dist/server/commandChanges.d.ts +0 -4
- package/dist/server/commandChanges.d.ts.map +0 -1
- package/dist/server/commandChanges.js +0 -48
- package/dist/server/commandChanges.js.map +0 -1
- package/dist/server/local.d.ts.map +0 -1
- package/dist/server/local.js.map +0 -1
- package/dist/server/proxyRanges.d.ts.map +0 -1
- package/dist/server/proxyRanges.js.map +0 -1
- package/dist/server/sessionKeys.d.ts +0 -13
- package/dist/server/sessionKeys.d.ts.map +0 -1
- package/dist/server/sessionKeys.js +0 -27
- package/dist/server/sessionKeys.js.map +0 -1
- package/dist/server/trustedProxy.d.ts.map +0 -1
- package/dist/server/trustedProxy.js.map +0 -1
- package/dist/server/trustedProxyRanges.d.ts.map +0 -1
- package/dist/server/trustedProxyRanges.js.map +0 -1
- package/src/server/better-auth/emailWindow.ts +0 -27
- package/src/server/better-auth/memoryRateLimit.ts +0 -56
- package/src/server/commandChanges.ts +0 -63
- package/src/server/sessionKeys.ts +0 -42
- /package/dist/server/{proxyRanges.d.ts → adapters/proxyRanges.d.ts} +0 -0
- /package/dist/server/{proxyRanges.js → adapters/proxyRanges.js} +0 -0
- /package/dist/server/{trustedProxy.d.ts → adapters/trustedProxy.d.ts} +0 -0
- /package/dist/server/{trustedProxyRanges.d.ts → adapters/trustedProxyRanges.d.ts} +0 -0
- /package/dist/server/better-auth/{assertSchema.d.ts → adapters/assertSchema.d.ts} +0 -0
- /package/dist/server/better-auth/{bearerSessions.d.ts → adapters/bearerSessions.d.ts} +0 -0
- /package/dist/server/better-auth/{bearerSessions.js → adapters/bearerSessions.js} +0 -0
- /package/dist/server/better-auth/{closeRoleEndpoints.d.ts → adapters/closeRoleEndpoints.d.ts} +0 -0
- /package/dist/server/better-auth/{closeRoleEndpoints.js → adapters/closeRoleEndpoints.js} +0 -0
- /package/dist/server/better-auth/{columnDrift.d.ts → adapters/columnDrift.d.ts} +0 -0
- /package/dist/server/better-auth/{migrate.d.ts → adapters/migrate.d.ts} +0 -0
- /package/dist/server/better-auth/{migrationPlan.d.ts → adapters/migrationPlan.d.ts} +0 -0
- /package/dist/server/better-auth/{migrations → adapters/migrations}/generate.d.ts +0 -0
- /package/dist/server/better-auth/{mountedSessions.d.ts → adapters/mountedSessions.d.ts} +0 -0
- /package/dist/server/better-auth/{mountedSessions.js → adapters/mountedSessions.js} +0 -0
- /package/dist/server/better-auth/{tables.d.ts → adapters/tables.d.ts} +0 -0
- /package/dist/server/better-auth/{tables.js → adapters/tables.js} +0 -0
- /package/src/server/{proxyRanges.ts → adapters/proxyRanges.ts} +0 -0
- /package/src/server/better-auth/{bearerSessions.ts → adapters/bearerSessions.ts} +0 -0
- /package/src/server/better-auth/{closeRoleEndpoints.ts → adapters/closeRoleEndpoints.ts} +0 -0
- /package/src/server/better-auth/{mountedSessions.ts → adapters/mountedSessions.ts} +0 -0
- /package/src/server/better-auth/{tables.ts → adapters/tables.ts} +0 -0
package/README.md
CHANGED
|
@@ -75,7 +75,7 @@ Provide one `SessionPolicy` Layer as the host's `sessions` input. Middleware, pe
|
|
|
75
75
|
import { Layer } from "effect";
|
|
76
76
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
77
77
|
import { betterAuthSessions } from "@shivaedev/identity/server/adapters/betterAuthSessions.ts";
|
|
78
|
-
import { trustedOrigins } from "@shivaedev/identity/server/
|
|
78
|
+
import { trustedOrigins } from "@shivaedev/identity/server/adapters/trustedOrigins.ts";
|
|
79
79
|
import { auth } from "./auth.ts";
|
|
80
80
|
|
|
81
81
|
export const sessions = Layer.succeed(SessionPolicy, {
|
|
@@ -92,12 +92,13 @@ The application's `auth` owns its storage and session configuration. A null look
|
|
|
92
92
|
|
|
93
93
|
### Mount Better Auth
|
|
94
94
|
|
|
95
|
-
`betterAuthMount(options)` returns the Better Auth instance and a native route Layer for `/api/auth/*`. It accepts Better Auth options, including application plugins and session policy. Merge `routes` into the HTTP host and use `auth.api.getSession` with `betterAuthSessions` for the application's RPC session provider.
|
|
95
|
+
`betterAuthMount(options)` returns the Better Auth instance and a native route Layer for `/api/auth/*`. It accepts Better Auth options, including application plugins and session policy. Its scoped acquisition waits for the auth context and the provider’s schema check before returning; a provider initialization or schema-check failure logs the redacted cause and fails with `AuthUnavailable`. Building a Layer from this acquisition therefore completes only when authentication is ready. Merge `routes` into the HTTP host and use `auth.api.getSession` with `betterAuthSessions` for the application's RPC session provider.
|
|
96
96
|
|
|
97
97
|
```ts
|
|
98
98
|
import { Effect } from "effect";
|
|
99
99
|
import { betterAuthDatabase } from "@shivaedev/identity/server/better-auth/adapters/database.ts";
|
|
100
|
-
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
100
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
101
|
+
import { memoryStore } from "@shivaedev/rate-limit/memoryStore.ts";
|
|
101
102
|
|
|
102
103
|
const authentication = Effect.gen(function* () {
|
|
103
104
|
const database = yield* betterAuthDatabase();
|
|
@@ -109,25 +110,45 @@ const authentication = Effect.gen(function* () {
|
|
|
109
110
|
});
|
|
110
111
|
```
|
|
111
112
|
|
|
112
|
-
`betterAuthDatabase()` reads the application’s `SqlClient` and reserves connections from its PostgreSQL pool. Build it inside `appHost`’s `application` Effect, or provide sql’s `postgresLayer` for a standalone process. Set `maxConnections` and `applicationName` on the application SQL Layer. Generate frozen numbered auth migrations as described below.
|
|
113
|
+
`betterAuthDatabase()` reads the application’s `SqlClient` and reserves connections from its PostgreSQL pool. Build it inside `appHost`’s `application` Effect, or provide sql’s `postgresLayer` for a standalone process. Set `maxConnections` and `applicationName` on the application SQL Layer. Generate frozen numbered auth migrations as described below. The application SQL Layer owns shutdown.
|
|
114
|
+
|
|
115
|
+
The adapter captures the SQL transaction at creation. An adapter created at startup does not join a later `transact` around an `auth.api` call: its auth writes commit independently and survive the application's rollback. For a shared boundary, create the adapter inside `transact`, and use it only within that transaction. Create the mount there too when its Effect hooks must share the application transaction:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { SqlClient } from "effect/sql";
|
|
119
|
+
import { transact } from "@shivaedev/sql/transact.ts";
|
|
120
|
+
|
|
121
|
+
const register = (body: { email: string; name: string; password: string }) =>
|
|
122
|
+
Effect.gen(function* () {
|
|
123
|
+
const sql = yield* SqlClient.SqlClient;
|
|
124
|
+
const database = yield* betterAuthDatabase();
|
|
125
|
+
const { auth } = yield* betterAuthMount({ database, emailAndPassword: { enabled: true } });
|
|
126
|
+
const created = yield* Effect.tryPromise(() => auth.api.signUpEmail({ body }));
|
|
127
|
+
yield* sql`insert into registrations (email) values (${created.user.email})`;
|
|
128
|
+
return created.user;
|
|
129
|
+
}).pipe(transact({ onSqlError: (error) => error }), Effect.scoped);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
With `SqlClient`, `Reactivity` and `Store` provided, the auth and application rows commit or roll back together. The mount's `before` and `after` hook SQL shares that outer boundary too.
|
|
133
|
+
|
|
134
|
+
Provide `memoryStore` once around the host Layer with `Layer.provide(memoryStore)`, so auth mounts and other rate-limited operations share it. For a standalone authentication Effect, use `authentication.pipe(Effect.provide(memoryStore))`.
|
|
113
135
|
|
|
114
136
|
Run this Effect in the host's scope; the application SQL Layer manages its connections. A rejected auth handler returns HTTP 503 with `Authentication is temporarily unavailable`.
|
|
115
137
|
|
|
116
138
|
The mount reads `BETTER_AUTH_SECRET` unless options supply `secret`. `PUBLIC_URL` supplies the default base URL, trusted origin and HTTPS secure-cookie setting. With it unset, `baseURL.allowedHosts` defaults to `["127.0.0.1:*", "localhost:*"]` over HTTP and `trustedOrigins` defaults to `["http://127.0.0.1:*", "http://localhost:*"]`, accepting both loopback names on any port through a development proxy. Explicit `baseURL` (including `baseURL.allowedHosts`) and `trustedOrigins` options each replace their corresponding default; their lists are not merged. RPC Origin policy remains an application choice.
|
|
117
139
|
|
|
118
|
-
`AUTH_RATE_LIMIT_ENABLED` is a Config boolean that defaults to true and takes precedence over `options.rateLimit.enabled`.
|
|
140
|
+
`AUTH_RATE_LIMIT_ENABLED` is a Config boolean that defaults to true and takes precedence over `options.rateLimit.enabled`. Buckets belong to the host-provided `Store` from `@shivaedev/rate-limit/Store.ts`. Better Auth chooses the rules and client-IP keys; the mount prefixes keys with `identity:auth:` and always uses that Store, overriding Better Auth's `storage` and `customStorage` options. Memory budgets are shared by mounts using the same store and reset when a new host builds a fresh memory store. PostgreSQL budgets are shared across hosts using the same database; include `postgresMigration` from `@shivaedev/rate-limit/adapters/postgresMigration.ts` in the application's numbered migrations and provide `postgresStore` from `@shivaedev/rate-limit/adapters/postgresStore.ts`. Both stores start each window at the first admitted request; refused attempts leave the window unchanged. A refusal returns HTTP 429 with the remaining time rounded up to whole seconds in `X-Retry-After`; a store failure returns HTTP 503.
|
|
119
141
|
|
|
120
|
-
The mount also requires the current account password on `/change-email`.
|
|
142
|
+
The mount also requires the current account password on `/change-email`. Use `changeEmail` from `@shivaedev/identity/client/adapters/changeEmail.ts` with the application's Better Auth client. The browser-safe adapter returns an input-to-Effect function whose `ChangeEmailInput` requires `newEmail` and `password` and accepts an optional `callbackURL`. It maps refusals through `authCall` to typed auth failures, including `INVALID_PASSWORD`.
|
|
121
143
|
|
|
122
144
|
```ts
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
});
|
|
145
|
+
import { changeEmail } from "@shivaedev/identity/client/adapters/changeEmail.ts";
|
|
146
|
+
|
|
147
|
+
const submitEmailChange = changeEmail(authClient);
|
|
148
|
+
yield* submitEmailChange({ newEmail, password: currentPassword });
|
|
128
149
|
```
|
|
129
150
|
|
|
130
|
-
Better Auth's
|
|
151
|
+
Missing, empty, non-string, overlong and incorrect passwords are refused with HTTP 400 and `INVALID_PASSWORD`; accounts without a credential password are also refused. The check uses Better Auth's configured password verifier and applies to cookie and signed bearer sessions before an email can change or a verification email can be sent. Better Auth still owns email verification and the rest of the email-change flow. To use a different account-verification policy, explicitly pass `{ hardening: { requirePasswordForEmailChange: false } }` as the second argument to `betterAuthMount`. Passwordless applications must make this choice before enabling email changes.
|
|
131
152
|
|
|
132
153
|
Password resets revoke existing sessions by default. Set `emailAndPassword.revokeSessionsOnPasswordReset: false` in the Better Auth options to retain them explicitly. These defaults sit alongside the mount's rate limiting; application plugins and the provider's email-change settings remain in effect.
|
|
133
154
|
|
|
@@ -145,7 +166,7 @@ Pass Effect hooks in the mount's second argument under `databaseHooks`. The shap
|
|
|
145
166
|
import type { BetterAuthOptions } from "better-auth";
|
|
146
167
|
import { Context, Effect } from "effect";
|
|
147
168
|
import type { BetterAuthHookError } from "@shivaedev/identity/server/better-auth/databaseHooks.ts";
|
|
148
|
-
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
169
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
149
170
|
|
|
150
171
|
class SessionAdmission extends Context.Service<
|
|
151
172
|
SessionAdmission,
|
|
@@ -170,6 +191,8 @@ Provide the hook's services when building the mount. Mounted HTTP requests run h
|
|
|
170
191
|
|
|
171
192
|
Fail a `before` hook with `{ code: "MEMBERS_ONLY", message: "Membership is required" }`, or an application tagged error with those fields, to refuse the operation with HTTP 403 and that code and message. Defects remain defects in the mounted request, even when Better Auth catches the callback rejection. Hooks follow Better Auth's lifecycle: use `before` to refuse a write; `after` runs after the write and does not undo it.
|
|
172
193
|
|
|
194
|
+
Effect hook SQL uses the hook runtime's Effect context; it does not inherit Better Auth's internal write transaction. In a startup mount, a `before` hook's application SQL can commit even when that hook refuses the operation and Better Auth rolls back its auth rows. Use the transaction-local adapter and mount composition above when those writes must roll back together. Completing an `after` hook does not mean the outer application transaction has committed.
|
|
195
|
+
|
|
173
196
|
Native callbacks in the first argument run before the corresponding Effect callbacks. A native `before` returning `false` stops the Effect callback too. Data changes compose in order. Identity's sign-in policy still runs after the application's session hook.
|
|
174
197
|
|
|
175
198
|
#### Application password-reset hook
|
|
@@ -185,6 +208,24 @@ const authentication = (options: BetterAuthOptions) =>
|
|
|
185
208
|
|
|
186
209
|
The native `emailAndPassword.onPasswordReset` callback runs first. An Effect failure with `BetterAuthHookError` fields reaches the caller as HTTP 403 with its code and message. This callback follows Better Auth's post-reset lifecycle; a failure does not undo the password change.
|
|
187
210
|
|
|
211
|
+
### User directory
|
|
212
|
+
|
|
213
|
+
Applications use the `UserDirectory` port from `@shivaedev/identity/server/UserDirectory.ts` instead of reading auth tables. Provide `betterAuthUserDirectory(AppAccess, authOptions)` from `@shivaedev/identity/server/better-auth/adapters/userDirectory.ts` with the application's SQL Layer. The adapter follows Better Auth's configured user model, name, email, creation and modification columns, and additional-field or plugin role mapping. It shares an existing Reactivity service when supplied and creates one otherwise.
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
import { UserDirectory } from "@shivaedev/identity/server/UserDirectory.ts";
|
|
217
|
+
|
|
218
|
+
const directory = yield* UserDirectory;
|
|
219
|
+
const page = yield* directory.list({ limit: 25 });
|
|
220
|
+
const role = yield* directory.role(userId);
|
|
221
|
+
const changed = yield* directory.assignRole(userId, "member");
|
|
222
|
+
const names = yield* directory.names([userId]);
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
`list` takes `UserListInput` (a limit of 1–100 and an optional exclusive user-id cursor) and returns `UserList`: users ordered by id with id, name, email, declared role and UTC creation time, plus an optional next cursor. `role` and `assignRole` fail with `NotFound` for a missing user. `names` returns existing `{ id, name }` accounts ordered by id, omitting unknown ids and duplicates; an empty request returns no accounts. Storage and decoding failures return `AuthUnavailable`, including an undeclared role requested through the port.
|
|
226
|
+
|
|
227
|
+
The port is for trusted server code; applications authorize callers before using it. Assignments share the transactional last-assigner guard below. Identity exports `userKeys` and `roleKeys` collections from `@shivaedev/identity/users.ts`. Successful role changes announce both user and role item keys after commit, also refreshing their list readers. Contract queries can declare `reads: () => [userKeys.list]` or `reads: ({ userId }) => [roleKeys.item(userId)]`.
|
|
228
|
+
|
|
188
229
|
### Role assignments
|
|
189
230
|
|
|
190
231
|
Pass `{ defaultRole: "member", roles: AppAccess }` as the second argument to `betterAuthMount`. Identity adds `/admin/set-role`, `/admin/update-user` and `/admin/create-user` to the disabled HTTP paths and sets the Better Auth admin plugin's `adminRoles` to `[]`. Existing disabled paths remain in effect. The admin Users page remains the application path for role changes.
|
|
@@ -197,7 +238,7 @@ import { assignRole } from "@shivaedev/identity/server/better-auth/assignRole.ts
|
|
|
197
238
|
yield* assignRole(AppAccess, userId, "owner");
|
|
198
239
|
```
|
|
199
240
|
|
|
200
|
-
Supply the application's `SqlClient` Layer. `assignRole` uses the existing Reactivity service when present and supplies its own when absent, so server-only apps need no Users page or Reactivity Layer. This trusted server verb has no caller authorization check; authorize operator access before calling it. It returns whether the role changed, fails with `NotFound` for a missing user, and refuses to remove the final holder of `AssignRoles` (`roles.assign`) with `LastRoleAssigner`. Both declarations live in `@shivaedev/
|
|
241
|
+
Supply the application's `SqlClient` Layer. `assignRole` uses the existing Reactivity service when present and supplies its own when absent, so server-only apps need no Users page or Reactivity Layer. This trusted server verb has no caller authorization check; authorize operator access before calling it. It returns whether the role changed, fails with `NotFound` for a missing user, and refuses to remove the final holder of `AssignRoles` (`roles.assign`) with `LastRoleAssigner`. Both declarations live in `@shivaedev/identity/roles.ts`. Writes serialize through the same PostgreSQL transaction lock and publish identity’s user and role change keys after commit. The Users page adds its caller permission check and audit log.
|
|
201
242
|
|
|
202
243
|
For custom auth tables, pass the same Better Auth options used by `betterAuthMount` as the fourth argument: `assignRole(AppAccess, userId, "owner", authOptions)`. Role administration uses `user.modelName`, `user.fields.updatedAt` and `user.additionalFields.role.fieldName`. Role-aware migrations and schema checks preserve the role field mapping. Omitting the options keeps Better Auth's default table and column names.
|
|
203
244
|
|
|
@@ -207,10 +248,10 @@ For named provider accounts, declare the role once and pass a configured `accoun
|
|
|
207
248
|
import { Config } from "effect";
|
|
208
249
|
import { role } from "@shivaedev/access/role.ts";
|
|
209
250
|
import { roleSet } from "@shivaedev/access/roleSet.ts";
|
|
210
|
-
import { AssignRoles } from "@shivaedev/
|
|
251
|
+
import { AssignRoles } from "@shivaedev/identity/roles.ts";
|
|
211
252
|
import { accountRoleSeed } from "@shivaedev/identity/server/better-auth/accountRoleSeed.ts";
|
|
212
253
|
import { ProviderAccounts } from "@shivaedev/identity/server/better-auth/allowedAccounts.ts";
|
|
213
|
-
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
254
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
214
255
|
|
|
215
256
|
const Member = role("member", []);
|
|
216
257
|
const Operator = role("operator", [AssignRoles]);
|
|
@@ -278,6 +319,19 @@ Use the WebView's own fetch with `credentials: "omit"` for incremental NDJSON ch
|
|
|
278
319
|
|
|
279
320
|
### Decide who may sign in
|
|
280
321
|
|
|
322
|
+
For applications that sign in only through an OAuth provider, select the provider-only preset:
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
const mounted = yield* betterAuthMount(
|
|
326
|
+
{ database, socialProviders: { github } },
|
|
327
|
+
{ preset: "provider-only" },
|
|
328
|
+
);
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
The preset disables email/password sign-in and sign-up, password reset and change requests, password verification, email change and verification, magic-link sign-in and verification, and every Better Auth admin HTTP endpoint. Closed endpoints answer HTTP 404 even when the admin or magic-link plugin is installed. It strips access, refresh and ID tokens from account creates and updates, disables account cookies and turns off the session cookie cache, including when the supplied Better Auth options enable it. It preserves application hooks and disabled paths. Existing stored credentials are not deleted at startup.
|
|
332
|
+
|
|
333
|
+
Use `{ preset: "provider-only", enabledPaths: ["/admin/list-users"] }` to reopen a single preset endpoint. Better Auth still enforces that endpoint's authentication and permissions. An application `disabledPaths` entry or the mount's role restrictions still closes it. Email/password sign-in remains disabled by the preset; endpoint exceptions do not change that setting. Without a preset, the mount keeps the application's existing sign-in configuration.
|
|
334
|
+
|
|
281
335
|
Give the mount a sign-in policy as its second argument, and resolve RPC sessions through `admittedSessions` so a removal ends access on the next request:
|
|
282
336
|
|
|
283
337
|
```ts
|
|
@@ -285,14 +339,14 @@ import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
|
285
339
|
import { Effect, Layer } from "effect";
|
|
286
340
|
import { allowedAccounts } from "@shivaedev/identity/server/better-auth/allowedAccounts.ts";
|
|
287
341
|
import { betterAuthDatabase } from "@shivaedev/identity/server/better-auth/adapters/database.ts";
|
|
288
|
-
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
289
|
-
import { trustedOrigins } from "@shivaedev/identity/server/
|
|
342
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
343
|
+
import { trustedOrigins } from "@shivaedev/identity/server/adapters/trustedOrigins.ts";
|
|
290
344
|
|
|
291
345
|
const authentication = Effect.gen(function* () {
|
|
292
346
|
const database = yield* betterAuthDatabase();
|
|
293
347
|
const mounted = yield* betterAuthMount(
|
|
294
|
-
{ database,
|
|
295
|
-
{ signIn: { accounts: allowedAccounts, recheckInterval: "5 minutes", rule: inOrganization } },
|
|
348
|
+
{ database, socialProviders: { github } },
|
|
349
|
+
{ preset: "provider-only", signIn: { accounts: allowedAccounts, recheckInterval: "5 minutes", rule: inOrganization } },
|
|
296
350
|
);
|
|
297
351
|
yield* mounted.revokeUnadmitted;
|
|
298
352
|
const sessions = Layer.succeed(SessionPolicy, {
|
|
@@ -342,15 +396,15 @@ export const GreetingHandlers = Greetings.toLayer({
|
|
|
342
396
|
|
|
343
397
|
A missing session produces `Option.none()` here. The same policy still rejects forbidden origins and distinguishes provider failure from an anonymous caller. Signed-in authenticated requests annotate the user's id on logs as `userId` and spans as `user.id`.
|
|
344
398
|
|
|
345
|
-
For an HTTP RPC server that serves only the local machine, wrap its HTTP effect with `localRpcGuard` from `@shivaedev/identity/server/local.ts`. Provide the native `HttpServerRequest` and `RpcSerialization` services around the returned effect, using the same serialization as the RPC server. No session provider is required.
|
|
399
|
+
For an HTTP RPC server that serves only the local machine, wrap its HTTP effect with `localRpcGuard` from `@shivaedev/identity/server/adapters/local.ts`. Provide the native `HttpServerRequest` and `RpcSerialization` services around the returned effect, using the same serialization as the RPC server. No session provider is required.
|
|
346
400
|
|
|
347
401
|
By default, the guard returns HTTP 403 before running the effect unless the transport reports a loopback peer address, the Host is a loopback host, any Origin matches the HTTP Host, and the content type matches the serialization. An absent peer address is rejected, and a DNS-rebinding Host on a loopback connection is refused. The optional second argument, `localRpcGuard(effect, trustedProxy)`, enables the same address and range forwarding policy as `appHost`.
|
|
348
402
|
|
|
349
|
-
The same module exports `loopbackOnly(
|
|
403
|
+
The same module exports `loopbackOnly(effect)` for local page routes, reading `HttpServerRequest` from the Effect environment and `sameOrigin(request)` for an HTTP Origin check. `loopbackOnly` checks Host and any known peer address; it permits an absent peer address so embedded Fetch page handlers remain usable. It does not check Origin or content type.
|
|
350
404
|
|
|
351
405
|
`trustedProxyPeer(trustedProxy?)` compiles the guard's proxy address list into an `(address: string) => boolean` predicate. Use it with the transport's remote address when another route needs the same proxy trust decision. It supports the same IP addresses, CIDR ranges and IPv4-mapped IPv6 peers as `appHost`; absent or malformed configuration matches no peer. It does not read forwarded headers.
|
|
352
406
|
|
|
353
|
-
`trustedProxyRanges(trustedProxy?)` from `@shivaedev/identity/server/trustedProxyRanges.ts` returns the equivalent IP addresses and CIDR ranges used by that matcher. Mapped IPv6 addresses and CIDRs become IPv4 entries: `::ffff:127.0.0.0/104` becomes `127.0.0.0/8`, including hexadecimal mapped forms. Broader IPv6 ranges retain both native IPv6 and mapped IPv4 coverage. Missing or malformed configuration returns an empty list. Pass these ranges to a forwarded-header integration after checking the transport with `trustedProxyPeer`.
|
|
407
|
+
`trustedProxyRanges(trustedProxy?)` from `@shivaedev/identity/server/adapters/trustedProxyRanges.ts` returns the equivalent IP addresses and CIDR ranges used by that matcher. Mapped IPv6 addresses and CIDRs become IPv4 entries: `::ffff:127.0.0.0/104` becomes `127.0.0.0/8`, including hexadecimal mapped forms. Broader IPv6 ranges retain both native IPv6 and mapped IPv4 coverage. Missing or malformed configuration returns an empty list. Pass these ranges to a forwarded-header integration after checking the transport with `trustedProxyPeer`.
|
|
354
408
|
|
|
355
409
|
Declare expected refusals with the shared tagged error schemas from [`@shivaedev/errors`](https://github.com/ShivaeDev/platform/tree/main/packages/errors#readme). They work with native RPC without authentication middleware.
|
|
356
410
|
|
|
@@ -416,12 +470,12 @@ A custom session provider supplies `user.providerAccounts` as a lazy Effect with
|
|
|
416
470
|
|
|
417
471
|
### Reading other users' public profiles
|
|
418
472
|
|
|
419
|
-
Use `userProfiles(
|
|
473
|
+
Use `userProfiles(storage, userIds)` in server code to display the names of users who made changes. Pass the `profiles` port returned by `betterAuthMount` and a list of user IDs. Other storage implementations supply `UserProfileStorage.findByIds`, returning an Effect of public profiles or `AuthUnavailable`; the lookup has no provider dependency.
|
|
420
474
|
|
|
421
475
|
```ts
|
|
422
476
|
import { userProfiles } from "@shivaedev/identity/server/better-auth/userProfiles.ts";
|
|
423
477
|
|
|
424
|
-
const profiles = yield* userProfiles(
|
|
478
|
+
const profiles = yield* userProfiles(mounted.profiles, changedByUserIds);
|
|
425
479
|
```
|
|
426
480
|
|
|
427
481
|
The Effect returns an array of `{ id, name, image }`, with `image: null` when unset and unknown IDs omitted. It reads duplicate IDs once in one storage query through Better Auth's adapter, honoring the application's model and field mappings. An empty list returns an empty array without querying storage. Each lookup reads the current profile, including names changed through Better Auth. The result never includes email, role, session or account data. A storage failure logs its cause in redacted form and fails with a generic `AuthUnavailable`, without exposing provider exception details to the caller.
|
|
@@ -436,7 +490,7 @@ import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
|
436
490
|
import { permission } from "@shivaedev/access/permission.ts";
|
|
437
491
|
import { role } from "@shivaedev/access/role.ts";
|
|
438
492
|
import { roleSet } from "@shivaedev/access/roleSet.ts";
|
|
439
|
-
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
493
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
440
494
|
|
|
441
495
|
const UseTools = permission("tools.use");
|
|
442
496
|
const Access = roleSet(role("member", []), role("operator", [UseTools]));
|
|
@@ -446,7 +500,46 @@ const sessions = Layer.succeed(SessionPolicy, { ...mounted.sessions, origin: tru
|
|
|
446
500
|
|
|
447
501
|
For another session provider, put `roles: Access` alongside `provider` and `origin` in the host's existing `sessions` policy. The provider must read the current stored role on every invocation. `betterAuthMount`'s returned provider and its existing `/api/auth/get-session` endpoint bypass the cookie cache. That endpoint adds `user.permissions`, an array of `{ name, strength }` grants, and the request-local `SessionUser` exposes the same decoded role and grants. A missing or null stored role refuses access with `Forbidden` (HTTP 403 at the session endpoint) and logs the fix: generate and apply a frozen migration with `defaultRole`, then use `assignRole` for administrators. An undeclared non-null stored role fails as a defect naming that role. RPC request tracing logs it as a defect; `/api/auth/get-session` returns HTTP 500. Correct the stored role or restore its application declaration. Provider outages remain `AuthUnavailable`.
|
|
448
502
|
|
|
449
|
-
|
|
503
|
+
### Better Auth client adapters
|
|
504
|
+
|
|
505
|
+
The browser-safe client adapters turn Better Auth Promises into Effects without React or server imports. The application supplies its Better Auth client and owns UI text and session policy.
|
|
506
|
+
|
|
507
|
+
```ts
|
|
508
|
+
import { authCall } from "@shivaedev/identity/client/adapters/authCall.ts";
|
|
509
|
+
import { authQuery } from "@shivaedev/identity/client/adapters/authQuery.ts";
|
|
510
|
+
import { authSession } from "@shivaedev/identity/client/adapters/authSession.ts";
|
|
511
|
+
|
|
512
|
+
const signIn = authCall((credentials: { email: string; password: string }, signal) => authClient.signIn.email(credentials, { signal }));
|
|
513
|
+
const readProviderSession = authQuery((disableCookieCache: boolean, signal) =>
|
|
514
|
+
authClient.getSession({ query: { disableCookieCache }, fetchOptions: { signal } }),
|
|
515
|
+
);
|
|
516
|
+
const session = authSession((signal) => authClient.getSession({ query: { disableCookieCache: true }, fetchOptions: { signal } }));
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
The example uses the application's Better Auth client. `authCall` returns an input-to-Effect function. Its `AuthActionResult<A, E>` response shape is exported from the same module. Failures use `AuthFailure` from `@shivaedev/identity/client/AuthFailure.ts` and the closed `AuthFailureCode` schema and union from `@shivaedev/identity/client/AuthFailureCode.ts`: supported Better Auth core codes, `SIGN_IN_REFUSED` for identity's sign-in policy denial, `AUTH_UNAVAILABLE` for a failed policy check or account role seed, `RATE_LIMITED` for a code-less 429, and `UNKNOWN` for unsupported or missing codes and rejected promises. Identity's server and client read the wire codes from `authRefusals` in `@shivaedev/identity/authRefusal.ts`. The original error stays in `cause`. Applications can supply exhaustive UI text with `Record<AuthFailureCode, string>`.
|
|
520
|
+
|
|
521
|
+
Declare application refusal codes in a shared browser-safe schema and pass its literals as `authCall`'s second argument:
|
|
522
|
+
|
|
523
|
+
```ts
|
|
524
|
+
import { Effect, Schema } from "effect";
|
|
525
|
+
import { authCall } from "@shivaedev/identity/client/adapters/authCall.ts";
|
|
526
|
+
|
|
527
|
+
const ApplicationCode = Schema.Literals(["MEMBERS_ONLY", "MAIL_UNAVAILABLE"]);
|
|
528
|
+
const signIn = authCall(
|
|
529
|
+
(credentials: { email: string; password: string }, signal) => authClient.signIn.email(credentials, { signal }),
|
|
530
|
+
ApplicationCode.literals,
|
|
531
|
+
);
|
|
532
|
+
type SignInFailure = Effect.Error<ReturnType<typeof signIn>>;
|
|
533
|
+
type Messages = Record<SignInFailure["code"], string>;
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
The failure's `_tag` remains `AuthFailure`; its `code` union includes the declared application codes, so `Messages` requires text for each one as well as the standard codes. Database-hook and email-delivery Effects return their application code and message through `BetterAuthHookError`. The mounted HTTP route preserves these refusals even when Better Auth catches an email-delivery error internally. Undeclared codes remain `UNKNOWN`. `AuthFailure.withCodes(ApplicationCode.literals)` supplies the corresponding native error schema when the application needs to decode a failure.
|
|
537
|
+
|
|
538
|
+
`authQuery` returns an input-to-Effect function that preserves returned provider errors and maps rejected Promises to `AuthUnavailable` from `@shivaedev/errors/taxonomy.ts`. Both call adapters pass Effect's abort signal to the supplied client function.
|
|
539
|
+
|
|
540
|
+
`authSession` returns a session Effect with the same read failures. It decodes `user.permissions` through `PermissionSession` from `@shivaedev/identity/PermissionSession.ts` while preserving the provider's session and user data. Its `SessionWithPermissions<A>` type is exported from the adapter. Missing grants stay optional, malformed grants fail with `AuthUnavailable`, and a successful `null` means signed out. The reader must return a nullable session with a `user` object; use `authQuery` for other payloads.
|
|
541
|
+
|
|
542
|
+
React's `authAction`, `authQuery` and `authSession` consume these Effects to create atoms. See [React's Better Auth usage](https://github.com/ShivaeDev/platform/blob/main/packages/react/README.md#better-auth-actions).
|
|
450
543
|
|
|
451
544
|
### Frozen auth migrations
|
|
452
545
|
|
|
@@ -456,7 +549,7 @@ Start with a disposable PostgreSQL database containing only your previously ship
|
|
|
456
549
|
|
|
457
550
|
```ts
|
|
458
551
|
import { FileSystem } from "effect";
|
|
459
|
-
import { generateBetterAuthMigration } from "@shivaedev/identity/server/better-auth/migrations/generate.ts";
|
|
552
|
+
import { generateBetterAuthMigration } from "@shivaedev/identity/server/better-auth/adapters/migrations/generate.ts";
|
|
460
553
|
|
|
461
554
|
const fs = yield* FileSystem.FileSystem;
|
|
462
555
|
const source = yield* generateBetterAuthMigration({ emailAndPassword: { enabled: true } });
|
|
@@ -477,10 +570,12 @@ Review and commit `0002_auth_roles`, then apply it with the other numbered migra
|
|
|
477
570
|
|
|
478
571
|
A numbered migration calling `getMigrations(authOptions)` live is **not frozen**, even if it copies the options into that file: the installed Better Auth version still decides the DDL. `migrateBetterAuth` is also live; use it for disposable test setup, not shipped migrations. It executes compiled DDL on the native SQL connection. Generated modules use a PostgreSQL `DO` block to execute the compiled statements together on that connection.
|
|
479
572
|
|
|
573
|
+
If an application-authored numbered migration calls `auth.api`, create its adapter inside the migration Effect, and its mount there too when using Effect hooks. It then uses the migrator's transaction connection: auth reads and writes can follow auth-table DDL without waiting for another connection, including with a one-connection pool. Reusing a startup adapter instead can wait on the migration's table locks or exhaust the pool.
|
|
574
|
+
|
|
480
575
|
After applying all numbered migrations in an isolated story database, check them against the current options:
|
|
481
576
|
|
|
482
577
|
```ts
|
|
483
|
-
import { assertBetterAuthSchema } from "@shivaedev/identity/server/better-auth/assertSchema.ts";
|
|
578
|
+
import { assertBetterAuthSchema } from "@shivaedev/identity/server/better-auth/adapters/assertSchema.ts";
|
|
484
579
|
|
|
485
580
|
yield* assertBetterAuthSchema(authOptions, { defaultRole: "member" });
|
|
486
581
|
```
|
|
@@ -498,7 +593,7 @@ Identity declares `user.additionalFields.role` when the mount has `roles` and `d
|
|
|
498
593
|
|
|
499
594
|
```ts
|
|
500
595
|
import { assignRole } from "@shivaedev/identity/server/better-auth/assignRole.ts";
|
|
501
|
-
import { generateBetterAuthMigration } from "@shivaedev/identity/server/better-auth/migrations/generate.ts";
|
|
596
|
+
import { generateBetterAuthMigration } from "@shivaedev/identity/server/better-auth/adapters/migrations/generate.ts";
|
|
502
597
|
|
|
503
598
|
const migrationSource = yield* generateBetterAuthMigration(authOptions, { defaultRole: "member" });
|
|
504
599
|
|
|
@@ -546,11 +641,11 @@ An operation on one record reads that record's owner and uses the application's
|
|
|
546
641
|
|
|
547
642
|
### Session-scoped contract keys
|
|
548
643
|
|
|
549
|
-
For self-only features, declare `contract("preferences", { keyScope: "session", queries, commands }).middleware(Authenticated)`.
|
|
644
|
+
For self-only features, declare `contract("preferences", { keyScope: "session", queries, commands }).middleware(Authenticated)`. The client registry owns cache isolation. Server subscriptions use the same plain record, list and bucket keys as repository writes. Handlers read their owner from `Identity`, and queries need no additional session keys. Matching keys trigger each subscriber's read policy before it can receive a hint or result; shared dependencies can cause authorized rechecks across accounts.
|
|
550
645
|
|
|
551
|
-
The host's generated `$changes` handler accepts `{ queries: [{ query: "get", payload: { id: "theme" } }] }
|
|
646
|
+
The host's generated `$changes` handler accepts `{ queries: [{ query: "get", payload: { id: "theme" } }] }` and resolves the declared query dependencies during that subscription invocation. It accepts no physical subscription keys or caller-selected scope.
|
|
552
647
|
|
|
553
|
-
`authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer` and `permissionLayer` run
|
|
648
|
+
`authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer` and `permissionLayer` run command invalidation inside the authenticated invocation. Successful commands publish plain keys after the handler returns and omit keys the handler's transactions already published. Keys that must commit atomically with a write come from the stored model's `bucket()` fields and the repository, rather than command `invalidates`. A rejected transaction publishes no keys.
|
|
554
649
|
|
|
555
650
|
Declared-key publication retries twice, after 50 ms and 100 ms, without rerunning the handler. Exhausted retries preserve the committed result. On a database-backed host, they mark local live streams for Resync and attempt a broadcast Resync on the PostgreSQL change channel. If that broadcast also fails, the server logs that other hosts may remain stale. There is no durable replay: a remote host whose listener remains healthy cannot discover a notification that never reached PostgreSQL. Reconnect or listener recovery reconciles its streams.
|
|
556
651
|
|
|
@@ -558,42 +653,44 @@ Hosted applications use `Api.application.toLayer(...)` and let `appHost` own `$c
|
|
|
558
653
|
|
|
559
654
|
```ts
|
|
560
655
|
import { Effect, Stream } from "effect";
|
|
561
|
-
import { resolveChanges } from "@shivaedev/identity/server/
|
|
656
|
+
import { resolveChanges } from "@shivaedev/identity/server/resolveChanges.ts";
|
|
562
657
|
|
|
563
658
|
const changesRpc = Api.requests.get("preferences.$changes")!;
|
|
564
659
|
const handlers = Api.toLayer({
|
|
565
660
|
"preferences.$changes": ({ queries }) =>
|
|
566
|
-
Stream.unwrap(Effect.map(resolveChanges(changesRpc, queries), (
|
|
661
|
+
Stream.unwrap(Effect.map(resolveChanges(changesRpc, queries), (subscription) => changes.subscribe(subscription))),
|
|
567
662
|
"preferences.get": getPreference,
|
|
568
663
|
"preferences.save": savePreference,
|
|
569
664
|
});
|
|
570
665
|
```
|
|
571
666
|
|
|
572
|
-
Here `changes` is the application's `makeLiveServer` service. Pass the native RPC definition to `resolveChanges` so its typed failures and required services follow the policies declared by that contract. Keep `resolveChanges` in the invocation; resolving it while building a shared Layer would lose request identity. Pass the authorized subscription
|
|
667
|
+
Here `changes` is the application's `makeLiveServer` service. Pass the native RPC definition to `resolveChanges` so its typed failures and required services follow the policies declared by that contract. Keep `resolveChanges` in the invocation; resolving it while building a shared Layer would lose request identity. Pass the authorized subscription to `changes.subscribe`; it uses the query scopes to identify affected references and rechecks the same policies before hints leave.
|
|
573
668
|
|
|
574
|
-
Custom authentication middleware
|
|
669
|
+
Custom authentication middleware validates the transport session and supplies `Identity` and `CurrentViewer`:
|
|
575
670
|
|
|
576
671
|
```ts
|
|
577
672
|
import { Effect, Layer, Option } from "effect";
|
|
578
|
-
import {
|
|
673
|
+
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
579
674
|
import { Identity } from "@shivaedev/identity/identity.ts";
|
|
580
|
-
import { commandChanges } from "@shivaedev/identity/server/commandChanges.ts";
|
|
581
675
|
|
|
582
|
-
const authentication = Layer.succeed(MyAuthentication, (effect, { headers, rpc
|
|
676
|
+
const authentication = Layer.succeed(MyAuthentication, (effect, { headers, rpc }) =>
|
|
583
677
|
Effect.gen(function* () {
|
|
584
678
|
const session = yield* requireTransportSession(headers, rpc);
|
|
585
|
-
return yield*
|
|
679
|
+
return yield* effect.pipe(
|
|
680
|
+
Effect.provideService(CurrentViewer, Option.some({ id: session.user.id })),
|
|
586
681
|
Effect.provideService(Identity, { id: session.user.id }),
|
|
587
682
|
);
|
|
588
683
|
}),
|
|
589
684
|
);
|
|
590
685
|
```
|
|
591
686
|
|
|
592
|
-
`MyAuthentication` declares `provides: Identity
|
|
687
|
+
`MyAuthentication` declares `provides: Identity` and its authentication errors. It supplies the validated session viewer through `CurrentViewer`; contract groups carry their read-policy guard into native `RpcServer` hosts and the application host, evaluating ordinary query policies once per request. Custom hosts serve the contract group directly. Session middleware supplies identity and session validity; the contract guard owns read-policy evaluation. `requireTransportSession` is the application's session validation; use `transportHeaders` or `resolveSession` to read HTTP or WebSocket transport credentials. The identity comes from that validated session on each invocation.
|
|
688
|
+
|
|
689
|
+
The application host installs `CommandGuard` from `@shivaedev/contract/CommandGuard.ts` inside authentication middleware and supplies `commandGuardLayer(publishCommand)`, with `publishCommand` from `@shivaedev/server/publishCommand.ts`. Custom hosts serve `yield* guardCommands(group)` with that layer to publish declared command changes. Identity and tracing middleware do not publish changes. If a raw SQL transaction explicitly announces dependencies, use `invalidationKeys(keys)` with `invalidateOnCommit` inside `transact` so automatic command invalidation can deduplicate the same physical keys.
|
|
593
690
|
|
|
594
691
|
### Session freshness in streams
|
|
595
692
|
|
|
596
|
-
`authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, the role layers and signed-in `maybeAuthenticatedLayer` calls revalidate live RPC streams every 30 seconds by default, using the original transport headers. A signed-out, revoked or expired session ends the stream with `Unauthorized`, including an idle stream and a subscription receiving a change hint. A signed-in viewer whose query read policy now refuses
|
|
693
|
+
`authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, the role layers and signed-in `maybeAuthenticatedLayer` calls revalidate live RPC streams every 30 seconds by default, using the original transport headers. A signed-out, revoked or expired session ends the stream with `Unauthorized`, including an idle stream and a subscription receiving a change hint. A session-backed host reloads the current session for each change hint and supplies its current roles and permissions to the read policy and any pushed query rerun. A signed-in viewer whose query read policy now refuses receives a `QueryReadDenied` delivery on the established subscription. That subscription remains open and resumes delivery on a later authorized hint. Session intervals use Effect’s Clock, so advancing `TestClock` drives revalidation; batched session lookups do not need another clock advance. With a session store that reflects sign-out immediately, delivery can continue for up to that interval plus the session lookup time after sign-out. Provider cookie caching or secondary storage can add their own delay; keep Better Auth's cookie cache disabled for database-backed revocation.
|
|
597
694
|
|
|
598
695
|
Set `streamRevalidationInterval` in the `SessionPolicy` Layer to an Effect `Duration.Input` to change the interval for middleware using that policy:
|
|
599
696
|
|
|
@@ -649,28 +746,27 @@ Use `authTestDatabase` from `@shivaedev/identity/server/better-auth/testDatabase
|
|
|
649
746
|
`authTestDatabase` also exposes `sessionsFor(userId)`, returning that user’s stored sessions as `{ id, expiresAt, expired }`. `expiresAt` is a native Effect UTC value; `expired` compares it with Effect’s current clock. Expired sessions remain visible until removed. Revocation deletes a session, so its id disappears from this readout; it keeps no revocation history. For expiry stories, advance `TestClock` to the minted session’s expiry instead of rewriting storage timestamps. Identity’s Better Auth session provider, session administration list and expired-session sweep use Effect’s clock. Sessions minted by `signedInUser` take their expiry from Effect’s Clock and Better Auth’s configured session lifetime. Better Auth’s own auth endpoints, direct `testUtils` calls and session refresh still use the provider’s clock.
|
|
650
747
|
|
|
651
748
|
```ts
|
|
652
|
-
import {
|
|
653
|
-
import { testUtils } from "better-auth/plugins";
|
|
654
|
-
import { Effect } from "effect";
|
|
749
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
655
750
|
import { signedInUser } from "@shivaedev/identity/server/better-auth/testing.ts";
|
|
656
751
|
|
|
657
|
-
const
|
|
658
|
-
|
|
659
|
-
|
|
752
|
+
const mounted = yield* betterAuthMount(options, {
|
|
753
|
+
defaultRole: "member",
|
|
754
|
+
roles: Access,
|
|
755
|
+
roleSeed,
|
|
756
|
+
});
|
|
757
|
+
// Serve mounted.routes and mounted.sessions through appHost.
|
|
758
|
+
const { user, headers, cookies } = yield* signedInUser(mounted.auth, {
|
|
759
|
+
email: "member@example.test",
|
|
760
|
+
name: "Member",
|
|
761
|
+
providerAccounts: [{ providerId: "github", accountId: "123" }],
|
|
660
762
|
});
|
|
661
|
-
const { user, headers, cookies } = await Effect.runPromise(
|
|
662
|
-
signedInUser(testAuth, {
|
|
663
|
-
email: "member@example.test",
|
|
664
|
-
name: "Member",
|
|
665
|
-
providerAccounts: [{ providerId: "github", accountId: "123" }],
|
|
666
|
-
role: "user,admin",
|
|
667
|
-
}),
|
|
668
|
-
);
|
|
669
763
|
```
|
|
670
764
|
|
|
671
|
-
`
|
|
765
|
+
`signedInUser` uses the host's own auth instance. It needs no `testUtils()` plugin or second Better Auth instance. It saves the supplied user fields, creates each optional `providerAccounts` entry through Better Auth's internal adapter, then mints a session without OAuth or password hashing. The mounted session-create hooks run, including the application's role seed's `onSignIn`; create the provider accounts in the precondition so the real role seed can find them. Omit `role` to use the app's default role and let its role seed assign grants. The accounts carry no tokens or password. Omitting `providerAccounts` creates only the user and session.
|
|
672
766
|
|
|
673
|
-
|
|
767
|
+
The Effect returns Better Auth's login result: the user, session, signed request headers, browser cookies and token. Send `headers` to the real host, or pass `cookies` to test-story's `seedCookies` in a DOM story after setting its host location with `domFetch`. Minting uses the story's Effect Clock. If the story also calls Better Auth's auth endpoints, start its TestClock at the present because those endpoints still check the provider's wall clock. The starter's app and cookie story kits select that default; stories can still pass an explicit `clock`. Keep a real sign-in story for each sign-in flow; feature stories start from the minted precondition.
|
|
768
|
+
|
|
769
|
+
`passwordUser(auth, { email, passwordHash, ...fields })` saves a user and a credential account with a precomputed hash, without hashing or minting a session. Generate the hash once with the application's configured password hasher and keep it as a test fixture alongside its matching password. Then sign in through `/api/auth/sign-in/email` with that password: Better Auth still runs real password verification. A wrong password is refused. Identity's native-session stories use this precondition. The auth instance needs no testing plugin. The existing `passwordUser(auth, { email, password, ...fields })` form hashes with the configured hasher; choose either `passwordHash` or `password`, never both.
|
|
674
770
|
|
|
675
771
|
Call `yield* signInAgain(auth, userId)` from `server/better-auth/testing.ts` to mint a fresh session for an existing user after a long story clock jump. It returns the same login shape as `signedInUser` and sets expiry from the caller’s Effect Clock and the configured session lifetime. Replace the visitor’s request headers or seed the returned browser cookies.
|
|
676
772
|
|
|
@@ -679,7 +775,7 @@ Use `storedProviderAccounts(auth, userId)` to observe credential storage through
|
|
|
679
775
|
```ts
|
|
680
776
|
import { Effect } from "effect";
|
|
681
777
|
import { expect } from "vitest";
|
|
682
|
-
import { seedCookies } from "@shivaedev/test-story/server/seedCookies.ts";
|
|
778
|
+
import { seedCookies } from "@shivaedev/test-story/server/adapters/seedCookies.ts";
|
|
683
779
|
import { signedInUser, storedProviderAccounts } from "@shivaedev/identity/server/better-auth/testing.ts";
|
|
684
780
|
|
|
685
781
|
const member = app.trait("account", "a member starts signed in with GitHub", function* ({ auth }) {
|
|
@@ -729,11 +825,11 @@ const mounted = yield* betterAuthMount(options, {
|
|
|
729
825
|
});
|
|
730
826
|
```
|
|
731
827
|
|
|
732
|
-
`AuthEmail` from `server/better-auth/emails.ts` is a union discriminated by `_tag`: `ConfirmAccount`, `ApproveEmailChange`, `ConfirmNewAddress`, `ResetPassword` and `AccountAlreadyExists`. Each message carries `user` and `url`. All except `AccountAlreadyExists` carry `token`; both change messages also carry `newEmail`, decoded inside identity for the reused verification callback. The new-address message's `user.email` is the destination address. The app URL preserves its own query parameters and receives the token in a `token` query parameter. A confirmation route passes that token to Better Auth's verification API; a reset page submits it with the new password to its reset API.
|
|
828
|
+
`AuthEmail` from `server/better-auth/emails.ts` is a union discriminated by `_tag`: `ConfirmAccount`, `ApproveEmailChange`, `ConfirmNewAddress`, `ResetPassword` and `AccountAlreadyExists`. Each message carries `user` and `url`. The `url` and every `token` are `Redacted<string>` so delivered messages keep their links and tokens hidden in logs and traces. Read them with `Redacted.value(message.url)` or `Redacted.value(message.token)` only when rendering the email or submitting the token. All except `AccountAlreadyExists` carry `token`; both change messages also carry `newEmail`, decoded inside identity for the reused verification callback. The new-address message's `user.email` is the destination address. The app URL preserves its own query parameters and receives the token in a `token` query parameter. A confirmation route passes that token to Better Auth's verification API; a reset page submits it with the new password to its reset API.
|
|
733
829
|
|
|
734
830
|
The wiring replaces the four delivery callbacks and preserves the other Better Auth settings. Enable the flows through native options: `emailAndPassword.enabled`, `emailVerification.sendOnSignUp` or `emailAndPassword.requireEmailVerification`, and `user.changeEmail.enabled`. Better Auth calls `onExistingUserSignUp` only with its generic duplicate-signup response enabled, such as with `requireEmailVerification`.
|
|
735
831
|
|
|
736
|
-
|
|
832
|
+
Auth emails reserve one delivery attempt per account id and message kind for one minute by default in PostgreSQL. Provide the application's PostgreSQL Layer (`SqlClient` and `Reactivity`) to the mount. Include `postgresMigration` from `@shivaedev/rate-limit/adapters/postgresMigration.ts` in the application's numbered migration loader before enabling `emails`. `window` accepts an Effect Duration input. Different accounts and different kinds have separate windows; changing the destination address does not change the account key. Concurrent requests share the reservation, and another delivery is allowed at expiry. Suppressed requests return normally. A failed delivery keeps its reservation until expiry. The window uses database time and survives mount rebuilds and process restarts. Mounts sharing a database share the reservation, regardless of the `Store` supplied for request rate limits. It complements Better Auth's request rate limits. Delivery Effects use the same `BetterAuthHookError` and request runtime as database hooks.
|
|
737
833
|
|
|
738
834
|
### Sweep expired sessions in a worker
|
|
739
835
|
|
|
@@ -745,35 +841,34 @@ Register the Effect with a worker schedule, as the starter does at midnight UTC.
|
|
|
745
841
|
|
|
746
842
|
Import the module that defines the name; there is no package-root entry. Paths below follow `@shivaedev/identity/`.
|
|
747
843
|
|
|
748
|
-
| Module | Names and purpose
|
|
749
|
-
| -------------------------------------------- |
|
|
750
|
-
| `identity.ts` | `RequestId`, `Identity`, `OptionalIdentity`, `SessionUser`, `SessionUserWithProviderAccounts`, `SessionUserSchema`: request-local services and the shared user schema.
|
|
751
|
-
| `middleware.ts` | `RequestTracing`, `Authenticated`, `AuthenticatedUser`, `AuthenticatedUserWithProviderAccounts`, `MaybeAuthenticated`, `IdentityFailures`: native RPC middleware declarations and their shared failure schema.
|
|
752
|
-
| `server/providerFailure.ts` | `providerFailure(cause)`: log a redacted provider failure and fail with `AuthUnavailable`.
|
|
753
|
-
| `permission.ts` | `permissionMiddleware`, `hasPermission`: native permission middleware declarations and predicates over resolved grants.
|
|
754
|
-
| `server/permissions.ts` | `permissionLayer`, `permissionRoute`: permission middleware Layers and HTTP route guards.
|
|
755
|
-
| `server/session.ts` | `authenticatedLayer`, `maybeAuthenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, `withSessionUser`, `resolveSession`: session middleware implementations and the identity boundary.
|
|
756
|
-
| `server/adapters/betterAuthSessions.ts` | `betterAuthSessions(getSession, getProviderAccounts?)`: a session provider from Better Auth lookups.
|
|
757
|
-
| `server/
|
|
758
|
-
| `server/local.ts`
|
|
759
|
-
| `server/trustedProxyRanges.ts`
|
|
760
|
-
| `server/proxyRanges.ts`
|
|
761
|
-
| `server/transportHeaders.ts` | `transportHeaders(rpcHeaders)`: the headers used for a transport-level decision.
|
|
762
|
-
| `server/tracing.ts` | `requestTracingLayer({ header?, sensitive? })`: the `RequestTracing` implementation.
|
|
763
|
-
| `server/
|
|
764
|
-
| `server/
|
|
765
|
-
| `server/better-auth/
|
|
766
|
-
| `server/better-auth/
|
|
767
|
-
| `server/better-auth/
|
|
768
|
-
| `server/better-auth/
|
|
769
|
-
| `server/better-auth/
|
|
770
|
-
| `server/better-auth/
|
|
771
|
-
| `server/better-auth/
|
|
772
|
-
| `server/better-auth/
|
|
773
|
-
| `server/better-auth/
|
|
774
|
-
| `server/better-auth/
|
|
775
|
-
| `server/better-auth/
|
|
776
|
-
| `server/better-auth/testing.ts` | `signedInUser(auth, fields)`, `passwordUser(auth, fields)`, `storedProviderAccounts(auth, userId)`: test-only users, minted sessions and credential storage observations. |
|
|
844
|
+
| Module | Names and purpose |
|
|
845
|
+
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
846
|
+
| `identity.ts` | `RequestId`, `Identity`, `OptionalIdentity`, `SessionUser`, `SessionUserWithProviderAccounts`, `SessionUserSchema`: request-local services and the shared user schema. |
|
|
847
|
+
| `middleware.ts` | `RequestTracing`, `Authenticated`, `AuthenticatedUser`, `AuthenticatedUserWithProviderAccounts`, `MaybeAuthenticated`, `IdentityFailures`: native RPC middleware declarations and their shared failure schema. |
|
|
848
|
+
| `server/providerFailure.ts` | `providerFailure(cause)`: log a redacted provider failure and fail with `AuthUnavailable`. |
|
|
849
|
+
| `permission.ts` | `permissionMiddleware`, `hasPermission`: native permission middleware declarations and predicates over resolved grants. |
|
|
850
|
+
| `server/permissions.ts` | `permissionLayer`, `permissionRoute`: permission middleware Layers and HTTP route guards. |
|
|
851
|
+
| `server/session.ts` | `authenticatedLayer`, `maybeAuthenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, `withSessionUser`, `resolveSession`: session middleware implementations and the identity boundary. |
|
|
852
|
+
| `server/adapters/betterAuthSessions.ts` | `betterAuthSessions(getSession, getProviderAccounts?)`: a session provider from Better Auth lookups. |
|
|
853
|
+
| `server/adapters/trustedOrigins.ts` | `trustedOrigins({ allow, missing })`: an exact Origin allowlist. |
|
|
854
|
+
| `server/adapters/local.ts` | `localRpcGuard`, `loopbackOnly`, `sameOrigin`, `trustedProxyPeer`: loopback and proxy guards. |
|
|
855
|
+
| `server/adapters/trustedProxyRanges.ts` | `trustedProxyRanges(trustedProxy?)`: normalized proxy ranges. |
|
|
856
|
+
| `server/adapters/proxyRanges.ts` | `proxyRanges(value)`: parse configured proxy ranges. |
|
|
857
|
+
| `server/transportHeaders.ts` | `transportHeaders(rpcHeaders)`: the headers used for a transport-level decision. |
|
|
858
|
+
| `server/tracing.ts` | `requestTracingLayer({ header?, sensitive? })`: the `RequestTracing` implementation. |
|
|
859
|
+
| `server/resolveChanges.ts` | `resolveChanges`: authorized change subscriptions for custom change handlers. |
|
|
860
|
+
| `server/better-auth/adapters/mount.ts` | `betterAuthMount(options, { preset?, enabledPaths?, emails?, onPasswordReset?, signIn?, bearerSessions?, roles?, defaultRole?, roleSeed? })`, returning `{ auth, profiles, routes, sessions, admittedSessions, admitsUser, revokeUnadmitted }`: native auth routes and the sign-in policy. |
|
|
861
|
+
| `server/better-auth/adapters/database.ts` | `betterAuthDatabase()`: Better Auth storage on the application PostgreSQL client. |
|
|
862
|
+
| `server/better-auth/emails.ts` | `AuthEmail`, `BetterAuthEmails`: typed delivery messages, app routes and per-account delivery windows for the mount. |
|
|
863
|
+
| `server/better-auth/allowedAccounts.ts` | `ProviderAccounts`, `AllowedAccounts`, `allowedAccounts`: provider-account list Schemas and the non-empty `AUTH_ALLOWED_ACCOUNTS` Config. |
|
|
864
|
+
| `server/better-auth/accountRoleSeed.ts` | `accountRoleSeed(access, role, accounts)`: grant a configured role at boot and sign-in through `assignRole`. |
|
|
865
|
+
| `server/better-auth/signInGate.ts` | `SignInPolicy`: the `accounts`, `rule` and `recheckInterval` of a sign-in policy. |
|
|
866
|
+
| `server/better-auth/revokeUnadmitted.ts` | `RevokedSessions`: the `{ users, sessions }` counts of a revocation. |
|
|
867
|
+
| `server/better-auth/userProfiles.ts` | Public profile lookups for other users. |
|
|
868
|
+
| `server/better-auth/sweepExpiredSessions.ts` | `sweepExpiredSessions`: delete expired sessions through the application's SQL client and return the number removed. |
|
|
869
|
+
| `server/better-auth/userReference.ts` | `userReference`: the default auth user table and id column for application foreign keys. |
|
|
870
|
+
| `server/better-auth/testDatabase.ts` | `authTestDatabase`: test-only identity/session readouts and faults for the default PostgreSQL auth schema. |
|
|
871
|
+
| `server/better-auth/testing.ts` | `signedInUser(auth, fields)`, `passwordUser(auth, fields)`, `storedProviderAccounts(auth, userId)`: test-only users, minted sessions and credential storage observations. |
|
|
777
872
|
|
|
778
873
|
### Install, setup and limits
|
|
779
874
|
|
|
@@ -784,3 +879,25 @@ Install `@shivaedev/identity` with `effect` as its peer. Everything outside `ser
|
|
|
784
879
|
- When composing a native RPC server directly, add `RequestTracing` last on the group so it wraps authentication too; see the [native-server example](https://github.com/ShivaeDev/platform/blob/main/docs/framework/request-context.md#request-id-identity-and-logging). Middleware outside that tracing boundary is responsible for its own diagnostics.
|
|
785
880
|
|
|
786
881
|
The [framework request-context guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/request-context.md) explains the browser and native-client Origin choices.
|
|
882
|
+
|
|
883
|
+
### OAuth grants
|
|
884
|
+
|
|
885
|
+
`OauthGrants` from `@shivaedev/identity/server/oauthGrants.ts` is the environment service for a user's OAuth client consents. The Better Auth adapter supplies its Layer:
|
|
886
|
+
|
|
887
|
+
```ts
|
|
888
|
+
import { Effect } from "effect";
|
|
889
|
+
import { betterAuthOauthGrants } from "@shivaedev/identity/server/better-auth/adapters/oauthGrants.ts";
|
|
890
|
+
import { OauthGrants } from "@shivaedev/identity/server/oauthGrants.ts";
|
|
891
|
+
|
|
892
|
+
const grants = betterAuthOauthGrants({ auth: mounted.auth, admitsUser: mounted.admitsUser });
|
|
893
|
+
const disconnect = Effect.gen(function* () {
|
|
894
|
+
const grants = yield* OauthGrants;
|
|
895
|
+
yield* grants.revokeClient(userId, clientId);
|
|
896
|
+
}).pipe(Effect.provide(grants));
|
|
897
|
+
```
|
|
898
|
+
|
|
899
|
+
`list(userId, { limit, offset })` returns a page of client IDs and consented scopes, ordered by consent ID. `revokeClient(userId, clientId)` and `revokeAllClients(userId)` delete matching consents, stored access tokens and refresh tokens together through Better Auth's transaction adapter. Applications authorize these operations. Storage failures fail with `AuthUnavailable`.
|
|
900
|
+
|
|
901
|
+
After a transport verifies a token, `resolveGrant(grantId, userId, clientId)` returns the current session user and the grant’s live scopes only when that exact consent belongs to the user and client, the user exists, is not banned and passes the mount’s current admission policy. The consent row’s ID is the grant identity; a new consent after revocation has a new ID. It returns `Option.none()` for a refused subject. Grant revocation refuses subsequent resolution; it does not revoke browser sessions. MCP uses this service after checking token signatures, issuer, audience, scope and the `grant_id` reference. It requires `mcp` in the live grant’s scopes on every request.
|
|
902
|
+
|
|
903
|
+
The optional `@better-auth/oauth-provider` peer is exposed through `server/better-auth/adapters/oauthProvider.ts` for provider configuration and discovery. Core identity modules require neither Better Auth nor its OAuth provider.
|