@aura-stack/auth 0.1.0 → 0.2.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.
Files changed (99) hide show
  1. package/dist/@types/index.d.ts +3 -4
  2. package/dist/@types/router.d.d.ts +3 -4
  3. package/dist/@types/utility.d.ts +1 -5
  4. package/dist/actions/callback/access-token.cjs +51 -41
  5. package/dist/actions/callback/access-token.d.ts +3 -4
  6. package/dist/actions/callback/access-token.js +4 -3
  7. package/dist/actions/callback/callback.cjs +115 -210
  8. package/dist/actions/callback/callback.d.ts +3 -4
  9. package/dist/actions/callback/callback.js +9 -10
  10. package/dist/actions/callback/userinfo.cjs +35 -22
  11. package/dist/actions/callback/userinfo.d.ts +3 -4
  12. package/dist/actions/callback/userinfo.js +6 -5
  13. package/dist/actions/csrfToken/csrfToken.cjs +34 -103
  14. package/dist/actions/csrfToken/csrfToken.js +6 -6
  15. package/dist/actions/index.cjs +234 -391
  16. package/dist/actions/index.d.ts +3 -4
  17. package/dist/actions/index.js +16 -17
  18. package/dist/actions/session/session.cjs +25 -109
  19. package/dist/actions/session/session.js +4 -5
  20. package/dist/actions/signIn/authorization.cjs +64 -55
  21. package/dist/actions/signIn/authorization.d.ts +3 -4
  22. package/dist/actions/signIn/authorization.js +5 -5
  23. package/dist/actions/signIn/signIn.cjs +84 -206
  24. package/dist/actions/signIn/signIn.d.ts +3 -4
  25. package/dist/actions/signIn/signIn.js +7 -9
  26. package/dist/actions/signOut/signOut.cjs +88 -234
  27. package/dist/actions/signOut/signOut.js +8 -9
  28. package/dist/assert.cjs +5 -0
  29. package/dist/assert.d.ts +9 -1
  30. package/dist/assert.js +3 -1
  31. package/dist/chunk-2RXNXMCZ.js +55 -0
  32. package/dist/{chunk-UJJ7R56J.js → chunk-4V4JNXVF.js} +13 -10
  33. package/dist/chunk-6R2YZ4AC.js +22 -0
  34. package/dist/{chunk-VFTYH33W.js → chunk-7H3OR6UU.js} +29 -9
  35. package/dist/{chunk-256KIVJL.js → chunk-CXLATHS5.js} +53 -9
  36. package/dist/{chunk-6SM22VVJ.js → chunk-EIL2FPSS.js} +5 -1
  37. package/dist/chunk-IMICRJ5U.js +197 -0
  38. package/dist/{chunk-EBPE35JT.js → chunk-IUYZQTJV.js} +0 -1
  39. package/dist/{chunk-GZU3RBTB.js → chunk-N2APGLXA.js} +19 -10
  40. package/dist/chunk-NEVKX6K2.js +70 -0
  41. package/dist/{chunk-XXJKNKGQ.js → chunk-PTJUYB33.js} +9 -13
  42. package/dist/chunk-QDO2KSRJ.js +35 -0
  43. package/dist/{chunk-CAKJT3KS.js → chunk-QEZL7EYN.js} +21 -17
  44. package/dist/chunk-RRLIF4PQ.js +55 -0
  45. package/dist/chunk-TLE4PXY3.js +39 -0
  46. package/dist/chunk-UEH3LVON.js +97 -0
  47. package/dist/{chunk-HMRKN75I.js → chunk-WD7AUHQ5.js} +12 -7
  48. package/dist/{chunk-RLT4RFKV.js → chunk-ZLR3LI6X.js} +19 -9
  49. package/dist/cookie.cjs +140 -99
  50. package/dist/cookie.d.ts +33 -43
  51. package/dist/cookie.js +10 -17
  52. package/dist/errors.cjs +85 -0
  53. package/dist/errors.d.ts +48 -0
  54. package/dist/errors.js +18 -0
  55. package/dist/{index-DpfbvTZ_.d.ts → index-EqsoyjrF.d.ts} +139 -57
  56. package/dist/index.cjs +427 -389
  57. package/dist/index.d.ts +4 -5
  58. package/dist/index.js +37 -26
  59. package/dist/jose.cjs +23 -12
  60. package/dist/jose.d.ts +4 -1
  61. package/dist/jose.js +5 -4
  62. package/dist/oauth/bitbucket.d.ts +3 -4
  63. package/dist/oauth/discord.cjs +0 -1
  64. package/dist/oauth/discord.d.ts +3 -4
  65. package/dist/oauth/discord.js +1 -1
  66. package/dist/oauth/figma.d.ts +3 -4
  67. package/dist/oauth/github.d.ts +3 -4
  68. package/dist/oauth/gitlab.d.ts +3 -4
  69. package/dist/oauth/index.cjs +132 -6
  70. package/dist/oauth/index.d.ts +3 -4
  71. package/dist/oauth/index.js +12 -5
  72. package/dist/oauth/spotify.d.ts +3 -4
  73. package/dist/{response.cjs → oauth/strava.cjs} +21 -9
  74. package/dist/oauth/strava.d.ts +6 -0
  75. package/dist/oauth/strava.js +6 -0
  76. package/dist/oauth/x.d.ts +3 -4
  77. package/dist/schemas.cjs +11 -5
  78. package/dist/schemas.d.ts +70 -67
  79. package/dist/schemas.js +3 -1
  80. package/dist/secure.cjs +27 -19
  81. package/dist/secure.d.ts +3 -4
  82. package/dist/secure.js +4 -3
  83. package/dist/utils.cjs +90 -15
  84. package/dist/utils.d.ts +11 -2
  85. package/dist/utils.js +8 -4
  86. package/package.json +5 -6
  87. package/dist/chunk-FJUDBLCP.js +0 -59
  88. package/dist/chunk-HGJ4TXY4.js +0 -137
  89. package/dist/chunk-JAPMIE6S.js +0 -10
  90. package/dist/chunk-LLR722CL.js +0 -96
  91. package/dist/chunk-SJPDVKUS.js +0 -112
  92. package/dist/chunk-SMQO5WD7.js +0 -30
  93. package/dist/chunk-UTDLUEEG.js +0 -31
  94. package/dist/chunk-ZV4BH47P.js +0 -154
  95. package/dist/error.cjs +0 -88
  96. package/dist/error.d.ts +0 -62
  97. package/dist/error.js +0 -16
  98. package/dist/response.d.ts +0 -10
  99. package/dist/response.js +0 -6
