@alexsun-top/opencode-chat-room 0.8.0 → 0.8.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/CHANGELOG.md +29 -0
- package/LICENSE +2 -2
- package/README.md +38 -6
- package/README.zh-CN.md +38 -6
- package/cli.ts +27 -1
- package/dist/cli.js +5074 -3212
- package/package.json +23 -3
- package/packages/chat-room-channeld/README.md +98 -25
- package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
- package/packages/chat-room-channeld/src/adapter.ts +36 -2
- package/packages/chat-room-channeld/src/config.ts +63 -1
- package/packages/chat-room-channeld/src/delivery.ts +6 -1
- package/packages/chat-room-channeld/src/feishu-adapter.ts +122 -292
- package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
- package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
- package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
- package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +120 -2
- package/packages/chat-room-channeld/src/inbound.ts +26 -0
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -1
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +15 -9
- package/server/assets/chat/announcements.js +70 -7
- package/server/assets/chat/doc-preview.js +184 -35
- package/server/assets/chat/events.js +3 -0
- package/server/assets/chat/files.js +46 -4
- package/server/assets/chat/index.js +2 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +498 -0
- package/server/assets/chat/locales/de.js +40 -4
- package/server/assets/chat/locales/es.js +40 -4
- package/server/assets/chat/locales/fr.js +40 -4
- package/server/assets/chat/locales/it.js +40 -4
- package/server/assets/chat/locales/ja.js +40 -4
- package/server/assets/chat/locales/ko.js +40 -4
- package/server/assets/chat/markdown.js +22 -8
- package/server/assets/chat/messages.js +5 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/panels.js +36 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +15 -3
- package/server/assets/chat/reminders.js +69 -8
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/settings.js +30 -2
- package/server/assets/chat/side-pane.js +1 -2
- package/server/assets/chat/state.js +93 -10
- package/server/assets/chat/system-events.js +32 -0
- package/server/assets/chat/system-messages.js +23 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +121 -33
- package/server/assets/code-highlight.css +55 -32
- package/server/assets/conversation.css +123 -23
- package/server/assets/doc-preview.css +35 -3
- package/server/assets/files.css +5 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1297 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +50 -11
- package/server/assets/settings.css +73 -1
- package/server/assets/tasks.css +57 -7
- package/server/channel-integration.ts +519 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +261 -18
- package/server/chat-server.ts +32 -580
- package/server/chat.html +187 -21
- package/server/http-server.ts +3 -182
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +4 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +2 -10
- package/src/config/file-config.ts +7 -54
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/watch.ts +1 -1
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +148 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +121 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +87 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +33 -0
- package/src/state/sqlite-state.ts +15 -897
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +5 -1
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +439 -0
- package/src/web/integration-rules.ts +22 -0
- package/src/web/integration-schema.ts +228 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
// Admin-managed Channel D integration state: uploaded JavaScript adapters and
|
|
2
|
+
// a server-owned YAML config under <stateDir>/integrations. Account commands are
|
|
3
|
+
// never accepted from the API; the server always writes ["node", pluginPath].
|
|
4
|
+
import {
|
|
5
|
+
existsSync,
|
|
6
|
+
mkdirSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
readdirSync,
|
|
9
|
+
rmSync,
|
|
10
|
+
renameSync,
|
|
11
|
+
writeFileSync,
|
|
12
|
+
} from "node:fs";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
|
|
16
|
+
import { AdapterProcess } from "../packages/chat-room-channeld/src/adapter.ts";
|
|
17
|
+
import {
|
|
18
|
+
parseConfig,
|
|
19
|
+
type AccountConfig,
|
|
20
|
+
type ChannelConfig,
|
|
21
|
+
type RuleConfig,
|
|
22
|
+
} from "../packages/chat-room-channeld/src/config.ts";
|
|
23
|
+
import { validateTargets } from "../packages/chat-room-channeld/src/host-helpers.ts";
|
|
24
|
+
import { databasePath } from "../src/state/store.ts";
|
|
25
|
+
import { adminMessage } from "./channel-settings.ts";
|
|
26
|
+
|
|
27
|
+
export interface IntegrationRuntimeView {
|
|
28
|
+
host: {
|
|
29
|
+
accountRuntimeStates: ReadonlyMap<string, { state: string; lastError?: string }>;
|
|
30
|
+
};
|
|
31
|
+
config: ChannelConfig;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface IntegrationControl {
|
|
35
|
+
enabled(): boolean;
|
|
36
|
+
runtime(): IntegrationRuntimeView | undefined;
|
|
37
|
+
activate(configPath: string): Promise<Response>;
|
|
38
|
+
disable(): Promise<Response>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type PluginMeta = { id: string; name: string; platform: string };
|
|
42
|
+
type ManagedAccount = {
|
|
43
|
+
id: string;
|
|
44
|
+
platform: string;
|
|
45
|
+
pluginId: string;
|
|
46
|
+
env?: Record<string, string>;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
|
|
50
|
+
const PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs)$/;
|
|
51
|
+
const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
52
|
+
const RESERVED_ENV = new Set(["CHANNELD_ACCOUNT_ID", "CHANNELD_PLATFORM"]);
|
|
53
|
+
const MAX_ENV = 64;
|
|
54
|
+
const MAX_ENV_VALUE = 8192;
|
|
55
|
+
const MAX_PLUGIN_BYTES = 256 * 1024;
|
|
56
|
+
const MAX_REQUEST_BYTES = 1024 * 1024;
|
|
57
|
+
const HANDSHAKE_TIMEOUT_MS = 3000;
|
|
58
|
+
|
|
59
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
60
|
+
|
|
61
|
+
function integrationRoot(): string {
|
|
62
|
+
return path.resolve(path.dirname(databasePath()), "integrations");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function pluginsRoot(): string {
|
|
66
|
+
return path.join(integrationRoot(), "plugins");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function managedConfigPath(): string {
|
|
70
|
+
return path.join(integrationRoot(), "channeld.yml");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
74
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function publicError(error: unknown, fallback = "invalid integration request"): string {
|
|
78
|
+
const message = adminMessage(error)
|
|
79
|
+
.replace(/(?:[A-Za-z]:\\|\/)[^\s"']+/g, "[path]")
|
|
80
|
+
.trim();
|
|
81
|
+
return message || fallback;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Handshake failures keep the reason but never echo adapter stderr (env values). */
|
|
85
|
+
function handshakeError(error: unknown): string {
|
|
86
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
87
|
+
return publicError(new Error(raw.split(/\nstderr:/)[0] ?? ""), "plugin handshake failed");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function envEntry(key: string, item: unknown): [string, string] {
|
|
91
|
+
if (!ENV_KEY.test(key)) throw new Error(`env key ${key} is invalid`);
|
|
92
|
+
if (RESERVED_ENV.has(key)) throw new Error(`env key ${key} is reserved`);
|
|
93
|
+
if (typeof item !== "string") throw new Error(`env ${key} must be a string`);
|
|
94
|
+
if (item.length > MAX_ENV_VALUE) throw new Error(`env ${key} is too long`);
|
|
95
|
+
return [key, item];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function envValue(value: unknown): Record<string, string> | undefined {
|
|
99
|
+
if (value === undefined) return undefined;
|
|
100
|
+
if (!isRecord(value)) throw new Error("env must be an object of string values");
|
|
101
|
+
const entries = Object.entries(value);
|
|
102
|
+
if (entries.length > MAX_ENV) throw new Error(`env must contain at most ${MAX_ENV} variables`);
|
|
103
|
+
return Object.fromEntries(entries.map(([key, item]) => envEntry(key, item)));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Partial env edits: validate only the supplied keys, not the whole account. */
|
|
107
|
+
function envPatch(value: unknown): Record<string, string> {
|
|
108
|
+
if (!isRecord(value)) throw new Error("env must be an object of string values");
|
|
109
|
+
const entries = Object.entries(value);
|
|
110
|
+
if (entries.length > MAX_ENV) throw new Error(`env must contain at most ${MAX_ENV} variables`);
|
|
111
|
+
return Object.fromEntries(entries.map(([key, item]) => envEntry(key, item)));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function envDeleteKeys(value: unknown): string[] {
|
|
115
|
+
if (!Array.isArray(value)) throw new Error("envDelete must be an array of env names");
|
|
116
|
+
return value.map((key) => {
|
|
117
|
+
if (typeof key !== "string" || !ENV_KEY.test(key)) {
|
|
118
|
+
throw new Error(`envDelete key ${String(key)} is invalid`);
|
|
119
|
+
}
|
|
120
|
+
return key;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function accountEnv(
|
|
125
|
+
id: string,
|
|
126
|
+
item: Record<string, unknown>,
|
|
127
|
+
previous?: Record<string, string>,
|
|
128
|
+
): Record<string, string> | undefined {
|
|
129
|
+
const hasEnv = Object.prototype.hasOwnProperty.call(item, "env");
|
|
130
|
+
const hasDelete = Object.prototype.hasOwnProperty.call(item, "envDelete");
|
|
131
|
+
if (!hasEnv && !hasDelete) return previous;
|
|
132
|
+
const patch = hasEnv ? envPatch(item.env) : undefined;
|
|
133
|
+
const deletes = hasDelete ? envDeleteKeys(item.envDelete) : [];
|
|
134
|
+
for (const key of deletes) {
|
|
135
|
+
if (patch && Object.prototype.hasOwnProperty.call(patch, key)) {
|
|
136
|
+
throw new Error(`account ${id} lists ${key} in both env and envDelete`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// Empty env clears the account; a non-empty or omitted env starts from existing keys.
|
|
140
|
+
const clears = patch !== undefined && Object.keys(patch).length === 0;
|
|
141
|
+
const env = clears ? {} : { ...(previous ?? {}), ...(patch ?? {}) };
|
|
142
|
+
for (const key of deletes) delete env[key];
|
|
143
|
+
// Re-validate the merged map so deletions cannot hide bounds violations.
|
|
144
|
+
return envValue(env);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function readJsonBody(req: Request): Promise<{ ok: true; value: unknown } | { ok: false }> {
|
|
148
|
+
const declared = Number(req.headers.get("content-length") || 0);
|
|
149
|
+
if (declared > MAX_REQUEST_BYTES) return { ok: false };
|
|
150
|
+
let text: string;
|
|
151
|
+
try {
|
|
152
|
+
text = await req.text();
|
|
153
|
+
} catch {
|
|
154
|
+
return { ok: false };
|
|
155
|
+
}
|
|
156
|
+
if (Buffer.byteLength(text, "utf8") > MAX_REQUEST_BYTES) return { ok: false };
|
|
157
|
+
try {
|
|
158
|
+
return { ok: true, value: JSON.parse(text) as unknown };
|
|
159
|
+
} catch {
|
|
160
|
+
return { ok: false };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function atomicWrite(file: string, text: string): void {
|
|
165
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
166
|
+
writeFileSync(temp, text, { mode: 0o600 });
|
|
167
|
+
try {
|
|
168
|
+
renameSync(temp, file);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
try {
|
|
171
|
+
rmSync(temp, { force: true });
|
|
172
|
+
} catch {
|
|
173
|
+
// The original rename error is the useful one.
|
|
174
|
+
}
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function pluginDir(pluginId: string): string {
|
|
180
|
+
return path.join(pluginsRoot(), pluginId);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function readPlugin(pluginId: string): { dir: string; file: string; meta: PluginMeta } | undefined {
|
|
184
|
+
if (!IDENTIFIER.test(pluginId)) return undefined;
|
|
185
|
+
const dir = pluginDir(pluginId);
|
|
186
|
+
let meta: unknown;
|
|
187
|
+
try {
|
|
188
|
+
meta = JSON.parse(readFileSync(path.join(dir, "meta.json"), "utf8")) as unknown;
|
|
189
|
+
} catch {
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
if (!isRecord(meta)) return undefined;
|
|
193
|
+
const { id, name, platform } = meta;
|
|
194
|
+
if (id !== pluginId || typeof name !== "string" || !PLUGIN_NAME.test(name)) return undefined;
|
|
195
|
+
if (typeof platform !== "string" || !IDENTIFIER.test(platform)) return undefined;
|
|
196
|
+
const file = path.join(dir, name);
|
|
197
|
+
if (path.dirname(file) !== dir || !existsSync(file)) return undefined;
|
|
198
|
+
return { dir, file, meta: { id, name, platform } };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function uploadedPlugins(): Array<{ pluginId: string; name: string; platform: string }> {
|
|
202
|
+
let entries: string[];
|
|
203
|
+
try {
|
|
204
|
+
entries = readdirSync(pluginsRoot());
|
|
205
|
+
} catch {
|
|
206
|
+
return [];
|
|
207
|
+
}
|
|
208
|
+
return entries
|
|
209
|
+
.flatMap((pluginId) => {
|
|
210
|
+
const plugin = readPlugin(pluginId);
|
|
211
|
+
return plugin
|
|
212
|
+
? [{ pluginId: plugin.meta.id, name: plugin.meta.name, platform: plugin.meta.platform }]
|
|
213
|
+
: [];
|
|
214
|
+
})
|
|
215
|
+
.sort((left, right) => left.pluginId.localeCompare(right.pluginId));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
type ManagedState = {
|
|
219
|
+
config: ChannelConfig;
|
|
220
|
+
accounts: ManagedAccount[];
|
|
221
|
+
rules: RuleConfig[];
|
|
222
|
+
inbound: ChannelConfig["inbound"];
|
|
223
|
+
text: string;
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
function readManaged(): ManagedState | undefined {
|
|
227
|
+
const file = managedConfigPath();
|
|
228
|
+
let text: string;
|
|
229
|
+
try {
|
|
230
|
+
text = readFileSync(file, "utf8");
|
|
231
|
+
} catch {
|
|
232
|
+
return undefined;
|
|
233
|
+
}
|
|
234
|
+
const raw: unknown = parseYaml(text);
|
|
235
|
+
if (!isRecord(raw)) throw new Error("managed integration must be a mapping");
|
|
236
|
+
const rawAccounts = Array.isArray(raw.accounts) ? raw.accounts : [];
|
|
237
|
+
const pluginIds = new Map<string, string>();
|
|
238
|
+
for (const item of rawAccounts) {
|
|
239
|
+
if (!isRecord(item) || typeof item.id !== "string" || typeof item.pluginId !== "string") continue;
|
|
240
|
+
pluginIds.set(item.id, item.pluginId);
|
|
241
|
+
}
|
|
242
|
+
const config = parseConfig({ ...raw, stateFile: "managed-validation.sqlite" });
|
|
243
|
+
const accounts: ManagedAccount[] = config.accounts.map((account) => {
|
|
244
|
+
const pluginId = pluginIds.get(account.id) ?? "";
|
|
245
|
+
return {
|
|
246
|
+
id: account.id,
|
|
247
|
+
platform: account.platform,
|
|
248
|
+
pluginId: IDENTIFIER.test(pluginId) ? pluginId : "",
|
|
249
|
+
env: account.env,
|
|
250
|
+
};
|
|
251
|
+
});
|
|
252
|
+
return { config, accounts, rules: config.rules, inbound: config.inbound, text };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function integrationSnapshot(control: IntegrationControl): Record<string, unknown> {
|
|
256
|
+
let managed: ManagedState | undefined;
|
|
257
|
+
try {
|
|
258
|
+
managed = readManaged();
|
|
259
|
+
} catch {
|
|
260
|
+
// An unreadable managed file must not hide a healthy external runtime.
|
|
261
|
+
managed = undefined;
|
|
262
|
+
}
|
|
263
|
+
const runtime = control.runtime();
|
|
264
|
+
// A runtime can be started from an external YAML file. Its config is readable
|
|
265
|
+
// but must never be silently replaced by a managed save.
|
|
266
|
+
const external = !managed && runtime ? runtime.config : undefined;
|
|
267
|
+
const source = managed ? "managed" : external ? "external" : "none";
|
|
268
|
+
const editable = Boolean(managed) || !runtime;
|
|
269
|
+
const sourceAccounts: ManagedAccount[] = managed?.accounts
|
|
270
|
+
?? (external?.accounts ?? []).map((account) => ({
|
|
271
|
+
id: account.id,
|
|
272
|
+
platform: account.platform,
|
|
273
|
+
pluginId: "",
|
|
274
|
+
env: account.env,
|
|
275
|
+
}));
|
|
276
|
+
const states = runtime?.host.accountRuntimeStates;
|
|
277
|
+
const accounts = sourceAccounts.map((account) => {
|
|
278
|
+
const live = states?.get(`${account.platform}/${account.id}`);
|
|
279
|
+
const entry: Record<string, unknown> = {
|
|
280
|
+
id: account.id,
|
|
281
|
+
platform: account.platform,
|
|
282
|
+
pluginId: account.pluginId,
|
|
283
|
+
envKeys: Object.keys(account.env ?? {}).sort(),
|
|
284
|
+
state: live?.state ?? "unknown",
|
|
285
|
+
};
|
|
286
|
+
if (live?.lastError) {
|
|
287
|
+
const stderrAt = live.lastError.indexOf("stderr:");
|
|
288
|
+
entry.lastError = publicError(new Error(stderrAt >= 0 ? live.lastError.slice(0, stderrAt) : live.lastError));
|
|
289
|
+
}
|
|
290
|
+
return entry;
|
|
291
|
+
});
|
|
292
|
+
return {
|
|
293
|
+
enabled: control.enabled(),
|
|
294
|
+
source,
|
|
295
|
+
editable,
|
|
296
|
+
accounts,
|
|
297
|
+
rules: managed?.rules ?? external?.rules ?? [],
|
|
298
|
+
inbound: managed?.inbound ?? external?.inbound ?? [],
|
|
299
|
+
plugins: uploadedPlugins(),
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function parseAccounts(value: unknown, previous?: ManagedState): ManagedAccount[] {
|
|
304
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
305
|
+
throw new Error("accounts must be a non-empty array");
|
|
306
|
+
}
|
|
307
|
+
const oldEnv = new Map(previous?.accounts.map((account) => [account.id, account.env]));
|
|
308
|
+
const seen = new Set<string>();
|
|
309
|
+
return value.map((item, index) => {
|
|
310
|
+
if (!isRecord(item)) throw new Error(`accounts[${index}] must be an object`);
|
|
311
|
+
for (const key of ["command", "args", "argv", "adapter", "runtime", "cwd", "envFile"]) {
|
|
312
|
+
if (Object.prototype.hasOwnProperty.call(item, key)) {
|
|
313
|
+
throw new Error(`accounts[${index}].${key} is managed by the server; use pluginId and env`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const { id, platform, pluginId } = item;
|
|
317
|
+
if (typeof id !== "string" || !IDENTIFIER.test(id)) throw new Error(`accounts[${index}].id is invalid`);
|
|
318
|
+
if (seen.has(id)) throw new Error(`duplicate account id ${id}`);
|
|
319
|
+
seen.add(id);
|
|
320
|
+
if (typeof platform !== "string" || !IDENTIFIER.test(platform)) {
|
|
321
|
+
throw new Error(`accounts[${index}].platform is invalid`);
|
|
322
|
+
}
|
|
323
|
+
if (typeof pluginId !== "string" || !IDENTIFIER.test(pluginId)) {
|
|
324
|
+
throw new Error(`accounts[${index}].pluginId is invalid`);
|
|
325
|
+
}
|
|
326
|
+
const plugin = readPlugin(pluginId);
|
|
327
|
+
if (!plugin) throw new Error(`accounts[${index}].pluginId does not exist`);
|
|
328
|
+
if (plugin.meta.platform !== platform) {
|
|
329
|
+
throw new Error(`accounts[${index}].platform does not match its plugin`);
|
|
330
|
+
}
|
|
331
|
+
// Omitted env keeps current values, {} clears, non-empty merges, envDelete prunes.
|
|
332
|
+
const env = accountEnv(id, item, oldEnv.get(id));
|
|
333
|
+
return { id, platform, pluginId, env };
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function putIntegration(req: Request, control: IntegrationControl): Promise<Response> {
|
|
338
|
+
const body = await readJsonBody(req);
|
|
339
|
+
if (!body.ok || !isRecord(body.value)) {
|
|
340
|
+
return json({ error: "integration body must be a JSON object" }, 400);
|
|
341
|
+
}
|
|
342
|
+
if (typeof body.value.enabled !== "boolean") {
|
|
343
|
+
return json({ error: "enabled must be true or false" }, 400);
|
|
344
|
+
}
|
|
345
|
+
const file = managedConfigPath();
|
|
346
|
+
let previousText: string | undefined;
|
|
347
|
+
try {
|
|
348
|
+
previousText = readFileSync(file, "utf8");
|
|
349
|
+
} catch {
|
|
350
|
+
previousText = undefined;
|
|
351
|
+
}
|
|
352
|
+
let previous: ManagedState | undefined;
|
|
353
|
+
try {
|
|
354
|
+
previous = readManaged();
|
|
355
|
+
} catch {
|
|
356
|
+
previous = undefined;
|
|
357
|
+
}
|
|
358
|
+
// A running external config has no managed file to merge with; saving would
|
|
359
|
+
// replace a live runtime from a different source. Require an explicit disable.
|
|
360
|
+
if (!previous && control.runtime()) {
|
|
361
|
+
return json({
|
|
362
|
+
error: "active integrations use an external configuration file; disable it before saving managed integrations",
|
|
363
|
+
}, 409);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
let accounts: ManagedAccount[];
|
|
367
|
+
let config: ChannelConfig;
|
|
368
|
+
let rawAccounts: Array<Record<string, unknown>>;
|
|
369
|
+
try {
|
|
370
|
+
accounts = parseAccounts(body.value.accounts, previous);
|
|
371
|
+
rawAccounts = accounts.map((account) => {
|
|
372
|
+
const plugin = readPlugin(account.pluginId)!;
|
|
373
|
+
return {
|
|
374
|
+
id: account.id,
|
|
375
|
+
platform: account.platform,
|
|
376
|
+
pluginId: account.pluginId,
|
|
377
|
+
adapter: { command: ["node", plugin.file] },
|
|
378
|
+
...(account.env ? { env: account.env } : {}),
|
|
379
|
+
};
|
|
380
|
+
});
|
|
381
|
+
const rules = body.value.rules === undefined ? [] : body.value.rules;
|
|
382
|
+
const inbound = body.value.inbound === undefined ? previous?.inbound ?? [] : body.value.inbound;
|
|
383
|
+
config = parseConfig({
|
|
384
|
+
accounts: rawAccounts,
|
|
385
|
+
rules,
|
|
386
|
+
inbound,
|
|
387
|
+
stateFile: "managed-validation.sqlite",
|
|
388
|
+
});
|
|
389
|
+
validateTargets(config);
|
|
390
|
+
} catch (error) {
|
|
391
|
+
return json({ error: publicError(error) }, 400);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const text = stringifyYaml({
|
|
395
|
+
accounts: rawAccounts,
|
|
396
|
+
rules: config.rules,
|
|
397
|
+
...(config.inbound.length > 0 ? { inbound: config.inbound } : {}),
|
|
398
|
+
});
|
|
399
|
+
try {
|
|
400
|
+
mkdirSync(integrationRoot(), { recursive: true, mode: 0o700 });
|
|
401
|
+
atomicWrite(file, text);
|
|
402
|
+
} catch (error) {
|
|
403
|
+
return json({ error: publicError(error, "could not save integration") }, 400);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const response = body.value.enabled ? await control.activate(file) : await control.disable();
|
|
407
|
+
if (!response.ok) {
|
|
408
|
+
try {
|
|
409
|
+
if (previousText === undefined) rmSync(file, { force: true });
|
|
410
|
+
else atomicWrite(file, previousText);
|
|
411
|
+
} catch {
|
|
412
|
+
// The runtime already reported the failure; stale config is the lesser risk.
|
|
413
|
+
}
|
|
414
|
+
return response;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
if (previous) {
|
|
418
|
+
const kept = new Set(accounts.map((account) => account.pluginId));
|
|
419
|
+
for (const old of previous.accounts) {
|
|
420
|
+
if (!old.pluginId || !IDENTIFIER.test(old.pluginId) || kept.has(old.pluginId)) continue;
|
|
421
|
+
try {
|
|
422
|
+
rmSync(pluginDir(old.pluginId), { recursive: true, force: true });
|
|
423
|
+
} catch {
|
|
424
|
+
// Orphan cleanup is best effort.
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return json(integrationSnapshot(control));
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async function getIntegration(control: IntegrationControl): Promise<Response> {
|
|
432
|
+
try {
|
|
433
|
+
return json(integrationSnapshot(control));
|
|
434
|
+
} catch (error) {
|
|
435
|
+
return json({ error: publicError(error, "managed integration is unreadable") }, 500);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export async function handleIntegrationAdmin(
|
|
440
|
+
req: Request,
|
|
441
|
+
url: URL,
|
|
442
|
+
control: IntegrationControl,
|
|
443
|
+
): Promise<Response | undefined> {
|
|
444
|
+
if (url.pathname === "/channeld/plugins") {
|
|
445
|
+
if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
|
|
446
|
+
return uploadPlugin(req);
|
|
447
|
+
}
|
|
448
|
+
if (url.pathname === "/channeld/integration") {
|
|
449
|
+
if (req.method === "GET") return getIntegration(control);
|
|
450
|
+
if (req.method === "PUT") return putIntegration(req, control);
|
|
451
|
+
return json({ error: "method not allowed" }, 405);
|
|
452
|
+
}
|
|
453
|
+
return undefined;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
async function uploadPlugin(req: Request): Promise<Response> {
|
|
457
|
+
const body = await readJsonBody(req);
|
|
458
|
+
if (!body.ok || !isRecord(body.value)) {
|
|
459
|
+
return json({ error: "plugin body must be a JSON object" }, 400);
|
|
460
|
+
}
|
|
461
|
+
const { name, platform, source } = body.value;
|
|
462
|
+
if (typeof name !== "string" || !PLUGIN_NAME.test(name) || name.length > 128) {
|
|
463
|
+
return json({ error: "name must be a safe .js, .mjs, or .cjs file name" }, 400);
|
|
464
|
+
}
|
|
465
|
+
if (typeof platform !== "string" || !IDENTIFIER.test(platform)) {
|
|
466
|
+
return json({ error: "platform must be a safe identifier" }, 400);
|
|
467
|
+
}
|
|
468
|
+
if (typeof source !== "string" || Buffer.byteLength(source, "utf8") > MAX_PLUGIN_BYTES) {
|
|
469
|
+
return json({ error: `source must be UTF-8 text of at most ${MAX_PLUGIN_BYTES} bytes` }, 400);
|
|
470
|
+
}
|
|
471
|
+
let env: Record<string, string> | undefined;
|
|
472
|
+
try {
|
|
473
|
+
env = envValue(body.value.env);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
return json({ error: publicError(error) }, 400);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const root = integrationRoot();
|
|
479
|
+
const pluginId = randomUUID();
|
|
480
|
+
const tempDir = path.join(root, "tmp", pluginId);
|
|
481
|
+
const finalDir = pluginDir(pluginId);
|
|
482
|
+
const pluginFile = path.join(tempDir, name);
|
|
483
|
+
try {
|
|
484
|
+
mkdirSync(tempDir, { recursive: true, mode: 0o700 });
|
|
485
|
+
writeFileSync(pluginFile, source, { mode: 0o600 });
|
|
486
|
+
const meta: PluginMeta = { id: pluginId, name, platform };
|
|
487
|
+
writeFileSync(path.join(tempDir, "meta.json"), `${JSON.stringify(meta)}\n`, { mode: 0o600 });
|
|
488
|
+
|
|
489
|
+
const account: AccountConfig = {
|
|
490
|
+
id: `plugin-${pluginId}`,
|
|
491
|
+
platform,
|
|
492
|
+
adapter: { command: ["node", pluginFile] },
|
|
493
|
+
env,
|
|
494
|
+
};
|
|
495
|
+
const adapter = new AdapterProcess({
|
|
496
|
+
account,
|
|
497
|
+
onIngest: async () => ({ duplicate: false }),
|
|
498
|
+
onExit: () => {},
|
|
499
|
+
initializeTimeoutMs: HANDSHAKE_TIMEOUT_MS,
|
|
500
|
+
});
|
|
501
|
+
try {
|
|
502
|
+
await adapter.start();
|
|
503
|
+
} finally {
|
|
504
|
+
await adapter.stop();
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
mkdirSync(pluginsRoot(), { recursive: true, mode: 0o700 });
|
|
508
|
+
if (existsSync(finalDir)) throw new Error("plugin id collision");
|
|
509
|
+
renameSync(tempDir, finalDir);
|
|
510
|
+
return json({ pluginId, name, platform }, 201);
|
|
511
|
+
} catch (error) {
|
|
512
|
+
try {
|
|
513
|
+
rmSync(tempDir, { recursive: true, force: true });
|
|
514
|
+
} catch {
|
|
515
|
+
// Best effort: the temp directory may already be gone or unreadable.
|
|
516
|
+
}
|
|
517
|
+
return json({ error: handshakeError(error) }, 400);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Admin-side Channel D helpers: response sanitization, optional room-config
|
|
2
|
+
// persistence, and control-request body parsing. These stay out of the relay
|
|
3
|
+
// route file so a failed admin request can never leak adapter details.
|
|
4
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
|
|
7
|
+
import { findRoomConfigFile } from "../src/config/file-config.ts";
|
|
8
|
+
|
|
9
|
+
export type ChannelSettingsPatch = { enabled: boolean; config?: string };
|
|
10
|
+
|
|
11
|
+
/** Admin responses never echo credentials or the feature's internal name. */
|
|
12
|
+
export function adminMessage(error: unknown): string {
|
|
13
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
14
|
+
const clean = message
|
|
15
|
+
.replace(/channeld/gi, "relay")
|
|
16
|
+
.replace(/\bBearer\s+\S+/gi, "Bearer [redacted]")
|
|
17
|
+
.replace(/\b(secret|token|password|passwd|authorization|api[_-]?key)\b\s*[:=]\s*\S+/gi, "$1=[redacted]")
|
|
18
|
+
.replace(/[\r\n]+/g, " ")
|
|
19
|
+
.trim()
|
|
20
|
+
.slice(0, 300);
|
|
21
|
+
return clean || "relay request failed";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Best effort: rewrite channel settings in an existing JSON room config. */
|
|
25
|
+
export async function persistRoomSettings(
|
|
26
|
+
env: NodeJS.ProcessEnv,
|
|
27
|
+
next: ChannelSettingsPatch,
|
|
28
|
+
): Promise<boolean> {
|
|
29
|
+
try {
|
|
30
|
+
const file = findRoomConfigFile(env);
|
|
31
|
+
const extension = file ? path.extname(file).toLowerCase() : "";
|
|
32
|
+
if (!file || !(extension === ".json" || extension === ".yaml" || extension === ".yml")) return false;
|
|
33
|
+
const text = readFileSync(file, "utf8");
|
|
34
|
+
const parsed: unknown = extension === ".json" ? JSON.parse(text) : parseYaml(text);
|
|
35
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
36
|
+
const root = parsed as Record<string, unknown>;
|
|
37
|
+
const server = root.server && typeof root.server === "object" && !Array.isArray(root.server)
|
|
38
|
+
? root.server as Record<string, unknown>
|
|
39
|
+
: {};
|
|
40
|
+
const current = server.channeld && typeof server.channeld === "object" && !Array.isArray(server.channeld)
|
|
41
|
+
? server.channeld as Record<string, unknown>
|
|
42
|
+
: {};
|
|
43
|
+
const channeld: Record<string, unknown> = { ...current, enabled: next.enabled };
|
|
44
|
+
if (next.config !== undefined) channeld.config = next.config;
|
|
45
|
+
server.channeld = channeld;
|
|
46
|
+
root.server = server;
|
|
47
|
+
writeFileSync(file, extension === ".json" ? `${JSON.stringify(root, null, 2)}\n` : stringifyYaml(root));
|
|
48
|
+
return true;
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function readAdminBody(
|
|
55
|
+
req: Request,
|
|
56
|
+
): Promise<{ ok: true; config?: string } | { ok: false }> {
|
|
57
|
+
const declared = Number(req.headers.get("content-length") || 0);
|
|
58
|
+
if (declared > 64 * 1024) return { ok: false };
|
|
59
|
+
let text: string;
|
|
60
|
+
try {
|
|
61
|
+
text = await req.text();
|
|
62
|
+
} catch {
|
|
63
|
+
return { ok: false };
|
|
64
|
+
}
|
|
65
|
+
if (text.length > 64 * 1024) return { ok: false };
|
|
66
|
+
if (!text.trim()) return { ok: true };
|
|
67
|
+
try {
|
|
68
|
+
const value: unknown = JSON.parse(text);
|
|
69
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false };
|
|
70
|
+
const config = (value as Record<string, unknown>).config;
|
|
71
|
+
if (config === undefined) return { ok: true };
|
|
72
|
+
if (typeof config !== "string" || !config.trim()) return { ok: false };
|
|
73
|
+
return { ok: true, config: config.trim() };
|
|
74
|
+
} catch {
|
|
75
|
+
return { ok: false };
|
|
76
|
+
}
|
|
77
|
+
}
|