@aura-stack/auth 0.5.0 → 0.7.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 (220) hide show
  1. package/README.md +36 -1
  2. package/dist/@types/index.cjs +0 -18
  3. package/dist/@types/index.d.ts +2 -12
  4. package/dist/@types/index.js +0 -1
  5. package/dist/assert-_fBNnaOk.js +3 -0
  6. package/dist/assert-hDwQ_SPO.cjs +3 -0
  7. package/dist/client/index.cjs +1 -135
  8. package/dist/client/index.d.ts +11 -14
  9. package/dist/client/index.js +1 -10
  10. package/dist/crypto-D6_SoGMH.cjs +1 -0
  11. package/dist/crypto-DyrRzBSQ.js +1 -0
  12. package/dist/env-7as-tgzO.cjs +1 -0
  13. package/dist/env-CJtSi1eX.js +1 -0
  14. package/dist/errors-Czt_w1t_.js +1 -0
  15. package/dist/errors-DcK2ELlk.cjs +1 -0
  16. package/dist/identity-b8FCr0Oa.cjs +1 -0
  17. package/dist/index-C9U6ICDT.d.ts +2796 -0
  18. package/dist/index.cjs +1 -2427
  19. package/dist/index.d.ts +2 -14
  20. package/dist/index.js +1 -59
  21. package/dist/logger-DjXkgSn5.js +1 -0
  22. package/dist/logger-G5PinyEc.cjs +1 -0
  23. package/dist/oauth/atlassian.cjs +1 -57
  24. package/dist/oauth/atlassian.d.ts +2 -12
  25. package/dist/oauth/atlassian.js +1 -6
  26. package/dist/oauth/bitbucket.cjs +1 -49
  27. package/dist/oauth/bitbucket.d.ts +2 -12
  28. package/dist/oauth/bitbucket.js +1 -6
  29. package/dist/oauth/click-up.cjs +1 -0
  30. package/dist/oauth/click-up.d.ts +2 -0
  31. package/dist/oauth/click-up.js +1 -0
  32. package/dist/oauth/discord.cjs +1 -57
  33. package/dist/oauth/discord.d.ts +2 -12
  34. package/dist/oauth/discord.js +1 -6
  35. package/dist/oauth/dribbble.cjs +1 -0
  36. package/dist/oauth/dribbble.d.ts +2 -0
  37. package/dist/oauth/dribbble.js +1 -0
  38. package/dist/oauth/dropbox.cjs +1 -53
  39. package/dist/oauth/dropbox.d.ts +2 -12
  40. package/dist/oauth/dropbox.js +1 -6
  41. package/dist/oauth/figma.cjs +1 -49
  42. package/dist/oauth/figma.d.ts +2 -12
  43. package/dist/oauth/figma.js +1 -6
  44. package/dist/oauth/github.cjs +1 -49
  45. package/dist/oauth/github.d.ts +2 -12
  46. package/dist/oauth/github.js +1 -6
  47. package/dist/oauth/gitlab.cjs +1 -49
  48. package/dist/oauth/gitlab.d.ts +2 -12
  49. package/dist/oauth/gitlab.js +1 -6
  50. package/dist/oauth/index.cjs +1 -673
  51. package/dist/oauth/index.d.ts +2 -12
  52. package/dist/oauth/index.js +1 -68
  53. package/dist/oauth/mailchimp.cjs +1 -49
  54. package/dist/oauth/mailchimp.d.ts +2 -12
  55. package/dist/oauth/mailchimp.js +1 -6
  56. package/dist/oauth/notion.cjs +1 -131
  57. package/dist/oauth/notion.d.ts +2 -12
  58. package/dist/oauth/notion.js +1 -9
  59. package/dist/oauth/pinterest.cjs +1 -49
  60. package/dist/oauth/pinterest.d.ts +2 -12
  61. package/dist/oauth/pinterest.js +1 -6
  62. package/dist/oauth/spotify.cjs +1 -49
  63. package/dist/oauth/spotify.d.ts +2 -12
  64. package/dist/oauth/spotify.js +1 -6
  65. package/dist/oauth/strava.cjs +1 -49
  66. package/dist/oauth/strava.d.ts +2 -12
  67. package/dist/oauth/strava.js +1 -6
  68. package/dist/oauth/twitch.cjs +1 -95
  69. package/dist/oauth/twitch.d.ts +2 -12
  70. package/dist/oauth/twitch.js +1 -7
  71. package/dist/oauth/x.cjs +1 -49
  72. package/dist/oauth/x.d.ts +2 -12
  73. package/dist/oauth/x.js +1 -6
  74. package/dist/oauth-D3_mnBOx.js +1 -0
  75. package/dist/oauth-gPiWxjBd.cjs +1 -0
  76. package/dist/shared/crypto.cjs +1 -0
  77. package/dist/shared/crypto.d.ts +71 -0
  78. package/dist/shared/crypto.js +1 -0
  79. package/dist/shared/identity.cjs +1 -0
  80. package/dist/shared/identity.d.ts +2 -0
  81. package/dist/shared/identity.js +1 -0
  82. package/dist/shared/index.cjs +1 -0
  83. package/dist/shared/index.d.ts +5 -0
  84. package/dist/shared/index.js +1 -0
  85. package/package.json +37 -11
  86. package/dist/@types/router.d.cjs +0 -1
  87. package/dist/@types/router.d.d.ts +0 -16
  88. package/dist/@types/router.d.js +0 -0
  89. package/dist/@types/utility.cjs +0 -18
  90. package/dist/@types/utility.d.ts +0 -6
  91. package/dist/@types/utility.js +0 -1
  92. package/dist/actions/callback/access-token.cjs +0 -250
  93. package/dist/actions/callback/access-token.d.ts +0 -33
  94. package/dist/actions/callback/access-token.js +0 -9
  95. package/dist/actions/callback/callback.cjs +0 -715
  96. package/dist/actions/callback/callback.d.ts +0 -42
  97. package/dist/actions/callback/callback.js +0 -18
  98. package/dist/actions/callback/userinfo.cjs +0 -283
  99. package/dist/actions/callback/userinfo.d.ts +0 -25
  100. package/dist/actions/callback/userinfo.js +0 -13
  101. package/dist/actions/csrfToken/csrfToken.cjs +0 -189
  102. package/dist/actions/csrfToken/csrfToken.d.ts +0 -7
  103. package/dist/actions/csrfToken/csrfToken.js +0 -13
  104. package/dist/actions/index.cjs +0 -1161
  105. package/dist/actions/index.d.ts +0 -17
  106. package/dist/actions/index.js +0 -39
  107. package/dist/actions/session/session.cjs +0 -188
  108. package/dist/actions/session/session.d.ts +0 -7
  109. package/dist/actions/session/session.js +0 -12
  110. package/dist/actions/signIn/authorization-url.cjs +0 -288
  111. package/dist/actions/signIn/authorization-url.d.ts +0 -31
  112. package/dist/actions/signIn/authorization-url.js +0 -16
  113. package/dist/actions/signIn/authorization.cjs +0 -281
  114. package/dist/actions/signIn/authorization.d.ts +0 -54
  115. package/dist/actions/signIn/authorization.js +0 -19
  116. package/dist/actions/signIn/signIn.cjs +0 -595
  117. package/dist/actions/signIn/signIn.d.ts +0 -42
  118. package/dist/actions/signIn/signIn.js +0 -16
  119. package/dist/actions/signOut/signOut.cjs +0 -492
  120. package/dist/actions/signOut/signOut.d.ts +0 -16
  121. package/dist/actions/signOut/signOut.js +0 -15
  122. package/dist/api/createApi.cjs +0 -750
  123. package/dist/api/createApi.d.ts +0 -12
  124. package/dist/api/createApi.js +0 -19
  125. package/dist/api/getSession.cjs +0 -141
  126. package/dist/api/getSession.d.ts +0 -16
  127. package/dist/api/getSession.js +0 -10
  128. package/dist/api/signIn.cjs +0 -549
  129. package/dist/api/signIn.d.ts +0 -26
  130. package/dist/api/signIn.js +0 -15
  131. package/dist/api/signOut.cjs +0 -279
  132. package/dist/api/signOut.d.ts +0 -16
  133. package/dist/api/signOut.js +0 -13
  134. package/dist/assert.cjs +0 -194
  135. package/dist/assert.d.ts +0 -37
  136. package/dist/assert.js +0 -26
  137. package/dist/chunk-2A5B7GWR.js +0 -125
  138. package/dist/chunk-2GQLSIJ2.js +0 -40
  139. package/dist/chunk-2IR674WX.js +0 -44
  140. package/dist/chunk-3J5TUH2I.js +0 -50
  141. package/dist/chunk-4RWSYUKX.js +0 -98
  142. package/dist/chunk-4YHJ4IEQ.js +0 -25
  143. package/dist/chunk-54CZPKR4.js +0 -25
  144. package/dist/chunk-5LZ7TOM3.js +0 -25
  145. package/dist/chunk-5X7JZMEF.js +0 -0
  146. package/dist/chunk-7BE46WWS.js +0 -88
  147. package/dist/chunk-7YYXFKLR.js +0 -35
  148. package/dist/chunk-C3A37LQC.js +0 -33
  149. package/dist/chunk-CITNGXDA.js +0 -31
  150. package/dist/chunk-CWX724AG.js +0 -78
  151. package/dist/chunk-D2CSIUKP.js +0 -74
  152. package/dist/chunk-E6G5YCI6.js +0 -25
  153. package/dist/chunk-EBAMFRB7.js +0 -34
  154. package/dist/chunk-EEE7UM5T.js +0 -25
  155. package/dist/chunk-FPCVZUVG.js +0 -37
  156. package/dist/chunk-FW4W3REU.js +0 -25
  157. package/dist/chunk-GNNBM2WJ.js +0 -83
  158. package/dist/chunk-IPKO6UQN.js +0 -25
  159. package/dist/chunk-ITQ7352M.js +0 -0
  160. package/dist/chunk-JOCGX3RP.js +0 -59
  161. package/dist/chunk-KBXWTD6E.js +0 -94
  162. package/dist/chunk-KMMAZFSJ.js +0 -25
  163. package/dist/chunk-LATR3NIV.js +0 -117
  164. package/dist/chunk-LAYPUDQF.js +0 -39
  165. package/dist/chunk-LDU7A2JE.js +0 -25
  166. package/dist/chunk-LX3TJ2TJ.js +0 -294
  167. package/dist/chunk-NHZBQNRR.js +0 -143
  168. package/dist/chunk-OVHNRULD.js +0 -33
  169. package/dist/chunk-PDP3PHB3.js +0 -127
  170. package/dist/chunk-PG7UYFG5.js +0 -0
  171. package/dist/chunk-PHYNROD4.js +0 -47
  172. package/dist/chunk-QQEKY4XP.js +0 -29
  173. package/dist/chunk-U4RK4LKJ.js +0 -348
  174. package/dist/chunk-U5663F2U.js +0 -70
  175. package/dist/chunk-UN7X6SU5.js +0 -53
  176. package/dist/chunk-UZQJJD6A.js +0 -100
  177. package/dist/chunk-V6LLEAR4.js +0 -80
  178. package/dist/chunk-WHNDRO3N.js +0 -50
  179. package/dist/chunk-XY5R3EHH.js +0 -204
  180. package/dist/chunk-ZNCZVF6U.js +0 -14
  181. package/dist/client/client.cjs +0 -135
  182. package/dist/client/client.d.ts +0 -85
  183. package/dist/client/client.js +0 -9
  184. package/dist/context.cjs +0 -1237
  185. package/dist/context.d.ts +0 -16
  186. package/dist/context.js +0 -28
  187. package/dist/cookie.cjs +0 -277
  188. package/dist/cookie.d.ts +0 -89
  189. package/dist/cookie.js +0 -30
  190. package/dist/createAuth.cjs +0 -2320
  191. package/dist/createAuth.d.ts +0 -12
  192. package/dist/createAuth.js +0 -48
  193. package/dist/env.cjs +0 -78
  194. package/dist/env.d.ts +0 -10
  195. package/dist/env.js +0 -12
  196. package/dist/errors.cjs +0 -102
  197. package/dist/errors.d.ts +0 -60
  198. package/dist/errors.js +0 -22
  199. package/dist/headers.cjs +0 -61
  200. package/dist/headers.d.ts +0 -33
  201. package/dist/headers.js +0 -12
  202. package/dist/index-_aXtxb_s.d.ts +0 -1377
  203. package/dist/jose.cjs +0 -166
  204. package/dist/jose.d.ts +0 -12
  205. package/dist/jose.js +0 -20
  206. package/dist/logger.cjs +0 -424
  207. package/dist/logger.d.ts +0 -12
  208. package/dist/logger.js +0 -17
  209. package/dist/request.cjs +0 -38
  210. package/dist/request.d.ts +0 -13
  211. package/dist/request.js +0 -6
  212. package/dist/schemas.cjs +0 -158
  213. package/dist/schemas.d.ts +0 -229
  214. package/dist/schemas.js +0 -24
  215. package/dist/secure.cjs +0 -170
  216. package/dist/secure.d.ts +0 -41
  217. package/dist/secure.js +0 -20
  218. package/dist/utils.cjs +0 -329
  219. package/dist/utils.d.ts +0 -35
  220. package/dist/utils.js +0 -36
