@aura-stack/auth 0.4.0-rc.5 → 0.5.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 (201) hide show
  1. package/dist/@types/index.d.ts +8 -3
  2. package/dist/@types/router.d.cjs +0 -17
  3. package/dist/@types/router.d.d.ts +7 -2
  4. package/dist/@types/router.d.js +0 -1
  5. package/dist/actions/callback/access-token.cjs +130 -71
  6. package/dist/actions/callback/access-token.d.ts +9 -4
  7. package/dist/actions/callback/access-token.js +3 -4
  8. package/dist/actions/callback/callback.cjs +428 -152
  9. package/dist/actions/callback/callback.d.ts +11 -3
  10. package/dist/actions/callback/callback.js +12 -10
  11. package/dist/actions/callback/userinfo.cjs +159 -65
  12. package/dist/actions/callback/userinfo.d.ts +8 -3
  13. package/dist/actions/callback/userinfo.js +7 -6
  14. package/dist/actions/csrfToken/csrfToken.cjs +70 -19
  15. package/dist/actions/csrfToken/csrfToken.js +8 -7
  16. package/dist/actions/index.cjs +780 -348
  17. package/dist/actions/index.d.ts +6 -2
  18. package/dist/actions/index.js +23 -18
  19. package/dist/actions/session/session.cjs +107 -26
  20. package/dist/actions/session/session.js +7 -5
  21. package/dist/actions/signIn/authorization-url.cjs +288 -0
  22. package/dist/actions/signIn/authorization-url.d.ts +31 -0
  23. package/dist/actions/signIn/authorization-url.js +16 -0
  24. package/dist/actions/signIn/authorization.cjs +209 -211
  25. package/dist/actions/signIn/authorization.d.ts +32 -21
  26. package/dist/actions/signIn/authorization.js +12 -9
  27. package/dist/actions/signIn/signIn.cjs +470 -235
  28. package/dist/actions/signIn/signIn.d.ts +12 -3
  29. package/dist/actions/signIn/signIn.js +11 -8
  30. package/dist/actions/signOut/signOut.cjs +376 -228
  31. package/dist/actions/signOut/signOut.d.ts +1 -1
  32. package/dist/actions/signOut/signOut.js +10 -9
  33. package/dist/api/createApi.cjs +750 -0
  34. package/dist/api/createApi.d.ts +12 -0
  35. package/dist/api/createApi.js +19 -0
  36. package/dist/api/getSession.cjs +141 -0
  37. package/dist/api/getSession.d.ts +16 -0
  38. package/dist/api/getSession.js +10 -0
  39. package/dist/api/signIn.cjs +549 -0
  40. package/dist/api/signIn.d.ts +26 -0
  41. package/dist/api/signIn.js +15 -0
  42. package/dist/api/signOut.cjs +279 -0
  43. package/dist/api/signOut.d.ts +16 -0
  44. package/dist/api/signOut.js +13 -0
  45. package/dist/assert.cjs +150 -5
  46. package/dist/assert.d.ts +26 -3
  47. package/dist/assert.js +17 -3
  48. package/dist/{chunk-YRCB5FLE.js → chunk-2A5B7GWR.js} +52 -6
  49. package/dist/chunk-2GQLSIJ2.js +40 -0
  50. package/dist/chunk-2IR674WX.js +44 -0
  51. package/dist/chunk-3J5TUH2I.js +50 -0
  52. package/dist/chunk-4RWSYUKX.js +98 -0
  53. package/dist/chunk-4YHJ4IEQ.js +25 -0
  54. package/dist/chunk-54CZPKR4.js +25 -0
  55. package/dist/chunk-5LZ7TOM3.js +25 -0
  56. package/dist/chunk-7BE46WWS.js +88 -0
  57. package/dist/chunk-7YYXFKLR.js +35 -0
  58. package/dist/chunk-C3A37LQC.js +33 -0
  59. package/dist/chunk-CITNGXDA.js +31 -0
  60. package/dist/chunk-CWX724AG.js +78 -0
  61. package/dist/chunk-D2CSIUKP.js +74 -0
  62. package/dist/chunk-E6G5YCI6.js +25 -0
  63. package/dist/chunk-EBAMFRB7.js +34 -0
  64. package/dist/chunk-EEE7UM5T.js +25 -0
  65. package/dist/{chunk-HT4YLL7N.js → chunk-FPCVZUVG.js} +10 -8
  66. package/dist/chunk-FW4W3REU.js +25 -0
  67. package/dist/chunk-GNNBM2WJ.js +83 -0
  68. package/dist/chunk-IPKO6UQN.js +25 -0
  69. package/dist/chunk-JOCGX3RP.js +59 -0
  70. package/dist/chunk-KBXWTD6E.js +94 -0
  71. package/dist/chunk-KMMAZFSJ.js +25 -0
  72. package/dist/chunk-LATR3NIV.js +117 -0
  73. package/dist/chunk-LAYPUDQF.js +39 -0
  74. package/dist/chunk-LDU7A2JE.js +25 -0
  75. package/dist/chunk-LX3TJ2TJ.js +294 -0
  76. package/dist/chunk-NHZBQNRR.js +143 -0
  77. package/dist/chunk-OVHNRULD.js +33 -0
  78. package/dist/chunk-PDP3PHB3.js +127 -0
  79. package/dist/chunk-PHYNROD4.js +47 -0
  80. package/dist/chunk-QQEKY4XP.js +29 -0
  81. package/dist/chunk-U4RK4LKJ.js +348 -0
  82. package/dist/{chunk-RRLIF4PQ.js → chunk-U5663F2U.js} +16 -1
  83. package/dist/chunk-UN7X6SU5.js +53 -0
  84. package/dist/chunk-UZQJJD6A.js +100 -0
  85. package/dist/chunk-V6LLEAR4.js +80 -0
  86. package/dist/chunk-WHNDRO3N.js +50 -0
  87. package/dist/{chunk-W6LG7BFW.js → chunk-XY5R3EHH.js} +30 -23
  88. package/dist/client/client.cjs +135 -0
  89. package/dist/client/client.d.ts +85 -0
  90. package/dist/client/client.js +9 -0
  91. package/dist/client/index.cjs +135 -0
  92. package/dist/client/index.d.ts +14 -0
  93. package/dist/client/index.js +10 -0
  94. package/dist/context.cjs +1237 -0
  95. package/dist/context.d.ts +16 -0
  96. package/dist/context.js +28 -0
  97. package/dist/cookie.cjs +57 -22
  98. package/dist/cookie.d.ts +11 -6
  99. package/dist/cookie.js +3 -2
  100. package/dist/createAuth.cjs +2320 -0
  101. package/dist/createAuth.d.ts +12 -0
  102. package/dist/createAuth.js +48 -0
  103. package/dist/env.cjs +78 -0
  104. package/dist/env.d.ts +10 -0
  105. package/dist/env.js +12 -0
  106. package/dist/errors.cjs +17 -0
  107. package/dist/errors.d.ts +15 -4
  108. package/dist/errors.js +5 -1
  109. package/dist/headers.cjs +28 -2
  110. package/dist/headers.d.ts +25 -1
  111. package/dist/headers.js +9 -3
  112. package/dist/index-_aXtxb_s.d.ts +1377 -0
  113. package/dist/index.cjs +1843 -610
  114. package/dist/index.d.ts +11 -92
  115. package/dist/index.js +53 -85
  116. package/dist/jose.cjs +113 -38
  117. package/dist/jose.d.ts +12 -23
  118. package/dist/jose.js +17 -7
  119. package/dist/logger.cjs +424 -0
  120. package/dist/logger.d.ts +12 -0
  121. package/dist/logger.js +17 -0
  122. package/dist/oauth/atlassian.cjs +57 -0
  123. package/dist/oauth/atlassian.d.ts +12 -0
  124. package/dist/oauth/atlassian.js +6 -0
  125. package/dist/oauth/bitbucket.cjs +19 -15
  126. package/dist/oauth/bitbucket.d.ts +7 -2
  127. package/dist/oauth/bitbucket.js +1 -1
  128. package/dist/oauth/discord.cjs +27 -24
  129. package/dist/oauth/discord.d.ts +7 -2
  130. package/dist/oauth/discord.js +1 -1
  131. package/dist/oauth/dropbox.cjs +53 -0
  132. package/dist/oauth/dropbox.d.ts +12 -0
  133. package/dist/oauth/dropbox.js +6 -0
  134. package/dist/oauth/figma.cjs +19 -16
  135. package/dist/oauth/figma.d.ts +7 -2
  136. package/dist/oauth/figma.js +1 -1
  137. package/dist/oauth/github.cjs +19 -8
  138. package/dist/oauth/github.d.ts +7 -2
  139. package/dist/oauth/github.js +1 -1
  140. package/dist/oauth/gitlab.cjs +19 -16
  141. package/dist/oauth/gitlab.d.ts +7 -2
  142. package/dist/oauth/gitlab.js +1 -1
  143. package/dist/oauth/index.cjs +529 -239
  144. package/dist/oauth/index.d.ts +7 -2
  145. package/dist/oauth/index.js +39 -22
  146. package/dist/oauth/mailchimp.cjs +19 -16
  147. package/dist/oauth/mailchimp.d.ts +7 -2
  148. package/dist/oauth/mailchimp.js +1 -1
  149. package/dist/oauth/notion.cjs +131 -0
  150. package/dist/oauth/notion.d.ts +12 -0
  151. package/dist/oauth/notion.js +9 -0
  152. package/dist/oauth/pinterest.cjs +19 -16
  153. package/dist/oauth/pinterest.d.ts +7 -2
  154. package/dist/oauth/pinterest.js +1 -1
  155. package/dist/oauth/spotify.cjs +19 -16
  156. package/dist/oauth/spotify.d.ts +7 -2
  157. package/dist/oauth/spotify.js +1 -1
  158. package/dist/oauth/strava.cjs +19 -16
  159. package/dist/oauth/strava.d.ts +7 -2
  160. package/dist/oauth/strava.js +1 -1
  161. package/dist/oauth/twitch.cjs +95 -0
  162. package/dist/oauth/twitch.d.ts +12 -0
  163. package/dist/oauth/twitch.js +7 -0
  164. package/dist/oauth/x.cjs +19 -16
  165. package/dist/oauth/x.d.ts +7 -2
  166. package/dist/oauth/x.js +1 -1
  167. package/dist/schemas.cjs +89 -42
  168. package/dist/schemas.d.ts +114 -18
  169. package/dist/schemas.js +5 -3
  170. package/dist/secure.cjs +73 -31
  171. package/dist/secure.d.ts +11 -11
  172. package/dist/secure.js +7 -6
  173. package/dist/utils.cjs +203 -90
  174. package/dist/utils.d.ts +21 -40
  175. package/dist/utils.js +21 -12
  176. package/package.json +9 -6
  177. package/dist/chunk-3EUWD5BB.js +0 -63
  178. package/dist/chunk-42XB3YCW.js +0 -22
  179. package/dist/chunk-6R2YZ4AC.js +0 -22
  180. package/dist/chunk-A3N4PVAT.js +0 -70
  181. package/dist/chunk-B737EUJV.js +0 -22
  182. package/dist/chunk-CXLATHS5.js +0 -143
  183. package/dist/chunk-E3OXBRYF.js +0 -22
  184. package/dist/chunk-EIL2FPSS.js +0 -22
  185. package/dist/chunk-EMKJA2GJ.js +0 -89
  186. package/dist/chunk-FIPU4MLT.js +0 -21
  187. package/dist/chunk-FKRDCWBF.js +0 -22
  188. package/dist/chunk-GA2SMTJO.js +0 -58
  189. package/dist/chunk-HP34YGGJ.js +0 -22
  190. package/dist/chunk-IKHPGFCW.js +0 -14
  191. package/dist/chunk-IUYZQTJV.js +0 -30
  192. package/dist/chunk-IVET23KF.js +0 -58
  193. package/dist/chunk-JVFTCTTE.js +0 -33
  194. package/dist/chunk-KRNOMBXQ.js +0 -22
  195. package/dist/chunk-KSWLO5ZU.js +0 -102
  196. package/dist/chunk-N2APGLXA.js +0 -71
  197. package/dist/chunk-N4SX7TZT.js +0 -96
  198. package/dist/chunk-STHEPPUZ.js +0 -11
  199. package/dist/chunk-TLE4PXY3.js +0 -39
  200. package/dist/index-B8jeIElf.d.ts +0 -679
  201. /package/dist/{chunk-DIVDFNAP.js → chunk-5X7JZMEF.js} +0 -0
