@shivaedev/identity 0.22.0 → 0.23.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 CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.23.1 - 2026-11-04
4
+
5
+ ### Changed
6
+
7
+ - Support externally migrated Better Auth tables as a transition to identity's frozen auth migrations. Run `assertBetterAuthSchema` before `betterAuthMount` at startup to refuse schema drift with typed diagnostics naming missing tables or columns.
8
+
9
+ ## 0.23.0 - 2026-11-04
10
+
11
+ ### Added
12
+
13
+ - Identity provides `selfSubject`, `accountSubject` and a branded `Subject` service. Services can read the session user independently of the account being acted on; delegated accounts require the permission's `any` grant.
14
+
15
+ ## 0.22.1 - 2026-11-03
16
+
17
+ ### Changed
18
+
19
+ - Update `@shivaedev/contract` from 0.33.0 to 0.33.1.
20
+ - Update `@shivaedev/rate-limit` from 0.3.1 to 0.3.2.
21
+ - Update `@shivaedev/sql` from 0.35.0 to 0.36.0.
22
+
3
23
  ## 0.22.0 - 2026-11-03
4
24
 
5
25
  ### Added
package/README.md CHANGED
@@ -36,38 +36,46 @@ There are three parts to an authenticated RPC boundary:
36
36
 
37
37
  An **Origin policy** is a function of the transport request's origin, headers and RPC name. A **session provider** returns `Option<Session>` or fails with `AuthUnavailable`; a session carries `user.id`. These are application inputs, not a second authentication framework. Better Auth is the supported provider, mounted through `server/better-auth/`.
38
38
 
39
- ### Once per application: contracts and session policy
39
+ ### Declared request subjects
40
40
 
41
- Declare the RPC group in a shared module:
41
+ A **subject** is the account whose data this request acts on. The actor remains the session user. `Subject` from `@shivaedev/identity/subject.ts` provides `{ id: SubjectId }`, where `SubjectId` is a branded string. `selfSubject` resolves it from the session, ignoring account-selection headers. It also provides `Identity` and `SessionUser`, so service methods can read the caller without an actor argument.
42
42
 
43
43
  ```ts
44
44
  import { Effect, Schema } from "effect";
45
- import { Rpc, RpcGroup } from "effect/rpc";
46
- import { Forbidden } from "@shivaedev/errors/taxonomy.ts";
47
- import { Identity } from "@shivaedev/identity/identity.ts";
48
- import { Authenticated } from "@shivaedev/identity/middleware.ts";
45
+ import { contract } from "@shivaedev/contract/contract.ts";
46
+ import { command } from "@shivaedev/contract/operation.ts";
47
+ import { selfSubject, Subject } from "@shivaedev/identity/subject.ts";
48
+
49
+ const Save = command("save", { payload: { title: Schema.String }, success: Schema.String, invalidates: () => [] });
50
+ export const Account = contract("account", { commands: [Save], subject: selfSubject });
51
+ export const Handlers = Account.application.toLayer({
52
+ "account.save": ({ title }) => Effect.map(Subject, ({ id }) => `${id}: ${title}`),
53
+ });
54
+ ```
49
55
 
50
- export const Account = RpcGroup.make(
51
- Rpc.make("ReadOwn", {
52
- error: Forbidden,
53
- payload: { userId: Schema.String },
54
- success: Schema.String,
55
- }),
56
- ).middleware(Authenticated);
56
+ For delegation, use `accountSubject` with an application permission and a typed refusal:
57
57
 
