@better-auth/core 1.7.0-beta.0 → 1.7.0-beta.10

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 (218) hide show
  1. package/dist/api/index.d.mts +44 -1
  2. package/dist/api/index.mjs +69 -4
  3. package/dist/context/global.mjs +1 -1
  4. package/dist/context/transaction.d.mts +7 -4
  5. package/dist/context/transaction.mjs +6 -3
  6. package/dist/db/adapter/factory.mjs +91 -3
  7. package/dist/db/adapter/get-id-field.mjs +1 -1
  8. package/dist/db/adapter/index.d.mts +87 -3
  9. package/dist/db/adapter/types.d.mts +1 -1
  10. package/dist/db/get-tables.mjs +2 -1
  11. package/dist/db/type.d.mts +17 -0
  12. package/dist/env/env-impl.mjs +1 -1
  13. package/dist/error/codes.d.mts +1 -0
  14. package/dist/error/codes.mjs +1 -0
  15. package/dist/error/index.d.mts +7 -0
  16. package/dist/index.d.mts +2 -2
  17. package/dist/instrumentation/api.mjs +12 -0
  18. package/dist/instrumentation/noop.mjs +42 -0
  19. package/dist/instrumentation/pure.index.d.mts +7 -0
  20. package/dist/instrumentation/pure.index.mjs +7 -0
  21. package/dist/instrumentation/tracer.mjs +6 -3
  22. package/dist/oauth2/authorization-params.d.mts +12 -0
  23. package/dist/oauth2/authorization-params.mjs +12 -0
  24. package/dist/oauth2/basic-credentials.d.mts +30 -0
  25. package/dist/oauth2/basic-credentials.mjs +64 -0
  26. package/dist/oauth2/client-assertion.d.mts +38 -22
  27. package/dist/oauth2/client-assertion.mjs +63 -28
  28. package/dist/oauth2/client-credentials-token.d.mts +19 -40
  29. package/dist/oauth2/client-credentials-token.mjs +20 -31
  30. package/dist/oauth2/create-authorization-url.d.mts +11 -1
  31. package/dist/oauth2/create-authorization-url.mjs +27 -7
  32. package/dist/oauth2/dpop.d.mts +142 -0
  33. package/dist/oauth2/dpop.mjs +246 -0
  34. package/dist/oauth2/index.d.mts +14 -9
  35. package/dist/oauth2/index.mjs +12 -8
  36. package/dist/oauth2/oauth-provider.d.mts +150 -10
  37. package/dist/oauth2/refresh-access-token.d.mts +20 -40
  38. package/dist/oauth2/refresh-access-token.mjs +38 -36
  39. package/dist/oauth2/reject-redirects.mjs +65 -0
  40. package/dist/oauth2/token-endpoint-auth.d.mts +17 -0
  41. package/dist/oauth2/token-endpoint-auth.mjs +89 -0
  42. package/dist/oauth2/utils.d.mts +23 -1
  43. package/dist/oauth2/utils.mjs +48 -2
  44. package/dist/oauth2/validate-authorization-code.d.mts +17 -52
  45. package/dist/oauth2/validate-authorization-code.mjs +28 -34
  46. package/dist/oauth2/verify-id-token.d.mts +27 -0
  47. package/dist/oauth2/verify-id-token.mjs +62 -0
  48. package/dist/oauth2/verify.d.mts +88 -15
  49. package/dist/oauth2/verify.mjs +203 -25
  50. package/dist/social-providers/apple.d.mts +16 -4
  51. package/dist/social-providers/apple.mjs +17 -24
  52. package/dist/social-providers/atlassian.d.mts +5 -1
  53. package/dist/social-providers/atlassian.mjs +6 -3
  54. package/dist/social-providers/cognito.d.mts +27 -3
  55. package/dist/social-providers/cognito.mjs +15 -25
  56. package/dist/social-providers/discord.d.mts +7 -3
  57. package/dist/social-providers/discord.mjs +16 -3
  58. package/dist/social-providers/dropbox.d.mts +5 -1
  59. package/dist/social-providers/dropbox.mjs +5 -4
  60. package/dist/social-providers/facebook.d.mts +24 -5
  61. package/dist/social-providers/facebook.mjs +54 -20
  62. package/dist/social-providers/figma.d.mts +5 -1
  63. package/dist/social-providers/figma.mjs +4 -3
  64. package/dist/social-providers/github.d.mts +6 -2
  65. package/dist/social-providers/github.mjs +5 -4
  66. package/dist/social-providers/gitlab.d.mts +5 -1
  67. package/dist/social-providers/gitlab.mjs +3 -2
  68. package/dist/social-providers/google.d.mts +53 -5
  69. package/dist/social-providers/google.mjs +69 -25
  70. package/dist/social-providers/huggingface.d.mts +5 -1
  71. package/dist/social-providers/huggingface.mjs +3 -2
  72. package/dist/social-providers/index.d.mts +221 -45
  73. package/dist/social-providers/index.mjs +2 -2
  74. package/dist/social-providers/kakao.d.mts +5 -1
  75. package/dist/social-providers/kakao.mjs +3 -2
  76. package/dist/social-providers/kick.d.mts +5 -1
  77. package/dist/social-providers/kick.mjs +3 -2
  78. package/dist/social-providers/line.d.mts +8 -2
  79. package/dist/social-providers/line.mjs +5 -6
  80. package/dist/social-providers/linear.d.mts +5 -1
  81. package/dist/social-providers/linear.mjs +3 -2
  82. package/dist/social-providers/linkedin.d.mts +7 -3
  83. package/dist/social-providers/linkedin.mjs +4 -3
  84. package/dist/social-providers/microsoft-entra-id.d.mts +41 -7
  85. package/dist/social-providers/microsoft-entra-id.mjs +37 -28
  86. package/dist/social-providers/naver.d.mts +5 -1
  87. package/dist/social-providers/naver.mjs +3 -2
  88. package/dist/social-providers/notion.d.mts +5 -1
  89. package/dist/social-providers/notion.mjs +5 -2
  90. package/dist/social-providers/paybin.d.mts +5 -1
  91. package/dist/social-providers/paybin.mjs +4 -3
  92. package/dist/social-providers/paypal.d.mts +6 -2
  93. package/dist/social-providers/paypal.mjs +19 -14
  94. package/dist/social-providers/polar.d.mts +5 -1
  95. package/dist/social-providers/polar.mjs +3 -2
  96. package/dist/social-providers/railway.d.mts +5 -1
  97. package/dist/social-providers/railway.mjs +3 -2
  98. package/dist/social-providers/reddit.d.mts +5 -1
  99. package/dist/social-providers/reddit.mjs +7 -5
  100. package/dist/social-providers/roblox.d.mts +6 -2
  101. package/dist/social-providers/roblox.mjs +12 -2
  102. package/dist/social-providers/salesforce.d.mts +5 -1
  103. package/dist/social-providers/salesforce.mjs +4 -3
  104. package/dist/social-providers/slack.d.mts +6 -2
  105. package/dist/social-providers/slack.mjs +11 -8
  106. package/dist/social-providers/spotify.d.mts +5 -1
  107. package/dist/social-providers/spotify.mjs +3 -2
  108. package/dist/social-providers/tiktok.d.mts +5 -1
  109. package/dist/social-providers/tiktok.mjs +14 -2
  110. package/dist/social-providers/twitch.d.mts +5 -1
  111. package/dist/social-providers/twitch.mjs +3 -2
  112. package/dist/social-providers/twitter.d.mts +4 -1
  113. package/dist/social-providers/twitter.mjs +2 -1
  114. package/dist/social-providers/vercel.d.mts +5 -1
  115. package/dist/social-providers/vercel.mjs +3 -2
  116. package/dist/social-providers/vk.d.mts +5 -1
  117. package/dist/social-providers/vk.mjs +3 -2
  118. package/dist/social-providers/wechat.d.mts +5 -1
  119. package/dist/social-providers/wechat.mjs +8 -2
  120. package/dist/social-providers/zoom.d.mts +5 -1
  121. package/dist/social-providers/zoom.mjs +10 -17
  122. package/dist/types/context.d.mts +55 -6
  123. package/dist/types/index.d.mts +1 -1
  124. package/dist/types/init-options.d.mts +182 -12
  125. package/dist/types/plugin-client.d.mts +12 -2
  126. package/dist/utils/async.d.mts +22 -0
  127. package/dist/utils/async.mjs +32 -0
  128. package/dist/utils/host.d.mts +147 -0
  129. package/dist/utils/host.mjs +298 -0
  130. package/dist/utils/ip.d.mts +28 -5
  131. package/dist/utils/ip.mjs +118 -4
  132. package/dist/utils/is-api-error.d.mts +6 -0
  133. package/dist/utils/is-api-error.mjs +8 -0
  134. package/dist/utils/redirect-uri.d.mts +20 -0
  135. package/dist/utils/redirect-uri.mjs +48 -0
  136. package/dist/utils/string.d.mts +5 -1
  137. package/dist/utils/string.mjs +20 -1
  138. package/dist/utils/url.d.mts +18 -1
  139. package/dist/utils/url.mjs +34 -4
  140. package/package.json +26 -16
  141. package/src/api/index.ts +121 -5
  142. package/src/context/transaction.ts +45 -12
  143. package/src/db/adapter/factory.ts +193 -7
  144. package/src/db/adapter/get-id-field.ts +2 -2
  145. package/src/db/adapter/index.ts +85 -2
  146. package/src/db/adapter/types.ts +2 -0
  147. package/src/db/get-tables.ts +9 -1
  148. package/src/db/schema/account.ts +4 -1
  149. package/src/db/schema/user.ts +3 -0
  150. package/src/db/type.ts +17 -0
  151. package/src/env/env-impl.ts +1 -2
  152. package/src/error/codes.ts +1 -0
  153. package/src/error/index.ts +9 -0
  154. package/src/instrumentation/api.ts +17 -0
  155. package/src/instrumentation/noop.ts +74 -0
  156. package/src/instrumentation/pure.index.ts +31 -0
  157. package/src/instrumentation/tracer.ts +8 -3
  158. package/src/oauth2/authorization-params.ts +28 -0
  159. package/src/oauth2/basic-credentials.ts +87 -0
  160. package/src/oauth2/client-assertion.ts +131 -58
  161. package/src/oauth2/client-credentials-token.ts +50 -74
  162. package/src/oauth2/create-authorization-url.ts +33 -7
  163. package/src/oauth2/dpop.ts +568 -0
  164. package/src/oauth2/index.ts +81 -11
  165. package/src/oauth2/oauth-provider.ts +159 -11
  166. package/src/oauth2/refresh-access-token.ts +82 -83
  167. package/src/oauth2/reject-redirects.ts +75 -0
  168. package/src/oauth2/token-endpoint-auth.ts +221 -0
  169. package/src/oauth2/utils.ts +72 -5
  170. package/src/oauth2/validate-authorization-code.ts +69 -89
  171. package/src/oauth2/verify-id-token.ts +115 -0
  172. package/src/oauth2/verify.ts +409 -78
  173. package/src/social-providers/apple.ts +30 -40
  174. package/src/social-providers/atlassian.ts +8 -1
  175. package/src/social-providers/cognito.ts +36 -39
  176. package/src/social-providers/discord.ts +22 -18
  177. package/src/social-providers/dropbox.ts +7 -5
  178. package/src/social-providers/facebook.ts +108 -52
  179. package/src/social-providers/figma.ts +8 -1
  180. package/src/social-providers/github.ts +5 -3
  181. package/src/social-providers/gitlab.ts +2 -0
  182. package/src/social-providers/google.ts +141 -39
  183. package/src/social-providers/huggingface.ts +8 -1
  184. package/src/social-providers/kakao.ts +2 -1
  185. package/src/social-providers/kick.ts +8 -1
  186. package/src/social-providers/line.ts +25 -27
  187. package/src/social-providers/linear.ts +8 -1
  188. package/src/social-providers/linkedin.ts +5 -3
  189. package/src/social-providers/microsoft-entra-id.ts +100 -55
  190. package/src/social-providers/naver.ts +2 -1
  191. package/src/social-providers/notion.ts +8 -1
  192. package/src/social-providers/paybin.ts +2 -0
  193. package/src/social-providers/paypal.ts +28 -17
  194. package/src/social-providers/polar.ts +8 -1
  195. package/src/social-providers/railway.ts +8 -1
  196. package/src/social-providers/reddit.ts +9 -4
  197. package/src/social-providers/roblox.ts +16 -11
  198. package/src/social-providers/salesforce.ts +8 -1
  199. package/src/social-providers/slack.ts +15 -9
  200. package/src/social-providers/spotify.ts +8 -1
  201. package/src/social-providers/tiktok.ts +22 -9
  202. package/src/social-providers/twitch.ts +2 -1
  203. package/src/social-providers/twitter.ts +1 -0
  204. package/src/social-providers/vercel.ts +8 -1
  205. package/src/social-providers/vk.ts +8 -1
  206. package/src/social-providers/wechat.ts +17 -2
  207. package/src/social-providers/zoom.ts +15 -19
  208. package/src/types/context.ts +57 -5
  209. package/src/types/index.ts +7 -0
  210. package/src/types/init-options.ts +204 -14
  211. package/src/types/plugin-client.ts +16 -2
  212. package/src/utils/async.ts +53 -0
  213. package/src/utils/host.ts +425 -0
  214. package/src/utils/ip.ts +197 -13
  215. package/src/utils/is-api-error.ts +10 -0
  216. package/src/utils/redirect-uri.ts +54 -0
  217. package/src/utils/string.ts +37 -0
  218. package/src/utils/url.ts +38 -4
