@aura-stack/auth 0.1.0-rc.9 → 0.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/dist/@types/index.cjs +15 -15
  2. package/dist/@types/index.d.ts +7 -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 +7 -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 +176 -155
  10. package/dist/actions/callback/access-token.d.ts +15 -20
  11. package/dist/actions/callback/access-token.js +10 -4
  12. package/dist/actions/callback/callback.cjs +394 -490
  13. package/dist/actions/callback/callback.d.ts +10 -12
  14. package/dist/actions/callback/callback.js +16 -12
  15. package/dist/actions/callback/userinfo.cjs +166 -145
  16. package/dist/actions/callback/userinfo.d.ts +9 -9
  17. package/dist/actions/callback/userinfo.js +12 -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 +652 -814
  22. package/dist/actions/index.d.ts +13 -13
  23. package/dist/actions/index.js +34 -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 +254 -263
  28. package/dist/actions/signIn/authorization.d.ts +12 -18
  29. package/dist/actions/signIn/authorization.js +16 -6
  30. package/dist/actions/signIn/signIn.cjs +320 -456
  31. package/dist/actions/signIn/signIn.d.ts +10 -10
  32. package/dist/actions/signIn/signIn.js +13 -10
  33. package/dist/actions/signOut/signOut.cjs +304 -473
  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 +13 -4
  38. package/dist/assert.js +12 -2
  39. package/dist/chunk-3EUWD5BB.js +63 -0
  40. package/dist/chunk-42XB3YCW.js +19 -17
  41. package/dist/chunk-6R2YZ4AC.js +22 -0
  42. package/dist/chunk-A3N4PVAT.js +70 -0
  43. package/dist/chunk-B737EUJV.js +22 -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-EMKJA2GJ.js +89 -0
  48. package/dist/chunk-FIPU4MLT.js +18 -16
  49. package/dist/chunk-FKRDCWBF.js +19 -17
  50. package/dist/chunk-GA2SMTJO.js +58 -0
  51. package/dist/chunk-HP34YGGJ.js +22 -0
  52. package/dist/chunk-HT4YLL7N.js +35 -0
  53. package/dist/chunk-IKHPGFCW.js +11 -9
  54. package/dist/chunk-IUYZQTJV.js +30 -0
  55. package/dist/chunk-IVET23KF.js +58 -0
  56. package/dist/chunk-JVFTCTTE.js +33 -0
  57. package/dist/chunk-KRNOMBXQ.js +19 -17
  58. package/dist/chunk-KSWLO5ZU.js +102 -0
  59. package/dist/chunk-N2APGLXA.js +71 -0
  60. package/dist/chunk-N4SX7TZT.js +96 -0
  61. package/dist/chunk-RRLIF4PQ.js +55 -0
  62. package/dist/chunk-STHEPPUZ.js +8 -6
  63. package/dist/chunk-TLE4PXY3.js +39 -0
  64. package/dist/chunk-W6LG7BFW.js +197 -0
  65. package/dist/chunk-YRCB5FLE.js +79 -0
  66. package/dist/chunk-ZNCZVF6U.js +14 -0
  67. package/dist/cookie.cjs +222 -187
  68. package/dist/cookie.d.ts +39 -76
  69. package/dist/cookie.js +27 -34
  70. package/dist/errors.cjs +85 -0
  71. package/dist/errors.d.ts +49 -0
  72. package/dist/errors.js +18 -0
  73. package/dist/headers.cjs +28 -28
  74. package/dist/headers.d.ts +2 -2
  75. package/dist/headers.js +6 -2
  76. package/dist/index-DkaLJFn8.d.ts +679 -0
  77. package/dist/index.cjs +1074 -1007
  78. package/dist/index.d.ts +10 -31
  79. package/dist/index.js +85 -51
  80. package/dist/jose.cjs +74 -66
  81. package/dist/jose.d.ts +11 -8
  82. package/dist/jose.js +10 -5
  83. package/dist/oauth/bitbucket.cjs +38 -38
  84. package/dist/oauth/bitbucket.d.ts +7 -7
  85. package/dist/oauth/bitbucket.js +6 -2
  86. package/dist/oauth/discord.cjs +47 -48
  87. package/dist/oauth/discord.d.ts +7 -7
  88. package/dist/oauth/discord.js +6 -2
  89. package/dist/oauth/figma.cjs +39 -39
  90. package/dist/oauth/figma.d.ts +7 -7
  91. package/dist/oauth/figma.js +6 -2
  92. package/dist/oauth/github.cjs +31 -31
  93. package/dist/oauth/github.d.ts +7 -7
  94. package/dist/oauth/github.js +6 -2
  95. package/dist/oauth/gitlab.cjs +39 -39
  96. package/dist/oauth/gitlab.d.ts +7 -7
  97. package/dist/oauth/gitlab.js +6 -2
  98. package/dist/oauth/index.cjs +350 -180
  99. package/dist/oauth/index.d.ts +7 -26
  100. package/dist/oauth/index.js +51 -9
  101. package/dist/oauth/mailchimp.cjs +46 -0
  102. package/dist/oauth/mailchimp.d.ts +7 -0
  103. package/dist/oauth/mailchimp.js +6 -0
  104. package/dist/oauth/pinterest.cjs +46 -0
  105. package/dist/oauth/pinterest.d.ts +7 -0
  106. package/dist/oauth/pinterest.js +6 -0
  107. package/dist/oauth/spotify.cjs +39 -39
  108. package/dist/oauth/spotify.d.ts +7 -7
  109. package/dist/oauth/spotify.js +6 -2
  110. package/dist/oauth/strava.cjs +46 -0
  111. package/dist/oauth/strava.d.ts +7 -0
  112. package/dist/oauth/strava.js +6 -0
  113. package/dist/oauth/x.cjs +39 -39
  114. package/dist/oauth/x.d.ts +7 -7
  115. package/dist/oauth/x.js +6 -2
  116. package/dist/request.cjs +38 -0
  117. package/dist/request.d.ts +13 -0
  118. package/dist/request.js +6 -0
  119. package/dist/schemas.cjs +103 -97
  120. package/dist/schemas.d.ts +96 -126
  121. package/dist/schemas.js +20 -18
  122. package/dist/secure.cjs +106 -101
  123. package/dist/secure.d.ts +17 -17
  124. package/dist/secure.js +19 -4
  125. package/dist/utils.cjs +197 -135
  126. package/dist/utils.d.ts +20 -26
  127. package/dist/utils.js +25 -21
  128. package/package.json +8 -7
  129. package/dist/chunk-256KIVJL.js +0 -110
  130. package/dist/chunk-6SM22VVJ.js +0 -15
  131. package/dist/chunk-CAKJT3KS.js +0 -77
  132. package/dist/chunk-EBPE35JT.js +0 -29
  133. package/dist/chunk-FJUDBLCP.js +0 -52
  134. package/dist/chunk-GZU3RBTB.js +0 -51
  135. package/dist/chunk-HGJ4TXY4.js +0 -105
  136. package/dist/chunk-HMRKN75I.js +0 -74
  137. package/dist/chunk-JAPMIE6S.js +0 -8
  138. package/dist/chunk-LLR722CL.js +0 -75
  139. package/dist/chunk-RLT4RFKV.js +0 -36
  140. package/dist/chunk-SJPDVKUS.js +0 -93
  141. package/dist/chunk-SMQO5WD7.js +0 -20
  142. package/dist/chunk-UJJ7R56J.js +0 -42
  143. package/dist/chunk-UTDLUEEG.js +0 -25
  144. package/dist/chunk-VFTYH33W.js +0 -44
  145. package/dist/chunk-XXJKNKGQ.js +0 -27
  146. package/dist/chunk-ZV4BH47P.js +0 -156
  147. package/dist/error.cjs +0 -88
  148. package/dist/error.d.ts +0 -62
  149. package/dist/error.js +0 -9
  150. package/dist/index-DpfbvTZ_.d.ts +0 -597
  151. package/dist/response.cjs +0 -34
  152. package/dist/response.d.ts +0 -10
  153. package/dist/response.js +0 -2
package/dist/index.cjs CHANGED
@@ -1,1125 +1,1192 @@
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/index.ts
33
- var index_exports = {}
31
+ var index_exports = {};
34
32
  __export(index_exports, {
35
- createAuth: () => createAuth,
36
- })
37
- module.exports = __toCommonJS(index_exports)
38
- var import_config2 = require("dotenv/config")
39
- var import_router7 = require("@aura-stack/router")
33
+ createAuth: () => createAuth
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+ var import_config2 = require("dotenv/config");
37
+ var import_router7 = require("@aura-stack/router");
38
+
39
+ // src/jose.ts
40
+ var import_config = require("dotenv/config");
41
+ var import_jose = require("@aura-stack/jose");
42
+
43
+ // src/secure.ts
44
+ var import_crypto = __toESM(require("crypto"), 1);
40
45
 
41
46
  // src/utils.ts
42
- var import_router = require("@aura-stack/router")
47
+ var import_router = require("@aura-stack/router");
43
48
 
44
- // src/error.ts
45
- var AuthError = class extends Error {
46
- constructor(type, message) {
47
- super(message)
48
- this.type = type
49
- this.name = "AuthError"
50
- }
51
- }
52
- var InvalidCsrfTokenError = class extends AuthError {
53
- constructor(message = "The provided CSRF token is invalid or has expired") {
54
- super("invalid_csrf_token", message)
55
- this.name = "InvalidCsrfTokenError"
56
- }
57
- }
58
- var InvalidRedirectToError = class extends AuthError {
59
- constructor(message = "The redirectTo parameter does not match the hosted origin.") {
60
- super("invalid_redirect_to", message)
61
- this.name = "InvalidRedirectToError"
62
- }
63
- }
64
- var isAuthError = (error) => {
65
- return error instanceof AuthError
66
- }
67
- var throwAuthError = (error, message) => {
68
- if (error instanceof Error) {
69
- if (isAuthError(error)) {
70
- throw error
71
- }
72
- throw new AuthError("invalid_request", error.message ?? message)
73
- }
74
- }
75
- var ERROR_RESPONSE = {
76
- AUTHORIZATION: {
77
- INVALID_REQUEST: "invalid_request",
78
- UNAUTHORIZED_CLIENT: "unauthorized_client",
79
- ACCESS_DENIED: "access_denied",
80
- UNSUPPORTED_RESPONSE_TYPE: "unsupported_response_type",
81
- INVALID_SCOPE: "invalid_scope",
82
- SERVER_ERROR: "server_error",
83
- TEMPORARILY_UNAVAILABLE: "temporarily_unavailable",
84
- },
85
- ACCESS_TOKEN: {
86
- INVALID_REQUEST: "invalid_request",
87
- INVALID_CLIENT: "invalid_client",
88
- INVALID_GRANT: "invalid_grant",
89
- UNAUTHORIZED_CLIENT: "unauthorized_client",
90
- UNSUPPORTED_GRANT_TYPE: "unsupported_grant_type",
91
- INVALID_SCOPE: "invalid_scope",
92
- },
93
- }
49
+ // src/errors.ts
50
+ var OAuthProtocolError = class extends Error {
51
+ type = "OAUTH_PROTOCOL_ERROR";
52
+ error;
53
+ errorURI;
54
+ constructor(error, description, errorURI, options2) {
55
+ super(description, options2);
56
+ this.error = error;
57
+ this.errorURI = errorURI;
58
+ this.name = new.target.name;
59
+ Error.captureStackTrace(this, new.target);
60
+ }
61
+ };
62
+ var AuthInternalError = class extends Error {
63
+ type = "AUTH_INTERNAL_ERROR";
64
+ code;
65
+ constructor(code, message, options2) {
66
+ super(message, options2);
67
+ this.code = code;
68
+ this.name = new.target.name;
69
+ Error.captureStackTrace(this, new.target);
70
+ }
71
+ };
72
+ var AuthSecurityError = class extends Error {
73
+ type = "AUTH_SECURITY_ERROR";
74
+ code;
75
+ constructor(code, message, options2) {
76
+ super(message, options2);
77
+ this.code = code;
78
+ this.name = new.target.name;
79
+ Error.captureStackTrace(this, new.target);
80
+ }
81
+ };
82
+ var isNativeError = (error) => {
83
+ return error instanceof Error;
84
+ };
85
+ var isOAuthProtocolError = (error) => {
86
+ return error instanceof OAuthProtocolError;
87
+ };
88
+ var isAuthInternalError = (error) => {
89
+ return error instanceof AuthInternalError;
90
+ };
91
+ var isAuthSecurityError = (error) => {
92
+ return error instanceof AuthSecurityError;
93
+ };
94
94
 
