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
package/link-policy.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Pure policy shared by the Host and the dependency-free browser bundle (see build-client.js).
|
|
2
|
+
// lookup: safe metadata address; ref: the text copied/sent/opened. Never replace ref with a redirect.
|
|
3
|
+
export function parseLink(text) {
|
|
4
|
+
if (typeof text !== 'string' || text.length > 16384) return null
|
|
5
|
+
const raw = text.trim()
|
|
6
|
+
if (!/^https?:\/\//i.test(raw) || /[\s\\<>\u0000-\u001f\u007f\ufffc]/u.test(raw)) return null
|
|
7
|
+
let url
|
|
8
|
+
try { url = new URL(raw) } catch { return null }
|
|
9
|
+
if (url.username || url.password || url.port) return null
|
|
10
|
+
const host = url.hostname
|
|
11
|
+
if (!/^(?:[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?\.)+[a-z][a-z\d-]*$/i.test(host) ||
|
|
12
|
+
/\.(?:local|localhost|internal|intranet|lan|home|corp|test|example|invalid|onion|alt|arpa)$/i.test(host)) return null
|
|
13
|
+
|
|
14
|
+
const feishu = /(?:^|\.)(?:feishu\.cn|larksuite\.com|larkoffice\.com)$/i.test(host)
|
|
15
|
+
const wechat = host === 'mp.weixin.qq.com'
|
|
16
|
+
const feishuSecret = /^(?:disposable_login_token|(?:user_|tenant_|app_)?access_token|refresh_token|id_token)$/i
|
|
17
|
+
const webSecret = /^(?:x-amz-.+|x-goog-.+|(?:.*[_-])?(?:token|secret|signature|credential|password|ticket|sessionid|auth|jwt|sig)(?:[_-].*)?|api[_-]?key|access[_-]?key(?:id)?|authkey|passwd|oauth|code|sso|key|session)$/i
|
|
18
|
+
const wxSecret = /^(?:pass_ticket|appmsg_token|wxtoken|key|uin|exportkey|wx_header)$/i
|
|
19
|
+
|
|
20
|
+
// Preserve escaping/order of unaffected fields, including ordinary paragraph anchors.
|
|
21
|
+
const strip = fields => fields.split('&').filter(field => {
|
|
22
|
+
let key
|
|
23
|
+
try { key = decodeURIComponent(field.split('=', 1)[0]) } catch { return true }
|
|
24
|
+
return feishu ? !feishuSecret.test(key) : !wxSecret.test(key) && !webSecret.test(key)
|
|
25
|
+
}).join('&')
|
|
26
|
+
function cleanShareRef() {
|
|
27
|
+
const query = url.search.slice(1), clean = strip(query)
|
|
28
|
+
if (clean !== query) url.search = clean
|
|
29
|
+
const hash = url.hash.slice(1), split = hash.indexOf('?')
|
|
30
|
+
const fields = strip(hash.slice(split + 1))
|
|
31
|
+
const cleanHash = split < 0 ? fields : strip(hash.slice(0, split)) + (fields ? '?' + fields : '')
|
|
32
|
+
if (cleanHash !== hash) url.hash = cleanHash
|
|
33
|
+
return url.href
|
|
34
|
+
}
|
|
35
|
+
if (feishu) {
|
|
36
|
+
const doc = /^\/(docx|wiki)\/[A-Za-z0-9_-]{8,128}\/?$/.exec(url.pathname)
|
|
37
|
+
if (url.protocol !== 'https:' || !doc) return null // never send another Feishu resource to the web reader
|
|
38
|
+
return { kind: doc[1], lookup: url.origin + url.pathname.replace(/\/$/, ''), ref: cleanShareRef() }
|
|
39
|
+
}
|
|
40
|
+
if (wechat) {
|
|
41
|
+
// Copied article links often carry temporary WeChat parameters. Only article identity goes on the wire.
|
|
42
|
+
const lookup = new URL('https://mp.weixin.qq.com' + url.pathname)
|
|
43
|
+
if (/^\/s\/?$/.test(url.pathname)) {
|
|
44
|
+
if (!url.searchParams.get('__biz') || !(url.searchParams.get('mid') || url.searchParams.get('appmsgid'))) return null
|
|
45
|
+
for (const key of ['__biz', 'mid', 'appmsgid', 'idx', 'sn']) {
|
|
46
|
+
const value = url.searchParams.get(key)
|
|
47
|
+
if (value) lookup.searchParams.set(key, value)
|
|
48
|
+
}
|
|
49
|
+
} else if (!/^\/s\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) return null
|
|
50
|
+
return { kind: 'wechat', lookup: lookup.href, ref: cleanShareRef() }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Never automatically visit known credential/action URLs. Leave their normal paste untouched.
|
|
54
|
+
if (Array.from(url.searchParams.keys()).some(key => webSecret.test(key) || feishuSecret.test(key))) return null
|
|
55
|
+
if (/(?:^|[?&#])(?:access_token|id_token|refresh_token|token|code|api[_-]?key)=/i.test(url.hash)) return null
|
|
56
|
+
let path
|
|
57
|
+
try { path = decodeURIComponent(url.pathname) } catch { return null }
|
|
58
|
+
if (/(?:^|\/)(?:login|log[-_]?in|sign[-_]?in|log[-_]?out|sign[-_]?out|oauth2?|sso|captcha|unsubscribe|reset[-_]?password|verify[-_]?email|magic[-_]?link|webhooks?)(?:\/|$)/i.test(path)) return null
|
|
59
|
+
url.hash = '' // fragments are for the user's navigation only
|
|
60
|
+
return { kind: /^(?:www\.)?github\.com$/i.test(host) ? 'github' : 'web', lookup: url.href, ref: raw }
|
|
61
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Inline link previews",
|
|
4
|
+
"description": "Paste one link in the composer to see a document icon and its title in place. Copy and send keep the URL. Feishu/Lark docs and wikis need a signed-in lark-cli; public GitHub pages, WeChat articles and other webpages are requested anonymously on paste. If a title is unavailable, the URL stays editable."
|
|
5
|
+
}
|
|
6
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-inline-link-preview",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.0-beta.1",
|
|
4
|
+
"description": "Preview a pasted link as an inline title in the DeepSeek Harness composer. Supports Feishu/Lark, GitHub, WeChat articles and public webpages; copy or send the URL.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "dsh-inline-link-preview contributors",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/mark-qtech/dsh-inline-link-preview.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/mark-qtech/dsh-inline-link-preview#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/mark-qtech/dsh-inline-link-preview/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": ["deepseek-harness", "dsh-plugin", "link-preview", "composer", "feishu", "lark", "github", "wechat"],
|
|
16
|
+
"type": "module",
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22",
|
|
19
|
+
"dsh": ">=0.2.2-rc.5 <0.2.3-0"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"registry": "https://registry.npmjs.org/",
|
|
23
|
+
"access": "public",
|
|
24
|
+
"tag": "beta"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "node build-client.js",
|
|
28
|
+
"test": "node build-client.js --check && node --test"
|
|
29
|
+
},
|
|
30
|
+
"exports": {
|
|
31
|
+
".": "./index.js",
|
|
32
|
+
"./client": "./client.js",
|
|
33
|
+
"./locale/*.json": "./locale/*.json",
|
|
34
|
+
"./icon": "./icon.svg"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"index.js",
|
|
38
|
+
"link-policy.js",
|
|
39
|
+
"title.js",
|
|
40
|
+
"public-fetch.js",
|
|
41
|
+
"composer.js",
|
|
42
|
+
"build-client.js",
|
|
43
|
+
"client.js",
|
|
44
|
+
"test/*.test.js",
|
|
45
|
+
"cordis.patch.yml",
|
|
46
|
+
"locale/*.json",
|
|
47
|
+
"icon.svg",
|
|
48
|
+
"README.md",
|
|
49
|
+
"LICENSE"
|
|
50
|
+
],
|
|
51
|
+
"dsh": {
|
|
52
|
+
"bundle": {
|
|
53
|
+
"patch": "./cordis.patch.yml"
|
|
54
|
+
},
|
|
55
|
+
"client": {
|
|
56
|
+
"platform": "web",
|
|
57
|
+
"immediately": true,
|
|
58
|
+
"inject": [
|
|
59
|
+
"@deepseek-ai/dsh-client-ui-slots",
|
|
60
|
+
"@deepseek-ai/dsh-api-session-controller",
|
|
61
|
+
"@deepseek-ai/dsh-client-ui-conversation",
|
|
62
|
+
"@deepseek-ai/dsh-client-ui-input-trigger",
|
|
63
|
+
"@deepseek-ai/dsh-client-locale"
|
|
64
|
+
]
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
package/public-fetch.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
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_WIRE = 512 * 1024 // HTTP bytes across all hops, including headers and chunk framing
|
|
12
|
+
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(' '))
|
|
13
|
+
const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
|
14
|
+
const REDIRECT = new Set([301, 302, 303, 307, 308])
|
|
15
|
+
const unavailable = () => new Error('public HTML unavailable')
|
|
16
|
+
|
|
17
|
+
// This is a cheap lexical filter, not authorization to connect. A and AAAA are checked per hop.
|
|
18
|
+
export function isPublicPageUrl(url) {
|
|
19
|
+
if (!(url instanceof URL) || url.href.length > MAX_URL || !['http:', 'https:'].includes(url.protocol)) return false
|
|
20
|
+
if (url.username || url.password || url.port || url.hostname.length > 253 || isIP(url.hostname)) return false
|
|
21
|
+
const labels = url.hostname.split('.'), tld = labels.at(-1)
|
|
22
|
+
return labels.length > 1 && labels.every(label => LABEL.test(label)) &&
|
|
23
|
+
/^(?:[a-z]{2,63}|xn--[a-z0-9-]+)$/.test(tld) && !SPECIAL_TLDS.has(tld)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function checkedUrl(input, base, allowUrl) {
|
|
27
|
+
const raw = input instanceof URL ? input.href : input
|
|
28
|
+
if (typeof raw !== 'string' || !raw.length || raw.length > MAX_URL) throw unavailable()
|
|
29
|
+
const url = new URL(raw, base)
|
|
30
|
+
if (!isPublicPageUrl(url) || (allowUrl !== undefined && allowUrl(new URL(url.href)) !== true)) throw unavailable()
|
|
31
|
+
return url
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Exclude special-purpose networks, even the globally reachable protocol/anycast exceptions.
|
|
35
|
+
// IPv6 must also be in 2000::/3; that excludes mapped, NAT64, ULA, link-local and multicast.
|
|
36
|
+
const globalV6 = new BlockList()
|
|
37
|
+
globalV6.addSubnet('2000::', 3, 'ipv6')
|
|
38
|
+
const denied = new BlockList()
|
|
39
|
+
for (const cidr of [
|
|
40
|
+
'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',
|
|
41
|
+
'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',
|
|
42
|
+
'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',
|
|
43
|
+
'224.0.0.0/3', '168.63.129.16/32', // multicast/reserved; Azure's platform virtual IP
|
|
44
|
+
'2001::/23', '2001:db8::/32', '2002::/16', '2620:4f:8000::/48', '3ffe::/16', '3fff::/20',
|
|
45
|
+
]) {
|
|
46
|
+
const [address, bits] = cidr.split('/')
|
|
47
|
+
denied.addSubnet(address, Number(bits), address.includes(':') ? 'ipv6' : 'ipv4')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function resolvePin(resolver, host) {
|
|
51
|
+
async function records(family) {
|
|
52
|
+
try {
|
|
53
|
+
// Absolute names: never expand a public-looking name using a local search domain.
|
|
54
|
+
return await resolver[`resolve${family}`](`${host}.`)
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error?.code === 'ENODATA') return [] // No records of this family. Other DNS failures fail closed.
|
|
57
|
+
throw error
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const [v4, v6] = await Promise.all([records(4), records(6)])
|
|
61
|
+
if (!Array.isArray(v4) || !Array.isArray(v6) || !v4.length && !v6.length || v4.length + v6.length > 64) throw unavailable()
|
|
62
|
+
for (const [family, answers] of [[4, v4], [6, v6]]) {
|
|
63
|
+
for (const ip of answers) {
|
|
64
|
+
if (isIP(ip) !== family || ip.includes('%') || family === 6 && !globalV6.check(ip, 'ipv6') ||
|
|
65
|
+
denied.check(ip, family === 4 ? 'ipv4' : 'ipv6')) throw unavailable()
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return v4[0] ?? v6[0]
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function openPage(url, address, signal, budget) {
|
|
72
|
+
const secure = url.protocol === 'https:'
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
// Connect to the validated literal: no second lookup (including autoSelectFamily), proxy or pooled socket.
|
|
75
|
+
// The original DNS name is still the HTTP authority and the identity verified by TLS.
|
|
76
|
+
const req = (secure ? https : http).get({
|
|
77
|
+
protocol: url.protocol, hostname: address, path: url.pathname + url.search, agent: false, signal,
|
|
78
|
+
...(secure && { servername: url.hostname, rejectUnauthorized: true }),
|
|
79
|
+
maxHeaderSize: 16 * 1024,
|
|
80
|
+
headers: { Host: url.host, Accept: 'text/html, application/xhtml+xml', 'Accept-Encoding': 'identity' },
|
|
81
|
+
}, resolve)
|
|
82
|
+
req.on('error', reject)
|
|
83
|
+
req.once('upgrade', (_res, socket) => { socket.destroy(); reject(unavailable()) })
|
|
84
|
+
req.once('socket', socket => {
|
|
85
|
+
const count = chunk => {
|
|
86
|
+
budget.left -= chunk.length
|
|
87
|
+
if (budget.left < 0) req.destroy(unavailable())
|
|
88
|
+
}
|
|
89
|
+
socket.prependListener('data', count)
|
|
90
|
+
req.once('close', () => socket.off('data', count))
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function header(res, name) {
|
|
96
|
+
const values = res.headersDistinct[name]
|
|
97
|
+
if (values && values.length !== 1) throw unavailable()
|
|
98
|
+
return values?.[0]
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// A MIME declaration alone is not enough: reject binary/control bytes and ordinary non-markup text.
|
|
102
|
+
function startsWithHtml(text) {
|
|
103
|
+
let rest = text.trimStart()
|
|
104
|
+
if (/^<\?xml\s/i.test(rest)) {
|
|
105
|
+
const end = rest.indexOf('?>')
|
|
106
|
+
if (end === -1) return false
|
|
107
|
+
rest = rest.slice(end + 2).trimStart()
|
|
108
|
+
}
|
|
109
|
+
while (rest.startsWith('<!--')) {
|
|
110
|
+
const end = rest.indexOf('-->', 4)
|
|
111
|
+
if (end === -1) return false
|
|
112
|
+
rest = rest.slice(end + 3).trimStart()
|
|
113
|
+
}
|
|
114
|
+
return /^<(?:!doctype\s+html|html|head|body|title|meta|base|link|script|style)(?=[\s/>])/i.test(rest)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function htmlPrefix(res, mime) {
|
|
118
|
+
const prefix = Buffer.alloc(MAX_PREFIX)
|
|
119
|
+
let size = 0
|
|
120
|
+
for await (const chunk of res) {
|
|
121
|
+
size += chunk.copy(prefix, size)
|
|
122
|
+
if (size === MAX_PREFIX) break // do not drain/reject a large page just because its body is long
|
|
123
|
+
}
|
|
124
|
+
const sniff = prefix.toString('latin1', 0, Math.min(size, 1024))
|
|
125
|
+
const hint = /<meta\s[^<>]*?\bcharset\s*=\s*["']?\s*([\w.-]+)/i.exec(sniff)?.[1]
|
|
126
|
+
const decoder = new TextDecoder(mime.params.get('charset') ?? hint ?? 'utf-8', { fatal: true })
|
|
127
|
+
if (!['utf-8', 'gbk', 'gb18030', 'windows-1252'].includes(decoder.encoding)) throw unavailable()
|
|
128
|
+
// A capped prefix may end halfway through a character; don't replace it or discard the valid head.
|
|
129
|
+
const html = decoder.decode(prefix.subarray(0, size), { stream: size === MAX_PREFIX })
|
|
130
|
+
if (/[\u0000-\u0008\u000b\u000e-\u001f\u007f-\u009f]/.test(html) || !startsWithHtml(html)) throw unavailable()
|
|
131
|
+
return html
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function readChain(url, allowUrl, resolver, signal) {
|
|
135
|
+
const budget = { left: MAX_WIRE }
|
|
136
|
+
for (let hop = 0; ; hop++) {
|
|
137
|
+
signal.throwIfAborted()
|
|
138
|
+
const pin = await resolvePin(resolver, url.hostname)
|
|
139
|
+
signal.throwIfAborted()
|
|
140
|
+
const res = await openPage(url, pin, signal, budget)
|
|
141
|
+
try {
|
|
142
|
+
if (budget.left < 0) throw unavailable()
|
|
143
|
+
if (REDIRECT.has(res.statusCode)) {
|
|
144
|
+
if (hop >= MAX_REDIRECTS) throw unavailable()
|
|
145
|
+
url = checkedUrl(header(res, 'location'), url, allowUrl)
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
148
|
+
if (res.statusCode !== 200 || (header(res, 'content-encoding') ?? 'identity').trim().toLowerCase() !== 'identity' ||
|
|
149
|
+
/^\s*attachment\b/i.test(header(res, 'content-disposition') ?? '')) throw unavailable()
|
|
150
|
+
const mime = new MIMEType(header(res, 'content-type') ?? '')
|
|
151
|
+
if (mime.essence !== 'text/html' && mime.essence !== 'application/xhtml+xml') throw unavailable()
|
|
152
|
+
const html = await htmlPrefix(res, mime)
|
|
153
|
+
if (budget.left < 0) throw unavailable()
|
|
154
|
+
return { html, url: url.href, contentType: mime.essence }
|
|
155
|
+
} finally {
|
|
156
|
+
res.destroy() // includes redirects, refused responses, truncated reads and decode errors
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Anonymous HTML prefix for server-side metadata extraction only; never serve this HTML to clients. */
|
|
162
|
+
export async function readPublicHtml(input, options = {}) {
|
|
163
|
+
const control = new AbortController()
|
|
164
|
+
let resolver, timer
|
|
165
|
+
try {
|
|
166
|
+
const { allowUrl } = options
|
|
167
|
+
const url = checkedUrl(input, undefined, allowUrl)
|
|
168
|
+
resolver = new dns.Resolver({ timeout: 3_000, tries: 1 })
|
|
169
|
+
const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(unavailable()), TOTAL_MS) })
|
|
170
|
+
return await Promise.race([readChain(url, allowUrl, resolver, control.signal), deadline])
|
|
171
|
+
} catch {
|
|
172
|
+
throw unavailable() // never propagate remote text, addresses, paths or DNS/HTTP/TLS error details
|
|
173
|
+
} finally {
|
|
174
|
+
clearTimeout(timer)
|
|
175
|
+
control.abort()
|
|
176
|
+
resolver?.cancel()
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
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('same-URL concurrent lookups share work, unique active requests are bounded', async () => {
|
|
91
|
+
let count = 0
|
|
92
|
+
const ready = Promise.withResolvers()
|
|
93
|
+
const lookup = createMetadataLookup({ async readHtml(url) { count++; await ready.promise; return { url, html: '<title>Article title</title>' } } })
|
|
94
|
+
const first = parseLink(github)
|
|
95
|
+
const active = [lookup(first), lookup(first), ...Array.from({ length: 7 }, (_, i) => lookup(parseLink(`https://example.com/post/${i}`)))]
|
|
96
|
+
assert.deepEqual(await lookup(parseLink('https://example.com/overflow')), { ok: false, error: 'busy' })
|
|
97
|
+
ready.resolve(); assert.ok((await Promise.all(active)).every(r => r.ok)); assert.equal(count, 8)
|
|
98
|
+
assert.equal((await lookup(first)).ok, true); assert.equal(count, 8)
|
|
99
|
+
})
|