@shivaedev/identity 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.22.0 - 2026-11-03
4
+
5
+ ### Added
6
+
7
+ - Add `localOwner` for loopback applications to hand a process-local owner credential to their own client and resolve the owner through the existing session, viewer and permission middleware.
8
+ - Add PostgreSQL-backed scoped machine credentials with `machineTokenMigration` and `machineTokens`. Application access roles grant each scope's permissions; live lookups refuse revoked credentials on the next request and during open live-query revalidation. HTTP bearer and WebSocket first-frame authentication use the existing transports.
9
+
10
+ ## 0.21.0 - 2026-11-03
11
+
12
+ ### Breaking
13
+
14
+ - Move `signedInUser`, `signInAgain`, `passwordUser` and `storedProviderAccounts` from `@shivaedev/identity/server/better-auth/testing.ts` to `@shivaedev/test-kits/identity/adapters/betterAuth.ts`. Move `testUserEmail` and `signedSessionToken` from `@shivaedev/identity/server/better-auth/adapters/testingCredentials.ts` to `@shivaedev/test-kits/identity/adapters/testingCredentials.ts`. Add test-kits as a development dependency.
15
+
3
16
  ## 0.20.0 - 2026-11-03
4
17
 
5
18
  ### Added
package/README.md CHANGED
@@ -90,6 +90,36 @@ To also accept the transport guard's same-origin requests, pass `sameOrigin: { t
90
90
 
91
91
  The application's `auth` owns its storage and session configuration. A null lookup becomes a missing session. When the lookup returns Better Auth’s `session.expiresAt` as a `Date`, identity also rejects the session at or after that instant using Effect’s current clock. A thrown or rejected lookup is logged in redacted form and fails with the generic `AuthUnavailable` message. It remains a failure even on an RPC with optional authentication.
92
92
 
