auth-core-migration.ts73 lines · main
| 1 | /** |
| 2 | * briven-engine migration API (Phase 7 surface). |
| 3 | * |
| 4 | * POST /v1/auth-core/migration/users |
| 5 | */ |
| 6 | |
| 7 | import { Hono } from 'hono'; |
| 8 | |
| 9 | import { requireAuthCoreDashboard } from '../middleware/auth-core-guard.js'; |
| 10 | import { requireDashboardProjectAdmin } from '../services/auth-core/dashboard-project-auth.js'; |
| 11 | import { BRIVEN_ENGINE_ID } from '../services/auth-core/engine.js'; |
| 12 | import { |
| 13 | importBrivenEngineUsers, |
| 14 | type ImportUserInput, |
| 15 | } from '../services/auth-core/migration.js'; |
| 16 | import type { AppEnv } from '../types/app-env.js'; |
| 17 | |
| 18 | export const authCoreMigrationRouter = new Hono<AppEnv>(); |
| 19 | |
| 20 | authCoreMigrationRouter.use( |
| 21 | '/v1/auth-core/migration/*', |
| 22 | requireAuthCoreDashboard(), |
| 23 | ); |
| 24 | |
| 25 | authCoreMigrationRouter.post('/v1/auth-core/migration/users', async (c) => { |
| 26 | let body: { users?: ImportUserInput[]; projectId?: string } = {}; |
| 27 | try { |
| 28 | body = await c.req.json(); |
| 29 | } catch { |
| 30 | body = {}; |
| 31 | } |
| 32 | if (!Array.isArray(body.users) || body.users.length === 0) { |
| 33 | return c.json( |
| 34 | { |
| 35 | engine: BRIVEN_ENGINE_ID, |
| 36 | code: 'users_array_required', |
| 37 | message: 'Body must be { users: [...], projectId?: "p_…" }', |
| 38 | }, |
| 39 | 400, |
| 40 | ); |
| 41 | } |
| 42 | if (body.users.length > 500) { |
| 43 | return c.json( |
| 44 | { |
| 45 | engine: BRIVEN_ENGINE_ID, |
| 46 | code: 'batch_too_large', |
| 47 | message: 'Max 500 users per request', |
| 48 | }, |
| 49 | 400, |
| 50 | ); |
| 51 | } |
| 52 | // Stamp top-level projectId onto rows that omit it (dashboard migration UX). |
| 53 | const projectGate = await requireDashboardProjectAdmin(c, body.projectId); |
| 54 | if (projectGate instanceof Response) return projectGate; |
| 55 | const projectId = projectGate.projectId; |
| 56 | const users = body.users.map((u) => ({ |
| 57 | ...u, |
| 58 | projectId: u.projectId ?? projectId, |
| 59 | })); |
| 60 | // Reject rows that try to import into a different project. |
| 61 | if (users.some((u) => u.projectId && u.projectId !== projectId)) { |
| 62 | return c.json( |
| 63 | { |
| 64 | engine: BRIVEN_ENGINE_ID, |
| 65 | code: 'project_mismatch', |
| 66 | message: 'all users must target the same projectId as the request', |
| 67 | }, |
| 68 | 403, |
| 69 | ); |
| 70 | } |
| 71 | const result = await importBrivenEngineUsers(users); |
| 72 | return c.json(result, result.ok ? 200 : 503); |
| 73 | }); |