@aura-stack/auth 0.1.0-rc.9 → 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 (140) hide show
  1. package/dist/@types/index.cjs +15 -15
  2. package/dist/@types/index.d.ts +6 -31
  3. package/dist/@types/index.js +1 -1
  4. package/dist/@types/router.d.cjs +1 -1
  5. package/dist/@types/router.d.d.ts +6 -7
  6. package/dist/@types/utility.cjs +15 -15
  7. package/dist/@types/utility.d.ts +4 -8
  8. package/dist/@types/utility.js +1 -1
  9. package/dist/actions/callback/access-token.cjs +159 -149
  10. package/dist/actions/callback/access-token.d.ts +14 -20
  11. package/dist/actions/callback/access-token.js +9 -4
  12. package/dist/actions/callback/callback.cjs +371 -484
  13. package/dist/actions/callback/callback.d.ts +9 -12
  14. package/dist/actions/callback/callback.js +15 -12
  15. package/dist/actions/callback/userinfo.cjs +149 -139
  16. package/dist/actions/callback/userinfo.d.ts +8 -9
  17. package/dist/actions/callback/userinfo.js +11 -6
  18. package/dist/actions/csrfToken/csrfToken.cjs +112 -190
  19. package/dist/actions/csrfToken/csrfToken.d.ts +3 -3
  20. package/dist/actions/csrfToken/csrfToken.js +12 -8
  21. package/dist/actions/index.cjs +623 -807
  22. package/dist/actions/index.d.ts +12 -13
  23. package/dist/actions/index.js +33 -18
  24. package/dist/actions/session/session.cjs +86 -176
  25. package/dist/actions/session/session.d.ts +3 -3
  26. package/dist/actions/session/session.js +10 -7
  27. package/dist/actions/signIn/authorization.cjs +248 -257
  28. package/dist/actions/signIn/authorization.d.ts +11 -18
  29. package/dist/actions/signIn/authorization.js +16 -6
  30. package/dist/actions/signIn/signIn.cjs +302 -451
  31. package/dist/actions/signIn/signIn.d.ts +9 -10
  32. package/dist/actions/signIn/signIn.js +12 -10
  33. package/dist/actions/signOut/signOut.cjs +299 -468
  34. package/dist/actions/signOut/signOut.d.ts +3 -3
  35. package/dist/actions/signOut/signOut.js +14 -11
  36. package/dist/assert.cjs +40 -36
  37. package/dist/assert.d.ts +12 -4
  38. package/dist/assert.js +12 -2
  39. package/dist/chunk-2RXNXMCZ.js +55 -0
  40. package/dist/chunk-42XB3YCW.js +19 -17
  41. package/dist/chunk-4V4JNXVF.js +55 -0
  42. package/dist/chunk-6R2YZ4AC.js +22 -0
  43. package/dist/chunk-7H3OR6UU.js +81 -0
  44. package/dist/chunk-CXLATHS5.js +143 -0
  45. package/dist/chunk-E3OXBRYF.js +19 -17
  46. package/dist/chunk-EIL2FPSS.js +22 -0
  47. package/dist/chunk-FIPU4MLT.js +18 -16
  48. package/dist/chunk-FKRDCWBF.js +19 -17
  49. package/dist/chunk-IKHPGFCW.js +11 -9
  50. package/dist/chunk-IMICRJ5U.js +197 -0
  51. package/dist/chunk-IUYZQTJV.js +30 -0
  52. package/dist/chunk-KRNOMBXQ.js +19 -17
  53. package/dist/chunk-N2APGLXA.js +71 -0
  54. package/dist/chunk-NEVKX6K2.js +70 -0
  55. package/dist/chunk-PTJUYB33.js +33 -0
  56. package/dist/chunk-QDO2KSRJ.js +35 -0
  57. package/dist/chunk-QEZL7EYN.js +96 -0
  58. package/dist/chunk-RRLIF4PQ.js +55 -0
  59. package/dist/chunk-STHEPPUZ.js +8 -6
  60. package/dist/chunk-TLE4PXY3.js +39 -0
  61. package/dist/chunk-UEH3LVON.js +97 -0
  62. package/dist/chunk-WD7AUHQ5.js +79 -0
  63. package/dist/chunk-ZLR3LI6X.js +55 -0
  64. package/dist/cookie.cjs +222 -187
  65. package/dist/cookie.d.ts +38 -76
  66. package/dist/cookie.js +27 -34
  67. package/dist/errors.cjs +85 -0
  68. package/dist/errors.d.ts +48 -0
  69. package/dist/errors.js +18 -0
  70. package/dist/headers.cjs +28 -28
  71. package/dist/headers.d.ts +2 -2
  72. package/dist/headers.js +6 -2
  73. package/dist/{index-DpfbvTZ_.d.ts → index-EqsoyjrF.d.ts} +351 -318
  74. package/dist/index.cjs +1006 -1001
  75. package/dist/index.d.ts +9 -31
  76. package/dist/index.js +82 -51
  77. package/dist/jose.cjs +74 -66
  78. package/dist/jose.d.ts +11 -8
  79. package/dist/jose.js +10 -5
  80. package/dist/oauth/bitbucket.cjs +38 -38
  81. package/dist/oauth/bitbucket.d.ts +6 -7
  82. package/dist/oauth/bitbucket.js +6 -2
  83. package/dist/oauth/discord.cjs +47 -48
  84. package/dist/oauth/discord.d.ts +6 -7
  85. package/dist/oauth/discord.js +6 -2
  86. package/dist/oauth/figma.cjs +39 -39
  87. package/dist/oauth/figma.d.ts +6 -7
  88. package/dist/oauth/figma.js +6 -2
  89. package/dist/oauth/github.cjs +31 -31
  90. package/dist/oauth/github.d.ts +6 -7
  91. package/dist/oauth/github.js +6 -2
  92. package/dist/oauth/gitlab.cjs +39 -39
  93. package/dist/oauth/gitlab.d.ts +6 -7
  94. package/dist/oauth/gitlab.js +6 -2
  95. package/dist/oauth/index.cjs +306 -180
  96. package/dist/oauth/index.d.ts +6 -26
  97. package/dist/oauth/index.js +43 -9
  98. package/dist/oauth/spotify.cjs +39 -39
  99. package/dist/oauth/spotify.d.ts +6 -7
  100. package/dist/oauth/spotify.js +6 -2
  101. package/dist/oauth/strava.cjs +46 -0
  102. package/dist/oauth/strava.d.ts +6 -0
  103. package/dist/oauth/strava.js +6 -0
  104. package/dist/oauth/x.cjs +39 -39
  105. package/dist/oauth/x.d.ts +6 -7
  106. package/dist/oauth/x.js +6 -2
  107. package/dist/schemas.cjs +97 -91
  108. package/dist/schemas.d.ts +96 -126
  109. package/dist/schemas.js +20 -18
  110. package/dist/secure.cjs +106 -101
  111. package/dist/secure.d.ts +16 -17
  112. package/dist/secure.js +19 -4
  113. package/dist/utils.cjs +197 -135
  114. package/dist/utils.d.ts +20 -26
  115. package/dist/utils.js +25 -21
  116. package/package.json +5 -6
  117. package/dist/chunk-256KIVJL.js +0 -110
  118. package/dist/chunk-6SM22VVJ.js +0 -15
  119. package/dist/chunk-CAKJT3KS.js +0 -77
  120. package/dist/chunk-EBPE35JT.js +0 -29
  121. package/dist/chunk-FJUDBLCP.js +0 -52
  122. package/dist/chunk-GZU3RBTB.js +0 -51
  123. package/dist/chunk-HGJ4TXY4.js +0 -105
  124. package/dist/chunk-HMRKN75I.js +0 -74
  125. package/dist/chunk-JAPMIE6S.js +0 -8
  126. package/dist/chunk-LLR722CL.js +0 -75
  127. package/dist/chunk-RLT4RFKV.js +0 -36
  128. package/dist/chunk-SJPDVKUS.js +0 -93
  129. package/dist/chunk-SMQO5WD7.js +0 -20
  130. package/dist/chunk-UJJ7R56J.js +0 -42
  131. package/dist/chunk-UTDLUEEG.js +0 -25
  132. package/dist/chunk-VFTYH33W.js +0 -44
  133. package/dist/chunk-XXJKNKGQ.js +0 -27
  134. package/dist/chunk-ZV4BH47P.js +0 -156
  135. package/dist/error.cjs +0 -88
  136. package/dist/error.d.ts +0 -62
  137. package/dist/error.js +0 -9
  138. package/dist/response.cjs +0 -34
  139. package/dist/response.d.ts +0 -10
  140. package/dist/response.js +0 -2
