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