@@ -0,0 +1,147 @@
1
+ //#region src/utils/host.d.ts
2
+ /**
3
+ * Host classification per RFC 6890 (Special-Purpose IP Address Registries),
4
+ * RFC 6761 (Special-Use Domain Names), and RFC 8252 §7.3 (loopback redirect URIs).
5
+ *
6
+ * This module is the single source of truth for "is this host public? private?
7
+ * loopback? link-local?" in the codebase. Consumers MUST prefer these predicates
8
+ * over bespoke regexes or substring matches; divergent checks are how bypass
9
+ * vulnerabilities get introduced (e.g. Oligo's "0.0.0.0 Day" 2024).
10
+ *
11
+ * Four user-facing primitives:
12
+ *
13
+ * - `classifyHost(host)` — the workhorse. Returns a {@link HostClassification}
14
+ * with `kind`, `literal`, and `canonical` fields.
15
+ * - `isLoopbackIP(host)` — strict: IPv4 `127.0.0.0/8` or IPv6 `::1` only.
16
+ * Use this for RFC 8252 §7.3 loopback redirect URI matching where IP
17
+ * literals are REQUIRED.
18
+ * - `isLoopbackHost(host)` — permissive: also accepts `localhost` and RFC 6761
19
+ * `.localhost` subdomains. Use this for developer ergonomics (CORS, cookie
20
+ * secure bypass, dev-mode HTTP allow-list).
21
+ * - `isPublicRoutableHost(host)` — SSRF gate. Returns false for every
22
+ * non-`public` kind. Use this before server-side fetches to user-controlled
23
+ * URLs.
24
+ */
25
+ /**
26
+ * The semantic kind of a host, derived from RFC 6890 special-purpose registries
27
+ * plus a few domain-name categories (localhost, cloud metadata FQDNs).
28
+ */
29
+ type HostKind = /** IPv4 `127.0.0.0/8` or IPv6 `::1`. */"loopback" /** DNS name `localhost` or RFC 6761 `.localhost` TLD. */ | "localhost" /** IPv4 `0.0.0.0` or IPv6 `::` — "this host on this network", not loopback. */ | "unspecified" /** RFC 1918 `10/8`, `172.16/12`, `192.168/16`, or IPv6 ULA `fc00::/7`. */ | "private" /** IPv4 `169.254/16` or IPv6 `fe80::/10`. Includes AWS IMDS `169.254.169.254`. */ | "linkLocal" /** RFC 6598 carrier-grade NAT `100.64.0.0/10`. */ | "sharedAddressSpace" /** RFC 5737 `192.0.2/24`, `198.51.100/24`, `203.0.113/24`, or RFC 3849 `2001:db8::/32`. */ | "documentation" /** RFC 2544 `198.18.0.0/15`. */ | "benchmarking" /** IPv4 `224.0.0.0/4` or IPv6 `ff00::/8`. */ | "multicast" /** IPv4 limited broadcast `255.255.255.255`. */ | "broadcast" /** Other RFC 6890 special-purpose ranges (0.0.0.0/8, 192.0.0.0/24, 192.88.99.0/24, 240.0.0.0/4, 2001::/32, etc.). */ | "reserved" /** Cloud metadata service FQDN (e.g. `metadata.google.internal`). */ | "cloudMetadata" /** Any host not matching a special-purpose range above. */ | "public";
30
+ /**
31
+ * The syntactic form of the input host: an IPv4 literal, an IPv6 literal, or
32
+ * a domain name. IPv4-mapped IPv6 (`::ffff:192.0.2.1`) is reported as `ipv4`
33
+ * because it's unmapped during canonicalization.
34
+ */
35
+ type HostLiteral = "ipv4" | "ipv6" | "fqdn";
36
+ /**
37
+ * Result of {@link classifyHost}. All fields are readonly.
38
+ *
39
+ * @property kind - Semantic classification per RFC 6890 + RFC 6761.
40
+ * @property literal - Syntactic form of the input (IPv4, IPv6, or FQDN).
41
+ * @property canonical - Lowercase, port-stripped, bracket-stripped, zone-id-stripped
42
+ * form suitable for equality comparison. IPv6 is expanded to full form.
43
+ * IPv4-mapped IPv6 is collapsed to the underlying IPv4.
44
+ */
45
+ interface HostClassification {
46
+ readonly kind: HostKind;
47
+ readonly literal: HostLiteral;
48
+ readonly canonical: string;
49
+ }
50
+ /**
51
+ * Classify a host string according to RFC 6890 / RFC 6761.
52
+ *
53
+ * Accepts inputs in any of these shapes and normalizes before classifying:
54
+ *
55
+ * - Bare IPv4: `127.0.0.1`
56
+ * - Bare IPv6: `::1`, `fe80::1%eth0`
57
+ * - Bracketed IPv6: `[::1]`
58
+ * - Host with port: `localhost:3000`, `127.0.0.1:443`, `[::1]:8080`
59
+ * - FQDN: `example.com`, `tenant.localhost`
60
+ * - IPv4-mapped IPv6: `::ffff:192.0.2.1` (reported as `literal: "ipv4"`)
61
+ *
62
+ * Invalid or non-resolvable FQDNs are returned as `{ kind: "public", literal: "fqdn" }`
63
+ * — this function never throws. Callers that need structural validation must
64
+ * combine this with a URL/hostname validator upstream.
65
+ *
66
+ * @example
67
+ * classifyHost("127.0.0.1")
68
+ * // { kind: "loopback", literal: "ipv4", canonical: "127.0.0.1" }
69
+ *
70
+ * @example
71
+ * classifyHost("[::1]:8080")
72
+ * // { kind: "loopback", literal: "ipv6", canonical: "0000:0000:...:0001" }
73
+ *
74
+ * @example
75
+ * classifyHost("::ffff:192.0.2.1")
76
+ * // { kind: "documentation", literal: "ipv4", canonical: "192.0.2.1" }
77
+ *
78
+ * @example
79
+ * classifyHost("tenant-a.localhost")
80
+ * // { kind: "localhost", literal: "fqdn", canonical: "tenant-a.localhost" }
81
+ */
82
+ declare function classifyHost(host: string): HostClassification;
83
+ /**
84
+ * Strict loopback-IP-literal check per RFC 8252 §7.3.
85
+ *
86
+ * Returns true ONLY for IPv4 `127.0.0.0/8` or IPv6 `::1`. The DNS name
87
+ * `localhost` returns false — RFC 8252 §8.3 explicitly recommends against
88
+ * relying on name resolution for loopback redirect URIs.
89
+ *
90
+ * Use this for OAuth redirect URI matching.
91
+ *
92
+ * @example
93
+ * isLoopbackIP("127.0.0.1") // true
94
+ * isLoopbackIP("::1") // true
95
+ * isLoopbackIP("[::1]:8080") // true
96
+ * isLoopbackIP("localhost") // false (use isLoopbackHost for DNS names)
97
+ * isLoopbackIP("0.0.0.0") // false (unspecified, not loopback)
98
+ */
99
+ declare function isLoopbackIP(host: string): boolean;
100
+ /**
101
+ * Permissive loopback check for developer-ergonomics code paths.
102
+ *
103
+ * Returns true for IPv4 `127.0.0.0/8`, IPv6 `::1`, the literal name `localhost`,
104
+ * and any RFC 6761 `.localhost` subdomain (`tenant.localhost`, `app.localhost`).
105
+ *
106
+ * Use this for things like: allowing HTTP for dev servers, skipping Secure
107
+ * cookie requirements, browser-trust heuristics. Do NOT use this for OAuth
108
+ * redirect URI matching — use {@link isLoopbackIP} there.
109
+ *
110
+ * @example
111
+ * isLoopbackHost("localhost") // true
112
+ * isLoopbackHost("tenant.localhost") // true (RFC 6761)
113
+ * isLoopbackHost("127.0.0.1") // true
114
+ * isLoopbackHost("0.0.0.0") // false (unspecified, NOT loopback)
115
+ */
116
+ declare function isLoopbackHost(host: string): boolean;
117
+ /**
118
+ * First-line SSRF gate: returns true ONLY for hosts that classify as `public`.
119
+ *
120
+ * Every RFC 6890 special-purpose range (loopback, private, link-local,
121
+ * unspecified, documentation, multicast, broadcast, reserved, shared address
122
+ * space, benchmarking) and cloud-metadata FQDN returns false.
123
+ *
124
+ * Use this BEFORE issuing a server-side fetch to a user-supplied URL, e.g.
125
+ * OAuth introspection endpoints, webhook targets, or metadata-document
126
+ * fetches (CIMD).
127
+ *
128
+ * Limitations (this is a syntactic check, not a complete SSRF mitigation):
129
+ * - No DNS resolution: a public-looking FQDN that resolves to a private IP
130
+ * passes this check. Re-verify the resolved address before connecting, or
131
+ * pin the socket to the resolved IP.
132
+ * - No DNS-rebinding defense: attackers can return a public IP on the first
133
+ * lookup and a private IP on the second. Resolve once and reuse the IP.
134
+ * - No redirect following: HTTP 3xx responses can redirect to private hosts.
135
+ * Re-run this check on every redirect target, or disable auto-follow.
136
+ *
137
+ * @example
138
+ * isPublicRoutableHost("example.com") // true
139
+ * isPublicRoutableHost("127.0.0.1") // false (loopback)
140
+ * isPublicRoutableHost("169.254.169.254") // false (linkLocal / AWS IMDS)
141
+ * isPublicRoutableHost("metadata.google.internal") // false (cloudMetadata)
142
+ * isPublicRoutableHost("10.0.0.1") // false (private)
143
+ * isPublicRoutableHost("::ffff:127.0.0.1") // false (mapped loopback)
144
+ */
145
+ declare function isPublicRoutableHost(host: string): boolean;
146
+ //#endregion
147
+ export { HostClassification, HostKind, HostLiteral, classifyHost, isLoopbackHost, isLoopbackIP, isPublicRoutableHost };
@@ -0,0 +1,298 @@
1
+ import { isValidIP, normalizeIP } from "./ip.mjs";
2
+ //#region src/utils/host.ts
3
+ /**
4
+ * Cloud provider instance metadata service FQDNs. These resolve to link-local
5
+ * IPs (usually `169.254.169.254`) inside their respective clouds and are
6
+ * prime SSRF targets.
7
+ *
8
+ * The IPs themselves are already caught by the `linkLocal` kind; this set
9
+ * only exists for the FQDN form that a naive server-side fetch might resolve
10
+ * via its own resolver.
11
+ */
12
+ const CLOUD_METADATA_HOSTS = new Set([
13
+ "metadata.google.internal",
14
+ "metadata.goog",
15
+ "metadata",
16
+ "instance-data",
17
+ "instance-data.ec2.internal"
18
+ ]);
19
+ /** Strip `[...]` if the entire input is bracketed (IPv6 literal form). */
20
+ function stripBrackets(host) {
21
+ if (host.length >= 2 && host.startsWith("[") && host.endsWith("]")) return host.slice(1, -1);
22
+ return host;
23
+ }
24
+ /**
25
+ * Strip trailing `:port` from host-with-port strings.
26
+ *
27
+ * - Bracketed IPv6 with port: `[::1]:8080` → `[::1]`
28
+ * - IPv4/FQDN with port: `127.0.0.1:3000` / `example.com:443` → base form
29
+ * - Bare IPv6: `::1` / `fe80::1` → unchanged (multiple colons means no port)
30
+ */
31
+ function stripPort(host) {
32
+ if (host.startsWith("[")) {
33
+ const end = host.indexOf("]");
34
+ if (end === -1) return host;
35
+ return host.slice(0, end + 1);
36
+ }
37
+ const firstColon = host.indexOf(":");
38
+ if (firstColon === -1) return host;
39
+ if (host.indexOf(":", firstColon + 1) !== -1) return host;
40
+ return host.slice(0, firstColon);
41
+ }
42
+ /** Strip IPv6 zone identifier: `fe80::1%eth0` → `fe80::1`. */
43
+ function stripZoneId(host) {
44
+ const zone = host.indexOf("%");
45
+ if (zone === -1) return host;
46
+ return host.slice(0, zone);
47
+ }
48
+ /**
49
+ * Strip trailing dots (RFC 1034 absolute DNS form): `localhost.` → `localhost`.
50
+ * Without this, `metadata.google.internal.` would fall through to `public` and
51
+ * bypass the cloud-metadata / `.localhost` checks, since WHATWG URL parsing
52
+ * preserves the trailing dot in `url.hostname`.
53
+ */
54
+ function stripTrailingDot(host) {
55
+ return host.replace(/\.+$/, "");
56
+ }
57
+ /** Fast dotted-decimal shape check. Does NOT validate octet bounds. */
58
+ function looksLikeIPv4(host) {
59
+ return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
60
+ }
61
+ /** Pack a validated dotted-decimal IPv4 into a 32-bit unsigned integer. */
62
+ function ipv4ToUint32(ip) {
63
+ const parts = ip.split(".");
64
+ return (Number(parts[0]) << 24 | Number(parts[1]) << 16 | Number(parts[2]) << 8 | Number(parts[3])) >>> 0;
65
+ }
66
+ /** Check whether a 32-bit value matches `prefix/length` (both unsigned). */
67
+ function inIPv4Range(value, prefix, length) {
68
+ if (length === 0) return true;
69
+ const mask = length === 32 ? 4294967295 : -1 << 32 - length >>> 0;
70
+ return (value & mask) === (prefix & mask);
71
+ }
72
+ function classifyIPv4(ip) {
73
+ if (ip === "0.0.0.0") return "unspecified";
74
+ if (ip === "255.255.255.255") return "broadcast";
75
+ const n = ipv4ToUint32(ip);
76
+ if (inIPv4Range(n, ipv4ToUint32("127.0.0.0"), 8)) return "loopback";
77
+ if (inIPv4Range(n, ipv4ToUint32("10.0.0.0"), 8)) return "private";
78
+ if (inIPv4Range(n, ipv4ToUint32("172.16.0.0"), 12)) return "private";
79
+ if (inIPv4Range(n, ipv4ToUint32("192.168.0.0"), 16)) return "private";
80
+ if (inIPv4Range(n, ipv4ToUint32("169.254.0.0"), 16)) return "linkLocal";
81
+ if (inIPv4Range(n, ipv4ToUint32("100.64.0.0"), 10)) return "sharedAddressSpace";
82
+ if (inIPv4Range(n, ipv4ToUint32("192.0.2.0"), 24)) return "documentation";
83
+ if (inIPv4Range(n, ipv4ToUint32("198.51.100.0"), 24)) return "documentation";
84
+ if (inIPv4Range(n, ipv4ToUint32("203.0.113.0"), 24)) return "documentation";
85
+ if (inIPv4Range(n, ipv4ToUint32("198.18.0.0"), 15)) return "benchmarking";
86
+ if (inIPv4Range(n, ipv4ToUint32("224.0.0.0"), 4)) return "multicast";
87
+ if (inIPv4Range(n, ipv4ToUint32("0.0.0.0"), 8)) return "reserved";
88
+ if (inIPv4Range(n, ipv4ToUint32("192.0.0.0"), 24)) return "reserved";
89
+ if (inIPv4Range(n, ipv4ToUint32("192.88.99.0"), 24)) return "reserved";
90
+ if (inIPv4Range(n, ipv4ToUint32("240.0.0.0"), 4)) return "reserved";
91
+ return "public";
92
+ }
93
+ /**
94
+ * Extract an IPv4 address embedded in an expanded IPv6 literal.
95
+ *
96
+ * Used to recurse into tunnel/translation forms (6to4, NAT64, Teredo) so a
97
+ * private destination cannot be smuggled behind a syntactically-public IPv6
98
+ * literal. `startGroup` is the index of the first of two 16-bit groups in the
99
+ * expanded form (`0000:0000:...`). With `xor: true`, the 32-bit value is XORed
100
+ * with `0xffffffff` before decoding (Teredo obfuscates the client IPv4 this
101
+ * way).
102
+ */
103
+ function extractEmbeddedIPv4(expanded, startGroup, options = {}) {
104
+ const offset = startGroup * 5;
105
+ const g1 = Number.parseInt(expanded.slice(offset, offset + 4), 16);
106
+ const g2 = Number.parseInt(expanded.slice(offset + 5, offset + 9), 16);
107
+ if (!Number.isFinite(g1) || !Number.isFinite(g2)) return null;
108
+ let combined = (g1 << 16 | g2) >>> 0;
109
+ if (options.xor) combined = (combined ^ 4294967295) >>> 0;
110
+ return `${combined >>> 24 & 255}.${combined >>> 16 & 255}.${combined >>> 8 & 255}.${combined & 255}`;
111
+ }
112
+ /**
113
+ * Classify an expanded, full-form, lowercase IPv6 address (no IPv4-mapped
114
+ * input — those are unmapped to IPv4 before reaching here).
115
+ *
116
+ * 6to4 (`2002::/16`), NAT64 (`64:ff9b::/96`) and Teredo (`2001:0000::/32`)
117
+ * embed an IPv4 that can route to private/loopback space. If the embedded
118
+ * IPv4 classifies as non-`public`, return `reserved` — blocks SSRF without
119
+ * advertising the address as a loopback literal for RFC 8252 §7.3 matching.
120
+ */
121
+ function classifyIPv6(expanded) {
122
+ if (expanded === "0000:0000:0000:0000:0000:0000:0000:0000") return "unspecified";
123
+ if (expanded === "0000:0000:0000:0000:0000:0000:0000:0001") return "loopback";
124
+ const firstByte = Number.parseInt(expanded.slice(0, 2), 16);
125
+ const secondByte = Number.parseInt(expanded.slice(2, 4), 16);
126
+ if (firstByte === 255) return "multicast";
127
+ if (firstByte === 254 && (secondByte & 192) === 128) return "linkLocal";
128
+ if (firstByte === 254 && (secondByte & 192) === 192) return "reserved";
129
+ if ((firstByte & 254) === 252) return "private";
130
+ if (expanded.startsWith("2001:0db8:")) return "documentation";
131
+ if (expanded.startsWith("2001:0002:0000:")) return "benchmarking";
132
+ if (expanded.startsWith("2002:")) {
133
+ const embedded = extractEmbeddedIPv4(expanded, 1);
134
+ if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
135
+ return "public";
136
+ }
137
+ if (expanded.startsWith("0064:ff9b:0000:0000:0000:0000:")) {
138
+ const embedded = extractEmbeddedIPv4(expanded, 6);
139
+ if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
140
+ return "reserved";
141
+ }
142
+ if (expanded.startsWith("0064:ff9b:0001:")) return "reserved";
143
+ if (expanded.startsWith("2001:0000:")) {
144
+ const embedded = extractEmbeddedIPv4(expanded, 6, { xor: true });
145
+ if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
146
+ return "reserved";
147
+ }
148
+ if (expanded.startsWith("0100:0000:0000:0000:")) return "reserved";
149
+ if (expanded.startsWith("3fff:0")) return "documentation";
150
+ if (expanded.startsWith("5f00:")) return "reserved";
151
+ if (expanded.startsWith("0000:0000:0000:0000:0000:0000:")) return "reserved";
152
+ return "public";
153
+ }
154
+ /**
155
+ * Classify a host string according to RFC 6890 / RFC 6761.
156
+ *
157
+ * Accepts inputs in any of these shapes and normalizes before classifying:
158
+ *
159
+ * - Bare IPv4: `127.0.0.1`
160
+ * - Bare IPv6: `::1`, `fe80::1%eth0`
161
+ * - Bracketed IPv6: `[::1]`
162
+ * - Host with port: `localhost:3000`, `127.0.0.1:443`, `[::1]:8080`
163
+ * - FQDN: `example.com`, `tenant.localhost`
164
+ * - IPv4-mapped IPv6: `::ffff:192.0.2.1` (reported as `literal: "ipv4"`)
165
+ *
166
+ * Invalid or non-resolvable FQDNs are returned as `{ kind: "public", literal: "fqdn" }`
167
+ * — this function never throws. Callers that need structural validation must
168
+ * combine this with a URL/hostname validator upstream.
169
+ *
170
+ * @example
171
+ * classifyHost("127.0.0.1")
172
+ * // { kind: "loopback", literal: "ipv4", canonical: "127.0.0.1" }
173
+ *
174
+ * @example
175
+ * classifyHost("[::1]:8080")
176
+ * // { kind: "loopback", literal: "ipv6", canonical: "0000:0000:...:0001" }
177
+ *
178
+ * @example
179
+ * classifyHost("::ffff:192.0.2.1")
180
+ * // { kind: "documentation", literal: "ipv4", canonical: "192.0.2.1" }
181
+ *
182
+ * @example
183
+ * classifyHost("tenant-a.localhost")
184
+ * // { kind: "localhost", literal: "fqdn", canonical: "tenant-a.localhost" }
185
+ */
186
+ function classifyHost(host) {
187
+ const lowered = stripTrailingDot(stripZoneId(stripBrackets(stripPort(host.trim())))).toLowerCase();
188
+ if (lowered === "") return {
189
+ kind: "reserved",
190
+ literal: "fqdn",
191
+ canonical: ""
192
+ };
193
+ if (!isValidIP(lowered)) {
194
+ if (lowered === "localhost" || lowered.endsWith(".localhost")) return {
195
+ kind: "localhost",
196
+ literal: "fqdn",
197
+ canonical: lowered
198
+ };
199
+ if (CLOUD_METADATA_HOSTS.has(lowered)) return {
200
+ kind: "cloudMetadata",
201
+ literal: "fqdn",
202
+ canonical: lowered
203
+ };
204
+ return {
205
+ kind: "public",
206
+ literal: "fqdn",
207
+ canonical: lowered
208
+ };
209
+ }
210
+ if (looksLikeIPv4(lowered)) return {
211
+ kind: classifyIPv4(lowered),
212
+ literal: "ipv4",
213
+ canonical: lowered
214
+ };
215
+ const canonical = normalizeIP(lowered, { ipv6Subnet: 128 });
216
+ if (looksLikeIPv4(canonical)) return {
217
+ kind: classifyIPv4(canonical),
218
+ literal: "ipv4",
219
+ canonical
220
+ };
221
+ return {
222
+ kind: classifyIPv6(canonical),
223
+ literal: "ipv6",
224
+ canonical
225
+ };
226
+ }
227
+ /**
228
+ * Strict loopback-IP-literal check per RFC 8252 §7.3.
229
+ *
230
+ * Returns true ONLY for IPv4 `127.0.0.0/8` or IPv6 `::1`. The DNS name
231
+ * `localhost` returns false — RFC 8252 §8.3 explicitly recommends against
232
+ * relying on name resolution for loopback redirect URIs.
233
+ *
234
+ * Use this for OAuth redirect URI matching.
235
+ *
236
+ * @example
237
+ * isLoopbackIP("127.0.0.1") // true
238
+ * isLoopbackIP("::1") // true
239
+ * isLoopbackIP("[::1]:8080") // true
240
+ * isLoopbackIP("localhost") // false (use isLoopbackHost for DNS names)
241
+ * isLoopbackIP("0.0.0.0") // false (unspecified, not loopback)
242
+ */
243
+ function isLoopbackIP(host) {
244
+ return classifyHost(host).kind === "loopback";
245
+ }
246
+ /**
247
+ * Permissive loopback check for developer-ergonomics code paths.
248
+ *
249
+ * Returns true for IPv4 `127.0.0.0/8`, IPv6 `::1`, the literal name `localhost`,
250
+ * and any RFC 6761 `.localhost` subdomain (`tenant.localhost`, `app.localhost`).
251
+ *
252
+ * Use this for things like: allowing HTTP for dev servers, skipping Secure
253
+ * cookie requirements, browser-trust heuristics. Do NOT use this for OAuth
254
+ * redirect URI matching — use {@link isLoopbackIP} there.
255
+ *
256
+ * @example
257
+ * isLoopbackHost("localhost") // true
258
+ * isLoopbackHost("tenant.localhost") // true (RFC 6761)
259
+ * isLoopbackHost("127.0.0.1") // true
260
+ * isLoopbackHost("0.0.0.0") // false (unspecified, NOT loopback)
261
+ */
262
+ function isLoopbackHost(host) {
263
+ const kind = classifyHost(host).kind;
264
+ return kind === "loopback" || kind === "localhost";
265
+ }
266
+ /**
267
+ * First-line SSRF gate: returns true ONLY for hosts that classify as `public`.
268
+ *
269
+ * Every RFC 6890 special-purpose range (loopback, private, link-local,
270
+ * unspecified, documentation, multicast, broadcast, reserved, shared address
271
+ * space, benchmarking) and cloud-metadata FQDN returns false.
272
+ *
273
+ * Use this BEFORE issuing a server-side fetch to a user-supplied URL, e.g.
274
+ * OAuth introspection endpoints, webhook targets, or metadata-document
275
+ * fetches (CIMD).
276
+ *
277
+ * Limitations (this is a syntactic check, not a complete SSRF mitigation):
278
+ * - No DNS resolution: a public-looking FQDN that resolves to a private IP
279
+ * passes this check. Re-verify the resolved address before connecting, or
280
+ * pin the socket to the resolved IP.
281
+ * - No DNS-rebinding defense: attackers can return a public IP on the first
282
+ * lookup and a private IP on the second. Resolve once and reuse the IP.
283
+ * - No redirect following: HTTP 3xx responses can redirect to private hosts.
284
+ * Re-run this check on every redirect target, or disable auto-follow.
285
+ *
286
+ * @example
287
+ * isPublicRoutableHost("example.com") // true
288
+ * isPublicRoutableHost("127.0.0.1") // false (loopback)
289
+ * isPublicRoutableHost("169.254.169.254") // false (linkLocal / AWS IMDS)
290
+ * isPublicRoutableHost("metadata.google.internal") // false (cloudMetadata)
291
+ * isPublicRoutableHost("10.0.0.1") // false (private)
292
+ * isPublicRoutableHost("::ffff:127.0.0.1") // false (mapped loopback)
293
+ */
294
+ function isPublicRoutableHost(host) {
295
+ return classifyHost(host).kind === "public";
296
+ }
297
+ //#endregion
298
+ export { classifyHost, isLoopbackHost, isLoopbackIP, isPublicRoutableHost };
@@ -1,3 +1,4 @@
1
+ import { BetterAuthOptions } from "../types/init-options.mjs";
1
2
  //#region src/utils/ip.d.ts
