@shivaedev/identity 0.11.1 → 0.13.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +100 -9
  3. package/dist/server/better-auth/accountRoleSeed.d.ts +12 -0
  4. package/dist/server/better-auth/accountRoleSeed.d.ts.map +1 -0
  5. package/dist/server/better-auth/accountRoleSeed.js +28 -0
  6. package/dist/server/better-auth/accountRoleSeed.js.map +1 -0
  7. package/dist/server/better-auth/adapters/roleSeedOptions.d.ts +4 -0
  8. package/dist/server/better-auth/adapters/roleSeedOptions.d.ts.map +1 -0
  9. package/dist/server/better-auth/adapters/roleSeedOptions.js +34 -0
  10. package/dist/server/better-auth/adapters/roleSeedOptions.js.map +1 -0
  11. package/dist/server/better-auth/adapters/storedRoleOptions.d.ts +6 -0
  12. package/dist/server/better-auth/adapters/storedRoleOptions.d.ts.map +1 -0
  13. package/dist/server/better-auth/adapters/storedRoleOptions.js +16 -0
  14. package/dist/server/better-auth/adapters/storedRoleOptions.js.map +1 -0
  15. package/dist/server/better-auth/allowedAccounts.d.ts +4 -0
  16. package/dist/server/better-auth/allowedAccounts.d.ts.map +1 -1
  17. package/dist/server/better-auth/allowedAccounts.js +2 -1
  18. package/dist/server/better-auth/allowedAccounts.js.map +1 -1
  19. package/dist/server/better-auth/assertSchema.d.ts +12 -0
  20. package/dist/server/better-auth/assertSchema.d.ts.map +1 -0
  21. package/dist/server/better-auth/assertSchema.js +19 -0
  22. package/dist/server/better-auth/assertSchema.js.map +1 -0
  23. package/dist/server/better-auth/assignRole.d.ts +1 -1
  24. package/dist/server/better-auth/assignRole.d.ts.map +1 -1
  25. package/dist/server/better-auth/assignRole.js +4 -1
  26. package/dist/server/better-auth/assignRole.js.map +1 -1
  27. package/dist/server/better-auth/columnDrift.d.ts +6 -0
  28. package/dist/server/better-auth/columnDrift.d.ts.map +1 -0
  29. package/dist/server/better-auth/columnDrift.js +54 -0
  30. package/dist/server/better-auth/columnDrift.js.map +1 -0
  31. package/dist/server/better-auth/migrate.d.ts +6 -0
  32. package/dist/server/better-auth/migrate.d.ts.map +1 -0
  33. package/dist/server/better-auth/migrate.js +9 -0
  34. package/dist/server/better-auth/migrate.js.map +1 -0
  35. package/dist/server/better-auth/migrationPlan.d.ts +12 -0
  36. package/dist/server/better-auth/migrationPlan.d.ts.map +1 -0
  37. package/dist/server/better-auth/migrationPlan.js +37 -0
  38. package/dist/server/better-auth/migrationPlan.js.map +1 -0
  39. package/dist/server/better-auth/migrations/generate.d.ts +5 -0
  40. package/dist/server/better-auth/migrations/generate.d.ts.map +1 -0
  41. package/dist/server/better-auth/migrations/generate.js +8 -0
  42. package/dist/server/better-auth/migrations/generate.js.map +1 -0
  43. package/dist/server/better-auth/mount.d.ts +11 -4
  44. package/dist/server/better-auth/mount.d.ts.map +1 -1
  45. package/dist/server/better-auth/mount.js +8 -4
  46. package/dist/server/better-auth/mount.js.map +1 -1
  47. package/dist/server/better-auth/mountRoutes.d.ts.map +1 -1
  48. package/dist/server/better-auth/mountRoutes.js +1 -1
  49. package/dist/server/better-auth/mountRoutes.js.map +1 -1
  50. package/dist/server/better-auth/sessionPermissions.d.ts +2 -1
  51. package/dist/server/better-auth/sessionPermissions.d.ts.map +1 -1
  52. package/dist/server/better-auth/sessionPermissions.js.map +1 -1
  53. package/dist/server/better-auth/testDatabase.d.ts +11 -0
  54. package/dist/server/better-auth/testDatabase.d.ts.map +1 -1
  55. package/dist/server/better-auth/testDatabase.js +10 -0
  56. package/dist/server/better-auth/testDatabase.js.map +1 -1
  57. package/dist/server/lookupSession.d.ts +2 -2
  58. package/dist/server/lookupSession.d.ts.map +1 -1
  59. package/dist/server/permissions.d.ts +6 -3
  60. package/dist/server/permissions.d.ts.map +1 -1
  61. package/dist/server/permissions.js.map +1 -1
  62. package/dist/server/resolveRole.d.ts +2 -1
  63. package/dist/server/resolveRole.d.ts.map +1 -1
  64. package/dist/server/resolveRole.js +4 -0
  65. package/dist/server/resolveRole.js.map +1 -1
  66. package/dist/sessions.d.ts +4 -4
  67. package/dist/sessions.d.ts.map +1 -1
  68. package/package.json +10 -10
  69. package/src/server/better-auth/accountRoleSeed.ts +40 -0
  70. package/src/server/better-auth/adapters/roleSeedOptions.ts +39 -0
  71. package/src/server/better-auth/adapters/storedRoleOptions.ts +21 -0
  72. package/src/server/better-auth/allowedAccounts.ts +4 -2
  73. package/src/server/better-auth/assertSchema.ts +24 -0
  74. package/src/server/better-auth/assignRole.ts +4 -1
  75. package/src/server/better-auth/columnDrift.ts +67 -0
  76. package/src/server/better-auth/migrate.ts +14 -0
  77. package/src/server/better-auth/migrationPlan.ts +43 -0
  78. package/src/server/better-auth/migrations/generate.ts +13 -0
  79. package/src/server/better-auth/mount.ts +14 -7
  80. package/src/server/better-auth/mountRoutes.ts +8 -1
  81. package/src/server/better-auth/sessionPermissions.ts +2 -1
  82. package/src/server/better-auth/testDatabase.ts +11 -0
  83. package/src/server/permissions.ts +5 -3
  84. package/src/server/resolveRole.ts +9 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,54 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0 - 2026-10-31