@@ -1,891 +1,707 @@
1
- "use strict"
2
- var __create = Object.create
3
- var __defProp = Object.defineProperty
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor
5
- var __getOwnPropNames = Object.getOwnPropertyNames
6
- var __getProtoOf = Object.getPrototypeOf
7
- var __hasOwnProp = Object.prototype.hasOwnProperty
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __export = (target, all) => {
9
- for (var name in all) __defProp(target, name, { get: all[name], enumerable: true })
10
- }
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
11
12
  var __copyProps = (to, from, except, desc) => {
12
- if ((from && typeof from === "object") || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable })
16
- }
17
- return to
18
- }
19
- var __toESM = (mod, isNodeMode, target) => (
20
- (target = mod != null ? __create(__getProtoOf(mod)) : {}),
21
- __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- )
29
- )
30
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod)
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
29
 
32
30
  // src/actions/index.ts
33
- var actions_exports = {}
31
+ var actions_exports = {};
34
32
  __export(actions_exports, {
35
- callbackAction: () => callbackAction,
36
- csrfTokenAction: () => csrfTokenAction,
37
- sessionAction: () => sessionAction,
38
- signInAction: () => signInAction,
39
- signOutAction: () => signOutAction,
40
- })
41
- module.exports = __toCommonJS(actions_exports)
33
+ callbackAction: () => callbackAction,
34
+ csrfTokenAction: () => csrfTokenAction,
35
+ sessionAction: () => sessionAction,
36
+ signInAction: () => signInAction,
37
+ signOutAction: () => signOutAction
38
+ });
39
+ module.exports = __toCommonJS(actions_exports);
42
40
 
43
41
  // src/actions/signIn/signIn.ts
44
- var import_zod = __toESM(require("zod"), 1)
45
- var import_router2 = require("@aura-stack/router")
46
-
47
- // src/response.ts
48
- var AuraResponse = class extends Response {
49
- static json(body, init) {
50
- return Response.json(body, init)
51
- }
52
- }
42
+ var import_zod = __toESM(require("zod"), 1);
43
+ var import_router2 = require("@aura-stack/router");
53
44
 
54
45
  // src/secure.ts
55
- var import_node_crypto = __toESM(require("crypto"), 1)
46
+ var import_node_crypto = __toESM(require("crypto"), 1);
56
47
 
57
48
  // src/utils.ts
58
- var import_router = require("@aura-stack/router")
49
+ var import_router = require("@aura-stack/router");
59
50
 
60
- // src/error.ts
61
- var AuthError = class extends Error {
62
- constructor(type, message) {
63
- super(message)
64
- this.type = type
65
- this.name = "AuthError"
66
- }
67
- }
68
- var InvalidCsrfTokenError = class extends AuthError {
69
- constructor(message = "The provided CSRF token is invalid or has expired") {
70
- super("invalid_csrf_token", message)
71
- this.name = "InvalidCsrfTokenError"
72
- }
73
- }
74
- var InvalidRedirectToError = class extends AuthError {
75
- constructor(message = "The redirectTo parameter does not match the hosted origin.") {
76
- super("invalid_redirect_to", message)
77
- this.name = "InvalidRedirectToError"
78
- }
79
- }
80
- var isAuthError = (error) => {
81
- return error instanceof AuthError
82
- }
83
- var throwAuthError = (error, message) => {
84
- if (error instanceof Error) {
85
- if (isAuthError(error)) {
86
- throw error
87
- }
88
- throw new AuthError("invalid_request", error.message ?? message)
89
- }
90
- }
91
- var ERROR_RESPONSE = {
92
- AUTHORIZATION: {
93
- INVALID_REQUEST: "invalid_request",
94
- UNAUTHORIZED_CLIENT: "unauthorized_client",
95
- ACCESS_DENIED: "access_denied",
96
- UNSUPPORTED_RESPONSE_TYPE: "unsupported_response_type",
97
- INVALID_SCOPE: "invalid_scope",
98
- SERVER_ERROR: "server_error",
99
- TEMPORARILY_UNAVAILABLE: "temporarily_unavailable",
100
- },
101
- ACCESS_TOKEN: {
102
- INVALID_REQUEST: "invalid_request",
103
- INVALID_CLIENT: "invalid_client",
104
- INVALID_GRANT: "invalid_grant",
105
- UNAUTHORIZED_CLIENT: "unauthorized_client",
106
- UNSUPPORTED_GRANT_TYPE: "unsupported_grant_type",
107
- INVALID_SCOPE: "invalid_scope",
108
- },
109
- }
51
+ // src/errors.ts
52
+ var OAuthProtocolError = class extends Error {
53
+ type = "OAUTH_PROTOCOL_ERROR";
54
+ error;
55
+ errorURI;
56
+ constructor(error, description, errorURI, options2) {
57
+ super(description, options2);
58
+ this.error = error;
59
+ this.errorURI = errorURI;
60
+ this.name = new.target.name;
61
+ Error.captureStackTrace(this, new.target);
62
+ }
63
+ };
64
+ var AuthInternalError = class extends Error {
65
+ type = "AUTH_INTERNAL_ERROR";
66
+ code;
67
+ constructor(code, message, options2) {
68
+ super(message, options2);
69
+ this.code = code;
70
+ this.name = new.target.name;
71
+ Error.captureStackTrace(this, new.target);
72
+ }
73
+ };
74
+ var AuthSecurityError = class extends Error {
75
+ type = "AUTH_SECURITY_ERROR";
76
+ code;
77
+ constructor(code, message, options2) {
78
+ super(message, options2);
79
+ this.code = code;
80
+ this.name = new.target.name;
81
+ Error.captureStackTrace(this, new.target);
82
+ }
83
+ };
84
+ var isNativeError = (error) => {
85
+ return error instanceof Error;
86
+ };
87
+ var isOAuthProtocolError = (error) => {
88
+ return error instanceof OAuthProtocolError;
89
+ };
90
+ var isAuthSecurityError = (error) => {
91
+ return error instanceof AuthSecurityError;
92
+ };
110
93
 
111
94
  // src/utils.ts
