@aura-stack/auth 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/README.md +36 -1
  2. package/dist/@types/index.cjs +0 -18
  3. package/dist/@types/index.d.ts +2 -8
  4. package/dist/@types/index.js +0 -1
  5. package/dist/assert-B3iQSYlK.js +3 -0
  6. package/dist/assert-NJGroSJd.cjs +3 -0
  7. package/dist/client/index.cjs +1 -0
  8. package/dist/client/index.d.ts +11 -0
  9. package/dist/client/index.js +1 -0
  10. package/dist/crypto-Bz8nIciY.js +1 -0
  11. package/dist/crypto-CoXA5w_4.cjs +1 -0
  12. package/dist/env-bq387KyP.cjs +1 -0
  13. package/dist/env-nvh8QBNz.js +1 -0
  14. package/dist/errors-CCYPHuBO.cjs +1 -0
  15. package/dist/errors-DFWHOho6.js +1 -0
  16. package/dist/index-BkpwQ0l4.d.cts +2279 -0
  17. package/dist/index-nqLV2t91.d.ts +2279 -0
  18. package/dist/index.cjs +1 -1839
  19. package/dist/index.d.cts +2 -0
  20. package/dist/index.d.ts +2 -35
  21. package/dist/index.js +1 -132
  22. package/dist/logger-C59_CDMk.js +1 -0
  23. package/dist/logger-UnUhYL2V.cjs +1 -0
  24. package/dist/oauth/atlassian.cjs +1 -0
  25. package/dist/oauth/atlassian.d.ts +2 -0
  26. package/dist/oauth/atlassian.js +1 -0
  27. package/dist/oauth/bitbucket.cjs +1 -49
  28. package/dist/oauth/bitbucket.d.ts +2 -8
  29. package/dist/oauth/bitbucket.js +1 -6
  30. package/dist/oauth/discord.cjs +1 -57
  31. package/dist/oauth/discord.d.ts +2 -8
  32. package/dist/oauth/discord.js +1 -6
  33. package/dist/oauth/dropbox.cjs +1 -0
  34. package/dist/oauth/dropbox.d.ts +2 -0
  35. package/dist/oauth/dropbox.js +1 -0
  36. package/dist/oauth/figma.cjs +1 -49
  37. package/dist/oauth/figma.d.ts +2 -8
  38. package/dist/oauth/figma.js +1 -6
  39. package/dist/oauth/github.cjs +1 -49
  40. package/dist/oauth/github.d.ts +2 -8
  41. package/dist/oauth/github.js +1 -6
  42. package/dist/oauth/gitlab.cjs +1 -49
  43. package/dist/oauth/gitlab.d.ts +2 -8
  44. package/dist/oauth/gitlab.js +1 -6
  45. package/dist/oauth/index.cjs +1 -483
  46. package/dist/oauth/index.d.ts +2 -8
  47. package/dist/oauth/index.js +1 -52
  48. package/dist/oauth/mailchimp.cjs +1 -49
  49. package/dist/oauth/mailchimp.d.ts +2 -8
  50. package/dist/oauth/mailchimp.js +1 -6
  51. package/dist/oauth/notion.cjs +1 -0
  52. package/dist/oauth/notion.d.ts +2 -0
  53. package/dist/oauth/notion.js +1 -0
  54. package/dist/oauth/pinterest.cjs +1 -49
  55. package/dist/oauth/pinterest.d.ts +2 -8
  56. package/dist/oauth/pinterest.js +1 -6
  57. package/dist/oauth/spotify.cjs +1 -49
  58. package/dist/oauth/spotify.d.ts +2 -8
  59. package/dist/oauth/spotify.js +1 -6
  60. package/dist/oauth/strava.cjs +1 -49
  61. package/dist/oauth/strava.d.ts +2 -8
  62. package/dist/oauth/strava.js +1 -6
  63. package/dist/oauth/twitch.cjs +1 -0
  64. package/dist/oauth/twitch.d.ts +2 -0
  65. package/dist/oauth/twitch.js +1 -0
  66. package/dist/oauth/x.cjs +1 -49
  67. package/dist/oauth/x.d.ts +2 -8
  68. package/dist/oauth/x.js +1 -6
  69. package/dist/oauth-BntNm6aE.cjs +1 -0
  70. package/dist/oauth-DmHy9VrB.js +1 -0
  71. package/dist/shared/crypto.cjs +1 -0
  72. package/dist/shared/crypto.d.ts +47 -0
  73. package/dist/shared/crypto.js +1 -0
  74. package/dist/shared/identity.cjs +1 -0
  75. package/dist/shared/identity.d.ts +2 -0
  76. package/dist/shared/identity.js +1 -0
  77. package/dist/shared/index.cjs +1 -0
  78. package/dist/shared/index.d.ts +5 -0
  79. package/dist/shared/index.js +1 -0
  80. package/package.json +39 -12
  81. package/dist/@types/router.d.cjs +0 -1
  82. package/dist/@types/router.d.d.ts +0 -12
  83. package/dist/@types/router.d.js +0 -0
  84. package/dist/@types/utility.cjs +0 -18
  85. package/dist/@types/utility.d.ts +0 -6
  86. package/dist/@types/utility.js +0 -1
  87. package/dist/actions/callback/access-token.cjs +0 -206
  88. package/dist/actions/callback/access-token.d.ts +0 -29
  89. package/dist/actions/callback/access-token.js +0 -9
  90. package/dist/actions/callback/callback.cjs +0 -649
  91. package/dist/actions/callback/callback.d.ts +0 -13
  92. package/dist/actions/callback/callback.js +0 -19
  93. package/dist/actions/callback/userinfo.cjs +0 -250
  94. package/dist/actions/callback/userinfo.d.ts +0 -21
  95. package/dist/actions/callback/userinfo.js +0 -14
  96. package/dist/actions/csrfToken/csrfToken.cjs +0 -197
  97. package/dist/actions/csrfToken/csrfToken.d.ts +0 -5
  98. package/dist/actions/csrfToken/csrfToken.js +0 -14
  99. package/dist/actions/index.cjs +0 -954
  100. package/dist/actions/index.d.ts +0 -14
  101. package/dist/actions/index.js +0 -36
  102. package/dist/actions/session/session.cjs +0 -136
  103. package/dist/actions/session/session.d.ts +0 -5
  104. package/dist/actions/session/session.js +0 -10
  105. package/dist/actions/signIn/authorization.cjs +0 -322
  106. package/dist/actions/signIn/authorization.d.ts +0 -53
  107. package/dist/actions/signIn/authorization.js +0 -18
  108. package/dist/actions/signIn/signIn.cjs +0 -467
  109. package/dist/actions/signIn/signIn.d.ts +0 -13
  110. package/dist/actions/signIn/signIn.js +0 -15
  111. package/dist/actions/signOut/signOut.cjs +0 -493
  112. package/dist/actions/signOut/signOut.d.ts +0 -8
  113. package/dist/actions/signOut/signOut.js +0 -16
  114. package/dist/assert.cjs +0 -161
  115. package/dist/assert.d.ts +0 -33
  116. package/dist/assert.js +0 -26
  117. package/dist/chunk-4EKY7655.js +0 -123
  118. package/dist/chunk-4MYWAOLG.js +0 -31
  119. package/dist/chunk-4YHJ4IEQ.js +0 -25
  120. package/dist/chunk-54CZPKR4.js +0 -25
  121. package/dist/chunk-5LZ7TOM3.js +0 -25
  122. package/dist/chunk-5W4BRQYG.js +0 -201
  123. package/dist/chunk-6MXFPFR3.js +0 -143
  124. package/dist/chunk-7QF22LHP.js +0 -67
  125. package/dist/chunk-ALG3GIV4.js +0 -95
  126. package/dist/chunk-E6G5YCI6.js +0 -25
  127. package/dist/chunk-EBAMFRB7.js +0 -34
  128. package/dist/chunk-EEE7UM5T.js +0 -25
  129. package/dist/chunk-FRJFWTOY.js +0 -70
  130. package/dist/chunk-FW4W3REU.js +0 -25
  131. package/dist/chunk-ICAZ4OVS.js +0 -37
  132. package/dist/chunk-IPKO6UQN.js +0 -25
  133. package/dist/chunk-ITQ7352M.js +0 -0
  134. package/dist/chunk-KJBAQZX2.js +0 -92
  135. package/dist/chunk-KMMAZFSJ.js +0 -25
  136. package/dist/chunk-LDU7A2JE.js +0 -25
  137. package/dist/chunk-NUDITUKX.js +0 -73
  138. package/dist/chunk-OVHNRULD.js +0 -33
  139. package/dist/chunk-PG7UYFG5.js +0 -0
  140. package/dist/chunk-PHFH2MGS.js +0 -36
  141. package/dist/chunk-QQVSRXGX.js +0 -149
  142. package/dist/chunk-RRLIF4PQ.js +0 -55
  143. package/dist/chunk-TM5IPSNF.js +0 -113
  144. package/dist/chunk-TZB6MUXN.js +0 -78
  145. package/dist/chunk-VNCNJKS2.js +0 -267
  146. package/dist/chunk-XGLBNXL4.js +0 -75
  147. package/dist/chunk-XUP6KKNG.js +0 -106
  148. package/dist/chunk-ZNCZVF6U.js +0 -14
  149. package/dist/cookie.cjs +0 -246
  150. package/dist/cookie.d.ts +0 -85
  151. package/dist/cookie.js +0 -29
  152. package/dist/env.cjs +0 -56
  153. package/dist/env.d.ts +0 -7
  154. package/dist/env.js +0 -6
  155. package/dist/errors.cjs +0 -85
  156. package/dist/errors.d.ts +0 -50
  157. package/dist/errors.js +0 -18
  158. package/dist/headers.cjs +0 -61
  159. package/dist/headers.d.ts +0 -33
  160. package/dist/headers.js +0 -12
  161. package/dist/index-CSyIJmCM.d.ts +0 -1007
  162. package/dist/jose.cjs +0 -128
  163. package/dist/jose.d.ts +0 -25
  164. package/dist/jose.js +0 -12
  165. package/dist/logger.cjs +0 -292
  166. package/dist/logger.d.ts +0 -8
  167. package/dist/logger.js +0 -8
  168. package/dist/request.cjs +0 -38
  169. package/dist/request.d.ts +0 -13
  170. package/dist/request.js +0 -6
  171. package/dist/schemas.cjs +0 -125
  172. package/dist/schemas.d.ts +0 -149
  173. package/dist/schemas.js +0 -24
  174. package/dist/secure.cjs +0 -170
  175. package/dist/secure.d.ts +0 -35
  176. package/dist/secure.js +0 -19
  177. package/dist/utils.cjs +0 -223
  178. package/dist/utils.d.ts +0 -24
  179. package/dist/utils.js +0 -29
