|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { Command, Flags } from '@oclif/core'; |
| 4 | +import chalk from 'chalk'; |
| 5 | +import { createInterface } from 'node:readline'; |
| 6 | +import { |
| 7 | + printHeader, |
| 8 | + printSuccess, |
| 9 | + printWarning, |
| 10 | + printError, |
| 11 | + printInfo, |
| 12 | + printStep, |
| 13 | + createTimer, |
| 14 | +} from '../../utils/format.js'; |
| 15 | +import { bootSchemaStack } from '../../utils/schema-migrate.js'; |
| 16 | +import { bootstrapPlatformAdmin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; |
| 17 | + |
| 18 | +async function confirm(question: string): Promise<boolean> { |
| 19 | + if (!process.stdin.isTTY) return false; // non-interactive → require --yes |
| 20 | + const rl = createInterface({ input: process.stdin, output: process.stdout }); |
| 21 | + try { |
| 22 | + const answer: string = await new Promise((resolve) => rl.question(question, resolve)); |
| 23 | + return /^y(es)?$/i.test(answer.trim()); |
| 24 | + } finally { |
| 25 | + rl.close(); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +function safeGetService(kernel: any, name: string): any { |
| 30 | + try { |
| 31 | + return kernel?.getService?.(name); |
| 32 | + } catch { |
| 33 | + return undefined; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * `os meta resync` — reconcile materialized metadata to the compiled `dist` |
| 39 | + * without a `--fresh` wipe (#2705). |
| 40 | + * |
| 41 | + * The default permission sets (admin_full_access / member_default / |
| 42 | + * viewer_readonly …) are seeded INSERT-ONCE at boot: an existing row is never |
| 43 | + * clobbered, so an edit to a default set's source is served with its OLD value |
| 44 | + * until the DB is wiped — a silent dev-loop trap (a permission-gated action |
| 45 | + * "mysteriously" keeps its old behavior). Every OTHER metadata seed (declared |
| 46 | + * permission sets, positions, built-in roles, capabilities) already upserts on |
| 47 | + * boot; this command closes the one remaining gap by force-reconciling the |
| 48 | + * default permission-set rows to the shipped declaration. |
| 49 | + * |
| 50 | + * Business data is never touched — only `sys_permission_set` definition rows. |
| 51 | + * A row an admin has taken over in Setup (`managed_by:'user'`) or a package |
| 52 | + * owns (`'package'`) is an intentional override and is left alone. |
| 53 | + */ |
| 54 | +export default class MetaResync extends Command { |
| 55 | + static override description = |
| 56 | + 'Reconcile materialized metadata (default permission sets) to the compiled dist without a --fresh wipe (#2705)'; |
| 57 | + |
| 58 | + static override examples = [ |
| 59 | + '$ os meta resync', |
| 60 | + '$ os meta resync --yes', |
| 61 | + '$ os meta resync --json', |
| 62 | + ]; |
| 63 | + |
| 64 | + static override flags = { |
| 65 | + 'database-url': Flags.string({ |
| 66 | + description: 'Database URL to reconcile (defaults to $OS_DATABASE_URL / the project DB)', |
| 67 | + env: 'OS_DATABASE_URL', |
| 68 | + }), |
| 69 | + yes: Flags.boolean({ char: 'y', description: 'Skip the confirmation prompt', default: false }), |
| 70 | + json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to mutate)' }), |
| 71 | + }; |
| 72 | + |
| 73 | + async run(): Promise<void> { |
| 74 | + const { flags } = await this.parse(MetaResync); |
| 75 | + const timer = createTimer(); |
| 76 | + let exitCode = 0; |
| 77 | + |
| 78 | + if (!flags.json) { |
| 79 | + printHeader('Meta · resync'); |
| 80 | + printStep('Booting runtime stack…'); |
| 81 | + } |
| 82 | + |
| 83 | + let stack; |
| 84 | + try { |
| 85 | + stack = await bootSchemaStack({ databaseUrl: flags['database-url'] }); |
| 86 | + } catch (error: any) { |
| 87 | + if (flags.json) console.log(JSON.stringify({ error: error.message })); |
| 88 | + else printError(error.message || String(error)); |
| 89 | + process.exit(1); |
| 90 | + } |
| 91 | + |
| 92 | + try { |
| 93 | + const ql = safeGetService(stack.kernel, 'objectql'); |
| 94 | + // Prefer the SecurityPlugin's resolved set when a full stack is booted (it |
| 95 | + // picks up an app's `defaultPermissionSets` override); fall back to the |
| 96 | + // platform defaults, which is what the standalone stack this command boots |
| 97 | + // exposes. Either way these are the sets `bootstrapPlatformAdmin` seeds. |
| 98 | + const svcSets = safeGetService(stack.kernel, 'security.bootstrapPermissionSets'); |
| 99 | + const sets: any[] = Array.isArray(svcSets) && svcSets.length > 0 ? svcSets : securityDefaultPermissionSets; |
| 100 | + |
| 101 | + if (!ql) { |
| 102 | + if (flags.json) { |
| 103 | + console.log(JSON.stringify({ error: 'objectql_unavailable' })); |
| 104 | + return; |
| 105 | + } |
| 106 | + printError('ObjectQL service is not available — cannot resync.'); |
| 107 | + return; |
| 108 | + } |
| 109 | + if (!Array.isArray(sets) || sets.length === 0) { |
| 110 | + if (flags.json) { |
| 111 | + console.log(JSON.stringify({ resynced: 0, resyncSkipped: 0, inserted: 0, message: 'no_default_permission_sets' })); |
| 112 | + return; |
| 113 | + } |
| 114 | + printWarning('No default permission sets are available to resync.'); |
| 115 | + return; |
| 116 | + } |
| 117 | + |
| 118 | + // Confirmation gate — resync overwrites the default permission-set |
| 119 | + // definitions from the compiled dist, so admin Setup edits to those sets |
| 120 | + // are replaced. Business data is never touched. |
| 121 | + if (!flags.yes) { |
| 122 | + if (flags.json || !process.stdin.isTTY) { |
| 123 | + if (flags.json) { |
| 124 | + console.log(JSON.stringify({ resynced: 0, resyncSkipped: 0, inserted: 0, message: 'confirmation_required', hint: 'pass --yes' })); |
| 125 | + return; |
| 126 | + } |
| 127 | + printWarning('Confirmation required. Re-run with --yes to resync.'); |
| 128 | + return; |
| 129 | + } |
| 130 | + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); |
| 131 | + printWarning('This overwrites the default permission-set definitions from the compiled dist.'); |
| 132 | + console.log(chalk.dim(' Admin Setup edits to those sets are replaced. Business data is untouched.')); |
| 133 | + console.log(chalk.dim(' Sets an admin or a package has taken over (managed_by user/package) are left alone.')); |
| 134 | + const ok = await confirm(chalk.bold(`\nResync ${sets.length} default permission set(s) to ${stack.dbLabel}? [y/N] `)); |
| 135 | + if (!ok) { |
| 136 | + printInfo('Aborted — no changes made.'); |
| 137 | + return; |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + const logger = flags.json |
| 142 | + ? undefined |
| 143 | + : { info: (m: string) => printInfo(m), warn: (m: string) => printWarning(m) }; |
| 144 | + |
| 145 | + const report = await bootstrapPlatformAdmin(ql, sets as any[], { resync: true, logger }); |
| 146 | + const resynced = report.resynced ?? 0; |
| 147 | + const resyncSkipped = report.resyncSkipped ?? 0; |
| 148 | + // seeded = existing + newly inserted; existing (under resync) = resynced + |
| 149 | + // resyncSkipped, so the remainder is what this run freshly seeded. |
| 150 | + const inserted = Math.max(0, (report.seeded ?? 0) - resynced - resyncSkipped); |
| 151 | + |
| 152 | + if (flags.json) { |
| 153 | + console.log(JSON.stringify({ database: stack.dbLabel, resynced, resyncSkipped, inserted, duration: timer.elapsed() }, null, 2)); |
| 154 | + return; |
| 155 | + } |
| 156 | + |
| 157 | + console.log(''); |
| 158 | + if (resynced > 0 || inserted > 0) { |
| 159 | + printSuccess(`Reconciled ${resynced} default permission set(s) to dist${inserted > 0 ? `, seeded ${inserted} new` : ''}.`); |
| 160 | + } else { |
| 161 | + printInfo('Nothing reconciled.'); |
| 162 | + } |
| 163 | + if (resyncSkipped > 0) { |
| 164 | + printWarning(`Left ${resyncSkipped} set(s) untouched (admin- or package-owned override).`); |
| 165 | + } |
| 166 | + console.log(chalk.dim(` ${timer.display()}`)); |
| 167 | + console.log(''); |
| 168 | + } catch (error: any) { |
| 169 | + exitCode = 1; |
| 170 | + if (flags.json) console.log(JSON.stringify({ error: error.message })); |
| 171 | + else printError(error.message || String(error)); |
| 172 | + } finally { |
| 173 | + await stack.shutdown(); |
| 174 | + // A one-shot command must exit even when the booted app stack left |
| 175 | + // keep-alive handles open (schedulers/watchers registered on kernel:ready |
| 176 | + // that `runtime.stop()` cannot fully drain). Matches the process.exit |
| 177 | + // posture the other one-shot CLI commands use. |
| 178 | + process.exit(exitCode); |
| 179 | + } |
| 180 | + } |
| 181 | +} |
0 commit comments