@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
@@ -1,535 +1,439 @@
1
- "use strict"
2
- var __create = Object.create
3
- var __defProp = Object.defineProperty
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor
5
- var __getOwnPropNames = Object.getOwnPropertyNames
6
- var __getProtoOf = Object.getPrototypeOf
7
- var __hasOwnProp = Object.prototype.hasOwnProperty
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __export = (target, all) => {
9
- for (var name in all) __defProp(target, name, { get: all[name], enumerable: true })
10
- }
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
11
12
  var __copyProps = (to, from, except, desc) => {
12
- if ((from && typeof from === "object") || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable })
16
- }
17
- return to
18
- }
19
- var __toESM = (mod, isNodeMode, target) => (
20
- (target = mod != null ? __create(__getProtoOf(mod)) : {}),
21
- __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- )
29
- )
30
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod)
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
29
 
32
30
  // src/actions/callback/callback.ts
33
- var callback_exports = {}
31
+ var callback_exports = {};
34
32
  __export(callback_exports, {
35
- callbackAction: () => callbackAction,
36
- })
37
- module.exports = __toCommonJS(callback_exports)
38
- var import_zod = __toESM(require("zod"), 1)
39
- var import_router2 = require("@aura-stack/router")
33
+ callbackAction: () => callbackAction
34
+ });
35
+ module.exports = __toCommonJS(callback_exports);
36
+ var import_zod2 = require("zod");
37
+ var import_router2 = require("@aura-stack/router");
40
38
 
41
39
  // src/secure.ts
42
- var import_node_crypto = __toESM(require("crypto"), 1)
40
+ var import_crypto = __toESM(require("crypto"), 1);
43
41
 
44
42
  // src/utils.ts
45
- var import_router = require("@aura-stack/router")
43
+ var import_router = require("@aura-stack/router");
46
44
 
47
- // src/error.ts
48
- var AuthError = class extends Error {
49
- constructor(type, message) {
50
- super(message)
51
- this.type = type
52
- this.name = "AuthError"
53
- }
54
- }
55
- var isAuthError = (error) => {
56
- return error instanceof AuthError
57
- }
58
- var throwAuthError = (error, message) => {
59
- if (error instanceof Error) {
60
- if (isAuthError(error)) {
61
- throw error
62
- }
63
- throw new AuthError("invalid_request", error.message ?? message)
64
- }
65
- }
66
- var ERROR_RESPONSE = {
67
- AUTHORIZATION: {
68
- INVALID_REQUEST: "invalid_request",
69
- UNAUTHORIZED_CLIENT: "unauthorized_client",
70
- ACCESS_DENIED: "access_denied",
71
- UNSUPPORTED_RESPONSE_TYPE: "unsupported_response_type",
72
- INVALID_SCOPE: "invalid_scope",
73
- SERVER_ERROR: "server_error",
74
- TEMPORARILY_UNAVAILABLE: "temporarily_unavailable",
75
- },
76
- ACCESS_TOKEN: {
77
- INVALID_REQUEST: "invalid_request",
78
- INVALID_CLIENT: "invalid_client",
79
- INVALID_GRANT: "invalid_grant",
80
- UNAUTHORIZED_CLIENT: "unauthorized_client",
81
- UNSUPPORTED_GRANT_TYPE: "unsupported_grant_type",
82
- INVALID_SCOPE: "invalid_scope",
83
- },
84
- }
45
+ // src/errors.ts
46
+ var OAuthProtocolError = class extends Error {
47
+ type = "OAUTH_PROTOCOL_ERROR";
48
+ error;
49
+ errorURI;
50
+ constructor(error, description, errorURI, options2) {
51
+ super(description, options2);
52
+ this.error = error;
53
+ this.errorURI = errorURI;
54
+ this.name = new.target.name;
55
+ Error.captureStackTrace(this, new.target);
56
+ }
57
+ };
58
+ var AuthInternalError = class extends Error {
59
+ type = "AUTH_INTERNAL_ERROR";
60
+ code;
61
+ constructor(code, message, options2) {
62
+ super(message, options2);
63
+ this.code = code;
64
+ this.name = new.target.name;
65
+ Error.captureStackTrace(this, new.target);
66
+ }
67
+ };
68
+ var AuthSecurityError = class extends Error {
69
+ type = "AUTH_SECURITY_ERROR";
70
+ code;
71
+ constructor(code, message, options2) {
72
+ super(message, options2);
73
+ this.code = code;
74
+ this.name = new.target.name;
75
+ Error.captureStackTrace(this, new.target);
76
+ }
77
+ };
78
+ var isNativeError = (error) => {
79
+ return error instanceof Error;
80
+ };
81
+ var isOAuthProtocolError = (error) => {
82
+ return error instanceof OAuthProtocolError;
83
+ };
85
84
 
