从 MessageEvent.data、反序列化结果或其他外部边界取得的未知值。null、数组和非对象值会直接返回 false。
输入满足 v1/v2 envelope 及当前 type 的最低结构要求时返回 true,并将 TypeScript 类型收窄为
MiniProgramBridgeMessage;否则返回 false。
所有通过的消息都必须使用 MINI_PROGRAM_MESSAGE_NAMESPACE,version 必须为 1 或 2,
nonce 必须为非空字符串。随后按 type 执行以下最低校验:
handshake(v1/v2):id 非空,method 固定为 SDK_HANDSHAKE_METHOD,error 必须为 undefined;
payload 必须是对象,且包含非空 href、字符串 userAgent 和非空 sdkVersion。request(v1/v2):id 与 method 都是非空字符串,且 error 必须为 undefined;payload 不在此处校验。response(v1/v2):id 非空;method 可省略,提供时必须非空;error 可省略,提供时必须含非空
code 与字符串 message。该最低结构允许 payload 与合法 error 同时存在,终态语义由消费端决定。event(v1/v2):method 非空、error 必须为 undefined,id 可省略或为非空字符串;事件名和
payload 不在此处校验。operation.progress 与 cancel 只接受 v2。progress 还要求非空 id 和受支持的下载或 companion
prepare 进度 payload;cancel 要求非空 id,且 method、payload、error 都必须为 undefined。返回 true 只表示 wire envelope 可识别,不建立信任或授权边界。该函数不会校验
MessageEvent.source / origin,只检查 nonce 非空而不会与当前 iframe 的预期 nonce 比较,也不会确认
握手状态、协商后的版本、请求 ID 是否重复或对应 pending request。除握手和 operation progress 外,它也不校验
payload schema;不会把普通 method / 事件名限制在公开目录,不会检查 Manifest 权限、Runtime 权限状态、
Host 支持、可信用户手势或业务策略。顶层 envelope、握手 payload 与 bridge error 中的额外字段也不会被拒绝。
MINI_PROGRAM_MESSAGE_VERSION 是新消息的发送版本,不是本 guard 的唯一接收版本;接受 v1 是兼容行为, 调用方仍须在握手后确认消息版本与已协商版本一致。method 是否公开及其权限 requirement 应查询 MINI_PROGRAM_PROTOCOL_CAPABILITIES, 权限快照应先交给 parseMiniProgramRuntimePermissions 解析。
类型谓词只收窄到宽泛的 MiniProgramBridgeMessage:payload 仍为 unknown,method 等字段仍保持可选。
需要精确处理 v2 cancel 或 operation progress 时,应在检查判别字段后使用
MiniProgramBridgeCancelMessage 或
MiniProgramBridgeProgressMessage。
import {
MINI_PROGRAM_PROTOCOL_CAPABILITIES,
isMiniProgramBridgeMessage,
} from '@heybox/hb-sdk/protocol';
const publicMethods = new Set<string>(
MINI_PROGRAM_PROTOCOL_CAPABILITIES.map(({ method }) => method),
);
window.addEventListener('message', (event) => {
if (event.source !== iframe.contentWindow) return;
if (expectedOrigin && expectedOrigin !== '*' && event.origin !== expectedOrigin) return;
if (!isMiniProgramBridgeMessage(event.data)) return;
if (event.data.nonce !== expectedNonce) return;
if (event.data.type === 'request') {
const method = event.data.method;
if (!method || !publicMethods.has(method)) return;
// 继续检查握手状态、权限与 method 对应的 payload。
}
});
判断不可信输入是否具有受支持的小程序 bridge 消息结构。