@shivaedev/identity 0.19.0 → 0.21.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 +46 -0
- package/README.md +171 -80
- 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/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 +2 -2
- package/dist/server/better-auth/accountRoleSeed.d.ts.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/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/mount.d.ts +51 -40
- package/dist/server/better-auth/adapters/mount.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/mount.js +19 -6
- package/dist/server/better-auth/adapters/mount.js.map +1 -1
- package/dist/server/better-auth/adapters/oauthGrants.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/oauthGrants.js +17 -7
- package/dist/server/better-auth/adapters/oauthGrants.js.map +1 -1
- package/dist/server/better-auth/adapters/oauthProvider.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/oauthProvider.js +25 -2
- package/dist/server/better-auth/adapters/oauthProvider.js.map +1 -1
- 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/response.d.ts +3 -1
- package/dist/server/better-auth/adapters/response.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/response.js +8 -6
- 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/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/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/assignRole.d.ts +1 -1
- package/dist/server/better-auth/assignRole.d.ts.map +1 -1
- package/dist/server/better-auth/assignRole.js +4 -2
- 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 +1 -0
- package/dist/server/better-auth/mountRoutes.d.ts.map +1 -1
- package/dist/server/better-auth/mountRoutes.js +1 -1
- package/dist/server/better-auth/mountRoutes.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/oauthGrants.d.ts +4 -1
- package/dist/server/oauthGrants.d.ts.map +1 -1
- package/dist/server/oauthGrants.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/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 +22 -6
- 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 +17 -17
- 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/better-auth/UndeclaredDefaultRole.ts +9 -0
- package/src/server/better-auth/adapters/acquire.ts +17 -0
- 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/adapters/mount.ts +38 -7
- package/src/server/better-auth/adapters/oauthGrants.ts +17 -7
- package/src/server/better-auth/adapters/oauthProvider.ts +32 -2
- 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/response.ts +15 -7
- package/src/server/better-auth/adapters/roleSeedOptions.ts +2 -1
- package/src/server/better-auth/adapters/signInPolicyOptions.ts +3 -2
- package/src/server/better-auth/adapters/userDirectory.ts +33 -0
- package/src/server/better-auth/assignRole.ts +4 -2
- package/src/server/better-auth/emails.ts +11 -8
- package/src/server/better-auth/mountRoutes.ts +2 -1
- package/src/server/better-auth/userDirectoryReads.ts +47 -0
- package/src/server/better-auth/userProfiles.ts +6 -12
- package/src/server/oauthGrants.ts +5 -1
- package/src/server/permissions.ts +2 -4
- package/src/server/resolveChanges.ts +24 -0
- 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/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/testing.d.ts +0 -90
- package/dist/server/better-auth/testing.d.ts.map +0 -1
- package/dist/server/better-auth/testing.js +0 -37
- package/dist/server/better-auth/testing.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/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/src/server/better-auth/emailWindow.ts +0 -27
- package/src/server/better-auth/testing.ts +0 -59
- package/src/server/commandChanges.ts +0 -63
- package/src/server/sessionKeys.ts +0 -42
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,51 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.21.0 - 2026-11-03
|
|
4
|
+
|
|
5
|
+
### Breaking
|
|
6
|
+
|
|
7
|
+
- Move `signedInUser`, `signInAgain`, `passwordUser` and `storedProviderAccounts` from `@shivaedev/identity/server/better-auth/testing.ts` to `@shivaedev/test-kits/identity/adapters/betterAuth.ts`. Move `testUserEmail` and `signedSessionToken` from `@shivaedev/identity/server/better-auth/adapters/testingCredentials.ts` to `@shivaedev/test-kits/identity/adapters/testingCredentials.ts`. Add test-kits as a development dependency.
|
|
8
|
+
|
|
9
|
+
## 0.20.0 - 2026-11-03
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Browser client adapters expose Better Auth calls, queries and session reads as Effects, with typed failures and session permission decoding.
|
|
14
|
+
- Reject an undeclared `defaultRole` when mounting Better Auth with a role set. Startup fails with a typed `UndeclaredDefaultRole` error that names the role instead of assigning it to new users.
|
|
15
|
+
- `changeEmail` from `client/adapters/changeEmail.ts` wraps a Better Auth client with an Effect call that requires the current password and returns typed auth failures.
|
|
16
|
+
- Add the `UserDirectory` port for paged users, role reads and guarded assignments, and account names. Provide `betterAuthUserDirectory` with the application's role set, SQL Layer and Better Auth options to honour custom models and field mappings.
|
|
17
|
+
- Export `userKeys` and `roleKeys` from `@shivaedev/identity/users.ts`. Role assignments publish the affected user and role keys after commit.
|
|
18
|
+
- `passwordUser` accepts `passwordHash` to store a precomputed credential while sign-in still verifies the supplied password.
|
|
19
|
+
- Add the `betterAuthMount` provider-only preset to close email/password, magic-link and Better Auth admin HTTP endpoints, omit provider tokens from account writes and disable cookie caching. Apps can explicitly reopen individual preset endpoints with `enabledPaths`.
|
|
20
|
+
- Declare identity's refusal wire codes once and map policy denial to `SIGN_IN_REFUSED` and policy or account-role-seed failure to `AUTH_UNAVAILABLE` in `authCall`.
|
|
21
|
+
- Accept application code literals as `authCall`'s second argument, preserving database-hook and email-delivery codes in its closed failure union. `AuthFailure.withCodes` supplies a native schema for the extended union.
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
|
|
25
|
+
- Publish declared command changes and recover failed publication through `CommandPublication`, preserving the committed command result and its bounded publication retries.
|
|
26
|
+
- `signedInUser`, `signInAgain` and `passwordUser` work with the mounted host's own auth without installing a testing plugin or creating another auth instance. Minted sessions run the mounted session hooks and account role seed.
|
|
27
|
+
|
|
28
|
+
### Fixed
|
|
29
|
+
|
|
30
|
+
- Describe authentication email recipients with their public `id`, `email` and `name` fields without exposing Better Auth's `User` type.
|
|
31
|
+
- Resolve OAuth grant subjects whose temporary ban has expired by Effect Clock. Active bans and bans without an expiry continue to refuse access.
|
|
32
|
+
- Mount Better Auth routes under the configured `basePath`, including session permissions and native session replacement.
|
|
33
|
+
- Return application email-delivery refusals from mounted HTTP requests even when Better Auth catches the delivery error internally.
|
|
34
|
+
|
|
35
|
+
### Breaking
|
|
36
|
+
|
|
37
|
+
- Remove `@shivaedev/identity/server/commandChanges.ts` and its `commandChanges(effect, rpc, payload)` export. Session, permission and tracing middleware no longer publish command changes. Remove command wrappers from custom authentication middleware and supply only the validated viewer and session. Applications using `appHost` get command publication automatically. Custom hosts compose `guardCommands(group)` and `commandGuardLayer(publishCommand)` from `@shivaedev/contract/CommandGuard.ts` with `publishCommand` from `@shivaedev/server/publishCommand.ts`; provide the changes publication port for the chosen transport.
|
|
38
|
+
- Consumers observing role assignments through the former `admin.users` change collection must read `userKeys.list` or `userKeys.item(userId)` from identity. Role readers can use `roleKeys.item(userId)`. Pass these typed keys through `readKeys` when subscribing directly to Reactivity.
|
|
39
|
+
- `signedInUser` and `signInAgain` require the native auth cookie, secret and base URL context instead of only the testing plugin's helpers. Pass the host's `mounted.auth` directly; remove the separate testing auth instance and its `testUtils()` plugin.
|
|
40
|
+
- Auth email messages carry `url` and every `token` as Effect `Redacted<string>`. Apps must use `Redacted.value(message.url)` and `Redacted.value(message.token)` when rendering email content or submitting tokens, and pass the wrapped values directly to redacted queue fields.
|
|
41
|
+
- Replace `OauthGrants.resolveSubject(userId, clientId)` with `resolveGrant(grantId, userId, clientId)`, which returns an optional `{ user, scopes }` containing current grant scopes. Custom service implementations must look up the exact grant and verify its user and client. For custom stores, assign each stored grant an immutable unique ID, preserve it when scopes change, and allocate a fresh ID after revocation. Keep existing Better Auth consent rows and their IDs; no database migration is required. Never reuse a deleted grant ID when importing stored grants. Token issuers must include the consent ID as `grant_id`; `betterAuthOauthProvider` and `mcpProvider` do this automatically.
|
|
42
|
+
- `userProfiles` takes a `UserProfileStorage` port instead of a Better Auth instance. Replace `userProfiles(mounted.auth, ids)` with `userProfiles(mounted.profiles, ids)`, or supply an Effect-based `findByIds` implementation. Its import path and profile result shape stay the same.
|
|
43
|
+
- `betterAuthMount` now waits for the auth context and its schema check during scoped acquisition, failing with `AuthUnavailable` and logging the redacted provider cause when either fails. Apply auth migrations before building the mount Layer, handle this typed startup failure, and remove application readiness wrappers.
|
|
44
|
+
- Auth email limits now use PostgreSQL exclusively and share one per-account, per-kind window across mounts and restarts. Apps configuring `betterAuthMount` with `emails` must provide their PostgreSQL Layer (`SqlClient` and `Reactivity`) to the mount and include `postgresMigration` from `@shivaedev/rate-limit/adapters/postgresMigration.ts` in their numbered migration loader before starting the app. Remove imports of the deleted `server/better-auth/emailWindow.ts` helper. Request rate limits still use the app's supplied store.
|
|
45
|
+
- `sessionKeyContext` and the `@shivaedev/identity/server/sessionKeys.ts` module are removed. Import `resolveChanges` from `@shivaedev/identity/server/resolveChanges.ts` instead. `resolveChanges` now returns the authorized subscription directly, instead of `{ subscription, context }`; pass that result to `subscribe`. Keep request-local identity for read policy and data filtering. Session-scoped queries declare ordinary reads without additional session keys, and shared keys may trigger policy checks for several accounts.
|
|
46
|
+
- Identity's session and permission middleware now supply `CurrentViewer` and validate sessions without authorizing reads. Custom hosts using these layers must install `ReadPolicyGuard` as above. Custom authentication middleware on the application host must provide `CurrentViewer` from the resolved session instead of calling `authorizeReads`; the host performs authorization. Stock `appHost` users need no configuration changes.
|
|
47
|
+
- Exhaustive `AuthFailureCode` mappings must add `SIGN_IN_REFUSED` and `AUTH_UNAVAILABLE`. Handle declared application codes in the extended union returned by calls that pass application code literals.
|
|
48
|
+
|
|
3
49
|
## 0.19.0 - 2026-11-02
|
|
4
50
|
|
|
5
51
|
### Added
|
package/README.md
CHANGED
|
@@ -92,7 +92,7 @@ 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";
|
|
@@ -110,7 +110,26 @@ const authentication = Effect.gen(function* () {
|
|
|
110
110
|
});
|
|
111
111
|
```
|
|
112
112
|
|
|
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.
|
|
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.
|
|
114
133
|
|
|
115
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))`.
|
|
116
135
|
|
|
@@ -120,17 +139,16 @@ The mount reads `BETTER_AUTH_SECRET` unless options supply `secret`. `PUBLIC_URL
|
|
|
120
139
|
|
|
121
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.
|
|
122
141
|
|
|
123
|
-
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`.
|
|
124
143
|
|
|
125
144
|
```ts
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
});
|
|
145
|
+
import { changeEmail } from "@shivaedev/identity/client/adapters/changeEmail.ts";
|
|
146
|
+
|
|
147
|
+
const submitEmailChange = changeEmail(authClient);
|
|
148
|
+
yield* submitEmailChange({ newEmail, password: currentPassword });
|
|
131
149
|
```
|
|
132
150
|
|
|
133
|
-
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.
|
|
134
152
|
|
|
135
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.
|
|
136
154
|
|
|
@@ -173,6 +191,8 @@ Provide the hook's services when building the mount. Mounted HTTP requests run h
|
|
|
173
191
|
|
|
174
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.
|
|
175
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
|
+
|
|
176
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.
|
|
177
197
|
|
|
178
198
|
#### Application password-reset hook
|
|
@@ -188,6 +208,24 @@ const authentication = (options: BetterAuthOptions) =>
|
|
|
188
208
|
|
|
189
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.
|
|
190
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
|
+
|
|
191
229
|
### Role assignments
|
|
192
230
|
|
|
193
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.
|
|
@@ -200,7 +238,7 @@ import { assignRole } from "@shivaedev/identity/server/better-auth/assignRole.ts
|
|
|
200
238
|
yield* assignRole(AppAccess, userId, "owner");
|
|
201
239
|
```
|
|
202
240
|
|
|
203
|
-
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.
|
|
204
242
|
|
|
205
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.
|
|
206
244
|
|
|
@@ -210,7 +248,7 @@ For named provider accounts, declare the role once and pass a configured `accoun
|
|
|
210
248
|
import { Config } from "effect";
|
|
211
249
|
import { role } from "@shivaedev/access/role.ts";
|
|
212
250
|
import { roleSet } from "@shivaedev/access/roleSet.ts";
|
|
213
|
-
import { AssignRoles } from "@shivaedev/
|
|
251
|
+
import { AssignRoles } from "@shivaedev/identity/roles.ts";
|
|
214
252
|
import { accountRoleSeed } from "@shivaedev/identity/server/better-auth/accountRoleSeed.ts";
|
|
215
253
|
import { ProviderAccounts } from "@shivaedev/identity/server/better-auth/allowedAccounts.ts";
|
|
216
254
|
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
@@ -281,6 +319,19 @@ Use the WebView's own fetch with `credentials: "omit"` for incremental NDJSON ch
|
|
|
281
319
|
|
|
282
320
|
### Decide who may sign in
|
|
283
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
|
+
|
|
284
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:
|
|
285
336
|
|
|
286
337
|
```ts
|
|
@@ -294,8 +345,8 @@ import { trustedOrigins } from "@shivaedev/identity/server/adapters/trustedOrigi
|
|
|
294
345
|
const authentication = Effect.gen(function* () {
|
|
295
346
|
const database = yield* betterAuthDatabase();
|
|
296
347
|
const mounted = yield* betterAuthMount(
|
|
297
|
-
{ database,
|
|
298
|
-
{ signIn: { accounts: allowedAccounts, recheckInterval: "5 minutes", rule: inOrganization } },
|
|
348
|
+
{ database, socialProviders: { github } },
|
|
349
|
+
{ preset: "provider-only", signIn: { accounts: allowedAccounts, recheckInterval: "5 minutes", rule: inOrganization } },
|
|
299
350
|
);
|
|
300
351
|
yield* mounted.revokeUnadmitted;
|
|
301
352
|
const sessions = Layer.succeed(SessionPolicy, {
|
|
@@ -419,12 +470,12 @@ A custom session provider supplies `user.providerAccounts` as a lazy Effect with
|
|
|
419
470
|
|
|
420
471
|
### Reading other users' public profiles
|
|
421
472
|
|
|
422
|
-
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.
|
|
423
474
|
|
|
424
475
|
```ts
|
|
425
476
|
import { userProfiles } from "@shivaedev/identity/server/better-auth/userProfiles.ts";
|
|
426
477
|
|
|
427
|
-
const profiles = yield* userProfiles(
|
|
478
|
+
const profiles = yield* userProfiles(mounted.profiles, changedByUserIds);
|
|
428
479
|
```
|
|
429
480
|
|
|
430
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.
|
|
@@ -449,7 +500,46 @@ const sessions = Layer.succeed(SessionPolicy, { ...mounted.sessions, origin: tru
|
|
|
449
500
|
|
|
450
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`.
|
|
451
502
|
|
|
452
|
-
|
|
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).
|
|
453
543
|
|
|
454
544
|
### Frozen auth migrations
|
|
455
545
|
|
|
@@ -480,6 +570,8 @@ Review and commit `0002_auth_roles`, then apply it with the other numbered migra
|
|
|
480
570
|
|
|
481
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.
|
|
482
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
|
+
|
|
483
575
|
After applying all numbered migrations in an isolated story database, check them against the current options:
|
|
484
576
|
|
|
485
577
|
```ts
|
|
@@ -549,11 +641,11 @@ An operation on one record reads that record's owner and uses the application's
|
|
|
549
641
|
|
|
550
642
|
### Session-scoped contract keys
|
|
551
643
|
|
|
552
|
-
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.
|
|
553
645
|
|
|
554
|
-
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.
|
|
555
647
|
|
|
556
|
-
`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.
|
|
557
649
|
|
|
558
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.
|
|
559
651
|
|
|
@@ -561,38 +653,40 @@ Hosted applications use `Api.application.toLayer(...)` and let `appHost` own `$c
|
|
|
561
653
|
|
|
562
654
|
```ts
|
|
563
655
|
import { Effect, Stream } from "effect";
|
|
564
|
-
import { resolveChanges } from "@shivaedev/identity/server/
|
|
656
|
+
import { resolveChanges } from "@shivaedev/identity/server/resolveChanges.ts";
|
|
565
657
|
|
|
566
658
|
const changesRpc = Api.requests.get("preferences.$changes")!;
|
|
567
659
|
const handlers = Api.toLayer({
|
|
568
660
|
"preferences.$changes": ({ queries }) =>
|
|
569
|
-
Stream.unwrap(Effect.map(resolveChanges(changesRpc, queries), (
|
|
661
|
+
Stream.unwrap(Effect.map(resolveChanges(changesRpc, queries), (subscription) => changes.subscribe(subscription))),
|
|
570
662
|
"preferences.get": getPreference,
|
|
571
663
|
"preferences.save": savePreference,
|
|
572
664
|
});
|
|
573
665
|
```
|
|
574
666
|
|
|
575
|
-
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.
|
|
576
668
|
|
|
577
|
-
Custom authentication middleware
|
|
669
|
+
Custom authentication middleware validates the transport session and supplies `Identity` and `CurrentViewer`:
|
|
578
670
|
|
|
579
671
|
```ts
|
|
580
672
|
import { Effect, Layer, Option } from "effect";
|
|
581
|
-
import {
|
|
673
|
+
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
582
674
|
import { Identity } from "@shivaedev/identity/identity.ts";
|
|
583
|
-
import { commandChanges } from "@shivaedev/identity/server/commandChanges.ts";
|
|
584
675
|
|
|
585
|
-
const authentication = Layer.succeed(MyAuthentication, (effect, { headers, rpc
|
|
676
|
+
const authentication = Layer.succeed(MyAuthentication, (effect, { headers, rpc }) =>
|
|
586
677
|
Effect.gen(function* () {
|
|
587
678
|
const session = yield* requireTransportSession(headers, rpc);
|
|
588
|
-
return yield*
|
|
679
|
+
return yield* effect.pipe(
|
|
680
|
+
Effect.provideService(CurrentViewer, Option.some({ id: session.user.id })),
|
|
589
681
|
Effect.provideService(Identity, { id: session.user.id }),
|
|
590
682
|
);
|
|
591
683
|
}),
|
|
592
684
|
);
|
|
593
685
|
```
|
|
594
686
|
|
|
595
|
-
`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.
|
|
596
690
|
|
|
597
691
|
### Session freshness in streams
|
|
598
692
|
|
|
@@ -652,38 +746,37 @@ Use `authTestDatabase` from `@shivaedev/identity/server/better-auth/testDatabase
|
|
|
652
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.
|
|
653
747
|
|
|
654
748
|
```ts
|
|
655
|
-
import {
|
|
656
|
-
import {
|
|
657
|
-
import { Effect } from "effect";
|
|
658
|
-
import { signedInUser } from "@shivaedev/identity/server/better-auth/testing.ts";
|
|
749
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
750
|
+
import { signedInUser } from "@shivaedev/test-kits/identity/adapters/betterAuth.ts";
|
|
659
751
|
|
|
660
|
-
const
|
|
661
|
-
|
|
662
|
-
|
|
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" }],
|
|
663
762
|
});
|
|
664
|
-
const { user, headers, cookies } = await Effect.runPromise(
|
|
665
|
-
signedInUser(testAuth, {
|
|
666
|
-
email: "member@example.test",
|
|
667
|
-
name: "Member",
|
|
668
|
-
providerAccounts: [{ providerId: "github", accountId: "123" }],
|
|
669
|
-
role: "user,admin",
|
|
670
|
-
}),
|
|
671
|
-
);
|
|
672
763
|
```
|
|
673
764
|
|
|
674
|
-
`
|
|
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.
|
|
766
|
+
|
|
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.
|
|
675
768
|
|
|
676
|
-
`passwordUser(auth, { email,
|
|
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.
|
|
677
770
|
|
|
678
|
-
Call `yield* signInAgain(auth, userId)` from
|
|
771
|
+
Call `yield* signInAgain(auth, userId)` from `@shivaedev/test-kits/identity/adapters/betterAuth.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.
|
|
679
772
|
|
|
680
773
|
Use `storedProviderAccounts(auth, userId)` to observe credential storage through Better Auth's internal adapter. It returns account and provider IDs with `hasAccessToken`, `hasRefreshToken`, `hasIdToken` and `hasPassword` booleans. It never returns token values, passwords or password hashes. A DOM story kit that exposes its test auth instance and a session readout can use both helpers:
|
|
681
774
|
|
|
682
775
|
```ts
|
|
683
776
|
import { Effect } from "effect";
|
|
684
777
|
import { expect } from "vitest";
|
|
685
|
-
import { seedCookies } from "@shivaedev/test-story/server/seedCookies.ts";
|
|
686
|
-
import { signedInUser, storedProviderAccounts } from "@shivaedev/identity/
|
|
778
|
+
import { seedCookies } from "@shivaedev/test-story/server/adapters/seedCookies.ts";
|
|
779
|
+
import { signedInUser, storedProviderAccounts } from "@shivaedev/test-kits/identity/adapters/betterAuth.ts";
|
|
687
780
|
|
|
688
781
|
const member = app.trait("account", "a member starts signed in with GitHub", function* ({ auth }) {
|
|
689
782
|
const { cookies } = yield* signedInUser(auth, {
|
|
@@ -732,11 +825,11 @@ const mounted = yield* betterAuthMount(options, {
|
|
|
732
825
|
});
|
|
733
826
|
```
|
|
734
827
|
|
|
735
|
-
`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.
|
|
736
829
|
|
|
737
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`.
|
|
738
831
|
|
|
739
|
-
|
|
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.
|
|
740
833
|
|
|
741
834
|
### Sweep expired sessions in a worker
|
|
742
835
|
|
|
@@ -748,35 +841,33 @@ Register the Effect with a worker schedule, as the starter does at midnight UTC.
|
|
|
748
841
|
|
|
749
842
|
Import the module that defines the name; there is no package-root entry. Paths below follow `@shivaedev/identity/`.
|
|
750
843
|
|
|
751
|
-
| Module | Names and purpose
|
|
752
|
-
| -------------------------------------------- |
|
|
753
|
-
| `identity.ts` | `RequestId`, `Identity`, `OptionalIdentity`, `SessionUser`, `SessionUserWithProviderAccounts`, `SessionUserSchema`: request-local services and the shared user schema.
|
|
754
|
-
| `middleware.ts` | `RequestTracing`, `Authenticated`, `AuthenticatedUser`, `AuthenticatedUserWithProviderAccounts`, `MaybeAuthenticated`, `IdentityFailures`: native RPC middleware declarations and their shared failure schema.
|
|
755
|
-
| `server/providerFailure.ts` | `providerFailure(cause)`: log a redacted provider failure and fail with `AuthUnavailable`.
|
|
756
|
-
| `permission.ts` | `permissionMiddleware`, `hasPermission`: native permission middleware declarations and predicates over resolved grants.
|
|
757
|
-
| `server/permissions.ts` | `permissionLayer`, `permissionRoute`: permission middleware Layers and HTTP route guards.
|
|
758
|
-
| `server/session.ts` | `authenticatedLayer`, `maybeAuthenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, `withSessionUser`, `resolveSession`: session middleware implementations and the identity boundary.
|
|
759
|
-
| `server/adapters/betterAuthSessions.ts` | `betterAuthSessions(getSession, getProviderAccounts?)`: a session provider from Better Auth lookups.
|
|
760
|
-
| `server/adapters/trustedOrigins.ts` | `trustedOrigins({ allow, missing })`: an exact Origin allowlist.
|
|
761
|
-
| `server/adapters/local.ts` | `localRpcGuard`, `loopbackOnly`, `sameOrigin`, `trustedProxyPeer`: loopback and proxy guards.
|
|
762
|
-
| `server/adapters/trustedProxyRanges.ts` | `trustedProxyRanges(trustedProxy?)`: normalized proxy ranges.
|
|
763
|
-
| `server/adapters/proxyRanges.ts` | `proxyRanges(value)`: parse configured proxy ranges.
|
|
764
|
-
| `server/transportHeaders.ts` | `transportHeaders(rpcHeaders)`: the headers used for a transport-level decision.
|
|
765
|
-
| `server/tracing.ts` | `requestTracingLayer({ header?, sensitive? })`: the `RequestTracing` implementation.
|
|
766
|
-
| `server/
|
|
767
|
-
| `server/
|
|
768
|
-
| `server/better-auth/adapters/
|
|
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/
|
|
777
|
-
| `server/better-auth/
|
|
778
|
-
| `server/better-auth/testDatabase.ts` | `authTestDatabase`: test-only identity/session readouts and faults for the default PostgreSQL auth schema. |
|
|
779
|
-
| `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. |
|
|
780
871
|
|
|
781
872
|
### Install, setup and limits
|
|
782
873
|
|
|
@@ -806,6 +897,6 @@ const disconnect = Effect.gen(function* () {
|
|
|
806
897
|
|
|
807
898
|
`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`.
|
|
808
899
|
|
|
809
|
-
After a transport verifies a token, `
|
|
900
|
+
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.
|
|
810
901
|
|
|
811
902
|
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.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
export declare const PermissionSession: Schema.Struct<{
|
|
3
|
+
readonly user: Schema.Struct<{
|
|
4
|
+
readonly permissions: Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
5
|
+
readonly name: Schema.String;
|
|
6
|
+
readonly strength: Schema.Literals<readonly ["own", "any"]>;
|
|
7
|
+
}>>>;
|
|
8
|
+
}>;
|
|
9
|
+
}>;
|
|
10
|
+
export type PermissionSession = typeof PermissionSession.Type;
|
|
11
|
+
//# sourceMappingURL=PermissionSession.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PermissionSession.d.ts","sourceRoot":"","sources":["../src/PermissionSession.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,eAAO,MAAM,iBAAiB;;;;;;;EAE5B,CAAC;AACH,MAAM,MAAM,iBAAiB,GAAG,OAAO,iBAAiB,CAAC,IAAI,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import { Permission } from "@shivaedev/access/permission.ts";
|
|
3
|
+
export const PermissionSession = Schema.Struct({
|
|
4
|
+
user: Schema.Struct({ permissions: Schema.optionalKey(Schema.Array(Permission)) }),
|
|
5
|
+
});
|
|
6
|
+
//# sourceMappingURL=PermissionSession.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PermissionSession.js","sourceRoot":"","sources":["../src/PermissionSession.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7D,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC9C,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;CAClF,CAAC,CAAC"}
|