dsh-inline-link-preview 0.5.0-beta.1 → 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/README.md +46 -25
- package/assets/icon-180.png +0 -0
- package/assets/inline-preview-flow.png +0 -0
- package/assets/supported-sources.png +0 -0
- package/index.js +29 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/npm-adapter.js +90 -0
- package/package.json +5 -3
- package/public-fetch.js +104 -16
- package/test/host.test.js +69 -0
- package/test/npm-adapter.test.js +163 -0
- package/test/public-fetch.test.js +185 -1
- package/test/title.test.js +55 -0
- package/title.js +13 -6
package/README.md
CHANGED
|
@@ -1,49 +1,70 @@
|
|
|
1
|
-
# 行内链接预览
|
|
1
|
+
# 行内链接预览 (Inline Link Preview)
|
|
2
2
|
|
|
3
|
-
在 **DeepSeek Harness
|
|
3
|
+
在 **DeepSeek Harness** 聊天输入框中单独粘贴支持的链接后,自动尝试获取标题,并在原位显示为行内的「图标 + 标题」;复制或发送时仍保留原始网址,而不是标题或网页正文。
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
> **说明**:本插件(npm 包:`dsh-inline-link-preview`)仅用于 **DeepSeek Harness**,不是 DeepSeek 官网网页聊天页面的插件。本项目版本为 `0.5.0-beta.2`,声明兼容的 DeepSeek Harness 版本范围为 `>=0.2.2-rc.5 <0.2.3-0`,不承诺兼容其他版本。
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+

|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
## 效果示例
|
|
10
|
+
|
|
11
|
+
无需输入 `@`,也无需先发送消息。在聊天输入框中(包括一段话中间)**单独粘贴**一条支持的链接即可:
|
|
12
|
+
|
|
13
|
+
- **粘贴**:`https://example.com/`
|
|
14
|
+
- **输入框显示**:`📄 Example Domain`
|
|
15
|
+
- **复制或发送**:仍为 `https://example.com/`(不会替换成纯标题,也不会自动附带网页或文档正文)
|
|
16
|
+
|
|
17
|
+
嵌入句子中时,例如先输入 `请看 再写摘要`,把光标放到两个空格之间再单独粘贴 `https://example.com/`:
|
|
18
|
+
|
|
19
|
+
- **输入框显示**:`请看 📄 Example Domain 再写摘要`
|
|
20
|
+
- **复制或发送**:`请看 https://example.com/ 再写摘要`
|
|
21
|
+
|
|
22
|
+
点击行内标题可直接打开原链接;如果标题读取失败、超时或遇到登录验证,原网址会保留在输入框里,照常作为普通链接发送。
|
|
23
|
+
|
|
24
|
+
## 支持哪些链接?
|
|
25
|
+
|
|
26
|
+
| 链接类型 | 说明与前置条件 |
|
|
10
27
|
| --- | --- |
|
|
11
|
-
|
|
|
12
|
-
| GitHub
|
|
13
|
-
|
|
|
14
|
-
|
|
|
28
|
+
| **飞书 / Lark 文档与知识库** | 支持 `feishu.cn`、`larksuite.com`、`larkoffice.com` 及其子域的 HTTPS `/docx/…`、`/wiki/…`。运行 DeepSeek Harness 的主机需安装并登录 `lark-cli`,且登录账号拥有文档查看权限。 |
|
|
29
|
+
| **GitHub 公开页面** | 支持公开仓库、Issue、Pull Request 等公开页面;不需要 GitHub Token,也不读取私有仓库登录态。 |
|
|
30
|
+
| **npm 包页面** | 支持公开包及其明确版本页面;优先从 npm 官方注册表验证包名和版本后生成标题,不读取浏览器登录态。注册表查询失败或校验未通过时可能退回普通网页标题,后者未经注册表独立校验。 |
|
|
31
|
+
| **微信公众号文章** | 支持 `mp.weixin.qq.com/s/…` 或 `/s?__biz=…&mid=…` 等文章分享链接。遇到微信验证或文章失效时,可能无法获取标题,此时保留原网址。 |
|
|
32
|
+
| **普通公开网页** | 支持使用域名的公开 HTTP(S) 页面,需可正常访问且 HTML 含可用标题或静态标题元数据;并非所有公开网页都能预览。只用公开网页时不需要 `lark-cli`。 |
|
|
33
|
+
|
|
34
|
+

