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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-inline-link-preview contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # 行内链接预览
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在 **DeepSeek Harness 的聊天输入框**粘贴一条网址,它会在原位变成「文档图标 + 页面标题」。不用输入 `@`,也不用先发消息。点击标题打开链接;复制或发送时用的仍是网址,不是标题或网页正文。
4
+
5
+ **看个例子:** 输入 `请看 再写摘要`,把光标放在两个空格之间,单独粘贴 `https://example.com/`。页面可访问时,先显示的网址会变成 **请看 [▤ Example Domain] 再写摘要**(方括号是示意)。把整句复制到纯文本编辑器,得到的仍是 `请看 https://example.com/ 再写摘要`。
6
+
7
+ ## 哪些链接可以预览?
8
+
9
+ | 粘贴的链接 | 条件 |
10
+ | --- | --- |
11
+ | 飞书 / Lark 文档、知识库 | `feishu.cn`、`larksuite.com`、`larkoffice.com` 及其子域的 HTTPS `/docx/…`、`/wiki/…`。运行 Harness 的主机需装有已登录的 `lark-cli`,且该账号有文档权限。 |
12
+ | GitHub 公开页面 | 仓库、Issue、PR 等公开页面;不需要 GitHub Token,不读取私有仓库的登录态。 |
13
+ | 微信公众号文章 | `mp.weixin.qq.com/s/…` 或 `/s?__biz=…&mid=…` 等文章分享地址。遇到微信验证或文章已删除时,保留网址。 |
14
+ | 普通公开网页 | 使用域名的 HTTP(S) 页面,服务器返回的 HTML 中须有可用标题。只用公开网页时,不需要 `lark-cli`。 |
15
+
16
+ ## 安装和试用 Beta
17
+
18
+ 包名 `dsh-inline-link-preview`,版本 `0.5.0-beta.1`。本次兼容范围为 **DSH `>=0.2.2-rc.5 <0.2.3-0`**,开发和打包使用 Node.js 22。若正使用本地旧包 `@local/dsh-feishu-link-preview`,请先备份未发的草稿,再停用旧包,**不要同时启用两个版本**。
19
+
20
+ - **拿到预发布压缩包时:** 可先在独立 DSH profile 试装。在压缩包所在目录运行:
21
+
22
+ ```sh
23
+ dsh plugin --profile link-preview-beta add "$PWD/dsh-inline-link-preview-0.5.0-beta.1.tgz"
24
+ ```
25
+
26
+ - **此版本发布到 npm 后:** 可在目标 profile 安装精确版本。例如桌面版:
27
+
28
+ ```sh
29
+ dsh plugin --profile desktop add dsh-inline-link-preview@0.5.0-beta.1
30
+ ```
31
+
32
+ 打开对应 profile,确认插件「行内链接预览」已启用,刷新窗口(macOS:`⌘R`)。试试上面的 `Example Domain` 例子,等标题出现前先不要移动光标。插件市场是否能搜到,取决于该 profile 启用的索引是否已收录这个版本。
33
+
34
+ ## 为什么有时还是网址?
35
+
36
+ - 只处理**一次粘贴一条**链接。含说明的整段文字、多条链接或文件按原样粘贴;不扫描旧草稿或改写已发送消息。
37
+ - 标题返回前若继续打字、改变选区、发送或切换会话,插件不会用迟到的结果覆盖草稿。需要重试时,选中那段网址,重新粘贴同一条链接。
38
+ - 遇登录页、验证码、超时、非 HTML 或仅靠 JavaScript 才出现标题的页面,可能读不到。此时网址照常可发。飞书可先检查 `lark-cli` 的登录和文档权限,等待约一分钟再试。
39
+
40
+ ## 粘贴时会访问哪里?
41
+
42
+ **访问发生在粘贴时,不是发送时。** 公开网页由运行 Harness 的主机直接请求目标站点。站点能看到主机的网络地址、请求路径及查询参数;插件不发送浏览器 Cookie 或 Referer,不使用第三方预览服务,也不执行目标页面的脚本。本机 / 内网地址、直接写 IP 的地址、非标准端口,以及含已知凭证或操作特征的链接不会作为普通网页自动访问。请勿把该功能当成通用敏感链接清洗器。
43
+
44
+ 飞书标题通过 `lark-cli drive +inspect --as user` 获取,查询时只传文档路径;微信查询只传文章标识。两者的可识别临时登录参数会从可复制、可发送的引用中移除。标题查询只向编辑器返回标题,不附上正文;主机在内存中缓存结果(成功 10 分钟、失败 1 分钟)。
45
+
46
+ 编辑器向本机 Harness 服务查询标题时,目标地址会出现在请求的查询参数中;如果启用了 Web 服务或反向代理访问日志,这些日志**可能记录该地址和文档标识**。请按需配置日志保留与访问权限,避免预览不希望出现在日志里的链接。
47
+
48
+ ## 开发与许可
49
+
50
+ ```sh
51
+ npm run build
52
+ npm test
53
+ ```
54
+
55
+ 无需安装第三方 npm 依赖。构建会从[粘贴逻辑](./composer.js)和[链接识别规则](./link-policy.js)生成客户端入口;测试会检查入口与源码一致,并离线验证标题提取、粘贴行为和网络请求边界。
56
+
57
+ [MIT 许可证](./LICENSE) · 非 DeepSeek、飞书、GitHub 或微信的官方插件。
@@ -0,0 +1,13 @@
1
+ // DSH's loader consumes a standalone browser script. Bundle the two self-contained source
2
+ // functions deterministically at build time, without runtime module imports or a CDN.
3
+ import { readFile, writeFile } from 'node:fs/promises'
4
+ const here = name => new URL(name, import.meta.url)
5
+ const policy = await readFile(here('link-policy.js'), 'utf8')
6
+ const ui = await readFile(here('composer.js'), 'utf8')
7
+ const { name } = JSON.parse(await readFile(here('package.json'), 'utf8'))
8
+ const bundle = `// Generated by npm run build; edit link-policy.js or composer.js instead.\n;(() => {\n${policy.replace('export function parseLink(', 'function parseLink(')}\n${ui.replace('export function composer(', 'function composer(')}\nwindow.__ModuleLoader__.load({ id: ${JSON.stringify(name)}, factory(require) { return composer(require, parseLink) } })\n})()\n`
9
+ if (process.argv.includes('--check')) {
10
+ if (await readFile(here('client.js'), 'utf8') !== bundle) throw Error('client.js is stale; run npm run build')
11
+ } else {
12
+ await writeFile(here('client.js'), bundle)
13
+ }
package/client.js ADDED
@@ -0,0 +1,208 @@
1
+ // Generated by npm run build; edit link-policy.js or composer.js instead.
2
+ ;(() => {
3
+ // Pure policy shared by the Host and the dependency-free browser bundle (see build-client.js).
4
+ // lookup: safe metadata address; ref: the text copied/sent/opened. Never replace ref with a redirect.
5
+ function parseLink(text) {
6
+ if (typeof text !== 'string' || text.length > 16384) return null
7
+ const raw = text.trim()
8
+ if (!/^https?:\/\//i.test(raw) || /[\s\\<>\u0000-\u001f\u007f\ufffc]/u.test(raw)) return null
9
+ let url
10
+ try { url = new URL(raw) } catch { return null }
11
+ if (url.username || url.password || url.port) return null
12
+ const host = url.hostname
13
+ if (!/^(?:[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?\.)+[a-z][a-z\d-]*$/i.test(host) ||
14
+ /\.(?:local|localhost|internal|intranet|lan|home|corp|test|example|invalid|onion|alt|arpa)$/i.test(host)) return null
15
+
16
+ const feishu = /(?:^|\.)(?:feishu\.cn|larksuite\.com|larkoffice\.com)$/i.test(host)
17
+ const wechat = host === 'mp.weixin.qq.com'
18
+ const feishuSecret = /^(?:disposable_login_token|(?:user_|tenant_|app_)?access_token|refresh_token|id_token)$/i
19
+ 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
20
+ const wxSecret = /^(?:pass_ticket|appmsg_token|wxtoken|key|uin|exportkey|wx_header)$/i
21
+
22
+ // Preserve escaping/order of unaffected fields, including ordinary paragraph anchors.
23
+ const strip = fields => fields.split('&').filter(field => {
24
+ let key
25
+ try { key = decodeURIComponent(field.split('=', 1)[0]) } catch { return true }
26
+ return feishu ? !feishuSecret.test(key) : !wxSecret.test(key) && !webSecret.test(key)
27
+ }).join('&')
28
+ function cleanShareRef() {
29
+ const query = url.search.slice(1), clean = strip(query)
30
+ if (clean !== query) url.search = clean
31
+ const hash = url.hash.slice(1), split = hash.indexOf('?')
32
+ const fields = strip(hash.slice(split + 1))
33
+ const cleanHash = split < 0 ? fields : strip(hash.slice(0, split)) + (fields ? '?' + fields : '')
34
+ if (cleanHash !== hash) url.hash = cleanHash
35
+ return url.href
36
+ }
37
+ if (feishu) {
38
+ const doc = /^\/(docx|wiki)\/[A-Za-z0-9_-]{8,128}\/?$/.exec(url.pathname)
39
+ if (url.protocol !== 'https:' || !doc) return null // never send another Feishu resource to the web reader
40
+ return { kind: doc[1], lookup: url.origin + url.pathname.replace(/\/$/, ''), ref: cleanShareRef() }
41
+ }
42
+ if (wechat) {
43
+ // Copied article links often carry temporary WeChat parameters. Only article identity goes on the wire.
44
+ const lookup = new URL('https://mp.weixin.qq.com' + url.pathname)
45
+ if (/^\/s\/?$/.test(url.pathname)) {
46
+ if (!url.searchParams.get('__biz') || !(url.searchParams.get('mid') || url.searchParams.get('appmsgid'))) return null
47
+ for (const key of ['__biz', 'mid', 'appmsgid', 'idx', 'sn']) {
48
+ const value = url.searchParams.get(key)
49
+ if (value) lookup.searchParams.set(key, value)
50
+ }
51
+ } else if (!/^\/s\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) return null
52
+ return { kind: 'wechat', lookup: lookup.href, ref: cleanShareRef() }
53
+ }
54
+
55
+ // Never automatically visit known credential/action URLs. Leave their normal paste untouched.
56
+ if (Array.from(url.searchParams.keys()).some(key => webSecret.test(key) || feishuSecret.test(key))) return null
57
+ if (/(?:^|[?&#])(?:access_token|id_token|refresh_token|token|code|api[_-]?key)=/i.test(url.hash)) return null
58
+ let path
59
+ try { path = decodeURIComponent(url.pathname) } catch { return null }
60
+ 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
61
+ url.hash = '' // fragments are for the user's navigation only
62
+ return { kind: /^(?:www\.)?github\.com$/i.test(host) ? 'github' : 'web', lookup: url.href, ref: raw }
63
+ }
64
+
65
+ // Installed as a plain DSH module-loader factory by build-client.js. No editor-private imports.
66
+ function composer(require, parseLink) {
67
+ const SOURCE = 'feishu-link-preview' // stable across upgrades for restored drafts
68
+ const SLOT = 'conversation.input.overlay'
69
+ const NS = 'feishuLinkPreview'
70
+ const CAPTURE = { capture: true }
71
+
72
+ async function readTitle(url, signal) {
73
+ const response = await fetch(`/feishu-link-preview?url=${encodeURIComponent(url)}`, {
74
+ credentials: 'same-origin', headers: { accept: 'application/json' },
75
+ cache: 'no-store', signal: AbortSignal.any([signal, AbortSignal.timeout(10000)]),
76
+ })
77
+ if (!response.ok) return ''
78
+ const body = await response.json()
79
+ return body?.ok === true && typeof body.title === 'string' ? body.title.trim().replace(/\s+/gu, ' ') : ''
80
+ }
81
+
82
+ // null leaves an ordinary paste to DSH. Otherwise the fallback URL is inserted synchronously.
83
+ function pasteLink(text, api, signal) {
84
+ const link = parseLink(text)
85
+ if (!link || signal.aborted || !api.current()) return null
86
+ const before = api.actions.captureInsertion()
87
+ const leading = text.slice(0, text.length - text.trimStart().length), trailing = text.slice(text.trimEnd().length)
88
+ if (!api.actions.insertText(leading + link.ref + trailing, before)) return null
89
+ const after = api.actions.captureInsertion()
90
+ // Use editor offsets (a previous chip/quote counts as one), not indexOf in the expanded draft.
91
+ const start = before.start + leading.length, end = start + link.ref.length, pasteEnd = end + trailing.length
92
+ if (after.start !== pasteEnd || after.end !== pasteEnd) return Promise.resolve(false)
93
+ const span = { start, end, draftRev: after.draftRev }
94
+ return (async () => {
95
+ let title = ''
96
+ try { title = await api.readTitle(link.lookup, signal) } catch { /* Keep the usable link. */ }
97
+ if (signal.aborted || !api.current()) return false
98
+ const caret = api.actions.captureInsertion()
99
+ if (caret.draftRev !== span.draftRev || caret.start !== pasteEnd || caret.end !== pasteEnd) return false
100
+ if (!title) { api.unavailable(link.kind); return false }
101
+ const inserted = api.session.bail(api.session, 'slash/input-insert-reference', { span, reference: {
102
+ source: SOURCE, appearance: 'file', ref: link.ref, clipboardText: link.ref, label: title,
103
+ } }) === true
104
+ if (inserted && trailing) {
105
+ // The native chip leaves the caret before any pasted suffix and may add one ASCII space.
106
+ // Touch only our own separator/whitespace in this synchronous turn, never the text after it.
107
+ const chipEnd = start + 1, addedSpace = trailing[0] !== ' ', pos = api.actions.captureInsertion()
108
+ if (pos.draftRev === span.draftRev + 1 && pos.start === chipEnd + Number(addedSpace) && pos.end === pos.start) {
109
+ const finish = pos.end + trailing.length
110
+ api.actions.insertText(addedSpace ? trailing : '', {
111
+ start: addedSpace ? chipEnd : finish, end: finish, draftRev: pos.draftRev,
112
+ })
113
+ }
114
+ }
115
+ return inserted
116
+ })()
117
+ }
118
+
119
+ function watchInterruptions(card, view, cancel) {
120
+ const interrupt = event => {
121
+ // Actual editing is caught by beforeinput/IME and the draft revision. Navigation is
122
+ // checked against the captured selection; pressing Right at the end or Cmd+C is harmless.
123
+ if (event.type === 'keydown' && !['Enter', 'Escape', 'Tab'].includes(event.key)) return
124
+ cancel()
125
+ }
126
+ const events = ['focusout', 'beforeinput', 'compositionstart', 'pointerdown', 'keydown']
127
+ for (const type of events) card.addEventListener(type, interrupt, CAPTURE)
128
+ view?.addEventListener('blur', cancel)
129
+ return () => {
130
+ for (const type of events) card.removeEventListener(type, interrupt, CAPTURE)
131
+ view?.removeEventListener('blur', cancel)
132
+ }
133
+ }
134
+
135
+ const source = {
136
+ trigger: '@', name: SOURCE, showGroupTitle: false,
137
+ candidates: async () => [], onPick: () => undefined,
138
+ codec: { clipboardText: ref => ref, serialize: async ref => ref },
139
+ openReference(_session, { ref }) {
140
+ const link = parseLink(ref)
141
+ if (!link) return false
142
+ window.open(link.ref, '_blank', 'noopener,noreferrer')
143
+ return true
144
+ },
145
+ }
146
+
147
+ function apply(ctx) {
148
+ const React = require('react')
149
+ const sessions = ctx.get('sessions')
150
+ ctx.effect(() => ctx.locale.register(NS, {
151
+ zh: {
152
+ document: '未读到飞书标题,已保留网址。请确认登录和文档权限,约一分钟后可重新粘贴。',
153
+ publicPage: '未能读取公开标题,已保留网址,可照常发送。',
154
+ },
155
+ en: {
156
+ document: 'Title unavailable; the URL is unchanged. Check your lark-cli sign-in and document access, then paste again in a minute.',
157
+ publicPage: 'No public title was available. The URL is still here and can be sent as usual.',
158
+ },
159
+ }), 'link-preview: paste feedback')
160
+ const t = ctx.locale.bind(NS)
161
+ ctx.effect(() => ctx.get('inputTriggers').registerSource(source), 'link-preview: native reference codec')
162
+
163
+ function PasteScope({ sessionId, inputActions }) {
164
+ const marker = React.useRef(null)
165
+ React.useEffect(() => {
166
+ const binding = sessions.binding(sessionId)
167
+ const card = marker.current?.closest('[data-composer-card]')
168
+ if (!binding || !card || !inputActions) return
169
+ const input = ctx.get('conversation').input.for(binding.ctx)
170
+ let pending
171
+ const cancel = () => { pending?.abort(); pending = undefined }
172
+ function paste(event) {
173
+ cancel()
174
+ const editor = event.target?.closest?.('[data-composer-input][contenteditable="true"]')
175
+ const data = event.clipboardData
176
+ if (!editor || editor.closest('[data-composer-card]') !== card || !event.cancelable || event.defaultPrevented || !data || data.files.length) return
177
+ const controller = new AbortController()
178
+ const current = () => editor.isConnected && editor.isContentEditable &&
179
+ editor.contains(editor.ownerDocument.activeElement) && sessions.binding(sessionId) === binding &&
180
+ input.state.getSnapshot().phase === 'plain'
181
+ const result = pasteLink(data.getData('text/plain'), {
182
+ session: binding.ctx, actions: inputActions, current, readTitle,
183
+ unavailable: kind => input.notify('error', t(kind === 'docx' || kind === 'wiki' ? 'document' : 'publicPage')),
184
+ }, controller.signal)
185
+ if (result === null) return
186
+ event.preventDefault()
187
+ event.stopPropagation()
188
+ pending = controller
189
+ result.finally(() => { if (pending === controller) pending = undefined }).catch(() => {})
190
+ }
191
+ // No public paste hook in 0.2.2: scope to this composer, never edit or style its DOM.
192
+ card.addEventListener('paste', paste, CAPTURE)
193
+ const stopWatching = watchInterruptions(card, card.ownerDocument.defaultView, cancel)
194
+ return () => {
195
+ cancel()
196
+ stopWatching()
197
+ card.removeEventListener('paste', paste, CAPTURE)
198
+ }
199
+ }, [sessionId, inputActions])
200
+ return React.createElement('span', { ref: marker, hidden: true, 'aria-hidden': true })
201
+ }
202
+ ctx.slots.inject(SLOT, () => ctx.slots.register({ name: SLOT, id: SOURCE, order: 10 }, PasteScope))
203
+ }
204
+ return { inject: ['slots', 'sessions', 'conversation', 'inputTriggers', 'locale'], apply, parseLink, pasteLink, watchInterruptions }
205
+ }
206
+
207
+ window.__ModuleLoader__.load({ id: "dsh-inline-link-preview", factory(require) { return composer(require, parseLink) } })
208
+ })()
package/composer.js ADDED
@@ -0,0 +1,141 @@
1
+ // Installed as a plain DSH module-loader factory by build-client.js. No editor-private imports.
2
+ export function composer(require, parseLink) {
3
+ const SOURCE = 'feishu-link-preview' // stable across upgrades for restored drafts
4
+ const SLOT = 'conversation.input.overlay'
5
+ const NS = 'feishuLinkPreview'
6
+ const CAPTURE = { capture: true }
7
+
8
+ async function readTitle(url, signal) {
9
+ const response = await fetch(`/feishu-link-preview?url=${encodeURIComponent(url)}`, {
10
+ credentials: 'same-origin', headers: { accept: 'application/json' },
11
+ cache: 'no-store', signal: AbortSignal.any([signal, AbortSignal.timeout(10000)]),
12
+ })
13
+ if (!response.ok) return ''
14
+ const body = await response.json()
15
+ return body?.ok === true && typeof body.title === 'string' ? body.title.trim().replace(/\s+/gu, ' ') : ''
16
+ }
17
+
18
+ // null leaves an ordinary paste to DSH. Otherwise the fallback URL is inserted synchronously.
19
+ function pasteLink(text, api, signal) {
20
+ const link = parseLink(text)
21
+ if (!link || signal.aborted || !api.current()) return null
22
+ const before = api.actions.captureInsertion()
23
+ const leading = text.slice(0, text.length - text.trimStart().length), trailing = text.slice(text.trimEnd().length)
24
+ if (!api.actions.insertText(leading + link.ref + trailing, before)) return null
25
+ const after = api.actions.captureInsertion()
26
+ // Use editor offsets (a previous chip/quote counts as one), not indexOf in the expanded draft.
27
+ const start = before.start + leading.length, end = start + link.ref.length, pasteEnd = end + trailing.length
28
+ if (after.start !== pasteEnd || after.end !== pasteEnd) return Promise.resolve(false)
29
+ const span = { start, end, draftRev: after.draftRev }
30
+ return (async () => {
31
+ let title = ''
32
+ try { title = await api.readTitle(link.lookup, signal) } catch { /* Keep the usable link. */ }
33
+ if (signal.aborted || !api.current()) return false
34
+ const caret = api.actions.captureInsertion()
35
+ if (caret.draftRev !== span.draftRev || caret.start !== pasteEnd || caret.end !== pasteEnd) return false
36
+ if (!title) { api.unavailable(link.kind); return false }
37
+ const inserted = api.session.bail(api.session, 'slash/input-insert-reference', { span, reference: {
38
+ source: SOURCE, appearance: 'file', ref: link.ref, clipboardText: link.ref, label: title,
39
+ } }) === true
40
+ if (inserted && trailing) {
41
+ // The native chip leaves the caret before any pasted suffix and may add one ASCII space.
42
+ // Touch only our own separator/whitespace in this synchronous turn, never the text after it.
43
+ const chipEnd = start + 1, addedSpace = trailing[0] !== ' ', pos = api.actions.captureInsertion()
44
+ if (pos.draftRev === span.draftRev + 1 && pos.start === chipEnd + Number(addedSpace) && pos.end === pos.start) {
45
+ const finish = pos.end + trailing.length
46
+ api.actions.insertText(addedSpace ? trailing : '', {
47
+ start: addedSpace ? chipEnd : finish, end: finish, draftRev: pos.draftRev,
48
+ })
49
+ }
50
+ }
51
+ return inserted
52
+ })()
53
+ }
54
+
55
+ function watchInterruptions(card, view, cancel) {
56
+ const interrupt = event => {
57
+ // Actual editing is caught by beforeinput/IME and the draft revision. Navigation is
58
+ // checked against the captured selection; pressing Right at the end or Cmd+C is harmless.
59
+ if (event.type === 'keydown' && !['Enter', 'Escape', 'Tab'].includes(event.key)) return
60
+ cancel()
61
+ }
62
+ const events = ['focusout', 'beforeinput', 'compositionstart', 'pointerdown', 'keydown']
63
+ for (const type of events) card.addEventListener(type, interrupt, CAPTURE)
64
+ view?.addEventListener('blur', cancel)
65
+ return () => {
66
+ for (const type of events) card.removeEventListener(type, interrupt, CAPTURE)
67
+ view?.removeEventListener('blur', cancel)
68
+ }
69
+ }
70
+
71
+ const source = {
72
+ trigger: '@', name: SOURCE, showGroupTitle: false,
73
+ candidates: async () => [], onPick: () => undefined,
74
+ codec: { clipboardText: ref => ref, serialize: async ref => ref },
75
+ openReference(_session, { ref }) {
76
+ const link = parseLink(ref)
77
+ if (!link) return false
78
+ window.open(link.ref, '_blank', 'noopener,noreferrer')
79
+ return true
80
+ },
81
+ }
82
+
83
+ function apply(ctx) {
84
+ const React = require('react')
85
+ const sessions = ctx.get('sessions')
86
+ ctx.effect(() => ctx.locale.register(NS, {
87
+ zh: {
88
+ document: '未读到飞书标题,已保留网址。请确认登录和文档权限,约一分钟后可重新粘贴。',
89
+ publicPage: '未能读取公开标题,已保留网址,可照常发送。',
90
+ },
91
+ en: {
92
+ document: 'Title unavailable; the URL is unchanged. Check your lark-cli sign-in and document access, then paste again in a minute.',
93
+ publicPage: 'No public title was available. The URL is still here and can be sent as usual.',
94
+ },
95
+ }), 'link-preview: paste feedback')
96
+ const t = ctx.locale.bind(NS)
97
+ ctx.effect(() => ctx.get('inputTriggers').registerSource(source), 'link-preview: native reference codec')
98
+
99
+ function PasteScope({ sessionId, inputActions }) {
100
+ const marker = React.useRef(null)
101
+ React.useEffect(() => {
102
+ const binding = sessions.binding(sessionId)
103
+ const card = marker.current?.closest('[data-composer-card]')
104
+ if (!binding || !card || !inputActions) return
105
+ const input = ctx.get('conversation').input.for(binding.ctx)
106
+ let pending
107
+ const cancel = () => { pending?.abort(); pending = undefined }
108
+ function paste(event) {
109
+ cancel()
110
+ const editor = event.target?.closest?.('[data-composer-input][contenteditable="true"]')
111
+ const data = event.clipboardData
112
+ if (!editor || editor.closest('[data-composer-card]') !== card || !event.cancelable || event.defaultPrevented || !data || data.files.length) return
113
+ const controller = new AbortController()
114
+ const current = () => editor.isConnected && editor.isContentEditable &&
115
+ editor.contains(editor.ownerDocument.activeElement) && sessions.binding(sessionId) === binding &&
116
+ input.state.getSnapshot().phase === 'plain'
117
+ const result = pasteLink(data.getData('text/plain'), {
118
+ session: binding.ctx, actions: inputActions, current, readTitle,
119
+ unavailable: kind => input.notify('error', t(kind === 'docx' || kind === 'wiki' ? 'document' : 'publicPage')),
120
+ }, controller.signal)
121
+ if (result === null) return
122
+ event.preventDefault()
123
+ event.stopPropagation()
124
+ pending = controller
125
+ result.finally(() => { if (pending === controller) pending = undefined }).catch(() => {})
126
+ }
127
+ // No public paste hook in 0.2.2: scope to this composer, never edit or style its DOM.
128
+ card.addEventListener('paste', paste, CAPTURE)
129
+ const stopWatching = watchInterruptions(card, card.ownerDocument.defaultView, cancel)
130
+ return () => {
131
+ cancel()
132
+ stopWatching()
133
+ card.removeEventListener('paste', paste, CAPTURE)
134
+ }
135
+ }, [sessionId, inputActions])
136
+ return React.createElement('span', { ref: marker, hidden: true, 'aria-hidden': true })
137
+ }
138
+ ctx.slots.inject(SLOT, () => ctx.slots.register({ name: SLOT, id: SOURCE, order: 10 }, PasteScope))
139
+ }
140
+ return { inject: ['slots', 'sessions', 'conversation', 'inputTriggers', 'locale'], apply, parseLink, pasteLink, watchInterruptions }
141
+ }
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: inline-link-preview
3
+ name: dsh-inline-link-preview
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="Inline link preview">
2
+ <rect width="64" height="64" rx="14" fill="#3370ff"/>
3
+ <path d="M20 15h16l10 10v24H20z" fill="none" stroke="#ffffff" stroke-width="3" stroke-linejoin="round"/>
4
+ <path d="M36 15v10h10" fill="none" stroke="#ffffff" stroke-width="3" stroke-linejoin="round"/>
5
+ <path d="M26 32h14M26 38h12M26 44h9" fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round"/>
6
+ </svg>
package/index.js ADDED
@@ -0,0 +1,189 @@
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 { isPublicPageUrl, readPublicHtml } from './public-fetch.js'
7
+ import { extractPageTitle } from './title.js'
8
+
9
+ const ROUTE = '/feishu-link-preview'
10
+ const CACHE_TTL_MS = 10 * 60 * 1000
11
+ const FAILURE_TTL_MS = 60 * 1000
12
+ const MAX_CACHE_ENTRIES = 200
13
+ const INSPECT_TIMEOUT_MS = 8000
14
+ const MAX_INFLIGHT = 8
15
+ const MAX_TITLE = 200
16
+ const CLI_CANDIDATES = [
17
+ process.env.LARK_CLI_PATH,
18
+ '/opt/homebrew/bin/lark-cli',
19
+ '/usr/local/bin/lark-cli',
20
+ ].filter((candidate) => typeof candidate === 'string' && candidate.length > 0)
21
+
22
+ const execFileAsync = promisify(execFile)
23
+ let cliPathPromise
24
+
25
+ export const inject = ['webServer', 'connection']
26
+ const isDoc = kind => kind === 'docx' || kind === 'wiki'
27
+
28
+ // Validate every public redirect before connecting. Never upgrade an anonymous lookup into a
29
+ // credentialed Feishu call or follow GitHub/WeChat into a login/verification flow.
30
+ function allowedHop(originalKind, url) {
31
+ const hop = parseLink(url.href)
32
+ if (!hop || isDoc(hop.kind) || !isPublicPageUrl(url)) return false
33
+ if (originalKind !== 'web' && originalKind !== hop.kind) return false
34
+ return hop.lookup === url.href.split('#')[0]
35
+ }
36
+
37
+ // All sources, including lark-cli titles, are untrusted labels. Do not decode HTML
38
+ // entities here: a document's title is already plain text rather than HTML markup.
39
+ function safeLabel(value) {
40
+ if (typeof value !== 'string') return ''
41
+ const text = value.replace(/[\u0000-\u0008\u000e-\u001f\u007f-\u009f\p{Bidi_Control}\p{Cs}\u00ad\u200b\u2060-\u206f\ufffc]/gu, '')
42
+ .replace(/\s+/gu, ' ').trim()
43
+ if (text.length <= MAX_TITLE) return text
44
+ return text.slice(0, MAX_TITLE - 1).replace(/[\ud800-\udbff]$/, '').trimEnd() + '…'
45
+ }
46
+
47
+ function sendJson(res, statusCode, body) {
48
+ const payload = JSON.stringify(body)
49
+ res.statusCode = statusCode
50
+ res.setHeader('content-type', 'application/json; charset=utf-8')
51
+ res.setHeader('cache-control', 'no-store')
52
+ res.setHeader('content-length', String(Buffer.byteLength(payload)))
53
+ res.end(payload)
54
+ }
55
+
56
+ function sendEmpty(res, statusCode) {
57
+ res.statusCode = statusCode
58
+ res.setHeader('cache-control', 'no-store')
59
+ res.end()
60
+ }
61
+
62
+ async function resolveCliPath() {
63
+ cliPathPromise ??= (async () => {
64
+ for (const candidate of CLI_CANDIDATES) {
65
+ try {
66
+ await access(candidate, fsConstants.X_OK)
67
+ return candidate
68
+ } catch {
69
+ // Try the next candidate.
70
+ }
71
+ }
72
+ return 'lark-cli'
73
+ })()
74
+ return cliPathPromise
75
+ }
76
+
77
+ function parseLooseJson(text) {
78
+ if (typeof text !== 'string') return null
79
+ for (let index = text.indexOf('{'); index !== -1; index = text.indexOf('{', index + 1)) {
80
+ try {
81
+ const value = JSON.parse(text.slice(index))
82
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) return value
83
+ } catch {
84
+ // Progress text before the JSON payload: keep scanning.
85
+ }
86
+ }
87
+ return null
88
+ }
89
+
90
+ async function inspectFeishu(url) {
91
+ const cli = await resolveCliPath()
92
+ let stdout = ''
93
+ try {
94
+ const result = await execFileAsync(cli, ['drive', '+inspect', '--url', url, '--as', 'user', '--format', 'json'], {
95
+ timeout: INSPECT_TIMEOUT_MS,
96
+ maxBuffer: 2 * 1024 * 1024,
97
+ env: process.env,
98
+ })
99
+ stdout = result.stdout
100
+ } catch (error) {
101
+ // A non-zero exit can still carry a JSON error body on stdout.
102
+ stdout = typeof error?.stdout === 'string' ? error.stdout : ''
103
+ if (stdout.trim() === '') throw error
104
+ }
105
+
106
+ const parsed = parseLooseJson(stdout)
107
+ if (parsed === null) throw new Error('lark-cli did not return JSON')
108
+ if (parsed.ok !== true) {
109
+ const message = parsed?.error?.message ?? parsed?.error?.type ?? 'lark-cli refused the request'
110
+ throw new Error(String(message))
111
+ }
112
+
113
+ const data = parsed.data ?? {}
114
+ const title = typeof data.title === 'string' ? data.title.trim() : ''
115
+ if (!title) throw new Error('document title unavailable')
116
+ return title
117
+ }
118
+
119
+ // Per plugin activation, title-only in-memory cache. The public branch gets no lark-cli identity,
120
+ // browser state, DSH request headers or fallback that renders/executes the target page.
121
+ export function createMetadataLookup({ inspectDocument = inspectFeishu, readHtml = readPublicHtml } = {}) {
122
+ const cache = new Map(), inflight = new Map()
123
+ return async target => {
124
+ const key = target.lookup
125
+ const cached = cache.get(key)
126
+ if (cached?.expiresAt > Date.now()) return cached.value
127
+ if (inflight.has(key)) return inflight.get(key)
128
+ if (inflight.size >= MAX_INFLIGHT) return { ok: false, error: 'busy' }
129
+ const job = Promise.resolve().then(async () => {
130
+ if (isDoc(target.kind)) return inspectDocument(key)
131
+ const allowUrl = url => allowedHop(target.kind, url)
132
+ const page = await readHtml(key, { allowUrl })
133
+ return extractPageTitle(page.html, parseLink(String(page.url))?.kind ?? target.kind)
134
+ }).then(title => {
135
+ const label = safeLabel(title)
136
+ if (!label) throw Error('no usable title')
137
+ return { ok: true, kind: target.kind, title: label }
138
+ }).catch(() => ({ ok: false, error: 'unavailable' })).then(value => {
139
+ cache.delete(key)
140
+ cache.set(key, { value, expiresAt: Date.now() + (value.ok ? CACHE_TTL_MS : FAILURE_TTL_MS) })
141
+ if (cache.size > MAX_CACHE_ENTRIES) cache.delete(cache.keys().next().value)
142
+ return value
143
+ }).finally(() => inflight.delete(key))
144
+ inflight.set(key, job)
145
+ return job
146
+ }
147
+ }
148
+
149
+ export function createHandler(ctx, metadataFor = createMetadataLookup()) {
150
+ return async (req, res) => {
151
+ try {
152
+ const admission = ctx.connection.admit(req)
153
+ if ('rejection' in admission) return sendEmpty(res, admission.rejection)
154
+ if (admission.peer.principal.kind !== 'owner' || req.headers?.['sec-fetch-site'] === 'cross-site') return sendEmpty(res, 403)
155
+ } catch { return sendEmpty(res, 403) }
156
+
157
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
158
+ res.setHeader('allow', 'GET, HEAD')
159
+ sendJson(res, 405, { ok: false, error: 'method-not-allowed' })
160
+ return
161
+ }
162
+
163
+ let requested
164
+ try {
165
+ requested = new URL(String(req.url), 'http://dsh.internal').searchParams.get('url')
166
+ } catch {
167
+ requested = null
168
+ }
169
+ const target = parseLink(requested)
170
+ if (!target || (!isDoc(target.kind) && !isPublicPageUrl(new URL(target.lookup)))) {
171
+ sendJson(res, 400, { ok: false, error: 'invalid-url' })
172
+ return
173
+ }
174
+ if (req.method === 'HEAD') return sendEmpty(res, 200)
175
+ sendJson(res, 200, await metadataFor(target))
176
+ }
177
+ }
178
+
179
+ export function apply(ctx) {
180
+ ctx.effect(
181
+ () =>
182
+ ctx.webServer.register({
183
+ kind: 'exact',
184
+ path: ROUTE,
185
+ handler: createHandler(ctx),
186
+ }),
187
+ 'feishu-link-preview: document metadata route',
188
+ )
189
+ }