4
+
5
+ ### Added
6
+
7
+ - Admin pages can declare a detail path under `route.detail`. `adminDocuments` and `adminPermissionGuard` use the registered page's permission for its list and detail paths.
8
+ - Identity permission layers accept native context keys for permission middleware.
9
+ - Generate frozen PostgreSQL auth migration modules containing checked-in SQL with no Better Auth runtime dependency. Check migrated databases against current auth options and report missing tables, fields, indexes, types and nullability changes.
10
+ - Generated applications ship frozen auth migrations, retain their Quality configuration, and include a PostgreSQL story that checks their current auth options for drift.
11
+ - Baseline entries accept an optional `reason`, preserved when debt is lowered or moved.
12
+ - Identity mounts accept a configured `accountRoleSeed` to grant a role to named provider accounts at boot and sign-in through the guarded `assignRole` path. The shared `ProviderAccounts` schema accepts empty lists for seeds while `AllowedAccounts` continues to require at least one account.
13
+
14
+ ### Changed
15
+
16
+ - Generated applications declare their owner seed from `AUTH_OWNER_ACCOUNTS`, with empty and unset lists granting nothing.
17
+
18
+ ### Fixed
19
+
20
+ - Generated apps use admin registration for permission layers and guard each admin document by its registered page.
21
+ - Execute live auth migration DDL through the native SQL transaction connection, so a preceding migration referencing users cannot block a later auth alteration through another pool.
22
+ - Trusted `assignRole` commands work without an application Reactivity Layer and preserve an existing service for commit invalidation.
23
+
24
+ ### Breaking
25
+
26
+ - Admin registrations install their pages' permission middleware and require `AdminSessions` when their handler layer builds. Provide `Layer.succeed(AdminSessions, sessions)` once at the host instead of installing each page's `permissionLayer` by hand. Missing policy fails startup with the page id and permission name.
27
+ - Declare page middleware with identity’s `permissionMiddleware` so it provides `Identity` and `SessionUser` with the shared identity failures.
28
+ - Generated apps import `ReadStatistics` from `#ReadStatistics.ts` and `StatisticsPermission` from `#modules/notes/StatisticsPermission.ts`; migrate custom imports of `#appPermissions.ts` when applying the template update.
29
+ - `authColumnDrift` decodes PostgreSQL catalog rows and can fail with `SchemaError`. Callers that restrict its error channel to `SqlError` must also handle `SchemaError`.
30
+ - `suppressions/no-double-cast` reports hidden casts outside adapters and test kits: annotated JSON parsing, unchecked reflection bindings, SQL row generics, unchecked identity overloads, Context retagging and writes to readonly or native lifecycle fields. Decode unknown data with `Schema.decodeUnknownEffect` or `SqlSchema`, check implementation return types, and preserve native Context and lifecycle types. Existing repositories can record retained findings during first adoption with a reason.
31
+
32
+ ## 0.12.0 - 2026-10-31
33
+
34
+ ### Added
35
+
36
+ - `migrateBetterAuth` runs Better Auth schema migrations using the database from Effect's SQL service. Applications pass auth configuration without a database pool.
37
+ - Generated applications mount roles through identity, migrate the stored default through a numbered migration, and bootstrap the first owner through `assignRole`.
38
+ - Declare the user role field and its sign-up default through identity, and adopt existing users with `migrateBetterAuth(options, { defaultRole })` without an application backfill. Fresh and upgraded PostgreSQL schemas have the same non-null text column and database default.
39
+ - Let identity's database story kit migrate schemas with or without roles, inspect the stored role column and user roles, and model a missing role.
40
+
41
+ ### Fixed
42
+
43
+ - Generated applications start with no quality baseline and rely on the jobs package’s peer installation of `pg-boss`.
44
+ - Loaded editors construct their form from the supplied row without an unreachable synchronous guard.
45
+ - Refuse missing stored roles with `Forbidden` and log the migration fix instead of failing requests with a defect.
46
+
47
+ ### Breaking
48
+
49
+ - `registerAdmin` reports missing or extra page handlers as defects when its handler Layer is built. Consumers that catch synchronous registration errors must instead observe Layer acquisition failures.
50
+ - Pass `defaultRole` alongside `roles` to `betterAuthMount`. Remove application-owned role `additionalFields` and Better Auth's `admin()` plugin if it was only supplying roles. Add and run a numbered `migrateBetterAuth(options, { defaultRole })` migration before deploying, then bootstrap administrators through `assignRole`.
51
+
3
52
  ## 0.11.1 - 2026-10-31
4
53
 
5
54
  ### Changed
package/README.md CHANGED
@@ -107,7 +107,7 @@ const authentication = Effect.gen(function* () {
107
107
  });
108
108
  ```
109
109
 
110
- `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. The adapter also works with Better Auth’s `getMigrations`; create it inside a SQL transaction when auth writes must commit or roll back with application writes. The application SQL Layer owns shutdown.
110
+ `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. Create the database adapter inside a SQL transaction when auth writes must commit or roll back with application writes. The application SQL Layer owns shutdown.
111
111
 
112
112
  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`.
113
113
 
@@ -137,7 +137,7 @@ For email sign-in through `appHost`, the session record's `ipAddress` follows th
137
137
 
138
138
  ### Role assignments
139
139
 
140
- Pass `{ 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.
140
+ 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.
141
141
 
142
142
  Seeds and trusted operator commands use the same transactional write and last-role-assigner guard as the Users page:
143
143
 
@@ -147,7 +147,36 @@ import { assignRole } from "@shivaedev/identity/server/better-auth/assignRole.ts
147
147
  yield* assignRole(AppAccess, userId, "owner");
148
148
  ```
149
149
 
