@shivaedev/identity 0.24.0 → 0.25.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 +16 -0
- package/README.md +68 -2
- package/dist/accountPreferences.d.ts +26 -26
- package/dist/server/UserProvisioning.d.ts +15 -0
- package/dist/server/UserProvisioning.d.ts.map +1 -0
- package/dist/server/UserProvisioning.js +4 -0
- package/dist/server/UserProvisioning.js.map +1 -0
- package/dist/server/account-export/check.d.ts +15 -0
- package/dist/server/account-export/check.d.ts.map +1 -0
- package/dist/server/account-export/check.js +33 -0
- package/dist/server/account-export/check.js.map +1 -0
- package/dist/server/accountExport.d.ts +14 -0
- package/dist/server/accountExport.d.ts.map +1 -0
- package/dist/server/accountExport.js +15 -0
- package/dist/server/accountExport.js.map +1 -0
- package/dist/server/better-auth/adapters/SeedOptions.d.ts +14 -0
- package/dist/server/better-auth/adapters/SeedOptions.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/SeedOptions.js +2 -0
- package/dist/server/better-auth/adapters/SeedOptions.js.map +1 -0
- package/dist/server/better-auth/adapters/acquire.d.ts +37 -1
- package/dist/server/better-auth/adapters/acquire.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/acquire.js +4 -1
- package/dist/server/better-auth/adapters/acquire.js.map +1 -1
- package/dist/server/better-auth/adapters/assertSeedDatabase.d.ts +10 -0
- package/dist/server/better-auth/adapters/assertSeedDatabase.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/assertSeedDatabase.js +12 -0
- package/dist/server/better-auth/adapters/assertSeedDatabase.js.map +1 -0
- package/dist/server/better-auth/adapters/defineSeed.d.ts +4 -0
- package/dist/server/better-auth/adapters/defineSeed.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/defineSeed.js +19 -0
- package/dist/server/better-auth/adapters/defineSeed.js.map +1 -0
- package/dist/server/better-auth/adapters/emailOptions.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/emailOptions.js +19 -8
- package/dist/server/better-auth/adapters/emailOptions.js.map +1 -1
- package/dist/server/better-auth/adapters/mount.d.ts +37 -0
- package/dist/server/better-auth/adapters/mount.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/mount.js +1 -1
- package/dist/server/better-auth/adapters/mount.js.map +1 -1
- package/dist/server/better-auth/adapters/mountSettings.d.ts +1 -1
- package/dist/server/better-auth/adapters/mountSettings.d.ts.map +1 -1
- package/dist/server/better-auth/adapters/mountSettings.js +2 -2
- package/dist/server/better-auth/adapters/mountSettings.js.map +1 -1
- package/dist/server/better-auth/adapters/userDataExport.d.ts +38 -0
- package/dist/server/better-auth/adapters/userDataExport.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/userDataExport.js +55 -0
- package/dist/server/better-auth/adapters/userDataExport.js.map +1 -0
- package/dist/server/better-auth/adapters/userProvisioning.d.ts +9 -0
- package/dist/server/better-auth/adapters/userProvisioning.d.ts.map +1 -0
- package/dist/server/better-auth/adapters/userProvisioning.js +22 -0
- package/dist/server/better-auth/adapters/userProvisioning.js.map +1 -0
- package/dist/server/better-auth/emails.d.ts +1 -0
- package/dist/server/better-auth/emails.d.ts.map +1 -1
- package/dist/server/better-auth/seedUsers.d.ts +6 -0
- package/dist/server/better-auth/seedUsers.d.ts.map +1 -0
- package/dist/server/better-auth/seedUsers.js +15 -0
- package/dist/server/better-auth/seedUsers.js.map +1 -0
- package/dist/server/better-auth/testDatabase.d.ts.map +1 -1
- package/dist/server/better-auth/testDatabase.js +4 -1
- package/dist/server/better-auth/testDatabase.js.map +1 -1
- package/dist/server/userDataExport.d.ts +13 -0
- package/dist/server/userDataExport.d.ts.map +1 -0
- package/dist/server/userDataExport.js +2 -0
- package/dist/server/userDataExport.js.map +1 -0
- package/package.json +9 -9
- package/src/server/UserProvisioning.ts +16 -0
- package/src/server/account-export/check.ts +38 -0
- package/src/server/accountExport.ts +40 -0
- package/src/server/better-auth/adapters/SeedOptions.ts +12 -0
- package/src/server/better-auth/adapters/acquire.ts +4 -1
- package/src/server/better-auth/adapters/assertSeedDatabase.ts +15 -0
- package/src/server/better-auth/adapters/defineSeed.ts +23 -0
- package/src/server/better-auth/adapters/emailOptions.ts +27 -8
- package/src/server/better-auth/adapters/mount.ts +2 -1
- package/src/server/better-auth/adapters/mountSettings.ts +3 -2
- package/src/server/better-auth/adapters/userDataExport.ts +57 -0
- package/src/server/better-auth/adapters/userProvisioning.ts +25 -0
- package/src/server/better-auth/emails.ts +1 -0
- package/src/server/better-auth/seedUsers.ts +21 -0
- package/src/server/better-auth/testDatabase.ts +4 -3
- package/src/server/userDataExport.ts +15 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { checkUserDataExports } from "#server/account-export/check.ts";
|
|
3
|
+
import { userReference } from "#server/better-auth/userReference.ts";
|
|
4
|
+
import type { UserDataExport, UserExportReference } from "#server/userDataExport.ts";
|
|
5
|
+
|
|
6
|
+
type ExportEffects<T extends Readonly<Record<string, UserDataExport>>> = ReturnType<T[keyof T]["export"]>;
|
|
7
|
+
type ExportCoverage = ReturnType<typeof checkUserDataExports>;
|
|
8
|
+
type ExportData<T extends Readonly<Record<string, UserDataExport>>> = {
|
|
9
|
+
readonly [TDomain in keyof T]: Effect.Success<ReturnType<T[TDomain]["export"]>>;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export function accountExport<const T extends Readonly<Record<string, UserDataExport>>>(
|
|
13
|
+
registrations: T,
|
|
14
|
+
reference?: UserExportReference,
|
|
15
|
+
): {
|
|
16
|
+
readonly check: ExportCoverage;
|
|
17
|
+
readonly exportUser: (
|
|
18
|
+
userId: string,
|
|
19
|
+
) => Effect.Effect<
|
|
20
|
+
ExportData<T>,
|
|
21
|
+
Effect.Error<ExportEffects<T>> | Effect.Error<ExportCoverage>,
|
|
22
|
+
Effect.Services<ExportEffects<T>> | Effect.Services<ExportCoverage>
|
|
23
|
+
>;
|
|
24
|
+
};
|
|
25
|
+
export function accountExport(
|
|
26
|
+
registrations: Readonly<Record<string, UserDataExport>>,
|
|
27
|
+
reference: UserExportReference = { ...userReference, schema: "public" },
|
|
28
|
+
) {
|
|
29
|
+
const check = checkUserDataExports(registrations, reference);
|
|
30
|
+
return {
|
|
31
|
+
check,
|
|
32
|
+
exportUser: Effect.fn("Identity.exportUser")(function* (userId: string) {
|
|
33
|
+
yield* check;
|
|
34
|
+
const entries = yield* Effect.forEach(Object.entries(registrations), ([domain, registration]) =>
|
|
35
|
+
registration.export(userId).pipe(Effect.map((data) => [domain, data] as const)),
|
|
36
|
+
);
|
|
37
|
+
return Object.fromEntries(entries);
|
|
38
|
+
}),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
+
import type { Effect } from "effect";
|
|
3
|
+
import type { AccessPolicy } from "@shivaedev/access/roleSet.ts";
|
|
4
|
+
import type { PasswordUser } from "#server/UserProvisioning.ts";
|
|
5
|
+
|
|
6
|
+
export interface SeedOptions<TRole extends string, E, R> {
|
|
7
|
+
readonly auth?: Omit<BetterAuthOptions, "database">;
|
|
8
|
+
readonly defaultRole: NoInfer<TRole>;
|
|
9
|
+
readonly roles: AccessPolicy<TRole>;
|
|
10
|
+
readonly run: Effect.Effect<unknown, E, R>;
|
|
11
|
+
readonly users: readonly (PasswordUser & { readonly role: NoInfer<TRole> })[];
|
|
12
|
+
}
|
|
@@ -4,7 +4,10 @@ import { providerFailure } from "#server/providerFailure.ts";
|
|
|
4
4
|
import { profileStorage } from "./profileStorage.ts";
|
|
5
5
|
|
|
6
6
|
export const acquireAuth = Effect.fnUntraced(function* <TOptions extends BetterAuthOptions>(options: TOptions) {
|
|
7
|
-
const auth = betterAuth(
|
|
7
|
+
const auth = betterAuth({
|
|
8
|
+
...options,
|
|
9
|
+
advanced: { ...options.advanced, database: { joins: true, ...options.advanced?.database } },
|
|
10
|
+
});
|
|
8
11
|
const context = yield* Effect.tryPromise(async () => {
|
|
9
12
|
const ready = await auth.$context;
|
|
10
13
|
await ready.checkSchema?.();
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Data, Effect, Redacted } from "effect";
|
|
2
|
+
|
|
3
|
+
export class NonLocalSeedDatabase extends Data.TaggedError("NonLocalSeedDatabase") {
|
|
4
|
+
override readonly message = "Demo seeding requires a local PostgreSQL database URL";
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export const assertSeedDatabase = Effect.fnUntraced(function* (value: Redacted.Redacted<string>) {
|
|
8
|
+
const url = yield* Effect.try({ catch: () => new NonLocalSeedDatabase(), try: () => new URL(Redacted.value(value)) });
|
|
9
|
+
if (
|
|
10
|
+
!(["postgres:", "postgresql:"].includes(url.protocol) && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
|
|
11
|
+
|| [...url.searchParams.keys()].some((key) => ["host", "hostaddr", "service"].includes(key.toLowerCase()))
|
|
12
|
+
) {
|
|
13
|
+
return yield* new NonLocalSeedDatabase();
|
|
14
|
+
}
|
|
15
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Config, Effect } from "effect";
|
|
2
|
+
import { memoryStore } from "@shivaedev/rate-limit/memoryStore.ts";
|
|
3
|
+
import { postgresLayer } from "@shivaedev/sql/postgresLayer.ts";
|
|
4
|
+
import { seedUsers } from "#server/better-auth/seedUsers.ts";
|
|
5
|
+
import { assertSeedDatabase } from "./assertSeedDatabase.ts";
|
|
6
|
+
import { betterAuthDatabase } from "./database.ts";
|
|
7
|
+
import { betterAuthMount } from "./mount.ts";
|
|
8
|
+
import type { SeedOptions } from "./SeedOptions.ts";
|
|
9
|
+
import { betterAuthUserProvisioning } from "./userProvisioning.ts";
|
|
10
|
+
|
|
11
|
+
export function defineSeed<TRole extends string, E, R>(options: SeedOptions<TRole, E, R>) {
|
|
12
|
+
return Effect.gen(function* () {
|
|
13
|
+
const url = yield* Config.Redacted("DATABASE_URL");
|
|
14
|
+
yield* assertSeedDatabase(url);
|
|
15
|
+
return yield* Effect.gen(function* () {
|
|
16
|
+
const { auth } = yield* betterAuthMount(
|
|
17
|
+
{ emailAndPassword: { enabled: true }, ...options.auth, database: yield* betterAuthDatabase() },
|
|
18
|
+
{ defaultRole: options.defaultRole, roles: options.roles },
|
|
19
|
+
).pipe(Effect.provide(memoryStore));
|
|
20
|
+
return yield* seedUsers(options).pipe(Effect.provide(betterAuthUserProvisioning(auth)));
|
|
21
|
+
}).pipe(Effect.provide(postgresLayer(url)));
|
|
22
|
+
}).pipe(Effect.scoped);
|
|
23
|
+
}
|
|
@@ -9,6 +9,11 @@ import type { hookRuntime } from "./hookRuntime.ts";
|
|
|
9
9
|
type Outgoing = { [TKind in AuthEmail["_tag"]]: Omit<Extract<AuthEmail, { readonly _tag: TKind }>, "url"> }[AuthEmail["_tag"]];
|
|
10
10
|
|
|
11
11
|
const Verification = Schema.Struct({ updateTo: Schema.optionalKey(Schema.String) });
|
|
12
|
+
const SignUp = Schema.Struct({ "callbackURL": Schema.optionalKey(Schema.String) });
|
|
13
|
+
|
|
14
|
+
function continuation(url: string) {
|
|
15
|
+
return new URL(url).searchParams.get("callbackURL");
|
|
16
|
+
}
|
|
12
17
|
|
|
13
18
|
export const emailOptions = Effect.fnUntraced(function* <TOptions extends BetterAuthOptions, R>(
|
|
14
19
|
options: TOptions,
|
|
@@ -18,16 +23,23 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
18
23
|
if (emails === undefined) {
|
|
19
24
|
return options;
|
|
20
25
|
}
|
|
21
|
-
const { routes, deliver, window = "1 minute" } = emails;
|
|
26
|
+
const { routes, deliver, window = "1 minute", windows } = emails;
|
|
22
27
|
const store = yield* Store.pipe(Effect.provide(postgresStore));
|
|
23
|
-
function send(message: Outgoing, request?: Request) {
|
|
28
|
+
function send(message: Outgoing, request?: Request, callback?: string | null) {
|
|
24
29
|
const url = new URL(routes[message._tag]);
|
|
30
|
+
if (callback && URL.parse(callback, url.origin)?.origin === url.origin) {
|
|
31
|
+
url.searchParams.set("callbackURL", callback);
|
|
32
|
+
}
|
|
25
33
|
if ("token" in message) {
|
|
26
34
|
url.searchParams.set("token", Redacted.value(message.token));
|
|
27
35
|
}
|
|
28
36
|
return runtime.runHook(
|
|
29
37
|
() =>
|
|
30
|
-
rateLimit({
|
|
38
|
+
rateLimit({
|
|
39
|
+
key: `identity:email:${JSON.stringify([message.user.id, message._tag])}`,
|
|
40
|
+
per: 1,
|
|
41
|
+
window: windows?.[message._tag] ?? window,
|
|
42
|
+
}).pipe(
|
|
31
43
|
Effect.provideService(Store, store),
|
|
32
44
|
Effect.as(true),
|
|
33
45
|
Effect.catchTag("TooManyRequests", () => Effect.succeed(false)),
|
|
@@ -42,12 +54,18 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
42
54
|
emailAndPassword: {
|
|
43
55
|
...options.emailAndPassword,
|
|
44
56
|
enabled: options.emailAndPassword?.enabled ?? false,
|
|
45
|
-
onExistingUserSignUp: ({ user }, request) =>
|
|
46
|
-
|
|
57
|
+
onExistingUserSignUp: async ({ user }, request) =>
|
|
58
|
+
send(
|
|
59
|
+
{ _tag: "AccountAlreadyExists", user },
|
|
60
|
+
request,
|
|
61
|
+
request === undefined ? undefined : Schema.decodeUnknownSync(SignUp)(await request.json()).callbackURL,
|
|
62
|
+
),
|
|
63
|
+
sendResetPassword: ({ user, token, url }, request) =>
|
|
64
|
+
send({ _tag: "ResetPassword", token: Redacted.make(token), user }, request, continuation(url)),
|
|
47
65
|
},
|
|
48
66
|
emailVerification: {
|
|
49
67
|
...options.emailVerification,
|
|
50
|
-
sendVerificationEmail: ({ user, token }, request) => {
|
|
68
|
+
sendVerificationEmail: ({ user, token, url }, request) => {
|
|
51
69
|
const payload = token.split(".")[1] ?? "";
|
|
52
70
|
const { updateTo } = Schema.decodeUnknownSync(Schema.fromJsonString(Verification))(Buffer.from(payload, "base64url").toString("utf8"));
|
|
53
71
|
return send(
|
|
@@ -55,6 +73,7 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
55
73
|
? { _tag: "ConfirmAccount", token: Redacted.make(token), user }
|
|
56
74
|
: { _tag: "ConfirmNewAddress", newEmail: updateTo, token: Redacted.make(token), user },
|
|
57
75
|
request,
|
|
76
|
+
continuation(url),
|
|
58
77
|
);
|
|
59
78
|
},
|
|
60
79
|
},
|
|
@@ -63,8 +82,8 @@ export const emailOptions = Effect.fnUntraced(function* <TOptions extends Better
|
|
|
63
82
|
changeEmail: {
|
|
64
83
|
...options.user?.changeEmail,
|
|
65
84
|
enabled: options.user?.changeEmail?.enabled ?? false,
|
|
66
|
-
sendChangeEmailConfirmation: ({ user, newEmail, token }, request) =>
|
|
67
|
-
send({ _tag: "ApproveEmailChange", newEmail, token: Redacted.make(token), user }, request),
|
|
85
|
+
sendChangeEmailConfirmation: ({ user, newEmail, token, url }, request) =>
|
|
86
|
+
send({ _tag: "ApproveEmailChange", newEmail, token: Redacted.make(token), user }, request, continuation(url)),
|
|
68
87
|
},
|
|
69
88
|
},
|
|
70
89
|
} satisfies BetterAuthOptions;
|
|
@@ -34,6 +34,7 @@ import { authRouteHandler } from "./routeHandler.ts";
|
|
|
34
34
|
export type BetterAuthMountOptions<E = never, R = never> = {
|
|
35
35
|
readonly accountPreferences?: boolean;
|
|
36
36
|
readonly bearerSessions?: BearerSessionsOptions | undefined;
|
|
37
|
+
readonly clientIp?: "railway";
|
|
37
38
|
readonly databaseHooks?: BetterAuthDatabaseHooks<R> | undefined;
|
|
38
39
|
readonly emails?: BetterAuthEmails<R> | undefined;
|
|
39
40
|
readonly enabledPaths?: readonly string[];
|
|
@@ -53,7 +54,7 @@ const mountAuth = Effect.fn("Identity.mountAuth")(function* <const TOptions exte
|
|
|
53
54
|
if (mount.roles !== undefined) {
|
|
54
55
|
yield* mount.roles.resolve(mount.defaultRole).pipe(Effect.mapError(() => new UndeclaredDefaultRole({ role: mount.defaultRole })));
|
|
55
56
|
}
|
|
56
|
-
const { authOptions, clientIpHeader, rateLimitEnabled, trustedProxy } = yield* mountSettings(options);
|
|
57
|
+
const { authOptions, clientIpHeader, rateLimitEnabled, trustedProxy } = yield* mountSettings(options, mount.clientIp);
|
|
57
58
|
const policy = mount.signIn ?? {};
|
|
58
59
|
if (policy.accounts !== undefined) {
|
|
59
60
|
yield* policy.accounts;
|
|
@@ -2,12 +2,13 @@ import type { BetterAuthOptions } from "better-auth";
|
|
|
2
2
|
import { Config, Effect, Option, Redacted } from "effect";
|
|
3
3
|
import { PEER_IP_HEADER } from "#server/better-auth/adapters/clientIp.ts";
|
|
4
4
|
|
|
5
|
-
export const mountSettings = Effect.fnUntraced(function* (options: BetterAuthOptions) {
|
|
5
|
+
export const mountSettings = Effect.fnUntraced(function* (options: BetterAuthOptions, clientIp?: "railway") {
|
|
6
6
|
const secret = options.secret ?? Redacted.value(yield* Config.Redacted("BETTER_AUTH_SECRET"));
|
|
7
7
|
const publicUrl = yield* Config.URL("PUBLIC_URL").pipe(Config.option);
|
|
8
8
|
const origin = Option.map(publicUrl, (url) => url.origin);
|
|
9
9
|
const trustedProxy = Option.getOrUndefined(yield* Config.String("TRUSTED_PROXY").pipe(Config.option));
|
|
10
|
-
const clientIpHeader =
|
|
10
|
+
const clientIpHeader =
|
|
11
|
+
clientIp === "railway" ? "x-real-ip" : yield* Config.String("AUTH_CLIENT_IP_HEADER").pipe(Config.withDefault("x-forwarded-for"));
|
|
11
12
|
const rateLimitEnabled = yield* Config.Boolean("AUTH_RATE_LIMIT_ENABLED").pipe(Config.withDefault(true));
|
|
12
13
|
return {
|
|
13
14
|
authOptions: {
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from "better-auth";
|
|
2
|
+
import { getAuthTables } from "better-auth/db";
|
|
3
|
+
import { Effect, Schema } from "effect";
|
|
4
|
+
import { SqlClient, SqlSchema } from "effect/sql";
|
|
5
|
+
|
|
6
|
+
const Timestamps = { createdAt: Schema.DateTimeUtcFromDate, updatedAt: Schema.DateTimeUtcFromDate };
|
|
7
|
+
const User = Schema.Struct({
|
|
8
|
+
...Timestamps,
|
|
9
|
+
email: Schema.String,
|
|
10
|
+
emailVerified: Schema.Boolean,
|
|
11
|
+
id: Schema.String,
|
|
12
|
+
image: Schema.NullOr(Schema.String),
|
|
13
|
+
name: Schema.String,
|
|
14
|
+
});
|
|
15
|
+
const Account = Schema.Struct({ ...Timestamps, accountId: Schema.String, id: Schema.String, providerId: Schema.String, userId: Schema.String });
|
|
16
|
+
const Session = Schema.Struct({
|
|
17
|
+
...Timestamps,
|
|
18
|
+
expiresAt: Schema.DateTimeUtcFromDate,
|
|
19
|
+
id: Schema.String,
|
|
20
|
+
ipAddress: Schema.NullOr(Schema.String),
|
|
21
|
+
userAgent: Schema.NullOr(Schema.String),
|
|
22
|
+
userId: Schema.String,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
export function betterAuthUserDataExport(options: BetterAuthOptions = {}, schema = "public") {
|
|
26
|
+
const models = getAuthTables(options);
|
|
27
|
+
return {
|
|
28
|
+
export: Effect.fn("BetterAuth.export")(function* (userId: string) {
|
|
29
|
+
const sql = (yield* SqlClient.SqlClient).withoutTransforms();
|
|
30
|
+
function select(model: string, fields: readonly string[], owner: string, id: string) {
|
|
31
|
+
const table = models[model];
|
|
32
|
+
function column(name: string) {
|
|
33
|
+
return table?.fields[name]?.fieldName ?? name;
|
|
34
|
+
}
|
|
35
|
+
const columns = sql.csv(fields.map((name) => sql`${sql(column(name))} as ${sql(name)}`));
|
|
36
|
+
return sql`select ${columns} from ${sql(`${schema}.${table?.modelName ?? model}`)} where ${sql(column(owner))} = ${id} order by id`;
|
|
37
|
+
}
|
|
38
|
+
const users = yield* SqlSchema.findAll({
|
|
39
|
+
execute: (id) => select("user", Object.keys(User.fields), "id", id),
|
|
40
|
+
Request: Schema.String,
|
|
41
|
+
Result: User,
|
|
42
|
+
})(userId);
|
|
43
|
+
const accounts = yield* SqlSchema.findAll({
|
|
44
|
+
execute: (id) => select("account", Object.keys(Account.fields), "userId", id),
|
|
45
|
+
Request: Schema.String,
|
|
46
|
+
Result: Account,
|
|
47
|
+
})(userId);
|
|
48
|
+
const sessions = yield* SqlSchema.findAll({
|
|
49
|
+
execute: (id) => select("session", Object.keys(Session.fields), "userId", id),
|
|
50
|
+
Request: Schema.String,
|
|
51
|
+
Result: Session,
|
|
52
|
+
})(userId);
|
|
53
|
+
return { accounts, sessions, users };
|
|
54
|
+
}),
|
|
55
|
+
tables: ["user", "account", "session"].map((model) => ({ schema, table: models[model]?.modelName ?? model })),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AuthContext } from "better-auth";
|
|
2
|
+
import { Effect, Layer, Redacted } from "effect";
|
|
3
|
+
import { providerFailure } from "#server/providerFailure.ts";
|
|
4
|
+
import { type PasswordUser, UserProvisioning } from "#server/UserProvisioning.ts";
|
|
5
|
+
|
|
6
|
+
export function betterAuthUserProvisioning(auth: {
|
|
7
|
+
readonly $context: Promise<Pick<AuthContext, "internalAdapter"> & { readonly password: Pick<AuthContext["password"], "hash"> }>;
|
|
8
|
+
}) {
|
|
9
|
+
return Layer.succeed(UserProvisioning, {
|
|
10
|
+
findOrCreateUser: Effect.fn("Identity.findOrCreateUser")(function* ({ email, name, password }: PasswordUser) {
|
|
11
|
+
return yield* Effect.tryPromise(async () => {
|
|
12
|
+
const context = await auth.$context;
|
|
13
|
+
const normalized = email.toLowerCase();
|
|
14
|
+
const existing = await context.internalAdapter.findUserByEmail(normalized);
|
|
15
|
+
if (existing !== null) {
|
|
16
|
+
return { email: existing.user.email, id: existing.user.id, name: existing.user.name };
|
|
17
|
+
}
|
|
18
|
+
const hash = await context.password.hash(Redacted.value(password));
|
|
19
|
+
const user = await context.internalAdapter.createUser({ email: normalized, emailVerified: true, name }, { method: "seed" });
|
|
20
|
+
await context.internalAdapter.createAccount({ accountId: user.id, password: hash, providerId: "credential", userId: user.id });
|
|
21
|
+
return { email: user.email, id: user.id, name: user.name };
|
|
22
|
+
}).pipe(Effect.catch((error) => providerFailure(error.cause)));
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
@@ -23,4 +23,5 @@ export interface BetterAuthEmails<R = never> {
|
|
|
23
23
|
readonly deliver: (message: AuthEmail) => Effect.Effect<void, BetterAuthHookError, R>;
|
|
24
24
|
readonly routes: Readonly<Record<AuthEmail["_tag"], string>>;
|
|
25
25
|
readonly window?: Duration.Input;
|
|
26
|
+
readonly windows?: Readonly<Partial<Record<AuthEmail["_tag"], Duration.Input>>>;
|
|
26
27
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Effect, Option } from "effect";
|
|
2
|
+
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
3
|
+
import { Identity, SessionUser } from "#identity.ts";
|
|
4
|
+
import type { SeedOptions } from "#server/better-auth/adapters/SeedOptions.ts";
|
|
5
|
+
import { UserProvisioning } from "#server/UserProvisioning.ts";
|
|
6
|
+
import { assignRole } from "./assignRole.ts";
|
|
7
|
+
|
|
8
|
+
export const seedUsers = Effect.fn("Identity.seedUsers")(function* <TRole extends string, E, R>(options: SeedOptions<TRole, E, R>) {
|
|
9
|
+
const provisioning = yield* UserProvisioning;
|
|
10
|
+
for (const persona of options.users) {
|
|
11
|
+
const user = yield* provisioning.findOrCreateUser(persona);
|
|
12
|
+
yield* assignRole(options.roles, user.id, persona.role, options.auth);
|
|
13
|
+
const access = yield* options.roles.resolve(persona.role);
|
|
14
|
+
yield* options.run.pipe(
|
|
15
|
+
Effect.provideService(Identity, { id: user.id }),
|
|
16
|
+
Effect.provideService(SessionUser, { ...user, ...access }),
|
|
17
|
+
Effect.provideService(CurrentViewer, Option.some({ id: user.id })),
|
|
18
|
+
Effect.annotateLogs({ userId: user.id }),
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
@@ -13,9 +13,10 @@ export const authTestDatabase = Effect.gen(function* () {
|
|
|
13
13
|
});
|
|
14
14
|
return {
|
|
15
15
|
expireSessions: (userId?: string) =>
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
Effect.gen(function* () {
|
|
17
|
+
const expiredAt = DateTime.toDateUtc(DateTime.subtract(yield* DateTime.now, { seconds: 1 }));
|
|
18
|
+
yield* sql`update "session" set "expiresAt" = ${expiredAt} ${userId === undefined ? sql.literal("") : sql`where "userId" = ${userId}`}`;
|
|
19
|
+
}),
|
|
19
20
|
migrate: migrateBetterAuth,
|
|
20
21
|
omitImageColumn: sql`alter table "user" drop column image`.pipe(Effect.asVoid),
|
|
21
22
|
omitRole: (userId: string) =>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Effect } from "effect";
|
|
2
|
+
|
|
3
|
+
export interface UserExportTable {
|
|
4
|
+
readonly schema: string;
|
|
5
|
+
readonly table: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface UserExportReference extends UserExportTable {
|
|
9
|
+
readonly column: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface UserDataExport {
|
|
13
|
+
readonly export: (userId: string) => Effect.Effect<unknown, unknown, unknown>;
|
|
14
|
+
readonly tables: readonly UserExportTable[];
|
|
15
|
+
}
|