@@ -1,6 +1,3 @@
1
- import {
2
- figma
3
- } from "./chunk-FKRDCWBF.js";
4
1
  import {
5
2
  github
6
3
  } from "./chunk-IKHPGFCW.js";
@@ -10,6 +7,9 @@ import {
10
7
  import {
11
8
  spotify
12
9
  } from "./chunk-E3OXBRYF.js";
10
+ import {
11
+ strava
12
+ } from "./chunk-6R2YZ4AC.js";
13
13
  import {
14
14
  x
15
15
  } from "./chunk-42XB3YCW.js";
@@ -18,7 +18,19 @@ import {
18
18
  } from "./chunk-FIPU4MLT.js";
19
19
  import {
20
20
  discord
21
- } from "./chunk-EBPE35JT.js";
21
+ } from "./chunk-IUYZQTJV.js";
22
+ import {
23
+ figma
24
+ } from "./chunk-FKRDCWBF.js";
25
+ import {
26
+ OAuthEnvSchema
27
+ } from "./chunk-WD7AUHQ5.js";
28
+ import {
29
+ formatZodError
30
+ } from "./chunk-CXLATHS5.js";
31
+ import {
32
+ AuthInternalError
33
+ } from "./chunk-RRLIF4PQ.js";
22
34
 
23
35
  // src/oauth/index.ts
