@shivaedev/platform 0.22.1 → 0.23.1

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.
Files changed (32) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +42 -1
  3. package/dist/server/better-auth/allowedAccounts.d.ts +10 -0
  4. package/dist/server/better-auth/allowedAccounts.d.ts.map +1 -0
  5. package/dist/server/better-auth/allowedAccounts.js +20 -0
  6. package/dist/server/better-auth/allowedAccounts.js.map +1 -0
  7. package/dist/server/better-auth/mount.d.ts +192 -2
  8. package/dist/server/better-auth/mount.d.ts.map +1 -1
  9. package/dist/server/better-auth/mount.js +34 -2
  10. package/dist/server/better-auth/mount.js.map +1 -1
  11. package/dist/server/better-auth/revokeUnadmitted.d.ts +10 -0
  12. package/dist/server/better-auth/revokeUnadmitted.d.ts.map +1 -0
  13. package/dist/server/better-auth/revokeUnadmitted.js +29 -0
  14. package/dist/server/better-auth/revokeUnadmitted.js.map +1 -0
  15. package/dist/server/better-auth/signInGate.d.ts +37 -0
  16. package/dist/server/better-auth/signInGate.d.ts.map +1 -0
  17. package/dist/server/better-auth/signInGate.js +38 -0
  18. package/dist/server/better-auth/signInGate.js.map +1 -0
  19. package/dist/server/better-auth/signInPolicy.d.ts +193 -0
  20. package/dist/server/better-auth/signInPolicy.d.ts.map +1 -0
  21. package/dist/server/better-auth/signInPolicy.js +61 -0
  22. package/dist/server/better-auth/signInPolicy.js.map +1 -0
  23. package/dist/server/databaseLayer.d.ts.map +1 -1
  24. package/dist/server/databaseLayer.js +18 -1
  25. package/dist/server/databaseLayer.js.map +1 -1
  26. package/package.json +4 -3
  27. package/src/server/better-auth/allowedAccounts.ts +29 -0
  28. package/src/server/better-auth/mount.ts +49 -2
  29. package/src/server/better-auth/revokeUnadmitted.ts +41 -0
  30. package/src/server/better-auth/signInGate.ts +77 -0
  31. package/src/server/better-auth/signInPolicy.ts +72 -0
  32. package/src/server/databaseLayer.ts +20 -1
