@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
@@ -0,0 +1,55 @@
1
+ // src/errors.ts
2
+ var OAuthProtocolError = class extends Error {
3
+ type = "OAUTH_PROTOCOL_ERROR";
4
+ error;
5
+ errorURI;
6
+ constructor(error, description, errorURI, options) {
7
+ super(description, options);
8
+ this.error = error;
9
+ this.errorURI = errorURI;
10
+ this.name = new.target.name;
11
+ Error.captureStackTrace(this, new.target);
12
+ }
13
+ };
14
+ var AuthInternalError = class extends Error {
15
+ type = "AUTH_INTERNAL_ERROR";
16
+ code;
17
+ constructor(code, message, options) {
18
+ super(message, options);
19
+ this.code = code;
20
+ this.name = new.target.name;
21
+ Error.captureStackTrace(this, new.target);
22
+ }
23
+ };
24
+ var AuthSecurityError = class extends Error {
25
+ type = "AUTH_SECURITY_ERROR";
26
+ code;
27
+ constructor(code, message, options) {
28
+ super(message, options);
29
+ this.code = code;
30
+ this.name = new.target.name;
31
+ Error.captureStackTrace(this, new.target);
32
+ }
33
+ };
34
+ var isNativeError = (error) => {
35
+ return error instanceof Error;
36
+ };
37
+ var isOAuthProtocolError = (error) => {
38
+ return error instanceof OAuthProtocolError;
39
+ };
40
+ var isAuthInternalError = (error) => {
41
+ return error instanceof AuthInternalError;
42
+ };
43
+ var isAuthSecurityError = (error) => {
44
+ return error instanceof AuthSecurityError;
45
+ };
46
+
47
+ export {
48
+ OAuthProtocolError,
49
+ AuthInternalError,
50
+ AuthSecurityError,
51
+ isNativeError,
52
+ isOAuthProtocolError,
53
+ isAuthInternalError,
54
+ isAuthSecurityError
55
+ };
@@ -0,0 +1,39 @@
1
+ import {
2
+ createDerivedSalt
3
+ } from "./chunk-N2APGLXA.js";
4
+ import {
5
+ AuthInternalError
6
+ } from "./chunk-RRLIF4PQ.js";
7
+
8
+ // src/jose.ts
9
+ import "dotenv/config";
10
+ import { createJWT, createJWS, createJWE, createDeriveKey } from "@aura-stack/jose";
11
+ var createJoseInstance = (secret) => {
12
+ const env = process.env;
13
+ secret ??= env.AURA_AUTH_SECRET ?? env.AUTH_SECRET;
14
+ if (!secret) {
15
+ throw new AuthInternalError(
16
+ "JOSE_INITIALIZATION_FAILED",
17
+ "AURA_AUTH_SECRET environment variable is not set and no secret was provided."
18
+ );
19
+ }
20
+ const salt = env.AURA_AUTH_SALT ?? env.AUTH_SALT ?? createDerivedSalt(secret);
21
+ const { derivedKey: derivedSigningKey } = createDeriveKey(secret, salt, "signing");
22
+ const { derivedKey: derivedEncryptionKey } = createDeriveKey(secret, salt, "encryption");
23
+ const { derivedKey: derivedCsrfTokenKey } = createDeriveKey(secret, salt, "csrfToken");
24
+ const { decodeJWT, encodeJWT } = createJWT({ jws: derivedSigningKey, jwe: derivedEncryptionKey });
25
+ const { signJWS, verifyJWS } = createJWS(derivedCsrfTokenKey);
26
+ const { encryptJWE, decryptJWE } = createJWE(derivedEncryptionKey);
27
+ return {
28
+ decodeJWT,
29
+ encodeJWT,
30
+ signJWS,
31
+ verifyJWS,
32
+ encryptJWE,
33
+ decryptJWE
34
+ };
35
+ };
36
+
37
+ export {
38
+ createJoseInstance
39
+ };
@@ -0,0 +1,97 @@
1
+ import {
2
+ getUserInfo
3
+ } from "./chunk-ZLR3LI6X.js";
4
+ import {
5
+ createAccessToken
6
+ } from "./chunk-4V4JNXVF.js";
7
+ import {
8
+ createSessionCookie,
9
+ expiredCookieAttributes,
10
+ getCookie
11
+ } from "./chunk-IMICRJ5U.js";
12
+ import {
13
+ cacheControl
14
+ } from "./chunk-STHEPPUZ.js";
15
+ import {
16
+ OAuthAuthorizationErrorResponse,
17
+ OAuthAuthorizationResponse
18
+ } from "./chunk-WD7AUHQ5.js";
19
+ import {
20
+ createCSRF
21
+ } from "./chunk-N2APGLXA.js";
22
+ import {
23
+ equals,
24
+ isValidRelativePath,
25
+ sanitizeURL
26
+ } from "./chunk-CXLATHS5.js";
27
+ import {
28
+ AuthSecurityError,
29
+ OAuthProtocolError
30
+ } from "./chunk-RRLIF4PQ.js";
31
+
32
+ // src/actions/callback/callback.ts
33
+ import z from "zod";
34
+ import { createEndpoint, createEndpointConfig, HeadersBuilder } from "@aura-stack/router";
35
+ var callbackConfig = (oauth) => {
36
+ return createEndpointConfig("/callback/:oauth", {
37
+ schemas: {
38
+ searchParams: OAuthAuthorizationResponse,
39
+ params: z.object({
40
+ oauth: z.enum(Object.keys(oauth), "The OAuth provider is not supported or invalid.")
41
+ })
42
+ },
43
+ middlewares: [
44
+ (ctx) => {
45
+ const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams);
46
+ if (response.success) {
47
+ const { error, error_description } = response.data;
48
+ throw new OAuthProtocolError(error, error_description ?? "OAuth Authorization Error");
49
+ }
50
+ return ctx;
51
+ }
52
+ ]
53
+ });
54
+ };
55
+ var callbackAction = (oauth) => {
56
+ return createEndpoint(
57
+ "GET",
58
+ "/callback/:oauth",
59
+ async (ctx) => {
60
+ const {
61
+ request,
62
+ params: { oauth: oauth2 },
63
+ searchParams: { code, state },
64
+ context: { oauth: providers, cookies, jose }
65
+ } = ctx;
66
+ const oauthConfig = providers[oauth2];
67
+ const cookieState = getCookie(request, cookies.state.name);
68
+ const cookieRedirectTo = getCookie(request, cookies.redirect_to.name);
69
+ const cookieRedirectURI = getCookie(request, cookies.redirect_uri.name);
70
+ const codeVerifier = getCookie(request, cookies.code_verifier.name);
71
+ if (!equals(cookieState, state)) {
72
+ throw new AuthSecurityError(
73
+ "MISMATCHING_STATE",
74
+ "The provided state passed in the OAuth response does not match the stored state."
75
+ );
76
+ }
77
+ const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier);
78
+ const sanitized = sanitizeURL(cookieRedirectTo);
79
+ if (!isValidRelativePath(sanitized)) {
80
+ throw new AuthSecurityError(
81
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
82
+ "Invalid redirect path. Potential open redirect attack detected."
83
+ );
84
+ }
85
+ const userInfo = await getUserInfo(oauthConfig, accessToken.access_token);
86
+ const sessionCookie = await createSessionCookie(jose, userInfo);
87
+ const csrfToken = await createCSRF(jose);
88
+ const headers = new HeadersBuilder(cacheControl).setHeader("Location", sanitized).setCookie(cookies.sessionToken.name, sessionCookie, cookies.sessionToken.attributes).setCookie(cookies.csrfToken.name, csrfToken, cookies.csrfToken.attributes).setCookie(cookies.state.name, "", expiredCookieAttributes).setCookie(cookies.redirect_uri.name, "", expiredCookieAttributes).setCookie(cookies.redirect_to.name, "", expiredCookieAttributes).setCookie(cookies.code_verifier.name, "", expiredCookieAttributes).toHeaders();
89
+ return Response.json({ oauth: oauth2 }, { status: 302, headers });
90
+ },
91
+ callbackConfig(oauth)
92
+ );
93
+ };
94
+
95
+ export {
96
+ callbackAction
97
+ };
@@ -1,10 +1,10 @@
1
1
  // src/schemas.ts
