@shivaedev/identity 0.9.1 → 0.10.1
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 +177 -0
- package/README.md +41 -38
- package/dist/server/better-auth/adapters/database.d.ts +4 -0
- package/dist/server/better-auth/adapters/database.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/database.js +36 -0
- package/dist/server/better-auth/adapters/database.js.map +1 -0
- package/dist/server/better-auth/adapters/transaction.d.ts +4 -0
- package/dist/server/better-auth/adapters/transaction.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/transaction.js +29 -0
- package/dist/server/better-auth/adapters/transaction.js.map +1 -0
- package/dist/server/better-auth/mount.d.ts +1 -3
- package/dist/server/better-auth/mount.d.ts.map +1 -1
- package/dist/server/better-auth/mount.js +0 -25
- package/dist/server/better-auth/mount.js.map +1 -1
- package/dist/server/better-auth/testDatabase.d.ts +11 -11
- package/dist/server/better-auth/testDatabase.d.ts.map +1 -1
- package/dist/server/better-auth/testDatabase.js +9 -20
- package/dist/server/better-auth/testDatabase.js.map +1 -1
- package/dist/server/revalidateStream.d.ts +1 -1
- package/dist/server/revalidateStream.d.ts.map +1 -1
- package/dist/server/revalidateStream.js +2 -2
- package/dist/server/revalidateStream.js.map +1 -1
- package/dist/server/socketSession.js +1 -1
- package/dist/server/socketSession.js.map +1 -1
- package/dist/sessions.d.ts +4 -4
- package/dist/sessions.d.ts.map +1 -1
- package/package.json +10 -15
- package/src/server/better-auth/adapters/database.ts +62 -0
- package/src/server/better-auth/adapters/transaction.ts +37 -0
- package/src/server/better-auth/mount.ts +0 -35
- package/src/server/better-auth/testDatabase.ts +15 -26
- package/src/server/revalidateStream.ts +2 -2
- package/src/server/socketSession.ts +1 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.10.1 - 2026-10-31
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- End open authenticated streams with `AuthUnavailable` when a session revalidation cannot reach the auth provider. Revoked sessions still end with `Unauthorized`, and live-change subscriptions use identity's shared stream revalidation.
|
|
8
|
+
|
|
9
|
+
## 0.10.0 - 2026-10-31
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- List active sessions with user details and activity times, and revoke one session through the permission-guarded `identity.sessions` contract. Session revocation uses the existing request and live subscription revalidation path.
|
|
14
|
+
- Generated applications grant session management to their admin and owner roles.
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- Include `CHANGELOG.md` in published package contents so release notes are available in `node_modules`.
|
|
19
|
+
- Release checks reject published package `files` lists that omit `CHANGELOG.md`, naming the package and how to include it.
|
|
20
|
+
- End hosted live subscriptions with `Unauthorized` when the original session is signed out, revoked or expired, whether detected during a change hint or periodic revalidation. Keep `QueryReadDenied` for a signed-in viewer whose query policy refuses the read.
|
|
21
|
+
- Batch shared socket session lookups with an Effect scheduler yield so advancing `TestClock` past `streamRevalidationInterval` completes revalidation without another clock advance.
|
|
22
|
+
- Preserve typed session-provider failures during hint-time authorization instead of reporting them as read-policy refusals.
|
|
23
|
+
|
|
24
|
+
## 0.9.1 - 2026-10-30
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- Release with updated workspace dependencies.
|
|
29
|
+
|
|
30
|
+
## 0.9.0 - 2026-10-30
|
|
31
|
+
|
|
32
|
+
### Added
|
|
33
|
+
|
|
34
|
+
- Access exports `AssignRoles` and `LastRoleAssigner` from `@shivaedev/access/roles.ts` for shared role policy declarations.
|
|
35
|
+
- Identity provides `assignRole(access, userId, role)` for trusted seeds and operator commands. Supply `SqlClient` and `Reactivity`; it returns whether storage changed and uses the Users page's PostgreSQL lock, last-role-assigner guard and commit invalidation.
|
|
36
|
+
|
|
37
|
+
### Breaking
|
|
38
|
+
|
|
39
|
+
- Identity mounts with `roles` close Better Auth's `/admin/set-role`, `/admin/update-user` and `/admin/create-user` HTTP endpoints and set its admin plugin's `adminRoles` to `[]`. Remove that setup from applications. Use the admin Users page for authorized requests and identity's `assignRole` for trusted server commands.
|
|
40
|
+
- Admin consumers import `AssignRoles` and `LastRoleAssigner` from `@shivaedev/access/roles.ts` instead of `@shivaedev/admin/permissions.ts` and `@shivaedev/admin/users/roles.ts`. The Users page uses identity's shared assignment operation; its permission checks, typed refusal and audit log remain.
|
|
41
|
+
|
|
42
|
+
## 0.8.0 - 2026-10-30
|
|
43
|
+
|
|
44
|
+
### Added
|
|
45
|
+
|
|
46
|
+
- Pass a provider-account lookup to a Better Auth mount's `admittedSessions(getSession, getProviderAccounts)` to read linked provider IDs through `SessionUserWithProviderAccounts` while enforcing admission and session revocation. Omitting the lookup preserves the base session shape.
|
|
47
|
+
|
|
48
|
+
## 0.7.0 - 2026-10-30
|
|
49
|
+
|
|
50
|
+
### Fixed
|
|
51
|
+
|
|
52
|
+
- Live reads and change subscriptions preserve policy failures instead of reporting read denial. Generated starter apps report notes database connection failures as `ServiceUnavailable` during the owner's live read.
|
|
53
|
+
|
|
54
|
+
### Breaking
|
|
55
|
+
|
|
56
|
+
- Query read policies declare their error and service channels with `QueryReadPolicy<Payload, E, R>`. Declare policy errors in the query's `rejections` and provide policy services when building its handler Layer. Custom subscription adapters call `querySubscription(rpc, references, viewer)` instead of resolving requests themselves. Use the native RPC type when calling `authorizeReads` or `resolveChanges` so their inferred channels include policy requirements and errors. The generated change stream includes the queries' declared rejections and service requirements; consumers handling that stream must handle those errors too.
|
|
57
|
+
- Admin pages install their permission's read policy for every query, preserving additional query restrictions. Remove repeated page-grant policies from individual queries and supply the page's permission middleware with the handler Layers.
|
|
58
|
+
|
|
59
|
+
## 0.6.0 - 2026-10-30
|
|
60
|
+
|
|
61
|
+
### Added
|
|
62
|
+
|
|
63
|
+
- Identity exposes a socket-scoped session coordinator for hosts to share session rechecks within a batch and drive stream revalidation from one timer.
|
|
64
|
+
|
|
65
|
+
### Fixed
|
|
66
|
+
|
|
67
|
+
- Hosted live subscriptions on one socket share hint-time session lookups and periodic session revalidation while retaining per-query read-policy checks and typed revocation failures.
|
|
68
|
+
|
|
69
|
+
## 0.5.1 - 2026-10-30
|
|
70
|
+
|
|
71
|
+
### Changed
|
|
72
|
+
|
|
73
|
+
- Release with updated workspace dependencies.
|
|
74
|
+
|
|
75
|
+
## 0.5.0 - 2026-10-30
|
|
76
|
+
|
|
77
|
+
### Added
|
|
78
|
+
|
|
79
|
+
- Export `SessionUserSchema` from `identity.ts`, `IdentityFailures` from `middleware.ts`, and `providerFailure` from `server/providerFailure.ts` as the shared user description, middleware failure union and redacted provider-failure mapper.
|
|
80
|
+
- Access exports the `Permission` Schema and derives its type from it. Role resolution and identity session decoding use that Schema.
|
|
81
|
+
- Access exports `forbidden(permission)` and `unauthorized()` from `refusal.ts` for consistent permission refusals.
|
|
82
|
+
- Identity's `trustedOrigins` accepts an optional `sameOrigin: { trustedProxy }` policy using the transport guard's loopback and trusted-proxy authority checks. Session resolution supplies the transport peer address; RPC message headers cannot establish proxy trust.
|
|
83
|
+
|
|
84
|
+
### Fixed
|
|
85
|
+
|
|
86
|
+
- Report failures and defects masked by `rpcBoundary` through Effect's error reporters at Error severity with diagnostic redaction before returning the rejection.
|
|
87
|
+
- Log boundary-masked RPC failures once at ERROR with their redacted stack; keep declared rejections at INFO.
|
|
88
|
+
- Retry command-declared invalidation publication after the handler returns, with two bounded exponential backoffs. Exhausted retries preserve the committed result and resynchronize local live streams, then broadcast Resync to other PostgreSQL hosts when the change channel is reachable.
|
|
89
|
+
- Clarify that atomic record and bucket invalidation comes from the stored model and repository; command `invalidates` keys remain after-commit. No consumer API changes or migration are required.
|
|
90
|
+
- Run mounted session admission and session permission enrichment in the request fiber so request spans, log annotations and interruption survive policy checks.
|
|
91
|
+
- Generated apps accept their own forwarded HTTPS RPC requests without `PUBLIC_URL`, while refusing foreign origins. A configured `PUBLIC_URL` remains the explicit RPC origin allowlist.
|
|
92
|
+
|
|
93
|
+
### Breaking
|
|
94
|
+
|
|
95
|
+
- `mounted.admittedSessions(lookup)` now returns an Effect `SessionProvider`. Assign it directly to `sessions.provider` instead of wrapping it with `betterAuthSessions`, or use `mounted.sessions` for the default lookup and mounted roles. Provide the application's Config provider to the server Layer for request-time account checks and to explicit revocation workflows; revocation also uses the caller's environment.
|
|
96
|
+
- Import `trustedProxyRanges` from `server/trustedProxyRanges.ts` instead of `server/local.ts`, and `proxyRanges` from `server/proxyRanges.ts` instead of `server/trustedProxy.ts`. The forwarding exports have been removed.
|
|
97
|
+
- `sessionPermissions` now returns an Effect instead of a Promise. Yield it in the caller's Effect workflow.
|
|
98
|
+
- `server/sessionProfile.ts` has been removed. Decode or project profiles with `Schema.decodeSync(SessionUserSchema)` from `identity.ts`.
|
|
99
|
+
- Access, identity and React now share access's grant evaluator: an `any` grant covers an `own` check for the same permission name. An `own` grant still cannot cover an `any` check. Applications that need separate capabilities must declare separate permission names; record ownership checks still belong in `canAccess` or `requireAccess`.
|
|
100
|
+
- Replace `Access.requirePermission(user, permission)` with `requirePermission(yield* Access.resolve(user.role), permission)` from `@shivaedev/access/requirePermission.ts`. The new function takes a signed-in user; reject an absent session with `unauthorized()` from `@shivaedev/access/refusal.ts` before resolving its role. `requireAccess` continues to handle signed-out users itself.
|
|
101
|
+
- Replace identity's `requirePermission(permission)` with access's `requirePermission(yield* SessionUser, permission)`. There is no identity re-export. Admin's built-in handlers use this shared enforcement.
|
|
102
|
+
- Access's `requireAccess` now uses the shared permission refusal message, `Permission required: <name> (<strength>)`, instead of `Access denied: <name>`. Consumers should branch on the `Forbidden` tag.
|
|
103
|
+
- Identity treats an undeclared stored user role as a defect naming the role, rather than `AuthUnavailable`. RPC request tracing logs the defect and Better Auth's session endpoint returns HTTP 500. Consumers must correct the user's stored role or restore its application declaration; reserve `AuthUnavailable` handling for provider outages.
|
|
104
|
+
- Admin role assignment trusts its typed role input and leaves session role resolution to identity. RPC consumers need no change: the contract decodes the role. Direct callers of `changeUserRole` must decode untrusted role input with the application's `Role` schema before calling it.
|
|
105
|
+
|
|
106
|
+
## 0.4.0 - 2026-10-30
|
|
107
|
+
|
|
108
|
+
### Added
|
|
109
|
+
|
|
110
|
+
- Scope screen-driver verbs and readouts with `within(container)`, and mount named member screens with independent cookie sessions, atom registries and scoped roots through `memberScreens`.
|
|
111
|
+
- Create password-credential test users with Identity's `passwordUser` helper for real email sign-in stories.
|
|
112
|
+
- Quality accepts app migrations referencing the auth user id with `ON DELETE CASCADE` or `ON DELETE SET NULL`, while keeping auth reads and writes behind identity.
|
|
113
|
+
- Identity exports `userReference` from `server/better-auth/userReference.ts` so app migrations share the user table and id column names.
|
|
114
|
+
- Starter notes use a `user_id` foreign key with cascading deletion. A numbered migration renames the existing ownership column and adds the constraint for existing apps.
|
|
115
|
+
|
|
116
|
+
### Changed
|
|
117
|
+
|
|
118
|
+
- Require Effect 4.0.6 and align the Effect companion package peers and generated starter catalog to the same exact release. Install the 4.0.6 Effect stack together.
|
|
119
|
+
|
|
120
|
+
### Fixed
|
|
121
|
+
|
|
122
|
+
- Register hosted RPC cache-control handling through Effect 4.0.6's request-scoped pre-response API so responses keep `private, no-store`.
|
|
123
|
+
- Accept native RPC's `application/x-ndjson` media type while preserving `application/ndjson` callers at the transport guard.
|
|
124
|
+
- Keep subscriptions open after their HTTP request body completes; closing the socket still cancels them.
|
|
125
|
+
|
|
126
|
+
## 0.3.2 - 2026-10-29
|
|
127
|
+
|
|
128
|
+
### Changed
|
|
129
|
+
|
|
130
|
+
- Release with updated workspace dependencies.
|
|
131
|
+
|
|
132
|
+
## 0.3.1 - 2026-10-29
|
|
133
|
+
|
|
134
|
+
### Changed
|
|
135
|
+
|
|
136
|
+
- Release with updated workspace dependencies.
|
|
137
|
+
|
|
138
|
+
## 0.3.0 - 2026-10-28
|
|
139
|
+
|
|
140
|
+
### Added
|
|
141
|
+
|
|
142
|
+
- Identity exports `sweepExpiredSessions`, an Effect over the application's SQL client that deletes expired Better Auth sessions and returns the number removed without mounting auth.
|
|
143
|
+
- The starter worker sweeps expired auth sessions daily at midnight UTC. New apps and apps using the starter updater receive the schedule.
|
|
144
|
+
- `authTestDatabase(pool).expireSessions(userId)` expires only the selected user's sessions; omit the user id to expire every session.
|
|
145
|
+
|
|
146
|
+
### Fixed
|
|
147
|
+
|
|
148
|
+
- Enforce declared query read policies at the hosted RPC handler boundary, including contracts without identity middleware, whose viewer is anonymous. Query RPC error schemas include `QueryReadDenied` so native clients receive typed refusals before handlers run.
|
|
149
|
+
- Keep collection methods and untyped schema internals from making data parameters appear to carry callable services. Direct service implementations, nested dependency fields and service arrays remain subject to `effect/service-parameters`.
|
|
150
|
+
|
|
151
|
+
### Breaking
|
|
152
|
+
|
|
153
|
+
- Call `authTestDatabase(pool).expireSessions()` instead of yielding the `expireSessions` property directly.
|
|
154
|
+
- Move key imports from `@shivaedev/contract/keys.ts` to `@shivaedev/changes/keys.ts`. Declare bucket fields with `collection(name, idSchema, fields)` and publish affected buckets alongside record keys.
|
|
155
|
+
- Replace collection policy maps, `mergeReadPolicies`, `ReadPolicy` and `ReadPolicyMemoWindow` with each query's `readPolicy(payload, viewer)`. Declare the same query's live scope with `reads(payload, viewer)`. Bound query atoms and subscriptions refuse missing policies with a declaration error; one-off query `run` calls remain available. Denied queries refuse the entire subscription. Server adapters replace `QueryReads` and `ChangesReads` with `QueryDefinition` and `ChangesQueries`. Custom middleware calls `authorizeReads(effect, request, viewer)` and declares `MissingReadPolicy` and `QueryReadDenied` errors.
|
|
156
|
+
- Custom subscription adapters yield `ChangesQueries.resolve(references)`, call `querySubscription(requests, viewer)` and pass the authorized result to `makeLiveServer.subscribe(subscription, context)`. Metadata values expose `QueryDefinition.definition` and `CommandInvalidation.invalidates` instead of bare definitions and callbacks. Yield the Effect returned by `queryKeys(queries, references)` when projecting keys for a custom stream. `resolveChanges` supplies the authorized subscription in hosted applications. Changed hints can carry query positions so bindings can rerun session-scoped reads without deriving session scopes in the browser.
|
|
157
|
+
- Remove `appHost`'s `readPolicy` option and module policy registration. Session and permission middleware apply query policies using the current session viewer. Handle the new typed policy errors in native clients, including `QueryReadDenied` on query RPCs without identity middleware; widen explicit query error annotations accordingly.
|
|
158
|
+
- Replace `sessionCommandChanges` with `commandChanges` for custom session middleware. Command invalidation callbacks can receive the session viewer as their third argument. Announce viewer buckets there; background writers must explicitly publish those bucket keys after commit.
|
|
159
|
+
- Built-in admin queries declare their permission policies alongside their schemas and read scopes. Consumers keep supplying the existing session and permission middleware layers.
|
|
160
|
+
- Local Work Board and Fleet queries declare their existing loopback read access explicitly so their generated live subscriptions remain available.
|
|
161
|
+
|
|
162
|
+
## 0.2.0 - 2026-10-27
|
|
163
|
+
|
|
164
|
+
### Added
|
|
165
|
+
|
|
166
|
+
- Session hosts bound to a non-loopback address without proxy trust warn at startup to configure `TRUSTED_PROXY` or `config.trustedProxy` before forwarding RPC requests.
|
|
167
|
+
|
|
168
|
+
### Fixed
|
|
169
|
+
|
|
170
|
+
- Development auth accepts both `localhost` and `127.0.0.1` over HTTP on any port when `PUBLIC_URL` is unset. Explicit `baseURL` and `trustedOrigins` options replace those defaults.
|
|
171
|
+
- Auth rate limiting uses the connection peer address without a trusted proxy, separating client buckets and avoiding Better Auth's missing-client-IP warning. Trusted forwarding still takes precedence, and untrusted forwarding headers are ignored.
|
|
172
|
+
|
|
173
|
+
## 0.1.0 - 2026-10-27
|
|
174
|
+
|
|
175
|
+
### Added
|
|
176
|
+
|
|
177
|
+
- First release of `@shivaedev/identity`: request identity and the RPC middleware declarations (`identity.ts`, `middleware.ts`, `permission.ts`), session resolution, Origin policy, trusted proxies, permission enforcement and request tracing (`server/`), and the Better Auth mount, sign-in policy and test helpers (`server/better-auth/`). The service and middleware ids now name the package (`@shivaedev/identity/Identity`, `@shivaedev/identity/Authenticated` and so on).
|
package/README.md
CHANGED
|
@@ -93,11 +93,12 @@ The application's `auth` owns its storage and session configuration. A null look
|
|
|
93
93
|
`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.
|
|
94
94
|
|
|
95
95
|
```ts
|
|
96
|
-
import {
|
|
97
|
-
import {
|
|
96
|
+
import { Effect } from "effect";
|
|
97
|
+
import { betterAuthDatabase } from "@shivaedev/identity/server/better-auth/adapters/database.ts";
|
|
98
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
98
99
|
|
|
99
100
|
const authentication = Effect.gen(function* () {
|
|
100
|
-
const database = yield*
|
|
101
|
+
const database = yield* betterAuthDatabase();
|
|
101
102
|
return yield* betterAuthMount({
|
|
102
103
|
database,
|
|
103
104
|
emailAndPassword: { enabled: true },
|
|
@@ -106,9 +107,9 @@ const authentication = Effect.gen(function* () {
|
|
|
106
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
111
|
|
|
111
|
-
Run this Effect in the host's scope
|
|
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`.
|
|
112
113
|
|
|
113
114
|
The mount reads `BETTER_AUTH_SECRET` unless options supply `secret`. `PUBLIC_URL` supplies the default base URL, trusted origin and HTTPS secure-cookie setting. With it unset, `baseURL.allowedHosts` defaults to `["127.0.0.1:*", "localhost:*"]` over HTTP and `trustedOrigins` defaults to `["http://127.0.0.1:*", "http://localhost:*"]`, accepting both loopback names on any port through a development proxy. Explicit `baseURL` (including `baseURL.allowedHosts`) and `trustedOrigins` options each replace their corresponding default; their lists are not merged. RPC Origin policy remains an application choice.
|
|
114
115
|
|
|
@@ -181,13 +182,14 @@ Use the WebView's own fetch with `credentials: "omit"` for incremental NDJSON ch
|
|
|
181
182
|
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:
|
|
182
183
|
|
|
183
184
|
```ts
|
|
184
|
-
import {
|
|
185
|
+
import { Effect } from "effect";
|
|
185
186
|
import { allowedAccounts } from "@shivaedev/identity/server/better-auth/allowedAccounts.ts";
|
|
186
|
-
import {
|
|
187
|
+
import { betterAuthDatabase } from "@shivaedev/identity/server/better-auth/adapters/database.ts";
|
|
188
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
187
189
|
import { trustedOrigins } from "@shivaedev/identity/server/origin.ts";
|
|
188
190
|
|
|
189
191
|
const authentication = Effect.gen(function* () {
|
|
190
|
-
const database = yield*
|
|
192
|
+
const database = yield* betterAuthDatabase();
|
|
191
193
|
const mounted = yield* betterAuthMount(
|
|
192
194
|
{ database, session: { cookieCache: { enabled: false } }, socialProviders: { github } },
|
|
193
195
|
{ signIn: { accounts: allowedAccounts, recheckInterval: "5 minutes", rule: inOrganization } },
|
|
@@ -422,7 +424,7 @@ const authentication = Layer.succeed(MyAuthentication, (effect, { headers, rpc,
|
|
|
422
424
|
|
|
423
425
|
### Session freshness in streams
|
|
424
426
|
|
|
425
|
-
`authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, the role layers and signed-in `maybeAuthenticatedLayer` calls revalidate live RPC streams every 30 seconds by default, using the original transport headers. A
|
|
427
|
+
`authenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, the role layers and signed-in `maybeAuthenticatedLayer` calls revalidate live RPC streams every 30 seconds by default, using the original transport headers. A signed-out, revoked or expired session ends the stream with `Unauthorized`, including an idle stream and a subscription receiving a change hint. A signed-in viewer whose query read policy now refuses ends the subscription with `QueryReadDenied`. Session intervals use Effect’s Clock, so advancing `TestClock` drives revalidation; batched session lookups do not need another clock advance. With a session store that reflects sign-out immediately, delivery can continue for up to that interval plus the session lookup time after sign-out. Provider cookie caching or secondary storage can add their own delay; keep Better Auth's cookie cache disabled for database-backed revocation.
|
|
426
428
|
|
|
427
429
|
Set `SessionPolicy.streamRevalidationInterval` to an Effect `Duration.Input` to change the interval for middleware using that policy:
|
|
428
430
|
|
|
@@ -434,7 +436,7 @@ const sessions = {
|
|
|
434
436
|
};
|
|
435
437
|
```
|
|
436
438
|
|
|
437
|
-
An `AuthUnavailable` failure during revalidation
|
|
439
|
+
An `AuthUnavailable` failure during revalidation ends the stream with `AuthUnavailable`. Initial session lookup failures also reject the subscription. Unary calls resolve their session once per call. `MaybeAuthenticated` streams that start anonymous continue without a session monitor; a signed-in optional stream ends with `Unauthorized` when its session is removed. Callers can subscribe again to continue anonymously.
|
|
438
440
|
|
|
439
441
|
### Transport headers and request ids
|
|
440
442
|
|
|
@@ -471,7 +473,7 @@ Run the auth schema migration before the app migration. Use `ON DELETE CASCADE`
|
|
|
471
473
|
|
|
472
474
|
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.
|
|
473
475
|
|
|
474
|
-
Use `authTestDatabase
|
|
476
|
+
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.
|
|
475
477
|
|
|
476
478
|
```ts
|
|
477
479
|
import { betterAuth } from "better-auth";
|
|
@@ -541,36 +543,37 @@ Register the Effect with a worker schedule, as the starter does at midnight UTC.
|
|
|
541
543
|
|
|
542
544
|
Import the module that defines the name; there is no package-root entry. Paths below follow `@shivaedev/identity/`.
|
|
543
545
|
|
|
544
|
-
| Module | Names and purpose
|
|
545
|
-
| -------------------------------------------- |
|
|
546
|
-
| `identity.ts` | `RequestId`, `Identity`, `OptionalIdentity`, `SessionUser`, `SessionUserWithProviderAccounts`, `SessionUserSchema`: request-local services and the shared user schema.
|
|
547
|
-
| `middleware.ts` | `RequestTracing`, `Authenticated`, `AuthenticatedUser`, `AuthenticatedUserWithProviderAccounts`, `MaybeAuthenticated`, `IdentityFailures`: native RPC middleware declarations and their shared failure schema.
|
|
548
|
-
| `server/providerFailure.ts` | `providerFailure(cause)`: log a redacted provider failure and fail with `AuthUnavailable`.
|
|
549
|
-
| `permission.ts` | `permissionMiddleware`, `hasPermission`: native permission middleware declarations and predicates over resolved grants.
|
|
550
|
-
| `server/permissions.ts` | `permissionLayer`, `permissionRoute`: permission middleware Layers and HTTP route guards.
|
|
551
|
-
| `server/session.ts` | `authenticatedLayer`, `maybeAuthenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, `withSessionUser`, `resolveSession`: session middleware implementations and the identity boundary.
|
|
552
|
-
| `server/adapters/betterAuthSessions.ts` | `betterAuthSessions(getSession, getProviderAccounts?)`: a session provider from Better Auth lookups.
|
|
553
|
-
| `server/origin.ts` | `trustedOrigins({ allow, missing })`: an exact Origin allowlist.
|
|
554
|
-
| `server/local.ts` | `localRpcGuard`, `loopbackOnly`, `sameOrigin`, `trustedProxyPeer`: loopback and proxy guards.
|
|
555
|
-
| `server/trustedProxyRanges.ts` | `trustedProxyRanges(trustedProxy?)`: normalized proxy ranges.
|
|
556
|
-
| `server/proxyRanges.ts` | `proxyRanges(value)`: parse configured proxy ranges.
|
|
557
|
-
| `server/transportHeaders.ts` | `transportHeaders(rpcHeaders)`: the headers used for a transport-level decision.
|
|
558
|
-
| `server/tracing.ts` | `requestTracingLayer({ header?, sensitive? })`: the `RequestTracing` implementation.
|
|
559
|
-
| `server/sessionKeys.ts` | `resolveChanges`: session-scoped change subscriptions for custom change handlers.
|
|
560
|
-
| `server/commandChanges.ts` | `commandChanges(effect, rpc, payload)`: scoped command invalidation for custom authentication middleware.
|
|
561
|
-
| `server/better-auth/mount.ts` | `betterAuthMount(options, { signIn?, bearerSessions?, roles? })`, returning `{ auth, routes, sessions, admittedSessions, revokeUnadmitted }
|
|
562
|
-
| `server/better-auth/
|
|
563
|
-
| `server/better-auth/
|
|
564
|
-
| `server/better-auth/
|
|
565
|
-
| `server/better-auth/
|
|
566
|
-
| `server/better-auth/
|
|
567
|
-
| `server/better-auth/
|
|
568
|
-
| `server/better-auth/
|
|
569
|
-
| `server/better-auth/
|
|
546
|
+
| Module | Names and purpose |
|
|
547
|
+
| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
548
|
+
| `identity.ts` | `RequestId`, `Identity`, `OptionalIdentity`, `SessionUser`, `SessionUserWithProviderAccounts`, `SessionUserSchema`: request-local services and the shared user schema. |
|
|
549
|
+
| `middleware.ts` | `RequestTracing`, `Authenticated`, `AuthenticatedUser`, `AuthenticatedUserWithProviderAccounts`, `MaybeAuthenticated`, `IdentityFailures`: native RPC middleware declarations and their shared failure schema. |
|
|
550
|
+
| `server/providerFailure.ts` | `providerFailure(cause)`: log a redacted provider failure and fail with `AuthUnavailable`. |
|
|
551
|
+
| `permission.ts` | `permissionMiddleware`, `hasPermission`: native permission middleware declarations and predicates over resolved grants. |
|
|
552
|
+
| `server/permissions.ts` | `permissionLayer`, `permissionRoute`: permission middleware Layers and HTTP route guards. |
|
|
553
|
+
| `server/session.ts` | `authenticatedLayer`, `maybeAuthenticatedLayer`, `authenticatedUserLayer`, `authenticatedUserWithProviderAccountsLayer`, `withSessionUser`, `resolveSession`: session middleware implementations and the identity boundary. |
|
|
554
|
+
| `server/adapters/betterAuthSessions.ts` | `betterAuthSessions(getSession, getProviderAccounts?)`: a session provider from Better Auth lookups. |
|
|
555
|
+
| `server/origin.ts` | `trustedOrigins({ allow, missing })`: an exact Origin allowlist. |
|
|
556
|
+
| `server/local.ts` | `localRpcGuard`, `loopbackOnly`, `sameOrigin`, `trustedProxyPeer`: loopback and proxy guards. |
|
|
557
|
+
| `server/trustedProxyRanges.ts` | `trustedProxyRanges(trustedProxy?)`: normalized proxy ranges. |
|
|
558
|
+
| `server/proxyRanges.ts` | `proxyRanges(value)`: parse configured proxy ranges. |
|
|
559
|
+
| `server/transportHeaders.ts` | `transportHeaders(rpcHeaders)`: the headers used for a transport-level decision. |
|
|
560
|
+
| `server/tracing.ts` | `requestTracingLayer({ header?, sensitive? })`: the `RequestTracing` implementation. |
|
|
561
|
+
| `server/sessionKeys.ts` | `resolveChanges`: session-scoped change subscriptions for custom change handlers. |
|
|
562
|
+
| `server/commandChanges.ts` | `commandChanges(effect, rpc, payload)`: scoped command invalidation for custom authentication middleware. |
|
|
563
|
+
| `server/better-auth/mount.ts` | `betterAuthMount(options, { signIn?, bearerSessions?, roles? })`, returning `{ auth, routes, sessions, admittedSessions, revokeUnadmitted }`: native auth routes and the sign-in policy. |
|
|
564
|
+
| `server/better-auth/adapters/database.ts` | `betterAuthDatabase()`: Better Auth storage on the application PostgreSQL client. |
|
|
565
|
+
| `server/better-auth/allowedAccounts.ts` | `AllowedAccounts`, `allowedAccounts`: the provider-account list Schema and its `AUTH_ALLOWED_ACCOUNTS` Config. |
|
|
566
|
+
| `server/better-auth/signInGate.ts` | `SignInPolicy`: the `accounts`, `rule` and `recheckInterval` of a sign-in policy. |
|
|
567
|
+
| `server/better-auth/revokeUnadmitted.ts` | `RevokedSessions`: the `{ users, sessions }` counts of a revocation. |
|
|
568
|
+
| `server/better-auth/userProfiles.ts` | Public profile lookups for other users. |
|
|
569
|
+
| `server/better-auth/sweepExpiredSessions.ts` | `sweepExpiredSessions`: delete expired sessions through the application's SQL client and return the number removed. |
|
|
570
|
+
| `server/better-auth/userReference.ts` | `userReference`: the default auth user table and id column for application foreign keys. |
|
|
571
|
+
| `server/better-auth/testDatabase.ts` | `authTestDatabase`: test-only identity/session readouts and faults for the default PostgreSQL auth schema. |
|
|
572
|
+
| `server/better-auth/testing.ts` | `signedInUser(auth, fields)`, `passwordUser(auth, fields)`, `storedProviderAccounts(auth, userId)`: test-only users, minted sessions and credential storage observations. |
|
|
570
573
|
|
|
571
574
|
### Install, setup and limits
|
|
572
575
|
|
|
573
|
-
Install `@shivaedev/identity` with `effect` as its peer. Everything outside `server/better-auth/` works with only `effect` installed, including the Promise-based `betterAuthSessions` adapter. Better Auth mounts and test fixtures need the optional
|
|
576
|
+
Install `@shivaedev/identity` with `effect` as its peer. Everything outside `server/better-auth/` works with only `effect` installed, including the Promise-based `betterAuthSessions` adapter. Better Auth mounts and test fixtures need the optional peer `better-auth` and the application’s PostgreSQL `SqlClient`; `sweepExpiredSessions` needs only the application's Effect SQL client. Browser code imports only `identity.ts`, `middleware.ts` and `permission.ts`.
|
|
574
577
|
- The package needs Node 24 or newer.
|
|
575
578
|
- Keep the auth provider's configuration, cookie settings and resource authorization in the application. The session adapter takes a session lookup and an optional provider-account lookup and returns a session result; it does not write provider refresh cookies into RPC responses.
|
|
576
579
|
- Without an `HttpServerRequest`, `transportHeaders` falls back to the supplied RPC headers. An application using another transport must decide what headers it can trust.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/database.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAwB,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAiBvC,eAAO,MAAM,kBAAkB,oEA0C7B,CAAC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Effect, Exit, Option, Schema, Scope } from "effect";
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
|
+
import { betterAuthTransaction } from "./transaction.js";
|
|
4
|
+
const Result = Schema.Struct({ command: Schema.String, rowCount: Schema.Number, rows: Schema.Array(Schema.Unknown) });
|
|
5
|
+
export const betterAuthDatabase = Effect.fn("Identity.betterAuthDatabase")(function* () {
|
|
6
|
+
const sql = yield* SqlClient.SqlClient;
|
|
7
|
+
const transaction = yield* Effect.serviceOption(sql.transactionService);
|
|
8
|
+
const parent = yield* Scope.Scope;
|
|
9
|
+
const context = yield* Effect.context();
|
|
10
|
+
const run = Effect.runPromiseWith(context);
|
|
11
|
+
const pool = {
|
|
12
|
+
async connect() {
|
|
13
|
+
const scope = await run(Scope.fork(parent));
|
|
14
|
+
const connection = await run((Option.isSome(transaction) ? Effect.succeed(transaction.value[0]) : sql.reserve).pipe(Scope.provide(scope), Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause)))));
|
|
15
|
+
const control = Option.isSome(transaction) ? await run(betterAuthTransaction.pipe(Scope.provide(scope))) : undefined;
|
|
16
|
+
function query(text, parameters = []) {
|
|
17
|
+
if (typeof text !== "string") {
|
|
18
|
+
throw new Error("Better Auth database does not support cursors");
|
|
19
|
+
}
|
|
20
|
+
const nested = control?.(text);
|
|
21
|
+
return (nested === undefined ? run(connection.executeRaw(text, parameters)) : nested.then(() => ({ command: text, rowCount: 0, rows: [] }))).then(Schema.decodeUnknownSync(Result));
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
query,
|
|
25
|
+
release: () => {
|
|
26
|
+
void run(Scope.close(scope, Exit.void));
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
// The application SQL Layer owns pool shutdown.
|
|
31
|
+
end: () => Promise.resolve(),
|
|
32
|
+
options: {},
|
|
33
|
+
};
|
|
34
|
+
return pool;
|
|
35
|
+
});
|
|
36
|
+
//# sourceMappingURL=database.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.js","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/database.ts"],"names":[],"mappings":"AACA,O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AAE,CAAC,OAAO,CAAC,OAAO,EAAE;QAC5B,OAAO,EAAE,EAAE;KACX,CAAC;IACF,OAAO,IAAI,CAAC;AACb,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,MAAM,EAAS,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAKvC,eAAO,MAAM,qBAAqB,uBAMnB,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,2CAwB/C,CAAC"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Data, Deferred, Effect, Fiber, Scope } from "effect";
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
|
+
class Rollback extends Data.TaggedError("BetterAuthRollback") {
|
|
4
|
+
}
|
|
5
|
+
export const betterAuthTransaction = Effect.gen(function* () {
|
|
6
|
+
const sql = yield* SqlClient.SqlClient;
|
|
7
|
+
const context = yield* Effect.context();
|
|
8
|
+
const run = Effect.runPromiseWith(context);
|
|
9
|
+
const scope = yield* Scope.Scope;
|
|
10
|
+
let active;
|
|
11
|
+
return (text) => {
|
|
12
|
+
if (text === "begin") {
|
|
13
|
+
return run(Effect.gen(function* () {
|
|
14
|
+
const ready = yield* Deferred.make();
|
|
15
|
+
const done = yield* Deferred.make();
|
|
16
|
+
const fiber = yield* sql.withTransaction(Deferred.succeed(ready, undefined).pipe(Effect.andThen(Deferred.await(done)))).pipe(Effect.catchTag("BetterAuthRollback", () => Effect.void), Effect.forkIn(scope));
|
|
17
|
+
active = { done, fiber };
|
|
18
|
+
yield* Effect.raceFirst(Deferred.await(ready), Fiber.join(fiber));
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
if (active !== undefined && (text === "commit" || text === "rollback")) {
|
|
22
|
+
const { done, fiber } = active;
|
|
23
|
+
active = undefined;
|
|
24
|
+
return run((text === "commit" ? Deferred.succeed(done, undefined) : Deferred.fail(done, new Rollback())).pipe(Effect.andThen(Fiber.join(fiber))));
|
|
25
|
+
}
|
|
26
|
+
return undefined;
|
|
27
|
+
};
|
|
28
|
+
});
|
|
29
|
+
//# sourceMappingURL=transaction.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transaction.js","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,MAAM,QAAS,SAAQ,IAAI,CAAC,WAAW,CAAC,oBAAoB,CAAC;CAAG;AAEhE,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;IACxD,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC;IACvC,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,EAAS,CAAC;IAC/C,MAAM,GAAG,GAAG,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC;IACjC,IAAI,MAAqH,CAAC;IAC1H,OAAO,CAAC,IAAY,EAA6B,EAAE;QAClD,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YACtB,OAAO,GAAG,CACT,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;gBACnB,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAQ,CAAC;gBAC3C,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAkB,CAAC;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} from "better-auth";
|
|
2
|
-
import { Config, Effect
|
|
3
|
-
import { Pool, type PoolConfig } from "pg";
|
|
2
|
+
import { Config, Effect } from "effect";
|
|
4
3
|
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
5
4
|
import { type BearerSessionsOptions } from "#server/better-auth/bearerSessions.ts";
|
|
6
5
|
import { type SignInPolicy } from "#server/better-auth/signInGate.ts";
|
|
@@ -265,5 +264,4 @@ export declare const betterAuthMount: <const TOptions extends BetterAuthOptions,
|
|
|
265
264
|
}>;
|
|
266
265
|
};
|
|
267
266
|
}, Config.ConfigError, R | import("effect/Scope").Scope>;
|
|
268
|
-
export declare const authDatabase: (url: Redacted.Redacted<string>, options?: Pick<PoolConfig, "application_name" | "max"> | undefined) => Effect.Effect<Pool, never, import("effect/Scope").Scope>;
|
|
269
267
|
//# sourceMappingURL=mount.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mount.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/mount.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,iBAAiB,EAAc,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"mount.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/mount.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,iBAAiB,EAAc,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAoB,MAAM,QAAQ,CAAC;AAC1D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,KAAK,qBAAqB,EAAsB,MAAM,uCAAuC,CAAC;AAKvG,OAAO,EAAsB,KAAK,YAAY,EAAc,MAAM,mCAAmC,CAAC;AAMtG,MAAM,WAAW,sBAAsB,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,KAAK;IAC3D,QAAQ,CAAC,cAAc,CAAC,EAAE,qBAAqB,GAAG,SAAS,CAAC;IAC5D,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,SAAS,CAAC;CACjD;AAED,eAAO,MAAM,eAAe,SAA0D,QAAQ,SAAS,iBAAiB,EAAE,CAAC,UAAU,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wDA8DpI,CAAC"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { betterAuth } from "better-auth";
|
|
2
2
|
import { Config, Effect, Option, Redacted } from "effect";
|
|
3
|
-
import { Pool } from "pg";
|
|
4
3
|
import { withBearerSessions } from "#server/better-auth/bearerSessions.ts";
|
|
5
4
|
import { PEER_IP_HEADER } from "#server/better-auth/clientIp.ts";
|
|
6
5
|
import { memoryRateLimit } from "#server/better-auth/memoryRateLimit.ts";
|
|
@@ -68,28 +67,4 @@ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* (
|
|
|
68
67
|
const sessions = mountedSessions(lookupSession, admit, mount.roles);
|
|
69
68
|
return { admittedSessions: admit, auth, revokeUnadmitted: revoke, routes: authRoutes, sessions };
|
|
70
69
|
});
|
|
71
|
-
export const authDatabase = Effect.fn("Platform.authDatabase")(function* (url, options = {}) {
|
|
72
|
-
const clients = new Set();
|
|
73
|
-
const run = Effect.runForkWith(yield* Effect.context());
|
|
74
|
-
return yield* Effect.acquireRelease(Effect.sync(() => {
|
|
75
|
-
const pool = new Pool({
|
|
76
|
-
...options,
|
|
77
|
-
connectionString: Redacted.value(url),
|
|
78
|
-
});
|
|
79
|
-
pool.on("connect", (client) => clients.add(client));
|
|
80
|
-
pool.on("remove", (client) => clients.delete(client));
|
|
81
|
-
pool.on("error", (error) => {
|
|
82
|
-
run(Effect.logDebug({
|
|
83
|
-
event: "auth_database_idle_client_failed",
|
|
84
|
-
message: error.message,
|
|
85
|
-
}));
|
|
86
|
-
});
|
|
87
|
-
return pool;
|
|
88
|
-
}), (pool) => Effect.promise(async () => {
|
|
89
|
-
// pg-pool resolves end before its clients finish disconnecting.
|
|
90
|
-
const disconnected = [...clients].map((client) => new Promise((resolve) => client.once("end", resolve)));
|
|
91
|
-
await pool.end();
|
|
92
|
-
await Promise.all(disconnected);
|
|
93
|
-
}));
|
|
94
|
-
});
|
|
95
70
|
//# sourceMappingURL=mount.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mount.js","sourceRoot":"","sources":["../../../src/server/better-auth/mount.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,UAAU,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"mount.js","sourceRoot":"","sources":["../../../src/server/better-auth/mount.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,UAAU,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAE1D,OAAO,EAA8B,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AACvG,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AACjE,OAAO,EAAE,gBAAgB,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AI,CAAC,QAAQ,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;IAChF,MAAM,MAAM,GAAG,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC3D,MAAM,aAAa,GAAY,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;IACnE,MAAM,QAAQ,GAAG,eAAe,CAAC,aAAa,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IACpE,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;AAClG,CAAC,CAAC,CAAC"}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
-
import
|
|
3
|
-
export declare
|
|
4
|
-
expireSessions: (userId?: string) => Effect.Effect<void, import("effect/
|
|
5
|
-
omitImageColumn: Effect.Effect<void, import("effect/
|
|
6
|
-
sessionIpAddresses:
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
|
+
export declare const authTestDatabase: Effect.Effect<{
|
|
4
|
+
expireSessions: (userId?: string) => Effect.Effect<void, import("effect/sql/SqlError").SqlError, never>;
|
|
5
|
+
omitImageColumn: Effect.Effect<void, import("effect/sql/SqlError").SqlError, never>;
|
|
6
|
+
sessionIpAddresses: import("effect/sql/Statement").Statement<{
|
|
7
7
|
ipAddress: string | null;
|
|
8
|
-
}
|
|
9
|
-
sessions:
|
|
8
|
+
}>;
|
|
9
|
+
sessions: import("effect/sql/Statement").Statement<{
|
|
10
10
|
email: string;
|
|
11
11
|
id: string;
|
|
12
12
|
userId: string;
|
|
13
|
-
}
|
|
14
|
-
users:
|
|
13
|
+
}>;
|
|
14
|
+
users: import("effect/sql/Statement").Statement<{
|
|
15
15
|
email: string;
|
|
16
16
|
id: string;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
17
|
+
}>;
|
|
18
|
+
}, never, SqlClient.SqlClient>;
|
|
19
19
|
//# sourceMappingURL=testDatabase.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testDatabase.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/testDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,
|
|
1
|
+
{"version":3,"file":"testDatabase.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/testDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,eAAO,MAAM,gBAAgB;8BAGD,MAAM;;;mBAKK,MAAM,GAAG,IAAI;;;eAE1C,MAAM;YACT,MAAM;gBACF,MAAM;;;eAEK,MAAM;YAAM,MAAM;;8BAEtC,CAAC"}
|
|
@@ -1,24 +1,13 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
-
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
|
+
export const authTestDatabase = Effect.gen(function* () {
|
|
4
|
+
const sql = (yield* SqlClient.SqlClient).withoutTransforms();
|
|
3
5
|
return {
|
|
4
|
-
expireSessions: (userId) =>
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}),
|
|
10
|
-
sessionIpAddresses: Effect.tryPromise(async () => {
|
|
11
|
-
const result = await pool.query('select "ipAddress" from "session" order by "createdAt", id');
|
|
12
|
-
return result.rows;
|
|
13
|
-
}),
|
|
14
|
-
sessions: Effect.tryPromise(async () => {
|
|
15
|
-
const result = await pool.query('select s.id, s."userId", u.email from "session" s join "user" u on u.id = s."userId" order by u.email, s.id');
|
|
16
|
-
return result.rows;
|
|
17
|
-
}),
|
|
18
|
-
users: Effect.tryPromise(async () => {
|
|
19
|
-
const result = await pool.query('select id, email from "user" order by email');
|
|
20
|
-
return result.rows;
|
|
21
|
-
}),
|
|
6
|
+
expireSessions: (userId) => sql `update "session" set "expiresAt" = now() - interval '1 second' ${userId === undefined ? sql.literal("") : sql `where "userId" = ${userId}`}`.pipe(Effect.asVoid),
|
|
7
|
+
omitImageColumn: sql `alter table "user" drop column image`.pipe(Effect.asVoid),
|
|
8
|
+
sessionIpAddresses: sql `select "ipAddress" from "session" order by "createdAt", id`,
|
|
9
|
+
sessions: sql `select s.id, s."userId", u.email from "session" s join "user" u on u.id = s."userId" order by u.email, s.id`,
|
|
10
|
+
users: sql `select id, email from "user" order by email`,
|
|
22
11
|
};
|
|
23
|
-
}
|
|
12
|
+
});
|
|
24
13
|
//# sourceMappingURL=testDatabase.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testDatabase.js","sourceRoot":"","sources":["../../../src/server/better-auth/testDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"testDatabase.js","sourceRoot":"","sources":["../../../src/server/better-auth/testDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;IACnD,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,iBAAiB,EAAE,CAAC;IAC7D,OAAO;QACN,cAAc,EAAE,CAAC,MAAe,EAAE,EAAE,CACnC,GAAG,CAAA,kEAAkE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA,oBAAoB,MAAM,EAAE,EAAE,CAAC,IAAI,CACnJ,MAAM,CAAC,MAAM,CACb;QACF,eAAe,EAAE,GAAG,CAAA,sCAAsC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;QAC9E,kBAAkB,EAAE,GAAG,CAA8B,4DAA4D;QACjH,QAAQ,EAAE,GAAG,CAIX,6GAA6G;QAC/G,KAAK,EAAE,GAAG,CAA+B,6CAA6C;KACtF,CAAC;AACH,CAAC,CAAC,CAAC"}
|
|
@@ -2,5 +2,5 @@ import { Effect, Option } from "effect";
|
|
|
2
2
|
import { type Rpc } from "effect/rpc";
|
|
3
3
|
import { type AuthUnavailable, type Forbidden, Unauthorized } from "@shivaedev/errors/taxonomy.ts";
|
|
4
4
|
import type { SessionPolicy, SessionShape } from "./session.ts";
|
|
5
|
-
export declare function revalidateStream<TSession extends SessionShape>(policy: SessionPolicy<TSession>, rpc: Rpc.AnyWithProps, id: string, lookup: Effect.Effect<Option.Option<TSession>, AuthUnavailable | Forbidden>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | Forbidden | Unauthorized, R>;
|
|
5
|
+
export declare function revalidateStream<TSession extends SessionShape>(policy: SessionPolicy<TSession>, rpc: Rpc.AnyWithProps, id: string, lookup: Effect.Effect<Option.Option<TSession>, AuthUnavailable | Forbidden>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | AuthUnavailable | Forbidden | Unauthorized, R>;
|
|
6
6
|
//# sourceMappingURL=revalidateStream.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"revalidateStream.d.ts","sourceRoot":"","sources":["../../src/server/revalidateStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,KAAK,GAAG,EAAa,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,SAAS,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AACnG,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGhE,wBAAgB,gBAAgB,CAAC,QAAQ,SAAS,YAAY,EAC7D,MAAM,EAAE,aAAa,CAAC,QAAQ,CAAC,EAC/B,GAAG,EAAE,GAAG,CAAC,YAAY,EACrB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,IAEnE,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"revalidateStream.d.ts","sourceRoot":"","sources":["../../src/server/revalidateStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,KAAK,GAAG,EAAa,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,SAAS,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AACnG,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGhE,wBAAgB,gBAAgB,CAAC,QAAQ,SAAS,YAAY,EAC7D,MAAM,EAAE,aAAa,CAAC,QAAQ,CAAC,EAC/B,GAAG,EAAE,GAAG,CAAC,YAAY,EACrB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,IAEnE,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,yEAY/C"}
|
|
@@ -8,8 +8,8 @@ export function revalidateStream(policy, rpc, id, lookup) {
|
|
|
8
8
|
return effect;
|
|
9
9
|
}
|
|
10
10
|
const check = Effect.gen(function* () {
|
|
11
|
-
const session = yield* lookup
|
|
12
|
-
if (
|
|
11
|
+
const session = yield* lookup;
|
|
12
|
+
if (Option.isNone(session) || session.value.user.id !== id) {
|
|
13
13
|
return yield* new Unauthorized({ message: "Authentication required" });
|
|
14
14
|
}
|
|
15
15
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"revalidateStream.js","sourceRoot":"","sources":["../../src/server/revalidateStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAY,SAAS,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAwC,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAEnG,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,UAAU,gBAAgB,CAC/B,MAA+B,EAC/B,GAAqB,EACrB,EAAU,EACV,MAA2E;IAE3E,OAAO,CAAU,MAA8B,EAAE,EAAE;QAClD,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;YAClD,OAAO,MAAM,CAAC;QACf,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;YACjC,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC
|
|
1
|
+
{"version":3,"file":"revalidateStream.js","sourceRoot":"","sources":["../../src/server/revalidateStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAY,SAAS,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAwC,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAEnG,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,UAAU,gBAAgB,CAC/B,MAA+B,EAC/B,GAAqB,EACrB,EAAU,EACV,MAA2E;IAE3E,OAAO,CAAU,MAA8B,EAAE,EAAE;QAClD,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;YAClD,OAAO,MAAM,CAAC;QACf,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;YACjC,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC;YAC9B,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;gBAC5D,OAAO,KAAK,CAAC,CAAC,IAAI,YAAY,CAAC,EAAE,OAAO,EAAE,yBAAyB,EAAE,CAAC,CAAC;YACxE,CAAC;QACF,CAAC,CAAC,CAAC;QACH,OAAO,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,iBAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,0BAA0B,IAAI,YAAY,CAAC,CAAC,CAAC;IAC9G,CAAC,CAAC;AACH,CAAC"}
|
|
@@ -9,7 +9,7 @@ export const makeSocketSession = Effect.fnUntraced(function* (interval) {
|
|
|
9
9
|
lookup: (key, lookup) => Effect.gen(function* () {
|
|
10
10
|
let batch = pending.get(key);
|
|
11
11
|
if (batch === undefined) {
|
|
12
|
-
batch = yield* Effect.cached(Effect.
|
|
12
|
+
batch = yield* Effect.cached(Effect.yieldNow.pipe(Effect.andThen(lookup), Effect.ensuring(Effect.sync(() => pending.delete(key)))));
|
|
13
13
|
pending.set(key, batch);
|
|
14
14
|
}
|
|
15
15
|
return yield* batch;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socketSession.js","sourceRoot":"","sources":["../../src/server/socketSession.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAiB,MAAM,EAAE,MAAM,EAAc,MAAM,QA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AM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;KACxD,CAAC,CACF,CAAC;AACH,CAAC"}
|
package/dist/sessions.d.ts
CHANGED
|
@@ -100,7 +100,9 @@ export declare const Sessions: import("@shivaedev/contract/contract.ts").Contrac
|
|
|
100
100
|
readonly queryIndexes: Schema.optional<Schema.$Array<Schema.Number>>;
|
|
101
101
|
}>, Schema.Struct<{
|
|
102
102
|
readonly _tag: Schema.Literal<"Resync">;
|
|
103
|
-
}>]>, ...never[]]>, Schema.Union<readonly [typeof import("@shivaedev/contract/readPolicyErrors.ts").MissingReadPolicy, typeof import("@shivaedev/contract/readPolicyErrors.ts").QueryReadDenied, ...Schema.Union<readonly (typeof Forbidden | typeof AuthUnavailable)[]>[]]>>, Schema.Never, typeof SessionsPermission, never> | import("effect/rpc/Rpc").Rpc<"identity.sessions.
|
|
103
|
+
}>]>, ...never[]]>, Schema.Union<readonly [typeof import("@shivaedev/contract/readPolicyErrors.ts").MissingReadPolicy, typeof import("@shivaedev/contract/readPolicyErrors.ts").QueryReadDenied, ...Schema.Union<readonly (typeof Forbidden | typeof AuthUnavailable)[]>[]]>>, Schema.Never, typeof SessionsPermission, never> | import("effect/rpc/Rpc").Rpc<"identity.sessions.revoke", Schema.Struct<{
|
|
104
|
+
id: Schema.String;
|
|
105
|
+
}>, Schema.Void, Schema.Union<readonly (typeof NotFound | typeof Forbidden | typeof AuthUnavailable)[]>, typeof SessionsPermission, never> | import("effect/rpc/Rpc").Rpc<"identity.sessions.list", Schema.Struct<{
|
|
104
106
|
readonly cursor: Schema.optionalKey<Schema.Struct<{
|
|
105
107
|
readonly id: Schema.String;
|
|
106
108
|
readonly lastActivityAt: Schema.DateTimeUtcFromString;
|
|
@@ -122,7 +124,5 @@ export declare const Sessions: import("@shivaedev/contract/contract.ts").Contrac
|
|
|
122
124
|
readonly name: Schema.String;
|
|
123
125
|
}>;
|
|
124
126
|
}>>;
|
|
125
|
-
}>, Schema.Union<readonly [Schema.Union<readonly (typeof Forbidden | typeof AuthUnavailable)[]>, typeof import("@shivaedev/contract/readPolicyErrors.ts").QueryReadDenied]>, typeof SessionsPermission, never
|
|
126
|
-
id: Schema.String;
|
|
127
|
-
}>, Schema.Void, Schema.Union<readonly (typeof NotFound | typeof Forbidden | typeof AuthUnavailable)[]>, typeof SessionsPermission, never>, readonly [], undefined>;
|
|
127
|
+
}>, Schema.Union<readonly [Schema.Union<readonly (typeof Forbidden | typeof AuthUnavailable)[]>, typeof import("@shivaedev/contract/readPolicyErrors.ts").QueryReadDenied]>, typeof SessionsPermission, never>, readonly [], undefined>;
|
|
128
128
|
//# sourceMappingURL=sessions.d.ts.map
|
package/dist/sessions.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIxC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAI5D,eAAO,MAAM,eAAe;;;;;;;;;;EAM1B,CAAC;AAEH,eAAO,MAAM,aAAa;;;EAAqF,CAAC;AAChH,eAAO,MAAM,gBAAgB;;;;;;EAG3B,CAAC;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;EAA2G,CAAC;AAEpI,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIxC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAI5D,eAAO,MAAM,eAAe;;;;;;;;;;EAM1B,CAAC;AAEH,eAAO,MAAM,aAAa;;;EAAqF,CAAC;AAChH,eAAO,MAAM,gBAAgB;;;;;;EAG3B,CAAC;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;EAA2G,CAAC;AAEpI,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uOAiBY,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shivaedev/identity",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.1",
|
|
4
4
|
"description": "Request identity, sessions, transport trust and permission enforcement for Effect RPC servers",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"effect"
|
|
@@ -41,43 +41,38 @@
|
|
|
41
41
|
"!src/**/*.spec.ts",
|
|
42
42
|
"!src/**/*.spec.tsx",
|
|
43
43
|
"!src/**/test-support",
|
|
44
|
+
"CHANGELOG.md",
|
|
44
45
|
"README.md"
|
|
45
46
|
],
|
|
46
47
|
"dependencies": {
|
|
47
|
-
"@shivaedev/access": "0.3.
|
|
48
|
+
"@shivaedev/access": "0.3.1",
|
|
48
49
|
"@shivaedev/changes": "0.6.0",
|
|
49
|
-
"@shivaedev/contract": "0.
|
|
50
|
-
"@shivaedev/errors": "0.1.
|
|
50
|
+
"@shivaedev/contract": "0.27.0",
|
|
51
|
+
"@shivaedev/errors": "0.1.3",
|
|
51
52
|
"@shivaedev/sql": "0.27.0"
|
|
52
53
|
},
|
|
53
54
|
"devDependencies": {
|
|
54
55
|
"@effect/platform-node": "4.0.6",
|
|
55
56
|
"@effect/sql-pg": "4.0.6",
|
|
56
|
-
"@shivaedev/admin": "0.12.
|
|
57
|
-
"@shivaedev/quality": "0.48.
|
|
58
|
-
"@shivaedev/server": "0.
|
|
57
|
+
"@shivaedev/admin": "0.12.3",
|
|
58
|
+
"@shivaedev/quality": "0.48.2",
|
|
59
|
+
"@shivaedev/server": "0.10.0",
|
|
59
60
|
"@shivaedev/test": "0.12.0",
|
|
60
61
|
"@shivaedev/test-sql": "0.15.0",
|
|
61
|
-
"@shivaedev/test-story": "0.
|
|
62
|
+
"@shivaedev/test-story": "0.28.0",
|
|
62
63
|
"@types/node": "24.19.2",
|
|
63
|
-
"@types/pg": "8.20.0",
|
|
64
64
|
"better-auth": "1.7.12",
|
|
65
65
|
"effect": "4.0.6",
|
|
66
|
-
"pg": "8.23.0",
|
|
67
66
|
"typescript": "7.0.2",
|
|
68
67
|
"vitest": "5.0.5"
|
|
69
68
|
},
|
|
70
69
|
"peerDependencies": {
|
|
71
70
|
"better-auth": "1.7.12",
|
|
72
|
-
"effect": "4.0.6"
|
|
73
|
-
"pg": "8.23.0"
|
|
71
|
+
"effect": "4.0.6"
|
|
74
72
|
},
|
|
75
73
|
"peerDependenciesMeta": {
|
|
76
74
|
"better-auth": {
|
|
77
75
|
"optional": true
|
|
78
|
-
},
|
|
79
|
-
"pg": {
|
|
80
|
-
"optional": true
|
|
81
76
|
}
|
|
82
77
|
},
|
|
83
78
|
"engines": {
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
+
import { Effect, Exit, Option, Schema, Scope } from "effect";
|
|
3
|
+
import { SqlClient } from "effect/sql";
|
|
4
|
+
import { betterAuthTransaction } from "./transaction.ts";
|
|
5
|
+
|
|
6
|
+
type PostgresPool = Extract<NonNullable<BetterAuthOptions["database"]>, { connect: unknown }>;
|
|
7
|
+
type PoolClient = Awaited<ReturnType<PostgresPool["connect"]>>;
|
|
8
|
+
interface Cursor<R> {
|
|
9
|
+
close: () => Promise<void>;
|
|
10
|
+
read: (count: number) => Promise<R[]>;
|
|
11
|
+
}
|
|
12
|
+
const Result = Schema.Struct({ command: Schema.String, rowCount: Schema.Number, rows: Schema.Array(Schema.Unknown) });
|
|
13
|
+
|
|
14
|
+
interface QueryResult<R> {
|
|
15
|
+
command: "UPDATE" | "DELETE" | "INSERT" | "SELECT" | "MERGE";
|
|
16
|
+
rowCount: number;
|
|
17
|
+
rows: R[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const betterAuthDatabase = Effect.fn("Identity.betterAuthDatabase")(function* () {
|
|
21
|
+
const sql = yield* SqlClient.SqlClient;
|
|
22
|
+
const transaction = yield* Effect.serviceOption(sql.transactionService);
|
|
23
|
+
const parent = yield* Scope.Scope;
|
|
24
|
+
const context = yield* Effect.context<SqlClient.SqlClient>();
|
|
25
|
+
const run = Effect.runPromiseWith(context);
|
|
26
|
+
const pool: PostgresPool = {
|
|
27
|
+
async connect(): Promise<PoolClient> {
|
|
28
|
+
const scope = await run(Scope.fork(parent));
|
|
29
|
+
const connection = await run(
|
|
30
|
+
(Option.isSome(transaction) ? Effect.succeed(transaction.value[0]) : sql.reserve).pipe(
|
|
31
|
+
Scope.provide(scope),
|
|
32
|
+
Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),
|
|
33
|
+
),
|
|
34
|
+
);
|
|
35
|
+
const control = Option.isSome(transaction) ? await run(betterAuthTransaction.pipe(Scope.provide(scope))) : undefined;
|
|
36
|
+
function query<R>(text: string, parameters: readonly unknown[]): Promise<QueryResult<R>>;
|
|
37
|
+
function query<R>(cursor: Cursor<R>): Cursor<R>;
|
|
38
|
+
function query(
|
|
39
|
+
text: string | Cursor<unknown>,
|
|
40
|
+
parameters: readonly unknown[] = [],
|
|
41
|
+
): Promise<Schema.Schema.Type<typeof Result>> | Cursor<unknown> {
|
|
42
|
+
if (typeof text !== "string") {
|
|
43
|
+
throw new Error("Better Auth database does not support cursors");
|
|
44
|
+
}
|
|
45
|
+
const nested = control?.(text);
|
|
46
|
+
return (
|
|
47
|
+
nested === undefined ? run(connection.executeRaw(text, parameters)) : nested.then(() => ({ command: text, rowCount: 0, rows: [] }))
|
|
48
|
+
).then(Schema.decodeUnknownSync(Result));
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
query,
|
|
52
|
+
release: () => {
|
|
53
|
+
void run(Scope.close(scope, Exit.void));
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
// The application SQL Layer owns pool shutdown.
|
|
58
|
+
end: () => Promise.resolve(),
|
|
59
|
+
options: {},
|
|
60
|
+
};
|
|
61
|
+
return pool;
|
|
62
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Data, Deferred, Effect, Fiber, Scope } from "effect";
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
|
+
import type { SqlError } from "effect/sql/SqlError";
|
|
4
|
+
|
|
5
|
+
class Rollback extends Data.TaggedError("BetterAuthRollback") {}
|
|
6
|
+
|
|
7
|
+
export const betterAuthTransaction = Effect.gen(function* () {
|
|
8
|
+
const sql = yield* SqlClient.SqlClient;
|
|
9
|
+
const context = yield* Effect.context<never>();
|
|
10
|
+
const run = Effect.runPromiseWith(context);
|
|
11
|
+
const scope = yield* Scope.Scope;
|
|
12
|
+
let active: { readonly done: Deferred.Deferred<void, Rollback>; readonly fiber: Fiber.Fiber<void, SqlError> } | undefined;
|
|
13
|
+
return (text: string): Promise<void> | undefined => {
|
|
14
|
+
if (text === "begin") {
|
|
15
|
+
return run(
|
|
16
|
+
Effect.gen(function* () {
|
|
17
|
+
const ready = yield* Deferred.make<void>();
|
|
18
|
+
const done = yield* Deferred.make<void, Rollback>();
|
|
19
|
+
const fiber = yield* sql.withTransaction(Deferred.succeed(ready, undefined).pipe(Effect.andThen(Deferred.await(done)))).pipe(
|
|
20
|
+
Effect.catchTag("BetterAuthRollback", () => Effect.void),
|
|
21
|
+
Effect.forkIn(scope),
|
|
22
|
+
);
|
|
23
|
+
active = { done, fiber };
|
|
24
|
+
yield* Effect.raceFirst(Deferred.await(ready), Fiber.join(fiber));
|
|
25
|
+
}),
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
if (active !== undefined && (text === "commit" || text === "rollback")) {
|
|
29
|
+
const { done, fiber } = active;
|
|
30
|
+
active = undefined;
|
|
31
|
+
return run(
|
|
32
|
+
(text === "commit" ? Deferred.succeed(done, undefined) : Deferred.fail(done, new Rollback())).pipe(Effect.andThen(Fiber.join(fiber))),
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
};
|
|
37
|
+
});
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type BetterAuthOptions, betterAuth } from "better-auth";
|
|
2
2
|
import { Config, Effect, Option, Redacted } from "effect";
|
|
3
|
-
import { Pool, type PoolClient, type PoolConfig } from "pg";
|
|
4
3
|
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
5
4
|
import { type BearerSessionsOptions, withBearerSessions } from "#server/better-auth/bearerSessions.ts";
|
|
6
5
|
import { PEER_IP_HEADER } from "#server/better-auth/clientIp.ts";
|
|
@@ -82,37 +81,3 @@ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <
|
|
|
82
81
|
const sessions = mountedSessions(lookupSession, admit, mount.roles);
|
|
83
82
|
return { admittedSessions: admit, auth, revokeUnadmitted: revoke, routes: authRoutes, sessions };
|
|
84
83
|
});
|
|
85
|
-
|
|
86
|
-
export const authDatabase = Effect.fn("Platform.authDatabase")(function* (
|
|
87
|
-
url: Redacted.Redacted<string>,
|
|
88
|
-
options: Pick<PoolConfig, "max" | "application_name"> = {},
|
|
89
|
-
) {
|
|
90
|
-
const clients = new Set<PoolClient>();
|
|
91
|
-
const run = Effect.runForkWith(yield* Effect.context<never>());
|
|
92
|
-
return yield* Effect.acquireRelease(
|
|
93
|
-
Effect.sync(() => {
|
|
94
|
-
const pool = new Pool({
|
|
95
|
-
...options,
|
|
96
|
-
connectionString: Redacted.value(url),
|
|
97
|
-
});
|
|
98
|
-
pool.on("connect", (client) => clients.add(client));
|
|
99
|
-
pool.on("remove", (client) => clients.delete(client));
|
|
100
|
-
pool.on("error", (error) => {
|
|
101
|
-
run(
|
|
102
|
-
Effect.logDebug({
|
|
103
|
-
event: "auth_database_idle_client_failed",
|
|
104
|
-
message: error.message,
|
|
105
|
-
}),
|
|
106
|
-
);
|
|
107
|
-
});
|
|
108
|
-
return pool;
|
|
109
|
-
}),
|
|
110
|
-
(pool) =>
|
|
111
|
-
Effect.promise(async () => {
|
|
112
|
-
// pg-pool resolves end before its clients finish disconnecting.
|
|
113
|
-
const disconnected = [...clients].map((client) => new Promise<void>((resolve) => client.once("end", resolve)));
|
|
114
|
-
await pool.end();
|
|
115
|
-
await Promise.all(disconnected);
|
|
116
|
-
}),
|
|
117
|
-
);
|
|
118
|
-
});
|
|
@@ -1,31 +1,20 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
-
import
|
|
2
|
+
import { SqlClient } from "effect/sql";
|
|
3
3
|
|
|
4
|
-
export
|
|
4
|
+
export const authTestDatabase = Effect.gen(function* () {
|
|
5
|
+
const sql = (yield* SqlClient.SqlClient).withoutTransforms();
|
|
5
6
|
return {
|
|
6
7
|
expireSessions: (userId?: string) =>
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
return result.rows;
|
|
19
|
-
}),
|
|
20
|
-
sessions: Effect.tryPromise(async () => {
|
|
21
|
-
const result = await pool.query<{ email: string; id: string; userId: string }>(
|
|
22
|
-
'select s.id, s."userId", u.email from "session" s join "user" u on u.id = s."userId" order by u.email, s.id',
|
|
23
|
-
);
|
|
24
|
-
return result.rows;
|
|
25
|
-
}),
|
|
26
|
-
users: Effect.tryPromise(async () => {
|
|
27
|
-
const result = await pool.query<{ email: string; id: string }>('select id, email from "user" order by email');
|
|
28
|
-
return result.rows;
|
|
29
|
-
}),
|
|
8
|
+
sql`update "session" set "expiresAt" = now() - interval '1 second' ${userId === undefined ? sql.literal("") : sql`where "userId" = ${userId}`}`.pipe(
|
|
9
|
+
Effect.asVoid,
|
|
10
|
+
),
|
|
11
|
+
omitImageColumn: sql`alter table "user" drop column image`.pipe(Effect.asVoid),
|
|
12
|
+
sessionIpAddresses: sql<{ ipAddress: string | null }>`select "ipAddress" from "session" order by "createdAt", id`,
|
|
13
|
+
sessions: sql<{
|
|
14
|
+
email: string;
|
|
15
|
+
id: string;
|
|
16
|
+
userId: string;
|
|
17
|
+
}>`select s.id, s."userId", u.email from "session" s join "user" u on u.id = s."userId" order by u.email, s.id`,
|
|
18
|
+
users: sql<{ email: string; id: string }>`select id, email from "user" order by email`,
|
|
30
19
|
};
|
|
31
|
-
}
|
|
20
|
+
});
|
|
@@ -15,8 +15,8 @@ export function revalidateStream<TSession extends SessionShape>(
|
|
|
15
15
|
return effect;
|
|
16
16
|
}
|
|
17
17
|
const check = Effect.gen(function* () {
|
|
18
|
-
const session = yield* lookup
|
|
19
|
-
if (
|
|
18
|
+
const session = yield* lookup;
|
|
19
|
+
if (Option.isNone(session) || session.value.user.id !== id) {
|
|
20
20
|
return yield* new Unauthorized({ message: "Authentication required" });
|
|
21
21
|
}
|
|
22
22
|
});
|
|
@@ -27,7 +27,7 @@ export const makeSocketSession = Effect.fnUntraced(function* (interval: Duration
|
|
|
27
27
|
Effect.gen(function* () {
|
|
28
28
|
let batch = pending.get(key);
|
|
29
29
|
if (batch === undefined) {
|
|
30
|
-
batch = yield* Effect.cached(Effect.
|
|
30
|
+
batch = yield* Effect.cached(Effect.yieldNow.pipe(Effect.andThen(lookup), Effect.ensuring(Effect.sync(() => pending.delete(key)))));
|
|
31
31
|
pending.set(key, batch);
|
|
32
32
|
}
|
|
33
33
|
return yield* batch;
|