58
- export const Handlers = Account.toLayer({
59
- ReadOwn: ({ userId }) =>
60
- Effect.gen(function* () {
61
- const identity = yield* Identity;
62
- if (identity.id !== userId) {
63
- return yield* new Forbidden({ message: "Not your account" });
64
- }
65
- return identity.id;
66
- }),
58
+ ```ts
59
+ import { Schema } from "effect";
60
+ import { permission } from "@shivaedev/access/permission.ts";
61
+ import { accountSubject } from "@shivaedev/identity/subject.ts";
62
+
63
+ const EditAccount = permission("accounts.edit");
64
+ class CannotActForAccount extends Schema.TaggedError<CannotActForAccount>()("CannotActForAccount", { account: Schema.String }) {}
65
+ const delegated = accountSubject({
66
+ permission: EditAccount,
67
+ refusal: CannotActForAccount,
68
+ deny: (account) => new CannotActForAccount({ account }),
67
69
  });
68
70
  ```
69
71
 
70
- The middleware declaration makes `Identity` available to guarded handlers and adds `Unauthorized`, `AuthUnavailable` and `Forbidden` to the client's failure type. An unguarded handler that requires `Identity` cannot become a service-free handler Layer. Keep the group declaration in the shared module and the handler implementation on the server when organizing application files.
72
+ Pass `subject: delegated` to the contract. A delegated request selects the account with the `x-platform-subject` transport header; omitting it selects the session account. Acting on another account requires the named permission's `any` grant. An `own` grant does not authorize another account. A refusal reaches the native client as the declared error instance before the handler runs. `Identity` and `SessionUser` still describe the actor when `Subject` describes another account. The session provider must supply the `SessionUserSchema` profile fields, as for `AuthenticatedUser`.
73
+
74
+ `appHost` installs `subjectResolverLayer()` from `@shivaedev/identity/server/subjectResolverLayer.ts` for session hosts. Custom native RPC hosts provide that Layer with their `SessionPolicy` and install `subjectLayers(group)` from `@shivaedev/contract/subjectLayers.ts` when building the native RPC server. The subject declaration includes authentication failures in the client's error type; it needs no separate authentication middleware.
75
+
76
+ ### Once per application: contracts and session policy
77
+
78
+ Declare authentication middleware for actor-only boundaries. When a request acts on an account's data, declare its subject on the contract instead of accepting an owner id and checking it in each handler.
71
79
 
72
80
  Provide one `SessionPolicy` Layer as the host's `sessions` input. Middleware, permission routes and session resolution read that service from the Effect environment. For a Better Auth provider, adapt its existing session lookup:
73
81
 
@@ -140,7 +148,7 @@ const authentication = Effect.gen(function* () {
140
148
  });
141
149
  ```
142
150
 
143
- `betterAuthDatabase()` reads the application’s `SqlClient` and reserves connections from its PostgreSQL pool. Build it inside `appHost`’s `application` Effect, or provide sql’s `postgresLayer` for a standalone process. Set `maxConnections` and `applicationName` on the application SQL Layer. Generate frozen numbered auth migrations as described below. The application SQL Layer owns shutdown.
151
+ `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 mount does not run migrations or require identity's migration history. Use frozen numbered auth migrations as described below, or keep an existing migrator during the transition described in [Auth tables owned by another migrator](#auth-tables-owned-by-another-migrator). The application SQL Layer owns shutdown.
144
152
 
145
153
  The adapter captures the SQL transaction at creation. An adapter created at startup does not join a later `transact` around an `auth.api` call: its auth writes commit independently and survive the application's rollback. For a shared boundary, create the adapter inside `transact`, and use it only within that transaction. Create the mount there too when its Effect hooks must share the application transaction:
146
154
 
@@ -240,7 +248,7 @@ The native `emailAndPassword.onPasswordReset` callback runs first. An Effect fai
240
248
 
241
249
  ### User directory
242
250
 
243
- Applications use the `UserDirectory` port from `@shivaedev/identity/server/UserDirectory.ts` instead of reading auth tables. Provide `betterAuthUserDirectory(AppAccess, authOptions)` from `@shivaedev/identity/server/better-auth/adapters/userDirectory.ts` with the application's SQL Layer. The adapter follows Better Auth's configured user model, name, email, creation and modification columns, and additional-field or plugin role mapping. It shares an existing Reactivity service when supplied and creates one otherwise.
251
+ Applications use the `UserDirectory` port from `@shivaedev/identity/server/UserDirectory.ts` instead of reading auth tables. Provide `betterAuthUserDirectory(AppAccess, authOptions)` from `@shivaedev/identity/server/better-auth/adapters/userDirectory.ts` with the application's SQL Layer. Setting `authOptions.user.modelName` to `"users"` directs directory reads to that table, including the admin Users view and its pagination. The adapter follows Better Auth's configured user model, name, email, creation and modification columns, and additional-field or plugin role mapping. It shares an existing Reactivity service when supplied and creates one otherwise.
244
252
 
245
253
  ```ts
246
254
  import { UserDirectory } from "@shivaedev/identity/server/UserDirectory.ts";
@@ -571,6 +579,35 @@ The failure's `_tag` remains `AuthFailure`; its `code` union includes the declar
571
579
 
572
580
  React's `authAction`, `authQuery` and `authSession` consume these Effects to create atoms. See [React's Better Auth usage](https://github.com/ShivaeDev/platform/blob/main/packages/react/README.md#better-auth-actions).
573
581
 
582
+ ### Auth tables owned by another migrator
583
+
584
+ An application moving from Prisma can keep Prisma in charge of its auth tables while adopting identity's mount. Apply the existing migrator first, then run `assertBetterAuthSchema` as a startup guard before `betterAuthMount`. Both use the same application `SqlClient`; keep Better Auth's table and field mappings aligned with the existing schema.
585
+
586
+ ```ts
587
+ import { Effect } from "effect";
588
+ import { assertBetterAuthSchema } from "@shivaedev/identity/server/better-auth/adapters/assertSchema.ts";
589
+ import { betterAuthDatabase } from "@shivaedev/identity/server/better-auth/adapters/database.ts";
590
+ import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
591
+
592
+ const authOptions = {
593
+ account: { modelName: "Account" },
594
+ emailAndPassword: { enabled: true },
595
+ session: { modelName: "Session" },
596
+ user: { modelName: "User" },
597
+ verification: { modelName: "Verification" },
598
+ };
599
+
600
+ const authentication = Effect.gen(function* () {
601
+ yield* assertBetterAuthSchema(authOptions);
602
+ const database = yield* betterAuthDatabase();
603
+ return yield* betterAuthMount({ ...authOptions, database });
604
+ });
605
+ ```
606
+
607
+ Provide the SQL Layer and `memoryStore`, and supply the secret as for any mount. The guard fails in the Effect error channel with `BetterAuthSchemaDrift` from the assertion module; its `missing` array names missing tables and columns, such as `column User.emailVerified`. This failure stops acquisition before the mount starts, preserving the actionable schema diagnostic instead of the provider's generic `AuthUnavailable`. Extra application columns can stay in the auth tables. The mount reads existing sessions without changing the schema or taking over its migrations.
608
+
609
+ This is a migration step towards identity's frozen auth migrations. While Prisma owns the tables, make schema corrections in Prisma. When ownership moves, preserve the existing schema baseline in the application's migration history and use the frozen workflow below for subsequent auth changes. Generate each addition against a disposable database with the previously shipped schema applied, and register it with the application's numbered SQL migrations. Keep one migrator responsible for each auth schema change.
610
+
574
611
  ### Frozen auth migrations
575
612
 
576
613
  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.
@@ -671,7 +708,7 @@ An operation on one record reads that record's owner and uses the application's
671
708
 
672
709
  ### Session-scoped contract keys
673
710
 
674
- For self-only features, declare `contract("preferences", { keyScope: "session", queries, commands }).middleware(Authenticated)`. The client registry owns cache isolation. Server subscriptions use the same plain record, list and bucket keys as repository writes. Handlers read their owner from `Identity`, and queries need no additional session keys. Matching keys trigger each subscriber's read policy before it can receive a hint or result; shared dependencies can cause authorized rechecks across accounts.
711
+ For self-only features, declare `contract("preferences", { keyScope: "session", subject: selfSubject, queries, commands })`. The client registry owns cache isolation. Server subscriptions use the same plain record, list and bucket keys as repository writes. Handlers read their owner from `Subject`, and queries need no additional session keys. Matching keys trigger each subscriber's read policy before it can receive a hint or result; shared dependencies can cause authorized rechecks across accounts.
675
712
 
676
713
  The host's generated `$changes` handler accepts `{ queries: [{ query: "get", payload: { id: "theme" } }] }` and resolves the declared query dependencies during that subscription invocation. It accepts no physical subscription keys or caller-selected scope.
677
714
 
@@ -1,5 +1,5 @@
1
1
  import { Context, Effect, Option } from "effect";
2
2
  import { type AuthUnavailable, type Forbidden, Unauthorized } from "@shivaedev/errors/taxonomy.ts";
3
3
  import type { SessionShape } from "./session.ts";
4
- export declare const currentSessionContext: <TSession extends SessionShape, R>(id: string, lookup: Effect.Effect<Option.Option<TSession>, AuthUnavailable | Forbidden, R>) => Effect.Effect<Context.Context<never>, AuthUnavailable | Forbidden | Unauthorized, R>;
4
+ export declare const currentSessionContext: <TSession extends SessionShape, R, E = AuthUnavailable | Forbidden>(id: string, lookup: Effect.Effect<Option.Option<TSession>, E, R>) => Effect.Effect<Context.Context<never>, E | Unauthorized, R>;
5
5
  //# sourceMappingURL=currentSessionContext.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"currentSessionContext.d.ts","sourceRoot":"","sources":["../../src/server/currentSessionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,SAAS,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGnG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,eAAO,MAAM,qBAAqB,GAAgC,QAAQ,SAAS,YAAY,EAAE,CAAC,qLAgBhG,CAAC"}
1
+ {"version":3,"file":"currentSessionContext.d.ts","sourceRoot":"","sources":["../../src/server/currentSessionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OA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AAC,CAAC,MAAM,CAAC,OAAO,EAAS,CAAC;IAC7C,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC;QAC5D,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9G,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,+BAA+B,CAAC,CAAC,EAAE,CAAC;QAChF,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,+BAA+B,EAAE,KAAK,CAAC,CAAC,oBAAoB,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAClH,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC,CAAC"}
@@ -3,5 +3,5 @@ import { type Rpc } from "effect/rpc";
3
3
  import type { AuthUnavailable, Forbidden } from "@shivaedev/errors/taxonomy.ts";
4
4
  import { SessionPolicy } from "./SessionPolicy.ts";
5
5
  import type { SessionShape } from "./session.ts";
6
- export declare function revalidateStream<TSession extends SessionShape, TLookupRequirements>(rpc: Rpc.AnyWithProps, id: string, lookup: Effect.Effect<Option.Option<TSession>, AuthUnavailable | Forbidden, TLookupRequirements>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | AuthUnavailable | Forbidden | import("@shivaedev/errors/taxonomy.ts").Unauthorized, R | TLookupRequirements | SessionPolicy>;
6
+ export declare function revalidateStream<TSession extends SessionShape, TLookupRequirements, TLookupError = AuthUnavailable | Forbidden>(rpc: Rpc.AnyWithProps, id: string, lookup: Effect.Effect<Option.Option<TSession>, TLookupError, TLookupRequirements>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | TLookupError | import("@shivaedev/errors/taxonomy.ts").Unauthorized, R | TLookupRequirements | SessionPolicy>;
7
7
  //# 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,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,EAAE,KAAK,GAAG,EAAa,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGjD,wBAAgB,gBAAgB,CAAC,QAAQ,SAAS,YAAY,EAAE,mBAAmB,EAClF,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,EAAE,mBAAmB,CAAC,IAExF,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,uJAS/C"}
1
+ {"version":3,"file":"revalidateStream.d.ts","sourceRoot":"","sources":["../../src/server/revalidateStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,EAAE,KAAK,GAAG,EAAa,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG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,CACrG,CAAC;IACH,CAAC,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"revalidateStream.js","sourceRoot":"","sources":["../../src/server/revalidateStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAe,MAAM,QAAQ,CAAC;AAC7C,OAAO,EAAY,SAAS,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,UAAU,gBAAgB,CAC/B,GAAqB,EACrB,EAAU,EACV,MAAiF;IAEjF,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,MAAM,CAAC,qBAAqB,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,MAAM,EAAE,EAAE,CAC/C,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,iBAAiB,CAAC,KAAK,EAAE,MAAM,CAAC,0BAA0B,IAAI,YAAY,CAAC,CAAC,CACrG,CAAC;IACH,CAAC,CAAC;AACH,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { Layer } from "effect";
2
+ import { SubjectResolver } from "#subject.ts";
3
+ export declare function subjectResolverLayer(): Layer.Layer<SubjectResolver, never, never>;
4
+ //# sourceMappingURL=subjectResolverLayer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subjectResolverLayer.d.ts","sourceRoot":"","sources":["../../src/server/subjectResolverLayer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,EAAkB,MAAM,QAAQ,CAAC;AAWvD,OAAO,EAA8C,eAAe,EAAE,MAAM,aAAa,CAAC;AAqC1F,wBAAgB,oBAAoB,+CAiBnC"}
@@ -0,0 +1,47 @@
1
+ import { Effect, Layer, Option, Schema } from "effect";
2
+ import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
3
+ import { Unauthorized } from "@shivaedev/errors/taxonomy.ts";
4
+ import { Identity, SessionUser, SessionUserSchema } from "#identity.ts";
5
+ import { hasPermission } from "#permission.ts";
6
+ import { recheckSession } from "#server/recheckSession.ts";
7
+ import { revalidateStream } from "#server/revalidateStream.ts";
8
+ import { SessionPolicy } from "#server/SessionPolicy.ts";
9
+ import { resolveSession } from "#server/session.ts";
10
+ import { transportHeaders } from "#server/transportHeaders.ts";
11
+ import { Subject, SubjectId, SubjectResolver } from "#subject.ts";
12
+ function guard(policy) {
13
+ return (effect, { headers, rpc }) => Effect.gen(function* () {
14
+ const session = yield* resolveSession(headers, rpc._tag);
15
+ if (Option.isNone(session)) {
16
+ return yield* new Unauthorized({ message: "Authentication required" });
17
+ }
18
+ const user = session.value.user;
19
+ const transport = yield* transportHeaders(headers);
20
+ const id = policy.kind === "self" ? user.id : (transport["x-platform-subject"] ?? user.id);
21
+ if (policy.kind === "account" && id !== user.id && !hasPermission(user, { ...policy.permission, strength: "any" })) {
22
+ return yield* Effect.fail(policy.deny(id));
23
+ }
24
+ const lookup = recheckSession(headers, rpc._tag).pipe(Effect.tap((next) => Option.isSome(next)
25
+ && policy.kind === "account"
26
+ && id !== next.value.user.id
27
+ && !hasPermission(next.value.user, { ...policy.permission, strength: "any" })
28
+ ? Effect.fail(policy.deny(id))
29
+ : Effect.void));
30
+ return yield* effect.pipe(revalidateStream(rpc, user.id, lookup), Effect.provideService(Subject, { id: SubjectId(id) }), Effect.provideService(Identity, { id: user.id }), Effect.provideService(SessionUser, Schema.decodeUnknownSync(SessionUserSchema)(user)), Effect.provideService(CurrentViewer, Option.some({ id: user.id })));
31
+ });
32
+ }
33
+ export function subjectResolverLayer() {
34
+ return Layer.effect(SubjectResolver, Effect.map(Effect.serviceOption(SessionPolicy), (sessions) => {
35
+ function resolved(policy) {
36
+ const middleware = guard(policy);
37
+ return (effect, request) => Option.isSome(sessions)
38
+ ? middleware(effect, request).pipe(Effect.provideService(SessionPolicy, sessions.value))
39
+ : Effect.fail(new Unauthorized({ message: "Authentication required" }));
40
+ }
41
+ return {
42
+ account: (permission, deny) => resolved({ deny, kind: "account", permission }),
43
+ self: resolved({ kind: "self" }),
44
+ };
45
+ }));
46
+ }
47
+ //# sourceMappingURL=subjectResolverLayer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subjectResolverLayer.js","sourceRoot":"","sources":["../../src/server/subjectResolverLayer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,SAAS,EAA0B,eAAe,EAAE,MAAM,aAAa,CAAC;AAI1F,SAAS,KAAK,CAAI,MAAiB;IAClC,OAAO,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,CACnC,MAAM,C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c,CAAC,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;gBACxF,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,YAAY,CAAC,EAAE,OAAO,EAAE,yBAAyB,EAAE,CAAC,CAAC,CAAC;QAC3E,CAAC;QACD,OAAO;YACN,OAAO,EAAE,CAAI,UAAsB,EAAE,IAAuB,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC;YAChH,IAAI,EAAE,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;SAChC,CAAC;IACH,CAAC,CAAC,CACF,CAAC;AACH,CAAC"}
@@ -0,0 +1,34 @@
1
+ import { Brand, Context, Effect, Schema } from "effect";
2
+ import type { RpcMiddleware } from "effect/rpc";
3
+ import type { Permission } from "@shivaedev/access/permission.ts";
4
+ import type { TaggedRejection } from "@shivaedev/contract/rejection.ts";
5
+ import type { Identity, SessionUser } from "#identity.ts";
6
+ import { IdentityFailures } from "#middleware.ts";
7
+ export type SubjectId = string & Brand.Brand<"@shivaedev/identity/SubjectId">;
8
+ export declare const SubjectId: Brand.Constructor<SubjectId>;
9
+ declare const Subject_base: Context.ServiceClass<Subject, "@shivaedev/identity/Subject", {
10
+ readonly id: SubjectId;
11
+ }>;
12
+ export declare class Subject extends Subject_base {
13
+ }
14
+ export type SubjectMiddleware<E = never, R = never> = RpcMiddleware.RpcMiddleware<Subject | Identity | SessionUser, IdentityFailures | E, R>;
15
+ declare const SubjectResolver_base: Context.ServiceClass<SubjectResolver, "@shivaedev/identity/SubjectResolver", {
16
+ readonly self: SubjectMiddleware;
17
+ readonly account: <E>(permission: Permission, deny: (id: string) => E) => SubjectMiddleware<E>;
18
+ }>;
19
+ export declare class SubjectResolver extends SubjectResolver_base {
20
+ }
21
+ export declare const selfSubject: {
22
+ error: Schema.Union<readonly [typeof import("@shivaedev/errors/taxonomy.ts").Unauthorized, typeof import("@shivaedev/errors/taxonomy.ts").AuthUnavailable, typeof import("@shivaedev/errors/taxonomy.ts").Forbidden, typeof import("@shivaedev/contract/readPolicyErrors.ts").MissingReadPolicy, typeof import("@shivaedev/contract/readPolicyErrors.ts").QueryReadDenied]>;
23
+ middleware: Effect.Effect<SubjectMiddleware<never, never>, never, SubjectResolver>;
24
+ };
25
+ export declare function accountSubject<TRefusal extends TaggedRejection>(options: {
26
+ readonly permission: Permission;
27
+ readonly refusal: TRefusal;
28
+ readonly deny: (id: string) => NoInfer<TRefusal["Type"]>;
29
+ }): {
30
+ error: Schema.Union<readonly [Schema.Union<readonly [typeof import("@shivaedev/errors/taxonomy.ts").Unauthorized, typeof import("@shivaedev/errors/taxonomy.ts").AuthUnavailable, typeof import("@shivaedev/errors/taxonomy.ts").Forbidden, typeof import("@shivaedev/contract/readPolicyErrors.ts").MissingReadPolicy, typeof import("@shivaedev/contract/readPolicyErrors.ts").QueryReadDenied]>, TRefusal]>;
31
+ middleware: Effect.Effect<SubjectMiddleware<NoInfer<TRefusal["Type"]>, never>, never, SubjectResolver>;
32
+ };
33
+ export {};
34
+ //# sourceMappingURL=subject.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subject.d.ts","sourceRoot":"","sources":["../src/subject.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAExE,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAElD,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;AAC9E,eAAO,MAAM,SAAS,8BAA6B,CAAC;;iBACiB,SAAS;;AAA9E,qBAAa,OAAQ,SAAQ,YAAqF;CAAG;AAErH,MAAM,MAAM,iBAAiB,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,KAAK,IAAI,aAAa,CAAC,aAAa,CAAC,OAAO,GAAG,QAAQ,GAAG,WAAW,EAAE,gBAAgB,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;;mBAK5H,iBAAiB;sBACd,CAAC,CAAC,EAAE,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,CAAC,KAAK,iBAAiB,CAAC,CAAC,CAAC;;AAJhG,qBAAa,eAAgB,SAAQ,oBAMK;CAAG;AAE7C,eAAO,MAAM,WAAW;;;CAGM,CAAC;AAE/B,wBAAgB,cAAc,CAAC,QAAQ,SAAS,eAAe,EAAE,OAAO,EAAE;IACzE,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;CACzD;;;EAKA"}
@@ -0,0 +1,18 @@
1
+ import { Brand, Context, Effect, Schema } from "effect";
2
+ import { IdentityFailures } from "#middleware.ts";
3
+ export const SubjectId = Brand.nominal();
4
+ export class Subject extends Context.Service()("@shivaedev/identity/Subject") {
5
+ }
6
+ export class SubjectResolver extends Context.Service()("@shivaedev/identity/SubjectResolver") {
7
+ }
8
+ export const selfSubject = {
9
+ error: IdentityFailures,
10
+ middleware: Effect.map(SubjectResolver, (resolver) => resolver.self),
11
+ };
12
+ export function accountSubject(options) {
13
+ return {
14
+ error: Schema.Union([IdentityFailures, options.refusal]),
15
+ middleware: Effect.map(SubjectResolver, (resolver) => resolver.account(options.permission, options.deny)),
16
+ };
17
+ }
18
+ //# sourceMappingURL=subject.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subject.js","sourceRoot":"","sources":["../src/subject.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAMxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAGlD,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,EAAa,CAAC;AACpD,MAAM,OAAO,OAAQ,SAAQ,OAAO,CAAC,OAAO,EAAuC,CAAC,6BAA6B,CAAC;CAAG;AAIrH,MAAM,OAAO,eAAgB,SAAQ,OAAO,CAAC,OAAO,EAMjD,CAAC,qCAAqC,CAAC;CAAG;AAE7C,MAAM,CAAC,MAAM,WAAW,GAAG;IAC1B,KAAK,EAAE,gBAAgB;IACvB,UAAU,EAAE,MAAM,CAAC,GAAG,CAAC,eAAe,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC;CACvC,CAAC;AAE/B,MAAM,UAAU,cAAc,CAAmC,OAIhE;IACA,OAAO;QACN,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,gBAAgB,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QACxD,UAAU,EAAE,MAAM,CAAC,GAAG,CAAC,eAAe,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;KAC5E,CAAC;AAChC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/identity",
3
- "version": "0.22.0",
3
+ "version": "0.23.1",
4
4
  "description": "Request identity, sessions, transport trust and permission enforcement for Effect RPC servers",
5
5
  "keywords": [
6
6
  "effect"
@@ -45,23 +45,23 @@
45
45
  "README.md"
46
46
  ],
47
47
  "dependencies": {
48
- "@shivaedev/access": "0.4.1",
48
+ "@shivaedev/access": "0.4.2",
49
49
  "@shivaedev/changes": "0.9.0",
50
- "@shivaedev/contract": "0.33.0",
51
- "@shivaedev/errors": "0.7.0",
52
- "@shivaedev/rate-limit": "0.3.1",
53
- "@shivaedev/sql": "0.35.0"
50
+ "@shivaedev/contract": "0.35.0",
51
+ "@shivaedev/errors": "0.8.0",
52
+ "@shivaedev/rate-limit": "0.3.3",
53
+ "@shivaedev/sql": "0.36.1"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@better-auth/oauth-provider": "1.7.14",
57
57
  "@effect/platform-node": "4.0.6",
58
58
  "@effect/sql-pg": "4.0.6",
59
- "@shivaedev/admin": "0.19.2",
60
- "@shivaedev/quality": "0.57.1",
61
- "@shivaedev/server": "0.20.2",
62
- "@shivaedev/test-kits": "0.1.1",
63
- "@shivaedev/test-sql": "0.18.0",
64
- "@shivaedev/test-story": "0.36.0",
59
+ "@shivaedev/admin": "0.19.5",
60
+ "@shivaedev/quality": "0.59.0",
61
+ "@shivaedev/server": "0.23.0",
62
+ "@shivaedev/test-kits": "0.2.2",
63
+ "@shivaedev/test-sql": "0.19.0",
64
+ "@shivaedev/test-story": "0.37.1",
65
65
  "@types/node": "24.19.2",
66
66
  "better-auth": "1.7.14",
67
67
  "effect": "4.0.6",
@@ -4,9 +4,9 @@ import { SessionUser, SessionUserSchema, SessionUserWithProviderAccounts } from
4
4
  import { providerAccountsUser } from "./providerAccountsUser.ts";
5
5
  import type { SessionShape } from "./session.ts";
6
6
 
7
- export const currentSessionContext = Effect.fnUntraced(function* <TSession extends SessionShape, R>(
7
+ export const currentSessionContext = Effect.fnUntraced(function* <TSession extends SessionShape, R, E = AuthUnavailable | Forbidden>(
8
8
  id: string,
9
- lookup: Effect.Effect<Option.Option<TSession>, AuthUnavailable | Forbidden, R>,
9
+ lookup: Effect.Effect<Option.Option<TSession>, E, R>,
10
10
  ) {
11
11
  const session = yield* lookup;
12
12
  if (Option.isNone(session) || session.value.user.id !== id) {
@@ -6,10 +6,10 @@ import { SessionPolicy } from "./SessionPolicy.ts";
6
6
  import type { SessionShape } from "./session.ts";
7
7
  import { revalidateSession } from "./socketSession.ts";
8
8
 
9
- export function revalidateStream<TSession extends SessionShape, TLookupRequirements>(
9
+ export function revalidateStream<TSession extends SessionShape, TLookupRequirements, TLookupError = AuthUnavailable | Forbidden>(
10
10
  rpc: Rpc.AnyWithProps,
11
11
  id: string,
12
- lookup: Effect.Effect<Option.Option<TSession>, AuthUnavailable | Forbidden, TLookupRequirements>,
12
+ lookup: Effect.Effect<Option.Option<TSession>, TLookupError, TLookupRequirements>,
13
13
  ) {
14
14
  return <A, E, R>(effect: Effect.Effect<A, E, R>) => {
15
15
  if (!RpcSchema.isStreamSchema(rpc.successSchema)) {
@@ -0,0 +1,66 @@
1
+ import { Effect, Layer, Option, Schema } from "effect";
2
+ import type { Permission } from "@shivaedev/access/permission.ts";
3
+ import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
4
+ import { Unauthorized } from "@shivaedev/errors/taxonomy.ts";
5
+ import { Identity, SessionUser, SessionUserSchema } from "#identity.ts";
6
+ import { hasPermission } from "#permission.ts";
7
+ import { recheckSession } from "#server/recheckSession.ts";
8
+ import { revalidateStream } from "#server/revalidateStream.ts";
9
+ import { SessionPolicy } from "#server/SessionPolicy.ts";
10
+ import { resolveSession } from "#server/session.ts";
11
+ import { transportHeaders } from "#server/transportHeaders.ts";
12
+ import { Subject, SubjectId, type SubjectMiddleware, SubjectResolver } from "#subject.ts";
13
+
14
+ type Policy<E> = { readonly kind: "self" } | { readonly kind: "account"; readonly permission: Permission; readonly deny: (id: string) => E };
15
+
16
+ function guard<E>(policy: Policy<E>): SubjectMiddleware<E, SessionPolicy> {
17
+ return (effect, { headers, rpc }) =>
18
+ Effect.gen(function* () {
19
+ const session = yield* resolveSession(headers, rpc._tag);
20
+ if (Option.isNone(session)) {
21
+ return yield* new Unauthorized({ message: "Authentication required" });
22
+ }
23
+ const user = session.value.user;
24
+ const transport = yield* transportHeaders(headers);
25
+ const id = policy.kind === "self" ? user.id : (transport["x-platform-subject"] ?? user.id);
26
+ if (policy.kind === "account" && id !== user.id && !hasPermission(user, { ...policy.permission, strength: "any" })) {
27
+ return yield* Effect.fail(policy.deny(id));
28
+ }
29
+ const lookup = recheckSession(headers, rpc._tag).pipe(
30
+ Effect.tap((next) =>
31
+ Option.isSome(next)
32
+ && policy.kind === "account"
33
+ && id !== next.value.user.id
34
+ && !hasPermission(next.value.user, { ...policy.permission, strength: "any" })
35
+ ? Effect.fail(policy.deny(id))
36
+ : Effect.void,
37
+ ),
38
+ );
39
+ return yield* effect.pipe(
40
+ revalidateStream(rpc, user.id, lookup),
41
+ Effect.provideService(Subject, { id: SubjectId(id) }),
42
+ Effect.provideService(Identity, { id: user.id }),
43
+ Effect.provideService(SessionUser, Schema.decodeUnknownSync(SessionUserSchema)(user)),
44
+ Effect.provideService(CurrentViewer, Option.some({ id: user.id })),
45
+ );
46
+ });
47
+ }
48
+
49
+ export function subjectResolverLayer() {
50
+ return Layer.effect(
51
+ SubjectResolver,
52
+ Effect.map(Effect.serviceOption(SessionPolicy), (sessions) => {
53
+ function resolved<E>(policy: Policy<E>): SubjectMiddleware<E> {
54
+ const middleware = guard(policy);
55
+ return (effect, request) =>
56
+ Option.isSome(sessions)
57
+ ? middleware(effect, request).pipe(Effect.provideService(SessionPolicy, sessions.value))
58
+ : Effect.fail(new Unauthorized({ message: "Authentication required" }));
59
+ }
60
+ return {
61
+ account: <E>(permission: Permission, deny: (id: string) => E) => resolved({ deny, kind: "account", permission }),
62
+ self: resolved({ kind: "self" }),
63
+ };
64
+ }),
65
+ );
66
+ }
package/src/subject.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { Brand, Context, Effect, Schema } from "effect";
2
+ import type { RpcMiddleware } from "effect/rpc";
3
+ import type { Permission } from "@shivaedev/access/permission.ts";
4
+ import type { TaggedRejection } from "@shivaedev/contract/rejection.ts";
5
+ import type { SubjectDeclaration } from "@shivaedev/contract/subject.ts";
6
+ import type { Identity, SessionUser } from "#identity.ts";
7
+ import { IdentityFailures } from "#middleware.ts";
8
+
9
+ export type SubjectId = string & Brand.Brand<"@shivaedev/identity/SubjectId">;
10
+ export const SubjectId = Brand.nominal<SubjectId>();
11
+ export class Subject extends Context.Service<Subject, { readonly id: SubjectId }>()("@shivaedev/identity/Subject") {}
12
+
13
+ export type SubjectMiddleware<E = never, R = never> = RpcMiddleware.RpcMiddleware<Subject | Identity | SessionUser, IdentityFailures | E, R>;
14
+
15
+ export class SubjectResolver extends Context.Service<
16
+ SubjectResolver,
17
+ {
18
+ readonly self: SubjectMiddleware;
19
+ readonly account: <E>(permission: Permission, deny: (id: string) => E) => SubjectMiddleware<E>;
20
+ }
21
+ >()("@shivaedev/identity/SubjectResolver") {}
22
+
23
+ export const selfSubject = {
24
+ error: IdentityFailures,
25
+ middleware: Effect.map(SubjectResolver, (resolver) => resolver.self),
26
+ } satisfies SubjectDeclaration;
27
+
28
+ export function accountSubject<TRefusal extends TaggedRejection>(options: {
29
+ readonly permission: Permission;
30
+ readonly refusal: TRefusal;
31
+ readonly deny: (id: string) => NoInfer<TRefusal["Type"]>;
32
+ }) {
33
+ return {
34
+ error: Schema.Union([IdentityFailures, options.refusal]),
35
+ middleware: Effect.map(SubjectResolver, (resolver) => resolver.account(options.permission, options.deny)),
36
+ } satisfies SubjectDeclaration;
37
+ }