← 中文资源

简体中文版本

校验浏览器扩展的消息路由

按允许的"发送方到接收方"路由表检查每条消息,报告已路由的消息以及被拒绝并附原因的消息。

阅读英文原文

任务

先确认发送方在路由表中存在,再检查目标接收方是否在允许列表内,输出已路由与被拒绝的消息。

契约

  • 输入:JSON 对象:{ routes: { [sender]: string[] }, messages: [{ from, to, type }] }
  • 输出:JSON 对象:{ routed: string[], rejected: [{ id, reason }] }

样例

  1. 输入 {"routes":{"content":["background"],"background":["content","storage"]},"messages":[{"id":"m1","from":"content","to":"background","type":"sync"},{"id":"m2","from":"content","to":"storage","type":"read"}]} -> 期望 {"routed":["m1"],"rejected":[{"id":"m2","reason":"route-not-allowed"}]}。在这份策略下,内容脚本不允许直接与存储通信。
  2. 输入 {"routes":{"popup":["background"]},"messages":[{"id":"m3","from":"popup","to":"background","type":"query"},{"id":"m4","from":"unknown","to":"background","type":"query"}]} -> 期望 {"routed":["m3"],"rejected":[{"id":"m4","reason":"unknown-sender"}]}。发送方不在路由表中时,会在考虑路由之前就被拒绝。

参考实现

function solve({ routes, messages }) {
      const routed = [];
      const rejected = [];
      for (const message of messages) {
        if (!Object.prototype.hasOwnProperty.call(routes, message.from)) {
          rejected.push({ id: message.id, reason: 'unknown-sender' });
          continue;
        }
        if (!routes[message.from].includes(message.to)) {
          rejected.push({ id: message.id, reason: 'route-not-allowed' });
          continue;
        }
        routed.push(message.id);
      }
      return { routed, rejected };
    }

为什么有效

扩展的权限边界靠消息路由来落实。一个内容脚本若能向后台发送任意类型的消息,就等于开出了一条提权通道。

先检查发送方是否存在,再看路由权限;把两者混在一起会掩盖配置错误。