150
- Supply the application's `SqlClient` and `Reactivity` Layers. 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/access/roles.ts`. Writes serialize through the same PostgreSQL transaction lock and invalidate the Users list after commit. The Users page adds its caller permission check and audit log.
150
+ 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/access/roles.ts`. Writes serialize through the same PostgreSQL transaction lock and invalidate the Users list after commit. The Users page adds its caller permission check and audit log.
151
+
152
+ For named provider accounts, declare the role once and pass a configured `accountRoleSeed` to the mount:
153
+
154
+ ```ts
155
+ import { Config } from "effect";
156
+ import { role } from "@shivaedev/access/role.ts";
157
+ import { roleSet } from "@shivaedev/access/roleSet.ts";
158
+ import { AssignRoles } from "@shivaedev/access/roles.ts";
159
+ import { accountRoleSeed } from "@shivaedev/identity/server/better-auth/accountRoleSeed.ts";
160
+ import { ProviderAccounts } from "@shivaedev/identity/server/better-auth/allowedAccounts.ts";
161
+ import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
162
+
163
+ const Member = role("member", []);
164
+ const Operator = role("operator", [AssignRoles]);
165
+ const AppAccess = roleSet(Member, Operator);
166
+ const operators = Config.schema(ProviderAccounts, "AUTH_OPERATOR_ACCOUNTS").pipe(Config.withDefault([]));
167
+
168
+ const mounted = yield* betterAuthMount(authOptions, {
169
+ defaultRole: Member.name,
170
+ roles: AppAccess,
171
+ roleSeed: accountRoleSeed(AppAccess, Operator.name, operators),
172
+ });
173
+ ```
174
+
175
+ Set `AUTH_OPERATOR_ACCOUNTS=github:1001,github:1002` using stable provider account IDs. `ProviderAccounts` shares the parser and account-ID validation of `AllowedAccounts`, while accepting an empty list. `Config.withDefault([])` also accepts an unset variable. Both grant nothing. Invalid entries fail boot with `ConfigError`.
176
+
177
+ The mount runs the seed at boot for existing users and before creating sign-in sessions, including the first provider sign-in. A listed account that has never signed in is ignored until it does. Assignments go through `assignRole`, including its last-role-assigner guard and commit invalidation. The seed uses the application's SQL Layer and default Better Auth PostgreSQL tables.
178
+
179
+ The seed only grants: removing an account from config does not restore its previous role. To demote it, first remove the account from config and restart the server, then assign the desired role through the Users page or a trusted `assignRole` command. Keep another holder of `AssignRoles` before demoting the last administrator. A still-listed account receives the configured role again on sign-in or boot.
151
180
 
152
181
  ### Administer signed-in sessions
153
182
 
@@ -350,11 +379,72 @@ import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts
350
379
 
351
380
  const UseTools = permission("tools.use");
352
381
  const Access = roleSet(role("member", []), role("operator", [UseTools]));
353
- const mounted = yield* betterAuthMount(authOptions, { roles: Access });
382
+ const mounted = yield* betterAuthMount(authOptions, { defaultRole: "member", roles: Access });
354
383
  const sessions = { ...mounted.sessions, origin: trustedOrigins({ allow: ["https://app.example.com"], missing: "reject" }) };
355
384
  ```
356
385
 
357
- 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. An undeclared 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`.
386
+ 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`.
387
+
388
+ ### Frozen auth migrations
389
+
390
+ Generate each auth migration once, review its SQL and commit the generated module. `generateBetterAuthMigration(options, roleOptions?)` reads the current PostgreSQL schema through `SqlClient` and returns a TypeScript migration module. It does not apply the migration. The module imports only native Effect and executes fixed SQL on the migrator's transaction connection. Later auth option changes and Better Auth upgrades cannot change its SQL.
391
+
392
+ Start with a disposable PostgreSQL database containing only your previously shipped migrations. For the first auth migration that means an empty auth schema. In a scoped generation script with `postgresLayer` and Node services provided:
393
+
394
+ ```ts
395
+ import { FileSystem } from "effect";
396
+ import { generateBetterAuthMigration } from "@shivaedev/identity/server/better-auth/migrations/generate.ts";
397
+
398
+ const fs = yield* FileSystem.FileSystem;
399
+ const source = yield* generateBetterAuthMigration({ emailAndPassword: { enabled: true } });
400
+ yield* fs.writeFileString("src/server/migrations/0001_auth.ts", source, { flag: "wx" });
401
+ ```
402
+
403
+ Apply `0001_auth` through `migratePostgres`. When options change, such as adding `user.additionalFields.role`, keep `0001_auth` unchanged. Generate a new file against a database with the previous migrations applied:
404
+
405
+ ```ts
406
+ const source = yield* generateBetterAuthMigration({
407
+ emailAndPassword: { enabled: true },
408
+ user: { additionalFields: { role: { type: "string", required: true, defaultValue: "member" } } },
409
+ });
410
+ yield* fs.writeFileString("src/server/migrations/0002_auth_roles.ts", source, { flag: "wx" });
411
+ ```
412
+
413
+ Review and commit `0002_auth_roles`, then apply it with the other numbered migrations. If the app uses Quality, register each reviewed generated file in `boundaries/auth-sql`'s `options.owners` in its `quality.config.ts`; the generated file owns auth DDL, while application queries continue to use identity. For identity-managed roles, pass `{ defaultRole: "member" }` as the second argument instead of configuring the field yourself; its generated SQL also freezes the default, null backfill and NOT NULL constraint.
414
+
415
+ 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.
416
+
417
+ After applying all numbered migrations in an isolated story database, check them against the current options:
418
+
419
+ ```ts
420
+ import { assertBetterAuthSchema } from "@shivaedev/identity/server/better-auth/assertSchema.ts";
421
+
422
+ yield* assertBetterAuthSchema(authOptions, { defaultRole: "member" });
423
+ ```
424
+
425
+ `assertBetterAuthSchema` fails with `BetterAuthSchemaDrift`, whose `missing` entries name missing tables, columns and configured indexes, incompatible column types and missing NOT NULL constraints. It also reports an optional field whose existing non-null column has neither a database default nor an auth field default. With identity role options it checks the role default. A newly added `user.role` reports `column user.role` until the next migration is generated **and applied**. Generation follows Better Auth's additive migration planner; type and nullability changes may require reviewed, application-authored SQL in a new migration. The check does not compare arbitrary application constraints or detect changes to default functions.
426
+
427
+ The starter ships checked-in SQL for its auth migrations and checks all numbered migrations against current auth options in its PostgreSQL stories.
428
+
429
+ ### Adopting stored roles with existing users
430
+
431
+ Identity declares `user.additionalFields.role` when the mount has `roles` and `defaultRole`. Choose a default from your application's role set, such as `member`. It is a required string and cannot be supplied by sign-up input. No `additionalFields` entry or Better Auth `admin()` plugin is needed.
432
+ 1. Generate a new numbered application migration with `generateBetterAuthMigration(authOptions, { defaultRole: "member" })`, following the frozen workflow above. Run it before deploying the mount with roles. PostgreSQL fills existing users when the column is added; identity also fills null roles when adopting a nullable role column. Both fresh and upgraded schemas finish with a `text NOT NULL DEFAULT 'member'` column. The migration keeps existing non-null roles.
433
+ 2. Mount with `betterAuthMount(authOptions, { defaultRole: "member", roles: Access })`, using the same default as the migration. New users get that role. Remove any app-owned role field configuration and the admin plugin if you used it only for roles.
434
+ 3. In a trusted server-side bootstrap process, call `assignRole(Access, existingUserId, "admin")` to make the first administrator. Provide the application's SQL Layer, as for other role changes. Alternatively, configure `accountRoleSeed` on the mount for named provider accounts. `Access` must declare `admin` with the permissions that administrator needs, including `AssignRoles` to manage other users. Do not expose the bootstrap process as an unauthenticated endpoint.
435
+
436
+ ```ts
437
+ import { assignRole } from "@shivaedev/identity/server/better-auth/assignRole.ts";
438
+ import { generateBetterAuthMigration } from "@shivaedev/identity/server/better-auth/migrations/generate.ts";
439
+
440
+ const migrationSource = yield* generateBetterAuthMigration(authOptions, { defaultRole: "member" });
441
+
442
+ const changed = yield* assignRole(Access, existingUserId, "admin");
443
+ ```
444
+
445
+ Use a numbered migration for schema adoption and a separate bootstrap command for the assignment. Existing sessions read the stored role on their next request. In an isolated story database, `const storage = yield* authTestDatabase; yield* storage.migrate(authOptions)` builds the schema without a role field when the options omit it; store users through `signedInUser`, then call `storage.migrate(authOptions, { defaultRole: "member" })` to exercise adoption without writing SQL against auth tables.
446
+
447
+ ### Permission middleware
358
448
 