112
95
  var toSnakeCase = (str) => {
113
- return str
114
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
115
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
116
- .toLowerCase()
117
- .replace(/^_+/, "")
118
- }
96
+ return str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().replace(/^_+/, "");
97
+ };
119
98
  var toUpperCase = (str) => {
120
- return str.toUpperCase()
121
- }
99
+ return str.toUpperCase();
100
+ };
122
101
  var toCastCase = (obj, type = "snake") => {
123
- return Object.entries(obj).reduce((previous, [key, value]) => {
124
- const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key)
125
- return { ...previous, [newKey]: value }
126
- }, {})
127
- }
102
+ return Object.entries(obj).reduce((previous, [key, value]) => {
103
+ const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key);
104
+ return { ...previous, [newKey]: value };
105
+ }, {});
106
+ };
128
107
  var equals = (a, b) => {
129
- if (a === null || b === null || a === void 0 || b === void 0) return false
130
- return a === b
131
- }
132
- var sanitizeURL = (url2) => {
133
- try {
134
- let decodedURL = decodeURIComponent(url2).trim()
135
- const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/)
136
- let protocol = ""
137
- let rest = decodedURL
138
- if (protocolMatch) {
139
- protocol = protocolMatch[1]
140
- rest = decodedURL.slice(protocol.length)
141
- const slashIndex = rest.indexOf("/")
142
- if (slashIndex === -1) {
143
- return protocol + rest
144
- }
145
- const domain = rest.slice(0, slashIndex)
146
- let path = rest
147
- .slice(slashIndex)
148
- .replace(/\/\.\.\//g, "/")
149
- .replace(/\/\.\.$/, "")
150
- .replace(/\.{2,}/g, "")
151
- .replace(/\/{2,}/g, "/")
152
- if (path !== "/" && path.endsWith("/")) {
153
- path = path.replace(/\/+$/, "/")
154
- } else if (path !== "/") {
155
- path = path.replace(/\/+$/, "")
156
- }
157
- return protocol + domain + path
158
- }
159
- let sanitized = decodedURL
160
- .replace(/\/\.\.\//g, "/")
161
- .replace(/\/\.\.$/, "")
162
- .replace(/\.{2,}/g, "")
163
- .replace(/\/{2,}/g, "/")
164
- if (sanitized !== "/" && sanitized.endsWith("/")) {
165
- sanitized = sanitized.replace(/\/+$/, "/")
166
- } else if (sanitized !== "/") {
167
- sanitized = sanitized.replace(/\/+$/, "")
168
- }
169
- return sanitized
170
- } catch {
171
- return url2.trim()
108
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
109
+ return a === b;
110
+ };
111
+ var sanitizeURL = (url) => {
112
+ try {
113
+ let decodedURL = decodeURIComponent(url).trim();
114
+ const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/);
115
+ let protocol = "";
116
+ let rest = decodedURL;
117
+ if (protocolMatch) {
118
+ protocol = protocolMatch[1];
119
+ rest = decodedURL.slice(protocol.length);
120
+ const slashIndex = rest.indexOf("/");
121
+ if (slashIndex === -1) {
122
+ return protocol + rest;
123
+ }
124
+ const domain = rest.slice(0, slashIndex);
125
+ let path = rest.slice(slashIndex).replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
126
+ if (path !== "/" && path.endsWith("/")) {
127
+ path = path.replace(/\/+$/, "/");
128
+ } else if (path !== "/") {
129
+ path = path.replace(/\/+$/, "");
130
+ }
131
+ return protocol + domain + path;
172
132
  }
173
- }
133
+ let sanitized = decodedURL.replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
134
+ if (sanitized !== "/" && sanitized.endsWith("/")) {
135
+ sanitized = sanitized.replace(/\/+$/, "/");
136
+ } else if (sanitized !== "/") {
137
+ sanitized = sanitized.replace(/\/+$/, "");
138
+ }
139
+ return sanitized;
140
+ } catch {
141
+ return url.trim();
142
+ }
143
+ };
174
144
  var isValidRelativePath = (path) => {
175
- if (!path || typeof path !== "string") return false
176
- if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false
177
- if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false
178
- const sanitized = sanitizeURL(path)
179
- if (sanitized.includes("..")) return false
180
- return true
181
- }
145
+ if (!path || typeof path !== "string") return false;
146
+ if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false;
147
+ if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false;
148
+ const sanitized = sanitizeURL(path);
149
+ if (sanitized.includes("..")) return false;
150
+ return true;
151
+ };
182
152
  var getNormalizedOriginPath = (path) => {
183
- try {
184
- const url2 = new URL(path)
185
- url2.hash = ""
186
- url2.search = ""
187
- return `${url2.origin}${url2.pathname}`
188
- } catch {
189
- return sanitizeURL(path)
190
- }
191
- }
153
+ try {
154
+ const url = new URL(path);
155
+ url.hash = "";
156
+ url.search = "";
157
+ return `${url.origin}${url.pathname}`;
158
+ } catch {
159
+ return sanitizeURL(path);
160
+ }
161
+ };
192
162
  var toISOString = (date) => {
193
- return new Date(date).toISOString()
194
- }
163
+ return new Date(date).toISOString();
164
+ };
165
+ var formatZodError = (error) => {
166
+ if (!error.issues || error.issues.length === 0) {
167
+ return {};
168
+ }
169
+ return error.issues.reduce((previous, issue) => {
170
+ const key = issue.path.join(".");
171
+ return {
172
+ ...previous,
173
+ [key]: {
174
+ code: issue.code,
175
+ message: issue.message
176
+ }
177
+ };
178
+ }, {});
179
+ };
180
+
181
+ // src/assert.ts
182
+ var isValidURL = (value) => {
183
+ if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false;
184
+ const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/;
185
+ return regex.test(value);
186
+ };
187
+ var isJWTPayloadWithToken = (payload) => {
188
+ return typeof payload === "object" && payload !== null && "token" in payload && typeof payload?.token === "string";
189
+ };
195
190
 
196
191
  // src/secure.ts
