# Phase 3 - Token Security Layer

Status: implemented (foundation)  
Date: 2026-02-25

## What is implemented

- New security module: `src/security/tokenSecurity.ts`
  - `encryptToken(...)` / `decryptToken(...)` using AES-256-GCM
  - envelope format: `v1.keyId.iv.cipher.tag` (base64url segments)
  - key parsing support:
    - 32-byte utf8
    - 64-char hex (or `hex:...`)
    - base64 (or `base64:...`)
  - `maskToken(...)` helper for UI display
  - `redactTokenLikeText(...)` and `redactSensitiveObject(...)` for log/response hygiene

- Runtime config fields added:
  - `TOKEN_ENCRYPTION_KEY`
  - `TOKEN_ENCRYPTION_KEY_ID` (default `k1`)

- Redaction integrated in API error paths:
  - `POST /live/accounts`
  - `POST /live/dashboard`
  - token-like strings in error text are redacted before log/response

## Security properties

- Tokens intended for DB storage are encrypted at rest (when Phase 4 profile service uses this layer).
- Raw token is never required in read APIs once profile storage is wired.
- Error messages avoid leaking token query values (`access_token=...`) and Graph token-like strings.

## Tests

- `tests/token-security.test.ts`
  - encrypt/decrypt round-trip
  - key parsing variants
  - masking + text redaction
  - nested object sensitive field redaction

## Notes for next phase

- Phase 4 should use `encryptToken` before insert into `auth_user_api_sources.access_token_enc`.
- Phase 4 should use `decryptToken` only at execution boundary when calling Graph API.
- Enforce startup policy for missing `TOKEN_ENCRYPTION_KEY` when profile-token feature is enabled.

