@openclaw/nextcloud-talk 2026.5.2 → 2026.5.3-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.
Files changed (61) hide show
  1. package/dist/api.js +2 -0
  2. package/dist/channel-BVVRsVr5.js +1788 -0
  3. package/dist/channel-plugin-api.js +2 -0
  4. package/dist/contract-api.js +2 -0
  5. package/dist/doctor-contract-CYlB-4Bf.js +7 -0
  6. package/dist/doctor-contract-api.js +2 -0
  7. package/dist/index.js +22 -0
  8. package/dist/runtime-api-BcCzeRN9.js +15 -0
  9. package/dist/runtime-api.js +2 -0
  10. package/dist/secret-contract-api.js +2 -0
  11. package/dist/secret-contract-bczDw2-2.js +86 -0
  12. package/dist/setup-entry.js +15 -0
  13. package/package.json +14 -6
  14. package/api.ts +0 -1
  15. package/channel-plugin-api.ts +0 -1
  16. package/contract-api.ts +0 -4
  17. package/doctor-contract-api.ts +0 -1
  18. package/index.ts +0 -20
  19. package/runtime-api.ts +0 -33
  20. package/secret-contract-api.ts +0 -5
  21. package/setup-entry.ts +0 -13
  22. package/src/accounts.ts +0 -139
  23. package/src/approval-auth.test.ts +0 -17
  24. package/src/approval-auth.ts +0 -27
  25. package/src/channel-api.ts +0 -5
  26. package/src/channel.adapters.ts +0 -52
  27. package/src/channel.core.test.ts +0 -75
  28. package/src/channel.lifecycle.test.ts +0 -81
  29. package/src/channel.ts +0 -195
  30. package/src/config-schema.ts +0 -79
  31. package/src/core.test.ts +0 -397
  32. package/src/doctor-contract.ts +0 -9
  33. package/src/doctor.test.ts +0 -40
  34. package/src/doctor.ts +0 -10
  35. package/src/gateway.ts +0 -109
  36. package/src/inbound.authz.test.ts +0 -149
  37. package/src/inbound.behavior.test.ts +0 -202
  38. package/src/inbound.ts +0 -320
  39. package/src/monitor-runtime.ts +0 -138
  40. package/src/monitor.replay.test.ts +0 -279
  41. package/src/monitor.test-fixtures.ts +0 -30
  42. package/src/monitor.test-harness.ts +0 -59
  43. package/src/monitor.ts +0 -385
  44. package/src/normalize.ts +0 -44
  45. package/src/policy.ts +0 -180
  46. package/src/replay-guard.ts +0 -128
  47. package/src/room-info.test.ts +0 -116
  48. package/src/room-info.ts +0 -148
  49. package/src/runtime.ts +0 -9
  50. package/src/secret-contract.ts +0 -103
  51. package/src/secret-input.ts +0 -4
  52. package/src/send.cfg-threading.test.ts +0 -153
  53. package/src/send.runtime.ts +0 -8
  54. package/src/send.ts +0 -236
  55. package/src/session-route.ts +0 -40
  56. package/src/setup-core.ts +0 -248
  57. package/src/setup-surface.ts +0 -190
  58. package/src/setup.test.ts +0 -422
  59. package/src/signature.ts +0 -82
  60. package/src/types.ts +0 -193
  61. package/tsconfig.json +0 -16
