Initial public release

This commit is contained in:
GenOffice
2026-08-02 19:52:16 +08:00
commit d2fe8ddaae
994 changed files with 348937 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
{
"name": "@genoffice/electron-utils",
"version": "0.1.0",
"license": "Apache-2.0",
"private": true,
"type": "module",
"description": "Shared helpers for the Electron main processes (no Electron dependency, pure TS)",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest"
},
"devDependencies": {
"typescript": "^5.9.3",
"vitest": "^4.1.0"
}
}
+7
View File
@@ -0,0 +1,7 @@
export { safeExternalUrl, type SafeExternalUrlOptions } from './safe-external-url'
export {
fetchWithSsrfGuard,
isBlockedAddress,
isSafeRemoteUrl,
type FetchWithSsrfGuardOptions,
} from './safe-remote-url'
@@ -0,0 +1,28 @@
/// Single validation gate for every `shell.openExternal` call in the suite.
/// URLs reaching the main process (renderer IPC, window-open handlers, links
/// embedded in documents) are untrusted; anything that is not a well-formed
/// URL on the protocol allowlist is rejected so file:, javascript:, custom
/// app schemes, etc. can never reach the OS handler.
export interface SafeExternalUrlOptions {
/** Protocol allowlist (with trailing colon). Defaults to http/https only. */
allowedProtocols?: readonly string[]
}
const DEFAULT_PROTOCOLS: readonly string[] = ['http:', 'https:']
/**
* Returns the URL string when it parses and its protocol is on the allowlist,
* otherwise null. Callers must not fall back to opening the raw input.
*/
export function safeExternalUrl(url: unknown, options?: SafeExternalUrlOptions): string | null {
if (typeof url !== 'string') return null
let parsed: URL
try {
parsed = new URL(url)
} catch {
return null
}
const allowed = options?.allowedProtocols ?? DEFAULT_PROTOCOLS
return allowed.includes(parsed.protocol) ? url : null
}
@@ -0,0 +1,116 @@
/// SSRF gate for main-process fetches whose target is influenced by untrusted
/// input — most importantly AI tool calls, where a poisoned web-search result
/// can steer the model into requesting an internal address. Every hop of a
/// redirect chain has to pass, because validating only the initial URL lets a
/// public host bounce the request to loopback or a cloud metadata endpoint.
import { lookup } from 'node:dns/promises'
import { BlockList, isIP } from 'node:net'
/**
* Non-public address ranges. BlockList does the range math and maps
* ::ffff:0:0/96 addresses back onto the IPv4 rules, which hand-rolled string
* checks get wrong for normalized forms such as [::ffff:127.0.0.1], whose
* hostname becomes ::ffff:7f00:1.
*/
const blockedAddresses = (() => {
const list = new BlockList()
list.addSubnet('0.0.0.0', 8) // "this network"
list.addSubnet('10.0.0.0', 8) // private
list.addSubnet('100.64.0.0', 10) // carrier NAT
list.addSubnet('127.0.0.0', 8) // loopback
list.addSubnet('169.254.0.0', 16) // link-local (cloud metadata)
list.addSubnet('172.16.0.0', 12) // private
list.addSubnet('192.0.0.0', 24) // IETF protocol assignments
list.addSubnet('192.168.0.0', 16) // private
list.addSubnet('198.18.0.0', 15) // benchmarking
list.addSubnet('224.0.0.0', 4) // multicast
list.addSubnet('240.0.0.0', 4) // reserved + broadcast
list.addAddress('::', 'ipv6') // unspecified
list.addAddress('::1', 'ipv6') // loopback
list.addSubnet('::', 96, 'ipv6') // deprecated IPv4-compatible (::127.0.0.1)
list.addSubnet('64:ff9b::', 96, 'ipv6') // NAT64
list.addSubnet('fc00::', 7, 'ipv6') // unique local
list.addSubnet('fe80::', 10, 'ipv6') // link-local
list.addSubnet('ff00::', 8, 'ipv6') // multicast
return list
})()
/** Hostname suffixes that never denote a public host. */
const BLOCKED_HOST_SUFFIXES: readonly string[] = ['.localhost', '.local', '.internal']
/** True when `ip` is a literal address outside the public ranges (non-addresses count as unsafe). */
export function isBlockedAddress(ip: string): boolean {
const family = isIP(ip)
if (family === 0) return true
return blockedAddresses.check(ip, family === 4 ? 'ipv4' : 'ipv6')
}
/**
* True when the URL is http(s) and its host is public. Literal addresses are
* checked directly; hostnames are resolved and every returned address must pass,
* so a name pointing at an internal address is rejected.
*
* This is a best-effort control, not a guarantee: DNS can change between this
* check and the request (rebinding). Pair it with per-hop revalidation via
* `fetchWithSsrfGuard` rather than relying on a single up-front check.
*/
export async function isSafeRemoteUrl(raw: unknown): Promise<boolean> {
if (typeof raw !== 'string') return false
let url: URL
try {
url = new URL(raw)
} catch {
return false
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
// URL keeps IPv6 literals bracketed; isIP does not accept the brackets
const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase()
if (host === '') return false
if (isIP(host)) return !isBlockedAddress(host)
if (host === 'localhost' || BLOCKED_HOST_SUFFIXES.some((s) => host.endsWith(s))) return false
try {
const addrs = await lookup(host, { all: true })
return addrs.length > 0 && addrs.every((a) => !isBlockedAddress(a.address))
} catch {
return false
}
}
export interface FetchWithSsrfGuardOptions {
/** Redirect hops to follow. Each hop is revalidated. Defaults to 5. */
maxRedirects?: number
headers?: Record<string, string>
/** Injectable for tests; defaults to global fetch. */
fetchImpl?: typeof fetch
}
/**
* fetch() that validates the target before every hop, following redirects
* manually. Returns null when any hop fails validation, a redirect lacks a
* usable Location, or the hop budget is exhausted.
*/
export async function fetchWithSsrfGuard(
rawUrl: string,
options: FetchWithSsrfGuardOptions = {},
): Promise<Response | null> {
const { maxRedirects = 5, headers, fetchImpl = fetch } = options
let current = rawUrl
for (let hop = 0; hop <= maxRedirects; hop++) {
if (!(await isSafeRemoteUrl(current))) return null
// headers stays absent rather than explicitly undefined (exactOptionalPropertyTypes)
const resp = await fetchImpl(current, {
...(headers ? { headers } : {}),
redirect: 'manual',
})
if (resp.status < 300 || resp.status >= 400) return resp
const location = resp.headers.get('location')
if (!location) return null
try {
current = new URL(location, current).toString()
} catch {
return null
}
}
return null
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { safeExternalUrl } from '../src/index'
describe('safeExternalUrl', () => {
it('accepts http and https URLs', () => {
expect(safeExternalUrl('https://example.com/a?b=c')).toBe('https://example.com/a?b=c')
expect(safeExternalUrl('http://example.com')).toBe('http://example.com')
})
it('rejects non-string input', () => {
expect(safeExternalUrl(undefined)).toBeNull()
expect(safeExternalUrl(null)).toBeNull()
expect(safeExternalUrl(42)).toBeNull()
expect(safeExternalUrl({ toString: () => 'https://example.com' })).toBeNull()
})
it('rejects malformed URLs', () => {
expect(safeExternalUrl('not a url')).toBeNull()
expect(safeExternalUrl('')).toBeNull()
expect(safeExternalUrl('http//missing-colon.com')).toBeNull()
})
it('rejects dangerous protocols by default', () => {
expect(safeExternalUrl('file:///etc/passwd')).toBeNull()
expect(safeExternalUrl('javascript:alert(1)')).toBeNull()
expect(safeExternalUrl('smb://server/share')).toBeNull()
expect(safeExternalUrl('mailto:a@b.com')).toBeNull()
// prefix tricks that pass a bare startsWith('http') check
expect(safeExternalUrl('httpx://evil.example')).toBeNull()
})
it('supports a custom protocol allowlist', () => {
const opts = { allowedProtocols: ['https:', 'mailto:'] }
expect(safeExternalUrl('mailto:a@b.com', opts)).toBe('mailto:a@b.com')
expect(safeExternalUrl('http://example.com', opts)).toBeNull()
})
})
@@ -0,0 +1,160 @@
import { describe, expect, it, vi } from 'vitest'
import { fetchWithSsrfGuard, isBlockedAddress, isSafeRemoteUrl } from '../src/safe-remote-url'
describe('isBlockedAddress', () => {
it.each([
'127.0.0.1',
'169.254.169.254', // cloud metadata
'10.1.2.3',
'172.20.0.5',
'192.168.1.1',
'0.0.0.0',
'100.64.0.1',
'255.255.255.255',
])('blocks non-public IPv4 %s', (ip) => {
expect(isBlockedAddress(ip)).toBe(true)
})
it.each(['::1', '::', 'fe80::1', 'fd00::1', 'ff02::1'])('blocks non-public IPv6 %s', (ip) => {
expect(isBlockedAddress(ip)).toBe(true)
})
// URL normalizes [::ffff:127.0.0.1] to ::ffff:7f00:1, so the hex form must be
// classified through the IPv4 rules rather than read as a plain IPv6 address
it.each([
'::ffff:7f00:1', // ::ffff:127.0.0.1
'::ffff:a9fe:a9fe', // ::ffff:169.254.169.254
'::ffff:a00:1', // ::ffff:10.0.0.1
'::7f00:1', // deprecated IPv4-compatible ::127.0.0.1
'::a9fe:a9fe',
])('blocks IPv4-mapped/compatible form %s', (ip) => {
expect(isBlockedAddress(ip)).toBe(true)
})
it.each(['8.8.8.8', '1.1.1.1', '93.184.216.34', '2001:4860:4860::8888'])(
'allows public address %s',
(ip) => {
expect(isBlockedAddress(ip)).toBe(false)
},
)
it('treats non-addresses as unsafe', () => {
expect(isBlockedAddress('example.com')).toBe(true)
expect(isBlockedAddress('')).toBe(true)
})
})
describe('isSafeRemoteUrl', () => {
it.each([
'file:///etc/passwd',
'javascript:alert(1)',
'data:image/png;base64,AAAA',
'ftp://example.com/x.png',
])('rejects non-http scheme %s', async (url) => {
await expect(isSafeRemoteUrl(url)).resolves.toBe(false)
})
it.each([
'http://127.0.0.1/x.png',
'http://169.254.169.254/latest/meta-data/',
'http://[::1]/x.png',
'http://[::ffff:127.0.0.1]/x.png',
'http://10.0.0.1/x.png',
])('rejects literal internal target %s', async (url) => {
await expect(isSafeRemoteUrl(url)).resolves.toBe(false)
})
it.each([
'http://localhost:8080/x.png',
'http://foo.localhost/x.png',
'http://printer.local/x.png',
'http://metadata.internal/x.png',
])('rejects internal hostname %s', async (url) => {
await expect(isSafeRemoteUrl(url)).resolves.toBe(false)
})
it('rejects malformed input and non-strings', async () => {
await expect(isSafeRemoteUrl('not a url')).resolves.toBe(false)
await expect(isSafeRemoteUrl(undefined)).resolves.toBe(false)
await expect(isSafeRemoteUrl(42)).resolves.toBe(false)
})
it('allows a public literal address', async () => {
await expect(isSafeRemoteUrl('https://8.8.8.8/x.png')).resolves.toBe(true)
})
})
describe('fetchWithSsrfGuard', () => {
const res = (status: number, location?: string) =>
new Response(null, {
status,
headers: location ? { location } : undefined,
})
it('rejects a redirect from a public host to an internal address', async () => {
const fetchImpl = vi
.fn()
.mockResolvedValueOnce(res(302, 'http://169.254.169.254/latest/meta-data/'))
const out = await fetchWithSsrfGuard('https://8.8.8.8/start.png', { fetchImpl })
expect(out).toBeNull()
// the internal hop is never requested
expect(fetchImpl).toHaveBeenCalledTimes(1)
expect(fetchImpl.mock.calls[0][0]).toBe('https://8.8.8.8/start.png')
})
it('follows a redirect between public hosts and returns the final response', async () => {
const final = new Response('ok', { status: 200 })
const fetchImpl = vi
.fn()
.mockResolvedValueOnce(res(301, 'https://1.1.1.1/final.png'))
.mockResolvedValueOnce(final)
const out = await fetchWithSsrfGuard('https://8.8.8.8/start.png', { fetchImpl })
expect(out).toBe(final)
expect(fetchImpl.mock.calls[1][0]).toBe('https://1.1.1.1/final.png')
})
it('resolves relative Location headers against the current URL', async () => {
const final = new Response('ok', { status: 200 })
const fetchImpl = vi
.fn()
.mockResolvedValueOnce(res(302, '/moved.png'))
.mockResolvedValueOnce(final)
await fetchWithSsrfGuard('https://8.8.8.8/a/b.png', { fetchImpl })
expect(fetchImpl.mock.calls[1][0]).toBe('https://8.8.8.8/moved.png')
})
it('gives up on a redirect loop instead of following forever', async () => {
const fetchImpl = vi.fn().mockResolvedValue(res(302, 'https://8.8.8.8/loop.png'))
const out = await fetchWithSsrfGuard('https://8.8.8.8/loop.png', {
fetchImpl,
maxRedirects: 3,
})
expect(out).toBeNull()
expect(fetchImpl).toHaveBeenCalledTimes(4) // initial + 3 hops
})
it('returns null when a redirect has no Location header', async () => {
const fetchImpl = vi.fn().mockResolvedValueOnce(res(302))
await expect(fetchWithSsrfGuard('https://8.8.8.8/x.png', { fetchImpl })).resolves.toBeNull()
})
it('passes headers through and disables automatic redirects', async () => {
const fetchImpl = vi.fn().mockResolvedValueOnce(new Response('ok', { status: 200 }))
await fetchWithSsrfGuard('https://8.8.8.8/x.png', {
fetchImpl,
headers: { 'User-Agent': 'test-agent' },
})
expect(fetchImpl.mock.calls[0][1]).toMatchObject({
headers: { 'User-Agent': 'test-agent' },
redirect: 'manual',
})
})
it('never requests a target that fails the initial check', async () => {
const fetchImpl = vi.fn()
await expect(
fetchWithSsrfGuard('http://169.254.169.254/latest/meta-data/', { fetchImpl }),
).resolves.toBeNull()
expect(fetchImpl).not.toHaveBeenCalled()
})
})
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src", "tests", "vitest.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
},
})