@@ -1,715 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/actions/callback/callback.ts
21
- var callback_exports = {};
22
- __export(callback_exports, {
23
- callbackAction: () => callbackAction
24
- });
25
- module.exports = __toCommonJS(callback_exports);
26
- var import_v42 = require("zod/v4");
27
- var import_router2 = require("@aura-stack/router");
28
-
29
- // src/utils.ts
30
- var import_router = require("@aura-stack/router");
31
-
32
- // src/errors.ts
33
- var OAuthProtocolError = class extends Error {
34
- type = "OAUTH_PROTOCOL_ERROR";
35
- error;
36
- errorURI;
37
- constructor(error, description, errorURI, options2) {
38
- super(description, options2);
39
- this.error = error;
40
- this.errorURI = errorURI;
41
- this.name = new.target.name;
42
- Error.captureStackTrace(this, new.target);
43
- }
44
- };
45
- var AuthInternalError = class extends Error {
46
- type = "AUTH_INTERNAL_ERROR";
47
- code;
48
- constructor(code, message, options2) {
49
- super(message, options2);
50
- this.code = code;
51
- this.name = new.target.name;
52
- Error.captureStackTrace(this, new.target);
53
- }
54
- };
55
- var AuthSecurityError = class extends Error {
56
- type = "AUTH_SECURITY_ERROR";
57
- code;
58
- constructor(code, message, options2) {
59
- super(message, options2);
60
- this.code = code;
61
- this.name = new.target.name;
62
- Error.captureStackTrace(this, new.target);
63
- }
64
- };
65
- var isNativeError = (error) => {
66
- return error instanceof Error;
67
- };
68
- var isOAuthProtocolError = (error) => {
69
- return error instanceof OAuthProtocolError;
70
- };
71
-
72
- // src/env.ts
73
- var import_meta = {};
74
- var env = new Proxy({}, {
75
- get(_, prop) {
76
- if (typeof prop !== "string") return void 0;
77
- const hasProperty = (process2) => {
78
- return process2 && Object.prototype.hasOwnProperty.call(process2, prop);
79
- };
80
- try {
81
- if (typeof process !== "undefined" && hasProperty(process.env)) {
82
- return process.env[prop];
83
- }
84
- if (typeof import_meta !== "undefined" && hasProperty(import_meta.env)) {
85
- return import_meta.env[prop];
86
- }
87
- if (typeof Deno !== "undefined" && Deno.env?.get) {
88
- return Deno.env.get(prop);
89
- }
90
- if (typeof Bun !== "undefined" && hasProperty(Bun.env)) {
91
- return Bun.env[prop];
92
- }
93
- const globalValue = globalThis[prop];
94
- return typeof globalValue === "string" ? globalValue : void 0;
95
- } catch {
96
- return void 0;
97
- }
98
- }
99
- });
100
- var getEnv = (key) => {
101
- const keys = [`AURA_AUTH_${key.toUpperCase()}`, `AURA_${key.toUpperCase()}`, `AUTH_${key.toUpperCase()}`, key.toUpperCase()];
102
- return env[keys.find((k) => env[k]) ?? ""];
103
- };
104
-
105
- // src/assert.ts
106
- var import_crypto = require("@aura-stack/jose/crypto");
107
- var unsafeChars = [
108
- "<",
109
- ">",
110
- '"',
111
- "`",
112
- " ",
113
- "\r",
114
- "\n",
115
- " ",
116
- "\\",
117
- "%2F",
118
- "%5C",
119
- "%2f",
120
- "%5c",
121
- "\r\n",
122
- "%0A",
123
- "%0D",
124
- "%0a",
125
- "%0d",
126
- "..",
127
- "//",
128
- "///",
129
- "...",
130
- "%20",
131
- "\0"
132
- ];
133
- var isValidURL = (value) => {
134
- if (!new RegExp(/^https?:\/\/[^/]/).test(value)) {
135
- return false;
136
- }
137
- const match = value.match(/^(https?:\/\/)(.*)$/);
138
- if (!match) return false;
139
- const rest = match[2];
140
- for (const char of unsafeChars) {
141
- if (rest.includes(char)) return false;
142
- }
143
- const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()?#*+,;=:@-]*)*\/?$/;
144
- return regex.test(match[0]);
145
- };
146
- var isRelativeURL = (value) => {
147
- if (value.length > 100) return false;
148
- for (const char of unsafeChars) {
149
- if (value.includes(char)) return false;
150
- }
151
- const regex = /^\/[a-zA-Z0-9\-_\/.?&=#]*\/?$/;
152
- return regex.test(value);
153
- };
154
- var isSameOrigin = (origin, expected) => {
155
- const originURL = new URL(origin);
156
- const expectedURL = new URL(expected);
157
- return equals(originURL.origin, expectedURL.origin);
158
- };
159
- var patternToRegex = (pattern) => {
160
- try {
161
- if (pattern.length > 2048) return null;
162
- pattern = pattern.replace(/\\/g, "");
163
- const match = pattern.match(/^(https?):\/\/([a-zA-Z0-9.*-]{1,253})(?::(\d{1,5}|\*))?(?:\/.*)?$/);
164
- if (!match) return null;
165
- const [, protocol, host, port] = match;
166
- const hasWildcard = host.includes("*");
167
- if (hasWildcard && !host.startsWith("*.")) return null;
168
- if (hasWildcard && host.slice(2).includes("*")) return null;
169
- const domain = hasWildcard ? host.slice(2) : host;
170
- const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
171
- const hostRegex = hasWildcard ? `[^.]+\\.${escapedDomain}` : escapedDomain;
172
- const portRegex = port === "*" ? ":\\d{1,5}" : port ? `:${port}` : "";
173
- return new RegExp(`^${protocol}:\\/\\/${hostRegex}${portRegex}$`);
174
- } catch {
175
- return null;
176
- }
177
- };
178
- var isTrustedOrigin = (url, trustedOrigins) => {
179
- if (!isValidURL(url) || trustedOrigins.length === 0) return false;
180
- try {
181
- const urlOrigin = new URL(url).origin;
182
- for (const pattern of trustedOrigins) {
183
- const regex = patternToRegex(pattern);
184
- if (regex?.test(urlOrigin)) return true;
185
- try {
186
- if (isValidURL(pattern) && equals(new URL(pattern).origin, urlOrigin)) return true;
187
- } catch {
188
- }
189
- }
190
- } catch {
191
- }
192
- return false;
193
- };
194
- var timingSafeEqual = (a, b) => {
195
- const bufferA = import_crypto.encoder.encode(a);
196
- const bufferB = import_crypto.encoder.encode(b);
197
- const len = Math.max(bufferA.length, bufferB.length);
198
- let diff = 0;
199
- for (let i = 0; i < len; i++) {
200
- diff |= (bufferA[i] ?? 0) ^ (bufferB[i] ?? 0);
201
- }
202
- return diff === 0 && bufferA.length === bufferB.length;
203
- };
204
-
205
- // src/utils.ts
206
- var AURA_AUTH_VERSION = "0.4.0";
207
- var equals = (a, b) => {
208
- if (a === null || b === null || a === void 0 || b === void 0) return false;
209
- return a === b;
210
- };
211
-
212
- // src/jose.ts
213
- var import_jose = require("@aura-stack/jose");
214
- var import_jose2 = require("@aura-stack/jose/jose");
215
- var import_crypto2 = require("@aura-stack/jose/crypto");
216
- var jwtVerificationOptions = {
217
- algorithms: ["HS256"],
218
- typ: "JWT"
219
- };
220
-
221
- // src/secure.ts
222
- var generateSecure = (length = 32) => {
223
- return import_jose2.base64url.encode((0, import_crypto2.getRandomBytes)(length));
224
- };
225
- var createCSRF = async (jose, csrfCookie) => {
226
- try {
227
- const token = generateSecure(32);
228
- if (csrfCookie) {
229
- await jose.verifyJWS(csrfCookie, jwtVerificationOptions);
230
- return csrfCookie;
231
- }
232
- return jose.signJWS({ token });
233
- } catch {
234
- const token = generateSecure(32);
235
- return jose.signJWS({ token });
236
- }
237
- };
238
-
239
- // src/headers.ts
240
- var cacheControl = {
241
- "Cache-Control": "no-store",
242
- Pragma: "no-cache",
243
- Expires: "0",
244
- Vary: "Cookie"
245
- };
246
- var contentSecurityPolicy = {
247
- "Content-Security-Policy": [
248
- "default-src 'none'",
249
- "script-src 'self'",
250
- "frame-src 'none'",
251
- "object-src 'none'",
252
- "frame-ancestors 'none'",
253
- "base-uri 'none'"
254
- ].join("; ")
255
- };
256
- var secureHeaders = {
257
- "X-Content-Type-Options": "nosniff",
258
- "X-Frame-Options": "DENY",
259
- "Referrer-Policy": "strict-origin-when-cross-origin"
260
- };
261
- var secureApiHeaders = {
262
- ...cacheControl,
263
- ...contentSecurityPolicy,
264
- ...secureHeaders
265
- };
266
-
267
- // src/request.ts
268
- var fetchAsync = async (url, options2 = {}, timeout = 5e3) => {
269
- const controller = new AbortController();
270
- const timeoutId = setTimeout(() => controller.abort(), timeout);
271
- const response = await fetch(url, {
272
- ...options2,
273
- signal: controller.signal
274
- }).finally(() => clearTimeout(timeoutId));
275
- return response;
276
- };
277
-
278
- // src/schemas.ts
279
- var import_v4 = require("zod/v4");
280
- var AuthorizeConfigSchema = import_v4.z.union([
281
- (0, import_v4.string)().url(),
282
- (0, import_v4.object)({
283
- url: (0, import_v4.string)().url(),
284
- params: (0, import_v4.object)({
285
- responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
286
- scope: (0, import_v4.string)().optional()
287
- })
288
- })
289
- ]);
290
- var AccessTokenConfigSchema = import_v4.z.union([
291
- (0, import_v4.string)().url(),
292
- (0, import_v4.object)({
293
- url: (0, import_v4.string)().url(),
294
- headers: import_v4.z.record((0, import_v4.string)(), (0, import_v4.string)()).optional()
295
- })
296
- ]);
297
- var UserInfoConfigSchema = import_v4.z.union([
298
- (0, import_v4.string)().url(),
299
- (0, import_v4.object)({
300
- url: (0, import_v4.string)().url(),
301
- headers: import_v4.z.record((0, import_v4.string)(), (0, import_v4.string)()).optional(),
302
- method: (0, import_v4.string)().optional()
303
- })
304
- ]);
305
- var OAuthProviderCredentialsSchema = (0, import_v4.object)({
306
- id: (0, import_v4.string)(),
307
- name: (0, import_v4.string)(),
308
- authorize: AuthorizeConfigSchema.optional(),
309
- /** @deprecated */
310
- authorizeURL: (0, import_v4.string)().url().optional(),
311
- accessToken: AccessTokenConfigSchema,
312
- /** @deprecated */
313
- scope: (0, import_v4.string)().optional(),
314
- userInfo: UserInfoConfigSchema,
315
- /** @deprecated */
316
- responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
317
- clientId: (0, import_v4.string)(),
318
- clientSecret: (0, import_v4.string)(),
319
- profile: import_v4.z.function().optional()
320
- });
321
- var OAuthProviderConfigSchema = (0, import_v4.object)({
322
- authorize: AuthorizeConfigSchema.optional(),
323
- /** @deprecated */
324
- authorizeURL: (0, import_v4.string)().url().optional(),
325
- accessToken: AccessTokenConfigSchema,
326
- /** @deprecated */
327
- scope: (0, import_v4.string)().optional(),
328
- userInfo: UserInfoConfigSchema,
329
- /** @deprecated */
330
- responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
331
- clientId: (0, import_v4.string)(),
332
- clientSecret: (0, import_v4.string)()
333
- });
334
- var OAuthAuthorization = OAuthProviderConfigSchema.extend({
335
- redirectURI: (0, import_v4.string)(),
336
- state: (0, import_v4.string)(),
337
- codeChallenge: (0, import_v4.string)(),
338
- codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"])
339
- });
340
- var OAuthAuthorizationResponse = (0, import_v4.object)({
341
- state: (0, import_v4.string)({ message: "Missing state parameter in the OAuth authorization response." }),
342
- code: (0, import_v4.string)({ message: "Missing code parameter in the OAuth authorization response." })
343
- });
344
- var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
345
- error: (0, import_v4.enum)([
346
- "invalid_request",
347
- "unauthorized_client",
348
- "access_denied",
349
- "unsupported_response_type",
350
- "invalid_scope",
351
- "server_error",
352
- "temporarily_unavailable"
353
- ]),
354
- error_description: (0, import_v4.string)().optional(),
355
- error_uri: (0, import_v4.string)().optional(),
356
- state: (0, import_v4.string)()
357
- });
358
- var OAuthAccessToken = OAuthProviderConfigSchema.extend({
359
- redirectURI: (0, import_v4.string)(),
360
- code: (0, import_v4.string)(),
361
- codeVerifier: (0, import_v4.string)().min(43).max(128)
362
- });
363
- var OAuthAccessTokenResponse = (0, import_v4.object)({
364
- access_token: (0, import_v4.string)(),
365
- token_type: (0, import_v4.string)().optional(),
366
- expires_in: (0, import_v4.number)().optional(),
367
- refresh_token: (0, import_v4.string)().optional(),
368
- scope: (0, import_v4.union)([(0, import_v4.string)().optional().or((0, import_v4.null)()), (0, import_v4.array)((0, import_v4.string)()).optional()])
369
- });
370
- var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
371
- error: (0, import_v4.enum)([
372
- "invalid_request",
373
- "invalid_client",
374
- "invalid_grant",
375
- "unauthorized_client",
376
- "unsupported_grant_type",
377
- "invalid_scope"
378
- ]),
379
- error_description: (0, import_v4.string)().optional(),
380
- error_uri: (0, import_v4.string)().optional()
381
- });
382
- var OAuthErrorResponse = (0, import_v4.object)({
383
- error: (0, import_v4.string)(),
384
- error_description: (0, import_v4.string)().optional()
385
- });
386
- var OAuthEnvSchema = (0, import_v4.object)({
387
- clientId: import_v4.z.string().min(1, "OAuth Client ID is required in the environment variables."),
388
- clientSecret: import_v4.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
389
- });
390
-
391
- // src/actions/callback/userinfo.ts
392
- var getDefaultUserInfo = (profile) => {
393
- const sub = generateSecure(16);
394
- return {
395
- sub: profile?.id ?? profile?.sub ?? sub,
396
- email: profile?.email,
397
- name: profile?.name ?? profile?.username ?? profile?.nickname,
398
- image: profile?.image ?? profile?.picture
399
- };
400
- };
401
- var getUserInfo = async (oauthConfig, accessToken, logger) => {
402
- const userInfoConfig = oauthConfig.userInfo;
403
- const userinfoURL = typeof userInfoConfig === "string" ? userInfoConfig : userInfoConfig.url;
404
- const extraHeaders = typeof userInfoConfig === "string" ? void 0 : userInfoConfig.headers;
405
- const method = typeof userInfoConfig === "string" ? "GET" : (userInfoConfig.method ?? "GET").toUpperCase();
406
- try {
407
- logger?.log("OAUTH_USERINFO_REQUEST_INITIATED", {
408
- structuredData: {
409
- endpoint: userinfoURL
410
- }
411
- });
412
- const response = await fetchAsync(userinfoURL, {
413
- method,
414
- headers: {
415
- "User-Agent": `Aura Auth/${AURA_AUTH_VERSION}`,
416
- Accept: "application/json",
417
- Authorization: `Bearer ${accessToken}`,
418
- ...extraHeaders ?? {}
419
- }
420
- });
421
- if (!response.ok) {
422
- logger?.log("OAUTH_USERINFO_INVALID_RESPONSE");
423
- throw new OAuthProtocolError("INVALID_REQUEST", "Invalid userinfo response format");
424
- }
425
- const json = await response.json();
426
- const { success, data } = OAuthErrorResponse.safeParse(json);
427
- if (success) {
428
- logger?.log("OAUTH_USERINFO_ERROR", {
429
- message: "Error response received from OAuth userinfo endpoint",
430
- structuredData: {
431
- error: data.error,
432
- error_description: data.error_description ?? ""
433
- }
434
- });
435
- throw new OAuthProtocolError("INVALID_REQUEST", "An error was received from the OAuth userinfo endpoint.");
436
- }
437
- logger?.log("OAUTH_USERINFO_SUCCESS");
438
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
439
- } catch (error) {
440
- if (isOAuthProtocolError(error)) {
441
- throw error;
442
- }
443
- logger?.log("OAUTH_USERINFO_REQUEST_FAILED");
444
- if (isNativeError(error)) {
445
- throw new OAuthProtocolError("SERVER_ERROR", "Failed to fetch user information from OAuth provider", "", {
446
- cause: error
447
- });
448
- }
449
- throw new OAuthProtocolError("SERVER_ERROR", "Failed to fetch user information", "", { cause: error });
450
- }
451
- };
452
-
453
- // src/actions/signIn/authorization.ts
454
- var getTrustedOrigins = async (request, trustedOrigins) => {
455
- if (!trustedOrigins) return [];
456
- const raw = typeof trustedOrigins === "function" ? await trustedOrigins(request) : trustedOrigins;
457
- return Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [];
458
- };
459
- var getBaseURL = async ({
460
- ctx,
461
- request,
462
- headers: headersInit
463
- }) => {
464
- const origin = getEnv("BASE_URL") || ctx?.baseURL;
465
- if (origin && origin !== "/") return origin;
466
- if (ctx?.trustedProxyHeaders) {
467
- const headers = headersInit && new Headers(headersInit) || request?.headers;
468
- const protocol = headers?.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? headers?.get("X-Forwarded-Proto") ?? "http";
469
- const host = headers?.get("Host") ?? headers?.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? headers?.get("X-Forwarded-Host") ?? null;
470
- if (host) return `${protocol}://${host}`;
471
- throw new AuthInternalError(
472
- "INVALID_OAUTH_CONFIGURATION",
473
- "The URL cannot be constructed. Please set the BASE_URL environment variable or provide trusted proxy host headers."
474
- );
475
- }
476
- try {
477
- return new URL(request?.url ?? "not-found").origin;
478
- } catch (error) {
479
- throw new AuthInternalError(
480
- "INVALID_OAUTH_CONFIGURATION",
481
- "The URL cannot be constructed. Please set the BASE_URL environment variable or enable trustedProxyHeaders.",
482
- { cause: error }
483
- );
484
- }
485
- };
486
- var getOriginURL = async (request, context) => {
487
- const trustedOrigins = await getTrustedOrigins(request, context?.trustedOrigins);
488
- trustedOrigins.push(new URL(request.url).origin);
489
- const origin = await getBaseURL({ request, ctx: context });
490
- if (!isTrustedOrigin(origin, trustedOrigins)) {
491
- context?.logger?.log("UNTRUSTED_ORIGIN", { structuredData: { origin } });
492
- throw new AuthInternalError("UNTRUSTED_ORIGIN", "The constructed origin URL is not trusted.");
493
- }
494
- return origin;
495
- };
496
-
497
- // src/actions/callback/access-token.ts
498
- var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier, logger) => {
499
- const { accessToken, clientId, clientSecret } = oauthConfig;
500
- if (!clientId || !clientSecret || !redirectURI || !code || !codeVerifier || !accessToken) {
501
- logger?.log("INVALID_OAUTH_CONFIGURATION", {
502
- structuredData: {
503
- has_client_id: Boolean(clientId),
504
- has_client_secret: Boolean(clientSecret),
505
- has_access_token: Boolean(accessToken),
506
- has_redirect_uri: Boolean(redirectURI),
507
- has_code: Boolean(code),
508
- has_code_verifier: Boolean(codeVerifier)
509
- }
510
- });
511
- throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", "The OAuth provider configuration is invalid.");
512
- }
513
- const tokenURL = typeof accessToken === "string" ? accessToken : accessToken.url;
514
- const extraHeaders = typeof accessToken === "string" ? void 0 : accessToken.headers;
515
- try {
516
- logger?.log("OAUTH_ACCESS_TOKEN_REQUEST_INITIATED", {
517
- structuredData: {
518
- has_client_id: Boolean(clientId),
519
- redirect_uri: redirectURI,
520
- grant_type: "authorization_code"
521
- }
522
- });
523
- const response = await fetchAsync(tokenURL, {
524
- method: "POST",
525
- headers: {
526
- ...extraHeaders ?? {},
527
- Accept: "application/json",
528
- "Content-Type": "application/x-www-form-urlencoded"
529
- },
530
- body: new URLSearchParams({
531
- client_id: clientId,
532
- client_secret: clientSecret,
533
- code,
534
- redirect_uri: redirectURI,
535
- grant_type: "authorization_code",
536
- code_verifier: codeVerifier
537
- }).toString()
538
- });
539
- if (!response.ok) {
540
- logger?.log("INVALID_OAUTH_ACCESS_TOKEN_RESPONSE");
541
- throw new OAuthProtocolError("invalid_request", "Invalid access token response");
542
- }
543
- const json = await response.json();
544
- const token = OAuthAccessTokenResponse.safeParse(json);
545
- if (!token.success) {
546
- const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json);
547
- if (!success) {
548
- logger?.log("INVALID_OAUTH_ACCESS_TOKEN_RESPONSE");
549
- throw new OAuthProtocolError("invalid_request", "Invalid access token response format");
550
- }
551
- logger?.log("OAUTH_ACCESS_TOKEN_ERROR", {
552
- structuredData: {
553
- error: data.error,
554
- error_description: data.error_description ?? ""
555
- }
556
- });
557
- throw new OAuthProtocolError("INVALID_ACCESS_TOKEN", "Failed to retrieve access token");
558
- }
559
- logger?.log("OAUTH_ACCESS_TOKEN_SUCCESS");
560
- return token.data;
561
- } catch (error) {
562
- logger?.log("OAUTH_ACCESS_TOKEN_REQUEST_FAILED");
563
- if (error instanceof Error) {
564
- throw new OAuthProtocolError("server_error", "Failed to communicate with OAuth provider", "", { cause: error });
565
- }
566
- throw error;
567
- }
568
- };
569
-
570
- // src/cookie.ts
571
- var import_cookie = require("@aura-stack/router/cookie");
572
- var defaultCookieOptions = {
573
- httpOnly: true,
574
- sameSite: "lax",
575
- path: "/",
576
- maxAge: 60 * 60 * 24 * 15
577
- };
578
- var oauthCookieOptions = {
579
- httpOnly: true,
580
- maxAge: 5 * 60,
581
- sameSite: "lax",
582
- expires: new Date(Date.now() + 5 * 60 * 1e3)
583
- };
584
- var expiredCookieAttributes = {
585
- ...defaultCookieOptions,
586
- expires: /* @__PURE__ */ new Date(0),
587
- maxAge: 0,
588
- secure: true
589
- };
590
- var getCookie = (request, cookieName) => {
591
- const cookies = request instanceof Request ? request.headers.get("Cookie") : request.get("Cookie");
592
- if (!cookies) {
593
- throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
594
- }
595
- const value = (0, import_cookie.parse)(cookies)[cookieName];
596
- if (!value) {
597
- throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
598
- }
599
- return value;
600
- };
601
- var createSessionCookie = async (jose, session) => {
602
- try {
603
- const encoded = await jose.encodeJWT(session);
604
- return encoded;
605
- } catch (error) {
606
- throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
607
- }
608
- };
609
-
610
- // src/actions/callback/callback.ts
611
- var callbackConfig = (oauth) => {
612
- return (0, import_router2.createEndpointConfig)("/callback/:oauth", {
613
- schemas: {
614
- params: import_v42.z.object({
615
- oauth: import_v42.z.enum(
616
- Object.keys(oauth),
617
- "The OAuth provider is not supported or invalid."
618
- )
619
- }),
620
- searchParams: import_v42.z.object({
621
- code: import_v42.z.string("Missing code parameter in the OAuth authorization response."),
622
- state: import_v42.z.string("Missing state parameter in the OAuth authorization response.")
623
- })
624
- },
625
- use: [
626
- (ctx) => {
627
- const {
628
- searchParams,
629
- context: { logger }
630
- } = ctx;
631
- const response = OAuthAuthorizationErrorResponse.safeParse(searchParams);
632
- if (response.success) {
633
- const { error, error_description } = response.data;
634
- const criticalAuthErrors = ["access_denied", "server_error"];
635
- const severity = criticalAuthErrors.includes(error.toLowerCase()) ? "critical" : "warning";
636
- logger?.log("OAUTH_AUTHORIZATION_ERROR", {
637
- severity,
638
- structuredData: {
639
- error,
640
- error_description: error_description ?? ""
641
- }
642
- });
643
- throw new OAuthProtocolError(error, error_description || "OAuth Authorization Error");
644
- }
645
- return ctx;
646
- }
647
- ]
648
- });
649
- };
650
- var callbackAction = (oauth) => {
651
- return (0, import_router2.createEndpoint)(
652
- "GET",
653
- "/callback/:oauth",
654
- async (ctx) => {
655
- const {
656
- request,
657
- params: { oauth: oauth2 },
658
- searchParams: { code, state },
659
- context
660
- } = ctx;
661
- const { oauth: providers, cookies, jose, logger, trustedOrigins } = context;
662
- const oauthConfig = providers[oauth2];
663
- const cookieState = getCookie(request, cookies.state.name);
664
- const codeVerifier = getCookie(request, cookies.codeVerifier.name);
665
- const cookieRedirectTo = getCookie(request, cookies.redirectTo.name);
666
- const cookieRedirectURI = getCookie(request, cookies.redirectURI.name);
667
- if (!timingSafeEqual(cookieState, state)) {
668
- logger?.log("MISMATCHING_STATE", {
669
- structuredData: {
670
- oauth_provider: oauth2
671
- }
672
- });
673
- throw new AuthSecurityError(
674
- "MISMATCHING_STATE",
675
- "The provided state passed in the OAuth response does not match the stored state."
676
- );
677
- }
678
- const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier, logger);
679
- const origins = await getTrustedOrigins(request, trustedOrigins);
680
- const requestOrigin = await getOriginURL(request, context);
681
- if (!isRelativeURL(cookieRedirectTo)) {
682
- const isValid = origins.length > 0 ? isTrustedOrigin(cookieRedirectTo, origins) : isSameOrigin(cookieRedirectTo, requestOrigin);
683
- if (!isValid) {
684
- logger?.log("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", {
685
- structuredData: {
686
- redirect_path: cookieRedirectTo,
687
- provider: oauth2,
688
- has_trusted_origins: origins.length > 0,
689
- request_origin: requestOrigin
690
- }
691
- });
692
- throw new AuthSecurityError(
693
- "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
694
- "Invalid redirect path. Potential open redirect attack detected."
695
- );
696
- }
697
- }
698
- const userInfo = await getUserInfo(oauthConfig, accessToken.access_token, logger);
699
- const sessionCookie = await createSessionCookie(jose, userInfo);
700
- const csrfToken = await createCSRF(jose);
701
- logger?.log("OAUTH_CALLBACK_SUCCESS", {
702
- structuredData: {
703
- provider: oauth2
704
- }
705
- });
706
- 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();
707
- return Response.json({ oauth: oauth2 }, { status: 302, headers });
708
- },
709
- callbackConfig(oauth)
710
- );
711
- };
712
- // Annotate the CommonJS export names for ESM import in node:
713
- 0 && (module.exports = {
714
- callbackAction
715
- });