@aura-stack/auth 0.5.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 (215) 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-B3iQSYlK.js +3 -0
  6. package/dist/assert-NJGroSJd.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-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 -2427
  19. package/dist/index.d.cts +2 -0
  20. package/dist/index.d.ts +2 -14
  21. package/dist/index.js +1 -59
  22. package/dist/logger-C59_CDMk.js +1 -0
  23. package/dist/logger-UnUhYL2V.cjs +1 -0
  24. package/dist/oauth/atlassian.cjs +1 -57
  25. package/dist/oauth/atlassian.d.ts +2 -12
  26. package/dist/oauth/atlassian.js +1 -6
  27. package/dist/oauth/bitbucket.cjs +1 -49
  28. package/dist/oauth/bitbucket.d.ts +2 -12
  29. package/dist/oauth/bitbucket.js +1 -6
  30. package/dist/oauth/discord.cjs +1 -57
  31. package/dist/oauth/discord.d.ts +2 -12
  32. package/dist/oauth/discord.js +1 -6
  33. package/dist/oauth/dropbox.cjs +1 -53
  34. package/dist/oauth/dropbox.d.ts +2 -12
  35. package/dist/oauth/dropbox.js +1 -6
  36. package/dist/oauth/figma.cjs +1 -49
  37. package/dist/oauth/figma.d.ts +2 -12
  38. package/dist/oauth/figma.js +1 -6
  39. package/dist/oauth/github.cjs +1 -49
  40. package/dist/oauth/github.d.ts +2 -12
  41. package/dist/oauth/github.js +1 -6
  42. package/dist/oauth/gitlab.cjs +1 -49
  43. package/dist/oauth/gitlab.d.ts +2 -12
  44. package/dist/oauth/gitlab.js +1 -6
  45. package/dist/oauth/index.cjs +1 -673
  46. package/dist/oauth/index.d.ts +2 -12
  47. package/dist/oauth/index.js +1 -68
  48. package/dist/oauth/mailchimp.cjs +1 -49
  49. package/dist/oauth/mailchimp.d.ts +2 -12
  50. package/dist/oauth/mailchimp.js +1 -6
  51. package/dist/oauth/notion.cjs +1 -131
  52. package/dist/oauth/notion.d.ts +2 -12
  53. package/dist/oauth/notion.js +1 -9
  54. package/dist/oauth/pinterest.cjs +1 -49
  55. package/dist/oauth/pinterest.d.ts +2 -12
  56. package/dist/oauth/pinterest.js +1 -6
  57. package/dist/oauth/spotify.cjs +1 -49
  58. package/dist/oauth/spotify.d.ts +2 -12
  59. package/dist/oauth/spotify.js +1 -6
  60. package/dist/oauth/strava.cjs +1 -49
  61. package/dist/oauth/strava.d.ts +2 -12
  62. package/dist/oauth/strava.js +1 -6
  63. package/dist/oauth/twitch.cjs +1 -95
  64. package/dist/oauth/twitch.d.ts +2 -12
  65. package/dist/oauth/twitch.js +1 -7
  66. package/dist/oauth/x.cjs +1 -49
  67. package/dist/oauth/x.d.ts +2 -12
  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 +32 -9
  81. package/dist/@types/router.d.cjs +0 -1
  82. package/dist/@types/router.d.d.ts +0 -16
  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 -250
  88. package/dist/actions/callback/access-token.d.ts +0 -33
  89. package/dist/actions/callback/access-token.js +0 -9
  90. package/dist/actions/callback/callback.cjs +0 -715
  91. package/dist/actions/callback/callback.d.ts +0 -42
  92. package/dist/actions/callback/callback.js +0 -18
  93. package/dist/actions/callback/userinfo.cjs +0 -283
  94. package/dist/actions/callback/userinfo.d.ts +0 -25
  95. package/dist/actions/callback/userinfo.js +0 -13
  96. package/dist/actions/csrfToken/csrfToken.cjs +0 -189
  97. package/dist/actions/csrfToken/csrfToken.d.ts +0 -7
  98. package/dist/actions/csrfToken/csrfToken.js +0 -13
  99. package/dist/actions/index.cjs +0 -1161
  100. package/dist/actions/index.d.ts +0 -17
  101. package/dist/actions/index.js +0 -39
  102. package/dist/actions/session/session.cjs +0 -188
  103. package/dist/actions/session/session.d.ts +0 -7
  104. package/dist/actions/session/session.js +0 -12
  105. package/dist/actions/signIn/authorization-url.cjs +0 -288
  106. package/dist/actions/signIn/authorization-url.d.ts +0 -31
  107. package/dist/actions/signIn/authorization-url.js +0 -16
  108. package/dist/actions/signIn/authorization.cjs +0 -281
  109. package/dist/actions/signIn/authorization.d.ts +0 -54
  110. package/dist/actions/signIn/authorization.js +0 -19
  111. package/dist/actions/signIn/signIn.cjs +0 -595
  112. package/dist/actions/signIn/signIn.d.ts +0 -42
  113. package/dist/actions/signIn/signIn.js +0 -16
  114. package/dist/actions/signOut/signOut.cjs +0 -492
  115. package/dist/actions/signOut/signOut.d.ts +0 -16
  116. package/dist/actions/signOut/signOut.js +0 -15
  117. package/dist/api/createApi.cjs +0 -750
  118. package/dist/api/createApi.d.ts +0 -12
  119. package/dist/api/createApi.js +0 -19
  120. package/dist/api/getSession.cjs +0 -141
  121. package/dist/api/getSession.d.ts +0 -16
  122. package/dist/api/getSession.js +0 -10
  123. package/dist/api/signIn.cjs +0 -549
  124. package/dist/api/signIn.d.ts +0 -26
  125. package/dist/api/signIn.js +0 -15
  126. package/dist/api/signOut.cjs +0 -279
  127. package/dist/api/signOut.d.ts +0 -16
  128. package/dist/api/signOut.js +0 -13
  129. package/dist/assert.cjs +0 -194
  130. package/dist/assert.d.ts +0 -37
  131. package/dist/assert.js +0 -26
  132. package/dist/chunk-2A5B7GWR.js +0 -125
  133. package/dist/chunk-2GQLSIJ2.js +0 -40
  134. package/dist/chunk-2IR674WX.js +0 -44
  135. package/dist/chunk-3J5TUH2I.js +0 -50
  136. package/dist/chunk-4RWSYUKX.js +0 -98
  137. package/dist/chunk-4YHJ4IEQ.js +0 -25
  138. package/dist/chunk-54CZPKR4.js +0 -25
  139. package/dist/chunk-5LZ7TOM3.js +0 -25
  140. package/dist/chunk-5X7JZMEF.js +0 -0
  141. package/dist/chunk-7BE46WWS.js +0 -88
  142. package/dist/chunk-7YYXFKLR.js +0 -35
  143. package/dist/chunk-C3A37LQC.js +0 -33
  144. package/dist/chunk-CITNGXDA.js +0 -31
  145. package/dist/chunk-CWX724AG.js +0 -78
  146. package/dist/chunk-D2CSIUKP.js +0 -74
  147. package/dist/chunk-E6G5YCI6.js +0 -25
  148. package/dist/chunk-EBAMFRB7.js +0 -34
  149. package/dist/chunk-EEE7UM5T.js +0 -25
  150. package/dist/chunk-FPCVZUVG.js +0 -37
  151. package/dist/chunk-FW4W3REU.js +0 -25
  152. package/dist/chunk-GNNBM2WJ.js +0 -83
  153. package/dist/chunk-IPKO6UQN.js +0 -25
  154. package/dist/chunk-ITQ7352M.js +0 -0
  155. package/dist/chunk-JOCGX3RP.js +0 -59
  156. package/dist/chunk-KBXWTD6E.js +0 -94
  157. package/dist/chunk-KMMAZFSJ.js +0 -25
  158. package/dist/chunk-LATR3NIV.js +0 -117
  159. package/dist/chunk-LAYPUDQF.js +0 -39
  160. package/dist/chunk-LDU7A2JE.js +0 -25
  161. package/dist/chunk-LX3TJ2TJ.js +0 -294
  162. package/dist/chunk-NHZBQNRR.js +0 -143
  163. package/dist/chunk-OVHNRULD.js +0 -33
  164. package/dist/chunk-PDP3PHB3.js +0 -127
  165. package/dist/chunk-PG7UYFG5.js +0 -0
  166. package/dist/chunk-PHYNROD4.js +0 -47
  167. package/dist/chunk-QQEKY4XP.js +0 -29
  168. package/dist/chunk-U4RK4LKJ.js +0 -348
  169. package/dist/chunk-U5663F2U.js +0 -70
  170. package/dist/chunk-UN7X6SU5.js +0 -53
  171. package/dist/chunk-UZQJJD6A.js +0 -100
  172. package/dist/chunk-V6LLEAR4.js +0 -80
  173. package/dist/chunk-WHNDRO3N.js +0 -50
  174. package/dist/chunk-XY5R3EHH.js +0 -204
  175. package/dist/chunk-ZNCZVF6U.js +0 -14
  176. package/dist/client/client.cjs +0 -135
  177. package/dist/client/client.d.ts +0 -85
  178. package/dist/client/client.js +0 -9
  179. package/dist/context.cjs +0 -1237
  180. package/dist/context.d.ts +0 -16
  181. package/dist/context.js +0 -28
  182. package/dist/cookie.cjs +0 -277
  183. package/dist/cookie.d.ts +0 -89
  184. package/dist/cookie.js +0 -30
  185. package/dist/createAuth.cjs +0 -2320
  186. package/dist/createAuth.d.ts +0 -12
  187. package/dist/createAuth.js +0 -48
  188. package/dist/env.cjs +0 -78
  189. package/dist/env.d.ts +0 -10
  190. package/dist/env.js +0 -12
  191. package/dist/errors.cjs +0 -102
  192. package/dist/errors.d.ts +0 -60
  193. package/dist/errors.js +0 -22
  194. package/dist/headers.cjs +0 -61
  195. package/dist/headers.d.ts +0 -33
  196. package/dist/headers.js +0 -12
  197. package/dist/index-_aXtxb_s.d.ts +0 -1377
  198. package/dist/jose.cjs +0 -166
  199. package/dist/jose.d.ts +0 -12
  200. package/dist/jose.js +0 -20
  201. package/dist/logger.cjs +0 -424
  202. package/dist/logger.d.ts +0 -12
  203. package/dist/logger.js +0 -17
  204. package/dist/request.cjs +0 -38
  205. package/dist/request.d.ts +0 -13
  206. package/dist/request.js +0 -6
  207. package/dist/schemas.cjs +0 -158
  208. package/dist/schemas.d.ts +0 -229
  209. package/dist/schemas.js +0 -24
  210. package/dist/secure.cjs +0 -170
  211. package/dist/secure.d.ts +0 -41
  212. package/dist/secure.js +0 -20
  213. package/dist/utils.cjs +0 -329
  214. package/dist/utils.d.ts +0 -35
  215. package/dist/utils.js +0 -36
