@aiti-ai/aiti-msg-share 0.1.0 → 0.1.10
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 +33 -0
- package/client/src/index.js +474 -24
- package/dist/aiti-msg-share-client.mjs +679 -25
- package/index.ts +190 -28
- package/lib/provider-icons.mjs +63 -0
- package/lib/share-core.mjs +28 -0
- package/package.json +3 -3
- package/test/provider-icons.test.mjs +47 -0
- package/test/share-core.test.mjs +25 -0
package/index.ts
CHANGED
|
@@ -7,25 +7,36 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { join, dirname } from "node:path";
|
|
9
9
|
// @ts-ignore pure JS core shared with tests
|
|
10
|
-
import { ShareStore, makeRedactor, publicTarget, exportSessionMarkdown } from "./lib/share-core.mjs";
|
|
10
|
+
import { ShareStore, makeRedactor, publicTarget, exportSessionMarkdown, classifyFile, MAX_SHARE_FILE_BYTES } from "./lib/share-core.mjs";
|
|
11
|
+
// @ts-ignore pure JS icon rules shared with tests
|
|
12
|
+
import { resolveProviderIcon } from "./lib/provider-icons.mjs";
|
|
11
13
|
|
|
12
14
|
let configDir = "";
|
|
13
15
|
let stateDir = "";
|
|
16
|
+
let cacheDir = "";
|
|
14
17
|
let store;
|
|
15
18
|
let registry = null;
|
|
16
19
|
let redact = (t) => ({ text: t, hits: [] });
|
|
17
20
|
let secretEngineReady = false;
|
|
18
21
|
|
|
22
|
+
/** Published audit catalog (dead markings + bilingual notes); overridable for tests/dev. */
|
|
23
|
+
const CATALOG_URL = process.env.AITI_SHARE_TARGETS_URL || "https://aiti.pw/share-targets.json";
|
|
24
|
+
|
|
19
25
|
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {
|
|
20
26
|
status,
|
|
21
27
|
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
|
|
22
28
|
});
|
|
23
29
|
|
|
24
|
-
async function ensureRuntime() {
|
|
25
|
-
if (registry) return registry;
|
|
30
|
+
async function ensureRuntime(force = false) {
|
|
31
|
+
if (registry && !force) return registry;
|
|
26
32
|
const cs = await import("@aiti-ai/content-share");
|
|
27
|
-
registry = new cs.Registry(
|
|
28
|
-
|
|
33
|
+
registry = new cs.Registry({
|
|
34
|
+
// Remote overlay: dead markings, bilingual notes and labels from the
|
|
35
|
+
// published audit doc; falls back to the bundled catalog when unreachable.
|
|
36
|
+
url: CATALOG_URL,
|
|
37
|
+
cacheDir: cacheDir || undefined,
|
|
38
|
+
});
|
|
39
|
+
await registry.init(force);
|
|
29
40
|
const { customProvider } = cs;
|
|
30
41
|
registry.register(customProvider());
|
|
31
42
|
// Re-register user-imported .sxcu configs (persisted on the target record) —
|
|
@@ -57,6 +68,7 @@ async function ensureSecretEngine() {
|
|
|
57
68
|
/** Derive a target's setup state for the UI: anonymous / ready / needs-setup. */
|
|
58
69
|
function configState(entry: any, userTarget: any, reg: any): string {
|
|
59
70
|
if (entry.status === "dead") return "dead";
|
|
71
|
+
if (entry.status === "legacy") return "legacy";
|
|
60
72
|
const provider = reg.get(entry.id) || reg.get(userTarget?.provider);
|
|
61
73
|
const required = (provider?.metaFields || []).filter((f: any) => f.required);
|
|
62
74
|
// A user-created target with all required fields filled → ready.
|
|
@@ -89,12 +101,14 @@ function allTargets(reg) {
|
|
|
89
101
|
return { ...t, custom: true, auth: entry?.auth ?? (t.provider === "custom" ? "key" : "none"),
|
|
90
102
|
kinds: entry?.kinds ?? ["text"], category: entry?.category ?? "publish",
|
|
91
103
|
fields: targetFields(t.provider, reg),
|
|
104
|
+
...containerInfo(reg, t.provider),
|
|
92
105
|
configState: configState(entry || { id: t.provider }, t, reg) };
|
|
93
106
|
}),
|
|
94
107
|
...entries.filter((e) => !userByProvider.has(e.id)).map((e) => ({ id: e.id, name: e.name, provider: e.id,
|
|
95
108
|
kinds: e.kinds, category: e.category, auth: e.auth, recommended: e.recommended, note: e.note,
|
|
96
109
|
status: e.status, source: e.source, values: {},
|
|
97
110
|
fields: targetFields(e.id, reg),
|
|
111
|
+
...containerInfo(reg, e.id),
|
|
98
112
|
configState: configState(e, null, reg) })),
|
|
99
113
|
];
|
|
100
114
|
}
|
|
@@ -106,6 +120,16 @@ function findTarget(reg, id) {
|
|
|
106
120
|
return entry ? { id: entry.id, provider: entry.id, values: {}, name: entry.name, kinds: entry.kinds, category: entry.category } : null;
|
|
107
121
|
}
|
|
108
122
|
|
|
123
|
+
/** Provider UI metadata surfaced to the client: container picker visibility/label
|
|
124
|
+
* and the picker glyph. The catalog has no icon metadata, so the glyph comes from
|
|
125
|
+
* curated keyword rules (lib/provider-icons.mjs); null lets the client fall back
|
|
126
|
+
* to its category/status glyph. */
|
|
127
|
+
function containerInfo(reg: any, providerId: string) {
|
|
128
|
+
const p = reg.get(providerId);
|
|
129
|
+
const c = p?.containers;
|
|
130
|
+
return { supportsContainers: !!c, containerLabel: c?.label || null, icon: resolveProviderIcon(providerId, p) };
|
|
131
|
+
}
|
|
132
|
+
|
|
109
133
|
export default {
|
|
110
134
|
id: "aiti-msg-share",
|
|
111
135
|
name: "消息分享",
|
|
@@ -126,6 +150,9 @@ export default {
|
|
|
126
150
|
i18n: {
|
|
127
151
|
"en": {
|
|
128
152
|
"share.err.forbidden": "That path is outside the allowed roots — only session workspaces can be shared.",
|
|
153
|
+
"share.err.kind": "This target doesn't accept {kind} content ({detail}). Pick a target that supports it.",
|
|
154
|
+
"share.noCompatible": "No targets support {kind} — add one via \"Add more\".",
|
|
155
|
+
"share.notCompatible": "Doesn't accept {kind}",
|
|
129
156
|
"share.err.endpoint": "「{name}」的 API 端点无响应或不支持该操作({detail})。该服务的 API 可能已变更,请在「管理目标」检查端点配置。",
|
|
130
157
|
"share.err.network": "Cannot reach 「{name}」 (network unreachable / blocked / service down). Pick another target in Manage targets, or use local-link.",
|
|
131
158
|
"share.err.timeout": "「{name}」 timed out.",
|
|
@@ -158,6 +185,12 @@ export default {
|
|
|
158
185
|
"share.openInNewTab": "Open in new tab",
|
|
159
186
|
"ext.displayName": "Message Share",
|
|
160
187
|
"share.subtitle": "{kind} · {chars} chars",
|
|
188
|
+
"share.sinks": "Save to",
|
|
189
|
+
"share.sink.copy": "Copy",
|
|
190
|
+
"share.sink.copied": "Copied to clipboard",
|
|
191
|
+
"share.sink.saved": "Saved",
|
|
192
|
+
"share.sink.unsupported": "This content cannot be saved here",
|
|
193
|
+
"share.sink.empty": "Nothing to save — the dialog only carries the page-info header (edit the content or share a message/selection)",
|
|
161
194
|
"share.targets": "Share targets",
|
|
162
195
|
"share.more": "Add more…",
|
|
163
196
|
"share.copy": "Copy link",
|
|
@@ -199,9 +232,21 @@ export default {
|
|
|
199
232
|
"share.cfg.ready": "Configured",
|
|
200
233
|
"share.cfg.needs": "Needs setup",
|
|
201
234
|
"share.cfg.dead": "Unavailable",
|
|
235
|
+
"share.cfg.legacy": "Outdated — upload path broken",
|
|
236
|
+
"share.container.label": "Notebook",
|
|
237
|
+
"share.container.default": "Service default",
|
|
238
|
+
"share.container.refresh": "Refresh containers",
|
|
239
|
+
"share.container.search": "Search notebooks…",
|
|
240
|
+
"share.container.empty": "No containers found",
|
|
241
|
+
"share.container.fail": "Could not list containers: {detail}",
|
|
242
|
+
"share.container.missing": "Last selection no longer exists — using default",
|
|
243
|
+
"share.container.matches": "{n} matches",
|
|
202
244
|
},
|
|
203
245
|
"zh-CN": {
|
|
204
246
|
"share.err.forbidden": "该路径不在允许范围内——只能分享会话工作区内的文件。",
|
|
247
|
+
"share.err.kind": "该目标不支持{kind}内容({detail})。请换一个支持该类型的目标。",
|
|
248
|
+
"share.noCompatible": "没有支持{kind}的目标——可在「加更多…」里添加。",
|
|
249
|
+
"share.notCompatible": "不接受{kind}",
|
|
205
250
|
"share.err.endpoint": "「{name}」的 API 端点无效或已变更({detail})。请在「管理目标」检查端点配置。",
|
|
206
251
|
"share.err.network": "无法连接「{name}」的服务端(网络不可达 / 被拦截 / 服务宕机)。可在「管理目标」换一个服务,或用 local-link。",
|
|
207
252
|
"share.err.timeout": "「{name}」响应超时。",
|
|
@@ -234,6 +279,12 @@ export default {
|
|
|
234
279
|
"share.openInNewTab": "在新窗口打开",
|
|
235
280
|
"ext.displayName": "消息分享",
|
|
236
281
|
"share.subtitle": "{kind} · {chars} 字符",
|
|
282
|
+
"share.sinks": "收藏",
|
|
283
|
+
"share.sink.copy": "复制",
|
|
284
|
+
"share.sink.copied": "已复制到剪贴板",
|
|
285
|
+
"share.sink.saved": "已保存",
|
|
286
|
+
"share.sink.unsupported": "该内容不能收藏到这里",
|
|
287
|
+
"share.sink.empty": "没有可收藏的正文——当前只有页信息头(可先编辑正文,或改分享消息/选区)",
|
|
237
288
|
"share.targets": "分享目标",
|
|
238
289
|
"share.more": "加更多…",
|
|
239
290
|
"share.copy": "复制链接",
|
|
@@ -275,9 +326,22 @@ export default {
|
|
|
275
326
|
"share.cfg.ready": "已配置",
|
|
276
327
|
"share.cfg.needs": "需配置",
|
|
277
328
|
"share.cfg.dead": "不可用",
|
|
329
|
+
"share.cfg.legacy": "已過時(上傳通道異常)",
|
|
330
|
+
"share.cfg.legacy": "已过时(上传通道异常)",
|
|
331
|
+
"share.container.label": "笔记本",
|
|
332
|
+
"share.container.default": "默认位置",
|
|
333
|
+
"share.container.refresh": "刷新容器列表",
|
|
334
|
+
"share.container.search": "搜索笔记本…",
|
|
335
|
+
"share.container.empty": "未找到容器",
|
|
336
|
+
"share.container.fail": "容器列表获取失败:{detail}",
|
|
337
|
+
"share.container.missing": "上次选择的容器已不存在,使用默认位置",
|
|
338
|
+
"share.container.matches": "{n} 条匹配",
|
|
278
339
|
},
|
|
279
340
|
"zh-TW": {
|
|
280
341
|
"share.err.forbidden": "該路徑不在允許範圍內——只能分享工作階段工作區內的檔案。",
|
|
342
|
+
"share.err.kind": "該目標不支援{kind}內容({detail})。請換一個支援該類型的目標。",
|
|
343
|
+
"share.noCompatible": "沒有支援{kind}的目標——可在「加更多…」裡添加。",
|
|
344
|
+
"share.notCompatible": "不接受{kind}",
|
|
281
345
|
"share.err.endpoint": "「{name}」的 API 端點無效或已變更({detail})。請在「管理目標」檢查端點設定。",
|
|
282
346
|
"share.err.network": "無法連線「{name}」的伺服端(網路不可達 / 被封鎖 / 服務當機)。可在「管理目標」換一個服務,或用 local-link。",
|
|
283
347
|
"share.err.timeout": "「{name}」回應逾時。",
|
|
@@ -310,6 +374,12 @@ export default {
|
|
|
310
374
|
"share.openInNewTab": "在新視窗開啟",
|
|
311
375
|
"ext.displayName": "訊息分享",
|
|
312
376
|
"share.subtitle": "{kind} · {chars} 字元",
|
|
377
|
+
"share.sinks": "收藏",
|
|
378
|
+
"share.sink.copy": "複製",
|
|
379
|
+
"share.sink.copied": "已複製到剪貼簿",
|
|
380
|
+
"share.sink.saved": "已儲存",
|
|
381
|
+
"share.sink.unsupported": "此內容無法收藏到這裡",
|
|
382
|
+
"share.sink.empty": "沒有可收藏的正文——目前只有頁資訊標頭(可先編輯正文,或改分享訊息/選取區)",
|
|
313
383
|
"share.targets": "分享目標",
|
|
314
384
|
"share.more": "加更多…",
|
|
315
385
|
"share.copy": "複製連結",
|
|
@@ -348,9 +418,17 @@ export default {
|
|
|
348
418
|
"share.deleteTarget": "刪除目標",
|
|
349
419
|
"share.notSet": "(未設定)",
|
|
350
420
|
"share.cfg.anonymous": "匿名可用",
|
|
351
|
-
"share.cfg.ready": "
|
|
352
|
-
"share.cfg.needs": "
|
|
421
|
+
"share.cfg.ready": "已配置",
|
|
422
|
+
"share.cfg.needs": "需配置",
|
|
353
423
|
"share.cfg.dead": "不可用",
|
|
424
|
+
"share.container.label": "筆記本",
|
|
425
|
+
"share.container.default": "預設位置",
|
|
426
|
+
"share.container.refresh": "重新整理容器列表",
|
|
427
|
+
"share.container.search": "搜尋筆記本…",
|
|
428
|
+
"share.container.empty": "未找到容器",
|
|
429
|
+
"share.container.fail": "容器列表取得失敗:{detail}",
|
|
430
|
+
"share.container.missing": "上次選擇的容器已不存在,使用預設位置",
|
|
431
|
+
"share.container.matches": "{n} 筆匹配",
|
|
354
432
|
},
|
|
355
433
|
},
|
|
356
434
|
dialogs: [{ id: "aiti-msg-share-dialog", label: "aiti-msg-share" }],
|
|
@@ -367,23 +445,30 @@ export default {
|
|
|
367
445
|
if (!configDir) {
|
|
368
446
|
configDir = ctx.configDir || "";
|
|
369
447
|
stateDir = ctx.stateDir || join(dirname(configDir), "state", "aiti-msg-share");
|
|
448
|
+
cacheDir = ctx.cacheDir || join(dirname(configDir), "cache", "aiti-msg-share");
|
|
370
449
|
store = new ShareStore(configDir, stateDir);
|
|
371
450
|
}
|
|
372
451
|
const reg = await ensureRuntime();
|
|
373
452
|
await ensureSecretEngine();
|
|
374
453
|
|
|
454
|
+
// POST /refresh — force-reload the remote catalog overlay (bypasses TTL).
|
|
455
|
+
if (p[0] === "refresh" && req.method === "POST") {
|
|
456
|
+
const fresh = await ensureRuntime(true);
|
|
457
|
+
return json({ ok: true, count: fresh.catalog().length });
|
|
458
|
+
}
|
|
459
|
+
|
|
375
460
|
// GET /catalog — all targets + metadata
|
|
376
461
|
if (p[0] === "catalog" && req.method === "GET") {
|
|
377
462
|
return json({ ok: true, targets: allTargets(reg), count: reg.catalog().length });
|
|
378
463
|
}
|
|
379
464
|
|
|
380
|
-
// GET /targets — persisted user targets
|
|
381
|
-
if (p[0] === "targets" && req.method === "GET") {
|
|
465
|
+
// GET /targets — persisted user targets (!p[1]: sub-resources have own handlers)
|
|
466
|
+
if (p[0] === "targets" && !p[1] && req.method === "GET") {
|
|
382
467
|
return json({ ok: true, targets: store.readTargets().map((t) => publicTarget(t, reg.get(t.provider))) });
|
|
383
468
|
}
|
|
384
469
|
|
|
385
470
|
// POST /targets — upsert a target (secrets stored raw, 0600; masked in responses)
|
|
386
|
-
if (p[0] === "targets" && req.method === "POST") {
|
|
471
|
+
if (p[0] === "targets" && !p[1] && req.method === "POST") {
|
|
387
472
|
const body = await req.json();
|
|
388
473
|
if (!body?.id || !body?.provider) return json({ ok: false, error: "id and provider required", errorCode: "badRequest" }, 400);
|
|
389
474
|
const saved = store.upsertTarget({ id: body.id, provider: body.provider, name: body.name || body.id,
|
|
@@ -407,6 +492,49 @@ export default {
|
|
|
407
492
|
return json(await provider.probe({ provider: body.provider, values: body.values || {} }));
|
|
408
493
|
}
|
|
409
494
|
|
|
495
|
+
// POST /containers — list selectable containers (Joplin notebooks, Obsidian dirs, …).
|
|
496
|
+
// Saved target: credentials come from the stored values; setup form: ad-hoc values.
|
|
497
|
+
// Credentials never leave the server — only {id,label,parent,path} are returned.
|
|
498
|
+
if (p[0] === "containers" && req.method === "POST") {
|
|
499
|
+
const body = await req.json().catch(() => null);
|
|
500
|
+
let providerId: string = body?.provider || "";
|
|
501
|
+
let values: Record<string, string> = body?.values || {};
|
|
502
|
+
if (body?.targetId) {
|
|
503
|
+
const t = findTarget(reg, body.targetId);
|
|
504
|
+
if (!t) return json({ ok: false, error: "unknown target", errorCode: "unknownTarget" }, 404);
|
|
505
|
+
providerId = t.provider;
|
|
506
|
+
values = t.values || {};
|
|
507
|
+
}
|
|
508
|
+
const provider = providerId ? reg.get(providerId) : null;
|
|
509
|
+
if (!provider?.containers) return json({ ok: true, supportsContainers: false, containers: [] });
|
|
510
|
+
try {
|
|
511
|
+
const containers = await provider.containers.list({ provider: providerId, values, container: "" },
|
|
512
|
+
typeof body?.parent === "string" ? body.parent : undefined);
|
|
513
|
+
return json({ ok: true, supportsContainers: true, containerLabel: provider.containers.label || null, containers });
|
|
514
|
+
} catch (err: any) {
|
|
515
|
+
return json({ ok: false, errorCode: "containerFail", error: String(err?.message || err),
|
|
516
|
+
detail: String(err?.message || err) }, 502);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// POST /targets/last-container — record the user's container pick on the target.
|
|
521
|
+
// Persisted in targets.json (0600): survives restarts and browsers; AI/headless
|
|
522
|
+
// shares fall back to it when the request carries no explicit container.
|
|
523
|
+
// recentContainers keeps a small quick-pick history (most recent distinct first).
|
|
524
|
+
if (p[0] === "targets" && p[1] === "last-container" && req.method === "POST") {
|
|
525
|
+
const body = await req.json().catch(() => null);
|
|
526
|
+
const t = store.readTargets().find((x) => x.id === body?.id);
|
|
527
|
+
if (!t) return json({ ok: false, error: "unknown target", errorCode: "unknownTarget" }, 404);
|
|
528
|
+
const container = String(body?.container ?? "");
|
|
529
|
+
const label = body?.label ? String(body.label) : (container ? t.lastContainerLabel || "" : "");
|
|
530
|
+
const recents: Array<{ id: string; label: string }> = (Array.isArray(t.recentContainers) ? t.recentContainers : [])
|
|
531
|
+
.filter((r: any) => r && r.id && r.id !== container).slice(0, 2);
|
|
532
|
+
const recentContainers = container ? [{ id: container, label }, ...recents] : recents;
|
|
533
|
+
const saved = store.upsertTarget({ ...t, lastContainer: container, lastContainerLabel: label,
|
|
534
|
+
lastContainerAt: new Date().toISOString(), recentContainers });
|
|
535
|
+
return json({ ok: true, target: publicTarget(saved, reg.get(saved.provider)) });
|
|
536
|
+
}
|
|
537
|
+
|
|
410
538
|
// POST /import-sxcu — register a config at runtime + persist as a target
|
|
411
539
|
if (p[0] === "import-sxcu" && req.method === "POST") {
|
|
412
540
|
const body = await req.json();
|
|
@@ -436,17 +564,29 @@ export default {
|
|
|
436
564
|
const text = body.rawText || exportSessionMarkdown(session, { full: !!body.full, title: meta.title,
|
|
437
565
|
tags: String(meta.tags).split(",").map((s) => s.trim()).filter(Boolean) });
|
|
438
566
|
content = { text };
|
|
439
|
-
} else if (body.imageSrc) {
|
|
440
|
-
//
|
|
441
|
-
//
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
567
|
+
} else if (body.imageBase64 || body.imageSrc) {
|
|
568
|
+
// Preferred path: the browser already loaded the image (same-origin or
|
|
569
|
+
// data: URL) and sends base64 — no server-side fetch, no CORS, works for
|
|
570
|
+
// pasted data: URLs too.
|
|
571
|
+
if (body.imageBase64) {
|
|
572
|
+
const m = /^data:([^;,]+)?(;base64)?,([\s\S]*)$/.exec(String(body.imageBase64));
|
|
573
|
+
const b64 = (m ? m[3] : String(body.imageBase64)).trim();
|
|
574
|
+
if (!b64) return json({ ok: false, errorCode: "badRequest", error: "empty image payload" }, 400);
|
|
575
|
+
const mime = (m?.[1] || body.mime || "image/png").split(";")[0];
|
|
576
|
+
content = { buffer: Buffer.from(b64, "base64"), filename: body.filename || "image.png", mime };
|
|
577
|
+
} else {
|
|
578
|
+
// Fallback: relative /api/... paths resolved against THIS request's
|
|
579
|
+
// origin (the old "http://localhost" base hit port 80 / nginx → 404).
|
|
580
|
+
// Same-origin only: image previews are served by pi-web itself; blocks SSRF.
|
|
581
|
+
const origin = new URL(req.url).origin;
|
|
582
|
+
const url = new URL(String(body.imageSrc), origin);
|
|
583
|
+
const sameOrigin = url.origin === origin || url.hostname === "127.0.0.1" || url.hostname === "localhost";
|
|
584
|
+
if (!sameOrigin) return json({ ok: false, errorCode: "badRequest",
|
|
585
|
+
error: "imageSrc must be a pi-web relative path or same-origin URL", detail: url.host }, 400);
|
|
586
|
+
const r = await fetch(url);
|
|
587
|
+
if (!r.ok) return json({ ok: false, error: `image fetch ${r.status}`, errorCode: "imageFetch", detail: String(r.status) }, 502);
|
|
588
|
+
content = { buffer: Buffer.from(await r.arrayBuffer()), filename: body.filename || "image.png", mime: r.headers.get("content-type") || "image/png" };
|
|
589
|
+
}
|
|
450
590
|
} else if (body.filePath) {
|
|
451
591
|
// Respect pi-web allowed-roots (session cwds): never read arbitrary
|
|
452
592
|
// server files on behalf of the caller.
|
|
@@ -457,13 +597,17 @@ export default {
|
|
|
457
597
|
if (!allowed) return json({ ok: false, errorCode: "forbidden",
|
|
458
598
|
error: "path is outside the allowed roots", detail: body.filePath }, 403);
|
|
459
599
|
}
|
|
460
|
-
const { readFile } = await import("node:fs/promises");
|
|
600
|
+
const { readFile, stat } = await import("node:fs/promises");
|
|
601
|
+
const st = await stat(body.filePath).catch(() => null);
|
|
602
|
+
if (!st?.isFile()) return json({ ok: false, errorCode: "badRequest", error: "file not found", detail: body.filePath }, 400);
|
|
603
|
+
if (st.size > MAX_SHARE_FILE_BYTES) return json({ ok: false, errorCode: "tooLarge",
|
|
604
|
+
error: `file too large: ${st.size} bytes`, detail: String(st.size) }, 413);
|
|
605
|
+
const name = body.filename || body.filePath.split("/").pop() || "file";
|
|
606
|
+
const cls = classifyFile(name);
|
|
461
607
|
const buffer = await readFile(body.filePath);
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
? { buffer, filename: body.filename || body.filePath.split("/").pop(), mime }
|
|
466
|
-
: { text: buffer.toString("utf8"), filename: body.filename || body.filePath.split("/").pop() };
|
|
608
|
+
content = cls.kind === "text"
|
|
609
|
+
? { text: buffer.toString("utf8"), filename: name }
|
|
610
|
+
: { buffer, filename: name, mime: cls.mime };
|
|
467
611
|
} else {
|
|
468
612
|
content = { text: body.text || "" };
|
|
469
613
|
}
|
|
@@ -471,10 +615,22 @@ export default {
|
|
|
471
615
|
const doRedact = body.redact !== false && "text" in content;
|
|
472
616
|
const hooks = doRedact ? { transformText: redact } : undefined;
|
|
473
617
|
const cs = await import("@aiti-ai/content-share");
|
|
618
|
+
// Kind guard (defense in depth — the pipeline checks too): an image buffer
|
|
619
|
+
// to a text-only target would silently produce garbage on the service.
|
|
620
|
+
const contentKind = "text" in content ? "text" : /^image\//i.test(content.mime) ? "image" : "file";
|
|
621
|
+
const kinds = (provider as any).kinds || [];
|
|
622
|
+
if (kinds.length && !kinds.includes(contentKind)) {
|
|
623
|
+
return json({ ok: false, errorCode: "kind", errorTarget: target.id, providerLabel: (provider as any).label,
|
|
624
|
+
error: `kind mismatch: ${contentKind} not in [${kinds.join("/")}]`,
|
|
625
|
+
detail: `${(provider as any).label} accepts: ${kinds.join(", ")}` }, 400);
|
|
626
|
+
}
|
|
474
627
|
let result;
|
|
628
|
+
// Container selection: an explicit request wins ("" = service default);
|
|
629
|
+
// otherwise fall back to the target's recorded last selection (AI/headless path).
|
|
630
|
+
const container = typeof body.container === "string" ? body.container : String(target.lastContainer || "");
|
|
475
631
|
try {
|
|
476
632
|
result = await cs.share(provider, content,
|
|
477
|
-
{ provider: target.provider, values: target.values || {}, tags: meta.tags, pathPrefix: target.pathPrefix },
|
|
633
|
+
{ provider: target.provider, values: target.values || {}, tags: meta.tags, pathPrefix: target.pathPrefix, container },
|
|
478
634
|
meta, hooks);
|
|
479
635
|
} catch (err: any) {
|
|
480
636
|
// Turn a bare "fetch failed" into an actionable message (target + cause + hint).
|
|
@@ -498,6 +654,12 @@ export default {
|
|
|
498
654
|
store.appendHistory({ at: new Date().toISOString(), targetId: target.id, kind,
|
|
499
655
|
title: meta.title, url: result.url, extra: result.extra, hits: result.hits,
|
|
500
656
|
redacted: doRedact, bytes: "text" in content ? Buffer.byteLength(content.text) : content.buffer.byteLength });
|
|
657
|
+
// Refresh the last-selection memory on success (bump timestamp only when the
|
|
658
|
+
// value changed) so headless/AI shares keep landing in the same notebook.
|
|
659
|
+
const stored = store.readTargets().find((t) => t.id === target.id);
|
|
660
|
+
if (stored && String(stored.lastContainer || "") !== container) {
|
|
661
|
+
store.upsertTarget({ ...stored, lastContainer: container, lastContainerAt: new Date().toISOString() });
|
|
662
|
+
}
|
|
501
663
|
return json({ ok: true, ...result });
|
|
502
664
|
}
|
|
503
665
|
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* provider-icons — curated per-target glyphs for the share picker (pure data, no DOM).
|
|
3
|
+
*
|
|
4
|
+
* The content-share catalog carries no icon/favicon metadata (checked against
|
|
5
|
+
* @aiti-ai/content-share 0.1.17: catalog entries have id/name/kinds/category/
|
|
6
|
+
* source/auth/note/status only, and providers have no icon field), so the old
|
|
7
|
+
* `icon: p?.icon` was always null. Rather than fetching third-party favicons
|
|
8
|
+
* (privacy + offline), resolve a stable local glyph:
|
|
9
|
+
*
|
|
10
|
+
* 1. provider.icon when a future catalog version supplies one (string or { emoji })
|
|
11
|
+
* 2. ordered keyword rules over the target id (ids are domain-ish: "imgur.com",
|
|
12
|
+
* "0x0.st (URL shortener)", "aliyun-oss", "gitee-gist", …)
|
|
13
|
+
* 3. null → the client keeps its category/status glyph
|
|
14
|
+
*
|
|
15
|
+
* Order matters: specific families first, generic "shortener"/"file" last.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Curated glyphs keyed by exact target id (the few curated aiti entries). */
|
|
19
|
+
const EXACT = {
|
|
20
|
+
"aliyun-oss": "☁️",
|
|
21
|
+
"gitee-gist": "🟠",
|
|
22
|
+
"local-link": "🔗",
|
|
23
|
+
custom: "⚙️",
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Ordered keyword rules over the lower-cased target id. */
|
|
27
|
+
const RULES = [
|
|
28
|
+
[/(^|[^a-z])github|(^|[^a-z])gist|gitlab|git\.io|gitee|codeberg|sourcehut/, "💻"],
|
|
29
|
+
[/catbox|litterbox/, "🐱"],
|
|
30
|
+
[/shortener|short\.?url|\bshort\b/, "✂️"],
|
|
31
|
+
[/imgur|imgbb|freeimage|gyazo|chevereto|postimag|epvpimg|\bimage\b|\bimg\b|\bpic\b|photo|lsky/, "🖼️"],
|
|
32
|
+
[/paste|haste|dpaste|ghostbin|privatebin|ix\.io|0x0\.st/, "📋"],
|
|
33
|
+
[/\boss\b|s3|storage|qiniu|tencent|upyun|wasabi|minio|backblaze|\bb2\b|\br2\b|bucket/, "☁️"],
|
|
34
|
+
[/joplin|obsidian|notion|evernote/, "📓"],
|
|
35
|
+
[/telegram|discord|slack|feishu|lark|flomo|\bim\b/, "💬"],
|
|
36
|
+
[/\bmail|smtp|email/, "✉️"],
|
|
37
|
+
[/ipfs|ipns/, "🌐"],
|
|
38
|
+
[/local-link/, "🔗"],
|
|
39
|
+
[/webhook|httpreq|httpbin/, "🔗"],
|
|
40
|
+
[/\bfile\b|gofile|transfer|dropfile|filebin|tmpfiles|uguu|fuwa|fuck\.it|catbox/, "📦"],
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the glyph for one target.
|
|
45
|
+
* @param {string} providerId target id from the catalog
|
|
46
|
+
* @param {{ icon?: unknown } | null | undefined} provider registry provider (future metadata)
|
|
47
|
+
* @returns {string | null} glyph, or null so the client falls back
|
|
48
|
+
*/
|
|
49
|
+
export function resolveProviderIcon(providerId, provider) {
|
|
50
|
+
const fromProvider = provider?.icon;
|
|
51
|
+
if (typeof fromProvider === "string" && fromProvider.trim()) return fromProvider.trim();
|
|
52
|
+
if (fromProvider && typeof fromProvider === "object" && typeof fromProvider.emoji === "string") {
|
|
53
|
+
return fromProvider.emoji.trim() || null;
|
|
54
|
+
}
|
|
55
|
+
const id = String(providerId || "").trim();
|
|
56
|
+
if (!id) return null;
|
|
57
|
+
if (EXACT[id]) return EXACT[id];
|
|
58
|
+
const lower = id.toLowerCase();
|
|
59
|
+
for (const [pattern, glyph] of RULES) {
|
|
60
|
+
if (pattern.test(lower)) return glyph;
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
package/lib/share-core.mjs
CHANGED
|
@@ -10,6 +10,34 @@ import { join, dirname } from "node:path";
|
|
|
10
10
|
|
|
11
11
|
const HISTORY_MAX = 200;
|
|
12
12
|
|
|
13
|
+
/** Files above this size are rejected before reading (provider limits are checked later). */
|
|
14
|
+
export const MAX_SHARE_FILE_BYTES = 200 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
const IMAGE_MIME = {
|
|
17
|
+
png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif",
|
|
18
|
+
webp: "image/webp", bmp: "image/bmp", svg: "image/svg+xml", ico: "image/x-icon", avif: "image/avif",
|
|
19
|
+
};
|
|
20
|
+
const TEXT_EXT = new Set([
|
|
21
|
+
"txt", "md", "markdown", "json", "js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "rb", "go", "rs", "java",
|
|
22
|
+
"c", "h", "cpp", "hpp", "cs", "php", "sh", "bash", "zsh", "yml", "yaml", "toml", "ini", "cfg", "conf",
|
|
23
|
+
"csv", "tsv", "log", "html", "htm", "css", "scss", "xml", "sql", "env", "properties", "gradle", "vim",
|
|
24
|
+
"dockerfile", "makefile", "gitignore", "license",
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Classify a shared file: image (binary, image/* mime), text (decoded as utf8),
|
|
29
|
+
* or binary (byte-exact buffer, application/octet-stream). Mirrors the client's
|
|
30
|
+
* kind filter so both ends agree on what the content is.
|
|
31
|
+
*/
|
|
32
|
+
export function classifyFile(filename) {
|
|
33
|
+
const ext = String(filename || "").split(".").pop()?.toLowerCase() || "";
|
|
34
|
+
if (IMAGE_MIME[ext]) return { kind: "image", mime: IMAGE_MIME[ext] };
|
|
35
|
+
if (TEXT_EXT.has(ext)) return { kind: "text", mime: "text/plain" };
|
|
36
|
+
// Executables/scripts without extension sometimes carry a shebang — still treat
|
|
37
|
+
// unknown types as binary: byte-exact upload never corrupts, utf8 decode can.
|
|
38
|
+
return { kind: "binary", mime: "application/octet-stream" };
|
|
39
|
+
}
|
|
40
|
+
|
|
13
41
|
/** Mask a secret for display: keep first 2 / last 4 chars only. */
|
|
14
42
|
export function maskSecret(value) {
|
|
15
43
|
if (!value || typeof value !== "string") return "";
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiti-ai/aiti-msg-share",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Share sessions, messages, selections, files and images through pluggable targets with secret redaction and QR codes",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"aitiExtProtocol": "1.0",
|
|
8
8
|
"soul": "分享出去,是为了让对话继续。",
|
|
9
9
|
"dependencies": {
|
|
10
|
-
"@aiti-ai/content-share": "^0.1.
|
|
10
|
+
"@aiti-ai/content-share": "^0.1.16",
|
|
11
11
|
"@aiti-ai/secret-mask-core": "^0.1.0",
|
|
12
12
|
"qrcode": "^1.5.4"
|
|
13
13
|
},
|
|
@@ -27,5 +27,5 @@
|
|
|
27
27
|
"bugs": {
|
|
28
28
|
"url": "https://github.com/aiti-ai/aiti-ai/issues"
|
|
29
29
|
},
|
|
30
|
-
"contentHash": "
|
|
30
|
+
"contentHash": "fdc082bfb2d6a3cf"
|
|
31
31
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* provider-icons — curated glyph rules for the share picker (pure, no DOM).
|
|
3
|
+
* Run: node --test extensions/aiti-msg-share/test/provider-icons.test.mjs
|
|
4
|
+
*/
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import assert from "node:assert/strict";
|
|
7
|
+
import { resolveProviderIcon } from "../lib/provider-icons.mjs";
|
|
8
|
+
|
|
9
|
+
test("exact curated ids win", () => {
|
|
10
|
+
assert.equal(resolveProviderIcon("aliyun-oss"), "☁️");
|
|
11
|
+
assert.equal(resolveProviderIcon("gitee-gist"), "🟠");
|
|
12
|
+
assert.equal(resolveProviderIcon("local-link"), "🔗");
|
|
13
|
+
assert.equal(resolveProviderIcon("custom"), "⚙️");
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test("domain-shaped catalog ids map to families", () => {
|
|
17
|
+
assert.equal(resolveProviderIcon("imgur.com"), "🖼️");
|
|
18
|
+
assert.equal(resolveProviderIcon("imgbb.com"), "🖼️");
|
|
19
|
+
assert.equal(resolveProviderIcon("catbox.moe"), "🐱");
|
|
20
|
+
assert.equal(resolveProviderIcon("paste.rs"), "📋");
|
|
21
|
+
assert.equal(resolveProviderIcon("ix.io"), "📋");
|
|
22
|
+
assert.equal(resolveProviderIcon("Discord post"), "💬");
|
|
23
|
+
assert.equal(resolveProviderIcon("joplin"), "📓");
|
|
24
|
+
assert.equal(resolveProviderIcon("ipfs.io"), "🌐");
|
|
25
|
+
assert.equal(resolveProviderIcon("file.io"), "📦");
|
|
26
|
+
assert.equal(resolveProviderIcon("github-gist"), "💻");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("multi-variant ids resolve by their variant, not the base host", () => {
|
|
30
|
+
assert.equal(resolveProviderIcon("0x0.st (URL shortener)"), "✂️");
|
|
31
|
+
assert.equal(resolveProviderIcon("0x0.st (Image uploader)"), "🖼️");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("unknown ids return null so the client keeps its category glyph", () => {
|
|
35
|
+
assert.equal(resolveProviderIcon("example"), null);
|
|
36
|
+
assert.equal(resolveProviderIcon(""), null);
|
|
37
|
+
assert.equal(resolveProviderIcon(undefined), null);
|
|
38
|
+
assert.equal(resolveProviderIcon(null), null);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("future provider metadata wins; invalid metadata falls through", () => {
|
|
42
|
+
assert.equal(resolveProviderIcon("imgur.com", { icon: "🔒" }), "🔒");
|
|
43
|
+
assert.equal(resolveProviderIcon("imgur.com", { icon: { emoji: "🅰️" } }), "🅰️");
|
|
44
|
+
assert.equal(resolveProviderIcon("imgur.com", { icon: {} }), "🖼️");
|
|
45
|
+
assert.equal(resolveProviderIcon("imgur.com", { icon: 42 }), "🖼️");
|
|
46
|
+
assert.equal(resolveProviderIcon("unknown-id", { icon: " " }), null);
|
|
47
|
+
});
|
package/test/share-core.test.mjs
CHANGED
|
@@ -48,3 +48,28 @@ test("exportSessionMarkdown: role headers + folded tool output", () => {
|
|
|
48
48
|
assert.ok(md.includes("## User\n\nhello"));
|
|
49
49
|
assert.ok(md.includes("folded"));
|
|
50
50
|
});
|
|
51
|
+
|
|
52
|
+
test("classifyFile: image / text / binary by extension", async () => {
|
|
53
|
+
const { classifyFile } = await import("../lib/share-core.mjs");
|
|
54
|
+
assert.deepEqual(classifyFile("shot.png"), { kind: "image", mime: "image/png" });
|
|
55
|
+
assert.deepEqual(classifyFile("photo.JPG"), { kind: "image", mime: "image/jpeg" });
|
|
56
|
+
assert.deepEqual(classifyFile("notes.md"), { kind: "text", mime: "text/plain" });
|
|
57
|
+
assert.deepEqual(classifyFile("data.json"), { kind: "text", mime: "text/plain" });
|
|
58
|
+
assert.deepEqual(classifyFile("report.pdf"), { kind: "binary", mime: "application/octet-stream" });
|
|
59
|
+
assert.deepEqual(classifyFile("archive.tar.gz"), { kind: "binary", mime: "application/octet-stream" });
|
|
60
|
+
assert.deepEqual(classifyFile("noext"), { kind: "binary", mime: "application/octet-stream" });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("ShareStore persists container last-selection fields", () => {
|
|
64
|
+
const dir = mkdtempSync(join(tmpdir(), "share-store-"));
|
|
65
|
+
const store = new ShareStore(join(dir, "config"), join(dir, "state"));
|
|
66
|
+
store.upsertTarget({ id: "joplin", provider: "joplin", values: { token: "t" } });
|
|
67
|
+
const t = store.readTargets()[0];
|
|
68
|
+
store.upsertTarget({ ...t, lastContainer: "nb1", lastContainerLabel: "My Notebook / Work", lastContainerAt: "2026-11-20T00:00:00.000Z" });
|
|
69
|
+
const back = store.readTargets()[0];
|
|
70
|
+
assert.equal(back.lastContainer, "nb1");
|
|
71
|
+
assert.equal(back.lastContainerLabel, "My Notebook / Work");
|
|
72
|
+
// Clearing the selection keeps the label empty too.
|
|
73
|
+
store.upsertTarget({ ...back, lastContainer: "", lastContainerLabel: "" });
|
|
74
|
+
assert.equal(store.readTargets()[0].lastContainer, "");
|
|
75
|
+
});
|