@angular-helpers/security 21.2.0 → 21.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.es.md +195 -0
- package/README.md +197 -0
- package/fesm2022/angular-helpers-security-forms.mjs +110 -0
- package/fesm2022/angular-helpers-security-signal-forms.mjs +159 -0
- package/fesm2022/angular-helpers-security.mjs +920 -180
- package/package.json +15 -1
- package/types/angular-helpers-security-forms.d.ts +65 -0
- package/types/angular-helpers-security-signal-forms.d.ts +99 -0
- package/types/angular-helpers-security.d.ts +414 -10
package/README.es.md
CHANGED
|
@@ -49,6 +49,37 @@ Paquete de seguridad para aplicaciones Angular que previene ataques comunes como
|
|
|
49
49
|
- **Detección de Patrones**: Detectar patrones de teclado y secuencias
|
|
50
50
|
- **Feedback Accionable**: Sugerencias específicas para mejorar
|
|
51
51
|
|
|
52
|
+
### **Validators de Formularios (sub-entries)**
|
|
53
|
+
|
|
54
|
+
- **`@angular-helpers/security/forms`**: puente para Reactive Forms — `SecurityValidators.strongPassword`, `safeHtml`, `safeUrl`, `noScriptInjection`, `noSqlInjectionHints`.
|
|
55
|
+
- **`@angular-helpers/security/signal-forms`**: puente para Signal Forms de Angular v21 — `strongPassword`, `safeHtml`, `safeUrl`, `noScriptInjection`, `noSqlInjectionHints`, y el async `hibpPassword`.
|
|
56
|
+
- **Core compartido**: ambos paradigmas delegan en los mismos helpers puros para garantizar paridad de comportamiento.
|
|
57
|
+
|
|
58
|
+
### **Inspección de JWT**
|
|
59
|
+
|
|
60
|
+
- **Decodificación client-side**: `decode`, `claim`, `isExpired`, `expiresIn`.
|
|
61
|
+
- **Explícitamente NO verifica firma**: la validación criptográfica se hace server-side.
|
|
62
|
+
|
|
63
|
+
### **Protección CSRF**
|
|
64
|
+
|
|
65
|
+
- **`CsrfService`**: double-submit con tokens generados por `WebCryptoService.generateRandomBytes`.
|
|
66
|
+
- **`withCsrfHeader()`**: interceptor funcional que inyecta el header en POST/PUT/PATCH/DELETE.
|
|
67
|
+
|
|
68
|
+
### **Rate Limiter**
|
|
69
|
+
|
|
70
|
+
- **Token-bucket** y **sliding-window**, configurables por clave.
|
|
71
|
+
- **Estado basado en signals**: `canExecute(key)` y `remaining(key)` devuelven `Signal<T>`.
|
|
72
|
+
|
|
73
|
+
### **HIBP Leaked Password Check**
|
|
74
|
+
|
|
75
|
+
- **k-anonymity**: sólo los primeros 5 caracteres hex del SHA-1 salen del navegador.
|
|
76
|
+
- **Fail-open**: los errores de red nunca bloquean el envío del formulario.
|
|
77
|
+
|
|
78
|
+
### **Clipboard Sensible**
|
|
79
|
+
|
|
80
|
+
- **Auto-clear verificado**: lee el clipboard antes de limpiar para no pisar contenido ajeno.
|
|
81
|
+
- **Estilo password-manager**: default 15 segundos, configurable.
|
|
82
|
+
|
|
52
83
|
### **Patrón Builder**
|
|
53
84
|
|
|
54
85
|
- **API Fluida**: Construye expresiones regulares de forma intuitiva.
|
|
@@ -305,6 +336,170 @@ export class RegistrationComponent {
|
|
|
305
336
|
}
|
|
306
337
|
```
|
|
307
338
|
|
|
339
|
+
### **SecurityValidators — Reactive Forms**
|
|
340
|
+
|
|
341
|
+
```typescript
|
|
342
|
+
import { FormControl, FormGroup, Validators } from '@angular/forms';
|
|
343
|
+
import { SecurityValidators } from '@angular-helpers/security/forms';
|
|
344
|
+
|
|
345
|
+
export class SignupFormComponent {
|
|
346
|
+
form = new FormGroup({
|
|
347
|
+
password: new FormControl('', [
|
|
348
|
+
Validators.required,
|
|
349
|
+
SecurityValidators.strongPassword({ minScore: 3 }),
|
|
350
|
+
]),
|
|
351
|
+
bio: new FormControl('', [SecurityValidators.safeHtml()]),
|
|
352
|
+
homepage: new FormControl('', [SecurityValidators.safeUrl({ schemes: ['https:'] })]),
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
Los validators son factory functions estáticas — no hace falta registrar providers. Delegan en los
|
|
358
|
+
mismos helpers puros que usa la versión Signal Forms, así que ambos paradigmas devuelven resultados
|
|
359
|
+
equivalentes para el mismo input.
|
|
360
|
+
|
|
361
|
+
### **Validators para Signal Forms**
|
|
362
|
+
|
|
363
|
+
```typescript
|
|
364
|
+
import { signal } from '@angular/core';
|
|
365
|
+
import { form, required } from '@angular/forms/signals';
|
|
366
|
+
import {
|
|
367
|
+
strongPassword,
|
|
368
|
+
hibpPassword,
|
|
369
|
+
safeHtml,
|
|
370
|
+
safeUrl,
|
|
371
|
+
} from '@angular-helpers/security/signal-forms';
|
|
372
|
+
|
|
373
|
+
export class SignupSignalFormsComponent {
|
|
374
|
+
model = signal({ email: '', password: '', bio: '', homepage: '' });
|
|
375
|
+
|
|
376
|
+
f = form(this.model, (p) => {
|
|
377
|
+
required(p.email);
|
|
378
|
+
required(p.password);
|
|
379
|
+
strongPassword(p.password, { minScore: 3 });
|
|
380
|
+
hibpPassword(p.password); // async — valida contra HIBP
|
|
381
|
+
safeHtml(p.bio);
|
|
382
|
+
safeUrl(p.homepage, { schemes: ['https:'] });
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
**Requisito del sub-entry**: instalar `@angular/forms`. El entry principal
|
|
388
|
+
`@angular-helpers/security` no depende de `@angular/forms`.
|
|
389
|
+
|
|
390
|
+
**Regla HIBP async**: `hibpPassword` requiere `provideHibp()` en la jerarquía del inyector. Falla
|
|
391
|
+
en modo open — errores de red nunca bloquean el submit del formulario.
|
|
392
|
+
|
|
393
|
+
### **JwtService — Inspección Client-Side**
|
|
394
|
+
|
|
395
|
+
```typescript
|
|
396
|
+
import { JwtService } from '@angular-helpers/security';
|
|
397
|
+
|
|
398
|
+
export class SessionGuard {
|
|
399
|
+
private jwt = inject(JwtService);
|
|
400
|
+
|
|
401
|
+
isAuthenticated(): boolean {
|
|
402
|
+
const token = localStorage.getItem('access_token');
|
|
403
|
+
if (!token) return false;
|
|
404
|
+
return !this.jwt.isExpired(token, 30); // 30 segundos de leeway
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
currentUserId(): string | null {
|
|
408
|
+
const token = localStorage.getItem('access_token');
|
|
409
|
+
return token ? this.jwt.claim<string>(token, 'sub') : null;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
> **Nota de seguridad**: `JwtService` sólo decodifica payloads para inspección. **Nunca** confíes
|
|
415
|
+
> en el contenido para decisiones de autorización — la verificación de la firma va siempre
|
|
416
|
+
> server-side.
|
|
417
|
+
|
|
418
|
+
### **CsrfService + `withCsrfHeader()`**
|
|
419
|
+
|
|
420
|
+
```typescript
|
|
421
|
+
import { bootstrapApplication } from '@angular/platform-browser';
|
|
422
|
+
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
|
423
|
+
import { provideSecurity, CsrfService, withCsrfHeader } from '@angular-helpers/security';
|
|
424
|
+
|
|
425
|
+
bootstrapApplication(App, {
|
|
426
|
+
providers: [
|
|
427
|
+
provideSecurity({ enableCsrf: true }),
|
|
428
|
+
provideHttpClient(withInterceptors([withCsrfHeader()])),
|
|
429
|
+
],
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
// Tras el login:
|
|
433
|
+
const csrf = inject(CsrfService);
|
|
434
|
+
csrf.storeToken(response.csrfToken);
|
|
435
|
+
// A partir de ahora, todas las requests POST/PUT/PATCH/DELETE llevan X-CSRF-Token.
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
### **RateLimiterService**
|
|
439
|
+
|
|
440
|
+
```typescript
|
|
441
|
+
import { RateLimiterService, RateLimitExceededError } from '@angular-helpers/security';
|
|
442
|
+
|
|
443
|
+
export class SearchComponent {
|
|
444
|
+
private rateLimiter = inject(RateLimiterService);
|
|
445
|
+
|
|
446
|
+
constructor() {
|
|
447
|
+
this.rateLimiter.configure('search', {
|
|
448
|
+
type: 'token-bucket',
|
|
449
|
+
capacity: 5,
|
|
450
|
+
refillPerSecond: 1,
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
canSearch = this.rateLimiter.canExecute('search'); // Signal<boolean>
|
|
455
|
+
remaining = this.rateLimiter.remaining('search'); // Signal<number>
|
|
456
|
+
|
|
457
|
+
async search(query: string) {
|
|
458
|
+
try {
|
|
459
|
+
await this.rateLimiter.consume('search');
|
|
460
|
+
return this.api.search(query);
|
|
461
|
+
} catch (err) {
|
|
462
|
+
if (err instanceof RateLimitExceededError) {
|
|
463
|
+
// Mostrar countdown usando err.retryAfterMs
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
### **HibpService**
|
|
471
|
+
|
|
472
|
+
```typescript
|
|
473
|
+
import { HibpService } from '@angular-helpers/security';
|
|
474
|
+
|
|
475
|
+
export class RegistrationComponent {
|
|
476
|
+
private hibp = inject(HibpService);
|
|
477
|
+
|
|
478
|
+
async checkPassword(password: string) {
|
|
479
|
+
const { leaked, count, error } = await this.hibp.isPasswordLeaked(password);
|
|
480
|
+
if (error) return; // fail-open en errores de red
|
|
481
|
+
if (leaked) alert(`Esta contraseña apareció en ${count} brechas.`);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
### **SensitiveClipboardService**
|
|
487
|
+
|
|
488
|
+
```typescript
|
|
489
|
+
import { SensitiveClipboardService } from '@angular-helpers/security';
|
|
490
|
+
|
|
491
|
+
export class ApiKeyPanel {
|
|
492
|
+
private sensitiveClipboard = inject(SensitiveClipboardService);
|
|
493
|
+
|
|
494
|
+
async copy(value: string) {
|
|
495
|
+
await this.sensitiveClipboard.copy(value, { clearAfterMs: 15_000 });
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
El servicio lee el clipboard antes de limpiarlo y omite el clear si el contenido ya no coincide con
|
|
501
|
+
lo que escribió — así evita pisar copias que el usuario haya hecho en otra parte.
|
|
502
|
+
|
|
308
503
|
## 📊 Niveles de Riesgo
|
|
309
504
|
|
|
310
505
|
| Nivel | Descripción | Acción |
|
package/README.md
CHANGED
|
@@ -45,6 +45,37 @@ Security package for Angular applications that prevents common attacks like ReDo
|
|
|
45
45
|
- **Common Password Check**: Blocks frequently used passwords
|
|
46
46
|
- **Feedback Messages**: Actionable improvement suggestions
|
|
47
47
|
|
|
48
|
+
### **Forms Validators (sub-entries)**
|
|
49
|
+
|
|
50
|
+
- **`@angular-helpers/security/forms`**: Reactive Forms bridge — `SecurityValidators.strongPassword`, `safeHtml`, `safeUrl`, `noScriptInjection`, `noSqlInjectionHints`.
|
|
51
|
+
- **`@angular-helpers/security/signal-forms`**: Angular v21 Signal Forms bridge — `strongPassword`, `safeHtml`, `safeUrl`, `noScriptInjection`, `noSqlInjectionHints`, and async `hibpPassword`.
|
|
52
|
+
- **Shared core**: both paradigms delegate to the same pure helpers for guaranteed behavioural parity.
|
|
53
|
+
|
|
54
|
+
### **JWT Inspection**
|
|
55
|
+
|
|
56
|
+
- **Client-side decode**: `decode`, `claim`, `isExpired`, `expiresIn`.
|
|
57
|
+
- **Explicit non-verifying**: signature validation must happen server-side.
|
|
58
|
+
|
|
59
|
+
### **CSRF Protection**
|
|
60
|
+
|
|
61
|
+
- **`CsrfService`**: double-submit token helper backed by `WebCryptoService.generateRandomBytes`.
|
|
62
|
+
- **`withCsrfHeader()`**: functional HTTP interceptor that injects the token on POST/PUT/PATCH/DELETE.
|
|
63
|
+
|
|
64
|
+
### **Rate Limiter**
|
|
65
|
+
|
|
66
|
+
- **Token-bucket** and **sliding-window** policies.
|
|
67
|
+
- **Signal-based state**: `canExecute(key)`, `remaining(key)` return `Signal<T>`.
|
|
68
|
+
|
|
69
|
+
### **HIBP Leaked-Password Check**
|
|
70
|
+
|
|
71
|
+
- **k-anonymity**: only the first 5 hex chars of SHA-1 leave the browser.
|
|
72
|
+
- **Fail-open**: network errors never block form submissions.
|
|
73
|
+
|
|
74
|
+
### **Sensitive Clipboard**
|
|
75
|
+
|
|
76
|
+
- **Verified auto-clear**: reads back the clipboard before clearing to avoid clobbering unrelated content.
|
|
77
|
+
- **Password-manager semantics**: default 15-second clear, configurable.
|
|
78
|
+
|
|
48
79
|
### **Builder Pattern**
|
|
49
80
|
|
|
50
81
|
- **Fluent API**: Intuitively build regular expressions.
|
|
@@ -371,6 +402,172 @@ export class RegistrationComponent {
|
|
|
371
402
|
}
|
|
372
403
|
```
|
|
373
404
|
|
|
405
|
+
### **SecurityValidators (Reactive Forms)**
|
|
406
|
+
|
|
407
|
+
```typescript
|
|
408
|
+
import { FormControl, FormGroup, Validators } from '@angular/forms';
|
|
409
|
+
import { SecurityValidators } from '@angular-helpers/security/forms';
|
|
410
|
+
|
|
411
|
+
export class SignupFormComponent {
|
|
412
|
+
form = new FormGroup({
|
|
413
|
+
password: new FormControl('', [
|
|
414
|
+
Validators.required,
|
|
415
|
+
SecurityValidators.strongPassword({ minScore: 3 }),
|
|
416
|
+
]),
|
|
417
|
+
bio: new FormControl('', [SecurityValidators.safeHtml()]),
|
|
418
|
+
homepage: new FormControl('', [SecurityValidators.safeUrl({ schemes: ['https:'] })]),
|
|
419
|
+
query: new FormControl('', [
|
|
420
|
+
SecurityValidators.noScriptInjection(),
|
|
421
|
+
SecurityValidators.noSqlInjectionHints(),
|
|
422
|
+
]),
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
The validators are static factory functions — no provider registration required. They delegate to
|
|
428
|
+
shared pure helpers, so the Signal Forms variant below produces equivalent results for the same input.
|
|
429
|
+
|
|
430
|
+
### **Signal Forms validators**
|
|
431
|
+
|
|
432
|
+
```typescript
|
|
433
|
+
import { signal } from '@angular/core';
|
|
434
|
+
import { form, required } from '@angular/forms/signals';
|
|
435
|
+
import {
|
|
436
|
+
strongPassword,
|
|
437
|
+
hibpPassword,
|
|
438
|
+
safeHtml,
|
|
439
|
+
safeUrl,
|
|
440
|
+
} from '@angular-helpers/security/signal-forms';
|
|
441
|
+
|
|
442
|
+
export class SignupSignalFormsComponent {
|
|
443
|
+
model = signal({ email: '', password: '', bio: '', homepage: '' });
|
|
444
|
+
|
|
445
|
+
f = form(this.model, (p) => {
|
|
446
|
+
required(p.email);
|
|
447
|
+
required(p.password);
|
|
448
|
+
strongPassword(p.password, { minScore: 3 });
|
|
449
|
+
hibpPassword(p.password); // async — calls HIBP via validateAsync
|
|
450
|
+
safeHtml(p.bio);
|
|
451
|
+
safeUrl(p.homepage, { schemes: ['https:'] });
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
**Sub-entry requirement**: ensure `@angular/forms` is installed. The main entry has zero runtime
|
|
457
|
+
dependency on `@angular/forms`; only the sub-entries need it.
|
|
458
|
+
|
|
459
|
+
**Async HIBP rule**: `hibpPassword` requires `provideHibp()` in the injector hierarchy. The rule
|
|
460
|
+
fails open — network errors never block form submission.
|
|
461
|
+
|
|
462
|
+
### **JwtService**
|
|
463
|
+
|
|
464
|
+
```typescript
|
|
465
|
+
import { JwtService } from '@angular-helpers/security';
|
|
466
|
+
|
|
467
|
+
export class SessionGuard {
|
|
468
|
+
private jwt = inject(JwtService);
|
|
469
|
+
|
|
470
|
+
isAuthenticated(): boolean {
|
|
471
|
+
const token = localStorage.getItem('access_token');
|
|
472
|
+
if (!token) return false;
|
|
473
|
+
return !this.jwt.isExpired(token, /* leewaySeconds */ 30);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
currentUserId(): string | null {
|
|
477
|
+
const token = localStorage.getItem('access_token');
|
|
478
|
+
return token ? this.jwt.claim<string>(token, 'sub') : null;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
> **Security note**: `JwtService` decodes payloads for client-side inspection only. **Never** trust
|
|
484
|
+
> the decoded contents for authorization decisions — signature verification must happen server-side.
|
|
485
|
+
|
|
486
|
+
### **CsrfService + `withCsrfHeader()`**
|
|
487
|
+
|
|
488
|
+
```typescript
|
|
489
|
+
import { bootstrapApplication } from '@angular/platform-browser';
|
|
490
|
+
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
|
491
|
+
import { provideSecurity, CsrfService, withCsrfHeader } from '@angular-helpers/security';
|
|
492
|
+
|
|
493
|
+
bootstrapApplication(App, {
|
|
494
|
+
providers: [
|
|
495
|
+
provideSecurity({ enableCsrf: true }),
|
|
496
|
+
provideHttpClient(withInterceptors([withCsrfHeader()])),
|
|
497
|
+
],
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
// After login:
|
|
501
|
+
const csrf = inject(CsrfService);
|
|
502
|
+
csrf.storeToken(response.csrfToken);
|
|
503
|
+
// Subsequent POST/PUT/PATCH/DELETE requests automatically carry X-CSRF-Token.
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
### **RateLimiterService**
|
|
507
|
+
|
|
508
|
+
```typescript
|
|
509
|
+
import { RateLimiterService, RateLimitExceededError } from '@angular-helpers/security';
|
|
510
|
+
|
|
511
|
+
export class SearchComponent {
|
|
512
|
+
private rateLimiter = inject(RateLimiterService);
|
|
513
|
+
|
|
514
|
+
constructor() {
|
|
515
|
+
this.rateLimiter.configure('search', {
|
|
516
|
+
type: 'token-bucket',
|
|
517
|
+
capacity: 5,
|
|
518
|
+
refillPerSecond: 1,
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
canSearch = this.rateLimiter.canExecute('search'); // Signal<boolean>
|
|
523
|
+
remaining = this.rateLimiter.remaining('search'); // Signal<number>
|
|
524
|
+
|
|
525
|
+
async search(query: string) {
|
|
526
|
+
try {
|
|
527
|
+
await this.rateLimiter.consume('search');
|
|
528
|
+
return this.api.search(query);
|
|
529
|
+
} catch (err) {
|
|
530
|
+
if (err instanceof RateLimitExceededError) {
|
|
531
|
+
// Show countdown using err.retryAfterMs
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
### **HibpService**
|
|
539
|
+
|
|
540
|
+
```typescript
|
|
541
|
+
import { HibpService } from '@angular-helpers/security';
|
|
542
|
+
|
|
543
|
+
export class RegistrationComponent {
|
|
544
|
+
private hibp = inject(HibpService);
|
|
545
|
+
|
|
546
|
+
async checkPassword(password: string) {
|
|
547
|
+
const { leaked, count, error } = await this.hibp.isPasswordLeaked(password);
|
|
548
|
+
if (error) return; // fail-open on network failures
|
|
549
|
+
if (leaked) alert(`This password has appeared in ${count} data breaches.`);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
### **SensitiveClipboardService**
|
|
555
|
+
|
|
556
|
+
```typescript
|
|
557
|
+
import { SensitiveClipboardService } from '@angular-helpers/security';
|
|
558
|
+
|
|
559
|
+
export class ApiKeyPanel {
|
|
560
|
+
private sensitiveClipboard = inject(SensitiveClipboardService);
|
|
561
|
+
|
|
562
|
+
async copy(value: string) {
|
|
563
|
+
await this.sensitiveClipboard.copy(value, { clearAfterMs: 15_000 });
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
The service reads the clipboard before clearing and skips the clear if the content no longer
|
|
569
|
+
matches what was copied — so third-party copies by the user are never overwritten.
|
|
570
|
+
|
|
374
571
|
## 🔧 Advanced Configuration
|
|
375
572
|
|
|
376
573
|
### **Security Options**
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { assessPasswordStrength, isHtmlSafe, isUrlSafe, containsScriptInjection, containsSqlInjectionHints } from '@angular-helpers/security';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Collection of Reactive Forms validators that bridge the shared security helpers into
|
|
5
|
+
* the Angular `ValidatorFn` contract. All validators are static factory functions and do not
|
|
6
|
+
* require provider registration.
|
|
7
|
+
*
|
|
8
|
+
* For the Signal Forms equivalents see `@angular-helpers/security/signal-forms`.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* const form = new FormGroup({
|
|
12
|
+
* password: new FormControl('', [
|
|
13
|
+
* Validators.required,
|
|
14
|
+
* SecurityValidators.strongPassword({ minScore: 3 }),
|
|
15
|
+
* ]),
|
|
16
|
+
* bio: new FormControl('', [SecurityValidators.safeHtml()]),
|
|
17
|
+
* homepage: new FormControl('', [SecurityValidators.safeUrl({ schemes: ['https:'] })]),
|
|
18
|
+
* });
|
|
19
|
+
*/
|
|
20
|
+
class SecurityValidators {
|
|
21
|
+
/**
|
|
22
|
+
* Validates password strength using the shared entropy-based scoring logic.
|
|
23
|
+
* Returns `{ weakPassword: { score, required } }` when the score is below `minScore`.
|
|
24
|
+
*
|
|
25
|
+
* @param options.minScore Minimum acceptable score (0..4). Default: `2` (fair).
|
|
26
|
+
*/
|
|
27
|
+
static strongPassword(options = {}) {
|
|
28
|
+
const required = options.minScore ?? 2;
|
|
29
|
+
return (control) => {
|
|
30
|
+
const value = control.value;
|
|
31
|
+
if (value === null || value === undefined || value === '')
|
|
32
|
+
return null;
|
|
33
|
+
if (typeof value !== 'string')
|
|
34
|
+
return null;
|
|
35
|
+
const { score } = assessPasswordStrength(value);
|
|
36
|
+
return score < required ? { weakPassword: { score, required } } : null;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Validates that the given HTML string contains no tags or attributes outside the allowlist.
|
|
41
|
+
* Returns `{ unsafeHtml: true }` when sanitization would alter the value.
|
|
42
|
+
*
|
|
43
|
+
* Requires a browser environment (DOMParser). In SSR contexts the validator returns `null`
|
|
44
|
+
* (no error) to avoid blocking forms server-side; re-validation happens automatically on
|
|
45
|
+
* hydration.
|
|
46
|
+
*/
|
|
47
|
+
static safeHtml(options = {}) {
|
|
48
|
+
return (control) => {
|
|
49
|
+
const value = control.value;
|
|
50
|
+
if (value === null || value === undefined || value === '')
|
|
51
|
+
return null;
|
|
52
|
+
if (typeof value !== 'string')
|
|
53
|
+
return null;
|
|
54
|
+
if (typeof DOMParser === 'undefined')
|
|
55
|
+
return null;
|
|
56
|
+
return isHtmlSafe(value, options) ? null : { unsafeHtml: true };
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Validates that the given URL is well-formed and uses an allowed scheme.
|
|
61
|
+
* Returns `{ unsafeUrl: true }` for `javascript:`, `data:`, relative URLs, and other
|
|
62
|
+
* non-allowlisted protocols.
|
|
63
|
+
*/
|
|
64
|
+
static safeUrl(options = {}) {
|
|
65
|
+
const schemes = options.schemes ?? ['http:', 'https:'];
|
|
66
|
+
return (control) => {
|
|
67
|
+
const value = control.value;
|
|
68
|
+
if (value === null || value === undefined || value === '')
|
|
69
|
+
return null;
|
|
70
|
+
if (typeof value !== 'string')
|
|
71
|
+
return null;
|
|
72
|
+
return isUrlSafe(value, schemes) ? null : { unsafeUrl: true };
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Rejects values that look like script injection attempts (`<script>`, `javascript:`,
|
|
77
|
+
* or inline event handlers). Lightweight pattern check — NOT a substitute for a full
|
|
78
|
+
* HTML sanitizer.
|
|
79
|
+
*/
|
|
80
|
+
static noScriptInjection() {
|
|
81
|
+
return (control) => {
|
|
82
|
+
const value = control.value;
|
|
83
|
+
if (value === null || value === undefined || value === '')
|
|
84
|
+
return null;
|
|
85
|
+
if (typeof value !== 'string')
|
|
86
|
+
return null;
|
|
87
|
+
return containsScriptInjection(value) ? { scriptInjection: true } : null;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Heuristic check for common SQL-injection sentinel strings. Intended as defense-in-depth
|
|
92
|
+
* for user-facing inputs. Use parameterized queries on the server as the primary defense.
|
|
93
|
+
*/
|
|
94
|
+
static noSqlInjectionHints() {
|
|
95
|
+
return (control) => {
|
|
96
|
+
const value = control.value;
|
|
97
|
+
if (value === null || value === undefined || value === '')
|
|
98
|
+
return null;
|
|
99
|
+
if (typeof value !== 'string')
|
|
100
|
+
return null;
|
|
101
|
+
return containsSqlInjectionHints(value) ? { sqlInjectionHint: true } : null;
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Generated bundle index. Do not edit.
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
export { SecurityValidators };
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { inject, resource } from '@angular/core';
|
|
2
|
+
import { validate, validateAsync } from '@angular/forms/signals';
|
|
3
|
+
import { assessPasswordStrength, isHtmlSafe, isUrlSafe, containsScriptInjection, containsSqlInjectionHints, HibpService } from '@angular-helpers/security';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Registers a sync validation rule on a string field that fails when the password strength
|
|
7
|
+
* is below the required score. Uses the shared `assessPasswordStrength` helper for behavioural
|
|
8
|
+
* parity with the Reactive Forms `SecurityValidators.strongPassword`.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* form(model, (p) => {
|
|
12
|
+
* required(p.password);
|
|
13
|
+
* strongPassword(p.password, { minScore: 3 });
|
|
14
|
+
* });
|
|
15
|
+
*/
|
|
16
|
+
function strongPassword(path, options) {
|
|
17
|
+
const required = options?.minScore ?? 2;
|
|
18
|
+
const message = options?.message ?? 'Password is too weak';
|
|
19
|
+
validate(path, ({ value }) => {
|
|
20
|
+
const raw = value();
|
|
21
|
+
if (!raw)
|
|
22
|
+
return null;
|
|
23
|
+
const { score } = assessPasswordStrength(raw);
|
|
24
|
+
return score < required ? { kind: 'weakPassword', message } : null;
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Registers a sync validation rule that fails when the input contains tags or attributes
|
|
29
|
+
* outside the allowed HTML sanitizer allowlist.
|
|
30
|
+
*
|
|
31
|
+
* Requires a browser environment. In SSR contexts the rule is a no-op (returns `null`) so
|
|
32
|
+
* server-rendered forms remain submittable; re-validation happens on hydration.
|
|
33
|
+
*/
|
|
34
|
+
function safeHtml(path, options) {
|
|
35
|
+
const message = options?.message ?? 'Value contains unsafe HTML';
|
|
36
|
+
const sanitizerOptions = {
|
|
37
|
+
allowedTags: options?.allowedTags,
|
|
38
|
+
allowedAttributes: options?.allowedAttributes,
|
|
39
|
+
};
|
|
40
|
+
validate(path, ({ value }) => {
|
|
41
|
+
const raw = value();
|
|
42
|
+
if (!raw)
|
|
43
|
+
return null;
|
|
44
|
+
if (typeof DOMParser === 'undefined')
|
|
45
|
+
return null;
|
|
46
|
+
return isHtmlSafe(raw, sanitizerOptions) ? null : { kind: 'unsafeHtml', message };
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Registers a sync validation rule that fails for malformed URLs or URLs using schemes
|
|
51
|
+
* outside the allowlist (default: `http:` and `https:`).
|
|
52
|
+
*/
|
|
53
|
+
function safeUrl(path, options) {
|
|
54
|
+
const schemes = options?.schemes ?? ['http:', 'https:'];
|
|
55
|
+
const message = options?.message ?? 'URL scheme is not allowed';
|
|
56
|
+
validate(path, ({ value }) => {
|
|
57
|
+
const raw = value();
|
|
58
|
+
if (!raw)
|
|
59
|
+
return null;
|
|
60
|
+
return isUrlSafe(raw, schemes) ? null : { kind: 'unsafeUrl', message };
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Registers a sync validation rule that rejects values matching common script-injection
|
|
65
|
+
* sentinels (`<script>`, `javascript:`, inline event handlers).
|
|
66
|
+
*/
|
|
67
|
+
function noScriptInjection(path, options) {
|
|
68
|
+
const message = options?.message ?? 'Value contains script injection patterns';
|
|
69
|
+
validate(path, ({ value }) => {
|
|
70
|
+
const raw = value();
|
|
71
|
+
if (!raw)
|
|
72
|
+
return null;
|
|
73
|
+
return containsScriptInjection(raw) ? { kind: 'scriptInjection', message } : null;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Registers a sync validation rule that rejects common SQL-injection sentinel strings.
|
|
78
|
+
* Intended as defense-in-depth alongside server-side parameterized queries.
|
|
79
|
+
*/
|
|
80
|
+
function noSqlInjectionHints(path, options) {
|
|
81
|
+
const message = options?.message ?? 'Value contains SQL injection hints';
|
|
82
|
+
validate(path, ({ value }) => {
|
|
83
|
+
const raw = value();
|
|
84
|
+
if (!raw)
|
|
85
|
+
return null;
|
|
86
|
+
return containsSqlInjectionHints(raw) ? { kind: 'sqlInjectionHint', message } : null;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Registers an async validation rule that checks the password against the Have I Been Pwned
|
|
91
|
+
* breach corpus via the k-anonymity API. Requires `provideHibp()` to be set up in the
|
|
92
|
+
* injector hierarchy.
|
|
93
|
+
*
|
|
94
|
+
* Fail-open semantics: network errors and unsupported environments do NOT produce a
|
|
95
|
+
* validation error — the form remains submittable. This is intentional to prevent HIBP
|
|
96
|
+
* outages from blocking user sign-ups.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* form(model, (p) => {
|
|
100
|
+
* required(p.password);
|
|
101
|
+
* strongPassword(p.password, { minScore: 3 });
|
|
102
|
+
* hibpPassword(p.password);
|
|
103
|
+
* });
|
|
104
|
+
*/
|
|
105
|
+
function hibpPassword(path, options) {
|
|
106
|
+
const message = options?.message ?? 'This password has appeared in a data breach';
|
|
107
|
+
const debounceMs = options?.debounceMs ?? 300;
|
|
108
|
+
validateAsync(path, {
|
|
109
|
+
params: ({ value }) => {
|
|
110
|
+
const raw = value();
|
|
111
|
+
return raw && raw.length >= 8 ? raw : undefined;
|
|
112
|
+
},
|
|
113
|
+
factory: (passwordSignal) => {
|
|
114
|
+
const hibp = inject(HibpService);
|
|
115
|
+
return resource({
|
|
116
|
+
params: () => passwordSignal(),
|
|
117
|
+
loader: async ({ params: password, abortSignal }) => {
|
|
118
|
+
if (!password)
|
|
119
|
+
return undefined;
|
|
120
|
+
if (debounceMs > 0) {
|
|
121
|
+
await debounce(debounceMs, abortSignal);
|
|
122
|
+
}
|
|
123
|
+
return hibp.isPasswordLeaked(password);
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
},
|
|
127
|
+
onSuccess: (result) => {
|
|
128
|
+
if (!result)
|
|
129
|
+
return null;
|
|
130
|
+
if (result.error)
|
|
131
|
+
return null;
|
|
132
|
+
return result.leaked ? { kind: 'leakedPassword', message, count: result.count } : null;
|
|
133
|
+
},
|
|
134
|
+
onError: () => null,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
function debounce(ms, signal) {
|
|
138
|
+
return new Promise((resolve, reject) => {
|
|
139
|
+
if (signal.aborted) {
|
|
140
|
+
reject(signal.reason);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const timer = setTimeout(() => {
|
|
144
|
+
signal.removeEventListener('abort', onAbort);
|
|
145
|
+
resolve();
|
|
146
|
+
}, ms);
|
|
147
|
+
const onAbort = () => {
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
reject(signal.reason);
|
|
150
|
+
};
|
|
151
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Generated bundle index. Do not edit.
|
|
157
|
+
*/
|
|
158
|
+
|
|
159
|
+
export { hibpPassword, noScriptInjection, noSqlInjectionHints, safeHtml, safeUrl, strongPassword };
|