XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
// Native ia32 instrumentation inside WXWork.exe; no browser or window APIs.
'use strict';
const profile = __PROFILE__;
if (Process.arch !== 'ia32' || Process.mainModule.name.toLowerCase() !== 'wxwork.exe') throw new Error('客户端架构不匹配。');
const base = Process.mainModule.base;
const entries = {
  create: [0x0816FFB0, '6690558bec'], assign: [0x001F81DA, '558bec5156'],
  release: [0x0026D0F0, '568b710485'], allocate: [0x0A04CDC4, '558beceb0d'],
  infoConstructor: [0x026988F0, '8bd10f57c0'], parseContent: [0x015D8B90, '6690558bec'],
  selfId: [0x097D11B0, '8b414485c0'], submit: [0x096358B0, '6690558bec'],
  stringDestroy: [0x001F8530, 'e9c2ffffff'], notification: [0x00496C30, '558bec6aff'],
  postNotification: [0x00496160, '558bec6aff']
};
function entry(name) {
  const e = entries[name], p = base.add(e[0]);
  const hex = Array.from(new Uint8Array(p.readByteArray(5))).map(n => n.toString(16).padStart(2, '0')).join('');
  if (hex !== e[1]) throw new Error('原生入口不匹配:' + name);
  return p;
}
const create = new NativeFunction(entry('create'), 'pointer', ['pointer', 'pointer'], 'mscdecl');
const assign = new NativeFunction(entry('assign'), 'pointer', ['pointer', 'pointer', 'uint32'], 'thiscall');
const release = new NativeFunction(entry('release'), 'void', ['pointer'], 'thiscall');
const allocate = new NativeFunction(entry('allocate'), 'pointer', ['uint32'], 'mscdecl');
const infoConstructor = new NativeFunction(entry('infoConstructor'), 'pointer', ['pointer'], 'thiscall');
const parseContent = new NativeFunction(entry('parseContent'), 'pointer', ['pointer', 'uint32', 'pointer'], 'mscdecl');
const getSelfId = new NativeFunction(entry('selfId'), 'uint64', ['pointer'], 'thiscall');
const submit = new NativeFunction(entry('submit'), 'pointer', ['pointer', 'pointer', 'pointer', 'pointer', 'pointer'], 'thiscall');
const destroyString = new NativeFunction(entry('stringDestroy'), 'void', ['pointer'], 'thiscall');
const postNotification = new NativeFunction(entry('postNotification'), 'void', ['pointer', 'pointer', 'pointer', 'uint32'], 'thiscall');
const manager = ptr(profile.managerObject), managerControl = ptr(profile.managerControl);
function currentSelfId() {
  if (!manager.equals(managerControl.add(12)) ||
      !managerControl.readPointer().equals(base.add(0x0BA69DC0)) || managerControl.add(4).readU32() === 0)
    throw new Error('发送上下文已失效。');
  const environment = manager.add(8).readPointer();
  if (environment.isNull()) throw new Error('登录会话已失效。');
  const id = getSelfId(environment).toString();
  if (id === '0' || id === '18446744073709551615') throw new Error('当前账号未登录。');
  return id;
}
const selfId = currentSelfId();
function stringAt(p, limit = 256) {
  const n = p.add(16).readU32(), c = p.add(20).readU32();
  if (n > limit || c < n || c > 131072 || c < 15) throw new Error('原生字符串结构异常。');
  return (c === 15 ? p : p.readPointer()).readUtf8String(n);
}
function empty(size) { const p = Memory.alloc(size); p.writeByteArray(new Uint8Array(size)); return p; }
function utf8Length(text) {
  let size = 0;
  for (const character of text) { const c = character.codePointAt(0); size += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; }
  return size;
}
let active = false, listeningSince = 0, stopped = false, selfTestSince = 0;
const seen = new Set(profile.baselineIds);
let nativeReceived = 0, dispatchCount = 0;
const observer = Interceptor.attach(entry('notification'), {
  onEnter(args) {
    if (stopped) return;
    dispatchCount++;
    try {
      if (args[1].add(16).readU32() > 128) return;
      const name = stringAt(args[1], 128);
      const testingSelf = selfTestSince > 0 && Date.now() - selfTestSince < 10000;
      if (name !== 'ConversationMessagesDidReceiveNotification' && !testingSelf) return;
      const holder = args[2].readPointer();
      if (holder.isNull() || !holder.readPointer().equals(base.add(0x0B0343D8))) return;
      const begin = holder.add(4).readPointer(), end = holder.add(8).readPointer(), capacity = holder.add(12).readPointer();
      if (end.compare(begin) < 0 || capacity.compare(end) < 0) throw new Error('消息向量结构异常。');
      const bytes = end.sub(begin).toUInt32();
      if (bytes % 8 !== 0 || bytes > 80000) throw new Error('消息向量长度异常。');
      for (let offset = 0; offset < bytes; offset += 8) {
        const shared = begin.add(offset), object = shared.readPointer(), control = shared.add(4).readPointer();
        if (object.isNull() || control.isNull() || !control.readPointer().equals(base.add(0x0AF984F0))) continue;
        const conversationId = stringAt(object.add(0x28));
        const ownTest = testingSelf && conversationId === 'FILEASSIST';
        if (!ownTest && name !== 'ConversationMessagesDidReceiveNotification') continue;
        if (!conversationId || conversationId.length > 512 || /[\x00-\x1f\x7f]/.test(conversationId)) continue;
        const senderId = object.add(0x48).readU64().toString();
        if (!ownTest && (senderId === '0' || senderId === '18446744073709551615' || senderId === selfId)) continue;
        const localId = object.readU64().toString(), clientId = stringAt(object.add(0x10));
        if (localId === '0' && !clientId) continue;
        const messageId = clientId || 'L:' + localId;
        const createdSeconds = Number(object.add(0x58).readU64().toString());
        const event = {event: ownTest ? 'self-test-notification' : 'message', notification: name,
          messageId, localId, clientId, serverId: object.add(8).readU64().toString(),
          conversationId, senderId, rawType: object.add(0x50).readU32(),
          createdSeconds, receivedAtUtc: new Date().toISOString()};
        if (ownTest) { if (createdSeconds * 1000 >= selfTestSince - 2000) send(event); continue; }
        const messageKey = conversationId + ':' + messageId;
        if (seen.has(messageKey)) continue;
        if (seen.size >= 100000) throw new Error('消息去重缓存已满,请重新连接。');
        seen.add(messageKey);
        if (!active || Date.now() < listeningSince) continue;
        nativeReceived++; send(event);
      }
    } catch (error) {
      // Fail closed on a structure mismatch instead of silently losing orders.
      if (active) { active = false; send({event: 'fatal', detail: String(error)}); }
    }
  }
});
function sendText(conversationId, content, selfTest, quoteReference = null) {
  if (stopped || currentSelfId() !== selfId) throw new Error('登录账号已变更,请重新连接。');
  if (selfTest ? conversationId !== 'FILEASSIST' : typeof conversationId !== 'string' || !conversationId || /[\x00-\x1f\x7f]/.test(conversationId) || !quoteReference || !quoteReference.messageId || !quoteReference.localId || !quoteReference.senderId)
    throw new Error('回复必须来自有效的收到消息事件。');
  if (typeof content !== 'string' || content.length === 0 || content.length > 256 || /[\x00-\x1f\x7f]/.test(content))
    throw new Error('回复内容无效。');
  const text = empty(24), output = empty(8), infoShared = empty(8);
  text.add(20).writeU32(15);
  try {
    assign(text, Memory.allocUtf8String(content), utf8Length(content));
    create(output, text);
    const model = output.readPointer();
    if (model.isNull() || !output.add(4).readPointer().readPointer().equals(base.add(0x0AF984F0)))
      throw new Error('文本消息构造失败。');
    const control = allocate(0x138);
    if (control.isNull()) throw new Error('原生分配失败。');
    control.writeByteArray(new Uint8Array(0x138));
    control.writePointer(base.add(0x0B0B2D24)); control.add(4).writeU32(1); control.add(8).writeU32(1);
    const info = control.add(16);
    infoConstructor(info); infoShared.writePointer(info); infoShared.add(4).writePointer(control);
    assign(info, Memory.allocUtf8String(conversationId), utf8Length(conversationId));
    info.add(0x18).writeU32(2);
    parseContent(info.add(0x1C), 2, model.add(0x1B8));
    if (info.add(0x1C).readPointer().isNull()) throw new Error('原生文本内容解析失败。');
    const quoted = quoteReference?.quoteOriginal ? applyNativeQuote(info, conversationId, quoteReference.messageId, quoteReference.localId, selfTest, quoteReference.senderId) : null;
    const result = empty(16), emptyCallback = empty(40);
    submit(manager, result, infoShared, emptyCallback, emptyCallback);
    // The native result is two uint64 values: task ID and local message ID.
    // It is NOT a shared_ptr/future and must never be passed to release().
    const taskId = result.readU64().toString(), localId = result.add(8).readU64().toString();
    return {status: taskId !== '0' && localId !== '0' ? 'Accepted' : 'Rejected', taskId, localId, quoted};
  } finally {
    if (!infoShared.readPointer().isNull()) release(infoShared);
    if (!output.readPointer().isNull()) release(output);
    destroyString(text);
  }
}
rpc.exports = {
  initialize() {
    // A unique notification with no subscribers or message payload checks the
    // installed native interception path without creating any chat message.
    const name = empty(24), any = empty(4), count = dispatchCount;
    name.add(20).writeU32(15);
    const nonce = 'WeChatAutoReplySystem.NativeHealthPing.' + Process.id;
    try {
      assign(name, Memory.allocUtf8String(nonce), nonce.length);
      const center = base.add(0x0FB256BC).readPointer();
      if (center.isNull()) throw new Error('通知中心未就绪。');
      postNotification(center, name, any, 0);
      if (dispatchCount <= count) throw new Error('原生消息观察入口未生效。');
    } finally { destroyString(name); }
    return {selfId, pid: Process.id, nativeReceived, hookVerified: true};
  },
  watch(since, baselineIds = []) {
    if (stopped) throw new Error('接口已停止。');
    currentSelfId();
    if (!Array.isArray(baselineIds) || baselineIds.length >= 100000 || baselineIds.some(id => typeof id !== 'string' || !id))
      throw new Error('消息基线无效。');
    for (const id of baselineIds) seen.add(id);
    if (seen.size >= 100000) throw new Error('消息去重缓存已满,请重新连接。');
    listeningSince = Date.parse(since);
    if (!Number.isFinite(listeningSince)) throw new Error('监听时间无效。');
    active = true; return {watching: true};
  },
  unwatch() { active = false; return {watching: false, nativeReceived}; },
  sendtext(conversationId, content, reference) { return sendText(conversationId, content, false, reference); },
  sendselftest() { selfTestSince = Date.now(); return sendText('FILEASSIST', '1', true); },
  stop() { active = false; stopped = true; observer.detach(); return {stopped: true, nativeReceived}; }
};