64 lines
5.2 KiB
JavaScript
64 lines
5.2 KiB
JavaScript
import 'reflect-metadata';
|
|
import { webcrypto, createPrivateKey, X509Certificate as NativeCertificate } from 'node:crypto';
|
|
import { X509CertificateGenerator, BasicConstraintsExtension, KeyUsagesExtension, KeyUsageFlags,
|
|
ExtendedKeyUsageExtension, ExtendedKeyUsage, SubjectAlternativeNameExtension, SubjectKeyIdentifierExtension, AuthorityKeyIdentifierExtension } from '@peculiar/x509';
|
|
import { protectCredential, unprotectCredential } from '../desktop/windows-dpapi.mjs';
|
|
import { companionError, companionHash } from '../../shared/contracts/companion.mjs';
|
|
|
|
const algorithm = { name: 'ECDSA', namedCurve: 'P-256', hash: 'SHA-256' };
|
|
const signing = { name: 'ECDSA', hash: 'SHA-256' };
|
|
const day = 86400000;
|
|
export class CompanionTLS {
|
|
constructor(registry, { protect = protectCredential, unprotect = unprotectCredential } = {}) {
|
|
this.registry = registry; this.protect = protect; this.unprotect = unprotect;
|
|
}
|
|
publicCertificate() {
|
|
const tls = this.registry.read().tls;
|
|
if (!tls) throw companionError('请先在电脑开启手机连接以生成证书。', 409);
|
|
const cert = new NativeCertificate(tls.certificate);
|
|
if (companionHash(cert.raw) !== tls.sha256) throw companionError('手机证书登记校验失败。', 409);
|
|
return { bytes: cert.raw, sha256: tls.sha256, expiresAt: tls.expiresAt };
|
|
}
|
|
async material(address) {
|
|
const registry = this.registry, entropy = Buffer.from(companionHash('companion-tls:' + registry.binding), 'hex');
|
|
let record = registry.read().tls, privateBytes, keys, certificate;
|
|
try {
|
|
if (record) {
|
|
const cert = new NativeCertificate(record.certificate);
|
|
if (companionHash(cert.raw) !== record.sha256 || Date.parse(cert.validTo) <= Date.now() + day) throw companionError('原手机根证书已变化或即将到期,请在电脑处理证书更新。', 409);
|
|
privateBytes = this.unprotect(Buffer.from(record.ciphertext, 'base64'), entropy);
|
|
const payload = JSON.parse(privateBytes.toString('utf8'));
|
|
if (payload.binding !== registry.binding || payload.sha256 !== record.sha256) throw companionError('手机TLS私钥不属于当前Windows用户和数据目录。', 409);
|
|
const privateKey = await webcrypto.subtle.importKey('pkcs8', Buffer.from(payload.pkcs8, 'base64'), algorithm, false, ['sign']);
|
|
if (!cert.checkPrivateKey(createPrivateKey({ key: Buffer.from(payload.pkcs8, 'base64'), format: 'der', type: 'pkcs8' }))) throw companionError('手机证书与私钥不匹配。', 409);
|
|
keys = { privateKey }; certificate = record.certificate;
|
|
} else {
|
|
keys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
|
|
const ca = await X509CertificateGenerator.createSelfSigned({ name: 'CN=Agent Workbench Mobile ' + registry.read().gatewayId,
|
|
keys, signingAlgorithm: signing, notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 730 * day),
|
|
extensions: [new BasicConstraintsExtension(true, 0, true), new KeyUsagesExtension(KeyUsageFlags.keyCertSign | KeyUsageFlags.cRLSign, true),
|
|
await SubjectKeyIdentifierExtension.create(keys.publicKey)] }, webcrypto);
|
|
certificate = ca.toString('pem');
|
|
const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', keys.privateKey));
|
|
let encrypted;
|
|
try {
|
|
privateBytes = Buffer.from(JSON.stringify({ binding: registry.binding, sha256: companionHash(new NativeCertificate(certificate).raw), pkcs8: pkcs8.toString('base64') }));
|
|
encrypted = this.protect(privateBytes, entropy);
|
|
record = { certificate, sha256: companionHash(new NativeCertificate(certificate).raw), expiresAt: ca.notAfter.toISOString(), ciphertext: encrypted.toString('base64') };
|
|
registry.mutate(state => { if (state.tls) throw companionError('证书已由另一操作生成,请刷新。', 409); state.tls = record; });
|
|
} finally { pkcs8.fill(0); encrypted?.fill(0); }
|
|
}
|
|
const leafKeys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
|
|
const leaf = await X509CertificateGenerator.create({ subject: 'CN=Agent Workbench Companion', issuer: new NativeCertificate(certificate).subject,
|
|
publicKey: leafKeys.publicKey, signingKey: keys.privateKey, signingAlgorithm: signing,
|
|
notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 90 * day),
|
|
extensions: [new BasicConstraintsExtension(false, undefined, true), new KeyUsagesExtension(KeyUsageFlags.digitalSignature, true),
|
|
new ExtendedKeyUsageExtension([ExtendedKeyUsage.serverAuth]), new SubjectAlternativeNameExtension([{ type: 'ip', value: address }]),
|
|
await SubjectKeyIdentifierExtension.create(leafKeys.publicKey), await AuthorityKeyIdentifierExtension.create(new NativeCertificate(certificate).publicKey.export({ type: 'spki', format: 'der' }))] }, webcrypto);
|
|
const der = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', leafKeys.privateKey));
|
|
try { return { key: createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }).export({ format: 'pem', type: 'pkcs8' }), cert: leaf.toString('pem') + '\n' + certificate, ca: certificate }; }
|
|
finally { der.fill(0); }
|
|
} finally { privateBytes?.fill(0); entropy.fill(0); }
|
|
}
|
|
}
|