197
192
  var generateSecure = (length = 32) => {
198
- return import_node_crypto.default.randomBytes(length).toString("base64url")
199
- }
193
+ return import_node_crypto.default.randomBytes(length).toString("base64url");
194
+ };
200
195
  var createHash = (data, base = "hex") => {
201
- return import_node_crypto.default.createHash("sha256").update(data).digest().toString(base)
202
- }
196
+ return import_node_crypto.default.createHash("sha256").update(data).digest().toString(base);
197
+ };
203
198
  var createPKCE = async (verifier) => {
204
- const codeVerifier = verifier ?? generateSecure(86)
205
- const codeChallenge = createHash(codeVerifier, "base64url")
206
- return { codeVerifier, codeChallenge, method: "S256" }
207
- }
199
+ const codeVerifier = verifier ?? generateSecure(86);
200
+ const codeChallenge = createHash(codeVerifier, "base64url");
201
+ return { codeVerifier, codeChallenge, method: "S256" };
202
+ };
208
203
  var createCSRF = async (jose, csrfCookie) => {
209
- try {
210
- const token = generateSecure(32)
211
- if (csrfCookie) {
212
- await jose.verifyJWS(csrfCookie)
213
- return csrfCookie
214
- }
215
- return jose.signJWS({ token })
216
- } catch {
217
- const token = generateSecure(32)
218
- return jose.signJWS({ token })
204
+ try {
205
+ const token = generateSecure(32);
206
+ if (csrfCookie) {
207
+ await jose.verifyJWS(csrfCookie);
208
+ return csrfCookie;
219
209
  }
220
- }
210
+ return jose.signJWS({ token });
211
+ } catch {
212
+ const token = generateSecure(32);
213
+ return jose.signJWS({ token });
214
+ }
215
+ };
221
216
  var verifyCSRF = async (jose, cookie, header) => {
222
- try {
223
- const { token: cookieToken } = await jose.verifyJWS(cookie)
224
- const { token: headerToken } = await jose.verifyJWS(header)
225
- const cookieBuffer = Buffer.from(cookieToken)
226
- const headerBuffer = Buffer.from(headerToken)
227
- if (!equals(headerBuffer.length, cookieBuffer.length)) {
228
- throw new InvalidCsrfTokenError()
229
- }
230
- if (!import_node_crypto.default.timingSafeEqual(cookieBuffer, headerBuffer)) {
231
- throw new InvalidCsrfTokenError()
232
- }
233
- return true
234
- } catch {
235
- throw new InvalidCsrfTokenError()
217
+ try {
218
+ const cookiePayload = await jose.verifyJWS(cookie);
219
+ const headerPayload = await jose.verifyJWS(header);
220
+ if (!isJWTPayloadWithToken(cookiePayload)) {
221
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Cookie payload missing token field.");
236
222
  }
237
- }
238
-
239
- // src/cookie.ts
240
- var import_cookie = require("cookie")
241
-
242
- // src/assert.ts
243
- var isRequest = (value) => {
244
- return typeof Request !== "undefined" && value instanceof Request
245
- }
246
- var isValidURL = (value) => {
247
- if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false
248
- const regex =
249
- /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/
250
- return regex.test(value)
251
- }
252
-
253
- // src/cookie.ts
254
- var import_cookie2 = require("cookie")
255
- var COOKIE_NAME = "aura-auth"
256
- var defaultCookieOptions = {
257
- httpOnly: true,
258
- sameSite: "lax",
259
- path: "/",
260
- maxAge: 60 * 60 * 24 * 15,
261
- }
262
- var defaultStandardCookieConfig = {
263
- secure: false,
264
- httpOnly: true,
265
- prefix: "",
266
- }
267
- var defaultSecureCookieConfig = {
268
- secure: true,
269
- prefix: "__Secure-",
270
- }
271
- var defaultHostCookieConfig = {
272
- secure: true,
273
- prefix: "__Host-",
274
- path: "/",
275
- domain: void 0,
276
- }
277
- var expiredCookieOptions = {
278
- ...defaultCookieOptions,
279
- expires: /* @__PURE__ */ new Date(0),
280
- maxAge: 0,
281
- }
282
- var defineDefaultCookieOptions = (options2) => {
283
- return {
284
- name: options2?.name ?? COOKIE_NAME,
285
- prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
286
- ...defaultCookieOptions,
287
- ...options2,
288
- }
289
- }
290
- var setCookie = (cookieName, value, options2) => {
291
- const { prefix, name } = defineDefaultCookieOptions(options2)
292
- const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`
293
- return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
294
- ...defaultCookieOptions,
295
- ...options2,
296
- })
297
- }
298
- var getCookie = (petition, cookie, options2, optional = false) => {
299
- const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ")
300
- if (!cookies) {
301
- if (optional) {
302
- return ""
303
- }
304
- throw new AuthError("invalid_request", "No cookies found. There is no active session")
305
- }
306
- const { name, prefix } = defineDefaultCookieOptions(options2)
307
- const parsedCookies = (0, import_cookie.parse)(cookies)
308
- const value = parsedCookies[`${prefix}${name}.${cookie}`]
309
- if (value === void 0) {
310
- if (optional) {
311
- return ""
312
- }
313
- throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`)
223
+ if (!isJWTPayloadWithToken(headerPayload)) {
224
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Header payload missing token field.");
314
225
  }
315
- return value
316
- }
317
- var createSessionCookie = async (session, cookieOptions, jose) => {
318
- try {
319
- const encoded = await jose.encodeJWT(session)
320
- return setCookie("sessionToken", encoded, cookieOptions)
321
- } catch (error) {
322
- throw new AuthError("server_error", "Failed to create session cookie", { cause: error })
226
+ const cookieBuffer = Buffer.from(cookiePayload.token);
227
+ const headerBuffer = Buffer.from(headerPayload.token);
228
+ if (!equals(headerBuffer.length, cookieBuffer.length)) {
229
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
323
230
  }
324
- }
325
- var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
326
- const name = cookieOptions.name ?? COOKIE_NAME
327
- const isSecure = trustedProxyHeaders
328
- ? request.url.startsWith("https://") ||
329
- request.headers.get("X-Forwarded-Proto") === "https" ||
330
- request.headers.get("Forwarded")?.includes("proto=https")
331
- : request.url.startsWith("https://")
332
- if (!cookieOptions.options?.httpOnly) {
333
- console.warn(
334
- "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
335
- )
231
+ if (!import_node_crypto.default.timingSafeEqual(cookieBuffer, headerBuffer)) {
232
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
336
233
  }
337
- if (cookieOptions.options?.domain === "*") {
338
- console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.")
339
- }
340
- if (!isSecure) {
341
- const options2 = cookieOptions.options
342
- if (options2?.secure) {
343
- console.warn(
344
- "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
345
- )
346
- }
347
- if (options2?.sameSite == "none") {
348
- console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.")
349
- }
350
- if (process.env.NODE_ENV === "production") {
351
- console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.")
352
- }
353
- return {
354
- ...defaultCookieOptions,
355
- ...cookieOptions.options,
356
- sameSite: options2?.sameSite === "none" ? "lax" : (options2?.sameSite ?? "lax"),
357
- ...defaultStandardCookieConfig,
358
- name,
359
- }
360
- }
361
- return cookieOptions.strategy === "host"
362
- ? {
363
- ...defaultCookieOptions,
364
- ...cookieOptions.options,
365
- ...defaultHostCookieConfig,
366
- name,
367
- }
368
- : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name }
369
- }
370
- var expireCookie = (name, options2) => {
371
- return setCookie(name, "", { ...options2, ...expiredCookieOptions })
372
- }
373
- var oauthCookie = (options2) => {
374
- return {
375
- ...options2,
376
- secure: options2.secure,
377
- httpOnly: options2.httpOnly,
378
- maxAge: 5 * 60,
379
- expires: new Date(Date.now() + 5 * 60 * 1e3),
380
- }
381
- }
234
+ return true;
235
+ } catch {
236
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
237
+ }
238
+ };
382
239
 
383
240
  // src/schemas.ts
384
- var import_v4 = require("zod/v4")
241
+ var import_v4 = require("zod/v4");
385
242
  var OAuthProviderConfigSchema = (0, import_v4.object)({
386
- authorizeURL: (0, import_v4.url)(),
387
- accessToken: (0, import_v4.url)(),
388
- scope: (0, import_v4.string)().optional(),
389
- userInfo: (0, import_v4.url)(),
390
- responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
391
- clientId: (0, import_v4.string)(),
392
- clientSecret: (0, import_v4.string)(),
393
- })
243
+ authorizeURL: (0, import_v4.httpUrl)(),
244
+ accessToken: (0, import_v4.httpUrl)(),
245
+ scope: (0, import_v4.string)().optional(),
246
+ userInfo: (0, import_v4.httpUrl)(),
247
+ responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
248
+ clientId: (0, import_v4.string)(),
249
+ clientSecret: (0, import_v4.string)()
250
+ });
394
251
  var OAuthAuthorization = OAuthProviderConfigSchema.extend({
395
- redirectURI: (0, import_v4.string)(),
396
- state: (0, import_v4.string)(),
397
- codeChallenge: (0, import_v4.string)(),
398
- codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"]),
399
- })
252
+ redirectURI: (0, import_v4.string)(),
253
+ state: (0, import_v4.string)(),
254
+ codeChallenge: (0, import_v4.string)(),
255
+ codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"])
256
+ });
400
257
  var OAuthAuthorizationResponse = (0, import_v4.object)({
401
- state: (0, import_v4.string)(),
402
- code: (0, import_v4.string)(),
403
- })
258
+ state: (0, import_v4.string)("Missing state parameter in the OAuth authorization response."),
259
+ code: (0, import_v4.string)("Missing code parameter in the OAuth authorization response.")
260
+ });
404
261
  var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
405
- error: (0, import_v4.enum)([
406
- "invalid_request",
407
- "unauthorized_client",
408
- "access_denied",
409
- "unsupported_response_type",
410
- "invalid_scope",
411
- "server_error",
412
- "temporarily_unavailable",
413
- ]),
414
- error_description: (0, import_v4.string)().optional(),
415
- error_uri: (0, import_v4.string)().optional(),
416
- state: (0, import_v4.string)(),
417
- })
262
+ error: (0, import_v4.enum)([
263
+ "invalid_request",
264
+ "unauthorized_client",
265
+ "access_denied",
266
+ "unsupported_response_type",
267
+ "invalid_scope",
268
+ "server_error",
269
+ "temporarily_unavailable"
270
+ ]),
271
+ error_description: (0, import_v4.string)().optional(),
272
+ error_uri: (0, import_v4.string)().optional(),
273
+ state: (0, import_v4.string)()
274
+ });
418
275
  var OAuthAccessToken = OAuthProviderConfigSchema.extend({
419
- redirectURI: (0, import_v4.string)(),
420
- code: (0, import_v4.string)(),
421
- codeVerifier: (0, import_v4.string)().min(43).max(128),
422
- })
276
+ redirectURI: (0, import_v4.string)(),
277
+ code: (0, import_v4.string)(),
278
+ codeVerifier: (0, import_v4.string)().min(43).max(128)
279
+ });
423
280
  var OAuthAccessTokenResponse = (0, import_v4.object)({
424
- access_token: (0, import_v4.string)(),
425
- token_type: (0, import_v4.string)(),
426
- expires_in: (0, import_v4.number)().optional(),
427
- refresh_token: (0, import_v4.string)().optional(),
428
- scope: (0, import_v4.string)().optional(),
429
- })
281
+ access_token: (0, import_v4.string)(),
282
+ token_type: (0, import_v4.string)(),
283
+ expires_in: (0, import_v4.number)().optional(),
284
+ refresh_token: (0, import_v4.string)().optional(),
285
+ scope: (0, import_v4.string)().optional()
286
+ });
430
287
  var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
