@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
@@ -20,264 +20,262 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/actions/signIn/authorization.ts
21
21
  var authorization_exports = {};
22
22
  __export(authorization_exports, {
23
- createAuthorizationURL: () => createAuthorizationURL,
24
23
  createRedirectTo: () => createRedirectTo,
25
24
  createRedirectURI: () => createRedirectURI,
26
- getOriginURL: () => getOriginURL
25
+ createSignInURL: () => createSignInURL,
26
+ getBaseURL: () => getBaseURL,
27
+ getOriginURL: () => getOriginURL,
28
+ getTrustedOrigins: () => getTrustedOrigins
27
29
  });
28
30
  module.exports = __toCommonJS(authorization_exports);
29
31
 
30
- // src/assert.ts
31
- var isValidURL = (value) => {
32
- if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false;
33
- const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/;
34
- return regex.test(value);
35
- };
36
-
37
- // src/schemas.ts
38
- var import_zod = require("zod");
39
- var OAuthProviderConfigSchema = (0, import_zod.object)({
40
- authorizeURL: (0, import_zod.string)().url(),
41
- accessToken: (0, import_zod.string)().url(),
42
- scope: (0, import_zod.string)().optional(),
43
- userInfo: (0, import_zod.string)().url(),
44
- responseType: (0, import_zod.enum)(["code", "token", "id_token"]),
45
- clientId: (0, import_zod.string)(),
46
- clientSecret: (0, import_zod.string)()
47
- });
48
- var OAuthAuthorization = OAuthProviderConfigSchema.extend({
49
- redirectURI: (0, import_zod.string)(),
50
- state: (0, import_zod.string)(),
51
- codeChallenge: (0, import_zod.string)(),
52
- codeChallengeMethod: (0, import_zod.enum)(["plain", "S256"])
53
- });
54
- var OAuthAuthorizationResponse = (0, import_zod.object)({
55
- state: (0, import_zod.string)({ message: "Missing state parameter in the OAuth authorization response." }),
56
- code: (0, import_zod.string)({ message: "Missing code parameter in the OAuth authorization response." })
57
- });
58
- var OAuthAuthorizationErrorResponse = (0, import_zod.object)({
59
- error: (0, import_zod.enum)([
60
- "invalid_request",
61
- "unauthorized_client",
62
- "access_denied",
63
- "unsupported_response_type",
64
- "invalid_scope",
65
- "server_error",
66
- "temporarily_unavailable"
67
- ]),
68
- error_description: (0, import_zod.string)().optional(),
69
- error_uri: (0, import_zod.string)().optional(),
70
- state: (0, import_zod.string)()
71
- });
72
- var OAuthAccessToken = OAuthProviderConfigSchema.extend({
73
- redirectURI: (0, import_zod.string)(),
74
- code: (0, import_zod.string)(),
75
- codeVerifier: (0, import_zod.string)().min(43).max(128)
76
- });
77
- var OAuthAccessTokenResponse = (0, import_zod.object)({
78
- access_token: (0, import_zod.string)(),
79
- token_type: (0, import_zod.string)().optional(),
80
- expires_in: (0, import_zod.number)().optional(),
81
- refresh_token: (0, import_zod.string)().optional(),
82
- scope: (0, import_zod.string)().optional().or((0, import_zod.null)())
83
- });
84
- var OAuthAccessTokenErrorResponse = (0, import_zod.object)({
85
- error: (0, import_zod.enum)([
86
- "invalid_request",
87
- "invalid_client",
88
- "invalid_grant",
89
- "unauthorized_client",
90
- "unsupported_grant_type",
91
- "invalid_scope"
92
- ]),
93
- error_description: (0, import_zod.string)().optional(),
94
- error_uri: (0, import_zod.string)().optional()
95
- });
96
- var OAuthErrorResponse = (0, import_zod.object)({
97
- error: (0, import_zod.string)(),
98
- error_description: (0, import_zod.string)().optional()
99
- });
100
- var OAuthEnvSchema = (0, import_zod.object)({
101
- clientId: import_zod.z.string().min(1, "OAuth Client ID is required in the environment variables."),
102
- clientSecret: import_zod.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
32
+ // src/env.ts
33
+ var import_meta = {};
34
+ var env = new Proxy({}, {
35
+ get(_, prop) {
36
+ if (typeof prop !== "string") return void 0;
37
+ const hasProperty = (process2) => {
38
+ return process2 && Object.prototype.hasOwnProperty.call(process2, prop);
39
+ };
40
+ try {
41
+ if (typeof process !== "undefined" && hasProperty(process.env)) {
42
+ return process.env[prop];
43
+ }
44
+ if (typeof import_meta !== "undefined" && hasProperty(import_meta.env)) {
45
+ return import_meta.env[prop];
46
+ }
47
+ if (typeof Deno !== "undefined" && Deno.env?.get) {
48
+ return Deno.env.get(prop);
49
+ }
50
+ if (typeof Bun !== "undefined" && hasProperty(Bun.env)) {
51
+ return Bun.env[prop];
52
+ }
53
+ const globalValue = globalThis[prop];
54
+ return typeof globalValue === "string" ? globalValue : void 0;
55
+ } catch {
56
+ return void 0;
57
+ }
58
+ }
103
59
  });
60
+ var getEnv = (key) => {
61
+ const keys = [`AURA_AUTH_${key.toUpperCase()}`, `AURA_${key.toUpperCase()}`, `AUTH_${key.toUpperCase()}`, key.toUpperCase()];
62
+ return env[keys.find((k) => env[k]) ?? ""];
63
+ };
104
64
 
105
65
  // src/errors.ts
106
66
  var AuthInternalError = class extends Error {
107
67
  type = "AUTH_INTERNAL_ERROR";
108
68
  code;
109
- constructor(code, message, options2) {
110
- super(message, options2);
69
+ constructor(code, message, options) {
70
+ super(message, options);
111
71
  this.code = code;
112
72
  this.name = new.target.name;
113
73
  Error.captureStackTrace(this, new.target);
114
74
  }
115
75
  };
116
- var AuthSecurityError = class extends Error {
117
- type = "AUTH_SECURITY_ERROR";
118
- code;
119
- constructor(code, message, options2) {
120
- super(message, options2);
121
- this.code = code;
122
- this.name = new.target.name;
123
- Error.captureStackTrace(this, new.target);
124
- }
125
- };
126
- var isAuthSecurityError = (error) => {
127
- return error instanceof AuthSecurityError;
128
- };
129
76
 
130
77
  // src/utils.ts
131
78
  var import_router = require("@aura-stack/router");
132
- var toSnakeCase = (str) => {
133
- return str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().replace(/^_+/, "");
134
- };
135
- var toUpperCase = (str) => {
136
- return str.toUpperCase();
79
+
80
+ // src/assert.ts
81
+ var import_crypto = require("@aura-stack/jose/crypto");
82
+ var unsafeChars = [
83
+ "<",
84
+ ">",
85
+ '"',
86
+ "`",
87
+ " ",
88
+ "\r",
89
+ "\n",
90
+ " ",
91
+ "\\",
92
+ "%2F",
93
+ "%5C",
94
+ "%2f",
95
+ "%5c",
96
+ "\r\n",
97
+ "%0A",
98
+ "%0D",
99
+ "%0a",
100
+ "%0d",
101
+ "..",
102
+ "//",
103
+ "///",
104
+ "...",
105
+ "%20",
106
+ "\0"
107
+ ];
108
+ var isValidURL = (value) => {
109
+ if (!new RegExp(/^https?:\/\/[^/]/).test(value)) {
110
+ return false;
111
+ }
112
+ const match = value.match(/^(https?:\/\/)(.*)$/);
113
+ if (!match) return false;
114
+ const rest = match[2];
115
+ for (const char of unsafeChars) {
116
+ if (rest.includes(char)) return false;
117
+ }
118
+ const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()?#*+,;=:@-]*)*\/?$/;
119
+ return regex.test(match[0]);
137
120
  };
138
- var toCastCase = (obj, type = "snake") => {
139
- return Object.entries(obj).reduce((previous, [key, value]) => {
140
- const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key);
141
- return { ...previous, [newKey]: value };
142
- }, {});
121
+ var isRelativeURL = (value) => {
122
+ if (value.length > 100) return false;
123
+ for (const char of unsafeChars) {
124
+ if (value.includes(char)) return false;
125
+ }
126
+ const regex = /^\/[a-zA-Z0-9\-_\/.?&=#]*\/?$/;
127
+ return regex.test(value);
143
128
  };
144
- var equals = (a, b) => {
145
- if (a === null || b === null || a === void 0 || b === void 0) return false;
146
- return a === b;
129
+ var isSameOrigin = (origin, expected) => {
130
+ const originURL = new URL(origin);
131
+ const expectedURL = new URL(expected);
132
+ return equals(originURL.origin, expectedURL.origin);
147
133
  };
148
- var sanitizeURL = (url) => {
134
+ var patternToRegex = (pattern) => {
149
135
  try {
150
- let decodedURL = decodeURIComponent(url).trim();
151
- const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/);
152
- let protocol = "";
153
- let rest = decodedURL;
154
- if (protocolMatch) {
155
- protocol = protocolMatch[1];
156
- rest = decodedURL.slice(protocol.length);
157
- const slashIndex = rest.indexOf("/");
158
- if (slashIndex === -1) {
159
- return protocol + rest;
160
- }
161
- const domain = rest.slice(0, slashIndex);
162
- let path = rest.slice(slashIndex).replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
163
- if (path !== "/" && path.endsWith("/")) {
164
- path = path.replace(/\/+$/, "/");
165
- } else if (path !== "/") {
166
- path = path.replace(/\/+$/, "");
167
- }
168
- return protocol + domain + path;
169
- }
170
- let sanitized = decodedURL.replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
171
- if (sanitized !== "/" && sanitized.endsWith("/")) {
172
- sanitized = sanitized.replace(/\/+$/, "/");
173
- } else if (sanitized !== "/") {
174
- sanitized = sanitized.replace(/\/+$/, "");
175
- }
176
- return sanitized;
136
+ if (pattern.length > 2048) return null;
137
+ pattern = pattern.replace(/\\/g, "");
138
+ const match = pattern.match(/^(https?):\/\/([a-zA-Z0-9.*-]{1,253})(?::(\d{1,5}|\*))?(?:\/.*)?$/);
139
+ if (!match) return null;
140
+ const [, protocol, host, port] = match;
141
+ const hasWildcard = host.includes("*");
142
+ if (hasWildcard && !host.startsWith("*.")) return null;
143
+ if (hasWildcard && host.slice(2).includes("*")) return null;
144
+ const domain = hasWildcard ? host.slice(2) : host;
145
+ const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
146
+ const hostRegex = hasWildcard ? `[^.]+\\.${escapedDomain}` : escapedDomain;
147
+ const portRegex = port === "*" ? ":\\d{1,5}" : port ? `:${port}` : "";
148
+ return new RegExp(`^${protocol}:\\/\\/${hostRegex}${portRegex}$`);
177
149
  } catch {
178
- return url.trim();
150
+ return null;
179
151
  }
180
152
  };
181
- var getNormalizedOriginPath = (path) => {
153
+ var isTrustedOrigin = (url, trustedOrigins) => {
154
+ if (!isValidURL(url) || trustedOrigins.length === 0) return false;
182
155
  try {
183
- const url = new URL(path);
184
- url.hash = "";
185
- url.search = "";
186
- return `${url.origin}${url.pathname}`;
156
+ const urlOrigin = new URL(url).origin;
157
+ for (const pattern of trustedOrigins) {
158
+ const regex = patternToRegex(pattern);
159
+ if (regex?.test(urlOrigin)) return true;
160
+ try {
161
+ if (isValidURL(pattern) && equals(new URL(pattern).origin, urlOrigin)) return true;
162
+ } catch {
163
+ }
164
+ }
187
165
  } catch {
188
- return sanitizeURL(path);
189
166
  }
167
+ return false;
190
168
  };
191
- var formatZodError = (error) => {
192
- if (!error.issues || error.issues.length === 0) {
193
- return {};
194
- }
195
- return error.issues.reduce((previous, issue) => {
196
- const key = issue.path.join(".");
197
- return {
198
- ...previous,
199
- [key]: {
200
- code: issue.code,
201
- message: issue.message
202
- }
203
- };
204
- }, {});
169
+
170
+ // src/utils.ts
171
+ var equals = (a, b) => {
172
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
173
+ return a === b;
174
+ };
175
+ var extractPath = (url) => {
176
+ const pathRegex = /^https?:\/\/[a-zA-Z0-9_\-\.]+(:\d+)?(\/.*)$/;
177
+ const match = url.match(pathRegex);
178
+ return match && match[2] ? match[2] : "/";
205
179
  };
206
180
 
207
181
  // src/actions/signIn/authorization.ts
208
- var createAuthorizationURL = (oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod) => {
209
- const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod });
210
- if (!parsed.success) {
211
- const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
212
- throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
182
+ var getTrustedOrigins = async (request, trustedOrigins) => {
183
+ if (!trustedOrigins) return [];
184
+ const raw = typeof trustedOrigins === "function" ? await trustedOrigins(request) : trustedOrigins;
185
+ return Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [];
186
+ };
187
+ var getBaseURL = async ({
188
+ ctx,
189
+ request,
190
+ headers: headersInit
191
+ }) => {
192
+ const origin = getEnv("BASE_URL") || ctx?.baseURL;
193
+ if (origin && origin !== "/") return origin;
194
+ if (ctx?.trustedProxyHeaders) {
195
+ const headers = headersInit && new Headers(headersInit) || request?.headers;
196
+ const protocol = headers?.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? headers?.get("X-Forwarded-Proto") ?? "http";
197
+ const host = headers?.get("Host") ?? headers?.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? headers?.get("X-Forwarded-Host") ?? null;
198
+ if (host) return `${protocol}://${host}`;
199
+ throw new AuthInternalError(
200
+ "INVALID_OAUTH_CONFIGURATION",
201
+ "The URL cannot be constructed. Please set the BASE_URL environment variable or provide trusted proxy host headers."
202
+ );
203
+ }
204
+ try {
205
+ return new URL(request?.url ?? "not-found").origin;
206
+ } catch (error) {
207
+ throw new AuthInternalError(
208
+ "INVALID_OAUTH_CONFIGURATION",
209
+ "The URL cannot be constructed. Please set the BASE_URL environment variable or enable trustedProxyHeaders.",
210
+ { cause: error }
211
+ );
213
212
  }
214
- const { authorizeURL, ...options2 } = parsed.data;
215
- const { userInfo, accessToken, clientSecret, ...required } = options2;
216
- const searchParams = new URLSearchParams(toCastCase(required));
217
- return `${authorizeURL}?${searchParams}`;
218
213
  };
219
- var getOriginURL = (request, trustedProxyHeaders) => {
220
- const headers = request.headers;
221
- if (trustedProxyHeaders) {
222
- const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http";
223
- const host = headers.get("X-Forwarded-Host") ?? headers.get("Host") ?? headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? null;
224
- return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`);
225
- } else {
226
- return new URL(getNormalizedOriginPath(request.url));
214
+ var getOriginURL = async (request, context) => {
215
+ const trustedOrigins = await getTrustedOrigins(request, context?.trustedOrigins);
216
+ trustedOrigins.push(new URL(request.url).origin);
217
+ const origin = await getBaseURL({ request, ctx: context });
218
+ if (!isTrustedOrigin(origin, trustedOrigins)) {
219
+ context?.logger?.log("UNTRUSTED_ORIGIN", { structuredData: { origin } });
220
+ throw new AuthInternalError("UNTRUSTED_ORIGIN", "The constructed origin URL is not trusted.");
227
221
  }
222
+ return origin;
228
223
  };
229
- var createRedirectURI = (request, oauth, basePath, trustedProxyHeaders) => {
230
- const url = getOriginURL(request, trustedProxyHeaders);
231
- return `${url.origin}${basePath}/callback/${oauth}`;
224
+ var createRedirectURI = async (request, oauth, context) => {
225
+ const origin = await getOriginURL(request, context);
226
+ return `${origin}${context.basePath}/callback/${oauth}`;
232
227
  };
233
- var createRedirectTo = (request, redirectTo, trustedProxyHeaders) => {
228
+ var createSignInURL = async ({
229
+ request,
230
+ oauth,
231
+ ctx,
232
+ redirectTo
233
+ }) => {
234
+ const origin = await getOriginURL(request, ctx);
235
+ const searchParams = new URLSearchParams();
236
+ if (redirectTo !== void 0) searchParams.set("redirectTo", String(redirectTo));
237
+ return `${origin}${ctx.basePath}/signIn/${oauth}?${searchParams.toString()}`;
238
+ };
239
+ var createRedirectTo = async (request, redirectTo, context) => {
234
240
  try {
235
241
  const headers = request.headers;
236
- const origin = headers.get("Origin");
237
- const referer = headers.get("Referer");
238
- let hostedURL = getOriginURL(request, trustedProxyHeaders);
239
- if (redirectTo) {
240
- if (redirectTo.startsWith("/")) {
241
- return sanitizeURL(redirectTo);
242
+ const requestOrigin = await getOriginURL(request, context);
243
+ const origins = await getTrustedOrigins(request, context?.trustedOrigins);
244
+ const validateURL = (url) => {
245
+ if (!isRelativeURL(url) && !isValidURL(url)) return "/";
246
+ if (isRelativeURL(url)) return url;
247
+ if (origins.length > 0) {
248
+ if (isTrustedOrigin(url, origins)) {
249
+ const urlOrigin = new URL(url).origin;
250
+ for (const pattern of origins) {
251
+ const regex = patternToRegex(pattern);
252
+ if (regex?.test(urlOrigin)) {
253
+ return isSameOrigin(url, request.url) ? extractPath(url) : url;
254
+ }
255
+ if (isValidURL(pattern) && equals(new URL(pattern).origin, urlOrigin)) return url;
256
+ }
257
+ }
258
+ context?.logger?.log("OPEN_REDIRECT_ATTACK");
259
+ return "/";
242
260
  }
243
- const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)));
244
- if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
245
- throw new AuthSecurityError(
246
- "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
247
- "The redirectTo parameter does not match the hosted origin."
248
- );
261
+ if (isSameOrigin(url, requestOrigin)) {
262
+ return extractPath(url);
249
263
  }
250
- return sanitizeURL(redirectToURL.pathname);
251
- }
252
- if (referer) {
253
- const refererURL = new URL(sanitizeURL(referer));
254
- if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
255
- throw new AuthSecurityError(
256
- "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
257
- "The referer of the request does not match the hosted origin."
258
- );
259
- }
260
- return sanitizeURL(refererURL.pathname);
261
- }
262
- if (origin) {
263
- const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)));
264
- if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
265
- throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
266
- }
267
- return sanitizeURL(originURL.pathname);
268
- }
269
- return "/";
264
+ context?.logger?.log("OPEN_REDIRECT_ATTACK");
265
+ return "/";
266
+ };
267
+ return validateURL(redirectTo ?? headers.get("Referer") ?? headers.get("Origin") ?? "/");
270
268
  } catch (error) {
271
- if (isAuthSecurityError(error)) {
272
- throw error;
273
- }
274
- throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
269
+ context?.logger?.log("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED");
270
+ return "/";
275
271
  }
276
272
  };
277
273
  // Annotate the CommonJS export names for ESM import in node:
278
274
  0 && (module.exports = {
279
- createAuthorizationURL,
280
275
  createRedirectTo,
281
276
  createRedirectURI,
282
- getOriginURL
277
+ createSignInURL,
278
+ getBaseURL,
279
+ getOriginURL,
280
+ getTrustedOrigins
283
281
  });
@@ -1,43 +1,54 @@
1
- import { h as OAuthProviderCredentials } from '../../index-B8jeIElf.js';
1
+ import { A as AuthConfig } from '../../index-_aXtxb_s.js';
2
+ import { GlobalContext } from '@aura-stack/router';
2
3
  import 'zod';
3
4
  import '../../schemas.js';
4
- import '@aura-stack/router/cookie';
5
+ import 'zod/v4';
5
6
  import '@aura-stack/jose';
6
7
  import '@aura-stack/jose/jose';
8
+ import '@aura-stack/jose/crypto';
9
+ import '@aura-stack/router/cookie';
7
10
  import '../../@types/utility.js';
11
+ import 'jose';
12
+ import 'zod/v4/core';
8
13
 
9
14
  /**
10
- * Constructs the request URI for the Authorization Request to the third-party OAuth service. It includes
11
- * the necessary query parameters such as `client_id`, `redirect_uri`, `response_type`, `scope`, `state`,
12
- * `code_challenge`, and `code_challenge_method`.
13
- *
14
- * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1
15
- * @see https://datatracker.ietf.org/doc/html/rfc7636#section-4
16
- *
17
- * @param oauthConfig - The OAuth configuration for the third-party service.
18
- * @param redirectURI - The redirect URI where the OAuth service will send the user after authorization.
19
- * @param state - A unique string used to maintain state between the request and callback.
15
+ * Resolves trusted origins from config (array or function).
20
16
  */
21
- declare const createAuthorizationURL: (oauthConfig: OAuthProviderCredentials, redirectURI: string, state: string, codeChallenge: string, codeChallengeMethod: string) => string;
22
- declare const getOriginURL: (request: Request, trustedProxyHeaders?: boolean) => URL;
17
+ declare const getTrustedOrigins: (request: Request, trustedOrigins: AuthConfig["trustedOrigins"]) => Promise<string[]>;
18
+ declare const getBaseURL: ({ ctx, request, headers: headersInit, }: {
19
+ ctx?: GlobalContext;
20
+ request?: Request;
21
+ headers?: HeadersInit;
22
+ }) => Promise<string>;
23
+ declare const getOriginURL: (request: Request, context?: GlobalContext) => Promise<string>;
23
24
  /**
24
25
  * Creates the redirect URI for the OAuth callback based on the original request URL and the OAuth provider.
25
26
  *
26
27
  * @param requestURL - the original request URL
27
28
  * @param oauth - OAuth provider name
29
+ * @param context - Global context containing configuration and utilities
28
30
  * @returns The redirect URI for the OAuth callback.
29
31
  */
30
- declare const createRedirectURI: (request: Request, oauth: string, basePath: string, trustedProxyHeaders?: boolean) => string;
32
+ declare const createRedirectURI: (request: Request, oauth: string, context: GlobalContext) => Promise<string>;
33
+ declare const createSignInURL: ({ request, oauth, ctx, redirectTo, }: {
34
+ request: Request;
35
+ oauth: string;
36
+ ctx: GlobalContext;
37
+ redirectTo?: string;
38
+ }) => Promise<string>;
31
39
  /**
32
40
  * Verifies if the request's origin matches the expected origin. It accepts the redirectTo search
33
- * parameter for redirection. It checks the 'Referer' header of the request with the origin where
34
- * the authentication flow is hosted. If they do not match, it throws an AuthError to avoid
35
- * potential `Open URL Redirection` attacks.
41
+ * parameter for redirection. It checks the Referer and Origin headers and the request URL against
42
+ * the trusted origins list. If they do not match, it returns "/" to avoid potential open redirect attacks.
43
+ *
44
+ * When `trustedOrigins` is provided, URLs are validated against that list. When not provided,
45
+ * the request's derived origin (from request.url or proxy headers) is used as the only trusted origin.
36
46
  *
37
47
  * @param request The incoming request object
38
48
  * @param redirectTo Optional redirectTo parameter to override the referer
39
- * @returns The pathname of the referer URL if origins match
49
+ * @param context Global context containing configuration and utilities
50
+ * @returns A safe URL to redirect to after authentication, or "/" if the URL is not considered safe.
40
51
  */
41
- declare const createRedirectTo: (request: Request, redirectTo?: string, trustedProxyHeaders?: boolean) => string;
52
+ declare const createRedirectTo: (request: Request, redirectTo?: string, context?: GlobalContext) => Promise<string>;
42
53
 
43
- export { createAuthorizationURL, createRedirectTo, createRedirectURI, getOriginURL };
54
+ export { createRedirectTo, createRedirectURI, createSignInURL, getBaseURL, getOriginURL, getTrustedOrigins };
@@ -1,16 +1,19 @@
1
1
  import {
2
- createAuthorizationURL,
3
2
  createRedirectTo,
4
3
  createRedirectURI,
5
- getOriginURL
6
- } from "../../chunk-N4SX7TZT.js";
7
- import "../../chunk-CXLATHS5.js";
8
- import "../../chunk-EIL2FPSS.js";
9
- import "../../chunk-RRLIF4PQ.js";
10
- import "../../chunk-YRCB5FLE.js";
4
+ createSignInURL,
5
+ getBaseURL,
6
+ getOriginURL,
7
+ getTrustedOrigins
8
+ } from "../../chunk-LATR3NIV.js";
9
+ import "../../chunk-LX3TJ2TJ.js";
10
+ import "../../chunk-WHNDRO3N.js";
11
+ import "../../chunk-U5663F2U.js";
11
12
  export {
12
- createAuthorizationURL,
13
13
  createRedirectTo,
14
14
  createRedirectURI,
15
- getOriginURL
15
+ createSignInURL,
16
+ getBaseURL,
17
+ getOriginURL,
18
+ getTrustedOrigins
16
19
  };