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
package/public-fetch.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import dns from 'node:dns/promises'
|
|
2
|
+
import http from 'node:http'
|
|
3
|
+
import https from 'node:https'
|
|
4
|
+
import { BlockList, isIP } from 'node:net'
|
|
5
|
+
import { MIMEType } from 'node:util'
|
|
6
|
+
|
|
7
|
+
const TOTAL_MS = 6_000
|
|
8
|
+
const MAX_URL = 4_096
|
|
9
|
+
const MAX_REDIRECTS = 3
|
|
10
|
+
const MAX_PREFIX = 128 * 1024
|
|
11
|
+
const MAX_DNS_RESPONSE = 16 * 1024
|
|
12
|
+
const MAX_WIRE = 512 * 1024 // HTTP bytes across all hops, including headers and chunk framing
|
|
13
|
+
const SPECIAL_TLDS = new Set('alt arpa bit corp domain example home i2p internal intra intranet invalid lan local localdomain localhost localnet mail onion private test workgroup'.split(' '))
|
|
14
|
+
const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
|
15
|
+
const REDIRECT = new Set([301, 302, 303, 307, 308])
|
|
16
|
+
const unavailable = () => new Error('public HTML unavailable')
|
|
17
|
+
const budgetStates = new WeakMap()
|
|
18
|
+
|
|
19
|
+
// An opaque token lets sequential attempts share the same immutable 512 KiB cap.
|
|
20
|
+
export function createPublicBudget() {
|
|
21
|
+
const token = Object.freeze({})
|
|
22
|
+
budgetStates.set(token, { left: MAX_WIRE })
|
|
23
|
+
return token
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// This is a cheap lexical filter, not authorization to connect. A and AAAA are checked per hop.
|
|
27
|
+
export function isPublicPageUrl(url) {
|
|
28
|
+
if (!(url instanceof URL) || url.href.length > MAX_URL || !['http:', 'https:'].includes(url.protocol)) return false
|
|
29
|
+
if (url.username || url.password || url.port || url.hostname.length > 253 || isIP(url.hostname)) return false
|
|
30
|
+
const labels = url.hostname.split('.'), tld = labels.at(-1)
|
|
31
|
+
return labels.length > 1 && labels.every(label => LABEL.test(label)) &&
|
|
32
|
+
/^(?:[a-z]{2,63}|xn--[a-z0-9-]+)$/.test(tld) && !SPECIAL_TLDS.has(tld)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function checkedUrl(input, base, allowUrl) {
|
|
36
|
+
const raw = input instanceof URL ? input.href : input
|
|
37
|
+
if (typeof raw !== 'string' || !raw.length || raw.length > MAX_URL) throw unavailable()
|
|
38
|
+
const url = new URL(raw, base)
|
|
39
|
+
if (!isPublicPageUrl(url) || (allowUrl !== undefined && allowUrl(new URL(url.href)) !== true)) throw unavailable()
|
|
40
|
+
return url
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Exclude special-purpose networks, even the globally reachable protocol/anycast exceptions.
|
|
44
|
+
// IPv6 must also be in 2000::/3; that excludes mapped, NAT64, ULA, link-local and multicast.
|
|
45
|
+
const globalV6 = new BlockList()
|
|
46
|
+
globalV6.addSubnet('2000::', 3, 'ipv6')
|
|
47
|
+
const denied = new BlockList()
|
|
48
|
+
for (const cidr of [
|
|
49
|
+
'0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8', '169.254.0.0/16', '172.16.0.0/12',
|
|
50
|
+
'192.0.0.0/24', '192.0.2.0/24', '192.31.196.0/24', '192.52.193.0/24', '192.88.99.0/24',
|
|
51
|
+
'192.168.0.0/16', '192.175.48.0/24', '198.18.0.0/15', '198.51.100.0/24', '203.0.113.0/24',
|
|
52
|
+
'224.0.0.0/3', '168.63.129.16/32', // multicast/reserved; Azure's platform virtual IP
|
|
53
|
+
'2001::/23', '2001:db8::/32', '2002::/16', '2620:4f:8000::/48', '3ffe::/16', '3fff::/20',
|
|
54
|
+
]) {
|
|
55
|
+
const [address, bits] = cidr.split('/')
|
|
56
|
+
denied.addSubnet(address, Number(bits), address.includes(':') ? 'ipv6' : 'ipv4')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const fakeV4 = new BlockList()
|
|
60
|
+
fakeV4.addSubnet('198.18.0.0', 15, 'ipv4')
|
|
61
|
+
|
|
62
|
+
// User-opted-in DoH is only used when *all* local answers are fake IPv4 addresses.
|
|
63
|
+
// The DoH origin and public address are constants: never send paths, queries or credentials.
|
|
64
|
+
async function publicAnswers(host, signal, budget) {
|
|
65
|
+
async function query(family) {
|
|
66
|
+
signal.throwIfAborted()
|
|
67
|
+
const url = new URL('https://cloudflare-dns.com/dns-query')
|
|
68
|
+
url.searchParams.set('name', host)
|
|
69
|
+
url.searchParams.set('type', family === 4 ? 'A' : 'AAAA')
|
|
70
|
+
const res = await openPage(url, '1.1.1.1', signal, budget, 'application/dns-json')
|
|
71
|
+
try {
|
|
72
|
+
if (res.statusCode !== 200 || (header(res, 'content-encoding') ?? 'identity').trim().toLowerCase() !== 'identity' ||
|
|
73
|
+
new MIMEType(header(res, 'content-type') ?? '').essence !== 'application/dns-json') throw unavailable()
|
|
74
|
+
const data = await jsonBody(res, MAX_DNS_RESPONSE)
|
|
75
|
+
if (!data || typeof data !== 'object' || Array.isArray(data) || data.Status !== 0 ||
|
|
76
|
+
(data.Answer !== undefined && !Array.isArray(data.Answer)) || (data.Answer?.length ?? 0) > 128) throw unavailable()
|
|
77
|
+
const answers = []
|
|
78
|
+
for (const item of data.Answer ?? []) {
|
|
79
|
+
if (item?.type !== 1 && item?.type !== 28) continue // e.g. a CNAME in the validated DNS chain
|
|
80
|
+
if (item.type !== (family === 4 ? 1 : 28) || typeof item.data !== 'string') throw unavailable()
|
|
81
|
+
answers.push(item.data)
|
|
82
|
+
}
|
|
83
|
+
return answers
|
|
84
|
+
} finally {
|
|
85
|
+
res.destroy()
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return Promise.all([query(4), query(6)])
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function resolvePin(resolver, host, signal, budget, publicDnsFallback) {
|
|
92
|
+
async function records(family) {
|
|
93
|
+
try {
|
|
94
|
+
// Absolute names: never expand a public-looking name using a local search domain.
|
|
95
|
+
return await resolver[`resolve${family}`](`${host}.`)
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error?.code === 'ENODATA') return [] // No records of this family. Other DNS failures fail closed.
|
|
98
|
+
throw error
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
let [v4, v6] = await Promise.all([records(4), records(6)])
|
|
102
|
+
if (!Array.isArray(v4) || !Array.isArray(v6) || !v4.length && !v6.length || v4.length + v6.length > 64) throw unavailable()
|
|
103
|
+
if (publicDnsFallback === true && v4.length > 0 && v6.length === 0 &&
|
|
104
|
+
v4.every(ip => isIP(ip) === 4 && fakeV4.check(ip, 'ipv4'))) {
|
|
105
|
+
;[v4, v6] = await publicAnswers(host, signal, budget)
|
|
106
|
+
signal.throwIfAborted()
|
|
107
|
+
if (!v4.length && !v6.length || v4.length + v6.length > 64) throw unavailable()
|
|
108
|
+
}
|
|
109
|
+
for (const [family, answers] of [[4, v4], [6, v6]]) {
|
|
110
|
+
for (const ip of answers) {
|
|
111
|
+
if (typeof ip !== 'string' || isIP(ip) !== family || ip.includes('%') || family === 6 && !globalV6.check(ip, 'ipv6') ||
|
|
112
|
+
denied.check(ip, family === 4 ? 'ipv4' : 'ipv6')) throw unavailable()
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return v4[0] ?? v6[0]
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function openPage(url, address, signal, budget, accept = 'text/html, application/xhtml+xml') {
|
|
119
|
+
const secure = url.protocol === 'https:'
|
|
120
|
+
return new Promise((resolve, reject) => {
|
|
121
|
+
// Connect to the validated literal: no second lookup (including autoSelectFamily), proxy or pooled socket.
|
|
122
|
+
// The original DNS name is still the HTTP authority and the identity verified by TLS.
|
|
123
|
+
const req = (secure ? https : http).get({
|
|
124
|
+
protocol: url.protocol, hostname: address, path: url.pathname + url.search, agent: false, signal,
|
|
125
|
+
...(secure && { servername: url.hostname, rejectUnauthorized: true }),
|
|
126
|
+
maxHeaderSize: 16 * 1024,
|
|
127
|
+
headers: { Host: url.host, Accept: accept, 'Accept-Encoding': 'identity' },
|
|
128
|
+
}, resolve)
|
|
129
|
+
req.on('error', reject)
|
|
130
|
+
req.once('upgrade', (_res, socket) => { socket.destroy(); reject(unavailable()) })
|
|
131
|
+
req.once('socket', socket => {
|
|
132
|
+
const count = chunk => {
|
|
133
|
+
budget.left -= chunk.length
|
|
134
|
+
if (budget.left < 0) req.destroy(unavailable())
|
|
135
|
+
}
|
|
136
|
+
socket.prependListener('data', count)
|
|
137
|
+
req.once('close', () => socket.off('data', count))
|
|
138
|
+
})
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function header(res, name) {
|
|
143
|
+
const values = res.headersDistinct[name]
|
|
144
|
+
if (values && values.length !== 1) throw unavailable()
|
|
145
|
+
return values?.[0]
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// A MIME declaration alone is not enough: reject binary/control bytes and ordinary non-markup text.
|
|
149
|
+
function startsWithHtml(text) {
|
|
150
|
+
let rest = text.trimStart()
|
|
151
|
+
if (/^<\?xml\s/i.test(rest)) {
|
|
152
|
+
const end = rest.indexOf('?>')
|
|
153
|
+
if (end === -1) return false
|
|
154
|
+
rest = rest.slice(end + 2).trimStart()
|
|
155
|
+
}
|
|
156
|
+
while (rest.startsWith('<!--')) {
|
|
157
|
+
const end = rest.indexOf('-->', 4)
|
|
158
|
+
if (end === -1) return false
|
|
159
|
+
rest = rest.slice(end + 3).trimStart()
|
|
160
|
+
}
|
|
161
|
+
return /^<(?:!doctype\s+html|html|head|body|title|meta|base|link|script|style)(?=[\s/>])/i.test(rest)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function htmlPrefix(res, mime) {
|
|
165
|
+
const prefix = Buffer.alloc(MAX_PREFIX)
|
|
166
|
+
let size = 0
|
|
167
|
+
for await (const chunk of res) {
|
|
168
|
+
size += chunk.copy(prefix, size)
|
|
169
|
+
if (size === MAX_PREFIX) break // do not drain/reject a large page just because its body is long
|
|
170
|
+
}
|
|
171
|
+
const sniff = prefix.toString('latin1', 0, Math.min(size, 1024))
|
|
172
|
+
const hint = /<meta\s[^<>]*?\bcharset\s*=\s*["']?\s*([\w.-]+)/i.exec(sniff)?.[1]
|
|
173
|
+
const decoder = new TextDecoder(mime.params.get('charset') ?? hint ?? 'utf-8', { fatal: true })
|
|
174
|
+
if (!['utf-8', 'gbk', 'gb18030', 'windows-1252'].includes(decoder.encoding)) throw unavailable()
|
|
175
|
+
// A capped prefix may end halfway through a character; don't replace it or discard the valid head.
|
|
176
|
+
const html = decoder.decode(prefix.subarray(0, size), { stream: size === MAX_PREFIX })
|
|
177
|
+
if (/[\u0000-\u0008\u000b\u000e-\u001f\u007f-\u009f]/.test(html) || !startsWithHtml(html)) throw unavailable()
|
|
178
|
+
return html
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// JSON is only used for bounded service metadata, never exposed as a raw response to clients.
|
|
182
|
+
async function jsonBody(res, limit) {
|
|
183
|
+
let size = 0
|
|
184
|
+
const chunks = []
|
|
185
|
+
for await (const chunk of res) {
|
|
186
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
187
|
+
size += bytes.length
|
|
188
|
+
if (size > limit) throw unavailable()
|
|
189
|
+
chunks.push(bytes)
|
|
190
|
+
}
|
|
191
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)))
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function readChain(url, allowUrl, resolver, signal, publicDnsFallback, mode, budget) {
|
|
195
|
+
for (let hop = 0; ; hop++) {
|
|
196
|
+
signal.throwIfAborted()
|
|
197
|
+
if (budget.left <= 0) throw unavailable()
|
|
198
|
+
const pin = await resolvePin(resolver, url.hostname, signal, budget, publicDnsFallback)
|
|
199
|
+
signal.throwIfAborted()
|
|
200
|
+
if (budget.left <= 0) throw unavailable()
|
|
201
|
+
const res = await openPage(url, pin, signal, budget, mode === 'json' ? 'application/json' : undefined)
|
|
202
|
+
try {
|
|
203
|
+
if (budget.left < 0) throw unavailable()
|
|
204
|
+
if (REDIRECT.has(res.statusCode)) {
|
|
205
|
+
if (mode === 'json' || hop >= MAX_REDIRECTS) throw unavailable()
|
|
206
|
+
const next = checkedUrl(header(res, 'location'), url, allowUrl)
|
|
207
|
+
if (url.protocol === 'https:' && next.protocol !== 'https:') throw unavailable()
|
|
208
|
+
url = next
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
if (res.statusCode !== 200 || (header(res, 'content-encoding') ?? 'identity').trim().toLowerCase() !== 'identity' ||
|
|
212
|
+
/^\s*attachment\b/i.test(header(res, 'content-disposition') ?? '')) throw unavailable()
|
|
213
|
+
const mime = new MIMEType(header(res, 'content-type') ?? '')
|
|
214
|
+
if (mode === 'json') {
|
|
215
|
+
if (mime.essence !== 'application/json' || (mime.params.get('charset') ?? 'utf-8').toLowerCase() !== 'utf-8') throw unavailable()
|
|
216
|
+
const data = await jsonBody(res, MAX_PREFIX)
|
|
217
|
+
if (budget.left < 0) throw unavailable()
|
|
218
|
+
return data
|
|
219
|
+
}
|
|
220
|
+
if (mime.essence !== 'text/html' && mime.essence !== 'application/xhtml+xml') throw unavailable()
|
|
221
|
+
const html = await htmlPrefix(res, mime)
|
|
222
|
+
if (budget.left < 0) throw unavailable()
|
|
223
|
+
return { html, url: url.href, contentType: mime.essence }
|
|
224
|
+
} finally {
|
|
225
|
+
res.destroy() // includes redirects, refused responses, truncated reads and decode errors
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function readPublic(input, options, mode) {
|
|
231
|
+
const control = new AbortController()
|
|
232
|
+
let resolver, timer, signal, abortListener
|
|
233
|
+
try {
|
|
234
|
+
const { allowUrl, publicDnsFallback = false, signal: callerSignal, budget: token } = options
|
|
235
|
+
const budget = token === undefined ? { left: MAX_WIRE } : budgetStates.get(token)
|
|
236
|
+
if (!budget || budget.left <= 0) throw unavailable()
|
|
237
|
+
signal = callerSignal ? AbortSignal.any([control.signal, callerSignal]) : control.signal
|
|
238
|
+
signal.throwIfAborted()
|
|
239
|
+
const url = checkedUrl(input, undefined, allowUrl)
|
|
240
|
+
if (mode === 'json' && url.protocol !== 'https:') throw unavailable()
|
|
241
|
+
resolver = new dns.Resolver({ timeout: 3_000, tries: 1 })
|
|
242
|
+
const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(unavailable()), TOTAL_MS) })
|
|
243
|
+
const aborted = new Promise((_, reject) => {
|
|
244
|
+
abortListener = () => reject(unavailable())
|
|
245
|
+
signal.addEventListener('abort', abortListener, { once: true })
|
|
246
|
+
})
|
|
247
|
+
return await Promise.race([readChain(url, allowUrl, resolver, signal, publicDnsFallback, mode, budget), deadline, aborted])
|
|
248
|
+
} catch {
|
|
249
|
+
throw unavailable() // never propagate remote text, addresses, paths or DNS/HTTP/TLS error details
|
|
250
|
+
} finally {
|
|
251
|
+
clearTimeout(timer)
|
|
252
|
+
if (abortListener) signal.removeEventListener('abort', abortListener)
|
|
253
|
+
control.abort()
|
|
254
|
+
resolver?.cancel()
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Anonymous HTML prefix for server-side metadata extraction only; never serve this HTML to clients. */
|
|
259
|
+
export function readPublicHtml(input, options = {}) {
|
|
260
|
+
return readPublic(input, options, 'html')
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Anonymous, bounded HTTPS JSON without redirects; callers restrict their allowed fixed origin and path. */
|
|
264
|
+
export function readPublicJson(input, options = {}) {
|
|
265
|
+
return readPublic(input, options, 'json')
|
|
266
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import test from 'node:test'
|
|
3
|
+
import { createHandler, createMetadataLookup } from '../index.js'
|
|
4
|
+
import { parseLink } from '../link-policy.js'
|
|
5
|
+
|
|
6
|
+
const doc = 'https://team.feishu.cn/docx/ExampleDoc0001'
|
|
7
|
+
const github = 'https://github.com/octocat/Hello-World'
|
|
8
|
+
const wx = 'https://mp.weixin.qq.com/s/ArticleSlug'
|
|
9
|
+
const web = 'https://example.com/article?q=sample'
|
|
10
|
+
const owner = { peer: { principal: { kind: 'owner' } } }
|
|
11
|
+
const makeCtx = admission => ({ connection: { admit: () => admission } })
|
|
12
|
+
async function invoke(handler, url, method = 'GET', headers = {}) {
|
|
13
|
+
const res = { headers: {}, setHeader(k, v) { this.headers[k] = v }, end(s) { this.body = s && JSON.parse(s) } }
|
|
14
|
+
await handler({ url: '/feishu-link-preview?url=' + encodeURIComponent(url), method, headers }, res)
|
|
15
|
+
return res
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
test('the real route checks ownership before all reads; HEAD does not start network work', async () => {
|
|
19
|
+
let hits = 0
|
|
20
|
+
const metadata = async () => { hits++; return { ok: false, error: 'unavailable' } }
|
|
21
|
+
for (const [admission, status] of [[{ rejection: 401 }, 401], [{ rejection: 403 }, 403], [{ peer: { principal: { kind: 'visitor' } } }, 403], [null, 403]]) {
|
|
22
|
+
assert.equal((await invoke(createHandler(makeCtx(admission), metadata), github)).statusCode, status)
|
|
23
|
+
}
|
|
24
|
+
const get = createHandler(makeCtx(owner), metadata)
|
|
25
|
+
assert.equal((await invoke(get, github, 'GET', { 'sec-fetch-site': 'cross-site' })).statusCode, 403)
|
|
26
|
+
assert.equal((await invoke(get, github, 'POST')).statusCode, 405)
|
|
27
|
+
assert.equal((await invoke(get, github, 'HEAD')).statusCode, 200)
|
|
28
|
+
assert.equal((await invoke(get, 'https://localhost/doc')).statusCode, 400)
|
|
29
|
+
assert.equal((await invoke(get, web + '&token=sample')).statusCode, 400)
|
|
30
|
+
assert.equal(hits, 0)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
test('route -> policy -> reader -> extracted title: distinct Feishu, GitHub, WeChat and web paths', async () => {
|
|
34
|
+
const publicReads = [], documentReads = []
|
|
35
|
+
const pages = new Map([
|
|
36
|
+
[github, '<html><head><title>GitHub - octocat/Hello-World</title></head></html>'],
|
|
37
|
+
[wx, '<html><head><meta property="og:title" content="微信文章测试"></head></html>'],
|
|
38
|
+
[web, '<html><head><title>Public & readable</title></head></html>'],
|
|
39
|
+
])
|
|
40
|
+
const lookup = createMetadataLookup({
|
|
41
|
+
async inspectDocument(url) { documentReads.push(url); return '飞书标题' },
|
|
42
|
+
async readHtml(url, { allowUrl }) {
|
|
43
|
+
publicReads.push(url); assert.equal(allowUrl(new URL(url)), true)
|
|
44
|
+
for (const blocked of ['http://localhost/', doc, 'https://example.com/login', web + '&token=fixture']) {
|
|
45
|
+
assert.equal(allowUrl(new URL(blocked)), false)
|
|
46
|
+
}
|
|
47
|
+
if (url === wx) assert.equal(allowUrl(new URL('https://mp.weixin.qq.com/cgi-bin/login')), false)
|
|
48
|
+
return { html: pages.get(url), url, contentType: 'text/html' }
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
const get = createHandler(makeCtx(owner), lookup)
|
|
52
|
+
for (const [url, kind, pattern] of [
|
|
53
|
+
[doc + '?disposable_login_token=sample#p', 'docx', /飞书标题/], [github + '#readme', 'github', /octocat\/Hello-World/],
|
|
54
|
+
[wx + '?scene=1&pass_ticket=sample#rd', 'wechat', /微信文章测试/], [web + '#part', 'web', /Public & readable/],
|
|
55
|
+
]) {
|
|
56
|
+
const res = await invoke(get, url)
|
|
57
|
+
assert.equal(res.statusCode, 200); assert.equal(res.headers['cache-control'], 'no-store')
|
|
58
|
+
assert.equal(res.body.ok, true); assert.equal(res.body.kind, kind); assert.match(res.body.title, pattern)
|
|
59
|
+
assert.deepEqual(Object.keys(res.body).sort(), ['kind','ok','title'])
|
|
60
|
+
}
|
|
61
|
+
assert.deepEqual(documentReads, [doc]); assert.deepEqual(publicReads, [github, wx, web])
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
test('Feishu labels strip bidi controls and bound long titles without decoding HTML entities', async () => {
|
|
65
|
+
const cases = [
|
|
66
|
+
[' A & B\u202e\t C ', 'A & B C'],
|
|
67
|
+
['x'.repeat(198) + '😀' + 'z', 'x'.repeat(198) + '…'],
|
|
68
|
+
['\u202e\u0000', ''],
|
|
69
|
+
]
|
|
70
|
+
for (const [input, expected] of cases) {
|
|
71
|
+
const get = createHandler(makeCtx(owner), createMetadataLookup({ async inspectDocument() { return input } }))
|
|
72
|
+
const result = (await invoke(get, doc)).body
|
|
73
|
+
if (!expected) assert.deepEqual(result, { ok: false, error: 'unavailable' })
|
|
74
|
+
else { assert.equal(result.ok, true); assert.equal(result.title, expected); assert.ok(result.title.length <= 200) }
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('no title or transport failure: title-only response fails closed and negative result is cached', async () => {
|
|
79
|
+
for (const fail of ['empty', 'throw']) {
|
|
80
|
+
let count = 0
|
|
81
|
+
const get = createHandler(makeCtx(owner), createMetadataLookup({ async readHtml(url) {
|
|
82
|
+
count++; if (fail === 'throw') throw Error('internal detail')
|
|
83
|
+
return { url, html: '<html></html>' }
|
|
84
|
+
} }))
|
|
85
|
+
for (let i = 0; i < 2; i++) assert.deepEqual((await invoke(get, web)).body, { ok: false, error: 'unavailable' })
|
|
86
|
+
assert.equal(count, 1)
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
test('npm package pages use only the fixed registry path and verify name/version before returning a title', async () => {
|
|
91
|
+
const requested = 'https://www.npmjs.com/package/dsh-inline-link-preview/v/0.5.0-beta.1?tab=readme#details'
|
|
92
|
+
const registryUrl = 'https://registry.npmjs.org/dsh-inline-link-preview/0.5.0-beta.1'
|
|
93
|
+
let jsonReads = 0, htmlReads = 0
|
|
94
|
+
const lookup = createMetadataLookup({
|
|
95
|
+
publicDnsFallback: true,
|
|
96
|
+
async readJson(url, options) {
|
|
97
|
+
jsonReads++
|
|
98
|
+
assert.equal(url, registryUrl)
|
|
99
|
+
assert.equal(options.publicDnsFallback, true)
|
|
100
|
+
assert.ok(options.signal instanceof AbortSignal)
|
|
101
|
+
assert.equal(options.allowUrl(new URL(registryUrl)), true)
|
|
102
|
+
for (const denied of [registryUrl + '?x=1', registryUrl + '/other', 'https://registry.npmjs.org.evil.example/pkg', 'http://registry.npmjs.org/pkg']) {
|
|
103
|
+
assert.equal(options.allowUrl(new URL(denied)), false)
|
|
104
|
+
}
|
|
105
|
+
return { name: 'dsh-inline-link-preview', version: '0.5.0-beta.1', description: '<ignored>' }
|
|
106
|
+
},
|
|
107
|
+
async readHtml() { htmlReads++; throw Error('not expected') },
|
|
108
|
+
})
|
|
109
|
+
const get = createHandler(makeCtx(owner), lookup)
|
|
110
|
+
for (let i = 0; i < 2; i++) {
|
|
111
|
+
assert.deepEqual((await invoke(get, requested)).body, { ok: true, kind: 'web', title: 'dsh-inline-link-preview@0.5.0-beta.1 - npm' })
|
|
112
|
+
}
|
|
113
|
+
assert.equal(jsonReads, 1)
|
|
114
|
+
assert.equal(htmlReads, 0)
|
|
115
|
+
assert.equal((await invoke(get, requested + '&token=fixture')).statusCode, 400)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
test('invalid npm registry metadata cannot create a chip; ordinary HTML fallback shares privacy and timeout options', async () => {
|
|
119
|
+
const requested = 'https://www.npmjs.com/package/pkg/v/1.2.3'
|
|
120
|
+
const cases = [{ name: 'wrong', version: '1.2.3' }, { name: 'pkg', version: '2.0.0' }, null]
|
|
121
|
+
for (const data of cases) {
|
|
122
|
+
let registrySignal, registryBudget
|
|
123
|
+
const lookup = createMetadataLookup({
|
|
124
|
+
async readJson(_url, options) {
|
|
125
|
+
registrySignal = options.signal; registryBudget = options.budget
|
|
126
|
+
assert.equal(options.publicDnsFallback, false); assert.ok(Object.isFrozen(registryBudget))
|
|
127
|
+
return data
|
|
128
|
+
},
|
|
129
|
+
async readHtml(url, options) {
|
|
130
|
+
assert.equal(url, requested)
|
|
131
|
+
assert.equal(options.publicDnsFallback, false)
|
|
132
|
+
assert.equal(options.signal, registrySignal)
|
|
133
|
+
assert.equal(options.budget, registryBudget)
|
|
134
|
+
assert.equal(options.allowUrl(new URL(url)), true)
|
|
135
|
+
return { url, html: '<html></html>' }
|
|
136
|
+
},
|
|
137
|
+
})
|
|
138
|
+
assert.deepEqual(await lookup(parseLink(requested)), { ok: false, error: 'unavailable' })
|
|
139
|
+
}
|
|
140
|
+
const fallback = createMetadataLookup({
|
|
141
|
+
async readJson() { throw Error('503') },
|
|
142
|
+
async readHtml(url) { return { url, html: '<title>Original npm page</title>' } },
|
|
143
|
+
})
|
|
144
|
+
assert.equal((await fallback(parseLink(requested))).title, 'Original npm page')
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
test('npm lookalike hosts and unsupported npm routes do not reach registry adapter', async () => {
|
|
148
|
+
let jsonReads = 0
|
|
149
|
+
const lookup = createMetadataLookup({
|
|
150
|
+
async readJson() { jsonReads++; throw Error('not expected') },
|
|
151
|
+
async readHtml(url) { return { url, html: '<title>Public page</title>' } },
|
|
152
|
+
})
|
|
153
|
+
for (const url of ['https://www.npmjs.com.evil.org/package/pkg', 'https://www.npmjs.com/package/pkg/v/latest', 'https://www.npmjs.com/loginx']) {
|
|
154
|
+
assert.equal((await lookup(parseLink(url))).title, 'Public page')
|
|
155
|
+
}
|
|
156
|
+
assert.equal(jsonReads, 0)
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
test('same-URL concurrent lookups share work, unique active requests are bounded', async () => {
|
|
160
|
+
let count = 0
|
|
161
|
+
const ready = Promise.withResolvers()
|
|
162
|
+
const lookup = createMetadataLookup({ async readHtml(url) { count++; await ready.promise; return { url, html: '<title>Article title</title>' } } })
|
|
163
|
+
const first = parseLink(github)
|
|
164
|
+
const active = [lookup(first), lookup(first), ...Array.from({ length: 7 }, (_, i) => lookup(parseLink(`https://example.com/post/${i}`)))]
|
|
165
|
+
assert.deepEqual(await lookup(parseLink('https://example.com/overflow')), { ok: false, error: 'busy' })
|
|
166
|
+
ready.resolve(); assert.ok((await Promise.all(active)).every(r => r.ok)); assert.equal(count, 8)
|
|
167
|
+
assert.equal((await lookup(first)).ok, true); assert.equal(count, 8)
|
|
168
|
+
})
|