@zhin.js/core 1.5.16 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -195
- package/lib/ai-completion-contract.d.ts +135 -0
- package/lib/ai-completion-contract.js +69 -0
- package/lib/built/ai-access.d.ts +2 -21
- package/lib/built/ai-access.js +1 -46
- package/lib/built/ai-outbound/index.d.ts +0 -2
- package/lib/built/ai-outbound/index.js +0 -2
- package/lib/built/ai-outbound/prompt.d.ts +2 -0
- package/lib/built/ai-outbound/prompt.js +2 -0
- package/lib/built/ai-outbound/types.d.ts +1 -10
- package/lib/built/ai-trigger.d.ts +39 -78
- package/lib/built/ai-trigger.js +3 -254
- package/lib/built/common-adapter-tools.d.ts +21 -6
- package/lib/built/common-adapter-tools.js +28 -17
- package/lib/built/generic-segment-mapper.js +4 -1
- package/lib/built/html-segment-fallback.d.ts +6 -7
- package/lib/built/html-segment-fallback.js +1 -16
- package/lib/built/html-to-text.d.ts +0 -3
- package/lib/built/html-to-text.js +131 -40
- package/lib/built/interaction-messages.d.ts +1 -0
- package/lib/built/interaction-messages.js +30 -0
- package/lib/built/interactive-segments/action.d.ts +3 -4
- package/lib/built/interactive-segments/action.js +2 -5
- package/lib/built/interactive-segments/index.d.ts +0 -2
- package/lib/built/interactive-segments/index.js +0 -2
- package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
- package/lib/built/interactive-segments/keyboard-segment.js +0 -1
- package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
- package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
- package/lib/built/interactive-segments/resolve.d.ts +2 -3
- package/lib/built/interactive-segments/resolve.js +21 -14
- package/lib/built/interactive-segments/types.d.ts +2 -7
- package/lib/built/interactive-segments/types.js +22 -2
- package/lib/built/login-assist.d.ts +330 -25
- package/lib/built/login-assist.js +1156 -75
- package/lib/built/login-captcha.d.ts +62 -0
- package/lib/built/login-captcha.js +107 -0
- package/lib/built/message-enrich.d.ts +24 -27
- package/lib/built/message-enrich.js +53 -49
- package/lib/built/outbound-content-arrays.d.ts +4 -0
- package/lib/built/outbound-content-arrays.js +32 -0
- package/lib/built/outbound-media-trust.d.ts +46 -0
- package/lib/built/outbound-media-trust.js +245 -0
- package/lib/built/outbound-media-utils.d.ts +5 -3
- package/lib/built/outbound-media-utils.js +5 -3
- package/lib/built/readable-link.d.ts +4 -0
- package/lib/built/readable-link.js +32 -0
- package/lib/built/rich-segments/markdown-to-text.d.ts +1 -2
- package/lib/built/rich-segments/markdown-to-text.js +141 -17
- package/lib/built/roles.d.ts +141 -12
- package/lib/built/roles.js +253 -52
- package/lib/built/segment-contract/assert.js +8 -2
- package/lib/built/segment-contract/delivery.js +1 -0
- package/lib/built/segment-contract/index.d.ts +3 -3
- package/lib/built/segment-contract/index.js +2 -2
- package/lib/built/segment-contract/json-schema.d.ts +39 -5
- package/lib/built/segment-contract/json-schema.js +207 -24
- package/lib/built/segment-contract/preview.js +8 -1
- package/lib/built/segment-contract/text.js +1 -1
- package/lib/built/segment-contract/types.d.ts +2 -2
- package/lib/built/segment-contract/validate.d.ts +1553 -224
- package/lib/built/segment-contract/validate.js +39 -3
- package/lib/built/tool-access.d.ts +5 -0
- package/lib/built/tool-access.js +17 -0
- package/lib/built/user-interaction.d.ts +5 -4
- package/lib/built/user-interaction.js +64 -52
- package/lib/errors.d.ts +1 -18
- package/lib/errors.js +1 -26
- package/lib/feature/command-public-api.d.ts +5 -0
- package/lib/feature/command-public-api.js +5 -0
- package/lib/feature/command.d.ts +2 -0
- package/lib/feature/command.js +1 -0
- package/lib/feature/component.d.ts +1 -0
- package/lib/feature/component.js +1 -0
- package/lib/feature/handler.d.ts +13 -7
- package/lib/feature/handler.js +2 -1
- package/lib/feature/middleware-public-api.d.ts +6 -0
- package/lib/feature/middleware-public-api.js +6 -0
- package/lib/feature/middleware.d.ts +22 -2
- package/lib/feature/middleware.js +7 -2
- package/lib/im-scene.d.ts +4 -3
- package/lib/im-scene.js +9 -9
- package/lib/im-session-id.d.ts +20 -12
- package/lib/im-session-id.js +8 -8
- package/lib/index.d.ts +20 -48
- package/lib/index.js +15 -41
- package/lib/jsx/intrinsic-elements.d.ts +83 -0
- package/lib/jsx/message-renderer.d.ts +13 -0
- package/lib/jsx/message-renderer.js +128 -0
- package/lib/jsx/message-tags.d.ts +133 -0
- package/lib/jsx/message-tags.js +50 -0
- package/lib/jsx-dev-runtime.d.ts +2 -2
- package/lib/jsx-dev-runtime.js +1 -2
- package/lib/jsx-runtime.d.ts +2 -12
- package/lib/jsx-runtime.js +1 -10
- package/lib/jsx.d.ts +6 -30
- package/lib/jsx.js +3 -93
- package/lib/message.d.ts +0 -40
- package/lib/message.js +1 -27
- package/lib/models/system-log.d.ts +0 -2
- package/lib/models/system-log.js +1 -8
- package/lib/models/user.d.ts +0 -2
- package/lib/models/user.js +1 -7
- package/lib/notice.d.ts +38 -33
- package/lib/notice.js +23 -7
- package/lib/plugin-runtime/im/command-feedback.d.ts +59 -0
- package/lib/plugin-runtime/im/command-feedback.js +148 -0
- package/lib/plugin-runtime/im/contracts.d.ts +217 -32
- package/lib/plugin-runtime/im/contracts.js +141 -23
- package/lib/plugin-runtime/im/conversation-runtime.d.ts +42 -0
- package/lib/plugin-runtime/im/conversation-runtime.js +451 -0
- package/lib/plugin-runtime/im/endpoint-runtime.d.ts +112 -0
- package/lib/plugin-runtime/im/endpoint-runtime.js +434 -0
- package/lib/plugin-runtime/im/feature-gate.d.ts +21 -0
- package/lib/plugin-runtime/im/feature-gate.js +88 -0
- package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
- package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
- package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
- package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
- package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
- package/lib/plugin-runtime/im/host/database-config.js +152 -0
- package/lib/plugin-runtime/im/host/database-console-schema.d.ts +79 -0
- package/lib/plugin-runtime/im/host/database-console-schema.js +477 -0
- package/lib/plugin-runtime/im/host/database-console-sql.d.ts +66 -0
- package/lib/plugin-runtime/im/host/database-console-sql.js +459 -0
- package/lib/plugin-runtime/im/host/database-host-installer.d.ts +60 -0
- package/lib/plugin-runtime/im/host/database-host-installer.js +1166 -0
- package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
- package/lib/plugin-runtime/im/host/database-state.js +91 -0
- package/lib/plugin-runtime/im/host/index.d.ts +8 -0
- package/lib/plugin-runtime/im/host/index.js +8 -0
- package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
- package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
- package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
- package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
- package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +34 -0
- package/lib/plugin-runtime/im/host/sender-enrichment.js +82 -0
- package/lib/plugin-runtime/im/im-runtime.d.ts +40 -111
- package/lib/plugin-runtime/im/im-runtime.js +235 -1059
- package/lib/plugin-runtime/im/inbound-dedup.d.ts +84 -0
- package/lib/plugin-runtime/im/inbound-dedup.js +322 -0
- package/lib/plugin-runtime/im/inbound-origin.d.ts +150 -0
- package/lib/plugin-runtime/im/inbound-origin.js +183 -0
- package/lib/plugin-runtime/im/inbound-runtime.d.ts +59 -0
- package/lib/plugin-runtime/im/inbound-runtime.js +478 -0
- package/lib/plugin-runtime/im/inbound-spine.d.ts +196 -0
- package/lib/plugin-runtime/im/inbound-spine.js +335 -0
- package/lib/plugin-runtime/im/index.d.ts +15 -4
- package/lib/plugin-runtime/im/index.js +11 -4
- package/lib/plugin-runtime/im/interaction-runtime.d.ts +50 -0
- package/lib/plugin-runtime/im/interaction-runtime.js +390 -0
- package/lib/plugin-runtime/im/interactive-router.d.ts +81 -0
- package/lib/plugin-runtime/im/interactive-router.js +382 -0
- package/lib/plugin-runtime/im/message-diagnostics.d.ts +70 -0
- package/lib/plugin-runtime/im/message-diagnostics.js +182 -0
- package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -4
- package/lib/plugin-runtime/im/message-dispatcher.js +138 -20
- package/lib/plugin-runtime/im/message-events.d.ts +85 -0
- package/lib/plugin-runtime/im/message-events.js +113 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +39 -0
- package/lib/plugin-runtime/im/outbound-delivery-runtime.js +450 -0
- package/lib/plugin-runtime/im/outbound-renderer.d.ts +52 -3
- package/lib/plugin-runtime/im/outbound-renderer.js +188 -8
- package/lib/plugin-runtime/im/outbound-segments.d.ts +29 -5
- package/lib/plugin-runtime/im/outbound-segments.js +130 -36
- package/lib/plugin-runtime/im/progressive-reply.d.ts +58 -0
- package/lib/plugin-runtime/im/progressive-reply.js +501 -0
- package/lib/plugin-runtime/im/public-api.d.ts +1 -1
- package/lib/request.d.ts +27 -36
- package/lib/request.js +14 -6
- package/lib/side-event/base.d.ts +64 -44
- package/lib/side-event/base.js +72 -19
- package/lib/side-event/index.d.ts +1 -1
- package/lib/side-event/index.js +1 -1
- package/lib/side-event/normalize.d.ts +7 -38
- package/lib/side-event/normalize.js +4 -109
- package/lib/side-event/scene-events.d.ts +40 -0
- package/lib/side-event/scene-events.js +147 -0
- package/lib/side-event/types.d.ts +4 -13
- package/lib/side-event/types.js +1 -55
- package/lib/system-event.d.ts +17 -12
- package/lib/system-event.js +8 -6
- package/lib/types.d.ts +23 -167
- package/lib/utils.d.ts +50 -33
- package/lib/utils.js +12 -185
- package/lib/venue/contracts.d.ts +21 -0
- package/lib/venue/contracts.js +3 -0
- package/lib/venue/floor-controller.d.ts +11 -0
- package/lib/venue/floor-controller.js +63 -0
- package/lib/venue/index.d.ts +13 -0
- package/lib/venue/index.js +11 -0
- package/lib/venue/membership-port.d.ts +23 -0
- package/lib/venue/membership-port.js +141 -0
- package/lib/venue/projector.d.ts +38 -0
- package/lib/venue/projector.js +45 -0
- package/lib/venue/registry.d.ts +16 -0
- package/lib/venue/registry.js +63 -0
- package/lib/venue/router.d.ts +19 -0
- package/lib/venue/router.js +101 -0
- package/lib/venue/send-limiter.d.ts +17 -0
- package/lib/venue/send-limiter.js +73 -0
- package/lib/venue/validator.d.ts +6 -0
- package/lib/venue/validator.js +160 -0
- package/package.json +24 -50
- package/lib/adapter.d.ts +0 -145
- package/lib/adapter.js +0 -377
- package/lib/built/adapter-process.d.ts +0 -58
- package/lib/built/adapter-process.js +0 -128
- package/lib/built/agent-preset.d.ts +0 -64
- package/lib/built/agent-preset.js +0 -79
- package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
- package/lib/built/ai-outbound/adapter-access.js +0 -9
- package/lib/built/ai-outbound/extensions/qq-message.d.ts +0 -3
- package/lib/built/ai-outbound/extensions/qq-message.js +0 -23
- package/lib/built/authorization.d.ts +0 -10
- package/lib/built/authorization.js +0 -76
- package/lib/built/command.d.ts +0 -72
- package/lib/built/command.js +0 -105
- package/lib/built/component.d.ts +0 -67
- package/lib/built/component.js +0 -97
- package/lib/built/config.d.ts +0 -98
- package/lib/built/config.js +0 -372
- package/lib/built/connect-endpoint-instance.d.ts +0 -17
- package/lib/built/connect-endpoint-instance.js +0 -42
- package/lib/built/database.d.ts +0 -68
- package/lib/built/database.js +0 -106
- package/lib/built/dispatcher.d.ts +0 -141
- package/lib/built/dispatcher.js +0 -383
- package/lib/built/endpoint-commands.d.ts +0 -3
- package/lib/built/endpoint-commands.js +0 -99
- package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
- package/lib/built/endpoint-lifecycle-service.js +0 -242
- package/lib/built/endpoint-lifecycle.d.ts +0 -27
- package/lib/built/endpoint-lifecycle.js +0 -36
- package/lib/built/endpoint-manager.d.ts +0 -34
- package/lib/built/html-renderer-loader.d.ts +0 -13
- package/lib/built/html-renderer-loader.js +0 -33
- package/lib/built/inbound-pipeline.d.ts +0 -37
- package/lib/built/inbound-pipeline.js +0 -63
- package/lib/built/inbound-runner.d.ts +0 -22
- package/lib/built/inbound-runner.js +0 -34
- package/lib/built/interactive-segment-contract.d.ts +0 -6
- package/lib/built/interactive-segment-contract.js +0 -9
- package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
- package/lib/built/interactive-segments/fallback-store.js +0 -63
- package/lib/built/interactive-segments/handlers.d.ts +0 -16
- package/lib/built/interactive-segments/handlers.js +0 -74
- package/lib/built/introspection-format.d.ts +0 -10
- package/lib/built/introspection-format.js +0 -28
- package/lib/built/management-command-guard.d.ts +0 -15
- package/lib/built/management-command-guard.js +0 -25
- package/lib/built/message-filter.d.ts +0 -176
- package/lib/built/message-filter.js +0 -239
- package/lib/built/optional-peer-import.d.ts +0 -3
- package/lib/built/optional-peer-import.js +0 -33
- package/lib/built/outbound-media-contract.d.ts +0 -22
- package/lib/built/outbound-media-contract.js +0 -10
- package/lib/built/permission.d.ts +0 -51
- package/lib/built/permission.js +0 -99
- package/lib/built/permit-check.d.ts +0 -7
- package/lib/built/permit-check.js +0 -35
- package/lib/built/permit-parse.d.ts +0 -16
- package/lib/built/permit-parse.js +0 -32
- package/lib/built/platform-permit.d.ts +0 -20
- package/lib/built/platform-permit.js +0 -91
- package/lib/built/queue-im-field-contract.d.ts +0 -32
- package/lib/built/queue-im-field-contract.js +0 -67
- package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
- package/lib/built/rich-segments/adapter-policies.js +0 -27
- package/lib/built/rich-segments/base.d.ts +0 -11
- package/lib/built/rich-segments/base.js +0 -24
- package/lib/built/rich-segments/builtins.d.ts +0 -4
- package/lib/built/rich-segments/builtins.js +0 -40
- package/lib/built/rich-segments/capabilities.d.ts +0 -6
- package/lib/built/rich-segments/capabilities.js +0 -38
- package/lib/built/rich-segments/html-segment.d.ts +0 -15
- package/lib/built/rich-segments/html-segment.js +0 -62
- package/lib/built/rich-segments/index.d.ts +0 -13
- package/lib/built/rich-segments/index.js +0 -13
- package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
- package/lib/built/rich-segments/markdown-segment.js +0 -58
- package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
- package/lib/built/rich-segments/qrcode-segment.js +0 -73
- package/lib/built/rich-segments/registry.d.ts +0 -16
- package/lib/built/rich-segments/registry.js +0 -52
- package/lib/built/rich-segments/resolve.d.ts +0 -5
- package/lib/built/rich-segments/resolve.js +0 -87
- package/lib/built/rich-segments/tts-segment.d.ts +0 -13
- package/lib/built/rich-segments/tts-segment.js +0 -51
- package/lib/built/rich-segments/types.d.ts +0 -79
- package/lib/built/rich-segments/types.js +0 -17
- package/lib/built/runtime-io.d.ts +0 -9
- package/lib/built/runtime-io.js +0 -67
- package/lib/built/schedule.d.ts +0 -54
- package/lib/built/schedule.js +0 -112
- package/lib/built/schema-endpoint-manager.d.ts +0 -17
- package/lib/built/schema-endpoint-manager.js +0 -73
- package/lib/built/schema-feature.d.ts +0 -77
- package/lib/built/schema-feature.js +0 -130
- package/lib/built/skill.d.ts +0 -120
- package/lib/built/skill.js +0 -151
- package/lib/built/speech-loader.d.ts +0 -14
- package/lib/built/speech-loader.js +0 -32
- package/lib/built/tool.d.ts +0 -151
- package/lib/built/tool.js +0 -388
- package/lib/command.d.ts +0 -50
- package/lib/command.js +0 -106
- package/lib/component.d.ts +0 -26
- package/lib/component.js +0 -583
- package/lib/endpoint-capabilities.d.ts +0 -46
- package/lib/endpoint-capabilities.js +0 -55
- package/lib/endpoint.d.ts +0 -19
- package/lib/endpoint.js +0 -3
- package/lib/host-plugin-registry.d.ts +0 -8
- package/lib/host-plugin-registry.js +0 -12
- package/lib/plugin-context.d.ts +0 -27
- package/lib/plugin-context.js +0 -64
- package/lib/plugin-runtime/im/interactive.d.ts +0 -26
- package/lib/plugin-runtime/im/interactive.js +0 -46
- package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
- package/lib/plugin-runtime/im/login-assist-host.js +0 -6
- package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
- package/lib/plugin-runtime/im/message-bus.js +0 -40
- package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
- package/lib/plugin-runtime/im/service-tokens.js +0 -13
- package/lib/plugin.d.ts +0 -268
- package/lib/plugin.js +0 -583
- package/lib/schema-interaction.d.ts +0 -117
- package/lib/schema-interaction.js +0 -247
- package/lib/side-event/dispatch.d.ts +0 -15
- package/lib/side-event/dispatch.js +0 -140
- package/lib/tool-zod.d.ts +0 -43
- package/lib/tool-zod.js +0 -184
- /package/lib/{built/endpoint-manager.js → jsx/intrinsic-elements.js} +0 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound media policy for content from untrusted sources (ADR 0056 §2: reading host files is a
|
|
3
|
+
* host-global capability).
|
|
4
|
+
*
|
|
5
|
+
* Adapter codecs read and upload `MediaRef kind: 'path'`, and several hand a `file` token or a
|
|
6
|
+
* non-http URL straight to the platform SDK (OneBot reads `file://…` and bare paths from the host).
|
|
7
|
+
* Content produced by an Agent model, or built from values a user controls, must therefore not be
|
|
8
|
+
* able to name a host file. Core applies this policy once, in the renderer, before outbound
|
|
9
|
+
* middleware and the Endpoint see the payload — no adapter repeats it and no parallel send path
|
|
10
|
+
* exists (CLAUDE.md Guardrail #1).
|
|
11
|
+
*
|
|
12
|
+
* Untrusted media may only be:
|
|
13
|
+
* - `url` with an `http:` / `https:` URL, or a base64 `data:` URL within the inline limit;
|
|
14
|
+
* - `base64` within the inline limit;
|
|
15
|
+
* - `file` that is a bare platform token (no scheme, no path separator, not `~` / `.`-relative);
|
|
16
|
+
* - `path` (or a `file:` URL) that `trust.authorizePath` admits — the sender's own file policy,
|
|
17
|
+
* e.g. the Agent Turn's workspace authority plus FilePolicy — or a MediaRef that trusted code
|
|
18
|
+
* built with {@link trustedMediaRef} (e.g. bytes the Agent itself spooled to a temp file).
|
|
19
|
+
*
|
|
20
|
+
* A refused segment is replaced by a visible notice and logged (`op: outbound_media_refused`);
|
|
21
|
+
* it is never sent silently and never sent as is.
|
|
22
|
+
*/
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
25
|
+
import { isMediaRef } from './segment-contract/validate.js';
|
|
26
|
+
import { toCanonicalSegments } from './generic-segment-mapper.js';
|
|
27
|
+
import { htmlToPlainText } from './html-to-text.js';
|
|
28
|
+
/** Same ceiling as the Agent's attachment limit (25 MiB of decoded bytes). */
|
|
29
|
+
export const DEFAULT_UNTRUSTED_INLINE_MEDIA_BYTES = 26_214_400;
|
|
30
|
+
const trustedRefs = new WeakSet();
|
|
31
|
+
/**
|
|
32
|
+
* Mark a MediaRef that trusted code constructed (not copied from model output) so it passes the
|
|
33
|
+
* untrusted-source policy unchanged. Identity-based: a copy of the object is not trusted.
|
|
34
|
+
*/
|
|
35
|
+
export function trustedMediaRef(media) {
|
|
36
|
+
trustedRefs.add(media);
|
|
37
|
+
return media;
|
|
38
|
+
}
|
|
39
|
+
export function isTrustedMediaRef(media) {
|
|
40
|
+
return typeof media === 'object' && media !== null && trustedRefs.has(media);
|
|
41
|
+
}
|
|
42
|
+
const SCHEME = /^[a-z][a-z0-9+.-]*:/iu;
|
|
43
|
+
const BASE64_BODY = /^[A-Za-z0-9+/_-]*={0,2}$/u;
|
|
44
|
+
/** A platform file token, not something an SDK would resolve against the host filesystem. */
|
|
45
|
+
export function isPlatformFileToken(value) {
|
|
46
|
+
const token = value.trim();
|
|
47
|
+
if (!token || token !== value || [...token].some(char => char.charCodeAt(0) < 0x20))
|
|
48
|
+
return false;
|
|
49
|
+
if (SCHEME.test(token))
|
|
50
|
+
return false; // file:, data:, other schemes, Windows drives (C:)
|
|
51
|
+
if (/[\\/]/u.test(token))
|
|
52
|
+
return false;
|
|
53
|
+
return !token.startsWith('~') && !token.startsWith('.');
|
|
54
|
+
}
|
|
55
|
+
function inlineWithinLimit(body, maxBytes) {
|
|
56
|
+
const compact = body.replace(/\s+/gu, '');
|
|
57
|
+
if (!BASE64_BODY.test(compact))
|
|
58
|
+
return { allowed: false, reason: 'inline_invalid' };
|
|
59
|
+
if (Math.floor((compact.length * 3) / 4) > maxBytes)
|
|
60
|
+
return { allowed: false, reason: 'inline_too_large' };
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
/** Decide one MediaRef from an untrusted source. */
|
|
64
|
+
export async function checkUntrustedMediaRef(media, trust) {
|
|
65
|
+
if (isTrustedMediaRef(media))
|
|
66
|
+
return { allowed: true, media };
|
|
67
|
+
const maxBytes = trust.maxInlineBytes ?? DEFAULT_UNTRUSTED_INLINE_MEDIA_BYTES;
|
|
68
|
+
const value = media.value;
|
|
69
|
+
switch (media.kind) {
|
|
70
|
+
case 'url': {
|
|
71
|
+
let url;
|
|
72
|
+
try {
|
|
73
|
+
url = new URL(value);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return { allowed: false, reason: 'url_scheme' };
|
|
77
|
+
}
|
|
78
|
+
if (url.protocol === 'http:' || url.protocol === 'https:')
|
|
79
|
+
return { allowed: true, media };
|
|
80
|
+
if (url.protocol === 'data:') {
|
|
81
|
+
const match = /^data:[^,]*;base64,([\s\S]*)$/iu.exec(value);
|
|
82
|
+
if (!match)
|
|
83
|
+
return { allowed: false, reason: 'inline_invalid' };
|
|
84
|
+
return inlineWithinLimit(match[1], maxBytes) ?? { allowed: true, media };
|
|
85
|
+
}
|
|
86
|
+
return { allowed: false, reason: 'url_scheme' };
|
|
87
|
+
}
|
|
88
|
+
case 'base64': {
|
|
89
|
+
const body = value.replace(/^base64:\/\//u, '').replace(/^data:[^,]*;base64,/iu, '');
|
|
90
|
+
return inlineWithinLimit(body, maxBytes) ?? { allowed: true, media };
|
|
91
|
+
}
|
|
92
|
+
case 'file':
|
|
93
|
+
return isPlatformFileToken(value) ? { allowed: true, media } : { allowed: false, reason: 'platform_ref_path' };
|
|
94
|
+
case 'path': {
|
|
95
|
+
if (!trust.authorizePath)
|
|
96
|
+
return { allowed: false, reason: 'host_path' };
|
|
97
|
+
let local = value;
|
|
98
|
+
if (/^file:/iu.test(local)) {
|
|
99
|
+
try {
|
|
100
|
+
local = fileURLToPath(local);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return { allowed: false, reason: 'host_path' };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (!local.trim() || local.includes('\u0000'))
|
|
107
|
+
return { allowed: false, reason: 'host_path' };
|
|
108
|
+
let canonical;
|
|
109
|
+
try {
|
|
110
|
+
canonical = await trust.authorizePath(local);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
canonical = undefined;
|
|
114
|
+
}
|
|
115
|
+
if (typeof canonical !== 'string' || !canonical)
|
|
116
|
+
return { allowed: false, reason: 'host_path' };
|
|
117
|
+
return { allowed: true, media: trustedMediaRef({ ...media, value: canonical }) };
|
|
118
|
+
}
|
|
119
|
+
default:
|
|
120
|
+
return { allowed: false, reason: 'host_path' };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
|
|
124
|
+
/** Wire field names adapters read as a media source inside extension / nested segments. */
|
|
125
|
+
const MEDIA_SOURCE_KEYS = new Set(['file', 'path', 'url', 'src', 'image', 'thumb', 'audio', 'video', 'file_path']);
|
|
126
|
+
const MAX_NESTED_DEPTH = 8;
|
|
127
|
+
/** Media nested inside another segment (forward nodes, extension payloads, platform fields). */
|
|
128
|
+
async function nestedMediaAllowed(value, trust, wireFields, depth = 0) {
|
|
129
|
+
if (depth > MAX_NESTED_DEPTH)
|
|
130
|
+
return false;
|
|
131
|
+
if (Array.isArray(value)) {
|
|
132
|
+
for (const item of value)
|
|
133
|
+
if (!await nestedMediaAllowed(item, trust, wireFields, depth + 1))
|
|
134
|
+
return false;
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
if (!value || typeof value !== 'object')
|
|
138
|
+
return true;
|
|
139
|
+
if (isMediaRef(value)) {
|
|
140
|
+
if (isTrustedMediaRef(value))
|
|
141
|
+
return true;
|
|
142
|
+
// A nested ref cannot be rewritten to its authorized canonical path: untrusted local paths never pass.
|
|
143
|
+
return (await checkUntrustedMediaRef(value, { ...trust, authorizePath: undefined })).allowed;
|
|
144
|
+
}
|
|
145
|
+
for (const [key, field] of Object.entries(value)) {
|
|
146
|
+
if (typeof field === 'string') {
|
|
147
|
+
if (wireFields && MEDIA_SOURCE_KEYS.has(key) && field && !isRemoteSourceString(field))
|
|
148
|
+
return false;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (!await nestedMediaAllowed(field, trust, wireFields, depth + 1))
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
/** Canonical types whose fields are never read as a media source (links and button URLs may use any scheme). */
|
|
157
|
+
const NON_MEDIA_TYPES = new Set(['text', 'mention', 'markdown', 'keyboard', 'link', 'share', 'reply', 'face', 'dice', 'rps', 'reaction', 'action']);
|
|
158
|
+
function isRemoteSourceString(value) {
|
|
159
|
+
return /^https?:\/\//iu.test(value) || /^base64:\/\//iu.test(value) || isPlatformFileToken(value);
|
|
160
|
+
}
|
|
161
|
+
const NOTICE = {
|
|
162
|
+
'zh-CN': {
|
|
163
|
+
labels: { image: '图片', audio: '语音', video: '视频', file: '文件' },
|
|
164
|
+
text: label => `[${label}未发送:媒体来源不被允许]`,
|
|
165
|
+
},
|
|
166
|
+
en: {
|
|
167
|
+
labels: { image: 'image', audio: 'audio', video: 'video', file: 'file' },
|
|
168
|
+
text: label => `[${label} not sent: media source not allowed]`,
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
function refusalNotice(type, locale) {
|
|
172
|
+
const notice = locale === 'en' ? NOTICE.en : NOTICE['zh-CN'];
|
|
173
|
+
return { type: 'text', data: { text: notice.text(notice.labels[type] ?? (locale === 'en' ? 'attachment' : '附件')) } };
|
|
174
|
+
}
|
|
175
|
+
const logger = getLogger('im.outbound');
|
|
176
|
+
function logRefusal(trust, context, segment, kind, reason) {
|
|
177
|
+
// Never log the media value: it is model / user controlled and may itself be the secret path.
|
|
178
|
+
logger.warn(formatCompact({
|
|
179
|
+
op: 'outbound_media_refused',
|
|
180
|
+
source: trust.source,
|
|
181
|
+
segment,
|
|
182
|
+
...(kind ? { kind } : {}),
|
|
183
|
+
reason,
|
|
184
|
+
...(context.requester ? { requester: context.requester } : {}),
|
|
185
|
+
...(context.conversation ? { conv: `${context.conversation.endpoint.id}/${context.conversation.kind}:${context.conversation.id}` } : {}),
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Hold rendered untrusted content to the policy. Strings stay text; segments are canonicalized first
|
|
190
|
+
* (legacy `{ file }` / `{ path }` fields become `data.media`), `html` is reduced to text (a renderer
|
|
191
|
+
* could load local files), raw native payloads are refused.
|
|
192
|
+
*/
|
|
193
|
+
export async function enforceUntrustedOutbound(rendered, trust, context = {}) {
|
|
194
|
+
const items = Array.isArray(rendered) ? rendered : [rendered];
|
|
195
|
+
const out = [];
|
|
196
|
+
for (const item of items) {
|
|
197
|
+
if (item == null)
|
|
198
|
+
continue;
|
|
199
|
+
if (typeof item === 'string') {
|
|
200
|
+
out.push(item);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (typeof item !== 'object' || Array.isArray(item) || typeof item.type !== 'string') {
|
|
204
|
+
logRefusal(trust, context, 'raw', undefined, 'raw_payload');
|
|
205
|
+
out.push(refusalNotice('raw', trust.locale));
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const [segment] = toCanonicalSegments([item]);
|
|
209
|
+
if (!segment)
|
|
210
|
+
continue;
|
|
211
|
+
if (segment.type === 'html') {
|
|
212
|
+
const data = segment.data;
|
|
213
|
+
const text = typeof data.text === 'string' && data.text ? data.text
|
|
214
|
+
: typeof data.html === 'string' ? htmlToPlainText(data.html) : '';
|
|
215
|
+
out.push({ type: 'text', data: { text } });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const data = (segment.data ?? {});
|
|
219
|
+
const media = data.media;
|
|
220
|
+
if (MEDIA_SEGMENT_TYPES.has(segment.type) && isMediaRef(media)) {
|
|
221
|
+
const decision = await checkUntrustedMediaRef(media, trust);
|
|
222
|
+
if (!decision.allowed) {
|
|
223
|
+
logRefusal(trust, context, segment.type, media.kind, decision.reason);
|
|
224
|
+
out.push(refusalNotice(segment.type, trust.locale));
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
const platformOk = await nestedMediaAllowed(segment.platform, trust, true);
|
|
228
|
+
if (!platformOk) {
|
|
229
|
+
logRefusal(trust, context, segment.type, media.kind, 'nested_media');
|
|
230
|
+
out.push(refusalNotice(segment.type, trust.locale));
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
out.push(decision.media === media ? segment : { ...segment, data: { ...data, media: decision.media } });
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
const wireFields = !NON_MEDIA_TYPES.has(segment.type);
|
|
237
|
+
if (!await nestedMediaAllowed(segment.data, trust, wireFields) || !await nestedMediaAllowed(segment.platform, trust, true)) {
|
|
238
|
+
logRefusal(trust, context, segment.type, undefined, 'nested_media');
|
|
239
|
+
out.push(refusalNotice(segment.type, trust.locale));
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
out.push(segment);
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import type { MessageElement
|
|
1
|
+
import type { MessageElement } from '../types.js';
|
|
2
2
|
export declare function isRemoteUrl(value: string): boolean;
|
|
3
3
|
/** 从 message 段 data 提取 base64 Buffer(data: URL / base64:// / raw base64) */
|
|
4
4
|
export declare function extractBase64Buffer(data: Record<string, unknown>): Buffer | undefined;
|
|
5
5
|
/** 解析本地文件路径(非 http(s) / base64) */
|
|
6
6
|
export declare function resolveLocalMediaPath(data: Record<string, unknown>): string | undefined;
|
|
7
|
-
|
|
7
|
+
/** Already rendered content; JSX, component calls and raw wrappers need OutboundRenderer first. */
|
|
8
|
+
export type RenderedMessageContent = string | MessageElement | readonly RenderedMessageContent[];
|
|
9
|
+
export declare function asMessageElements(content: RenderedMessageContent): MessageElement[];
|
|
8
10
|
export declare function isMediaSegmentType(type: string): boolean;
|
|
9
|
-
export declare function collectOutboundMediaKinds(content:
|
|
11
|
+
export declare function collectOutboundMediaKinds(content: RenderedMessageContent | undefined): string[];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isSegmentContent } from '../plugin-runtime/im/contracts.js';
|
|
1
2
|
const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
|
|
2
3
|
export function isRemoteUrl(value) {
|
|
3
4
|
return /^https?:\/\//i.test(value);
|
|
@@ -40,10 +41,11 @@ export function asMessageElements(content) {
|
|
|
40
41
|
if (typeof content === 'string') {
|
|
41
42
|
return [{ type: 'text', data: { text: content } }];
|
|
42
43
|
}
|
|
43
|
-
if (
|
|
44
|
+
if (Array.isArray(content))
|
|
45
|
+
return content.flatMap(item => asMessageElements(item));
|
|
46
|
+
if (isSegmentContent(content))
|
|
44
47
|
return [content];
|
|
45
|
-
|
|
46
|
-
return content.map((item) => typeof item === 'string' ? { type: 'text', data: { text: item } } : item);
|
|
48
|
+
throw new TypeError('Message elements require rendered content; JSX and component calls must use the outbound renderer');
|
|
47
49
|
}
|
|
48
50
|
export function isMediaSegmentType(type) {
|
|
49
51
|
return MEDIA_SEGMENT_TYPES.has(type);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Only portable, explicit user-facing links survive rich-message text fallback. */
|
|
2
|
+
export declare function readableLinkTarget(value: string): string | undefined;
|
|
3
|
+
/** Decode entities once; encoded markup remains literal text, never parsed again. */
|
|
4
|
+
export declare function decodeReadableEntities(text: string): string;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Only portable, explicit user-facing links survive rich-message text fallback. */
|
|
2
|
+
export function readableLinkTarget(value) {
|
|
3
|
+
const target = value.trim();
|
|
4
|
+
for (const character of target) {
|
|
5
|
+
const code = character.codePointAt(0);
|
|
6
|
+
if (code <= 32 || code === 127)
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(target);
|
|
11
|
+
if (!['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol))
|
|
12
|
+
return undefined;
|
|
13
|
+
// Embedded credentials should never be copied into a chat transcript.
|
|
14
|
+
if (url.username || url.password)
|
|
15
|
+
return undefined;
|
|
16
|
+
return target;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Decode entities once; encoded markup remains literal text, never parsed again. */
|
|
23
|
+
export function decodeReadableEntities(text) {
|
|
24
|
+
return text.replace(/&(#x[0-9a-fA-F]+|#\d+|nbsp|amp|lt|gt|quot|apos);/gi, (entity) => {
|
|
25
|
+
const key = entity.slice(1, -1).toLowerCase();
|
|
26
|
+
const named = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
27
|
+
if (named[key] !== undefined)
|
|
28
|
+
return named[key];
|
|
29
|
+
const value = key.startsWith('#x') ? parseInt(key.slice(2), 16) : Number(key.slice(1));
|
|
30
|
+
return Number.isFinite(value) && value >= 0 && value <= 0x10ffff ? String.fromCodePoint(value) : '';
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -1,27 +1,151 @@
|
|
|
1
|
-
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { readableLinkTarget, decodeReadableEntities } from '../readable-link.js';
|
|
3
|
+
const MAX_INPUT_LENGTH = 2 * 1024 * 1024;
|
|
4
|
+
/** Preserve link destinations and image descriptions without exposing embedded media. */
|
|
5
|
+
function readableLinks(text, literal, depth = 0) {
|
|
6
|
+
// Bound work for deliberately nested link labels. Such nesting is not portable Markdown.
|
|
7
|
+
if (depth >= 16)
|
|
8
|
+
return '[嵌套内容已省略]';
|
|
9
|
+
const pairs = new Map();
|
|
10
|
+
const brackets = [];
|
|
11
|
+
const parentheses = [];
|
|
12
|
+
for (let i = 0; i < text.length; i++) {
|
|
13
|
+
if (text[i] === '\\') {
|
|
14
|
+
i++;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (text[i] === '[')
|
|
18
|
+
brackets.push(i);
|
|
19
|
+
else if (text[i] === ']' && brackets.length)
|
|
20
|
+
pairs.set(brackets.pop(), i);
|
|
21
|
+
else if (text[i] === '(')
|
|
22
|
+
parentheses.push(i);
|
|
23
|
+
else if (text[i] === ')' && parentheses.length)
|
|
24
|
+
pairs.set(parentheses.pop(), i);
|
|
25
|
+
}
|
|
26
|
+
const out = [];
|
|
27
|
+
let start = 0;
|
|
28
|
+
for (let i = 0; i < text.length; i++) {
|
|
29
|
+
if (text[i] === '\\') {
|
|
30
|
+
i++;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const image = text[i] === '!' && text[i + 1] === '[';
|
|
34
|
+
const open = image ? i + 1 : i;
|
|
35
|
+
if (text[open] !== '[')
|
|
36
|
+
continue;
|
|
37
|
+
const close = pairs.get(open);
|
|
38
|
+
if (close === undefined || text[close + 1] !== '(')
|
|
39
|
+
continue;
|
|
40
|
+
const pairedEnd = pairs.get(close + 1);
|
|
41
|
+
// An ordinary incomplete link is literal prose; only unfinished media URLs
|
|
42
|
+
// need suppression so embedded data is not dumped into text fallback.
|
|
43
|
+
if (pairedEnd === undefined && !image)
|
|
44
|
+
continue;
|
|
45
|
+
// An incomplete inline image/link must not dump its data URL into plain text.
|
|
46
|
+
const lineEnd = pairedEnd === undefined ? text.indexOf('\n', close + 2) : -1;
|
|
47
|
+
const end = pairedEnd ?? (lineEnd === -1 ? text.length : lineEnd);
|
|
48
|
+
const label = readableLinks(text.slice(open + 1, close), literal, depth + 1);
|
|
49
|
+
let destination = text.slice(close + 2, end).trim();
|
|
50
|
+
// Optional Markdown titles are presentation, not part of the destination.
|
|
51
|
+
if (destination.startsWith('<'))
|
|
52
|
+
destination = destination.slice(1, destination.indexOf('>'));
|
|
53
|
+
else
|
|
54
|
+
destination = destination.split(/\s/u, 1)[0];
|
|
55
|
+
const target = pairedEnd === undefined ? undefined : readableLinkTarget(destination);
|
|
56
|
+
out.push(text.slice(start, i), image ? (label ? `[图片:${label}]` : '[图片]')
|
|
57
|
+
: target ? (target === label || !label ? literal(target) : `${label} (${literal(target)})`) : label);
|
|
58
|
+
start = pairedEnd === undefined ? end : end + 1;
|
|
59
|
+
i = start - 1;
|
|
60
|
+
}
|
|
61
|
+
out.push(text.slice(start));
|
|
62
|
+
return out.join('');
|
|
63
|
+
}
|
|
64
|
+
/** 将 Markdown 转为可读纯文本(出站 text 降级用)。代码内容不参与格式剥离。 */
|
|
2
65
|
export function markdownToPlainText(md) {
|
|
3
|
-
let text = md;
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
66
|
+
let text = md.slice(0, MAX_INPUT_LENGTH);
|
|
67
|
+
// A collision-free marker keeps source code and URL underscores intact.
|
|
68
|
+
let marker = `\uE000${randomUUID()}\uE001`;
|
|
69
|
+
while (text.includes(marker))
|
|
70
|
+
marker = `\uE000${randomUUID()}\uE001`;
|
|
71
|
+
const literal = [];
|
|
72
|
+
const stash = (value) => `${marker}${literal.push(value) - 1}${marker}`;
|
|
73
|
+
const lines = text.split('\n');
|
|
74
|
+
let fence;
|
|
75
|
+
text = lines.map(line => {
|
|
76
|
+
const match = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line);
|
|
77
|
+
if (fence) {
|
|
78
|
+
if (match && match[1][0] === fence.character && match[1].length >= fence.size && !match[2].trim()) {
|
|
79
|
+
const code = stash(fence.code.join('\n'));
|
|
80
|
+
fence = undefined;
|
|
81
|
+
return code;
|
|
82
|
+
}
|
|
83
|
+
fence.code.push(line);
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
if (match) {
|
|
87
|
+
fence = { character: match[1][0], size: match[1].length, code: [] };
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
// Match equal-length tick runs in linear time, including multi-tick code spans.
|
|
91
|
+
const runs = [...line.matchAll(/`+/gu)];
|
|
92
|
+
const next = new Map();
|
|
93
|
+
const closing = new Map();
|
|
94
|
+
for (let i = runs.length - 1; i >= 0; i--) {
|
|
95
|
+
const size = runs[i][0].length;
|
|
96
|
+
if (closing.has(size))
|
|
97
|
+
next.set(i, closing.get(size));
|
|
98
|
+
closing.set(size, i);
|
|
99
|
+
}
|
|
100
|
+
const out = [];
|
|
101
|
+
let start = 0;
|
|
102
|
+
for (let i = 0; i < runs.length; i++) {
|
|
103
|
+
const end = next.get(i);
|
|
104
|
+
if (end === undefined)
|
|
105
|
+
continue;
|
|
106
|
+
out.push(line.slice(start, runs[i].index), stash(line.slice(runs[i].index + runs[i][0].length, runs[end].index)));
|
|
107
|
+
start = runs[end].index + runs[end][0].length;
|
|
108
|
+
i = end;
|
|
109
|
+
}
|
|
110
|
+
out.push(line.slice(start));
|
|
111
|
+
return out.join('');
|
|
112
|
+
}).filter((line) => line !== undefined).join('\n');
|
|
113
|
+
if (fence)
|
|
114
|
+
text += `${text ? '\n' : ''}${stash(fence.code.join('\n'))}`;
|
|
115
|
+
text = readableLinks(decodeReadableEntities(text), stash);
|
|
116
|
+
text = formatMarkdownTables(text);
|
|
11
117
|
text = text.replace(/^#{1,6}\s+/gm, '');
|
|
12
118
|
text = text.replace(/^[ \t]*>[ \t]?/gm, '');
|
|
13
|
-
text = text.replace(/^[ \t]*[-*+][ \t]+/gm, '');
|
|
119
|
+
text = text.replace(/^([ \t]*)[-*+][ \t]+/gm, '$1• ');
|
|
14
120
|
text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
|
|
15
121
|
text = text.replace(/__([^_]+)__/g, '$1');
|
|
16
122
|
text = text.replace(/\*([^*]+)\*/g, '$1');
|
|
17
123
|
text = text.replace(/_([^_]+)_/g, '$1');
|
|
18
124
|
text = text.replace(/~~([^~]+)~~/g, '$1');
|
|
19
|
-
|
|
125
|
+
// A linear split avoids constructing a regular expression from user text.
|
|
126
|
+
const chunks = text.split(marker);
|
|
127
|
+
for (let i = 1; i < chunks.length; i += 2) {
|
|
128
|
+
const index = Number(chunks[i]);
|
|
129
|
+
if (Number.isInteger(index) && index >= 0 && index < literal.length)
|
|
130
|
+
chunks[i] = literal[index];
|
|
131
|
+
}
|
|
132
|
+
return chunks.join('').trim() + (md.length > MAX_INPUT_LENGTH ? '\n\n[内容过长,已省略后续内容;请缩小查询范围或分页查看。]' : '');
|
|
20
133
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
134
|
+
function formatMarkdownTables(text) {
|
|
135
|
+
if (!text.includes('|'))
|
|
136
|
+
return text;
|
|
137
|
+
const out = [];
|
|
138
|
+
for (const line of text.split('\n')) {
|
|
139
|
+
const trimmed = line.trim();
|
|
140
|
+
if (trimmed.length > 1 && trimmed.startsWith('|') && trimmed.endsWith('|')) {
|
|
141
|
+
const cells = trimmed.slice(1, -1).split('|').map(cell => cell.trim());
|
|
142
|
+
if (cells.length > 0 && cells.every(cell => /^:?-{2,}:?$/u.test(cell))) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
out.push(cells.join(' | '));
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
out.push(line);
|
|
149
|
+
}
|
|
150
|
+
return out.join('\n');
|
|
27
151
|
}
|
package/lib/built/roles.d.ts
CHANGED
|
@@ -1,14 +1,143 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
2
|
+
* ADR 0056: chat roles — zhin roles at four levels, next to (never derived from) the normalized
|
|
3
|
+
* platform standing.
|
|
4
|
+
*
|
|
5
|
+
* - zhin roles: `owner` ⊃ `admin` ⊃ `trusted`, held by a platform identity `(adapter alias, userId)`
|
|
6
|
+
* at one scope (`''`, `<alias>`, `<alias>/<endpointId>` or a conversation key) and effective at
|
|
7
|
+
* that scope and every scope under it. They come only from stored grants (the instance's
|
|
8
|
+
* `chat_roles` table, including grants migrated from the old configuration lists).
|
|
9
|
+
* - Platform standing (group owner / admin, platform roles and permissions) is *not* converted into
|
|
10
|
+
* a zhin role (ADR 0056 §4, revised 2026-11-12); it is a separate dimension read by `platform:*`
|
|
11
|
+
* permits, and the Bot account's own standing by `bot:*` permits.
|
|
12
|
+
* - Every inbound message gets `sender.chatRole` (highest role effective in its conversation) and a
|
|
13
|
+
* normalized `sender.platform` from {@link createChatRoleSenderEnricher}.
|
|
14
|
+
*/
|
|
15
|
+
import { type ChatRoleLevels, type ConversationRef, type PlatformStanding, type PlatformStandingLevel } from '@zhin.js/im-contract';
|
|
16
|
+
import { type FeatureConfigLevel, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
17
|
+
export type { PlatformStanding, PlatformStandingLevel } from '@zhin.js/im-contract';
|
|
18
|
+
export { CHAT_ROLE_LEVELS, chatRoleHeldAt, hostChatRole, isChatRoleLevel, normalizeChatRoleLevels, type ChatRoleLevel, type ChatRoleLevels, } from '@zhin.js/im-contract';
|
|
19
|
+
export type ChatRole = 'owner' | 'admin' | 'trusted';
|
|
20
|
+
export declare const CHAT_ROLES: readonly ChatRole[];
|
|
21
|
+
export declare function isChatRole(value: unknown): value is ChatRole;
|
|
22
|
+
/** `owner` ⊃ `admin` ⊃ `trusted`. */
|
|
23
|
+
export declare function chatRoleIncludes(held: ChatRole | undefined, required: ChatRole): boolean;
|
|
24
|
+
/** The higher of two roles. */
|
|
25
|
+
export declare function higherChatRole(left: ChatRole | undefined, right: ChatRole | undefined): ChatRole | undefined;
|
|
26
|
+
/** Whether a role list (expanded or not, other strings ignored) holds `required`. */
|
|
27
|
+
export declare function chatRolesInclude(roles: readonly string[] | undefined, required: ChatRole): boolean;
|
|
28
|
+
/** `owner` → `[owner, admin, trusted]`, `admin` → `[admin, trusted]`, none → `[]`. */
|
|
29
|
+
export declare function expandChatRole(role: ChatRole | undefined): readonly ChatRole[];
|
|
30
|
+
export interface ChatIdentity {
|
|
31
|
+
/** Adapter instance alias the user id belongs to. */
|
|
32
|
+
readonly adapter: string;
|
|
33
|
+
readonly userId: string;
|
|
34
|
+
}
|
|
35
|
+
export declare function isChatIdentity(value: unknown): value is ChatIdentity;
|
|
36
|
+
/** Validates `level` + `key` and returns the normalized scope key; throws TypeError. */
|
|
37
|
+
export declare function normalizeChatRoleScope(level: unknown, key: unknown): string;
|
|
38
|
+
/** Scope keys from global down to `key` (`''`, `qq`, `qq/bot`, `qq/bot/group:1`). */
|
|
39
|
+
export declare function chatScopeChain(key: string): readonly string[];
|
|
40
|
+
/** Whether scope `upper` is `lower` or one of its ancestors. */
|
|
41
|
+
export declare function chatScopeCovers(upper: string, lower: string): boolean;
|
|
42
|
+
export declare function chatScopeLevel(key: string): FeatureConfigLevel;
|
|
43
|
+
/** Where an entry comes from: `grant` (the `chat_roles` table). */
|
|
44
|
+
export type ChatRoleSourceKind = 'grant';
|
|
45
|
+
export interface ChatRoleEntry extends ChatIdentity {
|
|
46
|
+
readonly level: FeatureConfigLevel;
|
|
47
|
+
/** Normalized scope key (`''` for global). */
|
|
48
|
+
readonly key: string;
|
|
49
|
+
readonly role: ChatRole;
|
|
50
|
+
readonly source: ChatRoleSourceKind;
|
|
51
|
+
readonly grantedBy?: string;
|
|
52
|
+
readonly grantedAt?: number;
|
|
53
|
+
}
|
|
54
|
+
/** Snapshot parts needed to address a message's conversation. */
|
|
55
|
+
export type ChatRoleSnapshot = Pick<RuntimeSnapshot, 'config' | 'projections' | 'tree'>;
|
|
56
|
+
/** The conversation a message was sent in, and the sender's platform standing there (informational). */
|
|
57
|
+
export interface ChatRoleContext {
|
|
58
|
+
readonly conversationKey?: string;
|
|
59
|
+
readonly platform?: PlatformStanding;
|
|
60
|
+
}
|
|
61
|
+
/** Stored grants (the instance's `chat_roles` table, held in memory). */
|
|
62
|
+
export interface ChatRoleGrantStore {
|
|
63
|
+
list(): readonly ChatRoleEntry[];
|
|
64
|
+
}
|
|
65
|
+
/** Effective roles of one sender in one conversation. */
|
|
66
|
+
export interface ChatRoleResolution {
|
|
67
|
+
readonly identity: ChatIdentity;
|
|
68
|
+
readonly conversationKey: string;
|
|
69
|
+
/** Highest role effective in the conversation. */
|
|
70
|
+
readonly role?: ChatRole;
|
|
71
|
+
/** Every stored entry on the conversation's chain. */
|
|
72
|
+
readonly entries: readonly ChatRoleEntry[];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Resolution over stored grants (ADR 0056 §2): for a message the chain is
|
|
76
|
+
* conversation → endpoint → adapter → global and the highest role wins.
|
|
77
|
+
*/
|
|
78
|
+
export declare class ChatRoleService<TStore extends ChatRoleGrantStore = ChatRoleGrantStore> {
|
|
79
|
+
readonly store: TStore;
|
|
80
|
+
constructor(options: Readonly<{
|
|
81
|
+
store: TStore;
|
|
82
|
+
}>);
|
|
83
|
+
/** Entries of `identity` effective at `scopeKey` (own scope and every ancestor). */
|
|
84
|
+
entriesFor(identity: ChatIdentity, scopeKey: string): readonly ChatRoleEntry[];
|
|
85
|
+
/** Highest role of `identity` effective at `scopeKey`. */
|
|
86
|
+
roleAt(identity: ChatIdentity, scopeKey: string): ChatRole | undefined;
|
|
87
|
+
hasRole(identity: ChatIdentity, scopeKey: string, role: ChatRole): boolean;
|
|
88
|
+
/**
|
|
89
|
+
* Per role, the topmost level at which `identity` holds that role (or a higher one) on the chain
|
|
90
|
+
* of `scopeKey` (`sender.chatRoleLevels`).
|
|
91
|
+
*/
|
|
92
|
+
levelsFor(identity: ChatIdentity, scopeKey: string): ChatRoleLevels;
|
|
93
|
+
/** Highest role held at a scope strictly above `scopeKey`. */
|
|
94
|
+
roleAbove(identity: ChatIdentity, scopeKey: string): ChatRole | undefined;
|
|
95
|
+
/** Sender roles for a message (`undefined` outside a keyed conversation). */
|
|
96
|
+
effectiveRoles(snapshot: ChatRoleSnapshot, message: unknown): ChatRoleResolution | undefined;
|
|
97
|
+
/** Stored entries covering `scopeKey` (and below it with `descendants`). */
|
|
98
|
+
list(scopeKey: string, descendants?: boolean): readonly ChatRoleEntry[];
|
|
99
|
+
/**
|
|
100
|
+
* Stored `owner`s of `scopeKey` and its ancestors whose identity is on `adapter`, closest scope
|
|
101
|
+
* first (who to ask for owner approval on an account).
|
|
102
|
+
*/
|
|
103
|
+
ownersOf(scopeKey: string, adapter: string): readonly string[];
|
|
104
|
+
}
|
|
105
|
+
/** Normalized platform standing of a sender (`sender.platform`, ADR 0056 §1). */
|
|
106
|
+
export declare function platformStandingOf(sender: unknown): PlatformStanding | undefined;
|
|
107
|
+
/** `platform:admin` is met by `admin` and `owner` standings, `platform:owner` only by `owner`. */
|
|
108
|
+
export declare function platformStandingIncludes(held: PlatformStandingLevel | undefined, required: 'owner' | 'admin'): boolean;
|
|
109
|
+
/**
|
|
110
|
+
* Identity + context of a message's sender. `context.conversationKey` is the conversation key, or —
|
|
111
|
+
* when the conversation cannot be keyed (unknown kind, an id that cannot be part of a key) — the
|
|
112
|
+
* receiving endpoint's key, so roles granted at the endpoint level and above still resolve.
|
|
113
|
+
* Threads / topics (`conversation.threadId`) share their parent conversation's key, and a platform
|
|
114
|
+
* container (`conversation.parent`, e.g. a guild) adds no level (ADR 0056 §2).
|
|
115
|
+
* Undefined when not even the endpoint can be addressed.
|
|
116
|
+
*/
|
|
117
|
+
export declare function chatRoleMessageContext(snapshot: ChatRoleSnapshot, message: unknown): {
|
|
118
|
+
identity: ChatIdentity;
|
|
119
|
+
context: ChatRoleContext & {
|
|
120
|
+
conversationKey: string;
|
|
121
|
+
};
|
|
122
|
+
} | undefined;
|
|
123
|
+
export interface ChatRoleSenderFields {
|
|
124
|
+
readonly id: string;
|
|
125
|
+
readonly platform?: PlatformStanding;
|
|
126
|
+
readonly chatRole?: ChatRole;
|
|
127
|
+
readonly chatRoleLevels?: ChatRoleLevels;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Inbound sender enricher: drops any adapter-supplied `chatRole` / `chatRoleLevels`, normalizes
|
|
131
|
+
* `platform` (not in private chats) and sets `chatRole` to the highest role effective in the
|
|
132
|
+
* conversation and `chatRoleLevels` to where each role comes from.
|
|
133
|
+
*/
|
|
134
|
+
export declare function createChatRoleSenderEnricher(options: Readonly<{
|
|
135
|
+
roles: () => ChatRoleService | undefined;
|
|
136
|
+
}>): <TSender extends ChatRoleSenderFields>(sender: TSender | undefined, conversation: ConversationRef, snapshot?: RuntimeSnapshot) => TSender | undefined;
|
|
137
|
+
/**
|
|
138
|
+
* 转义用户正文里所有自造的 `[sender:` / `[origin:` 标签(任意位置、大小写不敏感,
|
|
139
|
+
* 容忍 `[ sender :`、零宽字符、全角冒号)。命中时把开头的 ASCII `[` 换成全角 `[`,
|
|
140
|
+
* 其余原样保留:模型仍能看出这是用户文本,但它不再是权威标签。
|
|
141
|
+
* 幂等(已转义文本再次调用不变),不再剥离开头,也不 trim 原文空白。
|
|
142
|
+
*/
|
|
14
143
|
export declare function stripUserSpoofedSenderPrefix(rawContent: string): string;
|