@@ -0,0 +1,1788 @@
1
+ import { n as normalizeCompatibilityConfig, t as legacyConfigRules } from "./doctor-contract-CYlB-4Bf.js";
2
+ import { a as fetchWithSsrFGuard, c as resolveAllowlistProviderRuntimeGroupPolicy, d as warnMissingProviderGroupPolicyFallbackOnce, f as getNextcloudTalkRuntime, i as dispatchInboundReplyWithBase, l as resolveDefaultGroupPolicy, n as createChannelPairingController, o as logInboundDrop, r as deliverFormattedTextWithAttachments, s as readStoreAllowFromForDmPolicy, t as GROUP_POLICY_BLOCKED_LABEL, u as resolveDmGroupAccessWithCommandGate } from "./runtime-api-BcCzeRN9.js";
3
+ import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-bczDw2-2.js";
4
+ import { describeWebhookAccountSnapshot } from "openclaw/plugin-sdk/account-helpers";
5
+ import { createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
6
+ import { createLoggedPairingApprovalNotifier, createPairingPrefixStripper } from "openclaw/plugin-sdk/channel-pairing";
7
+ import { createAllowlistProviderRouteAllowlistWarningCollector } from "openclaw/plugin-sdk/channel-policy";
8
+ import { buildWebhookChannelStatusSummary, createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
9
+ import { DEFAULT_ACCOUNT_ID, createAccountListHelpers, normalizeAccountId, resolveAccountWithDefaultFallback, resolveMergedAccountConfig } from "openclaw/plugin-sdk/account-core";
10
+ import { tryReadSecretFileSync } from "openclaw/plugin-sdk/secret-file-runtime";
11
+ import { convertMarkdownTables, normalizeLowercaseStringOrEmpty, normalizeOptionalLowercaseString, normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
12
+ import { buildSecretInputSchema, hasConfiguredSecretInput, normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input";
13
+ import { createResolvedApproverActionAuthAdapter, resolveApprovalApprovers } from "openclaw/plugin-sdk/approval-auth-runtime";
14
+ import { clearAccountEntryFields } from "openclaw/plugin-sdk/channel-plugin-common";
15
+ import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$2 } from "openclaw/plugin-sdk/account-id";
16
+ import { DmPolicySchema, GroupPolicySchema, MarkdownConfigSchema, ReplyRuntimeConfigSchemaShape, ToolPolicySchema, buildChannelConfigSchema, requireOpenAllowFrom } from "openclaw/plugin-sdk/channel-config-schema";
17
+ import { formatAllowFromLowercase } from "openclaw/plugin-sdk/allow-from";
18
+ import { adaptScopedAccountAccessor, createScopedChannelConfigAdapter, createScopedDmSecurityResolver } from "openclaw/plugin-sdk/channel-config-helpers";
19
+ import { requireChannelOpenAllowFrom, resolveLoggerBackedRuntime, runStoppablePassiveMonitor, safeParseJsonWithSchema } from "openclaw/plugin-sdk/extension-shared";
20
+ import { z } from "openclaw/plugin-sdk/zod";
21
+ import { ssrfPolicyFromPrivateNetworkOptIn, ssrfPolicyFromPrivateNetworkOptIn as ssrfPolicyFromPrivateNetworkOptIn$1 } from "openclaw/plugin-sdk/ssrf-runtime";
22
+ import { createAccountStatusSink } from "openclaw/plugin-sdk/channel-lifecycle";
23
+ import os from "node:os";
24
+ import { buildChannelKeyCandidates, normalizeChannelSlug, resolveChannelEntryMatchWithFallback, resolveNestedAllowlistDecision } from "openclaw/plugin-sdk/channel-targets";
25
+ import { evaluateMatchedGroupAccessForPolicy } from "openclaw/plugin-sdk/group-access";
26
+ import { readFileSync } from "node:fs";
27
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
28
+ import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
29
+ import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
30
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
31
+ import { createServer } from "node:http";
32
+ import { WEBHOOK_RATE_LIMIT_DEFAULTS, createAuthRateLimiter, isRequestBodyLimitError, readRequestBodyWithLimit, requestBodyErrorToText } from "openclaw/plugin-sdk/webhook-ingress";
33
+ import { z as z$1 } from "zod";
34
+ import path from "node:path";
35
+ import { createClaimableDedupe } from "openclaw/plugin-sdk/persistent-dedupe";
36
+ import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, buildOutboundBaseSessionKey, normalizeAccountId as normalizeAccountId$1 } from "openclaw/plugin-sdk/routing";
37
+ import { applyAccountNameToChannelSection, createStandardChannelSetupStatus, formatDocsLink, patchScopedAccountConfig, setSetupChannelEnabled } from "openclaw/plugin-sdk/setup";
38
+ import { createSetupInputPresenceValidator, mergeAllowFromEntries, promptParsedAllowFromForAccount, resolveSetupAccountId } from "openclaw/plugin-sdk/setup-runtime";
39
+ import { formatDocsLink as formatDocsLink$1 } from "openclaw/plugin-sdk/setup-tools";
40
+ //#region extensions/nextcloud-talk/src/accounts.ts
41
+ function isTruthyEnvValue(value) {
42
+ const normalized = normalizeLowercaseStringOrEmpty(value);
43
+ return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on";
44
+ }
45
+ const debugAccounts = (...args) => {
46
+ if (isTruthyEnvValue(process.env.OPENCLAW_DEBUG_NEXTCLOUD_TALK_ACCOUNTS)) console.warn("[nextcloud-talk:accounts]", ...args);
47
+ };
48
+ const { listAccountIds: listNextcloudTalkAccountIdsInternal, resolveDefaultAccountId: resolveDefaultNextcloudTalkAccountId } = createAccountListHelpers("nextcloud-talk", { normalizeAccountId });
49
+ function listNextcloudTalkAccountIds(cfg) {
50
+ const ids = listNextcloudTalkAccountIdsInternal(cfg);
51
+ debugAccounts("listNextcloudTalkAccountIds", ids);
52
+ return ids;
53
+ }
54
+ function mergeNextcloudTalkAccountConfig(cfg, accountId) {
55
+ return resolveMergedAccountConfig({
56
+ channelConfig: cfg.channels?.["nextcloud-talk"],
57
+ accounts: cfg.channels?.["nextcloud-talk"]?.accounts,
58
+ accountId,
59
+ omitKeys: ["defaultAccount"],
60
+ normalizeAccountId
61
+ });
62
+ }
63
+ function resolveNextcloudTalkSecret(cfg, opts) {
64
+ const resolvedAccountId = opts.accountId ?? resolveDefaultNextcloudTalkAccountId(cfg);
65
+ const merged = mergeNextcloudTalkAccountConfig(cfg, resolvedAccountId);
66
+ const envSecret = normalizeOptionalString(process.env.NEXTCLOUD_TALK_BOT_SECRET);
67
+ if (envSecret && resolvedAccountId === DEFAULT_ACCOUNT_ID) return {
68
+ secret: envSecret,
69
+ source: "env"
70
+ };
71
+ if (merged.botSecretFile) {
72
+ const fileSecret = tryReadSecretFileSync(merged.botSecretFile, "Nextcloud Talk bot secret file", { rejectSymlink: true });
73
+ if (fileSecret) return {
74
+ secret: fileSecret,
75
+ source: "secretFile"
76
+ };
77
+ }
78
+ const inlineSecret = normalizeResolvedSecretInputString({
79
+ value: merged.botSecret,
80
+ path: `channels.nextcloud-talk.accounts.${resolvedAccountId}.botSecret`
81
+ });
82
+ if (inlineSecret) return {
83
+ secret: inlineSecret,
84
+ source: "config"
85
+ };
86
+ return {
87
+ secret: "",
88
+ source: "none"
89
+ };
90
+ }
91
+ function resolveNextcloudTalkAccount(params) {
92
+ const baseEnabled = params.cfg.channels?.["nextcloud-talk"]?.enabled !== false;
93
+ const resolvedAccountId = params.accountId ?? resolveDefaultNextcloudTalkAccountId(params.cfg);
94
+ const resolve = (accountId) => {
95
+ const merged = mergeNextcloudTalkAccountConfig(params.cfg, accountId);
96
+ const accountEnabled = merged.enabled !== false;
97
+ const enabled = baseEnabled && accountEnabled;
98
+ const secretResolution = resolveNextcloudTalkSecret(params.cfg, { accountId });
99
+ const baseUrl = merged.baseUrl?.trim()?.replace(/\/$/, "") ?? "";
100
+ debugAccounts("resolve", {
101
+ accountId,
102
+ enabled,
103
+ secretSource: secretResolution.source,
104
+ baseUrl: baseUrl ? "[set]" : "[missing]"
105
+ });
106
+ return {
107
+ accountId,
108
+ enabled,
109
+ name: normalizeOptionalString(merged.name),
110
+ baseUrl,
111
+ secret: secretResolution.secret,
112
+ secretSource: secretResolution.source,
113
+ config: merged
114
+ };
115
+ };
116
+ return resolveAccountWithDefaultFallback({
117
+ accountId: resolvedAccountId,
118
+ normalizeAccountId,
119
+ resolvePrimary: resolve,
120
+ hasCredential: (account) => account.secretSource !== "none",
121
+ resolveDefaultAccountId: () => resolveDefaultNextcloudTalkAccountId(params.cfg)
122
+ });
123
+ }
124
+ //#endregion
125
+ //#region extensions/nextcloud-talk/src/approval-auth.ts
126
+ function normalizeNextcloudTalkApproverId(value) {
127
+ return normalizeOptionalLowercaseString(String(value).trim().replace(/^(nextcloud-talk|nc-talk|nc):/i, ""));
128
+ }
129
+ const nextcloudTalkApprovalAuth = createResolvedApproverActionAuthAdapter({
130
+ channelLabel: "Nextcloud Talk",
131
+ resolveApprovers: ({ cfg, accountId }) => {
132
+ return resolveApprovalApprovers({
133
+ allowFrom: resolveNextcloudTalkAccount({
134
+ cfg,
135
+ accountId
136
+ }).config.allowFrom,
137
+ normalizeApprover: normalizeNextcloudTalkApproverId
138
+ });
139
+ },
140
+ normalizeSenderId: (value) => normalizeNextcloudTalkApproverId(value)
141
+ });
142
+ //#endregion
143
+ //#region extensions/nextcloud-talk/src/channel.adapters.ts
144
+ const nextcloudTalkConfigAdapter = createScopedChannelConfigAdapter({
145
+ sectionKey: "nextcloud-talk",
146
+ listAccountIds: listNextcloudTalkAccountIds,
147
+ resolveAccount: adaptScopedAccountAccessor(resolveNextcloudTalkAccount),
148
+ defaultAccountId: resolveDefaultNextcloudTalkAccountId,
149
+ clearBaseFields: [
150
+ "botSecret",
151
+ "botSecretFile",
152
+ "baseUrl",
153
+ "name"
154
+ ],
155
+ resolveAllowFrom: (account) => account.config.allowFrom,
156
+ formatAllowFrom: (allowFrom) => formatAllowFromLowercase({
157
+ allowFrom,
158
+ stripPrefixRe: /^(nextcloud-talk|nc-talk|nc):/i
159
+ })
160
+ });
161
+ const nextcloudTalkSecurityAdapter = { resolveDmPolicy: createScopedDmSecurityResolver({
162
+ channelKey: "nextcloud-talk",
163
+ resolvePolicy: (account) => account.config.dmPolicy,
164
+ resolveAllowFrom: (account) => account.config.allowFrom,
165
+ policyPathSuffix: "dmPolicy",
166
+ normalizeEntry: (raw) => normalizeLowercaseStringOrEmpty(raw.trim().replace(/^(nextcloud-talk|nc-talk|nc):/i, ""))
167
+ }) };
168
+ const nextcloudTalkPairingTextAdapter = {
169
+ idLabel: "nextcloudUserId",
170
+ message: "OpenClaw: your access has been approved.",
171
+ normalizeAllowEntry: createPairingPrefixStripper(/^(nextcloud-talk|nc-talk|nc):/i, (entry) => normalizeLowercaseStringOrEmpty(entry))
172
+ };
173
+ //#endregion
174
+ //#region extensions/nextcloud-talk/src/config-schema.ts
175
+ const NextcloudTalkRoomSchema = z.object({
176
+ requireMention: z.boolean().optional(),
177
+ tools: ToolPolicySchema,
178
+ skills: z.array(z.string()).optional(),
179
+ enabled: z.boolean().optional(),
180
+ allowFrom: z.array(z.string()).optional(),
181
+ systemPrompt: z.string().optional()
182
+ }).strict();
183
+ const NextcloudTalkNetworkSchema = z.object({
184
+ /** Dangerous opt-in for self-hosted Nextcloud Talk on trusted private/internal hosts. */
185
+ dangerouslyAllowPrivateNetwork: z.boolean().optional() }).strict().optional();
186
+ const NextcloudTalkAccountSchemaBase = z.object({
187
+ name: z.string().optional(),
188
+ enabled: z.boolean().optional(),
189
+ markdown: MarkdownConfigSchema,
190
+ baseUrl: z.string().optional(),
191
+ botSecret: buildSecretInputSchema().optional(),
192
+ botSecretFile: z.string().optional(),
193
+ apiUser: z.string().optional(),
194
+ apiPassword: buildSecretInputSchema().optional(),
195
+ apiPasswordFile: z.string().optional(),
196
+ dmPolicy: DmPolicySchema.optional().default("pairing"),
197
+ webhookPort: z.number().int().positive().optional(),
198
+ webhookHost: z.string().optional(),
199
+ webhookPath: z.string().optional(),
200
+ webhookPublicUrl: z.string().optional(),
201
+ allowFrom: z.array(z.string()).optional(),
202
+ groupAllowFrom: z.array(z.string()).optional(),
203
+ groupPolicy: GroupPolicySchema.optional().default("allowlist"),
204
+ rooms: z.record(z.string(), NextcloudTalkRoomSchema.optional()).optional(),
205
+ /** Network policy overrides for self-hosted Nextcloud Talk on trusted private/internal hosts. */
206
+ network: NextcloudTalkNetworkSchema,
207
+ ...ReplyRuntimeConfigSchemaShape
208
+ }).strict();
209
+ const NextcloudTalkAccountSchema = NextcloudTalkAccountSchemaBase.superRefine((value, ctx) => {
210
+ requireChannelOpenAllowFrom({
211
+ channel: "nextcloud-talk",
212
+ policy: value.dmPolicy,
213
+ allowFrom: value.allowFrom,
214
+ ctx,
215
+ requireOpenAllowFrom
216
+ });
217
+ });
218
+ const NextcloudTalkConfigSchema = NextcloudTalkAccountSchemaBase.extend({
219
+ accounts: z.record(z.string(), NextcloudTalkAccountSchema.optional()).optional(),
220
+ defaultAccount: z.string().optional()
221
+ }).superRefine((value, ctx) => {
222
+ requireChannelOpenAllowFrom({
223
+ channel: "nextcloud-talk",
224
+ policy: value.dmPolicy,
225
+ allowFrom: value.allowFrom,
226
+ ctx,
227
+ requireOpenAllowFrom
228
+ });
229
+ });
230
+ //#endregion
231
+ //#region extensions/nextcloud-talk/src/doctor.ts
232
+ const nextcloudTalkDoctor = {
233
+ legacyConfigRules,
234
+ normalizeCompatibilityConfig
235
+ };
236
+ //#endregion
237
+ //#region extensions/nextcloud-talk/src/policy.ts
238
+ function normalizeAllowEntry(raw) {
239
+ return raw.trim().replace(/^(nextcloud-talk|nc-talk|nc):/i, "").toLowerCase();
240
+ }
241
+ function normalizeNextcloudTalkAllowlist(values) {
242
+ return (values ?? []).map((value) => normalizeAllowEntry(String(value))).filter(Boolean);
243
+ }
244
+ function resolveNextcloudTalkAllowlistMatch(params) {
245
+ const allowFrom = normalizeNextcloudTalkAllowlist(params.allowFrom);
246
+ if (allowFrom.length === 0) return { allowed: false };
247
+ if (allowFrom.includes("*")) return {
248
+ allowed: true,
249
+ matchKey: "*",
250
+ matchSource: "wildcard"
251
+ };
252
+ const senderId = normalizeAllowEntry(params.senderId);
253
+ if (allowFrom.includes(senderId)) return {
254
+ allowed: true,
255
+ matchKey: senderId,
256
+ matchSource: "id"
257
+ };
258
+ return { allowed: false };
259
+ }
260
+ function resolveNextcloudTalkRoomMatch(params) {
261
+ const rooms = params.rooms ?? {};
262
+ const allowlistConfigured = Object.keys(rooms).length > 0;
263
+ const match = resolveChannelEntryMatchWithFallback({
264
+ entries: rooms,
265
+ keys: buildChannelKeyCandidates(params.roomToken),
266
+ wildcardKey: "*",
267
+ normalizeKey: normalizeChannelSlug
268
+ });
269
+ const roomConfig = match.entry;
270
+ const allowed = resolveNestedAllowlistDecision({
271
+ outerConfigured: allowlistConfigured,
272
+ outerMatched: Boolean(roomConfig),
273
+ innerConfigured: false,
274
+ innerMatched: false
275
+ });
276
+ return {
277
+ roomConfig,
278
+ wildcardConfig: match.wildcardEntry,
279
+ roomKey: match.matchKey ?? match.key,
280
+ matchSource: match.matchSource,
281
+ allowed,
282
+ allowlistConfigured
283
+ };
284
+ }
285
+ function resolveNextcloudTalkGroupToolPolicy(params) {
286
+ const cfg = params.cfg;
287
+ const roomToken = params.groupId?.trim();
288
+ if (!roomToken) return;
289
+ const match = resolveNextcloudTalkRoomMatch({
290
+ rooms: cfg.channels?.["nextcloud-talk"]?.rooms,
291
+ roomToken
292
+ });
293
+ return match.roomConfig?.tools ?? match.wildcardConfig?.tools;
294
+ }
295
+ function resolveNextcloudTalkRequireMention(params) {
296
+ if (typeof params.roomConfig?.requireMention === "boolean") return params.roomConfig.requireMention;
297
+ if (typeof params.wildcardConfig?.requireMention === "boolean") return params.wildcardConfig.requireMention;
298
+ return true;
299
+ }
300
+ function resolveNextcloudTalkGroupAllow(params) {
301
+ const outerAllow = normalizeNextcloudTalkAllowlist(params.outerAllowFrom);
302
+ const innerAllow = normalizeNextcloudTalkAllowlist(params.innerAllowFrom);
303
+ const outerMatch = resolveNextcloudTalkAllowlistMatch({
304
+ allowFrom: params.outerAllowFrom,
305
+ senderId: params.senderId
306
+ });
307
+ const innerMatch = resolveNextcloudTalkAllowlistMatch({
308
+ allowFrom: params.innerAllowFrom,
309
+ senderId: params.senderId
310
+ });
311
+ return {
312
+ allowed: evaluateMatchedGroupAccessForPolicy({
313
+ groupPolicy: params.groupPolicy,
314
+ allowlistConfigured: outerAllow.length > 0 || innerAllow.length > 0,
315
+ allowlistMatched: resolveNestedAllowlistDecision({
316
+ outerConfigured: outerAllow.length > 0 || innerAllow.length > 0,
317
+ outerMatched: outerAllow.length > 0 ? outerMatch.allowed : true,
318
+ innerConfigured: innerAllow.length > 0,
319
+ innerMatched: innerMatch.allowed
320
+ })
321
+ }).allowed,
322
+ outerMatch: params.groupPolicy === "open" ? { allowed: true } : params.groupPolicy === "disabled" ? { allowed: false } : outerMatch,
323
+ innerMatch: params.groupPolicy === "open" ? { allowed: true } : params.groupPolicy === "disabled" ? { allowed: false } : innerMatch
324
+ };
325
+ }
326
+ function resolveNextcloudTalkMentionGate(params) {
327
+ const shouldBypassMention = params.isGroup && params.requireMention && !params.wasMentioned && params.allowTextCommands && params.commandAuthorized && params.hasControlCommand;
328
+ return {
329
+ shouldBypassMention,
330
+ shouldSkip: params.requireMention && !params.wasMentioned && !shouldBypassMention
331
+ };
332
+ }
333
+ //#endregion
334
+ //#region extensions/nextcloud-talk/src/room-info.ts
335
+ const ROOM_CACHE_TTL_MS = 300 * 1e3;
336
+ const ROOM_CACHE_ERROR_TTL_MS = 30 * 1e3;
337
+ const roomCache = /* @__PURE__ */ new Map();
338
+ function resolveRoomCacheKey(params) {
339
+ return `${params.accountId}:${params.roomToken}`;
340
+ }
341
+ function readApiPassword(params) {
342
+ const inlinePassword = normalizeResolvedSecretInputString({
343
+ value: params.apiPassword,
344
+ path: "channels.nextcloud-talk.apiPassword"
345
+ });
346
+ if (inlinePassword) return inlinePassword;
347
+ if (!params.apiPasswordFile) return;
348
+ try {
349
+ return readFileSync(params.apiPasswordFile, "utf-8").trim() || void 0;
350
+ } catch {
351
+ return;
352
+ }
353
+ }
354
+ function coerceRoomType(value) {
355
+ if (typeof value === "number" && Number.isFinite(value)) return value;
356
+ if (typeof value === "string" && value.trim()) {
357
+ const parsed = Number.parseInt(value, 10);
358
+ return Number.isFinite(parsed) ? parsed : void 0;
359
+ }
360
+ }
361
+ function resolveRoomKindFromType(type) {
362
+ if (!type) return;
363
+ if (type === 1 || type === 5 || type === 6) return "direct";
364
+ return "group";
365
+ }
366
+ async function resolveNextcloudTalkRoomKind(params) {
367
+ const { account, roomToken, runtime } = params;
368
+ const key = resolveRoomCacheKey({
369
+ accountId: account.accountId,
370
+ roomToken
371
+ });
372
+ const cached = roomCache.get(key);
373
+ if (cached) {
374
+ const age = Date.now() - cached.fetchedAt;
375
+ if (cached.kind && age < ROOM_CACHE_TTL_MS) return cached.kind;
376
+ if (cached.error && age < ROOM_CACHE_ERROR_TTL_MS) return;
377
+ }
378
+ const apiUser = account.config.apiUser?.trim();
379
+ const apiPassword = readApiPassword({
380
+ apiPassword: account.config.apiPassword,
381
+ apiPasswordFile: account.config.apiPasswordFile
382
+ });
383
+ if (!apiUser || !apiPassword) return;
384
+ const baseUrl = account.baseUrl?.trim();
385
+ if (!baseUrl) return;
386
+ const url = `${baseUrl}/ocs/v2.php/apps/spreed/api/v4/room/${roomToken}`;
387
+ const auth = Buffer.from(`${apiUser}:${apiPassword}`, "utf-8").toString("base64");
388
+ try {
389
+ const { response, release } = await fetchWithSsrFGuard({
390
+ url,
391
+ init: {
392
+ method: "GET",
393
+ headers: {
394
+ Authorization: `Basic ${auth}`,
395
+ "OCS-APIRequest": "true",
396
+ Accept: "application/json"
397
+ }
398
+ },
399
+ auditContext: "nextcloud-talk.room-info",
400
+ policy: ssrfPolicyFromPrivateNetworkOptIn(account.config)
401
+ });
402
+ try {
403
+ if (!response.ok) {
404
+ roomCache.set(key, {
405
+ fetchedAt: Date.now(),
406
+ error: `status:${response.status}`
407
+ });
408
+ runtime?.log?.(`nextcloud-talk: room lookup failed (${response.status}) token=${roomToken}`);
409
+ return;
410
+ }
411
+ const kind = resolveRoomKindFromType(coerceRoomType((await response.json()).ocs?.data?.type));
412
+ roomCache.set(key, {
413
+ fetchedAt: Date.now(),
414
+ kind
415
+ });
416
+ return kind;
417
+ } finally {
418
+ await release();
419
+ }
420
+ } catch (err) {
421
+ roomCache.set(key, {
422
+ fetchedAt: Date.now(),
423
+ error: formatErrorMessage(err)
424
+ });
425
+ runtime?.error?.(`nextcloud-talk: room lookup error: ${String(err)}`);
426
+ return;
427
+ }
428
+ }
429
+ //#endregion
430
+ //#region extensions/nextcloud-talk/src/normalize.ts
431
+ function stripNextcloudTalkTargetPrefix(raw) {
432
+ const trimmed = raw.trim();
433
+ if (!trimmed) return;
434
+ let normalized = trimmed;
435
+ if (normalized.startsWith("nextcloud-talk:")) normalized = normalized.slice(15).trim();
436
+ else if (normalized.startsWith("nc-talk:")) normalized = normalized.slice(8).trim();
437
+ else if (normalized.startsWith("nc:")) normalized = normalized.slice(3).trim();
438
+ if (normalized.startsWith("room:")) normalized = normalized.slice(5).trim();
439
+ if (!normalized) return;
440
+ return normalized;
441
+ }
442
+ function normalizeNextcloudTalkMessagingTarget(raw) {
443
+ const normalized = stripNextcloudTalkTargetPrefix(raw);
444
+ return normalized ? `nextcloud-talk:${normalized}`.toLowerCase() : void 0;
445
+ }
446
+ function looksLikeNextcloudTalkTargetId(raw) {
447
+ const trimmed = raw.trim();
448
+ if (!trimmed) return false;
449
+ if (/^(nextcloud-talk|nc-talk|nc):/i.test(trimmed)) return true;
450
+ return /^[a-z0-9]{8,}$/i.test(trimmed);
451
+ }
452
+ //#endregion
453
+ //#region extensions/nextcloud-talk/src/signature.ts
454
+ const SIGNATURE_HEADER = "x-nextcloud-talk-signature";
455
+ const RANDOM_HEADER = "x-nextcloud-talk-random";
456
+ const BACKEND_HEADER = "x-nextcloud-talk-backend";
457
+ /**
458
+ * Verify the HMAC-SHA256 signature of an incoming webhook request.
459
+ * Signature is calculated as: HMAC-SHA256(random + body, secret)
460
+ */
461
+ function verifyNextcloudTalkSignature(params) {
462
+ const { signature, random, body, secret } = params;
463
+ if (!signature || !random || !secret) return false;
464
+ const expected = createHmac("sha256", secret).update(random + body).digest("hex");
465
+ const expectedBuf = Buffer.from(expected, "utf8");
466
+ const signatureBuf = Buffer.from(signature, "utf8");
467
+ const maxLen = Math.max(expectedBuf.length, signatureBuf.length);
468
+ const paddedExpected = Buffer.alloc(maxLen);
469
+ const paddedSignature = Buffer.alloc(maxLen);
470
+ expectedBuf.copy(paddedExpected);
471
+ signatureBuf.copy(paddedSignature);
472
+ const timingResult = timingSafeEqual(paddedExpected, paddedSignature);
473
+ return expectedBuf.length === signatureBuf.length && timingResult;
474
+ }
475
+ /**
476
+ * Extract webhook headers from an incoming request.
477
+ */
478
+ function extractNextcloudTalkHeaders(headers) {
479
+ const getHeader = (name) => {
480
+ const value = headers[name] ?? headers[normalizeLowercaseStringOrEmpty(name)];
481
+ return Array.isArray(value) ? value[0] : value;
482
+ };
483
+ const signature = getHeader(SIGNATURE_HEADER);
484
+ const random = getHeader(RANDOM_HEADER);
485
+ const backend = getHeader(BACKEND_HEADER);
486
+ if (!signature || !random || !backend) return null;
487
+ return {
488
+ signature,
489
+ random,
490
+ backend
491
+ };
492
+ }
493
+ /**
494
+ * Generate signature headers for an outbound request to Nextcloud Talk.
495
+ */
496
+ function generateNextcloudTalkSignature(params) {
497
+ const { body, secret } = params;
498
+ const random = randomBytes(32).toString("hex");
499
+ return {
500
+ random,
501
+ signature: createHmac("sha256", secret).update(random + body).digest("hex")
502
+ };
503
+ }
504
+ //#endregion
505
+ //#region extensions/nextcloud-talk/src/send.ts
506
+ function resolveCredentials(explicit, account) {
507
+ const baseUrl = explicit.baseUrl?.trim() ?? account.baseUrl;
508
+ const secret = explicit.secret?.trim() ?? account.secret;
509
+ if (!baseUrl) throw new Error(`Nextcloud Talk baseUrl missing for account "${account.accountId}" (set channels.nextcloud-talk.baseUrl).`);
510
+ if (!secret) throw new Error(`Nextcloud Talk bot secret missing for account "${account.accountId}" (set channels.nextcloud-talk.botSecret/botSecretFile or NEXTCLOUD_TALK_BOT_SECRET for default).`);
511
+ return {
512
+ baseUrl,
513
+ secret
514
+ };
515
+ }
516
+ function normalizeRoomToken(to) {
517
+ const normalized = stripNextcloudTalkTargetPrefix(to);
518
+ if (!normalized) throw new Error("Room token is required for Nextcloud Talk sends");
519
+ return normalized;
520
+ }
521
+ function resolveNextcloudTalkSendContext(opts) {
522
+ const cfg = requireRuntimeConfig(opts.cfg, "Nextcloud Talk send");
523
+ const account = resolveNextcloudTalkAccount({
524
+ cfg,
525
+ accountId: opts.accountId
526
+ });
527
+ const { baseUrl, secret } = resolveCredentials({
528
+ baseUrl: opts.baseUrl,
529
+ secret: opts.secret
530
+ }, account);
531
+ return {
532
+ cfg,
533
+ account,
534
+ baseUrl,
535
+ secret
536
+ };
537
+ }
538
+ function recordNextcloudTalkOutboundActivity(accountId) {
539
+ try {
540
+ getNextcloudTalkRuntime().channel.activity.record({
541
+ channel: "nextcloud-talk",
542
+ accountId,
543
+ direction: "outbound"
544
+ });
545
+ } catch (error) {
546
+ if (!(error instanceof Error) || error.message !== "Nextcloud Talk runtime not initialized") throw error;
547
+ }
548
+ }
549
+ async function sendMessageNextcloudTalk(to, text, opts) {
550
+ const { cfg, account, baseUrl, secret } = resolveNextcloudTalkSendContext(opts);
551
+ const roomToken = normalizeRoomToken(to);
552
+ if (!text?.trim()) throw new Error("Message must be non-empty for Nextcloud Talk sends");
553
+ const tableMode = resolveMarkdownTableMode({
554
+ cfg,
555
+ channel: "nextcloud-talk",
556
+ accountId: account.accountId
557
+ });
558
+ const message = convertMarkdownTables(text.trim(), tableMode);
559
+ const body = { message };
560
+ if (opts.replyTo) body.replyTo = opts.replyTo;
561
+ const bodyStr = JSON.stringify(body);
562
+ const { random, signature } = generateNextcloudTalkSignature({
563
+ body: message,
564
+ secret
565
+ });
566
+ const { response, release } = await fetchWithSsrFGuard({
567
+ url: `${baseUrl}/ocs/v2.php/apps/spreed/api/v1/bot/${roomToken}/message`,
568
+ init: {
569
+ method: "POST",
570
+ headers: {
571
+ "Content-Type": "application/json",
572
+ "OCS-APIRequest": "true",
573
+ "X-Nextcloud-Talk-Bot-Random": random,
574
+ "X-Nextcloud-Talk-Bot-Signature": signature
575
+ },
576
+ body: bodyStr
577
+ },
578
+ auditContext: "nextcloud-talk-send",
579
+ policy: ssrfPolicyFromPrivateNetworkOptIn$1(account.config)
580
+ });
581
+ try {
582
+ if (!response.ok) {
583
+ const errorBody = await response.text().catch(() => "");
584
+ const status = response.status;
585
+ let errorMsg = `Nextcloud Talk send failed (${status})`;
586
+ if (status === 400) errorMsg = `Nextcloud Talk: bad request - ${errorBody || "invalid message format"}`;
587
+ else if (status === 401) errorMsg = "Nextcloud Talk: authentication failed - check bot secret";
588
+ else if (status === 403) errorMsg = "Nextcloud Talk: forbidden - bot may not have permission in this room";
589
+ else if (status === 404) errorMsg = `Nextcloud Talk: room not found (token=${roomToken})`;
590
+ else if (errorBody) errorMsg = `Nextcloud Talk send failed: ${errorBody}`;
591
+ throw new Error(errorMsg);
592
+ }
593
+ let messageId = "unknown";
594
+ let timestamp;
595
+ try {
596
+ const data = await response.json();
597
+ if (data.ocs?.data?.id != null) messageId = String(data.ocs.data.id);
598
+ if (typeof data.ocs?.data?.timestamp === "number") timestamp = data.ocs.data.timestamp;
599
+ } catch {}
600
+ if (opts.verbose) console.log(`[nextcloud-talk] Sent message ${messageId} to room ${roomToken}`);
601
+ recordNextcloudTalkOutboundActivity(account.accountId);
602
+ return {
603
+ messageId,
604
+ roomToken,
605
+ timestamp
606
+ };
607
+ } finally {
608
+ await release();
609
+ }
610
+ }
611
+ //#endregion
612
+ //#region extensions/nextcloud-talk/src/inbound.ts
613
+ const CHANNEL_ID = "nextcloud-talk";
614
+ async function deliverNextcloudTalkReply(params) {
615
+ const { cfg, payload, roomToken, accountId, statusSink } = params;
616
+ await deliverFormattedTextWithAttachments({
617
+ payload,
618
+ send: async ({ text, replyToId }) => {
619
+ await sendMessageNextcloudTalk(roomToken, text, {
620
+ cfg,
621
+ accountId,
622
+ replyTo: replyToId
623
+ });
624
+ statusSink?.({ lastOutboundAt: Date.now() });
625
+ }
626
+ });
627
+ }
628
+ async function handleNextcloudTalkInbound(params) {
629
+ const { message, account, config, runtime, statusSink } = params;
630
+ const core = getNextcloudTalkRuntime();
631
+ const pairing = createChannelPairingController({
632
+ core,
633
+ channel: CHANNEL_ID,
634
+ accountId: account.accountId
635
+ });
636
+ const rawBody = message.text?.trim() ?? "";
637
+ if (!rawBody) return;
638
+ const roomKind = await resolveNextcloudTalkRoomKind({
639
+ account,
640
+ roomToken: message.roomToken,
641
+ runtime
642
+ });
643
+ const isGroup = roomKind === "direct" ? false : roomKind === "group" ? true : message.isGroupChat;
644
+ const senderId = message.senderId;
645
+ const senderName = message.senderName;
646
+ const roomToken = message.roomToken;
647
+ const roomName = message.roomName;
648
+ statusSink?.({ lastInboundAt: message.timestamp });
649
+ const dmPolicy = account.config.dmPolicy ?? "pairing";
650
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(config);
651
+ const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
652
+ providerConfigPresent: (config.channels?.["nextcloud-talk"] ?? void 0) !== void 0,
653
+ groupPolicy: account.config.groupPolicy,
654
+ defaultGroupPolicy
655
+ });
656
+ warnMissingProviderGroupPolicyFallbackOnce({
657
+ providerMissingFallbackApplied,
658
+ providerKey: "nextcloud-talk",
659
+ accountId: account.accountId,
660
+ blockedLabel: GROUP_POLICY_BLOCKED_LABEL.room,
661
+ log: (message) => runtime.log?.(message)
662
+ });
663
+ const configAllowFrom = normalizeNextcloudTalkAllowlist(account.config.allowFrom);
664
+ const configGroupAllowFrom = normalizeNextcloudTalkAllowlist(account.config.groupAllowFrom);
665
+ const storeAllowList = normalizeNextcloudTalkAllowlist(await readStoreAllowFromForDmPolicy({
666
+ provider: CHANNEL_ID,
667
+ accountId: account.accountId,
668
+ dmPolicy,
669
+ readStore: pairing.readStoreForDmPolicy
670
+ }));
671
+ const roomMatch = resolveNextcloudTalkRoomMatch({
672
+ rooms: account.config.rooms,
673
+ roomToken
674
+ });
675
+ const roomConfig = roomMatch.roomConfig;
676
+ if (isGroup && !roomMatch.allowed) {
677
+ runtime.log?.(`nextcloud-talk: drop room ${roomToken} (not allowlisted)`);
678
+ return;
679
+ }
680
+ if (roomConfig?.enabled === false) {
681
+ runtime.log?.(`nextcloud-talk: drop room ${roomToken} (disabled)`);
682
+ return;
683
+ }
684
+ const roomAllowFrom = normalizeNextcloudTalkAllowlist(roomConfig?.allowFrom);
685
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
686
+ cfg: config,
687
+ surface: CHANNEL_ID
688
+ });
689
+ const useAccessGroups = config.commands?.useAccessGroups !== false;
690
+ const hasControlCommand = core.channel.text.hasControlCommand(rawBody, config);
691
+ const access = resolveDmGroupAccessWithCommandGate({
692
+ isGroup,
693
+ dmPolicy,
694
+ groupPolicy,
695
+ allowFrom: configAllowFrom,
696
+ groupAllowFrom: configGroupAllowFrom,
697
+ storeAllowFrom: storeAllowList,
698
+ isSenderAllowed: (allowFrom) => resolveNextcloudTalkAllowlistMatch({
699
+ allowFrom,
700
+ senderId
701
+ }).allowed,
702
+ command: {
703
+ useAccessGroups,
704
+ allowTextCommands,
705
+ hasControlCommand
706
+ }
707
+ });
708
+ const commandAuthorized = access.commandAuthorized;
709
+ const effectiveGroupAllowFrom = access.effectiveGroupAllowFrom;
710
+ if (isGroup) {
711
+ if (access.decision !== "allow") {
712
+ runtime.log?.(`nextcloud-talk: drop group sender ${senderId} (reason=${access.reason})`);
713
+ return;
714
+ }
715
+ if (!resolveNextcloudTalkGroupAllow({
716
+ groupPolicy,
717
+ outerAllowFrom: effectiveGroupAllowFrom,
718
+ innerAllowFrom: roomAllowFrom,
719
+ senderId
720
+ }).allowed) {
721
+ runtime.log?.(`nextcloud-talk: drop group sender ${senderId} (policy=${groupPolicy})`);
722
+ return;
723
+ }
724
+ } else if (access.decision !== "allow") {
725
+ if (access.decision === "pairing") await pairing.issueChallenge({
726
+ senderId,
727
+ senderIdLine: `Your Nextcloud user id: ${senderId}`,
728
+ meta: { name: senderName || void 0 },
729
+ sendPairingReply: async (text) => {
730
+ await sendMessageNextcloudTalk(roomToken, text, {
731
+ cfg: config,
732
+ accountId: account.accountId
733
+ });
734
+ statusSink?.({ lastOutboundAt: Date.now() });
735
+ },
736
+ onReplyError: (err) => {
737
+ runtime.error?.(`nextcloud-talk: pairing reply failed for ${senderId}: ${String(err)}`);
738
+ }
739
+ });
740
+ runtime.log?.(`nextcloud-talk: drop DM sender ${senderId} (reason=${access.reason})`);
741
+ return;
742
+ }
743
+ if (access.shouldBlockControlCommand) {
744
+ logInboundDrop({
745
+ log: (message) => runtime.log?.(message),
746
+ channel: CHANNEL_ID,
747
+ reason: "control command (unauthorized)",
748
+ target: senderId
749
+ });
750
+ return;
751
+ }
752
+ const mentionRegexes = core.channel.mentions.buildMentionRegexes(config);
753
+ const wasMentioned = mentionRegexes.length ? core.channel.mentions.matchesMentionPatterns(rawBody, mentionRegexes) : false;
754
+ const mentionGate = resolveNextcloudTalkMentionGate({
755
+ isGroup,
756
+ requireMention: isGroup ? resolveNextcloudTalkRequireMention({
757
+ roomConfig,
758
+ wildcardConfig: roomMatch.wildcardConfig
759
+ }) : false,
760
+ wasMentioned,
761
+ allowTextCommands,
762
+ hasControlCommand,
763
+ commandAuthorized
764
+ });
765
+ if (isGroup && mentionGate.shouldSkip) {
766
+ runtime.log?.(`nextcloud-talk: drop room ${roomToken} (no mention)`);
767
+ return;
768
+ }
769
+ const route = core.channel.routing.resolveAgentRoute({
770
+ cfg: config,
771
+ channel: CHANNEL_ID,
772
+ accountId: account.accountId,
773
+ peer: {
774
+ kind: isGroup ? "group" : "direct",
775
+ id: isGroup ? roomToken : senderId
776
+ }
777
+ });
778
+ const fromLabel = isGroup ? `room:${roomName || roomToken}` : senderName || `user:${senderId}`;
779
+ const storePath = core.channel.session.resolveStorePath(config.session?.store, { agentId: route.agentId });
780
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(config);
781
+ const previousTimestamp = core.channel.session.readSessionUpdatedAt({
782
+ storePath,
783
+ sessionKey: route.sessionKey
784
+ });
785
+ const body = core.channel.reply.formatAgentEnvelope({
786
+ channel: "Nextcloud Talk",
787
+ from: fromLabel,
788
+ timestamp: message.timestamp,
789
+ previousTimestamp,
790
+ envelope: envelopeOptions,
791
+ body: rawBody
792
+ });
793
+ const groupSystemPrompt = normalizeOptionalString(roomConfig?.systemPrompt);
794
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
795
+ Body: body,
796
+ BodyForAgent: rawBody,
797
+ RawBody: rawBody,
798
+ CommandBody: rawBody,
799
+ From: isGroup ? `nextcloud-talk:room:${roomToken}` : `nextcloud-talk:${senderId}`,
800
+ To: `nextcloud-talk:${roomToken}`,
801
+ SessionKey: route.sessionKey,
802
+ AccountId: route.accountId,
803
+ ChatType: isGroup ? "group" : "direct",
804
+ ConversationLabel: fromLabel,
805
+ SenderName: senderName || void 0,
806
+ SenderId: senderId,
807
+ GroupSubject: isGroup ? roomName || roomToken : void 0,
808
+ GroupSystemPrompt: isGroup ? groupSystemPrompt : void 0,
809
+ Provider: CHANNEL_ID,
810
+ Surface: CHANNEL_ID,
811
+ WasMentioned: isGroup ? wasMentioned : void 0,
812
+ MessageSid: message.messageId,
813
+ Timestamp: message.timestamp,
814
+ OriginatingChannel: CHANNEL_ID,
815
+ OriginatingTo: `nextcloud-talk:${roomToken}`,
816
+ CommandAuthorized: commandAuthorized
817
+ });
818
+ await dispatchInboundReplyWithBase({
819
+ cfg: config,
820
+ channel: CHANNEL_ID,
821
+ accountId: account.accountId,
822
+ route,
823
+ storePath,
824
+ ctxPayload,
825
+ core,
826
+ deliver: async (payload) => {
827
+ await deliverNextcloudTalkReply({
828
+ cfg: config,
829
+ payload,
830
+ roomToken,
831
+ accountId: account.accountId,
832
+ statusSink
833
+ });
834
+ },
835
+ onRecordError: (err) => {
836
+ runtime.error?.(`nextcloud-talk: failed updating session meta: ${String(err)}`);
837
+ },
838
+ onDispatchError: (err, info) => {
839
+ runtime.error?.(`nextcloud-talk ${info.kind} reply failed: ${String(err)}`);
840
+ },
841
+ replyOptions: {
842
+ skillFilter: roomConfig?.skills,
843
+ disableBlockStreaming: typeof account.config.blockStreaming === "boolean" ? !account.config.blockStreaming : void 0
844
+ }
845
+ });
846
+ }
847
+ //#endregion
848
+ //#region extensions/nextcloud-talk/src/monitor.ts
849
+ const DEFAULT_WEBHOOK_MAX_BODY_BYTES = 1024 * 1024;
850
+ const PREAUTH_WEBHOOK_MAX_BODY_BYTES = 64 * 1024;
851
+ const PREAUTH_WEBHOOK_BODY_TIMEOUT_MS = 5e3;
852
+ const HEALTH_PATH = "/healthz";
853
+ const WEBHOOK_AUTH_RATE_LIMIT_SCOPE = "nextcloud-talk-webhook-auth";
854
+ const NextcloudTalkWebhookPayloadSchema = z$1.object({
855
+ type: z$1.enum([
856
+ "Create",
857
+ "Update",
858
+ "Delete"
859
+ ]),
860
+ actor: z$1.object({
861
+ type: z$1.literal("Person"),
862
+ id: z$1.string().min(1),
863
+ name: z$1.string()
864
+ }),
865
+ object: z$1.object({
866
+ type: z$1.literal("Note"),
867
+ id: z$1.string().min(1),
868
+ name: z$1.string(),
869
+ content: z$1.string(),
870
+ mediaType: z$1.string()
871
+ }),
872
+ target: z$1.object({
873
+ type: z$1.literal("Collection"),
874
+ id: z$1.string().min(1),
875
+ name: z$1.string()
876
+ })
877
+ });
878
+ const WEBHOOK_ERRORS = {
879
+ missingSignatureHeaders: "Missing signature headers",
880
+ invalidBackend: "Invalid backend",
881
+ invalidSignature: "Invalid signature",
882
+ invalidPayloadFormat: "Invalid payload format",
883
+ payloadTooLarge: "Payload too large",
884
+ internalServerError: "Internal server error"
885
+ };
886
+ var NextcloudTalkRetryableWebhookError = class extends Error {
887
+ constructor(message, options) {
888
+ super(message, options);
889
+ this.name = "NextcloudTalkRetryableWebhookError";
890
+ }
891
+ };
892
+ async function processNextcloudTalkReplayGuardedMessage(params) {
893
+ if (await params.replayGuard.claimMessage({
894
+ accountId: params.accountId,
895
+ roomToken: params.message.roomToken,
896
+ messageId: params.message.messageId
897
+ }) !== "claimed") return "duplicate";
898
+ try {
899
+ await params.handleMessage();
900
+ await params.replayGuard.commitMessage({
901
+ accountId: params.accountId,
902
+ roomToken: params.message.roomToken,
903
+ messageId: params.message.messageId
904
+ });
905
+ return "processed";
906
+ } catch (error) {
907
+ if (error instanceof NextcloudTalkRetryableWebhookError) params.replayGuard.releaseMessage({
908
+ accountId: params.accountId,
909
+ roomToken: params.message.roomToken,
910
+ messageId: params.message.messageId,
911
+ error
912
+ });
913
+ else await params.replayGuard.commitMessage({
914
+ accountId: params.accountId,
915
+ roomToken: params.message.roomToken,
916
+ messageId: params.message.messageId
917
+ });
918
+ throw error;
919
+ }
920
+ }
921
+ function formatError(err) {
922
+ if (err instanceof Error) return err.message;
923
+ return typeof err === "string" ? err : JSON.stringify(err);
924
+ }
925
+ function parseWebhookPayload(body) {
926
+ return safeParseJsonWithSchema(NextcloudTalkWebhookPayloadSchema, body);
927
+ }
928
+ function writeJsonResponse(res, status, body) {
929
+ if (body) {
930
+ res.writeHead(status, { "Content-Type": "application/json" });
931
+ res.end(JSON.stringify(body));
932
+ return;
933
+ }
934
+ res.writeHead(status);
935
+ res.end();
936
+ }
937
+ function writeWebhookError(res, status, error) {
938
+ if (res.headersSent) return;
939
+ writeJsonResponse(res, status, { error });
940
+ }
941
+ function validateWebhookHeaders(params) {
942
+ const headers = extractNextcloudTalkHeaders(params.req.headers);
943
+ if (!headers) {
944
+ writeWebhookError(params.res, 400, WEBHOOK_ERRORS.missingSignatureHeaders);
945
+ return null;
946
+ }
947
+ if (params.isBackendAllowed && !params.isBackendAllowed(headers.backend)) {
948
+ writeWebhookError(params.res, 401, WEBHOOK_ERRORS.invalidBackend);
949
+ return null;
950
+ }
951
+ return headers;
952
+ }
953
+ function verifyWebhookSignature(params) {
954
+ if (!verifyNextcloudTalkSignature({
955
+ signature: params.headers.signature,
956
+ random: params.headers.random,
957
+ body: params.body,
958
+ secret: params.secret
959
+ })) {
960
+ params.authRateLimiter.recordFailure(params.clientIp, WEBHOOK_AUTH_RATE_LIMIT_SCOPE);
961
+ writeWebhookError(params.res, 401, WEBHOOK_ERRORS.invalidSignature);
962
+ return false;
963
+ }
964
+ params.authRateLimiter.reset(params.clientIp, WEBHOOK_AUTH_RATE_LIMIT_SCOPE);
965
+ return true;
966
+ }
967
+ function decodeWebhookCreateMessage(params) {
968
+ const payload = parseWebhookPayload(params.body);
969
+ if (!payload) {
970
+ writeWebhookError(params.res, 400, WEBHOOK_ERRORS.invalidPayloadFormat);
971
+ return { kind: "invalid" };
972
+ }
973
+ if (payload.type !== "Create") return { kind: "ignore" };
974
+ return {
975
+ kind: "message",
976
+ message: payloadToInboundMessage(payload)
977
+ };
978
+ }
979
+ function payloadToInboundMessage(payload) {
980
+ return {
981
+ messageId: payload.object.id,
982
+ roomToken: payload.target.id,
983
+ roomName: payload.target.name,
984
+ senderId: payload.actor.id,
985
+ senderName: payload.actor.name ?? "",
986
+ text: payload.object.content || payload.object.name || "",
987
+ mediaType: payload.object.mediaType || "text/plain",
988
+ timestamp: Date.now(),
989
+ isGroupChat: true
990
+ };
991
+ }
992
+ function readNextcloudTalkWebhookBody(req, maxBodyBytes) {
993
+ return readRequestBodyWithLimit(req, {
994
+ maxBytes: Math.min(maxBodyBytes, PREAUTH_WEBHOOK_MAX_BODY_BYTES),
995
+ timeoutMs: PREAUTH_WEBHOOK_BODY_TIMEOUT_MS
996
+ });
997
+ }
998
+ function createNextcloudTalkWebhookServer(opts) {
999
+ const { port, host, path, secret, onMessage, onError, abortSignal } = opts;
1000
+ const maxBodyBytes = typeof opts.maxBodyBytes === "number" && Number.isFinite(opts.maxBodyBytes) && opts.maxBodyBytes > 0 ? Math.floor(opts.maxBodyBytes) : DEFAULT_WEBHOOK_MAX_BODY_BYTES;
1001
+ const readBody = opts.readBody ?? readNextcloudTalkWebhookBody;
1002
+ const isBackendAllowed = opts.isBackendAllowed;
1003
+ const shouldProcessMessage = opts.shouldProcessMessage;
1004
+ const processMessage = opts.processMessage;
1005
+ const authRateLimitMaxRequests = typeof opts.authRateLimit?.maxRequests === "number" ? opts.authRateLimit.maxRequests : WEBHOOK_RATE_LIMIT_DEFAULTS.maxRequests;
1006
+ const authRateLimitWindowMs = typeof opts.authRateLimit?.windowMs === "number" ? opts.authRateLimit.windowMs : WEBHOOK_RATE_LIMIT_DEFAULTS.windowMs;
1007
+ const webhookAuthRateLimiter = createAuthRateLimiter({
1008
+ maxAttempts: authRateLimitMaxRequests,
1009
+ windowMs: authRateLimitWindowMs,
1010
+ lockoutMs: authRateLimitWindowMs,
1011
+ exemptLoopback: false,
1012
+ pruneIntervalMs: authRateLimitWindowMs
1013
+ });
1014
+ const server = createServer(async (req, res) => {
1015
+ if (req.url === HEALTH_PATH) {
1016
+ res.writeHead(200, { "Content-Type": "text/plain" });
1017
+ res.end("ok");
1018
+ return;
1019
+ }
1020
+ if (req.url !== path || req.method !== "POST") {
1021
+ res.writeHead(404);
1022
+ res.end();
1023
+ return;
1024
+ }
1025
+ const clientIp = req.socket.remoteAddress ?? "unknown";
1026
+ if (!webhookAuthRateLimiter.check(clientIp, WEBHOOK_AUTH_RATE_LIMIT_SCOPE).allowed) {
1027
+ res.writeHead(429);
1028
+ res.end("Too Many Requests");
1029
+ return;
1030
+ }
1031
+ try {
1032
+ const headers = validateWebhookHeaders({
1033
+ req,
1034
+ res,
1035
+ isBackendAllowed
1036
+ });
1037
+ if (!headers) return;
1038
+ const body = await readBody(req, maxBodyBytes);
1039
+ if (!verifyWebhookSignature({
1040
+ headers,
1041
+ body,
1042
+ secret,
1043
+ res,
1044
+ clientIp,
1045
+ authRateLimiter: webhookAuthRateLimiter
1046
+ })) return;
1047
+ const decoded = decodeWebhookCreateMessage({
1048
+ body,
1049
+ res
1050
+ });
1051
+ if (decoded.kind === "invalid") return;
1052
+ if (decoded.kind === "ignore") {
1053
+ writeJsonResponse(res, 200);
1054
+ return;
1055
+ }
1056
+ const message = decoded.message;
1057
+ if (processMessage) {
1058
+ writeJsonResponse(res, 200);
1059
+ try {
1060
+ await processMessage(message);
1061
+ } catch (err) {
1062
+ onError?.(err instanceof Error ? err : new Error(formatError(err)));
1063
+ }
1064
+ return;
1065
+ }
1066
+ if (shouldProcessMessage) {
1067
+ if (!await shouldProcessMessage(message)) {
1068
+ writeJsonResponse(res, 200);
1069
+ return;
1070
+ }
1071
+ }
1072
+ writeJsonResponse(res, 200);
1073
+ try {
1074
+ await onMessage(message);
1075
+ } catch (err) {
1076
+ onError?.(err instanceof Error ? err : new Error(formatError(err)));
1077
+ }
1078
+ } catch (err) {
1079
+ if (isRequestBodyLimitError(err, "PAYLOAD_TOO_LARGE")) {
1080
+ writeWebhookError(res, 413, WEBHOOK_ERRORS.payloadTooLarge);
1081
+ return;
1082
+ }
1083
+ if (isRequestBodyLimitError(err, "REQUEST_BODY_TIMEOUT")) {
1084
+ writeWebhookError(res, 408, requestBodyErrorToText("REQUEST_BODY_TIMEOUT"));
1085
+ return;
1086
+ }
1087
+ const error = err instanceof Error ? err : new Error(formatError(err));
1088
+ onError?.(error);
1089
+ writeWebhookError(res, 500, WEBHOOK_ERRORS.internalServerError);
1090
+ }
1091
+ });
1092
+ const start = () => {
1093
+ return new Promise((resolve) => {
1094
+ server.listen(port, host, () => resolve());
1095
+ });
1096
+ };
1097
+ let stopped = false;
1098
+ const stop = () => {
1099
+ if (stopped) return;
1100
+ stopped = true;
1101
+ try {
1102
+ server.close();
1103
+ } catch {}
1104
+ };
1105
+ if (abortSignal) if (abortSignal.aborted) stop();
1106
+ else abortSignal.addEventListener("abort", stop, { once: true });
1107
+ return {
1108
+ server,
1109
+ start,
1110
+ stop
1111
+ };
1112
+ }
1113
+ //#endregion
1114
+ //#region extensions/nextcloud-talk/src/replay-guard.ts
1115
+ const DEFAULT_REPLAY_TTL_MS = 1440 * 60 * 1e3;
1116
+ const DEFAULT_MEMORY_MAX_SIZE = 1e3;
1117
+ const DEFAULT_FILE_MAX_ENTRIES = 1e4;
1118
+ function sanitizeSegment(value) {
1119
+ const trimmed = value.trim();
1120
+ if (!trimmed) return "default";
1121
+ return trimmed.replace(/[^a-zA-Z0-9_-]/g, "_");
1122
+ }
1123
+ function buildReplayKey(params) {
1124
+ const roomToken = params.roomToken.trim();
1125
+ const messageId = params.messageId.trim();
1126
+ if (!roomToken || !messageId) return null;
1127
+ return `${roomToken}:${messageId}`;
1128
+ }
1129
+ function createNextcloudTalkReplayGuard(options) {
1130
+ const stateDir = options.stateDir?.trim();
1131
+ const baseOptions = {
1132
+ ttlMs: options.ttlMs ?? DEFAULT_REPLAY_TTL_MS,
1133
+ memoryMaxSize: options.memoryMaxSize ?? DEFAULT_MEMORY_MAX_SIZE
1134
+ };
1135
+ const dedupe = createClaimableDedupe(stateDir ? {
1136
+ ...baseOptions,
1137
+ fileMaxEntries: options.fileMaxEntries ?? DEFAULT_FILE_MAX_ENTRIES,
1138
+ resolveFilePath: (namespace) => path.join(stateDir, "nextcloud-talk", "replay-dedupe", `${sanitizeSegment(namespace)}.json`),
1139
+ onDiskError: options.onDiskError
1140
+ } : baseOptions);
1141
+ return {
1142
+ claimMessage: async ({ accountId, roomToken, messageId }) => {
1143
+ const replayKey = buildReplayKey({
1144
+ roomToken,
1145
+ messageId
1146
+ });
1147
+ if (!replayKey) return "invalid";
1148
+ return (await dedupe.claim(replayKey, { namespace: accountId })).kind;
1149
+ },
1150
+ commitMessage: async ({ accountId, roomToken, messageId }) => {
1151
+ const replayKey = buildReplayKey({
1152
+ roomToken,
1153
+ messageId
1154
+ });
1155
+ if (!replayKey) return true;
1156
+ return await dedupe.commit(replayKey, { namespace: accountId });
1157
+ },
1158
+ releaseMessage: ({ accountId, roomToken, messageId, error }) => {
1159
+ const replayKey = buildReplayKey({
1160
+ roomToken,
1161
+ messageId
1162
+ });
1163
+ if (!replayKey) return;
1164
+ dedupe.release(replayKey, {
1165
+ namespace: accountId,
1166
+ error
1167
+ });
1168
+ },
1169
+ shouldProcessMessage: async ({ accountId, roomToken, messageId }) => {
1170
+ const replayKey = buildReplayKey({
1171
+ roomToken,
1172
+ messageId
1173
+ });
1174
+ if (!replayKey) return true;
1175
+ if ((await dedupe.claim(replayKey, { namespace: accountId })).kind !== "claimed") return false;
1176
+ return await dedupe.commit(replayKey, { namespace: accountId });
1177
+ }
1178
+ };
1179
+ }
1180
+ //#endregion
1181
+ //#region extensions/nextcloud-talk/src/monitor-runtime.ts
1182
+ const DEFAULT_WEBHOOK_PORT = 8788;
1183
+ const DEFAULT_WEBHOOK_HOST = "0.0.0.0";
1184
+ const DEFAULT_WEBHOOK_PATH = "/nextcloud-talk-webhook";
1185
+ function normalizeOrigin(value) {
1186
+ try {
1187
+ return normalizeLowercaseStringOrEmpty(new URL(value).origin);
1188
+ } catch {
1189
+ return null;
1190
+ }
1191
+ }
1192
+ async function monitorNextcloudTalkProvider(opts) {
1193
+ const core = getNextcloudTalkRuntime();
1194
+ const cfg = opts.config ?? core.config.current();
1195
+ const account = resolveNextcloudTalkAccount({
1196
+ cfg,
1197
+ accountId: opts.accountId
1198
+ });
1199
+ const runtime = resolveLoggerBackedRuntime(opts.runtime, core.logging.getChildLogger());
1200
+ if (!account.secret) throw new Error(`Nextcloud Talk bot secret not configured for account "${account.accountId}"`);
1201
+ const port = account.config.webhookPort ?? DEFAULT_WEBHOOK_PORT;
1202
+ const host = account.config.webhookHost ?? DEFAULT_WEBHOOK_HOST;
1203
+ const path = account.config.webhookPath ?? DEFAULT_WEBHOOK_PATH;
1204
+ const logger = core.logging.getChildLogger({
1205
+ channel: "nextcloud-talk",
1206
+ accountId: account.accountId
1207
+ });
1208
+ const expectedBackendOrigin = normalizeOrigin(account.baseUrl);
1209
+ const replayGuard = createNextcloudTalkReplayGuard({
1210
+ stateDir: core.state.resolveStateDir(process.env, os.homedir),
1211
+ onDiskError: (error) => {
1212
+ logger.warn(`[nextcloud-talk:${account.accountId}] replay guard disk error: ${String(error)}`);
1213
+ }
1214
+ });
1215
+ const { start, stop } = createNextcloudTalkWebhookServer({
1216
+ port,
1217
+ host,
1218
+ path,
1219
+ secret: account.secret,
1220
+ isBackendAllowed: (backend) => {
1221
+ if (!expectedBackendOrigin) return true;
1222
+ return normalizeOrigin(backend) === expectedBackendOrigin;
1223
+ },
1224
+ processMessage: async (message) => {
1225
+ if (await processNextcloudTalkReplayGuardedMessage({
1226
+ replayGuard,
1227
+ accountId: account.accountId,
1228
+ message,
1229
+ handleMessage: async () => {
1230
+ core.channel.activity.record({
1231
+ channel: "nextcloud-talk",
1232
+ accountId: account.accountId,
1233
+ direction: "inbound",
1234
+ at: message.timestamp
1235
+ });
1236
+ if (opts.onMessage) await opts.onMessage(message);
1237
+ else await handleNextcloudTalkInbound({
1238
+ message,
1239
+ account,
1240
+ config: cfg,
1241
+ runtime,
1242
+ statusSink: opts.statusSink
1243
+ });
1244
+ }
1245
+ }) === "duplicate") {
1246
+ logger.warn(`[nextcloud-talk:${account.accountId}] replayed webhook ignored room=${message.roomToken} messageId=${message.messageId}`);
1247
+ return;
1248
+ }
1249
+ },
1250
+ onMessage: async () => {},
1251
+ onError: (error) => {
1252
+ logger.error(`[nextcloud-talk:${account.accountId}] webhook error: ${error.message}`);
1253
+ },
1254
+ abortSignal: opts.abortSignal
1255
+ });
1256
+ if (opts.abortSignal?.aborted) return { stop };
1257
+ await start();
1258
+ if (opts.abortSignal?.aborted) {
1259
+ stop();
1260
+ return { stop };
1261
+ }
1262
+ const publicUrl = account.config.webhookPublicUrl ?? `http://${host === "0.0.0.0" ? "localhost" : host}:${port}${path}`;
1263
+ logger.info(`[nextcloud-talk:${account.accountId}] webhook listening on ${publicUrl}`);
1264
+ return { stop };
1265
+ }
1266
+ //#endregion
1267
+ //#region extensions/nextcloud-talk/src/gateway.ts
1268
+ const nextcloudTalkGatewayAdapter = {
1269
+ startAccount: async (ctx) => {
1270
+ const account = ctx.account;
1271
+ if (!account.secret || !account.baseUrl) throw new Error(`Nextcloud Talk not configured for account "${account.accountId}" (missing secret or baseUrl)`);
1272
+ ctx.log?.info(`[${account.accountId}] starting Nextcloud Talk webhook server`);
1273
+ const statusSink = createAccountStatusSink({
1274
+ accountId: ctx.accountId,
1275
+ setStatus: ctx.setStatus
1276
+ });
1277
+ await runStoppablePassiveMonitor({
1278
+ abortSignal: ctx.abortSignal,
1279
+ start: async () => await monitorNextcloudTalkProvider({
1280
+ accountId: account.accountId,
1281
+ config: ctx.cfg,
1282
+ runtime: ctx.runtime,
1283
+ abortSignal: ctx.abortSignal,
1284
+ statusSink
1285
+ })
1286
+ });
1287
+ },
1288
+ logoutAccount: async ({ accountId, cfg }) => {
1289
+ const nextCfg = { ...cfg };
1290
+ const nextSection = cfg.channels?.["nextcloud-talk"] ? { ...cfg.channels["nextcloud-talk"] } : void 0;
1291
+ let cleared = false;
1292
+ let changed = false;
1293
+ if (nextSection) {
1294
+ if (accountId === DEFAULT_ACCOUNT_ID$2 && nextSection.botSecret) {
1295
+ delete nextSection.botSecret;
1296
+ cleared = true;
1297
+ changed = true;
1298
+ }
1299
+ const accountCleanup = clearAccountEntryFields({
1300
+ accounts: nextSection.accounts,
1301
+ accountId,
1302
+ fields: ["botSecret"]
1303
+ });
1304
+ if (accountCleanup.changed) {
1305
+ changed = true;
1306
+ if (accountCleanup.cleared) cleared = true;
1307
+ if (accountCleanup.nextAccounts) nextSection.accounts = accountCleanup.nextAccounts;
1308
+ else delete nextSection.accounts;
1309
+ }
1310
+ }
1311
+ if (changed) if (nextSection && Object.keys(nextSection).length > 0) nextCfg.channels = {
1312
+ ...nextCfg.channels,
1313
+ "nextcloud-talk": nextSection
1314
+ };
1315
+ else {
1316
+ const nextChannels = { ...nextCfg.channels };
1317
+ delete nextChannels["nextcloud-talk"];
1318
+ if (Object.keys(nextChannels).length > 0) nextCfg.channels = nextChannels;
1319
+ else delete nextCfg.channels;
1320
+ }
1321
+ const loggedOut = resolveNextcloudTalkAccount({
1322
+ cfg: changed ? nextCfg : cfg,
1323
+ accountId
1324
+ }).secretSource === "none";
1325
+ if (changed) await getNextcloudTalkRuntime().config.replaceConfigFile({
1326
+ nextConfig: nextCfg,
1327
+ afterWrite: { mode: "auto" }
1328
+ });
1329
+ return {
1330
+ cleared,
1331
+ envSecret: Boolean(process.env.NEXTCLOUD_TALK_BOT_SECRET?.trim()),
1332
+ loggedOut
1333
+ };
1334
+ }
1335
+ };
1336
+ //#endregion
1337
+ //#region extensions/nextcloud-talk/src/session-route.ts
1338
+ function resolveNextcloudTalkOutboundSessionRoute(params) {
1339
+ const roomId = stripNextcloudTalkTargetPrefix(params.target);
1340
+ if (!roomId) return null;
1341
+ const baseSessionKey = buildOutboundBaseSessionKey({
1342
+ cfg: params.cfg,
1343
+ agentId: params.agentId,
1344
+ channel: "nextcloud-talk",
1345
+ accountId: params.accountId,
1346
+ peer: {
1347
+ kind: "group",
1348
+ id: roomId
1349
+ }
1350
+ });
1351
+ return {
1352
+ sessionKey: baseSessionKey,
1353
+ baseSessionKey,
1354
+ peer: {
1355
+ kind: "group",
1356
+ id: roomId
1357
+ },
1358
+ chatType: "group",
1359
+ from: `nextcloud-talk:room:${roomId}`,
1360
+ to: `nextcloud-talk:${roomId}`
1361
+ };
1362
+ }
1363
+ //#endregion
1364
+ //#region extensions/nextcloud-talk/src/setup-core.ts
1365
+ const channel$1 = "nextcloud-talk";
1366
+ function addWildcardAllowFrom(allowFrom) {
1367
+ return mergeAllowFromEntries(allowFrom, ["*"]);
1368
+ }
1369
+ function normalizeNextcloudTalkBaseUrl(value) {
1370
+ return value?.trim().replace(/\/+$/, "") ?? "";
1371
+ }
1372
+ function validateNextcloudTalkBaseUrl(value) {
1373
+ if (!value) return "Required";
1374
+ if (!value.startsWith("http://") && !value.startsWith("https://")) return "URL must start with http:// or https://";
1375
+ }
1376
+ function setNextcloudTalkAccountConfig(cfg, accountId, updates) {
1377
+ return patchScopedAccountConfig({
1378
+ cfg,
1379
+ channelKey: channel$1,
1380
+ accountId,
1381
+ patch: updates
1382
+ });
1383
+ }
1384
+ function clearNextcloudTalkAccountFields(cfg, accountId, fields) {
1385
+ const section = cfg.channels?.["nextcloud-talk"];
1386
+ if (!section) return cfg;
1387
+ if (accountId === DEFAULT_ACCOUNT_ID$1) {
1388
+ const nextSection = { ...section };
1389
+ for (const field of fields) delete nextSection[field];
1390
+ return {
1391
+ ...cfg,
1392
+ channels: {
1393
+ ...cfg.channels,
1394
+ "nextcloud-talk": nextSection
1395
+ }
1396
+ };
1397
+ }
1398
+ const currentAccount = section.accounts?.[accountId];
1399
+ if (!currentAccount) return cfg;
1400
+ const nextAccount = { ...currentAccount };
1401
+ for (const field of fields) delete nextAccount[field];
1402
+ return {
1403
+ ...cfg,
1404
+ channels: {
1405
+ ...cfg.channels,
1406
+ "nextcloud-talk": {
1407
+ ...section,
1408
+ accounts: {
1409
+ ...section.accounts,
1410
+ [accountId]: nextAccount
1411
+ }
1412
+ }
1413
+ }
1414
+ };
1415
+ }
1416
+ async function promptNextcloudTalkAllowFrom(params) {
1417
+ return await promptParsedAllowFromForAccount({
1418
+ cfg: params.cfg,
1419
+ accountId: params.accountId,
1420
+ defaultAccountId: params.accountId,
1421
+ prompter: params.prompter,
1422
+ noteTitle: "Nextcloud Talk user id",
1423
+ noteLines: [
1424
+ "1) Check the Nextcloud admin panel for user IDs",
1425
+ "2) Or look at the webhook payload logs when someone messages",
1426
+ "3) User IDs are typically lowercase usernames in Nextcloud",
1427
+ `Docs: ${formatDocsLink$1("/channels/nextcloud-talk", "nextcloud-talk")}`
1428
+ ],
1429
+ message: "Nextcloud Talk allowFrom (user id)",
1430
+ placeholder: "username",
1431
+ parseEntries: (raw) => ({ entries: raw.split(/[\n,;]+/g).map(normalizeLowercaseStringOrEmpty).filter(Boolean) }),
1432
+ getExistingAllowFrom: ({ cfg, accountId }) => resolveNextcloudTalkAccount({
1433
+ cfg,
1434
+ accountId
1435
+ }).config.allowFrom ?? [],
1436
+ mergeEntries: ({ existing, parsed }) => mergeAllowFromEntries(existing.map((value) => normalizeLowercaseStringOrEmpty(String(value))), parsed),
1437
+ applyAllowFrom: ({ cfg, accountId, allowFrom }) => setNextcloudTalkAccountConfig(cfg, accountId, {
1438
+ dmPolicy: "allowlist",
1439
+ allowFrom
1440
+ })
1441
+ });
1442
+ }
1443
+ async function promptNextcloudTalkAllowFromForAccount(params) {
1444
+ const accountId = resolveSetupAccountId({
1445
+ accountId: params.accountId,
1446
+ defaultAccountId: resolveDefaultNextcloudTalkAccountId(params.cfg)
1447
+ });
1448
+ return await promptNextcloudTalkAllowFrom({
1449
+ cfg: params.cfg,
1450
+ prompter: params.prompter,
1451
+ accountId
1452
+ });
1453
+ }
1454
+ const nextcloudTalkDmPolicy = {
1455
+ label: "Nextcloud Talk",
1456
+ channel: channel$1,
1457
+ policyKey: "channels.nextcloud-talk.dmPolicy",
1458
+ allowFromKey: "channels.nextcloud-talk.allowFrom",
1459
+ resolveConfigKeys: (cfg, accountId) => (accountId ?? resolveDefaultNextcloudTalkAccountId(cfg)) !== DEFAULT_ACCOUNT_ID$1 ? {
1460
+ policyKey: `channels.nextcloud-talk.accounts.${accountId ?? resolveDefaultNextcloudTalkAccountId(cfg)}.dmPolicy`,
1461
+ allowFromKey: `channels.nextcloud-talk.accounts.${accountId ?? resolveDefaultNextcloudTalkAccountId(cfg)}.allowFrom`
1462
+ } : {
1463
+ policyKey: "channels.nextcloud-talk.dmPolicy",
1464
+ allowFromKey: "channels.nextcloud-talk.allowFrom"
1465
+ },
1466
+ getCurrent: (cfg, accountId) => resolveNextcloudTalkAccount({
1467
+ cfg,
1468
+ accountId: accountId ?? resolveDefaultNextcloudTalkAccountId(cfg)
1469
+ }).config.dmPolicy ?? "pairing",
1470
+ setPolicy: (cfg, policy, accountId) => {
1471
+ const resolvedAccountId = accountId ?? resolveDefaultNextcloudTalkAccountId(cfg);
1472
+ const resolved = resolveNextcloudTalkAccount({
1473
+ cfg,
1474
+ accountId: resolvedAccountId
1475
+ });
1476
+ return setNextcloudTalkAccountConfig(cfg, resolvedAccountId, {
1477
+ dmPolicy: policy,
1478
+ ...policy === "open" ? { allowFrom: addWildcardAllowFrom(resolved.config.allowFrom) } : {}
1479
+ });
1480
+ },
1481
+ promptAllowFrom: promptNextcloudTalkAllowFromForAccount
1482
+ };
1483
+ const nextcloudTalkSetupAdapter = {
1484
+ resolveAccountId: ({ accountId }) => normalizeAccountId$1(accountId),
1485
+ applyAccountName: ({ cfg, accountId, name }) => applyAccountNameToChannelSection({
1486
+ cfg,
1487
+ channelKey: channel$1,
1488
+ accountId,
1489
+ name
1490
+ }),
1491
+ validateInput: createSetupInputPresenceValidator({
1492
+ defaultAccountOnlyEnvError: "NEXTCLOUD_TALK_BOT_SECRET can only be used for the default account.",
1493
+ validate: ({ input }) => {
1494
+ const setupInput = input;
1495
+ if (!setupInput.useEnv && !setupInput.secret && !setupInput.secretFile) return "Nextcloud Talk requires bot secret or --secret-file (or --use-env).";
1496
+ if (!setupInput.baseUrl) return "Nextcloud Talk requires --base-url.";
1497
+ return null;
1498
+ }
1499
+ }),
1500
+ applyAccountConfig: ({ cfg, accountId, input }) => {
1501
+ const setupInput = input;
1502
+ const namedConfig = applyAccountNameToChannelSection({
1503
+ cfg,
1504
+ channelKey: channel$1,
1505
+ accountId,
1506
+ name: setupInput.name
1507
+ });
1508
+ return setNextcloudTalkAccountConfig(setupInput.useEnv ? clearNextcloudTalkAccountFields(namedConfig, accountId, ["botSecret", "botSecretFile"]) : namedConfig, accountId, {
1509
+ baseUrl: normalizeNextcloudTalkBaseUrl(setupInput.baseUrl),
1510
+ ...setupInput.useEnv ? {} : setupInput.secretFile ? { botSecretFile: setupInput.secretFile } : setupInput.secret ? { botSecret: setupInput.secret } : {}
1511
+ });
1512
+ }
1513
+ };
1514
+ //#endregion
1515
+ //#region extensions/nextcloud-talk/src/setup-surface.ts
1516
+ const channel = "nextcloud-talk";
1517
+ const CONFIGURE_API_FLAG = "__nextcloudTalkConfigureApiCredentials";
1518
+ const nextcloudTalkSetupWizard = {
1519
+ channel,
1520
+ stepOrder: "text-first",
1521
+ status: createStandardChannelSetupStatus({
1522
+ channelLabel: "Nextcloud Talk",
1523
+ configuredLabel: "configured",
1524
+ unconfiguredLabel: "needs setup",
1525
+ configuredHint: "configured",
1526
+ unconfiguredHint: "self-hosted chat",
1527
+ configuredScore: 1,
1528
+ unconfiguredScore: 5,
1529
+ resolveConfigured: ({ cfg, accountId }) => {
1530
+ const account = resolveNextcloudTalkAccount({
1531
+ cfg,
1532
+ accountId
1533
+ });
1534
+ return Boolean(account.secret && account.baseUrl);
1535
+ }
1536
+ }),
1537
+ introNote: {
1538
+ title: "Nextcloud Talk bot setup",
1539
+ lines: [
1540
+ "1) SSH into your Nextcloud server",
1541
+ "2) Run: ./occ talk:bot:install \"OpenClaw\" \"<shared-secret>\" \"<webhook-url>\" --feature reaction",
1542
+ "3) Copy the shared secret you used in the command",
1543
+ "4) Enable the bot in your Nextcloud Talk room settings",
1544
+ "Tip: you can also set NEXTCLOUD_TALK_BOT_SECRET in your env.",
1545
+ `Docs: ${formatDocsLink("/channels/nextcloud-talk", "channels/nextcloud-talk")}`
1546
+ ],
1547
+ shouldShow: ({ cfg, accountId }) => {
1548
+ const account = resolveNextcloudTalkAccount({
1549
+ cfg,
1550
+ accountId
1551
+ });
1552
+ return !account.secret || !account.baseUrl;
1553
+ }
1554
+ },
1555
+ prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
1556
+ const resolvedAccount = resolveNextcloudTalkAccount({
1557
+ cfg,
1558
+ accountId
1559
+ });
1560
+ const hasApiCredentials = Boolean(resolvedAccount.config.apiUser?.trim() && (hasConfiguredSecretInput(resolvedAccount.config.apiPassword) || resolvedAccount.config.apiPasswordFile));
1561
+ if (!await prompter.confirm({
1562
+ message: "Configure optional Nextcloud Talk API credentials for room lookups?",
1563
+ initialValue: hasApiCredentials
1564
+ })) return;
1565
+ return { credentialValues: {
1566
+ ...credentialValues,
1567
+ [CONFIGURE_API_FLAG]: "1"
1568
+ } };
1569
+ },
1570
+ credentials: [{
1571
+ inputKey: "token",
1572
+ providerHint: channel,
1573
+ credentialLabel: "bot secret",
1574
+ preferredEnvVar: "NEXTCLOUD_TALK_BOT_SECRET",
1575
+ envPrompt: "NEXTCLOUD_TALK_BOT_SECRET detected. Use env var?",
1576
+ keepPrompt: "Nextcloud Talk bot secret already configured. Keep it?",
1577
+ inputPrompt: "Enter Nextcloud Talk bot secret",
1578
+ allowEnv: ({ accountId }) => accountId === DEFAULT_ACCOUNT_ID$1,
1579
+ inspect: ({ cfg, accountId }) => {
1580
+ const resolvedAccount = resolveNextcloudTalkAccount({
1581
+ cfg,
1582
+ accountId
1583
+ });
1584
+ return {
1585
+ accountConfigured: Boolean(resolvedAccount.secret && resolvedAccount.baseUrl),
1586
+ hasConfiguredValue: Boolean(hasConfiguredSecretInput(resolvedAccount.config.botSecret) || resolvedAccount.config.botSecretFile),
1587
+ resolvedValue: resolvedAccount.secret || void 0,
1588
+ envValue: accountId === DEFAULT_ACCOUNT_ID$1 ? normalizeOptionalString(process.env.NEXTCLOUD_TALK_BOT_SECRET) : void 0
1589
+ };
1590
+ },
1591
+ applyUseEnv: async (params) => {
1592
+ const resolvedAccount = resolveNextcloudTalkAccount({
1593
+ cfg: params.cfg,
1594
+ accountId: params.accountId
1595
+ });
1596
+ return setNextcloudTalkAccountConfig(clearNextcloudTalkAccountFields(params.cfg, params.accountId, ["botSecret", "botSecretFile"]), params.accountId, { baseUrl: resolvedAccount.baseUrl });
1597
+ },
1598
+ applySet: async (params) => setNextcloudTalkAccountConfig(clearNextcloudTalkAccountFields(params.cfg, params.accountId, ["botSecret", "botSecretFile"]), params.accountId, { botSecret: params.value })
1599
+ }, {
1600
+ inputKey: "password",
1601
+ providerHint: "nextcloud-talk-api",
1602
+ credentialLabel: "API password",
1603
+ preferredEnvVar: "NEXTCLOUD_TALK_API_PASSWORD",
1604
+ envPrompt: "",
1605
+ keepPrompt: "Nextcloud Talk API password already configured. Keep it?",
1606
+ inputPrompt: "Enter Nextcloud Talk API password",
1607
+ inspect: ({ cfg, accountId }) => {
1608
+ const resolvedAccount = resolveNextcloudTalkAccount({
1609
+ cfg,
1610
+ accountId
1611
+ });
1612
+ const apiUser = resolvedAccount.config.apiUser?.trim();
1613
+ const apiPasswordConfigured = Boolean(hasConfiguredSecretInput(resolvedAccount.config.apiPassword) || resolvedAccount.config.apiPasswordFile);
1614
+ return {
1615
+ accountConfigured: Boolean(apiUser && apiPasswordConfigured),
1616
+ hasConfiguredValue: apiPasswordConfigured
1617
+ };
1618
+ },
1619
+ shouldPrompt: ({ credentialValues }) => credentialValues[CONFIGURE_API_FLAG] === "1",
1620
+ applySet: async (params) => setNextcloudTalkAccountConfig(clearNextcloudTalkAccountFields(params.cfg, params.accountId, ["apiPassword", "apiPasswordFile"]), params.accountId, { apiPassword: params.value })
1621
+ }],
1622
+ textInputs: [{
1623
+ inputKey: "httpUrl",
1624
+ message: "Enter Nextcloud instance URL (e.g., https://cloud.example.com)",
1625
+ currentValue: ({ cfg, accountId }) => resolveNextcloudTalkAccount({
1626
+ cfg,
1627
+ accountId
1628
+ }).baseUrl || void 0,
1629
+ shouldPrompt: ({ currentValue }) => !currentValue,
1630
+ validate: ({ value }) => validateNextcloudTalkBaseUrl(value),
1631
+ normalizeValue: ({ value }) => normalizeNextcloudTalkBaseUrl(value),
1632
+ applySet: async (params) => setNextcloudTalkAccountConfig(params.cfg, params.accountId, { baseUrl: params.value })
1633
+ }, {
1634
+ inputKey: "userId",
1635
+ message: "Nextcloud Talk API user",
1636
+ currentValue: ({ cfg, accountId }) => resolveNextcloudTalkAccount({
1637
+ cfg,
1638
+ accountId
1639
+ }).config.apiUser?.trim() || void 0,
1640
+ shouldPrompt: ({ credentialValues }) => credentialValues[CONFIGURE_API_FLAG] === "1",
1641
+ validate: ({ value }) => value ? void 0 : "Required",
1642
+ applySet: async (params) => setNextcloudTalkAccountConfig(params.cfg, params.accountId, { apiUser: params.value })
1643
+ }],
1644
+ dmPolicy: nextcloudTalkDmPolicy,
1645
+ disable: (cfg) => setSetupChannelEnabled(cfg, channel, false)
1646
+ };
1647
+ //#endregion
1648
+ //#region extensions/nextcloud-talk/src/channel.ts
1649
+ const meta = {
1650
+ id: "nextcloud-talk",
1651
+ label: "Nextcloud Talk",
1652
+ selectionLabel: "Nextcloud Talk (self-hosted)",
1653
+ docsPath: "/channels/nextcloud-talk",
1654
+ docsLabel: "nextcloud-talk",
1655
+ blurb: "Self-hosted chat via Nextcloud Talk webhook bots.",
1656
+ aliases: ["nc-talk", "nc"],
1657
+ order: 65,
1658
+ quickstartAllowFrom: true
1659
+ };
1660
+ const collectNextcloudTalkSecurityWarnings = createAllowlistProviderRouteAllowlistWarningCollector({
1661
+ providerConfigPresent: (cfg) => cfg.channels?.["nextcloud-talk"] !== void 0,
1662
+ resolveGroupPolicy: (account) => account.config.groupPolicy,
1663
+ resolveRouteAllowlistConfigured: (account) => Boolean(account.config.rooms) && Object.keys(account.config.rooms ?? {}).length > 0,
1664
+ restrictSenders: {
1665
+ surface: "Nextcloud Talk rooms",
1666
+ openScope: "any member in allowed rooms",
1667
+ groupPolicyPath: "channels.nextcloud-talk.groupPolicy",
1668
+ groupAllowFromPath: "channels.nextcloud-talk.groupAllowFrom"
1669
+ },
1670
+ noRouteAllowlist: {
1671
+ surface: "Nextcloud Talk rooms",
1672
+ routeAllowlistPath: "channels.nextcloud-talk.rooms",
1673
+ routeScope: "room",
1674
+ groupPolicyPath: "channels.nextcloud-talk.groupPolicy",
1675
+ groupAllowFromPath: "channels.nextcloud-talk.groupAllowFrom"
1676
+ }
1677
+ });
1678
+ const nextcloudTalkPlugin = createChatChannelPlugin({
1679
+ base: {
1680
+ id: "nextcloud-talk",
1681
+ meta,
1682
+ setupWizard: nextcloudTalkSetupWizard,
1683
+ capabilities: {
1684
+ chatTypes: ["direct", "group"],
1685
+ reactions: true,
1686
+ threads: false,
1687
+ media: true,
1688
+ nativeCommands: false,
1689
+ blockStreaming: true
1690
+ },
1691
+ reload: { configPrefixes: ["channels.nextcloud-talk"] },
1692
+ configSchema: buildChannelConfigSchema(NextcloudTalkConfigSchema),
1693
+ config: {
1694
+ ...nextcloudTalkConfigAdapter,
1695
+ isConfigured: (account) => Boolean(account.secret?.trim() && account.baseUrl?.trim()),
1696
+ describeAccount: (account) => describeWebhookAccountSnapshot({
1697
+ account,
1698
+ configured: Boolean(account.secret?.trim() && account.baseUrl?.trim()),
1699
+ extra: {
1700
+ secretSource: account.secretSource,
1701
+ baseUrl: account.baseUrl ? "[set]" : "[missing]"
1702
+ }
1703
+ })
1704
+ },
1705
+ approvalCapability: nextcloudTalkApprovalAuth,
1706
+ doctor: nextcloudTalkDoctor,
1707
+ groups: {
1708
+ resolveRequireMention: ({ cfg, accountId, groupId }) => {
1709
+ const rooms = resolveNextcloudTalkAccount({
1710
+ cfg,
1711
+ accountId
1712
+ }).config.rooms;
1713
+ if (!rooms || !groupId) return true;
1714
+ const roomConfig = rooms[groupId];
1715
+ if (roomConfig?.requireMention !== void 0) return roomConfig.requireMention;
1716
+ const wildcardConfig = rooms["*"];
1717
+ if (wildcardConfig?.requireMention !== void 0) return wildcardConfig.requireMention;
1718
+ return true;
1719
+ },
1720
+ resolveToolPolicy: resolveNextcloudTalkGroupToolPolicy
1721
+ },
1722
+ messaging: {
1723
+ targetPrefixes: [
1724
+ "nextcloud-talk",
1725
+ "nc-talk",
1726
+ "nc"
1727
+ ],
1728
+ normalizeTarget: normalizeNextcloudTalkMessagingTarget,
1729
+ resolveOutboundSessionRoute: (params) => resolveNextcloudTalkOutboundSessionRoute(params),
1730
+ targetResolver: {
1731
+ looksLikeId: looksLikeNextcloudTalkTargetId,
1732
+ hint: "<roomToken>"
1733
+ }
1734
+ },
1735
+ secrets: {
1736
+ secretTargetRegistryEntries,
1737
+ collectRuntimeConfigAssignments
1738
+ },
1739
+ setup: nextcloudTalkSetupAdapter,
1740
+ status: createComputedAccountStatusAdapter({
1741
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID$2),
1742
+ buildChannelSummary: ({ snapshot }) => buildWebhookChannelStatusSummary(snapshot, { secretSource: snapshot.secretSource ?? "none" }),
1743
+ resolveAccountSnapshot: ({ account }) => ({
1744
+ accountId: account.accountId,
1745
+ name: account.name,
1746
+ enabled: account.enabled,
1747
+ configured: Boolean(account.secret?.trim() && account.baseUrl?.trim()),
1748
+ extra: {
1749
+ secretSource: account.secretSource,
1750
+ baseUrl: account.baseUrl ? "[set]" : "[missing]",
1751
+ mode: "webhook"
1752
+ }
1753
+ })
1754
+ }),
1755
+ gateway: nextcloudTalkGatewayAdapter
1756
+ },
1757
+ pairing: { text: {
1758
+ ...nextcloudTalkPairingTextAdapter,
1759
+ notify: createLoggedPairingApprovalNotifier(({ id }) => `[nextcloud-talk] User ${id} approved for pairing`)
1760
+ } },
1761
+ security: {
1762
+ ...nextcloudTalkSecurityAdapter,
1763
+ collectWarnings: collectNextcloudTalkSecurityWarnings
1764
+ },
1765
+ outbound: {
1766
+ base: {
1767
+ deliveryMode: "direct",
1768
+ chunker: (text, limit) => getNextcloudTalkRuntime().channel.text.chunkMarkdownText(text, limit),
1769
+ chunkerMode: "markdown",
1770
+ textChunkLimit: 4e3
1771
+ },
1772
+ attachedResults: {
1773
+ channel: "nextcloud-talk",
1774
+ sendText: async ({ cfg, to, text, accountId, replyToId }) => await sendMessageNextcloudTalk(to, text, {
1775
+ accountId: accountId ?? void 0,
1776
+ replyTo: replyToId ?? void 0,
1777
+ cfg
1778
+ }),
1779
+ sendMedia: async ({ cfg, to, text, mediaUrl, accountId, replyToId }) => await sendMessageNextcloudTalk(to, mediaUrl ? `${text}\n\nAttachment: ${mediaUrl}` : text, {
1780
+ accountId: accountId ?? void 0,
1781
+ replyTo: replyToId ?? void 0,
1782
+ cfg
1783
+ })
1784
+ }
1785
+ }
1786
+ });
1787
+ //#endregion
1788
+ export { nextcloudTalkPlugin as t };