359
449
  Declare a native middleware service for each required permission and provide its Layer beside the handlers:
360
450
 
@@ -489,7 +579,7 @@ Run the auth schema migration before the app migration. Use `ON DELETE CASCADE`
489
579
 
490
580
  Use `testUtils()` from `better-auth/plugins` in a test-only Better Auth instance with the host's database, secret and cookie policy. Keep the plugin out of production auth options.
491
581
 
492
- Use `authTestDatabase` from `@shivaedev/identity/server/better-auth/testDatabase.ts` when a story needs observations or faults in the default Better Auth PostgreSQL schema. It returns Effect readouts `users` (IDs and emails) and `sessions` (IDs, user IDs and emails), plus the test-only faults `expireSessions(userId?)` and `omitImageColumn`. Pass a user id to expire only that user's sessions, or call `expireSessions()` to expire every session. It never returns tokens, password hashes or provider credentials. These fixtures assume the default table and column mappings and read `SqlClient` from the Effect environment; use only an isolated test database. Application stories keep their auth SQL in this provider-owned boundary.
582
+ Use `authTestDatabase` from `@shivaedev/identity/server/better-auth/testDatabase.ts` when a story needs observations or faults in the default Better Auth PostgreSQL schema. It returns Effect readouts `users` (IDs and emails) and `sessions` (IDs, user IDs and emails), plus `migrate(options, roleOptions?)`, `roleColumn` (PostgreSQL type, nullability and default), `userRoles` (emails and roles), and the test-only faults `expireSessions(userId?)`, `omitImageColumn` and `omitRole(userId)`. The last fault makes a role nullable and clears that user's role to model a partial migration. Pass a user id to expire only that user's sessions, or call `expireSessions()` to expire every session. It never returns tokens, password hashes or provider credentials. These fixtures assume the default table and column mappings and read `SqlClient` from the Effect environment; use only an isolated test database. Application stories keep their auth SQL in this provider-owned boundary.
493
583
 
494
584
  `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. Better Auth’s own auth endpoints, session creation and refresh still use the provider’s clock.
495
585
 
@@ -510,7 +600,7 @@ const { user, headers, cookies } = await signedInUser(testAuth, {
510
600
  });
511
601
  ```
512
602
 
513
- `options` is the application's auth configuration. `signedInUser` saves the supplied user fields, creates each optional `providerAccounts` entry for that user through Better Auth's internal adapter, and mints one session through Better Auth's `testUtils`, without OAuth or password hashing. The accounts carry no tokens or password. Omitting `providerAccounts` creates only the user and session. It returns Better Auth's login result: the user, session, signed request headers, browser cookies and token. Roles require the application's role plugin, such as Better Auth's `admin()`. 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`. Keep a real sign-in story for each sign-in flow; feature stories start from the minted precondition.
603
+ `options` is the application's auth configuration. `signedInUser` saves the supplied user fields, creates each optional `providerAccounts` entry for that user through Better Auth's internal adapter, and mints one session through Better Auth's `testUtils`, without OAuth or password hashing. The accounts carry no tokens or password. Omitting `providerAccounts` creates only the user and session. It returns Better Auth's login result: the user, session, signed request headers, browser cookies and token. To mint users with roles, use the auth instance returned by `betterAuthMount(options, { defaultRole: "member", roles: Access })`. 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`. Keep a real sign-in story for each sign-in flow; feature stories start from the minted precondition.
514
604
 
515
605
  `passwordUser(auth, { email, password, ...fields })` from the same testing module saves a user and a credential account using Better Auth's configured password hasher, and returns an Effect containing the user without minting a session. Use it for the one story that signs in through `/api/auth/sign-in/email`; keep feature stories on `signedInUser` so they avoid password hashing.
516
606
 
@@ -578,9 +668,10 @@ Import the module that defines the name; there is no package-root entry. Paths b
578
668
  | `server/tracing.ts` | `requestTracingLayer({ header?, sensitive? })`: the `RequestTracing` implementation. |
579
669
  | `server/sessionKeys.ts` | `resolveChanges`: session-scoped change subscriptions for custom change handlers. |
580
670
  | `server/commandChanges.ts` | `commandChanges(effect, rpc, payload)`: scoped command invalidation for custom authentication middleware. |
581
- | `server/better-auth/mount.ts` | `betterAuthMount(options, { signIn?, bearerSessions?, roles? })`, returning `{ auth, routes, sessions, admittedSessions, revokeUnadmitted }`: native auth routes and the sign-in policy. |
671
+ | `server/better-auth/mount.ts` | `betterAuthMount(options, { signIn?, bearerSessions?, roles?, defaultRole?, roleSeed? })`, returning `{ auth, routes, sessions, admittedSessions, revokeUnadmitted }`: native auth routes and the sign-in policy. |
582
672
  | `server/better-auth/adapters/database.ts` | `betterAuthDatabase()`: Better Auth storage on the application PostgreSQL client. |
