@shivaedev/identity 0.14.0 → 0.16.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 +20 -0
- package/README.md +66 -2
- package/dist/server/better-auth/adapters/effectHookOptions.d.ts +6 -0
- package/dist/server/better-auth/adapters/effectHookOptions.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/effectHookOptions.js +62 -0
- package/dist/server/better-auth/adapters/effectHookOptions.js.map +1 -0
- package/dist/server/better-auth/adapters/emailOptions.d.ts +8 -0
- package/dist/server/better-auth/adapters/emailOptions.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/emailOptions.js +43 -0
- package/dist/server/better-auth/adapters/emailOptions.js.map +1 -0
- package/dist/server/better-auth/adapters/hookRuntime.d.ts +7 -0
- package/dist/server/better-auth/adapters/hookRuntime.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/hookRuntime.js +37 -0
- package/dist/server/better-auth/adapters/hookRuntime.js.map +1 -0
- package/dist/server/better-auth/adapters/response.d.ts +23 -0
- package/dist/server/better-auth/adapters/response.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/response.js +41 -0
- package/dist/server/better-auth/adapters/response.js.map +1 -0
- package/dist/server/better-auth/databaseHooks.d.ts +12 -0
- package/dist/server/better-auth/databaseHooks.d.ts.map +1 -0
- package/dist/server/better-auth/databaseHooks.js +2 -0
- package/dist/server/better-auth/databaseHooks.js.map +1 -0
- package/dist/server/better-auth/emailWindow.d.ts +3 -0
- package/dist/server/better-auth/emailWindow.d.ts.map +1 -0
- package/dist/server/better-auth/emailWindow.js +23 -0
- package/dist/server/better-auth/emailWindow.js.map +1 -0
- package/dist/server/better-auth/emails.d.ts +31 -0
- package/dist/server/better-auth/emails.d.ts.map +1 -0
- package/dist/server/better-auth/emails.js +2 -0
- package/dist/server/better-auth/emails.js.map +1 -0
- package/dist/server/better-auth/mount.d.ts +4 -0
- package/dist/server/better-auth/mount.d.ts.map +1 -1
- package/dist/server/better-auth/mount.js +7 -1
- package/dist/server/better-auth/mount.js.map +1 -1
- package/dist/server/better-auth/mountRoutes.d.ts +1 -20
- package/dist/server/better-auth/mountRoutes.d.ts.map +1 -1
- package/dist/server/better-auth/mountRoutes.js +2 -39
- package/dist/server/better-auth/mountRoutes.js.map +1 -1
- package/dist/server/better-auth/testing.d.ts +18 -0
- package/dist/server/better-auth/testing.d.ts.map +1 -1
- package/dist/server/better-auth/testing.js +6 -2
- package/dist/server/better-auth/testing.js.map +1 -1
- package/package.json +10 -10
- package/src/server/better-auth/adapters/effectHookOptions.ts +87 -0
- package/src/server/better-auth/adapters/emailOptions.ts +59 -0
- package/src/server/better-auth/adapters/hookRuntime.ts +41 -0
- package/src/server/better-auth/adapters/response.ts +56 -0
- package/src/server/better-auth/databaseHooks.ts +15 -0
- package/src/server/better-auth/emailWindow.ts +27 -0
- package/src/server/better-auth/emails.ts +23 -0
- package/src/server/better-auth/mount.ts +11 -1
- package/src/server/better-auth/mountRoutes.ts +2 -53
- package/src/server/better-auth/testing.ts +10 -2
|
@@ -1,23 +1,4 @@
|
|
|
1
1
|
import { HttpRouter } from "effect/http";
|
|
2
|
-
import type
|
|
3
|
-
import { type BearerSessionsOptions } from "#server/better-auth/bearerSessions.ts";
|
|
4
|
-
interface MountedAuth {
|
|
5
|
-
readonly $context: Promise<{
|
|
6
|
-
readonly authCookies: {
|
|
7
|
-
readonly sessionToken: {
|
|
8
|
-
readonly name: string;
|
|
9
|
-
};
|
|
10
|
-
};
|
|
11
|
-
}>;
|
|
12
|
-
readonly handler: (request: Request) => Promise<Response>;
|
|
13
|
-
}
|
|
14
|
-
interface MountRouteOptions {
|
|
15
|
-
readonly bearerSessions?: BearerSessionsOptions | undefined;
|
|
16
|
-
readonly clientIpHeader: string;
|
|
17
|
-
readonly ipv6Subnet?: number | undefined;
|
|
18
|
-
readonly roles?: RoleSet | undefined;
|
|
19
|
-
readonly trustedProxy?: string | undefined;
|
|
20
|
-
}
|
|
2
|
+
import { type MountedAuth, type MountRouteOptions } from "#server/better-auth/adapters/response.ts";
|
|
21
3
|
export declare function mountRoutes(auth: MountedAuth, options: MountRouteOptions): import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter>;
|
|
22
|
-
export {};
|
|
23
4
|
//# sourceMappingURL=mountRoutes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mountRoutes.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/mountRoutes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAyC,MAAM,aAAa,CAAC;AAEhF,OAAO,
|
|
1
|
+
{"version":3,"file":"mountRoutes.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/mountRoutes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAyC,MAAM,aAAa,CAAC;AAEhF,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAY,MAAM,0CAA0C,CAAC;AAI9G,wBAAgB,WAAW,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,iBAAiB,qEA4BxE"}
|
|
@@ -1,46 +1,9 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
3
3
|
import * as HttpStatus from "effect/http/HttpStatus";
|
|
4
|
-
import {
|
|
4
|
+
import { response } from "#server/better-auth/adapters/response.ts";
|
|
5
5
|
import { providerFailure } from "#server/providerFailure.ts";
|
|
6
6
|
import { clientIpHeaders } from "./clientIp.js";
|
|
7
|
-
import { sessionPermissions } from "./sessionPermissions.js";
|
|
8
|
-
function replacesSession(request, response, native) {
|
|
9
|
-
return (native
|
|
10
|
-
&& response.ok
|
|
11
|
-
&& response.headers.has("set-auth-token")
|
|
12
|
-
&& request.headers.has("authorization")
|
|
13
|
-
&& new URL(request.url).pathname.startsWith("/api/auth/sign-in/"));
|
|
14
|
-
}
|
|
15
|
-
async function providerResponse(auth, web, options) {
|
|
16
|
-
if (options.bearerSessions === undefined) {
|
|
17
|
-
return auth.handler(web);
|
|
18
|
-
}
|
|
19
|
-
const { authCookies } = await auth.$context;
|
|
20
|
-
const cookieName = authCookies.sessionToken.name;
|
|
21
|
-
const headers = sessionHeaders(web.headers, cookieName);
|
|
22
|
-
const native = options.bearerSessions.origins.includes(web.headers.get("origin") ?? "") && !hasSessionCookie(web.headers, cookieName);
|
|
23
|
-
const request = new Request(web, { headers });
|
|
24
|
-
const response = await auth.handler(request);
|
|
25
|
-
if (replacesSession(request, response, native)) {
|
|
26
|
-
const revoked = await auth.handler(new Request(new URL("/api/auth/sign-out", web.url), { body: "{}", headers, method: "POST" }));
|
|
27
|
-
await revoked.body?.cancel();
|
|
28
|
-
if (!revoked.ok) {
|
|
29
|
-
throw new Error("Session replacement failed");
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return native ? response : cookieSessionResponse(response);
|
|
33
|
-
}
|
|
34
|
-
const authResponse = Effect.fnUntraced(function* (auth, web, options) {
|
|
35
|
-
const sessionRequest = options.roles !== undefined && new URL(web.url).pathname === "/api/auth/get-session";
|
|
36
|
-
const url = new URL(web.url);
|
|
37
|
-
if (sessionRequest) {
|
|
38
|
-
url.searchParams.set("disableCookieCache", "true");
|
|
39
|
-
}
|
|
40
|
-
const request = sessionRequest ? new Request(url, web) : web;
|
|
41
|
-
const response = yield* Effect.tryPromise((signal) => providerResponse(auth, new Request(request, { signal }), options));
|
|
42
|
-
return sessionRequest && response.ok && options.roles !== undefined ? yield* sessionPermissions(response, options.roles) : response;
|
|
43
|
-
});
|
|
44
7
|
export function mountRoutes(auth, options) {
|
|
45
8
|
const setClientIp = clientIpHeaders(options);
|
|
46
9
|
return HttpRouter.use((router) => router.add("*", "/api/auth/*", (request) => Effect.gen(function* () {
|
|
@@ -50,7 +13,7 @@ export function mountRoutes(auth, options) {
|
|
|
50
13
|
"auth.rate_limit.address": clientIp.address,
|
|
51
14
|
"auth.rate_limit.address_source": clientIp.source,
|
|
52
15
|
});
|
|
53
|
-
return HttpServerResponse.fromWeb(yield*
|
|
16
|
+
return HttpServerResponse.fromWeb(yield* response(auth, web, options).pipe(Effect.catchTag("Forbidden", (error) => Effect.succeed(Response.json({ message: error.message }, { status: HttpStatus.fromLiteral("Forbidden") }))), Effect.catch(providerFailure)));
|
|
54
17
|
}).pipe(Effect.catch(() => Effect.succeed(HttpServerResponse.text("Authentication is temporarily unavailable", { status: HttpStatus.fromLiteral("ServiceUnavailable") }))))));
|
|
55
18
|
}
|
|
56
19
|
//# sourceMappingURL=mountRoutes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mountRoutes.js","sourceRoot":"","sources":["../../../src/server/better-auth/mountRoutes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,KAAK,UAAU,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"mountRoutes.js","sourceRoot":"","sources":["../../../src/server/better-auth/mountRoutes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,KAAK,UAAU,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAA4C,QAAQ,EAAE,MAAM,0CAA0C,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,MAAM,UAAU,WAAW,CAAC,IAAiB,EAAE,OAA0B;IACxE,MAAM,WAAW,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE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export declare const signInAgain: (auth: {
|
|
38
|
+
readonly $context: Promise<TestContext & AccountContext & Pick<AuthContext, "sessionConfig">>;
|
|
39
|
+
}, userId: string) => Effect.Effect<{
|
|
40
|
+
user: import("better-auth").User;
|
|
41
|
+
headers: Headers;
|
|
42
|
+
cookies: import("better-auth/plugins").TestCookie[];
|
|
43
|
+
token: string;
|
|
44
|
+
session: {
|
|
45
|
+
id: string;
|
|
46
|
+
createdAt: Date;
|
|
47
|
+
updatedAt: Date;
|
|
48
|
+
userId: string;
|
|
49
|
+
token: string;
|
|
50
|
+
ipAddress?: string | null | undefined;
|
|
51
|
+
userAgent?: string | null | undefined;
|
|
52
|
+
expiresAt: Date;
|
|
53
|
+
};
|
|
54
|
+
}, never, never>;
|
|
37
55
|
export declare function storedProviderAccounts(auth: {
|
|
38
56
|
readonly $context: Promise<AccountContext>;
|
|
39
57
|
}, userId: string): Promise<{
|
|
@@ -1 +1 @@
|
|
|
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;AAC/C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAS,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEvC,KAAK,WAAW,GAAG,UAAU,CAAC,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AAC/E,KAAK,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAC;AAE3D,eAAO,MAAM,YAAY;uBACG,OAAO,CAAC,WAAW,GAAG,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,eAAe,CAAC,CAAC;;;;;;;;;;gCAKxE,SAAS;QAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA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;;gBAO9H,CAAC"}
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import { Clock, Effect } from "effect";
|
|
2
2
|
export const signedInUser = Effect.fnUntraced(function* (auth, { providerAccounts = [], ...fields }) {
|
|
3
|
-
const { test, internalAdapter
|
|
3
|
+
const { test, internalAdapter } = yield* Effect.promise(() => auth.$context);
|
|
4
4
|
const user = yield* Effect.promise(() => test.saveUser(test.createUser(fields)));
|
|
5
5
|
for (const { providerId, accountId } of providerAccounts) {
|
|
6
6
|
yield* Effect.promise(() => internalAdapter.createAccount({ accountId, providerId, userId: user.id }));
|
|
7
7
|
}
|
|
8
|
+
return yield* signInAgain(auth, user.id);
|
|
9
|
+
});
|
|
10
|
+
export const signInAgain = Effect.fnUntraced(function* (auth, userId) {
|
|
11
|
+
const { test, internalAdapter, sessionConfig } = yield* Effect.promise(() => auth.$context);
|
|
8
12
|
const now = yield* Clock.currentTimeMillis;
|
|
9
|
-
const login = yield* Effect.promise(() => test.login({ userId
|
|
13
|
+
const login = yield* Effect.promise(() => test.login({ userId }));
|
|
10
14
|
const expiresAt = new Date(now + sessionConfig.expiresIn * 1000);
|
|
11
15
|
yield* Effect.promise(() => internalAdapter.updateSession(login.token, { expiresAt }));
|
|
12
16
|
return { ...login, session: { ...login.session, expiresAt } };
|
|
@@ -1 +1 @@
|
|
|
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;AAKvC,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EACtD,IAAuG,EACvG,EACC,gBAAgB,GAAG,EAAE,EACrB,GAAG,MAAM,EAGT;IAED,MAAM,EAAE,IAAI,EAAE,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"testing.js","sourceRoot":"","sources":["../../../src/server/better-auth/testing.ts"],"names":[],"mappings":"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E,eAAe,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnG,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACjF,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACpE,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,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,CAAC,CAAC;IAC9I,OAAO,IAAI,CAAC;AACb,CAAC,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shivaedev/identity",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "Request identity, sessions, transport trust and permission enforcement for Effect RPC servers",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"effect"
|
|
@@ -45,21 +45,21 @@
|
|
|
45
45
|
"README.md"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@shivaedev/access": "0.3.
|
|
48
|
+
"@shivaedev/access": "0.3.5",
|
|
49
49
|
"@shivaedev/changes": "0.6.0",
|
|
50
|
-
"@shivaedev/contract": "0.30.
|
|
51
|
-
"@shivaedev/errors": "0.4.
|
|
52
|
-
"@shivaedev/sql": "0.
|
|
50
|
+
"@shivaedev/contract": "0.30.1",
|
|
51
|
+
"@shivaedev/errors": "0.4.1",
|
|
52
|
+
"@shivaedev/sql": "0.30.0"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@effect/platform-node": "4.0.6",
|
|
56
56
|
"@effect/sql-pg": "4.0.6",
|
|
57
|
-
"@shivaedev/admin": "0.16.
|
|
58
|
-
"@shivaedev/quality": "0.
|
|
59
|
-
"@shivaedev/server": "0.
|
|
57
|
+
"@shivaedev/admin": "0.16.3",
|
|
58
|
+
"@shivaedev/quality": "0.53.1",
|
|
59
|
+
"@shivaedev/server": "0.16.1",
|
|
60
60
|
"@shivaedev/test": "0.12.0",
|
|
61
|
-
"@shivaedev/test-sql": "0.15.
|
|
62
|
-
"@shivaedev/test-story": "0.31.
|
|
61
|
+
"@shivaedev/test-sql": "0.15.3",
|
|
62
|
+
"@shivaedev/test-story": "0.31.4",
|
|
63
63
|
"@types/node": "24.19.2",
|
|
64
64
|
"better-auth": "1.7.12",
|
|
65
65
|
"effect": "4.0.6",
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { BetterAuthOptions, GenericEndpointContext } from "better-auth";
|
|
2
|
+
import type { Effect } from "effect";
|
|
3
|
+
import type { BetterAuthDatabaseHooks, BetterAuthHookError } from "#server/better-auth/databaseHooks.ts";
|
|
4
|
+
import type { hookRuntime } from "./hookRuntime.ts";
|
|
5
|
+
|
|
6
|
+
type SessionCreate = NonNullable<NonNullable<NonNullable<BetterAuthOptions["databaseHooks"]>["session"]>["create"]>;
|
|
7
|
+
type HookResult = Awaited<ReturnType<NonNullable<SessionCreate["before"]>>>;
|
|
8
|
+
type NativeHook<TData, TResult> = (data: TData, endpoint: GenericEndpointContext | null) => Promise<TResult>;
|
|
9
|
+
type EffectHook<TData, TResult, R> = (data: TData, endpoint: GenericEndpointContext | null) => Effect.Effect<TResult, BetterAuthHookError, R>;
|
|
10
|
+
interface Operation<TBefore, TAfter, TResult> {
|
|
11
|
+
after?: NativeHook<TAfter, void>;
|
|
12
|
+
before?: NativeHook<TBefore, TResult>;
|
|
13
|
+
}
|
|
14
|
+
interface EffectOperation<TBefore, TAfter, TResult, R> {
|
|
15
|
+
readonly after?: EffectHook<TAfter, void, R>;
|
|
16
|
+
readonly before?: EffectHook<TBefore, TResult, R>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function mergeResult<T extends HookResult>(previous: T | undefined, next: T): T | undefined {
|
|
20
|
+
if (typeof previous === "object" && typeof next === "object") {
|
|
21
|
+
return { ...next, data: { ...previous.data, ...next.data } };
|
|
22
|
+
}
|
|
23
|
+
return next === undefined || next === true ? (previous ?? next) : next;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function effectHookOptions<TOptions extends BetterAuthOptions, R>(
|
|
27
|
+
options: TOptions,
|
|
28
|
+
hooks: BetterAuthDatabaseHooks<R> | undefined,
|
|
29
|
+
runtime: Effect.Success<ReturnType<typeof hookRuntime<R>>>,
|
|
30
|
+
): TOptions {
|
|
31
|
+
function composeBefore<TData extends object, TResult extends HookResult>(hook: EffectHook<TData, TResult, R>, own?: NativeHook<TData, TResult>) {
|
|
32
|
+
return async (data: TData, endpoint: GenericEndpointContext | null) => {
|
|
33
|
+
const previous = await own?.(data, endpoint);
|
|
34
|
+
if (previous === false) {
|
|
35
|
+
return previous;
|
|
36
|
+
}
|
|
37
|
+
const input = typeof previous === "object" ? { ...data, ...previous.data } : data;
|
|
38
|
+
const next = await runtime.runHook(() => hook(input, endpoint), endpoint?.request?.signal);
|
|
39
|
+
return mergeResult(previous, next);
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function composeAfter<TData>(hook: EffectHook<TData, void, R>, own?: NativeHook<TData, void>) {
|
|
43
|
+
return async (data: TData, endpoint: GenericEndpointContext | null) => {
|
|
44
|
+
await own?.(data, endpoint);
|
|
45
|
+
await runtime.runHook(() => hook(data, endpoint), endpoint?.request?.signal);
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function operation<TBefore extends object, TAfter, TResult extends HookResult>(
|
|
49
|
+
own: Operation<TBefore, TAfter, TResult> | undefined,
|
|
50
|
+
application: EffectOperation<TBefore, TAfter, TResult, R> | undefined,
|
|
51
|
+
) {
|
|
52
|
+
return {
|
|
53
|
+
...own,
|
|
54
|
+
...(application?.before === undefined ? {} : { before: composeBefore(application.before, own?.before) }),
|
|
55
|
+
...(application?.after === undefined ? {} : { after: composeAfter(application.after, own?.after) }),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (hooks === undefined) {
|
|
59
|
+
return options;
|
|
60
|
+
}
|
|
61
|
+
const native = options.databaseHooks;
|
|
62
|
+
return {
|
|
63
|
+
...options,
|
|
64
|
+
databaseHooks: {
|
|
65
|
+
account: {
|
|
66
|
+
create: operation(native?.account?.create, hooks.account?.create),
|
|
67
|
+
delete: operation(native?.account?.delete, hooks.account?.delete),
|
|
68
|
+
update: operation(native?.account?.update, hooks.account?.update),
|
|
69
|
+
},
|
|
70
|
+
session: {
|
|
71
|
+
create: operation(native?.session?.create, hooks.session?.create),
|
|
72
|
+
delete: operation(native?.session?.delete, hooks.session?.delete),
|
|
73
|
+
update: operation(native?.session?.update, hooks.session?.update),
|
|
74
|
+
},
|
|
75
|
+
user: {
|
|
76
|
+
create: operation(native?.user?.create, hooks.user?.create),
|
|
77
|
+
delete: operation(native?.user?.delete, hooks.user?.delete),
|
|
78
|
+
update: operation(native?.user?.update, hooks.user?.update),
|
|
79
|
+
},
|
|
80
|
+
verification: {
|
|
81
|
+
create: operation(native?.verification?.create, hooks.verification?.create),
|
|
82
|
+
delete: operation(native?.verification?.delete, hooks.verification?.delete),
|
|
83
|
+
update: operation(native?.verification?.update, hooks.verification?.update),
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
+
import { Effect, Schema } from "effect";
|
|
3
|
+
import type { AuthEmail, BetterAuthEmails } from "#server/better-auth/emails.ts";
|
|
4
|
+
import { emailWindow } from "#server/better-auth/emailWindow.ts";
|
|
5
|
+
import type { hookRuntime } from "./hookRuntime.ts";
|
|
6
|
+
|
|
7
|
+
type Outgoing = { [TKind in AuthEmail["_tag"]]: Omit<Extract<AuthEmail, { readonly _tag: TKind }>, "url"> }[AuthEmail["_tag"]];
|
|
8
|
+
|
|
9
|
+
const Verification = Schema.Struct({ updateTo: Schema.optionalKey(Schema.String) });
|
|
10
|
+
|
|
11
|
+
export const emailOptions = Effect.fnUntraced(function* <TOptions extends BetterAuthOptions, R>(
|
|
12
|
+
options: TOptions,
|
|
13
|
+
emails: BetterAuthEmails<R> | undefined,
|
|
14
|
+
runtime: Effect.Success<ReturnType<typeof hookRuntime<R>>>,
|
|
15
|
+
) {
|
|
16
|
+
if (emails === undefined) {
|
|
17
|
+
return options;
|
|
18
|
+
}
|
|
19
|
+
const { routes, deliver } = emails;
|
|
20
|
+
const claim = yield* emailWindow(emails.window);
|
|
21
|
+
function send(message: Outgoing, request?: Request) {
|
|
22
|
+
const url = new URL(routes[message._tag]);
|
|
23
|
+
if ("token" in message) {
|
|
24
|
+
url.searchParams.set("token", message.token);
|
|
25
|
+
}
|
|
26
|
+
return runtime.runHook(
|
|
27
|
+
() => claim(message.user.id, message._tag).pipe(Effect.flatMap((allowed) => (allowed ? deliver({ ...message, url: url.href }) : Effect.void))),
|
|
28
|
+
request?.signal,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
...options,
|
|
33
|
+
emailAndPassword: {
|
|
34
|
+
...options.emailAndPassword,
|
|
35
|
+
enabled: options.emailAndPassword?.enabled ?? false,
|
|
36
|
+
onExistingUserSignUp: ({ user }, request) => send({ _tag: "AccountAlreadyExists", user }, request),
|
|
37
|
+
sendResetPassword: ({ user, token }, request) => send({ _tag: "ResetPassword", token, user }, request),
|
|
38
|
+
},
|
|
39
|
+
emailVerification: {
|
|
40
|
+
...options.emailVerification,
|
|
41
|
+
sendVerificationEmail: ({ user, token }, request) => {
|
|
42
|
+
const payload = token.split(".")[1] ?? "";
|
|
43
|
+
const { updateTo } = Schema.decodeUnknownSync(Schema.fromJsonString(Verification))(Buffer.from(payload, "base64url").toString("utf8"));
|
|
44
|
+
return send(
|
|
45
|
+
updateTo === undefined ? { _tag: "ConfirmAccount", token, user } : { _tag: "ConfirmNewAddress", newEmail: updateTo, token, user },
|
|
46
|
+
request,
|
|
47
|
+
);
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
user: {
|
|
51
|
+
...options.user,
|
|
52
|
+
changeEmail: {
|
|
53
|
+
...options.user?.changeEmail,
|
|
54
|
+
enabled: options.user?.changeEmail?.enabled ?? false,
|
|
55
|
+
sendChangeEmailConfirmation: ({ user, newEmail, token }, request) => send({ _tag: "ApproveEmailChange", newEmail, token, user }, request),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
} satisfies BetterAuthOptions;
|
|
59
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { APIError } from "better-auth/api";
|
|
3
|
+
import { type Cause, Context, Effect, Result } from "effect";
|
|
4
|
+
import type { BetterAuthHookError } from "#server/better-auth/databaseHooks.ts";
|
|
5
|
+
|
|
6
|
+
export const hookRuntime = Effect.fnUntraced(function* <R>() {
|
|
7
|
+
const context = yield* Effect.context<R>();
|
|
8
|
+
const requests = new AsyncLocalStorage<{ readonly context: Context.Context<R>; cause?: Cause.Cause<never> }>();
|
|
9
|
+
return {
|
|
10
|
+
runHook: async <A>(hook: () => Effect.Effect<A, BetterAuthHookError, R>, signal: AbortSignal | undefined): Promise<A> => {
|
|
11
|
+
const request = requests.getStore();
|
|
12
|
+
function remember(cause: Cause.Cause<never>) {
|
|
13
|
+
return Effect.sync(() => {
|
|
14
|
+
if (request !== undefined) {
|
|
15
|
+
request.cause = cause;
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
const result = await Effect.runPromiseWith(request?.context ?? context)(Effect.suspend(hook).pipe(Effect.result, Effect.tapCause(remember)), {
|
|
20
|
+
signal,
|
|
21
|
+
});
|
|
22
|
+
if (Result.isFailure(result)) {
|
|
23
|
+
throw new APIError("FORBIDDEN", { code: result.failure.code, message: result.failure.message });
|
|
24
|
+
}
|
|
25
|
+
return result.success;
|
|
26
|
+
},
|
|
27
|
+
runRequest: <A>(request: (signal: AbortSignal) => Promise<A>) =>
|
|
28
|
+
Effect.withFiber((fiber) =>
|
|
29
|
+
Effect.gen(function* () {
|
|
30
|
+
const state: { readonly context: Context.Context<R>; cause?: Cause.Cause<never> } = {
|
|
31
|
+
context: Context.merge(context, fiber.context),
|
|
32
|
+
};
|
|
33
|
+
const exit = yield* Effect.exit(Effect.tryPromise((signal) => requests.run(state, () => request(signal))));
|
|
34
|
+
if (state.cause !== undefined) {
|
|
35
|
+
return yield* Effect.failCause(state.cause);
|
|
36
|
+
}
|
|
37
|
+
return yield* exit;
|
|
38
|
+
}),
|
|
39
|
+
),
|
|
40
|
+
};
|
|
41
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type Cause, Effect } from "effect";
|
|
2
|
+
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
3
|
+
import { type BearerSessionsOptions, cookieSessionResponse, hasSessionCookie, sessionHeaders } from "#server/better-auth/bearerSessions.ts";
|
|
4
|
+
import { sessionPermissions } from "#server/better-auth/sessionPermissions.ts";
|
|
5
|
+
|
|
6
|
+
export interface MountedAuth {
|
|
7
|
+
readonly $context: Promise<{ readonly authCookies: { readonly sessionToken: { readonly name: string } } }>;
|
|
8
|
+
readonly handler: (request: Request) => Promise<Response>;
|
|
9
|
+
}
|
|
10
|
+
export interface MountRouteOptions {
|
|
11
|
+
readonly bearerSessions?: BearerSessionsOptions | undefined;
|
|
12
|
+
readonly clientIpHeader: string;
|
|
13
|
+
readonly ipv6Subnet?: number | undefined;
|
|
14
|
+
readonly roles?: RoleSet | undefined;
|
|
15
|
+
readonly runRequest?: (<A>(request: (signal: AbortSignal) => Promise<A>) => Effect.Effect<A, Cause.UnknownError>) | undefined;
|
|
16
|
+
readonly trustedProxy?: string | undefined;
|
|
17
|
+
}
|
|
18
|
+
function replacesSession(request: Request, reply: Response, native: boolean) {
|
|
19
|
+
return (
|
|
20
|
+
native
|
|
21
|
+
&& reply.ok
|
|
22
|
+
&& reply.headers.has("set-auth-token")
|
|
23
|
+
&& request.headers.has("authorization")
|
|
24
|
+
&& new URL(request.url).pathname.startsWith("/api/auth/sign-in/")
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
async function providerResponse(auth: MountedAuth, web: Request, options: MountRouteOptions) {
|
|
28
|
+
if (options.bearerSessions === undefined) {
|
|
29
|
+
return auth.handler(web);
|
|
30
|
+
}
|
|
31
|
+
const { authCookies } = await auth.$context;
|
|
32
|
+
const cookieName = authCookies.sessionToken.name;
|
|
33
|
+
const headers = sessionHeaders(web.headers, cookieName);
|
|
34
|
+
const native = options.bearerSessions.origins.includes(web.headers.get("origin") ?? "") && !hasSessionCookie(web.headers, cookieName);
|
|
35
|
+
const request = new Request(web, { headers });
|
|
36
|
+
const reply = await auth.handler(request);
|
|
37
|
+
if (replacesSession(request, reply, native)) {
|
|
38
|
+
const revoked = await auth.handler(new Request(new URL("/api/auth/sign-out", web.url), { body: "{}", headers, method: "POST" }));
|
|
39
|
+
await revoked.body?.cancel();
|
|
40
|
+
if (!revoked.ok) {
|
|
41
|
+
throw new Error("Session replacement failed");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return native ? reply : cookieSessionResponse(reply);
|
|
45
|
+
}
|
|
46
|
+
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";
|
|
48
|
+
const url = new URL(web.url);
|
|
49
|
+
if (sessionRequest) {
|
|
50
|
+
url.searchParams.set("disableCookieCache", "true");
|
|
51
|
+
}
|
|
52
|
+
const request = sessionRequest ? new Request(url, web) : web;
|
|
53
|
+
const runRequest = options.runRequest ?? Effect.tryPromise;
|
|
54
|
+
const reply = yield* runRequest((signal) => providerResponse(auth, new Request(request, { signal }), options));
|
|
55
|
+
return sessionRequest && reply.ok && options.roles !== undefined ? yield* sessionPermissions(reply, options.roles) : reply;
|
|
56
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
+
import type { Effect } from "effect";
|
|
3
|
+
|
|
4
|
+
export interface BetterAuthHookError {
|
|
5
|
+
readonly code: string;
|
|
6
|
+
readonly message: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
type EffectHooks<T, R> = {
|
|
10
|
+
readonly [TKey in keyof T]: NonNullable<T[TKey]> extends (...args: infer TArgs) => infer TResult
|
|
11
|
+
? (...args: TArgs) => Effect.Effect<Awaited<TResult>, BetterAuthHookError, R>
|
|
12
|
+
: EffectHooks<NonNullable<T[TKey]>, R>;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export type BetterAuthDatabaseHooks<R = never> = EffectHooks<NonNullable<BetterAuthOptions["databaseHooks"]>, R>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Clock, Duration, Effect } from "effect";
|
|
2
|
+
|
|
3
|
+
export const emailWindow = Effect.fnUntraced(function* (window: Duration.Input = "1 minute") {
|
|
4
|
+
const milliseconds = Duration.toMillis(Duration.fromInputUnsafe(window));
|
|
5
|
+
const entries = yield* Effect.acquireRelease(
|
|
6
|
+
Effect.sync(() => new Map<string, number>()),
|
|
7
|
+
(map) => Effect.sync(() => map.clear()),
|
|
8
|
+
);
|
|
9
|
+
return (account: string, kind: string) =>
|
|
10
|
+
Effect.gen(function* () {
|
|
11
|
+
const now = yield* Clock.currentTimeMillis;
|
|
12
|
+
for (const [entryKey, expiry] of entries) {
|
|
13
|
+
if (expiry > now) {
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
entries.delete(entryKey);
|
|
17
|
+
}
|
|
18
|
+
const key = `${account}:${kind}`;
|
|
19
|
+
const reservedUntil = entries.get(key);
|
|
20
|
+
if (reservedUntil !== undefined && reservedUntil > now) {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
entries.delete(key);
|
|
24
|
+
entries.set(key, now + milliseconds);
|
|
25
|
+
return true;
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { User } from "better-auth";
|
|
2
|
+
import type { Duration, Effect } from "effect";
|
|
3
|
+
import type { BetterAuthHookError } from "./databaseHooks.ts";
|
|
4
|
+
|
|
5
|
+
interface Message {
|
|
6
|
+
readonly url: string;
|
|
7
|
+
readonly user: Pick<User, "id" | "email" | "name">;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type AuthEmail = Message &
|
|
11
|
+
(
|
|
12
|
+
| { readonly _tag: "ConfirmAccount"; readonly token: string }
|
|
13
|
+
| { readonly _tag: "ApproveEmailChange"; readonly token: string; readonly newEmail: string }
|
|
14
|
+
| { readonly _tag: "ConfirmNewAddress"; readonly token: string; readonly newEmail: string }
|
|
15
|
+
| { readonly _tag: "ResetPassword"; readonly token: string }
|
|
16
|
+
| { readonly _tag: "AccountAlreadyExists" }
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
export interface BetterAuthEmails<R = never> {
|
|
20
|
+
readonly deliver: (message: AuthEmail) => Effect.Effect<void, BetterAuthHookError, R>;
|
|
21
|
+
readonly routes: Readonly<Record<AuthEmail["_tag"], string>>;
|
|
22
|
+
readonly window?: Duration.Input;
|
|
23
|
+
}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { type BetterAuthOptions, betterAuth } from "better-auth";
|
|
2
2
|
import { Config, Effect, Option, Redacted } from "effect";
|
|
3
3
|
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
4
|
+
import { effectHookOptions } from "#server/better-auth/adapters/effectHookOptions.ts";
|
|
5
|
+
import { emailOptions } from "#server/better-auth/adapters/emailOptions.ts";
|
|
4
6
|
import { type BetterAuthHardeningOptions, withHardening } from "#server/better-auth/adapters/hardening.ts";
|
|
7
|
+
import { hookRuntime } from "#server/better-auth/adapters/hookRuntime.ts";
|
|
5
8
|
import { roleSeedOptions } from "#server/better-auth/adapters/roleSeedOptions.ts";
|
|
6
9
|
import { signInPolicyOptions } from "#server/better-auth/adapters/signInPolicyOptions.ts";
|
|
7
10
|
import { type StoredRoleOptions, storedRoleOptions } from "#server/better-auth/adapters/storedRoleOptions.ts";
|
|
@@ -14,10 +17,14 @@ import { type PolicyStorage, type SignInPolicy, signInGate } from "#server/bette
|
|
|
14
17
|
import type { AccountRoleSeed } from "./accountRoleSeed.ts";
|
|
15
18
|
import { admittedSessions } from "./admittedSessions.ts";
|
|
16
19
|
import { closeRoleEndpoints } from "./closeRoleEndpoints.ts";
|
|
20
|
+
import type { BetterAuthDatabaseHooks } from "./databaseHooks.ts";
|
|
21
|
+
import type { BetterAuthEmails } from "./emails.ts";
|
|
17
22
|
import { mountedSessions } from "./mountedSessions.ts";
|
|
18
23
|
|
|
19
24
|
export type BetterAuthMountOptions<E = never, R = never> = {
|
|
20
25
|
readonly bearerSessions?: BearerSessionsOptions | undefined;
|
|
26
|
+
readonly databaseHooks?: BetterAuthDatabaseHooks<R> | undefined;
|
|
27
|
+
readonly emails?: BetterAuthEmails<R> | undefined;
|
|
21
28
|
readonly hardening?: BetterAuthHardeningOptions;
|
|
22
29
|
readonly signIn?: SignInPolicy<E, R> | undefined;
|
|
23
30
|
} & (
|
|
@@ -40,7 +47,9 @@ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <
|
|
|
40
47
|
yield* policy.accounts;
|
|
41
48
|
}
|
|
42
49
|
const gate = yield* signInGate(policy);
|
|
43
|
-
const
|
|
50
|
+
const runtime = yield* hookRuntime<R>();
|
|
51
|
+
const hooked = effectHookOptions(yield* emailOptions(options, mount.emails, runtime), mount.databaseHooks, runtime);
|
|
52
|
+
const configured = mount.roles === undefined ? hooked : storedRoleOptions(closeRoleEndpoints(hooked), mount);
|
|
44
53
|
const gated = yield* signInPolicyOptions(configured, gate, (): Promise<PolicyStorage> => auth.$context);
|
|
45
54
|
const seed = mount.roleSeed === undefined ? undefined : yield* mount.roleSeed;
|
|
46
55
|
const seeded = roleSeedOptions(gate.active ? { ...configured, ...gated } : configured, seed);
|
|
@@ -80,6 +89,7 @@ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <
|
|
|
80
89
|
clientIpHeader,
|
|
81
90
|
ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet,
|
|
82
91
|
roles: mount.roles,
|
|
92
|
+
runRequest: runtime.runRequest,
|
|
83
93
|
trustedProxy,
|
|
84
94
|
});
|
|
85
95
|
const admit = admittedSessions(gate, () => auth.$context, mount.bearerSessions);
|
|
@@ -1,61 +1,10 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
3
3
|
import * as HttpStatus from "effect/http/HttpStatus";
|
|
4
|
-
import type
|
|
5
|
-
import { type BearerSessionsOptions, cookieSessionResponse, hasSessionCookie, sessionHeaders } from "#server/better-auth/bearerSessions.ts";
|
|
4
|
+
import { type MountedAuth, type MountRouteOptions, response } from "#server/better-auth/adapters/response.ts";
|
|
6
5
|
import { providerFailure } from "#server/providerFailure.ts";
|
|
7
6
|
import { clientIpHeaders } from "./clientIp.ts";
|
|
8
|
-
import { sessionPermissions } from "./sessionPermissions.ts";
|
|
9
7
|
|
|
10
|
-
interface MountedAuth {
|
|
11
|
-
readonly $context: Promise<{ readonly authCookies: { readonly sessionToken: { readonly name: string } } }>;
|
|
12
|
-
readonly handler: (request: Request) => Promise<Response>;
|
|
13
|
-
}
|
|
14
|
-
interface MountRouteOptions {
|
|
15
|
-
readonly bearerSessions?: BearerSessionsOptions | undefined;
|
|
16
|
-
readonly clientIpHeader: string;
|
|
17
|
-
readonly ipv6Subnet?: number | undefined;
|
|
18
|
-
readonly roles?: RoleSet | undefined;
|
|
19
|
-
readonly trustedProxy?: string | undefined;
|
|
20
|
-
}
|
|
21
|
-
function replacesSession(request: Request, response: Response, native: boolean) {
|
|
22
|
-
return (
|
|
23
|
-
native
|
|
24
|
-
&& response.ok
|
|
25
|
-
&& response.headers.has("set-auth-token")
|
|
26
|
-
&& request.headers.has("authorization")
|
|
27
|
-
&& new URL(request.url).pathname.startsWith("/api/auth/sign-in/")
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
async function providerResponse(auth: MountedAuth, web: Request, options: MountRouteOptions) {
|
|
31
|
-
if (options.bearerSessions === undefined) {
|
|
32
|
-
return auth.handler(web);
|
|
33
|
-
}
|
|
34
|
-
const { authCookies } = await auth.$context;
|
|
35
|
-
const cookieName = authCookies.sessionToken.name;
|
|
36
|
-
const headers = sessionHeaders(web.headers, cookieName);
|
|
37
|
-
const native = options.bearerSessions.origins.includes(web.headers.get("origin") ?? "") && !hasSessionCookie(web.headers, cookieName);
|
|
38
|
-
const request = new Request(web, { headers });
|
|
39
|
-
const response = await auth.handler(request);
|
|
40
|
-
if (replacesSession(request, response, native)) {
|
|
41
|
-
const revoked = await auth.handler(new Request(new URL("/api/auth/sign-out", web.url), { body: "{}", headers, method: "POST" }));
|
|
42
|
-
await revoked.body?.cancel();
|
|
43
|
-
if (!revoked.ok) {
|
|
44
|
-
throw new Error("Session replacement failed");
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
return native ? response : cookieSessionResponse(response);
|
|
48
|
-
}
|
|
49
|
-
const authResponse = Effect.fnUntraced(function* (auth: MountedAuth, web: Request, options: MountRouteOptions) {
|
|
50
|
-
const sessionRequest = options.roles !== undefined && new URL(web.url).pathname === "/api/auth/get-session";
|
|
51
|
-
const url = new URL(web.url);
|
|
52
|
-
if (sessionRequest) {
|
|
53
|
-
url.searchParams.set("disableCookieCache", "true");
|
|
54
|
-
}
|
|
55
|
-
const request = sessionRequest ? new Request(url, web) : web;
|
|
56
|
-
const response = yield* Effect.tryPromise((signal) => providerResponse(auth, new Request(request, { signal }), options));
|
|
57
|
-
return sessionRequest && response.ok && options.roles !== undefined ? yield* sessionPermissions(response, options.roles) : response;
|
|
58
|
-
});
|
|
59
8
|
export function mountRoutes(auth: MountedAuth, options: MountRouteOptions) {
|
|
60
9
|
const setClientIp = clientIpHeaders(options);
|
|
61
10
|
return HttpRouter.use((router) =>
|
|
@@ -68,7 +17,7 @@ export function mountRoutes(auth: MountedAuth, options: MountRouteOptions) {
|
|
|
68
17
|
"auth.rate_limit.address_source": clientIp.source,
|
|
69
18
|
});
|
|
70
19
|
return HttpServerResponse.fromWeb(
|
|
71
|
-
yield*
|
|
20
|
+
yield* response(auth, web, options).pipe(
|
|
72
21
|
Effect.catchTag("Forbidden", (error) =>
|
|
73
22
|
Effect.succeed(Response.json({ message: error.message }, { status: HttpStatus.fromLiteral("Forbidden") })),
|
|
74
23
|
),
|