95
95
  // src/utils.ts
96
96
  var toSnakeCase = (str) => {
97
- return str
98
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
99
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
100
- .toLowerCase()
101
- .replace(/^_+/, "")
102
- }
97
+ return str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().replace(/^_+/, "");
98
+ };
103
99
  var toUpperCase = (str) => {
104
- return str.toUpperCase()
105
- }
100
+ return str.toUpperCase();
101
+ };
106
102
  var toCastCase = (obj, type = "snake") => {
107
- return Object.entries(obj).reduce((previous, [key, value]) => {
108
- const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key)
109
- return { ...previous, [newKey]: value }
110
- }, {})
111
- }
103
+ return Object.entries(obj).reduce((previous, [key, value]) => {
104
+ const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key);
105
+ return { ...previous, [newKey]: value };
106
+ }, {});
107
+ };
112
108
  var equals = (a, b) => {
113
- if (a === null || b === null || a === void 0 || b === void 0) return false
114
- return a === b
115
- }
116
- var sanitizeURL = (url2) => {
117
- try {
118
- let decodedURL = decodeURIComponent(url2).trim()
119
- const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/)
120
- let protocol = ""
121
- let rest = decodedURL
122
- if (protocolMatch) {
123
- protocol = protocolMatch[1]
124
- rest = decodedURL.slice(protocol.length)
125
- const slashIndex = rest.indexOf("/")
126
- if (slashIndex === -1) {
127
- return protocol + rest
128
- }
129
- const domain = rest.slice(0, slashIndex)
130
- let path = rest
131
- .slice(slashIndex)
132
- .replace(/\/\.\.\//g, "/")
133
- .replace(/\/\.\.$/, "")
134
- .replace(/\.{2,}/g, "")
135
- .replace(/\/{2,}/g, "/")
136
- if (path !== "/" && path.endsWith("/")) {
137
- path = path.replace(/\/+$/, "/")
138
- } else if (path !== "/") {
139
- path = path.replace(/\/+$/, "")
140
- }
141
- return protocol + domain + path
142
- }
143
- let sanitized = decodedURL
144
- .replace(/\/\.\.\//g, "/")
145
- .replace(/\/\.\.$/, "")
146
- .replace(/\.{2,}/g, "")
147
- .replace(/\/{2,}/g, "/")
148
- if (sanitized !== "/" && sanitized.endsWith("/")) {
149
- sanitized = sanitized.replace(/\/+$/, "/")
150
- } else if (sanitized !== "/") {
151
- sanitized = sanitized.replace(/\/+$/, "")
152
- }
153
- return sanitized
154
- } catch {
155
- return url2.trim()
109
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
110
+ return a === b;
111
+ };
112
+ var sanitizeURL = (url) => {
113
+ try {
114
+ let decodedURL = decodeURIComponent(url).trim();
115
+ const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/);
116
+ let protocol = "";
117
+ let rest = decodedURL;
118
+ if (protocolMatch) {
119
+ protocol = protocolMatch[1];
120
+ rest = decodedURL.slice(protocol.length);
121
+ const slashIndex = rest.indexOf("/");
122
+ if (slashIndex === -1) {
123
+ return protocol + rest;
124
+ }
125
+ const domain = rest.slice(0, slashIndex);
126
+ let path = rest.slice(slashIndex).replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
127
+ if (path !== "/" && path.endsWith("/")) {
128
+ path = path.replace(/\/+$/, "/");
129
+ } else if (path !== "/") {
130
+ path = path.replace(/\/+$/, "");
131
+ }
132
+ return protocol + domain + path;
156
133
  }
157
- }
134
+ let sanitized = decodedURL.replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
135
+ if (sanitized !== "/" && sanitized.endsWith("/")) {
136
+ sanitized = sanitized.replace(/\/+$/, "/");
137
+ } else if (sanitized !== "/") {
138
+ sanitized = sanitized.replace(/\/+$/, "");
139
+ }
140
+ return sanitized;
141
+ } catch {
142
+ return url.trim();
143
+ }
144
+ };
158
145
  var isValidRelativePath = (path) => {
159
- if (!path || typeof path !== "string") return false
160
- if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false
161
- if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false
162
- const sanitized = sanitizeURL(path)
163
- if (sanitized.includes("..")) return false
164
- return true
165
- }
146
+ if (!path || typeof path !== "string") return false;
147
+ if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false;
148
+ if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false;
149
+ const sanitized = sanitizeURL(path);
150
+ if (sanitized.includes("..")) return false;
151
+ return true;
152
+ };
166
153
  var onErrorHandler = (error) => {
167
- if ((0, import_router.isRouterError)(error)) {
168
- const { message, status, statusText } = error
169
- return Response.json({ error: "invalid_request", error_description: message }, { status, statusText })
170
- }
171
- if (isAuthError(error)) {
172
- const { type, message } = error
173
- return Response.json({ error: type, error_description: message }, { status: 400 })
174
- }
175
- return Response.json({ error: "server_error", error_description: "An unexpected error occurred" }, { status: 500 })
176
- }
154
+ if ((0, import_router.isRouterError)(error)) {
155
+ const { message, status, statusText } = error;
156
+ return Response.json({ type: "ROUTER_ERROR", code: "ROUTER_INTERNAL_ERROR", message }, { status, statusText });
157
+ }
158
+ if ((0, import_router.isInvalidZodSchemaError)(error)) {
159
+ return Response.json({ type: "ROUTER_ERROR", code: "INVALID_REQUEST", message: error.errors }, { status: 422 });
160
+ }
161
+ if (isOAuthProtocolError(error)) {
162
+ const { error: errorCode, message, type, errorURI } = error;
163
+ return Response.json(
164
+ {
165
+ type,
166
+ error: errorCode,
167
+ error_description: message,
168
+ error_uri: errorURI
169
+ },
170
+ { status: 400 }
171
+ );
172
+ }
173
+ if (isAuthInternalError(error) || isAuthSecurityError(error)) {
174
+ const { type, code, message } = error;
175
+ return Response.json(
176
+ {
177
+ type,
178
+ code,
179
+ message
180
+ },
181
+ { status: 400 }
182
+ );
183
+ }
184
+ return Response.json({ type: "SERVER_ERROR", code: "server_error", message: "An unexpected error occurred" }, { status: 500 });
185
+ };
177
186
  var getNormalizedOriginPath = (path) => {
178
- try {
179
- const url2 = new URL(path)
180
- url2.hash = ""
181
- url2.search = ""
182
- return `${url2.origin}${url2.pathname}`
183
- } catch {
184
- return sanitizeURL(path)
185
- }
186
- }
187
+ try {
188
+ const url = new URL(path);
189
+ url.hash = "";
190
+ url.search = "";
191
+ return `${url.origin}${url.pathname}`;
192
+ } catch {
193
+ return sanitizeURL(path);
194
+ }
195
+ };
187
196
  var toISOString = (date) => {
188
- return new Date(date).toISOString()
189
- }
197
+ return new Date(date).toISOString();
198
+ };
199
+ var useSecureCookies = (request, trustedProxyHeaders) => {
200
+ return trustedProxyHeaders ? request.url.startsWith("https://") || request.headers.get("X-Forwarded-Proto") === "https" || (request.headers.get("Forwarded")?.includes("proto=https") ?? false) : request.url.startsWith("https://");
201
+ };
202
+ var formatZodError = (error) => {
203
+ if (!error.issues || error.issues.length === 0) {
204
+ return {};
205
+ }
206
+ return error.issues.reduce((previous, issue) => {
207
+ const key = issue.path.join(".");
208
+ return {
209
+ ...previous,
210
+ [key]: {
211
+ code: issue.code,
212
+ message: issue.message
213
+ }
214
+ };
215
+ }, {});
216
+ };
190
217
 
191
- // src/jose.ts
192
- var import_config = require("dotenv/config")
193
- var import_jose = require("@aura-stack/jose")
218
+ // src/assert.ts
219
+ var isValidURL = (value) => {
220
+ if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false;
221
+ const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/;
222
+ return regex.test(value);
223
+ };
224
+ var isJWTPayloadWithToken = (payload) => {
225
+ return typeof payload === "object" && payload !== null && "token" in payload && typeof payload?.token === "string";
226
+ };
194
227
 
195
228
  // src/secure.ts
196
- var import_node_crypto = __toESM(require("crypto"), 1)
197
229
  var generateSecure = (length = 32) => {
198
- return import_node_crypto.default.randomBytes(length).toString("base64url")
199
- }
230
+ return import_crypto.default.randomBytes(length).toString("base64url");
231
+ };
200
232
  var createHash = (data, base = "hex") => {
201
- return import_node_crypto.default.createHash("sha256").update(data).digest().toString(base)
202
- }
233
+ return import_crypto.default.createHash("sha256").update(data).digest().toString(base);
234
+ };
203
235
  var createPKCE = async (verifier) => {
204
- const codeVerifier = verifier ?? generateSecure(86)
205
- const codeChallenge = createHash(codeVerifier, "base64url")
206
- return { codeVerifier, codeChallenge, method: "S256" }
207
- }
236
+ const codeVerifier = verifier ?? generateSecure(86);
237
+ const codeChallenge = createHash(codeVerifier, "base64url");
238
+ return { codeVerifier, codeChallenge, method: "S256" };
239
+ };
208
240
  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 })
241
+ try {
242
+ const token = generateSecure(32);
243
+ if (csrfCookie) {
244
+ await jose.verifyJWS(csrfCookie);
245
+ return csrfCookie;
219
246
  }
220
- }
247
+ return jose.signJWS({ token });
248
+ } catch {
249
+ const token = generateSecure(32);
250
+ return jose.signJWS({ token });
251
+ }
252
+ };
221
253
  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()