583
- | `server/better-auth/allowedAccounts.ts` | `AllowedAccounts`, `allowedAccounts`: the provider-account list Schema and its `AUTH_ALLOWED_ACCOUNTS` Config. |
673
+ | `server/better-auth/allowedAccounts.ts` | `ProviderAccounts`, `AllowedAccounts`, `allowedAccounts`: provider-account list Schemas and the non-empty `AUTH_ALLOWED_ACCOUNTS` Config. |
674
+ | `server/better-auth/accountRoleSeed.ts` | `accountRoleSeed(access, role, accounts)`: grant a configured role at boot and sign-in through `assignRole`. |
584
675
  | `server/better-auth/signInGate.ts` | `SignInPolicy`: the `accounts`, `rule` and `recheckInterval` of a sign-in policy. |
585
676
  | `server/better-auth/revokeUnadmitted.ts` | `RevokedSessions`: the `{ users, sessions }` counts of a revocation. |
586
677
  | `server/better-auth/userProfiles.ts` | Public profile lookups for other users. |
@@ -0,0 +1,12 @@
1
+ import { type Config, Effect } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ import type { AccessPolicy } from "@shivaedev/access/roleSet.ts";
4
+ import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
5
+ import type { ProviderAccountValue } from "#identity.ts";
6
+ export interface AccountRoleSeed<E> {
7
+ readonly onSignIn: (userId: string) => Effect.Effect<void, E>;
8
+ }
9
+ export declare const accountRoleSeed: <TRole extends string>(access: Pick<AccessPolicy<TRole>, "Role" | "hasPermission">, role: NoInfer<TRole>, accounts: Config.Config<readonly ProviderAccountValue[]>) => Effect.Effect<{
10
+ onSignIn: (userId: string) => Effect.Effect<void, AuthUnavailable | import("@shivaedev/access/roles.ts").LastRoleAssigner | import("@shivaedev/errors/taxonomy.ts").NotFound, never>;
11
+ }, AuthUnavailable | Config.ConfigError | import("@shivaedev/access/roles.ts").LastRoleAssigner | import("@shivaedev/errors/taxonomy.ts").NotFound, SqlClient.SqlClient>;
12
+ //# sourceMappingURL=accountRoleSeed.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountRoleSeed.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/accountRoleSeed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AACrD,OAAO,EAAE,SAAS,EAAa,MAAM,YAAY,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAGzD,MAAM,WAAW,eAAe,CAAC,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;CAC9D;AAED,eAAO,MAAM,eAAe,GAAoD,KAAK,SAAS,MAAM;uBA2BvE,MAAM;wKACjC,CAAC"}
@@ -0,0 +1,28 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { SqlClient, SqlSchema } from "effect/sql";
3
+ import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
4
+ import { assignRole } from "./assignRole.js";
5
+ export const accountRoleSeed = Effect.fn("Identity.accountRoleSeed")(function* (access, role, accounts) {
6
+ const listed = yield* accounts;
7
+ const context = yield* Effect.context();
8
+ const sql = yield* SqlClient.SqlClient;
9
+ const findUsers = SqlSchema.findAll({
10
+ execute: ({ accountId, providerId, userId }) => sql `
11
+ select distinct "userId" as id from "account"
12
+ where "providerId" = ${providerId} and "accountId" = ${accountId}
13
+ ${userId === undefined ? sql.literal("") : sql `and "userId" = ${userId}`}`,
14
+ Request: Schema.Struct({ accountId: Schema.String, providerId: Schema.String, userId: Schema.optional(Schema.String) }),
15
+ Result: Schema.Struct({ id: Schema.String }),
16
+ });
17
+ const apply = Effect.fnUntraced(function* (userId) {
18
+ for (const account of listed) {
19
+ const users = yield* findUsers({ ...account, userId }).pipe(Effect.mapError(() => new AuthUnavailable({ message: "Could not access provider accounts" })));
20
+ for (const user of users) {
21
+ yield* assignRole(access, user.id, role);
22
+ }
23
+ }
24
+ });
25
+ yield* apply();
26
+ return { onSignIn: (userId) => apply(userId).pipe(Effect.provideContext(context)) };
27
+ });
28
+ //# sourceMappingURL=accountRoleSeed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountRoleSeed.js","sourceRoot":"","sources":["../../../src/server/better-auth/accountRoleSeed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEhE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAM7C,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,EAAE,CAAC,0BAA0B,CAAC,CAAC,QAAQ,CAAC,EAC7E,MAA2D,EAC3D,IAAoB,EACpB,QAAwD;IAExD,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC;IAC/B,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,EAAuB,CAAC;IAC7D,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC;IACvC,MAAM,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC;QACnC,OAAO,EAAE,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,CAAA;;0BAE3B,UAAU,sBAAsB,SAAS;KAC9D,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA,kBAAkB,MAAM,EAAE,EAAE;QAC3E,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QACvH,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;KAC5C,CAAC,CAAC;IACH,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,MAAe;QACzD,KAAK,MAAM,OAAO,IAAI,MAAM,EAAE,CAAC;YAC9B,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,SAAS,CAAC,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,IAAI,CAC1D,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,eAAe,CAAC,EAAE,OAAO,EAAE,oCAAoC,EAAE,CAAC,CAAC,CAC7F,CAAC;YACF,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;gBAC1B,KAAK,CAAC,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;YAC1C,CAAC;QACF,CAAC;IACF,CAAC,CAAC,CAAC;IACH,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC;IACf,OAAO,EAAE,QAAQ,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;AAC7F,CAAC,CAAC,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { BetterAuthOptions } from "better-auth";
2
+ import type { AccountRoleSeed } from "#server/better-auth/accountRoleSeed.ts";
3
+ export declare function roleSeedOptions<E>(options: BetterAuthOptions, seed: AccountRoleSeed<E> | undefined): BetterAuthOptions;
4
+ //# sourceMappingURL=roleSeedOptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roleSeedOptions.d.ts","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/roleSeedOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAIrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAE9E,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,eAAe,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,iBAAiB,CAgCtH"}
@@ -0,0 +1,34 @@
1
+ import { APIError } from "better-auth/api";
2
+ import { Effect, Exit } from "effect";
3
+ import { redact } from "@shivaedev/errors/redact.ts";
4
+ export function roleSeedOptions(options, seed) {
5
+ if (seed === undefined) {
6
+ return options;
7
+ }
8
+ const own = options.databaseHooks?.session?.create?.before;
9
+ return {
10
+ ...options,
11
+ databaseHooks: {
12
+ ...options.databaseHooks,
13
+ session: {
14
+ ...options.databaseHooks?.session,
15
+ create: {
16
+ ...options.databaseHooks?.session?.create,
17
+ before: async (session, endpoint) => {
18
+ const result = await own?.(session, endpoint);
19
+ if (result === false) {
20
+ return result;
21
+ }
22
+ const userId = typeof result === "object" && typeof result.data.userId === "string" ? result.data.userId : session.userId;
23
+ const exit = await Effect.runPromise(Effect.exit(seed.onSignIn(userId).pipe(Effect.tapCause((cause) => Effect.logError("Account role seed failed", redact(cause))))), { signal: endpoint?.request?.signal });
24
+ if (Exit.isFailure(exit)) {
25
+ throw new APIError("SERVICE_UNAVAILABLE", { code: "role_seed_failed", message: "Sign-in is temporarily unavailable" });
26
+ }
27
+ return result;
28
+ },
29
+ },
30
+ },
31
+ },
32
+ };
33
+ }
34
+ //# sourceMappingURL=roleSeedOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roleSeedOptions.js","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/roleSeedOpt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AQ,CAAC,0BAA0B,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAC/H,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,CACrC,CAAC;wBACF,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC;4BAC1B,MAAM,IAAI,QAAQ,CAAC,qBAAqB,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,OAAO,EAAE,oCAAoC,EAAE,CAAC,CAAC;wBACxH,CAAC;wBACD,OAAO,MAAM,CAAC;oBACf,CAAC;iBACD;aACD;SACD;KACD,CAAC;AACH,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { BetterAuthOptions } from "better-auth";
2
+ export interface StoredRoleOptions {
3
+ readonly defaultRole: string;
4
+ }
5
+ export declare function storedRoleOptions<TOptions extends BetterAuthOptions>(options: TOptions, role?: StoredRoleOptions): TOptions;
6
+ //# sourceMappingURL=storedRoleOptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storedRoleOptions.d.ts","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/storedRoleOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC7B;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,SAAS,iBAAiB,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,iBAAiB,GAAG,QAAQ,CAc3H"}
@@ -0,0 +1,16 @@
1
+ export function storedRoleOptions(options, role) {
2
+ if (role === undefined) {
3
+ return options;
4
+ }
5
+ return {
6
+ ...options,
7
+ user: {
8
+ ...options.user,
9
+ additionalFields: {
10
+ ...options.user?.additionalFields,
11
+ role: { defaultValue: role.defaultRole, input: false, required: true, type: "string" },
12
+ },
13
+ },
14
+ };
15
+ }
16
+ //# sourceMappingURL=storedRoleOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storedRoleOptions.js","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/storedRoleOptions.ts"],"names":[],"mappings":"AAMA,MAAM,UAAU,iBAAiB,CAAqC,OAAiB,EAAE,IAAwB;IAChH,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,OAAO,CAAC;IAChB,CAAC;IACD,OAAO;QACN,GAAG,OAAO;QACV,IAAI,EAAE;YACL,GAAG,OAAO,CAAC,IAAI;YACf,gBAAgB,EAAE;gBACjB,GAAG,OAAO,CAAC,IAAI,EAAE,gBAAgB;gBACjC,IAAI,EAAE,EAAE,YAAY,EAAE,IAAI,CAAC,WAAW,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE;aACtF;SACD;KACD,CAAC;AACH,CAAC"}
@@ -1,4 +1,8 @@
1
1
  import { Config, Schema } from "effect";