@@ -0,0 +1,1237 @@
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/context.ts
21
+ var context_exports = {};
22
+ __export(context_exports, {
23
+ createContext: () => createContext
24
+ });
25
+ module.exports = __toCommonJS(context_exports);
26
+
27
+ // src/env.ts
28
+ var import_meta = {};
29
+ var env = new Proxy({}, {
30
+ get(_, prop) {
31
+ if (typeof prop !== "string") return void 0;
32
+ const hasProperty = (process2) => {
33
+ return process2 && Object.prototype.hasOwnProperty.call(process2, prop);
34
+ };
35
+ try {
36
+ if (typeof process !== "undefined" && hasProperty(process.env)) {
37
+ return process.env[prop];
38
+ }
39
+ if (typeof import_meta !== "undefined" && hasProperty(import_meta.env)) {
40
+ return import_meta.env[prop];
41
+ }
42
+ if (typeof Deno !== "undefined" && Deno.env?.get) {
43
+ return Deno.env.get(prop);
44
+ }
45
+ if (typeof Bun !== "undefined" && hasProperty(Bun.env)) {
46
+ return Bun.env[prop];
47
+ }
48
+ const globalValue = globalThis[prop];
49
+ return typeof globalValue === "string" ? globalValue : void 0;
50
+ } catch {
51
+ return void 0;
52
+ }
53
+ }
54
+ });
55
+ var getEnv = (key) => {
56
+ const keys = [`AURA_AUTH_${key.toUpperCase()}`, `AURA_${key.toUpperCase()}`, `AUTH_${key.toUpperCase()}`, key.toUpperCase()];
57
+ return env[keys.find((k) => env[k]) ?? ""];
58
+ };
59
+ var getEnvBoolean = (key) => {
60
+ const value = getEnv(key);
61
+ if (value === void 0) return false;
62
+ const normalized = value.trim().toLowerCase();
63
+ if (["1", "true", "yes", "on", "debug"].includes(normalized)) return true;
64
+ return false;
65
+ };
66
+ var getEnvArray = (key, defaultValue = []) => {
67
+ const value = getEnv(key);
68
+ if (!value) return defaultValue;
69
+ return value.split(/[,;\n]+/).map((v) => v.trim()).filter(Boolean);
70
+ };
71
+
72
+ // src/jose.ts
73
+ var import_jose = require("@aura-stack/jose");
74
+
75
+ // src/errors.ts
76
+ var AuthInternalError = class extends Error {
77
+ type = "AUTH_INTERNAL_ERROR";
78
+ code;
79
+ constructor(code, message, options2) {
80
+ super(message, options2);
81
+ this.code = code;
82
+ this.name = new.target.name;
83
+ Error.captureStackTrace(this, new.target);
84
+ }
85
+ };
86
+
87
+ // src/jose.ts
88
+ var import_jose2 = require("@aura-stack/jose/jose");
89
+ var import_crypto = require("@aura-stack/jose/crypto");
90
+ var createJoseInstance = (secret) => {
91
+ secret ??= getEnv("SECRET");
92
+ if (!secret) {
93
+ throw new AuthInternalError(
94
+ "JOSE_INITIALIZATION_FAILED",
95
+ "AURA_AUTH_SECRET environment variable is not set and no secret was provided."
96
+ );
97
+ }
98
+ const salt = getEnv("SALT");
99
+ if (!salt) {
100
+ throw new AuthInternalError(
101
+ "JOSE_INITIALIZATION_FAILED",
102
+ "AURA_AUTH_SALT or AUTH_SALT environment variable is not set. A salt value is required for key derivation."
103
+ );
104
+ }
105
+ try {
106
+ (0, import_jose.createSecret)(salt);
107
+ } catch (error) {
108
+ throw new AuthInternalError(
109
+ "INVALID_SALT_SECRET_VALUE",
110
+ "AURA_AUTH_SALT/AUTH_SALT is invalid. It must be at least 32 bytes long and meet entropy requirements.",
111
+ { cause: error }
112
+ );
113
+ }
114
+ const jose = (async () => {
115
+ const derivedSigningKey = await (0, import_jose.createDeriveKey)(secret, salt, "signing");
116
+ const derivedEncryptionKey = await (0, import_jose.createDeriveKey)(secret, salt, "encryption");
117
+ const derivedCsrfTokenKey = await (0, import_jose.createDeriveKey)(secret, salt, "csrfToken");
118
+ return {
119
+ jwt: (0, import_jose.createJWT)({ jws: derivedSigningKey, jwe: derivedEncryptionKey }),
120
+ jws: (0, import_jose.createJWS)(derivedCsrfTokenKey),
121
+ jwe: (0, import_jose.createJWE)(derivedEncryptionKey)
122
+ };
123
+ })();
124
+ jose.catch(() => {
125
+ });
126
+ return {
127
+ decodeJWT: async (token, options2) => {
128
+ const { jwt } = await jose;
129
+ return jwt.decodeJWT(token, options2);
130
+ },
131
+ encodeJWT: async (payload) => {
132
+ const { jwt } = await jose;
133
+ return jwt.encodeJWT(payload);
134
+ },
135
+ signJWS: async (...args) => {
136
+ const { jws } = await jose;
137
+ return jws.signJWS(...args);
138
+ },
139
+ verifyJWS: async (...args) => {
140
+ const { jws } = await jose;
141
+ return jws.verifyJWS(...args);
142
+ },
143
+ encryptJWE: async (...args) => {
144
+ const { jwe } = await jose;
145
+ return jwe.encryptJWE(...args);
146
+ },
147
+ decryptJWE: async (...args) => {
148
+ const { jwe } = await jose;
149
+ return jwe.decryptJWE(...args);
150
+ }
151
+ };
152
+ };
153
+
154
+ // src/utils.ts
155
+ var import_router = require("@aura-stack/router");
156
+
157
+ // src/assert.ts
158
+ var import_crypto2 = require("@aura-stack/jose/crypto");
159
+
160
+ // src/utils.ts
161
+ var formatZodError = (error) => {
162
+ if (!error.issues || error.issues.length === 0) {
163
+ return {};
164
+ }
165
+ return error.issues.reduce((previous, issue) => {
166
+ const key = issue.path.join(".");
167
+ return {
168
+ ...previous,
169
+ [key]: {
170
+ code: issue.code,
171
+ message: issue.message
172
+ }
173
+ };
174
+ }, {});
175
+ };
176
+ var createStructuredData = (data, sdID = "metadata") => {
177
+ const entries = Object.entries(data);
178
+ if (entries.length === 0) return `[${sdID}]`;
179
+ const values = entries.map(([key, value]) => `${key}="${String(value).replace(/(["\\\]])/g, "\\$1")}"`).join(" ");
180
+ return `[${sdID} ${values}]`;
181
+ };
182
+ var createBasicAuthHeader = (username, password) => {
183
+ const getUsername = getEnv(username.toUpperCase()) ?? username;
184
+ const getPassword = getEnv(password.toUpperCase()) ?? password;
185
+ if (!getUsername || !getPassword) {
186
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", "Missing client credentials for OAuth provider configuration.");
187
+ }
188
+ const credentials = `${getUsername}:${getPassword}`;
189
+ return `Basic ${btoa(credentials)}`;
190
+ };
191
+
192
+ // src/logger.ts
193
+ var logMessages = {
194
+ ROUTER_INTERNAL_ERROR: {
195
+ facility: 10,
196
+ severity: "error",
197
+ msgId: "ROUTER_INTERNAL_ERROR",
198
+ message: "Unhandled router error while processing the request"
199
+ },
200
+ INVALID_REQUEST: {
201
+ facility: 10,
202
+ severity: "warning",
203
+ msgId: "INVALID_REQUEST",
204
+ message: "Request validation failed against the expected schema"
205
+ },
206
+ SERVER_ERROR: {
207
+ facility: 10,
208
+ severity: "error",
209
+ msgId: "SERVER_ERROR",
210
+ message: "Unexpected internal server error during authentication"
211
+ },
212
+ OAUTH_PROTOCOL_ERROR: {
213
+ facility: 10,
214
+ severity: "warning",
215
+ msgId: "OAUTH_PROTOCOL_ERROR",
216
+ message: "OAuth provider returned an invalid or unexpected protocol response"
217
+ },
218
+ OAUTH_AUTHORIZATION_ERROR: {
219
+ facility: 10,
220
+ severity: "error",
221
+ msgId: "OAUTH_AUTHORIZATION_ERROR",
222
+ message: "OAuth authorization request was rejected or failed"
223
+ },
224
+ INVALID_OAUTH_CONFIGURATION: {
225
+ facility: 10,
226
+ severity: "error",
227
+ msgId: "INVALID_OAUTH_CONFIGURATION",
228
+ message: "The OAuth provider configuration is invalid or incomplete"
229
+ },
230
+ OAUTH_ACCESS_TOKEN_REQUEST_INITIATED: {
231
+ facility: 10,
232
+ severity: "debug",
233
+ msgId: "OAUTH_ACCESS_TOKEN_REQUEST_INITIATED",
234
+ message: "Starting OAuth access token request to the provider"
235
+ },
236
+ INVALID_OAUTH_ACCESS_TOKEN_RESPONSE: {
237
+ facility: 10,
238
+ severity: "error",
239
+ msgId: "INVALID_OAUTH_ACCESS_TOKEN_RESPONSE",
240
+ message: "OAuth access token endpoint returned an invalid or malformed response"
241
+ },
242
+ OAUTH_ACCESS_TOKEN_ERROR: {
243
+ facility: 10,
244
+ severity: "error",
245
+ msgId: "OAUTH_ACCESS_TOKEN_ERROR",
246
+ message: "OAuth access token endpoint returned an error response"
247
+ },
248
+ OAUTH_ACCESS_TOKEN_SUCCESS: {
249
+ facility: 10,
250
+ severity: "info",
251
+ msgId: "OAUTH_ACCESS_TOKEN_SUCCESS",
252
+ message: "Successfully retrieved OAuth access token from the provider"
253
+ },
254
+ OAUTH_ACCESS_TOKEN_REQUEST_FAILED: {
255
+ facility: 10,
256
+ severity: "error",
257
+ msgId: "OAUTH_ACCESS_TOKEN_REQUEST_FAILED",
258
+ message: "Network or server error while requesting OAuth access token"
259
+ },
260
+ OAUTH_USERINFO_REQUEST_INITIATED: {
261
+ facility: 10,
262
+ severity: "debug",
263
+ msgId: "OAUTH_USERINFO_REQUEST_INITIATED",
264
+ message: "Starting OAuth userinfo request to the provider"
265
+ },
266
+ OAUTH_USERINFO_INVALID_RESPONSE: {
267
+ facility: 10,
268
+ severity: "error",
269
+ msgId: "OAUTH_USERINFO_INVALID_RESPONSE",
270
+ message: "OAuth userinfo endpoint returned an invalid or malformed response"
271
+ },
272
+ OAUTH_USERINFO_ERROR: {
273
+ facility: 10,
274
+ severity: "error",
275
+ msgId: "OAUTH_USERINFO_ERROR",
276
+ message: "OAuth userinfo endpoint returned an error response"
277
+ },
278
+ OAUTH_USERINFO_SUCCESS: {
279
+ facility: 10,
280
+ severity: "info",
281
+ msgId: "OAUTH_USERINFO_SUCCESS",
282
+ message: "Successfully retrieved user information from the OAuth provider"
283
+ },
284
+ OAUTH_USERINFO_REQUEST_FAILED: {
285
+ facility: 10,
286
+ severity: "error",
287
+ msgId: "OAUTH_USERINFO_REQUEST_FAILED",
288
+ message: "Network or server error while requesting user information from the OAuth provider"
289
+ },
290
+ OAUTH_CALLBACK_SUCCESS: {
291
+ facility: 4,
292
+ severity: "info",
293
+ msgId: "OAUTH_CALLBACK_SUCCESS",
294
+ message: "OAuth callback completed successfully and session was created"
295
+ },
296
+ MISMATCHING_STATE: {
297
+ facility: 4,
298
+ severity: "critical",
299
+ msgId: "MISMATCHING_STATE",
300
+ message: "OAuth response state parameter does not match the stored state value"
301
+ },
302
+ POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED: {
303
+ facility: 4,
304
+ severity: "critical",
305
+ msgId: "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
306
+ message: "Blocked redirect to untrusted or external URL (potential open redirect attack)"
307
+ },
308
+ OPEN_REDIRECT_ATTACK: {
309
+ facility: 4,
310
+ severity: "warning",
311
+ msgId: "OPEN_REDIRECT_ATTACK",
312
+ message: "Detected redirect target that does not match the trusted origin"
313
+ },
314
+ SESSION_TOKEN_MISSING: {
315
+ facility: 4,
316
+ severity: "warning",
317
+ msgId: "SESSION_TOKEN_MISSING",
318
+ message: "Session cookie is missing from the request"
319
+ },
320
+ CSRF_TOKEN_MISSING: {
321
+ facility: 4,
322
+ severity: "warning",
323
+ msgId: "CSRF_TOKEN_MISSING",
324
+ message: "CSRF token cookie is missing from the request"
325
+ },
326
+ CSRF_HEADER_MISSING: {
327
+ facility: 4,
328
+ severity: "warning",
329
+ msgId: "CSRF_HEADER_MISSING",
330
+ message: "CSRF header is missing from the request"
331
+ },
332
+ CSRF_TOKEN_INVALID: {
333
+ facility: 4,
334
+ severity: "error",
335
+ msgId: "CSRF_TOKEN_INVALID",
336
+ message: "CSRF token verification failed or token is invalid"
337
+ },
338
+ SIGN_IN_INITIATED: {
339
+ facility: 4,
340
+ severity: "info",
341
+ msgId: "SIGN_IN_INITIATED",
342
+ message: "Starting OAuth sign-in flow for the selected provider"
343
+ },
344
+ SIGN_OUT_ATTEMPT: {
345
+ facility: 4,
346
+ severity: "debug",
347
+ msgId: "SIGN_OUT_ATTEMPT",
348
+ message: "Received sign-out request from client"
349
+ },
350
+ SIGN_OUT_CSRF_VERIFIED: {
351
+ facility: 4,
352
+ severity: "info",
353
+ msgId: "SIGN_OUT_CSRF_VERIFIED",
354
+ message: "CSRF token was successfully verified during sign-out"
355
+ },
356
+ SIGN_OUT_SUCCESS: {
357
+ facility: 4,
358
+ severity: "info",
359
+ msgId: "SIGN_OUT_SUCCESS",
360
+ message: "User session was cleared and sign-out completed successfully"
361
+ },
362
+ SIGN_OUT_REDIRECT: {
363
+ facility: 4,
364
+ severity: "debug",
365
+ msgId: "SIGN_OUT_REDIRECT",
366
+ message: "Redirecting client after successful sign-out"
367
+ },
368
+ AUTH_SESSION_VALID: {
369
+ facility: 4,
370
+ severity: "info",
371
+ msgId: "AUTH_SESSION_VALID",
372
+ message: "Session token is valid and user session was returned"
373
+ },
374
+ AUTH_SESSION_INVALID: {
375
+ facility: 4,
376
+ severity: "notice",
377
+ msgId: "AUTH_SESSION_INVALID",
378
+ message: "Session token is missing, expired, or invalid"
379
+ },
380
+ INVALID_JWT_TOKEN: {
381
+ facility: 4,
382
+ severity: "warning",
383
+ msgId: "INVALID_JWT_TOKEN",
384
+ message: "JWT session token failed validation during sign-out"
385
+ },
386
+ CSRF_TOKEN_REQUESTED: {
387
+ facility: 4,
388
+ severity: "debug",
389
+ msgId: "CSRF_TOKEN_REQUESTED",
390
+ message: "Client requested a CSRF token"
391
+ },
392
+ CSRF_TOKEN_ISSUED: {
393
+ facility: 4,
394
+ severity: "debug",
395
+ msgId: "CSRF_TOKEN_ISSUED",
396
+ message: "Issued a new CSRF token to the client"
397
+ },
398
+ INVALID_URL: {
399
+ facility: 10,
400
+ severity: "error",
401
+ msgId: "INVALID_URL",
402
+ message: "Derived origin URL is invalid or malformed"
403
+ },
404
+ COOKIE_HTTPONLY_DISABLED: {
405
+ facility: 10,
406
+ severity: "critical",
407
+ msgId: "COOKIE_HTTPONLY_DISABLED",
408
+ message: "Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS exposure."
409
+ },
410
+ COOKIE_WILDCARD_DOMAIN: {
411
+ facility: 10,
412
+ severity: "critical",
413
+ msgId: "COOKIE_WILDCARD_DOMAIN",
414
+ message: "Cookie 'Domain' is set to a wildcard, which is insecure and should be avoided."
415
+ },
416
+ COOKIE_SECURE_DISABLED: {
417
+ facility: 10,
418
+ severity: "warning",
419
+ msgId: "COOKIE_SECURE_DISABLED",
420
+ message: "Cookie is configured with 'Secure' but the request is not HTTPS. The 'Secure' attribute will be ignored by the browser."
421
+ },
422
+ COOKIE_SAMESITE_NONE_WITHOUT_SECURE: {
423
+ facility: 10,
424
+ severity: "warning",
425
+ msgId: "COOKIE_SAMESITE_NONE_WITHOUT_SECURE",
426
+ message: "Cookie uses SameSite=None without Secure. Falling back to SameSite=Lax for safer defaults."
427
+ },
428
+ COOKIE_INSECURE_IN_PRODUCTION: {
429
+ facility: 10,
430
+ severity: "critical",
431
+ msgId: "COOKIE_INSECURE_IN_PRODUCTION",
432
+ message: "Cookies are being served over an insecure connection in production, which is a serious security risk."
433
+ },
434
+ COOKIE_HOST_STRATEGY_INSECURE: {
435
+ facility: 10,
436
+ severity: "critical",
437
+ msgId: "COOKIE_HOST_STRATEGY_INSECURE",
438
+ message: "__Host- cookies require a secure HTTPS context. Falling back to standard cookie settings."
439
+ },
440
+ UNTRUSTED_ORIGIN: {
441
+ facility: 10,
442
+ severity: "error",
443
+ msgId: "UNTRUSTED_ORIGIN",
444
+ message: "The constructed origin URL is not trusted."
445
+ }
446
+ };
447
+ var createLogEntry = (key, overrides) => {
448
+ const message = logMessages[key];
449
+ return {
450
+ ...message,
451
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
452
+ hostname: "aura-auth",
453
+ procId: typeof process !== "undefined" && process.pid ? process.pid.toString() : "-",
454
+ ...overrides
455
+ };
456
+ };
457
+ var logLevelToSeverity = {
458
+ debug: ["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"],
459
+ info: ["info", "notice", "warning", "error", "critical", "alert", "emergency"],
460
+ warn: ["warning", "error", "critical", "alert", "emergency"],
461
+ error: ["error", "critical", "alert", "emergency"]
462
+ };
463
+ var isValidLogLevel = (value) => {
464
+ return value === "debug" || value === "info" || value === "warn" || value === "error";
465
+ };
466
+ var getSeverityLevel = (severity) => {
467
+ const severities = {
468
+ emergency: 0,
469
+ alert: 1,
470
+ critical: 2,
471
+ error: 3,
472
+ warning: 4,
473
+ notice: 5,
474
+ info: 6,
475
+ debug: 7
476
+ };
477
+ return severities[severity] ?? 6;
478
+ };
479
+ var createSyslogMessage = (options2) => {
480
+ const { timestamp, hostname, appName = "aura-auth", procId = "-", msgId, structuredData, message } = options2;
481
+ const pri = (options2.facility ?? 16) * 8 + getSeverityLevel(options2.severity);
482
+ const structuredDataStr = createStructuredData(structuredData ?? {});
483
+ return `<${pri}>1 ${timestamp} ${hostname} ${appName} ${procId} ${msgId} ${structuredDataStr} ${message}`;
484
+ };
485
+ var createLogger = (logger) => {
486
+ if (!logger) return void 0;
487
+ const level = logger.level;
488
+ const allowedSeverities = logLevelToSeverity[level] ?? [];
489
+ return {
490
+ level,
491
+ log(key, overrides) {
492
+ const entry = createLogEntry(key, overrides);
493
+ if (!allowedSeverities.includes(entry.severity)) return entry;
494
+ logger.log({
495
+ timestamp: entry.timestamp,
496
+ appName: entry.appName ?? "aura-auth",
497
+ hostname: entry.hostname ?? "aura-auth",
498
+ ...entry
499
+ });
500
+ return entry;
501
+ }
502
+ };
503
+ };
504
+ var createProxyLogger = (config) => {
505
+ const level = getEnv("LOG_LEVEL");
506
+ const debug = getEnvBoolean("DEBUG");
507
+ if (typeof config?.logger === "object") {
508
+ return createLogger({
509
+ log: config.logger?.log || createSyslogMessage,
510
+ level: isValidLogLevel(config.logger?.level) ? config.logger?.level : isValidLogLevel(level) ? level : "error"
511
+ });
512
+ }
513
+ if (debug || config?.logger === true || level) {
514
+ return createLogger({
515
+ level: isValidLogLevel(level) ? level : "debug",
516
+ log: (options2) => {
517
+ const message = createSyslogMessage(options2);
518
+ console.log(message);
519
+ }
520
+ });
521
+ }
522
+ return void 0;
523
+ };
524
+
525
+ // src/cookie.ts
526
+ var import_cookie = require("@aura-stack/router/cookie");
527
+ var COOKIE_NAME = "aura-auth";
528
+ var defaultCookieOptions = {
529
+ httpOnly: true,
530
+ sameSite: "lax",
531
+ path: "/",
532
+ maxAge: 60 * 60 * 24 * 15
533
+ };
534
+ var defaultStandardCookieConfig = {
535
+ secure: false,
536
+ httpOnly: true
537
+ };
538
+ var defaultSecureCookieConfig = {
539
+ secure: true,
540
+ httpOnly: true
541
+ };
542
+ var defaultHostCookieConfig = {
543
+ secure: true,
544
+ httpOnly: true,
545
+ path: "/",
546
+ domain: void 0
547
+ };
548
+ var oauthCookieOptions = {
549
+ httpOnly: true,
550
+ maxAge: 5 * 60,
551
+ sameSite: "lax",
552
+ expires: new Date(Date.now() + 5 * 60 * 1e3)
553
+ };
554
+ var expiredCookieAttributes = {
555
+ ...defaultCookieOptions,
556
+ expires: /* @__PURE__ */ new Date(0),
557
+ maxAge: 0,
558
+ secure: true
559
+ };
560
+ var defineSecureCookieOptions = (useSecure, attributes, strategy, logger) => {
561
+ if (!attributes.httpOnly) {
562
+ logger?.log("COOKIE_HTTPONLY_DISABLED");
563
+ }
564
+ if (attributes.domain === "*") {
565
+ attributes.domain = void 0;
566
+ logger?.log("COOKIE_WILDCARD_DOMAIN");
567
+ }
568
+ if (!useSecure) {
569
+ if (attributes.secure) {
570
+ logger?.log("COOKIE_SECURE_DISABLED");
571
+ }
572
+ if (attributes.sameSite == "none") {
573
+ attributes.sameSite = "lax";
574
+ logger?.log("COOKIE_SAMESITE_NONE_WITHOUT_SECURE");
575
+ }
576
+ if (env.NODE_ENV === "production") {
577
+ logger?.log("COOKIE_INSECURE_IN_PRODUCTION");
578
+ }
579
+ if (strategy === "host") {
580
+ logger?.log("COOKIE_HOST_STRATEGY_INSECURE");
581
+ }
582
+ return {
583
+ ...defaultCookieOptions,
584
+ ...attributes,
585
+ ...defaultStandardCookieConfig
586
+ };
587
+ }
588
+ return strategy === "host" ? {
589
+ ...defaultCookieOptions,
590
+ ...attributes,
591
+ ...defaultHostCookieConfig
592
+ } : { ...defaultCookieOptions, ...attributes, ...defaultSecureCookieConfig };
593
+ };
594
+ var createCookieStore = (useSecure, prefix, overrides, logger) => {
595
+ prefix ??= COOKIE_NAME;
596
+ const securePrefix = useSecure ? "__Secure-" : "";
597
+ const hostPrefix = useSecure ? "__Host-" : "";
598
+ return {
599
+ sessionToken: {
600
+ name: `${securePrefix}${prefix}.${overrides?.sessionToken?.name ?? "session_token"}`,
601
+ attributes: defineSecureCookieOptions(
602
+ useSecure,
603
+ {
604
+ ...defaultCookieOptions,
605
+ ...overrides?.sessionToken?.attributes
606
+ },
607
+ overrides?.sessionToken?.attributes?.strategy ?? "secure",
608
+ logger
609
+ )
610
+ },
611
+ state: {
612
+ name: `${securePrefix}${prefix}.${overrides?.state?.name ?? "state"}`,
613
+ attributes: defineSecureCookieOptions(
614
+ useSecure,
615
+ {
616
+ ...oauthCookieOptions,
617
+ ...overrides?.state?.attributes
618
+ },
619
+ overrides?.state?.attributes?.strategy ?? "secure",
620
+ logger
621
+ )
622
+ },
623
+ csrfToken: {
624
+ name: `${hostPrefix}${prefix}.${overrides?.csrfToken?.name ?? "csrf_token"}`,
625
+ attributes: defineSecureCookieOptions(
626
+ useSecure,
627
+ {
628
+ ...overrides?.csrfToken?.attributes,
629
+ ...defaultHostCookieConfig,
630
+ sameSite: "strict"
631
+ },
632
+ overrides?.csrfToken?.attributes?.strategy ?? "host",
633
+ logger
634
+ )
635
+ },
636
+ redirectTo: {
637
+ name: `${securePrefix}${prefix}.${overrides?.redirectTo?.name ?? "redirect_to"}`,
638
+ attributes: defineSecureCookieOptions(
639
+ useSecure,
640
+ {
641
+ ...oauthCookieOptions,
642
+ ...overrides?.redirectTo?.attributes
643
+ },
644
+ overrides?.redirectTo?.attributes?.strategy ?? "secure",
645
+ logger
646
+ )
647
+ },
648
+ redirectURI: {
649
+ name: `${securePrefix}${prefix}.${overrides?.redirectURI?.name ?? "redirect_uri"}`,
650
+ attributes: defineSecureCookieOptions(
651
+ useSecure,
652
+ {
653
+ ...oauthCookieOptions,
654
+ ...overrides?.redirectURI?.attributes
655
+ },
656
+ overrides?.redirectURI?.attributes?.strategy ?? "secure",
657
+ logger
658
+ )
659
+ },
660
+ codeVerifier: {
661
+ name: `${securePrefix}${prefix}.${overrides?.codeVerifier?.name ?? "code_verifier"}`,
662
+ attributes: defineSecureCookieOptions(
663
+ useSecure,
664
+ {
665
+ ...oauthCookieOptions,
666
+ ...overrides?.codeVerifier?.attributes
667
+ },
668
+ overrides?.codeVerifier?.attributes?.strategy ?? "secure",
669
+ logger
670
+ )
671
+ }
672
+ };
673
+ };
674
+
675
+ // src/oauth/github.ts
676
+ var github = (options2) => {
677
+ return {
678
+ id: "github",
679
+ name: "GitHub",
680
+ authorizeURL: "https://github.com/login/oauth/authorize",
681
+ accessToken: "https://github.com/login/oauth/access_token",
682
+ userInfo: "https://api.github.com/user",
683
+ scope: "read:user user:email",
684
+ responseType: "code",
685
+ profile: (profile) => {
686
+ return {
687
+ sub: profile.id.toString(),
688
+ name: profile.name ?? profile.login,
689
+ email: profile.email ?? void 0,
690
+ image: profile.avatar_url
691
+ };
692
+ },
693
+ ...options2
694
+ };
695
+ };
696
+
697
+ // src/oauth/bitbucket.ts
698
+ var bitbucket = (options2) => {
699
+ return {
700
+ id: "bitbucket",
701
+ name: "Bitbucket",
702
+ authorizeURL: "https://bitbucket.org/site/oauth2/authorize",
703
+ accessToken: "https://bitbucket.org/site/oauth2/access_token",
704
+ userInfo: "https://api.bitbucket.org/2.0/user",
705
+ scope: "account email",
706
+ responseType: "code",
707
+ profile(profile) {
708
+ return {
709
+ sub: profile.uuid ?? profile.account_id,
710
+ name: profile.display_name ?? profile.nickname,
711
+ image: profile.links.avatar?.href,
712
+ email: void 0
713
+ };
714
+ },
715
+ ...options2
716
+ };
717
+ };
718
+
719
+ // src/oauth/figma.ts
720
+ var figma = (options2) => {
721
+ return {
722
+ id: "figma",
723
+ name: "Figma",
724
+ authorizeURL: "https://www.figma.com/oauth",
725
+ accessToken: "https://api.figma.com/v1/oauth/token",
726
+ userInfo: "https://api.figma.com/v1/me",
727
+ scope: "current_user:read",
728
+ responseType: "code",
729
+ profile(profile) {
730
+ return {
731
+ sub: profile.id,
732
+ name: profile.handle,
733
+ email: profile.email,
734
+ image: profile.img_url
735
+ };
736
+ },
737
+ ...options2
738
+ };
739
+ };
740
+
741
+ // src/oauth/discord.ts
742
+ var discord = (options2) => {
743
+ return {
744
+ id: "discord",
745
+ name: "Discord",
746
+ authorizeURL: "https://discord.com/oauth2/authorize",
747
+ accessToken: "https://discord.com/api/oauth2/token",
748
+ userInfo: "https://discord.com/api/users/@me",
749
+ scope: "identify email",
750
+ responseType: "code",
751
+ profile(profile) {
752
+ let image = "";
753
+ if (profile.avatar === null) {
754
+ const index = profile.discriminator === "0" ? (BigInt(profile.id) >> 22n) % 6n : Number(profile.discriminator) % 5;
755
+ image = `https://cdn.discordapp.com/embed/avatars/${index}.png`;
756
+ } else {
757
+ const format = profile.avatar.startsWith("a_") ? "gif" : "png";
758
+ image = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`;
759
+ }
760
+ return {
761
+ sub: profile.id,
762
+ name: profile.global_name ?? profile.username,
763
+ email: profile.email ?? "",
764
+ image
765
+ };
766
+ },
767
+ ...options2
768
+ };
769
+ };
770
+
771
+ // src/oauth/gitlab.ts
772
+ var gitlab = (options2) => {
773
+ return {
774
+ id: "gitlab",
775
+ name: "GitLab",
776
+ authorizeURL: "https://gitlab.com/oauth/authorize",
777
+ accessToken: "https://gitlab.com/oauth/token",
778
+ userInfo: "https://gitlab.com/api/v4/user",
779
+ scope: "read_user",
780
+ responseType: "code",
781
+ profile(profile) {
782
+ return {
783
+ sub: profile.id.toString(),
784
+ name: profile.name ?? profile.username,
785
+ email: profile.email,
786
+ image: profile.avatar_url
787
+ };
788
+ },
789
+ ...options2
790
+ };
791
+ };
792
+
793
+ // src/oauth/spotify.ts
794
+ var spotify = (options2) => {
795
+ return {
796
+ id: "spotify",
797
+ name: "Spotify",
798
+ authorizeURL: "https://accounts.spotify.com/authorize",
799
+ accessToken: "https://accounts.spotify.com/api/token",
800
+ userInfo: "https://api.spotify.com/v1/me",
801
+ scope: "user-read-private user-read-email",
802
+ responseType: "code",
803
+ profile(profile) {
804
+ return {
805
+ sub: profile.id,
806
+ name: profile.display_name,
807
+ email: profile.email,
808
+ image: profile.images[0]?.url ?? void 0
809
+ };
810
+ },
811
+ ...options2
812
+ };
813
+ };
814
+
815
+ // src/oauth/x.ts
816
+ var x = (options2) => {
817
+ return {
818
+ id: "x",
819
+ name: "X",
820
+ authorizeURL: "https://twitter.com/i/oauth2/authorize",
821
+ accessToken: "https://api.twitter.com/2/oauth2/token",
822
+ userInfo: "https://api.twitter.com/2/users/me?user.fields=profile_image_url",
823
+ scope: "tweet.read users.read offline.access",
824
+ responseType: "code",
825
+ profile(profile) {
826
+ return {
827
+ sub: profile.data.id,
828
+ name: profile.data.name,
829
+ image: profile.data.profile_image_url,
830
+ email: void 0
831
+ };
832
+ },
833
+ ...options2
834
+ };
835
+ };
836
+
837
+ // src/oauth/strava.ts
838
+ var strava = (options2) => {
839
+ return {
840
+ id: "strava",
841
+ name: "Strava",
842
+ authorizeURL: "https://www.strava.com/oauth/authorize",
843
+ accessToken: "https://www.strava.com/oauth/token",
844
+ userInfo: "https://www.strava.com/api/v3/athlete",
845
+ scope: "read",
846
+ responseType: "code",
847
+ profile(profile) {
848
+ return {
849
+ sub: profile.id.toString(),
850
+ name: `${profile.firstname} ${profile.lastname}`,
851
+ image: profile.profile,
852
+ email: void 0
853
+ };
854
+ },
855
+ ...options2
856
+ };
857
+ };
858
+
859
+ // src/oauth/mailchimp.ts
860
+ var mailchimp = (options2) => {
861
+ return {
862
+ id: "mailchimp",
863
+ name: "Mailchimp",
864
+ authorizeURL: "https://login.mailchimp.com/oauth2/authorize",
865
+ accessToken: "https://login.mailchimp.com/oauth2/token",
866
+ userInfo: "https://login.mailchimp.com/oauth2/metadata",
867
+ scope: "",
868
+ responseType: "code",
869
+ profile(profile) {
870
+ return {
871
+ sub: profile.user_id,
872
+ name: profile.accountname,
873
+ email: profile.login.email,
874
+ image: profile.login.avatar
875
+ };
876
+ },
877
+ ...options2
878
+ };
879
+ };
880
+
881
+ // src/oauth/pinterest.ts
882
+ var pinterest = (options2) => {
883
+ return {
884
+ id: "pinterest",
885
+ name: "Pinterest",
886
+ authorizeURL: "https://www.pinterest.com/oauth",
887
+ accessToken: "https://api.pinterest.com/v5/oauth/token",
888
+ userInfo: "https://api.pinterest.com/v5/user_account",
889
+ scope: "user_accounts:read",
890
+ responseType: "code",
891
+ profile(profile) {
892
+ return {
893
+ sub: profile.id,
894
+ name: profile.username,
895
+ image: profile.profile_image,
896
+ email: void 0
897
+ };
898
+ },
899
+ ...options2
900
+ };
901
+ };
902
+
903
+ // src/oauth/twitch.ts
904
+ var twitch = (options2) => {
905
+ const clientId = options2?.clientId ?? getEnv("TWITCH_CLIENT_ID");
906
+ return {
907
+ id: "twitch",
908
+ name: "Twitch",
909
+ authorize: {
910
+ url: "https://id.twitch.tv/oauth2/authorize",
911
+ params: { scope: "user:read:email", responseType: "code" }
912
+ },
913
+ accessToken: "https://id.twitch.tv/oauth2/token",
914
+ userInfo: {
915
+ url: "https://api.twitch.tv/helix/users",
916
+ headers: {
917
+ "Client-ID": clientId
918
+ }
919
+ },
920
+ profile(profile) {
921
+ const user = profile.data[0];
922
+ if (!user) {
923
+ throw new Error("No user data found in Twitch profile response");
924
+ }
925
+ return {
926
+ sub: user.id,
927
+ name: user.display_name,
928
+ email: user.email,
929
+ picture: user.profile_image_url
930
+ };
931
+ },
932
+ ...options2
933
+ };
934
+ };
935
+
936
+ // src/oauth/notion.ts
937
+ var notion = (options2) => {
938
+ return {
939
+ id: "notion",
940
+ name: "Notion",
941
+ authorize: {
942
+ url: "https://api.notion.com/v1/oauth/authorize",
943
+ params: {
944
+ owner: "user",
945
+ scope: "user:read",
946
+ responseType: "code"
947
+ }
948
+ },
949
+ accessToken: {
950
+ url: "https://api.notion.com/v1/oauth/token",
951
+ headers: {
952
+ Authorization: createBasicAuthHeader(
953
+ options2?.clientId ?? "NOTION_CLIENT_ID",
954
+ options2?.clientSecret ?? "NOTION_CLIENT_SECRET"
955
+ )
956
+ }
957
+ },
958
+ userInfo: {
959
+ url: "https://api.notion.com/v1/users/me",
960
+ headers: {
961
+ "Notion-Version": "2022-06-28"
962
+ }
963
+ },
964
+ profile(profile) {
965
+ return {
966
+ sub: profile.id,
967
+ name: profile.name,
968
+ image: profile.avatar_url ?? "",
969
+ email: profile?.bot?.owner?.user?.person?.email
970
+ };
971
+ },
972
+ ...options2
973
+ };
974
+ };
975
+
976
+ // src/oauth/dropbox.ts
977
+ var dropbox = (options2) => {
978
+ return {
979
+ id: "dropbox",
980
+ name: "Dropbox",
981
+ authorize: {
982
+ url: "https://www.dropbox.com/oauth2/authorize",
983
+ params: { scope: "account_info.read" }
984
+ },
985
+ accessToken: "https://api.dropboxapi.com/oauth2/token",
986
+ userInfo: {
987
+ method: "POST",
988
+ url: "https://api.dropboxapi.com/2/users/get_current_account"
989
+ },
990
+ profile(profile) {
991
+ return {
992
+ sub: profile.account_id,
993
+ name: profile.name.display_name,
994
+ email: profile.email,
995
+ image: profile.profile_photo_url
996
+ };
997
+ },
998
+ ...options2
999
+ };
1000
+ };
1001
+
1002
+ // src/oauth/atlassian.ts
1003
+ var atlassian = (options2) => {
1004
+ return {
1005
+ id: "atlassian",
1006
+ name: "Atlassian",
1007
+ authorize: {
1008
+ url: "https://auth.atlassian.com/authorize",
1009
+ params: {
1010
+ audience: "api.atlassian.com",
1011
+ scope: "read:me read:account",
1012
+ prompt: "consent"
1013
+ }
1014
+ },
1015
+ authorizeURL: "https://auth.atlassian.com/authorize",
1016
+ accessToken: "https://auth.atlassian.com/oauth/token",
1017
+ userInfo: "https://api.atlassian.com/me",
1018
+ scope: "read:me read:account",
1019
+ responseType: "code",
1020
+ profile(profile) {
1021
+ return {
1022
+ sub: profile.account_id,
1023
+ name: profile.name,
1024
+ email: profile.email,
1025
+ image: profile.picture
1026
+ };
1027
+ },
1028
+ ...options2
1029
+ };
1030
+ };
1031
+
1032
+ // src/schemas.ts
1033
+ var import_v4 = require("zod/v4");
1034
+ var AuthorizeConfigSchema = import_v4.z.union([
1035
+ (0, import_v4.string)().url(),
1036
+ (0, import_v4.object)({
1037
+ url: (0, import_v4.string)().url(),
1038
+ params: (0, import_v4.object)({
1039
+ responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
1040
+ scope: (0, import_v4.string)().optional()
1041
+ })
1042
+ })
1043
+ ]);
1044
+ var AccessTokenConfigSchema = import_v4.z.union([
1045
+ (0, import_v4.string)().url(),
1046
+ (0, import_v4.object)({
1047
+ url: (0, import_v4.string)().url(),
1048
+ headers: import_v4.z.record((0, import_v4.string)(), (0, import_v4.string)()).optional()
1049
+ })
1050
+ ]);
1051
+ var UserInfoConfigSchema = import_v4.z.union([
1052
+ (0, import_v4.string)().url(),
1053
+ (0, import_v4.object)({
1054
+ url: (0, import_v4.string)().url(),
1055
+ headers: import_v4.z.record((0, import_v4.string)(), (0, import_v4.string)()).optional(),
1056
+ method: (0, import_v4.string)().optional()
1057
+ })
1058
+ ]);
1059
+ var OAuthProviderCredentialsSchema = (0, import_v4.object)({
1060
+ id: (0, import_v4.string)(),
1061
+ name: (0, import_v4.string)(),
1062
+ authorize: AuthorizeConfigSchema.optional(),
1063
+ /** @deprecated */
1064
+ authorizeURL: (0, import_v4.string)().url().optional(),
1065
+ accessToken: AccessTokenConfigSchema,
1066
+ /** @deprecated */
1067
+ scope: (0, import_v4.string)().optional(),
1068
+ userInfo: UserInfoConfigSchema,
1069
+ /** @deprecated */
1070
+ responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
1071
+ clientId: (0, import_v4.string)(),
1072
+ clientSecret: (0, import_v4.string)(),
1073
+ profile: import_v4.z.function().optional()
1074
+ });
1075
+ var OAuthProviderConfigSchema = (0, import_v4.object)({
1076
+ authorize: AuthorizeConfigSchema.optional(),
1077
+ /** @deprecated */
1078
+ authorizeURL: (0, import_v4.string)().url().optional(),
1079
+ accessToken: AccessTokenConfigSchema,
1080
+ /** @deprecated */
1081
+ scope: (0, import_v4.string)().optional(),
1082
+ userInfo: UserInfoConfigSchema,
1083
+ /** @deprecated */
1084
+ responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
1085
+ clientId: (0, import_v4.string)(),
1086
+ clientSecret: (0, import_v4.string)()
1087
+ });
1088
+ var OAuthAuthorization = OAuthProviderConfigSchema.extend({
1089
+ redirectURI: (0, import_v4.string)(),
1090
+ state: (0, import_v4.string)(),
1091
+ codeChallenge: (0, import_v4.string)(),
1092
+ codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"])
1093
+ });
1094
+ var OAuthAuthorizationResponse = (0, import_v4.object)({
1095
+ state: (0, import_v4.string)({ message: "Missing state parameter in the OAuth authorization response." }),
1096
+ code: (0, import_v4.string)({ message: "Missing code parameter in the OAuth authorization response." })
1097
+ });
1098
+ var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
1099
+ error: (0, import_v4.enum)([
1100
+ "invalid_request",
1101
+ "unauthorized_client",
1102
+ "access_denied",
1103
+ "unsupported_response_type",
1104
+ "invalid_scope",
1105
+ "server_error",
1106
+ "temporarily_unavailable"
1107
+ ]),
1108
+ error_description: (0, import_v4.string)().optional(),
1109
+ error_uri: (0, import_v4.string)().optional(),
1110
+ state: (0, import_v4.string)()
1111
+ });
1112
+ var OAuthAccessToken = OAuthProviderConfigSchema.extend({
1113
+ redirectURI: (0, import_v4.string)(),
1114
+ code: (0, import_v4.string)(),
1115
+ codeVerifier: (0, import_v4.string)().min(43).max(128)
1116
+ });
1117
+ var OAuthAccessTokenResponse = (0, import_v4.object)({
1118
+ access_token: (0, import_v4.string)(),
1119
+ token_type: (0, import_v4.string)().optional(),
1120
+ expires_in: (0, import_v4.number)().optional(),
1121
+ refresh_token: (0, import_v4.string)().optional(),
1122
+ scope: (0, import_v4.union)([(0, import_v4.string)().optional().or((0, import_v4.null)()), (0, import_v4.array)((0, import_v4.string)()).optional()])
1123
+ });
1124
+ var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
1125
+ error: (0, import_v4.enum)([
1126
+ "invalid_request",
1127
+ "invalid_client",
1128
+ "invalid_grant",
1129
+ "unauthorized_client",
1130
+ "unsupported_grant_type",
1131
+ "invalid_scope"
1132
+ ]),
1133
+ error_description: (0, import_v4.string)().optional(),
1134
+ error_uri: (0, import_v4.string)().optional()
1135
+ });
1136
+ var OAuthErrorResponse = (0, import_v4.object)({
1137
+ error: (0, import_v4.string)(),
1138
+ error_description: (0, import_v4.string)().optional()
1139
+ });
1140
+ var OAuthEnvSchema = (0, import_v4.object)({
1141
+ clientId: import_v4.z.string().min(1, "OAuth Client ID is required in the environment variables."),
1142
+ clientSecret: import_v4.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
1143
+ });
1144
+
1145
+ // src/oauth/index.ts
1146
+ var builtInOAuthProviders = {
1147
+ github,
1148
+ bitbucket,
1149
+ figma,
1150
+ discord,
1151
+ gitlab,
1152
+ spotify,
1153
+ x,
1154
+ strava,
1155
+ mailchimp,
1156
+ pinterest,
1157
+ twitch,
1158
+ notion,
1159
+ dropbox,
1160
+ atlassian
1161
+ };
1162
+ var defineOAuthEnvironment = (oauth) => {
1163
+ const loadEnvs = OAuthEnvSchema.safeParse({
1164
+ clientId: getEnv(`${oauth.toUpperCase()}_CLIENT_ID`),
1165
+ clientSecret: getEnv(`${oauth.toUpperCase()}_CLIENT_SECRET`)
1166
+ });
1167
+ if (!loadEnvs.success) {
1168
+ const msg = JSON.stringify({ [oauth]: formatZodError(loadEnvs.error) }, null, 2);
1169
+ throw new AuthInternalError("INVALID_ENVIRONMENT_CONFIGURATION", msg);
1170
+ }
1171
+ return loadEnvs.data;
1172
+ };
1173
+ var defineOAuthProviderConfig = (config) => {
1174
+ if (typeof config === "string") {
1175
+ const definition = defineOAuthEnvironment(config);
1176
+ const oauthConfig = builtInOAuthProviders[config]();
1177
+ const parsed2 = OAuthProviderCredentialsSchema.safeParse({ ...oauthConfig, ...definition });
1178
+ if (!parsed2.success) {
1179
+ const details = JSON.stringify({ [config]: formatZodError(parsed2.error) }, null, 2);
1180
+ throw new AuthInternalError(
1181
+ "INVALID_OAUTH_PROVIDER_CONFIGURATION",
1182
+ `Invalid configuration for OAuth provider "${config}": ${details}`
1183
+ );
1184
+ }
1185
+ return parsed2.data;
1186
+ }
1187
+ const hasCredentials = config.clientId && config.clientSecret;
1188
+ const envConfig = hasCredentials ? {} : defineOAuthEnvironment(config.id);
1189
+ const parsed = OAuthProviderCredentialsSchema.safeParse({ ...envConfig, ...config });
1190
+ if (!parsed.success) {
1191
+ const details = JSON.stringify({ [config.id]: formatZodError(parsed.error) }, null, 2);
1192
+ throw new AuthInternalError(
1193
+ "INVALID_OAUTH_PROVIDER_CONFIGURATION",
1194
+ `Invalid configuration for OAuth provider "${config.id}": ${details}`
1195
+ );
1196
+ }
1197
+ return parsed.data;
1198
+ };
1199
+ var createBuiltInOAuthProviders = (oauth = []) => {
1200
+ return oauth.reduce((previous, config) => {
1201
+ const oauthConfig = defineOAuthProviderConfig(config);
1202
+ if (oauthConfig.id in previous) {
1203
+ throw new AuthInternalError(
1204
+ "DUPLICATED_OAUTH_PROVIDER_ID",
1205
+ `Duplicate OAuth provider id "${oauthConfig.id}" found. Each provider must have a unique id.`
1206
+ );
1207
+ }
1208
+ return { ...previous, [oauthConfig.id]: oauthConfig };
1209
+ }, {});
1210
+ };
1211
+
1212
+ // src/context.ts
1213
+ var createContext = (config) => {
1214
+ const trustedProxyHeadersEnv = getEnv("TRUSTED_PROXY_HEADERS");
1215
+ const useProxyHeaders = trustedProxyHeadersEnv === void 0 ? config?.trustedProxyHeaders ?? false : getEnvBoolean("TRUSTED_PROXY_HEADERS");
1216
+ const logger = createProxyLogger(config);
1217
+ const cookiePrefix = config?.cookies?.prefix;
1218
+ const cookieOverrides = config?.cookies?.overrides ?? {};
1219
+ const secureCookieStore = createCookieStore(true, cookiePrefix, cookieOverrides, logger);
1220
+ const standardCookieStore = createCookieStore(false, cookiePrefix, cookieOverrides, logger);
1221
+ return {
1222
+ oauth: createBuiltInOAuthProviders(config?.oauth),
1223
+ cookies: standardCookieStore,
1224
+ jose: createJoseInstance(config?.secret),
1225
+ secret: config?.secret,
1226
+ basePath: config?.basePath ?? "/auth",
1227
+ trustedProxyHeaders: useProxyHeaders,
1228
+ trustedOrigins: getEnvArray("TRUSTED_ORIGINS").length > 0 ? getEnvArray("TRUSTED_ORIGINS") : config?.trustedOrigins,
1229
+ logger,
1230
+ cookieConfig: { secure: secureCookieStore, standard: standardCookieStore },
1231
+ baseURL: config?.baseURL
1232
+ };
1233
+ };
1234
+ // Annotate the CommonJS export names for ESM import in node:
1235
+ 0 && (module.exports = {
1236
+ createContext
1237
+ });