254
+ try {
255
+ const cookiePayload = await jose.verifyJWS(cookie);
256
+ const headerPayload = await jose.verifyJWS(header);
257
+ if (!isJWTPayloadWithToken(cookiePayload)) {
258
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Cookie payload missing token field.");
259
+ }
260
+ if (!isJWTPayloadWithToken(headerPayload)) {
261
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Header payload missing token field.");
262
+ }
263
+ const cookieBuffer = Buffer.from(cookiePayload.token);
264
+ const headerBuffer = Buffer.from(headerPayload.token);
265
+ if (!equals(headerBuffer.length, cookieBuffer.length)) {
266
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
236
267
  }
237
- }
268
+ if (!import_crypto.default.timingSafeEqual(cookieBuffer, headerBuffer)) {
269
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
270
+ }
271
+ return true;
272
+ } catch {
273
+ throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
274
+ }
275
+ };
238
276
  var createDerivedSalt = (secret) => {
239
- return import_node_crypto.default.createHash("sha256").update(secret).update("aura-auth-salt").digest("hex")
240
- }
277
+ return import_crypto.default.createHash("sha256").update(secret).update("aura-auth-salt").digest("hex");
278
+ };
241
279
 
242
280
  // src/jose.ts
243
281
  var createJoseInstance = (secret) => {
244
- secret ?? (secret = process.env.AURA_AUTH_SECRET)
245
- if (!secret) {
246
- throw new AuthError("JOSE_INIT_ERROR", "AURA_AUTH_SECRET environment variable is not set and no secret was provided.")
247
- }
248
- const salt = process.env.AURA_AUTH_SALT ?? createDerivedSalt(secret)
249
- const { derivedKey: derivedSessionKey } = (0, import_jose.createDeriveKey)(secret, salt, "session")
250
- const { derivedKey: derivedCsrfTokenKey } = (0, import_jose.createDeriveKey)(secret, salt, "csrfToken")
251
- const { decodeJWT, encodeJWT } = (0, import_jose.createJWT)(derivedSessionKey)
252
- const { signJWS, verifyJWS } = (0, import_jose.createJWS)(derivedCsrfTokenKey)
253
- return {
254
- decodeJWT,
255
- encodeJWT,
256
- signJWS,
257
- verifyJWS,
258
- }
259
- }
282
+ const env = process.env;
283
+ secret ??= env.AURA_AUTH_SECRET ?? env.AUTH_SECRET;
284
+ if (!secret) {
285
+ throw new AuthInternalError(
286
+ "JOSE_INITIALIZATION_FAILED",
287
+ "AURA_AUTH_SECRET environment variable is not set and no secret was provided."
288
+ );
289
+ }
290
+ const salt = env.AURA_AUTH_SALT ?? env.AUTH_SALT ?? createDerivedSalt(secret);
291
+ const { derivedKey: derivedSigningKey } = (0, import_jose.createDeriveKey)(secret, salt, "signing");
292
+ const { derivedKey: derivedEncryptionKey } = (0, import_jose.createDeriveKey)(secret, salt, "encryption");
293
+ const { derivedKey: derivedCsrfTokenKey } = (0, import_jose.createDeriveKey)(secret, salt, "csrfToken");
294
+ const { decodeJWT, encodeJWT } = (0, import_jose.createJWT)({ jws: derivedSigningKey, jwe: derivedEncryptionKey });
295
+ const { signJWS, verifyJWS } = (0, import_jose.createJWS)(derivedCsrfTokenKey);
296
+ const { encryptJWE, decryptJWE } = (0, import_jose.createJWE)(derivedEncryptionKey);
297
+ return {
298
+ decodeJWT,
299
+ encodeJWT,
300
+ signJWS,
301
+ verifyJWS,
302
+ encryptJWE,
303
+ decryptJWE
304
+ };
305
+ };
260
306
 
261
307
  // src/cookie.ts
262
- var import_cookie = require("cookie")
263
-
264
- // src/assert.ts
265
- var isRequest = (value) => {
266
- return typeof Request !== "undefined" && value instanceof Request
267
- }
268
- var isValidURL = (value) => {
269
- if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false
270
- const regex =
271
- /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/
272
- return regex.test(value)
273
- }
274
-
275
- // src/cookie.ts
276
- var import_cookie2 = require("cookie")
277
- var COOKIE_NAME = "aura-auth"
308
+ var import_cookie = require("@aura-stack/router/cookie");
309
+ var COOKIE_NAME = "aura-auth";
278
310
  var defaultCookieOptions = {
279
- httpOnly: true,
280
- sameSite: "lax",
281
- path: "/",
282
- maxAge: 60 * 60 * 24 * 15,
283
- }
284
- var defaultCookieConfig = {
285
- strategy: "standard",
286
- name: COOKIE_NAME,
287
- options: defaultCookieOptions,
288
- }
311
+ httpOnly: true,
312
+ sameSite: "lax",
313
+ path: "/",
314
+ maxAge: 60 * 60 * 24 * 15
315
+ };
289
316
  var defaultStandardCookieConfig = {
290
- secure: false,
291
- httpOnly: true,
292
- prefix: "",
293
- }
317
+ secure: false,
318
+ httpOnly: true
319
+ };
294
320
  var defaultSecureCookieConfig = {
295
- secure: true,
296
- prefix: "__Secure-",
297
- }
321
+ secure: true,
322
+ httpOnly: true
323
+ };
298
324
  var defaultHostCookieConfig = {
299
- secure: true,
300
- prefix: "__Host-",
301
- path: "/",
302
- domain: void 0,
303
- }
304
- var expiredCookieOptions = {
305
- ...defaultCookieOptions,
306
- expires: /* @__PURE__ */ new Date(0),
307
- maxAge: 0,
308
- }
309
- var defineDefaultCookieOptions = (options2) => {
310
- return {
311
- name: options2?.name ?? COOKIE_NAME,
312
- prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
313
- ...defaultCookieOptions,
314
- ...options2,
315
- }
316
- }
325
+ secure: true,
326
+ httpOnly: true,
327
+ path: "/",
328
+ domain: void 0
329
+ };
330
+ var oauthCookieOptions = {
331
+ httpOnly: true,
332
+ maxAge: 5 * 60,
333
+ sameSite: "lax",
334
+ expires: new Date(Date.now() + 5 * 60 * 1e3)
335
+ };
317
336
  var setCookie = (cookieName, value, options2) => {
318
- const { prefix, name } = defineDefaultCookieOptions(options2)
319
- const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`
320
- return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
321
- ...defaultCookieOptions,
322
- ...options2,
323
- })
324
- }
325
- var getCookie = (petition, cookie, options2, optional = false) => {
326
- const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ")
327
- if (!cookies) {
328
- if (optional) {
329
- return ""
330
- }
331
- throw new AuthError("invalid_request", "No cookies found. There is no active session")
337
+ return (0, import_cookie.serialize)(cookieName, value, options2);
338
+ };
339
+ var expiredCookieAttributes = {
340
+ ...defaultCookieOptions,
341
+ expires: /* @__PURE__ */ new Date(0),
342
+ maxAge: 0
343
+ };
344
+ var getCookie = (request, cookieName) => {
345
+ const cookies = request.headers.get("Cookie");
346
+ if (!cookies) {
347
+ throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
348
+ }
349
+ const value = (0, import_cookie.parse)(cookies)[cookieName];
350
+ if (!value) {
351
+ throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
352
+ }
353
+ return value;
354
+ };
355
+ var createSessionCookie = async (jose, session) => {
356
+ try {
357
+ const encoded = await jose.encodeJWT(session);
358
+ return encoded;
359
+ } catch (error) {
360
+ throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
361
+ }
362
+ };
363
+ var defineSecureCookieOptions = (useSecure, attributes, strategy) => {
364
+ if (!attributes.httpOnly) {
365
+ console.warn(
366
+ "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
367
+ );
368
+ }
369
+ if (attributes.domain === "*") {
370
+ attributes.domain = void 0;
371
+ console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.");
372
+ }
373
+ if (!useSecure) {
374
+ if (attributes.secure) {
375
+ console.warn(
376
+ "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
377
+ );
332
378
  }
333
- const { name, prefix } = defineDefaultCookieOptions(options2)
334
- const parsedCookies = (0, import_cookie.parse)(cookies)
335
- const value = parsedCookies[`${prefix}${name}.${cookie}`]
336
- if (value === void 0) {
337
- if (optional) {
338
- return ""
339
- }
340
- throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`)
379
+ if (attributes.sameSite == "none") {
380
+ attributes.sameSite = "lax";
381
+ console.warn("[WARNING]: SameSite=None requires Secure attribute. Changing SameSite to 'Lax'.");
341
382
  }
342
- return value
343
- }
344
- var createSessionCookie = async (session, cookieOptions, jose) => {
345
- try {
346
- const encoded = await jose.encodeJWT(session)
347
- return setCookie("sessionToken", encoded, cookieOptions)
348
- } catch (error) {
349
- throw new AuthError("server_error", "Failed to create session cookie", { cause: error })
383
+ if (process.env.NODE_ENV === "production") {
384
+ console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.");
350
385
  }
351
- }
352
- var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
353
- const name = cookieOptions.name ?? COOKIE_NAME
354
- const isSecure = trustedProxyHeaders
355
- ? request.url.startsWith("https://") ||
356
- request.headers.get("X-Forwarded-Proto") === "https" ||
357
- request.headers.get("Forwarded")?.includes("proto=https")
358
- : request.url.startsWith("https://")
359
- if (!cookieOptions.options?.httpOnly) {
360
- console.warn(
361
- "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
362
- )
363
- }
364
- if (cookieOptions.options?.domain === "*") {
365
- console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.")
386
+ if (strategy === "host") {
387
+ console.warn("[WARNING]: __Host- cookies require a secure context. Falling back to standard cookie settings.");
366
388
  }
367
- if (!isSecure) {
368
- const options2 = cookieOptions.options
369
- if (options2?.secure) {
370
- console.warn(
371
- "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
372
- )
373
- }
374
- if (options2?.sameSite == "none") {
375
- console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.")
376
- }
377
- if (process.env.NODE_ENV === "production") {
378
- console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.")
379
- }
380
- return {
381
- ...defaultCookieOptions,
382
- ...cookieOptions.options,
383
- sameSite: options2?.sameSite === "none" ? "lax" : (options2?.sameSite ?? "lax"),
384
- ...defaultStandardCookieConfig,
385
- name,
386
- }
387
- }
388
- return cookieOptions.strategy === "host"
389
- ? {
390
- ...defaultCookieOptions,
391
- ...cookieOptions.options,
392
- ...defaultHostCookieConfig,
393
- name,
394
- }
395
- : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name }
396
- }
397
- var expireCookie = (name, options2) => {
398
- return setCookie(name, "", { ...options2, ...expiredCookieOptions })
399
- }
400
- var oauthCookie = (options2) => {
401
389
  return {
402
- ...options2,
403
- secure: options2.secure,
404
- httpOnly: options2.httpOnly,
405
- maxAge: 5 * 60,
406
- expires: new Date(Date.now() + 5 * 60 * 1e3),
390
+ ...defaultCookieOptions,
391
+ ...attributes,
392
+ ...defaultStandardCookieConfig
393
+ };
394
+ }
395
+ return strategy === "host" ? {
396
+ ...defaultCookieOptions,
397
+ ...attributes,
398
+ ...defaultHostCookieConfig
399
+ } : { ...defaultCookieOptions, ...attributes, ...defaultSecureCookieConfig };
400
+ };
401
+ var createCookieStore = (useSecure, prefix, overrides) => {
402
+ prefix ??= COOKIE_NAME;
403
+ const securePrefix = useSecure ? "__Secure-" : "";
404
+ const hostPrefix = useSecure ? "__Host-" : "";
405
+ return {
406
+ sessionToken: {
407
+ name: `${securePrefix}${prefix}.${overrides?.sessionToken?.name ?? "session_token"}`,
408
+ attributes: defineSecureCookieOptions(
409
+ useSecure,
410
+ {
411
+ ...defaultCookieOptions,
412
+ ...overrides?.sessionToken?.attributes
413
+ },
414
+ overrides?.sessionToken?.attributes?.strategy ?? "secure"
415
+ )
416
+ },
417
+ state: {
418
+ name: `${securePrefix}${prefix}.${overrides?.state?.name ?? "state"}`,
419
+ attributes: defineSecureCookieOptions(
420
+ useSecure,
421
+ {
422
+ ...oauthCookieOptions,
423
+ ...overrides?.state?.attributes
424
+ },
425
+ overrides?.state?.attributes?.strategy ?? "secure"
426
+ )
427
+ },
428
+ csrfToken: {
429
+ name: `${hostPrefix}${prefix}.${overrides?.csrfToken?.name ?? "csrf_token"}`,
430
+ attributes: defineSecureCookieOptions(
431
+ useSecure,
432
+ {
433
+ ...overrides?.csrfToken?.attributes,
434
+ ...defaultHostCookieConfig
435
+ },
436
+ overrides?.csrfToken?.attributes?.strategy ?? "host"
437
+ )
438
+ },
439
+ redirectTo: {
440
+ name: `${securePrefix}${prefix}.${overrides?.redirectTo?.name ?? "redirect_to"}`,
441
+ attributes: defineSecureCookieOptions(
442
+ useSecure,
443
+ {
444
+ ...oauthCookieOptions,
445
+ ...overrides?.redirectTo?.attributes
446
+ },
447
+ overrides?.redirectTo?.attributes?.strategy ?? "secure"
448
+ )
449
+ },
450
+ redirectURI: {
451
+ name: `${securePrefix}${prefix}.${overrides?.redirectURI?.name ?? "redirect_uri"}`,
452
+ attributes: defineSecureCookieOptions(
453
+ useSecure,
454
+ {
455
+ ...oauthCookieOptions,
456
+ ...overrides?.redirectURI?.attributes
457
+ },
458
+ overrides?.redirectURI?.attributes?.strategy ?? "secure"
459
+ )
460
+ },
461
+ codeVerifier: {
462
+ name: `${securePrefix}${prefix}.${overrides?.codeVerifier?.name ?? "code_verifier"}`,
463
+ attributes: defineSecureCookieOptions(
464
+ useSecure,
465
+ {
466
+ ...oauthCookieOptions,
467
+ ...overrides?.codeVerifier?.attributes
468
+ },
469
+ overrides?.codeVerifier?.attributes?.strategy ?? "secure"
470
+ )
407
471
  }
408
- }
472
+ };
473
+ };
409
474
 