431
- error: (0, import_v4.enum)([
432
- "invalid_request",
433
- "invalid_client",
434
- "invalid_grant",
435
- "unauthorized_client",
436
- "unsupported_grant_type",
437
- "invalid_scope",
438
- ]),
439
- error_description: (0, import_v4.string)().optional(),
440
- error_uri: (0, import_v4.string)().optional(),
441
- })
288
+ error: (0, import_v4.enum)([
289
+ "invalid_request",
290
+ "invalid_client",
291
+ "invalid_grant",
292
+ "unauthorized_client",
293
+ "unsupported_grant_type",
294
+ "invalid_scope"
295
+ ]),
296
+ error_description: (0, import_v4.string)().optional(),
297
+ error_uri: (0, import_v4.string)().optional()
298
+ });
442
299
  var OAuthErrorResponse = (0, import_v4.object)({
443
- error: (0, import_v4.string)(),
444
- error_description: (0, import_v4.string)().optional(),
445
- })
300
+ error: (0, import_v4.string)(),
301
+ error_description: (0, import_v4.string)().optional()
302
+ });
303
+ var OAuthEnvSchema = (0, import_v4.object)({
304
+ clientId: import_v4.z.string().min(1, "OAuth Client ID is required in the environment variables."),
305
+ clientSecret: import_v4.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
306
+ });
446
307
 
447
308
  // src/actions/signIn/authorization.ts
448
309
  var createAuthorizationURL = (oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod) => {
449
- const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod })
450
- if (!parsed.success) {
451
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR, "Invalid OAuth configuration")
452
- }
453
- const { authorizeURL, ...options2 } = parsed.data
454
- const { userInfo, accessToken, clientSecret, ...required } = options2
455
- const searchParams = new URLSearchParams(toCastCase(required))
456
- return `${authorizeURL}?${searchParams}`
457
- }
310
+ const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod });
311
+ if (!parsed.success) {
312
+ const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
313
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
314
+ }
315
+ const { authorizeURL, ...options2 } = parsed.data;
316
+ const { userInfo, accessToken, clientSecret, ...required } = options2;
317
+ const searchParams = new URLSearchParams(toCastCase(required));
318
+ return `${authorizeURL}?${searchParams}`;
319
+ };
458
320
  var getOriginURL = (request, trustedProxyHeaders) => {
459
- const headers = request.headers
460
- if (trustedProxyHeaders) {
461
- const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http"
462
- const host =
463
- headers.get("X-Forwarded-Host") ??
464
- headers.get("Host") ??
465
- headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ??
466
- null
467
- return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`)
468
- } else {
469
- return new URL(getNormalizedOriginPath(request.url))
470
- }
471
- }
321
+ const headers = request.headers;
322
+ if (trustedProxyHeaders) {
323
+ const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http";
324
+ const host = headers.get("X-Forwarded-Host") ?? headers.get("Host") ?? headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? null;
325
+ return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`);
326
+ } else {
327
+ return new URL(getNormalizedOriginPath(request.url));
328
+ }
329
+ };
472
330
  var createRedirectURI = (request, oauth, basePath, trustedProxyHeaders) => {
473
- const url2 = getOriginURL(request, trustedProxyHeaders)
474
- return `${url2.origin}${basePath}/callback/${oauth}`
475
- }
331
+ const url = getOriginURL(request, trustedProxyHeaders);
332
+ return `${url.origin}${basePath}/callback/${oauth}`;
333
+ };
476
334
  var createRedirectTo = (request, redirectTo, trustedProxyHeaders) => {
477
- try {
478
- const headers = request.headers
479
- const origin = headers.get("Origin")
480
- const referer = headers.get("Referer")
481
- let hostedURL = getOriginURL(request, trustedProxyHeaders)
482
- if (redirectTo) {
483
- if (redirectTo.startsWith("/")) {
484
- return sanitizeURL(redirectTo)
485
- }
486
- const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)))
487
- if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
488
- throw new InvalidRedirectToError()
489
- }
490
- return sanitizeURL(redirectToURL.pathname)
491
- }
492
- if (referer) {
493
- const refererURL = new URL(sanitizeURL(referer))
494
- if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
495
- throw new AuthError(
496
- ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST,
497
- "The referer of the request does not match the hosted origin."
498
- )
499
- }
500
- return sanitizeURL(refererURL.pathname)
501
- }
502
- if (origin) {
503
- const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)))
504
- if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
505
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).")
506
- }
507
- return sanitizeURL(originURL.pathname)
508
- }
509
- return "/"
510
- } catch (error) {
511
- if (isAuthError(error)) {
512
- throw error
513
- }
514
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).")
335
+ try {
336
+ const headers = request.headers;
337
+ const origin = headers.get("Origin");
338
+ const referer = headers.get("Referer");
339
+ let hostedURL = getOriginURL(request, trustedProxyHeaders);
340
+ if (redirectTo) {
341
+ if (redirectTo.startsWith("/")) {
342
+ return sanitizeURL(redirectTo);
343
+ }
344
+ const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)));
345
+ if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
346
+ throw new AuthSecurityError(
347
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
348
+ "The redirectTo parameter does not match the hosted origin."
349
+ );
350
+ }
351
+ return sanitizeURL(redirectToURL.pathname);
352
+ }
353
+ if (referer) {
354
+ const refererURL = new URL(sanitizeURL(referer));
355
+ if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
356
+ throw new AuthSecurityError(
357
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
358
+ "The referer of the request does not match the hosted origin."
359
+ );
360
+ }
361
+ return sanitizeURL(refererURL.pathname);
362
+ }
363
+ if (origin) {
364
+ const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)));
365
+ if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
366
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
367
+ }
368
+ return sanitizeURL(originURL.pathname);
369
+ }
370
+ return "/";
371
+ } catch (error) {
372
+ if (isAuthSecurityError(error)) {
373
+ throw error;
515
374
  }
516
- }
375
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
376
+ }
377
+ };
517
378
 
518
379
  // src/actions/signIn/signIn.ts