@@ -0,0 +1,193 @@
1
+ import type { BetterAuthOptions, ValidateUserInfoResult, ValidateUserInfoSource } from "better-auth";
2
+ import { Effect } from "effect";
3
+ import { type PolicyStorage, type SignInGate } from "#server/better-auth/signInGate.ts";
4
+ export type PolicyRun = <A, E>(effect: Effect.Effect<A, E>) => Promise<A>;
5
+ export declare function signInPolicyOptions<E>(options: BetterAuthOptions, gate: SignInGate<E>, run: PolicyRun, storage: () => Promise<PolicyStorage>): {
6
+ databaseHooks: {
7
+ user?: {
8
+ create?: {
9
+ before?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
10
+ data: {
11
+ id?: string | undefined;
12
+ createdAt?: Date | undefined;
13
+ updatedAt?: Date | undefined;
14
+ email?: string | undefined;
15
+ emailVerified?: boolean | undefined;
16
+ name?: string | undefined;
17
+ image?: string | null | undefined;
18
+ } & Record<string, any>;
19
+ }>;
20
+ after?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
21
+ };
22
+ update?: {
23
+ before?: (user: Partial<import("better-auth").User> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
24
+ data: {
25
+ [x: string]: any;
26
+ id?: string | undefined;
27
+ createdAt?: Date | undefined;
28
+ updatedAt?: Date | undefined;
29
+ email?: string | undefined;
30
+ emailVerified?: boolean | undefined;
31
+ name?: string | undefined;
32
+ image?: string | null | undefined;
33
+ };
34
+ }>;
35
+ after?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
36
+ };
37
+ delete?: {
38
+ before?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
39
+ after?: (user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
40
+ };
41
+ };
42
+ account?: {
43
+ create?: {
44
+ before?: (account: import("better-auth").Account, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
45
+ data: {
46
+ id?: string | undefined;
47
+ createdAt?: Date | undefined;
48
+ updatedAt?: Date | undefined;
49
+ providerId?: string | undefined;
50
+ accountId?: string | undefined;
51
+ userId?: string | undefined;
52
+ accessToken?: string | null | undefined;
53
+ refreshToken?: string | null | undefined;
54
+ idToken?: string | null | undefined;
55
+ accessTokenExpiresAt?: Date | null | undefined;
56
+ refreshTokenExpiresAt?: Date | null | undefined;
57
+ scope?: string | null | undefined;
58
+ password?: string | null | undefined;
59
+ } & Record<string, any>;
60
+ }>;
61
+ after?: (account: import("better-auth").Account, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
62
+ };
63
+ update?: {
64
+ before?: (account: Partial<import("better-auth").Account> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
65
+ data: {
66
+ [x: string]: any;
67
+ id?: string | undefined;
68
+ createdAt?: Date | undefined;
69
+ updatedAt?: Date | undefined;
70
+ providerId?: string | undefined;
71
+ accountId?: string | undefined;
72
+ userId?: string | undefined;
73
+ accessToken?: string | null | undefined;
74
+ refreshToken?: string | null | undefined;
75
+ idToken?: string | null | undefined;
76
+ accessTokenExpiresAt?: Date | null | undefined;
77
+ refreshTokenExpiresAt?: Date | null | undefined;
78
+ scope?: string | null | undefined;
79
+ password?: string | null | undefined;
80
+ };
81
+ }>;
82
+ after?: (account: import("better-auth").Account & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
83
+ };
84
+ delete?: {
85
+ before?: (account: import("better-auth").Account & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
86
+ after?: (account: import("better-auth").Account & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
87
+ };
88
+ };
89
+ verification?: {
90
+ create?: {
91
+ before?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
92
+ data: {
93
+ id?: string | undefined;
94
+ createdAt?: Date | undefined;
95
+ updatedAt?: Date | undefined;
96
+ value?: string | undefined;
97
+ expiresAt?: Date | undefined;
98
+ identifier?: string | undefined;
99
+ } & Record<string, any>;
100
+ }>;
101
+ after?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
102
+ };
103
+ update?: {
104
+ before?: (verification: Partial<import("better-auth").Verification> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
105
+ data: {
106
+ [x: string]: any;
107
+ id?: string | undefined;
108
+ createdAt?: Date | undefined;
109
+ updatedAt?: Date | undefined;
110
+ value?: string | undefined;
111
+ expiresAt?: Date | undefined;
112
+ identifier?: string | undefined;
113
+ };
114
+ }>;
115
+ after?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
116
+ };
117
+ delete?: {
118
+ before?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
119
+ after?: (verification: import("better-auth").Verification & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
120
+ };
121
+ };
122
+ session: {
123
+ update?: {
124
+ before?: (session: Partial<import("better-auth").Session> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
125
+ data: {
126
+ [x: string]: any;
127
+ id?: string | undefined;
128
+ createdAt?: Date | undefined;
129
+ updatedAt?: Date | undefined;
130
+ userId?: string | undefined;
131
+ expiresAt?: Date | undefined;
132
+ token?: string | undefined;
133
+ ipAddress?: string | null | undefined;
134
+ userAgent?: string | null | undefined;
135
+ };
136
+ }>;
137
+ after?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
138
+ };
139
+ delete?: {
140
+ before?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void>;
141
+ after?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
142
+ };
143
+ create: {
144
+ after?: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>;
145
+ before: (session: import("better-auth").Session & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<boolean | void | {
146
+ data: {
147
+ id?: string | undefined;
148
+ createdAt?: Date | undefined;
149
+ updatedAt?: Date | undefined;
150
+ userId?: string | undefined;
151
+ expiresAt?: Date | undefined;
152
+ token?: string | undefined;
153
+ ipAddress?: string | null | undefined;
154
+ userAgent?: string | null | undefined;
155
+ } & Record<string, any>;
156
+ }>;
157
+ };
158
+ };
159
+ };
160
+ user: {
161
+ modelName?: "user" | import("better-auth").LiteralString;
162
+ fields?: Partial<Record<"createdAt" | "email" | "emailVerified" | "image" | "name" | "updatedAt", string>>;
163
+ additionalFields?: {
164
+ [x: string]: import("better-auth").DBFieldAttribute;
165
+ };
166
+ changeEmail?: {
167
+ enabled: boolean;
168
+ sendChangeEmailConfirmation?: (data: {
169
+ user: import("better-auth").User;
170
+ newEmail: string;
171
+ url: string;
172
+ token: string;
173
+ }, request?: Request) => Promise<void>;
174
+ updateEmailWithoutVerification?: boolean;
175
+ };
176
+ deleteUser?: {
177
+ enabled?: boolean;
178
+ sendDeleteAccountVerification?: (data: {
179
+ user: import("better-auth").User;
180
+ url: string;
181
+ token: string;
182
+ }, request?: Request) => Promise<void>;
183
+ beforeDelete?: (user: import("better-auth").User, request?: Request) => Promise<void>;
184
+ afterDelete?: (user: import("better-auth").User, request?: Request) => Promise<void>;
185
+ deleteTokenExpiresIn?: number;
186
+ };
187
+ validateUserInfo: (data: {
188
+ user: Partial<import("better-auth").User> & Record<string, unknown>;
189
+ source: ValidateUserInfoSource;
190
+ }, context: import("better-auth").GenericEndpointContext) => import("better-auth").Awaitable<void | ValidateUserInfoResult>;
191
+ };
192
+ };
193
+ //# sourceMappingURL=signInPolicy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signInPolicy.d.ts","sourceRoot":"","sources":["../../../src/server/better-auth/signInPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,MAAM,EAAQ,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAe,KAAK,aAAa,EAAE,KAAK,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAKrG,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;AAwB1E,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuC5I"}
@@ -0,0 +1,61 @@
1
+ import { APIError } from "better-auth/api";
2
+ import { Effect, Exit } from "effect";
3
+ import { fromStorage } from "#server/better-auth/signInGate.ts";
4
+ import { redact } from "#server/rpc-server/redact.ts";
5
+ const REFUSED_MESSAGE = "This account may not sign in";
6
+ const UNAVAILABLE_MESSAGE = "Sign-in is temporarily unavailable";
7
+ const refused = { error: "sign_in_refused", errorDescription: REFUSED_MESSAGE };
8
+ const unavailable = { error: "sign_in_unavailable", errorDescription: UNAVAILABLE_MESSAGE };
9
+ function logged(effect) {
10
+ return Effect.tapCause(effect, (cause) => Effect.logError("Sign-in policy check failed", redact(cause)));
11
+ }
12
+ async function signingInAccount(source, providers) {
13
+ const profile = source.oauth?.profile;
14
+ const provider = providers.find(({ id }) => id === source.oauth?.providerId);
15
+ if (source.method !== "oauth" || profile === undefined || provider === undefined) {
16
+ return undefined;
17
+ }
18
+ const subject = await provider.accountSubject({ profile, tokens: {} });
19
+ return typeof subject === "string" || typeof subject === "number" ? { accountId: String(subject), providerId: provider.id } : undefined;
20
+ }
21
+ export function signInPolicyOptions(options, gate, run, storage) {
22
+ const sessionBefore = options.databaseHooks?.session?.create?.before;
23
+ const before = async (session, endpoint) => {
24
+ const own = await sessionBefore?.(session, endpoint);
25
+ if (own === false) {
26
+ return own;
27
+ }
28
+ const userId = typeof own === "object" && typeof own.data.userId === "string" ? own.data.userId : session.userId;
29
+ const exit = await run(Effect.exit(logged(Effect.flatMap(fromStorage(storage), (auth) => gate.admitsUser(auth, userId)))));
30
+ if (Exit.isFailure(exit)) {
31
+ throw new APIError("SERVICE_UNAVAILABLE", { code: unavailable.error, message: UNAVAILABLE_MESSAGE });
32
+ }
33
+ if (!exit.value) {
34
+ throw new APIError("FORBIDDEN", { code: refused.error, message: REFUSED_MESSAGE });
35
+ }
36
+ return own;
37
+ };
38
+ const validateUserInfo = async (data, endpoint) => {
39
+ const own = await options.user?.validateUserInfo?.(data, endpoint);
40
+ if (own !== undefined || data.source.action !== "create-user") {
41
+ return own;
42
+ }
43
+ const account = await signingInAccount(data.source, endpoint.context.socialProviders).catch(() => undefined);
44
+ if (account === undefined) {
45
+ return refused;
46
+ }
47
+ const exit = await run(Effect.exit(logged(gate.admits([account]))));
48
+ if (Exit.isFailure(exit)) {
49
+ return unavailable;
50
+ }
51
+ return exit.value ? undefined : refused;
52
+ };
53
+ return {
54
+ databaseHooks: {
55
+ ...options.databaseHooks,
56
+ session: { ...options.databaseHooks?.session, create: { ...options.databaseHooks?.session?.create, before } },
57
+ },
58
+ user: { ...options.user, validateUserInfo },
59
+ };
60
+ }
61
+ //# sourceMappingURL=signInPolicy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signInPolicy.js","sourceRoot":"","sources":["../../../src/server/better-auth/signInPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,WAAW,EAAuC,MAAM,mCAAmC,CAAC;AACrG,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AAMtD,MAAM,eAAe,GAAG,8BAA8B,CAAC;AACvD,MAAM,mBAAmB,GAAG,oCAAoC,CAAC;AACjE,MAAM,OAAO,GAA2B,EAAE,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,eAAe,EAAE,CAAC;AACxG,MAAM,WAAW,GAA2B,EAAE,KAAK,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC;AAEpH,SAAS,MAAM,CAAO,MAA2B;IAChD,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,6BAA6B,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC1G,CAAC;AAED,KAAK,UAAU,gBAAgB,CAC9B,MAA8B,EAC9B,SAAiI;IAEjI,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC;IACtC,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,KAAK,MAAM,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAC7E,IAAI,MAAM,CAAC,MAAM,KAAK,OAAO,IAAI,OAAO,KAAK,SAAS,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAClF,OAAO,SAAS,CAAC;I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
+ {"version":3,"file":"databaseLayer.d.ts","sourceRoot":"","sources":["../../src/server/databaseLayer.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,QAAQ,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAU,KAAK,EAAE,QAAQ,EAAY,MAAM,QAAQ,CAAC;AACnE,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAG3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AAEhF,OAAO,EAAE,KAAK,sBAAsB,EAAmB,MAAM,0CAA0C,CAAC;AACxG,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAGzE,MAAM,WAAW,cAAe,SAAQ,iBAAiB;IACxD,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB,EAAE,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC;IAC9E,QAAQ,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjD,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,EAAE,kBAAkB,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,OAAO,UAAU,+UA8CjG"}
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { createConnection } from "node:net";
2
3
  import * as PgClient from "@effect/sql-pg/PgClient";
3
4
  import { Config, Effect, Layer, Redacted, Schedule } from "effect";
4
5
  import * as Reactivity from "effect/reactivity/Reactivity";
@@ -10,11 +11,27 @@ import { databaseAddress } from "./databaseAddress.js";
10
11
  export function databaseLayer(options, changesService) {
11
12
  const pool = Layer.unwrap(Effect.gen(function* () {
12
13
  const url = options.config?.databaseUrl ?? (yield* Config.Redacted("DATABASE_URL"));
14
+ const address = databaseAddress(url);
15
+ const disconnected = new Set();
16
+ // Native pool shutdown sends Terminate without waiting for its sockets to close.
17
+ yield* Effect.addFinalizer(() => Effect.promise(() => Promise.all([...disconnected])));
13
18
  return PgClient.layer({
19
+ stream: () => {
20
+ const target = new URL(Redacted.value(url));
21
+ const host = address.host ?? target.searchParams.getAll("host").at(-1) ?? (decodeURIComponent(target.hostname) || "localhost");
22
+ const port = address.port ?? 5432;
23
+ const socket = createConnection(host.startsWith("/") ? { path: `${host}/.s.PGSQL.${port}` } : { host, noDelay: true, port });
24
+ const closed = new Promise((resolve) => socket.once("close", () => {
25
+ disconnected.delete(closed);
26
+ resolve();
27
+ }));
28
+ disconnected.add(closed);
29
+ return socket;
30
+ },
14
31
  transformQueryNames: options.config?.transformQueryNames,
15
32
  transformResultNames: options.config?.transformResultNames,
16
33
  url,
17
- ...databaseAddress(url),
34
+ ...address,
18
35
  ...(options.config?.maxConnections === undefined ? {} : { maxConnections: options.config.maxConnections }),
19
36
  ...(options.config?.applicationName === undefined ? {} : { applicationName: options.config.applicationName }),
20
37
  });
@@ -1 +1 @@
1
- {"version":3,"file":"databaseLayer.js","sourceRoot":"","sources":["../../src/server/databaseLayer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,QAAQ,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACnE,OAAO,KAAK,UAAU,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,8CAA8C,CAAC;AAC9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,mDAAmD,CAAC;AAE7F,OAAO,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AACtE,OAAO,EAA+B,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAExG,OAAO,EA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AAe,CAAC,EAAE,GAAG,UAAU,EAAE,WAAW,EAAE,UAAU,CAAC,WAAW,IAAI,WAAW,EAAE,CAAC,CAAC;IAChG,CAAC;AACF,CAAC;AAED,SAAS,iBAAiB,CAAI,UAA+C;IAC5E,OAAO,wBAAwB,CAAC,UAAU,CAAC,CAAC,IAAI,CAC/C,MAAM,CAAC,KAAK,CAAC;QACZ,QAAQ,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,YAAY,IAAI,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,IAAI,WAAW,CAAC,CAAC,CAAC;QACxI,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,gBAAgB,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;KAC9E,CAAC,CACF,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/platform",
3
- "version": "0.22.1",
3
+ "version": "0.23.1",
4
4
  "description": "Opinionated Effect application infrastructure for ShivaeDev services",
5
5
  "homepage": "https://github.com/ShivaeDev/platform/tree/main/packages/platform#readme",
6
6
  "bugs": {
@@ -41,7 +41,7 @@
41
41
  ],
42
42
  "dependencies": {
43
43
  "@shivaedev/effect-contract": "0.10.0",
44
- "@shivaedev/effect-sql": "0.12.0",
44
+ "@shivaedev/effect-sql": "0.13.0",
45
45
  "@shivaedev/types": "0.2.1"
46
46
  },
47
47
  "devDependencies": {
@@ -55,7 +55,8 @@
55
55
  "@prisma-next/sql-orm-client": "0.16.0",
56
56
  "@prisma-next/target-postgres": "0.16.0",
57
57
  "@shivaedev/effect-prisma": "0.10.2",
58
- "@shivaedev/effect-test-sql": "0.8.1",
58
+ "@shivaedev/effect-test": "0.7.1",
59
+ "@shivaedev/effect-test-sql": "0.8.2",
59
60
  "@shivaedev/effect-trpc": "0.8.2",
60
61
  "@shivaedev/quality": "0.31.0",
61
62
  "@shivaedev/test-story": "0.17.0",
@@ -0,0 +1,29 @@
1
+ import { Config, Schema, SchemaGetter } from "effect";
2
+
3
+ const ProviderAccount = Schema.Struct({ accountId: Schema.NonEmptyString, providerId: Schema.NonEmptyString });
4
+
5
+ const AccountEntry = Schema.String.pipe(
6
+ Schema.decodeTo(ProviderAccount, {
7
+ decode: SchemaGetter.transform((entry) => {
8
+ const separator = entry.indexOf(":");
9
+ return separator < 0
10
+ ? { accountId: "", providerId: entry }
11
+ : { accountId: entry.slice(separator + 1).trim(), providerId: entry.slice(0, separator).trim() };
12
+ }),
13
+ encode: SchemaGetter.transform(({ accountId, providerId }) => `${providerId}:${accountId}`),
14
+ }),
15
+ );
16
+
17
+ export const AllowedAccounts = Schema.String.pipe(
18
+ Schema.decodeTo(Schema.Array(AccountEntry).check(Schema.isMinLength(1)), {
19
+ decode: SchemaGetter.transform((value) =>
20
+ value
21
+ .split(",")
22
+ .map((entry) => entry.trim())
23
+ .filter((entry) => entry.length > 0),
24
+ ),
25
+ encode: SchemaGetter.transform((entries) => entries.join(",")),
26
+ }),
27
+ );
28
+
29
+ export const allowedAccounts = Config.schema(AllowedAccounts, "AUTH_ALLOWED_ACCOUNTS");
@@ -2,9 +2,21 @@ import { type BetterAuthOptions, betterAuth } from "better-auth";
2
2
  import { Config, Effect, Option, Redacted } from "effect";
3
3
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
4
4
  import { Pool, type PoolClient } from "pg";
5
+ import { type RevokeUnadmitted, revokeUnadmitted } from "#server/better-auth/revokeUnadmitted.ts";
6
+ import { type PolicyStorage, type SignInPolicy, signInGate } from "#server/better-auth/signInGate.ts";
7
+ import { signInPolicyOptions } from "#server/better-auth/signInPolicy.ts";
8
+ import type { GetSession } from "#server/rpc-server/adapters/betterAuthSessions.ts";
5
9
  import { trustedProxyPeer, trustedProxyRanges } from "#server/rpc-server/local.ts";
10
+ import type { SessionShape } from "#server/rpc-server/session.ts";
6
11
 
7
- export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <const TOptions extends BetterAuthOptions>(options: TOptions) {
12
+ export interface BetterAuthMountOptions<E = never, R = never> {
13
+ readonly signIn?: SignInPolicy<E, R> | undefined;
14
+ }
15
+
16
+ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <const TOptions extends BetterAuthOptions, E = never, R = never>(
17
+ options: TOptions,
18
+ mount: BetterAuthMountOptions<E, R> = {},
19
+ ) {
8
20
  const secret = options.secret ?? Redacted.value(yield* Config.Redacted("BETTER_AUTH_SECRET"));
9
21
  const publicUrl = yield* Config.URL("PUBLIC_URL").pipe(Config.option);
10
22
  const origin = Option.map(publicUrl, (url) => url.origin);
@@ -13,6 +25,14 @@ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <
13
25
  const rateLimitEnabled = yield* Config.Boolean("AUTH_RATE_LIMIT_ENABLED").pipe(Config.withDefault(true));
14
26
  const isTrustedProxy = trustedProxyPeer(trustedProxy);
15
27
  const trustedProxies = trustedProxyRanges(trustedProxy);
28
+ const context = yield* Effect.context<R>();
29
+ const run = Effect.runPromiseWith(context);
30
+ const policy = mount.signIn ?? {};
31
+ if (policy.accounts !== undefined) {
32
+ yield* policy.accounts;
33
+ }
34
+ const gate = yield* signInGate(policy);
35
+ const gated = signInPolicyOptions(options, gate, run, (): Promise<PolicyStorage> => auth.$context);
16
36
  const auth = betterAuth({
17
37
  ...options,
18
38
  advanced: {
@@ -25,9 +45,11 @@ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <
25
45
  },
26
46
  },
27
47
  "baseURL": options.baseURL ?? Option.getOrElse(origin, () => ({ allowedHosts: ["127.0.0.1:*"], protocol: "http" as const })),
48
+ databaseHooks: gate.active ? gated.databaseHooks : options.databaseHooks,
28
49
  rateLimit: { ...options.rateLimit, enabled: rateLimitEnabled },
29
50
  secret,
30
51
  trustedOrigins: options.trustedOrigins ?? [Option.getOrElse(origin, () => "http://127.0.0.1:*")],
52
+ user: gate.active ? gated.user : options.user,
31
53
  });
32
54
  const routes = HttpRouter.use((router) =>
33
55
  router.add("*", "/api/auth/*", (request) =>
@@ -41,7 +63,32 @@ export const betterAuthMount = Effect.fn("Platform.betterAuthMount")(function* <
41
63
  }).pipe(Effect.catch(() => Effect.succeed(HttpServerResponse.text("Authentication is temporarily unavailable", { status: 503 })))),
42
64
  ),
43
65
  );
44
- return { auth, routes };
66
+ function admittedSessions<TSession extends SessionShape>(getSession: GetSession<TSession>): GetSession<TSession> {
67
+ if (!gate.active) {
68
+ return getSession;
69
+ }
70
+ return (headers) =>
71
+ run(
72
+ Effect.gen(function* () {
73
+ const session = yield* Effect.tryPromise(() => getSession(headers));
74
+ if (session === null) {
75
+ return null;
76
+ }
77
+ const storage = yield* Effect.tryPromise(() => auth.$context);
78
+ if (yield* gate.admitsUser(storage, session.user.id)) {
79
+ return session;
80
+ }
81
+ yield* Effect.tryPromise(() => storage.internalAdapter.deleteUserSessions(session.user.id));
82
+ yield* Effect.logInfo("The sign-in policy revoked a user's sessions").pipe(Effect.annotateLogs({ userId: session.user.id }));
83
+ return null;
84
+ }),
85
+ );
86
+ }
87
+ const revoke: RevokeUnadmitted<E> = Effect.provideContext(
88
+ revokeUnadmitted(gate, () => auth.$context),
89
+ context,
90
+ );
91
+ return { admittedSessions, auth, revokeUnadmitted: revoke, routes };
45
92
  });
46
93
 
47
94
  export const authDatabase = Effect.fn("Platform.authDatabase")(function* (url: Redacted.Redacted<string>) {
@@ -0,0 +1,41 @@
1
+ import { type Config, Effect } from "effect";
2
+ import type { AuthUnavailable } from "#errors/taxonomy.ts";
3
+ import { fromStorage, type PolicyStorage, type SignInGate } from "#server/better-auth/signInGate.ts";
4
+
5
+ export interface RevokedSessions {
6
+ readonly sessions: number;
7
+ readonly users: number;
8
+ }
9
+
10
+ export type RevokeUnadmitted<E> = Effect.Effect<RevokedSessions, E | Config.ConfigError | AuthUnavailable>;
11
+
12
+ const PAGE_SIZE = 100;
13
+
14
+ export const revokeUnadmitted = Effect.fnUntraced(function* <E>(
15
+ gate: SignInGate<E>,
16
+ storage: () => Promise<PolicyStorage>,
17
+ ): Effect.fn.Return<RevokedSessions, E | Config.ConfigError | AuthUnavailable> {
18
+ if (!gate.active) {
19
+ return { sessions: 0, users: 0 } satisfies RevokedSessions;
20
+ }
21
+ const auth = yield* fromStorage(storage);
22
+ const revoked: Array<{ readonly sessions: number; readonly userId: string }> = [];
23
+ for (let offset = 0; ; offset += PAGE_SIZE) {
24
+ const users = yield* fromStorage(() => auth.internalAdapter.listUsers(PAGE_SIZE, offset, { direction: "asc", field: "id" }));
25
+ for (const { id } of users) {
26
+ if (!(yield* gate.admitsUser(auth, id))) {
27
+ const sessions = Number(yield* fromStorage(() => auth.adapter.count({ model: "session", where: [{ field: "userId", value: id }] })));
28
+ if (sessions > 0) {
29
+ revoked.push({ sessions, userId: id });
30
+ }
31
+ }
32
+ }
33
+ if (users.length < PAGE_SIZE) {
34
+ break;
35
+ }
36
+ }
37
+ for (const { userId } of revoked) {
38
+ yield* fromStorage(() => auth.internalAdapter.deleteUserSessions(userId));
39
+ }
40
+ return { sessions: revoked.reduce((total, user) => total + user.sessions, 0), users: revoked.length } satisfies RevokedSessions;
41
+ });
@@ -0,0 +1,77 @@
1
+ import { Cache, type Config, Duration, Effect, Exit } from "effect";
2
+ import { AuthUnavailable } from "#errors/taxonomy.ts";
3
+ import type { ProviderAccountValue } from "#rpc/identity.ts";
4
+ import { redact } from "#server/rpc-server/redact.ts";
5
+
6
+ export interface SignInPolicy<E = never, R = never> {
7
+ readonly accounts?: Config.Config<readonly ProviderAccountValue[]> | undefined;
8
+ readonly recheckInterval?: Duration.Input | undefined;
9
+ readonly rule?: ((account: ProviderAccountValue) => Effect.Effect<boolean, E, R>) | undefined;
10
+ }
11
+
12
+ export interface PolicyStorage {
13
+ readonly adapter: {
14
+ readonly count: (query: { readonly model: string; readonly where: Array<{ readonly field: string; readonly value: string }> }) => Promise<number>;
15
+ };
16
+ readonly internalAdapter: {
17
+ readonly deleteUserSessions: (userId: string) => Promise<void>;
18
+ readonly findAccounts: (userId: string) => Promise<readonly ProviderAccountValue[]>;
19
+ readonly listUsers: (
20
+ limit: number,
21
+ offset: number,
22
+ sortBy: { readonly direction: "asc" | "desc"; readonly field: string },
23
+ ) => Promise<readonly { readonly id: string }[]>;
24
+ };
25
+ }
26
+
27
+ export interface SignInGate<E> {
28
+ readonly active: boolean;
29
+ readonly admits: (candidates: readonly ProviderAccountValue[]) => Effect.Effect<boolean, E | Config.ConfigError>;
30
+ readonly admitsUser: (storage: PolicyStorage, userId: string) => Effect.Effect<boolean, E | Config.ConfigError | AuthUnavailable>;
31
+ }
32
+
33
+ const RULE_CACHE_CAPACITY = 10_000;
34
+
35
+ export function fromStorage<A>(read: () => Promise<A>) {
36
+ return Effect.tryPromise(read).pipe(
37
+ Effect.catch((error) =>
38
+ Effect.andThen(
39
+ Effect.logError("Sign-in policy storage failed", redact(error.cause)),
40
+ Effect.fail(new AuthUnavailable({ message: "Authentication is temporarily unavailable" })),
41
+ ),
42
+ ),
43
+ );
44
+ }
45
+
46
+ function sameAccount(left: ProviderAccountValue, right: ProviderAccountValue) {
47
+ return left.providerId === right.providerId && left.accountId === right.accountId;
48
+ }
49
+
50
+ export const signInGate = Effect.fnUntraced(function* <E, R>(policy: SignInPolicy<E, R>): Effect.fn.Return<SignInGate<E>, never, R> {
51
+ const { accounts, rule } = policy;
52
+ const recheckInterval = Duration.fromInputUnsafe(policy.recheckInterval ?? "5 minutes");
53
+ const verdicts =
54
+ rule === undefined
55
+ ? undefined
56
+ : yield* Cache.makeWith(rule, {
57
+ capacity: RULE_CACHE_CAPACITY,
58
+ timeToLive: (exit) => (Exit.isSuccess(exit) ? recheckInterval : Duration.zero),
59
+ });
60
+ const admits = Effect.fnUntraced(function* (candidates: readonly ProviderAccountValue[]) {
61
+ const allowed = accounts === undefined ? undefined : yield* accounts;
62
+ const listed = allowed === undefined ? candidates : candidates.filter((candidate) => allowed.some((entry) => sameAccount(entry, candidate)));
63
+ if (verdicts === undefined) {
64
+ return listed.length > 0;
65
+ }
66
+ for (const { accountId, providerId } of listed) {
67
+ if (yield* Cache.get(verdicts, { accountId, providerId })) {
68
+ return true;
69
+ }
70
+ }
71
+ return false;
72
+ });
73
+ const admitsUser = Effect.fnUntraced(function* (storage: PolicyStorage, userId: string) {
74
+ return yield* admits(yield* fromStorage(() => storage.internalAdapter.findAccounts(userId)));
75
+ });
76
+ return { active: accounts !== undefined || rule !== undefined, admits, admitsUser };
77
+ });