Сервис qbo_auth: OAuth-токены QuickBooks Online (callback services/api/qbo/callback), исследование и предложение quickbooks_bookkeeper (п.84)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
24
packages/qbo_auth/src/crypto.ts
Normal file
24
packages/qbo_auth/src/crypto.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
||||
|
||||
/** Ключ: 64 hex-символа или base64 от 32 байт. */
|
||||
export function parseKey(raw: string): Buffer {
|
||||
const k = /^[0-9a-fA-F]{64}$/.test(raw) ? Buffer.from(raw, "hex") : Buffer.from(raw, "base64");
|
||||
if (k.length !== 32) throw new Error("encryptionKey: нужно 32 байта (hex 64 символа или base64)");
|
||||
return k;
|
||||
}
|
||||
|
||||
/** AES-256-GCM; формат: v1.<iv>.<tag>.<данные> (base64url). */
|
||||
export function encrypt(plain: string, key: Buffer): string {
|
||||
const iv = randomBytes(12);
|
||||
const c = createCipheriv("aes-256-gcm", key, iv);
|
||||
const data = Buffer.concat([c.update(plain, "utf8"), c.final()]);
|
||||
return ["v1", iv.toString("base64url"), c.getAuthTag().toString("base64url"), data.toString("base64url")].join(".");
|
||||
}
|
||||
|
||||
export function decrypt(token: string, key: Buffer): string {
|
||||
const [v, iv, tag, data] = token.split(".");
|
||||
if (v !== "v1" || !iv || !tag || !data) throw new Error("неизвестный формат зашифрованного значения");
|
||||
const d = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64url"));
|
||||
d.setAuthTag(Buffer.from(tag, "base64url"));
|
||||
return Buffer.concat([d.update(Buffer.from(data, "base64url")), d.final()]).toString("utf8");
|
||||
}
|
||||
Reference in New Issue
Block a user