feat(affiliate): attribution modes, settlement hardening, trusted proxies, QR and poster

- 归因模式可配置(first_touch/last_touch)、停佣开关、懒结算与佣金基数降级复查
- aksrt_get_client_ip 接入 aksrt_trusted_proxies 信任代理名单,防 CDN 头伪造
- 收益页 Canvas 二维码 + 750x1000 推广海报(本地打包 qrcode.min.js,无 CDN)
- 契约测试固化归因/海报/信任代理链路
This commit is contained in:
2026-09-21 20:53:22 +08:00
parent 2618530afb
commit 20387fdb06
14 changed files with 715 additions and 6 deletions
@@ -0,0 +1,208 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const { execFileSync } = require('node:child_process');
const root = path.resolve(__dirname, '..', '..');
const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
test('captcha PHP security harness passes', () => {
const output = execFileSync('php', [path.join(root, 'tests/widget-system/captcha-security-harness.php')], { encoding: 'utf8' });
assert.match(output, /Captcha security harness passed/);
});
test('captcha exchange binds provider tokens to scene browser and one-time business proofs', () => {
const module = read('inc/modules/captcha.php');
const front = read('assets/js/captcha-front.js');
assert.match(module, /\/captcha\/exchange/);
assert.match(module, /aksrt_captcha_issue_challenge/);
assert.match(module, /aksrt_captcha_validate_challenge/);
assert.match(module, /aksrt_captcha_issue_proof/);
assert.match(module, /aksrt_captcha_consume_proof/);
assert.match(module, /browser_hash/);
assert.match(front, /exchange_url/);
assert.match(front, /aksrt_captcha_proof/);
assert.match(front, /runLocked/);
});
test('captcha defaults are opt-in and provider metadata is centralized', () => {
const module = read('inc/modules/captcha.php');
const phpSchema = read('src/Admin/Schema/SchemaPermissions.php');
const uiSchema = read('assets/admin/src/schema/sections/permissions/index.js');
assert.match(module, /function aksrt_captcha_provider_metadata/);
assert.match(module, /'enabled_scenarios'\s*=>\s*\[\]/);
assert.match(phpSchema, /'default'\s*=>\s*\[\]/);
assert.match(uiSchema, /enabled_scenarios:\s*\[\]/);
assert.match(phpSchema, /aksrt_captcha_provider_metadata/);
});
test('captcha verification is fail-closed with a true-or-WP_Error contract', () => {
const module = read('inc/modules/captcha.php');
assert.match(module, /return aksrt_captcha_error\('aksrt_captcha_config'/);
assert.match(module, /@return true\|\\WP_Error/);
assert.doesNotMatch(module, /is_wp_error\(\$result\) \? \$result->get_error_message\(\) : true/);
});
test('cloudflare siteverify performs one request and strictly binds action, cdata, and hostname', () => {
const module = read('inc/modules/captcha.php');
const start = module.indexOf('function aksrt_verify_cloudflare');
const end = module.indexOf('function aksrt_verify_geetest', start);
const cloudflare = module.slice(start, end);
assert.equal((cloudflare.match(/wp_remote_post\(/g) || []).length, 1);
assert.match(cloudflare, /array_key_exists\('action'/);
assert.match(cloudflare, /array_key_exists\('cdata'/);
assert.match(cloudflare, /hostname mismatch/);
assert.match(cloudflare, /hash_equals/);
});
test('TC3 signing derives tc3_request from the service key', () => {
const module = read('inc/modules/captcha.php');
assert.match(module, /hash_hmac\('sha256', 'tc3_request', \$secret_service, true\)/);
assert.doesNotMatch(module, /hash_hmac\('sha256', 'tc3_request', \$secret_signing, true\)/);
});
test('nested captcha secrets are masked, preserved, explicitly clearable, and excluded from standalone exports', () => {
const provider = read('src/Admin/SchemaProvider.php');
const settings = read('src/Settings/Settings.php');
const page = read('assets/admin/src/pages/SchemaPage.vue');
assert.match(provider, /mask_captcha_provider_secrets/);
assert.match(provider, /merge_captcha_provider_config/);
assert.match(provider, /\$value === '' \|\| \$value === '\*\*\*'/);
assert.match(settings, /SCHEMA_MANAGED_STANDALONE_OPTION_KEYS/);
assert.match(settings, /'aksrt_captcha_config'/);
assert.match(page, /captchaSecretsToClear/);
assert.match(page, /clear-secret/);
});
test('admin captcha test obtains a frontend token then calls the protected server verifier', () => {
const controller = read('src/Admin/ImportExportController.php');
const api = read('assets/admin/src/api/modules/schema.js');
const page = read('assets/admin/src/pages/SchemaPage.vue');
assert.match(controller, /'\/captcha\/test'/);
assert.match(controller, /aksrt_verify_captcha_provider/);
assert.match(api, /testCaptcha\(provider, token\)/);
assert.match(page, /submitCaptchaTest/);
assert.match(page, /action:\s*'aksrt-admin-test'/);
assert.match(page, /cdata:\s*'admin-captcha-test'/);
assert.doesNotMatch(page, /配置正确/);
});
test('Cloudflare custom domain setting is removed', () => {
const component = read('assets/admin/src/components/captcha/CloudflareConfig.vue');
assert.doesNotMatch(component, /自定义域名|model\.domain/);
});
test('cloud captcha server verifies over the WP HTTP API without disabling TLS', () => {
const module = read('inc/modules/captcha.php');
assert.doesNotMatch(module, /curl_init|curl_setopt|CURLOPT_SSL_VERIFYPEER/);
const posts = (module.match(/wp_remote_post\(/g) || []).length;
assert.ok(posts >= 4, `expected all four providers on wp_remote_post, found ${posts}`);
assert.match(module, /wp_generate_uuid4\(\)/, 'aliyun SignatureNonce must not be time-derived');
assert.doesNotMatch(module, /uniqid\(/);
});
test('cloud captcha verify requests use a 5s timeout and log raw failures', () => {
const module = read('inc/modules/captcha.php');
const timeouts = [...module.matchAll(/'timeout'\s*=>\s*(\d+)/g)].map((m) => Number(m[1]));
assert.ok(timeouts.length >= 4, 'every provider request must declare a timeout');
for (const timeout of timeouts) {
assert.strictEqual(timeout, 5);
}
assert.match(module, /error_log\('\[AKSRT Captcha\]/);
});
test('business requests consume one-time proofs without a shared download bypass', () => {
const module = read('inc/modules/captcha.php');
assert.match(module, /aksrt_captcha_consume_proof/);
assert.doesNotMatch(module, /aksrt_captcha_pass_ttl|aksrt_captcha_pass_key|aksrt_captcha_pass_/);
});
test('cloudflare siteverify stays bound to the aksrt action and scene', () => {
const module = read('inc/modules/captcha.php');
assert.match(module, /aksrt_verify_cloudflare\(array \$pcfg, array \$post_data, string \$client_ip, string \$scene = ''(?:, string \$action = 'aksrt-verify')?\)/);
assert.match(module, /action mismatch/);
assert.match(module, /cdata mismatch/);
});
test('captcha render is a data-driven mount without inline scripts or stylesheets', () => {
const module = read('inc/modules/captcha.php');
assert.match(module, /data-aksrt-captcha-config/);
assert.doesNotMatch(module, /<script|<link rel/);
});
test('legacy local captcha markers stay gone', () => {
const module = read('inc/modules/captcha.php');
assert.doesNotMatch(module, /machine-verification|imagecaptcha|slidercaptcha|canvas_yz/);
});
test('captcha front runtime ships inside the public bundle', () => {
const build = read('tools/build-public-assets.mjs');
assert.match(build, /'assets\/js\/captcha-front\.js'/);
assert.match(build, /'assets\/css\/shared\/captcha\.css'/);
const front = read('assets/js/captcha-front.js');
assert.match(front, /AKSRTCaptcha/);
assert.match(front, /data-aksrt-captcha-config/);
assert.match(front, /cdata: C\.scene/, 'turnstile widget must bind cdata to the scene');
});
test('captcha public runtime exposes only the shared API and resolves scoped uid instances', () => {
const front = read('assets/js/captcha-front.js');
assert.match(front, /window\.AKSRTCaptcha\s*=\s*Object\.freeze\(\{[\s\S]*verify:\s*verify,[\s\S]*collect:\s*collect,[\s\S]*reset:\s*reset,[\s\S]*run:\s*run,[\s\S]*TOKEN_FIELDS:\s*TOKEN_FIELDS/);
assert.match(front, /instances\[instance\.uid\]\s*=\s*instance/);
assert.match(front, /function resolve\(scene, scope\)/);
assert.doesNotMatch(front, /AKSRTCaptchaState/);
assert.doesNotMatch(front, /tencent_sid/);
});
test('captcha consumers use the shared API and reset every token-bearing request', () => {
const consumers = [
'assets/js/auth.js',
'assets/js/core/comments.js',
'assets/js/routes/user-center.js',
'assets/js/cms-download.js',
'assets/js/signin.js',
'assets/js/front-submit.js',
].map(read).join('\n');
assert.match(consumers, /AKSRTCaptcha\.run|captcha\.run/);
assert.match(consumers, /AKSRTCaptcha\.reset|captcha\.reset|resetCaptcha/);
assert.doesNotMatch(consumers, /AKSRTCaptchaState/);
assert.doesNotMatch(consumers, /tencent_sid/);
assert.doesNotMatch(read('assets/js/core/comments.js'), /wp-comments-post|performLegacySubmit/);
});
test('sign-in waits for main and fails closed when its enabled captcha mount is unavailable', () => {
const signin = read('assets/js/signin.js');
const scripts = read('src/Core/ScriptsPart1c.php');
assert.match(signin, /tbquire\(\['main'\], boot\)/);
assert.match(signin, /var captchaRequired = !!window\.aksrtData\.captchaSignin/);
assert.match(signin, /captchaRequired && \(!captcha \|\| !mount\)[\s\S]*?return;/);
assert.doesNotMatch(signin, /captcha \? captcha\.run\('signin', mount\) : Promise\.resolve\(\{\}\)/);
assert.match(scripts, /'captchaSignin'\s*=>\s*function_exists\('aksrt_is_captcha_enabled_for'\)\s*&&\s*aksrt_is_captcha_enabled_for\('signin'\)/);
});
test('auth and account security flows consume fresh captcha tickets', () => {
const auth = read('assets/js/auth.js');
assert.match(auth, /request\('code',[\s\S]*\.finally\(function \(\) \{[\s\S]*resetCaptcha/);
assert.match(auth, /function submit\(form\)[\s\S]*captcha\.run\(scene,[\s\S]*request\(action,[\s\S]*resetCaptcha/);
assert.match(auth, /qrPayload\.bind_pass = root\.dataset\.bindPass/);
assert.match(auth, /data\.bind_pass = root\.dataset\.bindPass/);
const center = read('assets/js/routes/user-center.js');
assert.match(center, /runCaptcha\('bind_phone', form\)[\s\S]*\/user\/phone-code/);
assert.match(center, /runCaptcha\('bind_phone', form\)[\s\S]*\/user\/phone/);
assert.match(center, /runCaptcha\(scene, fm\)[\s\S]*resetCaptcha\(scene, fm\)/);
assert.match(center, /\/oauth\/bind-pass/);
assert.match(center, /bind_verification_required:\s*'请先完成人机验证后再绑定'/);
});
test('captcha admin schema drops the dead single-option trigger mode', () => {
const schema = read('src/Admin/Schema/SchemaPermissions.php');
assert.doesNotMatch(schema, /'mode'/);
const ui = read('assets/admin/src/schema/sections/permissions/index.js');
assert.doesNotMatch(ui, /\bmode\s*:/);
assert.doesNotMatch(ui, /'mode'/);
const provider = read('src/Admin/SchemaProvider.php');
assert.doesNotMatch(provider, /'mode'/);
});
@@ -0,0 +1,77 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const root = path.resolve(__dirname, '..', '..')
const read = (...segments) => fs.readFileSync(path.join(root, ...segments), 'utf8')
test('referral attribution model is a single runtime source with schema surface', () => {
const runtime = read('src', 'Settings', 'CreditsRuntime.php')
const attribution = read('src', 'Payment', 'ReferralAttribution.php')
const phpSchema = read('src', 'Admin', 'Schema', 'SchemaPayment.php')
const jsSchema = read('assets', 'admin', 'src', 'schema', 'sections', 'payment', 'affiliate.js')
// 运行时:唯一枚举与默认值。
assert.match(runtime, /referral_attribution_model/)
assert.match(runtime, /\['first_touch', 'last_touch'\]/)
assert.match(runtime, /'attribution_model' => \$attribution/)
// 归因行为:capture 末触覆盖、首触保持;注册仲裁按模式取优先方。
assert.match(attribution, /\$this->attribution_model\(\) !== 'last_touch'/)
assert.match(attribution, /!?\(\$last_touch && \$submitted_valid\)/)
assert.match(attribution, /已按最近访问的推广关系绑定/)
assert.match(attribution, /已按首次访问的推广关系绑定/)
// 管理端双 schema 同步暴露该字段。
for (const schema of [phpSchema, jsSchema]) {
assert.match(schema, /referral_attribution_model/)
assert.match(schema, /first_touch/)
assert.match(schema, /last_touch/)
}
})
test('disabled-code stop-commission switch is wired end to end', () => {
const runtime = read('src', 'Settings', 'PaymentRuntime.php')
const ledger = read('src', 'Payment', 'CommissionLedger.php')
const attribution = read('src', 'Payment', 'ReferralAttribution.php')
const phpSchema = read('src', 'Admin', 'Schema', 'SchemaPayment.php')
const jsSchema = read('assets', 'admin', 'src', 'schema', 'sections', 'payment', 'affiliate.js')
assert.match(runtime, /'disabled_code_stops_commission' => !empty\(\$settings\['affiliate_disabled_code_stops_commission'\]\)/)
// 记账入口必须在 resolve 推广人之后、写 ledger 之前校验推广码状态。
assert.match(ledger, /ReferralAttribution::get_instance\(\)->resolve\(\$buyer\)/)
assert.match(ledger, /is_promoter_code_active\(\$promoter\)/)
assert.ok(
ledger.indexOf('is_promoter_code_active($promoter)') < ledger.indexOf('$wpdb->insert($table'),
'disabled-code gate must run before the ledger insert'
)
assert.match(attribution, /public function is_promoter_code_active\(int \$promoter_id\): bool/)
for (const schema of [phpSchema, jsSchema]) {
assert.match(schema, /affiliate_disabled_code_stops_commission/)
}
})
test('commission base is the discounted payable amount, not the list price', () => {
// 下单侧:content 订单金额取优惠链(推广让利 + 优惠券)后的应付净额。
const payOrders = read('src', 'Content', 'PayOrders.php')
assert.match(payOrders, /\$amount_minor = max\(0, \(int\) \(\$discounted\['payable_minor'\] \?\? 0\)\)/)
// 记账侧:佣金基数直接取订单实付金额。
const ledger = read('src', 'Payment', 'CommissionLedger.php')
assert.match(ledger, /AssetAmount::balance\(is_string\(\$order\['amount'\] \?\? null\) \? \$order\['amount'\] : ''\)/)
})
test('lazy settlement backstop guards the earnings entry points', () => {
const ledger = read('src', 'Payment', 'CommissionLedger.php')
const attribution = read('src', 'Payment', 'ReferralAttribution.php')
assert.match(ledger, /private static bool \$lazy_settled = false/)
assert.match(ledger, /public function lazy_settle_due\(\): void/)
assert.match(ledger, /if \(!\\AKSRT\\Settings\\Settings::affiliate_enabled\(\)\) return;/)
assert.ok(
ledger.indexOf('lazy_settle_due()') < ledger.indexOf('global \$wpdb; \$table=\$this->table\(\'commission_ledger\'\); \$row=\$wpdb->get_row'),
'overview() must trigger the backstop before aggregating balances'
)
// 收益总览与我的推广两个入口都接入了兜底。
assert.match(attribution, /CommissionLedger::get_instance\(\)->lazy_settle_due\(\)/)
})
@@ -0,0 +1,89 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const root = path.resolve(__dirname, '..', '..')
const read = (...segments) => fs.readFileSync(path.join(root, ...segments), 'utf8')
test('QR generator is bundled locally; no external QR CDN in front-end sources', () => {
const vendor = path.join(root, 'assets', 'js', 'vendor', 'qrcode.min.js')
assert.ok(fs.existsSync(vendor), 'assets/js/vendor/qrcode.min.js must be committed')
const script = fs.readFileSync(vendor, 'utf8')
assert.ok(script.length > 10000, 'qrcode.min.js must not be a placeholder')
// 前端引用面不允许出现外部二维码 CDN。
const sources = [
read('assets', 'js', 'credits.js'),
read('inc', 'helpers', 'user-center-renderers', 'profile-revenue.php'),
read('src', 'Core', 'ScriptsPart1b.php'),
].join('\n')
assert.doesNotMatch(sources, /cdnjs\.cloudflare\.com[^"']*qrcode|cdn\.jsdelivr\.net[^"']*qrcode|unpkg\.com[^"']*qrcode/)
})
test('revenue page renders the QR row and credits.js draws + downloads it', () => {
const template = read('inc', 'helpers', 'user-center-renderers', 'profile-revenue.php')
assert.match(template, /data-affiliate-qr-row/)
assert.match(template, /data-affiliate-qr(?!-)/)
assert.match(template, /data-affiliate-qr-download/)
assert.match(template, /data-affiliate-poster/)
const script = read('assets', 'js', 'credits.js')
assert.match(script, /renderAffiliateQr\(root, j\.url \|\| ''\)/)
// 库缺失时整行隐藏,不抛错。
assert.match(script, /typeof window\.qrcode !== 'function'/)
assert.match(script, /row\.hidden = true/)
// Canvas 绘制(isDark 逐模块填充)+ PNG 下载。
assert.match(script, /qr\.isDark\(r, c\)/)
assert.match(script, /canvas\.toDataURL\('image\/png'\)/)
})
test('poster canvas is built from admin-configured copy and gated on the poster switch', () => {
const runtime = read('src', 'Settings', 'PaymentRuntime.php')
assert.match(runtime, /'poster' => \[/)
assert.match(runtime, /pay_rebate_poster_s/)
assert.match(runtime, /pay_rebate_poster_img/)
assert.match(runtime, /pay_rebate_poster_title/)
assert.match(runtime, /pay_rebate_poster_desc/)
const attribution = read('src', 'Payment', 'ReferralAttribution.php')
assert.match(attribution, /'poster' => \(array\) \(\$affiliate\['poster'\] \?\? \['enabled' => false\]\)/)
assert.match(attribution, /'site_name' => get_bloginfo\('name'\)/)
const script = read('assets', 'js', 'credits.js')
// 海报仅在开关开启时暴露按钮;绘制含顶部图、文案换行、二维码与站点名。
assert.match(script, /initAffiliatePoster\(root, j\.url \|\| '', j\.poster \|\| \{\}, j\.site_name \|\| document\.title\)/)
assert.match(script, /poster\.enabled !== true\) return/)
assert.match(script, /function buildPosterCanvas/)
assert.match(script, /function wrapText\(ctx, text, maxWidth\)/)
assert.match(script, /image\.crossOrigin = 'anonymous'/)
})
test('invite-code input verifies live against the public REST endpoint', () => {
const template = read('templates', 'parts', 'auth-content.php')
assert.match(template, /data-invite-verify/)
assert.match(template, /data-invite-feedback/)
const script = read('assets', 'js', 'auth.js')
assert.match(script, /function initInviteVerify\(root\)/)
assert.match(script, /input\[data-invite-verify\]/)
assert.match(script, /initInviteVerify\(root\)/)
assert.match(script, /\/wp-json\/aksrt\/v1\/invite-code\/verify\?code=/)
})
test('qrcode asset is enqueued only for profile + affiliate and credits depends on it', () => {
const scripts = read('src', 'Core', 'ScriptsPart1b.php')
assert.match(scripts, /assets\/js\/vendor\/qrcode\.min\.js/)
assert.match(scripts, /'aksrt-qrcode'/)
// credits.js 的依赖数组必须在 enqueue 调用内合并 QR 库句柄。
assert.match(scripts, /array_merge\(\['loader_js', 'aksrt-vip-coordinator'\], \$affiliate_deps\)/)
})
test('client IP honours the trusted-proxy filter before CDN headers', () => {
const captcha = read('inc', 'modules', 'captcha.php')
assert.match(captcha, /apply_filters\('aksrt_trusted_proxies', \[\]\)/)
assert.match(captcha, /function aksrt_ip_in_list\(string \$ip, array \$list\): bool/)
// CIDR 比较必须先检查同族地址长度,避免跨族误判。
assert.match(captcha, /strlen\(\$ip_binary\) !== strlen\(\$subnet_binary\)/)
// 过滤命中失败时直接回落 REMOTE_ADDR,不读转发头。
assert.match(captcha, /!aksrt_ip_in_list\(\$remote, \$trusted\)/)
})