@better-auth/core 1.6.5 → 1.6.7
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.
- package/dist/api/index.mjs +29 -3
- package/dist/context/global.mjs +1 -1
- package/dist/db/adapter/factory.mjs +1 -1
- package/dist/instrumentation/api.mjs +12 -0
- package/dist/instrumentation/noop.mjs +42 -0
- package/dist/instrumentation/pure.index.d.mts +7 -0
- package/dist/instrumentation/pure.index.mjs +7 -0
- package/dist/instrumentation/tracer.mjs +6 -3
- package/dist/oauth2/index.d.mts +2 -2
- package/dist/oauth2/index.mjs +2 -2
- package/dist/oauth2/utils.d.mts +10 -1
- package/dist/oauth2/utils.mjs +13 -1
- package/dist/social-providers/apple.d.mts +11 -2
- package/dist/social-providers/apple.mjs +7 -1
- package/dist/social-providers/atlassian.mjs +1 -1
- package/dist/social-providers/cognito.d.mts +1 -1
- package/dist/social-providers/cognito.mjs +3 -2
- package/dist/social-providers/facebook.d.mts +1 -1
- package/dist/social-providers/facebook.mjs +7 -0
- package/dist/social-providers/figma.mjs +1 -1
- package/dist/social-providers/google.d.mts +1 -1
- package/dist/social-providers/google.mjs +3 -2
- package/dist/social-providers/microsoft-entra-id.d.mts +2 -2
- package/dist/social-providers/microsoft-entra-id.mjs +6 -1
- package/dist/social-providers/paybin.mjs +1 -1
- package/dist/social-providers/paypal.mjs +1 -1
- package/dist/social-providers/salesforce.mjs +1 -1
- package/dist/utils/async.d.mts +22 -0
- package/dist/utils/async.mjs +32 -0
- package/dist/utils/host.d.mts +147 -0
- package/dist/utils/host.mjs +291 -0
- package/dist/utils/is-api-error.d.mts +6 -0
- package/dist/utils/is-api-error.mjs +8 -0
- package/package.json +10 -1
- package/src/api/index.ts +39 -5
- package/src/instrumentation/api.ts +17 -0
- package/src/instrumentation/noop.ts +74 -0
- package/src/instrumentation/pure.index.ts +31 -0
- package/src/instrumentation/tracer.ts +8 -3
- package/src/oauth2/index.ts +5 -1
- package/src/oauth2/utils.ts +13 -0
- package/src/social-providers/apple.ts +10 -2
- package/src/social-providers/cognito.ts +3 -2
- package/src/social-providers/facebook.ts +10 -1
- package/src/social-providers/google.ts +3 -2
- package/src/social-providers/microsoft-entra-id.ts +13 -3
- package/src/utils/async.ts +53 -0
- package/src/utils/host.ts +401 -0
- package/src/utils/is-api-error.ts +10 -0
|
@@ -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/8, 192.0.0/24, 240/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,291 @@
|
|
|
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("240.0.0.0"), 4)) return "reserved";
|
|
90
|
+
return "public";
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Extract an IPv4 address embedded in an expanded IPv6 literal.
|
|
94
|
+
*
|
|
95
|
+
* Used to recurse into tunnel/translation forms (6to4, NAT64, Teredo) so a
|
|
96
|
+
* private destination cannot be smuggled behind a syntactically-public IPv6
|
|
97
|
+
* literal. `startGroup` is the index of the first of two 16-bit groups in the
|
|
98
|
+
* expanded form (`0000:0000:...`). With `xor: true`, the 32-bit value is XORed
|
|
99
|
+
* with `0xffffffff` before decoding (Teredo obfuscates the client IPv4 this
|
|
100
|
+
* way).
|
|
101
|
+
*/
|
|
102
|
+
function extractEmbeddedIPv4(expanded, startGroup, options = {}) {
|
|
103
|
+
const offset = startGroup * 5;
|
|
104
|
+
const g1 = Number.parseInt(expanded.slice(offset, offset + 4), 16);
|
|
105
|
+
const g2 = Number.parseInt(expanded.slice(offset + 5, offset + 9), 16);
|
|
106
|
+
if (!Number.isFinite(g1) || !Number.isFinite(g2)) return null;
|
|
107
|
+
let combined = (g1 << 16 | g2) >>> 0;
|
|
108
|
+
if (options.xor) combined = (combined ^ 4294967295) >>> 0;
|
|
109
|
+
return `${combined >>> 24 & 255}.${combined >>> 16 & 255}.${combined >>> 8 & 255}.${combined & 255}`;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Classify an expanded, full-form, lowercase IPv6 address (no IPv4-mapped
|
|
113
|
+
* input — those are unmapped to IPv4 before reaching here).
|
|
114
|
+
*
|
|
115
|
+
* 6to4 (`2002::/16`), NAT64 (`64:ff9b::/96`) and Teredo (`2001:0000::/32`)
|
|
116
|
+
* embed an IPv4 that can route to private/loopback space. If the embedded
|
|
117
|
+
* IPv4 classifies as non-`public`, return `reserved` — blocks SSRF without
|
|
118
|
+
* advertising the address as a loopback literal for RFC 8252 §7.3 matching.
|
|
119
|
+
*/
|
|
120
|
+
function classifyIPv6(expanded) {
|
|
121
|
+
if (expanded === "0000:0000:0000:0000:0000:0000:0000:0000") return "unspecified";
|
|
122
|
+
if (expanded === "0000:0000:0000:0000:0000:0000:0000:0001") return "loopback";
|
|
123
|
+
const firstByte = Number.parseInt(expanded.slice(0, 2), 16);
|
|
124
|
+
const secondByte = Number.parseInt(expanded.slice(2, 4), 16);
|
|
125
|
+
if (firstByte === 255) return "multicast";
|
|
126
|
+
if (firstByte === 254 && (secondByte & 192) === 128) return "linkLocal";
|
|
127
|
+
if ((firstByte & 254) === 252) return "private";
|
|
128
|
+
if (expanded.startsWith("2001:0db8:")) return "documentation";
|
|
129
|
+
if (expanded.startsWith("2002:")) {
|
|
130
|
+
const embedded = extractEmbeddedIPv4(expanded, 1);
|
|
131
|
+
if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
|
|
132
|
+
return "public";
|
|
133
|
+
}
|
|
134
|
+
if (expanded.startsWith("0064:ff9b:0000:0000:0000:0000:")) {
|
|
135
|
+
const embedded = extractEmbeddedIPv4(expanded, 6);
|
|
136
|
+
if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
|
|
137
|
+
return "reserved";
|
|
138
|
+
}
|
|
139
|
+
if (expanded.startsWith("2001:0000:")) {
|
|
140
|
+
const embedded = extractEmbeddedIPv4(expanded, 6, { xor: true });
|
|
141
|
+
if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
|
|
142
|
+
return "reserved";
|
|
143
|
+
}
|
|
144
|
+
if (expanded.startsWith("0100:0000:0000:0000:")) return "reserved";
|
|
145
|
+
return "public";
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Classify a host string according to RFC 6890 / RFC 6761.
|
|
149
|
+
*
|
|
150
|
+
* Accepts inputs in any of these shapes and normalizes before classifying:
|
|
151
|
+
*
|
|
152
|
+
* - Bare IPv4: `127.0.0.1`
|
|
153
|
+
* - Bare IPv6: `::1`, `fe80::1%eth0`
|
|
154
|
+
* - Bracketed IPv6: `[::1]`
|
|
155
|
+
* - Host with port: `localhost:3000`, `127.0.0.1:443`, `[::1]:8080`
|
|
156
|
+
* - FQDN: `example.com`, `tenant.localhost`
|
|
157
|
+
* - IPv4-mapped IPv6: `::ffff:192.0.2.1` (reported as `literal: "ipv4"`)
|
|
158
|
+
*
|
|
159
|
+
* Invalid or non-resolvable FQDNs are returned as `{ kind: "public", literal: "fqdn" }`
|
|
160
|
+
* — this function never throws. Callers that need structural validation must
|
|
161
|
+
* combine this with a URL/hostname validator upstream.
|
|
162
|
+
*
|
|
163
|
+
* @example
|
|
164
|
+
* classifyHost("127.0.0.1")
|
|
165
|
+
* // { kind: "loopback", literal: "ipv4", canonical: "127.0.0.1" }
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* classifyHost("[::1]:8080")
|
|
169
|
+
* // { kind: "loopback", literal: "ipv6", canonical: "0000:0000:...:0001" }
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* classifyHost("::ffff:192.0.2.1")
|
|
173
|
+
* // { kind: "documentation", literal: "ipv4", canonical: "192.0.2.1" }
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* classifyHost("tenant-a.localhost")
|
|
177
|
+
* // { kind: "localhost", literal: "fqdn", canonical: "tenant-a.localhost" }
|
|
178
|
+
*/
|
|
179
|
+
function classifyHost(host) {
|
|
180
|
+
const lowered = stripTrailingDot(stripZoneId(stripBrackets(stripPort(host.trim())))).toLowerCase();
|
|
181
|
+
if (lowered === "") return {
|
|
182
|
+
kind: "reserved",
|
|
183
|
+
literal: "fqdn",
|
|
184
|
+
canonical: ""
|
|
185
|
+
};
|
|
186
|
+
if (!isValidIP(lowered)) {
|
|
187
|
+
if (lowered === "localhost" || lowered.endsWith(".localhost")) return {
|
|
188
|
+
kind: "localhost",
|
|
189
|
+
literal: "fqdn",
|
|
190
|
+
canonical: lowered
|
|
191
|
+
};
|
|
192
|
+
if (CLOUD_METADATA_HOSTS.has(lowered)) return {
|
|
193
|
+
kind: "cloudMetadata",
|
|
194
|
+
literal: "fqdn",
|
|
195
|
+
canonical: lowered
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
kind: "public",
|
|
199
|
+
literal: "fqdn",
|
|
200
|
+
canonical: lowered
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
if (looksLikeIPv4(lowered)) return {
|
|
204
|
+
kind: classifyIPv4(lowered),
|
|
205
|
+
literal: "ipv4",
|
|
206
|
+
canonical: lowered
|
|
207
|
+
};
|
|
208
|
+
const canonical = normalizeIP(lowered, { ipv6Subnet: 128 });
|
|
209
|
+
if (looksLikeIPv4(canonical)) return {
|
|
210
|
+
kind: classifyIPv4(canonical),
|
|
211
|
+
literal: "ipv4",
|
|
212
|
+
canonical
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
kind: classifyIPv6(canonical),
|
|
216
|
+
literal: "ipv6",
|
|
217
|
+
canonical
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Strict loopback-IP-literal check per RFC 8252 §7.3.
|
|
222
|
+
*
|
|
223
|
+
* Returns true ONLY for IPv4 `127.0.0.0/8` or IPv6 `::1`. The DNS name
|
|
224
|
+
* `localhost` returns false — RFC 8252 §8.3 explicitly recommends against
|
|
225
|
+
* relying on name resolution for loopback redirect URIs.
|
|
226
|
+
*
|
|
227
|
+
* Use this for OAuth redirect URI matching.
|
|
228
|
+
*
|
|
229
|
+
* @example
|
|
230
|
+
* isLoopbackIP("127.0.0.1") // true
|
|
231
|
+
* isLoopbackIP("::1") // true
|
|
232
|
+
* isLoopbackIP("[::1]:8080") // true
|
|
233
|
+
* isLoopbackIP("localhost") // false (use isLoopbackHost for DNS names)
|
|
234
|
+
* isLoopbackIP("0.0.0.0") // false (unspecified, not loopback)
|
|
235
|
+
*/
|
|
236
|
+
function isLoopbackIP(host) {
|
|
237
|
+
return classifyHost(host).kind === "loopback";
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Permissive loopback check for developer-ergonomics code paths.
|
|
241
|
+
*
|
|
242
|
+
* Returns true for IPv4 `127.0.0.0/8`, IPv6 `::1`, the literal name `localhost`,
|
|
243
|
+
* and any RFC 6761 `.localhost` subdomain (`tenant.localhost`, `app.localhost`).
|
|
244
|
+
*
|
|
245
|
+
* Use this for things like: allowing HTTP for dev servers, skipping Secure
|
|
246
|
+
* cookie requirements, browser-trust heuristics. Do NOT use this for OAuth
|
|
247
|
+
* redirect URI matching — use {@link isLoopbackIP} there.
|
|
248
|
+
*
|
|
249
|
+
* @example
|
|
250
|
+
* isLoopbackHost("localhost") // true
|
|
251
|
+
* isLoopbackHost("tenant.localhost") // true (RFC 6761)
|
|
252
|
+
* isLoopbackHost("127.0.0.1") // true
|
|
253
|
+
* isLoopbackHost("0.0.0.0") // false (unspecified, NOT loopback)
|
|
254
|
+
*/
|
|
255
|
+
function isLoopbackHost(host) {
|
|
256
|
+
const kind = classifyHost(host).kind;
|
|
257
|
+
return kind === "loopback" || kind === "localhost";
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* First-line SSRF gate: returns true ONLY for hosts that classify as `public`.
|
|
261
|
+
*
|
|
262
|
+
* Every RFC 6890 special-purpose range (loopback, private, link-local,
|
|
263
|
+
* unspecified, documentation, multicast, broadcast, reserved, shared address
|
|
264
|
+
* space, benchmarking) and cloud-metadata FQDN returns false.
|
|
265
|
+
*
|
|
266
|
+
* Use this BEFORE issuing a server-side fetch to a user-supplied URL, e.g.
|
|
267
|
+
* OAuth introspection endpoints, webhook targets, or metadata-document
|
|
268
|
+
* fetches (CIMD).
|
|
269
|
+
*
|
|
270
|
+
* Limitations (this is a syntactic check, not a complete SSRF mitigation):
|
|
271
|
+
* - No DNS resolution: a public-looking FQDN that resolves to a private IP
|
|
272
|
+
* passes this check. Re-verify the resolved address before connecting, or
|
|
273
|
+
* pin the socket to the resolved IP.
|
|
274
|
+
* - No DNS-rebinding defense: attackers can return a public IP on the first
|
|
275
|
+
* lookup and a private IP on the second. Resolve once and reuse the IP.
|
|
276
|
+
* - No redirect following: HTTP 3xx responses can redirect to private hosts.
|
|
277
|
+
* Re-run this check on every redirect target, or disable auto-follow.
|
|
278
|
+
*
|
|
279
|
+
* @example
|
|
280
|
+
* isPublicRoutableHost("example.com") // true
|
|
281
|
+
* isPublicRoutableHost("127.0.0.1") // false (loopback)
|
|
282
|
+
* isPublicRoutableHost("169.254.169.254") // false (linkLocal / AWS IMDS)
|
|
283
|
+
* isPublicRoutableHost("metadata.google.internal") // false (cloudMetadata)
|
|
284
|
+
* isPublicRoutableHost("10.0.0.1") // false (private)
|
|
285
|
+
* isPublicRoutableHost("::ffff:127.0.0.1") // false (mapped loopback)
|
|
286
|
+
*/
|
|
287
|
+
function isPublicRoutableHost(host) {
|
|
288
|
+
return classifyHost(host).kind === "public";
|
|
289
|
+
}
|
|
290
|
+
//#endregion
|
|
291
|
+
export { classifyHost, isLoopbackHost, isLoopbackIP, isPublicRoutableHost };
|
|
@@ -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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@better-auth/core",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.7",
|
|
4
4
|
"description": "The most comprehensive authentication framework for TypeScript.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -93,6 +93,12 @@
|
|
|
93
93
|
"./instrumentation": {
|
|
94
94
|
"dev-source": "./src/instrumentation/index.ts",
|
|
95
95
|
"types": "./dist/instrumentation/index.d.mts",
|
|
96
|
+
"node": "./dist/instrumentation/index.mjs",
|
|
97
|
+
"deno": "./dist/instrumentation/index.mjs",
|
|
98
|
+
"bun": "./dist/instrumentation/index.mjs",
|
|
99
|
+
"edge": "./dist/instrumentation/pure.index.mjs",
|
|
100
|
+
"workerd": "./dist/instrumentation/index.mjs",
|
|
101
|
+
"browser": "./dist/instrumentation/pure.index.mjs",
|
|
96
102
|
"default": "./dist/instrumentation/index.mjs"
|
|
97
103
|
}
|
|
98
104
|
},
|
|
@@ -170,6 +176,9 @@
|
|
|
170
176
|
"peerDependenciesMeta": {
|
|
171
177
|
"@cloudflare/workers-types": {
|
|
172
178
|
"optional": true
|
|
179
|
+
},
|
|
180
|
+
"@opentelemetry/api": {
|
|
181
|
+
"optional": true
|
|
173
182
|
}
|
|
174
183
|
},
|
|
175
184
|
"scripts": {
|
package/src/api/index.ts
CHANGED
|
@@ -3,9 +3,34 @@ import type {
|
|
|
3
3
|
EndpointOptions,
|
|
4
4
|
StrictEndpoint,
|
|
5
5
|
} from "better-call";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
createEndpoint,
|
|
8
|
+
createMiddleware,
|
|
9
|
+
kAPIErrorHeaderSymbol,
|
|
10
|
+
} from "better-call";
|
|
7
11
|
import { runWithEndpointContext } from "../context";
|
|
8
12
|
import type { AuthContext } from "../types";
|
|
13
|
+
import { isAPIError } from "../utils/is-api-error";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Better-call's createEndpoint re-throws APIError without exposing the headers
|
|
17
|
+
* accumulated on ctx.responseHeaders (e.g. Set-Cookie from deleteSessionCookie
|
|
18
|
+
* before throw). Attach them to the error via kAPIErrorHeaderSymbol — matching
|
|
19
|
+
* better-call's createMiddleware contract so the outer pipeline can merge them
|
|
20
|
+
* into the response.
|
|
21
|
+
*/
|
|
22
|
+
function attachResponseHeadersToAPIError(
|
|
23
|
+
responseHeaders: Headers | undefined,
|
|
24
|
+
e: unknown,
|
|
25
|
+
): void {
|
|
26
|
+
if (!isAPIError(e) || !responseHeaders) return;
|
|
27
|
+
Object.defineProperty(e, kAPIErrorHeaderSymbol, {
|
|
28
|
+
enumerable: false,
|
|
29
|
+
configurable: true,
|
|
30
|
+
value: responseHeaders,
|
|
31
|
+
writable: false,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
9
34
|
|
|
10
35
|
export const optionsMiddleware = createMiddleware(async () => {
|
|
11
36
|
/**
|
|
@@ -76,6 +101,17 @@ export function createAuthEndpoint<
|
|
|
76
101
|
const handler: EndpointHandler<Path, Opts, R> =
|
|
77
102
|
typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever;
|
|
78
103
|
|
|
104
|
+
// todo: prettify the code, we want to call `runWithEndpointContext` to top level
|
|
105
|
+
const wrapped: EndpointHandler<Path, Opts, R> = async (ctx) => {
|
|
106
|
+
const runtimeCtx = ctx as unknown as { responseHeaders?: Headers };
|
|
107
|
+
try {
|
|
108
|
+
return await runWithEndpointContext(ctx as any, () => handler(ctx));
|
|
109
|
+
} catch (e) {
|
|
110
|
+
attachResponseHeadersToAPIError(runtimeCtx.responseHeaders, e);
|
|
111
|
+
throw e;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
79
115
|
if (path) {
|
|
80
116
|
return createEndpoint(
|
|
81
117
|
path,
|
|
@@ -83,8 +119,7 @@ export function createAuthEndpoint<
|
|
|
83
119
|
...options,
|
|
84
120
|
use: [...(options?.use || []), ...use],
|
|
85
121
|
},
|
|
86
|
-
|
|
87
|
-
async (ctx) => runWithEndpointContext(ctx as any, () => handler(ctx)),
|
|
122
|
+
wrapped,
|
|
88
123
|
);
|
|
89
124
|
}
|
|
90
125
|
|
|
@@ -93,8 +128,7 @@ export function createAuthEndpoint<
|
|
|
93
128
|
...options,
|
|
94
129
|
use: [...(options?.use || []), ...use],
|
|
95
130
|
},
|
|
96
|
-
|
|
97
|
-
async (ctx) => runWithEndpointContext(ctx as any, () => handler(ctx)),
|
|
131
|
+
wrapped,
|
|
98
132
|
);
|
|
99
133
|
}
|
|
100
134
|
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { OpenTelemetryAPI } from "./noop";
|
|
2
|
+
import { noopOpenTelemetryAPI } from "./noop";
|
|
3
|
+
|
|
4
|
+
let openTelemetryAPIPromise: Promise<void> | undefined;
|
|
5
|
+
let openTelemetryAPI: OpenTelemetryAPI | undefined;
|
|
6
|
+
|
|
7
|
+
export function getOpenTelemetryAPI(): OpenTelemetryAPI {
|
|
8
|
+
if (!openTelemetryAPIPromise) {
|
|
9
|
+
openTelemetryAPIPromise = import("@opentelemetry/api")
|
|
10
|
+
.then((mod) => {
|
|
11
|
+
openTelemetryAPI = mod;
|
|
12
|
+
})
|
|
13
|
+
.catch(() => /* ignore failures */ undefined);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return openTelemetryAPI ?? noopOpenTelemetryAPI;
|
|
17
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Span, Tracer } from "@opentelemetry/api";
|
|
2
|
+
|
|
3
|
+
export type OpenTelemetryAPI = Pick<
|
|
4
|
+
typeof import("@opentelemetry/api"),
|
|
5
|
+
"trace" | "SpanStatusCode"
|
|
6
|
+
>;
|
|
7
|
+
|
|
8
|
+
function createNoopSpan(): Span {
|
|
9
|
+
const span = {
|
|
10
|
+
end(): void {},
|
|
11
|
+
setAttribute(_key: string, _value: unknown): void {},
|
|
12
|
+
setStatus(_status: unknown): void {},
|
|
13
|
+
recordException(_exception: unknown): void {},
|
|
14
|
+
updateName(_name: string) {
|
|
15
|
+
return span;
|
|
16
|
+
},
|
|
17
|
+
} as unknown as Span;
|
|
18
|
+
return span;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function createNoopTracer(noopSpan: Span): Tracer {
|
|
22
|
+
// OpenTelemetry `Tracer.startActiveSpan` has three overloads:
|
|
23
|
+
// (name, fn)
|
|
24
|
+
// (name, options, fn)
|
|
25
|
+
// (name, options, context, fn)
|
|
26
|
+
// The callback is always the last argument; fish it out by arity so a
|
|
27
|
+
// 2-arg call (options omitted) doesn't try to invoke `undefined`.
|
|
28
|
+
function startActiveSpan<F extends (span: Span) => unknown>(
|
|
29
|
+
_name: string,
|
|
30
|
+
fn: F,
|
|
31
|
+
): ReturnType<F>;
|
|
32
|
+
function startActiveSpan<F extends (span: Span) => unknown>(
|
|
33
|
+
_name: string,
|
|
34
|
+
_options: { attributes?: Record<string, string | number | boolean> },
|
|
35
|
+
fn: F,
|
|
36
|
+
): ReturnType<F>;
|
|
37
|
+
function startActiveSpan<F extends (span: Span) => unknown>(
|
|
38
|
+
_name: string,
|
|
39
|
+
_options: { attributes?: Record<string, string | number | boolean> },
|
|
40
|
+
_context: unknown,
|
|
41
|
+
fn: F,
|
|
42
|
+
): ReturnType<F>;
|
|
43
|
+
function startActiveSpan(_name: string, ...rest: Array<unknown>): unknown {
|
|
44
|
+
const fn = rest[rest.length - 1] as (span: Span) => unknown;
|
|
45
|
+
return fn(noopSpan);
|
|
46
|
+
}
|
|
47
|
+
return { startActiveSpan } as Tracer;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function createNoopTraceAPI() {
|
|
51
|
+
const noopTracer = createNoopTracer(createNoopSpan());
|
|
52
|
+
return {
|
|
53
|
+
getTracer(_name?: string, _version?: string) {
|
|
54
|
+
return noopTracer;
|
|
55
|
+
},
|
|
56
|
+
getActiveSpan(): Span | undefined {
|
|
57
|
+
return undefined;
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function createNoopOpenTelemetryAPI(): OpenTelemetryAPI {
|
|
63
|
+
return {
|
|
64
|
+
SpanStatusCode: {
|
|
65
|
+
UNSET: 0,
|
|
66
|
+
OK: 1,
|
|
67
|
+
ERROR: 2,
|
|
68
|
+
},
|
|
69
|
+
trace: createNoopTraceAPI(),
|
|
70
|
+
} as OpenTelemetryAPI;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const noopOpenTelemetryAPI: OpenTelemetryAPI =
|
|
74
|
+
createNoopOpenTelemetryAPI();
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Noop variant of `./instrumentation` for runtimes where the dynamic
|
|
3
|
+
* `import("@opentelemetry/api")` in `./api` throws synchronously instead of
|
|
4
|
+
* rejecting its returned promise. Convex's V8 isolate is the reproducer: bare
|
|
5
|
+
* specifiers are rejected at resolve time in `get-convex/convex-backend`
|
|
6
|
+
* `crates/isolate/src/request_scope.rs`, so the `.catch()` in
|
|
7
|
+
* `getOpenTelemetryAPI` never runs and every `withSpan` call surfaces an
|
|
8
|
+
* uncaught error.
|
|
9
|
+
*
|
|
10
|
+
* Public surface must stay identical to `./index` (enforced by `pure.test.ts`).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export * from "./attributes";
|
|
14
|
+
|
|
15
|
+
export function withSpan<T>(
|
|
16
|
+
name: string,
|
|
17
|
+
attributes: Record<string, string | number | boolean>,
|
|
18
|
+
fn: () => T,
|
|
19
|
+
): T;
|
|
20
|
+
export function withSpan<T>(
|
|
21
|
+
name: string,
|
|
22
|
+
attributes: Record<string, string | number | boolean>,
|
|
23
|
+
fn: () => Promise<T>,
|
|
24
|
+
): Promise<T>;
|
|
25
|
+
export function withSpan<T>(
|
|
26
|
+
_name: string,
|
|
27
|
+
_attributes: Record<string, string | number | boolean>,
|
|
28
|
+
fn: () => T | Promise<T>,
|
|
29
|
+
): T | Promise<T> {
|
|
30
|
+
return fn();
|
|
31
|
+
}
|