519
380
  var signInConfig = (oauth) => {
520
- return (0, import_router2.createEndpointConfig)("/signIn/:oauth", {
521
- schemas: {
522
- params: import_zod.default.object({
523
- oauth: import_zod.default.enum(Object.keys(oauth)),
524
- redirectTo: import_zod.default.string().optional(),
525
- }),
526
- },
527
- })
528
- }
381
+ return (0, import_router2.createEndpointConfig)("/signIn/:oauth", {
382
+ schemas: {
383
+ params: import_zod.default.object({
384
+ oauth: import_zod.default.enum(Object.keys(oauth), "The OAuth provider is not supported or invalid."),
385
+ redirectTo: import_zod.default.string().optional()
386
+ })
387
+ }
388
+ });
389
+ };
529
390
  var signInAction = (oauth) => {
530
- return (0, import_router2.createEndpoint)(
531
- "GET",
532
- "/signIn/:oauth",
533
- async (ctx) => {
534
- const {
535
- request,
536
- params: { oauth: oauth2, redirectTo },
537
- context: { oauth: providers, cookies, trustedProxyHeaders, basePath },
538
- } = ctx
539
- try {
540
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
541
- const state = generateSecure()
542
- const redirectURI = createRedirectURI(request, oauth2, basePath, trustedProxyHeaders)
543
- const stateCookie = setCookie("state", state, oauthCookie(cookieOptions))
544
- const redirectURICookie = setCookie("redirect_uri", redirectURI, oauthCookie(cookieOptions))
545
- const redirectToCookie = setCookie(
546
- "redirect_to",
547
- createRedirectTo(request, redirectTo, trustedProxyHeaders),
548
- oauthCookie(cookieOptions)
549
- )
550
- const { codeVerifier, codeChallenge, method } = await createPKCE()
551
- const codeVerifierCookie = setCookie("code_verifier", codeVerifier, oauthCookie(cookieOptions))
552
- const authorization = createAuthorizationURL(providers[oauth2], redirectURI, state, codeChallenge, method)
553
- const headers = new Headers()
554
- headers.set("Location", authorization)
555
- headers.append("Set-Cookie", stateCookie)
556
- headers.append("Set-Cookie", redirectURICookie)
557
- headers.append("Set-Cookie", redirectToCookie)
558
- headers.append("Set-Cookie", codeVerifierCookie)
559
- return Response.json(
560
- { oauth: oauth2 },
561
- {
562
- status: 302,
563
- headers,
564
- }
565
- )
566
- } catch (error) {
567
- if (isAuthError(error)) {
568
- const { type, message } = error
569
- return AuraResponse.json(
570
- { error: type, error_description: message },
571
- { status: import_router2.statusCode.BAD_REQUEST }
572
- )
573
- }
574
- return AuraResponse.json(
575
- {
576
- error: ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR,
577
- error_description: "An unexpected error occurred",
578
- },
579
- { status: import_router2.statusCode.INTERNAL_SERVER_ERROR }
580
- )
581
- }
582
- },
583
- signInConfig(oauth)
584
- )
585
- }
391
+ return (0, import_router2.createEndpoint)(
392
+ "GET",
393
+ "/signIn/:oauth",
394
+ async (ctx) => {
395
+ const {
396
+ request,
397
+ headers: headersBuilder,
398
+ params: { oauth: oauth2, redirectTo },
399
+ context: { oauth: providers, cookies, trustedProxyHeaders, basePath }
400
+ } = ctx;
401
+ const state = generateSecure();
402
+ const redirectURI = createRedirectURI(request, oauth2, basePath, trustedProxyHeaders);
403
+ const redirectToValue = createRedirectTo(request, redirectTo, trustedProxyHeaders);
404
+ const { codeVerifier, codeChallenge, method } = await createPKCE();
405
+ const authorization = createAuthorizationURL(providers[oauth2], redirectURI, state, codeChallenge, method);
406
+ const headers = headersBuilder.setHeader("Location", authorization).setCookie(cookies.state.name, state, cookies.state.attributes).setCookie(cookies.redirect_uri.name, redirectURI, cookies.redirect_uri.attributes).setCookie(cookies.redirect_to.name, redirectToValue, cookies.redirect_to.attributes).setCookie(cookies.code_verifier.name, codeVerifier, cookies.code_verifier.attributes).toHeaders();
407
+ return Response.json(
408
+ { oauth: oauth2 },
409
+ {
410
+ status: 302,
411
+ headers
412
+ }
413
+ );
414
+ },
415
+ signInConfig(oauth)
416
+ );
417
+ };
586
418
 
587
419
  // src/actions/callback/callback.ts
588
- var import_zod2 = __toESM(require("zod"), 1)
589
- var import_router3 = require("@aura-stack/router")
420
+ var import_zod2 = __toESM(require("zod"), 1);
421
+ var import_router3 = require("@aura-stack/router");
590
422
 
591
423
  // src/headers.ts
592
424
  var cacheControl = {
593
- "Cache-Control": "no-store",
594
- Pragma: "no-cache",
595
- Expires: "0",
596
- Vary: "Cookie",
597
- }
425
+ "Cache-Control": "no-store",
426
+ Pragma: "no-cache",
427
+ Expires: "0",
428
+ Vary: "Cookie"
429
+ };
598
430
 
599
431
  // src/actions/callback/userinfo.ts
600
432
  var getDefaultUserInfo = (profile) => {
601
- const sub = generateSecure(16)
602
- return {
603
- sub: profile?.id ?? profile?.sub ?? sub,
604
- email: profile?.email,
605
- name: profile?.name ?? profile?.username ?? profile?.nickname,
606
- image: profile?.image ?? profile?.picture,
607
- }
608
- }
433
+ const sub = generateSecure(16);
434
+ return {
435
+ sub: profile?.id ?? profile?.sub ?? sub,
436
+ email: profile?.email,
437
+ name: profile?.name ?? profile?.username ?? profile?.nickname,
438
+ image: profile?.image ?? profile?.picture
439
+ };
440
+ };
609
441
  var getUserInfo = async (oauthConfig, accessToken) => {
610
- const userinfoEndpoint = oauthConfig.userInfo
611
- try {
612
- const response = await fetch(userinfoEndpoint, {
613
- method: "GET",
614
- headers: {
615
- Accept: "application/json",
616
- Authorization: `Bearer ${accessToken}`,
617
- },
618
- })
619
- const json = await response.json()
620
- const { success, data } = OAuthErrorResponse.safeParse(json)
621
- if (success) {
622
- throw new AuthError(data.error, data?.error_description ?? "An error occurred while fetching user information.")
623
- }
624
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json)
625
- } catch (error) {
626
- throw throwAuthError(error, "Failed to retrieve userinfo")
442
+ const userinfoEndpoint = oauthConfig.userInfo;
443
+ try {
444
+ const response = await fetch(userinfoEndpoint, {
445
+ method: "GET",
446
+ headers: {
447
+ Accept: "application/json",
448
+ Authorization: `Bearer ${accessToken}`
449
+ }
450
+ });
451
+ const json = await response.json();
452
+ const { success, data } = OAuthErrorResponse.safeParse(json);
453
+ if (success) {
454
+ throw new OAuthProtocolError(
455
+ data.error,
456
+ data?.error_description ?? "An error occurred while fetching user information."
457
+ );
458
+ }
459
+ return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
460
+ } catch (error) {
461
+ if (isOAuthProtocolError(error)) {
462
+ throw error;
463
+ }
464
+ if (isNativeError(error)) {
465
+ throw new OAuthProtocolError("invalid_request", error.message, "", { cause: error });
627
466
  }
628
- }
467
+ throw new OAuthProtocolError("invalid_request", "Failed to fetch user information.", "", { cause: error });
468
+ }
469
+ };
629
470
 
630
471
  // src/actions/callback/access-token.ts
631
472
  var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier) => {
632
- const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier })
633
- if (!parsed.success) {
634
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Invalid OAuth configuration")
473
+ const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier });
474
+ if (!parsed.success) {
475
+ const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
476
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
477
+ }
478
+ const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data;
479
+ try {
480
+ const response = await fetch(accessToken, {
481
+ method: "POST",
482
+ headers: {
483
+ Accept: "application/json",
484
+ "Content-Type": "application/x-www-form-urlencoded"
485
+ },
486
+ body: new URLSearchParams({
487
+ client_id: clientId,
488
+ client_secret: clientSecret,
489
+ code: codeParsed,
490
+ redirect_uri: redirectParsed,
491
+ grant_type: "authorization_code",
492
+ code_verifier: codeVerifier
493
+ }).toString()
494
+ });
495
+ const json = await response.json();
496
+ const token = OAuthAccessTokenResponse.safeParse(json);
497
+ if (!token.success) {
498
+ const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json);
499
+ if (!success) {
500
+ throw new OAuthProtocolError("INVALID_REQUEST", "Invalid access token response format");
501
+ }
502
+ throw new OAuthProtocolError(data.error, data?.error_description ?? "Failed to retrieve access token");
635
503
  }
