Tasks
Ecosistema completo para organización y gestión de contenido con interfaces espaciales
Security Library - Implementation Tasks
Sprint: Security Improvements Epic: Security Library Compliance Start Date: 2025-09-29
Phase 1: Critical Fixes (Week 1)
Task 1.1: Remove Timer-Based Auto-Refresh 🔴
Priority: Critical
Estimate: 8 hours
Assignee: TBD
Files: libs/core/security/src/lib/auth/token.service.ts
Description
Replace polling-based token refresh (timer every 30s) with event-driven refresh based on actual token expiration time.
Acceptance Criteria
- Remove
timer(0, 30000)fromsetupAutoRefresh()method - Implement event-driven refresh using token expiration calculation
- Calculate exact refresh time at 80% of token lifetime
- Use
timer(delayMs)for single scheduled refresh, not polling - Implement
repeat()operator to restart cycle after each refresh - No
setTimeoutorsetIntervalin codebase (verify with grep)
Definition of Done (DoD)
- Code changes implemented and reviewed
- No timer/setTimeout usage in TokenService
- Token refreshes at calculated time (not polling)
- Unit tests pass for token refresh scenarios
- Integration test validates refresh timing
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Verify no timer polling
grep -r "timer.*30000" libs/core/security/src/
# Should return: no matches
# Verify no setTimeout
grep -r "setTimeout\|setInterval" libs/core/security/src/ --exclude="*.spec.ts"
# Should return: no matches (tests are allowed)
# Run tests
npx nx test security
# Should pass: all tests green
Implementation Notes
- Use
getJWTTimeToExpiry()from jwt.utils - Refresh at 80% of token lifetime (configurable)
- Handle edge cases: expired tokens, missing tokens
- Use
distinctUntilChanged()to avoid duplicate refreshes - Log refresh events with LoggerService
Task 1.2: Replace Console Logging with LoggerService 🔴
Priority: Critical Estimate: 6 hours Assignee: TBD Files:
libs/core/security/src/lib/auth/token.service.tslibs/core/security/src/lib/auth/auth.service.ts
Description
Replace all console.error, console.log, console.warn with LoggerService from @libs-core/log-system.
Acceptance Criteria
- Inject LoggerService in TokenService
- Inject LoggerService in AuthService
- Replace all 13 console.* calls with appropriate log methods
- Use appropriate log levels (debug, info, warn, error)
- Include operation context in all log calls
- Add tenantId and correlationId where applicable
- No console.* usage in production code (grep verification)
Definition of Done (DoD)
- LoggerService injected in all affected services
- All console.* calls replaced with logger.* calls
- Log messages include structured context objects
- Appropriate log levels used (trace/debug/info/warn/error/critical)
- Multi-tenant context included (tenantId, correlationId)
- Unit tests updated to mock LoggerService
- No console.* in codebase except tests
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Verify no console usage in production code
grep -r "console\." libs/core/security/src/lib/ --exclude-dir=__tests__ --exclude="*.spec.ts"
# Should return: no matches
# Verify LoggerService injection
grep -r "private.*logger.*=.*inject(LoggerService)" libs/core/security/src/lib/auth/
# Should return: matches in token.service.ts and auth.service.ts
# Run tests
npx nx test security
# Should pass: all tests green
Log Level Guidelines
trace: Fine-grained debugging (token validation steps)debug: General debugging (initialization, state changes)info: Important business events (login, logout, context switch)warn: Recoverable errors (token near expiry, retry attempts)error: Error conditions (authentication failure, invalid token)critical: System failures (security breaches, service unavailable)
Example Replacements
// ❌ Before
console.error('Error inicializando tokens:', error);
// ✅ After
this.logger.error('Token initialization failed', {
error,
operation: 'token_initialization',
tenantId: this.contextService.getCurrentTenantId(),
correlationId: this.sessionService.getCorrelationId(),
recoverable: true
});
Task 1.3: Convert Crypto Utils to RxJS Observables 🔴
Priority: Critical
Estimate: 4 hours
Assignee: TBD
Files: libs/core/security/src/lib/utils/crypto.utils.ts
Description
Convert async/await Promise-based functions to Observable-based API to comply with "Always use rxJS, never use promises" rule.
Acceptance Criteria
- Convert
encryptForStorageto returnObservable<{...}> - Convert
decryptFromStorageto returnObservable<string> - Use
from()operator to wrap async operations - Remove
asynckeyword from function signatures - Remove
awaitkeywords from implementations - Update return types from Promise to Observable
- No Promise usage in crypto.utils (grep verification)
Definition of Done (DoD)
- Functions return Observables instead of Promises
- Implementation uses
from()for async operations - All async/await removed from crypto.utils
- Unit tests updated to test Observables
- Tests use
.subscribe()orfirstValueFrom()pattern - No Promise types in function signatures
- Code linted with no errors
- All tests passing
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Verify no Promise usage
grep -r "Promise<\|async function\|async (" libs/core/security/src/lib/utils/crypto.utils.ts
# Should return: no matches
# Verify Observable usage
grep -r "Observable<" libs/core/security/src/lib/utils/crypto.utils.ts
# Should return: matches for encryptForStorage and decryptFromStorage
# Run tests
npx nx test security --testNamePattern="CryptoUtils"
# Should pass: all crypto utils tests green
Implementation Example
// ❌ Before
export async function encryptForStorage(
data: string,
password: string
): Promise<{ encrypted: string; salt: string; iv: string }> {
const encoder = new TextEncoder();
const salt = generateRandomBytes(16);
// ... more async code
return { encrypted, salt, iv };
}
// ✅ After
export function encryptForStorage(
data: string,
password: string
): Observable<{ encrypted: string; salt: string; iv: string }> {
return new Observable(observer => {
const encoder = new TextEncoder();
const salt = generateRandomBytes(16);
performEncryption(data, password, salt)
.then(result => {
observer.next(result);
observer.complete();
})
.catch(error => observer.error(error));
});
}
// Or simpler with from()
export function encryptForStorage(
data: string,
password: string
): Observable<{ encrypted: string; salt: string; iv: string }> {
return from(performEncryptionAsync(data, password));
}
Task 1.4: Fix CSRFTokenService Test Failures 🔴
Priority: Critical Estimate: 3 hours Assignee: TBD Files:
libs/core/security/src/lib/interceptors/csrf.interceptor.tslibs/core/security/src/lib/interceptors/csrf.interceptor.spec.ts
Description
Fix 3 failing tests related to LoggerService injection in CSRFTokenService test suite.
Failing Tests
CSRFTokenService > token management > should get token for specific tenantCSRFTokenService > token management > should clear all tokensCSRFTokenService > token management > should clear token for specific tenant
Error Message
NG0203: The `LoggerService2` token injection failed.
inject() function must be called from an injection context
Acceptance Criteria
- TestBed properly provides LoggerService mock
- All service instantiations use
runInInjectionContext - LoggerService mock properly configured
- All 3 failing tests now pass
- No new test failures introduced
- Test coverage maintained or improved
Definition of Done (DoD)
- All CSRFTokenService tests passing
- LoggerService properly mocked in tests
- No NG0203 injection errors
- Test suite runs clean (no warnings)
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Run specific test suite
npx nx test security --testNamePattern="CSRFTokenService"
# Should pass: all tests green, no NG0203 errors
# Run full test suite
npx nx test security
# Should pass: all tests green
Implementation Notes
// ✅ Proper TestBed setup
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
CSRFTokenService,
{
provide: LoggerService,
useValue: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn()
}
},
{
provide: ContextService,
useValue: mockContextService
}
]
});
});
// ✅ Proper service instantiation in tests
it('should get token for specific tenant', () => {
TestBed.runInInjectionContext(() => {
const service = TestBed.inject(CSRFTokenService);
const token = service.getToken('tenant-123');
expect(token).toBeDefined();
});
});
Task 1.5: Full Test Suite Validation 🔴
Priority: Critical
Estimate: 2 hours
Assignee: TBD
Files: All test files in libs/core/security/
Description
Run complete test suite and ensure 100% pass rate after all Phase 1 fixes.
Acceptance Criteria
- All unit tests pass (100%)
- No test warnings or errors
- Test coverage >= 85%
- No skipped tests (
.skiporxit) - No console output from tests (except intentional)
- CI/CD pipeline passes
Definition of Done (DoD)
-
npx nx test securitypasses with 0 failures - Test coverage report generated
- Coverage >= 85% for all files
- No test warnings in output
- Lint passes:
npx nx lint security - Build passes:
npx nx build security - Documentation updated if needed
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Run all tests
npx nx test security
# Expected: ✅ All tests passing
# Check test coverage
npx nx test security --coverage
# Expected: >= 85% coverage
# Lint check
npx nx lint security
# Expected: ✅ No errors
# Build check
npx nx build security
# Expected: ✅ Build successful
Success Metrics
Test Suites: X passed, X total
Tests: Y passed, Y total
Coverage: >= 85%
Duration: < 3 minutes
Phase 2: High Priority Improvements (Week 2)
Task 2.1: Migrate Directives to Signal Inputs/Outputs 🟡
Priority: High
Estimate: 12 hours
Assignee: TBD
Files: All files in libs/core/security/src/lib/directives/
Description
Migrate all 8 directives from decorator-based @Input()/@Output() to Angular 20 signal-based input()/output().
Affected Directives
has-permission.directive.tshas-any-permission.directive.tshas-all-permissions.directive.tshas-role.directive.tshas-any-role.directive.tshas-minimum-role.directive.tsis-admin.directive.tssecure-content.directive.ts
Acceptance Criteria
- All
@Input()replaced withinput()orinput.required() - All
@Output()replaced withoutput() - Use
computed()for derived reactive state - Add
ChangeDetectionStrategy.OnPushto all directives - Update templates using these directives (if any)
- All directive tests updated and passing
- No decorator-based inputs/outputs remain
Definition of Done (DoD)
- All 8 directives use signal inputs/outputs
- Computed signals used for reactive logic
- OnPush change detection on all directives
- All directive tests passing
- No
@Input()or@Output()in directives (grep check) - Example usage documented
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Verify no decorator inputs/outputs in directives
grep -r "@Input()\|@Output()" libs/core/security/src/lib/directives/
# Should return: no matches
# Verify signal usage
grep -r "input()\|input\.required()\|output()" libs/core/security/src/lib/directives/
# Should return: matches in all directive files
# Verify OnPush
grep -r "ChangeDetectionStrategy.OnPush" libs/core/security/src/lib/directives/
# Should return: matches in all directive files
# Run tests
npx nx test security --testNamePattern="Directive"
# Should pass: all directive tests green
Migration Pattern
// ❌ Before
@Directive({
selector: '[hasPermission]',
standalone: true
})
export class HasPermissionDirective {
@Input() permission!: string;
@Input() strict = false;
@Output() accessDenied = new EventEmitter<void>();
constructor(
private authService: AuthService,
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
ngOnInit() {
if (this.authService.hasPermission(this.permission)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
this.accessDenied.emit();
}
}
}
// ✅ After
@Directive({
selector: '[hasPermission]',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HasPermissionDirective {
// Signal inputs
permission = input.required<string>();
strict = input(false);
// Signal output
accessDenied = output<void>();
// Services
private authService = inject(AuthService);
private templateRef = inject(TemplateRef<any>);
private viewContainer = inject(ViewContainerRef);
// Computed signal for access check
hasAccess = computed(() =>
this.authService.hasPermission(this.permission())
);
constructor() {
// Effect to react to access changes
effect(() => {
if (this.hasAccess()) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
this.accessDenied.emit();
}
});
}
}
Task 2.2: Add Performance Monitoring Decorators 🟡
Priority: High Estimate: 4 hours Assignee: TBD Files:
libs/core/security/src/lib/auth/auth.service.tslibs/core/security/src/lib/auth/token.service.ts
Description
Add @performance decorators from @libs-core/log-system to critical authentication methods.
Target Methods
AuthService:
login()logout()refreshAuthentication()selectContext()switchContext()
TokenService:
refreshAccessToken()setAccessToken()storeTokens()
Acceptance Criteria
- Import
@performancedecorator from log-system - Add decorator to all critical methods
- Set appropriate threshold values (50-200ms)
- Configure warning level for slow operations
- Verify performance logs are generated
- Test performance monitoring in dev environment
Definition of Done (DoD)
- All critical methods have @performance decorator
- Thresholds configured appropriately
- Performance logs appear in console/logs
- No performance regression introduced
- Tests still passing after decorator addition
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Verify @performance usage
grep -r "@performance" libs/core/security/src/lib/auth/
# Should return: matches for all target methods
# Run tests
npx nx test security
# Should pass: all tests green
# Manual test: Check logs for performance metrics
# Start dev server and perform login
# Expected: See performance logs like "login completed in 145ms"
Implementation Example
import { performance } from '@libs-core/log-system';
@Injectable({ providedIn: 'root' })
export class AuthService {
@performance({ threshold: 200, level: 'warn' })
login(credentials: LoginCredentials): Observable<LoginResult> {
// ... implementation
}
@performance({ threshold: 100, level: 'warn' })
logout(redirectToLogin = true): Observable<void> {
// ... implementation
}
@performance({ threshold: 150, level: 'warn' })
refreshAuthentication(): Observable<void> {
// ... implementation
}
@performance({ threshold: 100 })
selectContext(tenantId: string): Observable<void> {
// ... implementation
}
@performance({ threshold: 100 })
switchContext(tenantId: string): Observable<void> {
// ... implementation
}
}
Performance Thresholds
- Login: 200ms (network-dependent)
- Logout: 100ms (mostly local)
- Refresh: 150ms (network-dependent)
- Context operations: 100ms (network-dependent)
- Token operations: 50ms (local crypto operations)
Task 2.3: Enhance Error Handling 🟡
Priority: High Estimate: 8 hours Assignee: TBD Files:
libs/core/security/src/lib/auth/auth.service.tslibs/core/security/src/lib/auth/token.service.tslibs/core/security/src/lib/models/(new error classes)
Description
Implement structured error handling with custom error classes and rich context.
Acceptance Criteria
- Create custom error classes for security domain
- Replace generic errors with domain-specific errors
- Add error context (operation, tenantId, correlationId)
- Implement error recovery strategies
- Add
recoverableflag to errors - Log all errors with full context
- Update error handling in catch blocks
Custom Error Classes to Create
- SecurityError (base class)
- AuthenticationError
- InvalidCredentialsError
- TokenExpiredError
- TokenInvalidError
- AuthorizationError
- InsufficientPermissionsError
- TenantAccessDeniedError
- TokenError
- TokenRefreshError
- TokenStorageError
- ContextError
- ContextSelectionError
- ContextSwitchError
Definition of Done (DoD)
- All custom error classes created with proper inheritance
- Error classes include context properties
- All generic errors replaced with domain errors
- Error recovery strategies implemented
- All errors logged with LoggerService
- Tests for error scenarios passing
- Error types exported from index.ts
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Verify error classes exist
ls libs/core/security/src/lib/models/errors/
# Should show: security.errors.ts
# Verify error usage
grep -r "throw new.*Error" libs/core/security/src/lib/auth/
# Should show: domain-specific errors
# Run tests
npx nx test security
# Should pass: all tests including error scenarios
Implementation Example
// ❌ Before
catch (error) {
console.error('Error inicializando tokens:', error);
return this.clearTokens();
}
// ✅ After
catch (error) {
const tokenError = new TokenInitializationError(
'Failed to initialize authentication tokens',
{
cause: error,
operation: 'token_initialization',
tenantId: this.contextService.getCurrentTenantId(),
correlationId: this.sessionService.getCorrelationId(),
recoverable: true
}
);
this.logger.error('Token initialization failed', {
error: tokenError,
operation: 'token_initialization',
tenantId: tokenError.context.tenantId,
correlationId: tokenError.context.correlationId,
recoverable: tokenError.context.recoverable
});
return this.clearTokens().pipe(
catchError(() => throwError(() => tokenError))
);
}
Task 2.4: Add Correlation IDs to All Operations 🟡
Priority: High Estimate: 6 hours Assignee: TBD Files:
libs/core/security/src/lib/auth/auth.service.tslibs/core/security/src/lib/auth/session.service.ts
Description
Ensure all security operations include correlation IDs for distributed tracing and debugging.
Acceptance Criteria
- Generate correlation ID for each operation
- Pass correlation ID through entire operation flow
- Include correlation ID in all log statements
- Include correlation ID in HTTP headers (if applicable)
- Include correlation ID in event emissions
- Store correlation ID in session context
- Format:
{operation}-{userId}-{timestamp}
Definition of Done (DoD)
- All operations generate correlation IDs
- Correlation IDs flow through operation chain
- All logs include correlationId field
- SessionService provides correlation ID accessor
- Events include correlation ID in metadata
- Tests verify correlation ID propagation
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Verify correlation ID generation
grep -r "correlationId.*=.*Date.now()" libs/core/security/src/lib/auth/
# Should return: multiple matches
# Verify correlation ID in logs
grep -r "correlationId:" libs/core/security/src/lib/auth/
# Should return: many matches in log calls
# Run tests
npx nx test security
# Should pass: all tests including correlation ID tests
Implementation Example
login(credentials: LoginCredentials): Observable<LoginResult> {
const correlationId = `login-${credentials.username}-${Date.now()}`;
this.logger.info('Login attempt started', {
operation: 'login',
correlationId,
username: credentials.username
});
return generateDeviceFingerprint().pipe(
switchMap((deviceFingerprint) => {
this.logger.debug('Device fingerprint generated', {
operation: 'login',
correlationId
});
return this.httpClient.post<LoginResult>(
this.config.loginEndpoint,
{ ...credentials, deviceFingerprint },
{ headers: { 'X-Correlation-ID': correlationId } }
);
}),
tap(result => {
this.logger.info('Login successful', {
operation: 'login',
correlationId,
userId: result.user.id
});
}),
catchError(error => {
this.logger.error('Login failed', {
operation: 'login',
correlationId,
error
});
return throwError(() => error);
})
);
}
Phase 3: Architecture Improvements (Week 3)
Task 3.1: Evaluate AuthService Split (SRP Analysis) 🟠
Priority: Medium
Estimate: 4 hours
Assignee: TBD
Files: libs/core/security/src/lib/auth/auth.service.ts
Description
Analyze AuthService (883 lines) to determine if it violates Single Responsibility Principle and should be split into smaller services.
Analysis Areas
- Authentication Operations (login, logout, refresh)
- Authorization Operations (hasPermission, hasRole, etc.)
- Context Management (selectContext, switchContext)
- Session Management (initialization, monitoring)
- Event Management (authentication events)
Acceptance Criteria
- Document current responsibilities
- Identify violation of SRP
- Propose service split architecture
- Create ADR (Architecture Decision Record)
- Estimate refactoring effort
- Identify breaking changes
- Plan migration strategy
Definition of Done (DoD)
- Analysis document created
- ADR written and reviewed
- Service split proposal documented
- Breaking changes identified
- Migration plan created
- Team reviewed and approved proposal
- Go/No-Go decision made
- Document stored in
docs/libs/security/adr/
Deliverables
- Analysis Document:
docs/libs/security/adr/001-auth-service-split-analysis.md - Proposed Architecture Diagram
- Migration Plan (if split approved)
- Breaking Changes List
Decision Criteria
- Does split improve maintainability?
- Does split improve testability?
- Is effort justified by benefits?
- Can migration be non-breaking?
Task 3.2: Implement Service Split (If Approved) 🟠
Priority: Medium (Conditional on Task 3.1) Estimate: 16 hours Assignee: TBD Files: Multiple new service files
Description
If Task 3.1 approves split, implement the new service architecture.
Proposed New Services
- AuthenticationService: Login, logout, token operations
- AuthorizationService: Permission and role checks
- TenantContextService: Context selection and switching
- AuthStateService: State management and events
Acceptance Criteria
- Create new service files
- Move functionality from AuthService
- Update dependency injection
- Maintain backwards compatibility (facade pattern)
- Update all imports across codebase
- Update tests for new services
- Update documentation
Definition of Done (DoD)
- All new services created and tested
- Original AuthService deprecated (or facade)
- All tests passing
- No breaking changes (or migration guide provided)
- Documentation updated
- Code linted with no errors
- PR approved by 2+ reviewers
- Merged to main branch
Validation Commands
# Verify new services exist
ls libs/core/security/src/lib/auth/
# Should show: authentication.service.ts, authorization.service.ts, etc.
# Run all tests
npx nx test security
# Should pass: all tests green
# Verify no breaking changes
npx nx build security
# Should build successfully
Task 3.3: Add Integration Tests for Auth Flows 🟠
Priority: Medium
Estimate: 12 hours
Assignee: TBD
Files: libs/core/security/__tests__/integration/
Description
Create comprehensive integration tests for complex authentication flows.
Test Scenarios
Complete Login Flow
- Login → Context Selection → Dashboard
- Multi-tenant user with multiple contexts
Token Refresh Flow
- Token near expiry → Auto-refresh → Continue operation
Context Switching Flow
- User switches tenant → New tokens → Updated permissions
Session Timeout Flow
- User inactive → Warning → Auto-logout
Error Recovery Flow
- Network error → Retry → Success
- Invalid token → Refresh → Recover
Acceptance Criteria
- 5+ integration test suites created
- Tests cover happy path and error scenarios
- Tests use real HTTP mocks (not unit mocks)
- Tests validate state transitions
- Tests verify event emissions
- Tests check side effects (storage, logs)
- All integration tests passing
Definition of Done (DoD)
- Integration test directory created
- 5+ comprehensive test suites implemented
- Tests cover >80% of integration scenarios
- All tests passing consistently
- Tests documented with scenarios
- Tests run in CI/CD pipeline
- Code linted with no errors
- PR approved by 1+ reviewer
- Merged to main branch
Validation Commands
# Run integration tests
npx nx test security --testPathPattern="integration"
# Should pass: all integration tests green
# Check coverage
npx nx test security --coverage
# Should show: >80% coverage for auth flows
Phase 4: Documentation & Polish (Week 4)
Task 4.1: Complete API Documentation 🟢
Priority: Low Estimate: 8 hours Assignee: TBD Files: All service and utility files
Description
Add comprehensive JSDoc comments to all public APIs.
Acceptance Criteria
- All public methods documented
- All public interfaces documented
- Include @param descriptions
- Include @returns descriptions
- Include @throws descriptions
- Include @example usage
- Include @see cross-references
Definition of Done (DoD)
- 100% public API documented
- JSDoc format validated
- Examples compile and work
- No broken @see references
- Documentation generated successfully
- PR approved by 1+ reviewer
- Merged to main branch
Task 4.2: Create Usage Examples 🟢
Priority: Low
Estimate: 6 hours
Assignee: TBD
Files: docs/libs/security/examples/
Description
Create practical code examples for common use cases.
Examples to Create
- Basic authentication setup
- Protected route with guard
- Permission-based UI (directives)
- Multi-tenant context switching
- Custom authorization logic
- Error handling patterns
- Testing authentication
Definition of Done (DoD)
- 7+ example files created
- All examples compile
- All examples tested
- Examples include explanations
- Examples follow best practices
- PR approved by 1+ reviewer
- Merged to main branch
Task 4.3: Migration Guide (If Breaking Changes) 🟢
Priority: Low (Conditional)
Estimate: 4 hours
Assignee: TBD
Files: docs/libs/security/MIGRATION.md
Description
Create migration guide if Phase 1-3 introduced breaking changes.
Acceptance Criteria
- Document all breaking changes
- Provide before/after examples
- Explain rationale for changes
- Provide automated migration scripts (if possible)
- Include deprecation timeline
- Test migration guide with sample code
Definition of Done (DoD)
- Migration guide created
- All breaking changes documented
- Migration tested on sample project
- Team reviewed guide
- PR approved by 1+ reviewer
- Merged to main branch
Task 4.4: Final Cleanup & Code Review 🟢
Priority: Low
Estimate: 4 hours
Assignee: TBD
Files: All files in libs/core/security/
Description
Final code review and cleanup before marking improvements complete.
Acceptance Criteria
- Remove all commented code
- Remove all TODO comments (or create issues)
- Verify consistent formatting
- Verify naming conventions
- Remove unused imports
- Remove unused variables
- All linting rules passing
Definition of Done (DoD)
- No commented code blocks
- No TODO/FIXME comments
- Code formatted consistently
- No unused imports
- All lint rules passing
- Final test suite 100% passing
- Documentation complete
- PR approved by 2+ reviewers
- Merged to main branch
Summary Checklist
Phase 1 (Week 1) - Critical Fixes
- Task 1.1: Remove timer-based auto-refresh
- Task 1.2: Replace console with LoggerService
- Task 1.3: Convert crypto utils to RxJS
- Task 1.4: Fix CSRF test failures
- Task 1.5: Full test suite validation
Phase 2 (Week 2) - High Priority
- Task 2.1: Migrate to signal inputs/outputs
- Task 2.2: Add performance decorators
- Task 2.3: Enhance error handling
- Task 2.4: Add correlation IDs
Phase 3 (Week 3) - Architecture
- Task 3.1: Evaluate AuthService split
- Task 3.2: Implement split (if approved)
- Task 3.3: Add integration tests
Phase 4 (Week 4) - Documentation
- Task 4.1: Complete API documentation
- Task 4.2: Create usage examples
- Task 4.3: Migration guide (if needed)
- Task 4.4: Final cleanup & review
Success Criteria
Code Quality Metrics
- 0 timer/setTimeout usage
- 0 console.* usage in production code
- 100% Observable usage (no Promises)
- Test coverage >= 90%
- All tests passing
- 0 lint errors
- 0 TypeScript
anytypes
Architecture Metrics
- Services follow SOLID principles
- Clear separation of concerns
- Proper error handling
- Performance monitoring active
Documentation Metrics
- 100% public API documented
- 7+ usage examples
- Migration guide (if needed)
- ADRs for major decisions
Document Version: 1.0 Last Updated: 2025-09-29 Next Review: End of each phase