feat(uuid): implement UUID generation for non-secure contexts and replace crypto.randomUUID() usage

This commit is contained in:
PeymanHonarjoo
2026-10-12 16:50:52 +03:30
parent e268631386
commit 0af55f52a3
7 changed files with 64 additions and 15 deletions
+6 -5
View File
@@ -14,6 +14,7 @@ import { ThemeService } from '../../services/theme/theme.service';
import { DocumentsService } from '../../services/documents/documents.service';
import { AuthService } from '../../services/auth/auth.service';
import { HttpService } from '../../services/http-request/http.service';
import { uuid } from '../../shared/utils/uuid';
import {
AiModelConfigCardComponent,
AiModelConfig,
@@ -434,7 +435,7 @@ export class SettingsPage implements OnInit, OnDestroy {
progress: 0,
status: 'uploading',
error: null,
idempotencyKey: crypto.randomUUID(),
idempotencyKey: uuid(),
});
}
}
@@ -931,7 +932,7 @@ export class SettingsPage implements OnInit, OnDestroy {
checked: [],
note: '',
excludedGroupIds: [],
idempotencyKey: crypto.randomUUID(),
idempotencyKey: uuid(),
};
}
}
@@ -1023,7 +1024,7 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.warning('هنوز شواهد بازبینی تکمیل نشده‌اند.');
return;
}
const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID();
const key = this.retryKeys.get(doc.id) ?? uuid();
this.retryKeys.set(doc.id, key);
this.documentsService.retryDocument(doc.id, key).subscribe({
next: () => {
@@ -1051,7 +1052,7 @@ export class SettingsPage implements OnInit, OnDestroy {
checked: [],
note: '',
excludedGroupIds: [],
idempotencyKey: crypto.randomUUID(),
idempotencyKey: uuid(),
}
);
}
@@ -1169,7 +1170,7 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.warning('سند در حال حاضر قابل تلاش مجدد نیست.');
return;
}
const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID();
const key = this.retryKeys.get(doc.id) ?? uuid();
this.retryKeys.set(doc.id, key);
this.documentsService.retryDocument(doc.id, key).subscribe({
next: (res: RetryResult) => {
+2 -1
View File
@@ -3,6 +3,7 @@ import { Observable, BehaviorSubject, firstValueFrom, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { HttpService } from '../http-request/http.service';
import { uuid } from '../../shared/utils/uuid';
export interface AuthUser {
id: string;
@@ -92,7 +93,7 @@ export class AuthService {
/** Per-request correlation id shared with the server's `X-Request-ID`. */
private correlationHeaders(): Record<string, string> {
return { 'X-Request-ID': crypto.randomUUID() };
return { 'X-Request-ID': uuid() };
}
/**
@@ -3,6 +3,7 @@ import { HttpErrorResponse, HttpEventType, HttpHeaders, HttpParams } from '@angu
import { map, filter, Observable, tap } from 'rxjs';
import { HttpService } from '../http-request/http.service';
import { AuthService } from '../auth/auth.service';
import { uuid } from '../../shared/utils/uuid';
import {
DocumentDetail,
DocumentListParams,
@@ -34,7 +35,7 @@ export class DocumentsService {
* (from the login/`/me` flow) and a per-request correlation id.
*/
private csrfHeaders(): Record<string, string> {
const headers: Record<string, string> = { 'X-Request-ID': crypto.randomUUID() };
const headers: Record<string, string> = { 'X-Request-ID': uuid() };
const token = this.auth.getCsrfToken();
if (token) {
headers['X-CSRF-Token'] = token;
@@ -91,7 +92,7 @@ export class DocumentsService {
title: string | undefined,
onProgress: (percent: number) => void,
signal?: AbortSignal,
idempotencyKey: string = crypto.randomUUID(),
idempotencyKey: string = uuid(),
): Observable<DocumentUploadResult> {
const form = new FormData();
form.append('file', file);
@@ -123,7 +124,7 @@ export class DocumentsService {
submitReviewDecision(
documentId: string,
request: ReviewDecisionRequest,
idempotencyKey: string = crypto.randomUUID(),
idempotencyKey: string = uuid(),
): Observable<ReviewDecisionResponse> {
return this.http.postRaw<ReviewDecisionResponse>(
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`,
@@ -147,7 +148,7 @@ export class DocumentsService {
/** D04 — retry processing of a document. */
retryDocument(
documentId: string,
idempotencyKey: string = crypto.randomUUID(),
idempotencyKey: string = uuid(),
): Observable<RetryResult> {
return this.http.postRaw<RetryResult>(
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
@@ -52,7 +52,7 @@ export class HttpService {
* and is sent automatically; no bearer token is used for the MVP endpoints.
*
* NOTE: the origin MUST stay empty (`''`). Pointing these at an absolute host
* (e.g. `http://10.2.8.3:8080`) turns every request cross-origin, and browsers
* (e.g. `http://192.168.180.151:8080`) turns every request cross-origin, and browsers
* refuse to send the session cookie cross-origin over plain HTTP — the backend
* then answers 401 AUTH_REQUIRED even though the user is logged in.
*/
@@ -1,6 +1,7 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { firstValueFrom, Observable } from 'rxjs';
import { uuid } from '../../shared/utils/uuid';
import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types';
/**
@@ -165,7 +166,7 @@ export class VoiceApiService {
}
private readOptions() {
return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': crypto.randomUUID() }) };
return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': uuid() }) };
}
private writeOptions(csrf: string) {
@@ -173,7 +174,7 @@ export class VoiceApiService {
withCredentials: true,
headers: new HttpHeaders({
'X-CSRF-Token': csrf,
'X-Request-ID': crypto.randomUUID(),
'X-Request-ID': uuid(),
}),
};
}
+45
View File
@@ -0,0 +1,45 @@
/**
* UUID generation that works outside secure contexts.
*
* `crypto.randomUUID()` only exists in secure contexts (HTTPS or `localhost`). It is
* unavailable on plain-HTTP origins — common for internal/LAN deployments — and calling
* it there throws `TypeError: crypto.randomUUID is not a function`, which took down
* login entirely. Every id the frontend mints per request (`X-Request-ID`,
* `Idempotency-Key`, `client_request_id`) therefore goes through here.
*/
/**
* RFC 4122 v4 UUID.
*
* Prefers `crypto.randomUUID()`, then `crypto.getRandomValues()` (available in every
* context, and what `randomUUID` itself is built on), and only then `Math.random()` —
* ids stay unique per request in all cases.
*/
export function uuid(): string {
const c: Crypto | undefined = typeof crypto !== 'undefined' ? crypto : undefined;
if (typeof c?.randomUUID === 'function') return c.randomUUID();
if (typeof c?.getRandomValues === 'function') {
const bytes = new Uint8Array(16);
c.getRandomValues(bytes);
// Version 4 (random) + RFC 4122 variant bits.
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex: string[] = [];
for (let i = 0; i < 16; i++) {
hex.push(bytes[i].toString(16).padStart(2, '0'));
}
return (
`${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-` +
`${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}`
);
}
// Last resort: no Web Crypto at all. Not cryptographically strong, but still unique.
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
const r = (Math.random() * 16) | 0;
return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
}