86
85
  // src/utils.ts
87
86
  var equals = (a, b) => {
88
- if (a === null || b === null || a === void 0 || b === void 0) return false
89
- return a === b
90
- }
91
- var sanitizeURL = (url2) => {
92
- try {
93
- let decodedURL = decodeURIComponent(url2).trim()
94
- const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/)
95
- let protocol = ""
96
- let rest = decodedURL
97
- if (protocolMatch) {
98
- protocol = protocolMatch[1]
99
- rest = decodedURL.slice(protocol.length)
100
- const slashIndex = rest.indexOf("/")
101
- if (slashIndex === -1) {
102
- return protocol + rest
103
- }
104
- const domain = rest.slice(0, slashIndex)
105
- let path = rest
106
- .slice(slashIndex)
107
- .replace(/\/\.\.\//g, "/")
108
- .replace(/\/\.\.$/, "")
109
- .replace(/\.{2,}/g, "")
110
- .replace(/\/{2,}/g, "/")
111
- if (path !== "/" && path.endsWith("/")) {
112
- path = path.replace(/\/+$/, "/")
113
- } else if (path !== "/") {
114
- path = path.replace(/\/+$/, "")
115
- }
116
- return protocol + domain + path
117
- }
118
- let sanitized = decodedURL
119
- .replace(/\/\.\.\//g, "/")
120
- .replace(/\/\.\.$/, "")
121
- .replace(/\.{2,}/g, "")
122
- .replace(/\/{2,}/g, "/")
123
- if (sanitized !== "/" && sanitized.endsWith("/")) {
124
- sanitized = sanitized.replace(/\/+$/, "/")
125
- } else if (sanitized !== "/") {
126
- sanitized = sanitized.replace(/\/+$/, "")
127
- }
128
- return sanitized
129
- } catch {
130
- return url2.trim()
87
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
88
+ return a === b;
89
+ };
90
+ var sanitizeURL = (url) => {
91
+ try {
92
+ let decodedURL = decodeURIComponent(url).trim();
93
+ const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/);
94
+ let protocol = "";
95
+ let rest = decodedURL;
96
+ if (protocolMatch) {
97
+ protocol = protocolMatch[1];
98
+ rest = decodedURL.slice(protocol.length);
99
+ const slashIndex = rest.indexOf("/");
100
+ if (slashIndex === -1) {
101
+ return protocol + rest;
102
+ }
103
+ const domain = rest.slice(0, slashIndex);
104
+ let path = rest.slice(slashIndex).replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
105
+ if (path !== "/" && path.endsWith("/")) {
106
+ path = path.replace(/\/+$/, "/");
107
+ } else if (path !== "/") {
108
+ path = path.replace(/\/+$/, "");
109
+ }
110
+ return protocol + domain + path;
111
+ }
112
+ let sanitized = decodedURL.replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
113
+ if (sanitized !== "/" && sanitized.endsWith("/")) {
114
+ sanitized = sanitized.replace(/\/+$/, "/");
115
+ } else if (sanitized !== "/") {
116
+ sanitized = sanitized.replace(/\/+$/, "");
131
117
  }
132
- }
118
+ return sanitized;
119
+ } catch {
120
+ return url.trim();
121
+ }
122
+ };
133
123
  var isValidRelativePath = (path) => {
134
- if (!path || typeof path !== "string") return false
135
- if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false
136
- if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false
137
- const sanitized = sanitizeURL(path)
138
- if (sanitized.includes("..")) return false
139
- return true
140
- }
124
+ if (!path || typeof path !== "string") return false;
125
+ if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false;
126
+ if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false;
127
+ const sanitized = sanitizeURL(path);
128
+ if (sanitized.includes("..")) return false;
129
+ return true;
130
+ };
131
+ var formatZodError = (error) => {
132
+ if (!error.issues || error.issues.length === 0) {
133
+ return {};
134
+ }
135
+ return error.issues.reduce((previous, issue) => {
136
+ const key = issue.path.join(".");
137
+ return {
138
+ ...previous,
139
+ [key]: {
140
+ code: issue.code,
141
+ message: issue.message
142
+ }
143
+ };
144
+ }, {});
145
+ };
141
146
 
