|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * bootstrapPlatformAdmin — first-boot platform admin promotion. |
| 5 | + * |
| 6 | + * Two responsibilities, both idempotent and run on `kernel:ready`: |
| 7 | + * |
| 8 | + * 1. **Seed `sys_permission_set` rows** for each `defaultPermissionSets` |
| 9 | + * entry (admin_full_access / member_default / viewer_readonly). The |
| 10 | + * dashboard's CRUD on `sys_permission_set` needs persisted rows to |
| 11 | + * exist so admins can grant them to users by id; the in-memory |
| 12 | + * bootstrap list alone is invisible to the standard CRUD UI. |
| 13 | + * |
| 14 | + * 2. **Promote the first registered user to platform admin** by |
| 15 | + * inserting a `sys_user_permission_set` row that points at |
| 16 | + * `admin_full_access` with `organization_id = NULL` (= cross-tenant). |
| 17 | + * If a platform admin already exists, this is a no-op forever. |
| 18 | + * |
| 19 | + * Zero configuration: `pnpm dev:crm` → sign up → "I'm admin". |
| 20 | + * |
| 21 | + * The DB column shape (`object_permissions` JSON text) does not match |
| 22 | + * the spec shape (`objects` record). For now we only need stable rows |
| 23 | + * with the right `name` so `resolveExecutionContext` can translate the |
| 24 | + * link-table id back to the bootstrap permission set name; the actual |
| 25 | + * `objects`/`rowLevelSecurity` definitions are still served from the |
| 26 | + * in-memory `bootstrapPermissionSets` list inside SecurityPlugin. |
| 27 | + */ |
| 28 | + |
| 29 | +import type { PermissionSet } from '@objectstack/spec/security'; |
| 30 | + |
| 31 | +interface BootstrapOptions { |
| 32 | + /** Logger from PluginContext. */ |
| 33 | + logger?: { |
| 34 | + info: (message: string, meta?: Record<string, any>) => void; |
| 35 | + warn: (message: string, meta?: Record<string, any>) => void; |
| 36 | + }; |
| 37 | +} |
| 38 | + |
| 39 | +const SYSTEM_CTX = { isSystem: true }; |
| 40 | + |
| 41 | +async function tryFind(ql: any, object: string, where: any, limit = 100): Promise<any[]> { |
| 42 | + try { |
| 43 | + const rows = await ql.find(object, { where, limit }, { context: SYSTEM_CTX }); |
| 44 | + return Array.isArray(rows) ? rows : []; |
| 45 | + } catch { |
| 46 | + return []; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +async function tryInsert(ql: any, object: string, data: any): Promise<any | null> { |
| 51 | + try { |
| 52 | + return await ql.insert(object, data, { context: SYSTEM_CTX }); |
| 53 | + } catch { |
| 54 | + return null; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +function genId(prefix: string): string { |
| 59 | + const rand = Math.random().toString(36).slice(2, 10); |
| 60 | + const ts = Date.now().toString(36); |
| 61 | + return `${prefix}_${ts}${rand}`; |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Persist seed permission sets and promote the first registered user to |
| 66 | + * platform admin. Safe to call multiple times. |
| 67 | + */ |
| 68 | +export async function bootstrapPlatformAdmin( |
| 69 | + ql: any, |
| 70 | + bootstrapPermissionSets: PermissionSet[], |
| 71 | + options: BootstrapOptions = {}, |
| 72 | +): Promise<{ seeded: number; adminPromoted: boolean; reason?: string }> { |
| 73 | + const logger = options.logger; |
| 74 | + if (!ql || typeof ql.find !== 'function' || typeof ql.insert !== 'function') { |
| 75 | + return { seeded: 0, adminPromoted: false, reason: 'objectql_unavailable' }; |
| 76 | + } |
| 77 | + |
| 78 | + // 1. Seed permission set rows (one row per name, idempotent). |
| 79 | + const seeded: Record<string, string> = {}; // name -> id |
| 80 | + for (const ps of bootstrapPermissionSets) { |
| 81 | + if (!ps.name) continue; |
| 82 | + const existing = await tryFind(ql, 'sys_permission_set', { name: ps.name }, 1); |
| 83 | + if (existing.length > 0 && existing[0].id) { |
| 84 | + seeded[ps.name] = existing[0].id; |
| 85 | + continue; |
| 86 | + } |
| 87 | + const id = genId('ps'); |
| 88 | + const created = await tryInsert(ql, 'sys_permission_set', { |
| 89 | + id, |
| 90 | + name: ps.name, |
| 91 | + label: ps.label ?? ps.name, |
| 92 | + description: ps.description ?? null, |
| 93 | + object_permissions: JSON.stringify(ps.objects ?? {}), |
| 94 | + field_permissions: JSON.stringify(ps.fields ?? {}), |
| 95 | + active: true, |
| 96 | + }); |
| 97 | + if (created?.id) seeded[ps.name] = created.id; |
| 98 | + else if (created) seeded[ps.name] = id; |
| 99 | + } |
| 100 | + |
| 101 | + const seededCount = Object.keys(seeded).length; |
| 102 | + |
| 103 | + // 2. First-user platform admin promotion. |
| 104 | + const adminPsId = seeded['admin_full_access']; |
| 105 | + if (!adminPsId) { |
| 106 | + return { seeded: seededCount, adminPromoted: false, reason: 'admin_permission_set_missing' }; |
| 107 | + } |
| 108 | + |
| 109 | + // If a platform admin already exists, we're done. |
| 110 | + const existingAdminLinks = await tryFind( |
| 111 | + ql, |
| 112 | + 'sys_user_permission_set', |
| 113 | + { permission_set_id: adminPsId }, |
| 114 | + 5, |
| 115 | + ); |
| 116 | + if (existingAdminLinks.some((r) => !r.organization_id)) { |
| 117 | + return { seeded: seededCount, adminPromoted: false, reason: 'already_have_admin' }; |
| 118 | + } |
| 119 | + |
| 120 | + // Promote the oldest user (= first registrant). If no users yet, the |
| 121 | + // sys_user post-create middleware will rerun this on first sign-up. |
| 122 | + const allUsers = await tryFind(ql, 'sys_user', {}, 50); |
| 123 | + if (allUsers.length === 0) { |
| 124 | + logger?.info?.('[security] no users yet — first sign-up will be promoted to platform admin'); |
| 125 | + return { seeded: seededCount, adminPromoted: false, reason: 'no_users' }; |
| 126 | + } |
| 127 | + const sorted = [...allUsers].sort((a, b) => { |
| 128 | + const ta = a.created_at ? new Date(a.created_at).getTime() : 0; |
| 129 | + const tb = b.created_at ? new Date(b.created_at).getTime() : 0; |
| 130 | + return ta - tb; |
| 131 | + }); |
| 132 | + const target = sorted[0]; |
| 133 | + |
| 134 | + const inserted = await tryInsert(ql, 'sys_user_permission_set', { |
| 135 | + id: genId('ups'), |
| 136 | + user_id: target.id, |
| 137 | + permission_set_id: adminPsId, |
| 138 | + organization_id: null, |
| 139 | + granted_by: null, |
| 140 | + }); |
| 141 | + if (!inserted) { |
| 142 | + logger?.warn?.(`[security] failed to grant admin_full_access to first user ${target.email ?? target.id}`); |
| 143 | + return { seeded: seededCount, adminPromoted: false, reason: 'insert_failed' }; |
| 144 | + } |
| 145 | + logger?.info?.(`[security] first user promoted to platform admin: ${target.email ?? target.id}`); |
| 146 | + return { seeded: seededCount, adminPromoted: true }; |
| 147 | +} |
0 commit comments