2
3
  /**
3
4
  * Normalizes an IP address for consistent rate limiting.
@@ -10,12 +11,13 @@
10
11
  */
11
12
  interface NormalizeIPOptions {
12
13
  /**
13
- * For IPv6 addresses, extract the subnet prefix instead of full address.
14
- * Common values: 32, 48, 64, 128 (default: 128 = full address)
14
+ * Prefix length used to collapse IPv6 addresses before keying.
15
+ * Any integer from 0 to 128 is accepted. Common values: 32, 48, 56, 64, 128.
16
+ * Values outside 0-128 are clamped.
15
17
  *
16
- * @default 128
18
+ * @default 64
17
19
  */
18
- ipv6Subnet?: 128 | 64 | 48 | 32;
20
+ ipv6Subnet?: number;
19
21
  }
20
22
  /**
21
23
  * Checks if an IP is valid IPv4 or IPv6
@@ -41,6 +43,27 @@ declare function isValidIP(ip: string): boolean;
41
43
  * // -> "2001:0db8:0000:0000:0000:0000:0000:0000" (subnet /64)
42
44
  */
43
45
  declare function normalizeIP(ip: string, options?: NormalizeIPOptions): string;
46
+ /**
47
+ * Trusted-proxy entries that are not a valid IP address or CIDR range.
48
+ */
49
+ declare function findInvalidTrustedProxies(entries: string[]): string[];
50
+ /**
51
+ * Resolves the client IP from a forwarded header. The leftmost token is spoofable,
52
+ * so with `trustedProxies` the chain is stripped from the right to the first
53
+ * untrusted hop. Otherwise only a single-value header is trusted. Returns `null`
54
+ * when no trustworthy client IP can be resolved.
55
+ */
56
+ declare function getIPFromHeader(value: string, options?: {
57
+ ipv6Subnet?: number;
58
+ trustedProxies?: string[];
59
+ }): string | null;
60
+ /**
61
+ * Resolves the client IP for a request from the configured IP headers.
62
+ * Honors `disableIpTracking`, walks `ipAddressHeaders` in order (default
63
+ * `x-forwarded-for`), and falls back to localhost in development and test.
64
+ * Returns `null` when tracking is disabled or no trustworthy IP can be resolved.
65
+ */
66
+ declare function getIP(req: Request | Headers, options: BetterAuthOptions): string | null;
44
67
  /**
45
68
  * Creates a rate limit key from IP and path
46
69
  * Uses a separator to prevent collision attacks
@@ -51,4 +74,4 @@ declare function normalizeIP(ip: string, options?: NormalizeIPOptions): string;
51
74
  */
