@atproto-labs/fetch-node 0.3.3 → 0.3.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @atproto-labs/fetch-node
2
2
 
3
+ ## 0.3.4
4
+
5
+ ### Patch Changes
6
+
7
+ - [#5099](https://github.com/bluesky-social/atproto/pull/5099) [`b43ec31`](https://github.com/bluesky-social/atproto/commit/b43ec31f247f4461725b01226885f88bd430ca07) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Update TypeScript build to rely on references to composite internal projects
8
+
9
+ - [#5099](https://github.com/bluesky-social/atproto/pull/5099) [`b43ec31`](https://github.com/bluesky-social/atproto/commit/b43ec31f247f4461725b01226885f88bd430ca07) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Bundle only necessary files in the NPM tarball, including the `CHANGELOG.md` and `README.md` files (if present).
10
+
11
+ - Updated dependencies [[`b43ec31`](https://github.com/bluesky-social/atproto/commit/b43ec31f247f4461725b01226885f88bd430ca07), [`b43ec31`](https://github.com/bluesky-social/atproto/commit/b43ec31f247f4461725b01226885f88bd430ca07)]:
12
+ - @atproto-labs/fetch@0.3.3
13
+ - @atproto-labs/pipe@0.2.3
14
+
3
15
  ## 0.3.3
4
16
 
5
17
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto-labs/fetch-node",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "license": "MIT",
5
5
  "description": "SSRF protection for fetch() in Node.js",
6
6
  "keywords": [
@@ -14,6 +14,10 @@
14
14
  "url": "https://github.com/bluesky-social/atproto",
15
15
  "directory": "packages/internal/fetch-node"
16
16
  },
17
+ "files": [
18
+ "./dist",
19
+ "./CHANGELOG.md"
20
+ ],
17
21
  "type": "module",
18
22
  "exports": {
19
23
  ".": {
@@ -29,8 +33,8 @@
29
33
  "undici_v6": "npm:undici@^6.x",
30
34
  "undici_v7": "npm:undici@^7.x",
31
35
  "undici_v8": "npm:undici@^8.x",
32
- "@atproto-labs/fetch": "^0.3.2",
33
- "@atproto-labs/pipe": "^0.2.2"
36
+ "@atproto-labs/fetch": "^0.3.3",
37
+ "@atproto-labs/pipe": "^0.2.3"
34
38
  },
35
39
  "devDependencies": {
36
40
  "vitest": "^4.0.16"
package/src/index.ts DELETED
@@ -1,10 +0,0 @@
1
- export * from '@atproto-labs/fetch'
2
-
3
- export * from './safe.js'
4
- export * from './unicast.js'
5
-
6
- export {
7
- isUnicastIpHostname,
8
- /** @deprecated use {@link isUnicastIpHostname} instead */
9
- isUnicastIpHostname as isUnicastIp,
10
- } from './util.js'
package/src/safe.ts DELETED
@@ -1,117 +0,0 @@
1
- import {
2
- DEFAULT_FORBIDDEN_DOMAIN_NAMES,
3
- Fetch,
4
- asRequest,
5
- explicitRedirectCheckRequestTransform,
6
- fetchMaxSizeProcessor,
7
- forbiddenDomainNameRequestTransform,
8
- protocolCheckRequestTransform,
9
- requireHostHeaderTransform,
10
- timedFetch,
11
- } from '@atproto-labs/fetch'
12
- import { pipe } from '@atproto-labs/pipe'
13
- import { UnicastFetchWrapOptions, unicastFetchWrap } from './unicast.js'
14
-
15
- export type SafeFetchWrapOptions<C> = UnicastFetchWrapOptions<C> & {
16
- responseMaxSize?: number
17
- ssrfProtection?: boolean
18
- allowCustomPort?: boolean
19
- allowData?: boolean
20
- allowHttp?: boolean
21
- allowIpHost?: boolean
22
- allowPrivateIps?: boolean
23
- timeout?: number
24
- forbiddenDomainNames?: Iterable<string>
25
- /**
26
- * When `false`, a {@link RequestInit['redirect']} value must be explicitly
27
- * provided as second argument to the returned function or requests will fail.
28
- *
29
- * @default false
30
- */
31
- allowImplicitRedirect?: boolean
32
- }
33
-
34
- /**
35
- * Wrap a fetch function with safety checks so that it can be safely used
36
- * with user provided input (URL).
37
- *
38
- * @see {@link https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html}
39
- *
40
- * @note When {@link SafeFetchWrapOptions.allowImplicitRedirect} is `false`
41
- * (default), then the returned function **must** be called setting the second
42
- * argument's `redirect` property to one of the allowed values. Otherwise, if
43
- * the returned fetch function is called with a `Request` object (and no
44
- * explicit `redirect` init object), then the verification code will not be able
45
- * to determine if the `redirect` property was explicitly set or based on the
46
- * default value (`follow`), causing it to preventively block the request (throw
47
- * an error). For this reason, unless you set
48
- * {@link SafeFetchWrapOptions.allowImplicitRedirect} to `true`, you should
49
- * **not** wrap the returned function into another function that creates a
50
- * {@link Request} object before passing it to the function (as a e.g. a logging
51
- * function would).
52
- */
53
- export function safeFetchWrap<C>({
54
- fetch = globalThis.fetch as Fetch<C>,
55
- responseMaxSize = 512 * 1024, // 512kB
56
- ssrfProtection = true,
57
- allowCustomPort = !ssrfProtection,
58
- allowData = false,
59
- allowHttp = !ssrfProtection,
60
- allowIpHost = true,
61
- allowPrivateIps = !ssrfProtection,
62
- timeout = 10e3,
63
- forbiddenDomainNames = DEFAULT_FORBIDDEN_DOMAIN_NAMES as Iterable<string>,
64
- allowImplicitRedirect = false,
65
- }: SafeFetchWrapOptions<C> = {}) {
66
- return pipe(
67
- /**
68
- * Require explicit {@link RequestInit['redirect']} mode
69
- */
70
- allowImplicitRedirect ? asRequest : explicitRedirectCheckRequestTransform(),
71
-
72
- /**
73
- * Only requests that will be issued with a "Host" header are allowed.
74
- */
75
- allowIpHost ? asRequest : requireHostHeaderTransform(),
76
-
77
- /**
78
- * Prevent using http:, file: or data: protocols.
79
- */
80
- protocolCheckRequestTransform({
81
- 'about:': false,
82
- 'data:': allowData,
83
- 'file:': false,
84
- 'http:': allowHttp && { allowCustomPort },
85
- 'https:': { allowCustomPort },
86
- }),
87
-
88
- /**
89
- * Disallow fetching from domains we know are not atproto/OIDC client
90
- * implementation. Note that other domains can be blocked by providing a
91
- * custom fetch function combined with another
92
- * forbiddenDomainNameRequestTransform.
93
- */
94
- forbiddenDomainNameRequestTransform(forbiddenDomainNames),
95
-
96
- /**
97
- * Since we will be fetching from the network based on user provided
98
- * input, let's mitigate resource exhaustion attacks by setting a timeout.
99
- */
100
- timedFetch(
101
- timeout,
102
-
103
- /**
104
- * Since we will be fetching from the network based on user provided
105
- * input, we need to make sure that the request is not vulnerable to SSRF
106
- * attacks.
107
- */
108
- allowPrivateIps ? fetch : unicastFetchWrap({ fetch }),
109
- ),
110
-
111
- /**
112
- * Since we will be fetching user owned data, we need to make sure that an
113
- * attacker cannot force us to download a large amounts of data.
114
- */
115
- fetchMaxSizeProcessor(responseMaxSize),
116
- ) satisfies Fetch<unknown>
117
- }
@@ -1,135 +0,0 @@
1
- import { assert, describe, expect, it, vi } from 'vitest'
2
- import { unicastFetchWrap, unicastLookup } from './unicast.js'
3
-
4
- vi.mock(import('node:dns'), async (importOriginal) => {
5
- const dns = await importOriginal()
6
- return {
7
- ...dns,
8
- lookup: ((hostname, options, callback) => {
9
- if (hostname === 'invalid.com') {
10
- setTimeout(callback, 0, null, '127.2.2.2', 4)
11
- return
12
- }
13
-
14
- if (hostname === 'valid.com') {
15
- setTimeout(callback, 0, null, '1.2.3.4', 4)
16
- return
17
- }
18
-
19
- // @ts-ignore
20
- return dns.lookup(hostname, options, callback)
21
- }) as typeof dns.lookup,
22
- }
23
- })
24
-
25
- describe(unicastLookup, () => {
26
- it('should reject hostnames that resolve to private IPs', async () => {
27
- await expect(
28
- new Promise((resolve, reject) => {
29
- unicastLookup('invalid.com', { all: true }, (err, address, family) => {
30
- if (err) {
31
- reject(err)
32
- } else {
33
- resolve({ address, family })
34
- }
35
- })
36
- }),
37
- ).rejects.toThrow('Hostname resolved to non-unicast address')
38
- })
39
-
40
- it('should allow hostnames that resolve to public IPs', async () => {
41
- await expect(
42
- new Promise((resolve, reject) => {
43
- unicastLookup('valid.com', { all: true }, (err, address, family) => {
44
- if (err) {
45
- reject(err)
46
- } else {
47
- resolve({ address, family })
48
- }
49
- })
50
- }),
51
- ).resolves.toEqual({ address: '1.2.3.4', family: 4 })
52
- })
53
- })
54
-
55
- describe(unicastFetchWrap, () => {
56
- describe('expected failures', () => {
57
- it('should reject private IPv4 hostnames', async () => {
58
- const fetch = unicastFetchWrap()
59
- await expect(fetch('http://127.0.0.1/test')).rejects.toSatisfy(
60
- fetchFailedErrorCauseBy('Hostname is a non-unicast address'),
61
- )
62
- })
63
-
64
- it('should reject private IPv6 hostnames', async () => {
65
- const fetch = unicastFetchWrap()
66
- await expect(fetch('http://[::1]/test')).rejects.toSatisfy(
67
- fetchFailedErrorCauseBy('Hostname is a non-unicast address'),
68
- )
69
- })
70
-
71
- it('should reject hostnames that are not public domain tlds', async () => {
72
- const fetch = unicastFetchWrap()
73
- await expect(fetch('http://localhost/test')).rejects.toSatisfy(
74
- fetchFailedErrorCauseBy('Hostname is not a public domain'),
75
- )
76
-
77
- await expect(fetch('https://printer.local')).rejects.toSatisfy(
78
- fetchFailedErrorCauseBy('Hostname is not a public domain'),
79
- )
80
- })
81
-
82
- it('should reject hostnames that resolve to private IPs', async () => {
83
- const fetch = unicastFetchWrap()
84
- await expect(fetch('http://invalid.com/test')).rejects.toSatisfy(
85
- fetchFailedErrorCauseBy('Hostname resolved to non-unicast address'),
86
- )
87
- })
88
- })
89
-
90
- describe('expected successes', () => {
91
- // Let's avoid calling actual services in tests. There is no easy way to
92
- // ensure this works without a real public domain hostname that resolves to
93
- // a public IP. So we skip this test for now.
94
- it.skip('should allow public domain hostnames that resolve to public IPs', async () => {
95
- const fetch = unicastFetchWrap()
96
- await fetch('http://atproto.com/@atproto/node-fetch/test')
97
- })
98
- })
99
-
100
- describe('version handling', () => {
101
- it('should throw an error if undici version is too old', () => {
102
- using _ = vi
103
- .spyOn(process.versions, 'undici', 'get')
104
- .mockReturnValue('6.11.0')
105
- expect(process.versions.undici).toBe('6.11.0')
106
- expect(() => unicastFetchWrap()).toThrowError()
107
- })
108
-
109
- it('should support undici version 6.11.1', () => {
110
- using _ = vi
111
- .spyOn(process.versions, 'undici', 'get')
112
- .mockReturnValue('6.11.1')
113
- expect(process.versions.undici).toBe('6.11.1')
114
- expect(() => unicastFetchWrap()).not.toThrowError()
115
- })
116
-
117
- it('should throw an error if undici version is too new', () => {
118
- using _ = vi
119
- .spyOn(process.versions, 'undici', 'get')
120
- .mockReturnValue('9.0.0')
121
- expect(process.versions.undici).toBe('9.0.0')
122
- expect(() => unicastFetchWrap()).toThrowError()
123
- })
124
- })
125
- })
126
-
127
- function fetchFailedErrorCauseBy(message: string) {
128
- return (err: unknown) => {
129
- assert(err instanceof TypeError)
130
- expect(err.message).toBe('fetch failed')
131
- assert(err.cause instanceof Error)
132
- expect(err.cause.message).toBe(message)
133
- return true
134
- }
135
- }
package/src/unicast.ts DELETED
@@ -1,167 +0,0 @@
1
- import type { LookupAddress, LookupOptions } from 'node:dns'
2
- import { lookup } from 'node:dns'
3
- import type { LookupFunction } from 'node:net'
4
- import ipaddr from 'ipaddr.js'
5
- import { Agent as Undici6Agent } from 'undici_v6' // NodeJS 22
6
- import { Agent as Undici7Agent } from 'undici_v7' // NodeJS 24
7
- import { Agent as Undici8Agent } from 'undici_v8' // NodeJS 26
8
- import {
9
- Fetch,
10
- FetchContext,
11
- FetchRequestError,
12
- asRequest,
13
- extractUrl,
14
- } from '@atproto-labs/fetch'
15
- import { compareVersions, isUnicastIpHostname, parseVersion } from './util.js'
16
-
17
- const { IPv4, IPv6 } = ipaddr
18
-
19
- export type UnicastFetchWrapOptions<C = FetchContext> = {
20
- fetch?: Fetch<C>
21
- }
22
-
23
- /**
24
- * @see {@link https://owasp.org/Top10/A10_2021-Server-Side_Request_Forgery_%28SSRF%29/}
25
- */
26
- export function unicastFetchWrap<C = FetchContext>({
27
- fetch = globalThis.fetch,
28
- }: UnicastFetchWrapOptions<C> = {}): Fetch<C> {
29
- // @NOTE we parse here instead of top-level to allow version mocking in tests.
30
- const nodeUndiciVersion = parseVersion(process.versions.undici)
31
-
32
- if (
33
- !nodeUndiciVersion ||
34
- // https://github.com/nodejs/undici/pull/2928
35
- compareVersions(nodeUndiciVersion, [6, 11, 1]) < 0
36
- ) {
37
- throw new Error('Unicast SSRF protection requires Node.js 20.6+')
38
- }
39
-
40
- // @NOTE Since major versions of undici are not guaranteed to be backwards
41
- // compatible, we need to check the major version and use the appropriate
42
- // Agent class for that version, to ensure that the dispatcher interface is
43
- // compatible with the version of undici being used.
44
- const dispatcher =
45
- nodeUndiciVersion[0] === 6
46
- ? new Undici6Agent({ connect: { lookup: unicastLookup } })
47
- : nodeUndiciVersion[0] === 7
48
- ? new Undici7Agent({ connect: { lookup: unicastLookup } })
49
- : nodeUndiciVersion[0] === 8
50
- ? new Undici8Agent({ connect: { lookup: unicastLookup } })
51
- : null
52
-
53
- // @NOTE Because this is a security feature, we don't want to fallback to
54
- // using Agent8 to "future proof" this package. Although future version of
55
- // undici may have a backwards compatible dispatcher interface, we don't want
56
- // to assume that and risk a security issue.
57
- if (!dispatcher) {
58
- throw new Error(
59
- 'This version of @atproto-labs/fetch-node does not support your version of undici. Please upgrade @atproto-labs/fetch-node, and use a version of NodeJS that uses undici 6, 7, or 8 internally.',
60
- )
61
- }
62
-
63
- return async function (this: C, input, init): Promise<Response> {
64
- if (init != null && 'dispatcher' in init && init.dispatcher != null) {
65
- const request = asRequest(input, init)
66
- await request.body?.cancel()
67
- const cause = new FetchRequestError(
68
- request,
69
- 500,
70
- 'SSRF protection cannot be used with a custom request dispatcher',
71
- )
72
- // @NOTE Use Whatwg style errors so that the error is similar whether
73
- // caused by this line of an error caused by the lookup function
74
- throw new TypeError('fetch failed', { cause })
75
- }
76
-
77
- const url = extractUrl(input)
78
-
79
- if (url.hostname && isUnicastIpHostname(url.hostname) === false) {
80
- const request = asRequest(input, init)
81
- await request.body?.cancel()
82
- const cause = new FetchRequestError(
83
- request,
84
- 400,
85
- 'Hostname is a non-unicast address',
86
- )
87
- // @NOTE Use Whatwg style errors so that the error is similar whether
88
- // caused by this line of an error caused by the lookup function
89
- throw new TypeError('fetch failed', { cause })
90
- }
91
-
92
- return fetch.call(this, input, {
93
- ...init,
94
- // @ts-ignore There is a type mismatch because of undici version
95
- // differences, but we know this is safe because we are using the correct
96
- // Agent class for the undici version.
97
- dispatcher,
98
- })
99
- }
100
- }
101
-
102
- export function unicastLookup(
103
- hostname: string,
104
- options: LookupOptions,
105
- callback: Parameters<LookupFunction>[2],
106
- ) {
107
- if (isLocalHostname(hostname)) {
108
- callback(new Error('Hostname is not a public domain'), [])
109
- return
110
- }
111
-
112
- lookup(hostname, options, (err, address, family) => {
113
- if (err) {
114
- callback(err, address, family)
115
- } else {
116
- const ips = Array.isArray(address)
117
- ? address.map(parseLookupAddress)
118
- : [parseLookupAddress({ address, family })]
119
-
120
- if (ips.some(isNotUnicast)) {
121
- callback(
122
- new Error('Hostname resolved to non-unicast address'),
123
- address,
124
- family,
125
- )
126
- } else {
127
- callback(null, address, family)
128
- }
129
- }
130
- })
131
- }
132
-
133
- /**
134
- * @param hostname - a syntactically valid hostname
135
- * @returns whether the hostname is a name typically used for on locale area networks.
136
- * @note **DO NOT** use for security reasons. Only as heuristic.
137
- */
138
- function isLocalHostname(hostname: string): boolean {
139
- const parts = hostname.split('.')
140
- if (parts.length < 2) return true
141
-
142
- const tld = parts.at(-1)!.toLowerCase()
143
- return (
144
- tld === 'test' ||
145
- tld === 'local' ||
146
- tld === 'localhost' ||
147
- tld === 'invalid' ||
148
- tld === 'example'
149
- )
150
- }
151
-
152
- function isNotUnicast(ip: ipaddr.IPv4 | ipaddr.IPv6): boolean {
153
- return ip.range() !== 'unicast'
154
- }
155
-
156
- function parseLookupAddress({
157
- address,
158
- family,
159
- }: LookupAddress): ipaddr.IPv4 | ipaddr.IPv6 {
160
- const ip = family === 4 ? IPv4.parse(address) : IPv6.parse(address)
161
-
162
- if (ip instanceof IPv6 && ip.isIPv4MappedAddress()) {
163
- return ip.toIPv4Address()
164
- } else {
165
- return ip
166
- }
167
- }
package/src/util.test.ts DELETED
@@ -1,108 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
- import { compareVersions, isUnicastIpHostname, parseVersion } from './util.js'
3
-
4
- describe(isUnicastIpHostname, () => {
5
- describe('IPv4', () => {
6
- it('should return true for unicast IP addresses', () => {
7
- expect(isUnicastIpHostname('1.1.1.1')).toBe(true)
8
- expect(isUnicastIpHostname('8.8.8.8')).toBe(true)
9
- })
10
-
11
- it('should return false for Multicast IP addresses', () => {
12
- // https://en.wikipedia.org/wiki/Multicast_address
13
-
14
- expect(isUnicastIpHostname('224.0.0.0')).toBe(false)
15
- expect(isUnicastIpHostname('224.0.0.255')).toBe(false)
16
- expect(isUnicastIpHostname('224.0.1.0')).toBe(false)
17
- expect(isUnicastIpHostname('224.0.1.255')).toBe(false)
18
- expect(isUnicastIpHostname('224.0.2.0')).toBe(false)
19
- expect(isUnicastIpHostname('224.0.255.255')).toBe(false)
20
- expect(isUnicastIpHostname('224.1.0.0')).toBe(false)
21
- expect(isUnicastIpHostname('224.1.255.255')).toBe(false)
22
- expect(isUnicastIpHostname('224.2.0.0')).toBe(false)
23
- expect(isUnicastIpHostname('224.2.255.255')).toBe(false)
24
- expect(isUnicastIpHostname('224.3.0.0')).toBe(false)
25
- expect(isUnicastIpHostname('224.4.255.255')).toBe(false)
26
- expect(isUnicastIpHostname('224.5.0.0')).toBe(false)
27
- expect(isUnicastIpHostname('224.255.255.255')).toBe(false)
28
- expect(isUnicastIpHostname('225.0.0.0')).toBe(false)
29
- expect(isUnicastIpHostname('231.255.255.255')).toBe(false)
30
- expect(isUnicastIpHostname('232.0.0.0')).toBe(false)
31
- expect(isUnicastIpHostname('232.255.255.255')).toBe(false)
32
- expect(isUnicastIpHostname('233.0.0.0')).toBe(false)
33
- expect(isUnicastIpHostname('233.251.255.255')).toBe(false)
34
- expect(isUnicastIpHostname('233.252.0.0')).toBe(false)
35
- expect(isUnicastIpHostname('233.255.255.255')).toBe(false)
36
- expect(isUnicastIpHostname('234.0.0.0')).toBe(false)
37
- expect(isUnicastIpHostname('234.255.255.255')).toBe(false)
38
- expect(isUnicastIpHostname('235.0.0.0')).toBe(false)
39
- expect(isUnicastIpHostname('238.255.255.255')).toBe(false)
40
- expect(isUnicastIpHostname('239.0.0.0')).toBe(false)
41
- expect(isUnicastIpHostname('239.255.255.255')).toBe(false)
42
- })
43
-
44
- it('should return false for loopback IP addresses', () => {
45
- // https://en.wikipedia.org/wiki/Loopback
46
-
47
- expect(isUnicastIpHostname('127.0.0.0')).toBe(false)
48
- expect(isUnicastIpHostname('127.0.0.1')).toBe(false)
49
- expect(isUnicastIpHostname('127.0.34.54')).toBe(false)
50
- expect(isUnicastIpHostname('127.255.255.255')).toBe(false)
51
- })
52
-
53
- it('should return false for private IP addresses', () => {
54
- // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
55
-
56
- expect(isUnicastIpHostname('10.0.0.0')).toBe(false)
57
- expect(isUnicastIpHostname('10.255.255.255')).toBe(false)
58
- expect(isUnicastIpHostname('172.16.0.0')).toBe(false)
59
- expect(isUnicastIpHostname('172.16.0.1')).toBe(false)
60
- expect(isUnicastIpHostname('172.31.255.255')).toBe(false)
61
- expect(isUnicastIpHostname('192.168.0.0')).toBe(false)
62
- expect(isUnicastIpHostname('192.168.1.1')).toBe(false)
63
- expect(isUnicastIpHostname('192.168.255.255')).toBe(false)
64
- })
65
- })
66
-
67
- it('should return undefined for non-IP hostnames', () => {
68
- expect(isUnicastIpHostname('example.com')).toBeUndefined()
69
- expect(isUnicastIpHostname('localhost')).toBeUndefined()
70
- })
71
- })
72
-
73
- describe(parseVersion, () => {
74
- it('should parse valid version strings', () => {
75
- expect(parseVersion('1.2.3')).toEqual([1, 2, 3])
76
- expect(parseVersion('0.0.1')).toEqual([0, 0, 1])
77
- expect(parseVersion('10.20.30')).toEqual([10, 20, 30])
78
- })
79
-
80
- it('should return undefined for invalid version strings', () => {
81
- expect(parseVersion('1.2')).toBeUndefined()
82
- expect(parseVersion('1.2.3.4')).toBeUndefined()
83
- expect(parseVersion('abc')).toBeUndefined()
84
- })
85
-
86
- it('should return undefined for empty or undefined input', () => {
87
- expect(parseVersion('')).toBeUndefined()
88
- expect(parseVersion(undefined)).toBeUndefined()
89
- })
90
- })
91
-
92
- describe(compareVersions, () => {
93
- it('should return 0 for equal versions', () => {
94
- expect(compareVersions([1, 2, 3], [1, 2, 3])).toBe(0)
95
- })
96
-
97
- it('should return -1 for a < b', () => {
98
- expect(compareVersions([1, 2, 3], [1, 2, 4])).toBe(-1)
99
- expect(compareVersions([1, 2, 3], [1, 3, 0])).toBe(-1)
100
- expect(compareVersions([1, 2, 3], [2, 0, 0])).toBe(-1)
101
- })
102
-
103
- it('should return 1 for a > b', () => {
104
- expect(compareVersions([1, 2, 4], [1, 2, 3])).toBe(1)
105
- expect(compareVersions([1, 3, 0], [1, 2, 3])).toBe(1)
106
- expect(compareVersions([2, 0, 0], [1, 2, 3])).toBe(1)
107
- })
108
- })
package/src/util.ts DELETED
@@ -1,37 +0,0 @@
1
- import ipaddr from 'ipaddr.js'
2
-
3
- const { IPv4, IPv6 } = ipaddr
4
-
5
- function parseIpHostname(
6
- hostname: string,
7
- ): ipaddr.IPv4 | ipaddr.IPv6 | undefined {
8
- if (IPv4.isIPv4(hostname)) {
9
- return IPv4.parse(hostname)
10
- }
11
-
12
- if (hostname.startsWith('[') && hostname.endsWith(']')) {
13
- return IPv6.parse(hostname.slice(1, -1))
14
- }
15
-
16
- return undefined
17
- }
18
-
19
- export function isUnicastIpHostname(hostname: string): boolean | undefined {
20
- const ip = parseIpHostname(hostname)
21
- return ip ? ip.range() === 'unicast' : undefined
22
- }
23
-
24
- export type Version = [major: number, minor: number, patch: number]
25
- export function parseVersion(version?: string): Version | undefined {
26
- const match = version?.match(/^(\d+)\.(\d+)\.(\d+)$/)
27
- if (!match) return undefined
28
- return [Number(match[1]), Number(match[2]), Number(match[3])]
29
- }
30
-
31
- export function compareVersions(a: Version, b: Version): number {
32
- for (let i = 0; i < 3; i++) {
33
- if (a[i] < b[i]) return -1
34
- if (a[i] > b[i]) return 1
35
- }
36
- return 0
37
- }
@@ -1,9 +0,0 @@
1
- {
2
- "extends": ["../../../tsconfig/node.json"],
3
- "include": ["./src"],
4
- "exclude": ["**/*.test.ts"],
5
- "compilerOptions": {
6
- "outDir": "dist",
7
- "rootDir": "src",
8
- },
9
- }
@@ -1 +0,0 @@
1
- {"version":"7.0.0-dev.20260614.1","root":["./src/index.ts","./src/safe.ts","./src/unicast.ts","./src/util.ts"]}
package/tsconfig.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "include": [],
3
- "references": [
4
- { "path": "./tsconfig.build.json" },
5
- { "path": "./tsconfig.test.json" },
6
- ],
7
- }
@@ -1,8 +0,0 @@
1
- {
2
- "extends": ["../../../tsconfig/vitest.json"],
3
- "include": ["./tests", "./src/**/*.test.ts"],
4
- "compilerOptions": {
5
- "noImplicitAny": true,
6
- "rootDir": "./",
7
- },
8
- }
@@ -1 +0,0 @@
1
- {"version":"7.0.0-dev.20260614.1","root":["./src/unicast.test.ts","./src/util.test.ts"]}
package/vitest.config.ts DELETED
@@ -1,5 +0,0 @@
1
- import { defineProject } from 'vitest/config'
2
-
3
- export default defineProject({
4
- test: {},
5
- })