|
| 1 | +/** |
| 2 | + * KEON ACTIVATION — PROVISION API |
| 3 | + * |
| 4 | + * POST /api/activation/provision |
| 5 | + * Start a provisioning session for a magic-link token. |
| 6 | + * In production: validates the invite token against the database, |
| 7 | + * creates the tenant/membership, and returns a provisioning session ID. |
| 8 | + * Currently: simulates the flow using time-based state progression. |
| 9 | + * |
| 10 | + * GET /api/activation/provision?id=<provisioningId> |
| 11 | + * Poll for current provisioning state. |
| 12 | + * Returns the derived user-facing state (never internal state names). |
| 13 | + * |
| 14 | + * ─── Magic Link Integration Note ────────────────────────────────────────────── |
| 15 | + * When wiring to a real auth layer: |
| 16 | + * 1. The magic link handler should redirect to /activate?token=<signed_token> |
| 17 | + * 2. POST here with that token — server validates signature + expiry |
| 18 | + * 3. On valid token: create tenant row + membership binding, return provisioningId |
| 19 | + * 4. On invalid/expired token: return 401 with failureCode "token_expired" or "token_invalid" |
| 20 | + * 5. Store provisioningId in session/cookie for safe refresh support |
| 21 | + */ |
| 22 | + |
| 23 | +import { deriveProvisioningState, resolveSimulatedState } from "@/lib/activation/state-machine"; |
| 24 | +import type { ProvisioningStatusResponse, StartProvisioningResponse } from "@/lib/activation/types"; |
| 25 | +import { NextRequest, NextResponse } from "next/server"; |
| 26 | +import crypto from "node:crypto"; |
| 27 | + |
| 28 | +// ─── In-process session store ───────────────────────────────────────────────── |
| 29 | +// In production: replace with Redis/Postgres-backed provisioning records. |
| 30 | +// This module-level map persists within a single server process. |
| 31 | + |
| 32 | +interface ProvisioningRecord { |
| 33 | + id: string; |
| 34 | + token: string; |
| 35 | + createdAt: number; |
| 36 | + forceFailed?: boolean; |
| 37 | +} |
| 38 | + |
| 39 | +const sessions = new Map<string, ProvisioningRecord>(); |
| 40 | + |
| 41 | +// ─── POST — Start Provisioning ──────────────────────────────────────────────── |
| 42 | + |
| 43 | +export async function POST(request: NextRequest): Promise<NextResponse> { |
| 44 | + try { |
| 45 | + const body = await request.json().catch(() => ({})); |
| 46 | + const token = typeof body?.token === "string" ? body.token.trim() : ""; |
| 47 | + |
| 48 | + // In production: validate token signature, check expiry, prevent replay. |
| 49 | + // For now: accept any non-empty token string. |
| 50 | + if (!token) { |
| 51 | + return NextResponse.json( |
| 52 | + { error: "activation_token_required", message: "A valid activation token is required." }, |
| 53 | + { status: 400 } |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + // Check if a session already exists for this token (idempotent POST) |
| 58 | + for (const [, record] of sessions) { |
| 59 | + if (record.token === token) { |
| 60 | + return NextResponse.json<StartProvisioningResponse>({ provisioningId: record.id }); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + const provisioningId = `prov_${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`; |
| 65 | + sessions.set(provisioningId, { |
| 66 | + id: provisioningId, |
| 67 | + token, |
| 68 | + createdAt: Date.now(), |
| 69 | + }); |
| 70 | + |
| 71 | + // Cleanup stale sessions (> 30 minutes old) on each new session creation |
| 72 | + const cutoff = Date.now() - 30 * 60 * 1000; |
| 73 | + for (const [id, record] of sessions) { |
| 74 | + if (record.createdAt < cutoff) sessions.delete(id); |
| 75 | + } |
| 76 | + |
| 77 | + return NextResponse.json<StartProvisioningResponse>({ provisioningId }, { status: 201 }); |
| 78 | + } catch { |
| 79 | + return NextResponse.json( |
| 80 | + { error: "internal_error", message: "Unable to start provisioning." }, |
| 81 | + { status: 500 } |
| 82 | + ); |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +// ─── GET — Poll Provisioning State ─────────────────────────────────────────── |
| 87 | + |
| 88 | +export async function GET(request: NextRequest): Promise<NextResponse> { |
| 89 | + const provisioningId = request.nextUrl.searchParams.get("id"); |
| 90 | + |
| 91 | + if (!provisioningId) { |
| 92 | + return NextResponse.json( |
| 93 | + { error: "provisioning_id_required", message: "Provisioning ID is required." }, |
| 94 | + { status: 400 } |
| 95 | + ); |
| 96 | + } |
| 97 | + |
| 98 | + const record = sessions.get(provisioningId); |
| 99 | + if (!record) { |
| 100 | + return NextResponse.json( |
| 101 | + { error: "session_not_found", message: "Provisioning session not found or has expired." }, |
| 102 | + { status: 404 } |
| 103 | + ); |
| 104 | + } |
| 105 | + |
| 106 | + const internalState = record.forceFailed |
| 107 | + ? "provisioning_failed" |
| 108 | + : resolveSimulatedState(record.createdAt); |
| 109 | + |
| 110 | + const state = deriveProvisioningState(internalState); |
| 111 | + |
| 112 | + const response: ProvisioningStatusResponse = { |
| 113 | + provisioningId, |
| 114 | + state, |
| 115 | + ...(internalState === "provisioning_complete" && { |
| 116 | + completedAt: new Date().toISOString(), |
| 117 | + }), |
| 118 | + ...(internalState === "provisioning_failed" && { |
| 119 | + failedAt: new Date().toISOString(), |
| 120 | + failureCode: "workspace_bootstrap_failed", |
| 121 | + failureMessage: "Unable to initialize workspace. Your invitation is still valid.", |
| 122 | + }), |
| 123 | + }; |
| 124 | + |
| 125 | + return NextResponse.json(response); |
| 126 | +} |
0 commit comments