52
75
  declare function createRateLimitKey(ip: string, path: string): string;
53
76
  //#endregion
54
- export { createRateLimitKey, isValidIP, normalizeIP };
77
+ export { createRateLimitKey, findInvalidTrustedProxies, getIP, getIPFromHeader, isValidIP, normalizeIP };
package/dist/utils/ip.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { isDevelopment, isTest } from "../env/env-impl.mjs";
1
2
  import * as z from "zod";
2
3
  //#region src/utils/ip.ts
3
4
  /**
@@ -60,8 +61,8 @@ function expandIPv6(ipv6) {
60
61
  */
61
62
  function normalizeIPv6(ipv6, subnetPrefix) {
62
63
  const groups = expandIPv6(ipv6);
63
- if (subnetPrefix && subnetPrefix < 128) {
64
- let bitsRemaining = subnetPrefix;
64
+ if (subnetPrefix !== void 0 && subnetPrefix < 128) {
65
+ let bitsRemaining = Math.max(0, Math.floor(subnetPrefix));
65
66
  return groups.map((group) => {
66
67
  if (bitsRemaining <= 0) return "0000";
67
68
  if (bitsRemaining >= 16) {
@@ -99,7 +100,120 @@ function normalizeIP(ip, options = {}) {
99
100
  if (!isIPv6(ip)) return ip.toLowerCase();
100
101
  const ipv4 = extractIPv4FromMapped(ip);
101
102
  if (ipv4) return ipv4.toLowerCase();
102
- return normalizeIPv6(ip, options.ipv6Subnet || 64);
103
+ return normalizeIPv6(ip, options.ipv6Subnet ?? 64);
104
+ }
105
+ /**
106
+ * Raw bytes of an IP for CIDR comparison. Returns `null` for an invalid IP.
107
+ */
108
+ function ipToBytes(ip) {
109
+ if (z.ipv4().safeParse(ip).success) return Uint8Array.from(ip.split(".").map((octet) => Number(octet)));
110
+ if (!isIPv6(ip)) return null;
111
+ const mapped = extractIPv4FromMapped(ip);
112
+ if (mapped) return Uint8Array.from(mapped.split(".").map((octet) => Number(octet)));
113
+ const groups = expandIPv6(ip);
114
+ const bytes = new Uint8Array(16);
115
+ for (let i = 0; i < 8; i++) {
116
+ const group = Number.parseInt(groups[i] ?? "0", 16);
117
+ bytes[i * 2] = group >> 8 & 255;
118
+ bytes[i * 2 + 1] = group & 255;
119
+ }
120
+ return bytes;
121
+ }
122
+ const CIDR_PREFIX_PATTERN = /^\d+$/;
123
+ /**
124
+ * Parses an IP or `IP/prefix` string into network bytes and a prefix length.
125
+ * The prefix must be digits only and within the address family. `null` if the
126
+ * value is not a valid IP or CIDR range, which keeps a malformed entry from
127
+ * silently behaving like a non-match.
128
+ */
129
+ function parseCIDR(value) {
130
+ const slash = value.lastIndexOf("/");
131
+ const bytes = ipToBytes(slash === -1 ? value : value.slice(0, slash));
132
+ if (!bytes) return null;
133
+ const maxBits = bytes.length * 8;
134
+ if (slash === -1) return {
135
+ bytes,
136
+ prefix: maxBits
137
+ };
138
+ const prefixPart = value.slice(slash + 1);
139
+ if (!CIDR_PREFIX_PATTERN.test(prefixPart)) return null;
140
+ const prefix = Number(prefixPart);
141
+ return prefix <= maxBits ? {
142
+ bytes,
143
+ prefix
144
+ } : null;
145
+ }
146
+ /**
147
+ * Whether `ipBytes` falls inside an already-parsed CIDR network.
148
+ */
149
+ function matchesCIDR(ipBytes, net) {
150
+ if (ipBytes.length !== net.bytes.length) return false;
151
+ let bitsRemaining = net.prefix;
152
+ for (let i = 0; i < ipBytes.length && bitsRemaining > 0; i++) {
153
+ const take = bitsRemaining >= 8 ? 8 : bitsRemaining;
154
+ const mask = take === 8 ? 255 : 255 << 8 - take & 255;
155
+ if (((ipBytes[i] ?? 0) & mask) !== ((net.bytes[i] ?? 0) & mask)) return false;
156
+ bitsRemaining -= 8;
157
+ }
158
+ return true;
159
+ }
160
+ /**
161
+ * Trusted-proxy entries that are not a valid IP address or CIDR range.
162
+ */
163
+ function findInvalidTrustedProxies(entries) {
164
+ return entries.filter((entry) => parseCIDR(entry) === null);
165
+ }
166
+ /**
167
+ * Resolves the client IP from a forwarded header. The leftmost token is spoofable,
168
+ * so with `trustedProxies` the chain is stripped from the right to the first
169
+ * untrusted hop. Otherwise only a single-value header is trusted. Returns `null`
170
+ * when no trustworthy client IP can be resolved.
171
+ */
172
+ function getIPFromHeader(value, options = {}) {
173
+ const forwardedIps = value.split(",").map((ip) => ip.trim()).filter(Boolean);
174
+ if (forwardedIps.length === 0) return null;
175
+ const trustedProxies = (options.trustedProxies ?? []).map(parseCIDR).filter((proxy) => {
176
+ return proxy !== null;
177
+ });
178
+ if (trustedProxies.length > 0) {
179
+ for (let i = forwardedIps.length - 1; i >= 0; i--) {
180
+ const ip = forwardedIps[i];
181
+ const ipBytes = ip ? ipToBytes(ip) : null;
182
+ if (!ip || !ipBytes) return null;
183
+ if (trustedProxies.some((proxy) => matchesCIDR(ipBytes, proxy))) continue;
184
+ return normalizeIP(ip, { ipv6Subnet: options.ipv6Subnet });
185
+ }
186
+ return null;
187
+ }
188
+ if (forwardedIps.length !== 1) return null;
189
+ const selectedIp = forwardedIps[0];
190
+ if (!selectedIp || !isValidIP(selectedIp)) return null;
191
+ return normalizeIP(selectedIp, { ipv6Subnet: options.ipv6Subnet });
192
+ }
193
+ const LOCALHOST_IP = "127.0.0.1";
194
+ const DEFAULT_IP_HEADERS = ["x-forwarded-for"];
195
+ /**
196
+ * Resolves the client IP for a request from the configured IP headers.
197
+ * Honors `disableIpTracking`, walks `ipAddressHeaders` in order (default
198
+ * `x-forwarded-for`), and falls back to localhost in development and test.
199
+ * Returns `null` when tracking is disabled or no trustworthy IP can be resolved.
200
+ */
201
+ function getIP(req, options) {
202
+ if (options.advanced?.ipAddress?.disableIpTracking) return null;
203
+ const headers = "headers" in req ? req.headers : req;
204
+ const ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;
205
+ for (const key of ipHeaders) {
206
+ const value = "get" in headers ? headers.get(key) : headers[key];
207
+ if (typeof value === "string") {
208
+ const ip = getIPFromHeader(value, {
209
+ ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet,
210
+ trustedProxies: options.advanced?.ipAddress?.trustedProxies
211
+ });
212
+ if (ip) return ip;
213
+ }
214
+ }
215
+ if (isTest() || isDevelopment()) return LOCALHOST_IP;
216
+ return null;
103
217
  }
104
218
  /**
105
219
  * Creates a rate limit key from IP and path
@@ -113,4 +227,4 @@ function createRateLimitKey(ip, path) {
113
227
  return `${ip}|${path}`;
114
228
  }
115
229
  //#endregion
116
- export { createRateLimitKey, isValidIP, normalizeIP };
230
+ export { createRateLimitKey, findInvalidTrustedProxies, getIP, getIPFromHeader, isValidIP, normalizeIP };
@@ -0,0 +1,6 @@
1
+ import { APIError } from "../error/index.mjs";
2
+
3
+ //#region src/utils/is-api-error.d.ts
4
+ declare function isAPIError(error: unknown): error is APIError;
5
+ //#endregion
6
+ export { isAPIError };
@@ -0,0 +1,8 @@
1
+ import { APIError as APIError$1 } from "../error/index.mjs";
2
+ import { APIError } from "better-call";
3
+ //#region src/utils/is-api-error.ts
4
+ function isAPIError(error) {
5
+ return error instanceof APIError || error instanceof APIError$1 || error?.name === "APIError";
6
+ }
7
+ //#endregion
8
+ export { isAPIError };