feat(models): persist explicitly saved credentials with user-scoped DPAPI
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { projectEnvironment } from '../process-environment.mjs';
|
||||
|
||||
export const credentialError = (message, code = 'CREDENTIAL_UNAVAILABLE', status = 409) => Object.assign(new Error(message), { code, status });
|
||||
|
||||
// The command and environment contain no credential. Both directions travel
|
||||
// over private pipes as ASCII frames; raw child output is never logged.
|
||||
function transform(action, bytes, entropy) {
|
||||
if (process.platform !== 'win32') throw credentialError('本机加密凭据仅支持Windows用户级DPAPI。', 'CREDENTIAL_PLATFORM_UNSUPPORTED');
|
||||
if (!Buffer.isBuffer(bytes) || bytes.length > 128000 || !Buffer.isBuffer(entropy) || entropy.length !== 32) throw credentialError('加密凭据输入无效。');
|
||||
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';Add-Type -AssemblyName System.Security;"
|
||||
+ '$awbInput=[Console]::In.ReadToEnd()|ConvertFrom-Json;'
|
||||
+ '$awbBytes=[Convert]::FromBase64String($awbInput.bytes);$awbEntropy=[Convert]::FromBase64String($awbInput.entropy);'
|
||||
+ 'try{$awbOutput=[Security.Cryptography.ProtectedData]::' + action + '($awbBytes,$awbEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser);'
|
||||
+ '[Console]::Out.Write([Convert]::ToBase64String($awbOutput))}'
|
||||
+ 'finally{[Array]::Clear($awbBytes,0,$awbBytes.Length);[Array]::Clear($awbEntropy,0,$awbEntropy.Length);if($awbOutput){[Array]::Clear($awbOutput,0,$awbOutput.Length)}}';
|
||||
try {
|
||||
const output = execFileSync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),
|
||||
['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
|
||||
{ input: JSON.stringify({ bytes: bytes.toString('base64'), entropy: entropy.toString('base64') }), encoding: 'utf8',
|
||||
windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], timeout: 15000, maxBuffer: 256000, env: projectEnvironment() }).trim();
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(output) || output.length > 200000) throw new Error('Invalid response');
|
||||
return Buffer.from(output, 'base64');
|
||||
} catch { throw credentialError('本机加密凭据无法处理,请核对Windows用户、数据目录或保存块。'); }
|
||||
}
|
||||
export const protectCredential = (bytes, entropy) => transform('Protect', bytes, entropy);
|
||||
export const unprotectCredential = (bytes, entropy) => transform('Unprotect', bytes, entropy);
|
||||
Reference in New Issue
Block a user