142
147
  // src/secure.ts
143
148
  var generateSecure = (length = 32) => {
144
- return import_node_crypto.default.randomBytes(length).toString("base64url")
145
- }
149
+ return import_crypto.default.randomBytes(length).toString("base64url");
150
+ };
146
151
  var createCSRF = async (jose, csrfCookie) => {
147
- try {
148
- const token = generateSecure(32)
149
- if (csrfCookie) {
150
- await jose.verifyJWS(csrfCookie)
151
- return csrfCookie
152
- }
153
- return jose.signJWS({ token })
154
- } catch {
155
- const token = generateSecure(32)
156
- return jose.signJWS({ token })
152
+ try {
153
+ const token = generateSecure(32);
154
+ if (csrfCookie) {
155
+ await jose.verifyJWS(csrfCookie);
156
+ return csrfCookie;
157
157
  }
158
- }
158
+ return jose.signJWS({ token });
159
+ } catch {
160
+ const token = generateSecure(32);
161
+ return jose.signJWS({ token });
162
+ }
163
+ };
159
164
 
160
165
  // src/headers.ts
161
166
  var cacheControl = {
162
- "Cache-Control": "no-store",
163
- Pragma: "no-cache",
164
- Expires: "0",
165
- Vary: "Cookie",
166
- }
167
+ "Cache-Control": "no-store",
168
+ Pragma: "no-cache",
169
+ Expires: "0",
170
+ Vary: "Cookie"
171
+ };
172
+
173
+ // src/request.ts
174
+ var fetchAsync = async (url, options2 = {}, timeout = 5e3) => {
175
+ const controller = new AbortController();
176
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
177
+ const response = await fetch(url, {
178
+ ...options2,
179
+ signal: controller.signal
180
+ }).finally(() => clearTimeout(timeoutId));
181
+ return response;
182
+ };
167
183
 
168
184
  // src/schemas.ts
