The Four Phases
You MUST complete each phase before proceeding to the next.
Phase 1: Authentication Architecture (The Handshake)
BEFORE writing a single line of auth code:
Select the Flow
- Mobile/SPA: MUST use Authorization Code Flow with PKCE (Proof Key for Code Exchange).
- Backend: Authorization Code Flow.
- Implicit Flow: FORBIDDEN. Never use it. It returns tokens in the URL.
- Device Flow: Only for input-constrained devices (TVs/IoT).
Scope Strategy (Least Privilege)
- Define exactly which permissions are needed from YouTube (
youtube.readonly) vs Twitch (chat:read).
- Incremental Auth: Do not ask for all scopes at signup. Ask for
youtube.upload only when the user actually clicks "Upload."
- Justification: Be ready to explain to the user why you need this access.
The "No-Credential" Rule
- Principle: We never see, touch, or store the user's password.
- Identity Provider (IdP): Delegate login to the provider (Google/Twitch).
- Redirect URIs: strict allow-listing. No wildcards (
*).
Phase 2: Token Management & Storage (The Vault)
Protecting the delegated access:
Storage Hierarchy
- Passwords: NEVER STORED.
- Client Secrets: NEVER in frontend code (Mobile/React). Backend/BFF (Backend for Frontend) only.
- Access Tokens (Short-lived): Keep in memory (frontend) or
HttpOnly Secure Cookies. Never localStorage.
- Refresh Tokens (Long-lived): Encrypt at Rest (AES-256 or Cloud KMS) in the database. Never plaintext.
Token Rotation Strategy
- Detect reused tokens. If a Refresh Token is used twice, revoke the entire chain (Rotation Policy).
- Handle
invalid_grant errors gracefully (prompt user to re-login).
- Revocation: If the user deletes their account, call the provider's
revoke endpoint immediately.
State & Nonce Validation
- CSRF Protection: Always send a unique, random
state parameter during the auth request.
- Verify the
state matches upon return.
- Use
nonce (OIDC) to prevent Replay Attacks.
Phase 3: Multi-Provider Mesh (The Integration)
Managing the Identity Map:
Account Linking Logic
- Primary Identity: The user logs in with "Main Account" (e.g., Gmail).
- Connected Accounts: User connects Twitch as a secondary resource.
- The Map:
User(ID: 123) -> LinkedAccount(Provider: Twitch, Token: ***) + LinkedAccount(Provider: YouTube, Token: ***).
- Rule: Never merge accounts automatically based on email match (Security risk). Require explicit linking verification.
The "Refresh Loop" Middleware
- Pattern: Before calling the Twitch API, check Access Token expiration.
- Expired? Use the Encrypted Refresh Token to get a new Access Token transparently.
- Failed? (User revoked access externally). Pause the integration and notify the user: "Please reconnect Twitch."
- Concurrency: Handle race conditions if multiple requests try to refresh the token simultaneously.
Rate Limit Isolation
- YouTube and Twitch have different API quotas.
- Track usage per provider. Don't let a Twitch outage crash the YouTube integration.
Phase 4: Threat Modeling & Compliance (The Guard)
Assuming breach:
Dependency Scanning
- Audit auth libraries (e.g.,
passport, next-auth) for vulnerabilities weekly.
- Supply Chain: Pin versions. Authentication logic is a high-value target for hackers.
Anomaly Detection
- Log auth failures. "User 123 failed Twitch refresh 50 times in 1 minute." -> Alert.
- Monitor for "Token Export" attempts (large volume of token reads).
- Audit Logs: Log who linked what and when. (Immutable logs).
Penetration Testing (Self)
- Try to swap the
code parameter from one user to another.
- Try to manipulate the
redirect_uri to send the token to evil.com.
- Try to bypass the
state check.
Red Flags - STOP and Follow Process
If you catch yourself thinking:
- "I'll store the Access Token in LocalStorage so it persists." (XSS Vulnerability).
- "I'll just ask for
scope: all just in case we need it later." (Privacy violation).
- "I'll use the same
state string for everyone." (CSRF Vulnerability).
- "I'll hardcode the Client Secret in the React app." (Secret Leak).
- "I'll decrypt the token, use it, and leave it in the logs." (Data Leak).
- "If the refresh fails, I'll just crash the app." (Bad UX).
- "I'll merge these two accounts because they have the same email." (Account Takeover Risk).
ALL of these mean: STOP. Return to Phase 1.
Your Human Partner's Signals You're Doing It Wrong
Watch for these complaints:
- User: "Why is it asking to read my emails? I just wanted to share a video." (Bad Scoping).
- Dev: "The token expired and the background job failed." (Missing Refresh Loop).
- Sec: "I found your Twitch Client Secret on GitHub." (Failed Secret Management).
- User: "I revoked the app in Google Settings, but your app still says connected." (Missing Error Handling).
- Dev: "I can't reproduce this login bug." (Missing Audit Logs).
When you see these: STOP. Audit the Auth Flow.
Common Rationalizations
| Excuse |
Reality |
| "Implicit Flow is easier" |
It is insecure and deprecated by IETF. Use PKCE. |
| "Encryption slows down the DB" |
Leaking tokens shuts down the company. |
| "I'll handle token rotation later" |
You will be blocked by the API provider quickly. |
| "HTTPS protects the token in URL" |
Browser history and server logs still see it. |
| "We trust our database admin" |
Defense in Depth. Even admins shouldn't see plaintext tokens. |
Quick Reference
| Phase |
Key Activities |
Success Criteria |
| 1. Architecture |
PKCE, Scopes, Redirects |
Secure flow defined |
| 2. Storage |
Encryption, HTTPOnly Cookies |
No secrets in frontend/logs |
| 3. Integration |
Refresh Loops, Linking |
Seamless multi-API calls |
| 4. Defense |
CSRF, Audit Logs, Scanning |
Resilient to attacks |
When The Provider Changes The Rules
If Google or Twitch changes their auth policies (e.g., "OOB flow deprecation"):
- Subscribe to Security News: (Google Identity Blog, Twitch Developers).
- Deprecation is a P0: Drop everything and migrate. Auth breakage means 0 users.
- Graceful Degrade: If an API feature is removed, disable that specific button, don't crash the whole login.
Supporting Techniques
superpowers:oauth-debugging - Using tools like jwt.io and OIDC Debugger.
superpowers:threat-modeling - STRIDE model for identity flows.
superpowers:encryption-at-rest - Using AWS KMS / Vault for token storage.
Real-World Impact
- "Naive" implementation: Storing tokens in local storage -> XSS attack -> Attacker drains user's bank/Twitch bits.
- "Secure" implementation: Tokens are encrypted cookies -> XSS attack fails to steal identity -> User is safe, Platform is trusted.
1---2name: security-architect3description: Security Architect Skill4---5## The Four Phases67You MUST complete each phase before proceeding to the next.89### Phase 1: Authentication Architecture (The Handshake)1011**BEFORE writing a single line of auth code:**12131. **Select the Flow**14 - **Mobile/SPA:** MUST use **Authorization Code Flow with PKCE** (Proof Key for Code Exchange).15 - **Backend:** Authorization Code Flow.16 - **Implicit Flow:** **FORBIDDEN.** Never use it. It returns tokens in the URL.17 - **Device Flow:** Only for input-constrained devices (TVs/IoT).18192. **Scope Strategy (Least Privilege)**20 - Define exactly which permissions are needed from YouTube (`youtube.readonly`) vs Twitch (`chat:read`).21 - **Incremental Auth:** Do not ask for all scopes at signup. Ask for `youtube.upload` only when the user actually clicks "Upload."22 - **Justification:** Be ready to explain to the user *why* you need this access.23243. **The "No-Credential" Rule**25 - **Principle:** We never see, touch, or store the user's password.26 - **Identity Provider (IdP):** Delegate login to the provider (Google/Twitch).27 - **Redirect URIs:** strict allow-listing. No wildcards (`*`).2829### Phase 2: Token Management & Storage (The Vault)3031**Protecting the delegated access:**32331. **Storage Hierarchy**34 - **Passwords:** NEVER STORED.35 - **Client Secrets:** NEVER in frontend code (Mobile/React). Backend/BFF (Backend for Frontend) only.36 - **Access Tokens (Short-lived):** Keep in memory (frontend) or `HttpOnly` Secure Cookies. Never `localStorage`.37 - **Refresh Tokens (Long-lived):** Encrypt at Rest (AES-256 or Cloud KMS) in the database. Never plaintext.38392. **Token Rotation Strategy**40 - Detect reused tokens. If a Refresh Token is used twice, revoke the entire chain (Rotation Policy).41 - Handle `invalid_grant` errors gracefully (prompt user to re-login).42 - **Revocation:** If the user deletes their account, call the provider's `revoke` endpoint immediately.43443. **State & Nonce Validation**45 - **CSRF Protection:** Always send a unique, random `state` parameter during the auth request.46 - Verify the `state` matches upon return.47 - Use `nonce` (OIDC) to prevent Replay Attacks.4849### Phase 3: Multi-Provider Mesh (The Integration)5051**Managing the Identity Map:**52531. **Account Linking Logic**54 - **Primary Identity:** The user logs in with "Main Account" (e.g., Gmail).55 - **Connected Accounts:** User connects Twitch as a *secondary* resource.56 - **The Map:** `User(ID: 123)` -> `LinkedAccount(Provider: Twitch, Token: ***)` + `LinkedAccount(Provider: YouTube, Token: ***)`.57 - **Rule:** Never merge accounts automatically based on email match (Security risk). Require explicit linking verification.58592. **The "Refresh Loop" Middleware**60 - **Pattern:** Before calling the Twitch API, check Access Token expiration.61 - **Expired?** Use the Encrypted Refresh Token to get a new Access Token transparently.62 - **Failed?** (User revoked access externally). Pause the integration and notify the user: "Please reconnect Twitch."63 - **Concurrency:** Handle race conditions if multiple requests try to refresh the token simultaneously.64653. **Rate Limit Isolation**66 - YouTube and Twitch have different API quotas.67 - Track usage *per provider*. Don't let a Twitch outage crash the YouTube integration.6869### Phase 4: Threat Modeling & Compliance (The Guard)7071**Assuming breach:**72731. **Dependency Scanning**74 - Audit auth libraries (e.g., `passport`, `next-auth`) for vulnerabilities weekly.75 - **Supply Chain:** Pin versions. Authentication logic is a high-value target for hackers.76772. **Anomaly Detection**78 - Log auth failures. "User 123 failed Twitch refresh 50 times in 1 minute." -> Alert.79 - Monitor for "Token Export" attempts (large volume of token reads).80 - **Audit Logs:** Log *who* linked *what* and *when*. (Immutable logs).81823. **Penetration Testing (Self)**83 - Try to swap the `code` parameter from one user to another.84 - Try to manipulate the `redirect_uri` to send the token to `evil.com`.85 - Try to bypass the `state` check.8687## Red Flags - STOP and Follow Process8889If you catch yourself thinking:90- "I'll store the Access Token in LocalStorage so it persists." (XSS Vulnerability).91- "I'll just ask for `scope: all` just in case we need it later." (Privacy violation).92- "I'll use the same `state` string for everyone." (CSRF Vulnerability).93- "I'll hardcode the Client Secret in the React app." (Secret Leak).94- "I'll decrypt the token, use it, and leave it in the logs." (Data Leak).95- "If the refresh fails, I'll just crash the app." (Bad UX).96- "I'll merge these two accounts because they have the same email." (Account Takeover Risk).9798**ALL of these mean: STOP. Return to Phase 1.**99100## Your Human Partner's Signals You're Doing It Wrong101102**Watch for these complaints:**103- **User:** "Why is it asking to read my emails? I just wanted to share a video." (Bad Scoping).104- **Dev:** "The token expired and the background job failed." (Missing Refresh Loop).105- **Sec:** "I found your Twitch Client Secret on GitHub." (Failed Secret Management).106- **User:** "I revoked the app in Google Settings, but your app still says connected." (Missing Error Handling).107- **Dev:** "I can't reproduce this login bug." (Missing Audit Logs).108109**When you see these:** STOP. Audit the Auth Flow.110111## Common Rationalizations112113| Excuse | Reality |114|--------|---------|115| "Implicit Flow is easier" | It is insecure and deprecated by IETF. Use PKCE. |116| "Encryption slows down the DB" | Leaking tokens shuts down the company. |117| "I'll handle token rotation later" | You will be blocked by the API provider quickly. |118| "HTTPS protects the token in URL" | Browser history and server logs still see it. |119| "We trust our database admin" | Defense in Depth. Even admins shouldn't see plaintext tokens. |120121## Quick Reference122123| Phase | Key Activities | Success Criteria |124|-------|---------------|------------------|125| **1. Architecture** | PKCE, Scopes, Redirects | Secure flow defined |126| **2. Storage** | Encryption, HTTPOnly Cookies | No secrets in frontend/logs |127| **3. Integration** | Refresh Loops, Linking | Seamless multi-API calls |128| **4. Defense** | CSRF, Audit Logs, Scanning | Resilient to attacks |129130## When The Provider Changes The Rules131132If Google or Twitch changes their auth policies (e.g., "OOB flow deprecation"):1331341. **Subscribe to Security News:** (Google Identity Blog, Twitch Developers).1352. **Deprecation is a P0:** Drop everything and migrate. Auth breakage means 0 users.1363. **Graceful Degrade:** If an API feature is removed, disable that specific button, don't crash the whole login.137138## Supporting Techniques139140- **`superpowers:oauth-debugging`** - Using tools like `jwt.io` and OIDC Debugger.141- **`superpowers:threat-modeling`** - STRIDE model for identity flows.142- **`superpowers:encryption-at-rest`** - Using AWS KMS / Vault for token storage.143144## Real-World Impact145146- **"Naive" implementation:** Storing tokens in local storage -> XSS attack -> Attacker drains user's bank/Twitch bits.147- **"Secure" implementation:** Tokens are encrypted cookies -> XSS attack fails to steal identity -> User is safe, Platform is trusted.