@shivaedev/identity 0.21.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,12 @@
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
+
3
10
  ## 0.21.0 - 2026-11-03
4
11
 
5
12
  ### Breaking
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.
@@ -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,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACzE,OAAO,KAAK,GAAG,MAAM,qBAAqB,CAAC;AAG3C,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnD,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,EAAE,CAAC,qBAAqB,CAAC,CAAC,QAAQ,CAAC,EAAE,OAIrE;IACA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IACjC,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC;IACpC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACvE,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;IACjC,MAAM,QAAQ,GAA6B;QAC1C,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,CAAC,aAAa,IAAI,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACjH,QAAQ,EAAE;YACT,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE;gBAChB,MAAM,MAAM,GAAG,0BAA0B,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC;gBAC3F,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;oBAC1B,OAAO,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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AAO,MAAM,CAAC,IAAI,EAAE,CAAC;YACtB,CAAC;YACD,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACpF,OAAO,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;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"}
@@ -71,9 +71,7 @@ export declare const Sessions: import("@shivaedev/contract/contract.ts").Contrac
71
71
  readonly AuthUnavailable: typeof AuthUnavailable;
72
72
  readonly Forbidden: typeof Forbidden;
73
73
  readonly NotFound: typeof NotFound;
74
- }>>], import("effect/rpc/Rpc").Rpc<"identity.sessions.revoke", Schema.Struct<{
75
- id: Schema.String;
76
- }>, Schema.Void, Schema.Union<readonly (typeof NotFound | typeof Forbidden | typeof AuthUnavailable)[]>, typeof SessionsPermission, never> | import("effect/rpc/Rpc").Rpc<"identity.sessions.$changes", Schema.Struct<{
74
+ }>>], import("effect/rpc/Rpc").Rpc<"identity.sessions.$changes", Schema.Struct<{
77
75
  queries: Schema.$Array<Schema.Union<readonly Schema.Struct<{
78
76
  query: Schema.Literal<"list">;
79
77
  payload: Schema.Struct<{
@@ -140,5 +138,7 @@ export declare const Sessions: import("@shivaedev/contract/contract.ts").Contrac
140
138
  "~ClientError": never;
141
139
  error: Schema.Union<readonly [typeof import("@shivaedev/contract/readPolicyErrors.ts").MissingReadPolicy, typeof import("@shivaedev/contract/readPolicyErrors.ts").QueryReadDenied, typeof import("@shivaedev/contract/WebSocketRequired.ts").WebSocketRequired]>;
142
140
  requiredForClient: false;
143
- }), never>, readonly [], undefined>;
141
+ }), never> | import("effect/rpc/Rpc").Rpc<"identity.sessions.revoke", Schema.Struct<{
142
+ id: Schema.String;
143
+ }>, Schema.Void, Schema.Union<readonly (typeof NotFound | typeof Forbidden | typeof AuthUnavailable)[]>, typeof SessionsPermission, never>, readonly [], undefined>;
144
144
  //# sourceMappingURL=sessions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIxC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAI5D,eAAO,MAAM,eAAe;;;;;;;;;;EAM1B,CAAC;AAEH,eAAO,MAAM,aAAa;;;EAAqF,CAAC;AAChH,eAAO,MAAM,gBAAgB;;;;;;EAG3B,CAAC;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;EAA2G,CAAC;AAEpI,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCAiBY,CAAC"}
1
+ {"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIxC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAI5D,eAAO,MAAM,eAAe;;;;;;;;;;EAM1B,CAAC;AAEH,eAAO,MAAM,aAAa;;;EAAqF,CAAC;AAChH,eAAO,MAAM,gBAAgB;;;;;;EAG3B,CAAC;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;EAA2G,CAAC;AAEpI,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mKAiBY,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/identity",
3
- "version": "0.21.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"
@@ -56,10 +56,10 @@
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.1",
59
+ "@shivaedev/admin": "0.19.2",
60
60
  "@shivaedev/quality": "0.57.1",
61
- "@shivaedev/server": "0.20.1",
62
- "@shivaedev/test-kits": "0.1.0",
61
+ "@shivaedev/server": "0.20.2",
62
+ "@shivaedev/test-kits": "0.1.1",
63
63
  "@shivaedev/test-sql": "0.18.0",
64
64
  "@shivaedev/test-story": "0.36.0",
65
65
  "@types/node": "24.19.2",
@@ -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
+ });