93
+ ### Local owners and machine callers
94
+
95
+ `localOwner` supplies a single configured person for a loopback application. Apply `machineTokenMigration` from `@shivaedev/identity/server/adapters/machineTokenMigration.ts` through the application's numbered PostgreSQL migrations, then create the provider with the application's `SqlClient` and Effect `Crypto` service:
96
+
97
+ ```ts
98
+ import { Layer, Redacted } from "effect";
99
+ import { permission } from "@shivaedev/access/permission.ts";
100
+ import { role } from "@shivaedev/access/role.ts";
101
+ import { roleSet } from "@shivaedev/access/roleSet.ts";
102
+ import { localOwner } from "@shivaedev/identity/server/localOwner.ts";
103
+ import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
104
+
105
+ const Manage = permission("app.manage");
106
+ const Read = permission("app.read");
107
+ const roles = roleSet(role("owner", [Read, Manage]), role("reader", [Read]));
108
+ const local = yield* localOwner({
109
+ owner: { id: "owner", name: "Owner", email: "owner@example.test", role: "owner" },
110
+ roles,
111
+ });
112
+ const sessions = Layer.succeed(SessionPolicy, local.sessions);
113
+ const bearerToken = Redacted.value(local.token);
114
+ const machine = yield* local.machines.issue({ name: "reader agent", scope: "reader" });
115
+ ```
116
+
117
+ 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.
118
+
119
+ 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 }`.
120
+
121
+ Call `local.machines.revoke(machine.id)` from authorized application code. Every machine lookup reads PostgreSQL, so the next request is refused after revocation. Existing live-query revalidation checks the same provider and closes a revoked bearer connection. `streamRevalidationInterval` configures that interval on `localOwner`, with the usual 30-second default. The token store does not authorize its administrative methods; applications decide who may issue and revoke credentials.
122
+
93
123
  ### Mount Better Auth
94
124
 
95
125
  `betterAuthMount(options)` returns the Better Auth instance and a native route Layer for `/api/auth/*`. It accepts Better Auth options, including application plugins and session policy. Its scoped acquisition waits for the auth context and the provider’s schema check before returning; a provider initialization or schema-check failure logs the redacted cause and fails with `AuthUnavailable`. Building a Layer from this acquisition therefore completes only when authentication is ready. Merge `routes` into the HTTP host and use `auth.api.getSession` with `betterAuthSessions` for the application's RPC session provider.
@@ -747,7 +777,7 @@ Use `authTestDatabase` from `@shivaedev/identity/server/better-auth/testDatabase
747
777
 
748
778
  ```ts
749
779
  import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
750
- import { signedInUser } from "@shivaedev/identity/server/better-auth/testing.ts";
780
+ import { signedInUser } from "@shivaedev/test-kits/identity/adapters/betterAuth.ts";
751
781
 
752
782
  const mounted = yield* betterAuthMount(options, {
753
783
  defaultRole: "member",
@@ -768,7 +798,7 @@ The Effect returns Better Auth's login result: the user, session, signed request
768
798
 
769
799
  `passwordUser(auth, { email, passwordHash, ...fields })` saves a user and a credential account with a precomputed hash, without hashing or minting a session. Generate the hash once with the application's configured password hasher and keep it as a test fixture alongside its matching password. Then sign in through `/api/auth/sign-in/email` with that password: Better Auth still runs real password verification. A wrong password is refused. Identity's native-session stories use this precondition. The auth instance needs no testing plugin. The existing `passwordUser(auth, { email, password, ...fields })` form hashes with the configured hasher; choose either `passwordHash` or `password`, never both.
770
800
 
771
- Call `yield* signInAgain(auth, userId)` from `server/better-auth/testing.ts` to mint a fresh session for an existing user after a long story clock jump. It returns the same login shape as `signedInUser` and sets expiry from the caller’s Effect Clock and the configured session lifetime. Replace the visitor’s request headers or seed the returned browser cookies.
801
+ Call `yield* signInAgain(auth, userId)` from `@shivaedev/test-kits/identity/adapters/betterAuth.ts` to mint a fresh session for an existing user after a long story clock jump. It returns the same login shape as `signedInUser` and sets expiry from the caller’s Effect Clock and the configured session lifetime. Replace the visitor’s request headers or seed the returned browser cookies.
772
802
 
773
803
  Use `storedProviderAccounts(auth, userId)` to observe credential storage through Better Auth's internal adapter. It returns account and provider IDs with `hasAccessToken`, `hasRefreshToken`, `hasIdToken` and `hasPassword` booleans. It never returns token values, passwords or password hashes. A DOM story kit that exposes its test auth instance and a session readout can use both helpers:
774
804
 
@@ -776,7 +806,7 @@ Use `storedProviderAccounts(auth, userId)` to observe credential storage through
776
806
  import { Effect } from "effect";
777
807
  import { expect } from "vitest";
778
808
  import { seedCookies } from "@shivaedev/test-story/server/adapters/seedCookies.ts";
779
- import { signedInUser, storedProviderAccounts } from "@shivaedev/identity/server/better-auth/testing.ts";
809
+ import { signedInUser, storedProviderAccounts } from "@shivaedev/test-kits/identity/adapters/betterAuth.ts";
780
810
 
781
811
  const member = app.trait("account", "a member starts signed in with GitHub", function* ({ auth }) {
782
812
  const { cookies } = yield* signedInUser(auth, {
@@ -868,7 +898,6 @@ Import the module that defines the name; there is no package-root entry. Paths b
868
898
  | `server/better-auth/sweepExpiredSessions.ts` | `sweepExpiredSessions`: delete expired sessions through the application's SQL client and return the number removed. |
869
899
  | `server/better-auth/userReference.ts` | `userReference`: the default auth user table and id column for application foreign keys. |
870
900
  | `server/better-auth/testDatabase.ts` | `authTestDatabase`: test-only identity/session readouts and faults for the default PostgreSQL auth schema. |
871
- | `server/better-auth/testing.ts` | `signedInUser(auth, fields)`, `passwordUser(auth, fields)`, `storedProviderAccounts(auth, userId)`: test-only users, minted sessions and credential storage observations. |
872
901
 
873
902
  ### Install, setup and limits
874
903
 
@@ -0,0 +1,4 @@
1
+ import { Effect } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ export declare const machineTokenMigration: Effect.Effect<void, import("effect/sql/SqlError").SqlError, SqlClient.SqlClient>;
4
+ //# sourceMappingURL=machineTokenMigration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machineTokenMigration.d.ts","sourceRoot":"","sources":["../../../src/server/adapters/machineTokenMigration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,eAAO,MAAM,qBAAqB,kFAQhC,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { Effect } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ export const machineTokenMigration = Effect.gen(function* () {
4
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
5
+ yield* sql `create table identity_machine_tokens (
6
+ id text primary key,
7
+ name text not null,
8
+ "ownerId" text not null,
9
+ scope text not null
10
+ )`;
11
+ });
12
+ //# sourceMappingURL=machineTokenMigration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machineTokenMigration.js","sourceRoot":"","sources":["../../../src/server/adapters/machineTokenMigration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,MAAM,CAAC,MAAM,qBAAqB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;IACxD,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,iBAAiB,EAAE,CAAC;IAC7D,KAAK,CAAC,CAAC,GAAG,CAAA;;;;;GAKR,CAAC;AACJ,CAAC,CAAC,CAAC"}
@@ -0,0 +1,64 @@
1
+ import { Crypto, type Duration, Effect, Option, Redacted } from "effect";
2
+ import type { RoleSet } from "@shivaedev/access/roleSet.ts";
3
+ import type { SessionUserValue } from "#identity.ts";
4
+ export declare const localOwner: (options: {
5
+ readonly owner: Pick<SessionUserValue, "id" | "name" | "email"> & {
6
+ readonly role: string;
7
+ };
8
+ readonly roles: RoleSet;
9
+ readonly streamRevalidationInterval?: Duration.Input;
10
+ }) => Effect.Effect<{
11
+ machines: {
12
+ issue: (input: {
13
+ readonly name: string;
14
+ readonly scope: string;
15
+ }) => Effect.Effect<{
16
+ name: string;
17
+ scope: string;
18
+ id: string;
19
+ token: Redacted.Redacted<string>;
20
+ }, import("effect/PlatformError").PlatformError | import("effect/Schema").SchemaError | import("effect/sql/SqlError").SqlError, never>;
21
+ resolve: (token: string) => Effect.Effect<Option.None<{
22
+ machine: {
23
+ id: string;
24
+ name: string;
25
+ scope: string;
26
+ };
27
+ user: {
28
+ email: string;
29
+ id: string;
30
+ name: string;
31
+ permissions: readonly {
32
+ readonly name: string;
33
+ readonly strength: "any" | "own";
34
+ }[];
35
+ role: string;
36
+ };
37
+ }> | Option.Some<{
38
+ machine: {
39
+ id: string;
40
+ name: string;
41
+ scope: string;
42
+ };
43
+ user: {
44
+ email: string;
45
+ id: string;
46
+ name: string;
47
+ permissions: readonly {
48
+ readonly name: string;
49
+ readonly strength: "any" | "own";
50
+ }[];
51
+ role: string;
52
+ };
53
+ }>, import("@shivaedev/errors/taxonomy.ts").AuthUnavailable, never>;
54
+ revoke: (id: string) => Effect.Effect<void, import("effect/Schema").SchemaError | import("effect/sql/SqlError").SqlError, never>;
55
+ };
56
+ sessions: {
57
+ readonly origin: import("./origin.ts").OriginPolicy;
58
+ readonly provider: import("./session.ts").SessionProvider<import("./session.ts").SessionShape>;
59
+ readonly roles?: RoleSet;
60
+ readonly streamRevalidationInterval?: Duration.Input | undefined;
61
+ };
62
+ token: Redacted.Redacted<string>;
63
+ }, import("@shivaedev/sql/repositoryCollection.ts").BucketRegistrationError | import("effect/PlatformError").PlatformError | import("effect/Schema").SchemaError, Crypto.Crypto | import("effect/sql/SqlClient").SqlClient>;
64
+ //# sourceMappingURL=localOwner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localOwner.d.ts","sourceRoot":"","sources":["../../src/server/localOwner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEzE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAKrD,eAAO,MAAM,UAAU;oBACN,IAAI,CAAC,gBAAgB,EAAE,IAAI,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE;oBAC3E,OAAO;0CACe,QAAQ,CAAC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2NAsBnD,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { Crypto, Effect, Option, Redacted } from "effect";
2
+ import * as Hex from "effect/encoding/Hex";
3
+ import { localTransport } from "#server/adapters/local.ts";
4
+ import { machineTokens } from "./machineTokens.js";
5
+ export const localOwner = Effect.fn("Identity.localOwner")(function* (options) {
6
+ const { owner, roles } = options;
7
+ const access = yield* roles.resolve(owner.role);
8
+ const crypto = yield* Crypto.Crypto;
9
+ const token = Redacted.make(Hex.encode(yield* crypto.randomBytes(32)));
10
+ const machines = yield* machineTokens({ owner, roles });
11
+ const allowed = localTransport();
12
+ const sessions = {
13
+ origin: (request) => allowed({ headers: request.headers, remoteAddress: request.remoteAddress ?? Option.none() }),
14
+ provider: {
15
+ get: (headers) => {
16
+ const bearer = /^Bearer (?<token>\S+)$/iu.exec(headers.authorization ?? "")?.groups?.token;
17
+ if (bearer === undefined) {
18
+ return Effect.succeed(Option.none());
19
+ }
20
+ return bearer === Redacted.value(token) ? Effect.succeed(Option.some({ user: { ...owner, ...access } })) : machines.resolve(bearer);
21
+ },
22
+ },
23
+ streamRevalidationInterval: options.streamRevalidationInterval,
24
+ };
25
+ return { machines, sessions, token };
26
+ });
27
+ //# sourceMappingURL=localOwner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localOwner.js","sourceRoot":"","sources":["../../src/server/localOwner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,EAAE,MAAM,EAA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AAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;gBACtC,CAAC;gBACD,OAAO,MAAM,KAAK,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,GAAG,KAAK,EAAE,GAAG,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YACrI,CAAC;SACD;QACD,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;KAC9D,CAAC;IACF,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AACtC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,52 @@
1
+ import { Crypto, Effect, Option, Redacted, Schema } from "effect";
2
+ import type { RoleSet } from "@shivaedev/access/roleSet.ts";
3
+ import type { SessionUserValue } from "#identity.ts";
4
+ export declare const machineTokens: (options: {
5
+ readonly owner: Pick<SessionUserValue, "id" | "name" | "email">;
6
+ readonly roles: RoleSet;
7
+ }) => Effect.Effect<{
8
+ issue: (input: {
9
+ readonly name: string;
10
+ readonly scope: string;
11
+ }) => Effect.Effect<{
12
+ name: string;
13
+ scope: string;
14
+ id: string;
15
+ token: Redacted.Redacted<string>;
16
+ }, import("effect/PlatformError").PlatformError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, never>;
17
+ resolve: (token: string) => Effect.Effect<Option.None<{
18
+ machine: {
19
+ id: string;
20
+ name: string;
21
+ scope: string;
22
+ };
23
+ user: {
24
+ email: string;
25
+ id: string;
26
+ name: string;
27
+ permissions: readonly {
28
+ readonly name: string;
29
+ readonly strength: "any" | "own";
30
+ }[];
31
+ role: string;
32
+ };
33
+ }> | Option.Some<{
34
+ machine: {
35
+ id: string;
36
+ name: string;
37
+ scope: string;
38
+ };
39
+ user: {
40
+ email: string;
41
+ id: string;
42
+ name: string;
43
+ permissions: readonly {
44
+ readonly name: string;
45
+ readonly strength: "any" | "own";
46
+ }[];
47
+ role: string;
48
+ };
49
+ }>, import("@shivaedev/errors/taxonomy.ts").AuthUnavailable, never>;
50
+ revoke: (id: string) => Effect.Effect<void, Schema.SchemaError | import("effect/sql/SqlError").SqlError, never>;
51
+ }, import("@shivaedev/sql/repositoryCollection.ts").BucketRegistrationError, Crypto.Crypto | import("effect/sql/SqlClient").SqlClient>;
52
+ //# sourceMappingURL=machineTokens.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machineTokens.d.ts","sourceRoot":"","sources":["../../src/server/machineTokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGlE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAUrD,eAAO,MAAM,aAAa;oBACT,IAAI,CAAC,gBAAgB,EAAE,IAAI,GAAG,MAAM,GAAG,OAAO,CAAC;oBAC/C,OAAO;;;uBAYqD,MAAM;wBAAkB,MAAM;;cAA9B,MAAM;eAAkB,MAAM;;;;;;YAmB5F,EAAE;YAAmB,IAAI;YAAqB,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sIAMhE,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { Crypto, Effect, Option, Redacted, Schema } from "effect";
2
+ import * as Hex from "effect/encoding/Hex";
3
+ import { Model } from "effect/schema";
4
+ import { makeRepository } from "@shivaedev/sql/repository.ts";
5
+ import { providerFailure } from "./providerFailure.js";
6
+ class MachineToken extends Model.Class("IdentityMachineToken")({
7
+ id: Schema.String,
8
+ name: Schema.String,
9
+ ownerId: Schema.String,
10
+ scope: Schema.String,
11
+ }) {
12
+ }
13
+ export const machineTokens = Effect.fn("Identity.machineTokens")(function* (options) {
14
+ const crypto = yield* Crypto.Crypto;
15
+ const repository = yield* makeRepository(MachineToken, {
16
+ idColumn: "id",
17
+ spanPrefix: "MachineTokens",
18
+ tableName: "identity_machine_tokens",
19
+ });
20
+ function digest(token) {
21
+ return crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(Effect.map(Hex.encode));
22
+ }
23
+ return {
24
+ issue: Effect.fn("MachineTokens.issue")(function* (input) {
25
+ yield* options.roles.resolve(input.scope);
26
+ const token = Hex.encode(yield* crypto.randomBytes(32));
27
+ const id = yield* digest(token);
28
+ yield* repository.insertVoid({ id, name: input.name, ownerId: options.owner.id, scope: input.scope });
29
+ return { id, ...input, token: Redacted.make(token) };
30
+ }),
31
+ resolve: Effect.fn("MachineTokens.resolve")(function* (token) {
32
+ const stored = yield* digest(token).pipe(Effect.flatMap(repository.findById), Effect.map(Option.some), Effect.catchTag("NoSuchElementError", () => Effect.succeed(Option.none())), Effect.catch(providerFailure));
33
+ if (Option.isNone(stored) || stored.value.ownerId !== options.owner.id) {
34
+ return Option.none();
35
+ }
36
+ const access = yield* options.roles.resolve(stored.value.scope).pipe(Effect.option);
37
+ return Option.map(access, (grants) => ({
38
+ machine: { id: stored.value.id, name: stored.value.name, scope: stored.value.scope },
39
+ user: { ...options.owner, ...grants },
40
+ }));
41
+ }),
42
+ revoke: Effect.fn("MachineTokens.revoke")((id) => repository.delete({ id, ownerId: options.owner.id })),
43
+ };
44
+ });
45
+ //# sourceMappingURL=machineTokens.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machineTokens.js","sourceRoot":"","sources":["../../src/server/machineTokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAClE,OAAO,KAAK,GAAG,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAEtC,OAAO,EAAE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C;gBACtC,OAAO,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE;gBACpF,IAAI,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,GAAG,MAAM,EAAE;aACrC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QACF,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC,sBAAsB,CAAC,CAAC,CAAC,EAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;KAC/G,CAAC;AACH,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/identity",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "Request identity, sessions, transport trust and permission enforcement for Effect RPC servers",
5
5
  "keywords": [
6
6
  "effect"
@@ -45,22 +45,23 @@
45
45
  "README.md"
46
46
  ],
47
47
  "dependencies": {
48
- "@shivaedev/access": "0.4.0",
48
+ "@shivaedev/access": "0.4.1",
49
49
  "@shivaedev/changes": "0.9.0",
50
- "@shivaedev/contract": "0.32.0",
51
- "@shivaedev/errors": "0.6.0",
52
- "@shivaedev/rate-limit": "0.3.0",
53
- "@shivaedev/sql": "0.34.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"
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.0",
60
- "@shivaedev/quality": "0.57.0",
61
- "@shivaedev/server": "0.20.0",
62
- "@shivaedev/test-sql": "0.17.0",
63
- "@shivaedev/test-story": "0.35.0",
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",
64
65
  "@types/node": "24.19.2",
65
66
  "better-auth": "1.7.14",
66
67
  "effect": "4.0.6",
@@ -0,0 +1,12 @@
1
+ import { Effect } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+
4
+ export const machineTokenMigration = Effect.gen(function* () {
5
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
6
+ yield* sql`create table identity_machine_tokens (
7
+ id text primary key,
8
+ name text not null,
9
+ "ownerId" text not null,
10
+ scope text not null
11
+ )`;
12
+ });
@@ -0,0 +1,34 @@
1
+ import { Crypto, type Duration, Effect, Option, Redacted } from "effect";
2
+ import * as Hex from "effect/encoding/Hex";
3
+ import type { RoleSet } from "@shivaedev/access/roleSet.ts";
4
+ import type { SessionUserValue } from "#identity.ts";
5
+ import { localTransport } from "#server/adapters/local.ts";
6
+ import { machineTokens } from "./machineTokens.ts";
7
+ import type { SessionPolicy } from "./SessionPolicy.ts";
8
+
9
+ export const localOwner = Effect.fn("Identity.localOwner")(function* (options: {
10
+ readonly owner: Pick<SessionUserValue, "id" | "name" | "email"> & { readonly role: string };
11
+ readonly roles: RoleSet;
12
+ readonly streamRevalidationInterval?: Duration.Input;
13
+ }) {
14
+ const { owner, roles } = options;
15
+ const access = yield* roles.resolve(owner.role);
16
+ const crypto = yield* Crypto.Crypto;
17
+ const token = Redacted.make(Hex.encode(yield* crypto.randomBytes(32)));
18
+ const machines = yield* machineTokens({ owner, roles });
19
+ const allowed = localTransport();
20
+ const sessions: SessionPolicy["Service"] = {
21
+ origin: (request) => allowed({ headers: request.headers, remoteAddress: request.remoteAddress ?? Option.none() }),
22
+ provider: {
23
+ get: (headers) => {
24
+ const bearer = /^Bearer (?<token>\S+)$/iu.exec(headers.authorization ?? "")?.groups?.token;
25
+ if (bearer === undefined) {
26
+ return Effect.succeed(Option.none());
27
+ }
28
+ return bearer === Redacted.value(token) ? Effect.succeed(Option.some({ user: { ...owner, ...access } })) : machines.resolve(bearer);
29
+ },
30
+ },
31
+ streamRevalidationInterval: options.streamRevalidationInterval,
32
+ };
33
+ return { machines, sessions, token };
34
+ });
@@ -0,0 +1,55 @@
1
+ import { Crypto, Effect, Option, Redacted, Schema } from "effect";
2
+ import * as Hex from "effect/encoding/Hex";
3
+ import { Model } from "effect/schema";
4
+ import type { RoleSet } from "@shivaedev/access/roleSet.ts";
5
+ import { makeRepository } from "@shivaedev/sql/repository.ts";
6
+ import type { SessionUserValue } from "#identity.ts";
7
+ import { providerFailure } from "./providerFailure.ts";
8
+
9
+ class MachineToken extends Model.Class<MachineToken>("IdentityMachineToken")({
10
+ id: Schema.String,
11
+ name: Schema.String,
12
+ ownerId: Schema.String,
13
+ scope: Schema.String,
14
+ }) {}
15
+
16
+ export const machineTokens = Effect.fn("Identity.machineTokens")(function* (options: {
17
+ readonly owner: Pick<SessionUserValue, "id" | "name" | "email">;
18
+ readonly roles: RoleSet;
19
+ }) {
20
+ const crypto = yield* Crypto.Crypto;
21
+ const repository = yield* makeRepository(MachineToken, {
22
+ idColumn: "id",
23
+ spanPrefix: "MachineTokens",
24
+ tableName: "identity_machine_tokens",
25
+ });
26
+ function digest(token: string) {
27
+ return crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(Effect.map(Hex.encode));
28
+ }
29
+ return {
30
+ issue: Effect.fn("MachineTokens.issue")(function* (input: { readonly name: string; readonly scope: string }) {
31
+ yield* options.roles.resolve(input.scope);
32
+ const token = Hex.encode(yield* crypto.randomBytes(32));
33
+ const id = yield* digest(token);
34
+ yield* repository.insertVoid({ id, name: input.name, ownerId: options.owner.id, scope: input.scope });
35
+ return { id, ...input, token: Redacted.make(token) };
36
+ }),
37
+ resolve: Effect.fn("MachineTokens.resolve")(function* (token: string) {
38
+ const stored = yield* digest(token).pipe(
39
+ Effect.flatMap(repository.findById),
40
+ Effect.map(Option.some),
41
+ Effect.catchTag("NoSuchElementError", () => Effect.succeed(Option.none())),
42
+ Effect.catch(providerFailure),
43
+ );
44
+ if (Option.isNone(stored) || stored.value.ownerId !== options.owner.id) {
45
+ return Option.none();
46
+ }
47
+ const access = yield* options.roles.resolve(stored.value.scope).pipe(Effect.option);
48
+ return Option.map(access, (grants) => ({
49
+ machine: { id: stored.value.id, name: stored.value.name, scope: stored.value.scope },
50
+ user: { ...options.owner, ...grants },
51
+ }));
52
+ }),
53
+ revoke: Effect.fn("MachineTokens.revoke")((id: string) => repository.delete({ id, ownerId: options.owner.id })),
54
+ };
55
+ });
@@ -1,4 +0,0 @@
1
- import { Effect } from "effect";
2
- export declare const testUserEmail: Effect.Effect<string, never, never>;
3
- export declare const signedSessionToken: (token: string, secret: string) => Effect.Effect<string, never, never>;
4
- //# sourceMappingURL=testingCredentials.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testingCredentials.d.ts","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/testingCredentials.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,eAAO,MAAM,aAAa,qCAAmE,CAAC;AAE9F,eAAO,MAAM,kBAAkB,wEAG7B,CAAC"}
@@ -1,8 +0,0 @@
1
- import { generateRandomString, makeSignature } from "better-auth/crypto";
2
- import { Effect } from "effect";
3
- export const testUserEmail = Effect.sync(() => `test-${generateRandomString(8)}@example.com`);
4
- export const signedSessionToken = Effect.fnUntraced(function* (token, secret) {
5
- const signature = yield* Effect.promise(() => makeSignature(token, secret));
6
- return `${token}.${signature}`;
7
- });
8
- //# sourceMappingURL=testingCredentials.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testingCredentials.js","sourceRoot":"","sources":["../../../../src/server/better-auth/adapters/testingCredentials.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,oBAAoB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC;AAE9F,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,KAAa,EAAE,MAAc;IAC3F,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5E,OAAO,GAAG,KAAK,IAAI,SAAS,EAAE,CAAC;AAChC,CAAC,CAAC,CAAC"}
@@ -1,64 +0,0 @@
1
- import type { AuthContext } from "better-auth";
2
- import { Effect } from "effect";
3
- type AccountContext = Pick<AuthContext, "internalAdapter">;
4
- type SessionContext = AccountContext & Pick<AuthContext, "sessionConfig" | "secret" | "authCookies" | "baseURL">;
5
- export declare const signedInUser: (auth: {
6
- readonly $context: Promise<SessionContext>;
7
- }, args_1: Partial<{
8
- id: string;
9
- createdAt: Date;
10
- updatedAt: Date;
11
- email: string;
12
- emailVerified: boolean;
13
- name: string;
14
- image?: string | null | undefined;
15
- }> & Record<string, unknown> & {
16
- readonly providerAccounts?: readonly {
17
- readonly providerId: string;
18
- readonly accountId: string;
19
- }[];
20
- }) => Effect.Effect<import("better-auth/plugins").LoginResult, never, never>;
21
- export declare const signInAgain: (auth: {
22
- readonly $context: Promise<SessionContext>;
23
- }, userId: string) => Effect.Effect<import("better-auth/plugins").LoginResult, never, never>;
24
- export declare function storedProviderAccounts(auth: {
25
- readonly $context: Promise<AccountContext>;
26
- }, userId: string): Promise<{
27
- accountId: string;
28
- hasAccessToken: boolean;
29
- hasIdToken: boolean;
30
- hasPassword: boolean;
31
- hasRefreshToken: boolean;
32
- providerId: string;
33
- }[]>;
34
- export declare const passwordUser: (auth: {
35
- readonly $context: Promise<AccountContext & {
36
- readonly password: Pick<AuthContext["password"], "hash">;
37
- }>;
38
- }, args_1: Partial<{
39
- id: string;
40
- createdAt: Date;
41
- updatedAt: Date;
42
- email: string;
43
- emailVerified: boolean;
44
- name: string;
45
- image?: string | null | undefined;
46
- }> & Record<string, unknown> & ({
47
- readonly email: string;
48
- } & ({
49
- readonly password: string;
50
- readonly passwordHash?: never;
51
- } | {
52
- readonly passwordHash: string;
53
- readonly password?: never;
54
- }))) => Effect.Effect<Record<string, any> & {
55
- id: string;
56
- createdAt: Date;
57
- updatedAt: Date;
58
- email: string;
59
- emailVerified: boolean;
60
- name: string;
61
- image?: string | null | undefined;
62
- }, never, never>;
63
- export {};
64
- //# sourceMappingURL=testing.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/testing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAS,MAAM,EAAE,MAAM,QAAQ,CAAC;AAMvC,KAAK,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAC;AAC3D,KAAK,cAAc,GAAG,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,eAAe,GAAG,QAAQ,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC;AAqBjH,eAAO,MAAM,YAAY;uBACG,OAAO,CAAC,cAAc,CAAC;;;;;;;;;;gCAKrB,SAAS;QAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;KAAE,EAAE;4EASlG,CAAC;AAEH,eAAO,MAAM,WAAW;uBACI,OAAO,CAAC,cAAc,CAAC;4FA2BjD,CAAC;AAEH,wBAAsB,sBAAsB,CAAC,IAAI,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;CAAE,EAAE,MAAM,EAAE,MAAM;;;;;;;KAWhH;AAED,eAAO,MAAM,YAAY;uBACG,OAAO,CAAC,cAAc,GAAG;QAAE,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;;;;;;;;;;oBAK/E,MAAM;;uBACf,MAAM;4BAA0B,KAAK;;2BACjC,MAAM;wBAAsB,KAAK;;;;;;;;;gBAU7D,CAAC"}
@@ -1,69 +0,0 @@
1
- import { Clock, Effect } from "effect";
2
- import { signedSessionToken, testUserEmail } from "#server/better-auth/adapters/testingCredentials.ts";
3
- function saveUser(context, fields) {
4
- return Effect.flatMap(testUserEmail, (email) => Effect.promise(() => context.internalAdapter.createUser({ email, emailVerified: true, image: null, name: "Test User", ...fields }, { method: "test" })));
5
- }
6
- function cookieSameSite(value) {
7
- switch (value?.toLowerCase()) {
8
- case "strict":
9
- return "Strict";
10
- case "none":
11
- return "None";
12
- default:
13
- return "Lax";
14
- }
15
- }
16
- export const signedInUser = Effect.fnUntraced(function* (auth, { providerAccounts = [], ...fields }) {
17
- const context = yield* Effect.promise(() => auth.$context);
18
- const user = yield* saveUser(context, fields);
19
- for (const { providerId, accountId } of providerAccounts) {
20
- yield* Effect.promise(() => context.internalAdapter.createAccount({ accountId, providerId, userId: user.id }));
21
- }
22
- return yield* signInAgain(auth, user.id);
23
- });
24
- export const signInAgain = Effect.fnUntraced(function* (auth, userId) {
25
- const { internalAdapter, sessionConfig, authCookies, secret, baseURL } = yield* Effect.promise(() => auth.$context);
26
- const now = yield* Clock.currentTimeMillis;
27
- const session = yield* Effect.promise(() => internalAdapter.createSession(userId, false, {}, true));
28
- const expiresAt = new Date(now + sessionConfig.expiresIn * 1000);
29
- yield* Effect.promise(() => internalAdapter.updateSession(session.token, { expiresAt }));
30
- const user = yield* Effect.promise(() => internalAdapter.findUserById(userId));
31
- if (user === null) {
32
- return yield* Effect.die(`User not found: ${userId}`);
33
- }
34
- const value = yield* signedSessionToken(session.token, secret);
35
- const { name, attributes } = authCookies.sessionToken;
36
- const cookies = [
37
- {
38
- domain: URL.canParse(baseURL) ? new URL(baseURL).hostname : "localhost",
39
- httpOnly: attributes.httpOnly ?? true,
40
- name,
41
- path: attributes.path || "/",
42
- sameSite: cookieSameSite(attributes.sameSite),
43
- secure: attributes.secure ?? false,
44
- value,
45
- ...(attributes.maxAge ? { expires: Math.floor(now / 1000) + attributes.maxAge } : {}),
46
- },
47
- ];
48
- return { cookies, headers: new Headers({ cookie: `${name}=${value}` }), session: { ...session, expiresAt }, token: session.token, user };
49
- });
50
- export async function storedProviderAccounts(auth, userId) {
51
- const { internalAdapter } = await auth.$context;
52
- const accounts = await internalAdapter.findAccounts(userId);
53
- return accounts.map(({ providerId, accountId, accessToken, refreshToken, idToken, password }) => ({
54
- accountId,
55
- hasAccessToken: Boolean(accessToken),
56
- hasIdToken: Boolean(idToken),
57
- hasPassword: Boolean(password),
58
- hasRefreshToken: Boolean(refreshToken),
59
- providerId,
60
- }));
61
- }
62
- export const passwordUser = Effect.fnUntraced(function* (auth, { password, passwordHash, ...fields }) {
63
- const context = yield* Effect.promise(() => auth.$context);
64
- const user = yield* saveUser(context, fields);
65
- const hash = passwordHash ?? (yield* Effect.promise(() => context.password.hash(password)));
66
- yield* Effect.promise(() => context.internalAdapter.createAccount({ accountId: user.id, password: hash, providerId: "credential", userId: user.id }));
67
- return user;
68
- });
69
- //# sourceMappingURL=testing.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testing.js","sourceRoot":"","sources":["../../../src/server/better-auth/testing.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,oDAAoD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AAO,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;QACjG,SAAS;QACT,cAAc,EAAE,OAAO,CAAC,WAAW,CAAC;QACpC,UAAU,EAAE,OAAO,CAAC,OAAO,CAAC;QAC5B,WAAW,EAAE,OAAO,CAAC,QAAQ,CAAC;QAC9B,eAAe,EAAE,OAAO,CAAC,YAAY,CAAC;QACtC,UAAU;KACV,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EACtD,IAAmH,EACnH,EACC,QAAQ,EACR,YAAY,EACZ,GAAG,MAAM,EAIR;IAEF,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC3D,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC9C,MAAM,IAAI,GAAG,YAAY,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC5F,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAC1B,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CACxH,CAAC;IACF,OAAO,IAAI,CAAC;AACb,CAAC,CAAC,CAAC"}
@@ -1,9 +0,0 @@
1
- import { generateRandomString, makeSignature } from "better-auth/crypto";
2
- import { Effect } from "effect";
3
-
4
- export const testUserEmail = Effect.sync(() => `test-${generateRandomString(8)}@example.com`);
5
-
6
- export const signedSessionToken = Effect.fnUntraced(function* (token: string, secret: string) {
7
- const signature = yield* Effect.promise(() => makeSignature(token, secret));
8
- return `${token}.${signature}`;
9
- });
@@ -1,109 +0,0 @@
1
- import type { AuthContext } from "better-auth";
2
- import type { testUtils } from "better-auth/plugins";
3
- import { Clock, Effect } from "effect";
4
- import { signedSessionToken, testUserEmail } from "#server/better-auth/adapters/testingCredentials.ts";
5
-
6
- type TestContext = ReturnType<ReturnType<typeof testUtils>["init"]>["context"];
7
- type UserFields = NonNullable<Parameters<TestContext["test"]["createUser"]>[0]>;
8
- type Login = Awaited<ReturnType<TestContext["test"]["login"]>>;
9
- type AccountContext = Pick<AuthContext, "internalAdapter">;
10
- type SessionContext = AccountContext & Pick<AuthContext, "sessionConfig" | "secret" | "authCookies" | "baseURL">;
11
-
12
- function saveUser(context: AccountContext, fields: UserFields) {
13
- return Effect.flatMap(testUserEmail, (email) =>
14
- Effect.promise(() =>
15
- context.internalAdapter.createUser({ email, emailVerified: true, image: null, name: "Test User", ...fields }, { method: "test" }),
16
- ),
17
- );
18
- }
19
-
20
- function cookieSameSite(value: string | undefined) {
21
- switch (value?.toLowerCase()) {
22
- case "strict":
23
- return "Strict";
24
- case "none":
25
- return "None";
26
- default:
27
- return "Lax";
28
- }
29
- }
30
-
31
- export const signedInUser = Effect.fnUntraced(function* (
32
- auth: { readonly $context: Promise<SessionContext> },
33
- {
34
- providerAccounts = [],
35
- ...fields
36
- }: UserFields & {
37
- readonly providerAccounts?: readonly { readonly providerId: string; readonly accountId: string }[];
38
- },
39
- ): Effect.fn.Return<Login> {
40
- const context = yield* Effect.promise(() => auth.$context);
41
- const user = yield* saveUser(context, fields);
42
- for (const { providerId, accountId } of providerAccounts) {
43
- yield* Effect.promise(() => context.internalAdapter.createAccount({ accountId, providerId, userId: user.id }));
44
- }
45
- return yield* signInAgain(auth, user.id);
46
- });
47
-
48
- export const signInAgain = Effect.fnUntraced(function* (
49
- auth: { readonly $context: Promise<SessionContext> },
50
- userId: string,
51
- ): Effect.fn.Return<Login> {
52
- const { internalAdapter, sessionConfig, authCookies, secret, baseURL } = yield* Effect.promise(() => auth.$context);
53
- const now = yield* Clock.currentTimeMillis;
54
- const session = yield* Effect.promise(() => internalAdapter.createSession(userId, false, {}, true));
55
- const expiresAt = new Date(now + sessionConfig.expiresIn * 1000);
56
- yield* Effect.promise(() => internalAdapter.updateSession(session.token, { expiresAt }));
57
- const user = yield* Effect.promise(() => internalAdapter.findUserById(userId));
58
- if (user === null) {
59
- return yield* Effect.die(`User not found: ${userId}`);
60
- }
61
- const value = yield* signedSessionToken(session.token, secret);
62
- const { name, attributes } = authCookies.sessionToken;
63
- const cookies: Login["cookies"] = [
64
- {
65
- domain: URL.canParse(baseURL) ? new URL(baseURL).hostname : "localhost",
66
- httpOnly: attributes.httpOnly ?? true,
67
- name,
68
- path: attributes.path || "/",
69
- sameSite: cookieSameSite(attributes.sameSite),
70
- secure: attributes.secure ?? false,
71
- value,
72
- ...(attributes.maxAge ? { expires: Math.floor(now / 1000) + attributes.maxAge } : {}),
73
- },
74
- ];
75
- return { cookies, headers: new Headers({ cookie: `${name}=${value}` }), session: { ...session, expiresAt }, token: session.token, user };
76
- });
77
-
78
- export async function storedProviderAccounts(auth: { readonly $context: Promise<AccountContext> }, userId: string) {
79
- const { internalAdapter } = await auth.$context;
80
- const accounts = await internalAdapter.findAccounts(userId);
81
- return accounts.map(({ providerId, accountId, accessToken, refreshToken, idToken, password }) => ({
82
- accountId,
83
- hasAccessToken: Boolean(accessToken),
84
- hasIdToken: Boolean(idToken),
85
- hasPassword: Boolean(password),
86
- hasRefreshToken: Boolean(refreshToken),
87
- providerId,
88
- }));
89
- }
90
-
91
- export const passwordUser = Effect.fnUntraced(function* (
92
- auth: { readonly $context: Promise<AccountContext & { readonly password: Pick<AuthContext["password"], "hash"> }> },
93
- {
94
- password,
95
- passwordHash,
96
- ...fields
97
- }: UserFields & { readonly email: string } & (
98
- | { readonly password: string; readonly passwordHash?: never }
99
- | { readonly passwordHash: string; readonly password?: never }
100
- ),
101
- ) {
102
- const context = yield* Effect.promise(() => auth.$context);
103
- const user = yield* saveUser(context, fields);
104
- const hash = passwordHash ?? (yield* Effect.promise(() => context.password.hash(password)));
105
- yield* Effect.promise(() =>
106
- context.internalAdapter.createAccount({ accountId: user.id, password: hash, providerId: "credential", userId: user.id }),
107
- );
108
- return user;
109
- });