169
- var import_v4 = require("zod/v4")
170
- var OAuthProviderConfigSchema = (0, import_v4.object)({
171
- authorizeURL: (0, import_v4.url)(),
172
- accessToken: (0, import_v4.url)(),
173
- scope: (0, import_v4.string)().optional(),
174
- userInfo: (0, import_v4.url)(),
175
- responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
176
- clientId: (0, import_v4.string)(),
177
- clientSecret: (0, import_v4.string)(),
178
- })
185
+ var import_zod = require("zod");
186
+ var OAuthProviderConfigSchema = (0, import_zod.object)({
187
+ authorizeURL: (0, import_zod.string)().url(),
188
+ accessToken: (0, import_zod.string)().url(),
189
+ scope: (0, import_zod.string)().optional(),
190
+ userInfo: (0, import_zod.string)().url(),
191
+ responseType: (0, import_zod.enum)(["code", "token", "id_token"]),
192
+ clientId: (0, import_zod.string)(),
193
+ clientSecret: (0, import_zod.string)()
194
+ });
179
195
  var OAuthAuthorization = OAuthProviderConfigSchema.extend({
180
- redirectURI: (0, import_v4.string)(),
181
- state: (0, import_v4.string)(),
182
- codeChallenge: (0, import_v4.string)(),
183
- codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"]),
184
- })
185
- var OAuthAuthorizationResponse = (0, import_v4.object)({
186
- state: (0, import_v4.string)(),
187
- code: (0, import_v4.string)(),
188
- })
189
- var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
190
- error: (0, import_v4.enum)([
191
- "invalid_request",
192
- "unauthorized_client",
193
- "access_denied",
194
- "unsupported_response_type",
195
- "invalid_scope",
196
- "server_error",
197
- "temporarily_unavailable",
198
- ]),
199
- error_description: (0, import_v4.string)().optional(),
200
- error_uri: (0, import_v4.string)().optional(),
201
- state: (0, import_v4.string)(),
202
- })
196
+ redirectURI: (0, import_zod.string)(),
197
+ state: (0, import_zod.string)(),
198
+ codeChallenge: (0, import_zod.string)(),
199
+ codeChallengeMethod: (0, import_zod.enum)(["plain", "S256"])
200
+ });
201
+ var OAuthAuthorizationResponse = (0, import_zod.object)({
202
+ state: (0, import_zod.string)({ message: "Missing state parameter in the OAuth authorization response." }),
203
+ code: (0, import_zod.string)({ message: "Missing code parameter in the OAuth authorization response." })
204
+ });
205
+ var OAuthAuthorizationErrorResponse = (0, import_zod.object)({
206
+ error: (0, import_zod.enum)([
207
+ "invalid_request",
208
+ "unauthorized_client",
209
+ "access_denied",
210
+ "unsupported_response_type",
211
+ "invalid_scope",
212
+ "server_error",
213
+ "temporarily_unavailable"
214
+ ]),
215
+ error_description: (0, import_zod.string)().optional(),
216
+ error_uri: (0, import_zod.string)().optional(),
217
+ state: (0, import_zod.string)()
218
+ });
203
219
  var OAuthAccessToken = OAuthProviderConfigSchema.extend({
204
- redirectURI: (0, import_v4.string)(),
205
- code: (0, import_v4.string)(),
206
- codeVerifier: (0, import_v4.string)().min(43).max(128),
207
- })
208
- var OAuthAccessTokenResponse = (0, import_v4.object)({
209
- access_token: (0, import_v4.string)(),
210
- token_type: (0, import_v4.string)(),
211
- expires_in: (0, import_v4.number)().optional(),
212
- refresh_token: (0, import_v4.string)().optional(),
213
- scope: (0, import_v4.string)().optional(),
214
- })
215
- var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
216
- error: (0, import_v4.enum)([
217
- "invalid_request",
218
- "invalid_client",
219
- "invalid_grant",
220
- "unauthorized_client",
221
- "unsupported_grant_type",
222
- "invalid_scope",
223
- ]),
224
- error_description: (0, import_v4.string)().optional(),
225
- error_uri: (0, import_v4.string)().optional(),
226
- })
227
- var OAuthErrorResponse = (0, import_v4.object)({
228
- error: (0, import_v4.string)(),
229
- error_description: (0, import_v4.string)().optional(),
230
- })
220
+ redirectURI: (0, import_zod.string)(),
221
+ code: (0, import_zod.string)(),
222
+ codeVerifier: (0, import_zod.string)().min(43).max(128)
223
+ });
224
+ var OAuthAccessTokenResponse = (0, import_zod.object)({
225
+ access_token: (0, import_zod.string)(),
226
+ token_type: (0, import_zod.string)().optional(),
227
+ expires_in: (0, import_zod.number)().optional(),
228
+ refresh_token: (0, import_zod.string)().optional(),
229
+ scope: (0, import_zod.string)().optional().or((0, import_zod.null)())
230
+ });
231
+ var OAuthAccessTokenErrorResponse = (0, import_zod.object)({
232
+ error: (0, import_zod.enum)([
233
+ "invalid_request",
234
+ "invalid_client",
235
+ "invalid_grant",
236
+ "unauthorized_client",
237
+ "unsupported_grant_type",
238
+ "invalid_scope"
239
+ ]),
240
+ error_description: (0, import_zod.string)().optional(),
241
+ error_uri: (0, import_zod.string)().optional()
242
+ });
243
+ var OAuthErrorResponse = (0, import_zod.object)({
244
+ error: (0, import_zod.string)(),
245
+ error_description: (0, import_zod.string)().optional()
246
+ });
247
+ var OAuthEnvSchema = (0, import_zod.object)({
248
+ clientId: import_zod.z.string().min(1, "OAuth Client ID is required in the environment variables."),
249
+ clientSecret: import_zod.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
250
+ });
231
251
 
232
252
  // src/actions/callback/userinfo.ts