410
475
  // src/oauth/github.ts
411
476
  var github = {
412
- id: "github",
413
- name: "GitHub",
414
- authorizeURL: "https://github.com/login/oauth/authorize",
415
- accessToken: "https://github.com/login/oauth/access_token",
416
- userInfo: "https://api.github.com/user",
417
- scope: "read:user user:email",
418
- responseType: "code",
419
- }
477
+ id: "github",
478
+ name: "GitHub",
479
+ authorizeURL: "https://github.com/login/oauth/authorize",
480
+ accessToken: "https://github.com/login/oauth/access_token",
481
+ userInfo: "https://api.github.com/user",
482
+ scope: "read:user user:email",
483
+ responseType: "code"
484
+ };
420
485
 
421
486
  // src/oauth/bitbucket.ts
422
487
  var bitbucket = {
423
- id: "bitbucket",
424
- name: "Bitbucket",
425
- authorizeURL: "https://bitbucket.org/site/oauth2/authorize",
426
- accessToken: "https://bitbucket.org/site/oauth2/access_token",
427
- userInfo: "https://api.bitbucket.org/2.0/user",
428
- scope: "account email",
429
- responseType: "code",
430
- profile(profile) {
431
- return {
432
- sub: profile.uuid ?? profile.account_id,
433
- name: profile.display_name ?? profile.nickname,
434
- image: profile.links.avatar.href,
435
- }
436
- },
437
- }
488
+ id: "bitbucket",
489
+ name: "Bitbucket",
490
+ authorizeURL: "https://bitbucket.org/site/oauth2/authorize",
491
+ accessToken: "https://bitbucket.org/site/oauth2/access_token",
492
+ userInfo: "https://api.bitbucket.org/2.0/user",
493
+ scope: "account email",
494
+ responseType: "code",
495
+ profile(profile) {
496
+ return {
497
+ sub: profile.uuid ?? profile.account_id,
498
+ name: profile.display_name ?? profile.nickname,
499
+ image: profile.links.avatar.href
500
+ };
501
+ }
502
+ };
438
503
 
439
504
  // src/oauth/figma.ts
440
505
  var figma = {
441
- id: "figma",
442
- name: "Figma",
443
- authorizeURL: "https://www.figma.com/oauth",
444
- accessToken: "https://api.figma.com/v1/oauth/token",
445
- userInfo: "https://api.figma.com/v1/me",
446
- scope: "current_user:read",
447
- responseType: "code",
448
- profile(profile) {
449
- return {
450
- sub: profile.id,
451
- name: profile.handle,
452
- email: profile.email,
453
- image: profile.img_url,
454
- }
455
- },
456
- }
506
+ id: "figma",
507
+ name: "Figma",
508
+ authorizeURL: "https://www.figma.com/oauth",
509
+ accessToken: "https://api.figma.com/v1/oauth/token",
510
+ userInfo: "https://api.figma.com/v1/me",
511
+ scope: "current_user:read",
512
+ responseType: "code",
513
+ profile(profile) {
514
+ return {
515
+ sub: profile.id,
516
+ name: profile.handle,
517
+ email: profile.email,
518
+ image: profile.img_url
519
+ };
520
+ }
521
+ };
457
522
 
458
523
  // src/oauth/discord.ts
