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/index.js ADDED
@@ -0,0 +1,214 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { constants as fsConstants } from 'node:fs'
3
+ import { access } from 'node:fs/promises'
4
+ import { promisify } from 'node:util'
5
+ import { parseLink } from './link-policy.js'
6
+ import { createPublicBudget, isPublicPageUrl, readPublicHtml, readPublicJson } from './public-fetch.js'
7
+ import { parseNpmPage, extractNpmTitle } from './npm-adapter.js'
8
+ import { extractPageTitle } from './title.js'
9
+
10
+ const ROUTE = '/feishu-link-preview'
11
+ const CACHE_TTL_MS = 10 * 60 * 1000
12
+ const FAILURE_TTL_MS = 60 * 1000
13
+ const MAX_CACHE_ENTRIES = 200
14
+ const INSPECT_TIMEOUT_MS = 8000
15
+ const NPM_TIMEOUT_MS = 8000 // one deadline across registry lookup and optional HTML fallback
16
+ const MAX_INFLIGHT = 8
17
+ const MAX_TITLE = 200
18
+ const CLI_CANDIDATES = [
19
+ process.env.LARK_CLI_PATH,
20
+ '/opt/homebrew/bin/lark-cli',
21
+ '/usr/local/bin/lark-cli',
22
+ ].filter((candidate) => typeof candidate === 'string' && candidate.length > 0)
23
+
24
+ const execFileAsync = promisify(execFile)
25
+ let cliPathPromise
26
+
27
+ export const inject = ['webServer', 'connection']
28
+ const isDoc = kind => kind === 'docx' || kind === 'wiki'
29
+
30
+ // Validate every public redirect before connecting. Never upgrade an anonymous lookup into a
31
+ // credentialed Feishu call or follow GitHub/WeChat into a login/verification flow.
32
+ function allowedHop(originalKind, url) {
33
+ const hop = parseLink(url.href)
34
+ if (!hop || isDoc(hop.kind) || !isPublicPageUrl(url)) return false
35
+ if (originalKind !== 'web' && originalKind !== hop.kind) return false
36
+ return hop.lookup === url.href.split('#')[0]
37
+ }
38
+
39
+ // All sources, including lark-cli titles, are untrusted labels. Do not decode HTML
40
+ // entities here: a document's title is already plain text rather than HTML markup.
41
+ function safeLabel(value) {
42
+ if (typeof value !== 'string') return ''
43
+ const text = value.replace(/[\u0000-\u0008\u000e-\u001f\u007f-\u009f\p{Bidi_Control}\p{Cs}\u00ad\u200b\u2060-\u206f\ufffc]/gu, '')
44
+ .replace(/\s+/gu, ' ').trim()
45
+ if (text.length <= MAX_TITLE) return text
46
+ return text.slice(0, MAX_TITLE - 1).replace(/[\ud800-\udbff]$/, '').trimEnd() + '…'
47
+ }
48
+
49
+ function sendJson(res, statusCode, body) {
50
+ const payload = JSON.stringify(body)
51
+ res.statusCode = statusCode
52
+ res.setHeader('content-type', 'application/json; charset=utf-8')
53
+ res.setHeader('cache-control', 'no-store')
54
+ res.setHeader('content-length', String(Buffer.byteLength(payload)))
55
+ res.end(payload)
56
+ }
57
+
58
+ function sendEmpty(res, statusCode) {
59
+ res.statusCode = statusCode
60
+ res.setHeader('cache-control', 'no-store')
61
+ res.end()
62
+ }
63
+
64
+ async function resolveCliPath() {
65
+ cliPathPromise ??= (async () => {
66
+ for (const candidate of CLI_CANDIDATES) {
67
+ try {
68
+ await access(candidate, fsConstants.X_OK)
69
+ return candidate
70
+ } catch {
71
+ // Try the next candidate.
72
+ }
73
+ }
74
+ return 'lark-cli'
75
+ })()
76
+ return cliPathPromise
77
+ }
78
+
79
+ function parseLooseJson(text) {
80
+ if (typeof text !== 'string') return null
81
+ for (let index = text.indexOf('{'); index !== -1; index = text.indexOf('{', index + 1)) {
82
+ try {
83
+ const value = JSON.parse(text.slice(index))
84
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) return value
85
+ } catch {
86
+ // Progress text before the JSON payload: keep scanning.
87
+ }
88
+ }
89
+ return null
90
+ }
91
+
92
+ async function inspectFeishu(url) {
93
+ const cli = await resolveCliPath()
94
+ let stdout = ''
95
+ try {
96
+ const result = await execFileAsync(cli, ['drive', '+inspect', '--url', url, '--as', 'user', '--format', 'json'], {
97
+ timeout: INSPECT_TIMEOUT_MS,
98
+ maxBuffer: 2 * 1024 * 1024,
99
+ env: process.env,
100
+ })
101
+ stdout = result.stdout
102
+ } catch (error) {
103
+ // A non-zero exit can still carry a JSON error body on stdout.
104
+ stdout = typeof error?.stdout === 'string' ? error.stdout : ''
105
+ if (stdout.trim() === '') throw error
106
+ }
107
+
108
+ const parsed = parseLooseJson(stdout)
109
+ if (parsed === null) throw new Error('lark-cli did not return JSON')
110
+ if (parsed.ok !== true) {
111
+ const message = parsed?.error?.message ?? parsed?.error?.type ?? 'lark-cli refused the request'
112
+ throw new Error(String(message))
113
+ }
114
+
115
+ const data = parsed.data ?? {}
116
+ const title = typeof data.title === 'string' ? data.title.trim() : ''
117
+ if (!title) throw new Error('document title unavailable')
118
+ return title
119
+ }
120
+
121
+ // Per plugin activation, title-only in-memory cache. The public branch gets no lark-cli identity,
122
+ // browser state, DSH request headers or fallback that renders/executes the target page.
123
+ export function createMetadataLookup({
124
+ inspectDocument = inspectFeishu, readHtml = readPublicHtml, readJson = readPublicJson, publicDnsFallback = false,
125
+ } = {}) {
126
+ const cache = new Map(), inflight = new Map()
127
+ return async target => {
128
+ const key = target.lookup
129
+ const cached = cache.get(key)
130
+ if (cached?.expiresAt > Date.now()) return cached.value
131
+ if (inflight.has(key)) return inflight.get(key)
132
+ if (inflight.size >= MAX_INFLIGHT) return { ok: false, error: 'busy' }
133
+ const job = Promise.resolve().then(async () => {
134
+ if (isDoc(target.kind)) return inspectDocument(key)
135
+ const allowUrl = url => allowedHop(target.kind, url)
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 })
155
+ return extractPageTitle(page.html, parseLink(String(page.url))?.kind ?? target.kind)
156
+ }).then(title => {
157
+ const label = safeLabel(title)
158
+ if (!label) throw Error('no usable title')
159
+ return { ok: true, kind: target.kind, title: label }
160
+ }).catch(() => ({ ok: false, error: 'unavailable' })).then(value => {
161
+ cache.delete(key)
162
+ cache.set(key, { value, expiresAt: Date.now() + (value.ok ? CACHE_TTL_MS : FAILURE_TTL_MS) })
163
+ if (cache.size > MAX_CACHE_ENTRIES) cache.delete(cache.keys().next().value)
164
+ return value
165
+ }).finally(() => inflight.delete(key))
166
+ inflight.set(key, job)
167
+ return job
168
+ }
169
+ }
170
+
171
+ export function createHandler(ctx, metadataFor = createMetadataLookup()) {
172
+ return async (req, res) => {
173
+ try {
174
+ const admission = ctx.connection.admit(req)
175
+ if ('rejection' in admission) return sendEmpty(res, admission.rejection)
176
+ if (admission.peer.principal.kind !== 'owner' || req.headers?.['sec-fetch-site'] === 'cross-site') return sendEmpty(res, 403)
177
+ } catch { return sendEmpty(res, 403) }
178
+
179
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
180
+ res.setHeader('allow', 'GET, HEAD')
181
+ sendJson(res, 405, { ok: false, error: 'method-not-allowed' })
182
+ return
183
+ }
184
+
185
+ let requested
186
+ try {
187
+ requested = new URL(String(req.url), 'http://dsh.internal').searchParams.get('url')
188
+ } catch {
189
+ requested = null
190
+ }
191
+ const target = parseLink(requested)
192
+ if (!target || (!isDoc(target.kind) && !isPublicPageUrl(new URL(target.lookup)))) {
193
+ sendJson(res, 400, { ok: false, error: 'invalid-url' })
194
+ return
195
+ }
196
+ if (req.method === 'HEAD') return sendEmpty(res, 200)
197
+ sendJson(res, 200, await metadataFor(target))
198
+ }
199
+ }
200
+
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 })
205
+ ctx.effect(
206
+ () =>
207
+ ctx.webServer.register({
208
+ kind: 'exact',
209
+ path: ROUTE,
210
+ handler: createHandler(ctx, metadataFor),
211
+ }),
212
+ 'feishu-link-preview: document metadata route',
213
+ )
214
+ }
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 and npm 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
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "行内链接预览",
4
+ "description": "在聊天输入框单独粘贴一条链接,读到标题后在原位显示文档图标和标题;复制、发送仍是网址。支持飞书文档与知识库(需已登录 lark-cli)、公开 GitHub 页面、npm 包页面、微信公众号文章和普通网页。公开页面在粘贴时匿名访问,失败或遇验证时保留网址。"
5
+ }
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,6 +1,69 @@
1
1
  {
2
2
  "name": "dsh-inline-link-preview",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
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
+ "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", "npm", "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
+ "npm-adapter.js",
40
+ "title.js",
41
+ "public-fetch.js",
42
+ "composer.js",
43
+ "build-client.js",
44
+ "client.js",
45
+ "test/*.test.js",
46
+ "cordis.patch.yml",
47
+ "locale/*.json",
48
+ "icon.svg",
49
+ "assets/*.png",
50
+ "README.md",
51
+ "LICENSE"
52
+ ],
53
+ "dsh": {
54
+ "bundle": {
55
+ "patch": "./cordis.patch.yml"
56
+ },
57
+ "client": {
58
+ "platform": "web",
59
+ "immediately": true,
60
+ "inject": [
61
+ "@deepseek-ai/dsh-client-ui-slots",
62
+ "@deepseek-ai/dsh-api-session-controller",
63
+ "@deepseek-ai/dsh-client-ui-conversation",
64
+ "@deepseek-ai/dsh-client-ui-input-trigger",
65
+ "@deepseek-ai/dsh-client-locale"
66
+ ]
67
+ }
68
+ }
69
+ }