233
253
  var getDefaultUserInfo = (profile) => {
234
- const sub = generateSecure(16)
235
- return {
236
- sub: profile?.id ?? profile?.sub ?? sub,
237
- email: profile?.email,
238
- name: profile?.name ?? profile?.username ?? profile?.nickname,
239
- image: profile?.image ?? profile?.picture,
240
- }
241
- }
254
+ const sub = generateSecure(16);
255
+ return {
256
+ sub: profile?.id ?? profile?.sub ?? sub,
257
+ email: profile?.email,
258
+ name: profile?.name ?? profile?.username ?? profile?.nickname,
259
+ image: profile?.image ?? profile?.picture
260
+ };
261
+ };
242
262
  var getUserInfo = async (oauthConfig, accessToken) => {
243
- const userinfoEndpoint = oauthConfig.userInfo
244
- try {
245
- const response = await fetch(userinfoEndpoint, {
246
- method: "GET",
247
- headers: {
248
- Accept: "application/json",
249
- Authorization: `Bearer ${accessToken}`,
250
- },
251
- })
252
- const json = await response.json()
253
- const { success, data } = OAuthErrorResponse.safeParse(json)
254
- if (success) {
255
- throw new AuthError(data.error, data?.error_description ?? "An error occurred while fetching user information.")
256
- }
257
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json)
258
- } catch (error) {
259
- throw throwAuthError(error, "Failed to retrieve userinfo")
263
+ const userinfoEndpoint = oauthConfig.userInfo;
264
+ try {
265
+ const response = await fetchAsync(userinfoEndpoint, {
266
+ method: "GET",
267
+ headers: {
268
+ Accept: "application/json",
269
+ Authorization: `Bearer ${accessToken}`
270
+ }
271
+ });
272
+ const json = await response.json();
273
+ const { success, data } = OAuthErrorResponse.safeParse(json);
274
+ if (success) {
275
+ throw new OAuthProtocolError(
276
+ data.error,
277
+ data?.error_description ?? "An error occurred while fetching user information."
278
+ );
260
279
  }
261
- }
262
-
263
- // src/response.ts
264
- var AuraResponse = class extends Response {
265
- static json(body, init) {
266
- return Response.json(body, init)
280
+ return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
281
+ } catch (error) {
282
+ if (isOAuthProtocolError(error)) {
283
+ throw error;
267
284
  }
268
- }
285
+ if (isNativeError(error)) {
286
+ throw new OAuthProtocolError("invalid_request", error.message, "", { cause: error });
287
+ }
288
+ throw new OAuthProtocolError("invalid_request", "Failed to fetch user information.", "", { cause: error });
289
+ }
290
+ };
269
291
 
270
292
  // src/actions/callback/access-token.ts
271
293
  var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier) => {
272
- const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier })
273
- if (!parsed.success) {
274
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Invalid OAuth configuration")
275
- }
276
- const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data
277
- try {
278
- const response = await fetch(accessToken, {
279
- method: "POST",
280
- headers: {
281
- Accept: "application/json",
282
- "Content-Type": "application/x-www-form-urlencoded",
283
- },
284
- body: new URLSearchParams({
285
- client_id: clientId,
286
- client_secret: clientSecret,
287
- code: codeParsed,
288
- redirect_uri: redirectParsed,
289
- grant_type: "authorization_code",
290
- code_verifier: codeVerifier,
291
- }).toString(),
292
- })
293
- const json = await response.json()
294
- const token = OAuthAccessTokenResponse.safeParse(json)
295
- if (!token.success) {
296
- const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json)
297
- if (!success) {
298
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_GRANT, "Invalid access token response format")
299
- }
300
- throw new AuthError(data.error, data?.error_description ?? "Failed to retrieve access token")
301
- }
302
- return token.data
303
- } catch (error) {
304
- throw throwAuthError(error, "Failed to create access token")
294
+ const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier });
295
+ if (!parsed.success) {
296
+ const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
297
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
298
+ }
299
+ const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data;
300
+ try {
301
+ const response = await fetchAsync(accessToken, {
302
+ method: "POST",
303
+ headers: {
304
+ Accept: "application/json",
305
+ "Content-Type": "application/x-www-form-urlencoded"
306
+ },
307
+ body: new URLSearchParams({
308
+ client_id: clientId,
309
+ client_secret: clientSecret,
310
+ code: codeParsed,
311
+ redirect_uri: redirectParsed,
312
+ grant_type: "authorization_code",
313
+ code_verifier: codeVerifier
314
+ }).toString()
315
+ });
316
+ const json = await response.json();
317
+ const token = OAuthAccessTokenResponse.safeParse(json);
318
+ if (!token.success) {
319
+ const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json);
320
+ if (!success) {
321
+ throw new OAuthProtocolError("INVALID_REQUEST", "Invalid access token response format");
322
+ }
323
+ throw new OAuthProtocolError(data.error, data?.error_description ?? "Failed to retrieve access token");
305
324
  }
