Compare commits
2 Commits
7cf6c31da3
...
34ff62d317
| Author | SHA1 | Date | |
|---|---|---|---|
| 34ff62d317 | |||
| 1a91e16ac9 |
@@ -39,6 +39,7 @@
|
||||
"fetch-event-stream": "^0.1.6",
|
||||
"highlight.js": "^11.11.1",
|
||||
"markdown-it": "^14.1.0",
|
||||
"node-forge": "1.3.1",
|
||||
"pinia": "catalog:",
|
||||
"radash": "^12.1.1",
|
||||
"vue": "catalog:",
|
||||
@@ -48,6 +49,7 @@
|
||||
"vue3-json-viewer": "^2.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"cssnano": "catalog:",
|
||||
"unplugin-element-plus": "catalog:"
|
||||
}
|
||||
|
||||
@@ -28,40 +28,41 @@ interface TransitionPayload {
|
||||
oldKeyId: string;
|
||||
}
|
||||
|
||||
interface EncryptedCredentialEnvelope {
|
||||
ciphertext: string;
|
||||
encryptedKey: string;
|
||||
iv: string;
|
||||
keyId: string;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
interface CredentialCryptoEngine {
|
||||
encryptPayload(
|
||||
material: CredentialKeyMaterial,
|
||||
plaintext: string,
|
||||
): Promise<EncryptedCredentialEnvelope>;
|
||||
verifyTransition(
|
||||
publicKeyPem: string,
|
||||
transition: CredentialKeyTransition,
|
||||
): Promise<boolean>;
|
||||
}
|
||||
|
||||
const PIN_STORAGE_KEY = 'easyflow:credential-key-pin:v1';
|
||||
const SECURITY_ERROR = '登录安全校验失败,请刷新或联系管理员';
|
||||
const UNSUPPORTED_ERROR = '当前浏览器不支持登录安全加密,请升级浏览器';
|
||||
let forgeModulePromise: Promise<any> | null = null;
|
||||
|
||||
/**
|
||||
* 加密密码类请求载荷。
|
||||
* @param loadMaterial 获取后端公钥材料的方法
|
||||
* @param payload 待加密载荷
|
||||
* @returns 加密信封
|
||||
*/
|
||||
export async function encryptCredentialPayload(
|
||||
loadMaterial: () => Promise<CredentialKeyMaterial>,
|
||||
payload: Record<string, any>,
|
||||
) {
|
||||
ensureWebCrypto();
|
||||
const material = await loadMaterial();
|
||||
await verifyAndPersistPin(material);
|
||||
const webCryptoEngine: CredentialCryptoEngine = {
|
||||
async encryptPayload(material, plaintext) {
|
||||
const aesKey = await window.crypto.subtle.generateKey(
|
||||
{ length: 256, name: 'AES-GCM' },
|
||||
true,
|
||||
['encrypt'],
|
||||
);
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
...payload,
|
||||
nonce: material.nonce,
|
||||
timestamp: Date.now(),
|
||||
}),
|
||||
);
|
||||
const ciphertext = await window.crypto.subtle.encrypt(
|
||||
{ iv, name: 'AES-GCM' },
|
||||
aesKey,
|
||||
plaintext,
|
||||
stringToUtf8Bytes(plaintext),
|
||||
);
|
||||
const rawAesKey = await window.crypto.subtle.exportKey('raw', aesKey);
|
||||
const publicKey = await importRsaPublicKey(material.publicKey, ['encrypt']);
|
||||
@@ -77,9 +78,105 @@ export async function encryptCredentialPayload(
|
||||
keyId: material.keyId,
|
||||
nonce: material.nonce,
|
||||
};
|
||||
},
|
||||
|
||||
async verifyTransition(publicKeyPem, transition) {
|
||||
const publicKey = await importSignPublicKey(publicKeyPem);
|
||||
return window.crypto.subtle.verify(
|
||||
{ name: 'RSASSA-PKCS1-v1_5' },
|
||||
publicKey,
|
||||
base64ToBytes(transition.signature),
|
||||
stringToUtf8Bytes(transition.payload),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const forgeCryptoEngine: CredentialCryptoEngine = {
|
||||
async encryptPayload(material, plaintext) {
|
||||
const forge = await loadForge();
|
||||
const aesKey = forge.random.getBytesSync(32);
|
||||
const iv = forge.random.getBytesSync(12);
|
||||
const cipher = forge.cipher.createCipher('AES-GCM', aesKey);
|
||||
cipher.start({ iv, tagLength: 128 });
|
||||
cipher.update(forge.util.createBuffer(plaintext, 'utf8'));
|
||||
cipher.finish();
|
||||
const ciphertextWithTag = cipher.output.getBytes() + cipher.mode.tag.getBytes();
|
||||
const publicKey = forge.pki.publicKeyFromPem(material.publicKey);
|
||||
const encryptedKey = publicKey.encrypt(aesKey, 'RSA-OAEP', {
|
||||
md: forge.md.sha256.create(),
|
||||
mgf1: {
|
||||
md: forge.md.sha256.create(),
|
||||
},
|
||||
});
|
||||
return {
|
||||
ciphertext: binaryToBase64(ciphertextWithTag),
|
||||
encryptedKey: binaryToBase64(encryptedKey),
|
||||
iv: binaryToBase64(iv),
|
||||
keyId: material.keyId,
|
||||
nonce: material.nonce,
|
||||
};
|
||||
},
|
||||
|
||||
async verifyTransition(publicKeyPem, transition) {
|
||||
const forge = await loadForge();
|
||||
const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
|
||||
const md = forge.md.sha256.create();
|
||||
md.update(transition.payload, 'utf8');
|
||||
return publicKey.verify(
|
||||
md.digest().bytes(),
|
||||
forge.util.decode64(transition.signature),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 加密密码类请求载荷。
|
||||
* @param loadMaterial 获取后端公钥材料的方法
|
||||
* @param payload 待加密载荷
|
||||
* @returns 加密信封
|
||||
*/
|
||||
export async function encryptCredentialPayload(
|
||||
loadMaterial: () => Promise<CredentialKeyMaterial>,
|
||||
payload: Record<string, any>,
|
||||
) {
|
||||
const material = await loadMaterial();
|
||||
const engine = getCredentialCryptoEngine();
|
||||
try {
|
||||
await verifyAndPersistPin(material, engine);
|
||||
return await engine.encryptPayload(
|
||||
material,
|
||||
JSON.stringify({
|
||||
...payload,
|
||||
nonce: material.nonce,
|
||||
timestamp: Date.now(),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === SECURITY_ERROR) {
|
||||
throw error;
|
||||
}
|
||||
throw new Error(SECURITY_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyAndPersistPin(material: CredentialKeyMaterial) {
|
||||
function getCredentialCryptoEngine() {
|
||||
return isWebCryptoAvailable() ? webCryptoEngine : forgeCryptoEngine;
|
||||
}
|
||||
|
||||
function isWebCryptoAvailable() {
|
||||
return Boolean(window.crypto?.subtle && window.crypto.getRandomValues);
|
||||
}
|
||||
|
||||
async function loadForge() {
|
||||
forgeModulePromise ||= import('node-forge');
|
||||
const forgeModule = await forgeModulePromise;
|
||||
return forgeModule.default || forgeModule;
|
||||
}
|
||||
|
||||
async function verifyAndPersistPin(
|
||||
material: CredentialKeyMaterial,
|
||||
engine: CredentialCryptoEngine,
|
||||
) {
|
||||
const current = readPin();
|
||||
if (!current) {
|
||||
writePin(material);
|
||||
@@ -89,7 +186,7 @@ async function verifyAndPersistPin(material: CredentialKeyMaterial) {
|
||||
writePin(material);
|
||||
return;
|
||||
}
|
||||
const nextPin = await verifyTransitionChain(current, material);
|
||||
const nextPin = await verifyTransitionChain(current, material, engine);
|
||||
if (!nextPin || nextPin.fingerprint !== material.fingerprint) {
|
||||
throw new Error(SECURITY_ERROR);
|
||||
}
|
||||
@@ -99,6 +196,7 @@ async function verifyAndPersistPin(material: CredentialKeyMaterial) {
|
||||
async function verifyTransitionChain(
|
||||
current: CredentialKeyPin,
|
||||
material: CredentialKeyMaterial,
|
||||
engine: CredentialCryptoEngine,
|
||||
) {
|
||||
let cursor = { ...current };
|
||||
const transitions = material.transitions || [];
|
||||
@@ -119,7 +217,7 @@ async function verifyTransitionChain(
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const verified = await verifyTransition(cursor.publicKey, transition);
|
||||
const verified = await safeVerifyTransition(engine, cursor.publicKey, transition);
|
||||
if (!verified) {
|
||||
return null;
|
||||
}
|
||||
@@ -132,21 +230,20 @@ async function verifyTransitionChain(
|
||||
return cursor;
|
||||
}
|
||||
|
||||
async function verifyTransition(
|
||||
publicKeyPem: string,
|
||||
async function safeVerifyTransition(
|
||||
engine: CredentialCryptoEngine,
|
||||
publicKey: string,
|
||||
transition: CredentialKeyTransition,
|
||||
) {
|
||||
const publicKey = await importSignPublicKey(publicKeyPem);
|
||||
return window.crypto.subtle.verify(
|
||||
{ name: 'RSASSA-PKCS1-v1_5' },
|
||||
publicKey,
|
||||
base64ToBytes(transition.signature),
|
||||
new TextEncoder().encode(transition.payload),
|
||||
);
|
||||
try {
|
||||
return await engine.verifyTransition(publicKey, transition);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeTransitionPayload(payload: string): TransitionPayload {
|
||||
const json = new TextDecoder().decode(base64UrlToBytes(payload));
|
||||
const json = utf8BytesToString(base64UrlToBytes(payload));
|
||||
return JSON.parse(json) as TransitionPayload;
|
||||
}
|
||||
|
||||
@@ -170,12 +267,6 @@ async function importSignPublicKey(publicKeyPem: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function ensureWebCrypto() {
|
||||
if (!window.crypto?.subtle || !window.crypto.getRandomValues) {
|
||||
throw new Error(UNSUPPORTED_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
function readPin(): CredentialKeyPin | null {
|
||||
const raw = window.localStorage.getItem(PIN_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
@@ -209,7 +300,14 @@ function pemToBytes(pem: string) {
|
||||
}
|
||||
|
||||
function base64ToBytes(value: string) {
|
||||
const binary = window.atob(value);
|
||||
return binaryToBytes(base64ToBinary(value));
|
||||
}
|
||||
|
||||
function base64ToBinary(value: string) {
|
||||
return window.atob(value);
|
||||
}
|
||||
|
||||
function binaryToBytes(binary: string) {
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
@@ -219,16 +317,35 @@ function base64ToBytes(value: string) {
|
||||
|
||||
function base64UrlToBytes(value: string) {
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
|
||||
let padded = normalized;
|
||||
while (padded.length % 4 !== 0) {
|
||||
padded += '=';
|
||||
}
|
||||
return base64ToBytes(padded);
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array) {
|
||||
return binaryToBase64(bytesToBinary(bytes));
|
||||
}
|
||||
|
||||
function bytesToBinary(bytes: Uint8Array) {
|
||||
let binary = '';
|
||||
bytes.forEach((item) => {
|
||||
binary += String.fromCharCode(item);
|
||||
});
|
||||
for (let index = 0; index < bytes.length; index += 1) {
|
||||
binary += String.fromCharCode(bytes[index] ?? 0);
|
||||
}
|
||||
return binary;
|
||||
}
|
||||
|
||||
function binaryToBase64(binary: string) {
|
||||
return window.btoa(binary);
|
||||
}
|
||||
|
||||
function stringToUtf8Bytes(value: string) {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
|
||||
function utf8BytesToString(bytes: Uint8Array) {
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
|
||||
export type { CredentialKeyMaterial };
|
||||
|
||||
@@ -258,7 +258,7 @@ function selectedVariant(round: AgentTryoutRawRound) {
|
||||
return (
|
||||
round.variants.find(
|
||||
(variant) => variant.variantIndex === round.selectedVariantIndex,
|
||||
) || round.variants.at(-1)
|
||||
) || round.variants[round.variants.length - 1]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import type { FormInstance } from 'element-plus';
|
||||
import type {FormInstance} from 'element-plus';
|
||||
import {ElForm, ElFormItem, ElInput, ElMessage} from 'element-plus';
|
||||
|
||||
import { onMounted, ref } from 'vue';
|
||||
import {onMounted, ref} from 'vue';
|
||||
|
||||
import { EasyFlowFormModal } from '@easyflow/common-ui';
|
||||
import { getResourceType } from '@easyflow/utils';
|
||||
import {EasyFlowFormModal} from '@easyflow/common-ui';
|
||||
import {getResourceType} from '@easyflow/utils';
|
||||
|
||||
import { ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus';
|
||||
|
||||
import { api } from '#/api/request';
|
||||
import {api} from '#/api/request';
|
||||
import DictSelect from '#/components/dict/DictSelect.vue';
|
||||
import Upload from '#/components/upload/Upload.vue';
|
||||
import { $t } from '#/locales';
|
||||
import { syncProgrammaticFieldValidation } from '#/utils/form-validation';
|
||||
import {$t} from '#/locales';
|
||||
import {syncProgrammaticFieldValidation} from '#/utils/form-validation';
|
||||
|
||||
const emit = defineEmits(['reload']);
|
||||
// vue
|
||||
@@ -99,7 +98,7 @@ function closeDialog() {
|
||||
function beforeUpload(f: any) {
|
||||
const fileName = f?.name || '';
|
||||
const fileNameParts = fileName.split('.');
|
||||
const fExt = fileNameParts.length > 1 ? fileNameParts.at(-1) || '' : '';
|
||||
const fExt = fileNameParts.length > 1 ? fileNameParts[fileNameParts.length - 1] || '' : '';
|
||||
const fName =
|
||||
fileNameParts.length > 1 ? fileNameParts.slice(0, -1).join('.') : fileName;
|
||||
entity.value.resourceType = getResourceType(fExt);
|
||||
|
||||
13
easyflow-ui-admin/pnpm-lock.yaml
generated
13
easyflow-ui-admin/pnpm-lock.yaml
generated
@@ -667,6 +667,9 @@ importers:
|
||||
markdown-it:
|
||||
specifier: ^14.1.0
|
||||
version: 14.1.0
|
||||
node-forge:
|
||||
specifier: 1.3.1
|
||||
version: 1.3.1
|
||||
pinia:
|
||||
specifier: ^3.0.3
|
||||
version: 3.0.4(typescript@5.9.3)(vue@3.5.24(typescript@5.9.3))
|
||||
@@ -689,6 +692,9 @@ importers:
|
||||
specifier: ^2.4.1
|
||||
version: 2.4.1(vue@3.5.24(typescript@5.9.3))
|
||||
devDependencies:
|
||||
'@types/node-forge':
|
||||
specifier: ^1.3.14
|
||||
version: 1.3.14
|
||||
cssnano:
|
||||
specifier: 'catalog:'
|
||||
version: 7.1.2(postcss@8.5.6)
|
||||
@@ -4291,6 +4297,9 @@ packages:
|
||||
'@types/ms@2.1.0':
|
||||
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
|
||||
|
||||
'@types/node-forge@1.3.14':
|
||||
resolution: {integrity: sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==}
|
||||
|
||||
'@types/node@12.20.55':
|
||||
resolution: {integrity: sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==}
|
||||
|
||||
@@ -14120,6 +14129,10 @@ snapshots:
|
||||
|
||||
'@types/ms@2.1.0': {}
|
||||
|
||||
'@types/node-forge@1.3.14':
|
||||
dependencies:
|
||||
'@types/node': 22.19.11
|
||||
|
||||
'@types/node@12.20.55': {}
|
||||
|
||||
'@types/node@22.19.11':
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
"dayjs": "catalog:",
|
||||
"element-plus": "catalog:",
|
||||
"fetch-event-stream": "^0.1.6",
|
||||
"node-forge": "1.3.1",
|
||||
"pinia": "catalog:",
|
||||
"radash": "^12.1.1",
|
||||
"vue": "catalog:",
|
||||
@@ -41,6 +42,7 @@
|
||||
"vue3-json-viewer": "^2.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"unplugin-element-plus": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,40 +28,41 @@ interface TransitionPayload {
|
||||
oldKeyId: string;
|
||||
}
|
||||
|
||||
interface EncryptedCredentialEnvelope {
|
||||
ciphertext: string;
|
||||
encryptedKey: string;
|
||||
iv: string;
|
||||
keyId: string;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
interface CredentialCryptoEngine {
|
||||
encryptPayload(
|
||||
material: CredentialKeyMaterial,
|
||||
plaintext: string,
|
||||
): Promise<EncryptedCredentialEnvelope>;
|
||||
verifyTransition(
|
||||
publicKeyPem: string,
|
||||
transition: CredentialKeyTransition,
|
||||
): Promise<boolean>;
|
||||
}
|
||||
|
||||
const PIN_STORAGE_KEY = 'easyflow:credential-key-pin:v1';
|
||||
const SECURITY_ERROR = '登录安全校验失败,请刷新或联系管理员';
|
||||
const UNSUPPORTED_ERROR = '当前浏览器不支持登录安全加密,请升级浏览器';
|
||||
let forgeModulePromise: Promise<any> | null = null;
|
||||
|
||||
/**
|
||||
* 加密密码类请求载荷。
|
||||
* @param loadMaterial 获取后端公钥材料的方法
|
||||
* @param payload 待加密载荷
|
||||
* @returns 加密信封
|
||||
*/
|
||||
export async function encryptCredentialPayload(
|
||||
loadMaterial: () => Promise<CredentialKeyMaterial>,
|
||||
payload: Record<string, any>,
|
||||
) {
|
||||
ensureWebCrypto();
|
||||
const material = await loadMaterial();
|
||||
await verifyAndPersistPin(material);
|
||||
const webCryptoEngine: CredentialCryptoEngine = {
|
||||
async encryptPayload(material, plaintext) {
|
||||
const aesKey = await window.crypto.subtle.generateKey(
|
||||
{ length: 256, name: 'AES-GCM' },
|
||||
true,
|
||||
['encrypt'],
|
||||
);
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
...payload,
|
||||
nonce: material.nonce,
|
||||
timestamp: Date.now(),
|
||||
}),
|
||||
);
|
||||
const ciphertext = await window.crypto.subtle.encrypt(
|
||||
{ iv, name: 'AES-GCM' },
|
||||
aesKey,
|
||||
plaintext,
|
||||
stringToUtf8Bytes(plaintext),
|
||||
);
|
||||
const rawAesKey = await window.crypto.subtle.exportKey('raw', aesKey);
|
||||
const publicKey = await importRsaPublicKey(material.publicKey, ['encrypt']);
|
||||
@@ -77,9 +78,105 @@ export async function encryptCredentialPayload(
|
||||
keyId: material.keyId,
|
||||
nonce: material.nonce,
|
||||
};
|
||||
},
|
||||
|
||||
async verifyTransition(publicKeyPem, transition) {
|
||||
const publicKey = await importSignPublicKey(publicKeyPem);
|
||||
return window.crypto.subtle.verify(
|
||||
{ name: 'RSASSA-PKCS1-v1_5' },
|
||||
publicKey,
|
||||
base64ToBytes(transition.signature),
|
||||
stringToUtf8Bytes(transition.payload),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const forgeCryptoEngine: CredentialCryptoEngine = {
|
||||
async encryptPayload(material, plaintext) {
|
||||
const forge = await loadForge();
|
||||
const aesKey = forge.random.getBytesSync(32);
|
||||
const iv = forge.random.getBytesSync(12);
|
||||
const cipher = forge.cipher.createCipher('AES-GCM', aesKey);
|
||||
cipher.start({ iv, tagLength: 128 });
|
||||
cipher.update(forge.util.createBuffer(plaintext, 'utf8'));
|
||||
cipher.finish();
|
||||
const ciphertextWithTag = cipher.output.getBytes() + cipher.mode.tag.getBytes();
|
||||
const publicKey = forge.pki.publicKeyFromPem(material.publicKey);
|
||||
const encryptedKey = publicKey.encrypt(aesKey, 'RSA-OAEP', {
|
||||
md: forge.md.sha256.create(),
|
||||
mgf1: {
|
||||
md: forge.md.sha256.create(),
|
||||
},
|
||||
});
|
||||
return {
|
||||
ciphertext: binaryToBase64(ciphertextWithTag),
|
||||
encryptedKey: binaryToBase64(encryptedKey),
|
||||
iv: binaryToBase64(iv),
|
||||
keyId: material.keyId,
|
||||
nonce: material.nonce,
|
||||
};
|
||||
},
|
||||
|
||||
async verifyTransition(publicKeyPem, transition) {
|
||||
const forge = await loadForge();
|
||||
const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
|
||||
const md = forge.md.sha256.create();
|
||||
md.update(transition.payload, 'utf8');
|
||||
return publicKey.verify(
|
||||
md.digest().bytes(),
|
||||
forge.util.decode64(transition.signature),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 加密密码类请求载荷。
|
||||
* @param loadMaterial 获取后端公钥材料的方法
|
||||
* @param payload 待加密载荷
|
||||
* @returns 加密信封
|
||||
*/
|
||||
export async function encryptCredentialPayload(
|
||||
loadMaterial: () => Promise<CredentialKeyMaterial>,
|
||||
payload: Record<string, any>,
|
||||
) {
|
||||
const material = await loadMaterial();
|
||||
const engine = getCredentialCryptoEngine();
|
||||
try {
|
||||
await verifyAndPersistPin(material, engine);
|
||||
return await engine.encryptPayload(
|
||||
material,
|
||||
JSON.stringify({
|
||||
...payload,
|
||||
nonce: material.nonce,
|
||||
timestamp: Date.now(),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === SECURITY_ERROR) {
|
||||
throw error;
|
||||
}
|
||||
throw new Error(SECURITY_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyAndPersistPin(material: CredentialKeyMaterial) {
|
||||
function getCredentialCryptoEngine() {
|
||||
return isWebCryptoAvailable() ? webCryptoEngine : forgeCryptoEngine;
|
||||
}
|
||||
|
||||
function isWebCryptoAvailable() {
|
||||
return Boolean(window.crypto?.subtle && window.crypto.getRandomValues);
|
||||
}
|
||||
|
||||
async function loadForge() {
|
||||
forgeModulePromise ||= import('node-forge');
|
||||
const forgeModule = await forgeModulePromise;
|
||||
return forgeModule.default || forgeModule;
|
||||
}
|
||||
|
||||
async function verifyAndPersistPin(
|
||||
material: CredentialKeyMaterial,
|
||||
engine: CredentialCryptoEngine,
|
||||
) {
|
||||
const current = readPin();
|
||||
if (!current) {
|
||||
writePin(material);
|
||||
@@ -89,7 +186,7 @@ async function verifyAndPersistPin(material: CredentialKeyMaterial) {
|
||||
writePin(material);
|
||||
return;
|
||||
}
|
||||
const nextPin = await verifyTransitionChain(current, material);
|
||||
const nextPin = await verifyTransitionChain(current, material, engine);
|
||||
if (!nextPin || nextPin.fingerprint !== material.fingerprint) {
|
||||
throw new Error(SECURITY_ERROR);
|
||||
}
|
||||
@@ -99,6 +196,7 @@ async function verifyAndPersistPin(material: CredentialKeyMaterial) {
|
||||
async function verifyTransitionChain(
|
||||
current: CredentialKeyPin,
|
||||
material: CredentialKeyMaterial,
|
||||
engine: CredentialCryptoEngine,
|
||||
) {
|
||||
let cursor = { ...current };
|
||||
const transitions = material.transitions || [];
|
||||
@@ -119,7 +217,7 @@ async function verifyTransitionChain(
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const verified = await verifyTransition(cursor.publicKey, transition);
|
||||
const verified = await safeVerifyTransition(engine, cursor.publicKey, transition);
|
||||
if (!verified) {
|
||||
return null;
|
||||
}
|
||||
@@ -132,21 +230,20 @@ async function verifyTransitionChain(
|
||||
return cursor;
|
||||
}
|
||||
|
||||
async function verifyTransition(
|
||||
publicKeyPem: string,
|
||||
async function safeVerifyTransition(
|
||||
engine: CredentialCryptoEngine,
|
||||
publicKey: string,
|
||||
transition: CredentialKeyTransition,
|
||||
) {
|
||||
const publicKey = await importSignPublicKey(publicKeyPem);
|
||||
return window.crypto.subtle.verify(
|
||||
{ name: 'RSASSA-PKCS1-v1_5' },
|
||||
publicKey,
|
||||
base64ToBytes(transition.signature),
|
||||
new TextEncoder().encode(transition.payload),
|
||||
);
|
||||
try {
|
||||
return await engine.verifyTransition(publicKey, transition);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeTransitionPayload(payload: string): TransitionPayload {
|
||||
const json = new TextDecoder().decode(base64UrlToBytes(payload));
|
||||
const json = utf8BytesToString(base64UrlToBytes(payload));
|
||||
return JSON.parse(json) as TransitionPayload;
|
||||
}
|
||||
|
||||
@@ -170,12 +267,6 @@ async function importSignPublicKey(publicKeyPem: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function ensureWebCrypto() {
|
||||
if (!window.crypto?.subtle || !window.crypto.getRandomValues) {
|
||||
throw new Error(UNSUPPORTED_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
function readPin(): CredentialKeyPin | null {
|
||||
const raw = window.localStorage.getItem(PIN_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
@@ -209,7 +300,14 @@ function pemToBytes(pem: string) {
|
||||
}
|
||||
|
||||
function base64ToBytes(value: string) {
|
||||
const binary = window.atob(value);
|
||||
return binaryToBytes(base64ToBinary(value));
|
||||
}
|
||||
|
||||
function base64ToBinary(value: string) {
|
||||
return window.atob(value);
|
||||
}
|
||||
|
||||
function binaryToBytes(binary: string) {
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
@@ -219,16 +317,35 @@ function base64ToBytes(value: string) {
|
||||
|
||||
function base64UrlToBytes(value: string) {
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
|
||||
let padded = normalized;
|
||||
while (padded.length % 4 !== 0) {
|
||||
padded += '=';
|
||||
}
|
||||
return base64ToBytes(padded);
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array) {
|
||||
return binaryToBase64(bytesToBinary(bytes));
|
||||
}
|
||||
|
||||
function bytesToBinary(bytes: Uint8Array) {
|
||||
let binary = '';
|
||||
bytes.forEach((item) => {
|
||||
binary += String.fromCharCode(item);
|
||||
});
|
||||
for (let index = 0; index < bytes.length; index += 1) {
|
||||
binary += String.fromCharCode(bytes[index] ?? 0);
|
||||
}
|
||||
return binary;
|
||||
}
|
||||
|
||||
function binaryToBase64(binary: string) {
|
||||
return window.btoa(binary);
|
||||
}
|
||||
|
||||
function stringToUtf8Bytes(value: string) {
|
||||
return new TextEncoder().encode(value);
|
||||
}
|
||||
|
||||
function utf8BytesToString(bytes: Uint8Array) {
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
|
||||
export type { CredentialKeyMaterial };
|
||||
|
||||
14
easyflow-ui-usercenter/pnpm-lock.yaml
generated
14
easyflow-ui-usercenter/pnpm-lock.yaml
generated
@@ -646,6 +646,9 @@ importers:
|
||||
fetch-event-stream:
|
||||
specifier: ^0.1.6
|
||||
version: 0.1.6
|
||||
node-forge:
|
||||
specifier: 1.3.1
|
||||
version: 1.3.1
|
||||
pinia:
|
||||
specifier: ^3.0.3
|
||||
version: 3.0.4(typescript@5.9.3)(vue@3.5.24(typescript@5.9.3))
|
||||
@@ -668,6 +671,9 @@ importers:
|
||||
specifier: ^2.4.1
|
||||
version: 2.4.1(vue@3.5.24(typescript@5.9.3))
|
||||
devDependencies:
|
||||
'@types/node-forge':
|
||||
specifier: ^1.3.14
|
||||
version: 1.3.14
|
||||
unplugin-element-plus:
|
||||
specifier: 'catalog:'
|
||||
version: 0.10.0
|
||||
@@ -3986,6 +3992,9 @@ packages:
|
||||
'@types/ms@2.1.0':
|
||||
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
|
||||
|
||||
'@types/node-forge@1.3.14':
|
||||
resolution: {integrity: sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==}
|
||||
|
||||
'@types/node@12.20.55':
|
||||
resolution: {integrity: sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==}
|
||||
|
||||
@@ -10033,6 +10042,7 @@ packages:
|
||||
whatwg-encoding@3.1.1:
|
||||
resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}
|
||||
engines: {node: '>=18'}
|
||||
deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation
|
||||
|
||||
whatwg-mimetype@3.0.0:
|
||||
resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
|
||||
@@ -12962,6 +12972,10 @@ snapshots:
|
||||
|
||||
'@types/ms@2.1.0': {}
|
||||
|
||||
'@types/node-forge@1.3.14':
|
||||
dependencies:
|
||||
'@types/node': 24.10.1
|
||||
|
||||
'@types/node@12.20.55': {}
|
||||
|
||||
'@types/node@24.10.1':
|
||||
|
||||
Reference in New Issue
Block a user