Merge branch 'hugo-shipping-notice' into dev
This commit is contained in:
commit
a2931e0095
37 files changed
+1790
-126
No files matched your search
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* shared/utils/id.test.ts
|
||||
* 用途:校验 createRandomUuid 在缺少 randomUUID 时仍可生成可用 ID。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRandomUuid } from './id';
|
||||
|
||||
describe('createRandomUuid', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('uses crypto.randomUUID when available', () => {
|
||||
// 断言:安全上下文走原生 API。
|
||||
vi.stubGlobal('crypto', {
|
||||
randomUUID: () => '11111111-2222-4333-8444-555555555555',
|
||||
});
|
||||
expect(createRandomUuid()).toBe('11111111-2222-4333-8444-555555555555');
|
||||
});
|
||||
|
||||
it('falls back when randomUUID is missing (HTTP non-secure context)', () => {
|
||||
// 断言:模拟内网 HTTP,无 randomUUID 也不抛错,且返回非空串。
|
||||
vi.stubGlobal('crypto', {
|
||||
getRandomValues: (bytes: Uint8Array) => {
|
||||
for (let i = 0; i < bytes.length; i += 1) bytes[i] = i;
|
||||
return bytes;
|
||||
},
|
||||
});
|
||||
const value = createRandomUuid();
|
||||
expect(value).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* shared/utils/id.ts
|
||||
* 用途:生成客户端随机 ID(会话号、operation_id、幂等键等)。
|
||||
* 依赖:Web Crypto(优先);无安全上下文时回退到 getRandomValues / Math.random。
|
||||
* 逻辑:HTTP 内网(如 192.168.x)不是 secure context,`crypto.randomUUID` 不可用,
|
||||
* 直接调用会在 Vue setup 阶段抛 TypeError 导致白屏;统一走本工具避免分叉。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 生成 UUID 风格随机串;优先 `crypto.randomUUID`,HTTP 等非安全上下文自动降级。
|
||||
* 核心逻辑:secure context 用原生 API;否则用 getRandomValues 拼 RFC4122 v4;再不行用时间戳+随机。
|
||||
* @returns 形如 `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` 的字符串(降级路径不保证密码学强度)
|
||||
*/
|
||||
export function createRandomUuid(): string {
|
||||
const webCrypto = globalThis.crypto;
|
||||
if (webCrypto && typeof webCrypto.randomUUID === 'function') {
|
||||
return webCrypto.randomUUID();
|
||||
}
|
||||
if (webCrypto && typeof webCrypto.getRandomValues === 'function') {
|
||||
const bytes = new Uint8Array(16);
|
||||
webCrypto.getRandomValues(bytes);
|
||||
// noUncheckedIndexedAccess 下 Uint8Array 下标为 number | undefined
|
||||
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
||||
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
return `fallback-${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 10)}`;
|
||||
}
|
||||
Reference in new issue
Block a user