636
- const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data
637
- try {
638
- const response = await fetch(accessToken, {
639
- method: "POST",
640
- headers: {
641
- Accept: "application/json",
642
- "Content-Type": "application/x-www-form-urlencoded",
643
- },
644
- body: new URLSearchParams({
645
- client_id: clientId,
646
- client_secret: clientSecret,
647
- code: codeParsed,
648
- redirect_uri: redirectParsed,
649
- grant_type: "authorization_code",
650
- code_verifier: codeVerifier,
651
- }).toString(),
652
- })
653
- const json = await response.json()
654
- const token = OAuthAccessTokenResponse.safeParse(json)
655
- if (!token.success) {
656
- const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json)
657
- if (!success) {
658
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_GRANT, "Invalid access token response format")
659
- }
660
- throw new AuthError(data.error, data?.error_description ?? "Failed to retrieve access token")
661
- }
662
- return token.data
663
- } catch (error) {
664
- throw throwAuthError(error, "Failed to create access token")
665
- }
666
- }
504
+ return token.data;
505
+ } catch (error) {
506
+ throw error;
507
+ }
508
+ };
509
+
510
+ // src/cookie.ts
511
+ var import_cookie = require("@aura-stack/router/cookie");
512
+ var defaultCookieOptions = {
513
+ httpOnly: true,
514
+ sameSite: "lax",
515
+ path: "/",
516
+ maxAge: 60 * 60 * 24 * 15
517
+ };
518
+ var oauthCookieOptions = {
519
+ httpOnly: true,
520
+ maxAge: 5 * 60,
521
+ sameSite: "lax",
522
+ expires: new Date(Date.now() + 5 * 60 * 1e3)
523
+ };
524
+ var setCookie = (cookieName, value, options2) => {
525
+ return (0, import_cookie.serialize)(cookieName, value, options2);
526
+ };
527
+ var expiredCookieAttributes = {
528
+ ...defaultCookieOptions,
529
+ expires: /* @__PURE__ */ new Date(0),
530
+ maxAge: 0
531
+ };
532
+ var getCookie = (request, cookieName) => {
533
+ const cookies = request.headers.get("Cookie");
534
+ if (!cookies) {
535
+ throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
536
+ }
537
+ const value = (0, import_cookie.parse)(cookies)[cookieName];
538
+ if (!value) {
539
+ throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
540
+ }
541
+ return value;
542
+ };
543
+ var createSessionCookie = async (jose, session) => {
544
+ try {
545
+ const encoded = await jose.encodeJWT(session);
546
+ return encoded;
547
+ } catch (error) {
548
+ throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
549
+ }
550
+ };
667
551
 
668
552
  // src/actions/callback/callback.ts
669
553
  var callbackConfig = (oauth) => {
670
- return (0, import_router3.createEndpointConfig)("/callback/:oauth", {
671
- schemas: {
672
- searchParams: OAuthAuthorizationResponse,
673
- params: import_zod2.default.object({
674
- oauth: import_zod2.default.enum(Object.keys(oauth)),
675
- }),
676
- },
677
- middlewares: [
678
- (ctx) => {
679
- const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams)
680
- if (response.success) {
681
- const { error, error_description } = response.data
682
- throw new AuthError(error, error_description ?? "OAuth Authorization Error")
683
- }
684
- return ctx
685
- },
686
- ],
687
- })
688
- }
554
+ return (0, import_router3.createEndpointConfig)("/callback/:oauth", {
555
+ schemas: {
556
+ searchParams: OAuthAuthorizationResponse,
557
+ params: import_zod2.default.object({
558
+ oauth: import_zod2.default.enum(Object.keys(oauth), "The OAuth provider is not supported or invalid.")
559
+ })
560
+ },
561
+ middlewares: [
562
+ (ctx) => {
563
+ const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams);
564
+ if (response.success) {
565
+ const { error, error_description } = response.data;
566
+ throw new OAuthProtocolError(error, error_description ?? "OAuth Authorization Error");
567
+ }
568
+ return ctx;
569
+ }
570
+ ]
571
+ });
572
+ };
689
573
  var callbackAction = (oauth) => {
690
- return (0, import_router3.createEndpoint)(
691
- "GET",
692
- "/callback/:oauth",
693
- async (ctx) => {
694
- const {
695
- request,
696
- params: { oauth: oauth2 },
697
- searchParams: { code, state },
698
- context: { oauth: providers, cookies, jose, trustedProxyHeaders },
699
- } = ctx
700
- try {
701
- const oauthConfig = providers[oauth2]
702
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
703
- const cookieState = getCookie(request, "state", cookieOptions)
704
- const cookieRedirectTo = getCookie(request, "redirect_to", cookieOptions)
705
- const cookieRedirectURI = getCookie(request, "redirect_uri", cookieOptions)
706
- const codeVerifier = getCookie(request, "code_verifier", cookieOptions)
707
- if (!equals(cookieState, state)) {
708
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Mismatching state")
709
- }
710
- const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier)
711
- const sanitized = sanitizeURL(cookieRedirectTo)
712
- if (!isValidRelativePath(sanitized)) {
713
- throw new AuthError(
714
- ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST,
715
- "Invalid redirect path. Potential open redirect attack detected."
716
- )
717
- }
718
- const headers = new Headers(cacheControl)
719
- headers.set("Location", sanitized)
720
- const userInfo = await getUserInfo(oauthConfig, accessToken.access_token)
721
- const sessionCookie = await createSessionCookie(userInfo, cookieOptions, jose)
722
- const csrfToken = await createCSRF(jose)
723
- const csrfCookie = setCookie(
724
- "csrfToken",
725
- csrfToken,
726
- secureCookieOptions(
727
- request,
728
- {
729
- ...cookies,
730
- strategy: "host",
731
- },
732
- trustedProxyHeaders
733
- )
734
- )
735
- headers.set("Set-Cookie", sessionCookie)
736
- headers.append("Set-Cookie", expireCookie("state", cookieOptions))
737
- headers.append("Set-Cookie", expireCookie("redirect_uri", cookieOptions))
738
- headers.append("Set-Cookie", expireCookie("redirect_to", cookieOptions))
739
- headers.append("Set-Cookie", expireCookie("code_verifier", cookieOptions))
740
- headers.append("Set-Cookie", csrfCookie)
741
- return Response.json({ oauth: oauth2 }, { status: 302, headers })
742
- } catch (error) {
743
- if (isAuthError(error)) {
744
- const { type, message } = error
745
- return AuraResponse.json(
746
- { error: type, error_description: message },
747
- { status: import_router3.statusCode.BAD_REQUEST }
748
- )
749
- }
750
- return AuraResponse.json(
751
- {
752
- error: ERROR_RESPONSE.ACCESS_TOKEN.INVALID_CLIENT,
753
- error_description: "An unexpected error occurred",
754
- },
755
- { status: import_router3.statusCode.INTERNAL_SERVER_ERROR }
756
- )
757
- }
758
- },
759
- callbackConfig(oauth)
760
- )
761
- }
574
+ return (0, import_router3.createEndpoint)(
575
+ "GET",
576
+ "/callback/:oauth",
577
+ async (ctx) => {
578
+ const {
579
+ request,
580
+ params: { oauth: oauth2 },
581
+ searchParams: { code, state },
582
+ context: { oauth: providers, cookies, jose }
583
+ } = ctx;
584
+ const oauthConfig = providers[oauth2];
585
+ const cookieState = getCookie(request, cookies.state.name);
586
+ const cookieRedirectTo = getCookie(request, cookies.redirect_to.name);
587
+ const cookieRedirectURI = getCookie(request, cookies.redirect_uri.name);
588
+ const codeVerifier = getCookie(request, cookies.code_verifier.name);
589
+ if (!equals(cookieState, state)) {
590
+ throw new AuthSecurityError(
591
+ "MISMATCHING_STATE",
592
+ "The provided state passed in the OAuth response does not match the stored state."
593
+ );
594
+ }
595
+ const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier);
596
+ const sanitized = sanitizeURL(cookieRedirectTo);
597
+ if (!isValidRelativePath(sanitized)) {
598
+ throw new AuthSecurityError(
599
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
600
+ "Invalid redirect path. Potential open redirect attack detected."
601
+ );
602
+ }
603
+ const userInfo = await getUserInfo(oauthConfig, accessToken.access_token);
604
+ const sessionCookie = await createSessionCookie(jose, userInfo);
605
+ const csrfToken = await createCSRF(jose);
606
+ const headers = new import_router3.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();
607
+ return Response.json({ oauth: oauth2 }, { status: 302, headers });
608
+ },
609
+ callbackConfig(oauth)
610
+ );
611
+ };
762
612
 
763
613
  // src/actions/session/session.ts
