Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mail): 隔离附件快照并对齐邮件声明校验

Dash653df10afcfd
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts
index 7f9dcca6d1..b143d7d198 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts
@@ -358,18 +358,23 @@ it('only a live draft can open the host file picker, and a superseded view canno
status: 'Synced', sendLabel: 'Send', fromLabel: 'From' };
let html = renderMailCard(mail);
const chosen = { path: '/selected/file.pdf', filename: 'file.pdf', bytes: 12, sha256: 'a'.repeat(64) };
- const pickMailAttachment = vi.fn(async () => chosen);
+ const staged = { attachment: chosen, accepted: vi.fn(), discard: vi.fn(async () => {}) };
+ const pickMailAttachment = vi.fn(async () => staged);
const f = makeDispatcher({ getGhost: () => ghost, pickMailAttachment,
- resolvePersistedCard: async () => ({ ghostId: 'cindy-mivo', sessionId: null, html }) });
+ resolveLiveInfo: () => ({ ghostId: 'cindy-mivo', sessionId: 's' }),
+ resolvePersistedCard: async () => ({ ghostId: 'cindy-mivo', sessionId: 's', html }) });
const values = Object.fromEntries(mail.fields.map(f => [f.name, f.value]));
const attach = () => f.dispatcher.dispatch('call', `mail:attach:${mail.key}`, undefined, undefined, values);
expect(await attach()).toEqual({ ok: true });
expect(f.sendToGhost.mock.calls[0][1].mailAttachment).toEqual(chosen);
+ expect(pickMailAttachment).toHaveBeenCalledWith(false, 's');
+ expect(staged.accepted).toHaveBeenCalledTimes(1);
html = renderMailCard({ ...mail, state: 'sent', continueLabel: 'Continue' });
expect((await attach()).ok).toBe(false); expect(pickMailAttachment).toHaveBeenCalledTimes(1);
html = renderMailCard(mail);
- pickMailAttachment.mockImplementation(async () => { html = renderMailCard({ ...mail, supersededBy: 'new' }); return chosen; });
+ pickMailAttachment.mockImplementation(async () => { html = renderMailCard({ ...mail, supersededBy: 'new' }); return staged; });
expect((await attach()).ok).toBe(false); expect(f.sendToGhost).toHaveBeenCalledTimes(1);
+ expect(staged.discard).toHaveBeenCalledTimes(1);
});
it('phone uploads use the task materializer and discard late files when the draft becomes readonly', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts
index 3608bd0422..0ea03cc622 100644
--- a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts
+++ b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts
@@ -18,7 +18,7 @@
*/
import { parseGhostCardFormValues, readMailCard } from '@cindy/maker-shared/ghost-card-form';
-import type { MailAttachmentUpload, prepareMailAttachmentUpload } from './mailAttachmentUpload.js';
+import type { MailAttachmentUpload, PreparedMailAttachment, prepareMailAttachmentUpload } from './mailAttachmentUpload.js';
import {
GHOST_CARD_ACTION_ID_RE,
GHOST_CARD_ACTION_PROMPT_MAX_LEN,
@@ -61,7 +61,7 @@ export interface CardActionDispatchDeps {
onActivityStart?(key: string, sessionId: string): void;
ownerScope?: GhostOwnerScope;
now?(): number;
- pickMailAttachment?(inline: boolean): Promise<{ path: string; filename: string; bytes: number; sha256: string; contentId?: string } | null>;
+ pickMailAttachment?(inline: boolean, sessionId: string): Promise<PreparedMailAttachment | null>;
prepareMailUpload?: typeof prepareMailAttachmentUpload;
log?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
@@ -144,8 +144,8 @@ export class GhostCardActionDispatcher {
return { ok: false, reason: 'ghost-unavailable' };
}
let mailAction = false;
- let mailAttachment: Awaited<ReturnType<NonNullable<CardActionDispatchDeps['pickMailAttachment']>>> = null;
- let staged: Awaited<ReturnType<typeof prepareMailAttachmentUpload>> | undefined;
+ let mailAttachment: PreparedMailAttachment['attachment'] | null = null;
+ let staged: PreparedMailAttachment | undefined;
if (upload && (!mobilePageId || change || !actionId.startsWith('mail:attach:'))) return { ok: false, reason: 'bad-mail-upload' };
if (actionId.startsWith('mail:')) {
const stored = await this.deps.resolvePersistedCard(callId);
@@ -165,12 +165,12 @@ export class GhostCardActionDispatcher {
(mail.state === 'sent' && expected !== 'continue'))) return { ok: false, reason: 'mail-view-readonly' };
if (!countdownAction && !deleteAction && expected !== 'continue' && (!fields || Object.keys(fields).length !== mail.fields.length || mail.fields.some(f => !(f.name in fields)))) return { ok: false, reason: 'bad-mail-fields' };
if (attachmentAction) {
- if (mobilePageId ? (!upload || !sessionId || !this.deps.prepareMailUpload) : !this.deps.pickMailAttachment) return { ok: false, reason: 'mail-attachment-picker-unavailable' };
+ if (!sessionId || (mobilePageId ? (!upload || !this.deps.prepareMailUpload) : !this.deps.pickMailAttachment)) return { ok: false, reason: 'mail-attachment-picker-unavailable' };
try {
if (mobilePageId) {
staged = await this.deps.prepareMailUpload!(upload!, sessionId!);
- mailAttachment = staged.attachment;
- } else mailAttachment = await this.deps.pickMailAttachment!(actionId.startsWith('mail:image:'));
+ } else staged = await this.deps.pickMailAttachment!(actionId.startsWith('mail:image:'), sessionId) ?? undefined;
+ mailAttachment = staged?.attachment ?? null;
}
catch { return { ok: false, reason: 'mail-attachment-read-failed' }; }
if (!ownerUsable()) { await staged?.discard(); return rejectStaleOwner(ghostId); }
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 17466b3f97..eadb73a46e 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1854,6 +1854,8 @@ v3 直接用顶层字段声明插件贡献项与自主 Host 能力,不再有 \
邮件插件声明 \`mail: true\`,调用 Cindy 内置 \`cindyMail.register(adapter)\`
(version 1),不生成卡片 HTML、不打包公共流程;纯邮件插件不需要 \`card\`。
阅读邮件可声明 \`mailReader:{tool,hosts}\`,工具接收 \`{url}\` 并返回 MailMessage,默认只读。
+\`mail\` 只能省略或写字面量 \`true\`;声明 \`mailReader\` 时必须同时有 \`mail: true\`,
+且 \`tool\` 必须指向本清单 \`tools\` 中的工具。协议校验与桌面安装校验都会拒绝不完整组合。
支持打开即已读时增加 \`mailReader.markRead:true\`,读取工具接受可选 \`markRead:true\`;
声明中的 \`markRead\` 只能省略或为字面量 \`true\`,\`false\`、字符串等其它值不合法。
仅用户主动打开时传入,AI 读取和邻近预加载不传。成功读取后只标记当前邮件,不标记整个会话或草稿。
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 7beefdcfd0..02fe8d308b 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -334,7 +334,8 @@ import { GHOST_SCHEME, ghostExternalLinkUrls } from '../../shared/ghost.js';
import { GhostPipeDispatcher } from './pipeDispatcher.js';
import { GhostCardService, parseCardHeightReport } from './cardService.js';
import { MailCardService } from './mailCards.js';
-import { prepareMailAttachmentUpload } from './mailAttachmentUpload.js';
+import { prepareMailAttachmentSelection, prepareMailAttachmentUpload } from './mailAttachmentUpload.js';
+import { writeTempFile } from '../maker-ipc/normalizeAttachments.js';
import { GhostCardActionDispatcher } from './cardActionDispatch.js';
import { GhostSessionActivityTracker } from './ghostSessionActivity.js';
import { sanitizeGhostCardHtml } from './cardSanitizer.js';
@@ -2354,20 +2355,11 @@ export function getGhostCardActionDispatcher(): GhostCardActionDispatcher {
},
issueUserActionToken: (ghostId, sessionId) =>
getGhostAgentSlot().issueUserActionToken(ghostId, sessionId),
- pickMailAttachment: async inline => {
+ pickMailAttachment: async (inline, sessionId) => {
const result = await dialog.showOpenDialog({ properties: ['openFile'],
...(inline ? { filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'] }] } : {}) });
if (result.canceled || !result.filePaths[0]) return null;
- const filePath = result.filePaths[0];
- const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
- try {
- const stat = await handle.stat();
- if (!stat.isFile() || stat.size > 16 * 1024 * 1024) throw new Error('attachment-too-large');
- const bytes = await handle.readFile();
- return { path: filePath, filename: path.basename(filePath), bytes: bytes.length,
- sha256: createHash('sha256').update(bytes).digest('hex'),
- ...(inline ? { contentId: randomUUID() + '@cindy.local' } : {}) };
- } finally { await handle.close(); }
+ return prepareMailAttachmentSelection(result.filePaths[0], sessionId, inline, writeTempFile);
},
prepareMailUpload: prepareMailAttachmentUpload,
// 呼吸起点:点击成功投递即把该会话标为"意识活动中"(结束由 card-update
diff --git a/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts b/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts
index 106c3e345e..44673a012c 100644
--- a/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts
+++ b/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts
@@ -1,10 +1,40 @@
import fs from 'node:fs/promises';
-import { createHash } from 'node:crypto';
+import { constants } from 'node:fs';
+import path from 'node:path';
+import { createHash, randomUUID } from 'node:crypto';
import { parseAttachmentOssRef, parsePeerAttachmentRef } from '@cindy/device-link';
+import type { writeTempFile } from '../maker-ipc/normalizeAttachments.js';
const parseUploadRef = (url: string) => parsePeerAttachmentRef(url) || parseAttachmentOssRef(url);
export interface MailAttachmentUpload { url: string; name: string }
+/** Both local selection and phone uploads share the dispatch acceptance lifecycle. */
+export interface PreparedMailAttachment {
+ attachment: { path: string; filename: string; bytes: number; sha256: string; contentId?: string };
+ accepted(): void;
+ discard(): Promise<void>;
+}
+
+/** Snapshot the selected bytes into the existing session-owned temporary store.
+ * The sandbox/Node adapter never receives the user's source path or rereads it. */
+export async function prepareMailAttachmentSelection(filePath: string, sessionId: string, inline: boolean, writeSnapshot: typeof writeTempFile): Promise<PreparedMailAttachment> {
+ const handle = await fs.open(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ let bytes: Buffer;
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size > 16 * 1024 * 1024) throw new Error('attachment-too-large');
+ bytes = await handle.readFile();
+ if (bytes.length > 16 * 1024 * 1024) throw new Error('attachment-too-large');
+ } finally { await handle.close(); }
+ const stagedPath = await writeSnapshot(sessionId, bytes, undefined);
+ return {
+ attachment: { path: stagedPath, filename: path.basename(filePath), bytes: bytes.length,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ ...(inline ? { contentId: randomUUID() + '@cindy.local' } : {}) },
+ accepted: () => {}, // Session/orphan cleanup already owns accepted files.
+ discard: async () => { await fs.rm(stagedPath, { force: true }); },
+ };
+}
export function parseMailAttachmentUpload(value: unknown): MailAttachmentUpload | null {
if (!value || typeof value !== 'object') return null;
const p = value as Record<string, unknown>;
@@ -18,7 +48,7 @@ export function parseMailAttachmentUpload(value: unknown): MailAttachmentUpload
/** Reuse task attachment materialization and its owner/session cleanup. Never
* accept a phone-supplied desktop path, or create a second upload store. */
-export async function prepareMailAttachmentUpload(input: MailAttachmentUpload, sessionId: string) {
+export async function prepareMailAttachmentUpload(input: MailAttachmentUpload, sessionId: string): Promise<PreparedMailAttachment> {
const upload = parseMailAttachmentUpload(input);
if (!upload) throw new Error('INVALID_MAIL_ATTACHMENT');
const ref = parseUploadRef(upload.url)!;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
index f8d6694774..ef2569466e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
@@ -37,12 +37,14 @@ import {
materializeDirectSendOssAttachments,
materializeQueuedOssAttachmentsDeferred,
normalizeUserMessage,
+ writeTempFile,
} from '../normalizeAttachments.js';
import * as imageCacheStore from '../../imageCacheStore.js';
import * as cindyMediaBlobStore from '../../cindy-media/blobStore.js';
import { ingestMedia } from '../../cindy-media/ingest.js';
import { downloadToFile, removeRemote } from '../../device-link/mediaTransfer.js';
import { buildAttachmentOssRef } from '../../../shared/attachmentOssRef.js';
+import { prepareMailAttachmentSelection } from '../../cindy-brain/mailAttachmentUpload.js';
const tempDirs: string[] = [];
@@ -61,6 +63,30 @@ afterEach(async () => {
});
describe('inline attachment temporary files', () => {
+ // Unit, real isolated bytes: PR #6404 selected-file path disclosure/TOCTOU.
+ // Existing temp tests did not traverse the mail picker handoff. Replacing the
+ // selected source must not change the delivered file; rollback removes only
+ // the staged copy, and acceptance retains the existing session cleanup.
+ it('stages selected mail bytes without exposing or retaining the source path', async () => {
+ const source = path.join(tempRoot.value, 'personal-name.txt');
+ for (const inline of [false, true]) {
+ await fs.writeFile(source, 'selected');
+ const staged = await prepareMailAttachmentSelection(source, 'mail-selection', inline, writeTempFile);
+ expect(staged.attachment.filename).toBe('personal-name.txt');
+ expect(staged.attachment.path).not.toBe(source);
+ expect(staged.attachment.path).not.toContain('personal-name');
+ await fs.writeFile(source, 'replaced');
+ expect(await fs.readFile(staged.attachment.path, 'utf8')).toBe('selected');
+ expect(staged.attachment.bytes).toBe(8);
+ expect(Boolean(staged.attachment.contentId)).toBe(inline);
+ if (inline) {
+ staged.accepted();
+ await cleanupSessionTempAttachments('mail-selection');
+ } else await staged.discard();
+ await expect(fs.stat(staged.attachment.path)).rejects.toThrow();
+ expect(await fs.readFile(source, 'utf8')).toBe('replaced');
+ }
+ });
it('keeps a resolved xdt-image URL as the Host-managed image identity', async () => {
const imageUrl = 'xdt-image://managed-reference/source.png';
const absPath = path.join(tempRoot.value, 'source.png');
diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
index 49ab85301a..ba57078c83 100644
--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
@@ -257,7 +257,7 @@ async function ensureTempPath(sessionId: string, mimeType: string | undefined):
return path.join(dir, `${randomUUID()}${ext}`);
}
-async function writeTempFile(
+export async function writeTempFile(
sessionId: string,
bytes: Buffer,
mimeType: string | undefined,
diff --git a/apps/desktop/src/shared/__tests__/mailMessage.test.ts b/apps/desktop/src/shared/__tests__/mailMessage.test.ts
index 87967b325d..7f163d6217 100644
--- a/apps/desktop/src/shared/__tests__/mailMessage.test.ts
+++ b/apps/desktop/src/shared/__tests__/mailMessage.test.ts
@@ -2,6 +2,25 @@ import { expect, it } from 'vitest';
import { parseMailMessage, parseMailReader, mailMessageFields } from '@cindy/maker-shared/mail-message';
import { validateGhostManifest } from '../ghost';
import { validateGhostManifest as validateProtocolManifest } from '@cindy/plugin-protocol';
+// Unit: protocol and installer must reject an unusable known capability, not
+// silently accept it as a future extension (PR #6404 review). Prior tests only
+// exercised reader shape; malformed mail and cross-field links were accepted.
+it('validates mail and reader dependencies in both manifest entry points', () => {
+ for (const schemaVersion of [2, 3]) for (const validate of [validateGhostManifest, validateProtocolManifest]) {
+ const base = { schemaVersion, ...(schemaVersion === 2 ? { slots: ['tool'] } : { minCindyVersion: '0.1.92' }),
+ id: 'example-mail', name: 'Mail', version: '1.0.0', entry: 'main.js',
+ tools: [{ name: 'read_mail', description: 'Read only' }] };
+ for (const mail of [false, 'yes', null, {}, []]) expect(validate({ ...base, mail }).ok).toBe(false);
+ const valid = validate({ ...base, mail: true });
+ expect(valid.ok).toBe(true);
+ if (valid.ok) expect(valid.manifest.mail).toBe(true);
+ const mailReader = { tool: 'read_mail', hosts: ['mail.example.com'] };
+ for (const patch of [{}, { mail: true, tools: undefined }, { mail: true, tools: [{ name: 'other', description: 'Other' }] }]) {
+ expect(validate({ ...base, mailReader, ...patch }).ok).toBe(false);
+ }
+ expect(validate({ ...base, mail: true, mailReader }).ok).toBe(true);
+ }
+});
it.each([null, false, [], { tool: 'read_mail', hosts: 'mail.example.com' }, { tool: 'read_mail', hosts: ['*.com'] }, { hosts: ['mail.example.com'] },
...[false, 'false', 'true', 0, 1, null, {}, []].map(markRead => ({ tool: 'read_mail', hosts: ['mail.example.com'], markRead })),
].map(mailReader => ({ mailReader })))('rejects a malformed known mailReader declaration: $mailReader', ({ mailReader }) => {
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index f4e890506d..41726db29f 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -3118,7 +3118,6 @@ function prepareGhostManifestForValidation(
}
}
- if (value.mail !== undefined && value.mail !== true) return { ok: false, reason: 'mail 出现时必须是 true' };
const syntheticSlots: string[] = [];
for (const [field, slot] of V3_DECLARATION_TO_LEGACY_SLOT) {
if (value[field] !== undefined) syntheticSlots.push(slot);
@@ -3829,10 +3828,15 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
if (!preparation.ok) return preparation;
const prepared = preparation.prepared;
const raw = prepared.raw;
+ if (raw.mail !== undefined && raw.mail !== true) return { ok: false, reason: 'mail 出现时必须是 true' };
const mailReader = raw.mailReader === undefined ? undefined : parseMailReader(raw.mailReader);
if (raw.mailReader !== undefined && !mailReader) {
return { ok: false, reason: 'mailReader 必须声明合法的 tool 与 hosts' };
}
+ if (mailReader && (raw.mail !== true || !Array.isArray(raw.tools) ||
+ !raw.tools.some(tool => isPlainObject(tool) && tool.name === mailReader.tool))) {
+ return { ok: false, reason: 'mailReader 必须同时声明 mail: true 与对应的 tools 工具' };
+ }
if (!isValidGhostId(raw.id)) {
return { ok: false, reason: 'id 必须是 1–32 位小写字母/数字/连字符(不能以连字符开头)' };
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 8f8795a2f8..dbde9e6609 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -2384,7 +2384,11 @@ Desktop attachment actions `mail:attach` / `mail:image` are native Host gestures
not plugin HTML controls. The dispatcher verifies current view, owner, mail
capability and draft state before and after the native picker, and passes one
transient hash/size-bound file descriptor to the provider event. No arbitrary
-path comes from form text. Pending or sent mail cannot open the picker. Mobile
+path comes from form text. Selected desktop bytes are copied into the existing
+session-owned temporary attachment store; only the staged descriptor crosses
+the plugin boundary, never the user's original path. Source replacement after
+selection cannot change the staged bytes. Failed/stale delivery discards the
+copy; accepted files retain normal session/orphan cleanup. Pending or sent mail cannot open the picker. Mobile
resource metadata adds optional `mailUpload`; old hosts omit it and new phones
hide the upload button. Supporting hosts accept `mail:attach:<key>` with optional
`input.mailAttachment: {url,name}` and the complete form. Only existing OSS/peer
@@ -2440,6 +2444,8 @@ blocked; preview sanitization never mutates the saved HTML.
### Read-only mail preview
Mail providers may declare `mailReader: { tool, hosts }` alongside `mail: true`.
+`mail` accepts only omission or literal `true` in both v2 and v3; both validators
+reject a reader without `mail: true` or without its matching tool in `tools`.
Desktop and plugin-protocol validate this known declaration and retain future
extension data; malformed declarations cannot survive as unknown top-level fields.
The tool must be declared and read-only by default. Cindy matches exact HTTPS hosts
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index 61fd68c167..33fbe1ca74 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -856,6 +856,8 @@ export const GHOST_SETUP_KV_KEY_RE = /^[A-Za-z0-9_.-]{1,64}$/;
/** 已校验的 ghost.json 协议文档;Desktop 会再投影成无 slots 的运行时模型。 */
export interface GhostManifest {
+ /** Host-owned mail editor; providers supply mailbox adapters only. */
+ mail?: true;
/** Provider-owned read capability; Cindy owns mail presentation. */
mailReader?: { tool: string; hosts: string[]; markRead?: true };
/** Optional v3 extension; consumers validate it without changing legacy approval content. */
@@ -1174,6 +1176,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set([
'settingsHeight',
'slots',
'card',
+ 'mail',
'mailReader',
'tools',
'cindy',
@@ -1338,6 +1341,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
if (!preparation.ok) return preparation;
const prepared = preparation.prepared;
const raw = prepared.raw;
+ if (raw.mail !== undefined && raw.mail !== true) return { ok: false, reason: 'mail 出现时必须是 true' };
// Keep this shape aligned with maker-shared's runtime reader parser.
const reader = raw.mailReader as Record<string, unknown> | undefined;
if (raw.mailReader !== undefined && (!reader || typeof reader !== 'object' ||
@@ -1347,6 +1351,10 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
!reader.hosts.every(h => typeof h === 'string' && h.length <= 253 && /^[a-z0-9]+(?:[.-][a-z0-9]+)*\.[a-z]{2,}$/.test(h)))) {
return { ok: false, reason: 'mailReader 必须声明合法的 tool 与 hosts' };
}
+ if (reader && (raw.mail !== true || !Array.isArray(raw.tools) ||
+ !raw.tools.some(tool => isPlainObject(tool) && tool.name === reader.tool))) {
+ return { ok: false, reason: 'mailReader 必须同时声明 mail: true 与对应的 tools 工具' };
+ }
if (!isValidGhostId(raw.id)) {
return {
ok: false,
@@ -3765,6 +3773,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
? { card: card ?? {} }
: {}),
...(tools !== undefined ? { tools } : {}),
+ ...(raw.mail === true ? { mail: true as const } : {}),
...(reader ? { mailReader: { ...reader, tool: reader.tool as string, hosts: [...new Set(reader.hosts as string[])] } } : {}),
...(cindy !== undefined ? { cindy } : {}),
...(subscribe !== undefined ? { subscribe } : {}),