2
- import { object, string, enum as options, number, url } from "zod/v4";
2
+ import { object, string, enum as options, number, httpUrl, z } from "zod/v4";
3
3
  var OAuthProviderConfigSchema = object({
4
- authorizeURL: url(),
5
- accessToken: url(),
4
+ authorizeURL: httpUrl(),
5
+ accessToken: httpUrl(),
6
6
  scope: string().optional(),
7
- userInfo: url(),
7
+ userInfo: httpUrl(),
8
8
  responseType: options(["code", "token", "id_token"]),
9
9
  clientId: string(),
10
10
  clientSecret: string()
@@ -16,8 +16,8 @@ var OAuthAuthorization = OAuthProviderConfigSchema.extend({
16
16
  codeChallengeMethod: options(["plain", "S256"])
17
17
  });
18
18
  var OAuthAuthorizationResponse = object({
19
- state: string(),
20
- code: string()
19
+ state: string("Missing state parameter in the OAuth authorization response."),
20
+ code: string("Missing code parameter in the OAuth authorization response.")
21
21
  });
22
22
  var OAuthAuthorizationErrorResponse = object({
23
23
  error: options([
@@ -61,6 +61,10 @@ var OAuthErrorResponse = object({
61
61
  error: string(),
62
62
  error_description: string().optional()
63
63
  });
64
+ var OAuthEnvSchema = object({
65
+ clientId: z.string().min(1, "OAuth Client ID is required in the environment variables."),
66
+ clientSecret: z.string().min(1, "OAuth Client Secret is required in the environment variables.")
67
+ });
64
68
 
65
69
  export {
66
70
  OAuthProviderConfigSchema,
@@ -70,5 +74,6 @@ export {
70
74
  OAuthAccessToken,
71
75
  OAuthAccessTokenResponse,
72
76
  OAuthAccessTokenErrorResponse,
73
- OAuthErrorResponse
77
+ OAuthErrorResponse,
78
+ OAuthEnvSchema
74
79
  };
@@ -1,13 +1,14 @@
1
1
  import {
2
- generateSecure
3
- } from "./chunk-GZU3RBTB.js";
2
+ OAuthErrorResponse
3
+ } from "./chunk-WD7AUHQ5.js";
4
4
  import {
5
- AuthError,
6
- throwAuthError
7
- } from "./chunk-FJUDBLCP.js";
5
+ generateSecure
6
+ } from "./chunk-N2APGLXA.js";
8
7
  import {
9
- OAuthErrorResponse
10
- } from "./chunk-HMRKN75I.js";
8
+ OAuthProtocolError,
9
+ isNativeError,
10
+ isOAuthProtocolError
11
+ } from "./chunk-RRLIF4PQ.js";
11
12
 
12
13
  // src/actions/callback/userinfo.ts
13
14
  var getDefaultUserInfo = (profile) => {
@@ -32,11 +33,20 @@ var getUserInfo = async (oauthConfig, accessToken) => {
32
33
  const json = await response.json();
33
34
  const { success, data } = OAuthErrorResponse.safeParse(json);
34
35
  if (success) {
35
- throw new AuthError(data.error, data?.error_description ?? "An error occurred while fetching user information.");
36
+ throw new OAuthProtocolError(
37
+ data.error,
38
+ data?.error_description ?? "An error occurred while fetching user information."
39
+ );
36
40
  }
37
41
  return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
38
42
  } catch (error) {
39
- throw throwAuthError(error, "Failed to retrieve userinfo");
43
+ if (isOAuthProtocolError(error)) {
44
+ throw error;
45
+ }
46
+ if (isNativeError(error)) {
47
+ throw new OAuthProtocolError("invalid_request", error.message, "", { cause: error });
48
+ }
49
+ throw new OAuthProtocolError("invalid_request", "Failed to fetch user information.", "", { cause: error });
40
50
  }
41
51
  };
42
52
 
package/dist/cookie.cjs CHANGED
@@ -21,40 +21,34 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var cookie_exports = {};
22
22
  __export(cookie_exports, {
23
23
  COOKIE_NAME: () => COOKIE_NAME,
24
+ createCookieStore: () => createCookieStore,
24
25
  createSessionCookie: () => createSessionCookie,
25
- defaultCookieConfig: () => defaultCookieConfig,
26
26
  defaultCookieOptions: () => defaultCookieOptions,
27
27
  defaultHostCookieConfig: () => defaultHostCookieConfig,
28
28
  defaultSecureCookieConfig: () => defaultSecureCookieConfig,
29
29
  defaultStandardCookieConfig: () => defaultStandardCookieConfig,
30
- defineDefaultCookieOptions: () => defineDefaultCookieOptions,
31
- expireCookie: () => expireCookie,
32
- expiredCookieOptions: () => expiredCookieOptions,
30
+ defineSecureCookieOptions: () => defineSecureCookieOptions,
31
+ expiredCookieAttributes: () => expiredCookieAttributes,
33
32
  getCookie: () => getCookie,
34
- oauthCookie: () => oauthCookie,
35
- parse: () => import_cookie2.parse,
36
- secureCookieOptions: () => secureCookieOptions,
33
+ getSetCookie: () => getSetCookie,
37
34
  setCookie: () => setCookie
38
35
  });
39
36
  module.exports = __toCommonJS(cookie_exports);
40
- var import_cookie = require("cookie");
37
+ var import_cookie = require("@aura-stack/router/cookie");
41
38
 
42
- // src/error.ts
43
- var AuthError = class extends Error {
44
- constructor(type, message) {
45
- super(message);
46
- this.type = type;
47
- this.name = "AuthError";
39
+ // src/errors.ts
40
+ var AuthInternalError = class extends Error {
41
+ type = "AUTH_INTERNAL_ERROR";
42
+ code;
43
+ constructor(code, message, options) {
44
+ super(message, options);
45
+ this.code = code;
46
+ this.name = new.target.name;
47
+ Error.captureStackTrace(this, new.target);
48
48
  }
49
49
  };
50
50
 
51
- // src/assert.ts
52
- var isRequest = (value) => {
53
- return typeof Request !== "undefined" && value instanceof Request;
54
- };
55
-
56
51
  // src/cookie.ts
57
- var import_cookie2 = require("cookie");
58
52
  var COOKIE_NAME = "aura-auth";
59
53
  var defaultCookieOptions = {
60
54
  httpOnly: true,
@@ -62,140 +56,187 @@ var defaultCookieOptions = {
62
56
  path: "/",
63
57
  maxAge: 60 * 60 * 24 * 15
64
58
  };
65
- var defaultCookieConfig = {
66
- strategy: "standard",
67
- name: COOKIE_NAME,
68
- options: defaultCookieOptions
69
- };
70
59
  var defaultStandardCookieConfig = {
71
60
  secure: false,
72
- httpOnly: true,
73
- prefix: ""
61
+ httpOnly: true
74
62
  };
75
63
  var defaultSecureCookieConfig = {
76
64
  secure: true,
77
- prefix: "__Secure-"
65
+ httpOnly: true
78
66
  };
79
67
  var defaultHostCookieConfig = {
80
68
  secure: true,
81
- prefix: "__Host-",
69
+ httpOnly: true,
82
70
  path: "/",
83
71
  domain: void 0
84
72
  };
85
- var expiredCookieOptions = {
73
+ var oauthCookieOptions = {
74
+ httpOnly: true,
75
+ maxAge: 5 * 60,
76
+ sameSite: "lax",
77
+ expires: new Date(Date.now() + 5 * 60 * 1e3)
78
+ };
79
+ var setCookie = (cookieName, value, options) => {
80
+ return (0, import_cookie.serialize)(cookieName, value, options);
81
+ };
82
+ var expiredCookieAttributes = {
86
83
  ...defaultCookieOptions,
87
84
  expires: /* @__PURE__ */ new Date(0),
88
85
  maxAge: 0
89
86
  };
90
- var defineDefaultCookieOptions = (options) => {
91
- return {
92
- name: options?.name ?? COOKIE_NAME,
93
- prefix: options?.prefix ?? (options?.secure ? "__Secure-" : ""),
94
- ...defaultCookieOptions,
95
- ...options
96
- };
97
- };
98
- var setCookie = (cookieName, value, options) => {
99
- const { prefix, name } = defineDefaultCookieOptions(options);
100
- const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`;
101
- return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
102
- ...defaultCookieOptions,
103
- ...options
104
- });
105
- };
106
- var getCookie = (petition, cookie, options, optional = false) => {
107
- const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ");
87
+ var getCookie = (request, cookieName) => {
88
+ const cookies = request.headers.get("Cookie");
108
89
  if (!cookies) {
109
- if (optional) {
110
- return "";
111
- }
112
- throw new AuthError("invalid_request", "No cookies found. There is no active session");
90
+ throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
113
91
  }
114
- const { name, prefix } = defineDefaultCookieOptions(options);
115
- const parsedCookies = (0, import_cookie.parse)(cookies);
116
- const value = parsedCookies[`${prefix}${name}.${cookie}`];
117
- if (value === void 0) {
118
- if (optional) {
119
- return "";
120
- }
121
- throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`);
92
+ const value = (0, import_cookie.parse)(cookies)[cookieName];
93
+ if (!value) {
94
+ throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
122
95
  }
123
96
  return value;
124
97
  };
125
- var createSessionCookie = async (session, cookieOptions, jose) => {
98
+ var getSetCookie = (response, cookieName) => {
99
+ const cookies = response.headers.getSetCookie();
100
+ if (!cookies) {
101
+ throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found in response.");
102
+ }
103
+ const strCookie = cookies.find((cookie) => cookie.startsWith(`${cookieName}=`));
104
+ if (!strCookie) {
105
+ throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found in response.`);
106
+ }
107
+ return (0, import_cookie.parseSetCookie)(strCookie).value;
108
+ };
109
+ var createSessionCookie = async (jose, session) => {
126
110
  try {
127
111
  const encoded = await jose.encodeJWT(session);
128
- return setCookie("sessionToken", encoded, cookieOptions);
112
+ return encoded;
129
113
  } catch (error) {
130
- throw new AuthError("server_error", "Failed to create session cookie", { cause: error });
114
+ throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
131
115
  }
132
116
  };
133
- var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
134
- const name = cookieOptions.name ?? COOKIE_NAME;
135
- const isSecure = trustedProxyHeaders ? request.url.startsWith("https://") || request.headers.get("X-Forwarded-Proto") === "https" || request.headers.get("Forwarded")?.includes("proto=https") : request.url.startsWith("https://");
136
- if (!cookieOptions.options?.httpOnly) {
117
+ var defineSecureCookieOptions = (useSecure, attributes, strategy) => {
118
+ if (!attributes.httpOnly) {
137
119
  console.warn(
138
120
  "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
139
121
  );
140
122
  }
141
- if (cookieOptions.options?.domain === "*") {
123
+ if (attributes.domain === "*") {
124
+ attributes.domain = void 0;
142
125
  console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.");
143
126
  }
144
- if (!isSecure) {
145
- const options = cookieOptions.options;
146
- if (options?.secure) {
127
+ if (!useSecure) {
128
+ if (attributes.secure) {
147
129
  console.warn(
148
130
  "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
149
131
  );
150
132
  }
151
- if (options?.sameSite == "none") {
152
- console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.");
133
+ if (attributes.sameSite == "none") {
134
+ attributes.sameSite = "lax";
135
+ console.warn("[WARNING]: SameSite=None requires Secure attribute. Changing SameSite to 'Lax'.");
153
136
  }
154
137
  if (process.env.NODE_ENV === "production") {
155
138
  console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.");
156
139
  }
140
+ if (strategy === "host") {
141
+ console.warn("[WARNING]: __Host- cookies require a secure context. Falling back to standard cookie settings.");
142
+ }
157
143
  return {
158
144
  ...defaultCookieOptions,
159
- ...cookieOptions.options,
160
- sameSite: options?.sameSite === "none" ? "lax" : options?.sameSite ?? "lax",
161
- ...defaultStandardCookieConfig,
162
- name
145
+ ...attributes,
146
+ ...defaultStandardCookieConfig
163
147
  };
164
148
  }
165
- return cookieOptions.strategy === "host" ? {
149
+ return strategy === "host" ? {
166
150
  ...defaultCookieOptions,
167
- ...cookieOptions.options,
168
- ...defaultHostCookieConfig,
169
- name
170
- } : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name };
171
- };
172
- var expireCookie = (name, options) => {
173
- return setCookie(name, "", { ...options, ...expiredCookieOptions });
174
- };
175
- var oauthCookie = (options) => {
151
+ ...attributes,
152
+ ...defaultHostCookieConfig
153
+ } : { ...defaultCookieOptions, ...attributes, ...defaultSecureCookieConfig };
154
+ };
155
+ var createCookieStore = (useSecure, prefix, overrides) => {
156
+ prefix ??= COOKIE_NAME;
157
+ const securePrefix = useSecure ? "__Secure-" : "";
158
+ const hostPrefix = useSecure ? "__Host-" : "";
176
159
  return {
177
- ...options,
178
- secure: options.secure,
179
- httpOnly: options.httpOnly,
180
- maxAge: 5 * 60,
181
- expires: new Date(Date.now() + 5 * 60 * 1e3)
160
+ sessionToken: {
161
+ name: `${securePrefix}${prefix}.${overrides?.sessionToken?.name ?? "sessionToken"}`,
162
+ attributes: defineSecureCookieOptions(
163
+ useSecure,
164
+ {
165
+ ...defaultCookieOptions,
166
+ ...overrides?.sessionToken?.attributes
167
+ },
168
+ overrides?.sessionToken?.attributes?.strategy ?? "secure"
169
+ )
170
+ },
171
+ state: {
172
+ name: `${securePrefix}${prefix}.${overrides?.state?.name ?? "state"}`,
173
+ attributes: defineSecureCookieOptions(
174
+ useSecure,
175
+ {
176
+ ...oauthCookieOptions,
177
+ ...overrides?.state?.attributes
178
+ },
179
+ overrides?.state?.attributes?.strategy ?? "secure"
180
+ )
181
+ },
182
+ csrfToken: {
183
+ name: `${hostPrefix}${prefix}.${overrides?.csrfToken?.name ?? "csrfToken"}`,
184
+ attributes: defineSecureCookieOptions(
185
+ useSecure,
186
+ {
187
+ ...overrides?.csrfToken?.attributes,
188
+ ...defaultHostCookieConfig
189
+ },
190
+ overrides?.csrfToken?.attributes?.strategy ?? "host"
191
+ )
192
+ },
193
+ redirect_to: {
194
+ name: `${securePrefix}${prefix}.${overrides?.redirect_to?.name ?? "redirect_to"}`,
195
+ attributes: defineSecureCookieOptions(
196
+ useSecure,
197
+ {
198
+ ...oauthCookieOptions,
199
+ ...overrides?.redirect_to?.attributes
200
+ },
201
+ overrides?.redirect_to?.attributes?.strategy ?? "secure"
202
+ )
203
+ },
204
+ redirect_uri: {
205
+ name: `${securePrefix}${prefix}.${overrides?.redirect_uri?.name ?? "redirect_uri"}`,
206
+ attributes: defineSecureCookieOptions(
207
+ useSecure,
208
+ {
209
+ ...oauthCookieOptions,
210
+ ...overrides?.redirect_uri?.attributes
211
+ },
212
+ overrides?.redirect_uri?.attributes?.strategy ?? "secure"
213
+ )
214
+ },
215
+ code_verifier: {
216
+ name: `${securePrefix}${prefix}.${overrides?.code_verifier?.name ?? "code_verifier"}`,
217
+ attributes: defineSecureCookieOptions(
218
+ useSecure,
219
+ {
220
+ ...oauthCookieOptions,
221
+ ...overrides?.code_verifier?.attributes
222
+ },
223
+ overrides?.code_verifier?.attributes?.strategy ?? "secure"
224
+ )
225
+ }
182
226
  };
183
227
  };
184
228
  // Annotate the CommonJS export names for ESM import in node:
185
229
  0 && (module.exports = {
186
230
  COOKIE_NAME,
231
+ createCookieStore,
187
232
  createSessionCookie,
188
- defaultCookieConfig,
189
233
  defaultCookieOptions,
190
234
  defaultHostCookieConfig,
191
235
  defaultSecureCookieConfig,
192
236
  defaultStandardCookieConfig,
193
- defineDefaultCookieOptions,
194
- expireCookie,
195
- expiredCookieOptions,
237
+ defineSecureCookieOptions,
238
+ expiredCookieAttributes,
196
239
  getCookie,
197
- oauthCookie,
198
- parse,
199
- secureCookieOptions,
240
+ getSetCookie,
200
241
  setCookie
201
242
  });