@@ -1,649 +0,0 @@
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/actions/callback/callback.ts
31
- var callback_exports = {};
32
- __export(callback_exports, {
33
- callbackAction: () => callbackAction
34
- });
35
- module.exports = __toCommonJS(callback_exports);
36
- var import_zod2 = require("zod");
37
- var import_router2 = require("@aura-stack/router");
38
-
39
- // src/secure.ts
40
- var import_crypto2 = __toESM(require("crypto"), 1);
41
-
42
- // src/utils.ts
43
- var import_router = require("@aura-stack/router");
44
-
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
- };
84
-
85
- // src/utils.ts
86
- var equals = (a, b) => {
87
- if (a === null || b === null || a === void 0 || b === void 0) return false;
88
- return a === b;
89
- };
90
-
91
- // src/assert.ts
92
- var import_crypto = require("crypto");
93
- var unsafeChars = [
94
- "<",
95
- ">",
96
- '"',
97
- "`",
98
- " ",
99
- "\r",
100
- "\n",
101
- " ",
102
- "\\",
103
- "%2F",
104
- "%5C",
105
- "%2f",
106
- "%5c",
107
- "\r\n",
108
- "%0A",
109
- "%0D",
110
- "%0a",
111
- "%0d",
112
- "..",
113
- "//",
114
- "///",
115
- "...",
116
- "%20",
117
- "\0"
118
- ];
119
- var isValidURL = (value) => {
120
- if (!new RegExp(/^https?:\/\/[^/]/).test(value)) {
121
- return false;
122
- }
123
- const match = value.match(/^(https?:\/\/)(.*)$/);
124
- if (!match) return false;
125
- const rest = match[2];
126
- for (const char of unsafeChars) {
127
- if (rest.includes(char)) return false;
128
- }
129
- const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()?#*+,;=:@-]*)*\/?$/;
130
- return regex.test(match[0]);
131
- };
132
- var isRelativeURL = (value) => {
133
- if (value.length > 100) return false;
134
- for (const char of unsafeChars) {
135
- if (value.includes(char)) return false;
136
- }
137
- const regex = /^\/[a-zA-Z0-9\-_\/.?&=#]*\/?$/;
138
- return regex.test(value);
139
- };
140
- var isSameOrigin = (origin, expected) => {
141
- const originURL = new URL(origin);
142
- const expectedURL = new URL(expected);
143
- return equals(originURL.origin, expectedURL.origin);
144
- };
145
- var patternToRegex = (pattern) => {
146
- try {
147
- if (pattern.length > 2048) return null;
148
- pattern = pattern.replace(/\\/g, "");
149
- const match = pattern.match(/^(https?):\/\/([a-zA-Z0-9.*-]{1,253})(?::(\d{1,5}|\*))?(?:\/.*)?$/);
150
- if (!match) return null;
151
- const [, protocol, host, port] = match;
152
- const hasWildcard = host.includes("*");
153
- if (hasWildcard && !host.startsWith("*.")) return null;
154
- if (hasWildcard && host.slice(2).includes("*")) return null;
155
- const domain = hasWildcard ? host.slice(2) : host;
156
- const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
157
- const hostRegex = hasWildcard ? `[^.]+\\.${escapedDomain}` : escapedDomain;
158
- const portRegex = port === "*" ? ":\\d{1,5}" : port ? `:${port}` : "";
159
- return new RegExp(`^${protocol}:\\/\\/${hostRegex}${portRegex}$`);
160
- } catch {
161
- return null;
162
- }
163
- };
164
- var isTrustedOrigin = (url, trustedOrigins) => {
165
- if (!isValidURL(url) || trustedOrigins.length === 0) return false;
166
- try {
167
- const urlOrigin = new URL(url).origin;
168
- for (const pattern of trustedOrigins) {
169
- const regex = patternToRegex(pattern);
170
- if (regex?.test(urlOrigin)) return true;
171
- try {
172
- if (isValidURL(pattern) && equals(new URL(pattern).origin, urlOrigin)) return true;
173
- } catch {
174
- }
175
- }
176
- } catch {
177
- }
178
- return false;
179
- };
180
- var safeEquals = (a, b) => {
181
- const bufferA = Buffer.from(a);
182
- const bufferB = Buffer.from(b);
183
- if (bufferA.length !== bufferB.length) {
184
- return false;
185
- }
186
- return (0, import_crypto.timingSafeEqual)(bufferA, bufferB);
187
- };
188
-
189
- // src/env.ts
190
- var import_meta = {};
191
- var env = new Proxy({}, {
192
- get(_, prop) {
193
- if (typeof prop !== "string") return void 0;
194
- const hasProperty = (process2) => {
195
- return process2 && Object.prototype.hasOwnProperty.call(process2, prop);
196
- };
197
- try {
198
- if (typeof process !== "undefined" && hasProperty(process.env)) {
199
- return process.env[prop];
200
- }
201
- if (typeof import_meta !== "undefined" && hasProperty(import_meta.env)) {
202
- return import_meta.env[prop];
203
- }
204
- if (typeof Deno !== "undefined" && Deno.env?.get) {
205
- return Deno.env.get(prop);
206
- }
207
- if (typeof Bun !== "undefined" && hasProperty(Bun.env)) {
208
- return Bun.env[prop];
209
- }
210
- const globalValue = globalThis[prop];
211
- return typeof globalValue === "string" ? globalValue : void 0;
212
- } catch {
213
- return void 0;
214
- }
215
- }
216
- });
217
-
218
- // src/jose.ts
219
- var import_jose = require("@aura-stack/jose");
220
- var jwtVerificationOptions = {
221
- algorithms: ["HS256"],
222
- typ: "JWT"
223
- };
224
-
225
- // src/secure.ts
226
- var generateSecure = (length = 32) => {
227
- return import_crypto2.default.randomBytes(length).toString("base64url");
228
- };
229
- var createCSRF = async (jose, csrfCookie) => {
230
- try {
231
- const token = generateSecure(32);
232
- if (csrfCookie) {
233
- await jose.verifyJWS(csrfCookie, jwtVerificationOptions);
234
- return csrfCookie;
235
- }
236
- return jose.signJWS({ token });
237
- } catch {
238
- const token = generateSecure(32);
239
- return jose.signJWS({ token });
240
- }
241
- };
242
-
243
- // src/headers.ts
244
- var cacheControl = {
245
- "Cache-Control": "no-store",
246
- Pragma: "no-cache",
247
- Expires: "0",
248
- Vary: "Cookie"
249
- };
250
- var contentSecurityPolicy = {
251
- "Content-Security-Policy": [
252
- "default-src 'none'",
253
- "script-src 'self'",
254
- "frame-src 'none'",
255
- "object-src 'none'",
256
- "frame-ancestors 'none'",
257
- "base-uri 'none'"
258
- ].join("; ")
259
- };
260
- var secureHeaders = {
261
- "X-Content-Type-Options": "nosniff",
262
- "X-Frame-Options": "DENY",
263
- "Referrer-Policy": "strict-origin-when-cross-origin"
264
- };
265
- var secureApiHeaders = {
266
- ...cacheControl,
267
- ...contentSecurityPolicy,
268
- ...secureHeaders
269
- };
270
-
271
- // src/request.ts
272
- var fetchAsync = async (url, options2 = {}, timeout = 5e3) => {
273
- const controller = new AbortController();
274
- const timeoutId = setTimeout(() => controller.abort(), timeout);
275
- const response = await fetch(url, {
276
- ...options2,
277
- signal: controller.signal
278
- }).finally(() => clearTimeout(timeoutId));
279
- return response;
280
- };
281
-
282
- // src/schemas.ts
283
- var import_zod = require("zod");
284
- var OAuthProviderCredentialsSchema = (0, import_zod.object)({
285
- id: (0, import_zod.string)(),
286
- name: (0, import_zod.string)(),
287
- authorizeURL: (0, import_zod.string)().url(),
288
- accessToken: (0, import_zod.string)().url(),
289
- scope: (0, import_zod.string)(),
290
- userInfo: (0, import_zod.string)().url(),
291
- responseType: (0, import_zod.enum)(["code", "token", "id_token"]),
292
- clientId: (0, import_zod.string)(),
293
- clientSecret: (0, import_zod.string)(),
294
- profile: import_zod.z.function().optional()
295
- });
296
- var OAuthProviderConfigSchema = (0, import_zod.object)({
297
- authorizeURL: (0, import_zod.string)().url(),
298
- accessToken: (0, import_zod.string)().url(),
299
- scope: (0, import_zod.string)().optional(),
300
- userInfo: (0, import_zod.string)().url(),
301
- responseType: (0, import_zod.enum)(["code", "token", "id_token"]),
302
- clientId: (0, import_zod.string)(),
303
- clientSecret: (0, import_zod.string)()
304
- });
305
- var OAuthAuthorization = OAuthProviderConfigSchema.extend({
306
- redirectURI: (0, import_zod.string)(),
307
- state: (0, import_zod.string)(),
308
- codeChallenge: (0, import_zod.string)(),
309
- codeChallengeMethod: (0, import_zod.enum)(["plain", "S256"])
310
- });
311
- var OAuthAuthorizationResponse = (0, import_zod.object)({
312
- state: (0, import_zod.string)({ message: "Missing state parameter in the OAuth authorization response." }),
313
- code: (0, import_zod.string)({ message: "Missing code parameter in the OAuth authorization response." })
314
- });
315
- var OAuthAuthorizationErrorResponse = (0, import_zod.object)({
316
- error: (0, import_zod.enum)([
317
- "invalid_request",
318
- "unauthorized_client",
319
- "access_denied",
320
- "unsupported_response_type",
321
- "invalid_scope",
322
- "server_error",
323
- "temporarily_unavailable"
324
- ]),
325
- error_description: (0, import_zod.string)().optional(),
326
- error_uri: (0, import_zod.string)().optional(),
327
- state: (0, import_zod.string)()
328
- });
329
- var OAuthAccessToken = OAuthProviderConfigSchema.extend({
330
- redirectURI: (0, import_zod.string)(),
331
- code: (0, import_zod.string)(),
332
- codeVerifier: (0, import_zod.string)().min(43).max(128)
333
- });
334
- var OAuthAccessTokenResponse = (0, import_zod.object)({
335
- access_token: (0, import_zod.string)(),
336
- token_type: (0, import_zod.string)().optional(),
337
- expires_in: (0, import_zod.number)().optional(),
338
- refresh_token: (0, import_zod.string)().optional(),
339
- scope: (0, import_zod.string)().optional().or((0, import_zod.null)())
340
- });
341
- var OAuthAccessTokenErrorResponse = (0, import_zod.object)({
342
- error: (0, import_zod.enum)([
343
- "invalid_request",
344
- "invalid_client",
345
- "invalid_grant",
346
- "unauthorized_client",
347
- "unsupported_grant_type",
348
- "invalid_scope"
349
- ]),
350
- error_description: (0, import_zod.string)().optional(),
351
- error_uri: (0, import_zod.string)().optional()
352
- });
353
- var OAuthErrorResponse = (0, import_zod.object)({
354
- error: (0, import_zod.string)(),
355
- error_description: (0, import_zod.string)().optional()
356
- });
357
- var OAuthEnvSchema = (0, import_zod.object)({
358
- clientId: import_zod.z.string().min(1, "OAuth Client ID is required in the environment variables."),
359
- clientSecret: import_zod.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
360
- });
361
-
362
- // src/actions/callback/userinfo.ts
363
- var getDefaultUserInfo = (profile) => {
364
- const sub = generateSecure(16);
365
- return {
366
- sub: profile?.id ?? profile?.sub ?? sub,
367
- email: profile?.email,
368
- name: profile?.name ?? profile?.username ?? profile?.nickname,
369
- image: profile?.image ?? profile?.picture
370
- };
371
- };
372
- var getUserInfo = async (oauthConfig, accessToken, logger) => {
373
- const userinfoEndpoint = oauthConfig.userInfo;
374
- try {
375
- logger?.log("OAUTH_USERINFO_REQUEST_INITIATED", {
376
- structuredData: {
377
- endpoint: userinfoEndpoint
378
- }
379
- });
380
- const response = await fetchAsync(userinfoEndpoint, {
381
- method: "GET",
382
- headers: {
383
- Accept: "application/json",
384
- Authorization: `Bearer ${accessToken}`
385
- }
386
- });
387
- if (!response.ok) {
388
- logger?.log("OAUTH_USERINFO_INVALID_RESPONSE");
389
- throw new OAuthProtocolError("INVALID_REQUEST", "Invalid userinfo response format");
390
- }
391
- const json = await response.json();
392
- const { success, data } = OAuthErrorResponse.safeParse(json);
393
- if (success) {
394
- logger?.log("OAUTH_USERINFO_ERROR", {
395
- message: "Error response received from OAuth userinfo endpoint",
396
- structuredData: {
397
- error: data.error,
398
- error_description: data.error_description ?? ""
399
- }
400
- });
401
- throw new OAuthProtocolError("INVALID_REQUEST", "An error was received from the OAuth userinfo endpoint.");
402
- }
403
- logger?.log("OAUTH_USERINFO_SUCCESS");
404
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
405
- } catch (error) {
406
- if (isOAuthProtocolError(error)) {
407
- throw error;
408
- }
409
- logger?.log("OAUTH_USERINFO_REQUEST_FAILED");
410
- if (isNativeError(error)) {
411
- throw new OAuthProtocolError("SERVER_ERROR", "Failed to fetch user information from OAuth provider", "", {
412
- cause: error
413
- });
414
- }
415
- throw new OAuthProtocolError("SERVER_ERROR", "Failed to fetch user information", "", { cause: error });
416
- }
417
- };
418
-
419
- // src/actions/signIn/authorization.ts
420
- var getTrustedOrigins = async (request, trustedOrigins) => {
421
- if (!trustedOrigins) return [];
422
- const raw = typeof trustedOrigins === "function" ? await trustedOrigins(request) : trustedOrigins;
423
- return Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [];
424
- };
425
- var getOriginURL = async (request, context) => {
426
- const headers = request.headers;
427
- let origin = new URL(request.url).origin;
428
- const trustedOrigins = await getTrustedOrigins(request, context?.trustedOrigins);
429
- trustedOrigins.push(origin);
430
- if (context?.trustedProxyHeaders) {
431
- const protocol = headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? headers.get("X-Forwarded-Proto") ?? "http";
432
- const host = headers.get("Host") ?? headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? headers.get("X-Forwarded-Host") ?? null;
433
- origin = `${protocol}://${host}`;
434
- }
435
- if (!isTrustedOrigin(origin, trustedOrigins)) {
436
- context?.logger?.log("UNTRUSTED_ORIGIN", { structuredData: { origin } });
437
- throw new AuthInternalError("UNTRUSTED_ORIGIN", "The constructed origin URL is not trusted.");
438
- }
439
- return origin;
440
- };
441
-
442
- // src/actions/callback/access-token.ts
443
- var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier, logger) => {
444
- const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier });
445
- if (!parsed.success) {
446
- logger?.log("INVALID_OAUTH_CONFIGURATION");
447
- throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", "The OAuth provider configuration is invalid.");
448
- }
449
- const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data;
450
- try {
451
- logger?.log("OAUTH_ACCESS_TOKEN_REQUEST_INITIATED", {
452
- structuredData: {
453
- has_client_id: Boolean(clientId),
454
- redirect_uri: redirectParsed,
455
- grant_type: "authorization_code"
456
- }
457
- });
458
- const response = await fetchAsync(accessToken, {
459
- method: "POST",
460
- headers: {
461
- Accept: "application/json",
462
- "Content-Type": "application/x-www-form-urlencoded"
463
- },
464
- body: new URLSearchParams({
465
- client_id: clientId,
466
- client_secret: clientSecret,
467
- code: codeParsed,
468
- redirect_uri: redirectParsed,
469
- grant_type: "authorization_code",
470
- code_verifier: codeVerifier
471
- }).toString()
472
- });
473
- if (!response.ok) {
474
- logger?.log("INVALID_OAUTH_ACCESS_TOKEN_RESPONSE");
475
- throw new OAuthProtocolError("invalid_request", "Invalid access token response");
476
- }
477
- const json = await response.json();
478
- const token = OAuthAccessTokenResponse.safeParse(json);
479
- if (!token.success) {
480
- const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json);
481
- if (!success) {
482
- logger?.log("INVALID_OAUTH_ACCESS_TOKEN_RESPONSE");
483
- throw new OAuthProtocolError("invalid_request", "Invalid access token response format");
484
- }
485
- logger?.log("OAUTH_ACCESS_TOKEN_ERROR", {
486
- structuredData: {
487
- error: data.error,
488
- error_description: data.error_description ?? ""
489
- }
490
- });
491
- throw new OAuthProtocolError("INVALID_ACCESS_TOKEN", "Failed to retrieve access token");
492
- }
493
- logger?.log("OAUTH_ACCESS_TOKEN_SUCCESS");
494
- return token.data;
495
- } catch (error) {
496
- logger?.log("OAUTH_ACCESS_TOKEN_REQUEST_FAILED");
497
- if (error instanceof Error) {
498
- throw new OAuthProtocolError("server_error", "Failed to communicate with OAuth provider", "", { cause: error });
499
- }
500
- throw error;
501
- }
502
- };
503
-
504
- // src/cookie.ts
505
- var import_cookie = require("@aura-stack/router/cookie");
506
- var defaultCookieOptions = {
507
- httpOnly: true,
508
- sameSite: "lax",
509
- path: "/",
510
- maxAge: 60 * 60 * 24 * 15
511
- };
512
- var oauthCookieOptions = {
513
- httpOnly: true,
514
- maxAge: 5 * 60,
515
- sameSite: "lax",
516
- expires: new Date(Date.now() + 5 * 60 * 1e3)
517
- };
518
- var expiredCookieAttributes = {
519
- ...defaultCookieOptions,
520
- expires: /* @__PURE__ */ new Date(0),
521
- maxAge: 0,
522
- secure: true
523
- };
524
- var getCookie = (request, cookieName) => {
525
- const cookies = request.headers.get("Cookie");
526
- if (!cookies) {
527
- throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
528
- }
529
- const value = (0, import_cookie.parse)(cookies)[cookieName];
530
- if (!value) {
531
- throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
532
- }
533
- return value;
534
- };
535
- var createSessionCookie = async (jose, session) => {
536
- try {
537
- const encoded = await jose.encodeJWT(session);
538
- return encoded;
539
- } catch (error) {
540
- throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
541
- }
542
- };
543
-
544
- // src/actions/callback/callback.ts
545
- var callbackConfig = (oauth) => {
546
- return (0, import_router2.createEndpointConfig)("/callback/:oauth", {
547
- schemas: {
548
- params: import_zod2.z.object({
549
- oauth: import_zod2.z.enum(
550
- Object.keys(oauth),
551
- "The OAuth provider is not supported or invalid."
552
- )
553
- }),
554
- searchParams: import_zod2.z.object({
555
- code: import_zod2.z.string("Missing code parameter in the OAuth authorization response."),
556
- state: import_zod2.z.string("Missing state parameter in the OAuth authorization response.")
557
- })
558
- },
559
- middlewares: [
560
- (ctx) => {
561
- const {
562
- searchParams,
563
- context: { logger }
564
- } = ctx;
565
- const response = OAuthAuthorizationErrorResponse.safeParse(searchParams);
566
- if (response.success) {
567
- const { error, error_description } = response.data;
568
- const criticalAuthErrors = ["access_denied", "server_error"];
569
- const severity = criticalAuthErrors.includes(error.toLowerCase()) ? "critical" : "warning";
570
- logger?.log("OAUTH_AUTHORIZATION_ERROR", {
571
- severity,
572
- structuredData: {
573
- error,
574
- error_description: error_description ?? ""
575
- }
576
- });
577
- throw new OAuthProtocolError(error, error_description || "OAuth Authorization Error");
578
- }
579
- return ctx;
580
- }
581
- ]
582
- });
583
- };
584
- var callbackAction = (oauth) => {
585
- return (0, import_router2.createEndpoint)(
586
- "GET",
587
- "/callback/:oauth",
588
- async (ctx) => {
589
- const {
590
- request,
591
- params: { oauth: oauth2 },
592
- searchParams: { code, state },
593
- context
594
- } = ctx;
595
- const { oauth: providers, cookies, jose, logger, trustedOrigins } = context;
596
- const oauthConfig = providers[oauth2];
597
- const cookieState = getCookie(request, cookies.state.name);
598
- const codeVerifier = getCookie(request, cookies.codeVerifier.name);
599
- const cookieRedirectTo = getCookie(request, cookies.redirectTo.name);
600
- const cookieRedirectURI = getCookie(request, cookies.redirectURI.name);
601
- if (!safeEquals(cookieState, state)) {
602
- logger?.log("MISMATCHING_STATE", {
603
- structuredData: {
604
- oauth_provider: oauth2
605
- }
606
- });
607
- throw new AuthSecurityError(
608
- "MISMATCHING_STATE",
609
- "The provided state passed in the OAuth response does not match the stored state."
610
- );
611
- }
612
- const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier, logger);
613
- const origins = await getTrustedOrigins(request, trustedOrigins);
614
- const requestOrigin = await getOriginURL(request, context);
615
- if (!isRelativeURL(cookieRedirectTo)) {
616
- const isValid = origins.length > 0 ? isTrustedOrigin(cookieRedirectTo, origins) : isSameOrigin(cookieRedirectTo, requestOrigin);
617
- if (!isValid) {
618
- logger?.log("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", {
619
- structuredData: {
620
- redirect_path: cookieRedirectTo,
621
- provider: oauth2,
622
- has_trusted_origins: origins.length > 0,
623
- request_origin: requestOrigin
624
- }
625
- });
626
- throw new AuthSecurityError(
627
- "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
628
- "Invalid redirect path. Potential open redirect attack detected."
629
- );
630
- }
631
- }
632
- const userInfo = await getUserInfo(oauthConfig, accessToken.access_token, logger);
633
- const sessionCookie = await createSessionCookie(jose, userInfo);
634
- const csrfToken = await createCSRF(jose);
635
- logger?.log("OAUTH_CALLBACK_SUCCESS", {
636
- structuredData: {
637
- provider: oauth2
638
- }
639
- });
640
- const headers = new import_router2.HeadersBuilder(cacheControl).setHeader("Location", cookieRedirectTo).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();
641
- return Response.json({ oauth: oauth2 }, { status: 302, headers });
642
- },
643
- callbackConfig(oauth)
644
- );
645
- };
646
- // Annotate the CommonJS export names for ESM import in node:
647
- 0 && (module.exports = {
648
- callbackAction
649
- });
@@ -1,13 +0,0 @@
1
- import * as _aura_stack_router from '@aura-stack/router';
2
- import { k as OAuthProviderRecord } from '../../index-CSyIJmCM.js';
3
- import 'zod';
4
- import '../../schemas.js';
5
- import '../../jose.js';
6
- import '@aura-stack/jose';
7
- import '@aura-stack/jose/jose';
8
- import '@aura-stack/router/cookie';
9
- import '../../@types/utility.js';
10
-
11
- declare const callbackAction: (oauth: OAuthProviderRecord) => _aura_stack_router.RouteEndpoint<"GET", "/callback/:oauth", {}>;
12
-
13
- export { callbackAction };
@@ -1,19 +0,0 @@
1
- import {
2
- callbackAction
3
- } from "../../chunk-6MXFPFR3.js";
4
- import "../../chunk-TZB6MUXN.js";
5
- import "../../chunk-XGLBNXL4.js";
6
- import "../../chunk-XUP6KKNG.js";
7
- import "../../chunk-ZNCZVF6U.js";
8
- import "../../chunk-KJBAQZX2.js";
9
- import "../../chunk-NUDITUKX.js";
10
- import "../../chunk-4EKY7655.js";
11
- import "../../chunk-QQVSRXGX.js";
12
- import "../../chunk-5W4BRQYG.js";
13
- import "../../chunk-EBAMFRB7.js";
14
- import "../../chunk-FRJFWTOY.js";
15
- import "../../chunk-4MYWAOLG.js";
16
- import "../../chunk-RRLIF4PQ.js";
17
- export {
18
- callbackAction
19
- };