chore(ci): remove one-off compatibility validation
This commit is contained in:
1 parent
ff37736a4a
commit
6797143b04
10 files changed
-914
No files matched your search
@@ -1,93 +0,0 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const { join } = require('node:path');
|
||||
const { test } = require('node:test');
|
||||
|
||||
const nativePath = join(__dirname, '../../../packages/napcat-native');
|
||||
const napiPath = join(nativePath, 'napi2native', 'napi2native.darwin.' + process.arch + '.node');
|
||||
const packetPath = join(nativePath, 'packet', 'MoeHoo.darwin.' + process.arch + '.node');
|
||||
|
||||
async function probe (mode) {
|
||||
if (mode === 'missing-wrapper') {
|
||||
const napi = require(napiPath);
|
||||
assert.throws(() => napi.initHook('1', '2'), /Failed to initialize send hook/);
|
||||
const packet = require(packetPath);
|
||||
assert.equal(packet.initHook('2', '4', () => {}, false), 'error search');
|
||||
return;
|
||||
}
|
||||
|
||||
const wrapper = require('./wrapper.node');
|
||||
const addresses = wrapper.addresses();
|
||||
const napi = require(napiPath);
|
||||
assert.equal(napi.initHook(addresses.coerce, addresses.resolver), true);
|
||||
const lengths = [0, 1, 21, 22, 23, 24, 255, 4096];
|
||||
for (const length of lengths) {
|
||||
const payload = Buffer.from(Array.from({ length }, (_, index) => index % 256));
|
||||
assert.deepEqual(wrapper.convert(payload), payload, 'convert length ' + length);
|
||||
const error = Buffer.from('e'.repeat(length));
|
||||
const result = await wrapper.resolve(-17, error, payload);
|
||||
assert.equal(result.result, -17);
|
||||
assert.equal(result.errMsg, error.toString());
|
||||
assert.equal(result.rsp, payload.toString());
|
||||
assert.deepEqual(result.rspbuffer, payload, 'resolve length ' + length);
|
||||
}
|
||||
for (const value of ['', '文🙂'.repeat(20), 12345, null, true]) {
|
||||
assert.deepEqual(wrapper.convert(value), Buffer.from(String(value)));
|
||||
}
|
||||
const responses = await Promise.all(Array.from({ length: 64 }, (_, index) => {
|
||||
const payload = Buffer.from([0, index, 255, 128]);
|
||||
return wrapper.resolve(index, Buffer.alloc(0), payload).then(result => {
|
||||
assert.equal(result.result, index);
|
||||
assert.deepEqual(result.rspbuffer, payload);
|
||||
});
|
||||
}));
|
||||
assert.equal(responses.length, 64);
|
||||
|
||||
const packet = require(packetPath);
|
||||
const received = [];
|
||||
assert.equal(packet.initHook(addresses.send, addresses.recv, (...args) => received.push(args), false), 'success');
|
||||
assert.equal(wrapper.emptyPackets(), 7);
|
||||
const expected = [];
|
||||
for (const length of lengths) {
|
||||
const uin = Buffer.from('1'.repeat(length));
|
||||
const command = Buffer.from('C'.repeat(length));
|
||||
const payload = Buffer.from(Array.from({ length }, (_, index) => index % 256));
|
||||
for (const direction of [0, 1]) {
|
||||
const sequence = length + 3000;
|
||||
const result = wrapper.packet(direction, uin, command, sequence, payload);
|
||||
assert.equal(result.returned, direction === 0 ? 102 : 209);
|
||||
assert.deepEqual(result.command, command);
|
||||
expected.push([direction, direction === 0 ? '0' : uin.toString(), command.toString(), sequence, payload.toString('hex').toUpperCase()]);
|
||||
}
|
||||
}
|
||||
const embeddedNull = Buffer.from('A\0B');
|
||||
wrapper.packet(1, embeddedNull, embeddedNull, 99, Buffer.from([255, 0, 128]));
|
||||
expected.push([1, 'A\0B', 'A\0B', 99, 'FF0080']);
|
||||
packet.setO3Setting(true);
|
||||
const replaced = wrapper.packet(0, Buffer.from('1'), Buffer.from('trpc.o3.report.Report.SsoReport'), 0, Buffer.alloc(0));
|
||||
assert.equal(replaced.command.toString(), 'fuck.trpc.o3');
|
||||
packet.setO3Setting(false);
|
||||
for (let attempt = 0; received.length < expected.length && attempt < 100; attempt++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
assert.deepEqual(received, expected);
|
||||
}
|
||||
|
||||
if (process.argv[2] === '--probe') {
|
||||
probe(process.argv[3]).catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
} else {
|
||||
for (const mode of ['missing-wrapper', 'hooks']) {
|
||||
test('macOS ' + process.arch + ' native ' + mode, () => {
|
||||
const result = spawnSync(process.execPath, [__filename, '--probe', mode], {
|
||||
encoding: 'utf8',
|
||||
timeout: 20000,
|
||||
});
|
||||
assert.ifError(result.error);
|
||||
assert.equal(result.signal, null, result.stderr);
|
||||
assert.equal(result.status, 0, result.stderr + result.stdout);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,317 +0,0 @@
|
||||
#include <node_api.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct alignas(8) QQString
|
||||
{
|
||||
std::array<uint8_t, 24> bytes{};
|
||||
};
|
||||
|
||||
#if defined(__aarch64__)
|
||||
constexpr size_t flagOffset = 23;
|
||||
constexpr size_t dataOffset = 0;
|
||||
constexpr uint8_t heapMask = 0x80;
|
||||
#else
|
||||
constexpr size_t flagOffset = 0;
|
||||
constexpr size_t dataOffset = 16;
|
||||
constexpr uint8_t heapMask = 1;
|
||||
#endif
|
||||
|
||||
static uint64_t ReadWord(const QQString &value, size_t offset)
|
||||
{
|
||||
uint64_t word;
|
||||
std::memcpy(&word, value.bytes.data() + offset, sizeof(word));
|
||||
return word;
|
||||
}
|
||||
|
||||
static void WriteWord(QQString &value, size_t offset, uint64_t word)
|
||||
{
|
||||
std::memcpy(value.bytes.data() + offset, &word, sizeof(word));
|
||||
}
|
||||
|
||||
static QQString MakeString(const void *data, size_t length)
|
||||
{
|
||||
QQString value;
|
||||
if (length <= 22)
|
||||
{
|
||||
#if defined(__aarch64__)
|
||||
std::memcpy(value.bytes.data(), data, length);
|
||||
value.bytes[23] = length;
|
||||
#else
|
||||
std::memcpy(value.bytes.data() + 1, data, length);
|
||||
value.bytes[0] = length * 2;
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t capacity = (length | 15) + 1;
|
||||
auto buffer = static_cast<uint8_t *>(std::calloc(capacity, 1));
|
||||
std::memcpy(buffer, data, length);
|
||||
WriteWord(value, dataOffset, reinterpret_cast<uintptr_t>(buffer));
|
||||
WriteWord(value, 8, length);
|
||||
#if defined(__aarch64__)
|
||||
WriteWord(value, 16, capacity | (uint64_t{1} << 63));
|
||||
#else
|
||||
WriteWord(value, 0, capacity | 1);
|
||||
#endif
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static std::string ReadString(const QQString &value)
|
||||
{
|
||||
if ((value.bytes[flagOffset] & heapMask) != 0)
|
||||
return {reinterpret_cast<const char *>(ReadWord(value, dataOffset)), ReadWord(value, 8)};
|
||||
#if defined(__aarch64__)
|
||||
return {reinterpret_cast<const char *>(value.bytes.data()), value.bytes[23]};
|
||||
#else
|
||||
return {reinterpret_cast<const char *>(value.bytes.data() + 1), static_cast<size_t>(value.bytes[0] / 2)};
|
||||
#endif
|
||||
}
|
||||
|
||||
static void FreeString(const QQString &value)
|
||||
{
|
||||
if ((value.bytes[flagOffset] & heapMask) != 0)
|
||||
std::free(reinterpret_cast<void *>(ReadWord(value, dataOffset)));
|
||||
}
|
||||
|
||||
static QQString FromBuffer(napi_env env, napi_value input)
|
||||
{
|
||||
void *data;
|
||||
size_t length;
|
||||
napi_get_buffer_info(env, input, &data, &length);
|
||||
return MakeString(data, length);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((noinline)) QQString MockCoerce(napi_env env, napi_value input)
|
||||
{
|
||||
napi_value text;
|
||||
napi_coerce_to_string(env, input, &text);
|
||||
size_t length;
|
||||
napi_get_value_string_utf8(env, text, nullptr, 0, &length);
|
||||
std::vector<char> bytes(length + 1);
|
||||
napi_get_value_string_utf8(env, text, bytes.data(), bytes.size(), &length);
|
||||
return MakeString(bytes.data(), length);
|
||||
}
|
||||
|
||||
struct Context
|
||||
{
|
||||
uint8_t padding[24]{};
|
||||
napi_env env;
|
||||
napi_deferred deferred;
|
||||
};
|
||||
|
||||
struct AsyncResult
|
||||
{
|
||||
uint8_t padding[16]{};
|
||||
Context *context;
|
||||
int32_t result;
|
||||
int32_t alignment{};
|
||||
QQString error;
|
||||
QQString response;
|
||||
};
|
||||
|
||||
extern "C" __attribute__((noinline)) void MockResolver(AsyncResult *result)
|
||||
{
|
||||
napi_throw_error(result->context->env, nullptr, "Resolver was not intercepted");
|
||||
}
|
||||
|
||||
static volatile int64_t sendCalls = 0;
|
||||
static volatile int64_t recvCalls = 0;
|
||||
|
||||
extern "C" __attribute__((noinline)) int64_t MockSend(void *self, void **packet)
|
||||
{
|
||||
sendCalls += 1;
|
||||
return 101 + (self != nullptr) + (packet != nullptr);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((noinline)) int64_t MockRecv(void *self, void **packet, uint32_t marker)
|
||||
{
|
||||
recvCalls += 1;
|
||||
return 201 + marker + (self != nullptr) + (packet != nullptr);
|
||||
}
|
||||
|
||||
static napi_value Convert(napi_env env, napi_callback_info info)
|
||||
{
|
||||
size_t argc = 1;
|
||||
napi_value input;
|
||||
napi_get_cb_info(env, info, &argc, &input, nullptr, nullptr);
|
||||
auto output = MockCoerce(env, input);
|
||||
auto bytes = ReadString(output);
|
||||
napi_value result;
|
||||
napi_create_buffer_copy(env, bytes.size(), bytes.data(), nullptr, &result);
|
||||
FreeString(output);
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value Resolve(napi_env env, napi_callback_info info)
|
||||
{
|
||||
size_t argc = 3;
|
||||
napi_value args[3];
|
||||
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
|
||||
Context context{};
|
||||
context.env = env;
|
||||
napi_value promise;
|
||||
napi_create_promise(env, &context.deferred, &promise);
|
||||
AsyncResult result{};
|
||||
result.context = &context;
|
||||
napi_get_value_int32(env, args[0], &result.result);
|
||||
result.error = FromBuffer(env, args[1]);
|
||||
result.response = FromBuffer(env, args[2]);
|
||||
MockResolver(&result);
|
||||
FreeString(result.error);
|
||||
FreeString(result.response);
|
||||
return promise;
|
||||
}
|
||||
|
||||
struct ByteVector
|
||||
{
|
||||
uint8_t *begin;
|
||||
uint8_t *end;
|
||||
};
|
||||
|
||||
struct SendInner
|
||||
{
|
||||
QQString command;
|
||||
uint64_t padding{};
|
||||
ByteVector *payload;
|
||||
};
|
||||
|
||||
struct SendPacket
|
||||
{
|
||||
SendInner *inner;
|
||||
uint8_t padding[48]{};
|
||||
QQString uin;
|
||||
uint64_t alignment{};
|
||||
int64_t sequence;
|
||||
uint8_t tail[16]{};
|
||||
};
|
||||
|
||||
struct RecvPacket
|
||||
{
|
||||
QQString uin;
|
||||
int64_t sequence;
|
||||
QQString command;
|
||||
ByteVector *payload;
|
||||
};
|
||||
|
||||
static_assert(offsetof(AsyncResult, error) == 32);
|
||||
static_assert(offsetof(AsyncResult, response) == 56);
|
||||
static_assert(offsetof(SendPacket, uin) == 56);
|
||||
static_assert(offsetof(SendPacket, sequence) == 88);
|
||||
static_assert(offsetof(RecvPacket, payload) == 56);
|
||||
|
||||
static napi_value Packet(napi_env env, napi_callback_info info)
|
||||
{
|
||||
size_t argc = 5;
|
||||
napi_value args[5];
|
||||
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
|
||||
int32_t direction;
|
||||
int64_t sequence;
|
||||
napi_get_value_int32(env, args[0], &direction);
|
||||
napi_get_value_int64(env, args[3], &sequence);
|
||||
auto uin = FromBuffer(env, args[1]);
|
||||
auto command = FromBuffer(env, args[2]);
|
||||
void *payloadData;
|
||||
size_t payloadLength;
|
||||
napi_get_buffer_info(env, args[4], &payloadData, &payloadLength);
|
||||
uint8_t emptyPayload = 0;
|
||||
auto bytes = payloadLength ? static_cast<uint8_t *>(payloadData) : &emptyPayload;
|
||||
ByteVector payload{bytes, bytes + payloadLength};
|
||||
int64_t returnValue;
|
||||
if (direction == 0)
|
||||
{
|
||||
SendInner inner{command, 0, &payload};
|
||||
SendPacket packet{};
|
||||
packet.inner = &inner;
|
||||
packet.uin = uin;
|
||||
packet.sequence = sequence;
|
||||
void *pointer = &packet;
|
||||
returnValue = MockSend(nullptr, &pointer);
|
||||
command = inner.command;
|
||||
}
|
||||
else
|
||||
{
|
||||
RecvPacket packet{uin, sequence, command, &payload};
|
||||
void *pointer = &packet;
|
||||
returnValue = MockRecv(nullptr, &pointer, 7);
|
||||
}
|
||||
napi_value result;
|
||||
napi_create_object(env, &result);
|
||||
napi_value returned;
|
||||
napi_create_int64(env, returnValue, &returned);
|
||||
napi_set_named_property(env, result, "returned", returned);
|
||||
auto commandBytes = ReadString(command);
|
||||
napi_value outputCommand;
|
||||
napi_create_buffer_copy(env, commandBytes.size(), commandBytes.data(), nullptr, &outputCommand);
|
||||
napi_set_named_property(env, result, "command", outputCommand);
|
||||
FreeString(uin);
|
||||
FreeString(command);
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value EmptyPackets(napi_env env, napi_callback_info info)
|
||||
{
|
||||
void *missing = nullptr;
|
||||
MockSend(nullptr, nullptr);
|
||||
MockSend(nullptr, &missing);
|
||||
SendPacket send{};
|
||||
void *sendPointer = &send;
|
||||
MockSend(nullptr, &sendPointer);
|
||||
SendInner inner{};
|
||||
send.inner = &inner;
|
||||
MockSend(nullptr, &sendPointer);
|
||||
MockRecv(nullptr, nullptr, 0);
|
||||
MockRecv(nullptr, &missing, 0);
|
||||
RecvPacket recv{};
|
||||
void *recvPointer = &recv;
|
||||
MockRecv(nullptr, &recvPointer, 0);
|
||||
napi_value result;
|
||||
napi_create_int64(env, sendCalls + recvCalls, &result);
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value Addresses(napi_env env, napi_callback_info info)
|
||||
{
|
||||
Dl_info image{};
|
||||
dladdr(reinterpret_cast<void *>(MockCoerce), &image);
|
||||
uintptr_t base = reinterpret_cast<uintptr_t>(image.dli_fbase);
|
||||
napi_value result;
|
||||
napi_create_object(env, &result);
|
||||
const std::pair<const char *, uintptr_t> functions[] = {
|
||||
{"coerce", reinterpret_cast<uintptr_t>(MockCoerce) - base},
|
||||
{"resolver", reinterpret_cast<uintptr_t>(MockResolver) - base},
|
||||
{"send", (reinterpret_cast<uintptr_t>(MockSend) - base) * 2},
|
||||
{"recv", (reinterpret_cast<uintptr_t>(MockRecv) - base) * 2},
|
||||
};
|
||||
for (const auto &entry : functions)
|
||||
{
|
||||
std::ostringstream hex;
|
||||
hex << std::hex << entry.second;
|
||||
napi_value value;
|
||||
napi_create_string_utf8(env, hex.str().c_str(), NAPI_AUTO_LENGTH, &value);
|
||||
napi_set_named_property(env, result, entry.first, value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static napi_value Init(napi_env env, napi_value exports)
|
||||
{
|
||||
const napi_property_descriptor properties[] = {
|
||||
{"addresses", nullptr, Addresses, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"convert", nullptr, Convert, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"resolve", nullptr, Resolve, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"packet", nullptr, Packet, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
{"emptyPackets", nullptr, EmptyPackets, nullptr, nullptr, nullptr, napi_default, nullptr},
|
||||
};
|
||||
napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties);
|
||||
return exports;
|
||||
}
|
||||
|
||||
NAPI_MODULE(wrapper, Init)
|
||||
@@ -1,75 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
application = Path(sys.argv[1]).resolve()
|
||||
distribution = Path(sys.argv[2]).resolve()
|
||||
evidence = Path('qq-runtime-evidence')
|
||||
evidence.mkdir(exist_ok=True)
|
||||
signature = subprocess.run(['/usr/bin/codesign', '-d', '--entitlements', ':-', str(application)],
|
||||
capture_output=True, check=True, timeout=20)
|
||||
(evidence / 'entitlements.plist').write_bytes(signature.stdout)
|
||||
(evidence / 'signature.txt').write_bytes(signature.stderr)
|
||||
entitlements = plistlib.loads(signature.stdout)
|
||||
print(json.dumps({'entitlements': entitlements}, ensure_ascii=False), flush=True)
|
||||
|
||||
documents = Path.home() / 'Library/Containers/com.tencent.qq/Data/Documents'
|
||||
runtime = documents / 'napcat-runtime-audit'
|
||||
runtime.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copytree(distribution, runtime / 'napcat', dirs_exist_ok=True)
|
||||
bootstrap = runtime / 'loader.cjs'
|
||||
bootstrap.write_text('''const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
const addon = { exports: {} };
|
||||
process.dlopen(addon, path.join(__dirname, 'napcat/native/ffmpeg', `ffmpegAddon.darwin.${process.arch}.node`));
|
||||
console.log('QQ_NATIVE_ADDON_PROBE', Object.keys(addon.exports));
|
||||
import(pathToFileURL(path.join(__dirname, 'napcat/napcat.mjs')).href);
|
||||
''')
|
||||
package_path = application / 'Contents/Resources/app/package.json'
|
||||
package = json.loads(package_path.read_text())
|
||||
assert package['version'] == '7.0.2-53644', package
|
||||
package['main'] = os.path.relpath(bootstrap, package_path.parent)
|
||||
package_path.write_text(json.dumps(package))
|
||||
executable = application / 'Contents/MacOS/QQ'
|
||||
raw_log = evidence / 'runtime.log'
|
||||
started = time.monotonic()
|
||||
with raw_log.open('w') as output:
|
||||
process = subprocess.Popen([str(executable), '--no-sandbox'], cwd=runtime, start_new_session=True,
|
||||
stdout=output, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
deadline = time.monotonic() + 35
|
||||
while process.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
premature_exit = process.poll()
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait(timeout=5)
|
||||
log = raw_log.read_text(errors='replace')
|
||||
log = re.sub(r'(?i)(token[=:]\s*)[^\s]+', r'\1[redacted]', log)
|
||||
raw_log.write_text(log)
|
||||
checks = {
|
||||
'remains_running': premature_exit is None,
|
||||
'external_native_module': 'QQ_NATIVE_ADDON_PROBE' in log,
|
||||
'napcat_started': 'NapCat.Core Version:' in log,
|
||||
'packet_hook_initialized': '[PacketHandler] 初始化成功' in log,
|
||||
'napi_module_loaded': '[Napi2NativeLoader] 加载成功' in log,
|
||||
'ffmpeg_native_available': '使用 Native Addon 适配器' in log,
|
||||
}
|
||||
result = {'exit_code': premature_exit, 'seconds': time.monotonic() - started, 'checks': checks}
|
||||
(evidence / 'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(log[-16000:], flush=True)
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
assert all(checks.values()), result
|
||||
@@ -1,122 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { test } from 'node:test';
|
||||
|
||||
const script = fileURLToPath(new URL('../../scripts/generate-release-notes.mjs', import.meta.url));
|
||||
|
||||
function fixture (context) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'napcat-release-'));
|
||||
context.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
function git (...args) {
|
||||
return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: 'pipe' }).trim();
|
||||
}
|
||||
git('init', '--initial-branch=main');
|
||||
git('config', 'user.name', 'Release Test');
|
||||
git('config', 'user.email', 'release-test@example.invalid');
|
||||
git('config', 'commit.gpgSign', 'false');
|
||||
git('config', 'tag.gpgSign', 'false');
|
||||
function commit (subject, tag) {
|
||||
git('commit', '--allow-empty', '-m', subject);
|
||||
if (tag) git('tag', tag);
|
||||
return git('rev-parse', 'HEAD');
|
||||
}
|
||||
function generate (tag, cwd = root) {
|
||||
return spawnSync(process.execPath, [script, tag, 'NapNeko/NapCatQQ', join(root, '说明 # release.md')], {
|
||||
cwd,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
}
|
||||
function notes () {
|
||||
return readFileSync(join(root, '说明 # release.md'), 'utf8');
|
||||
}
|
||||
return { root, git, commit, generate, notes };
|
||||
}
|
||||
|
||||
test('uses numeric version order, exact tagged range, and UTF-8 output paths', context => {
|
||||
const repository = fixture(context);
|
||||
repository.commit('old release', 'v4.18.9');
|
||||
repository.commit('previous release', 'v4.18.10');
|
||||
const changeHash = repository.commit('fix: 中文 [loader] *paths* <native> `quoted` \\ newline', 'v4.18.11');
|
||||
repository.commit('unreleased change', 'v4.18.12');
|
||||
const result = repository.generate('v4.18.11');
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
const notes = repository.notes();
|
||||
assert.ok(notes.includes('fix: 中文 \\[loader\\] \\*paths\\* \\<native\\> \\`quoted\\` \\\\ newline'));
|
||||
assert.ok(notes.includes(`/commit/${changeHash}`));
|
||||
assert.ok(notes.includes('/compare/v4.18.10...v4.18.11'));
|
||||
assert.doesNotMatch(notes, /old release|previous release|unreleased change|v4\.10\.7|MacOS 暂不支持/);
|
||||
});
|
||||
|
||||
test('ignores version tags from an unmerged branch', context => {
|
||||
const repository = fixture(context);
|
||||
repository.commit('base', 'v1.0.0');
|
||||
repository.git('checkout', '-b', 'other');
|
||||
repository.commit('unmerged change', 'v1.9.0');
|
||||
repository.git('checkout', 'main');
|
||||
repository.commit('released change', 'v2.0.0');
|
||||
const result = repository.generate('v2.0.0');
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.ok(repository.notes().includes('/compare/v1.0.0...v2.0.0'));
|
||||
assert.doesNotMatch(repository.notes(), /unmerged change/);
|
||||
});
|
||||
|
||||
test('orders prerelease identifiers using semantic version precedence', context => {
|
||||
const repository = fixture(context);
|
||||
const versions = ['v1.0.0', 'v2.0.0-alpha.1', 'v2.0.0-alpha.2', 'v2.0.0-alpha.10',
|
||||
'v2.0.0-alpha.a10', 'v2.0.0-alpha.a2', 'v2.0.0-beta', 'v2.0.0-beta.1', 'v2.0.0-rc.1', 'v2.0.0'];
|
||||
for (const version of versions) repository.commit(version, version);
|
||||
for (let index = 1; index < versions.length; index++) {
|
||||
const result = repository.generate(versions[index]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.ok(repository.notes().includes(`/compare/${versions[index - 1]}...${versions[index]}`));
|
||||
}
|
||||
});
|
||||
|
||||
test('accepts annotated release tags and ignores invalid version tags', context => {
|
||||
const repository = fixture(context);
|
||||
repository.commit('base', 'v1.0.0');
|
||||
repository.commit('change');
|
||||
repository.git('tag', '-a', 'v1.1.0', '-m', 'Release v1.1.0');
|
||||
for (const tag of ['v1.2.0-01', 'v1.2.0-.rc', 'v1.02.0', 'preview']) repository.git('tag', tag);
|
||||
repository.commit('current', 'v2.0.0');
|
||||
const result = repository.generate('v2.0.0');
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.ok(repository.notes().includes('/compare/v1.1.0...v2.0.0'));
|
||||
});
|
||||
|
||||
test('reports an empty tagged range without inventing changes', context => {
|
||||
const repository = fixture(context);
|
||||
repository.commit('base', 'v1.0.0');
|
||||
repository.git('tag', 'v1.0.1');
|
||||
const result = repository.generate('v1.0.1');
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.ok(repository.notes().includes('此标签范围内没有新增提交。'));
|
||||
});
|
||||
|
||||
test('fails for missing or invalid versions without replacing existing output', context => {
|
||||
const repository = fixture(context);
|
||||
repository.commit('base', 'v1.0.0');
|
||||
const output = join(repository.root, '说明 # release.md');
|
||||
writeFileSync(output, 'existing output');
|
||||
for (const tag of ['v1.0.0', 'v2.0.0', 'v2.0.0-01', '--help', 'v1.0.1;echo invalid']) {
|
||||
const result = repository.generate(tag);
|
||||
assert.notEqual(result.status, 0, tag);
|
||||
assert.equal(repository.notes(), 'existing output');
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects a shallow checkout instead of generating incomplete notes', context => {
|
||||
const repository = fixture(context);
|
||||
repository.commit('base', 'v1.0.0');
|
||||
repository.commit('current', 'v1.1.0');
|
||||
const shallow = join(repository.root, 'shallow');
|
||||
repository.git('clone', '--depth=1', '--no-local', pathToFileURL(repository.root).href, shallow);
|
||||
const result = repository.generate('v1.1.0', shallow);
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /complete Git history/);
|
||||
assert.equal(existsSync(join(repository.root, '说明 # release.md')), false);
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$auditRoot = Join-Path ([IO.Path]::GetTempPath()) 'napcat-windows-launcher-tests'
|
||||
$sourceRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../../packages/napcat-shell-loader'))
|
||||
New-Item -ItemType Directory -Path $auditRoot -Force | Out-Null
|
||||
$compiledStub = Join-Path $auditRoot ('stub-' + [guid]::NewGuid().ToString('N') + '.exe')
|
||||
& (Join-Path $env:WINDIR 'Microsoft.NET/Framework64/v4.0.30319/csc.exe') /nologo ("/out:" + $compiledStub) (Join-Path $PSScriptRoot 'windows-launcher-stub.cs')
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Failed to compile launcher fixture' }
|
||||
$stubDirectory = Join-Path $auditRoot 'tools'
|
||||
New-Item -ItemType Directory -Path $stubDirectory -Force | Out-Null
|
||||
foreach ($stubName in @('reg.exe', 'net.exe', 'powershell.exe')) {
|
||||
Copy-Item -LiteralPath $compiledStub -Destination (Join-Path $stubDirectory $stubName) -Force
|
||||
}
|
||||
$results = [Collections.Generic.List[object]]::new()
|
||||
foreach ($launcher in @('launcher.bat', 'launcher-win10.bat', 'launcher-user.bat', 'launcher-win10-user.bat')) {
|
||||
foreach ($pathKind in @('plain', 'space', 'special', 'unquoted', 'missing-registry', 'boot-error', 'elevation')) {
|
||||
if ($pathKind -eq 'elevation' -and $launcher -like '*-user.bat') { continue }
|
||||
$directoryName = switch ($pathKind) {
|
||||
plain { 'plain' }
|
||||
space { 'space path' }
|
||||
special { "路径 & () ! # ' test" }
|
||||
default { "路径 & () ! # ' $pathKind" }
|
||||
}
|
||||
$fixture = Join-Path $auditRoot ($launcher.Replace('.bat', '') + '\' + $directoryName)
|
||||
New-Item -ItemType Directory -Path $fixture -Force | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $sourceRoot $launcher) -Destination $fixture -Force
|
||||
Copy-Item -LiteralPath $compiledStub -Destination (Join-Path $fixture 'NapCatWinBootMain.exe') -Force
|
||||
New-Item -ItemType File -Path (Join-Path $fixture 'QQ.exe') -Force | Out-Null
|
||||
$output = Join-Path $fixture 'arguments.txt'
|
||||
if (Test-Path -LiteralPath $output) { Remove-Item -LiteralPath $output }
|
||||
$startInfo = [Diagnostics.ProcessStartInfo]::new()
|
||||
$startInfo.FileName = $env:ComSpec
|
||||
$startInfo.Arguments = '/d /s /c ""' + (Join-Path $fixture $launcher) + '" -q "123456" "argument with spaces" "literal!value""'
|
||||
$startInfo.WorkingDirectory = $auditRoot
|
||||
$startInfo.UseShellExecute = $false
|
||||
$startInfo.CreateNoWindow = $true
|
||||
$startInfo.RedirectStandardInput = $true
|
||||
$startInfo.RedirectStandardOutput = $true
|
||||
$startInfo.RedirectStandardError = $true
|
||||
$startInfo.EnvironmentVariables['PATH'] = $stubDirectory + ';' + $env:PATH
|
||||
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_UNINSTALL'] = if ($pathKind -eq 'missing-registry') { '' } elseif ($pathKind -eq 'unquoted') { Join-Path $fixture 'Uninstall.exe' } else { '"' + (Join-Path $fixture 'Uninstall.exe') + '"' }
|
||||
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_NET_STATUS'] = if ($pathKind -eq 'elevation') { '1' } else { '0' }
|
||||
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_BOOT_STATUS'] = if ($pathKind -eq 'boot-error') { '31' } else { '0' }
|
||||
$startInfo.EnvironmentVariables['NAPCAT_AUDIT_OUTPUT'] = $output
|
||||
$process = [Diagnostics.Process]::Start($startInfo)
|
||||
$stdout = $process.StandardOutput.ReadToEndAsync()
|
||||
$stderr = $process.StandardError.ReadToEndAsync()
|
||||
$process.StandardInput.WriteLine('')
|
||||
$process.StandardInput.Close()
|
||||
if (-not $process.WaitForExit(10000)) {
|
||||
& taskkill.exe /PID $process.Id /T /F | Out-Null
|
||||
throw "$launcher $pathKind timed out"
|
||||
}
|
||||
$expected = @((Join-Path $fixture 'QQ.exe'), (Join-Path $fixture 'NapCatWinBootHook.dll'), '-q', '123456', 'argument with spaces', 'literal!value')
|
||||
if ($pathKind -eq 'missing-registry') { $expected = @() }
|
||||
if ($pathKind -eq 'elevation') {
|
||||
$terminal = if ($launcher -eq 'launcher.bat') { 'wt.exe' } else { 'powershell.exe' }
|
||||
$expected = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $fixture 'launcher-elevate.ps1'), $terminal, (Join-Path $fixture $launcher), '-q', '123456', 'argument with spaces', 'literal!value')
|
||||
}
|
||||
$actual = @()
|
||||
if (Test-Path -LiteralPath $output) {
|
||||
$actual = @(Get-Content -LiteralPath $output -Encoding UTF8 | Select-Object -Skip 1 | ForEach-Object { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($_)) })
|
||||
}
|
||||
$passed = $actual.Count -eq $expected.Count
|
||||
for ($argumentIndex = 0; $argumentIndex -lt $expected.Count -and $passed; $argumentIndex++) {
|
||||
$passed = $actual[$argumentIndex] -ceq $expected[$argumentIndex]
|
||||
}
|
||||
$expectedExit = if ($pathKind -eq 'missing-registry') { 1 } elseif ($pathKind -eq 'boot-error') { 31 } else { 0 }
|
||||
$passed = $passed -and $process.ExitCode -eq $expectedExit
|
||||
$result = [PSCustomObject]@{ launcher=$launcher; path=$pathKind; passed=$passed; exit=$process.ExitCode; actual=$actual; stdout=$stdout.Result; stderr=$stderr.Result }
|
||||
$results.Add($result)
|
||||
$result | Select-Object launcher,path,passed,exit | ConvertTo-Json -Compress
|
||||
}
|
||||
}
|
||||
function Start-Process {
|
||||
param([string]$FilePath, [string]$ArgumentList, [string]$Verb)
|
||||
$global:napcatAuditElevationRequest = @{ file=$FilePath; arguments=$ArgumentList; verb=$Verb }
|
||||
}
|
||||
foreach ($terminal in @('wt.exe', 'powershell.exe')) {
|
||||
$testScript = "C:\路径 & () ! # '\launcher.bat"
|
||||
$testArguments = @('-q', '123456', 'argument with spaces', 'literal!value', 'literal$()', 'quote"value')
|
||||
& (Join-Path $sourceRoot 'launcher-elevate.ps1') $terminal $testScript @testArguments
|
||||
$encodedCommand = ($global:napcatAuditElevationRequest.arguments -split ' ')[-1]
|
||||
$command = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encodedCommand))
|
||||
$parseTokens = $null
|
||||
$parseErrors = $null
|
||||
[Management.Automation.Language.Parser]::ParseInput($command, [ref]$parseTokens, [ref]$parseErrors) | Out-Null
|
||||
$match = [regex]::Match($command, "FromBase64String\('([A-Za-z0-9+/=]+)'\)")
|
||||
$payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($match.Groups[1].Value)) | ConvertFrom-Json
|
||||
$passed = $parseErrors.Count -eq 0 -and $payload.script -ceq $testScript -and $global:napcatAuditElevationRequest.verb -eq 'RunAs'
|
||||
$passed = $passed -and ($payload.arguments | ConvertTo-Json -Compress) -ceq ($testArguments | ConvertTo-Json -Compress)
|
||||
$result = [PSCustomObject]@{ launcher='launcher-elevate.ps1'; path=$terminal; passed=$passed; exit=0 }
|
||||
$results.Add($result)
|
||||
$result | ConvertTo-Json -Compress
|
||||
}
|
||||
$results | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $auditRoot 'results.json') -Encoding UTF8
|
||||
if ($results.Where({ -not $_.passed }).Count) { exit 1 }
|
||||
@@ -1,24 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
public class NapCatLauncherAudit {
|
||||
public static int Main(string[] arguments) {
|
||||
string name = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);
|
||||
if (name == "reg") {
|
||||
string uninstall = Environment.GetEnvironmentVariable("NAPCAT_AUDIT_UNINSTALL");
|
||||
if (String.IsNullOrEmpty(uninstall)) return 1;
|
||||
Console.OutputEncoding = new UTF8Encoding(false);
|
||||
Console.WriteLine(" UninstallString REG_SZ " + uninstall);
|
||||
return 0;
|
||||
}
|
||||
if (name == "net") return Int32.Parse(Environment.GetEnvironmentVariable("NAPCAT_AUDIT_NET_STATUS"));
|
||||
string output = Environment.GetEnvironmentVariable("NAPCAT_AUDIT_OUTPUT");
|
||||
using (StreamWriter writer = new StreamWriter(output, false, new UTF8Encoding(false))) {
|
||||
writer.WriteLine(name);
|
||||
foreach (string argument in arguments) writer.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(argument)));
|
||||
}
|
||||
return Int32.Parse(Environment.GetEnvironmentVariable("NAPCAT_AUDIT_BOOT_STATUS") ?? "0");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user