@shivaedev/identity 0.38.1 → 0.38.3

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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.38.3 - 2026-11-21
4
+
5
+ ### Changed
6
+
7
+ - Update `@shivaedev/contract` from 0.56.0 to 0.57.0.
8
+
9
+ ## 0.38.2 - 2026-11-21
10
+
11
+ ### Changed
12
+
13
+ - Update `@shivaedev/contract` from 0.55.0 to 0.56.0.
14
+
3
15
  ## 0.38.1 - 2026-11-21
4
16
 
5
17
  ### Changed
package/README.md CHANGED
@@ -240,7 +240,7 @@ const bearerToken = Redacted.value(local.token);
240
240
  const machine = yield* local.machines.issue({ name: "reader agent", scope: "reader" });
241
241
  ```
242
242
 
243
- Pass `sessions` to `appHost` and hand `bearerToken` directly from the launching process to its own client. Use the session host with contracts declaring `Authenticated`, `AuthenticatedUser` or permission middleware. The existing `makeClient` option `bearerToken` sends HTTP authorization and the WebSocket's first authentication frame. Native HTTP callers send `Authorization: Bearer <token>`. Credentials are required even on loopback; the policy also requires a loopback Host and peer and the existing same-origin check. Authenticated handlers, query read policies and audit code receive the configured owner's id.
243
+ Pass `sessions` to `appHost` and hand `bearerToken` directly from the launching process to its own client. Use the session host with contracts declaring `Authenticated`, `AuthenticatedUser` or permission middleware. Pass it to `makeClient` as `bearerToken: Effect.succeed(bearerToken)`, which sends it as the WebSocket's first authentication frame. Native HTTP callers send `Authorization: Bearer <token>`. Credentials are required even on loopback; the policy also requires a loopback Host and peer and the existing same-origin check. Authenticated handlers, query read policies and audit code receive the configured owner's id.
244
244
 
245
245
  The owner credential lasts for this provider instance. Machine credentials persist in PostgreSQL as SHA-256 digests, and `issue` returns a redacted credential once. A machine acts on behalf of the owner, with `SessionUser.role` and `permissions` resolved solely from its scope through the application's `roleSet`. Use permission middleware for owner-only commands; an owner id alone does not distinguish machine rights. An undeclared scope cannot be issued. `machineTokens` from `server/machineTokens.ts` also exposes this store independently, taking `{ owner, roles }` and returning `issue`, `resolve` and `revoke`; resolved machine sessions include `{ machine: { id, name, scope }, user }`.
246
246
 
@@ -492,7 +492,7 @@ The seed only grants: removing an account from config does not restore its previ
492
492
 
493
493
  ### Administer signed-in sessions
494
494
 
495
- `Sessions` from `@shivaedev/identity/Sessions.ts` is a defined module, which is server code: register it as `module: Sessions`, or serve it through admin's sessions page with `moduleHandlers(Sessions)` from `@shivaedev/contract/moduleHandlers.ts`. Install `permissionLayer(SessionsPermission)` using `SessionsPermission` from `@shivaedev/identity/sessionPermissions.ts` and the mounted session policy. Supply the application's Effect `SqlClient`; the operations use the default Better Auth PostgreSQL user and session tables. Browser code imports the client contract under the same name from `@shivaedev/identity/generated/Sessions.ts`, and the `SignedInSession`, `SessionCursor` and `SessionListInput` schemas and the `SessionList` type from `@shivaedev/identity/signedInSessions.ts`.
495
+ `Sessions` from `@shivaedev/identity/Sessions.ts` is a defined module, which is server code: register it as `module: Sessions`, or serve it through admin's sessions page by registering `sessions: Sessions` with admin's `registerAdmin`. Install `permissionLayer(SessionsPermission)` using `SessionsPermission` from `@shivaedev/identity/sessionPermissions.ts` and the mounted session policy. Supply the application's Effect `SqlClient`; the operations use the default Better Auth PostgreSQL user and session tables. Browser code imports the client contract under the same name from `@shivaedev/identity/generated/Sessions.ts`, and the `SignedInSession`, `SessionCursor` and `SessionListInput` schemas and the `SessionList` type from `@shivaedev/identity/signedInSessions.ts`.
496
496
 
497
497
  Grant `ManageSessions` (`sessions.manage`) from `sessionPermissions.ts` to the roles that manage sessions. The starter grants it to admin and owner. Both operations use the same permission middleware and `Forbidden` refusal as the admin Users page. They require no Better Auth admin plugin.
498
498
 
@@ -521,7 +521,40 @@ const host = appHost({ group, handlers, routes: mounted.routes, sessions, native
521
521
 
522
522
  Always take the provider from the mount's `sessions`, or wrap a custom lookup in `admittedSessions`, even without a sign-in policy: both apply the mount's credential selection to the same request-local identity, profile and role middleware used by cookies. A same-origin request or a request without an Origin carrying the session cookie uses only that cookie, even if invalid or revoked; its bearer header cannot switch accounts or rescue it. Otherwise the signed bearer is resolved by Better Auth. Missing, unsigned, tampered, expired and revoked bearer sessions produce `Unauthorized` at protected RPCs.
523
523
 
524
- A native client signs in through `/api/auth/sign-in/email` with `credentials: "omit"` and its bundled Origin, reads the signed credential from the `set-auth-token` response header, and sends that exact value as `Authorization: Bearer <credential>` with `credentials: "omit"` on later auth and RPC requests. Persist it only in OS-backed secure storage, such as iOS Keychain or Android Keystore-backed storage; never use localStorage, sessionStorage or IndexedDB. Browser responses keep HttpOnly cookies and omit the plugin's token header and JSON token fields. Clients without a bundled Origin receive cookie responses.
524
+ A native client keeps its signed credential behind identity's credential port and hands its storage to one Layer. `SessionCredential` from `@shivaedev/identity/client/SessionCredential.ts` is shaped like `SessionMemory`: `read`, `write` and `clear` Effects that fail with `SessionCredentialUnavailable`. The application's Layer wraps the OS-backed secure storage of its shell's plugin, such as iOS Keychain or Android Keystore-backed storage, in its own `adapters/`; never use localStorage, sessionStorage or IndexedDB. For a Capacitor shell with a secure-storage plugin:
525
+
526
+ ```ts
527
+ import { SecureStorage } from "@aparajita/capacitor-secure-storage";
528
+ import { Effect, Layer } from "effect";
529
+ import { SessionCredential, SessionCredentialUnavailable } from "@shivaedev/identity/client/SessionCredential.ts";
530
+
531
+ const KEY = "session-credential";
532
+
533
+ function secure<A>(call: () => Promise<A>) {
534
+ return Effect.tryPromise({ catch: (cause) => new SessionCredentialUnavailable({ cause }), try: call });
535
+ }
536
+
537
+ export const secureCredential = Layer.succeed(SessionCredential, {
538
+ clear: secure(() => SecureStorage.remove(KEY)).pipe(Effect.asVoid),
539
+ read: secure(() => SecureStorage.get(KEY)).pipe(Effect.map((value) => (typeof value === "string" ? value : null))),
540
+ write: (value) => secure(() => SecureStorage.set(KEY, value)).pipe(Effect.asVoid),
541
+ });
542
+ ```
543
+
544
+ Pass that Layer to the Better Auth client as a plugin, and to `makeClient` through `storedCredential`:
545
+
546
+ ```ts
547
+ import { createAuthClient } from "better-auth/client";
548
+ import { Effect } from "effect";
549
+ import { makeClient } from "@shivaedev/contract/makeClient.ts";
550
+ import { sessionCredentialPlugin } from "@shivaedev/identity/client/adapters/sessionCredentialPlugin.ts";
551
+ import { storedCredential } from "@shivaedev/identity/client/SessionCredential.ts";
552
+
553
+ export const authClient = createAuthClient({ baseURL: publicOrigin, plugins: [sessionCredentialPlugin(secureCredential)] });
554
+ const client = makeClient(contracts, { bearerToken: Effect.provide(storedCredential, secureCredential), registry, url: `${publicOrigin}/rpc` });
555
+ ```
556
+
557
+ The plugin sends every auth request with `credentials: "omit"` and the stored credential as `Authorization: Bearer <credential>`, stores the `set-auth-token` header of a sign-in answer, and clears the credential when sign-out succeeds or a `get-session` check answers signed out. An answer changes the stored credential only when its request carried the credential stored at the moment it answers, so a session check sent before sign-in that answers signed out after it leaves the new credential in place. The application never reads or writes the token itself. Browser responses keep HttpOnly cookies and omit the plugin's token header and JSON token fields. Clients without a bundled Origin receive cookie responses.
525
558
 
526
559
  Native sign-out revokes the stored session. Signing in again while sending the current bearer replaces it and revokes the old session after successful sign-in. Streams keep their original request headers, so the old session ends with `Unauthorized` on the next revalidation; it never adopts the replacement. Keep cookie caching disabled for database-backed revocation and choose `streamRevalidationInterval` for the required delivery window.
527
560
 
@@ -529,7 +562,7 @@ Native sign-out revokes the stored session. Signing in again while sending the c
529
562
 
530
563
  The host answers native preflights with POST for RPC, GET and POST for auth, and only `Authorization` and `Content-Type` headers. Native responses echo the allowed origin exactly with `Vary: Origin`; auth responses expose `set-auth-token`. Native responses never enable CORS credentials. It strips cookies from admitted native requests before auth or RPC session resolution, so only the signed bearer session can authenticate them. This prevents native access from opening a cookie CSRF path, even if a caller sends a cookie. Resource authorization remains app-owned.
531
564
 
532
- A WebView's live queries subscribe over the shared WebSocket client: pass the signed credential as `bearerToken` to contract's `makeClient`, which sends it as the socket's first frame, as the [contract guide](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md#build-a-shared-websocket-client) describes. The host refuses a query's change stream over HTTP with `WebSocketRequired`. Over HTTP, use the WebView's own fetch with `credentials: "omit"` for commands, one-off reads and explicit NDJSON streams, and abort a stream's request to release server work; a buffering native HTTP bridge cannot deliver a stream incrementally. The host still validates trusted proxy peers and forwarded authority, enforces NDJSON and body limits, uses only transport credentials, redacts diagnostics and authorizes sessions. Native HTTP callers without an Origin can exercise bearer RPC with an origin policy that explicitly permits missing Origins.
565
+ A WebView's live queries subscribe over the shared WebSocket client. `storedCredential` reads the port each time the socket connects: contract's `makeClient` sends the credential stored then as the socket's first frame, as the [contract guide](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md#build-a-shared-websocket-client) describes, and connects without one when none is stored. A new client after each sign-in, sign-out or second sign-in, as React's `SessionBoundary` makes one per session, therefore carries the current credential. The host refuses a query's change stream over HTTP with `WebSocketRequired`. Over HTTP, use the WebView's own fetch with `credentials: "omit"` for commands, one-off reads and explicit NDJSON streams, and abort a stream's request to release server work; a buffering native HTTP bridge cannot deliver a stream incrementally. The host still validates trusted proxy peers and forwarded authority, enforces NDJSON and body limits, uses only transport credentials, redacts diagnostics and authorizes sessions. Native HTTP callers without an Origin can exercise bearer RPC with an origin policy that explicitly permits missing Origins.
533
566
 
534
567
  ### Decide who may sign in
535
568
 
@@ -0,0 +1,18 @@
1
+ import { Context, Effect } from "effect";
2
+ declare const SessionCredentialUnavailable_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
3
+ readonly _tag: "SessionCredentialUnavailable";
4
+ } & Readonly<A>;
5
+ export declare class SessionCredentialUnavailable extends SessionCredentialUnavailable_base<{
6
+ readonly cause: unknown;
7
+ }> {
8
+ }
9
+ declare const SessionCredential_base: Context.ServiceClass<SessionCredential, "@shivaedev/identity/SessionCredential", {
10
+ readonly clear: Effect.Effect<void, SessionCredentialUnavailable>;
11
+ readonly read: Effect.Effect<string | null, SessionCredentialUnavailable>;
12
+ readonly write: (value: string) => Effect.Effect<void, SessionCredentialUnavailable>;
13
+ }>;
14
+ export declare class SessionCredential extends SessionCredential_base {
15
+ }
16
+ export declare const storedCredential: Effect.Effect<string | null, never, SessionCredential>;
17
+ export {};
18
+ //# sourceMappingURL=SessionCredential.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SessionCredential.d.ts","sourceRoot":"","sources":["../../src/client/SessionCredential.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAQ,MAAM,EAAE,MAAM,QAAQ,CAAC;;;;AAE/C,qBAAa,4BAA6B,SAAQ,kCAAiD;IAAE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;CAAG;;oBAKhH,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,4BAA4B,CAAC;mBAClD,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,EAAE,4BAA4B,CAAC;oBACzD,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,4BAA4B,CAAC;;AALtF,qBAAa,iBAAkB,SAAQ,sBAOK;CAAG;AAG/C,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,iBAAiB,CAGlF,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { Context, Data, Effect } from "effect";
2
+ export class SessionCredentialUnavailable extends Data.TaggedError("SessionCredentialUnavailable") {
3
+ }
4
+ export class SessionCredential extends Context.Service()("@shivaedev/identity/SessionCredential") {
5
+ }
6
+ // A socket connect has no caller to report to, so storage that cannot answer connects without a credential.
7
+ export const storedCredential = Effect.gen(function* () {
8
+ const credential = yield* SessionCredential;
9
+ return yield* Effect.orElseSucceed(credential.read, () => null);
10
+ });
11
+ //# sourceMappingURL=SessionCredential.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SessionCredential.js","sourceRoot":"","sources":["../../src/client/SessionCredential.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE/C,MAAM,OAAO,4BAA6B,SAAQ,IAAI,CAAC,WAAW,CAAC,8BAA8B,CAA8B;CAAG;AAElI,MAAM,OAAO,iBAAkB,SAAQ,OAAO,CAAC,OAAO,EAOnD,CAAC,uCAAuC,CAAC;CAAG;AAE/C,4GAA4G;AAC5G,MAAM,CAAC,MAAM,gBAAgB,GAA2D,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;IAC3G,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,iBAAiB,CAAC;IAC5C,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;AACjE,CAAC,CAAC,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { type Layer } from "effect";
2
+ import { SessionCredential } from "#client/SessionCredential.ts";
3
+ interface CredentialRequest {
4
+ credentials?: "include" | "omit" | "same-origin" | undefined;
5
+ readonly headers: Headers;
6
+ readonly url: URL | string;
7
+ }
8
+ interface CredentialAnswer {
9
+ readonly data: unknown;
10
+ readonly request: CredentialRequest;
11
+ readonly response: Response;
12
+ }
13
+ interface CredentialFetchPlugin {
14
+ readonly hooks: {
15
+ readonly onRequest: (context: CredentialRequest) => Promise<void>;
16
+ readonly onSuccess: (context: CredentialAnswer) => Promise<void>;
17
+ };
18
+ readonly id: string;
19
+ readonly name: string;
20
+ }
21
+ export interface SessionCredentialPlugin {
22
+ readonly fetchPlugins: CredentialFetchPlugin[];
23
+ readonly id: "session-credential";
24
+ }
25
+ export declare function sessionCredentialPlugin(credential: Layer.Layer<SessionCredential>): SessionCredentialPlugin;
26
+ export {};
27
+ //# sourceMappingURL=sessionCredentialPlugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionCredentialPlugin.d.ts","sourceRoot":"","sources":["../../../src/client/adapters/sessionCredentialPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAGjE,UAAU,iBAAiB;IAC1B,WAAW,CAAC,EAAE,SAAS,GAAG,MAAM,GAAG,aAAa,GAAG,SAAS,CAAC;IAC7D,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAAC;CAC3B;AAED,UAAU,gBAAgB;IACzB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IACpC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;CAC5B;AAED,UAAU,qBAAqB;IAC9B,QAAQ,CAAC,KAAK,EAAE;QACf,QAAQ,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;QAClE,QAAQ,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACjE,CAAC;IACF,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,YAAY,EAAE,qBAAqB,EAAE,CAAC;IAC/C,QAAQ,CAAC,EAAE,EAAE,oBAAoB,CAAC;CAClC;AAgCD,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,KAAK,CAAC,iBAAiB,CAAC,GAAG,uBAAuB,CAc3G"}
@@ -0,0 +1,45 @@
1
+ import { Effect } from "effect";
2
+ import { SessionCredential } from "#client/SessionCredential.ts";
3
+ function bearerOf(credential) {
4
+ return credential === null ? null : `Bearer ${credential}`;
5
+ }
6
+ const send = Effect.fnUntraced(function* (request) {
7
+ const credential = yield* SessionCredential;
8
+ const authorization = bearerOf(yield* credential.read);
9
+ if (authorization !== null) {
10
+ request.headers.set("authorization", authorization);
11
+ }
12
+ request.credentials = "omit";
13
+ });
14
+ // An answer changes the stored credential only when its request carried the one stored now, so a session check sent
15
+ // before sign-in that answers signed out after it cannot wipe the credential sign-in saved.
16
+ const settle = Effect.fnUntraced(function* ({ data, request, response }) {
17
+ const credential = yield* SessionCredential;
18
+ if (bearerOf(yield* credential.read) !== request.headers.get("authorization")) {
19
+ return;
20
+ }
21
+ const path = new URL(request.url, "http://localhost").pathname;
22
+ const issued = response.headers.get("set-auth-token");
23
+ if (path.endsWith("/sign-out") || (path.endsWith("/get-session") && data === null)) {
24
+ return yield* credential.clear;
25
+ }
26
+ if (issued !== null) {
27
+ yield* credential.write(issued);
28
+ }
29
+ });
30
+ export function sessionCredentialPlugin(credential) {
31
+ return {
32
+ fetchPlugins: [
33
+ {
34
+ hooks: {
35
+ onRequest: (request) => Effect.runPromise(Effect.provide(send(request), credential)),
36
+ onSuccess: (answer) => Effect.runPromise(Effect.provide(settle(answer), credential)),
37
+ },
38
+ id: "session-credential",
39
+ name: "session credential",
40
+ },
41
+ ],
42
+ id: "session-credential",
43
+ };
44
+ }
45
+ //# sourceMappingURL=sessionCredentialPlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionCredentialPlugin.js","sourceRoot":"","sources":["../../../src/client/adapters/sessionCredentialPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAc,MAAM,QAAQ,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AA6BjE,SAAS,QAAQ,CAAC,UAAyB;IAC1C,OAAO,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,UAAU,EAAE,CAAC;AAC5D,CAAC;AAED,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,OAA0B;IACnE,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,iBAAiB,CAAC;IAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,aAAa,KAAK,IAAI,EAAE,CAAC;QAC5B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,aAAa,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,CAAC,WAAW,GAAG,MAAM,CAAC;AAC9B,CAAC,CAAC,CAAC;AAEH,oHAAoH;AACpH,4FAA4F;AAC5F,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAoB;IACxF,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,iBAAiB,CAAC;IAC5C,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;QAC/E,OAAO;IACR,CAAC;IACD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,EAAE,kBAAkB,CAAC,CAAC,QAAQ,CAAC;IAC/D,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IACtD,IAAI,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QACpF,OAAO,KAAK,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC;IAChC,CAAC;IACD,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACrB,KAAK,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;AACF,CAAC,CAAC,CAAC;AAEH,MAAM,UAAU,uBAAuB,CAAC,UAA0C;IACjF,OAAO;QACN,YAAY,EAAE;YACb;gBACC,KAAK,EAAE;oBACN,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,UAAU,CAAC,CAAC;oBACpF,SAAS,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC;iBACpF;gBACD,EAAE,EAAE,oBAAoB;gBACxB,IAAI,EAAE,oBAAoB;aAC1B;SACD;QACD,EAAE,EAAE,oBAAoB;KACxB,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/identity",
3
- "version": "0.38.1",
3
+ "version": "0.38.3",
4
4
  "description": "Request identity, sessions, transport trust and permission enforcement for Effect RPC servers",
5
5
  "keywords": [
6
6
  "effect"
@@ -48,32 +48,32 @@
48
48
  "dependencies": {
49
49
  "@shivaedev/access": "0.7.0",
50
50
  "@shivaedev/changes": "0.14.1",
51
- "@shivaedev/contract": "0.55.0",
51
+ "@shivaedev/contract": "0.57.0",
52
52
  "@shivaedev/errors": "0.14.1",
53
53
  "@shivaedev/rate-limit": "0.8.0",
54
54
  "@shivaedev/service": "0.9.2",
55
55
  "@shivaedev/sql": "0.54.0"
56
56
  },
57
57
  "devDependencies": {
58
- "@better-auth/oauth-provider": "1.7.22",
58
+ "@better-auth/oauth-provider": "1.7.23",
59
59
  "@effect/platform-node": "4.1.4",
60
60
  "@effect/sql-pg": "4.1.4",
61
- "@shivaedev/admin": "0.28.2",
62
- "@shivaedev/build": "0.5.1",
63
- "@shivaedev/quality": "0.83.0",
64
- "@shivaedev/server": "0.41.0",
65
- "@shivaedev/test-kits": "0.16.1",
61
+ "@shivaedev/admin": "0.29.0",
62
+ "@shivaedev/build": "0.6.0",
63
+ "@shivaedev/quality": "0.83.2",
64
+ "@shivaedev/server": "0.41.2",
65
+ "@shivaedev/test-kits": "0.16.3",
66
66
  "@shivaedev/test-sql": "0.26.0",
67
- "@shivaedev/test-story": "0.52.1",
67
+ "@shivaedev/test-story": "0.52.3",
68
68
  "@types/node": "24.19.2",
69
- "better-auth": "1.7.22",
69
+ "better-auth": "1.7.23",
70
70
  "effect": "4.1.4",
71
71
  "typescript": "7.0.2",
72
72
  "vitest": "5.1.0"
73
73
  },
74
74
  "peerDependencies": {
75
- "@better-auth/oauth-provider": "1.7.22",
76
- "better-auth": "1.7.22",
75
+ "@better-auth/oauth-provider": "1.7.23",
76
+ "better-auth": "1.7.23",
77
77
  "effect": "4.1.4"
78
78
  },
79
79
  "peerDependenciesMeta": {
@@ -0,0 +1,18 @@
1
+ import { Context, Data, Effect } from "effect";
2
+
3
+ export class SessionCredentialUnavailable extends Data.TaggedError("SessionCredentialUnavailable")<{ readonly cause: unknown }> {}
4
+
5
+ export class SessionCredential extends Context.Service<
6
+ SessionCredential,
7
+ {
8
+ readonly clear: Effect.Effect<void, SessionCredentialUnavailable>;
9
+ readonly read: Effect.Effect<string | null, SessionCredentialUnavailable>;
10
+ readonly write: (value: string) => Effect.Effect<void, SessionCredentialUnavailable>;
11
+ }
12
+ >()("@shivaedev/identity/SessionCredential") {}
13
+
14
+ // A socket connect has no caller to report to, so storage that cannot answer connects without a credential.
15
+ export const storedCredential: Effect.Effect<string | null, never, SessionCredential> = Effect.gen(function* () {
16
+ const credential = yield* SessionCredential;
17
+ return yield* Effect.orElseSucceed(credential.read, () => null);
18
+ });
@@ -0,0 +1,75 @@
1
+ import { Effect, type Layer } from "effect";
2
+ import { SessionCredential } from "#client/SessionCredential.ts";
3
+
4
+ // Structural copies of the Better Auth client plugin shapes: the client core must not reach the optional better-auth peer.
5
+ interface CredentialRequest {
6
+ credentials?: "include" | "omit" | "same-origin" | undefined;
7
+ readonly headers: Headers;
8
+ readonly url: URL | string;
9
+ }
10
+
11
+ interface CredentialAnswer {
12
+ readonly data: unknown;
13
+ readonly request: CredentialRequest;
14
+ readonly response: Response;
15
+ }
16
+
17
+ interface CredentialFetchPlugin {
18
+ readonly hooks: {
19
+ readonly onRequest: (context: CredentialRequest) => Promise<void>;
20
+ readonly onSuccess: (context: CredentialAnswer) => Promise<void>;
21
+ };
22
+ readonly id: string;
23
+ readonly name: string;
24
+ }
25
+
26
+ export interface SessionCredentialPlugin {
27
+ readonly fetchPlugins: CredentialFetchPlugin[];
28
+ readonly id: "session-credential";
29
+ }
30
+
31
+ function bearerOf(credential: string | null) {
32
+ return credential === null ? null : `Bearer ${credential}`;
33
+ }
34
+
35
+ const send = Effect.fnUntraced(function* (request: CredentialRequest) {
36
+ const credential = yield* SessionCredential;
37
+ const authorization = bearerOf(yield* credential.read);
38
+ if (authorization !== null) {
39
+ request.headers.set("authorization", authorization);
40
+ }
41
+ request.credentials = "omit";
42
+ });
43
+
44
+ // An answer changes the stored credential only when its request carried the one stored now, so a session check sent
45
+ // before sign-in that answers signed out after it cannot wipe the credential sign-in saved.
46
+ const settle = Effect.fnUntraced(function* ({ data, request, response }: CredentialAnswer) {
47
+ const credential = yield* SessionCredential;
48
+ if (bearerOf(yield* credential.read) !== request.headers.get("authorization")) {
49
+ return;
50
+ }
51
+ const path = new URL(request.url, "http://localhost").pathname;
52
+ const issued = response.headers.get("set-auth-token");
53
+ if (path.endsWith("/sign-out") || (path.endsWith("/get-session") && data === null)) {
54
+ return yield* credential.clear;
55
+ }
56
+ if (issued !== null) {
57
+ yield* credential.write(issued);
58
+ }
59
+ });
60
+
61
+ export function sessionCredentialPlugin(credential: Layer.Layer<SessionCredential>): SessionCredentialPlugin {
62
+ return {
63
+ fetchPlugins: [
64
+ {
65
+ hooks: {
66
+ onRequest: (request) => Effect.runPromise(Effect.provide(send(request), credential)),
67
+ onSuccess: (answer) => Effect.runPromise(Effect.provide(settle(answer), credential)),
68
+ },
69
+ id: "session-credential",
70
+ name: "session credential",
71
+ },
72
+ ],
73
+ id: "session-credential",
74
+ };
75
+ }