2
+ export declare const ProviderAccounts: Schema.decodeTo<Schema.$Array<Schema.decodeTo<Schema.Struct<{
3
+ readonly accountId: Schema.String;
4
+ readonly providerId: Schema.NonEmptyString;
5
+ }>, Schema.String, never, never>>, Schema.String, never, never>;
2
6
  export declare const AllowedAccounts: Schema.decodeTo<Schema.$Array<Schema.decodeTo<Schema.Struct<{
3
7
  readonly accountId: Schema.String;
4
8
  readonly providerId: Schema.NonEmptyString;
@@ -1 +1 @@
1
- {"version":3,"file":"allowedAccounts.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/allowedAccounts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAU,MAAM,EAAgB,MAAM,QAAQ,CAAC;AAwB9D,eAAO,MAAM,eAAe;;;+DAU3B,CAAC;AAEF,eAAO,MAAM,eAAe;;;IAA0D,CAAC"}
1
+ {"version":3,"file":"allowedAccounts.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/allowedAccounts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAU,MAAM,EAAgB,MAAM,QAAQ,CAAC;AAwB9D,eAAO,MAAM,gBAAgB;;;+DAU5B,CAAC;AAEF,eAAO,MAAM,eAAe;;;+DAAgD,CAAC;AAE7E,eAAO,MAAM,eAAe;;;IAA0D,CAAC"}
@@ -14,12 +14,13 @@ const AccountEntry = Schema.String.pipe(Schema.decodeTo(ProviderAccount, {
14
14
  }),
15
15
  encode: SchemaGetter.transform(({ accountId, providerId }) => `${providerId}:${accountId}`),
16
16
  }));
