diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue index 8832c7af..565cb91a 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue @@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { BusinessError } from '@/shared/api/client'; import { useMessage } from '@/shared/composables/useMessage'; +import { createRandomUuid } from '@/shared/utils/id'; import { approveOrderProfileTestSuite, confirmOrderProfileBlindTestReviews, @@ -36,7 +37,7 @@ const router = useRouter(); const message = useMessage(); const { t } = useI18n(); const profileId = Number(route.params.profileId); -const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID(); +const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid(); const suite = ref(null); const availableSamples = ref([]); const selectedSampleKey = ref(''); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue index f312f70d..442a59eb 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue @@ -11,6 +11,7 @@ import { useI18n } from 'vue-i18n'; import { ArrowLeft, ArrowRight, Check, FileText, Layers3, Sparkles } from 'lucide-vue-next'; import { BusinessError } from '@/shared/api/client'; import { useMessage } from '@/shared/composables/useMessage'; +import { createRandomUuid } from '@/shared/utils/id'; import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api'; import { completeOrderDocumentProfileWizard, getOrderProfileSampleTables, listOrderProfileSamples } from '@/features/admin/api/shipping-order-document-profile.api'; import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types'; @@ -33,7 +34,7 @@ const tables = ref({ displayName: '', schemaId: 0 }); const documentId = ref(0); const tableId = ref(''); -const browserSessionId = crypto.randomUUID(); +const browserSessionId = createRandomUuid(); let sampleRefreshTimer: ReturnType | null = null; const publishedSchemas = computed(() => schemas.value.filter((item) => item.status === 'published')); @@ -140,7 +141,7 @@ async function finish(enterEditor: boolean): Promise { document_id: documentId.value, main_table_id: tableId.value, browser_session_id: browserSessionId, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), }; const profile = await completeOrderDocumentProfileWizard(payload); message.success(t('admin.shippingOrderProfiles.created')); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue index f6ff1e9c..240aea70 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue @@ -21,6 +21,7 @@ import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router"; import { useI18n } from "vue-i18n"; import { BusinessError } from "@/shared/api/client"; import { useMessage } from "@/shared/composables/useMessage"; +import { createRandomUuid } from "@/shared/utils/id"; import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api"; import { authorizeOrderProfilePreviewPages, @@ -218,7 +219,7 @@ const documentAnchorNotice = ref(''); const history = ref([]); const future = ref([]); const editLeaseToken = ref(null); -const editorSessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID(); +const editorSessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid(); const compactEditor = ref(false); const saveState = ref<'saved' | 'saving' | 'failed' | 'readonly'>('saved'); @@ -1820,7 +1821,7 @@ const save = async (automatic = false) => { expected_lock_version: existingProfile.lock_version, browser_session_id: editorSessionId, lease_token: editLeaseToken.value || '', - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), ...(adapterPayload.splitRuleConfirmationTokens ? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens } : {}), @@ -2139,7 +2140,7 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted await decideOrderDocumentProfileSuggestion(active.value.id, { suggestion_id: item.id, suggestion_checksum: item.checksum, suggestion_summary: item.summary, decision, adjustment_summary: adjustmentSummary, - browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: crypto.randomUUID(), + browser_session_id: editorSessionId, lease_token: editLeaseToken.value, operation_id: createRandomUuid(), }); if (decision !== 'rejected') { checkpoint(); @@ -2758,7 +2759,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => { const acquireEditLease = async (profileId: number): Promise => { const lease = await acquireOrderDocumentProfileEditLease(profileId, { browser_session_id: editorSessionId, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), }); editLeaseToken.value = lease.lease_token; startLeaseRenewal(); @@ -2774,7 +2775,7 @@ const renewEditLease = async (): Promise => { const lease = await renewOrderDocumentProfileEditLease(active.value.id, { browser_session_id: editorSessionId, lease_token: editLeaseToken.value, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), }); editLeaseToken.value = lease.lease_token; } catch (error) { @@ -2961,7 +2962,7 @@ const recoverEditLease = async (confirmTakeover = false) => { try { const lease = await acquireOrderDocumentProfileEditLease(active.value.id, { browser_session_id: editorSessionId, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), confirm_takeover: confirmTakeover, }); editLeaseToken.value = lease.lease_token; @@ -3124,7 +3125,7 @@ onBeforeUnmount(() => { void releaseOrderDocumentProfileEditLease(active.value.id, { browser_session_id: editorSessionId, lease_token: editLeaseToken.value, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), }); } }); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue index 1fbf9fc8..b3ae71cb 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue @@ -10,6 +10,7 @@ import { useRoute, useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { BusinessError } from '@/shared/api/client'; import { useMessage } from '@/shared/composables/useMessage'; +import { createRandomUuid } from '@/shared/utils/id'; import { acquireOrderDocumentProfileEditLease, confirmOrderProfilePublishCheck, @@ -31,7 +32,7 @@ const runs = ref([]); const report = ref(null); const confirmed = ref([]); const busy = ref(false); -const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID(); +const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid(); const leaseToken = ref(''); const validationRun = computed(() => runs.value.find((item) => item.run_type === 'current_sample' && item.status === 'passed') || null); @@ -92,7 +93,7 @@ async function ensureLease(): Promise { try { leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, { browser_session_id: sessionId, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), })).lease_token; return true; } catch (error) { @@ -121,7 +122,7 @@ async function createReport(): Promise { overlap_validation_run_id: overlapRun.value?.id, browser_session_id: sessionId, lease_token: leaseToken.value, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), }); confirmed.value = []; await loadRuns(); @@ -141,7 +142,7 @@ async function publish(): Promise { confirmed_warning_keys: confirmed.value, browser_session_id: sessionId, lease_token: leaseToken.value, - operation_id: crypto.randomUUID(), + operation_id: createRandomUuid(), }); await router.replace({ name: 'AdminShippingOrderDocumentProfileVersionDetail', diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue index 366fde26..120a47bc 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue @@ -11,6 +11,7 @@ import { useRoute, useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { BusinessError } from '@/shared/api/client'; import { useMessage } from '@/shared/composables/useMessage'; +import { createRandomUuid } from '@/shared/utils/id'; import { getShippingOrderSchemaVersion } from '@/features/admin/api/shipping-order-schema.api'; import { acquireOrderDocumentProfileEditLease, @@ -42,7 +43,7 @@ const leaseToken = ref(''); const profile = ref(null); const sample = ref(null); const fieldNames = ref(new Map()); -const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID(); +const sessionId = String(route.query.editorSessionId || '').trim() || createRandomUuid(); const blindTestSuite = ref(null); const validationEvidence = computed(() => { const raw = sampleRun.value?.summary?.validation_evidence; @@ -206,7 +207,7 @@ async function ensureLease(): Promise { if (leaseToken.value) return true; try { leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, { - browser_session_id: sessionId, operation_id: crypto.randomUUID(), + browser_session_id: sessionId, operation_id: createRandomUuid(), })).lease_token; return true; } catch (error) { report(error); return false; } @@ -221,7 +222,7 @@ async function validateCurrentDraft(): Promise { } executing.value = true; try { - const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() }); + const payload = () => ({ browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: createRandomUuid() }); await runOrderProfileInstantCheck(profileId, payload()); await runOrderProfileCurrentSample(profileId, { ...payload(), sample_binding_id: sample.value.id }); await loadRuns(); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue index 511e03dd..010c4933 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue @@ -10,6 +10,7 @@ import { computed, onMounted, ref, watch } from 'vue'; import { useI18n } from 'vue-i18n'; import { BusinessError } from '@/shared/api/client'; import { useMessage } from '@/shared/composables/useMessage'; +import { createRandomUuid } from '@/shared/utils/id'; import { previewOrderProfileSampleXfaSplitRules, } from '@/features/admin/api/shipping-order-document-profile.api'; @@ -97,9 +98,10 @@ const showUnsavedConfirmBanner = computed(() => ( /** * 生成 seg-/rule-/stage- 前缀的客户端 UUID(无连字符)。 + * HTTP 非安全上下文亦可用(经 createRandomUuid 降级)。 */ function newClientId(prefix: 'seg' | 'rule' | 'stage'): string { - return `${prefix}-${crypto.randomUUID().replace(/-/g, '')}`; + return `${prefix}-${createRandomUuid().replace(/-/g, '')}`; } /** diff --git a/frontend/src/shared/utils/id.test.ts b/frontend/src/shared/utils/id.test.ts new file mode 100644 index 00000000..c09c511f --- /dev/null +++ b/frontend/src/shared/utils/id.test.ts @@ -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, + ); + }); +}); diff --git a/frontend/src/shared/utils/id.ts b/frontend/src/shared/utils/id.ts new file mode 100644 index 00000000..93943e29 --- /dev/null +++ b/frontend/src/shared/utils/id.ts @@ -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)}`; +}