@@ -1,1161 +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/index.ts
21
- var actions_exports = {};
22
- __export(actions_exports, {
23
- callbackAction: () => callbackAction,
24
- csrfTokenAction: () => csrfTokenAction,
25
- sessionAction: () => sessionAction,
26
- signInAction: () => signInAction,
27
- signOutAction: () => signOutAction
28
- });
29
- module.exports = __toCommonJS(actions_exports);
30
-
31
- // src/actions/signIn/signIn.ts
32
- var import_v42 = require("zod/v4");
33
-
34
- // src/headers.ts
35
- var cacheControl = {
36
- "Cache-Control": "no-store",
37
- Pragma: "no-cache",
38
- Expires: "0",
39
- Vary: "Cookie"
40
- };
41
- var contentSecurityPolicy = {
42
- "Content-Security-Policy": [
43
- "default-src 'none'",
44
- "script-src 'self'",
45
- "frame-src 'none'",
46
- "object-src 'none'",
47
- "frame-ancestors 'none'",
48
- "base-uri 'none'"
49
- ].join("; ")
50
- };
51
- var secureHeaders = {
52
- "X-Content-Type-Options": "nosniff",
53
- "X-Frame-Options": "DENY",
54
- "Referrer-Policy": "strict-origin-when-cross-origin"
55
- };
56
- var secureApiHeaders = {
57
- ...cacheControl,
58
- ...contentSecurityPolicy,
59
- ...secureHeaders
60
- };
61
-
62
- // src/errors.ts
63
- var OAuthProtocolError = class extends Error {
64
- type = "OAUTH_PROTOCOL_ERROR";
65
- error;
66
- errorURI;
67
- constructor(error, description, errorURI, options2) {
68
- super(description, options2);
69
- this.error = error;
70
- this.errorURI = errorURI;
71
- this.name = new.target.name;
72
- Error.captureStackTrace(this, new.target);
73
- }
74
- };
75
- var AuthInternalError = class extends Error {
76
- type = "AUTH_INTERNAL_ERROR";
77
- code;
78
- constructor(code, message, options2) {
79
- super(message, options2);
80
- this.code = code;
81
- this.name = new.target.name;
82
- Error.captureStackTrace(this, new.target);
83
- }
84
- };
85
- var AuthSecurityError = class extends Error {
86
- type = "AUTH_SECURITY_ERROR";
87
- code;
88
- constructor(code, message, options2) {
89
- super(message, options2);
90
- this.code = code;
91
- this.name = new.target.name;
92
- Error.captureStackTrace(this, new.target);
93
- }
94
- };
95
- var isNativeError = (error) => {
96
- return error instanceof Error;
97
- };
98
- var isOAuthProtocolError = (error) => {
99
- return error instanceof OAuthProtocolError;
100
- };
101
-
102
- // src/api/signIn.ts
103
- var import_router2 = require("@aura-stack/router");
104
-
105
- // src/schemas.ts
106
- var import_v4 = require("zod/v4");
107
- var AuthorizeConfigSchema = import_v4.z.union([
108
- (0, import_v4.string)().url(),
109
- (0, import_v4.object)({
110
- url: (0, import_v4.string)().url(),
111
- params: (0, import_v4.object)({
112
- responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
113
- scope: (0, import_v4.string)().optional()
114
- })
115
- })
116
- ]);
117
- var AccessTokenConfigSchema = import_v4.z.union([
118
- (0, import_v4.string)().url(),
119
- (0, import_v4.object)({
120
- url: (0, import_v4.string)().url(),
121
- headers: import_v4.z.record((0, import_v4.string)(), (0, import_v4.string)()).optional()
122
- })
123
- ]);
124
- var UserInfoConfigSchema = import_v4.z.union([
125
- (0, import_v4.string)().url(),
126
- (0, import_v4.object)({
127
- url: (0, import_v4.string)().url(),
128
- headers: import_v4.z.record((0, import_v4.string)(), (0, import_v4.string)()).optional(),
129
- method: (0, import_v4.string)().optional()
130
- })
131
- ]);
132
- var OAuthProviderCredentialsSchema = (0, import_v4.object)({
133
- id: (0, import_v4.string)(),
134
- name: (0, import_v4.string)(),
135
- authorize: AuthorizeConfigSchema.optional(),
136
- /** @deprecated */
137
- authorizeURL: (0, import_v4.string)().url().optional(),
138
- accessToken: AccessTokenConfigSchema,
139
- /** @deprecated */
140
- scope: (0, import_v4.string)().optional(),
141
- userInfo: UserInfoConfigSchema,
142
- /** @deprecated */
143
- responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
144
- clientId: (0, import_v4.string)(),
145
- clientSecret: (0, import_v4.string)(),
146
- profile: import_v4.z.function().optional()
147
- });
148
- var OAuthProviderConfigSchema = (0, import_v4.object)({
149
- authorize: AuthorizeConfigSchema.optional(),
150
- /** @deprecated */
151
- authorizeURL: (0, import_v4.string)().url().optional(),
152
- accessToken: AccessTokenConfigSchema,
153
- /** @deprecated */
154
- scope: (0, import_v4.string)().optional(),
155
- userInfo: UserInfoConfigSchema,
156
- /** @deprecated */
157
- responseType: (0, import_v4.enum)(["code", "token", "id_token", "refresh_token"]).optional(),
158
- clientId: (0, import_v4.string)(),
159
- clientSecret: (0, import_v4.string)()
160
- });
161
- var OAuthAuthorization = OAuthProviderConfigSchema.extend({
162
- redirectURI: (0, import_v4.string)(),
163
- state: (0, import_v4.string)(),
164
- codeChallenge: (0, import_v4.string)(),
165
- codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"])
166
- });
167
- var OAuthAuthorizationResponse = (0, import_v4.object)({
168
- state: (0, import_v4.string)({ message: "Missing state parameter in the OAuth authorization response." }),
169
- code: (0, import_v4.string)({ message: "Missing code parameter in the OAuth authorization response." })
170
- });
171
- var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
172
- error: (0, import_v4.enum)([
173
- "invalid_request",
174
- "unauthorized_client",
175
- "access_denied",
176
- "unsupported_response_type",
177
- "invalid_scope",
178
- "server_error",
179
- "temporarily_unavailable"
180
- ]),
181
- error_description: (0, import_v4.string)().optional(),
182
- error_uri: (0, import_v4.string)().optional(),
183
- state: (0, import_v4.string)()
184
- });
185
- var OAuthAccessToken = OAuthProviderConfigSchema.extend({
186
- redirectURI: (0, import_v4.string)(),
187
- code: (0, import_v4.string)(),
188
- codeVerifier: (0, import_v4.string)().min(43).max(128)
189
- });
190
- var OAuthAccessTokenResponse = (0, import_v4.object)({
191
- access_token: (0, import_v4.string)(),
192
- token_type: (0, import_v4.string)().optional(),
193
- expires_in: (0, import_v4.number)().optional(),
194
- refresh_token: (0, import_v4.string)().optional(),
195
- scope: (0, import_v4.union)([(0, import_v4.string)().optional().or((0, import_v4.null)()), (0, import_v4.array)((0, import_v4.string)()).optional()])
196
- });
197
- var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
198
- error: (0, import_v4.enum)([
199
- "invalid_request",
200
- "invalid_client",
201
- "invalid_grant",
202
- "unauthorized_client",
203
- "unsupported_grant_type",
204
- "invalid_scope"
205
- ]),
206
- error_description: (0, import_v4.string)().optional(),
207
- error_uri: (0, import_v4.string)().optional()
208
- });
209
- var OAuthErrorResponse = (0, import_v4.object)({
210
- error: (0, import_v4.string)(),
211
- error_description: (0, import_v4.string)().optional()
212
- });
213
- var OAuthEnvSchema = (0, import_v4.object)({
214
- clientId: import_v4.z.string().min(1, "OAuth Client ID is required in the environment variables."),
215
- clientSecret: import_v4.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
216
- });
217
-
218
- // src/utils.ts
219
- var import_router = require("@aura-stack/router");
220
-
221
- // src/env.ts
222
- var import_meta = {};
223
- var env = new Proxy({}, {
224
- get(_, prop) {
225
- if (typeof prop !== "string") return void 0;
226
- const hasProperty = (process2) => {
227
- return process2 && Object.prototype.hasOwnProperty.call(process2, prop);
228
- };
229
- try {
230
- if (typeof process !== "undefined" && hasProperty(process.env)) {
231
- return process.env[prop];
232
- }
233
- if (typeof import_meta !== "undefined" && hasProperty(import_meta.env)) {
234
- return import_meta.env[prop];
235
- }
236
- if (typeof Deno !== "undefined" && Deno.env?.get) {
237
- return Deno.env.get(prop);
238
- }
239
- if (typeof Bun !== "undefined" && hasProperty(Bun.env)) {
240
- return Bun.env[prop];
241
- }
242
- const globalValue = globalThis[prop];
243
- return typeof globalValue === "string" ? globalValue : void 0;
244
- } catch {
245
- return void 0;
246
- }
247
- }
248
- });
249
- var getEnv = (key) => {
250
- const keys = [`AURA_AUTH_${key.toUpperCase()}`, `AURA_${key.toUpperCase()}`, `AUTH_${key.toUpperCase()}`, key.toUpperCase()];
251
- return env[keys.find((k) => env[k]) ?? ""];
252
- };
253
-
254
- // src/assert.ts
255
- var import_crypto = require("@aura-stack/jose/crypto");
256
- var unsafeChars = [
257
- "<",
258
- ">",
259
- '"',
260
- "`",
261
- " ",
262
- "\r",
263
- "\n",
264
- " ",
265
- "\\",
266
- "%2F",
267
- "%5C",
268
- "%2f",
269
- "%5c",
270
- "\r\n",
271
- "%0A",
272
- "%0D",
273
- "%0a",
274
- "%0d",
275
- "..",
276
- "//",
277
- "///",
278
- "...",
279
- "%20",
280
- "\0"
281
- ];
282
- var isValidURL = (value) => {
283
- if (!new RegExp(/^https?:\/\/[^/]/).test(value)) {
284
- return false;
285
- }
286
- const match = value.match(/^(https?:\/\/)(.*)$/);
287
- if (!match) return false;
288
- const rest = match[2];
289
- for (const char of unsafeChars) {
290
- if (rest.includes(char)) return false;
291
- }
292
- const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()?#*+,;=:@-]*)*\/?$/;
293
- return regex.test(match[0]);
294
- };
295
- var isJWTPayloadWithToken = (payload) => {
296
- return typeof payload === "object" && payload !== null && "token" in payload && typeof payload?.token === "string";
297
- };
298
- var isRelativeURL = (value) => {
299
- if (value.length > 100) return false;
300
- for (const char of unsafeChars) {
301
- if (value.includes(char)) return false;
302
- }
303
- const regex = /^\/[a-zA-Z0-9\-_\/.?&=#]*\/?$/;
304
- return regex.test(value);
305
- };
306
- var isSameOrigin = (origin, expected) => {
307
- const originURL = new URL(origin);
308
- const expectedURL = new URL(expected);
309
- return equals(originURL.origin, expectedURL.origin);
310
- };
311
- var patternToRegex = (pattern) => {
312
- try {
313
- if (pattern.length > 2048) return null;
314
- pattern = pattern.replace(/\\/g, "");
315
- const match = pattern.match(/^(https?):\/\/([a-zA-Z0-9.*-]{1,253})(?::(\d{1,5}|\*))?(?:\/.*)?$/);
316
- if (!match) return null;
317
- const [, protocol, host, port] = match;
318
- const hasWildcard = host.includes("*");
319
- if (hasWildcard && !host.startsWith("*.")) return null;
320
- if (hasWildcard && host.slice(2).includes("*")) return null;
321
- const domain = hasWildcard ? host.slice(2) : host;
322
- const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
323
- const hostRegex = hasWildcard ? `[^.]+\\.${escapedDomain}` : escapedDomain;
324
- const portRegex = port === "*" ? ":\\d{1,5}" : port ? `:${port}` : "";
325
- return new RegExp(`^${protocol}:\\/\\/${hostRegex}${portRegex}$`);
326
- } catch {
327
- return null;
328
- }
329
- };
330
- var isTrustedOrigin = (url, trustedOrigins) => {
331
- if (!isValidURL(url) || trustedOrigins.length === 0) return false;
332
- try {
333
- const urlOrigin = new URL(url).origin;
334
- for (const pattern of trustedOrigins) {
335
- const regex = patternToRegex(pattern);
336
- if (regex?.test(urlOrigin)) return true;
337
- try {
338
- if (isValidURL(pattern) && equals(new URL(pattern).origin, urlOrigin)) return true;
339
- } catch {
340
- }
341
- }
342
- } catch {
343
- }
344
- return false;
345
- };
346
- var timingSafeEqual = (a, b) => {
347
- const bufferA = import_crypto.encoder.encode(a);
348
- const bufferB = import_crypto.encoder.encode(b);
349
- const len = Math.max(bufferA.length, bufferB.length);
350
- let diff = 0;
351
- for (let i = 0; i < len; i++) {
352
- diff |= (bufferA[i] ?? 0) ^ (bufferB[i] ?? 0);
353
- }
354
- return diff === 0 && bufferA.length === bufferB.length;
355
- };
356
-
357
- // src/utils.ts
358
- var AURA_AUTH_VERSION = "0.4.0";
359
- var equals = (a, b) => {
360
- if (a === null || b === null || a === void 0 || b === void 0) return false;
361
- return a === b;
362
- };
363
- var getBaseURL = (request) => {
364
- const url = new URL(request.url);
365
- return `${url.origin}${url.pathname}`;
366
- };
367
- var toISOString = (date) => {
368
- return new Date(date).toISOString();
369
- };
370
- var extractPath = (url) => {
371
- const pathRegex = /^https?:\/\/[a-zA-Z0-9_\-\.]+(:\d+)?(\/.*)$/;
372
- const match = url.match(pathRegex);
373
- return match && match[2] ? match[2] : "/";
374
- };
375
- var getErrorName = (error) => {
376
- if (error instanceof Error) {
377
- return error.name;
378
- }
379
- return typeof error === "string" ? error : "UnknownError";
380
- };
381
-
382
- // src/jose.ts
383
- var import_jose = require("@aura-stack/jose");
384
- var import_jose2 = require("@aura-stack/jose/jose");
385
- var import_crypto2 = require("@aura-stack/jose/crypto");
386
- var jwtVerificationOptions = {
387
- algorithms: ["HS256"],
388
- typ: "JWT"
389
- };
390
-
391
- // src/secure.ts
392
- var generateSecure = (length = 32) => {
393
- return import_jose2.base64url.encode((0, import_crypto2.getRandomBytes)(length));
394
- };
395
- var createSecretValue = (length = 32) => {
396
- return import_jose2.base64url.encode((0, import_crypto2.getRandomBytes)(length));
397
- };
398
- var createHash = async (data) => {
399
- const subtle = (0, import_crypto2.getSubtleCrypto)();
400
- const digest = await subtle.digest("SHA-256", import_crypto2.encoder.encode(data));
401
- return import_jose2.base64url.encode(new Uint8Array(digest));
402
- };
403
- var createPKCE = async (verifier) => {
404
- const byteLength = verifier ? void 0 : Math.floor(Math.random() * (96 - 32 + 1) + 32);
405
- const codeVerifier = verifier ?? generateSecure(byteLength ?? 64);
406
- if (codeVerifier.length < 43 || codeVerifier.length > 128) {
407
- throw new AuthSecurityError("PKCE_VERIFIER_INVALID", "The code verifier must be between 43 and 128 characters in length.");
408
- }
409
- const codeChallenge = await createHash(codeVerifier);
410
- return { codeVerifier, codeChallenge, method: "S256" };
411
- };
412
- var createCSRF = async (jose, csrfCookie) => {
413
- try {
414
- const token = generateSecure(32);
415
- if (csrfCookie) {
416
- await jose.verifyJWS(csrfCookie, jwtVerificationOptions);
417
- return csrfCookie;
418
- }
419
- return jose.signJWS({ token });
420
- } catch {
421
- const token = generateSecure(32);
422
- return jose.signJWS({ token });
423
- }
424
- };
425
- var verifyCSRF = async (jose, cookie, header) => {
426
- try {
427
- const cookiePayload = await jose.verifyJWS(cookie, jwtVerificationOptions);
428
- const headerPayload = await jose.verifyJWS(header, jwtVerificationOptions);
429
- if (!isJWTPayloadWithToken(cookiePayload)) {
430
- throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Cookie payload missing token field.");
431
- }
432
- if (!isJWTPayloadWithToken(headerPayload)) {
433
- throw new AuthSecurityError("CSRF_TOKEN_INVALID", "Header payload missing token field.");
434
- }
435
- if (!equals(cookiePayload.token.length, headerPayload.token.length)) {
436
- throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
437
- }
438
- if (!timingSafeEqual(cookiePayload.token, headerPayload.token)) {
439
- throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
440
- }
441
- return true;
442
- } catch {
443
- throw new AuthSecurityError("CSRF_TOKEN_INVALID", "The CSRF tokens do not match.");
444
- }
445
- };
446
-
447
- // src/actions/signIn/authorization-url.ts
448
- var setSearchParams = (url, params) => {
449
- for (const [key, value] of Object.entries(params)) {
450
- if (value !== void 0 && value !== "") {
451
- url.searchParams.set(key, value);
452
- }
453
- }
454
- };
455
- var buildAuthorizationURL = (oauth, redirect_uri, state, code_challenge, code_challenge_method) => {
456
- const authorizeConfig = oauth.authorize;
457
- const baseURL = typeof authorizeConfig === "string" ? authorizeConfig : authorizeConfig?.url ?? oauth.authorizeURL;
458
- if (!baseURL) {
459
- throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", "Missing authorization URL in OAuth provider configuration.");
460
- }
461
- const url = new URL(baseURL);
462
- const authorizeParams = typeof authorizeConfig === "string" ? void 0 : authorizeConfig?.params;
463
- setSearchParams(url, {
464
- response_type: authorizeParams?.responseType ?? oauth.responseType ?? "code",
465
- client_id: oauth.clientId,
466
- redirect_uri,
467
- state,
468
- code_challenge,
469
- code_challenge_method,
470
- scope: authorizeParams?.scope ?? oauth.scope,
471
- prompt: authorizeParams?.prompt,
472
- response_mode: authorizeParams?.responseMode,
473
- login_hint: authorizeParams?.loginHint,
474
- nonce: authorizeParams?.nonce,
475
- display: authorizeParams?.display,
476
- audience: authorizeParams?.audience
477
- });
478
- return url.toString();
479
- };
480
- var createAuthorizationURL = async (oauth, redirectURI, ctx) => {
481
- const state = createSecretValue();
482
- const { codeVerifier, codeChallenge, method } = await createPKCE();
483
- const authorization = buildAuthorizationURL(oauth, redirectURI, state, codeChallenge, method);
484
- const parsed = OAuthAuthorization.safeParse({ ...oauth, redirectURI, state, codeChallenge, codeChallengeMethod: method });
485
- if (!parsed.success) {
486
- ctx?.logger?.log("INVALID_OAUTH_CONFIGURATION", {
487
- structuredData: {
488
- scope: oauth?.scope ?? "",
489
- redirect_uri: redirectURI,
490
- has_state: Boolean(state),
491
- has_code_challenge: Boolean(codeChallenge),
492
- code_challenge_method: method
493
- }
494
- });
495
- throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", "The OAuth provider configuration is invalid.");
496
- }
497
- return {
498
- authorization,
499
- state,
500
- codeVerifier,
501
- method
502
- };
503
- };
504
-
505
- // src/actions/signIn/authorization.ts
506
- var getTrustedOrigins = async (request, trustedOrigins) => {
507
- if (!trustedOrigins) return [];
508
- const raw = typeof trustedOrigins === "function" ? await trustedOrigins(request) : trustedOrigins;
509
- return Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [];
510
- };
511
- var getBaseURL2 = async ({
512
- ctx,
513
- request,
514
- headers: headersInit
515
- }) => {
516
- const origin = getEnv("BASE_URL") || ctx?.baseURL;
517
- if (origin && origin !== "/") return origin;
518
- if (ctx?.trustedProxyHeaders) {
519
- const headers = headersInit && new Headers(headersInit) || request?.headers;
520
- const protocol = headers?.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? headers?.get("X-Forwarded-Proto") ?? "http";
521
- const host = headers?.get("Host") ?? headers?.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? headers?.get("X-Forwarded-Host") ?? null;
522
- if (host) return `${protocol}://${host}`;
523
- throw new AuthInternalError(
524
- "INVALID_OAUTH_CONFIGURATION",
525
- "The URL cannot be constructed. Please set the BASE_URL environment variable or provide trusted proxy host headers."
526
- );
527
- }
528
- try {
529
- return new URL(request?.url ?? "not-found").origin;
530
- } catch (error) {
531
- throw new AuthInternalError(
532
- "INVALID_OAUTH_CONFIGURATION",
533
- "The URL cannot be constructed. Please set the BASE_URL environment variable or enable trustedProxyHeaders.",
534
- { cause: error }
535
- );
536
- }
537
- };
538
- var getOriginURL = async (request, context) => {
539
- const trustedOrigins = await getTrustedOrigins(request, context?.trustedOrigins);
540
- trustedOrigins.push(new URL(request.url).origin);
541
- const origin = await getBaseURL2({ request, ctx: context });
542
- if (!isTrustedOrigin(origin, trustedOrigins)) {
543
- context?.logger?.log("UNTRUSTED_ORIGIN", { structuredData: { origin } });
544
- throw new AuthInternalError("UNTRUSTED_ORIGIN", "The constructed origin URL is not trusted.");
545
- }
546
- return origin;
547
- };
548
- var createRedirectURI = async (request, oauth, context) => {
549
- const origin = await getOriginURL(request, context);
550
- return `${origin}${context.basePath}/callback/${oauth}`;
551
- };
552
- var createSignInURL = async ({
553
- request,
554
- oauth,
555
- ctx,
556
- redirectTo
557
- }) => {
558
- const origin = await getOriginURL(request, ctx);
559
- const searchParams = new URLSearchParams();
560
- if (redirectTo !== void 0) searchParams.set("redirectTo", String(redirectTo));
561
- return `${origin}${ctx.basePath}/signIn/${oauth}?${searchParams.toString()}`;
562
- };
563
- var createRedirectTo = async (request, redirectTo, context) => {
564
- try {
565
- const headers = request.headers;
566
- const requestOrigin = await getOriginURL(request, context);
567
- const origins = await getTrustedOrigins(request, context?.trustedOrigins);
568
- const validateURL = (url) => {
569
- if (!isRelativeURL(url) && !isValidURL(url)) return "/";
570
- if (isRelativeURL(url)) return url;
571
- if (origins.length > 0) {
572
- if (isTrustedOrigin(url, origins)) {
573
- const urlOrigin = new URL(url).origin;
574
- for (const pattern of origins) {
575
- const regex = patternToRegex(pattern);
576
- if (regex?.test(urlOrigin)) {
577
- return isSameOrigin(url, request.url) ? extractPath(url) : url;
578
- }
579
- if (isValidURL(pattern) && equals(new URL(pattern).origin, urlOrigin)) return url;
580
- }
581
- }
582
- context?.logger?.log("OPEN_REDIRECT_ATTACK");
583
- return "/";
584
- }
585
- if (isSameOrigin(url, requestOrigin)) {
586
- return extractPath(url);
587
- }
588
- context?.logger?.log("OPEN_REDIRECT_ATTACK");
589
- return "/";
590
- };
591
- return validateURL(redirectTo ?? headers.get("Referer") ?? headers.get("Origin") ?? "/");
592
- } catch (error) {
593
- context?.logger?.log("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED");
594
- return "/";
595
- }
596
- };
597
-
598
- // src/api/signIn.ts
599
- var signIn = async (oauth, {
600
- ctx,
601
- headers: headersInit,
602
- redirectTo = "/",
603
- redirect,
604
- request: requestInit
605
- }) => {
606
- const headers = new Headers(headersInit);
607
- const provider = ctx.oauth[oauth];
608
- if (!provider) {
609
- throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", `The OAuth provider "${oauth}" is not configured.`);
610
- }
611
- let request = requestInit;
612
- if (!request) {
613
- const origin = await getBaseURL2({ ctx, headers });
614
- const url = `${origin}${ctx.basePath}/signIn/${oauth}`;
615
- request = new Request(url, { headers });
616
- }
617
- if (redirect === false) {
618
- const signInURL = await createSignInURL({ request, oauth, ctx, redirectTo });
619
- return { redirect: false, signInURL };
620
- }
621
- const redirectURI = await createRedirectURI(request, oauth, ctx);
622
- const redirectToValue = await createRedirectTo(request, redirectTo, ctx);
623
- const { authorization, state, codeVerifier } = await createAuthorizationURL(provider, redirectURI, ctx);
624
- ctx?.logger?.log("SIGN_IN_INITIATED", {
625
- structuredData: { oauth_provider: oauth }
626
- });
627
- const headersList = new import_router2.HeadersBuilder(cacheControl).setHeader("Location", authorization).setCookie(ctx.cookies.state.name, state, ctx.cookies.state.attributes).setCookie(ctx.cookies.redirectURI.name, redirectURI, ctx.cookies.redirectURI.attributes).setCookie(ctx.cookies.redirectTo.name, redirectToValue, ctx.cookies.redirectTo.attributes).setCookie(ctx.cookies.codeVerifier.name, codeVerifier, ctx.cookies.codeVerifier.attributes).toHeaders();
628
- return Response.json(
629
- { redirect: redirect ?? true, signInURL: authorization },
630
- {
631
- status: redirect ?? true ? 302 : 200,
632
- headers: headersList
633
- }
634
- );
635
- };
636
-
637
- // src/actions/signIn/signIn.ts
638
- var import_router3 = require("@aura-stack/router");
639
- var signInConfig = (oauth) => {
640
- return (0, import_router3.createEndpointConfig)("/signIn/:oauth", {
641
- schemas: {
642
- params: import_v42.z.object({
643
- oauth: import_v42.z.enum(
644
- Object.keys(oauth),
645
- "The OAuth provider is not supported or invalid."
646
- )
647
- }),
648
- searchParams: import_v42.z.object({
649
- redirect: import_v42.z.stringbool().optional().default(true),
650
- redirectTo: import_v42.z.string().optional()
651
- })
652
- }
653
- });
654
- };
655
- var signInAction = (oauth) => {
656
- return (0, import_router3.createEndpoint)(
657
- "GET",
658
- "/signIn/:oauth",
659
- async (ctx) => {
660
- const {
661
- request,
662
- params: { oauth: oauth2 },
663
- searchParams: { redirectTo, redirect },
664
- context
665
- } = ctx;
666
- const signInResult = await signIn(oauth2, {
667
- ctx: context,
668
- headers: request.headers,
669
- redirect,
670
- redirectTo,
671
- request
672
- });
673
- if (!redirect) {
674
- return Response.json(signInResult, { status: 200 });
675
- }
676
- return signInResult;
677
- },
678
- signInConfig(oauth)
679
- );
680
- };
681
-
682
- // src/actions/callback/callback.ts
683
- var import_v43 = require("zod/v4");
684
- var import_router4 = require("@aura-stack/router");
685
-
686
- // src/request.ts
687
- var fetchAsync = async (url, options2 = {}, timeout = 5e3) => {
688
- const controller = new AbortController();
689
- const timeoutId = setTimeout(() => controller.abort(), timeout);
690
- const response = await fetch(url, {
691
- ...options2,
692
- signal: controller.signal
693
- }).finally(() => clearTimeout(timeoutId));
694
- return response;
695
- };
696
-
697
- // src/actions/callback/userinfo.ts
698
- var getDefaultUserInfo = (profile) => {
699
- const sub = generateSecure(16);
700
- return {
701
- sub: profile?.id ?? profile?.sub ?? sub,
702
- email: profile?.email,
703
- name: profile?.name ?? profile?.username ?? profile?.nickname,
704
- image: profile?.image ?? profile?.picture
705
- };
706
- };
707
- var getUserInfo = async (oauthConfig, accessToken, logger) => {
708
- const userInfoConfig = oauthConfig.userInfo;
709
- const userinfoURL = typeof userInfoConfig === "string" ? userInfoConfig : userInfoConfig.url;
710
- const extraHeaders = typeof userInfoConfig === "string" ? void 0 : userInfoConfig.headers;
711
- const method = typeof userInfoConfig === "string" ? "GET" : (userInfoConfig.method ?? "GET").toUpperCase();
712
- try {
713
- logger?.log("OAUTH_USERINFO_REQUEST_INITIATED", {
714
- structuredData: {
715
- endpoint: userinfoURL
716
- }
717
- });
718
- const response = await fetchAsync(userinfoURL, {
719
- method,
720
- headers: {
721
- "User-Agent": `Aura Auth/${AURA_AUTH_VERSION}`,
722
- Accept: "application/json",
723
- Authorization: `Bearer ${accessToken}`,
724
- ...extraHeaders ?? {}
725
- }
726
- });
727
- if (!response.ok) {
728
- logger?.log("OAUTH_USERINFO_INVALID_RESPONSE");
729
- throw new OAuthProtocolError("INVALID_REQUEST", "Invalid userinfo response format");
730
- }
731
- const json = await response.json();
732
- const { success, data } = OAuthErrorResponse.safeParse(json);
733
- if (success) {
734
- logger?.log("OAUTH_USERINFO_ERROR", {
735
- message: "Error response received from OAuth userinfo endpoint",
736
- structuredData: {
737
- error: data.error,
738
- error_description: data.error_description ?? ""
739
- }
740
- });
741
- throw new OAuthProtocolError("INVALID_REQUEST", "An error was received from the OAuth userinfo endpoint.");
742
- }
743
- logger?.log("OAUTH_USERINFO_SUCCESS");
744
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
745
- } catch (error) {
746
- if (isOAuthProtocolError(error)) {
747
- throw error;
748
- }
749
- logger?.log("OAUTH_USERINFO_REQUEST_FAILED");
750
- if (isNativeError(error)) {
751
- throw new OAuthProtocolError("SERVER_ERROR", "Failed to fetch user information from OAuth provider", "", {
752
- cause: error
753
- });
754
- }
755
- throw new OAuthProtocolError("SERVER_ERROR", "Failed to fetch user information", "", { cause: error });
756
- }
757
- };
758
-
759
- // src/actions/callback/access-token.ts
760
- var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier, logger) => {
761
- const { accessToken, clientId, clientSecret } = oauthConfig;
762
- if (!clientId || !clientSecret || !redirectURI || !code || !codeVerifier || !accessToken) {
763
- logger?.log("INVALID_OAUTH_CONFIGURATION", {
764
- structuredData: {
765
- has_client_id: Boolean(clientId),
766
- has_client_secret: Boolean(clientSecret),
767
- has_access_token: Boolean(accessToken),
768
- has_redirect_uri: Boolean(redirectURI),
769
- has_code: Boolean(code),
770
- has_code_verifier: Boolean(codeVerifier)
771
- }
772
- });
773
- throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", "The OAuth provider configuration is invalid.");
774
- }
775
- const tokenURL = typeof accessToken === "string" ? accessToken : accessToken.url;
776
- const extraHeaders = typeof accessToken === "string" ? void 0 : accessToken.headers;
777
- try {
778
- logger?.log("OAUTH_ACCESS_TOKEN_REQUEST_INITIATED", {
779
- structuredData: {
780
- has_client_id: Boolean(clientId),
781
- redirect_uri: redirectURI,
782
- grant_type: "authorization_code"
783
- }
784
- });
785
- const response = await fetchAsync(tokenURL, {
786
- method: "POST",
787
- headers: {
788
- ...extraHeaders ?? {},
789
- Accept: "application/json",
790
- "Content-Type": "application/x-www-form-urlencoded"
791
- },
792
- body: new URLSearchParams({
793
- client_id: clientId,
794
- client_secret: clientSecret,
795
- code,
796
- redirect_uri: redirectURI,
797
- grant_type: "authorization_code",
798
- code_verifier: codeVerifier
799
- }).toString()
800
- });
801
- if (!response.ok) {
802
- logger?.log("INVALID_OAUTH_ACCESS_TOKEN_RESPONSE");
803
- throw new OAuthProtocolError("invalid_request", "Invalid access token response");
804
- }
805
- const json = await response.json();
806
- const token = OAuthAccessTokenResponse.safeParse(json);
807
- if (!token.success) {
808
- const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json);
809
- if (!success) {
810
- logger?.log("INVALID_OAUTH_ACCESS_TOKEN_RESPONSE");
811
- throw new OAuthProtocolError("invalid_request", "Invalid access token response format");
812
- }
813
- logger?.log("OAUTH_ACCESS_TOKEN_ERROR", {
814
- structuredData: {
815
- error: data.error,
816
- error_description: data.error_description ?? ""
817
- }
818
- });
819
- throw new OAuthProtocolError("INVALID_ACCESS_TOKEN", "Failed to retrieve access token");
820
- }
821
- logger?.log("OAUTH_ACCESS_TOKEN_SUCCESS");
822
- return token.data;
823
- } catch (error) {
824
- logger?.log("OAUTH_ACCESS_TOKEN_REQUEST_FAILED");
825
- if (error instanceof Error) {
826
- throw new OAuthProtocolError("server_error", "Failed to communicate with OAuth provider", "", { cause: error });
827
- }
828
- throw error;
829
- }
830
- };
831
-
832
- // src/cookie.ts
833
- var import_cookie = require("@aura-stack/router/cookie");
834
- var defaultCookieOptions = {
835
- httpOnly: true,
836
- sameSite: "lax",
837
- path: "/",
838
- maxAge: 60 * 60 * 24 * 15
839
- };
840
- var oauthCookieOptions = {
841
- httpOnly: true,
842
- maxAge: 5 * 60,
843
- sameSite: "lax",
844
- expires: new Date(Date.now() + 5 * 60 * 1e3)
845
- };
846
- var setCookie = (cookieName, value, options2) => {
847
- return (0, import_cookie.serialize)(cookieName, value, options2);
848
- };
849
- var expiredCookieAttributes = {
850
- ...defaultCookieOptions,
851
- expires: /* @__PURE__ */ new Date(0),
852
- maxAge: 0,
853
- secure: true
854
- };
855
- var getCookie = (request, cookieName) => {
856
- const cookies = request instanceof Request ? request.headers.get("Cookie") : request.get("Cookie");
857
- if (!cookies) {
858
- throw new AuthInternalError("COOKIE_NOT_FOUND", "No cookies found. There is no active session");
859
- }
860
- const value = (0, import_cookie.parse)(cookies)[cookieName];
861
- if (!value) {
862
- throw new AuthInternalError("COOKIE_NOT_FOUND", `Cookie "${cookieName}" not found. There is no active session`);
863
- }
864
- return value;
865
- };
866
- var createSessionCookie = async (jose, session) => {
867
- try {
868
- const encoded = await jose.encodeJWT(session);
869
- return encoded;
870
- } catch (error) {
871
- throw new AuthInternalError("INVALID_JWT_TOKEN", "Failed to create session cookie", { cause: error });
872
- }
873
- };
874
-
875
- // src/actions/callback/callback.ts
876
- var callbackConfig = (oauth) => {
877
- return (0, import_router4.createEndpointConfig)("/callback/:oauth", {
878
- schemas: {
879
- params: import_v43.z.object({
880
- oauth: import_v43.z.enum(
881
- Object.keys(oauth),
882
- "The OAuth provider is not supported or invalid."
883
- )
884
- }),
885
- searchParams: import_v43.z.object({
886
- code: import_v43.z.string("Missing code parameter in the OAuth authorization response."),
887
- state: import_v43.z.string("Missing state parameter in the OAuth authorization response.")
888
- })
889
- },
890
- use: [
891
- (ctx) => {
892
- const {
893
- searchParams,
894
- context: { logger }
895
- } = ctx;
896
- const response = OAuthAuthorizationErrorResponse.safeParse(searchParams);
897
- if (response.success) {
898
- const { error, error_description } = response.data;
899
- const criticalAuthErrors = ["access_denied", "server_error"];
900
- const severity = criticalAuthErrors.includes(error.toLowerCase()) ? "critical" : "warning";
901
- logger?.log("OAUTH_AUTHORIZATION_ERROR", {
902
- severity,
903
- structuredData: {
904
- error,
905
- error_description: error_description ?? ""
906
- }
907
- });
908
- throw new OAuthProtocolError(error, error_description || "OAuth Authorization Error");
909
- }
910
- return ctx;
911
- }
912
- ]
913
- });
914
- };
915
- var callbackAction = (oauth) => {
916
- return (0, import_router4.createEndpoint)(
917
- "GET",
918
- "/callback/:oauth",
919
- async (ctx) => {
920
- const {
921
- request,
922
- params: { oauth: oauth2 },
923
- searchParams: { code, state },
924
- context
925
- } = ctx;
926
- const { oauth: providers, cookies, jose, logger, trustedOrigins } = context;
927
- const oauthConfig = providers[oauth2];
928
- const cookieState = getCookie(request, cookies.state.name);
929
- const codeVerifier = getCookie(request, cookies.codeVerifier.name);
930
- const cookieRedirectTo = getCookie(request, cookies.redirectTo.name);
931
- const cookieRedirectURI = getCookie(request, cookies.redirectURI.name);
932
- if (!timingSafeEqual(cookieState, state)) {
933
- logger?.log("MISMATCHING_STATE", {
934
- structuredData: {
935
- oauth_provider: oauth2
936
- }
937
- });
938
- throw new AuthSecurityError(
939
- "MISMATCHING_STATE",
940
- "The provided state passed in the OAuth response does not match the stored state."
941
- );
942
- }
943
- const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier, logger);
944
- const origins = await getTrustedOrigins(request, trustedOrigins);
945
- const requestOrigin = await getOriginURL(request, context);
946
- if (!isRelativeURL(cookieRedirectTo)) {
947
- const isValid = origins.length > 0 ? isTrustedOrigin(cookieRedirectTo, origins) : isSameOrigin(cookieRedirectTo, requestOrigin);
948
- if (!isValid) {
949
- logger?.log("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", {
950
- structuredData: {
951
- redirect_path: cookieRedirectTo,
952
- provider: oauth2,
953
- has_trusted_origins: origins.length > 0,
954
- request_origin: requestOrigin
955
- }
956
- });
957
- throw new AuthSecurityError(
958
- "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
959
- "Invalid redirect path. Potential open redirect attack detected."
960
- );
961
- }
962
- }
963
- const userInfo = await getUserInfo(oauthConfig, accessToken.access_token, logger);
964
- const sessionCookie = await createSessionCookie(jose, userInfo);
965
- const csrfToken = await createCSRF(jose);
966
- logger?.log("OAUTH_CALLBACK_SUCCESS", {
967
- structuredData: {
968
- provider: oauth2
969
- }
970
- });
971
- const headers = new import_router4.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();
972
- return Response.json({ oauth: oauth2 }, { status: 302, headers });
973
- },
974
- callbackConfig(oauth)
975
- );
976
- };
977
-
978
- // src/actions/session/session.ts
979
- var import_router5 = require("@aura-stack/router");
980
-
981
- // src/api/getSession.ts
982
- var getSession = async ({ ctx, headers }) => {
983
- try {
984
- const session = getCookie(new Headers(headers), ctx.cookies.sessionToken.name);
985
- const decoded = await ctx.jose.decodeJWT(session);
986
- ctx?.logger?.log("AUTH_SESSION_VALID");
987
- const { exp, iat, jti, nbf, aud, iss, ...user } = decoded;
988
- return {
989
- session: {
990
- user,
991
- expires: toISOString(exp * 1e3)
992
- },
993
- authenticated: true
994
- };
995
- } catch (error) {
996
- ctx?.logger?.log("AUTH_SESSION_INVALID", { structuredData: { error_type: getErrorName(error) } });
997
- return { session: null, authenticated: false };
998
- }
999
- };
1000
-
1001
- // src/actions/session/session.ts
1002
- var sessionAction = (0, import_router5.createEndpoint)("GET", "/session", async (ctx) => {
1003
- const {
1004
- request,
1005
- context: { cookies }
1006
- } = ctx;
1007
- try {
1008
- const session = await getSession({ ctx: ctx.context, headers: request.headers });
1009
- if (!session.authenticated) {
1010
- throw new AuthInternalError("INVALID_JWT_TOKEN", "Session not authenticated");
1011
- }
1012
- return Response.json(session, { headers: secureApiHeaders });
1013
- } catch (error) {
1014
- const headers = new import_router5.HeadersBuilder(secureApiHeaders).setCookie(cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
1015
- return Response.json({ session: null, authenticated: false }, { status: 401, headers });
1016
- }
1017
- });
1018
-
1019
- // src/actions/signOut/signOut.ts
1020
- var import_v44 = require("zod/v4");
1021
- var import_router7 = require("@aura-stack/router");
1022
-
1023
- // src/api/signOut.ts
1024
- var import_router6 = require("@aura-stack/router");
1025
- var signOut = async ({
1026
- ctx,
1027
- headers: headersInit,
1028
- redirectTo = "/",
1029
- skipCSRFCheck = false
1030
- }) => {
1031
- const headers = new Headers(headersInit);
1032
- const header = headers.get("X-CSRF-Token");
1033
- let session = null;
1034
- let csrfToken = null;
1035
- try {
1036
- session = getCookie(headers, ctx.cookies.sessionToken.name);
1037
- } catch {
1038
- throw new AuthSecurityError("SESSION_TOKEN_MISSING", "The sessionToken is missing.");
1039
- }
1040
- try {
1041
- csrfToken = getCookie(headers, ctx.cookies.csrfToken.name);
1042
- } catch {
1043
- throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF token is missing.");
1044
- }
1045
- ctx?.logger?.log("SIGN_OUT_ATTEMPT", {
1046
- structuredData: {
1047
- has_session: Boolean(session),
1048
- has_csrf_token: Boolean(csrfToken),
1049
- has_csrf_header: Boolean(header),
1050
- skip_csrf_check: skipCSRFCheck
1051
- }
1052
- });
1053
- if (!session) {
1054
- ctx?.logger?.log("SESSION_TOKEN_MISSING");
1055
- throw new AuthSecurityError("SESSION_TOKEN_MISSING", "The sessionToken is missing.");
1056
- }
1057
- if (!skipCSRFCheck) {
1058
- if (!csrfToken) {
1059
- ctx?.logger?.log("CSRF_TOKEN_MISSING");
1060
- throw new AuthSecurityError("CSRF_TOKEN_MISSING", "The CSRF token is missing.");
1061
- }
1062
- if (!header) {
1063
- ctx?.logger?.log("CSRF_HEADER_MISSING");
1064
- throw new AuthSecurityError("CSRF_HEADER_MISSING", "The CSRF header is missing.");
1065
- }
1066
- try {
1067
- await verifyCSRF(ctx.jose, csrfToken, header);
1068
- } catch (error) {
1069
- ctx?.logger?.log("CSRF_TOKEN_INVALID", { structuredData: { error_type: getErrorName(error) } });
1070
- throw new AuthSecurityError("CSRF_TOKEN_INVALID", "CSRF token verification failed");
1071
- }
1072
- ctx?.logger?.log("SIGN_OUT_CSRF_VERIFIED");
1073
- } else {
1074
- try {
1075
- await ctx.jose.verifyJWS(csrfToken);
1076
- } catch (error) {
1077
- ctx?.logger?.log("CSRF_TOKEN_INVALID", { structuredData: { error_type: getErrorName(error) } });
1078
- throw new AuthSecurityError("CSRF_TOKEN_INVALID", "CSRF token verification failed");
1079
- }
1080
- }
1081
- try {
1082
- await ctx.jose.decodeJWT(session);
1083
- ctx?.logger?.log("SIGN_OUT_SUCCESS");
1084
- } catch (error) {
1085
- ctx?.logger?.log("INVALID_JWT_TOKEN", { structuredData: { error_type: getErrorName(error) } });
1086
- }
1087
- const headersList = new import_router6.HeadersBuilder(secureApiHeaders).setHeader("Location", redirectTo).setCookie(ctx.cookies.csrfToken.name, "", expiredCookieAttributes).setCookie(ctx.cookies.sessionToken.name, "", expiredCookieAttributes).toHeaders();
1088
- return Response.json(
1089
- { redirect: Boolean(redirectTo), url: redirectTo },
1090
- {
1091
- status: 202,
1092
- headers: headersList
1093
- }
1094
- );
1095
- };
1096
-
1097
- // src/actions/signOut/signOut.ts
1098
- var config = (0, import_router7.createEndpointConfig)({
1099
- schemas: {
1100
- searchParams: import_v44.z.object({
1101
- token_type_hint: import_v44.z.literal("session_token"),
1102
- redirectTo: import_v44.z.string().optional()
1103
- })
1104
- }
1105
- });
1106
- var signOutAction = (0, import_router7.createEndpoint)(
1107
- "POST",
1108
- "/signOut",
1109
- async (ctx) => {
1110
- const {
1111
- request,
1112
- searchParams: { redirectTo },
1113
- context
1114
- } = ctx;
1115
- const baseURL = getBaseURL(request);
1116
- const location = await createRedirectTo(
1117
- new Request(baseURL, {
1118
- headers: request.headers
1119
- }),
1120
- redirectTo,
1121
- context
1122
- );
1123
- return await signOut({
1124
- ctx: context,
1125
- headers: request.headers,
1126
- redirectTo: location
1127
- });
1128
- },
1129
- config
1130
- );
1131
-
1132
- // src/actions/csrfToken/csrfToken.ts
1133
- var import_router8 = require("@aura-stack/router");
1134
- var getCSRFToken = (request, cookieName) => {
1135
- try {
1136
- return getCookie(request, cookieName);
1137
- } catch {
1138
- return void 0;
1139
- }
1140
- };
1141
- var csrfTokenAction = (0, import_router8.createEndpoint)("GET", "/csrfToken", async (ctx) => {
1142
- const {
1143
- request,
1144
- context: { jose, cookies, logger }
1145
- } = ctx;
1146
- const token = getCSRFToken(request, cookies.csrfToken.name);
1147
- logger?.log("CSRF_TOKEN_REQUESTED", { structuredData: { has_token: Boolean(token) } });
1148
- const csrfToken = await createCSRF(jose, token);
1149
- logger?.log("CSRF_TOKEN_ISSUED", { structuredData: { issued: Boolean(csrfToken) } });
1150
- const headers = new Headers(secureApiHeaders);
1151
- headers.append("Set-Cookie", setCookie(cookies.csrfToken.name, csrfToken, cookies.csrfToken.attributes));
1152
- return Response.json({ csrfToken }, { headers });
1153
- });
1154
- // Annotate the CommonJS export names for ESM import in node:
1155
- 0 && (module.exports = {
1156
- callbackAction,
1157
- csrfTokenAction,
1158
- sessionAction,
1159
- signInAction,
1160
- signOutAction
1161
- });