@shivaedev/identity 0.19.0 → 0.20.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 +40 -0
- package/README.md +169 -77
- package/dist/PermissionSession.d.ts +11 -0
- package/dist/PermissionSession.d.ts.map +1 -0
- package/dist/PermissionSession.js +6 -0
- package/dist/PermissionSession.js.map +1 -0
- package/dist/authRefusal.d.ts +18 -0
- package/dist/authRefusal.d.ts.map +1 -0
- package/dist/authRefusal.js +11 -0
- package/dist/authRefusal.js.map +1 -0
- package/dist/client/AuthFailure.d.ts +18 -0
- package/dist/client/AuthFailure.d.ts.map +1 -0
- package/dist/client/AuthFailure.js +15 -0
- package/dist/client/AuthFailure.js.map +1 -0
- package/dist/client/AuthFailureCode.d.ts +4 -0
- package/dist/client/AuthFailureCode.d.ts.map +1 -0
- package/dist/client/AuthFailureCode.js +57 -0
- package/dist/client/AuthFailureCode.js.map +1 -0
- package/dist/client/adapters/authCall.d.ts +8 -0
- package/dist/client/adapters/authCall.d.ts.map +1 -0
- package/dist/client/adapters/authCall.js +31 -0
- package/dist/client/adapters/authCall.js.map +1 -0
- package/dist/client/adapters/authQuery.d.ts +5 -0
- package/dist/client/adapters/authQuery.d.ts.map +1 -0
- package/dist/client/adapters/authQuery.js +9 -0
- package/dist/client/adapters/authQuery.js.map +1 -0
- package/dist/client/adapters/authSession.d.ts +9 -0
- package/dist/client/adapters/authSession.d.ts.map +1 -0
- package/dist/client/adapters/authSession.js +20 -0
- package/dist/client/adapters/authSession.js.map +1 -0
- package/dist/client/adapters/changeEmail.d.ts +12 -0
- package/dist/client/adapters/changeEmail.d.ts.map +1 -0
- package/dist/client/adapters/changeEmail.js +5 -0
- package/dist/client/adapters/changeEmail.js.map +1 -0
- package/dist/roles.d.ts +16 -0
- package/dist/roles.d.ts.map +1 -0
- package/dist/roles.js +6 -0
- package/dist/roles.js.map +1 -0
- package/dist/server/UserDirectory.d.ts +14 -0
- package/dist/server/UserDirectory.d.ts.map +1 -0
- package/dist/server/UserDirectory.js +4 -0
- package/dist/server/UserDirectory.js.map +1 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.d.ts +9 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.d.ts.map +1 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.js +9 -0
- package/dist/server/better-auth/UndeclaredDefaultRole.js.map +1 -0
- package/dist/server/better-auth/accountRoleSeed.d.ts +2 -2
- package/dist/server/better-auth/accountRoleSeed.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/acquire.d.ts +7 -0
- package/dist/server/better-auth/adapters/acquire.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/acquire.js +14 -0
- package/dist/server/better-auth/adapters/acquire.js.map +1 -0
- package/dist/server/better-auth/adapters/emailOptions.d.ts +2 -2
- package/dist/server/better-auth/adapters/emailOptions.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/emailOptions.js +13 -9
- package/dist/server/better-auth/adapters/emailOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/hookRuntime.d.ts +7 -1
- package/dist/server/better-auth/adapters/hookRuntime.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/hookRuntime.js +9 -1
- package/dist/server/better-auth/adapters/hookRuntime.js.map +1 -1
- package/dist/server/better-auth/adapters/mount.d.ts +51 -40
- package/dist/server/better-auth/adapters/mount.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/mount.js +19 -6
- package/dist/server/better-auth/adapters/mount.js.map +1 -1
- package/dist/server/better-auth/adapters/oauthGrants.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/oauthGrants.js +17 -7
- package/dist/server/better-auth/adapters/oauthGrants.js.map +1 -1
- package/dist/server/better-auth/adapters/oauthProvider.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/oauthProvider.js +25 -2
- package/dist/server/better-auth/adapters/oauthProvider.js.map +1 -1
- package/dist/server/better-auth/adapters/profileStorage.d.ts +6 -0
- package/dist/server/better-auth/adapters/profileStorage.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/profileStorage.js +13 -0
- package/dist/server/better-auth/adapters/profileStorage.js.map +1 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.d.ts +3 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.js +56 -0
- package/dist/server/better-auth/adapters/providerOnlyOptions.js.map +1 -0
- package/dist/server/better-auth/adapters/response.d.ts +3 -1
- package/dist/server/better-auth/adapters/response.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/response.js +8 -6
- package/dist/server/better-auth/adapters/response.js.map +1 -1
- package/dist/server/better-auth/adapters/roleSeedOptions.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/roleSeedOptions.js +2 -1
- package/dist/server/better-auth/adapters/roleSeedOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/signInPolicyOptions.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/signInPolicyOptions.js +3 -2
- package/dist/server/better-auth/adapters/signInPolicyOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/testingCredentials.d.ts +4 -0
- package/dist/server/better-auth/adapters/testingCredentials.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/testingCredentials.js +8 -0
- package/dist/server/better-auth/adapters/testingCredentials.js.map +1 -0
- package/dist/server/better-auth/adapters/userDirectory.d.ts +7 -0
- package/dist/server/better-auth/adapters/userDirectory.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/userDirectory.js +20 -0
- package/dist/server/better-auth/adapters/userDirectory.js.map +1 -0
- package/dist/server/better-auth/assignRole.d.ts +1 -1
- package/dist/server/better-auth/assignRole.d.ts.map +1 -1
- package/dist/server/better-auth/assignRole.js +4 -2
- package/dist/server/better-auth/assignRole.js.map +1 -1
- package/dist/server/better-auth/emails.d.ts +11 -8
- package/dist/server/better-auth/emails.d.ts.map +1 -1
- package/dist/server/better-auth/mountRoutes.d.ts +1 -0
- package/dist/server/better-auth/mountRoutes.d.ts.map +1 -1
- package/dist/server/better-auth/mountRoutes.js +1 -1
- package/dist/server/better-auth/mountRoutes.js.map +1 -1
- package/dist/server/better-auth/testing.d.ts +13 -39
- package/dist/server/better-auth/testing.d.ts.map +1 -1
- package/dist/server/better-auth/testing.js +44 -12
- package/dist/server/better-auth/testing.js.map +1 -1
- package/dist/server/better-auth/userDirectoryReads.d.ts +26 -0
- package/dist/server/better-auth/userDirectoryReads.d.ts.map +1 -0
- package/dist/server/better-auth/userDirectoryReads.js +42 -0
- package/dist/server/better-auth/userDirectoryReads.js.map +1 -0
- package/dist/server/better-auth/userProfiles.d.ts +4 -6
- package/dist/server/better-auth/userProfiles.d.ts.map +1 -1
- package/dist/server/better-auth/userProfiles.js +2 -11
- package/dist/server/better-auth/userProfiles.js.map +1 -1
- package/dist/server/oauthGrants.d.ts +4 -1
- package/dist/server/oauthGrants.d.ts.map +1 -1
- package/dist/server/oauthGrants.js.map +1 -1
- package/dist/server/permissions.d.ts.map +1 -1
- package/dist/server/permissions.js +2 -4
- package/dist/server/permissions.js.map +1 -1
- package/dist/server/resolveChanges.d.ts +8 -0
- package/dist/server/resolveChanges.d.ts.map +1 -0
- package/dist/server/resolveChanges.js +13 -0
- package/dist/server/resolveChanges.js.map +1 -0
- package/dist/server/session.d.ts +1 -1
- package/dist/server/session.d.ts.map +1 -1
- package/dist/server/session.js +10 -11
- package/dist/server/session.js.map +1 -1
- package/dist/server/tracing.d.ts.map +1 -1
- package/dist/server/tracing.js +3 -7
- package/dist/server/tracing.js.map +1 -1
- package/dist/sessions.d.ts +19 -3
- package/dist/sessions.d.ts.map +1 -1
- package/dist/users.d.ts +29 -0
- package/dist/users.d.ts.map +1 -0
- package/dist/users.js +18 -0
- package/dist/users.js.map +1 -0
- package/package.json +16 -17
- package/src/PermissionSession.ts +7 -0
- package/src/authRefusal.ts +13 -0
- package/src/client/AuthFailure.ts +19 -0
- package/src/client/AuthFailureCode.ts +58 -0
- package/src/client/adapters/authCall.ts +44 -0
- package/src/client/adapters/authQuery.ts +13 -0
- package/src/client/adapters/authSession.ts +30 -0
- package/src/client/adapters/changeEmail.ts +13 -0
- package/src/roles.ts +5 -0
- package/src/server/UserDirectory.ts +14 -0
- package/src/server/better-auth/UndeclaredDefaultRole.ts +9 -0
- package/src/server/better-auth/adapters/acquire.ts +17 -0
- package/src/server/better-auth/adapters/emailOptions.ts +21 -9
- package/src/server/better-auth/adapters/hookRuntime.ts +17 -3
- package/src/server/better-auth/adapters/mount.ts +38 -7
- package/src/server/better-auth/adapters/oauthGrants.ts +17 -7
- package/src/server/better-auth/adapters/oauthProvider.ts +32 -2
- package/src/server/better-auth/adapters/profileStorage.ts +18 -0
- package/src/server/better-auth/adapters/providerOnlyOptions.ts +63 -0
- package/src/server/better-auth/adapters/response.ts +15 -7
- package/src/server/better-auth/adapters/roleSeedOptions.ts +2 -1
- package/src/server/better-auth/adapters/signInPolicyOptions.ts +3 -2
- package/src/server/better-auth/adapters/testingCredentials.ts +9 -0
- package/src/server/better-auth/adapters/userDirectory.ts +33 -0
- package/src/server/better-auth/assignRole.ts +4 -2
- package/src/server/better-auth/emails.ts +11 -8
- package/src/server/better-auth/mountRoutes.ts +2 -1
- package/src/server/better-auth/testing.ts +68 -18
- package/src/server/better-auth/userDirectoryReads.ts +47 -0
- package/src/server/better-auth/userProfiles.ts +6 -12
- package/src/server/oauthGrants.ts +5 -1
- package/src/server/permissions.ts +2 -4
- package/src/server/resolveChanges.ts +24 -0
- package/src/server/session.ts +14 -11
- package/src/server/tracing.ts +4 -9
- package/src/users.ts +19 -0
- package/dist/server/better-auth/emailWindow.d.ts +0 -3
- package/dist/server/better-auth/emailWindow.d.ts.map +0 -1
- package/dist/server/better-auth/emailWindow.js +0 -23
- package/dist/server/better-auth/emailWindow.js.map +0 -1
- package/dist/server/commandChanges.d.ts +0 -4
- package/dist/server/commandChanges.d.ts.map +0 -1
- package/dist/server/commandChanges.js +0 -48
- package/dist/server/commandChanges.js.map +0 -1
- package/dist/server/sessionKeys.d.ts +0 -13
- package/dist/server/sessionKeys.d.ts.map +0 -1
- package/dist/server/sessionKeys.js +0 -27
- package/dist/server/sessionKeys.js.map +0 -1
- package/src/server/better-auth/emailWindow.ts +0 -27
- package/src/server/commandChanges.ts +0 -63
- package/src/server/sessionKeys.ts +0 -42
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
import * as HttpStatus from "effect/http/HttpStatus";
|
|
3
|
+
import { identityAuthFailureCode } from "#authRefusal.ts";
|
|
4
|
+
import { AuthFailure, type AuthFailureWithCodes } from "#client/AuthFailure.ts";
|
|
5
|
+
import { AuthFailureCode } from "#client/AuthFailureCode.ts";
|
|
6
|
+
|
|
7
|
+
export interface AuthActionResult<A, E> {
|
|
8
|
+
readonly data: A;
|
|
9
|
+
readonly error: E | null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const supportedCode = Schema.is(AuthFailureCode);
|
|
13
|
+
|
|
14
|
+
function fallbackCode(error: object) {
|
|
15
|
+
return "status" in error && error.status === HttpStatus.fromLiteral("TooManyRequests") ? "RATE_LIMITED" : "UNKNOWN";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function authCall<TInput, A, E extends object = never, TCode extends string = never>(
|
|
19
|
+
run: (input: TInput, signal: AbortSignal) => Promise<AuthActionResult<A, E>>,
|
|
20
|
+
codes: readonly TCode[] = [],
|
|
21
|
+
): (input: TInput) => Effect.Effect<A, AuthFailure | AuthFailureWithCodes<TCode>> {
|
|
22
|
+
const ApplicationFailure = AuthFailure.withCodes(codes);
|
|
23
|
+
const applicationCode = Schema.is(Schema.Literals(codes));
|
|
24
|
+
return (input: TInput) =>
|
|
25
|
+
Effect.tryPromise({
|
|
26
|
+
catch: (cause) => new AuthFailure({ cause, code: "UNKNOWN" }),
|
|
27
|
+
try: (signal) => run(input, signal),
|
|
28
|
+
}).pipe(
|
|
29
|
+
Effect.flatMap(({ data, error }) => {
|
|
30
|
+
if (error === null) {
|
|
31
|
+
return Effect.succeed(data);
|
|
32
|
+
}
|
|
33
|
+
const wire = "code" in error ? error.code : undefined;
|
|
34
|
+
const code = identityAuthFailureCode(wire) ?? wire;
|
|
35
|
+
if (supportedCode(code)) {
|
|
36
|
+
return Effect.fail(new AuthFailure({ cause: error, code }));
|
|
37
|
+
}
|
|
38
|
+
if (applicationCode(wire)) {
|
|
39
|
+
return Effect.fail(new ApplicationFailure({ cause: error, code: wire }));
|
|
40
|
+
}
|
|
41
|
+
return Effect.fail(new AuthFailure({ cause: error, code: fallbackCode(error) }));
|
|
42
|
+
}),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
3
|
+
import type { AuthActionResult } from "./authCall.ts";
|
|
4
|
+
|
|
5
|
+
export function authQuery<TInput, A, E extends object = never>(
|
|
6
|
+
run: (input: TInput, signal: AbortSignal) => Promise<AuthActionResult<A, E>>,
|
|
7
|
+
): (input: TInput) => Effect.Effect<A, E | AuthUnavailable> {
|
|
8
|
+
return (input) =>
|
|
9
|
+
Effect.tryPromise({
|
|
10
|
+
catch: (cause) => new AuthUnavailable({ message: String(cause) }),
|
|
11
|
+
try: (signal) => run(input, signal),
|
|
12
|
+
}).pipe(Effect.flatMap((result) => (result.error === null ? Effect.succeed(result.data) : Effect.fail(result.error))));
|
|
13
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
3
|
+
import { PermissionSession } from "#PermissionSession.ts";
|
|
4
|
+
import type { AuthActionResult } from "./authCall.ts";
|
|
5
|
+
|
|
6
|
+
export type SessionWithPermissions<A> = A extends null ? null : A & PermissionSession;
|
|
7
|
+
|
|
8
|
+
function decodeSession<A extends { readonly user: object } | null>(data: A): Effect.Effect<SessionWithPermissions<A>, AuthUnavailable>;
|
|
9
|
+
function decodeSession(data: { readonly user: object } | null) {
|
|
10
|
+
if (data === null) {
|
|
11
|
+
return Effect.succeed(null);
|
|
12
|
+
}
|
|
13
|
+
return Schema.decodeUnknownEffect(PermissionSession)(data).pipe(
|
|
14
|
+
Effect.map((access) => ({ ...data, user: { ...data.user, ...access.user } })),
|
|
15
|
+
Effect.mapError(() => new AuthUnavailable({ message: "Could not read session permissions" })),
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const authSession = Effect.fnUntraced(function* <A extends { readonly user: object } | null, E extends object = never>(
|
|
20
|
+
read: (signal: AbortSignal) => Promise<AuthActionResult<A, E>>,
|
|
21
|
+
): Effect.fn.Return<SessionWithPermissions<A>, E | AuthUnavailable> {
|
|
22
|
+
const result = yield* Effect.tryPromise({
|
|
23
|
+
catch: (cause) => new AuthUnavailable({ message: String(cause) }),
|
|
24
|
+
try: read,
|
|
25
|
+
});
|
|
26
|
+
if (result.error !== null) {
|
|
27
|
+
return yield* Effect.fail(result.error);
|
|
28
|
+
}
|
|
29
|
+
return yield* decodeSession(result.data);
|
|
30
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type AuthActionResult, authCall } from "./authCall.ts";
|
|
2
|
+
|
|
3
|
+
export interface ChangeEmailInput {
|
|
4
|
+
readonly "callbackURL"?: string;
|
|
5
|
+
readonly newEmail: string;
|
|
6
|
+
readonly password: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function changeEmail<A, E extends object>(client: {
|
|
10
|
+
readonly changeEmail: (input: ChangeEmailInput, options: { readonly signal: AbortSignal }) => Promise<AuthActionResult<A, E>>;
|
|
11
|
+
}) {
|
|
12
|
+
return authCall((input: ChangeEmailInput, signal) => client.changeEmail(input, { signal }));
|
|
13
|
+
}
|
package/src/roles.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import { permission } from "@shivaedev/access/permission.ts";
|
|
3
|
+
|
|
4
|
+
export const AssignRoles = permission("roles.assign");
|
|
5
|
+
export class LastRoleAssigner extends Schema.TaggedError<LastRoleAssigner>()("LastRoleAssigner", { userId: Schema.String }) {}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Context, type Effect } from "effect";
|
|
2
|
+
import type { AuthUnavailable, NotFound } from "@shivaedev/errors/taxonomy.ts";
|
|
3
|
+
import type { LastRoleAssigner } from "#roles.ts";
|
|
4
|
+
import type { AccountName, UserList, UserListInput } from "#users.ts";
|
|
5
|
+
|
|
6
|
+
export class UserDirectory extends Context.Service<
|
|
7
|
+
UserDirectory,
|
|
8
|
+
{
|
|
9
|
+
readonly list: (input: typeof UserListInput.Type) => Effect.Effect<typeof UserList.Type, AuthUnavailable>;
|
|
10
|
+
readonly role: (userId: string) => Effect.Effect<string, AuthUnavailable | NotFound>;
|
|
11
|
+
readonly assignRole: (userId: string, role: string) => Effect.Effect<boolean, AuthUnavailable | NotFound | LastRoleAssigner>;
|
|
12
|
+
readonly names: (userIds: readonly string[]) => Effect.Effect<readonly (typeof AccountName.Type)[], AuthUnavailable>;
|
|
13
|
+
}
|
|
14
|
+
>()("@shivaedev/identity/UserDirectory") {}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
export class UndeclaredDefaultRole extends Schema.TaggedError<UndeclaredDefaultRole>()("UndeclaredDefaultRole", {
|
|
4
|
+
role: Schema.String,
|
|
5
|
+
}) {
|
|
6
|
+
override get message() {
|
|
7
|
+
return `Default user role is not declared by the application: ${JSON.stringify(this.role)}`;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type BetterAuthOptions, betterAuth } from "better-auth";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { providerFailure } from "#server/providerFailure.ts";
|
|
4
|
+
import { profileStorage } from "./profileStorage.ts";
|
|
5
|
+
|
|
6
|
+
export const acquireAuth = Effect.fnUntraced(function* <TOptions extends BetterAuthOptions>(options: TOptions) {
|
|
7
|
+
const auth = betterAuth(options);
|
|
8
|
+
const context = yield* Effect.tryPromise(async () => {
|
|
9
|
+
const ready = await auth.$context;
|
|
10
|
+
await ready.checkSchema?.();
|
|
11
|
+
return ready;
|
|
12
|
+
}).pipe(
|
|
13
|
+
Effect.uninterruptible,
|
|
14
|
+
Effect.catch((error) => providerFailure(error.cause)),
|
|
15
|
+
);
|
|
16
|
+
return { auth, profiles: profileStorage(context) };
|
|
17
|
+
});
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
-
import { Effect, Schema } from "effect";
|
|
2
|
+
import { Effect, Redacted, Schema } from "effect";
|
|
3
|
+
import { postgresStore } from "@shivaedev/rate-limit/adapters/postgresStore.ts";
|
|
4
|
+
import { rateLimit } from "@shivaedev/rate-limit/rateLimit.ts";
|
|
5
|
+
import { Store } from "@shivaedev/rate-limit/Store.ts";
|
|
3
6
|
import type { AuthEmail, BetterAuthEmails } from "#server/better-auth/emails.ts";
|
|
4
|
-
import { emailWindow } from "#server/better-auth/emailWindow.ts";
|
|
5
7
|
import type { hookRuntime } from "./hookRuntime.ts";
|
|
6
8
|
|
|
7
9
|
type Outgoing = { [TKind in AuthEmail["_tag"]]: Omit<Extract<AuthEmail, { readonly _tag: TKind }>, "url"> }[AuthEmail["_tag"]];
|
|
@@ -16,15 +18,22 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
16
18
|
if (emails === undefined) {
|
|
17
19
|
return options;
|
|
18
20
|
}
|
|
19
|
-
const { routes, deliver } = emails;
|
|
20
|
-
const
|
|
21
|
+
const { routes, deliver, window = "1 minute" } = emails;
|
|
22
|
+
const store = yield* Store.pipe(Effect.provide(postgresStore));
|
|
21
23
|
function send(message: Outgoing, request?: Request) {
|
|
22
24
|
const url = new URL(routes[message._tag]);
|
|
23
25
|
if ("token" in message) {
|
|
24
|
-
url.searchParams.set("token", message.token);
|
|
26
|
+
url.searchParams.set("token", Redacted.value(message.token));
|
|
25
27
|
}
|
|
26
28
|
return runtime.runHook(
|
|
27
|
-
() =>
|
|
29
|
+
() =>
|
|
30
|
+
rateLimit({ key: `identity:email:${JSON.stringify([message.user.id, message._tag])}`, per: 1, window }).pipe(
|
|
31
|
+
Effect.provideService(Store, store),
|
|
32
|
+
Effect.as(true),
|
|
33
|
+
Effect.catchTag("TooManyRequests", () => Effect.succeed(false)),
|
|
34
|
+
Effect.orDie,
|
|
35
|
+
Effect.flatMap((allowed) => (allowed ? deliver({ ...message, url: Redacted.make(url.href) }) : Effect.void)),
|
|
36
|
+
),
|
|
28
37
|
request?.signal,
|
|
29
38
|
);
|
|
30
39
|
}
|
|
@@ -34,7 +43,7 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
34
43
|
...options.emailAndPassword,
|
|
35
44
|
enabled: options.emailAndPassword?.enabled ?? false,
|
|
36
45
|
onExistingUserSignUp: ({ user }, request) => send({ _tag: "AccountAlreadyExists", user }, request),
|
|
37
|
-
sendResetPassword: ({ user, token }, request) => send({ _tag: "ResetPassword", token, user }, request),
|
|
46
|
+
sendResetPassword: ({ user, token }, request) => send({ _tag: "ResetPassword", token: Redacted.make(token), user }, request),
|
|
38
47
|
},
|
|
39
48
|
emailVerification: {
|
|
40
49
|
...options.emailVerification,
|
|
@@ -42,7 +51,9 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
42
51
|
const payload = token.split(".")[1] ?? "";
|
|
43
52
|
const { updateTo } = Schema.decodeUnknownSync(Schema.fromJsonString(Verification))(Buffer.from(payload, "base64url").toString("utf8"));
|
|
44
53
|
return send(
|
|
45
|
-
updateTo === undefined
|
|
54
|
+
updateTo === undefined
|
|
55
|
+
? { _tag: "ConfirmAccount", token: Redacted.make(token), user }
|
|
56
|
+
: { _tag: "ConfirmNewAddress", newEmail: updateTo, token: Redacted.make(token), user },
|
|
46
57
|
request,
|
|
47
58
|
);
|
|
48
59
|
},
|
|
@@ -52,7 +63,8 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
52
63
|
changeEmail: {
|
|
53
64
|
...options.user?.changeEmail,
|
|
54
65
|
enabled: options.user?.changeEmail?.enabled ?? false,
|
|
55
|
-
sendChangeEmailConfirmation: ({ user, newEmail, token }, request) =>
|
|
66
|
+
sendChangeEmailConfirmation: ({ user, newEmail, token }, request) =>
|
|
67
|
+
send({ _tag: "ApproveEmailChange", newEmail, token: Redacted.make(token), user }, request),
|
|
56
68
|
},
|
|
57
69
|
},
|
|
58
70
|
} satisfies BetterAuthOptions;
|
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { APIError } from "better-auth/api";
|
|
3
|
-
import { type Cause, Context, Effect, Result } from "effect";
|
|
3
|
+
import { type Cause, Context, Data, Effect, Result } from "effect";
|
|
4
4
|
import { authCall } from "#server/adapters/authCall.ts";
|
|
5
5
|
import type { BetterAuthHookError } from "#server/better-auth/databaseHooks.ts";
|
|
6
6
|
|
|
7
|
+
export class HookRefusal extends Data.TaggedError("HookRefusal")<BetterAuthHookError> {}
|
|
8
|
+
|
|
9
|
+
interface RequestState<R> {
|
|
10
|
+
cause?: Cause.Cause<never>;
|
|
11
|
+
readonly context: Context.Context<R>;
|
|
12
|
+
refusal?: HookRefusal;
|
|
13
|
+
}
|
|
14
|
+
|
|
7
15
|
export const hookRuntime = Effect.fnUntraced(function* <R>() {
|
|
8
16
|
const context = yield* Effect.context<R>();
|
|
9
|
-
const requests = new AsyncLocalStorage<
|
|
17
|
+
const requests = new AsyncLocalStorage<RequestState<R>>();
|
|
10
18
|
return {
|
|
11
19
|
runHook: async <A>(hook: () => Effect.Effect<A, BetterAuthHookError, R>, signal: AbortSignal | undefined): Promise<A> => {
|
|
12
20
|
const request = requests.getStore();
|
|
@@ -21,6 +29,9 @@ export const hookRuntime = Effect.fnUntraced(function* <R>() {
|
|
|
21
29
|
signal,
|
|
22
30
|
});
|
|
23
31
|
if (Result.isFailure(result)) {
|
|
32
|
+
if (request !== undefined) {
|
|
33
|
+
request.refusal = new HookRefusal(result.failure);
|
|
34
|
+
}
|
|
24
35
|
throw new APIError("FORBIDDEN", { code: result.failure.code, message: result.failure.message });
|
|
25
36
|
}
|
|
26
37
|
return result.success;
|
|
@@ -28,13 +39,16 @@ export const hookRuntime = Effect.fnUntraced(function* <R>() {
|
|
|
28
39
|
runRequest: <A>(request: (signal: AbortSignal) => Promise<A>) =>
|
|
29
40
|
Effect.withFiber((fiber) =>
|
|
30
41
|
Effect.gen(function* () {
|
|
31
|
-
const state:
|
|
42
|
+
const state: RequestState<R> = {
|
|
32
43
|
context: Context.merge(context, fiber.context),
|
|
33
44
|
};
|
|
34
45
|
const exit = yield* Effect.exit(authCall((signal) => requests.run(state, () => request(signal))));
|
|
35
46
|
if (state.cause !== undefined) {
|
|
36
47
|
return yield* Effect.failCause(state.cause);
|
|
37
48
|
}
|
|
49
|
+
if (state.refusal !== undefined) {
|
|
50
|
+
return yield* Effect.fail(state.refusal);
|
|
51
|
+
}
|
|
38
52
|
return yield* exit;
|
|
39
53
|
}),
|
|
40
54
|
),
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Config, Effect, Layer, Option, Redacted } from "effect";
|
|
1
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
+
import { Config, Effect, Layer, Option, Redacted, type Scope } from "effect";
|
|
3
3
|
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
4
|
+
import type { Store } from "@shivaedev/rate-limit/Store.ts";
|
|
4
5
|
import type { AccountRoleSeed } from "#server/better-auth/accountRoleSeed.ts";
|
|
5
6
|
import { type BearerSessionsOptions, withBearerSessions } from "#server/better-auth/adapters/bearerSessions.ts";
|
|
6
7
|
import { PEER_IP_HEADER } from "#server/better-auth/adapters/clientIp.ts";
|
|
@@ -11,6 +12,7 @@ import { type BetterAuthHardeningOptions, withHardening } from "#server/better-a
|
|
|
11
12
|
import { hookRuntime } from "#server/better-auth/adapters/hookRuntime.ts";
|
|
12
13
|
import { mountedSessions } from "#server/better-auth/adapters/mountedSessions.ts";
|
|
13
14
|
import { passwordResetOptions } from "#server/better-auth/adapters/passwordResetOptions.ts";
|
|
15
|
+
import { providerOnlyOptions } from "#server/better-auth/adapters/providerOnlyOptions.ts";
|
|
14
16
|
import { rateLimitStorage } from "#server/better-auth/adapters/rateLimitStorage.ts";
|
|
15
17
|
import { roleSeedOptions } from "#server/better-auth/adapters/roleSeedOptions.ts";
|
|
16
18
|
import { signInPolicyOptions } from "#server/better-auth/adapters/signInPolicyOptions.ts";
|
|
@@ -22,25 +24,32 @@ import { AuthRouteHandler, mountRoutes } from "#server/better-auth/mountRoutes.t
|
|
|
22
24
|
import type { BetterAuthPasswordReset } from "#server/better-auth/PasswordReset.ts";
|
|
23
25
|
import { revokeUnadmitted } from "#server/better-auth/revokeUnadmitted.ts";
|
|
24
26
|
import { fromStorage, type PolicyStorage, type SignInPolicy, signInGate } from "#server/better-auth/signInGate.ts";
|
|
27
|
+
import { UndeclaredDefaultRole } from "#server/better-auth/UndeclaredDefaultRole.ts";
|
|
25
28
|
import { providerFailure } from "#server/providerFailure.ts";
|
|
29
|
+
import { acquireAuth } from "./acquire.ts";
|
|
26
30
|
import { authRouteHandler } from "./routeHandler.ts";
|
|
27
31
|
|
|
28
32
|
export type BetterAuthMountOptions<E = never, R = never> = {
|
|
29
33
|
readonly bearerSessions?: BearerSessionsOptions | undefined;
|
|
30
34
|
readonly databaseHooks?: BetterAuthDatabaseHooks<R> | undefined;
|
|
31
35
|
readonly emails?: BetterAuthEmails<R> | undefined;
|
|
36
|
+
readonly enabledPaths?: readonly string[];
|
|
32
37
|
readonly hardening?: BetterAuthHardeningOptions;
|
|
33
38
|
readonly onPasswordReset?: BetterAuthPasswordReset<R> | undefined;
|
|
39
|
+
readonly preset?: "provider-only";
|
|
34
40
|
readonly signIn?: SignInPolicy<E, R> | undefined;
|
|
35
41
|
} & (
|
|
36
42
|
| { readonly roles?: undefined; readonly roleSeed?: undefined }
|
|
37
43
|
| (StoredRoleOptions & { readonly roles: RoleSet; readonly roleSeed?: Effect.Effect<AccountRoleSeed<E>, E, R> })
|
|
38
44
|
);
|
|
39
45
|
|
|
40
|
-
|
|
46
|
+
const mountAuth = Effect.fn("Identity.mountAuth")(function* <const TOptions extends BetterAuthOptions, E = never, R = never>(
|
|
41
47
|
options: TOptions,
|
|
42
48
|
mount: BetterAuthMountOptions<E, R> = {},
|
|
43
49
|
) {
|
|
50
|
+
if (mount.roles !== undefined) {
|
|
51
|
+
yield* mount.roles.resolve(mount.defaultRole).pipe(Effect.mapError(() => new UndeclaredDefaultRole({ role: mount.defaultRole })));
|
|
52
|
+
}
|
|
44
53
|
const secret = options.secret ?? Redacted.value(yield* Config.Redacted("BETTER_AUTH_SECRET"));
|
|
45
54
|
const publicUrl = yield* Config.URL("PUBLIC_URL").pipe(Config.option);
|
|
46
55
|
const origin = Option.map(publicUrl, (url) => url.origin);
|
|
@@ -59,10 +68,14 @@ export const betterAuthMount = Effect.fn("Identity.betterAuthMount")(function* <
|
|
|
59
68
|
const gated = yield* signInPolicyOptions(configured, gate, (): Promise<PolicyStorage> => auth.$context);
|
|
60
69
|
const seed = mount.roleSeed === undefined ? undefined : yield* mount.roleSeed;
|
|
61
70
|
const seeded = roleSeedOptions(gate.active ? { ...configured, ...gated } : configured, seed);
|
|
71
|
+
const base = { ...configured, databaseHooks: seeded.databaseHooks };
|
|
72
|
+
const preset = mount.preset === "provider-only" ? providerOnlyOptions(base, mount.enabledPaths) : base;
|
|
62
73
|
const rateLimit = options.rateLimit;
|
|
74
|
+
const prefix = `/${(options.basePath || "/api/auth").replace(/^\/|\/+$/gu, "")}` as const;
|
|
75
|
+
const basePath = prefix === "/" ? "" : prefix;
|
|
63
76
|
const customStorage = yield* rateLimitStorage;
|
|
64
|
-
const auth =
|
|
65
|
-
...withHardening(withBearerSessions(
|
|
77
|
+
const { auth, profiles } = yield* acquireAuth({
|
|
78
|
+
...withHardening(withBearerSessions(preset, mount.bearerSessions !== undefined), mount.hardening),
|
|
66
79
|
advanced: {
|
|
67
80
|
useSecureCookies: Option.isSome(publicUrl) && publicUrl.value.protocol === "https:",
|
|
68
81
|
...options.advanced,
|
|
@@ -78,7 +91,6 @@ export const betterAuthMount = Effect.fn("Identity.betterAuthMount")(function* <
|
|
|
78
91
|
allowedHosts: ["127.0.0.1:*", "localhost:*"],
|
|
79
92
|
protocol: "http" as const,
|
|
80
93
|
})),
|
|
81
|
-
databaseHooks: seeded.databaseHooks,
|
|
82
94
|
rateLimit: {
|
|
83
95
|
...rateLimit,
|
|
84
96
|
customStorage,
|
|
@@ -92,7 +104,9 @@ export const betterAuthMount = Effect.fn("Identity.betterAuthMount")(function* <
|
|
|
92
104
|
const authRoutes = mountRoutes.pipe(
|
|
93
105
|
Layer.provide(
|
|
94
106
|
Layer.succeed(AuthRouteHandler, {
|
|
107
|
+
basePath,
|
|
95
108
|
handle: authRouteHandler(auth, {
|
|
109
|
+
basePath,
|
|
96
110
|
bearerSessions: mount.bearerSessions,
|
|
97
111
|
clientIpHeader,
|
|
98
112
|
ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet,
|
|
@@ -115,5 +129,22 @@ export const betterAuthMount = Effect.fn("Identity.betterAuthMount")(function* <
|
|
|
115
129
|
const revoke = revokeUnadmitted(gate, () => auth.$context);
|
|
116
130
|
const lookupSession: unknown = Reflect.get(auth.api, "getSession");
|
|
117
131
|
const sessions = mountedSessions(lookupSession, admit, mount.roles);
|
|
118
|
-
return { admitsUser, admittedSessions: admit, auth, revokeUnadmitted: revoke, routes: authRoutes, sessions };
|
|
132
|
+
return { admitsUser, admittedSessions: admit, auth, profiles, revokeUnadmitted: revoke, routes: authRoutes, sessions };
|
|
119
133
|
});
|
|
134
|
+
|
|
135
|
+
type Mounted<TOptions extends BetterAuthOptions, E, R> = ReturnType<typeof mountAuth<TOptions, E, R>>;
|
|
136
|
+
|
|
137
|
+
export function betterAuthMount<const TOptions extends BetterAuthOptions, E = never, R = never>(
|
|
138
|
+
options: TOptions,
|
|
139
|
+
mount?: BetterAuthMountOptions<E, R> & { readonly emails?: undefined },
|
|
140
|
+
): Effect.Effect<Effect.Success<Mounted<TOptions, E, R>>, Effect.Error<Mounted<TOptions, E, R>>, R | Scope.Scope | Store>;
|
|
141
|
+
export function betterAuthMount<const TOptions extends BetterAuthOptions, E = never, R = never>(
|
|
142
|
+
options: TOptions,
|
|
143
|
+
mount: BetterAuthMountOptions<E, R>,
|
|
144
|
+
): Mounted<TOptions, E, R>;
|
|
145
|
+
export function betterAuthMount<const TOptions extends BetterAuthOptions, E = never, R = never>(
|
|
146
|
+
options: TOptions,
|
|
147
|
+
mount: BetterAuthMountOptions<E, R> = {},
|
|
148
|
+
) {
|
|
149
|
+
return mountAuth(options, mount);
|
|
150
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AuthContext } from "better-auth";
|
|
2
|
-
import { Effect, Layer, Option, Schema } from "effect";
|
|
2
|
+
import { Clock, Effect, Layer, Option, Schema } from "effect";
|
|
3
3
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
4
4
|
import { OauthGrant, OauthGrants } from "#server/oauthGrants.ts";
|
|
5
5
|
|
|
@@ -51,30 +51,40 @@ export function betterAuthOauthGrants(options: {
|
|
|
51
51
|
});
|
|
52
52
|
return yield* Schema.decodeUnknownEffect(Schema.Array(OauthGrant))(consents).pipe(Effect.mapError(unavailable));
|
|
53
53
|
}),
|
|
54
|
-
|
|
54
|
+
resolveGrant: Effect.fn("OauthGrants.resolveGrant")(function* (grantId: string, userId: string, clientId: string) {
|
|
55
|
+
const now = yield* Clock.currentTimeMillis;
|
|
55
56
|
const subject = yield* Effect.tryPromise({
|
|
56
57
|
catch: unavailable,
|
|
57
58
|
try: async () => {
|
|
58
59
|
const { adapter, internalAdapter } = await auth.$context;
|
|
59
60
|
const user = await internalAdapter.findUserById(userId);
|
|
60
|
-
if (user === null
|
|
61
|
+
if (user === null) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
const banExpires: unknown = Reflect.get(user, "banExpires");
|
|
65
|
+
if (Reflect.get(user, "banned") === true && !(banExpires instanceof Date && banExpires.getTime() < now)) {
|
|
61
66
|
return null;
|
|
62
67
|
}
|
|
63
68
|
const consent = await adapter.findOne({
|
|
64
69
|
model: "oauthConsent",
|
|
65
70
|
where: [
|
|
71
|
+
{ field: "id", value: grantId },
|
|
66
72
|
{ field: "userId", value: userId },
|
|
67
73
|
{ field: "clientId", value: clientId },
|
|
68
74
|
],
|
|
69
75
|
});
|
|
70
|
-
return consent === null ? null : user;
|
|
76
|
+
return consent === null ? null : { consent, user };
|
|
71
77
|
},
|
|
72
78
|
});
|
|
73
|
-
if (subject === null || !(yield* admitsUser(subject.id))) {
|
|
79
|
+
if (subject === null || !(yield* admitsUser(subject.user.id))) {
|
|
74
80
|
return Option.none();
|
|
75
81
|
}
|
|
76
|
-
const role: unknown = Reflect.get(subject, "role");
|
|
77
|
-
|
|
82
|
+
const role: unknown = Reflect.get(subject.user, "role");
|
|
83
|
+
const grant = yield* Schema.decodeUnknownEffect(OauthGrant)(subject.consent).pipe(Effect.mapError(unavailable));
|
|
84
|
+
return Option.some({
|
|
85
|
+
scopes: grant.scopes,
|
|
86
|
+
user: { email: subject.user.email, id: subject.user.id, name: subject.user.name, ...(typeof role === "string" ? { role } : {}) },
|
|
87
|
+
});
|
|
78
88
|
}),
|
|
79
89
|
revokeAllClients: (userId) => revoke(userId),
|
|
80
90
|
revokeClient: (userId, clientId) => revoke(userId, clientId),
|
|
@@ -1,11 +1,41 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type OAuthClaimExtensionInput,
|
|
3
|
+
type OAuthOptions,
|
|
4
|
+
oauthProvider,
|
|
5
|
+
oauthProviderAuthServerMetadata,
|
|
6
|
+
type Scope,
|
|
7
|
+
} from "@better-auth/oauth-provider";
|
|
8
|
+
import { APIError } from "better-auth/api";
|
|
2
9
|
import { Effect } from "effect";
|
|
3
10
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
4
11
|
|
|
5
12
|
export type OauthResourceOptions = Omit<OAuthOptions<Scope[]>, "resources" | "clientRegistrationDefaultResources"> & { readonly resource: string };
|
|
6
13
|
|
|
14
|
+
async function grantClaims({ ctx, user, client, referenceId }: OAuthClaimExtensionInput) {
|
|
15
|
+
if (!user) {
|
|
16
|
+
return {};
|
|
17
|
+
}
|
|
18
|
+
const consent = await ctx.context.adapter.findOne<{ id: string }>({
|
|
19
|
+
model: "oauthConsent",
|
|
20
|
+
where: [
|
|
21
|
+
{ field: "userId", value: user.id },
|
|
22
|
+
{ field: "clientId", value: client.clientId },
|
|
23
|
+
{ field: "referenceId", value: referenceId ?? null },
|
|
24
|
+
],
|
|
25
|
+
});
|
|
26
|
+
if (consent === null) {
|
|
27
|
+
throw new APIError("BAD_REQUEST", { error: "invalid_grant", "error_description": "Consent is required" });
|
|
28
|
+
}
|
|
29
|
+
return { "grant_id": consent.id };
|
|
30
|
+
}
|
|
31
|
+
|
|
7
32
|
export function betterAuthOauthProvider({ resource, ...options }: OauthResourceOptions): ReturnType<typeof oauthProvider> {
|
|
8
|
-
return oauthProvider({
|
|
33
|
+
return oauthProvider({
|
|
34
|
+
...options,
|
|
35
|
+
clientRegistrationDefaultResources: [resource],
|
|
36
|
+
extensions: [...(options.extensions ?? []), { claims: { accessToken: grantClaims } }],
|
|
37
|
+
resources: [resource],
|
|
38
|
+
});
|
|
9
39
|
}
|
|
10
40
|
|
|
11
41
|
export const oauthAuthorizationMetadata = Effect.fn("Identity.oauthAuthorizationMetadata")(function* (
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AuthContext } from "better-auth";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import type { UserProfile, UserProfileStorage } from "#server/better-auth/userProfiles.ts";
|
|
4
|
+
import { providerFailure } from "#server/providerFailure.ts";
|
|
5
|
+
|
|
6
|
+
export function profileStorage({ adapter }: { readonly adapter: Pick<AuthContext["adapter"], "findMany"> }): UserProfileStorage {
|
|
7
|
+
return {
|
|
8
|
+
findByIds: (userIds) =>
|
|
9
|
+
Effect.tryPromise(() =>
|
|
10
|
+
adapter.findMany<UserProfile>({
|
|
11
|
+
limit: userIds.length,
|
|
12
|
+
model: "user",
|
|
13
|
+
select: ["id", "name", "image"],
|
|
14
|
+
where: [{ field: "id", operator: "in", value: [...userIds] }],
|
|
15
|
+
}),
|
|
16
|
+
).pipe(Effect.catch((error) => providerFailure(error.cause))),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { BetterAuthOptions, GenericEndpointContext } from "better-auth";
|
|
2
|
+
|
|
3
|
+
const closedPaths = [
|
|
4
|
+
"/sign-in/email",
|
|
5
|
+
"/sign-up/email",
|
|
6
|
+
"/request-password-reset",
|
|
7
|
+
"/reset-password",
|
|
8
|
+
"/change-password",
|
|
9
|
+
"/verify-password",
|
|
10
|
+
"/change-email",
|
|
11
|
+
"/send-verification-email",
|
|
12
|
+
"/verify-email",
|
|
13
|
+
"/sign-in/magic-link",
|
|
14
|
+
"/magic-link/verify",
|
|
15
|
+
"/admin/set-role",
|
|
16
|
+
"/admin/get-user",
|
|
17
|
+
"/admin/create-user",
|
|
18
|
+
"/admin/update-user",
|
|
19
|
+
"/admin/list-users",
|
|
20
|
+
"/admin/list-user-sessions",
|
|
21
|
+
"/admin/unban-user",
|
|
22
|
+
"/admin/ban-user",
|
|
23
|
+
"/admin/impersonate-user",
|
|
24
|
+
"/admin/stop-impersonating",
|
|
25
|
+
"/admin/revoke-user-session",
|
|
26
|
+
"/admin/revoke-user-sessions",
|
|
27
|
+
"/admin/remove-user",
|
|
28
|
+
"/admin/set-user-password",
|
|
29
|
+
"/admin/has-permission",
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
type AccountHooks = NonNullable<NonNullable<BetterAuthOptions["databaseHooks"]>["account"]>;
|
|
33
|
+
type AccountBefore = NonNullable<NonNullable<AccountHooks["create"]>["before"]>;
|
|
34
|
+
type Before<T> = (data: T, context: GenericEndpointContext | null) => ReturnType<AccountBefore>;
|
|
35
|
+
|
|
36
|
+
function withoutTokens<T extends object>(before?: Before<T>) {
|
|
37
|
+
return async (data: T, context: GenericEndpointContext | null) => {
|
|
38
|
+
const result = await before?.(data, context);
|
|
39
|
+
if (result === false) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
return { data: { ...data, ...(typeof result === "object" ? result.data : {}), accessToken: null, idToken: null, refreshToken: null } };
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function providerOnlyOptions<TOptions extends BetterAuthOptions>(options: TOptions, enabledPaths: readonly string[] = []): TOptions {
|
|
47
|
+
const account = options.databaseHooks?.account;
|
|
48
|
+
return {
|
|
49
|
+
...options,
|
|
50
|
+
account: { ...options.account, storeAccountCookie: false },
|
|
51
|
+
databaseHooks: {
|
|
52
|
+
...options.databaseHooks,
|
|
53
|
+
account: {
|
|
54
|
+
...account,
|
|
55
|
+
create: { ...account?.create, before: withoutTokens(account?.create?.before) },
|
|
56
|
+
update: { ...account?.update, before: withoutTokens(account?.update?.before) },
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
disabledPaths: [...(options.disabledPaths ?? []), ...closedPaths.filter((path) => !enabledPaths.includes(path))],
|
|
60
|
+
emailAndPassword: { ...options.emailAndPassword, enabled: false },
|
|
61
|
+
session: { ...options.session, cookieCache: { ...options.session?.cookieCache, enabled: false } },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type Cause, Effect } from "effect";
|
|
2
|
+
import * as HttpStatus from "effect/http/HttpStatus";
|
|
2
3
|
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
3
4
|
import { type BearerSessionsOptions, cookieSessionResponse, hasSessionCookie, sessionHeaders } from "#server/better-auth/adapters/bearerSessions.ts";
|
|
5
|
+
import type { HookRefusal } from "#server/better-auth/adapters/hookRuntime.ts";
|
|
4
6
|
import { sessionPermissions } from "#server/better-auth/sessionPermissions.ts";
|
|
5
7
|
|
|
6
8
|
export interface MountedAuth {
|
|
@@ -8,20 +10,21 @@ export interface MountedAuth {
|
|
|
8
10
|
readonly handler: (request: Request) => Promise<Response>;
|
|
9
11
|
}
|
|
10
12
|
export interface MountRouteOptions {
|
|
13
|
+
readonly basePath?: string | undefined;
|
|
11
14
|
readonly bearerSessions?: BearerSessionsOptions | undefined;
|
|
12
15
|
readonly clientIpHeader: string;
|
|
13
16
|
readonly ipv6Subnet?: number | undefined;
|
|
14
17
|
readonly roles?: RoleSet | undefined;
|
|
15
|
-
readonly runRequest?: (<A>(request: (signal: AbortSignal) => Promise<A>) => Effect.Effect<A, Cause.UnknownError>) | undefined;
|
|
18
|
+
readonly runRequest?: (<A>(request: (signal: AbortSignal) => Promise<A>) => Effect.Effect<A, Cause.UnknownError | HookRefusal>) | undefined;
|
|
16
19
|
readonly trustedProxy?: string | undefined;
|
|
17
20
|
}
|
|
18
|
-
function replacesSession(request: Request, reply: Response, native: boolean) {
|
|
21
|
+
function replacesSession(request: Request, reply: Response, native: boolean, basePath: string) {
|
|
19
22
|
return (
|
|
20
23
|
native
|
|
21
24
|
&& reply.ok
|
|
22
25
|
&& reply.headers.has("set-auth-token")
|
|
23
26
|
&& request.headers.has("authorization")
|
|
24
|
-
&& new URL(request.url).pathname.startsWith(
|
|
27
|
+
&& new URL(request.url).pathname.startsWith(`${basePath}/sign-in/`)
|
|
25
28
|
);
|
|
26
29
|
}
|
|
27
30
|
async function providerResponse(auth: MountedAuth, web: Request, options: MountRouteOptions) {
|
|
@@ -34,8 +37,9 @@ async function providerResponse(auth: MountedAuth, web: Request, options: MountR
|
|
|
34
37
|
const native = options.bearerSessions.origins.includes(web.headers.get("origin") ?? "") && !hasSessionCookie(web.headers, cookieName);
|
|
35
38
|
const request = new Request(web, { headers });
|
|
36
39
|
const reply = await auth.handler(request);
|
|
37
|
-
|
|
38
|
-
|
|
40
|
+
const basePath = options.basePath ?? "/api/auth";
|
|
41
|
+
if (replacesSession(request, reply, native, basePath)) {
|
|
42
|
+
const revoked = await auth.handler(new Request(new URL(`${basePath}/sign-out`, web.url), { body: "{}", headers, method: "POST" }));
|
|
39
43
|
await revoked.body?.cancel();
|
|
40
44
|
if (!revoked.ok) {
|
|
41
45
|
throw new Error("Session replacement failed");
|
|
@@ -44,13 +48,17 @@ async function providerResponse(auth: MountedAuth, web: Request, options: MountR
|
|
|
44
48
|
return native ? reply : cookieSessionResponse(reply);
|
|
45
49
|
}
|
|
46
50
|
export const response = Effect.fnUntraced(function* (auth: MountedAuth, web: Request, options: MountRouteOptions) {
|
|
47
|
-
const sessionRequest = options.roles !== undefined && new URL(web.url).pathname === "/api/auth/get-session
|
|
51
|
+
const sessionRequest = options.roles !== undefined && new URL(web.url).pathname === `${options.basePath ?? "/api/auth"}/get-session`;
|
|
48
52
|
const url = new URL(web.url);
|
|
49
53
|
if (sessionRequest) {
|
|
50
54
|
url.searchParams.set("disableCookieCache", "true");
|
|
51
55
|
}
|
|
52
56
|
const request = sessionRequest ? new Request(url, web) : web;
|
|
53
57
|
const runRequest = options.runRequest ?? Effect.tryPromise;
|
|
54
|
-
const reply = yield* runRequest((signal) => providerResponse(auth, new Request(request, { signal }), options))
|
|
58
|
+
const reply = yield* runRequest((signal) => providerResponse(auth, new Request(request, { signal }), options)).pipe(
|
|
59
|
+
Effect.catchTag("HookRefusal", ({ code, message }) =>
|
|
60
|
+
Effect.succeed<Response>(Response.json({ code, message }, { status: HttpStatus.fromLiteral("Forbidden") })),
|
|
61
|
+
),
|
|
62
|
+
);
|
|
55
63
|
return sessionRequest && reply.ok && options.roles !== undefined ? yield* sessionPermissions(reply, options.roles) : reply;
|
|
56
64
|
});
|
|
@@ -2,6 +2,7 @@ import type { BetterAuthOptions } from "better-auth";
|
|
|
2
2
|
import { APIError } from "better-auth/api";
|
|
3
3
|
import { Effect, Exit } from "effect";
|
|
4
4
|
import { redact } from "@shivaedev/errors/redact.ts";
|
|
5
|
+
import { authRefusals } from "#authRefusal.ts";
|
|
5
6
|
import type { AccountRoleSeed } from "#server/better-auth/accountRoleSeed.ts";
|
|
6
7
|
|
|
7
8
|
export function roleSeedOptions<E>(options: BetterAuthOptions, seed: AccountRoleSeed<E> | undefined): BetterAuthOptions {
|
|
@@ -28,7 +29,7 @@ export function roleSeedOptions<E>(options: BetterAuthOptions, seed: AccountRole
|
|
|
28
29
|
{ signal: endpoint?.request?.signal },
|
|
29
30
|
);
|
|
30
31
|
if (Exit.isFailure(exit)) {
|
|
31
|
-
throw new APIError("SERVICE_UNAVAILABLE", { code:
|
|
32
|
+
throw new APIError("SERVICE_UNAVAILABLE", { code: authRefusals.roleSeedFailed.wire, message: "Sign-in is temporarily unavailable" });
|
|
32
33
|
}
|
|
33
34
|
return result;
|
|
34
35
|
},
|