dsh-inline-link-preview 0.0.0-stage → 0.5.0-beta.1
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 +56 -2
- 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 +189 -0
- package/link-policy.js +61 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +65 -4
- package/public-fetch.js +178 -0
- package/test/host.test.js +99 -0
- package/test/inline.test.js +256 -0
- package/test/public-fetch.test.js +248 -0
- package/test/title.test.js +72 -0
- package/title.js +183 -0
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import test from 'node:test'
|
|
4
|
+
import vm from 'node:vm'
|
|
5
|
+
|
|
6
|
+
// Load the actual Client entry, but never render an editor, touch the clipboard or send a message.
|
|
7
|
+
let plugin, source
|
|
8
|
+
const loader = { load(module) { plugin = module.factory(() => ({})) } }
|
|
9
|
+
vm.runInNewContext(readFileSync(new URL('../client.js', import.meta.url), 'utf8'), {
|
|
10
|
+
window: { __ModuleLoader__: loader }, URL, AbortController, AbortSignal,
|
|
11
|
+
})
|
|
12
|
+
plugin.apply({
|
|
13
|
+
get: name => name === 'inputTriggers' ? { registerSource(value) { source = value } } : {},
|
|
14
|
+
effect: fn => fn(), locale: { register() {}, bind: () => key => key }, slots: { inject() {} },
|
|
15
|
+
})
|
|
16
|
+
const token = 'ExampleToken00001'
|
|
17
|
+
const doc = `https://team.feishu.cn/docx/${token}`
|
|
18
|
+
const wiki = `https://team.feishu.cn/wiki/${token}`
|
|
19
|
+
const signal = () => new AbortController().signal
|
|
20
|
+
|
|
21
|
+
// A test double for the published InputActions contract. Offsets are UTF-16 units in the
|
|
22
|
+
// detect projection, in which each earlier chip/quote occupies exactly one unit, not its URL.
|
|
23
|
+
function actionsFor(text, start, end = start) {
|
|
24
|
+
const s = { text, start, end, draftRev: 1, current: true, requests: [], notices: 0, chips: [] }
|
|
25
|
+
const api = {
|
|
26
|
+
current: () => s.current,
|
|
27
|
+
actions: {
|
|
28
|
+
captureInsertion: () => ({ start: s.start, end: s.end, draftRev: s.draftRev }),
|
|
29
|
+
insertText(value, at) {
|
|
30
|
+
if (at.draftRev !== s.draftRev) return false
|
|
31
|
+
s.text = s.text.slice(0, at.start) + value + s.text.slice(at.end)
|
|
32
|
+
s.start = s.end = at.start + value.length
|
|
33
|
+
s.draftRev++
|
|
34
|
+
return true
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
async readTitle(lookup) { s.requests.push(lookup); return '文档标题' },
|
|
38
|
+
unavailable() { s.notices++ },
|
|
39
|
+
session: {
|
|
40
|
+
bail(scope, eventName, { span, reference }) {
|
|
41
|
+
assert.equal(scope, this, 'explicit Cordis origin required to avoid affecting another retained session')
|
|
42
|
+
assert.equal(eventName, 'slash/input-insert-reference')
|
|
43
|
+
if (span.draftRev !== s.draftRev) return false
|
|
44
|
+
assert.equal(s.text.slice(span.start, span.end), reference.clipboardText)
|
|
45
|
+
s.chips.push({ span, reference })
|
|
46
|
+
const next = s.text.slice(span.end), inserted = next[0] === ' ' ? '\ufffc' : '\ufffc '
|
|
47
|
+
s.text = s.text.slice(0, span.start) + inserted + next
|
|
48
|
+
s.start = s.end = span.start + inserted.length
|
|
49
|
+
s.draftRev++
|
|
50
|
+
return true
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
}
|
|
54
|
+
return { s, api }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
for (const kind of ['docx', 'wiki']) {
|
|
58
|
+
for (const host of ['feishu.cn', 'tenant.larksuite.com', 'a.b.larkoffice.com']) {
|
|
59
|
+
test(`one ${kind} link on ${host}: render only the title, keep original path for copy/serialize`, async () => {
|
|
60
|
+
const clean = `https://${host}/${kind}/${token}`
|
|
61
|
+
const url = `${clean}?from=copy&disposable_login_token=not-a-credential#section`
|
|
62
|
+
const { api, s } = actionsFor('', 0)
|
|
63
|
+
const pending = plugin.pasteLink(url, api, signal())
|
|
64
|
+
// Even sending before +inspect finishes must not send a disposable login token.
|
|
65
|
+
assert.equal(s.text, `${clean}?from=copy#section`)
|
|
66
|
+
assert.equal(await pending, true)
|
|
67
|
+
assert.deepEqual(s.requests, [clean])
|
|
68
|
+
assert.equal(s.chips.length, 1)
|
|
69
|
+
const { reference } = s.chips[0]
|
|
70
|
+
assert.equal(reference.source, source.name)
|
|
71
|
+
assert.equal(reference.appearance, 'file')
|
|
72
|
+
assert.equal(reference.label, '文档标题')
|
|
73
|
+
assert.equal(reference.clipboardText, `${clean}?from=copy#section`)
|
|
74
|
+
assert.equal(source.codec.clipboardText(reference.ref), reference.clipboardText)
|
|
75
|
+
assert.equal(await source.codec.serialize(reference.ref, signal()), reference.clipboardText)
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
for (const [kind, ref, expectedLookup] of [
|
|
81
|
+
['github', 'https://github.com/octocat/Hello-World/issues/1#issuecomment-1', 'https://github.com/octocat/Hello-World/issues/1'],
|
|
82
|
+
['wechat', 'https://mp.weixin.qq.com/s/ArticleSlug#rd', 'https://mp.weixin.qq.com/s/ArticleSlug'],
|
|
83
|
+
['web', 'https://example.org/articles?q=word#section', 'https://example.org/articles?q=word'],
|
|
84
|
+
['web', 'http://www.example.com/', 'http://www.example.com/'],
|
|
85
|
+
['web', `https://feishu.cn.example.com/wiki/${token}`, `https://feishu.cn.example.com/wiki/${token}`],
|
|
86
|
+
]) {
|
|
87
|
+
test(`${kind}: native icon + title in the pasted range, copy/send the original link`, async () => {
|
|
88
|
+
const { api, s } = actionsFor('参考 谢谢', 3)
|
|
89
|
+
assert.equal(plugin.parseLink(ref).kind, kind)
|
|
90
|
+
const result = plugin.pasteLink(ref, api, signal())
|
|
91
|
+
assert.equal(s.text, `参考 ${ref} 谢谢`)
|
|
92
|
+
assert.equal(await result, true)
|
|
93
|
+
assert.deepEqual(s.requests, [expectedLookup])
|
|
94
|
+
assert.equal(s.text, '参考 \ufffc 谢谢')
|
|
95
|
+
const { reference } = s.chips[0]
|
|
96
|
+
assert.equal(reference.appearance, 'file')
|
|
97
|
+
assert.equal(reference.label, '文档标题')
|
|
98
|
+
assert.equal(source.codec.clipboardText(reference.ref), ref)
|
|
99
|
+
assert.equal(await source.codec.serialize(reference.ref, signal()), ref)
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
test('WeChat long article: signed/tracking parameters never go into the metadata request; retain article identity', () => {
|
|
104
|
+
const base = 'https://mp.weixin.qq.com/s?__biz=abc%3D&mid=10&idx=1&sn=test'
|
|
105
|
+
const url = base + '&scene=1&pass_ticket=fixture&exportkey=fixture#wechat_redirect'
|
|
106
|
+
const result = plugin.parseLink(url)
|
|
107
|
+
assert.equal(result.kind, 'wechat')
|
|
108
|
+
assert.equal(result.lookup, base)
|
|
109
|
+
assert.equal(result.ref, base + '&scene=1#wechat_redirect')
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
test('private, sensitive, non-article and non-web addresses use normal paste without lookup', () => {
|
|
113
|
+
for (const url of ['http://127.0.0.1/a', 'https://team.local/a', 'https://localhost/', 'https://host/',
|
|
114
|
+
'http://[::1]/', 'ftp://example.org/file', 'https://example.org:8080/', 'https://u:p@example.org/',
|
|
115
|
+
'https://example.org/page?access_token=test', 'https://example.org/page?X-Amz-Signature=test',
|
|
116
|
+
'https://example.org/page#access_token=test', 'https://example.org/oauth/authorize',
|
|
117
|
+
'https://mp.weixin.qq.com/cgi-bin/login', 'https://mp.weixin.qq.com/s?scene=1']) {
|
|
118
|
+
const { api, s } = actionsFor('原文', 0)
|
|
119
|
+
assert.equal(plugin.pasteLink(url, api, signal()), null, url)
|
|
120
|
+
assert.equal(s.text, '原文'); assert.equal(s.requests.length, 0)
|
|
121
|
+
}
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
test('public failure/challenge preserves a working copyable URL and uses public-page feedback', async () => {
|
|
125
|
+
const { api, s } = actionsFor('看 ', 2)
|
|
126
|
+
const url = 'https://mp.weixin.qq.com/s/ArticleSlug#rd'
|
|
127
|
+
let notice
|
|
128
|
+
api.readTitle = async () => ''
|
|
129
|
+
api.unavailable = kind => { notice = kind }
|
|
130
|
+
assert.equal(await plugin.pasteLink(url, api, signal()), false)
|
|
131
|
+
assert.equal(notice, 'wechat'); assert.equal(s.chips.length, 0); assert.equal(s.text, `看 ${url}`)
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
test('replace the selection in a sentence after an earlier chip and an identical literal link', async () => {
|
|
135
|
+
const prefix = '看📄 \ufffc ' + wiki + '\n这里 ', suffix = ' 再写摘要'
|
|
136
|
+
const { api, s } = actionsFor(prefix + '占位' + suffix, prefix.length, prefix.length + 2)
|
|
137
|
+
assert.equal(await plugin.pasteLink(wiki, api, signal()), true)
|
|
138
|
+
assert.equal(s.chips[0].span.start, prefix.length)
|
|
139
|
+
assert.equal(s.text, prefix + '\ufffc' + suffix)
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
test('normal text, multiple links and nonmatching URLs are not intercepted', () => {
|
|
143
|
+
const { s, api } = actionsFor('原文', 0)
|
|
144
|
+
for (const text of [`说明 ${doc}`, `${doc}\n${wiki}`, `${doc} ${wiki}`, 'file:///tmp/index.html',
|
|
145
|
+
`http://team.feishu.cn/docx/${token}`, `https://team.feishu.cn/sheets/${token}`,
|
|
146
|
+
`https://localhost/wiki/${token}`, doc.replace('team.feishu.cn', 'u@team.feishu.cn'),
|
|
147
|
+
doc.replace('team.feishu.cn', 'team.feishu.cn:3000'), `${wiki}/extra`]) {
|
|
148
|
+
assert.equal(plugin.pasteLink(text, api, signal()), null, text)
|
|
149
|
+
}
|
|
150
|
+
assert.equal(s.text, '原文')
|
|
151
|
+
assert.equal(s.requests.length, 0)
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
test('lookup drops all parameters, reference drops repeated/case-insensitive credential keys only', () => {
|
|
155
|
+
const info = plugin.parseLink(` ${wiki}/?Access_TOKEN=first&from=search&access_token=second&disposable_login_token=third&disposable_login_token=fourth#block `)
|
|
156
|
+
assert.equal(info.lookup, wiki)
|
|
157
|
+
assert.equal(info.ref, `${wiki}/?from=search#block`)
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
test('strip known credential fields in fragments without altering normal paragraph anchors', async () => {
|
|
161
|
+
for (const [hash, keep] of [
|
|
162
|
+
['#access_token=sample', ''], ['#?%61ccess_token=sample&from=copy', '#?from=copy'],
|
|
163
|
+
['#block42?disposable_login_token=one&refresh_token=two', '#block42'],
|
|
164
|
+
['#block42&ID_TOKEN=sample', '#block42'], ['#scroll=%e4%b8%ad&access_token=sample', '#scroll=%e4%b8%ad'],
|
|
165
|
+
['#paragraph%2F42', '#paragraph%2F42'],
|
|
166
|
+
]) {
|
|
167
|
+
const { api, s } = actionsFor('', 0)
|
|
168
|
+
const pending = plugin.pasteLink(wiki + hash, api, signal())
|
|
169
|
+
assert.equal(s.text, wiki + keep)
|
|
170
|
+
assert.equal(await pending, true)
|
|
171
|
+
assert.deepEqual(s.requests, [wiki])
|
|
172
|
+
assert.equal(await source.codec.serialize(s.chips[0].reference.ref, signal()), wiki + keep)
|
|
173
|
+
}
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
test('two retained sessions: only the explicitly addressed session consumes the reference', async () => {
|
|
177
|
+
const a = actionsFor(wiki, wiki.length), b = actionsFor('', 0)
|
|
178
|
+
a.s.draftRev = b.s.draftRev + 1 // same revision and replaceable URL after B pastes
|
|
179
|
+
const handlers = new Map([a, b].map(({ api }) => [api.session, api.session.bail.bind(api.session)]))
|
|
180
|
+
for (const context of handlers.keys()) context.bail = (origin, event, data) => {
|
|
181
|
+
if (typeof origin === 'string') return handlers.get(a.api.session)(a.api.session, origin, event)
|
|
182
|
+
return handlers.get(origin)(origin, event, data)
|
|
183
|
+
}
|
|
184
|
+
assert.equal(await plugin.pasteLink(wiki, b.api, signal()), true)
|
|
185
|
+
assert.equal(a.s.text, wiki)
|
|
186
|
+
assert.equal(a.s.chips.length, 0)
|
|
187
|
+
assert.equal(b.s.chips.length, 1)
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
test('no-op navigation, copy and modifiers do not cancel; submit, edit, IME and blur do', () => {
|
|
191
|
+
const card = new EventTarget(), view = new EventTarget()
|
|
192
|
+
let count = 0
|
|
193
|
+
const off = plugin.watchInterruptions(card, view, () => { count++ })
|
|
194
|
+
const key = (name, metaKey = false) => card.dispatchEvent(Object.assign(new Event('keydown'), { key: name, metaKey }))
|
|
195
|
+
key('Shift'); key('Meta'); key('ArrowRight'); key('c', true); assert.equal(count, 0)
|
|
196
|
+
key('Enter'); card.dispatchEvent(new Event('beforeinput')); card.dispatchEvent(new Event('compositionstart')); view.dispatchEvent(new Event('blur'))
|
|
197
|
+
assert.equal(count, 4)
|
|
198
|
+
off(); key('Escape'); view.dispatchEvent(new Event('blur'))
|
|
199
|
+
assert.equal(count, 4)
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
test('padded clipboard: preserve plain whitespace around a normalized link, including a newline, and the typing position', async () => {
|
|
203
|
+
for (const suffix of ['\n', ' ', '\t', ' \n ']) {
|
|
204
|
+
const { api, s } = actionsFor('参考:下一段', 3)
|
|
205
|
+
const pending = plugin.pasteLink(' ' + wiki + '?disposable_login_token=sample' + suffix, api, signal())
|
|
206
|
+
assert.equal(s.text, '参考: ' + wiki + suffix + '下一段')
|
|
207
|
+
assert.equal(await pending, true)
|
|
208
|
+
const expected = '参考: \ufffc' + suffix + '下一段'
|
|
209
|
+
assert.equal(s.text, expected)
|
|
210
|
+
assert.equal(s.start, expected.indexOf('下一段')); assert.equal(s.end, s.start)
|
|
211
|
+
assert.equal(expected.replace('\ufffc', await source.codec.serialize(s.chips[0].reference.ref, signal())), '参考: ' + wiki + suffix + '下一段')
|
|
212
|
+
}
|
|
213
|
+
const { api, s } = actionsFor('请看:下一段', 3)
|
|
214
|
+
api.readTitle = async () => ''
|
|
215
|
+
assert.equal(await plugin.pasteLink('\t' + doc + '\n', api, signal()), false)
|
|
216
|
+
assert.equal(s.text, '请看:\t' + doc + '\n下一段')
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
for (const interrupted of ['move caret', 'edit draft', 'switch session', 'cancel lookup']) {
|
|
220
|
+
test(`late result after ${interrupted} cannot replace text or raise a notice`, async () => {
|
|
221
|
+
const { s, api } = actionsFor('请看 ', 3)
|
|
222
|
+
const controller = new AbortController(), lookup = Promise.withResolvers()
|
|
223
|
+
api.readTitle = () => lookup.promise
|
|
224
|
+
const pending = plugin.pasteLink(wiki, api, controller.signal)
|
|
225
|
+
if (interrupted === 'move caret') s.start = s.end = 0
|
|
226
|
+
if (interrupted === 'edit draft') { s.draftRev++; s.text += '另写' }
|
|
227
|
+
if (interrupted === 'switch session') s.current = false
|
|
228
|
+
if (interrupted === 'cancel lookup') controller.abort()
|
|
229
|
+
const text = s.text
|
|
230
|
+
lookup.resolve('迟到的标题')
|
|
231
|
+
assert.equal(await pending, false)
|
|
232
|
+
assert.equal(s.text, text)
|
|
233
|
+
assert.equal(s.chips.length + s.notices, 0)
|
|
234
|
+
})
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
for (const failure of ['no access/title', 'network failure']) {
|
|
238
|
+
test(`${failure}: retain a usable clean URL and notify only the originating input`, async () => {
|
|
239
|
+
const { s, api } = actionsFor('请看 谢谢', 3)
|
|
240
|
+
api.readTitle = async () => { if (failure === 'network failure') throw Error('offline'); return '' }
|
|
241
|
+
assert.equal(await plugin.pasteLink(doc + '?disposable_login_token=sample', api, signal()), false)
|
|
242
|
+
assert.equal(s.text, '请看 ' + doc + ' 谢谢')
|
|
243
|
+
assert.equal(s.chips.length, 0)
|
|
244
|
+
assert.equal(s.notices, 1)
|
|
245
|
+
})
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
test('do not consume paste if its session is unavailable or its initial insertion refused', () => {
|
|
249
|
+
const { api, s } = actionsFor('', 0)
|
|
250
|
+
s.current = false
|
|
251
|
+
assert.equal(plugin.pasteLink(doc, api, signal()), null)
|
|
252
|
+
s.current = true
|
|
253
|
+
api.actions.insertText = () => false
|
|
254
|
+
assert.equal(plugin.pasteLink(doc, api, signal()), null)
|
|
255
|
+
assert.equal(s.requests.length, 0)
|
|
256
|
+
})
|
|
@@ -0,0 +1,248 @@
|
|
|
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 { isPublicPageUrl, readPublicHtml } 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('the total deadline cancels unresolved DNS; late DNS completion cannot start a request', async t => {
|
|
220
|
+
t.mock.timers.enable({ apis: ['setTimeout'] })
|
|
221
|
+
const slow = Promise.withResolvers(), calls = network(t, [], (_host, family) => family === 4 ? slow.promise : [])
|
|
222
|
+
const done = rejected(readPublicHtml(page))
|
|
223
|
+
t.mock.timers.tick(6000)
|
|
224
|
+
await done
|
|
225
|
+
assert.equal(calls.cancelled, 1)
|
|
226
|
+
slow.resolve([ipv4]); await new Promise(setImmediate)
|
|
227
|
+
assert.deepEqual(calls.http, [])
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
test('slow DNS and a stalled response share one deadline, including across a redirect', async t => {
|
|
231
|
+
t.mock.timers.enable({ apis: ['setTimeout'] })
|
|
232
|
+
const slow = Promise.withResolvers(), opened = Promise.withResolvers(), body = new PassThrough()
|
|
233
|
+
const calls = network(t, [{ status: 302, headers: { location: page } }, { body, opened: opened.resolve }],
|
|
234
|
+
(host, family) => family === 6 ? [] : host === 'other.org.' ? slow.promise : [ipv4])
|
|
235
|
+
const done = rejected(readPublicHtml('https://other.org/'))
|
|
236
|
+
t.mock.timers.tick(4000); slow.resolve([ipv4]); await opened.promise
|
|
237
|
+
t.mock.timers.tick(2000); await done
|
|
238
|
+
assert.ok(body.destroyed)
|
|
239
|
+
assert.ok(calls.http.every(({ req }) => req.destroyed))
|
|
240
|
+
assert.equal(calls.cancelled, 1)
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
test('transport errors and protocol upgrades are sanitized and release the socket', async t => {
|
|
244
|
+
const calls = network(t, [{ error: Error('fake remote details') }, { upgrade: true }])
|
|
245
|
+
await rejected(readPublicHtml(page))
|
|
246
|
+
await rejected(readPublicHtml(page))
|
|
247
|
+
assert.ok(calls.http.every(({ req }) => req.destroyed))
|
|
248
|
+
})
|
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
]
|
|
20
|
+
for (const [page, kind, html, expected] of pages) test(page, () => assert.equal(extractPageTitle(html, kind), expected))
|
|
21
|
+
|
|
22
|
+
const unavailable = [
|
|
23
|
+
['GitHub brand alone', 'github', '<meta content=GitHub property=og:title><title>GitHub · GitHub</title>'],
|
|
24
|
+
['GitHub sign-in page with plausible OG', 'github', '<meta content="river-lab/paper-boat" property=og:title><title>Sign in to GitHub · GitHub</title>'],
|
|
25
|
+
['GitHub soft 404', 'github', '<TITLE>Page not found · GitHub</TITLE>'],
|
|
26
|
+
['GitHub challenge despite plausible tab title', 'github', '<meta property=og:title content="Just a moment…"><title>river-lab/paper-boat</title>'],
|
|
27
|
+
['WeChat platform title is not an article title', 'wechat', '<meta name=og:title content="微信公众平台"><title>微信公众平台</title><h1>欢迎</h1>'],
|
|
28
|
+
['WeChat verification page', 'wechat', '<title>微信公众平台</title><meta name=og:title content="昨日的文章"><div class="weui-msg__title">环境异常</div><div>完成验证后即可继续访问。</div>'],
|
|
29
|
+
['WeChat removal notice with stale metadata', 'wechat', '<meta property=og:title content="河边游记"><h2 class="weui-msg__title">该内容已被发布者删除</h2>'],
|
|
30
|
+
['WeChat removal notice overrides even a retained article heading', 'wechat', '<h1 id="activity-name">旧标题</h1><p>该文章已被作者删除。</p>'],
|
|
31
|
+
['WeChat article-heading marker without a useful title', 'wechat', '<h1 id="activity-name">\u200b\n </h1>'],
|
|
32
|
+
['web challenge heading on a branded page', 'web', '<title>Field Notes</title><h1>Verify you are human</h1>'],
|
|
33
|
+
['web rate-limit response', 'web', '<title>429 Too Many Requests</title>'],
|
|
34
|
+
['web placeholder with no metadata', 'web', '<meta property="og:description" content="A description, not a title"><title>Untitled Document</title>'],
|
|
35
|
+
['JS-only site', 'web', `<script>document.title = 'Not a static title'</script><div id=app></div>`],
|
|
36
|
+
['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>`],
|
|
37
|
+
['unterminated comment in a partial response', 'web', '<!-- navigation starts here <meta property=og:title content=not-a-title>'],
|
|
38
|
+
['incomplete quoted metadata', 'web', '<meta property=og:title content="Not complete'],
|
|
39
|
+
['truncated document title', 'web', '<title>Still loading'],
|
|
40
|
+
]
|
|
41
|
+
for (const [page, kind, html] of unavailable) test(page, () => assert.equal(extractPageTitle(html, kind), ''))
|
|
42
|
+
|
|
43
|
+
test('ignore decoys without losing later genuine metadata in a minified document', () => {
|
|
44
|
+
const decoy = '<meta property=og:title content=decoy>'
|
|
45
|
+
const html = `<!--${decoy}--><STYLE>q::after{content:'${decoy}'}</STYLE><script>let example = '${decoy}'</SCRIPT ><div data-sample='${decoy}'></div><title>Actual title</title>`
|
|
46
|
+
assert.equal(extractPageTitle(html, 'web'), 'Actual title')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
test('WeChat status-like strings in a script do not invalidate an article', () => {
|
|
50
|
+
const html = `<script>var warning = '该内容已被发布者删除';</script><title>河道笔记</title>`
|
|
51
|
+
assert.equal(extractPageTitle(html, 'wechat'), '河道笔记')
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test('truncate a long label without cutting a surrogate pair', () => {
|
|
55
|
+
const long = 'a'.repeat(198) + '📘'.repeat(30)
|
|
56
|
+
const actual = extractPageTitle(`<title>${long}</title>`, 'web')
|
|
57
|
+
assert.equal(actual, 'a'.repeat(198) + '…')
|
|
58
|
+
assert.ok(actual.isWellFormed())
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
test('reject unsupported inputs without throwing or guessing a title', () => {
|
|
62
|
+
for (const input of [undefined, null, '', {}, Buffer.from('<title>Encoded</title>')]) assert.equal(extractPageTitle(input, 'web'), '')
|
|
63
|
+
assert.equal(extractPageTitle('<title>Page</title>', 'unknown'), '')
|
|
64
|
+
assert.equal(extractPageTitle(`<title>${'��'}</title>`, 'web'), '')
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test('scan broken or bounded prefixes without treating script text or a partial tag as metadata', () => {
|
|
68
|
+
const incomplete = '<div data-note="' + '<meta property=og:title content=wrong>'.repeat(6000)
|
|
69
|
+
assert.equal(extractPageTitle(incomplete, 'web'), '')
|
|
70
|
+
assert.equal(extractPageTitle('<script>' + '<script>'.repeat(40000) + '<title>wrong</title>', 'web'), '')
|
|
71
|
+
assert.equal(extractPageTitle(' '.repeat(1024 * 1024) + '<title>Outside the budget</title>', 'web'), '')
|
|
72
|
+
})
|