24
36
  var builtInOAuthProviders = {
@@ -28,14 +40,22 @@ var builtInOAuthProviders = {
28
40
  discord,
29
41
  gitlab,
30
42
  spotify,
31
- x
43
+ x,
44
+ strava
32
45
  };
33
46
  var defineOAuthEnvironment = (oauth) => {
34
47
  const env = process.env;
35
- return {
36
- clientId: env[`AURA_AUTH_${oauth.toUpperCase()}_CLIENT_ID`],
37
- clientSecret: env[`AURA_AUTH_${oauth.toUpperCase()}_CLIENT_SECRET`]
38
- };
48
+ const clientIdSuffix = `${oauth.toUpperCase()}_CLIENT_ID`;
49
+ const clientSecretSuffix = `${oauth.toUpperCase()}_CLIENT_SECRET`;
50
+ const loadEnvs = OAuthEnvSchema.safeParse({
51
+ clientId: env[`AURA_AUTH_${clientIdSuffix}`] ?? env[`AUTH_${clientIdSuffix}`] ?? env[`${clientIdSuffix}`],
52
+ clientSecret: env[`AURA_AUTH_${clientSecretSuffix}`] ?? env[`AUTH_${clientSecretSuffix}`] ?? env[`${clientSecretSuffix}`]
53
+ });
54
+ if (!loadEnvs.success) {
55
+ const msg = JSON.stringify(formatZodError(loadEnvs.error), null, 2);
56
+ throw new AuthInternalError("INVALID_ENVIRONMENT_CONFIGURATION", msg);
57
+ }
58
+ return loadEnvs.data;
39
59
  };
40
60
  var defineOAuthProviderConfig = (config) => {
41
61
  if (typeof config === "string") {
@@ -1,9 +1,11 @@
1
1
  import {
2
- isAuthError
3
- } from "./chunk-FJUDBLCP.js";
2
+ isAuthInternalError,
3
+ isAuthSecurityError,
4
+ isOAuthProtocolError
5
+ } from "./chunk-RRLIF4PQ.js";
4
6
 
5
7
  // src/utils.ts
6
- import { isRouterError } from "@aura-stack/router";
8
+ import { isInvalidZodSchemaError, isRouterError } from "@aura-stack/router";
7
9
  var toSnakeCase = (str) => {
8
10
  return str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().replace(/^_+/, "");
9
11
  };
@@ -64,13 +66,35 @@ var isValidRelativePath = (path) => {
64
66
  var onErrorHandler = (error) => {
65
67
  if (isRouterError(error)) {
66
68
  const { message, status, statusText } = error;
67
- return Response.json({ error: "invalid_request", error_description: message }, { status, statusText });
69
+ return Response.json({ type: "ROUTER_ERROR", code: "ROUTER_INTERNAL_ERROR", message }, { status, statusText });
68
70
  }
69
- if (isAuthError(error)) {
70
- const { type, message } = error;
71
- return Response.json({ error: type, error_description: message }, { status: 400 });
71
+ if (isInvalidZodSchemaError(error)) {
72
+ return Response.json({ type: "ROUTER_ERROR", code: "INVALID_REQUEST", message: error.errors }, { status: 422 });
72
73
  }
73
- return Response.json({ error: "server_error", error_description: "An unexpected error occurred" }, { status: 500 });
74
+ if (isOAuthProtocolError(error)) {
75
+ const { error: errorCode, message, type, errorURI } = error;
76
+ return Response.json(
77
+ {
78
+ type,
79
+ error: errorCode,
80
+ error_description: message,
81
+ error_uri: errorURI
82
+ },
83
+ { status: 400 }
84
+ );
85
+ }
86
+ if (isAuthInternalError(error) || isAuthSecurityError(error)) {
87
+ const { type, code, message } = error;
88
+ return Response.json(
89
+ {
90
+ type,
91
+ code,
92
+ message
93
+ },
94
+ { status: 400 }
95
+ );
96
+ }
97
+ return Response.json({ type: "SERVER_ERROR", code: "server_error", message: "An unexpected error occurred" }, { status: 500 });
74
98
  };
75
99
  var getNormalizedOriginPath = (path) => {
76
100
  try {
@@ -85,6 +109,24 @@ var getNormalizedOriginPath = (path) => {
85
109
  var toISOString = (date) => {
86
110
  return new Date(date).toISOString();
87
111
  };
112
+ var useSecureCookies = (request, trustedProxyHeaders) => {
113
+ return trustedProxyHeaders ? request.url.startsWith("https://") || request.headers.get("X-Forwarded-Proto") === "https" || (request.headers.get("Forwarded")?.includes("proto=https") ?? false) : request.url.startsWith("https://");
114
+ };
115
+ var formatZodError = (error) => {
116
+ if (!error.issues || error.issues.length === 0) {
117
+ return {};
118
+ }
119
+ return error.issues.reduce((previous, issue) => {
120
+ const key = issue.path.join(".");
121
+ return {
122
+ ...previous,
123
+ [key]: {
124
+ code: issue.code,
125
+ message: issue.message
126
+ }
127
+ };
128
+ }, {});
129
+ };
88
130
 
89
131
  export {
90
132
  toSnakeCase,
@@ -95,5 +137,7 @@ export {
95
137
  isValidRelativePath,
96
138
  onErrorHandler,
97
139
  getNormalizedOriginPath,
98
- toISOString
140
+ toISOString,
141
+ useSecureCookies,
142
+ formatZodError
99
143
  };
@@ -10,9 +10,13 @@ var isValidURL = (value) => {
10
10
  const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/;
11
11
  return regex.test(value);
12
12
  };
13
+ var isJWTPayloadWithToken = (payload) => {
14
+ return typeof payload === "object" && payload !== null && "token" in payload && typeof payload?.token === "string";
15
+ };
13
16
 
14
17
  export {
15
18
  isFalsy,
16
19
  isRequest,
17
- isValidURL
20
+ isValidURL,
21
+ isJWTPayloadWithToken
18
22
  };
@@ -0,0 +1,197 @@
1
+ import {
2
+ AuthInternalError
3
+ } from "./chunk-RRLIF4PQ.js";
4
+
5
+ // src/cookie.ts
6
+ import { parse, parseSetCookie, serialize } from "@aura-stack/router/cookie";
7
+ var COOKIE_NAME = "aura-auth";
8
+ var defaultCookieOptions = {
9
+ httpOnly: true,
10
+ sameSite: "lax",
11
+ path: "/",
12
+ maxAge: 60 * 60 * 24 * 15
13
+ };
14
+ var defaultStandardCookieConfig = {
15
+ secure: false,
16
+ httpOnly: true
17
+ };
18
+ var defaultSecureCookieConfig = {
19
+ secure: true,
20
+ httpOnly: true
21
+ };
22
+ var defaultHostCookieConfig = {
23
+ secure: true,
24
+ httpOnly: true,
25
+ path: "/",
26
+ domain: void 0
27
+ };
28
+ var oauthCookieOptions = {
29
+ httpOnly: true,
30
+ maxAge: 5 * 60,
31
+ sameSite: "lax",
32
+ expires: new Date(Date.now() + 5 * 60 * 1e3)
33
+ };
34
+ var setCookie = (cookieName, value, options) => {
35
+ return serialize(cookieName, value, options);
36
+ };
37
+ var expiredCookieAttributes = {
38
+ ...defaultCookieOptions,
39
+ expires: /* @__PURE__ */ new Date(0),
40
+ maxAge: 0
41
+ };
42
+ var getCookie = (request, cookieName) => {
43
+ const cookies = request.headers.get("Cookie");
44
+ if (!cookies) {
45
+ throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
46
+ }
47
+ const value = parse(cookies)[cookieName];
48
+ if (!value) {
49
+ throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
50
+ }
51
+ return value;
52
+ };
53
+ var getSetCookie = (response, cookieName) => {
54
+ const cookies = response.headers.getSetCookie();
55
+ if (!cookies) {
56
+ throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found in response.");
57
+ }
58
+ const strCookie = cookies.find((cookie) => cookie.startsWith(`${cookieName}=`));
59
+ if (!strCookie) {
60
+ throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found in response.`);
61
+ }
62
+ return parseSetCookie(strCookie).value;
63
+ };
64
+ var createSessionCookie = async (jose, session) => {
65
+ try {
66
+ const encoded = await jose.encodeJWT(session);
67
+ return encoded;
68
+ } catch (error) {
69
+ throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
70
+ }
71
+ };
72
+ var defineSecureCookieOptions = (useSecure, attributes, strategy) => {
73
+ if (!attributes.httpOnly) {
74
+ console.warn(
75
+ "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
76
+ );
77
+ }
78
+ if (attributes.domain === "*") {
79
+ attributes.domain = void 0;
80
+ console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.");
81
+ }
82
+ if (!useSecure) {
83
+ if (attributes.secure) {
84
+ console.warn(
85
+ "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
86
+ );
87
+ }
88
+ if (attributes.sameSite == "none") {
89
+ attributes.sameSite = "lax";
90
+ console.warn("[WARNING]: SameSite=None requires Secure attribute. Changing SameSite to 'Lax'.");
91
+ }
92
+ if (process.env.NODE_ENV === "production") {
93
+ console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.");
94
+ }
95
+ if (strategy === "host") {
96
+ console.warn("[WARNING]: __Host- cookies require a secure context. Falling back to standard cookie settings.");
97
+ }
98
+ return {
99
+ ...defaultCookieOptions,
100
+ ...attributes,
101
+ ...defaultStandardCookieConfig
102
+ };
103
+ }
104
+ return strategy === "host" ? {
105
+ ...defaultCookieOptions,
106
+ ...attributes,
107
+ ...defaultHostCookieConfig
108
+ } : { ...defaultCookieOptions, ...attributes, ...defaultSecureCookieConfig };
109
+ };
110
+ var createCookieStore = (useSecure, prefix, overrides) => {
111
+ prefix ??= COOKIE_NAME;
112
+ const securePrefix = useSecure ? "__Secure-" : "";
113
+ const hostPrefix = useSecure ? "__Host-" : "";
114
+ return {
115
+ sessionToken: {
116
+ name: `${securePrefix}${prefix}.${overrides?.sessionToken?.name ?? "sessionToken"}`,
117
+ attributes: defineSecureCookieOptions(
118
+ useSecure,
119
+ {
120
+ ...defaultCookieOptions,
121
+ ...overrides?.sessionToken?.attributes
122
+ },
123
+ overrides?.sessionToken?.attributes?.strategy ?? "secure"
124
+ )
125
+ },
126
+ state: {
127
+ name: `${securePrefix}${prefix}.${overrides?.state?.name ?? "state"}`,
128
+ attributes: defineSecureCookieOptions(
129
+ useSecure,
130
+ {
131
+ ...oauthCookieOptions,
132
+ ...overrides?.state?.attributes
133
+ },
134
+ overrides?.state?.attributes?.strategy ?? "secure"
135
+ )
136
+ },
137
+ csrfToken: {
138
+ name: `${hostPrefix}${prefix}.${overrides?.csrfToken?.name ?? "csrfToken"}`,
139
+ attributes: defineSecureCookieOptions(
140
+ useSecure,
141
+ {
142
+ ...overrides?.csrfToken?.attributes,
143
+ ...defaultHostCookieConfig
144
+ },
145
+ overrides?.csrfToken?.attributes?.strategy ?? "host"
146
+ )
147
+ },
148
+ redirect_to: {
149
+ name: `${securePrefix}${prefix}.${overrides?.redirect_to?.name ?? "redirect_to"}`,
150
+ attributes: defineSecureCookieOptions(
151
+ useSecure,
152
+ {
153
+ ...oauthCookieOptions,
154
+ ...overrides?.redirect_to?.attributes
155
+ },
156
+ overrides?.redirect_to?.attributes?.strategy ?? "secure"
157
+ )
158
+ },
159
+ redirect_uri: {
160
+ name: `${securePrefix}${prefix}.${overrides?.redirect_uri?.name ?? "redirect_uri"}`,
161
+ attributes: defineSecureCookieOptions(
162
+ useSecure,
163
+ {
164
+ ...oauthCookieOptions,
165
+ ...overrides?.redirect_uri?.attributes
166
+ },
167
+ overrides?.redirect_uri?.attributes?.strategy ?? "secure"
168
+ )
169
+ },
170
+ code_verifier: {
171
+ name: `${securePrefix}${prefix}.${overrides?.code_verifier?.name ?? "code_verifier"}`,
172
+ attributes: defineSecureCookieOptions(
173
+ useSecure,
174
+ {
175
+ ...oauthCookieOptions,
176
+ ...overrides?.code_verifier?.attributes
177
+ },
178
+ overrides?.code_verifier?.attributes?.strategy ?? "secure"
179
+ )
180
+ }
181
+ };
182
+ };
183
+
184
+ export {
185
+ COOKIE_NAME,
186
+ defaultCookieOptions,
187
+ defaultStandardCookieConfig,
188
+ defaultSecureCookieConfig,
189
+ defaultHostCookieConfig,
190
+ setCookie,
191
+ expiredCookieAttributes,
192
+ getCookie,
193
+ getSetCookie,
194
+ createSessionCookie,
195
+ defineSecureCookieOptions,
196
+ createCookieStore
197
+ };
@@ -18,7 +18,6 @@ var discord = {
18
18
  }
19
19
  return {
20
20
  sub: profile.id,
21
- // https://discord.com/developers/docs/change-log#display-names
22
21
  name: profile.global_name ?? profile.username,
23
22
  email: profile.email ?? "",
24
23
  image
@@ -1,9 +1,12 @@
1
1
  import {
2
2
  equals
3
- } from "./chunk-256KIVJL.js";
3
+ } from "./chunk-CXLATHS5.js";
4
4
  import {
5
- InvalidCsrfTokenError
6
- } from "./chunk-FJUDBLCP.js";
5
+ isJWTPayloadWithToken
6
+ } from "./chunk-EIL2FPSS.js";
7
+ import {
8
+ AuthSecurityError
9
+ } from "./chunk-RRLIF4PQ.js";
7
10
 
8
11
  // src/secure.ts
9
12
  import crypto from "crypto";
@@ -33,19 +36,25 @@ var createCSRF = async (jose, csrfCookie) => {
33
36
  };
34
37
  var verifyCSRF = async (jose, cookie, header) => {
35
38
  try {
36
- const { token: cookieToken } = await jose.verifyJWS(cookie);
37
- const { token: headerToken } = await jose.verifyJWS(header);
38
- const cookieBuffer = Buffer.from(cookieToken);
39
- const headerBuffer = Buffer.from(headerToken);
39
+ const cookiePayload = await jose.verifyJWS(cookie);
40
+ const headerPayload = await jose.verifyJWS(header);
41
+ if (!isJWTPayloadWithToken(cookiePayload)) {
42
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Cookie payload missing token field.");
43
+ }
44
+ if (!isJWTPayloadWithToken(headerPayload)) {
45
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Header payload missing token field.");
46
+ }
47
+ const cookieBuffer = Buffer.from(cookiePayload.token);
48
+ const headerBuffer = Buffer.from(headerPayload.token);
40
49
  if (!equals(headerBuffer.length, cookieBuffer.length)) {
41
- throw new InvalidCsrfTokenError();
50
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
42
51
  }
43
52
  if (!crypto.timingSafeEqual(cookieBuffer, headerBuffer)) {
44
- throw new InvalidCsrfTokenError();
53
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
45
54
  }
46
55
  return true;
47
56
  } catch {
48
- throw new InvalidCsrfTokenError();
57
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
49
58
  }
50
59
  };
51
60
  var createDerivedSalt = (secret) => {
@@ -0,0 +1,70 @@
1
+ import {
2
+ createRedirectTo
3
+ } from "./chunk-QEZL7EYN.js";
4
+ import {
5
+ expiredCookieAttributes
6
+ } from "./chunk-IMICRJ5U.js";
7
+ import {
8
+ cacheControl
9
+ } from "./chunk-STHEPPUZ.js";
10
+ import {
11
+ verifyCSRF
12
+ } from "./chunk-N2APGLXA.js";
13
+ import {
14
+ getNormalizedOriginPath
15
+ } from "./chunk-CXLATHS5.js";
16
+ import {
17
+ AuthSecurityError
18
+ } from "./chunk-RRLIF4PQ.js";
19
+
20
+ // src/actions/signOut/signOut.ts
21
+ import z from "zod";
22
+ import { createEndpoint, createEndpointConfig, HeadersBuilder, statusCode } from "@aura-stack/router";
23
+ var config = createEndpointConfig({
24
+ schemas: {
25
+ searchParams: z.object({
26
+ token_type_hint: z.literal("session_token"),
27
+ redirectTo: z.string().optional()
28
+ })
29
+ }
30
+ });
31
+ var signOutAction = createEndpoint(
32
+ "POST",
33
+ "/signOut",
34
+ async (ctx) => {
35
+ const {
36
+ request,
37
+ headers,
38
+ searchParams: { redirectTo },
39
+ context: { jose, cookies }
40
+ } = ctx;
41
+ const session = headers.getCookie(cookies.sessionToken.name);
42
+ const csrfToken = headers.getCookie(cookies.csrfToken.name);
43
+ const header = headers.getHeader("X-CSRF-Token");
44
+ if (!session) {
45
+ throw new AuthSecurityError("SESSION_TOKEN_MISSING", "The sessionToken is missing.");
46
+ }
47
+ if (!csrfToken) {
48
+ throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF token is missing.");
49
+ }
50
+ if (!header) {
51
+ throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF header is missing.");
52
+ }
53
+ await verifyCSRF(jose, csrfToken, header);
54
+ await jose.decodeJWT(session);
55
+ const normalizedOriginPath = getNormalizedOriginPath(request.url);
56
+ const location = createRedirectTo(
57
+ new Request(normalizedOriginPath, {
58
+ headers: headers.toHeaders()
59
+ }),
60
+ redirectTo
61
+ );
62
+ const headersList = new HeadersBuilder(cacheControl).setHeader("Location", location).setCookie(cookies.csrfToken.name, "", expiredCookieAttributes).setCookie(cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
63
+ return Response.json({ message: "Signed out successfully" }, { status: statusCode.ACCEPTED, headers: headersList });
64
+ },
65
+ config
66
+ );
67
+
68
+ export {
69
+ signOutAction
70
+ };
@@ -1,33 +1,29 @@
1
1
  import {
2
- expireCookie,
3
- getCookie,
4
- secureCookieOptions
5
- } from "./chunk-ZV4BH47P.js";
2
+ expiredCookieAttributes,
3
+ getCookie
4
+ } from "./chunk-IMICRJ5U.js";
6
5
  import {
7
6
  cacheControl
8
7
  } from "./chunk-STHEPPUZ.js";
9
8
  import {
10
9
  toISOString
11
- } from "./chunk-256KIVJL.js";
10
+ } from "./chunk-CXLATHS5.js";
12
11
 
13
12
  // src/actions/session/session.ts
14
- import { createEndpoint } from "@aura-stack/router";
13
+ import { createEndpoint, HeadersBuilder } from "@aura-stack/router";
15
14
  var sessionAction = createEndpoint("GET", "/session", async (ctx) => {
16
15
  const {
17
16
  request,
18
- context: { cookies, jose, trustedProxyHeaders }
17
+ context: { jose, cookies }
19
18
  } = ctx;
20
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders);
21
19
  try {
22
- const session = getCookie(request, "sessionToken", cookieOptions);
20
+ const session = getCookie(request, cookies.sessionToken.name);
23
21
  const decoded = await jose.decodeJWT(session);
24
22
  const { exp, iat, jti, nbf, ...user } = decoded;
25
23
  const headers = new Headers(cacheControl);
26
24
  return Response.json({ user, expires: toISOString(exp * 1e3) }, { headers });
27
- } catch {
28
- const headers = new Headers(cacheControl);
29
- const sessionCookie = expireCookie("sessionToken", cookieOptions);
30
- headers.set("Set-Cookie", sessionCookie);
25
+ } catch (error) {
26
+ const headers = new HeadersBuilder(cacheControl).setCookie(cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
31
27
  return Response.json({ authenticated: false, message: "Unauthorized" }, { status: 401, headers });
32
28
  }
33
29
  });
@@ -0,0 +1,35 @@
1
+ import {
2
+ getCookie,
3
+ setCookie
4
+ } from "./chunk-IMICRJ5U.js";
5
+ import {
6
+ cacheControl
7
+ } from "./chunk-STHEPPUZ.js";
8
+ import {
9
+ createCSRF
10
+ } from "./chunk-N2APGLXA.js";
11
+
12
+ // src/actions/csrfToken/csrfToken.ts
13
+ import { createEndpoint } from "@aura-stack/router";
14
+ var getCSRFToken = (request, cookieName) => {
15
+ try {
16
+ return getCookie(request, cookieName);
17
+ } catch {
18
+ return void 0;
19
+ }
20
+ };
21
+ var csrfTokenAction = createEndpoint("GET", "/csrfToken", async (ctx) => {
22
+ const {
23
+ request,
24
+ context: { jose, cookies }
25
+ } = ctx;
26
+ const token = getCSRFToken(request, cookies.csrfToken.name);
27
+ const csrfToken = await createCSRF(jose, token);
28
+ const headers = new Headers(cacheControl);
29
+ headers.append("Set-Cookie", setCookie(cookies.csrfToken.name, csrfToken, cookies.csrfToken.attributes));
30
+ return Response.json({ csrfToken }, { headers });
31
+ });
32
+
33
+ export {
34
+ csrfTokenAction
35
+ };
@@ -1,27 +1,28 @@
1
1
  import {
2
- isValidURL
3
- } from "./chunk-6SM22VVJ.js";
2
+ OAuthAuthorization
3
+ } from "./chunk-WD7AUHQ5.js";
4
4
  import {
5
5
  equals,
6
+ formatZodError,
6
7
  getNormalizedOriginPath,
7
8
  sanitizeURL,
8
9
  toCastCase
9
- } from "./chunk-256KIVJL.js";
10
+ } from "./chunk-CXLATHS5.js";
10
11
  import {
11
- AuthError,
12
- ERROR_RESPONSE,
13
- InvalidRedirectToError,
14
- isAuthError
15
- } from "./chunk-FJUDBLCP.js";
12
+ isValidURL
13
+ } from "./chunk-EIL2FPSS.js";
16
14
  import {
17
- OAuthAuthorization
18
- } from "./chunk-HMRKN75I.js";
15
+ AuthInternalError,
16
+ AuthSecurityError,
17
+ isAuthSecurityError
18
+ } from "./chunk-RRLIF4PQ.js";
19
19
 
20
20
  // src/actions/signIn/authorization.ts
21
21
  var createAuthorizationURL = (oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod) => {
22
22
  const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod });
23
23
  if (!parsed.success) {
24
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR, "Invalid OAuth configuration");
24
+ const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
25
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
25
26
  }
26
27
  const { authorizeURL, ...options } = parsed.data;
27
28
  const { userInfo, accessToken, clientSecret, ...required } = options;
@@ -54,15 +55,18 @@ var createRedirectTo = (request, redirectTo, trustedProxyHeaders) => {
54
55
  }
55
56
  const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)));
56
57
  if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
57
- throw new InvalidRedirectToError();
58
+ throw new AuthSecurityError(
59
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
60
+ "The redirectTo parameter does not match the hosted origin."
61
+ );
58
62
  }
59
63
  return sanitizeURL(redirectToURL.pathname);
60
64
  }
61
65
  if (referer) {
62
66
  const refererURL = new URL(sanitizeURL(referer));
63
67
  if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
64
- throw new AuthError(
65
- ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST,
68
+ throw new AuthSecurityError(
69
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
66
70
  "The referer of the request does not match the hosted origin."
67
71
  );
68
72
  }
@@ -71,16 +75,16 @@ var createRedirectTo = (request, redirectTo, trustedProxyHeaders) => {
71
75
  if (origin) {
72
76
  const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)));
73
77
  if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
74
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).");
78
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
75
79
  }
76
80
  return sanitizeURL(originURL.pathname);
77
81
  }
78
82
  return "/";
79
83
  } catch (error) {
80
- if (isAuthError(error)) {
84
+ if (isAuthSecurityError(error)) {
81
85
  throw error;
82
86
  }
83
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).");
87
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
84
88
  }
85
89
  };
86
90