764
- var import_router4 = require("@aura-stack/router")
614
+ var import_router4 = require("@aura-stack/router");
765
615
  var sessionAction = (0, import_router4.createEndpoint)("GET", "/session", async (ctx) => {
766
- const {
767
- request,
768
- context: { cookies, jose, trustedProxyHeaders },
769
- } = ctx
770
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
771
- try {
772
- const session = getCookie(request, "sessionToken", cookieOptions)
773
- const decoded = await jose.decodeJWT(session)
774
- const { exp, iat, jti, nbf, ...user } = decoded
775
- const headers = new Headers(cacheControl)
776
- return Response.json({ user, expires: toISOString(exp * 1e3) }, { headers })
777
- } catch {
778
- const headers = new Headers(cacheControl)
779
- const sessionCookie = expireCookie("sessionToken", cookieOptions)
780
- headers.set("Set-Cookie", sessionCookie)
781
- return Response.json({ authenticated: false, message: "Unauthorized" }, { status: 401, headers })
782
- }
783
- })
616
+ const {
617
+ request,
618
+ context: { jose, cookies }
619
+ } = ctx;
620
+ try {
621
+ const session = getCookie(request, cookies.sessionToken.name);
622
+ const decoded = await jose.decodeJWT(session);
623
+ const { exp, iat, jti, nbf, ...user } = decoded;
624
+ const headers = new Headers(cacheControl);
625
+ return Response.json({ user, expires: toISOString(exp * 1e3) }, { headers });
626
+ } catch (error) {
627
+ const headers = new import_router4.HeadersBuilder(cacheControl).setCookie(cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
628
+ return Response.json({ authenticated: false, message: "Unauthorized" }, { status: 401, headers });
629
+ }
630
+ });
784
631
 
785
632
  // src/actions/signOut/signOut.ts
786
- var import_zod3 = __toESM(require("zod"), 1)
787
- var import_router5 = require("@aura-stack/router")
633
+ var import_zod3 = __toESM(require("zod"), 1);
634
+ var import_router5 = require("@aura-stack/router");
788
635
  var config = (0, import_router5.createEndpointConfig)({
789
- schemas: {
790
- searchParams: import_zod3.default.object({
791
- token_type_hint: import_zod3.default.literal("session_token"),
792
- redirectTo: import_zod3.default.string().optional(),
793
- }),
794
- },
795
- })
636
+ schemas: {
637
+ searchParams: import_zod3.default.object({
638
+ token_type_hint: import_zod3.default.literal("session_token"),
639
+ redirectTo: import_zod3.default.string().optional()
640
+ })
641
+ }
642
+ });
796
643
  var signOutAction = (0, import_router5.createEndpoint)(
797
- "POST",
798
- "/signOut",
799
- async (ctx) => {
800
- const {
801
- request,
802
- headers,
803
- searchParams: { redirectTo },
804
- context: { cookies, jose, trustedProxyHeaders },
805
- } = ctx
806
- try {
807
- const cookiesOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
808
- const session = getCookie(request, "sessionToken", cookiesOptions)
809
- const csrfToken = getCookie(request, "csrfToken", {
810
- ...cookiesOptions,
811
- prefix: cookiesOptions.secure ? "__Host-" : "",
812
- })
813
- const header = headers.get("X-CSRF-Token")
814
- if (!header || !session || !csrfToken) {
815
- throw new Error("Missing CSRF token or session token")
816
- }
817
- await verifyCSRF(jose, csrfToken, header)
818
- await jose.decodeJWT(session)
819
- const normalizedOriginPath = getNormalizedOriginPath(request.url)
820
- const location = createRedirectTo(
821
- new Request(normalizedOriginPath, {
822
- headers,
823
- }),
824
- redirectTo
825
- )
826
- const responseHeaders = new Headers(cacheControl)
827
- responseHeaders.append("Set-Cookie", expireCookie("sessionToken", cookiesOptions))
828
- responseHeaders.append(
829
- "Set-Cookie",
830
- expireCookie("csrfToken", { ...cookiesOptions, prefix: cookiesOptions.secure ? "__Host-" : "" })
831
- )
832
- responseHeaders.append("Location", location)
833
- return Response.json(
834
- { message: "Signed out successfully" },
835
- { status: import_router5.statusCode.ACCEPTED, headers: responseHeaders }
836
- )
837
- } catch (error) {
838
- if (error instanceof InvalidCsrfTokenError) {
839
- return AuraResponse.json(
840
- {
841
- error: "invalid_csrf_token",
842
- error_description: "The provided CSRF token is invalid or has expired",
843
- },
844
- { status: import_router5.statusCode.UNAUTHORIZED }
845
- )
846
- }
847
- if (error instanceof InvalidRedirectToError) {
848
- const { type, message } = error
849
- return AuraResponse.json(
850
- {
851
- error: type,
852
- error_description: message,
853
- },
854
- { status: import_router5.statusCode.BAD_REQUEST }
855
- )
856
- }
857
- return AuraResponse.json(
858
- {
859
- error: "invalid_session_token",
860
- error_description: "The provided sessionToken is invalid or has already expired",
861
- },
862
- { status: import_router5.statusCode.UNAUTHORIZED }
863
- )
864
- }
865
- },
866
- config
867
- )
644
+ "POST",
645
+ "/signOut",
646
+ async (ctx) => {
647
+ const {
648
+ request,
649
+ headers,
650
+ searchParams: { redirectTo },
651
+ context: { jose, cookies }
652
+ } = ctx;
653
+ const session = headers.getCookie(cookies.sessionToken.name);
654
+ const csrfToken = headers.getCookie(cookies.csrfToken.name);
655
+ const header = headers.getHeader("X-CSRF-Token");
656
+ if (!session) {
657
+ throw new AuthSecurityError("SESSION_TOKEN_MISSING", "The sessionToken is missing.");
658
+ }
659
+ if (!csrfToken) {
660
+ throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF token is missing.");
661
+ }
662
+ if (!header) {
663
+ throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF header is missing.");
664
+ }
665
+ await verifyCSRF(jose, csrfToken, header);
666
+ await jose.decodeJWT(session);
667
+ const normalizedOriginPath = getNormalizedOriginPath(request.url);
668
+ const location = createRedirectTo(
669
+ new Request(normalizedOriginPath, {
670
+ headers: headers.toHeaders()
671
+ }),
672
+ redirectTo
673
+ );
674
+ const headersList = new import_router5.HeadersBuilder(cacheControl).setHeader("Location", location).setCookie(cookies.csrfToken.name, "", expiredCookieAttributes).setCookie(cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
675
+ return Response.json({ message: "Signed out successfully" }, { status: import_router5.statusCode.ACCEPTED, headers: headersList });
676
+ },
677
+ config
678
+ );
868
679
 
869
680
  // src/actions/csrfToken/csrfToken.ts
870
- var import_router6 = require("@aura-stack/router")
681
+ var import_router6 = require("@aura-stack/router");
682
+ var getCSRFToken = (request, cookieName) => {
683
+ try {
684
+ return getCookie(request, cookieName);
685
+ } catch {
686
+ return void 0;
687
+ }
688
+ };
871
689
  var csrfTokenAction = (0, import_router6.createEndpoint)("GET", "/csrfToken", async (ctx) => {
872
- const {
873
- request,
874
- context: { cookies, jose, trustedProxyHeaders },
875
- } = ctx
876
- const cookieOptions = secureCookieOptions(request, { ...cookies, strategy: "host" }, trustedProxyHeaders)
877
- const existingCSRFToken = getCookie(request, "csrfToken", cookieOptions, true)
878
- const csrfToken = await createCSRF(jose, existingCSRFToken)
879
- const headers = new Headers(cacheControl)
880
- headers.set("Set-Cookie", setCookie("csrfToken", csrfToken, cookieOptions))
881
- return Response.json({ csrfToken }, { headers })
882
- })
690
+ const {
691
+ request,
692
+ context: { jose, cookies }
693
+ } = ctx;
694
+ const token = getCSRFToken(request, cookies.csrfToken.name);
695
+ const csrfToken = await createCSRF(jose, token);
696
+ const headers = new Headers(cacheControl);
697
+ headers.append("Set-Cookie", setCookie(cookies.csrfToken.name, csrfToken, cookies.csrfToken.attributes));
698
+ return Response.json({ csrfToken }, { headers });
699
+ });
883
700
  // Annotate the CommonJS export names for ESM import in node:
884
- 0 &&
885
- (module.exports = {
886
- callbackAction,
887
- csrfTokenAction,
888
- sessionAction,
889
- signInAction,
890
- signOutAction,
891
- })
701
+ 0 && (module.exports = {
702
+ callbackAction,
703
+ csrfTokenAction,
704
+ sessionAction,
705
+ signInAction,
706
+ signOutAction
707
+ });