mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
refactor(realtime, systemNotices, addons, airports, audit, categories, permissions, query-helpers, tags, transit, trip-membership): async DB-touching methods; transactions through UnitOfWork
This commit is contained in:
@@ -78,7 +78,7 @@ export class JournalEntryRowsController {
|
||||
@Param('entryId') entryIdRaw: string,
|
||||
@Req() req: Request & { user?: { id: number } },
|
||||
): Promise<{ providers: ProviderResult[] }> {
|
||||
if (!pluginsEnabled() || !this.addons.isAddonEnabled(ADDON_IDS.JOURNEY)) return { providers: [] };
|
||||
if (!pluginsEnabled() || !(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) return { providers: [] };
|
||||
const entryId = Number(entryIdRaw);
|
||||
const userId = req.user?.id;
|
||||
if (!Number.isFinite(entryId) || userId == null) return { providers: [] };
|
||||
|
||||
@@ -52,8 +52,17 @@ export function parseDependencies(raw: string | null | undefined): PluginDepende
|
||||
}
|
||||
|
||||
/** Required addon ids that are currently NOT enabled — these block activation. */
|
||||
export function disabledRequiredAddons(deps: PluginDependencies, isAddonEnabled: (id: string) => boolean): string[] {
|
||||
return deps.requiredAddons.filter((a) => !isAddonEnabled(a));
|
||||
export async function disabledRequiredAddons(
|
||||
deps: PluginDependencies,
|
||||
isAddonEnabled: (id: string) => Promise<boolean>,
|
||||
): Promise<string[]> {
|
||||
// A `filter` cannot await, so the same predicate runs as an explicit loop —
|
||||
// same order, same result.
|
||||
const disabled: string[] = [];
|
||||
for (const a of deps.requiredAddons) {
|
||||
if (!(await isAddonEnabled(a))) disabled.push(a);
|
||||
}
|
||||
return disabled;
|
||||
}
|
||||
|
||||
export interface VersionMismatch {
|
||||
|
||||
@@ -56,9 +56,9 @@ export class PluginGuards {
|
||||
}
|
||||
|
||||
/** A write is allowed only if the acting user can access AND edit the trip. */
|
||||
requireTripEdit(tripId: number, userId: number, action: string): void {
|
||||
async requireTripEdit(tripId: number, userId: number, action: string): Promise<void> {
|
||||
if (!this.db.canAccessTrip(tripId, userId)) throw new ForbiddenResource(`no access to trip ${tripId}`);
|
||||
if (!this.canEditAs(action, tripId, userId)) throw new ForbiddenResource(`no permission to edit trip ${tripId}`);
|
||||
if (!(await this.canEditAs(action, tripId, userId))) throw new ForbiddenResource(`no permission to edit trip ${tripId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,7 +66,7 @@ export class PluginGuards {
|
||||
* per-domain canEdit. Returns false and never throws, so the caller decides which
|
||||
* message the refusal carries.
|
||||
*/
|
||||
canEditAs(action: string, tripId: number, userId: number): boolean {
|
||||
async canEditAs(action: string, tripId: number, userId: number): Promise<boolean> {
|
||||
const trip = this.db.canAccessTrip(tripId, userId);
|
||||
if (!trip) return false;
|
||||
const user = this.db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
|
||||
@@ -79,7 +79,7 @@ export class PluginGuards {
|
||||
* requireTripEdit. `trip_create` is the only one today: it has no trip to check
|
||||
* against yet, which is why the owner id is passed as null.
|
||||
*/
|
||||
canCreateAs(action: string, userId: number): boolean {
|
||||
async canCreateAs(action: string, userId: number): Promise<boolean> {
|
||||
const user = this.db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined;
|
||||
return this.permissions.checkPermission(action, user?.role ?? 'user', null, userId, false);
|
||||
}
|
||||
@@ -88,8 +88,8 @@ export class PluginGuards {
|
||||
* A subsystem read is refused when its addon is off, matching the app, where a
|
||||
* disabled addon means there is simply nothing to read.
|
||||
*/
|
||||
requireAddon(addonId: string, noun: string): void {
|
||||
if (!this.addons.isAddonEnabled(addonId)) throw new ForbiddenResource(`the ${noun} addon is disabled`);
|
||||
async requireAddon(addonId: string, noun: string): Promise<void> {
|
||||
if (!(await this.addons.isAddonEnabled(addonId))) throw new ForbiddenResource(`the ${noun} addon is disabled`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -122,7 +122,7 @@ export class HostSurfaceRpc {
|
||||
@PluginMethod('ai.complete', { permission: 'ai:invoke' })
|
||||
async aiComplete(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
const actor = this.guards.requireActor(ctx, 'AI');
|
||||
const config = this.requireLlm(actor);
|
||||
const config = await this.requireLlm(actor);
|
||||
const prompt = typeof params.prompt === 'string' ? params.prompt : '';
|
||||
if (prompt.trim() === '') throw new BadParams('prompt is required');
|
||||
if (prompt.length > AI_TEXT_MAX) throw new BadParams(`prompt exceeds the ${AI_TEXT_MAX}-char cap`);
|
||||
@@ -143,7 +143,7 @@ export class HostSurfaceRpc {
|
||||
@PluginMethod('ai.extract', { permission: 'ai:invoke' })
|
||||
async aiExtract(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
const actor = this.guards.requireActor(ctx, 'AI');
|
||||
const config = this.requireLlm(actor);
|
||||
const config = await this.requireLlm(actor);
|
||||
const text = typeof params.text === 'string' ? params.text : '';
|
||||
if (text.trim() === '') throw new BadParams('text is required');
|
||||
if (text.length > AI_TEXT_MAX) throw new BadParams(`text exceeds the ${AI_TEXT_MAX}-char cap`);
|
||||
@@ -221,9 +221,9 @@ export class HostSurfaceRpc {
|
||||
.get(actingUserId, targetUserId, actingUserId, targetUserId);
|
||||
}
|
||||
|
||||
private requireLlm(userId: number) {
|
||||
const config = this.llmConfig.resolve(userId);
|
||||
if (!config) throw new BadParams('no AI provider is configured for this user');
|
||||
private async requireLlm(userId: number) {
|
||||
const config = await this.llmConfig.resolve(userId);
|
||||
if (!(await config)) throw new BadParams('no AI provider is configured for this user');
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@@ -49,8 +49,8 @@ export class MetaRpc {
|
||||
) {}
|
||||
|
||||
@PluginMethod('meta.get', { permission: 'db:meta' })
|
||||
get(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = this.resolveEntity(params, ctx, false);
|
||||
async get(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
const { entityType, entityId } = await this.resolveEntity(params, ctx, false);
|
||||
const row = this.db
|
||||
.prepare('SELECT value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
|
||||
.get(ctx.pluginId, entityType, entityId, str(params.key, 'key')) as { value: string } | undefined;
|
||||
@@ -63,8 +63,8 @@ export class MetaRpc {
|
||||
}
|
||||
|
||||
@PluginMethod('meta.set', { permission: 'db:meta' })
|
||||
set(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = this.resolveEntity(params, ctx, true);
|
||||
async set(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
const { entityType, entityId } = await this.resolveEntity(params, ctx, true);
|
||||
const key = str(params.key, 'key');
|
||||
if (key.length > META_KEY_MAX) throw new BadParams(`metadata key too long (>${META_KEY_MAX} chars)`);
|
||||
const json = JSON.stringify(params.value ?? null);
|
||||
@@ -88,8 +88,8 @@ export class MetaRpc {
|
||||
}
|
||||
|
||||
@PluginMethod('meta.list', { permission: 'db:meta' })
|
||||
list(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = this.resolveEntity(params, ctx, false);
|
||||
async list(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
const { entityType, entityId } = await this.resolveEntity(params, ctx, false);
|
||||
const rows = this.db
|
||||
.prepare('SELECT key, value FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? ORDER BY key')
|
||||
.all(ctx.pluginId, entityType, entityId) as Array<{ key: string; value: string }>;
|
||||
@@ -105,8 +105,8 @@ export class MetaRpc {
|
||||
}
|
||||
|
||||
@PluginMethod('meta.delete', { permission: 'db:meta' })
|
||||
delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = this.resolveEntity(params, ctx, true);
|
||||
async delete(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
const { entityType, entityId } = await this.resolveEntity(params, ctx, true);
|
||||
const res = this.db
|
||||
.prepare('DELETE FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
|
||||
.run(ctx.pluginId, entityType, entityId, str(params.key, 'key'));
|
||||
@@ -118,11 +118,11 @@ export class MetaRpc {
|
||||
* resolves to a trip the acting user can access, and for a write that entity's own
|
||||
* edit permission.
|
||||
*/
|
||||
private resolveEntity(
|
||||
private async resolveEntity(
|
||||
params: Record<string, unknown>,
|
||||
ctx: PluginRpcContext,
|
||||
write: boolean,
|
||||
): { entityType: string; entityId: number } {
|
||||
): Promise<{ entityType: string; entityId: number }> {
|
||||
const entityType = str(params.entityType, 'entityType');
|
||||
if (!META_ENTITY_TYPES.has(entityType)) {
|
||||
throw new BadParams(`invalid entityType "${entityType}" (${[...META_ENTITY_TYPES].join('|')})`);
|
||||
@@ -133,7 +133,7 @@ export class MetaRpc {
|
||||
if (tripId === undefined || !this.db.canAccessTrip(tripId, ctx.actingUserId)) {
|
||||
throw new ForbiddenResource(`no access to ${entityType} ${entityId}`);
|
||||
}
|
||||
if (write && !this.guards.canEditAs(EDIT_ACTION[entityType], tripId, ctx.actingUserId)) {
|
||||
if (write && !(await this.guards.canEditAs(EDIT_ACTION[entityType], tripId, ctx.actingUserId))) {
|
||||
throw new ForbiddenResource(`no permission to edit ${entityType} ${entityId}`);
|
||||
}
|
||||
return { entityType, entityId };
|
||||
|
||||
@@ -473,7 +473,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
// blocked dependency never leaves the chain half-activated. Only the target
|
||||
// may consent-widen; dependencies are auto-enabled at their existing grant.
|
||||
const toCheck = rootInstalled ? order : [id];
|
||||
for (const nodeId of toCheck) this.assertActivatable(nodeId, installed, nodeId === id ? consentWiden : false);
|
||||
for (const nodeId of toCheck) await this.assertActivatable(nodeId, installed, nodeId === id ? consentWiden : false);
|
||||
|
||||
// Enable dependencies first (skip ones already enabled), then the target.
|
||||
for (const nodeId of order) {
|
||||
@@ -494,7 +494,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
* plugin-API version compatibility → permission re-consent → required addon disabled →
|
||||
* missing/mismatched plugin dependency.
|
||||
*/
|
||||
private assertActivatable(id: string, installed: Map<string, PluginDepRow>, consentWiden: boolean): void {
|
||||
private async assertActivatable(id: string, installed: Map<string, PluginDepRow>, consentWiden: boolean): Promise<void> {
|
||||
const row = this.db.prepare('SELECT permissions, granted_permissions, dependencies, trek_range, api_version FROM plugins WHERE id = ?').get(id) as
|
||||
| { permissions: string; granted_permissions: string; dependencies: string | null; trek_range: string | null; api_version: number | null }
|
||||
| undefined;
|
||||
@@ -548,7 +548,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
}
|
||||
|
||||
const deps = parseDependencies(row.dependencies);
|
||||
const disabledAddons = disabledRequiredAddons(deps, (id) => this.addons.isAddonEnabled(id));
|
||||
const disabledAddons = await disabledRequiredAddons(deps, (id) => this.addons.isAddonEnabled(id));
|
||||
if (disabledAddons.length) {
|
||||
throw new PluginDependencyError(`plugin ${id} requires disabled addon(s): ${disabledAddons.join(', ')}`, 'ADDON_DISABLED', {
|
||||
addons: disabledAddons,
|
||||
@@ -774,7 +774,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
// reconstructible after an incident. This goes to the ADMIN audit log, not the
|
||||
// plugin capability log — that one answers "what have plugins done in my name?"
|
||||
// and is shown to end users; a lifecycle action by an admin does not belong there.
|
||||
this.audit.writeAudit({
|
||||
await this.audit.writeAudit({
|
||||
userId: actor.userId,
|
||||
action: 'admin.plugin_retrust',
|
||||
resource: id,
|
||||
|
||||
@@ -156,7 +156,7 @@ export class PluginsService {
|
||||
}
|
||||
}
|
||||
|
||||
list(): { enabled: boolean; devLink: boolean; ignoreTrekRange: boolean; plugins: PluginListItem[] } {
|
||||
async list(): Promise<{ enabled: boolean; devLink: boolean; ignoreTrekRange: boolean; plugins: PluginListItem[] }> {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT id, name, description, type, icon, version, status, enabled, last_error, reviewed_at, source_repo,
|
||||
@@ -169,9 +169,12 @@ export class PluginsService {
|
||||
const installed = new Map<string, PluginDepRow>(
|
||||
rows.map((r) => [r.id, { id: r.id, version: r.version, enabled: r.enabled, dependencies: r.dependencies }]),
|
||||
);
|
||||
const plugins: PluginListItem[] = rows.map((r) => {
|
||||
// A `map` callback cannot await the addon gate, so the projection runs as an
|
||||
// explicit loop — same order, same rows.
|
||||
const plugins: PluginListItem[] = [];
|
||||
for (const r of rows) {
|
||||
const deps = parseDependencies(r.dependencies);
|
||||
const disabledAddons = disabledRequiredAddons(deps, (id) => this.addons.isAddonEnabled(id));
|
||||
const disabledAddons = await disabledRequiredAddons(deps, (id) => this.addons.isAddonEnabled(id));
|
||||
const state = resolveDependencyState(deps, installed);
|
||||
// Mirrors the order of assertActivatable's gate, so the card explains the same
|
||||
// blocker the activate call would hit rather than a second, lesser one.
|
||||
@@ -194,7 +197,7 @@ export class PluginsService {
|
||||
update_hold,
|
||||
...rest
|
||||
} = r as PluginRawRow & { operator_egress?: number };
|
||||
return {
|
||||
plugins.push({
|
||||
...rest,
|
||||
operatorEgress: _oe === 1,
|
||||
egressHostCount: this.egressHostCount(r.id),
|
||||
@@ -212,8 +215,8 @@ export class PluginsService {
|
||||
? { code: update_block_code, detail: update_block_detail, version: update_block_version }
|
||||
: null,
|
||||
updateHold: update_hold === 1,
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
return { enabled: pluginsEnabled(), devLink: devLinkEnabled(), ignoreTrekRange: trekRangeBypassed(), plugins };
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user