010 Implement 2 Fa and User Sessions

πŸ” Structured Prompt β€” Session Management + 2FA Implementation (Binding)

Objective: Implement backend-authoritative licensed session management with takeover flow and Two-Factor Authentication (2FA) in the Next.js frontend, fully mirroring the existing Blazor behavior.

Constraints:

  • Backend C# projects are frozen except for:

    • Session enforcement logic
    • 2FA verification endpoints (if already present or minimal additions)
  • Do not refactor existing business logic

  • Do not redesign authentication models

  • Reuse existing backend mechanisms wherever possible


PART 1 β€” LICENSED SESSION MANAGEMENT (MANDATORY)


1.1 Data Model (Backend)

Study the users table in the systemdb. You can write the migration script for extending this table.

1.2 Session Validity Rule

A session is ACTIVE if:

IsRevoked = 0
AND LastSeenAt >= NOW - IdleTimeout

IdleTimeout = 10 minutes


1.3 Session Start Flow

Endpoint:

POST /api/auth/session/start
Authorization: Bearer <Firebase JWT>

Backend logic:

  1. Resolve UserId + Tenant

  2. Fetch active sessions for user

  3. If active sessions < MaxConcurrentSessions:

    • Create new session
    • Return SessionToken
  4. Else:

    • Return 409 CONFLICT with payload:
{
  "reason": "ACTIVE_SESSION_EXISTS",
  "sessions": [
    {
      "deviceId": "...",
      "lastSeenAt": "..."
    }
  ]
}

1.4 Takeover Flow (β€œAlready signed in”)

Frontend UX:

Show modal:

You are already signed in on another device. Do you want to continue and release that session?

Buttons:

β€’ Continue & Sign Out Other Device β€’ Cancel


Endpoint:

POST /api/auth/session/takeover
Authorization: Bearer <Firebase JWT>

Backend logic:

  • Revoke all active sessions
  • Create new session
  • Return new SessionToken

1.5 Heartbeat

Every authenticated API call must:

UPDATE Users SET LastSeenAt = NOW WHERE SessionId = @SessionId

(Optional ping endpoint allowed)


1.6 Enforcement

For every API request:

  • Validate SessionToken
  • Ensure active lease
  • If invalid β†’ 401

PART 2 β€” TWO-FACTOR AUTHENTICATION (2FA) PARITY


2.1 Supported Methods (Must Match Blazor)

Implement in Next.js frontend:

βœ… Email OTP βœ… Google Authenticator (TOTP)

Reuse existing backend 2FA endpoints and logic.


2.2 2FA Flow

After Firebase login and before session start:

  1. Backend checks if user requires 2FA
  2. If yes β†’ return:
{
  "requires2FA": true,
  "methods": ["EMAIL", "TOTP"]
}
  1. Frontend displays 2FA selection UI
  2. User completes verification
  3. Backend confirms 2FA
  4. Proceed to session start

2.3 Verification Endpoints

Use existing backend endpoints if present:

  • Send OTP
  • Verify OTP
  • Verify TOTP

If minimal endpoints are missing, add without refactoring.


PART 3 β€” 6-HOUR TRUSTED SESSION WINDOW (CRITICAL)


3.1 Behavior (Must Match Blazor)

If user has completed 2FA successfully:

πŸ‘‰ Do NOT ask for 2FA again for 6 hours

Even if user logs out and logs in again.


3.2 Backend Storage

Add (or reuse) field:

Last2FAVerifiedAt

Associated with:

  • User or Session (prefer User-level)

3.3 Logic

On login:

if NOW - Last2FAVerifiedAt < 6 hours:
    skip 2FA
else:
    require 2FA

On successful 2FA:

update Last2FAVerifiedAt = NOW

PART 4 β€” FRONTEND UX REQUIREMENTS


4.1 Session Conflict UI

  • Modal, not alert
  • Clear explanation
  • No crash
  • Cancel option returns to login

4.2 2FA UI

  • Method selection screen
  • OTP input screen
  • TOTP input screen
  • Error handling
  • Resend OTP option

4.3 Edge Handling

  • Session expired β†’ redirect to login
  • 2FA failed β†’ retry allowed
  • Multiple wrong OTP attempts β†’ follow backend behavior

PART 5 β€” SECURITY & COMPLIANCE RULES


βœ… Backend authoritative for:

  • Sessions
  • 2FA enforcement

❌ Frontend must not:

  • Decide session validity
  • Skip 2FA without backend approval

❌ No localStorage for:

  • Session authority
  • 2FA state

PART 6 β€” COMPLETION CONFIRMATION (REQUIRED)

After implementation, explicitly confirm:

βœ” Licensed sessions enforce concurrency βœ” Takeover flow works βœ” Idle sessions auto-expire βœ” 2FA methods work βœ” 6-hour trusted window respected βœ” Backend authority preserved


πŸ“Œ FINAL NOTE (NON-NEGOTIABLE)

Do not redesign:

  • Authentication stack
  • RBAC
  • Tenant resolution

Implement exactly as specified.


βœ… What this will deliver

When Antigravity completes this:

βœ” No credential sharing abuse βœ” No capacity surprise βœ” Full security parity with Blazor βœ” Modern mobile UX βœ” No lockouts βœ” No repeated 2FA annoyance