459
524
  var discord = {
460
- id: "discord",
461
- name: "Discord",
462
- authorizeURL: "https://discord.com/oauth2/authorize",
463
- accessToken: "https://discord.com/api/oauth2/token",
464
- userInfo: "https://discord.com/api/users/@me",
465
- scope: "identify email",
466
- responseType: "code",
467
- profile(profile) {
468
- let image = ""
469
- if (profile.avatar === null) {
470
- const index = profile.discriminator === "0" ? (BigInt(profile.id) >> 22n) % 6n : Number(profile.discriminator) % 5
471
- image = `https://cdn.discordapp.com/embed/avatars/${index}.png`
472
- } else {
473
- const format = profile.avatar.startsWith("a_") ? "gif" : "png"
474
- image = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`
475
- }
476
- return {
477
- sub: profile.id,
478
- // https://discord.com/developers/docs/change-log#display-names
479
- name: profile.global_name ?? profile.username,
480
- email: profile.email ?? "",
481
- image,
482
- }
483
- },
484
- }
525
+ id: "discord",
526
+ name: "Discord",
527
+ authorizeURL: "https://discord.com/oauth2/authorize",
528
+ accessToken: "https://discord.com/api/oauth2/token",
529
+ userInfo: "https://discord.com/api/users/@me",
530
+ scope: "identify email",
531
+ responseType: "code",
532
+ profile(profile) {
533
+ let image = "";
534
+ if (profile.avatar === null) {
535
+ const index = profile.discriminator === "0" ? (BigInt(profile.id) >> 22n) % 6n : Number(profile.discriminator) % 5;
536
+ image = `https://cdn.discordapp.com/embed/avatars/${index}.png`;
537
+ } else {
538
+ const format = profile.avatar.startsWith("a_") ? "gif" : "png";
539
+ image = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`;
540
+ }
541
+ return {
542
+ sub: profile.id,
543
+ name: profile.global_name ?? profile.username,
544
+ email: profile.email ?? "",
545
+ image
546
+ };
547
+ }
548
+ };
485
549
 
486
550
  // src/oauth/gitlab.ts
487
551
  var gitlab = {
488
- id: "gitlab",
489
- name: "GitLab",
490
- authorizeURL: "https://gitlab.com/oauth/authorize",
491
- accessToken: "https://gitlab.com/oauth/token",
492
- userInfo: "https://gitlab.com/api/v4/user",
493
- scope: "read_user",
494
- responseType: "code",
495
- profile(profile) {
496
- return {
497
- sub: profile.id.toString(),
498
- name: profile.name ?? profile.username,
499
- email: profile.email,
500
- avatar: profile.avatar_url,
501
- }
502
- },
503
- }
552
+ id: "gitlab",
553
+ name: "GitLab",
554
+ authorizeURL: "https://gitlab.com/oauth/authorize",
555
+ accessToken: "https://gitlab.com/oauth/token",
556
+ userInfo: "https://gitlab.com/api/v4/user",
557
+ scope: "read_user",
558
+ responseType: "code",
559
+ profile(profile) {
560
+ return {
561
+ sub: profile.id.toString(),
562
+ name: profile.name ?? profile.username,
563
+ email: profile.email,
564
+ avatar: profile.avatar_url
565
+ };
566
+ }
567
+ };
504
568
 
505
569
  // src/oauth/spotify.ts
506
570
  var spotify = {
507
- id: "spotify",
508
- name: "Spotify",
509
- authorizeURL: "https://accounts.spotify.com/authorize",
510
- accessToken: "https://accounts.spotify.com/api/token",
511
- userInfo: "https://api.spotify.com/v1/me",
512
- scope: "user-read-email user-read-private",
513
- responseType: "token",
514
- profile(profile) {
515
- return {
516
- sub: profile.id,
517
- name: profile.display_name,
518
- email: profile.email,
519
- image: profile.images?.[0]?.url,
520
- }
521
- },
522
- }
571
+ id: "spotify",
572
+ name: "Spotify",
573
+ authorizeURL: "https://accounts.spotify.com/authorize",
574
+ accessToken: "https://accounts.spotify.com/api/token",
575
+ userInfo: "https://api.spotify.com/v1/me",
576
+ scope: "user-read-email user-read-private",
577
+ responseType: "token",
578
+ profile(profile) {
579
+ return {
580
+ sub: profile.id,
581
+ name: profile.display_name,
582
+ email: profile.email,
583
+ image: profile.images?.[0]?.url
584
+ };
585
+ }
586
+ };
523
587
 
524
588
  // src/oauth/x.ts
525
589
  var x = {
526
- id: "x",
527
- name: "X",
528
- authorizeURL: "https://x.com/i/oauth2/authorize",
529
- accessToken: "https://api.x.com/2/oauth2/token",
530
- userInfo: "https://api.x.com/2/users/me?user.fields=profile_image_url",
531
- scope: "users.read users.email tweet.read offline.access",
532
- responseType: "code",
533
- profile({ data }) {
534
- return {
535
- sub: data.id,
536
- name: data.name,
537
- image: data.profile_image_url,
538
- email: "",
539
- }
540
- },
541
- }
590
+ id: "x",
591
+ name: "X",
592
+ authorizeURL: "https://x.com/i/oauth2/authorize",
593
+ accessToken: "https://api.x.com/2/oauth2/token",
594
+ userInfo: "https://api.x.com/2/users/me?user.fields=profile_image_url",
595
+ scope: "users.read users.email tweet.read offline.access",
596
+ responseType: "code",
597
+ profile({ data }) {
598
+ return {
599
+ sub: data.id,
600
+ name: data.name,
601
+ image: data.profile_image_url,
602
+ email: ""
603
+ };
604
+ }
605
+ };
606
+
607
+ // src/oauth/strava.ts
608
+ var strava = {
609
+ id: "strava",
610
+ name: "Strava",
611
+ authorizeURL: "https://www.strava.com/oauth/authorize",
612
+ accessToken: "https://www.strava.com/oauth/token",
613
+ userInfo: "https://www.strava.com/api/v3/athlete",
614
+ scope: "read",
615
+ responseType: "code",
616
+ profile(profile) {
617
+ return {
618
+ sub: profile.id.toString(),
619
+ name: `${profile.firstname} ${profile.lastname}`,
620
+ image: profile.profile,
621
+ email: ""
622
+ };
623
+ }
624
+ };
625
+
626
+ // src/oauth/mailchimp.ts
627
+ var mailchimp = {
628
+ id: "mailchimp",
629
+ name: "Mailchimp",
630
+ authorizeURL: "https://login.mailchimp.com/oauth2/authorize",
631
+ accessToken: "https://login.mailchimp.com/oauth2/token",
632
+ userInfo: "https://login.mailchimp.com/oauth2/metadata",
633
+ scope: "",
634
+ responseType: "code",
635
+ profile(profile) {
636
+ return {
637
+ sub: profile.user_id,
638
+ name: profile.accountname,
639
+ email: profile.login.login_email,
640
+ image: null
641
+ };
642
+ }
643
+ };
644
+
645
+ // src/oauth/pinterest.ts
646
+ var pinterest = {
647
+ id: "pinterest",
648
+ name: "Pinterest",
649
+ authorizeURL: "https://api.pinterest.com/oauth/",
650
+ accessToken: "https://api.pinterest.com/v5/oauth/token",
651
+ userInfo: "https://api.pinterest.com/v5/user_account",
652
+ scope: "user_accounts:read",
653
+ responseType: "code",
654
+ profile(profile) {
655
+ return {
656
+ sub: profile.id,
657
+ name: profile.username,
658
+ email: null,
659
+ image: profile.profile_image
660
+ };
661
+ }
662
+ };
663
+
664
+ // src/schemas.ts
665
+ var import_zod = require("zod");
666
+ var OAuthProviderConfigSchema = (0, import_zod.object)({
667
+ authorizeURL: (0, import_zod.string)().url(),
668
+ accessToken: (0, import_zod.string)().url(),
669
+ scope: (0, import_zod.string)().optional(),
670
+ userInfo: (0, import_zod.string)().url(),
671
+ responseType: (0, import_zod.enum)(["code", "token", "id_token"]),
672
+ clientId: (0, import_zod.string)(),
673
+ clientSecret: (0, import_zod.string)()
674
+ });
675
+ var OAuthAuthorization = OAuthProviderConfigSchema.extend({
676
+ redirectURI: (0, import_zod.string)(),
677
+ state: (0, import_zod.string)(),
678
+ codeChallenge: (0, import_zod.string)(),
679
+ codeChallengeMethod: (0, import_zod.enum)(["plain", "S256"])
680
+ });
681
+ var OAuthAuthorizationResponse = (0, import_zod.object)({
682
+ state: (0, import_zod.string)({ message: "Missing state parameter in the OAuth authorization response." }),
683
+ code: (0, import_zod.string)({ message: "Missing code parameter in the OAuth authorization response." })
684
+ });
685
+ var OAuthAuthorizationErrorResponse = (0, import_zod.object)({
686
+ error: (0, import_zod.enum)([
687
+ "invalid_request",
688
+ "unauthorized_client",
689
+ "access_denied",
690
+ "unsupported_response_type",
691
+ "invalid_scope",
692
+ "server_error",
693
+ "temporarily_unavailable"
694
+ ]),
695
+ error_description: (0, import_zod.string)().optional(),
696
+ error_uri: (0, import_zod.string)().optional(),
697
+ state: (0, import_zod.string)()
698
+ });
699
+ var OAuthAccessToken = OAuthProviderConfigSchema.extend({
700
+ redirectURI: (0, import_zod.string)(),
701
+ code: (0, import_zod.string)(),
702
+ codeVerifier: (0, import_zod.string)().min(43).max(128)
703
+ });
704
+ var OAuthAccessTokenResponse = (0, import_zod.object)({
705
+ access_token: (0, import_zod.string)(),
706
+ token_type: (0, import_zod.string)().optional(),
707
+ expires_in: (0, import_zod.number)().optional(),
708
+ refresh_token: (0, import_zod.string)().optional(),
709
+ scope: (0, import_zod.string)().optional().or((0, import_zod.null)())
710
+ });
711
+ var OAuthAccessTokenErrorResponse = (0, import_zod.object)({
712
+ error: (0, import_zod.enum)([
713
+ "invalid_request",
714
+ "invalid_client",
715
+ "invalid_grant",
716
+ "unauthorized_client",
717
+ "unsupported_grant_type",
718
+ "invalid_scope"
719
+ ]),
720
+ error_description: (0, import_zod.string)().optional(),
721
+ error_uri: (0, import_zod.string)().optional()
722
+ });
723
+ var OAuthErrorResponse = (0, import_zod.object)({
724
+ error: (0, import_zod.string)(),
725
+ error_description: (0, import_zod.string)().optional()
726
+ });
727
+ var OAuthEnvSchema = (0, import_zod.object)({
728
+ clientId: import_zod.z.string().min(1, "OAuth Client ID is required in the environment variables."),
729
+ clientSecret: import_zod.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
730
+ });
542
731
 
543
732
  // src/oauth/index.ts
544
733
  var builtInOAuthProviders = {
545
- github,
546
- bitbucket,
547
- figma,
548
- discord,
549
- gitlab,
550
- spotify,
551
- x,
552
- }
734
+ github,
735
+ bitbucket,
736
+ figma,
737
+ discord,
738
+ gitlab,
739
+ spotify,
740
+ x,
741
+ strava,
742
+ mailchimp,
743
+ pinterest
744
+ };
553
745
  var defineOAuthEnvironment = (oauth) => {
554
- const env = process.env
555
- return {
556
- clientId: env[`AURA_AUTH_${oauth.toUpperCase()}_CLIENT_ID`],
557
- clientSecret: env[`AURA_AUTH_${oauth.toUpperCase()}_CLIENT_SECRET`],
558
- }
559
- }
746
+ const env = process.env;
747
+ const clientIdSuffix = `${oauth.toUpperCase()}_CLIENT_ID`;
748
+ const clientSecretSuffix = `${oauth.toUpperCase()}_CLIENT_SECRET`;
749
+ const loadEnvs = OAuthEnvSchema.safeParse({
750
+ clientId: env[`AURA_AUTH_${clientIdSuffix}`] ?? env[`AUTH_${clientIdSuffix}`] ?? env[`${clientIdSuffix}`],
751
+ clientSecret: env[`AURA_AUTH_${clientSecretSuffix}`] ?? env[`AUTH_${clientSecretSuffix}`] ?? env[`${clientSecretSuffix}`]
752
+ });
753
+ if (!loadEnvs.success) {
754
+ const msg = JSON.stringify(formatZodError(loadEnvs.error), null, 2);
755
+ throw new AuthInternalError("INVALID_ENVIRONMENT_CONFIGURATION", msg);
756
+ }
757
+ return loadEnvs.data;
758
+ };
560
759
  var defineOAuthProviderConfig = (config2) => {
561
- if (typeof config2 === "string") {
562
- const definition = defineOAuthEnvironment(config2)
563
- const oauthConfig = builtInOAuthProviders[config2]
564
- return {
565
- ...oauthConfig,
566
- ...definition,
567
- }
568
- }
569
- return config2
570
- }
760
+ if (typeof config2 === "string") {
761
+ const definition = defineOAuthEnvironment(config2);
762
+ const oauthConfig = builtInOAuthProviders[config2];
763
+ return {
764
+ ...oauthConfig,
765
+ ...definition
766
+ };
767
+ }
768
+ return config2;
769
+ };
571
770
  var createBuiltInOAuthProviders = (oauth = []) => {
572
- return oauth.reduce((previous, config2) => {
573
- const oauthConfig = defineOAuthProviderConfig(config2)
574
- return { ...previous, [oauthConfig.id]: oauthConfig }
575
- }, {})
576
- }
771
+ return oauth.reduce((previous, config2) => {
772
+ const oauthConfig = defineOAuthProviderConfig(config2);
773
+ return { ...previous, [oauthConfig.id]: oauthConfig };
774
+ }, {});
775
+ };
577
776
 
578
777
  // src/actions/signIn/signIn.ts
579
- var import_zod = __toESM(require("zod"), 1)
580
- var import_router2 = require("@aura-stack/router")
581
-
582
- // src/response.ts
583
- var AuraResponse = class extends Response {
584
- static json(body, init) {
585
- return Response.json(body, init)
586
- }
587
- }
778
+ var import_zod2 = require("zod");
779
+ var import_router2 = require("@aura-stack/router");
588
780
 
589
- // src/schemas.ts
590
- var import_v4 = require("zod/v4")
591
- var OAuthProviderConfigSchema = (0, import_v4.object)({
592
- authorizeURL: (0, import_v4.url)(),
593
- accessToken: (0, import_v4.url)(),
594
- scope: (0, import_v4.string)().optional(),
595
- userInfo: (0, import_v4.url)(),
596
- responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
597
- clientId: (0, import_v4.string)(),
598
- clientSecret: (0, import_v4.string)(),
599
- })
600
- var OAuthAuthorization = OAuthProviderConfigSchema.extend({
601
- redirectURI: (0, import_v4.string)(),
602
- state: (0, import_v4.string)(),
603
- codeChallenge: (0, import_v4.string)(),
604
- codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"]),
605
- })
606
- var OAuthAuthorizationResponse = (0, import_v4.object)({
607
- state: (0, import_v4.string)(),
608
- code: (0, import_v4.string)(),
609
- })
610
- var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
611
- error: (0, import_v4.enum)([
612
- "invalid_request",
613
- "unauthorized_client",
614
- "access_denied",
615
- "unsupported_response_type",
616
- "invalid_scope",
617
- "server_error",
618
- "temporarily_unavailable",
619
- ]),
620
- error_description: (0, import_v4.string)().optional(),
621
- error_uri: (0, import_v4.string)().optional(),
622
- state: (0, import_v4.string)(),
623
- })
624
- var OAuthAccessToken = OAuthProviderConfigSchema.extend({
625
- redirectURI: (0, import_v4.string)(),
626
- code: (0, import_v4.string)(),
627
- codeVerifier: (0, import_v4.string)().min(43).max(128),
628
- })
629
- var OAuthAccessTokenResponse = (0, import_v4.object)({
630
- access_token: (0, import_v4.string)(),
631
- token_type: (0, import_v4.string)(),
632
- expires_in: (0, import_v4.number)().optional(),
633
- refresh_token: (0, import_v4.string)().optional(),
634
- scope: (0, import_v4.string)().optional(),
635
- })
636
- var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
637
- error: (0, import_v4.enum)([
638
- "invalid_request",
639
- "invalid_client",
640
- "invalid_grant",
641
- "unauthorized_client",
642
- "unsupported_grant_type",
643
- "invalid_scope",
644
- ]),
645
- error_description: (0, import_v4.string)().optional(),
646
- error_uri: (0, import_v4.string)().optional(),
647
- })
648
- var OAuthErrorResponse = (0, import_v4.object)({
649
- error: (0, import_v4.string)(),
650
- error_description: (0, import_v4.string)().optional(),
651
- })
781
+ // src/headers.ts
782
+ var cacheControl = {
783
+ "Cache-Control": "no-store",
784
+ Pragma: "no-cache",
785
+ Expires: "0",
786
+ Vary: "Cookie"
787
+ };
652
788
 
653
789
  // src/actions/signIn/authorization.ts
654
790
  var createAuthorizationURL = (oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod) => {
655
- const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod })
656
- if (!parsed.success) {
657
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR, "Invalid OAuth configuration")
658
- }
659
- const { authorizeURL, ...options2 } = parsed.data
660
- const { userInfo, accessToken, clientSecret, ...required } = options2
661
- const searchParams = new URLSearchParams(toCastCase(required))
662
- return `${authorizeURL}?${searchParams}`
663
- }
791
+ const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod });
792
+ if (!parsed.success) {
793
+ const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
794
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
795
+ }
796
+ const { authorizeURL, ...options2 } = parsed.data;
797
+ const { userInfo, accessToken, clientSecret, ...required } = options2;
798
+ const searchParams = new URLSearchParams(toCastCase(required));
799
+ return `${authorizeURL}?${searchParams}`;
800
+ };
664
801
  var getOriginURL = (request, trustedProxyHeaders) => {
665
- const headers = request.headers
666
- if (trustedProxyHeaders) {
667
- const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http"
668
- const host =
669
- headers.get("X-Forwarded-Host") ??
670
- headers.get("Host") ??
671
- headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ??
672
- null
673
- return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`)
674
- } else {
675
- return new URL(getNormalizedOriginPath(request.url))
676
- }
677
- }
802
+ const headers = request.headers;
803
+ if (trustedProxyHeaders) {
804
+ const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http";
805
+ const host = headers.get("X-Forwarded-Host") ?? headers.get("Host") ?? headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? null;
806
+ return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`);
807
+ } else {
808
+ return new URL(getNormalizedOriginPath(request.url));
809
+ }
810
+ };
678
811
  var createRedirectURI = (request, oauth, basePath, trustedProxyHeaders) => {
679
- const url2 = getOriginURL(request, trustedProxyHeaders)
680
- return `${url2.origin}${basePath}/callback/${oauth}`
681
- }
812
+ const url = getOriginURL(request, trustedProxyHeaders);
813
+ return `${url.origin}${basePath}/callback/${oauth}`;
814
+ };
682
815
  var createRedirectTo = (request, redirectTo, trustedProxyHeaders) => {
683
- try {
684
- const headers = request.headers
685
- const origin = headers.get("Origin")
686
- const referer = headers.get("Referer")
687
- let hostedURL = getOriginURL(request, trustedProxyHeaders)
688
- if (redirectTo) {
689
- if (redirectTo.startsWith("/")) {
690
- return sanitizeURL(redirectTo)
691
- }
692
- const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)))
693
- if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
694
- throw new InvalidRedirectToError()
695
- }
696
- return sanitizeURL(redirectToURL.pathname)
697
- }
698
- if (referer) {
699
- const refererURL = new URL(sanitizeURL(referer))
700
- if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
701
- throw new AuthError(
702
- ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST,
703
- "The referer of the request does not match the hosted origin."
704
- )
705
- }
706
- return sanitizeURL(refererURL.pathname)
707
- }
708
- if (origin) {
709
- const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)))
710
- if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
711
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).")
712
- }
713
- return sanitizeURL(originURL.pathname)
714
- }
715
- return "/"
716
- } catch (error) {
717
- if (isAuthError(error)) {
718
- throw error
719
- }
720
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).")
816
+ try {
817
+ const headers = request.headers;
818
+ const origin = headers.get("Origin");
819
+ const referer = headers.get("Referer");
820
+ let hostedURL = getOriginURL(request, trustedProxyHeaders);
821
+ if (redirectTo) {
822
+ if (redirectTo.startsWith("/")) {
823
+ return sanitizeURL(redirectTo);
824
+ }
825
+ const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)));
826
+ if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
827
+ throw new AuthSecurityError(
828
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
829
+ "The redirectTo parameter does not match the hosted origin."
830
+ );
831
+ }
832
+ return sanitizeURL(redirectToURL.pathname);
833
+ }
834
+ if (referer) {
835
+ const refererURL = new URL(sanitizeURL(referer));
836
+ if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
837
+ throw new AuthSecurityError(
838
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
839
+ "The referer of the request does not match the hosted origin."
840
+ );
841
+ }
842
+ return sanitizeURL(refererURL.pathname);
843
+ }
844
+ if (origin) {
845
+ const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)));
846
+ if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
847
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
848
+ }
849
+ return sanitizeURL(originURL.pathname);
850
+ }
851
+ return "/";
852
+ } catch (error) {
853
+ if (isAuthSecurityError(error)) {
854
+ throw error;
721
855
  }
722
- }
856
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
857
+ }
858
+ };
723
859
 
724
860
  // src/actions/signIn/signIn.ts
725
861
  var signInConfig = (oauth) => {
726
- return (0, import_router2.createEndpointConfig)("/signIn/:oauth", {
727
- schemas: {
728
- params: import_zod.default.object({
729
- oauth: import_zod.default.enum(Object.keys(oauth)),
730
- redirectTo: import_zod.default.string().optional(),
731
- }),
732
- },
733
- })
734
- }
862
+ return (0, import_router2.createEndpointConfig)("/signIn/:oauth", {
863
+ schemas: {
864
+ params: import_zod2.z.object({
865
+ oauth: import_zod2.z.enum(
866
+ Object.keys(oauth),
867
+ "The OAuth provider is not supported or invalid."
868
+ )
869
+ }),
870
+ searchParams: import_zod2.z.object({
871
+ redirectTo: import_zod2.z.string().optional()
872
+ })
873
+ }
874
+ });
875
+ };
735
876
  var signInAction = (oauth) => {
736
- return (0, import_router2.createEndpoint)(
737
- "GET",
738
- "/signIn/:oauth",
739
- async (ctx) => {
740
- const {
741
- request,
742
- params: { oauth: oauth2, redirectTo },
743
- context: { oauth: providers, cookies, trustedProxyHeaders, basePath },
744
- } = ctx
745
- try {
746
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
747
- const state = generateSecure()
748
- const redirectURI = createRedirectURI(request, oauth2, basePath, trustedProxyHeaders)
749
- const stateCookie = setCookie("state", state, oauthCookie(cookieOptions))
750
- const redirectURICookie = setCookie("redirect_uri", redirectURI, oauthCookie(cookieOptions))
751
- const redirectToCookie = setCookie(
752
- "redirect_to",
753
- createRedirectTo(request, redirectTo, trustedProxyHeaders),
754
- oauthCookie(cookieOptions)
755
- )
756
- const { codeVerifier, codeChallenge, method } = await createPKCE()
757
- const codeVerifierCookie = setCookie("code_verifier", codeVerifier, oauthCookie(cookieOptions))
758
- const authorization = createAuthorizationURL(providers[oauth2], redirectURI, state, codeChallenge, method)
759
- const headers = new Headers()
760
- headers.set("Location", authorization)
761
- headers.append("Set-Cookie", stateCookie)
762
- headers.append("Set-Cookie", redirectURICookie)
763
- headers.append("Set-Cookie", redirectToCookie)
764
- headers.append("Set-Cookie", codeVerifierCookie)
765
- return Response.json(
766
- { oauth: oauth2 },
767
- {
768
- status: 302,
769
- headers,
770
- }
771
- )
772
- } catch (error) {
773
- if (isAuthError(error)) {
774
- const { type, message } = error
775
- return AuraResponse.json(
776
- { error: type, error_description: message },
777
- { status: import_router2.statusCode.BAD_REQUEST }
778
- )
779
- }
780
- return AuraResponse.json(
781
- {
782
- error: ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR,
783
- error_description: "An unexpected error occurred",
784
- },
785
- { status: import_router2.statusCode.INTERNAL_SERVER_ERROR }
786
- )
787
- }
788
- },
789
- signInConfig(oauth)
790
- )
791
- }
877
+ return (0, import_router2.createEndpoint)(
878
+ "GET",
879
+ "/signIn/:oauth",
880
+ async (ctx) => {
881
+ const {
882
+ request,
883
+ params: { oauth: oauth2 },
884
+ searchParams: { redirectTo },
885
+ context: { oauth: providers, cookies, trustedProxyHeaders, basePath }
886
+ } = ctx;
887
+ const state = generateSecure();
888
+ const redirectURI = createRedirectURI(request, oauth2, basePath, trustedProxyHeaders);
889
+ const redirectToValue = createRedirectTo(request, redirectTo, trustedProxyHeaders);
890
+ const { codeVerifier, codeChallenge, method } = await createPKCE();
891
+ const authorization = createAuthorizationURL(providers[oauth2], redirectURI, state, codeChallenge, method);
892
+ const headers = new import_router2.HeadersBuilder(cacheControl).setHeader("Location", authorization).setCookie(cookies.state.name, state, cookies.state.attributes).setCookie(cookies.redirectURI.name, redirectURI, cookies.redirectURI.attributes).setCookie(cookies.redirectTo.name, redirectToValue, cookies.redirectTo.attributes).setCookie(cookies.codeVerifier.name, codeVerifier, cookies.codeVerifier.attributes).toHeaders();
893
+ return Response.json(
894
+ { oauth: oauth2 },
895
+ {
896
+ status: 302,
897
+ headers
898
+ }
899
+ );
900
+ },
901
+ signInConfig(oauth)
902
+ );
903
+ };
792
904
 
793
905
  // src/actions/callback/callback.ts
794
- var import_zod2 = __toESM(require("zod"), 1)
795
- var import_router3 = require("@aura-stack/router")
906
+ var import_zod3 = require("zod");
907
+ var import_router3 = require("@aura-stack/router");
796
908
 
797
- // src/headers.ts
798
- var cacheControl = {
799
- "Cache-Control": "no-store",
800
- Pragma: "no-cache",
801
- Expires: "0",
802
- Vary: "Cookie",
803
- }
909
+ // src/request.ts
910
+ var fetchAsync = async (url, options2 = {}, timeout = 5e3) => {
911
+ const controller = new AbortController();
912
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
913
+ const response = await fetch(url, {
914
+ ...options2,
915
+ signal: controller.signal
916
+ }).finally(() => clearTimeout(timeoutId));
917
+ return response;
918
+ };
804
919
 
805
920
  // src/actions/callback/userinfo.ts
806
921
  var getDefaultUserInfo = (profile) => {
807
- const sub = generateSecure(16)
808
- return {
809
- sub: profile?.id ?? profile?.sub ?? sub,
810
- email: profile?.email,
811
- name: profile?.name ?? profile?.username ?? profile?.nickname,
812
- image: profile?.image ?? profile?.picture,
813
- }
814
- }
922
+ const sub = generateSecure(16);
923
+ return {
924
+ sub: profile?.id ?? profile?.sub ?? sub,
925
+ email: profile?.email,
926
+ name: profile?.name ?? profile?.username ?? profile?.nickname,
927
+ image: profile?.image ?? profile?.picture
928
+ };
929
+ };
815
930
  var getUserInfo = async (oauthConfig, accessToken) => {
816
- const userinfoEndpoint = oauthConfig.userInfo
817
- try {
818
- const response = await fetch(userinfoEndpoint, {
819
- method: "GET",
820
- headers: {
821
- Accept: "application/json",
822
- Authorization: `Bearer ${accessToken}`,
823
- },
824
- })
825
- const json = await response.json()
826
- const { success, data } = OAuthErrorResponse.safeParse(json)
827
- if (success) {
828
- throw new AuthError(data.error, data?.error_description ?? "An error occurred while fetching user information.")
829
- }
830
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json)
831
- } catch (error) {
832
- throw throwAuthError(error, "Failed to retrieve userinfo")
931
+ const userinfoEndpoint = oauthConfig.userInfo;
932
+ try {
933
+ const response = await fetchAsync(userinfoEndpoint, {
934
+ method: "GET",
935
+ headers: {
936
+ Accept: "application/json",
937
+ Authorization: `Bearer ${accessToken}`
938
+ }
939
+ });
940
+ const json = await response.json();
941
+ const { success, data } = OAuthErrorResponse.safeParse(json);
942
+ if (success) {
943
+ throw new OAuthProtocolError(
944
+ data.error,
945
+ data?.error_description ?? "An error occurred while fetching user information."
946
+ );
947
+ }
948
+ return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
949
+ } catch (error) {
950
+ if (isOAuthProtocolError(error)) {
951
+ throw error;
833
952
  }
834
- }
953
+ if (isNativeError(error)) {
954
+ throw new OAuthProtocolError("invalid_request", error.message, "", { cause: error });
955
+ }
956
+ throw new OAuthProtocolError("invalid_request", "Failed to fetch user information.", "", { cause: error });
957
+ }
958
+ };
835
959
 
836
960
  // src/actions/callback/access-token.ts
837
961
  var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier) => {
838
- const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier })
839
- if (!parsed.success) {
840
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Invalid OAuth configuration")
841
- }
842
- const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data
843
- try {
844
- const response = await fetch(accessToken, {
845
- method: "POST",
846
- headers: {
847
- Accept: "application/json",
848
- "Content-Type": "application/x-www-form-urlencoded",
849
- },
850
- body: new URLSearchParams({
851
- client_id: clientId,
852
- client_secret: clientSecret,
853
- code: codeParsed,
854
- redirect_uri: redirectParsed,
855
- grant_type: "authorization_code",
856
- code_verifier: codeVerifier,
857
- }).toString(),
858
- })
859
- const json = await response.json()
860
- const token = OAuthAccessTokenResponse.safeParse(json)
861
- if (!token.success) {
862
- const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json)
863
- if (!success) {
864
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_GRANT, "Invalid access token response format")
865
- }
866
- throw new AuthError(data.error, data?.error_description ?? "Failed to retrieve access token")
867
- }
868
- return token.data
869
- } catch (error) {
870
- throw throwAuthError(error, "Failed to create access token")
962
+ const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier });
963
+ if (!parsed.success) {
964
+ const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
965
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
966
+ }
967
+ const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data;
968
+ try {
969
+ const response = await fetchAsync(accessToken, {
970
+ method: "POST",
971
+ headers: {
972
+ Accept: "application/json",
973
+ "Content-Type": "application/x-www-form-urlencoded"
974
+ },
975
+ body: new URLSearchParams({
976
+ client_id: clientId,
977
+ client_secret: clientSecret,
978
+ code: codeParsed,
979
+ redirect_uri: redirectParsed,
980
+ grant_type: "authorization_code",
981
+ code_verifier: codeVerifier
982
+ }).toString()
983
+ });
984
+ const json = await response.json();
985
+ const token = OAuthAccessTokenResponse.safeParse(json);
986
+ if (!token.success) {
987
+ const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json);
988
+ if (!success) {
989
+ throw new OAuthProtocolError("INVALID_REQUEST", "Invalid access token response format");
990
+ }
991
+ throw new OAuthProtocolError(data.error, data?.error_description ?? "Failed to retrieve access token");
871
992
  }
872
- }
993
+ return token.data;
994
+ } catch (error) {
995
+ throw error;
996
+ }
997
+ };
873
998
 
874
999
  // src/actions/callback/callback.ts
875
1000
  var callbackConfig = (oauth) => {
876
- return (0, import_router3.createEndpointConfig)("/callback/:oauth", {
877
- schemas: {
878
- searchParams: OAuthAuthorizationResponse,
879
- params: import_zod2.default.object({
880
- oauth: import_zod2.default.enum(Object.keys(oauth)),
881
- }),
882
- },
883
- middlewares: [
884
- (ctx) => {
885
- const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams)
886
- if (response.success) {
887
- const { error, error_description } = response.data
888
- throw new AuthError(error, error_description ?? "OAuth Authorization Error")
889
- }
890
- return ctx
891
- },
892
- ],
893
- })
894
- }
1001
+ return (0, import_router3.createEndpointConfig)("/callback/:oauth", {
1002
+ schemas: {
1003
+ params: import_zod3.z.object({
1004
+ oauth: import_zod3.z.enum(
1005
+ Object.keys(oauth),
1006
+ "The OAuth provider is not supported or invalid."
1007
+ )
1008
+ }),
1009
+ searchParams: import_zod3.z.object({
1010
+ code: import_zod3.z.string("Missing code parameter in the OAuth authorization response."),
1011
+ state: import_zod3.z.string("Missing state parameter in the OAuth authorization response.")
1012
+ })
1013
+ },
1014
+ middlewares: [
1015
+ (ctx) => {
1016
+ const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams);
1017
+ if (response.success) {
1018
+ const { error, error_description } = response.data;
1019
+ throw new OAuthProtocolError(error, error_description ?? "OAuth Authorization Error");
1020
+ }
1021
+ return ctx;
1022
+ }
1023
+ ]
1024
+ });
1025
+ };
895
1026
  var callbackAction = (oauth) => {
896
- return (0, import_router3.createEndpoint)(
897
- "GET",
898
- "/callback/:oauth",
899
- async (ctx) => {
900
- const {
901
- request,
902
- params: { oauth: oauth2 },
903
- searchParams: { code, state },
904
- context: { oauth: providers, cookies, jose, trustedProxyHeaders },
905
- } = ctx
906
- try {
907
- const oauthConfig = providers[oauth2]
908
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
909
- const cookieState = getCookie(request, "state", cookieOptions)
910
- const cookieRedirectTo = getCookie(request, "redirect_to", cookieOptions)
911
- const cookieRedirectURI = getCookie(request, "redirect_uri", cookieOptions)
912
- const codeVerifier = getCookie(request, "code_verifier", cookieOptions)
913
- if (!equals(cookieState, state)) {
914
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Mismatching state")
915
- }
916
- const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier)
917
- const sanitized = sanitizeURL(cookieRedirectTo)
918
- if (!isValidRelativePath(sanitized)) {
919
- throw new AuthError(
920
- ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST,
921
- "Invalid redirect path. Potential open redirect attack detected."
922
- )
923
- }
924
- const headers = new Headers(cacheControl)
925
- headers.set("Location", sanitized)
926
- const userInfo = await getUserInfo(oauthConfig, accessToken.access_token)
927
- const sessionCookie = await createSessionCookie(userInfo, cookieOptions, jose)
928
- const csrfToken = await createCSRF(jose)
929
- const csrfCookie = setCookie(
930
- "csrfToken",
931
- csrfToken,
932
- secureCookieOptions(
933
- request,
934
- {
935
- ...cookies,
936
- strategy: "host",
937
- },
938
- trustedProxyHeaders
939
- )
940
- )
941
- headers.set("Set-Cookie", sessionCookie)
942
- headers.append("Set-Cookie", expireCookie("state", cookieOptions))
943
- headers.append("Set-Cookie", expireCookie("redirect_uri", cookieOptions))
944
- headers.append("Set-Cookie", expireCookie("redirect_to", cookieOptions))
945
- headers.append("Set-Cookie", expireCookie("code_verifier", cookieOptions))
946
- headers.append("Set-Cookie", csrfCookie)
947
- return Response.json({ oauth: oauth2 }, { status: 302, headers })
948
- } catch (error) {
949
- if (isAuthError(error)) {
950
- const { type, message } = error
951
- return AuraResponse.json(
952
- { error: type, error_description: message },
953
- { status: import_router3.statusCode.BAD_REQUEST }
954
- )
955
- }
956
- return AuraResponse.json(
957
- {
958
- error: ERROR_RESPONSE.ACCESS_TOKEN.INVALID_CLIENT,
959
- error_description: "An unexpected error occurred",
960
- },
961
- { status: import_router3.statusCode.INTERNAL_SERVER_ERROR }
962
- )
963
- }
964
- },
965
- callbackConfig(oauth)
966
- )
967
- }
1027
+ return (0, import_router3.createEndpoint)(
1028
+ "GET",
1029
+ "/callback/:oauth",
1030
+ async (ctx) => {
1031
+ const {
1032
+ request,
1033
+ params: { oauth: oauth2 },
1034
+ searchParams: { code, state },
1035
+ context: { oauth: providers, cookies, jose }
1036
+ } = ctx;
1037
+ const oauthConfig = providers[oauth2];
1038
+ const cookieState = getCookie(request, cookies.state.name);
1039
+ const cookieRedirectTo = getCookie(request, cookies.redirectTo.name);
1040
+ const cookieRedirectURI = getCookie(request, cookies.redirectURI.name);
1041
+ const codeVerifier = getCookie(request, cookies.codeVerifier.name);
1042
+ if (!equals(cookieState, state)) {
1043
+ throw new AuthSecurityError(
1044
+ "MISMATCHING_STATE",
1045
+ "The provided state passed in the OAuth response does not match the stored state."
1046
+ );
1047
+ }
1048
+ const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier);
1049
+ const sanitized = sanitizeURL(cookieRedirectTo);
1050
+ if (!isValidRelativePath(sanitized)) {
1051
+ throw new AuthSecurityError(
1052
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
1053
+ "Invalid redirect path. Potential open redirect attack detected."
1054
+ );
1055
+ }
1056
+ const userInfo = await getUserInfo(oauthConfig, accessToken.access_token);
1057
+ const sessionCookie = await createSessionCookie(jose, userInfo);
1058
+ const csrfToken = await createCSRF(jose);
1059
+ 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.redirectURI.name, "", expiredCookieAttributes).setCookie(cookies.redirectTo.name, "", expiredCookieAttributes).setCookie(cookies.codeVerifier.name, "", expiredCookieAttributes).toHeaders();
1060
+ return Response.json({ oauth: oauth2 }, { status: 302, headers });
1061
+ },
1062
+ callbackConfig(oauth)
1063
+ );
1064
+ };
968
1065
 
969
1066
  // src/actions/session/session.ts
970
- var import_router4 = require("@aura-stack/router")
1067
+ var import_router4 = require("@aura-stack/router");
971
1068
  var sessionAction = (0, import_router4.createEndpoint)("GET", "/session", async (ctx) => {
972
- const {
973
- request,
974
- context: { cookies, jose, trustedProxyHeaders },
975
- } = ctx
976
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
977
- try {
978
- const session = getCookie(request, "sessionToken", cookieOptions)
979
- const decoded = await jose.decodeJWT(session)
980
- const { exp, iat, jti, nbf, ...user } = decoded
981
- const headers = new Headers(cacheControl)
982
- return Response.json({ user, expires: toISOString(exp * 1e3) }, { headers })
983
- } catch {
984
- const headers = new Headers(cacheControl)
985
- const sessionCookie = expireCookie("sessionToken", cookieOptions)
986
- headers.set("Set-Cookie", sessionCookie)
987
- return Response.json({ authenticated: false, message: "Unauthorized" }, { status: 401, headers })
988
- }
989
- })
1069
+ const {
1070
+ request,
1071
+ context: { jose, cookies }
1072
+ } = ctx;
1073
+ try {
1074
+ const session = getCookie(request, cookies.sessionToken.name);
1075
+ const decoded = await jose.decodeJWT(session);
1076
+ const { exp, iat, jti, nbf, ...user } = decoded;
1077
+ const headers = new Headers(cacheControl);
1078
+ return Response.json({ user, expires: toISOString(exp * 1e3) }, { headers });
1079
+ } catch (error) {
1080
+ const headers = new import_router4.HeadersBuilder(cacheControl).setCookie(cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
1081
+ return Response.json({ authenticated: false, message: "Unauthorized" }, { status: 401, headers });
1082
+ }
1083
+ });
990
1084
 
991
1085
  // src/actions/signOut/signOut.ts
992
- var import_zod3 = __toESM(require("zod"), 1)
993
- var import_router5 = require("@aura-stack/router")
1086
+ var import_zod4 = require("zod");
1087
+ var import_router5 = require("@aura-stack/router");
994
1088
  var config = (0, import_router5.createEndpointConfig)({
995
- schemas: {
996
- searchParams: import_zod3.default.object({
997
- token_type_hint: import_zod3.default.literal("session_token"),
998
- redirectTo: import_zod3.default.string().optional(),
999
- }),
1000
- },
1001
- })
1089
+ schemas: {
1090
+ searchParams: import_zod4.z.object({
1091
+ token_type_hint: import_zod4.z.literal("session_token"),
1092
+ redirectTo: import_zod4.z.string().optional()
1093
+ })
1094
+ }
1095
+ });
1002
1096
  var signOutAction = (0, import_router5.createEndpoint)(
1003
- "POST",
1004
- "/signOut",
1005
- async (ctx) => {
1006
- const {
1007
- request,
1008
- headers,
1009
- searchParams: { redirectTo },
1010
- context: { cookies, jose, trustedProxyHeaders },
1011
- } = ctx
1012
- try {
1013
- const cookiesOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
1014
- const session = getCookie(request, "sessionToken", cookiesOptions)
1015
- const csrfToken = getCookie(request, "csrfToken", {
1016
- ...cookiesOptions,
1017
- prefix: cookiesOptions.secure ? "__Host-" : "",
1018
- })
1019
- const header = headers.get("X-CSRF-Token")
1020
- if (!header || !session || !csrfToken) {
1021
- throw new Error("Missing CSRF token or session token")
1022
- }
1023
- await verifyCSRF(jose, csrfToken, header)
1024
- await jose.decodeJWT(session)
1025
- const normalizedOriginPath = getNormalizedOriginPath(request.url)
1026
- const location = createRedirectTo(
1027
- new Request(normalizedOriginPath, {
1028
- headers,
1029
- }),
1030
- redirectTo
1031
- )
1032
- const responseHeaders = new Headers(cacheControl)
1033
- responseHeaders.append("Set-Cookie", expireCookie("sessionToken", cookiesOptions))
1034
- responseHeaders.append(
1035
- "Set-Cookie",
1036
- expireCookie("csrfToken", { ...cookiesOptions, prefix: cookiesOptions.secure ? "__Host-" : "" })
1037
- )
1038
- responseHeaders.append("Location", location)
1039
- return Response.json(
1040
- { message: "Signed out successfully" },
1041
- { status: import_router5.statusCode.ACCEPTED, headers: responseHeaders }
1042
- )
1043
- } catch (error) {
1044
- if (error instanceof InvalidCsrfTokenError) {
1045
- return AuraResponse.json(
1046
- {
1047
- error: "invalid_csrf_token",
1048
- error_description: "The provided CSRF token is invalid or has expired",
1049
- },
1050
- { status: import_router5.statusCode.UNAUTHORIZED }
1051
- )
1052
- }
1053
- if (error instanceof InvalidRedirectToError) {
1054
- const { type, message } = error
1055
- return AuraResponse.json(
1056
- {
1057
- error: type,
1058
- error_description: message,
1059
- },
1060
- { status: import_router5.statusCode.BAD_REQUEST }
1061
- )
1062
- }
1063
- return AuraResponse.json(
1064
- {
1065
- error: "invalid_session_token",
1066
- error_description: "The provided sessionToken is invalid or has already expired",
1067
- },
1068
- { status: import_router5.statusCode.UNAUTHORIZED }
1069
- )
1070
- }
1071
- },
1072
- config
1073
- )
1097
+ "POST",
1098
+ "/signOut",
1099
+ async (ctx) => {
1100
+ const {
1101
+ request,
1102
+ headers,
1103
+ searchParams: { redirectTo },
1104
+ context: { jose, cookies }
1105
+ } = ctx;
1106
+ const session = headers.getCookie(cookies.sessionToken.name);
1107
+ const csrfToken = headers.getCookie(cookies.csrfToken.name);
1108
+ const header = headers.getHeader("X-CSRF-Token");
1109
+ if (!session) {
1110
+ throw new AuthSecurityError("SESSION_TOKEN_MISSING", "The sessionToken is missing.");
1111
+ }
1112
+ if (!csrfToken) {
1113
+ throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF token is missing.");
1114
+ }
1115
+ if (!header) {
1116
+ throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF header is missing.");
1117
+ }
1118
+ await verifyCSRF(jose, csrfToken, header);
1119
+ await jose.decodeJWT(session);
1120
+ const normalizedOriginPath = getNormalizedOriginPath(request.url);
1121
+ const location = createRedirectTo(
1122
+ new Request(normalizedOriginPath, {
1123
+ headers: headers.toHeaders()
1124
+ }),
1125
+ redirectTo
1126
+ );
1127
+ const headersList = new import_router5.HeadersBuilder(cacheControl).setHeader("Location", location).setCookie(cookies.csrfToken.name, "", expiredCookieAttributes).setCookie(cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
1128
+ return Response.json({ message: "Signed out successfully" }, { status: import_router5.statusCode.ACCEPTED, headers: headersList });
1129
+ },
1130
+ config
1131
+ );
1074
1132
 
1075
1133
  // src/actions/csrfToken/csrfToken.ts
1076
- var import_router6 = require("@aura-stack/router")
1134
+ var import_router6 = require("@aura-stack/router");
1135
+ var getCSRFToken = (request, cookieName) => {
1136
+ try {
1137
+ return getCookie(request, cookieName);
1138
+ } catch {
1139
+ return void 0;
1140
+ }
1141
+ };
1077
1142
  var csrfTokenAction = (0, import_router6.createEndpoint)("GET", "/csrfToken", async (ctx) => {
1078
- const {
1079
- request,
1080
- context: { cookies, jose, trustedProxyHeaders },
1081
- } = ctx
1082
- const cookieOptions = secureCookieOptions(request, { ...cookies, strategy: "host" }, trustedProxyHeaders)
1083
- const existingCSRFToken = getCookie(request, "csrfToken", cookieOptions, true)
1084
- const csrfToken = await createCSRF(jose, existingCSRFToken)
1085
- const headers = new Headers(cacheControl)
1086
- headers.set("Set-Cookie", setCookie("csrfToken", csrfToken, cookieOptions))
1087
- return Response.json({ csrfToken }, { headers })
1088
- })
1143
+ const {
1144
+ request,
1145
+ context: { jose, cookies }
1146
+ } = ctx;
1147
+ const token = getCSRFToken(request, cookies.csrfToken.name);
1148
+ const csrfToken = await createCSRF(jose, token);
1149
+ const headers = new Headers(cacheControl);
1150
+ headers.append("Set-Cookie", setCookie(cookies.csrfToken.name, csrfToken, cookies.csrfToken.attributes));
1151
+ return Response.json({ csrfToken }, { headers });
1152
+ });
1089
1153
 
1090
1154
  // src/index.ts
1091
1155
  var createInternalConfig = (authConfig) => {
1092
- return {
1093
- basePath: authConfig?.basePath ?? "/auth",
1094
- onError: onErrorHandler,
1095
- context: {
1096
- oauth: createBuiltInOAuthProviders(authConfig?.oauth),
1097
- cookies: authConfig?.cookies ?? defaultCookieConfig,
1098
- jose: createJoseInstance(authConfig?.secret),
1099
- basePath: authConfig?.basePath ?? "/auth",
1100
- trustedProxyHeaders: !!authConfig?.trustedProxyHeaders,
1101
- },
1102
- }
1103
- }
1156
+ const useSecure = authConfig?.trustedProxyHeaders ?? false;
1157
+ return {
1158
+ basePath: authConfig?.basePath ?? "/auth",
1159
+ onError: onErrorHandler,
1160
+ context: {
1161
+ oauth: createBuiltInOAuthProviders(authConfig?.oauth),
1162
+ cookies: createCookieStore(useSecure, authConfig?.cookies?.prefix, authConfig?.cookies?.overrides ?? {}),
1163
+ jose: createJoseInstance(authConfig?.secret),
1164
+ secret: authConfig?.secret,
1165
+ basePath: authConfig?.basePath ?? "/auth",
1166
+ trustedProxyHeaders: useSecure
1167
+ },
1168
+ middlewares: [
1169
+ (ctx) => {
1170
+ const useSecure2 = useSecureCookies(ctx.request, ctx.context.trustedProxyHeaders);
1171
+ const cookies = createCookieStore(useSecure2, authConfig?.cookies?.prefix, authConfig?.cookies?.overrides ?? {});
1172
+ ctx.context.cookies = cookies;
1173
+ return ctx;
1174
+ }
1175
+ ]
1176
+ };
1177
+ };
1104
1178
  var createAuth = (authConfig) => {
1105
- const config2 = createInternalConfig(authConfig)
1106
- const router = (0, import_router7.createRouter)(
1107
- [
1108
- signInAction(config2.context.oauth),
1109
- callbackAction(config2.context.oauth),
1110
- sessionAction,
1111
- signOutAction,
1112
- csrfTokenAction,
1113
- ],
1114
- config2
1115
- )
1116
- return {
1117
- handlers: router,
1118
- jose: config2.context.jose,
1119
- }
1120
- }
1179
+ const config2 = createInternalConfig(authConfig);
1180
+ const router = (0, import_router7.createRouter)(
1181
+ [signInAction(config2.context.oauth), callbackAction(config2.context.oauth), sessionAction, signOutAction, csrfTokenAction],
1182
+ config2
1183
+ );
1184
+ return {
1185
+ handlers: router,
1186
+ jose: config2.context.jose
1187
+ };
1188
+ };
1121
1189
  // Annotate the CommonJS export names for ESM import in node:
1122
- 0 &&
1123
- (module.exports = {
1124
- createAuth,
1125
- })
1190
+ 0 && (module.exports = {
1191
+ createAuth
1192
+ });