|
|
15
35
|
|
|
16
36
|
## 安装和试用 Beta
|
|
17
37
|
|
|
18
|
-
包名 `dsh-inline-link-preview
|
|
38
|
+
包名 `dsh-inline-link-preview`,本项目版本 `0.5.0-beta.2`,声明兼容范围为 **DSH `>=0.2.2-rc.5 <0.2.3-0`**,开发和打包使用 Node.js 22。若正使用本地旧包 `@local/dsh-feishu-link-preview`,请先备份未发的草稿,再停用旧包,**不要同时启用两个版本**。
|
|
19
39
|
|
|
20
|
-
-
|
|
40
|
+
- **从 npm 安装精确 Beta 版本**(以桌面版 profile 为例):
|
|
21
41
|
|
|
22
42
|
```sh
|
|
23
|
-
dsh plugin --profile
|
|
43
|
+
dsh plugin --profile desktop add dsh-inline-link-preview@0.5.0-beta.2
|
|
24
44
|
```
|
|
25
45
|
|
|
26
|
-
-
|
|
46
|
+
- **拿到预发布压缩包时**:可先在独立 DSH profile 试装。在压缩包所在目录运行:
|
|
27
47
|
|
|
28
48
|
```sh
|
|
29
|
-
dsh plugin --profile
|
|
49
|
+
dsh plugin --profile link-preview-beta add "$PWD/dsh-inline-link-preview-0.5.0-beta.2.tgz"
|
|
30
50
|
```
|
|
31
51
|
|
|
32
|
-
打开对应 profile,确认插件「行内链接预览」已启用,刷新窗口(macOS:`⌘R`)。试试上面的 `
|
|
33
|
-
|
|
34
|
-
## 为什么有时还是网址?
|
|
35
|
-
|
|
36
|
-
- 只处理**一次粘贴一条**链接。含说明的整段文字、多条链接或文件按原样粘贴;不扫描旧草稿或改写已发送消息。
|
|
37
|
-
- 标题返回前若继续打字、改变选区、发送或切换会话,插件不会用迟到的结果覆盖草稿。需要重试时,选中那段网址,重新粘贴同一条链接。
|
|
38
|
-
- 遇登录页、验证码、超时、非 HTML 或仅靠 JavaScript 才出现标题的页面,可能读不到。此时网址照常可发。飞书可先检查 `lark-cli` 的登录和文档权限,等待约一分钟再试。
|
|
52
|
+
打开对应 profile,确认插件「行内链接预览」已启用,刷新窗口(macOS:`⌘R`)。试试上面的 `https://example.com/` 例子,等标题出现前先不要移动光标。插件市场是否能搜到,取决于该 profile 启用的索引是否已收录这个版本。
|
|
39
53
|
|
|
40
|
-
##
|
|
54
|
+
## 为什么有时还是网址?(主要限制)
|
|
41
55
|
|
|
42
|
-
|
|
56
|
+
- **仅处理单条粘贴**:当前一次只处理单独粘贴的一条链接。含说明的整段文字、多条链接或文件按原样粘贴;不会自动扫描旧草稿或改写已发送消息。
|
|
57
|
+
- **不覆盖后续编辑**:标题返回前如果继续打字、移动光标、改变选区、发送或切换会话,插件不会用迟到的结果覆盖草稿。需要重试时,选中那段网址重新粘贴即可。
|
|
58
|
+
- **受目标页面与权限限制**:遇登录页、验证码、网络超时、非 HTML 或仅靠 JavaScript 才渲染标题的页面,可能无法获取标题,此时原网址照常可发。飞书文档可先检查 `lark-cli` 登录状态和文档权限,等待约一分钟后再试。
|
|
43
59
|
|
|
44
|
-
|
|
60
|
+
## 粘贴时会访问哪里?(网络与隐私说明)
|
|
45
61
|
|
|
46
|
-
|
|
62
|
+
- **访问发生在粘贴时,不是发送时**:公开网页由运行 DeepSeek Harness 的主机直接请求目标站点,**不使用**浏览器 Cookie 或 Referer,**不经过**第三方预览服务,也不执行目标页面脚本。目标网站可以看到运行主机的网络出口来源、请求路径和查询参数。npm 包页面会先向固定的 npm 官方注册表查询包名和版本;原链接的查询参数和片段不会传给注册表。
|
|
63
|
+
- **可选公共 DNS(默认关闭)**:只有在运行 DSH 的进程环境中明确设置 `DSH_INLINE_PREVIEW_CLOUDFLARE_DNS=1`,且系统 DNS 仅返回 `198.18.0.0/15` 特殊代理地址时,才会向 Cloudflare `1.1.1.1` 查询该网址的**域名**,不发送网址路径、查询参数或片段。这会绕过系统的部分自定义 DNS 策略,Cloudflare 仍可获知所查询的域名和网络出口;不适合希望域名只交由系统 DNS 处理的环境。结果仍需通过全部公网地址校验并固定连接,每次跳转重新验证;无需时取消该环境变量并重启 DSH。桌面图形应用通常不会继承在终端中临时设置的变量,必须确保变量传入 DSH 进程;旧版 `0.5.0-beta.1` 没有此选项。
|
|
64
|
+
- **不会自动访问的地址**:本机 / 内网地址、直接写 IP 的地址、非标准端口,以及含已知凭证或操作特征的链接,不会作为普通网页自动请求。但识别规则无法覆盖所有具有副作用的公开 URL;请勿粘贴访问后可能执行操作的链接。HTTPS 页面不会降级跳转到 HTTP。
|
|
65
|
+
- **飞书与微信查询**:飞书标题通过 `lark-cli drive +inspect --as user` 获取,查询时只传文档路径;微信查询只传文章标识。两者的**可识别的部分临时登录参数**会从可复制、可发送的引用中移除,但**不保证能清除链接中的所有敏感信息**,请勿将其当成通用敏感链接清洗器。
|
|
66
|
+
- **只返回标题,不附带正文**:标题查询只向编辑器返回标题,不会自动把网页或飞书文档正文附到发送内容中;主机在内存中缓存结果(成功 10 分钟、失败 1 分钟)。
|
|
67
|
+
- **本地访问日志提示**:编辑器向本机 Harness 服务查询标题时,目标地址会出现在请求的查询参数中;如果启用了 Web 服务或反向代理访问日志,这些日志可能记录该地址和文档标识,请按需配置日志保留与访问权限。
|
|
47
68
|
|
|
48
69
|
## 开发与许可
|
|
49
70
|
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/index.js
CHANGED
|
@@ -3,7 +3,8 @@ import { constants as fsConstants } from 'node:fs'
|
|
|
3
3
|
import { access } from 'node:fs/promises'
|
|
4
4
|
import { promisify } from 'node:util'
|
|
5
5
|
import { parseLink } from './link-policy.js'
|
|
6
|
-
import { isPublicPageUrl, readPublicHtml } from './public-fetch.js'
|
|
6
|
+
import { createPublicBudget, isPublicPageUrl, readPublicHtml, readPublicJson } from './public-fetch.js'
|
|
7
|
+
import { parseNpmPage, extractNpmTitle } from './npm-adapter.js'
|
|
7
8
|
import { extractPageTitle } from './title.js'
|
|
8
9
|
|
|
9
10
|
const ROUTE = '/feishu-link-preview'
|
|
@@ -11,6 +12,7 @@ const CACHE_TTL_MS = 10 * 60 * 1000
|
|
|
11
12
|
const FAILURE_TTL_MS = 60 * 1000
|
|
12
13
|
const MAX_CACHE_ENTRIES = 200
|
|
13
14
|
const INSPECT_TIMEOUT_MS = 8000
|
|
15
|
+
const NPM_TIMEOUT_MS = 8000 // one deadline across registry lookup and optional HTML fallback
|
|
14
16
|
const MAX_INFLIGHT = 8
|
|
15
17
|
const MAX_TITLE = 200
|
|
16
18
|
const CLI_CANDIDATES = [
|
|
@@ -118,7 +120,9 @@ async function inspectFeishu(url) {
|
|
|
118
120
|
|
|
119
121
|
// Per plugin activation, title-only in-memory cache. The public branch gets no lark-cli identity,
|
|
120
122
|
// browser state, DSH request headers or fallback that renders/executes the target page.
|
|
121
|
-
export function createMetadataLookup({
|
|
123
|
+
export function createMetadataLookup({
|
|
124
|
+
inspectDocument = inspectFeishu, readHtml = readPublicHtml, readJson = readPublicJson, publicDnsFallback = false,
|
|
125
|
+
} = {}) {
|
|
122
126
|
const cache = new Map(), inflight = new Map()
|
|
123
127
|
return async target => {
|
|
124
128
|
const key = target.lookup
|
|
@@ -129,7 +133,25 @@ export function createMetadataLookup({ inspectDocument = inspectFeishu, readHtml
|
|
|
129
133
|
const job = Promise.resolve().then(async () => {
|
|
130
134
|
if (isDoc(target.kind)) return inspectDocument(key)
|
|
131
135
|
const allowUrl = url => allowedHop(target.kind, url)
|
|
132
|
-
const
|
|
136
|
+
const npm = target.kind === 'web' ? parseNpmPage(target.ref) : null
|
|
137
|
+
const signal = npm ? AbortSignal.timeout(NPM_TIMEOUT_MS) : undefined
|
|
138
|
+
const budget = npm ? createPublicBudget() : undefined
|
|
139
|
+
if (npm) {
|
|
140
|
+
try {
|
|
141
|
+
// Registry identity is constructed from validated components, never from page metadata.
|
|
142
|
+
// Do not forward the user's query/fragment or follow redirects to another endpoint.
|
|
143
|
+
const data = await readJson(npm.registryUrl, {
|
|
144
|
+
allowUrl: url => url.href === npm.registryUrl,
|
|
145
|
+
publicDnsFallback, signal, budget,
|
|
146
|
+
})
|
|
147
|
+
const title = extractNpmTitle(npm, data)
|
|
148
|
+
if (title) return title
|
|
149
|
+
} catch {
|
|
150
|
+
// A normal HTML page may still work when registry metadata is unavailable.
|
|
151
|
+
}
|
|
152
|
+
signal.throwIfAborted()
|
|
153
|
+
}
|
|
154
|
+
const page = await readHtml(key, { allowUrl, publicDnsFallback, signal, budget })
|
|
133
155
|
return extractPageTitle(page.html, parseLink(String(page.url))?.kind ?? target.kind)
|
|
134
156
|
}).then(title => {
|
|
135
157
|
const label = safeLabel(title)
|
|
@@ -177,12 +199,15 @@ export function createHandler(ctx, metadataFor = createMetadataLookup()) {
|
|
|
177
199
|
}
|
|
178
200
|
|
|
179
201
|
export function apply(ctx) {
|
|
202
|
+
// Opt-in protects existing users from silently sending domains to another DNS provider.
|
|
203
|
+
const publicDnsFallback = process.env.DSH_INLINE_PREVIEW_CLOUDFLARE_DNS === '1'
|
|
204
|
+
const metadataFor = createMetadataLookup({ publicDnsFallback })
|
|
180
205
|
ctx.effect(
|
|
181
206
|
() =>
|
|
182
207
|
ctx.webServer.register({
|
|
183
208
|
kind: 'exact',
|
|
184
209
|
path: ROUTE,
|
|
185
|
-
handler: createHandler(ctx),
|
|
210
|
+
handler: createHandler(ctx, metadataFor),
|
|
186
211
|
}),
|
|
187
212
|
'feishu-link-preview: document metadata route',
|
|
188
213
|
)
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
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."
|
|
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 and npm pages, WeChat articles and other webpages are requested anonymously on paste. If a title is unavailable, the URL stays editable."
|
|
5
5
|
}
|
|
6
6
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "行内链接预览",
|
|
4
|
-
"description": "在聊天输入框单独粘贴一条链接,读到标题后在原位显示文档图标和标题;复制、发送仍是网址。支持飞书文档与知识库(需已登录 lark-cli)、公开 GitHub
|
|
4
|
+
"description": "在聊天输入框单独粘贴一条链接,读到标题后在原位显示文档图标和标题;复制、发送仍是网址。支持飞书文档与知识库(需已登录 lark-cli)、公开 GitHub 页面、npm 包页面、微信公众号文章和普通网页。公开页面在粘贴时匿名访问,失败或遇验证时保留网址。"
|
|
5
5
|
}
|
|
6
6
|
}
|
package/npm-adapter.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// A pure adapter for npm package pages. It never performs I/O: the caller must obtain
|
|
2
|
+
// JSON from the exact registryUrl using an appropriately pinned, no-redirect transport.
|
|
3
|
+
const MAX_INPUT = 16384
|
|
4
|
+
const MAX_PATH = 2048
|
|
5
|
+
const MAX_PACKAGE = 214
|
|
6
|
+
const MAX_VERSION = 256
|
|
7
|
+
const REGISTRY = 'https://registry.npmjs.org/'
|
|
8
|
+
const namePart = /^[A-Za-z0-9~-][A-Za-z0-9._~-]*$/
|
|
9
|
+
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/
|
|
10
|
+
|
|
11
|
+
function validPackageName(name) {
|
|
12
|
+
if (typeof name !== 'string' || name.length === 0 || name.length > MAX_PACKAGE) return false
|
|
13
|
+
if (name[0] !== '@') return namePart.test(name)
|
|
14
|
+
const slash = name.indexOf('/')
|
|
15
|
+
return slash > 1 && name.indexOf('/', slash + 1) === -1 &&
|
|
16
|
+
namePart.test(name.slice(1, slash)) && namePart.test(name.slice(slash + 1))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function validVersion(version) {
|
|
20
|
+
if (typeof version !== 'string' || version.length === 0 || version.length > MAX_VERSION) return false
|
|
21
|
+
const match = semver.exec(version)
|
|
22
|
+
if (!match || !match.slice(1, 4).every(part => Number.isSafeInteger(Number(part)))) return false
|
|
23
|
+
// Numeric prerelease identifiers cannot have leading zeroes in exact SemVer.
|
|
24
|
+
return !match[4] || match[4].split('.').every(part => !/^\d+$/.test(part) || part === '0' || part[0] !== '0')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function registryUrl(packageName, version) {
|
|
28
|
+
return REGISTRY + encodeURIComponent(packageName) + '/' + encodeURIComponent(version ?? 'latest')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Recognize only npm's exact HTTPS package-page routes and return a fixed registry lookup. */
|
|
32
|
+
export function parseNpmPage(input) {
|
|
33
|
+
if (typeof input !== 'string' || input.length > MAX_INPUT || /[\s\\<>\u0000-\u001f\u007f\ufffc]/u.test(input)) return null
|
|
34
|
+
// Examine the original path before URL normalization can erase dot-segment tricks.
|
|
35
|
+
// Requiring this exact authority also rejects credentials, host aliases, and odd ports.
|
|
36
|
+
const match = /^https:\/\/(?:www\.)?npmjs\.com(?::443)?(\/[^?#]*)?(?:[?#]|$)/i.exec(input)
|
|
37
|
+
const path = match?.[1]
|
|
38
|
+
if (!path || path.length > MAX_PATH || !path.startsWith('/package/')) return null
|
|
39
|
+
const parts = path.slice('/package/'.length).split('/')
|
|
40
|
+
if (parts.at(-1) === '') parts.pop() // accept one ordinary trailing slash
|
|
41
|
+
if (!parts.length || parts.some(part => !part)) return null
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const first = decodeURIComponent(parts[0])
|
|
45
|
+
let packageName, consumed
|
|
46
|
+
if (first.startsWith('@') && !first.includes('/')) {
|
|
47
|
+
if (parts.length < 2) return null
|
|
48
|
+
packageName = first + '/' + decodeURIComponent(parts[1])
|
|
49
|
+
consumed = 2
|
|
50
|
+
} else {
|
|
51
|
+
// An encoded slash is permitted only as the single scope/name separator.
|
|
52
|
+
packageName = first
|
|
53
|
+
consumed = 1
|
|
54
|
+
}
|
|
55
|
+
if (!validPackageName(packageName)) return null
|
|
56
|
+
const rest = parts.slice(consumed)
|
|
57
|
+
let version = null
|
|
58
|
+
if (rest.length) {
|
|
59
|
+
if (rest.length !== 2 || rest[0] !== 'v') return null
|
|
60
|
+
version = decodeURIComponent(rest[1])
|
|
61
|
+
if (!validVersion(version)) return null
|
|
62
|
+
}
|
|
63
|
+
return { packageName, version, registryUrl: registryUrl(packageName, version) }
|
|
64
|
+
} catch {
|
|
65
|
+
// Malformed escapes are not a package-page identity.
|
|
66
|
+
return null
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Extract a plain title only when registry JSON proves this exact name and version. */
|
|
71
|
+
export function extractNpmTitle(page, data) {
|
|
72
|
+
try {
|
|
73
|
+
if (!page || typeof page !== 'object' || Array.isArray(page) ||
|
|
74
|
+
!Object.hasOwn(page, 'packageName') || !Object.hasOwn(page, 'version') || !Object.hasOwn(page, 'registryUrl')) return null
|
|
75
|
+
// Snapshot each property once, so even a hostile caller's getters cannot change it after validation.
|
|
76
|
+
const { packageName, version, registryUrl: url } = page
|
|
77
|
+
if (!validPackageName(packageName) || (version !== null && !validVersion(version)) ||
|
|
78
|
+
url !== registryUrl(packageName, version)) return null
|
|
79
|
+
if (!data || typeof data !== 'object' || Array.isArray(data) ||
|
|
80
|
+
!Object.hasOwn(data, 'name') || !Object.hasOwn(data, 'version')) return null
|
|
81
|
+
const { name, version: foundVersion } = data
|
|
82
|
+
if (name !== packageName || !validVersion(foundVersion) ||
|
|
83
|
+
(version !== null && foundVersion !== version)) return null
|
|
84
|
+
// Both fields use a restricted ASCII grammar; don't truncate away version or npm identity.
|
|
85
|
+
const title = `${name}@${foundVersion} - npm`
|
|
86
|
+
return title.length <= 200 ? title : null
|
|
87
|
+
} catch {
|
|
88
|
+
return null
|
|
89
|
+
}
|
|
90
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-inline-link-preview",
|
|
3
|
-
"version": "0.5.0-beta.
|
|
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.",
|
|
3
|
+
"version": "0.5.0-beta.2",
|
|
4
|
+
"description": "Preview a pasted link as an inline title in the DeepSeek Harness composer. Supports Feishu/Lark, GitHub, npm, WeChat articles and public webpages; copy or send the URL.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "dsh-inline-link-preview contributors",
|
|
7
7
|
"repository": {
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"bugs": {
|
|
13
13
|
"url": "https://github.com/mark-qtech/dsh-inline-link-preview/issues"
|
|
14
14
|
},
|
|
15
|
-
"keywords": ["deepseek-harness", "dsh-plugin", "link-preview", "composer", "feishu", "lark", "github", "wechat"],
|
|
15
|
+
"keywords": ["deepseek-harness", "dsh-plugin", "link-preview", "composer", "feishu", "lark", "github", "npm", "wechat"],
|
|
16
16
|
"type": "module",
|
|
17
17
|
"engines": {
|
|
18
18
|
"node": ">=22",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"files": [
|
|
37
37
|
"index.js",
|
|
38
38
|
"link-policy.js",
|
|
39
|
+
"npm-adapter.js",
|
|
39
40
|
"title.js",
|
|
40
41
|
"public-fetch.js",
|
|
41
42
|
"composer.js",
|
|
@@ -45,6 +46,7 @@
|
|
|
45
46
|
"cordis.patch.yml",
|
|
46
47
|
"locale/*.json",
|
|
47
48
|
"icon.svg",
|
|
49
|
+
"assets/*.png",
|
|
48
50
|
"README.md",
|
|
49
51
|
"LICENSE"
|
|
50
52
|
],
|
package/public-fetch.js
CHANGED
|
@@ -8,11 +8,20 @@ const TOTAL_MS = 6_000
|
|
|
8
8
|
const MAX_URL = 4_096
|
|
9
9
|
const MAX_REDIRECTS = 3
|
|
10
10
|
const MAX_PREFIX = 128 * 1024
|
|
11
|
+
const MAX_DNS_RESPONSE = 16 * 1024
|
|
11
12
|
const MAX_WIRE = 512 * 1024 // HTTP bytes across all hops, including headers and chunk framing
|
|
12
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(' '))
|
|
13
14
|
const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
|
14
15
|
const REDIRECT = new Set([301, 302, 303, 307, 308])
|
|
15
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
|
+
}
|
|
16
25
|
|
|
17
26
|
// This is a cheap lexical filter, not authorization to connect. A and AAAA are checked per hop.
|
|
18
27
|
export function isPublicPageUrl(url) {
|
|
@@ -47,7 +56,39 @@ for (const cidr of [
|
|
|
47
56
|
denied.addSubnet(address, Number(bits), address.includes(':') ? 'ipv6' : 'ipv4')
|
|
48
57
|
}
|
|
49
58
|
|
|
50
|
-
|
|
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) {
|
|
51
92
|
async function records(family) {
|
|
52
93
|
try {
|
|
53
94
|
// Absolute names: never expand a public-looking name using a local search domain.
|
|
@@ -57,18 +98,24 @@ async function resolvePin(resolver, host) {
|
|
|
57
98
|
throw error
|
|
58
99
|
}
|
|
59
100
|
}
|
|
60
|
-
|
|
101
|
+
let [v4, v6] = await Promise.all([records(4), records(6)])
|
|
61
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
|
+
}
|
|
62
109
|
for (const [family, answers] of [[4, v4], [6, v6]]) {
|
|
63
110
|
for (const ip of answers) {
|
|
64
|
-
if (isIP(ip) !== family || ip.includes('%') || family === 6 && !globalV6.check(ip, 'ipv6') ||
|
|
111
|
+
if (typeof ip !== 'string' || isIP(ip) !== family || ip.includes('%') || family === 6 && !globalV6.check(ip, 'ipv6') ||
|
|
65
112
|
denied.check(ip, family === 4 ? 'ipv4' : 'ipv6')) throw unavailable()
|
|
66
113
|
}
|
|
67
114
|
}
|
|
68
115
|
return v4[0] ?? v6[0]
|
|
69
116
|
}
|
|
70
117
|
|
|
71
|
-
function openPage(url, address, signal, budget) {
|
|
118
|
+
function openPage(url, address, signal, budget, accept = 'text/html, application/xhtml+xml') {
|
|
72
119
|
const secure = url.protocol === 'https:'
|
|
73
120
|
return new Promise((resolve, reject) => {
|
|
74
121
|
// Connect to the validated literal: no second lookup (including autoSelectFamily), proxy or pooled socket.
|
|
@@ -77,7 +124,7 @@ function openPage(url, address, signal, budget) {
|
|
|
77
124
|
protocol: url.protocol, hostname: address, path: url.pathname + url.search, agent: false, signal,
|
|
78
125
|
...(secure && { servername: url.hostname, rejectUnauthorized: true }),
|
|
79
126
|
maxHeaderSize: 16 * 1024,
|
|
80
|
-
headers: { Host: url.host, Accept:
|
|
127
|
+
headers: { Host: url.host, Accept: accept, 'Accept-Encoding': 'identity' },
|
|
81
128
|
}, resolve)
|
|
82
129
|
req.on('error', reject)
|
|
83
130
|
req.once('upgrade', (_res, socket) => { socket.destroy(); reject(unavailable()) })
|
|
@@ -131,23 +178,45 @@ async function htmlPrefix(res, mime) {
|
|
|
131
178
|
return html
|
|
132
179
|
}
|
|
133
180
|
|
|
134
|
-
|
|
135
|
-
|
|
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) {
|
|
136
195
|
for (let hop = 0; ; hop++) {
|
|
137
196
|
signal.throwIfAborted()
|
|
138
|
-
|
|
197
|
+
if (budget.left <= 0) throw unavailable()
|
|
198
|
+
const pin = await resolvePin(resolver, url.hostname, signal, budget, publicDnsFallback)
|
|
139
199
|
signal.throwIfAborted()
|
|
140
|
-
|
|
200
|
+
if (budget.left <= 0) throw unavailable()
|
|
201
|
+
const res = await openPage(url, pin, signal, budget, mode === 'json' ? 'application/json' : undefined)
|
|
141
202
|
try {
|
|
142
203
|
if (budget.left < 0) throw unavailable()
|
|
143
204
|
if (REDIRECT.has(res.statusCode)) {
|
|
144
|
-
if (hop >= MAX_REDIRECTS) throw unavailable()
|
|
145
|
-
|
|
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
|
|
146
209
|
continue
|
|
147
210
|
}
|
|
148
211
|
if (res.statusCode !== 200 || (header(res, 'content-encoding') ?? 'identity').trim().toLowerCase() !== 'identity' ||
|
|
149
212
|
/^\s*attachment\b/i.test(header(res, 'content-disposition') ?? '')) throw unavailable()
|
|
150
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
|
+
}
|
|
151
220
|
if (mime.essence !== 'text/html' && mime.essence !== 'application/xhtml+xml') throw unavailable()
|
|
152
221
|
const html = await htmlPrefix(res, mime)
|
|
153
222
|
if (budget.left < 0) throw unavailable()
|
|
@@ -158,21 +227,40 @@ async function readChain(url, allowUrl, resolver, signal) {
|
|
|
158
227
|
}
|
|
159
228
|
}
|
|
160
229
|
|
|
161
|
-
|
|
162
|
-
export async function readPublicHtml(input, options = {}) {
|
|
230
|
+
async function readPublic(input, options, mode) {
|
|
163
231
|
const control = new AbortController()
|
|
164
|
-
let resolver, timer
|
|
232
|
+
let resolver, timer, signal, abortListener
|
|
165
233
|
try {
|
|
166
|
-
const { allowUrl } = options
|
|
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()
|
|
167
239
|
const url = checkedUrl(input, undefined, allowUrl)
|
|
240
|
+
if (mode === 'json' && url.protocol !== 'https:') throw unavailable()
|
|
168
241
|
resolver = new dns.Resolver({ timeout: 3_000, tries: 1 })
|
|
169
242
|
const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(unavailable()), TOTAL_MS) })
|
|
170
|
-
|
|
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])
|
|
171
248
|
} catch {
|
|
172
249
|
throw unavailable() // never propagate remote text, addresses, paths or DNS/HTTP/TLS error details
|
|
173
250
|
} finally {
|
|
174
251
|
clearTimeout(timer)
|
|
252
|
+
if (abortListener) signal.removeEventListener('abort', abortListener)
|
|
175
253
|
control.abort()
|
|
176
254
|
resolver?.cancel()
|
|
177
255
|
}
|
|
178
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
|
+
}
|
package/test/host.test.js
CHANGED
|
@@ -87,6 +87,75 @@ test('no title or transport failure: title-only response fails closed and negati
|
|
|
87
87
|
}
|
|
88
88
|
})
|
|
89
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
|
+
|
|
90
159
|
test('same-URL concurrent lookups share work, unique active requests are bounded', async () => {
|
|
91
160
|
let count = 0
|
|
92
161
|
const ready = Promise.withResolvers()
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import test from 'node:test'
|
|
3
|
+
import { extractNpmTitle, parseNpmPage } from '../npm-adapter.js'
|
|
4
|
+
|
|
5
|
+
const page = path => `https://www.npmjs.com/package/${path}`
|
|
6
|
+
const result = (packageName, version = null) => ({
|
|
7
|
+
packageName,
|
|
8
|
+
version,
|
|
9
|
+
registryUrl: `https://registry.npmjs.org/${encodeURIComponent(packageName)}/${encodeURIComponent(version ?? 'latest')}`,
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
const validPages = [
|
|
13
|
+
['reported prerelease page', page('dsh-inline-link-preview/v/0.5.0-beta.1'), result('dsh-inline-link-preview', '0.5.0-beta.1')],
|
|
14
|
+
['unversioned page uses latest', page('lodash'), result('lodash')],
|
|
15
|
+
['bare official host', 'https://npmjs.com/package/react/v/18.3.1', result('react', '18.3.1')],
|
|
16
|
+
['case-insensitive host and default port', 'HTTPS://WWW.NPMJS.COM:443/package/Foo_Bar/v/1.2.3/', result('Foo_Bar', '1.2.3')],
|
|
17
|
+
['literal scoped path', page('@types/node/v/20.12.7'), result('@types/node', '20.12.7')],
|
|
18
|
+
['encoded @ in scoped path', page('%40types/node'), result('@types/node')],
|
|
19
|
+
['encoded slash in scoped path', page('@types%2fnode'), result('@types/node')],
|
|
20
|
+
['fully encoded scoped path', page('%40types%2Fnode/v/20.12.7'), result('@types/node', '20.12.7')],
|
|
21
|
+
['encoded ordinary characters and build metadata', page('some%2Epackage/v/1.2.3-beta.1%2Bbuild.7'), result('some.package', '1.2.3-beta.1+build.7')],
|
|
22
|
+
['raw build metadata, ignored query and fragment', page('react/v/1.2.3+build.1?next=https://evil.invalid/path#readme'), result('react', '1.2.3+build.1')],
|
|
23
|
+
['query and fragment do not reach registry', page('react?access_token=secret#foo?signature=secret'), result('react')],
|
|
24
|
+
['supported legacy name characters', page('Some_pkg.name~legacy'), result('Some_pkg.name~legacy')],
|
|
25
|
+
['hyphen-leading package names', page('-package-name'), result('-package-name')],
|
|
26
|
+
['tilde-leading legacy package names', page('~legacy'), result('~legacy')],
|
|
27
|
+
['SemVer maximum safe core integer', page('x/v/9007199254740991.0.0-0'), result('x', '9007199254740991.0.0-0')],
|
|
28
|
+
]
|
|
29
|
+
for (const [name, input, expected] of validPages) test(name, () => assert.deepEqual(parseNpmPage(input), expected))
|
|
30
|
+
|
|
31
|
+
test('reject non-strings and arbitrary hosts, credentials or ports', () => {
|
|
32
|
+
const bad = [
|
|
33
|
+
undefined, null, 1, {}, new URL(page('react')), '',
|
|
34
|
+
'http://www.npmjs.com/package/react',
|
|
35
|
+
'https://npmjs.com.evil.invalid/package/react',
|
|
36
|
+
'https://evil-npmjs.com/package/react',
|
|
37
|
+
'https://registry.npmjs.org/package/react',
|
|
38
|
+
'https://npmjs.com./package/react',
|
|
39
|
+
'https://www.%6Epmjs.com/package/react',
|
|
40
|
+
'https://user@www.npmjs.com/package/react',
|
|
41
|
+
'https://@www.npmjs.com/package/react',
|
|
42
|
+
'https://user:password@www.npmjs.com/package/react',
|
|
43
|
+
'https://npmjs.com@evil.invalid/package/react',
|
|
44
|
+
'https://www.npmjs.com:444/package/react',
|
|
45
|
+
'https://www.npmjs.com:/package/react',
|
|
46
|
+
'https://www.npmjs.com:0443/package/react',
|
|
47
|
+
'https://www.npmjs.com\\package\\react',
|
|
48
|
+
` ${page('react')}`,
|
|
49
|
+
page('re\nact'),
|
|
50
|
+
page('react?white space'),
|
|
51
|
+
]
|
|
52
|
+
for (const input of bad) assert.equal(parseNpmPage(input), null, String(input))
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('reject non-package routes and raw or encoded path tricks', () => {
|
|
56
|
+
const bad = [
|
|
57
|
+
'https://www.npmjs.com/',
|
|
58
|
+
'https://www.npmjs.com/package',
|
|
59
|
+
page(''), page('react//'), page('react//v/1.0.0'),
|
|
60
|
+
'https://www.npmjs.com/%70ackage/react',
|
|
61
|
+
'https://www.npmjs.com/Package/react',
|
|
62
|
+
page('react/extra'), page('react/v/1.0.0/extra'), page('react/%76/1.0.0'),
|
|
63
|
+
page('react/../other'), page('react/%2e%2e/other'), page('%2E%2E'),
|
|
64
|
+
page('react%2Fv%2F1.0.0'), page('react%252Fv%252F1.0.0'),
|
|
65
|
+
page('@scope%252Fpkg'), page('%2540scope%252Fpkg'),
|
|
66
|
+
page('@scope%2Fpkg%2Fother'), page('@scope/pkg%2Fother'),
|
|
67
|
+
page('@scope%2F..'), page('@scope%2F%2Fpkg'),
|
|
68
|
+
page('@scope%5Cpkg'), page('react%5Cother'),
|
|
69
|
+
page('react%3Fother'), page('react%23other'), page('react%00'), page('react%0A'), page('react%0D'),
|
|
70
|
+
page('%'), page('%2'), page('%GG'), page('%C0%AF'), page('%ED%A0%80'),
|
|
71
|
+
page('react/v/1.0.0%2Fother'), page('react/v/1.0.0%252Fother'),
|
|
72
|
+
]
|
|
73
|
+
for (const input of bad) assert.equal(parseNpmPage(input), null, input)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
test('reject ambiguous or unbounded package names and non-exact versions', () => {
|
|
77
|
+
const names = [
|
|
78
|
+
'.', '..', '.hidden', '_hidden', '@', '@scope', '@scope/', '@/pkg', '@.scope/pkg', '@scope/.pkg',
|
|
79
|
+
'@scope/_pkg', '@scope/pkg/other', '@scope%2Fpkg%2Fextra', 'a b', 'a%20b', 'a%00b',
|
|
80
|
+
'a%3Cb', 'a%26b', 'café', '%E2%80%AEabc', 'a'.repeat(215), '@scope/' + 'x'.repeat(208),
|
|
81
|
+
]
|
|
82
|
+
for (const name of names) assert.equal(parseNpmPage(page(name)), null, name)
|
|
83
|
+
const versions = [
|
|
84
|
+
'', 'latest', 'beta', '*', '1', '1.2', '1.2.x', '^1.2.3', '~1.2.3', 'v1.2.3', '=1.2.3',
|
|
85
|
+
'01.2.3', '1.02.3', '1.2.03', '1.2.3-01', '1.2.3-a.01', '1.2.3-', '1.2.3+',
|
|
86
|
+
'1.2.3-foo..bar', '1.2.3+foo..bar', '1.2.3-alpha_beta', '1.2.3%00',
|
|
87
|
+
'9007199254740992.0.0', '1.2.3-' + 'a'.repeat(251),
|
|
88
|
+
]
|
|
89
|
+
for (const version of versions) assert.equal(parseNpmPage(page('pkg/v/' + version)), null, version)
|
|
90
|
+
assert.ok(parseNpmPage(page('x'.repeat(214))))
|
|
91
|
+
assert.ok(parseNpmPage(page('x/v/1.2.3-' + 'a'.repeat(250)))) // 256 chars
|
|
92
|
+
assert.equal(parseNpmPage(page('x') + '?q=' + 'a'.repeat(16384)), null)
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('derive a plain title only from matching version JSON', () => {
|
|
96
|
+
const requested = parseNpmPage(page('dsh-inline-link-preview/v/0.5.0-beta.1'))
|
|
97
|
+
assert.equal(extractNpmTitle(requested, { name: 'dsh-inline-link-preview', version: '0.5.0-beta.1', description: '<b>ignored</b>' }), 'dsh-inline-link-preview@0.5.0-beta.1 - npm')
|
|
98
|
+
const scoped = parseNpmPage(page('%40scope%2Fpkg'))
|
|
99
|
+
assert.equal(extractNpmTitle(scoped, { name: '@scope/pkg', version: '1.2.3-beta.1+build.42' }), '@scope/pkg@1.2.3-beta.1+build.42 - npm')
|
|
100
|
+
assert.equal(extractNpmTitle(scoped, { name: '@scope/pkg', version: '0.0.0' }), '@scope/pkg@0.0.0 - npm')
|
|
101
|
+
assert.equal(extractNpmTitle(parseNpmPage(page('pkg/v/1.2.3+build.1')), { name: 'pkg', version: '1.2.3+build.1' }), 'pkg@1.2.3+build.1 - npm')
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
test('registry labels never truncate package version or npm identity', () => {
|
|
105
|
+
const shortName = 'a'.repeat(188), longName = 'a'.repeat(189), version = '1.2.3'
|
|
106
|
+
const short = extractNpmTitle(parseNpmPage(page(shortName)), { name: shortName, version })
|
|
107
|
+
assert.equal(short.length, 200)
|
|
108
|
+
assert.ok(short.endsWith('@1.2.3 - npm'))
|
|
109
|
+
assert.equal(extractNpmTitle(parseNpmPage(page(longName)), { name: longName, version }), null)
|
|
110
|
+
const longVersion = '1.2.3-' + 'b'.repeat(190)
|
|
111
|
+
assert.equal(extractNpmTitle(parseNpmPage(page('pkg')), { name: 'pkg', version: longVersion }), null)
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
test('no label for mismatched, malformed or attacker-controlled registry JSON', () => {
|
|
115
|
+
const requested = parseNpmPage(page('pkg/v/1.2.3'))
|
|
116
|
+
const latest = parseNpmPage(page('pkg'))
|
|
117
|
+
const invalid = [
|
|
118
|
+
undefined, null, '', '1.2.3', 0, [],
|
|
119
|
+
{}, { name: 'other', version: '1.2.3' }, { name: 'PKG', version: '1.2.3' },
|
|
120
|
+
{ name: 'pkg', version: '1.2.4' }, { name: 'pkg', version: '1.2.3+other' },
|
|
121
|
+
{ name: 'pkg', version: 'latest' }, { name: 'pkg', version: '1.2' },
|
|
122
|
+
{ name: 'pkg', version: '01.2.3' }, { name: 'pkg', version: '1.2.3-01' },
|
|
123
|
+
{ name: 'pkg', version: '1.2.3\n' }, { name: 'pkg', version: '1.2.3\u202e' },
|
|
124
|
+
{ name: 'pkg', version: '1.2.3</b>' }, { name: 'pkg\u202e', version: '1.2.3' },
|
|
125
|
+
{ name: ['pkg'], version: '1.2.3' }, { name: 'pkg', version: 123 },
|
|
126
|
+
{ name: 'pkg', version: '1.2.3-' + 'x'.repeat(251) },
|
|
127
|
+
Object.create({ name: 'pkg', version: '1.2.3' }),
|
|
128
|
+
]
|
|
129
|
+
for (const data of invalid) assert.equal(extractNpmTitle(requested, data), null, String(data))
|
|
130
|
+
for (const data of invalid.filter(data => !data || typeof data !== 'object' || !['1.2.4', '1.2.3+other'].includes(data.version))) {
|
|
131
|
+
// Another valid version is appropriate for latest, but malformed fixtures are not.
|
|
132
|
+
assert.equal(extractNpmTitle(latest, data), null, String(data))
|
|
133
|
+
}
|
|
134
|
+
assert.equal(extractNpmTitle(latest, { name: 'pkg', version: '1.2.4' }), 'pkg@1.2.4 - npm')
|
|
135
|
+
assert.equal(extractNpmTitle(latest, { name: 'pkg', version: '1.2.3+other' }), 'pkg@1.2.3+other - npm')
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
test('reject malformed page descriptors rather than synthesizing unverified labels', () => {
|
|
139
|
+
const data = { name: 'pkg', version: '1.2.3' }
|
|
140
|
+
const valid = parseNpmPage(page('pkg/v/1.2.3'))
|
|
141
|
+
const bad = [
|
|
142
|
+
undefined, null, [], {},
|
|
143
|
+
{ ...valid, packageName: 'other' }, { ...valid, version: 'latest' },
|
|
144
|
+
{ ...valid, version: undefined }, { ...valid, registryUrl: 'https://evil.invalid/pkg/1.2.3' },
|
|
145
|
+
{ ...valid, registryUrl: valid.registryUrl + '?url=evil' },
|
|
146
|
+
{ packageName: 'pkg', version: '1.2.3' },
|
|
147
|
+
Object.create(valid),
|
|
148
|
+
]
|
|
149
|
+
for (const input of bad) assert.equal(extractNpmTitle(input, data), null, String(input))
|
|
150
|
+
assert.equal(extractNpmTitle(valid, new Proxy({}, { getOwnPropertyDescriptor() { throw Error('bad data') } })), null)
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
test('validated labels cannot be swapped through changing getters', () => {
|
|
154
|
+
const requested = parseNpmPage(page('pkg/v/1.2.3'))
|
|
155
|
+
let names = 0, versions = 0
|
|
156
|
+
const data = {
|
|
157
|
+
get name() { return ++names === 1 ? 'pkg' : '<unsafe>' },
|
|
158
|
+
get version() { return ++versions === 1 ? '1.2.3' : '\u202e<script>' },
|
|
159
|
+
}
|
|
160
|
+
assert.equal(extractNpmTitle(requested, data), 'pkg@1.2.3 - npm')
|
|
161
|
+
assert.equal(names, 1)
|
|
162
|
+
assert.equal(versions, 1)
|
|
163
|
+
})
|
|
@@ -5,7 +5,7 @@ import http from 'node:http'
|
|
|
5
5
|
import https from 'node:https'
|
|
6
6
|
import { PassThrough, Readable } from 'node:stream'
|
|
7
7
|
import test from 'node:test'
|
|
8
|
-
import { isPublicPageUrl, readPublicHtml } from '../public-fetch.js'
|
|
8
|
+
import { createPublicBudget, isPublicPageUrl, readPublicHtml, readPublicJson } from '../public-fetch.js'
|
|
9
9
|
|
|
10
10
|
const page = 'https://news.example.com/story', ipv4 = '93.184.216.34', ipv6 = '2606:4700:4700::1111'
|
|
11
11
|
const rejected = promise => assert.rejects(promise, { name: 'Error', message: 'public HTML unavailable' })
|
|
@@ -216,6 +216,39 @@ test('the HTTP byte budget is shared across hops and includes data outside the d
|
|
|
216
216
|
assert.ok(calls.http.at(-1).req.destroyed)
|
|
217
217
|
})
|
|
218
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
|
+
|
|
219
252
|
test('the total deadline cancels unresolved DNS; late DNS completion cannot start a request', async t => {
|
|
220
253
|
t.mock.timers.enable({ apis: ['setTimeout'] })
|
|
221
254
|
const slow = Promise.withResolvers(), calls = network(t, [], (_host, family) => family === 4 ? slow.promise : [])
|
|
@@ -246,3 +279,154 @@ test('transport errors and protocol upgrades are sanitized and release the socke
|
|
|
246
279
|
await rejected(readPublicHtml(page))
|
|
247
280
|
assert.ok(calls.http.every(({ req }) => req.destroyed))
|
|
248
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
|
+
})
|
package/test/title.test.js
CHANGED
|
@@ -16,6 +16,16 @@ const pages = [
|
|
|
16
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
17
|
['web: only decode one layer of entities', 'web', '<title>R&amp;D © © 中</title>', 'R&D © © 中'],
|
|
18
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'],
|
|
19
29
|
]
|
|
20
30
|
for (const [page, kind, html, expected] of pages) test(page, () => assert.equal(extractPageTitle(html, kind), expected))
|
|
21
31
|
|
|
@@ -37,6 +47,17 @@ const unavailable = [
|
|
|
37
47
|
['unterminated comment in a partial response', 'web', '<!-- navigation starts here <meta property=og:title content=not-a-title>'],
|
|
38
48
|
['incomplete quoted metadata', 'web', '<meta property=og:title content="Not complete'],
|
|
39
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>'],
|
|
40
61
|
]
|
|
41
62
|
for (const [page, kind, html] of unavailable) test(page, () => assert.equal(extractPageTitle(html, kind), ''))
|
|
42
63
|
|
|
@@ -46,6 +67,40 @@ test('ignore decoys without losing later genuine metadata in a minified document
|
|
|
46
67
|
assert.equal(extractPageTitle(html, 'web'), 'Actual title')
|
|
47
68
|
})
|
|
48
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
|
+
|
|
49
104
|
test('WeChat status-like strings in a script do not invalidate an article', () => {
|
|
50
105
|
const html = `<script>var warning = '该内容已被发布者删除';</script><title>河道笔记</title>`
|
|
51
106
|
assert.equal(extractPageTitle(html, 'wechat'), '河道笔记')
|
package/title.js
CHANGED
|
@@ -150,7 +150,7 @@ function* pageParts(html) {
|
|
|
150
150
|
/** Extract only static page metadata (or the WeChat article heading) from a fetched HTML prefix. */
|
|
151
151
|
export function extractPageTitle(html, kind) {
|
|
152
152
|
if (typeof html !== 'string' || !['github', 'wechat', 'web'].includes(kind)) return ''
|
|
153
|
-
let og = '', document = '', article = '', heading = null
|
|
153
|
+
let og = '', document = '', twitter = '', article = '', heading = null
|
|
154
154
|
for (const part of pageParts(html.slice(0, MAX_HTML))) {
|
|
155
155
|
if (typeof part === 'string') {
|
|
156
156
|
if (heading) heading.chunks.push(part)
|
|
@@ -164,10 +164,14 @@ export function extractPageTitle(html, kind) {
|
|
|
164
164
|
const result = label(part.title, kind)
|
|
165
165
|
if (result.gate) return '' // don't trust stale OG metadata on a sign-in/error page
|
|
166
166
|
document ||= result.text
|
|
167
|
-
} else if (!closing && name === 'meta'
|
|
168
|
-
const
|
|
169
|
-
if (
|
|
170
|
-
|
|
167
|
+
} else if (!closing && name === 'meta') {
|
|
168
|
+
const keys = [attrs.property, attrs.name].map(value => value?.trim().toLowerCase())
|
|
169
|
+
if (keys.includes('og:title') || keys.includes('twitter:title')) {
|
|
170
|
+
const result = label(attrs.content ?? '', kind)
|
|
171
|
+
if (result.gate) return '' // a gate in any recognized title invalidates stale metadata
|
|
172
|
+
if (keys.includes('og:title')) og ||= result.text
|
|
173
|
+
if (keys.includes('twitter:title')) twitter ||= result.text
|
|
174
|
+
}
|
|
171
175
|
} else if (!closing && name === 'form' && attrs.id === 'challenge-form') return ''
|
|
172
176
|
else if (name === 'h1' || (kind === 'wechat' && name === 'h2')) {
|
|
173
177
|
if (!closing) heading = { name, article: kind === 'wechat' && attrs.id?.trim() === 'activity-name', chunks: [] }
|
|
@@ -179,5 +183,8 @@ export function extractPageTitle(html, kind) {
|
|
|
179
183
|
}
|
|
180
184
|
} else if (heading && name === 'br' && !closing) heading.chunks.push(' ')
|
|
181
185
|
}
|
|
182
|
-
|
|
186
|
+
// Unmarked headings can be hidden, navigation or login content. This metadata
|
|
187
|
+
// scanner cannot establish visibility or page intent, so only WeChat's explicit
|
|
188
|
+
// article marker is trusted as a heading source.
|
|
189
|
+
return article || og || document || twitter
|
|
183
190
|
}
|