306
- }
325
+ return token.data;
326
+ } catch (error) {
327
+ throw error;
328
+ }
329
+ };
307
330
 
308
331
  // src/cookie.ts
309
- var import_cookie = require("cookie")
310
-
311
- // src/assert.ts
312
- var isRequest = (value) => {
313
- return typeof Request !== "undefined" && value instanceof Request
314
- }
315
-
316
- // src/cookie.ts
317
- var import_cookie2 = require("cookie")
318
- var COOKIE_NAME = "aura-auth"
332
+ var import_cookie = require("@aura-stack/router/cookie");
319
333
  var defaultCookieOptions = {
320
- httpOnly: true,
321
- sameSite: "lax",
322
- path: "/",
323
- maxAge: 60 * 60 * 24 * 15,
324
- }
325
- var defaultStandardCookieConfig = {
326
- secure: false,
327
- httpOnly: true,
328
- prefix: "",
329
- }
330
- var defaultSecureCookieConfig = {
331
- secure: true,
332
- prefix: "__Secure-",
333
- }
334
- var defaultHostCookieConfig = {
335
- secure: true,
336
- prefix: "__Host-",
337
- path: "/",
338
- domain: void 0,
339
- }
340
- var expiredCookieOptions = {
341
- ...defaultCookieOptions,
342
- expires: /* @__PURE__ */ new Date(0),
343
- maxAge: 0,
344
- }
345
- var defineDefaultCookieOptions = (options2) => {
346
- return {
347
- name: options2?.name ?? COOKIE_NAME,
348
- prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
349
- ...defaultCookieOptions,
350
- ...options2,
351
- }
352
- }
353
- var setCookie = (cookieName, value, options2) => {
354
- const { prefix, name } = defineDefaultCookieOptions(options2)
355
- const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`
356
- return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
357
- ...defaultCookieOptions,
358
- ...options2,
359
- })
360
- }
361
- var getCookie = (petition, cookie, options2, optional = false) => {
362
- const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ")
363
- if (!cookies) {
364
- if (optional) {
365
- return ""
366
- }
367
- throw new AuthError("invalid_request", "No cookies found. There is no active session")
368
- }
369
- const { name, prefix } = defineDefaultCookieOptions(options2)
370
- const parsedCookies = (0, import_cookie.parse)(cookies)
371
- const value = parsedCookies[`${prefix}${name}.${cookie}`]
372
- if (value === void 0) {
373
- if (optional) {
374
- return ""
375
- }
376
- throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`)
377
- }
378
- return value
379
- }
380
- var createSessionCookie = async (session, cookieOptions, jose) => {
381
- try {
382
- const encoded = await jose.encodeJWT(session)
383
- return setCookie("sessionToken", encoded, cookieOptions)
384
- } catch (error) {
385
- throw new AuthError("server_error", "Failed to create session cookie", { cause: error })
386
- }
387
- }
388
- var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
389
- const name = cookieOptions.name ?? COOKIE_NAME
390
- const isSecure = trustedProxyHeaders
391
- ? request.url.startsWith("https://") ||
392
- request.headers.get("X-Forwarded-Proto") === "https" ||
393
- request.headers.get("Forwarded")?.includes("proto=https")
394
- : request.url.startsWith("https://")
395
- if (!cookieOptions.options?.httpOnly) {
396
- console.warn(
397
- "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
398
- )
399
- }
400
- if (cookieOptions.options?.domain === "*") {
401
- console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.")
402
- }
403
- if (!isSecure) {
404
- const options2 = cookieOptions.options
405
- if (options2?.secure) {
406
- console.warn(
407
- "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
408
- )
409
- }
410
- if (options2?.sameSite == "none") {
411
- console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.")
412
- }
413
- if (process.env.NODE_ENV === "production") {
414
- console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.")
415
- }
416
- return {
417
- ...defaultCookieOptions,
418
- ...cookieOptions.options,
419
- sameSite: options2?.sameSite === "none" ? "lax" : (options2?.sameSite ?? "lax"),
420
- ...defaultStandardCookieConfig,
421
- name,
422
- }
423
- }
424
- return cookieOptions.strategy === "host"
425
- ? {
426
- ...defaultCookieOptions,
427
- ...cookieOptions.options,
428
- ...defaultHostCookieConfig,
429
- name,
430
- }
431
- : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name }
432
- }
433
- var expireCookie = (name, options2) => {
434
- return setCookie(name, "", { ...options2, ...expiredCookieOptions })
435
- }
334
+ httpOnly: true,
335
+ sameSite: "lax",
336
+ path: "/",
337
+ maxAge: 60 * 60 * 24 * 15
338
+ };
339
+ var oauthCookieOptions = {
340
+ httpOnly: true,
341
+ maxAge: 5 * 60,
342
+ sameSite: "lax",
343
+ expires: new Date(Date.now() + 5 * 60 * 1e3)
344
+ };
345
+ var expiredCookieAttributes = {
346
+ ...defaultCookieOptions,
347
+ expires: /* @__PURE__ */ new Date(0),
348
+ maxAge: 0
349
+ };
350
+ var getCookie = (request, cookieName) => {
351
+ const cookies = request.headers.get("Cookie");
352
+ if (!cookies) {
353
+ throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
354
+ }
355
+ const value = (0, import_cookie.parse)(cookies)[cookieName];
356
+ if (!value) {
357
+ throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
358
+ }
359
+ return value;
360
+ };
361
+ var createSessionCookie = async (jose, session) => {
362
+ try {
363
+ const encoded = await jose.encodeJWT(session);
364
+ return encoded;
365
+ } catch (error) {
366
+ throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
367
+ }
368
+ };
436
369
 
