@better-auth/sso 1.5.0-beta.6 → 1.5.0-beta.8

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.
@@ -0,0 +1,78 @@
1
+ import type { GenericEndpointContext, StateData } from "better-auth";
2
+ import { generateGenericState, parseGenericState } from "better-auth";
3
+ import { generateRandomString } from "better-auth/crypto";
4
+ import { APIError } from "better-call";
5
+
6
+ export async function generateRelayState(
7
+ c: GenericEndpointContext,
8
+ link:
9
+ | {
10
+ email: string;
11
+ userId: string;
12
+ }
13
+ | undefined,
14
+ additionalData: Record<string, any> | false | undefined,
15
+ ) {
16
+ const callbackURL = c.body.callbackURL;
17
+ if (!callbackURL) {
18
+ throw new APIError("BAD_REQUEST", {
19
+ message: "callbackURL is required",
20
+ });
21
+ }
22
+
23
+ const codeVerifier = generateRandomString(128);
24
+ const stateData: StateData = {
25
+ ...(additionalData ? additionalData : {}),
26
+ callbackURL,
27
+ codeVerifier,
28
+ errorURL: c.body.errorCallbackURL,
29
+ newUserURL: c.body.newUserCallbackURL,
30
+ link,
31
+ /**
32
+ * This is the actual expiry time of the state
33
+ */
34
+ expiresAt: Date.now() + 10 * 60 * 1000,
35
+ requestSignUp: c.body.requestSignUp,
36
+ };
37
+
38
+ try {
39
+ return generateGenericState(c, stateData, {
40
+ cookieName: "relay_state",
41
+ });
42
+ } catch (error) {
43
+ c.context.logger.error(
44
+ "Failed to create verification for relay state",
45
+ error,
46
+ );
47
+ throw new APIError("INTERNAL_SERVER_ERROR", {
48
+ message: "State error: Unable to create verification for relay state",
49
+ cause: error,
50
+ });
51
+ }
52
+ }
53
+
54
+ export async function parseRelayState(c: GenericEndpointContext) {
55
+ const state = c.body.RelayState;
56
+ const errorURL =
57
+ c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
58
+
59
+ let parsedData: StateData;
60
+
61
+ try {
62
+ parsedData = await parseGenericState(c, state, {
63
+ cookieName: "relay_state",
64
+ });
65
+ } catch (error) {
66
+ c.context.logger.error("Failed to parse relay state", error);
67
+ throw new APIError("BAD_REQUEST", {
68
+ message: "State error: failed to validate relay state",
69
+ cause: error,
70
+ });
71
+ }
72
+
73
+ if (!parsedData.errorURL) {
74
+ parsedData.errorURL = errorURL;
75
+ }
76
+
77
+ return parsedData;
78
+ }