17
- export const AllowedAccounts = Schema.String.pipe(Schema.decodeTo(Schema.Array(AccountEntry).check(Schema.isMinLength(1)), {
17
+ export const ProviderAccounts = Schema.String.pipe(Schema.decodeTo(Schema.Array(AccountEntry), {
18
18
  decode: SchemaGetter.transform((value) => value
19
19
  .split(",")
20
20
  .map((entry) => entry.trim())
21
21
  .filter((entry) => entry.length > 0)),
22
22
  encode: SchemaGetter.transform((entries) => entries.join(",")),
23
23
  }));
24
+ export const AllowedAccounts = ProviderAccounts.check(Schema.isMinLength(1));
24
25
  export const allowedAccounts = Config.schema(AllowedAccounts, "AUTH_ALLOWED_ACCOUNTS");
25
26
  //# sourceMappingURL=allowedAccounts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"allowedAccounts.js","sourceRoot":"","sources":["../../../src/server/better-auth/allowedAccounts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAE9D,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,EAAE,QAAQ,EAAE,2CAA2C,EAAE,CAAC,CAAC,CAAC;AAEtI,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,cAAc,EAAE,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M,EAAE,YAAY,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CACxC,KAAK;SACH,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;SAC5B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CACrC;IACD,MAAM,EAAE,YAAY,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;CAC9D,CAAC,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,eAAe,GAAG,gBAAgB,CAAC,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;AAE7E,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,eAAe,EAAE,uBAAuB,CAAC,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { BetterAuthOptions } from "better-auth";
2
+ import { Effect, Schema } from "effect";
3
+ import { type StoredRoleOptions } from "#server/better-auth/adapters/storedRoleOptions.ts";
4
+ declare const BetterAuthSchemaDrift_base: Schema.Class<BetterAuthSchemaDrift, Schema.TaggedStruct<"BetterAuthSchemaDrift", {
5
+ readonly missing: Schema.$Array<Schema.String>;
6
+ }>, import("effect/Cause").YieldableError>;
7
+ export declare class BetterAuthSchemaDrift extends BetterAuthSchemaDrift_base {
8
+ get message(): string;
9
+ }
10
+ export declare const assertBetterAuthSchema: (options: Omit<BetterAuthOptions, "database">, role?: StoredRoleOptions | undefined) => Effect.Effect<undefined, BetterAuthSchemaDrift | Schema.SchemaError | import("effect/sql/SqlError").SqlError | import("effect/Cause").UnknownError, import("effect/Scope").Scope | import("effect/sql/SqlClient").SqlClient>;
11
+ export {};
12
+ //# sourceMappingURL=assertSchema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertSchema.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/assertSchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,KAAK,iBAAiB,EAAqB,MAAM,mDAAmD,CAAC;;;;AAI9G,qBAAa,qBAAsB,SAAQ,0BAEzC;IACD,IAAa,OAAO,WAEnB;CACD;AAED,eAAO,MAAM,sBAAsB,sTASjC,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { storedRoleOptions } from "#server/better-auth/adapters/storedRoleOptions.ts";
3
+ import { authColumnDrift } from "./columnDrift.js";
4
+ import { betterAuthMigrationPlan } from "./migrationPlan.js";
5
+ export class BetterAuthSchemaDrift extends Schema.TaggedError()("BetterAuthSchemaDrift", {
6
+ missing: Schema.Array(Schema.String),
7
+ }) {
8
+ get message() {
9
+ return `Auth schema needs a new migration:\n${this.missing.join("\n")}`;
10
+ }
11
+ }
12
+ export const assertBetterAuthSchema = Effect.fn("Identity.assertBetterAuthSchema")(function* (options, role) {
13
+ const { missing } = yield* betterAuthMigrationPlan(options, role, { throwOnUnsafe: false });
14
+ missing.push(...(yield* authColumnDrift(storedRoleOptions(options, role), role)));
15
+ if (missing.length > 0) {
16
+ return yield* new BetterAuthSchemaDrift({ missing });
17
+ }
18
+ });
19
+ //# sourceMappingURL=assertSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertSchema.js","sourceRoot":"","sources":["../../../src/server/better-auth/assertSchema.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAA0B,iBAAiB,EAAE,MAAM,mDAAmD,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAE7D,MAAM,OAAO,qBAAsB,SAAQ,MAAM,CAAC,WAAW,EAAyB,CAAC,uBAAuB,EAAE;IAC/G,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC;CACpC,CAAC;IACD,IAAa,OAAO;QACnB,OAAO,uCAAuC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;IACzE,CAAC;CACD;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC,EAAE,CAAC,iCAAiC,CAAC,CAAC,QAAQ,CAAC,EAC3F,OAA4C,EAC5C,IAAwB;IAExB,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,CAAC,uBAAuB,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5F,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,eAAe,CAAC,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAClF,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxB,OAAO,KAAK,CAAC,CAAC,IAAI,qBAAqB,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;IACtD,CAAC;AACF,CAAC,CAAC,CAAC"}
@@ -3,5 +3,5 @@ import { SqlClient } from "effect/sql";
3
3
  import type { AccessPolicy } from "@shivaedev/access/roleSet.ts";
4
4
  import { LastRoleAssigner } from "@shivaedev/access/roles.ts";
5
5
  import { AuthUnavailable, NotFound } from "@shivaedev/errors/taxonomy.ts";
6
- export declare const assignRole: <TRole extends string>(access: Pick<AccessPolicy<TRole>, "Role" | "hasPermission">, userId: string, role: NoInfer<TRole>) => Effect.Effect<boolean, AuthUnavailable | LastRoleAssigner | NotFound, import("effect/reactivity/Reactivity").Reactivity | SqlClient.SqlClient>;
6
+ export declare const assignRole: <TRole extends string>(access: Pick<AccessPolicy<TRole>, "Role" | "hasPermission">, userId: string, role: NoInfer<TRole>) => Effect.Effect<boolean, AuthUnavailable | LastRoleAssigner | NotFound, SqlClient.SqlClient>;
7
7
  //# sourceMappingURL=assignRole.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"assignRole.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/assignRole.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAkB,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,SAAS,EAAa,MAAM,YAAY,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAe,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAO1E,eAAO,MAAM,UAAU,GAA+C,KAAK,SAAS,MAAM,sPAoCxF,CAAC"}
1
+ {"version":3,"file":"assignRole.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/assignRole.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAkB,MAAM,QAAQ,CAAC;AAEhD,OAAO,EAAE,SAAS,EAAa,MAAM,YAAY,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAe,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAO1E,eAAO,MAAM,UAAU,GAA+C,KAAK,SAAS,MAAM,kMAsCxF,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { Effect, Option, Schema } from "effect";
2
+ import * as Reactivity from "effect/reactivity/Reactivity";
2
3
  import { SqlClient, SqlSchema } from "effect/sql";
3
4
  import { AssignRoles, LastRoleAssigner } from "@shivaedev/access/roles.ts";
4
5
  import { AuthUnavailable, NotFound } from "@shivaedev/errors/taxonomy.ts";
@@ -8,6 +9,8 @@ function unavailable() {
8
9
  }
9
10
  export const assignRole = Effect.fn("Identity.assignRole")(function* (access, userId, role) {
10
11
  const sql = yield* SqlClient.SqlClient;
12
+ const existing = yield* Effect.serviceOption(Reactivity.Reactivity);
13
+ const reactivity = Option.isSome(existing) ? existing.value : yield* Reactivity.make;
11
14
  return yield* Effect.gen(function* () {
12
15
  yield* sql `select pg_advisory_xact_lock(hashtext('platform.auth.user-roles'))`;
13
16
  const readTarget = SqlSchema.findOneOption({
@@ -37,6 +40,6 @@ export const assignRole = Effect.fn("Identity.assignRole")(function* (access, us
37
40
  yield* sql `update "user" set role = ${role}, "updatedAt" = now() where id = ${userId}`;
38
41
  yield* invalidateOnCommit(["admin.users"]);
39
42
  return true;
40
- }).pipe(transact({ onSqlError: unavailable }));
43
+ }).pipe(transact({ onSqlError: unavailable }), Effect.provideService(Reactivity.Reactivity, reactivity));
41
44
  });
42
45
  //# sourceMappingURL=assignRole.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assignRole.js","sourceRoot":"","sources":["../../../src/server/better-auth/assignRole.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAE1E,SAAS,WAAW;IACnB,OAAO,IAAI,eAAe,CAAC,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;AACvE,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,EAAE,CAAC,qBAAqB,CAAC,CAAC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AQ,CAAC,WAAW,CAAC,CAAC,CAAC;YACjF,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC1B,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;YAC7D,CAAC;QACF,CAAC;QACD,KAAK,CAAC,CAAC,GAAG,CAAA,4BAA4B,IAAI,oCAAoC,MAAM,EAAE,CAAC;QACvF,KAAK,CAAC,CAAC,kBAAkB,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC;QAC3C,OAAO,IAAI,CAAC;IACb,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAC1G,CAAC,CAAC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { BetterAuthOptions } from "better-auth";
2
+ import { Effect, Schema } from "effect";
3
+ import { SqlClient } from "effect/sql";
4
+ import type { StoredRoleOptions } from "#server/better-auth/adapters/storedRoleOptions.ts";
5
+ export declare const authColumnDrift: (options: BetterAuthOptions, role?: StoredRoleOptions | undefined) => Effect.Effect<string[], Schema.SchemaError | import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
6
+ //# sourceMappingURL=columnDrift.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"columnDrift.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/columnDrift.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGrD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mDAAmD,CAAC;AAmC3F,eAAO,MAAM,eAAe,iLA0B1B,CAAC"}
@@ -0,0 +1,54 @@
1
+ import { getSchema } from "better-auth/db";
2
+ import { matchType } from "better-auth/db/migration";
3
+ import { Effect, Schema } from "effect";
4
+ import { SqlClient } from "effect/sql";
5
+ const Column = Schema.Struct({
6
+ column: Schema.String,
7
+ default: Schema.NullOr(Schema.String),
8
+ nullable: Schema.String,
9
+ table: Schema.String,
10
+ type: Schema.String,
11
+ });
12
+ function columnProblems(table, name, field, column, serialIds) {
13
+ if (column === undefined) {
14
+ return [];
15
+ }
16
+ const type = (name === "id" || field.references?.field === "id") && serialIds ? "number" : field.type;
17
+ const missing = [];
18
+ if (!matchType(column.type, type, "postgres")) {
19
+ missing.push(`column ${table}.${name} requires type ${type} (found ${column.type})`);
20
+ }
21
+ if (field.required !== false && column.nullable === "YES") {
22
+ missing.push(`column ${table}.${name} requires NOT NULL`);
23
+ }
24
+ if (field.required === false && column.nullable === "NO" && column.default === null && field.defaultValue === undefined) {
25
+ missing.push(`column ${table}.${name} requires DROP NOT NULL`);
26
+ }
27
+ return missing;
28
+ }
29
+ export const authColumnDrift = Effect.fnUntraced(function* (options, role) {
30
+ const sql = yield* SqlClient.SqlClient;
31
+ const columns = yield* sql `
32
+ select table_name as "table", column_name as "column", udt_name as type, is_nullable as nullable, column_default as "default"
33
+ from information_schema.columns where table_schema = current_schema()`.withoutTransform.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Column))));
34
+ const missing = [];
35
+ for (const [table, schema] of Object.entries(getSchema(options))) {
36
+ if (schema.disableMigrations) {
37
+ continue;
38
+ }
39
+ for (const [name, field] of Object.entries(schema.fields)) {
40
+ const column = columns.find((value) => value.table === table && value.column === name);
41
+ missing.push(...columnProblems(table, name, field, column, options.advanced?.database?.generateId === "serial"));
42
+ }
43
+ }
44
+ if (role !== undefined) {
45
+ const table = options.user?.modelName ?? "user";
46
+ const column = columns.find((entry) => entry.table === table && entry.column === "role");
47
+ const value = `'${role.defaultRole.replaceAll("'", "''")}'`;
48
+ if (column !== undefined && column.default !== `${value}::text`) {
49
+ missing.push(`column ${table}.role requires DEFAULT ${value}`);
50
+ }
51
+ }
52
+ return missing;
53
+ });
54
+ //# sourceMappingURL=columnDrift.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"columnDrift.js","sourceRoot":"","sources":["../../../src/server/better-auth/columnDrift.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM;IACrB,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;IACrC,QAAQ,EAAE,MAAM,CAAC,MAAM;IACvB,KAAK,EAAE,MAAM,CAAC,MAAM;IACpB,IAAI,EAAE,MAAM,CAAC,MAAM;CACnB,CAAC,CAAC;AAGH,SAAS,cAAc,CACtB,KAAa,EACb,IAAY,EACZ,KAA6D,EAC7D,MAA0B,EAC1B,SAAkB;IAElB,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,IAAI,KAAK,IAAI,IAAI,KAAK,CAAC,UAAU,EAAE,KAAK,KAAK,IAAI,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;IACtG,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,UAAU,CAAC,EAAE,CAAC;QAC/C,OAAO,CAAC,IAAI,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O,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;YAC3D,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,KAAK,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;YACvF,OAAO,CAAC,IAAI,CAAC,GAAG,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,QAAQ,EAAE,QAAQ,EAAE,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC;QAClH,CAAC;IACF,CAAC;IACD,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACxB,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,EAAE,SAAS,IAAI,MAAM,CAAC;QAChD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,KAAK,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC;QACzF,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC;QAC5D,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,OAAO,KAAK,GAAG,KAAK,QAAQ,EAAE,CAAC;YACjE,OAAO,CAAC,IAAI,CAAC,UAAU,KAAK,0BAA0B,KAAK,EAAE,CAAC,CAAC;QAChE,CAAC;IACF,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { BetterAuthOptions } from "better-auth";
2
+ import { Effect } from "effect";
3
+ import { SqlClient } from "effect/sql";
4
+ import type { StoredRoleOptions } from "#server/better-auth/adapters/storedRoleOptions.ts";
5
+ export declare const migrateBetterAuth: (options: Omit<BetterAuthOptions, "database">, role?: StoredRoleOptions | undefined) => Effect.Effect<void, import("effect/sql/SqlError").SqlError | import("effect/Cause").UnknownError, import("effect/Scope").Scope | SqlClient.SqlClient>;
6
+ //# sourceMappingURL=migrate.d.ts.map