437
370
  // src/actions/callback/callback.ts
438
371
  var callbackConfig = (oauth) => {
439
- return (0, import_router2.createEndpointConfig)("/callback/:oauth", {
440
- schemas: {
441
- searchParams: OAuthAuthorizationResponse,
442
- params: import_zod.default.object({
443
- oauth: import_zod.default.enum(Object.keys(oauth)),
444
- }),
445
- },
446
- middlewares: [
447
- (ctx) => {
448
- const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams)
449
- if (response.success) {
450
- const { error, error_description } = response.data
451
- throw new AuthError(error, error_description ?? "OAuth Authorization Error")
452
- }
453
- return ctx
454
- },
455
- ],
456
- })
457
- }
372
+ return (0, import_router2.createEndpointConfig)("/callback/:oauth", {
373
+ schemas: {
374
+ params: import_zod2.z.object({
375
+ oauth: import_zod2.z.enum(
376
+ Object.keys(oauth),
377
+ "The OAuth provider is not supported or invalid."
378
+ )
379
+ }),
380
+ searchParams: import_zod2.z.object({
381
+ code: import_zod2.z.string("Missing code parameter in the OAuth authorization response."),
382
+ state: import_zod2.z.string("Missing state parameter in the OAuth authorization response.")
383
+ })
384
+ },
385
+ middlewares: [
386
+ (ctx) => {
387
+ const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams);
388
+ if (response.success) {
389
+ const { error, error_description } = response.data;
390
+ throw new OAuthProtocolError(error, error_description ?? "OAuth Authorization Error");
391
+ }
392
+ return ctx;
393
+ }
394
+ ]
395
+ });
396
+ };
458
397
  var callbackAction = (oauth) => {
459
- return (0, import_router2.createEndpoint)(
460
- "GET",
461
- "/callback/:oauth",
462
- async (ctx) => {
463
- const {
464
- request,
465
- params: { oauth: oauth2 },
466
- searchParams: { code, state },
467
- context: { oauth: providers, cookies, jose, trustedProxyHeaders },
468
- } = ctx
469
- try {
470
- const oauthConfig = providers[oauth2]
471
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
472
- const cookieState = getCookie(request, "state", cookieOptions)
473
- const cookieRedirectTo = getCookie(request, "redirect_to", cookieOptions)
474
- const cookieRedirectURI = getCookie(request, "redirect_uri", cookieOptions)
475
- const codeVerifier = getCookie(request, "code_verifier", cookieOptions)
476
- if (!equals(cookieState, state)) {
477
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Mismatching state")
478
- }
479
- const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier)
480
- const sanitized = sanitizeURL(cookieRedirectTo)
481
- if (!isValidRelativePath(sanitized)) {
482
- throw new AuthError(
483
- ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST,
484
- "Invalid redirect path. Potential open redirect attack detected."
485
- )
486
- }
487
- const headers = new Headers(cacheControl)
488
- headers.set("Location", sanitized)
489
- const userInfo = await getUserInfo(oauthConfig, accessToken.access_token)
490
- const sessionCookie = await createSessionCookie(userInfo, cookieOptions, jose)
491
- const csrfToken = await createCSRF(jose)
492
- const csrfCookie = setCookie(
493
- "csrfToken",
494
- csrfToken,
495
- secureCookieOptions(
496
- request,
497
- {
498
- ...cookies,
499
- strategy: "host",
500
- },
501
- trustedProxyHeaders
502
- )
503
- )
504
- headers.set("Set-Cookie", sessionCookie)
505
- headers.append("Set-Cookie", expireCookie("state", cookieOptions))
506
- headers.append("Set-Cookie", expireCookie("redirect_uri", cookieOptions))
507
- headers.append("Set-Cookie", expireCookie("redirect_to", cookieOptions))
508
- headers.append("Set-Cookie", expireCookie("code_verifier", cookieOptions))
509
- headers.append("Set-Cookie", csrfCookie)
510
- return Response.json({ oauth: oauth2 }, { status: 302, headers })
511
- } catch (error) {
512
- if (isAuthError(error)) {
513
- const { type, message } = error
514
- return AuraResponse.json(
515
- { error: type, error_description: message },
516
- { status: import_router2.statusCode.BAD_REQUEST }
517
- )
518
- }
519
- return AuraResponse.json(
520
- {
521
- error: ERROR_RESPONSE.ACCESS_TOKEN.INVALID_CLIENT,
522
- error_description: "An unexpected error occurred",
523
- },
524
- { status: import_router2.statusCode.INTERNAL_SERVER_ERROR }
525
- )
526
- }
527
- },
528
- callbackConfig(oauth)
529
- )
530
- }
398
+ return (0, import_router2.createEndpoint)(
399
+ "GET",
400
+ "/callback/:oauth",
401
+ async (ctx) => {
402
+ const {
403
+ request,
404
+ params: { oauth: oauth2 },
405
+ searchParams: { code, state },
406
+ context: { oauth: providers, cookies, jose }
407
+ } = ctx;
408
+ const oauthConfig = providers[oauth2];
409
+ const cookieState = getCookie(request, cookies.state.name);
410
+ const cookieRedirectTo = getCookie(request, cookies.redirectTo.name);
411
+ const cookieRedirectURI = getCookie(request, cookies.redirectURI.name);
412
+ const codeVerifier = getCookie(request, cookies.codeVerifier.name);
413
+ if (!equals(cookieState, state)) {
414
+ throw new AuthSecurityError(
415
+ "MISMATCHING_STATE",
416
+ "The provided state passed in the OAuth response does not match the stored state."
417
+ );
418
+ }
419
+ const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier);
420
+ const sanitized = sanitizeURL(cookieRedirectTo);
421
+ if (!isValidRelativePath(sanitized)) {
422
+ throw new AuthSecurityError(
423
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
424
+ "Invalid redirect path. Potential open redirect attack detected."
425
+ );
426
+ }
427
+ const userInfo = await getUserInfo(oauthConfig, accessToken.access_token);
428
+ const sessionCookie = await createSessionCookie(jose, userInfo);
429
+ const csrfToken = await createCSRF(jose);
430
+ const headers = new import_router2.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();
431
+ return Response.json({ oauth: oauth2 }, { status: 302, headers });
432
+ },
433
+ callbackConfig(oauth)
434
+ );
435
+ };
531
436
  // Annotate the CommonJS export names for ESM import in node:
532
- 0 &&
533
- (module.exports = {
534
- callbackAction,
535
- })
437
+ 0 && (module.exports = {
438
+ callbackAction
439
+ });