Files
order_site/apps/backend/src/services/semi-auto/semi-auto-credential-crypto.test.ts
T

95 lines
2.6 KiB
TypeScript

import assert from 'node:assert/strict'
import test from 'node:test'
import {
decryptSemiAutoCredential,
encryptSemiAutoCredential,
isEncryptedSemiAutoCredential,
} from './semi-auto-credential-crypto.js'
import { buildSemiAutoCredentialCookieHeader } from './semi-auto-credential-service.js'
const SECRET = 'test-semi-auto-credential-encryption-key-123456'
test('半自动履约凭证使用 AES-GCM 加密并可还原', () => {
const plaintext = JSON.stringify({
cookies: [{ name: 'SUB', value: 'secret-cookie', domain: '.weibo.com' }],
})
const encrypted = encryptSemiAutoCredential(plaintext, SECRET)
assert.equal(isEncryptedSemiAutoCredential(encrypted), true)
assert.notEqual(encrypted, plaintext)
assert.equal(encrypted.includes('secret-cookie'), false)
assert.equal(decryptSemiAutoCredential(encrypted, SECRET), plaintext)
})
test('半自动履约凭证密文被篡改时解密失败', () => {
const encrypted = encryptSemiAutoCredential('{"cookies":[]}', SECRET)
const tampered = `${encrypted.slice(0, -1)}${encrypted.endsWith('A') ? 'B' : 'A'}`
assert.throws(() => decryptSemiAutoCredential(tampered, SECRET))
})
test('错误密钥不能解密半自动履约凭证', () => {
const encrypted = encryptSemiAutoCredential('{"cookies":[]}', SECRET)
assert.throws(() =>
decryptSemiAutoCredential(encrypted, 'another-semi-auto-credential-encryption-key-123'),
)
})
test('账号 Cookie Header 按域名、路径和安全协议筛选', () => {
const header = buildSemiAutoCredentialCookieHeader(
[
{
name: 'SUB',
value: 'weibo-session',
domain: '.weibo.com',
path: '/',
secure: true,
httpOnly: true,
hostOnly: false,
expiresAt: null,
},
{
name: 'SUB',
value: 'passport-session',
domain: 'passport.weibo.com',
path: '/sso',
secure: true,
httpOnly: true,
hostOnly: true,
expiresAt: null,
},
{
name: 'INSECURE',
value: 'must-not-leak',
domain: '.weibo.com',
path: '/',
secure: false,
httpOnly: false,
hostOnly: false,
expiresAt: null,
},
],
'https://weibo.com/',
)
assert.equal(header, 'SUB=weibo-session; INSECURE=must-not-leak')
assert.equal(
buildSemiAutoCredentialCookieHeader(
[
{
name: 'SUB',
value: 'weibo-session',
domain: '.weibo.com',
path: '/',
secure: true,
httpOnly: true,
hostOnly: false,
expiresAt: null,
},
],
'http://weibo.com/',
),
'',
)
})