dsh-inline-link-preview 0.0.0-stage → 0.5.0-beta.2
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/LICENSE +21 -0
- package/README.md +77 -2
- package/assets/icon-180.png +0 -0
- package/assets/inline-preview-flow.png +0 -0
- package/assets/supported-sources.png +0 -0
- package/build-client.js +13 -0
- package/client.js +208 -0
- package/composer.js +141 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +6 -0
- package/index.js +214 -0
- package/link-policy.js +61 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/npm-adapter.js +90 -0
- package/package.json +67 -4
- package/public-fetch.js +266 -0
- package/test/host.test.js +168 -0
- package/test/inline.test.js +256 -0
- package/test/npm-adapter.test.js +163 -0
- package/test/public-fetch.test.js +432 -0
- package/test/title.test.js +127 -0
- package/title.js +190 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import dns from 'node:dns/promises'
|
|
3
|
+
import { EventEmitter } from 'node:events'
|
|
4
|
+
import http from 'node:http'
|
|
5
|
+
import https from 'node:https'
|
|
6
|
+
import { PassThrough, Readable } from 'node:stream'
|
|
7
|
+
import test from 'node:test'
|
|
8
|
+
import { createPublicBudget, isPublicPageUrl, readPublicHtml, readPublicJson } from '../public-fetch.js'
|
|
9
|
+
|
|
10
|
+
const page = 'https://news.example.com/story', ipv4 = '93.184.216.34', ipv6 = '2606:4700:4700::1111'
|
|
11
|
+
const rejected = promise => assert.rejects(promise, { name: 'Error', message: 'public HTML unavailable' })
|
|
12
|
+
const htmlHeaders = { 'content-type': 'text/html; charset=utf-8' }
|
|
13
|
+
|
|
14
|
+
// Replace BOTH DNS families and BOTH transports. No test starts a listener, resolves a name or opens a socket.
|
|
15
|
+
function network(t, replies = [], answers = (_host, family) => family === 4 ? [ipv4] : []) {
|
|
16
|
+
const calls = { dns: [], http: [], cancelled: 0 }
|
|
17
|
+
for (const family of [4, 6]) {
|
|
18
|
+
t.mock.method(dns.Resolver.prototype, `resolve${family}`, async host => {
|
|
19
|
+
calls.dns.push([host, family])
|
|
20
|
+
return answers(host, family)
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
t.mock.method(dns.Resolver.prototype, 'cancel', () => { calls.cancelled++ })
|
|
24
|
+
for (const transport of [http, https]) {
|
|
25
|
+
t.mock.method(transport, 'get', (options, respond) => {
|
|
26
|
+
const req = new EventEmitter(), socket = new EventEmitter()
|
|
27
|
+
const reply = replies.shift()
|
|
28
|
+
const call = { options, req, socket, res: undefined }
|
|
29
|
+
calls.http.push(call)
|
|
30
|
+
req.destroy = error => {
|
|
31
|
+
if (req.destroyed) return req
|
|
32
|
+
req.destroyed = true
|
|
33
|
+
if (error) req.emit('error', error)
|
|
34
|
+
call.res?.destroy()
|
|
35
|
+
req.emit('close')
|
|
36
|
+
return req
|
|
37
|
+
}
|
|
38
|
+
socket.destroy = () => req.destroy()
|
|
39
|
+
options.signal.addEventListener('abort', () => req.destroy(), { once: true })
|
|
40
|
+
queueMicrotask(() => {
|
|
41
|
+
if (req.destroyed) return
|
|
42
|
+
req.emit('socket', socket)
|
|
43
|
+
if (!reply || reply.error) return req.destroy(reply?.error ?? Error('unexpected test request'))
|
|
44
|
+
for (const data of reply.wire ?? []) socket.emit('data', data)
|
|
45
|
+
if (req.destroyed) return
|
|
46
|
+
if (reply.upgrade) return req.emit('upgrade', {}, socket)
|
|
47
|
+
const res = call.res = reply.body instanceof Readable ? reply.body : Readable.from([Buffer.from(reply.body ?? '<html>ok</html>')])
|
|
48
|
+
res.statusCode = reply.status ?? 200
|
|
49
|
+
res.headersDistinct = Object.fromEntries(Object.entries(reply.headers ?? htmlHeaders)
|
|
50
|
+
.map(([key, value]) => [key, Array.isArray(value) ? value : [value]]))
|
|
51
|
+
res.once('close', () => req.destroy())
|
|
52
|
+
respond(res)
|
|
53
|
+
reply.opened?.()
|
|
54
|
+
})
|
|
55
|
+
return req
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
return calls
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
test('lexical policy accepts standard public DNS URLs, never grants network access by itself', () => {
|
|
62
|
+
for (const text of [page, 'http://example.com:80/', 'https://example.org:443/q?a=b#h', 'https://例子.中国/']) {
|
|
63
|
+
assert.equal(isPublicPageUrl(new URL(text)), true, text)
|
|
64
|
+
}
|
|
65
|
+
for (const text of ['file:///etc/hosts', 'ftp://news.example.com/', 'https://user@news.example.com/',
|
|
66
|
+
'https://news.example.com:444/', 'http://127.0.0.1/', 'http://0x7f000001/', `http://${ipv4}/`, `https://[${ipv6}]/`,
|
|
67
|
+
'https://intranet/', 'https://a.home.arpa/', 'https://x.localhost/', 'https://a.local/', 'https://a.internal/',
|
|
68
|
+
'https://a.invalid/', 'https://a.test/', 'https://a.example/', 'https://a.onion/', 'https://a.alt/',
|
|
69
|
+
'https://bad_name.org/', 'https://-foo.net/', 'https://foo-.net/', 'https://news..org/', 'https://news.org./',
|
|
70
|
+
`https://${'x'.repeat(64)}.org/`, `${page}/${'x'.repeat(4096)}`]) {
|
|
71
|
+
assert.equal(isPublicPageUrl(new URL(text)), false, text)
|
|
72
|
+
}
|
|
73
|
+
assert.equal(isPublicPageUrl(null), false)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
test('initial lexical and caller refusals fail before even DNS; only a synchronous true allows', async t => {
|
|
77
|
+
const calls = network(t)
|
|
78
|
+
for (const input of ['not a URL', 'http://localhost/', 'http://10.0.0.1/', null, 'https://news.org:80/']) {
|
|
79
|
+
await rejected(readPublicHtml(input))
|
|
80
|
+
}
|
|
81
|
+
for (const allowUrl of [() => false, async () => true, () => { throw Error('internal policy details') }]) {
|
|
82
|
+
await rejected(readPublicHtml(page, { allowUrl }))
|
|
83
|
+
}
|
|
84
|
+
assert.deepEqual(calls.dns, [])
|
|
85
|
+
assert.deepEqual(calls.http, [])
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test('each hop validates both families; literal socket target is pinned and original Host/TLS identity preserved', async t => {
|
|
89
|
+
const calls = network(t, [
|
|
90
|
+
{ status: 302, headers: { location: `${page}?n=2#view`, 'set-cookie': 'test-value=ignore' } },
|
|
91
|
+
{ body: '<!doctype html><title>News</title>', headers: { 'content-type': 'Text/HTML; charset="UTF-8"' } },
|
|
92
|
+
], (host, family) => {
|
|
93
|
+
if (host === 'news.example.com.') return family === 6 ? [ipv6] : []
|
|
94
|
+
if (family === 6) throw Object.assign(Error('no IPv6 record'), { code: 'ENODATA' })
|
|
95
|
+
return [ipv4]
|
|
96
|
+
})
|
|
97
|
+
const start = 'http://example.net:80/old#anchor', seen = []
|
|
98
|
+
const result = await readPublicHtml(new URL(start), { allowUrl(url) {
|
|
99
|
+
seen.push(url.href)
|
|
100
|
+
url.hostname = 'changed.invalid' // a policy cannot mutate the separately validated target
|
|
101
|
+
return true
|
|
102
|
+
} })
|
|
103
|
+
assert.deepEqual(seen, [new URL(start).href, `${page}?n=2#view`])
|
|
104
|
+
assert.deepEqual(calls.dns, [['example.net.', 4], ['example.net.', 6], ['news.example.com.', 4], ['news.example.com.', 6]])
|
|
105
|
+
assert.deepEqual(calls.http.map(({ options: o }) => [o.protocol, o.hostname, o.path, o.servername]), [
|
|
106
|
+
['http:', ipv4, '/old', undefined], ['https:', ipv6, '/story?n=2', 'news.example.com'],
|
|
107
|
+
])
|
|
108
|
+
for (const [i, { options, res }] of calls.http.entries()) {
|
|
109
|
+
assert.equal(options.agent, false)
|
|
110
|
+
assert.deepEqual(options.headers, { Host: i ? 'news.example.com' : 'example.net', Accept: 'text/html, application/xhtml+xml', 'Accept-Encoding': 'identity' })
|
|
111
|
+
assert.equal(options.maxHeaderSize, 16 * 1024)
|
|
112
|
+
assert.ok(res.destroyed)
|
|
113
|
+
}
|
|
114
|
+
assert.equal(calls.http[1].options.rejectUnauthorized, true)
|
|
115
|
+
assert.deepEqual(result, { html: '<!doctype html><title>News</title>', url: `${page}?n=2#view`, contentType: 'text/html' })
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
test('a single unsafe or malformed answer in either family prevents any connection', async t => {
|
|
119
|
+
let v4, v6
|
|
120
|
+
const calls = network(t, [], (_host, family) => family === 4 ? v4 : v6)
|
|
121
|
+
for (const bad of ['0.0.0.1', '10.1.2.3', '100.127.255.1', '127.0.0.1', '169.254.0.1', '172.31.255.2', '192.0.0.2',
|
|
122
|
+
'192.0.2.1', '192.31.196.42', '192.52.193.2', '192.88.99.2', '192.168.1.1', '192.175.48.1', '198.18.0.1',
|
|
123
|
+
'198.51.100.1', '203.0.113.1', '224.0.0.1', '240.0.0.1', '255.255.255.255', '168.63.129.16', 'invalid', ipv6]) {
|
|
124
|
+
v4 = [ipv4, bad]; v6 = [ipv6]
|
|
125
|
+
await rejected(readPublicHtml(page))
|
|
126
|
+
}
|
|
127
|
+
for (const bad of ['::', '::1', '::ffff:8.8.8.8', '::192.168.0.1', '64:ff9b::1', '64:ff9b:1::1', 'fc00::1', 'fe80::1',
|
|
128
|
+
'ff02::1', '100::1', '2001::1', '2001:20::1', '2001:db8::1', '2002::1', '3ffe::1', '3fff::1', '2620:4f:8000::1',
|
|
129
|
+
`${ipv6}%eth0`, ipv4]) {
|
|
130
|
+
v4 = [ipv4]; v6 = [ipv6, bad]
|
|
131
|
+
await rejected(readPublicHtml(page))
|
|
132
|
+
}
|
|
133
|
+
v4 = []; v6 = []
|
|
134
|
+
await rejected(readPublicHtml(page))
|
|
135
|
+
v4 = Array(65).fill(ipv4)
|
|
136
|
+
await rejected(readPublicHtml(page))
|
|
137
|
+
assert.deepEqual(calls.http, [])
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
test('DNS errors do not fall back to a partial result or leak details', async t => {
|
|
141
|
+
const calls = network(t, [], (_host, family) => {
|
|
142
|
+
if (family === 4) return [ipv4]
|
|
143
|
+
throw Object.assign(Error('private resolution details'), { code: 'ETIMEOUT' })
|
|
144
|
+
})
|
|
145
|
+
await rejected(readPublicHtml(page))
|
|
146
|
+
assert.equal(calls.cancelled, 1)
|
|
147
|
+
assert.deepEqual(calls.http, [])
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
test('redirect destinations and caller policy are checked before any further DNS/contact; bodies discarded', async t => {
|
|
151
|
+
const locations = ['http://foo.local/', '/login?mock=1#guard', 'http://[::1]/', 'https://name@news.org/', undefined]
|
|
152
|
+
const calls = network(t, locations.map(location => ({ status: 307, headers: location ? { location } : {} })))
|
|
153
|
+
const seen = []
|
|
154
|
+
for (const _ of locations) await rejected(readPublicHtml(page, { allowUrl: url => { seen.push(url.href); return url.pathname !== '/login' } }))
|
|
155
|
+
assert.ok(seen.includes('https://news.example.com/login?mock=1#guard'))
|
|
156
|
+
assert.equal(calls.dns.length, 2 * locations.length)
|
|
157
|
+
assert.equal(calls.http.length, locations.length)
|
|
158
|
+
assert.ok(calls.http.every(({ res }) => res.destroyed && !res.readableDidRead))
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
test('relative same-host redirects re-resolve and cannot reuse earlier authorization for a changed DNS answer', async t => {
|
|
162
|
+
let count = 0
|
|
163
|
+
const calls = network(t, [{ status: 301, headers: { location: '../two' } }], (_host, family) => {
|
|
164
|
+
return family === 6 ? [] : [++count === 1 ? ipv4 : '10.0.0.2']
|
|
165
|
+
})
|
|
166
|
+
await rejected(readPublicHtml(page))
|
|
167
|
+
assert.equal(calls.dns.length, 4)
|
|
168
|
+
assert.equal(calls.http.length, 1)
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
test('stop after three redirects', async t => {
|
|
172
|
+
const calls = network(t, Array.from({ length: 4 }, () => ({ status: 308, headers: { location: './next' } })))
|
|
173
|
+
await rejected(readPublicHtml(page))
|
|
174
|
+
assert.equal(calls.http.length, 4)
|
|
175
|
+
assert.equal(calls.dns.length, 8)
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
test('accept HTML or XHTML with supported text encodings, including GBK', async t => {
|
|
179
|
+
const gbk = Buffer.concat([Buffer.from('<html><meta charset="gbk"><title>'), Buffer.from([0xb2, 0xe2, 0xca, 0xd4]), Buffer.from('</title>')])
|
|
180
|
+
network(t, [{ headers: { 'content-type': 'text/html' }, body: gbk },
|
|
181
|
+
{ headers: { 'content-type': 'text/html; charset=gb2312' }, body: gbk },
|
|
182
|
+
{ headers: { 'content-type': 'application/xhtml+xml' }, body: '<?xml version="1.0"?>\n<!--info--><html xmlns="http://www.w3.org/1999/xhtml"/>' }])
|
|
183
|
+
assert.match((await readPublicHtml(page)).html, /测试/)
|
|
184
|
+
assert.match((await readPublicHtml(page)).html, /测试/)
|
|
185
|
+
assert.equal((await readPublicHtml(page)).contentType, 'application/xhtml+xml')
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
test('unknown/missing types, binary content, unsupported charset/coding, duplicate headers, attachments and non-200s are refused', async t => {
|
|
189
|
+
const replies = [ {}, { 'content-type': 'application/octet-stream' }, { 'content-type': 'text/plain' },
|
|
190
|
+
{ 'content-type': 'application/json' }, { 'content-type': 'image/svg+xml' },
|
|
191
|
+
{ 'content-type': ['text/html', 'text/plain'] }, { 'content-type': 'text/html; charset=utf-16' },
|
|
192
|
+
{ ...htmlHeaders, 'content-encoding': 'gzip' }, { ...htmlHeaders, 'content-disposition': 'attachment; filename=page.html' },
|
|
193
|
+
].map(headers => ({ headers }))
|
|
194
|
+
replies.push({ body: '<html>\x00data' }, { body: Buffer.from([0xff, 0xfe]) }, { body: '{"a":"<html>"}' },
|
|
195
|
+
{ body: '%PDF-1.' }, { body: '<?xml version="1.0"?><svg/>' }, { body: 'not markup' }, ...[204, 206, 401, 403, 429, 503].map(status => ({ status })))
|
|
196
|
+
const n = replies.length, calls = network(t, replies)
|
|
197
|
+
for (let i = 0; i < n; i++) await rejected(readPublicHtml(page))
|
|
198
|
+
assert.equal(calls.http.length, n, 'no authentication or error retries')
|
|
199
|
+
assert.ok(calls.http.every(({ res }) => res.destroyed))
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
test('do not drain a huge page; return a clean prefix even if the cap splits a UTF-8 character', async t => {
|
|
203
|
+
const bytes = 128 * 1024, body = new PassThrough()
|
|
204
|
+
body.write(Buffer.concat([Buffer.from('<html>'), Buffer.alloc(bytes - 7, 0x61), Buffer.from('好more')])) // intentionally never ends
|
|
205
|
+
network(t, [{ body, headers: { ...htmlHeaders, 'content-length': '999999999' } }])
|
|
206
|
+
const { html } = await readPublicHtml(page)
|
|
207
|
+
assert.equal(html, '<html>' + 'a'.repeat(bytes - 7))
|
|
208
|
+
assert.ok(body.destroyed)
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
test('the HTTP byte budget is shared across hops and includes data outside the decoded body', async t => {
|
|
212
|
+
const chunk = Buffer.alloc(64 * 1024)
|
|
213
|
+
const calls = network(t, Array.from({ length: 3 }, () => ({ status: 302, headers: { location: '/next' }, wire: [chunk, chunk, chunk] })))
|
|
214
|
+
await rejected(readPublicHtml(page))
|
|
215
|
+
assert.equal(calls.http.length, 3)
|
|
216
|
+
assert.ok(calls.http.at(-1).req.destroyed)
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
test('JSON and HTML fallback share a single opaque wire budget', async t => {
|
|
220
|
+
const chunk = Buffer.alloc(64 * 1024), budget = createPublicBudget()
|
|
221
|
+
assert.ok(Object.isFrozen(budget))
|
|
222
|
+
const calls = network(t, [
|
|
223
|
+
{ status: 503, headers: { 'content-type': 'application/json' }, wire: Array(4).fill(chunk) },
|
|
224
|
+
{ body: '<html><title>Would exceed budget</title>', wire: Array(5).fill(chunk) },
|
|
225
|
+
])
|
|
226
|
+
await rejected(readPublicJson(page, { budget }))
|
|
227
|
+
await rejected(readPublicHtml(page, { budget }))
|
|
228
|
+
assert.equal(calls.http.length, 2)
|
|
229
|
+
assert.ok(calls.http[1].req.destroyed)
|
|
230
|
+
assert.equal(calls.http[1].res, undefined)
|
|
231
|
+
await rejected(readPublicHtml(page, { budget: {} }))
|
|
232
|
+
assert.equal(calls.http.length, 2, 'invented budget tokens cannot authorize a request')
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
test('an exact-limit redirect cannot initiate another DNS lookup or request', async t => {
|
|
236
|
+
const chunk = Buffer.alloc(64 * 1024)
|
|
237
|
+
const calls = network(t, [{ status: 302, headers: { location: '/next' }, wire: Array(8).fill(chunk) }])
|
|
238
|
+
await rejected(readPublicHtml(page))
|
|
239
|
+
assert.equal(calls.dns.length, 2)
|
|
240
|
+
assert.equal(calls.http.length, 1)
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
test('an exact-limit final response is accepted but cannot fund another attempt', async t => {
|
|
244
|
+
const chunk = Buffer.alloc(64 * 1024), budget = createPublicBudget()
|
|
245
|
+
const calls = network(t, [{ body: '<html><title>At the limit</title>', wire: Array(8).fill(chunk) }])
|
|
246
|
+
assert.match((await readPublicHtml(page, { budget })).html, /At the limit/)
|
|
247
|
+
await rejected(readPublicHtml(page, { budget }))
|
|
248
|
+
assert.equal(calls.dns.length, 2)
|
|
249
|
+
assert.equal(calls.http.length, 1)
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
test('the total deadline cancels unresolved DNS; late DNS completion cannot start a request', async t => {
|
|
253
|
+
t.mock.timers.enable({ apis: ['setTimeout'] })
|
|
254
|
+
const slow = Promise.withResolvers(), calls = network(t, [], (_host, family) => family === 4 ? slow.promise : [])
|
|
255
|
+
const done = rejected(readPublicHtml(page))
|
|
256
|
+
t.mock.timers.tick(6000)
|
|
257
|
+
await done
|
|
258
|
+
assert.equal(calls.cancelled, 1)
|
|
259
|
+
slow.resolve([ipv4]); await new Promise(setImmediate)
|
|
260
|
+
assert.deepEqual(calls.http, [])
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
test('slow DNS and a stalled response share one deadline, including across a redirect', async t => {
|
|
264
|
+
t.mock.timers.enable({ apis: ['setTimeout'] })
|
|
265
|
+
const slow = Promise.withResolvers(), opened = Promise.withResolvers(), body = new PassThrough()
|
|
266
|
+
const calls = network(t, [{ status: 302, headers: { location: page } }, { body, opened: opened.resolve }],
|
|
267
|
+
(host, family) => family === 6 ? [] : host === 'other.org.' ? slow.promise : [ipv4])
|
|
268
|
+
const done = rejected(readPublicHtml('https://other.org/'))
|
|
269
|
+
t.mock.timers.tick(4000); slow.resolve([ipv4]); await opened.promise
|
|
270
|
+
t.mock.timers.tick(2000); await done
|
|
271
|
+
assert.ok(body.destroyed)
|
|
272
|
+
assert.ok(calls.http.every(({ req }) => req.destroyed))
|
|
273
|
+
assert.equal(calls.cancelled, 1)
|
|
274
|
+
})
|
|
275
|
+
|
|
276
|
+
test('transport errors and protocol upgrades are sanitized and release the socket', async t => {
|
|
277
|
+
const calls = network(t, [{ error: Error('fake remote details') }, { upgrade: true }])
|
|
278
|
+
await rejected(readPublicHtml(page))
|
|
279
|
+
await rejected(readPublicHtml(page))
|
|
280
|
+
assert.ok(calls.http.every(({ req }) => req.destroyed))
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
const dohAnswer = (family, answers = []) => ({
|
|
284
|
+
headers: { 'content-type': 'application/dns-json' },
|
|
285
|
+
body: JSON.stringify({ Status: 0, Answer: answers.map(data => ({ type: family === 4 ? 1 : 28, data })) }),
|
|
286
|
+
})
|
|
287
|
+
const fakeAnswers = (_host, family) => family === 4 ? ['198.18.0.34'] : []
|
|
288
|
+
|
|
289
|
+
test('an exact-limit DNS fallback cannot initiate the target connection', async t => {
|
|
290
|
+
const chunk = Buffer.alloc(64 * 1024)
|
|
291
|
+
const calls = network(t, [
|
|
292
|
+
{ ...dohAnswer(4, [ipv4]), wire: Array(4).fill(chunk) },
|
|
293
|
+
{ ...dohAnswer(6, []), wire: Array(4).fill(chunk) },
|
|
294
|
+
], fakeAnswers)
|
|
295
|
+
await rejected(readPublicHtml(page, { publicDnsFallback: true }))
|
|
296
|
+
assert.equal(calls.http.length, 2)
|
|
297
|
+
assert.ok(calls.http.every(({ options }) => options.hostname === '1.1.1.1'))
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
test('public DNS is opt-in; fake addresses are never connected even without fallback', async t => {
|
|
301
|
+
const calls = network(t, [], fakeAnswers)
|
|
302
|
+
await rejected(readPublicHtml(page))
|
|
303
|
+
assert.equal(calls.http.length, 0)
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
test('opted-in fake-IP DNS fallback sends only the hostname to a fixed pinned DNS endpoint', async t => {
|
|
307
|
+
const calls = network(t, [dohAnswer(4, [ipv4]), dohAnswer(6, [ipv6]), { body: '<html><title>OK</title>' }], fakeAnswers)
|
|
308
|
+
const result = await readPublicHtml(`${page}?article=example#anchor`, { publicDnsFallback: true })
|
|
309
|
+
assert.match(result.html, /<title>OK/)
|
|
310
|
+
assert.equal(calls.http.length, 3)
|
|
311
|
+
for (const { options } of calls.http.slice(0, 2)) {
|
|
312
|
+
assert.equal(options.hostname, '1.1.1.1')
|
|
313
|
+
assert.equal(options.servername, 'cloudflare-dns.com')
|
|
314
|
+
assert.equal(options.rejectUnauthorized, true)
|
|
315
|
+
assert.deepEqual(options.headers, { Host: 'cloudflare-dns.com', Accept: 'application/dns-json', 'Accept-Encoding': 'identity' })
|
|
316
|
+
const request = new URL(options.path, 'https://cloudflare-dns.com')
|
|
317
|
+
assert.equal(request.pathname, '/dns-query')
|
|
318
|
+
assert.equal(request.searchParams.get('name'), 'news.example.com')
|
|
319
|
+
assert.ok(['A', 'AAAA'].includes(request.searchParams.get('type')))
|
|
320
|
+
assert.equal(request.searchParams.size, 2)
|
|
321
|
+
assert.doesNotMatch(options.path, /story|article|anchor/)
|
|
322
|
+
}
|
|
323
|
+
const target = calls.http[2].options
|
|
324
|
+
assert.equal(target.hostname, ipv4)
|
|
325
|
+
assert.equal(target.servername, 'news.example.com')
|
|
326
|
+
assert.equal(target.path, '/story?article=example')
|
|
327
|
+
})
|
|
328
|
+
|
|
329
|
+
test('a normal system DNS answer does not contact the public DNS fallback', async t => {
|
|
330
|
+
const calls = network(t, [{ body: '<html>normal</html>' }])
|
|
331
|
+
assert.match((await readPublicHtml(page, { publicDnsFallback: true })).html, /normal/)
|
|
332
|
+
assert.equal(calls.http.length, 1)
|
|
333
|
+
assert.equal(calls.http[0].options.hostname, ipv4)
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
test('mixed fake, public, private, or malformed system answers never trigger fallback', async t => {
|
|
337
|
+
let v4, v6
|
|
338
|
+
const calls = network(t, [], (_host, family) => family === 4 ? v4 : v6)
|
|
339
|
+
for (const [a, b] of [
|
|
340
|
+
[['198.18.0.1', ipv4], []], [['198.18.0.1', '10.0.0.1'], []], [['198.18.0.1'], [ipv6]],
|
|
341
|
+
[['198.18.0.1'], ['::1']], [['198.18.0.1', 'invalid'], []], [[], []],
|
|
342
|
+
]) {
|
|
343
|
+
v4 = a; v6 = b
|
|
344
|
+
await rejected(readPublicHtml(page, { publicDnsFallback: true }))
|
|
345
|
+
}
|
|
346
|
+
assert.equal(calls.http.length, 0)
|
|
347
|
+
})
|
|
348
|
+
|
|
349
|
+
test('fallback answers are rechecked in both families; private, malformed or mixed IPs never reach a target socket', async t => {
|
|
350
|
+
const cases = [
|
|
351
|
+
[dohAnswer(4, ['10.0.0.1']), dohAnswer(6, [])],
|
|
352
|
+
[dohAnswer(4, [ipv4, '198.18.0.34']), dohAnswer(6, [])],
|
|
353
|
+
[dohAnswer(4, [ipv4]), dohAnswer(6, ['::1'])],
|
|
354
|
+
[dohAnswer(4, ['invalid']), dohAnswer(6, [ipv6])],
|
|
355
|
+
[dohAnswer(4, []), dohAnswer(6, [])],
|
|
356
|
+
[dohAnswer(4, Array(65).fill(ipv4)), dohAnswer(6, [])],
|
|
357
|
+
]
|
|
358
|
+
const calls = network(t, cases.flat(), fakeAnswers)
|
|
359
|
+
for (const _case of cases) await rejected(readPublicHtml(page, { publicDnsFallback: true }))
|
|
360
|
+
assert.equal(calls.http.length, cases.length * 2)
|
|
361
|
+
assert.ok(calls.http.every(({ options }) => options.hostname === '1.1.1.1'))
|
|
362
|
+
})
|
|
363
|
+
|
|
364
|
+
test('fallback DNS refuses redirects, status failures, bad encodings, duplicate headers and oversized or invalid JSON', async t => {
|
|
365
|
+
const bad = [
|
|
366
|
+
{ status: 302, headers: { location: 'https://elsewhere.org/' } },
|
|
367
|
+
{ status: 403, headers: { 'content-type': 'application/dns-json' } },
|
|
368
|
+
{ headers: { 'content-type': ['application/dns-json', 'text/html'] } },
|
|
369
|
+
{ headers: { 'content-type': 'application/dns-json', 'content-encoding': 'gzip' } },
|
|
370
|
+
{ headers: { 'content-type': 'text/html' }, body: '<html>wrong</html>' },
|
|
371
|
+
{ headers: { 'content-type': 'application/dns-json' }, body: '{' },
|
|
372
|
+
{ headers: { 'content-type': 'application/dns-json' }, body: ' '.repeat(16 * 1024 + 1) },
|
|
373
|
+
{ headers: { 'content-type': 'application/dns-json' }, body: JSON.stringify({ Status: 3 }) },
|
|
374
|
+
{ headers: { 'content-type': 'application/dns-json' }, body: JSON.stringify({ Status: 0, Answer: [{ type: 28, data: ipv6 }] }) },
|
|
375
|
+
]
|
|
376
|
+
const calls = network(t, bad.flatMap(reply => [reply, dohAnswer(6)]), fakeAnswers)
|
|
377
|
+
for (const _case of bad) await rejected(readPublicHtml(page, { publicDnsFallback: true }))
|
|
378
|
+
assert.equal(calls.http.length, bad.length * 2)
|
|
379
|
+
assert.ok(calls.http.every(({ options }) => options.hostname === '1.1.1.1'))
|
|
380
|
+
})
|
|
381
|
+
|
|
382
|
+
test('caller cancellation stops pending DNS before a connection can be made', async t => {
|
|
383
|
+
const slow = Promise.withResolvers(), control = new AbortController()
|
|
384
|
+
const calls = network(t, [], (_host, family) => family === 4 ? slow.promise : [])
|
|
385
|
+
const done = rejected(readPublicJson(page, { signal: control.signal }))
|
|
386
|
+
control.abort()
|
|
387
|
+
await done
|
|
388
|
+
slow.resolve([ipv4]); await new Promise(setImmediate)
|
|
389
|
+
assert.equal(calls.http.length, 0)
|
|
390
|
+
assert.equal(calls.cancelled, 1)
|
|
391
|
+
})
|
|
392
|
+
|
|
393
|
+
test('fallback DNS queries share the total deadline and stalled requests are aborted', async t => {
|
|
394
|
+
t.mock.timers.enable({ apis: ['setTimeout'] })
|
|
395
|
+
const opened4 = Promise.withResolvers(), opened6 = Promise.withResolvers()
|
|
396
|
+
const first = new PassThrough(), second = new PassThrough()
|
|
397
|
+
const calls = network(t, [
|
|
398
|
+
{ body: first, headers: { 'content-type': 'application/dns-json' }, opened: opened4.resolve },
|
|
399
|
+
{ body: second, headers: { 'content-type': 'application/dns-json' }, opened: opened6.resolve },
|
|
400
|
+
], fakeAnswers)
|
|
401
|
+
const done = rejected(readPublicHtml(page, { publicDnsFallback: true }))
|
|
402
|
+
await Promise.all([opened4.promise, opened6.promise])
|
|
403
|
+
t.mock.timers.tick(6000)
|
|
404
|
+
await done
|
|
405
|
+
assert.ok(first.destroyed && second.destroyed)
|
|
406
|
+
assert.ok(calls.http.every(({ req }) => req.destroyed))
|
|
407
|
+
assert.equal(calls.cancelled, 1)
|
|
408
|
+
})
|
|
409
|
+
|
|
410
|
+
test('HTTPS pages cannot downgrade to HTTP on a redirect', async t => {
|
|
411
|
+
const calls = network(t, [{ status: 302, headers: { location: 'http://news.example.com/plain' } }])
|
|
412
|
+
await rejected(readPublicHtml(page))
|
|
413
|
+
assert.equal(calls.http.length, 1)
|
|
414
|
+
assert.equal(calls.dns.length, 2)
|
|
415
|
+
})
|
|
416
|
+
|
|
417
|
+
test('bounded JSON requires HTTPS, exact JSON type and no redirects', async t => {
|
|
418
|
+
const calls = network(t, [
|
|
419
|
+
{ headers: { 'content-type': 'application/json; charset=utf-8' }, body: '{"name":"ok"}' },
|
|
420
|
+
{ status: 302, headers: { location: '/next' } },
|
|
421
|
+
{ headers: { 'content-type': 'text/html' }, body: '{"name":"bad"}' },
|
|
422
|
+
{ headers: { 'content-type': 'application/json', 'content-encoding': 'gzip' }, body: '{"name":"bad"}' },
|
|
423
|
+
{ headers: { 'content-type': 'application/json' }, body: '{"x":"' + 'x'.repeat(128 * 1024) + '"}' },
|
|
424
|
+
{ headers: { 'content-type': 'application/json' }, body: '{' },
|
|
425
|
+
{ headers: { 'content-type': 'application/json' }, body: Buffer.from([0xff]) },
|
|
426
|
+
])
|
|
427
|
+
assert.deepEqual(await readPublicJson(page), { name: 'ok' })
|
|
428
|
+
assert.equal(calls.http[0].options.headers.Accept, 'application/json')
|
|
429
|
+
for (let i = 0; i < 6; i++) await rejected(readPublicJson(page))
|
|
430
|
+
await rejected(readPublicJson('http://news.example.com/'))
|
|
431
|
+
assert.equal(calls.http.length, 7)
|
|
432
|
+
})
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import test from 'node:test'
|
|
3
|
+
import { extractPageTitle } from '../title.js'
|
|
4
|
+
|
|
5
|
+
// Local fixtures only. Paths describe the intended page; the caller classifies the URL.
|
|
6
|
+
const pages = [
|
|
7
|
+
['GitHub repository', 'github', '<!doctype html><html><head><title>river-lab/paper-boat · GitHub</title><meta property="og:type" content="object"><meta content="GitHub - river-lab/paper-boat: Fold & float" property="og:title"></head><body><nav><a>Sign in</a></nav>', 'GitHub - river-lab/paper-boat: Fold & float'],
|
|
8
|
+
['GitHub issue', 'github', `<meta property='og:title' content='Fix the sign-in error > 2 tabs · Issue #7 · river-lab/paper-boat'><title>Issue #7 · GitHub</title>`, 'Fix the sign-in error > 2 tabs · Issue #7 · river-lab/paper-boat'],
|
|
9
|
+
['GitHub pull request (document title only)', 'github', '<title>Make boats foldable · Pull Request #8 · river-lab/paper-boat · GitHub</title>', 'Make boats foldable · Pull Request #8 · river-lab/paper-boat · GitHub'],
|
|
10
|
+
['WeChat /s/ShortArticleKey: prefer visible article h1', 'wechat', '<head><meta property="og:title" content="旧版标题"><title>微信公众平台</title></head><div class="rich_media_area_primary"><h1 class="rich_media_title" id="activity-name">\n 河畔<strong>手记</strong><br> 风与山 </h1><div id="js_content">', '河畔手记 风与山'],
|
|
11
|
+
['WeChat /s?__biz=TestAccount&mid=10&idx=1&sn=a: head prefix only', 'wechat', '<meta property="og:type" content="article"><META NAME=og:title CONTENT="\n小城 & 大海 🌊 \t"><script type="application/json">', '小城 & 大海 🌊'],
|
|
12
|
+
['WeChat: body h1 without OG', 'wechat', `<h1 ID=activity-name>写给<em>春天</em>的信</h1>`, '写给春天的信'],
|
|
13
|
+
['WeChat: bare article-specific title fallback', 'wechat', '<title>初雪之后的河岸</title>', '初雪之后的河岸'],
|
|
14
|
+
['web: OG wins, attribute order/case/quotes and whitespace', 'web', `<title>Alternate title</title><mEtA data-note='not content="decoy"' CONTENT=' A > B\n "résumé" — 明日 ' PrOpErTy = og:title>`, 'A > B "résumé" — 明日'],
|
|
15
|
+
['web: unquoted text and name attribute', 'web', '<meta CONTENT=Wind&Water name=og:title />', 'Wind&Water'],
|
|
16
|
+
['web: empty OG falls back to a complete title in an incomplete document', 'web', '<meta content=" " property="og:title"><title>Memo: café < 10% & rising</title><div data-note="', 'Memo: café < 10% & rising'],
|
|
17
|
+
['web: only decode one layer of entities', 'web', '<title>R&amp;D © © 中</title>', 'R&D © © 中'],
|
|
18
|
+
['web: controls and bidirectional overrides are not part of labels', 'web', '<title>\u0000Atlas\u001b\u202e⁦‏\n 工\u202c具\u0007</title>', 'Atlas 工具'],
|
|
19
|
+
['web: Twitter name fallback with attribute order, case and whitespace', 'web', `<META CONTENT=' Sky & Sea — 明天 ' NAME=' TwItTeR:TiTlE '>`, 'Sky & Sea — 明天'],
|
|
20
|
+
['web: Twitter property fallback with unquoted value', 'web', '<meta content=Wind&Water property=twitter:title />', 'Wind&Water'],
|
|
21
|
+
['web: Twitter skips empty or generic labels', 'web', '<meta name=twitter:title content=" "><meta property=twitter:title content=Home><meta name=twitter:title content="First valid"><meta name=twitter:title content="Second valid">', 'First valid'],
|
|
22
|
+
['web: document title keeps precedence over Twitter regardless of order', 'web', '<meta name=twitter:title content="Social title"><title>Document title</title>', 'Document title'],
|
|
23
|
+
['web: OG keeps precedence over Twitter and document title', 'web', '<meta name=twitter:title content="Social title"><title>Document title</title><meta property=og:title content="Open Graph title">', 'Open Graph title'],
|
|
24
|
+
['web: a tag can declare both OG and Twitter keys', 'web', '<meta name=twitter:title property=og:title content="Shared metadata"><meta property=og:title content="Later OG">', 'Shared metadata'],
|
|
25
|
+
['GitHub: Twitter when only generic document title exists', 'github', '<title>GitHub · GitHub</title><meta name=twitter:title content="river-lab/paper-boat">', 'river-lab/paper-boat'],
|
|
26
|
+
['WeChat: Twitter when only platform document title exists', 'wechat', '<title>微信公众平台</title><meta property=twitter:title content="河畔手记">', '河畔手记'],
|
|
27
|
+
['WeChat: article heading keeps precedence over all metadata', 'wechat', '<meta name=twitter:title content="社交标题"><meta property=og:title content="旧版标题"><title>文档标题</title><h1 id=activity-name>正文标题</h1>', '正文标题'],
|
|
28
|
+
['web: Twitter labels decode one entity layer and strip controls', 'web', '<meta name=twitter:title content="A&amp;B © \u0000\u202e⁦‏\n Cafe">', 'A&B © Cafe'],
|
|
29
|
+
]
|
|
30
|
+
for (const [page, kind, html, expected] of pages) test(page, () => assert.equal(extractPageTitle(html, kind), expected))
|
|
31
|
+
|
|
32
|
+
const unavailable = [
|
|
33
|
+
['GitHub brand alone', 'github', '<meta content=GitHub property=og:title><title>GitHub · GitHub</title>'],
|
|
34
|
+
['GitHub sign-in page with plausible OG', 'github', '<meta content="river-lab/paper-boat" property=og:title><title>Sign in to GitHub · GitHub</title>'],
|
|
35
|
+
['GitHub soft 404', 'github', '<TITLE>Page not found · GitHub</TITLE>'],
|
|
36
|
+
['GitHub challenge despite plausible tab title', 'github', '<meta property=og:title content="Just a moment…"><title>river-lab/paper-boat</title>'],
|
|
37
|
+
['WeChat platform title is not an article title', 'wechat', '<meta name=og:title content="微信公众平台"><title>微信公众平台</title><h1>欢迎</h1>'],
|
|
38
|
+
['WeChat verification page', 'wechat', '<title>微信公众平台</title><meta name=og:title content="昨日的文章"><div class="weui-msg__title">环境异常</div><div>完成验证后即可继续访问。</div>'],
|
|
39
|
+
['WeChat removal notice with stale metadata', 'wechat', '<meta property=og:title content="河边游记"><h2 class="weui-msg__title">该内容已被发布者删除</h2>'],
|
|
40
|
+
['WeChat removal notice overrides even a retained article heading', 'wechat', '<h1 id="activity-name">旧标题</h1><p>该文章已被作者删除。</p>'],
|
|
41
|
+
['WeChat article-heading marker without a useful title', 'wechat', '<h1 id="activity-name">\u200b\n </h1>'],
|
|
42
|
+
['web challenge heading on a branded page', 'web', '<title>Field Notes</title><h1>Verify you are human</h1>'],
|
|
43
|
+
['web rate-limit response', 'web', '<title>429 Too Many Requests</title>'],
|
|
44
|
+
['web placeholder with no metadata', 'web', '<meta property="og:description" content="A description, not a title"><title>Untitled Document</title>'],
|
|
45
|
+
['JS-only site', 'web', `<script>document.title = 'Not a static title'</script><div id=app></div>`],
|
|
46
|
+
['comment, raw text, inert content and SVG icon titles are not page metadata', 'web', `<!-- <title>comment</title> --><script type=application/ld+json>{"example":"<meta property=og:title content=JSON>"}</script><textarea><title>draft</title></textarea><template><template><title>template</title></template></template><svg><title>Icon</title></svg>`],
|
|
47
|
+
['unterminated comment in a partial response', 'web', '<!-- navigation starts here <meta property=og:title content=not-a-title>'],
|
|
48
|
+
['incomplete quoted metadata', 'web', '<meta property=og:title content="Not complete'],
|
|
49
|
+
['truncated document title', 'web', '<title>Still loading'],
|
|
50
|
+
['Twitter rejects a challenge even with plausible OG and document titles', 'web', '<meta property=og:title content="Old title"><title>Old title</title><meta name=twitter:title content="Just a moment…">'],
|
|
51
|
+
['Twitter property rejects a sign-in gate despite an article heading', 'wechat', '<h1 id=activity-name>旧文章</h1><meta property=twitter:title content="Sign in required">'],
|
|
52
|
+
['Twitter duplicate gate is not hidden by an earlier usable value', 'web', '<meta name=twitter:title content="Old article"><meta name=twitter:title content="Access denied">'],
|
|
53
|
+
['document login gate overrides stale Twitter metadata', 'github', '<meta name=twitter:title content="river-lab/paper-boat"><title>Sign in to GitHub · GitHub</title>'],
|
|
54
|
+
['OG challenge overrides stale Twitter metadata', 'web', '<meta name=twitter:title content="Old article"><meta property=og:title content="Just a moment…">'],
|
|
55
|
+
['challenge form overrides stale Twitter metadata', 'web', '<meta name=twitter:title content="Old article"><form id=challenge-form></form>'],
|
|
56
|
+
['challenge heading overrides stale Twitter metadata', 'web', '<meta name=twitter:title content="Old article"><h1>Verify you are human</h1>'],
|
|
57
|
+
['WeChat removal notice overrides stale Twitter metadata', 'wechat', '<meta name=twitter:title content="河边游记"><div>该内容已被发布者删除。</div>'],
|
|
58
|
+
['Twitter-like descriptions are not titles', 'web', '<meta name=twitter:description content="Not a title"><meta property=twitter:title:alt content="Not a title">'],
|
|
59
|
+
['incomplete Twitter metadata is not a title', 'web', '<meta name=twitter:title content="Not complete'],
|
|
60
|
+
['hidden and unmarked headings are not title fallbacks', 'web', '<div hidden><h1>Private account</h1></div><h1>Welcome back</h1><form><input type=password></form>'],
|
|
61
|
+
]
|
|
62
|
+
for (const [page, kind, html] of unavailable) test(page, () => assert.equal(extractPageTitle(html, kind), ''))
|
|
63
|
+
|
|
64
|
+
test('ignore decoys without losing later genuine metadata in a minified document', () => {
|
|
65
|
+
const decoy = '<meta property=og:title content=decoy>'
|
|
66
|
+
const html = `<!--${decoy}--><STYLE>q::after{content:'${decoy}'}</STYLE><script>let example = '${decoy}'</SCRIPT ><div data-sample='${decoy}'></div><title>Actual title</title>`
|
|
67
|
+
assert.equal(extractPageTitle(html, 'web'), 'Actual title')
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
test('title precedence does not depend on the order of metadata or headings', () => {
|
|
71
|
+
const twitter = '<meta name=twitter:title content="Twitter title">'
|
|
72
|
+
const document = '<title>Document title</title>'
|
|
73
|
+
const og = '<meta property=og:title content="OG title">'
|
|
74
|
+
const article = '<h1 id=activity-name>WeChat article</h1>'
|
|
75
|
+
for (const order of [[twitter, document], [document, twitter]]) {
|
|
76
|
+
assert.equal(extractPageTitle(order.join(''), 'web'), 'Document title')
|
|
77
|
+
}
|
|
78
|
+
for (const order of [[twitter, document, og], [og, document, twitter]]) {
|
|
79
|
+
assert.equal(extractPageTitle(order.join(''), 'web'), 'OG title')
|
|
80
|
+
}
|
|
81
|
+
for (const order of [[twitter, document, og, article], [article, og, document, twitter]]) {
|
|
82
|
+
assert.equal(extractPageTitle(order.join(''), 'wechat'), 'WeChat article')
|
|
83
|
+
}
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
test('Twitter metadata in comments, raw text and inert content is ignored', () => {
|
|
87
|
+
const decoy = '<meta name=twitter:title content=decoy>'
|
|
88
|
+
const html = `<!--${decoy}--><style>${decoy}</style><script>${decoy}</script><textarea>${decoy}</textarea><template>${decoy}</template><svg>${decoy}</svg>`
|
|
89
|
+
assert.equal(extractPageTitle(html, 'web'), '')
|
|
90
|
+
assert.equal(extractPageTitle(`${html}<meta name=twitter:title content="Real title">`, 'web'), 'Real title')
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
test('Twitter labels obey the 200-character and surrogate protections', () => {
|
|
94
|
+
const long = 'a'.repeat(198) + '📘'.repeat(30)
|
|
95
|
+
const actual = extractPageTitle(`<meta name=twitter:title content="${long}">`, 'web')
|
|
96
|
+
assert.equal(actual, 'a'.repeat(198) + '…')
|
|
97
|
+
assert.ok(actual.isWellFormed())
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
test('Twitter metadata outside the bounded HTML prefix is ignored', () => {
|
|
101
|
+
assert.equal(extractPageTitle(' '.repeat(1024 * 1024) + '<meta name=twitter:title content=late>', 'web'), '')
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
test('WeChat status-like strings in a script do not invalidate an article', () => {
|
|
105
|
+
const html = `<script>var warning = '该内容已被发布者删除';</script><title>河道笔记</title>`
|
|
106
|
+
assert.equal(extractPageTitle(html, 'wechat'), '河道笔记')
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
test('truncate a long label without cutting a surrogate pair', () => {
|
|
110
|
+
const long = 'a'.repeat(198) + '📘'.repeat(30)
|
|
111
|
+
const actual = extractPageTitle(`<title>${long}</title>`, 'web')
|
|
112
|
+
assert.equal(actual, 'a'.repeat(198) + '…')
|
|
113
|
+
assert.ok(actual.isWellFormed())
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('reject unsupported inputs without throwing or guessing a title', () => {
|
|
117
|
+
for (const input of [undefined, null, '', {}, Buffer.from('<title>Encoded</title>')]) assert.equal(extractPageTitle(input, 'web'), '')
|
|
118
|
+
assert.equal(extractPageTitle('<title>Page</title>', 'unknown'), '')
|
|
119
|
+
assert.equal(extractPageTitle(`<title>${'��'}</title>`, 'web'), '')
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
test('scan broken or bounded prefixes without treating script text or a partial tag as metadata', () => {
|
|
123
|
+
const incomplete = '<div data-note="' + '<meta property=og:title content=wrong>'.repeat(6000)
|
|
124
|
+
assert.equal(extractPageTitle(incomplete, 'web'), '')
|
|
125
|
+
assert.equal(extractPageTitle('<script>' + '<script>'.repeat(40000) + '<title>wrong</title>', 'web'), '')
|
|
126
|
+
assert.equal(extractPageTitle(' '.repeat(1024 * 1024) + '<title>Outside the budget</title>', 'web'), '')
|
|
127
|
+
})
|