mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
style: format server and shared with prettier
A mechanical prettier --write over server/src, server/tests, server/scripts and shared/src with the workspaces' .prettierrc; nothing but layout and import order changes, and every file keeps the same set of imports. shared is formatted throughout and its format baseline is empty. The server baseline keeps the 35 files that Prettier would grow past their lint:size limit (they need a split first, which is not a formatting change), and the generated entity files stay as their generator writes them.
This commit is contained in:
@@ -54,7 +54,11 @@ export class DailyBudget {
|
||||
private ai = 0;
|
||||
private notify = 0;
|
||||
|
||||
constructor(private readonly cfg: DailyBudgetConfig, now: number, seed?: { ai?: number; notify?: number }) {
|
||||
constructor(
|
||||
private readonly cfg: DailyBudgetConfig,
|
||||
now: number,
|
||||
seed?: { ai?: number; notify?: number },
|
||||
) {
|
||||
this.day = utcDay(now);
|
||||
this.ai = seed?.ai ?? 0;
|
||||
this.notify = seed?.notify ?? 0;
|
||||
@@ -85,6 +89,12 @@ export class DailyBudget {
|
||||
/** Current usage snapshot for the admin view (read-only). */
|
||||
used(now: number): { day: string; ai: number; aiMax: number; notify: number; notifyMax: number } {
|
||||
this.rollover(now);
|
||||
return { day: this.day, ai: this.ai, aiMax: this.cfg.aiPerDay, notify: this.notify, notifyMax: this.cfg.notifyPerDay };
|
||||
return {
|
||||
day: this.day,
|
||||
ai: this.ai,
|
||||
aiMax: this.cfg.aiPerDay,
|
||||
notify: this.notify,
|
||||
notifyMax: this.cfg.notifyPerDay,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import crypto from 'node:crypto';
|
||||
import type {
|
||||
PluginCapabilityAuditRepository,
|
||||
AuditForPluginRow,
|
||||
AuditForUserRow,
|
||||
} from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { METHOD_PERMISSION } from '../protocol/envelope';
|
||||
import type { PluginCapabilityAuditRepository, AuditForPluginRow, AuditForUserRow } from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Host-side, hash-chained capability audit (#plugins, L1 hardening).
|
||||
@@ -26,10 +31,12 @@ export function auditResource(method: string, params: Record<string, unknown>):
|
||||
if (method === 'trips.create') return 'trips:new';
|
||||
if (method === 'trips.listMine') return 'trips:all';
|
||||
if (method === 'reservations.listMine') return 'reservations:all';
|
||||
if (method.startsWith('trips.') || method.startsWith('reservations.') || method.startsWith('accommodations.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('trips.') || method.startsWith('reservations.') || method.startsWith('accommodations.'))
|
||||
return `trip:${params.tripId ?? '?'}`;
|
||||
if (method === 'costs.listMine') return 'costs:all';
|
||||
if (method.startsWith('costs.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('places.') || method.startsWith('days.') || method.startsWith('itinerary.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('places.') || method.startsWith('days.') || method.startsWith('itinerary.'))
|
||||
return `trip:${params.tripId ?? '?'}`;
|
||||
if (method.startsWith('packing.') || method.startsWith('files.')) return `trip:${params.tripId ?? '?'}`;
|
||||
if (method === 'journal.listMine') return 'journal:all';
|
||||
if (method.startsWith('journal.')) return `journal:entry:${params.entryId ?? params.journeyId ?? '?'}`;
|
||||
@@ -50,7 +57,10 @@ export function auditResource(method: string, params: Record<string, unknown>):
|
||||
if (method === 'users.getById') return `user:${params.id ?? '?'}`;
|
||||
if (method === 'ws.broadcastToTrip') return `trip:${params.tripId ?? '?'}`;
|
||||
if (method === 'ws.broadcastToUser') return `user:${params.userId ?? '?'}`;
|
||||
if (method === 'notify.send') { const i = (params.input ?? {}) as Record<string, unknown>; return `notify:${i.scope ?? '?'}:${i.targetId ?? '?'}`; }
|
||||
if (method === 'notify.send') {
|
||||
const i = (params.input ?? {}) as Record<string, unknown>;
|
||||
return `notify:${i.scope ?? '?'}:${i.targetId ?? '?'}`;
|
||||
}
|
||||
if (method === 'ai.complete' || method === 'ai.extract') return 'ai:invoke';
|
||||
if (method === 'oauth.getToken') return 'oauth:token';
|
||||
if (method.startsWith('scheduler.')) return `scheduler:${params.name ?? '?'}`;
|
||||
@@ -142,7 +152,11 @@ function envInt(name: string, def: number): number {
|
||||
|
||||
/** Keep only the newest `MAX_AUDIT_ROWS` rows for a plugin. Called amortised from
|
||||
* appendAudit; exported for tests. No-op when disabled or under the cap. */
|
||||
export async function pruneAudit(audit: PluginCapabilityAuditRepository, pluginId: string, keep = MAX_AUDIT_ROWS): Promise<void> {
|
||||
export async function pruneAudit(
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
pluginId: string,
|
||||
keep = MAX_AUDIT_ROWS,
|
||||
): Promise<void> {
|
||||
if (keep <= 0) return;
|
||||
await audit.pruneKeepingNewest(pluginId, keep);
|
||||
}
|
||||
@@ -167,7 +181,10 @@ export async function appendAudit(audit: PluginCapabilityAuditRepository, e: Aud
|
||||
const prev = (await audit.lastHash(e.pluginId)) ?? '';
|
||||
const ts = new Date().toISOString();
|
||||
const row = JSON.stringify([e.pluginId, e.actingUserId ?? null, e.method, e.resource ?? null, e.code, ts]);
|
||||
const hash = crypto.createHash('sha256').update(prev + row).digest('hex');
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
.update(prev + row)
|
||||
.digest('hex');
|
||||
await audit.insertRow({
|
||||
plugin_id: e.pluginId,
|
||||
acting_user_id: e.actingUserId ?? null,
|
||||
@@ -181,20 +198,30 @@ export async function appendAudit(audit: PluginCapabilityAuditRepository, e: Aud
|
||||
});
|
||||
// Amortised retention: prune roughly every PRUNE_EVERY appends per plugin.
|
||||
const n = (appendsSincePrune.get(e.pluginId) ?? 0) + 1;
|
||||
if (n >= PRUNE_EVERY) { appendsSincePrune.set(e.pluginId, 0); await pruneAudit(audit, e.pluginId); }
|
||||
else appendsSincePrune.set(e.pluginId, n);
|
||||
if (n >= PRUNE_EVERY) {
|
||||
appendsSincePrune.set(e.pluginId, 0);
|
||||
await pruneAudit(audit, e.pluginId);
|
||||
} else appendsSincePrune.set(e.pluginId, n);
|
||||
}
|
||||
|
||||
/** Read the most recent audit rows across ALL plugins for one acting user — the
|
||||
* "what have plugins done in my name?" view. This is what legitimizes the broad
|
||||
* read grants: the user, not just the admin, can see every plugin action bound to
|
||||
* them. Joined with the plugin name for display; capped. */
|
||||
export async function readAuditForUser(audit: PluginCapabilityAuditRepository, userId: number, limit = 200): Promise<AuditForUserRow[]> {
|
||||
export async function readAuditForUser(
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
userId: number,
|
||||
limit = 200,
|
||||
): Promise<AuditForUserRow[]> {
|
||||
return audit.forUser(userId, limit);
|
||||
}
|
||||
|
||||
/** Read the most recent audit rows for a plugin (admin view). */
|
||||
export async function readAudit(audit: PluginCapabilityAuditRepository, pluginId: string, limit = 200): Promise<AuditForPluginRow[]> {
|
||||
export async function readAudit(
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
pluginId: string,
|
||||
limit = 200,
|
||||
): Promise<AuditForPluginRow[]> {
|
||||
return audit.forPlugin(pluginId, limit);
|
||||
}
|
||||
|
||||
@@ -214,13 +241,25 @@ export async function readAudit(audit: PluginCapabilityAuditRepository, pluginId
|
||||
* admin "verify audit integrity" surface would want exactly this.
|
||||
*/
|
||||
export function verifyChain(
|
||||
rows: Array<{ plugin_id: string; acting_user_id: number | null; method: string; resource: string | null; code: string; ts: string; prev_hash: string | null; hash: string }>,
|
||||
rows: Array<{
|
||||
plugin_id: string;
|
||||
acting_user_id: number | null;
|
||||
method: string;
|
||||
resource: string | null;
|
||||
code: string;
|
||||
ts: string;
|
||||
prev_hash: string | null;
|
||||
hash: string;
|
||||
}>,
|
||||
): boolean {
|
||||
let prev = '';
|
||||
for (const r of rows) {
|
||||
if ((r.prev_hash ?? '') !== prev) return false;
|
||||
const row = JSON.stringify([r.plugin_id, r.acting_user_id ?? null, r.method, r.resource ?? null, r.code, r.ts]);
|
||||
const hash = crypto.createHash('sha256').update(prev + row).digest('hex');
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
.update(prev + row)
|
||||
.digest('hex');
|
||||
if (hash !== r.hash) return false;
|
||||
prev = r.hash;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Database as Db, Statement } from 'better-sqlite3';
|
||||
import { openDatabase } from '../../../db/connection';
|
||||
import { pluginDataDir, pluginDbFile, pluginsDataRoot } from '../paths';
|
||||
import { splitAfterSemicolons } from './sql-script';
|
||||
|
||||
import type { Database as Db, Statement } from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* A plugin's own sqlite database (#plugins, db:own). The HOST owns the handle;
|
||||
* the plugin child never gets a path or a connection — it can only reach this
|
||||
@@ -81,7 +82,11 @@ const openDbs = new Set<PluginDataDb>();
|
||||
* Best-effort per handle; never throws. */
|
||||
export function checkpointAllPluginDataDbs(): void {
|
||||
for (const d of openDbs) {
|
||||
try { d.checkpoint(); } catch { /* a busy/closed handle is skipped, not fatal */ }
|
||||
try {
|
||||
d.checkpoint();
|
||||
} catch {
|
||||
/* a busy/closed handle is skipped, not fatal */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,9 +107,7 @@ export class PluginDataDb {
|
||||
const pageSize = Number(this.db.pragma('page_size', { simple: true })) || 4096;
|
||||
this.db.pragma(`max_page_count = ${Math.max(1, Math.floor(QUOTA_BYTES / pageSize))}`);
|
||||
// Track applied migrations so db.migrate is idempotent per (plugin, id).
|
||||
this.db.exec(
|
||||
`CREATE TABLE IF NOT EXISTS _plugin_migrations (id TEXT PRIMARY KEY, applied_at INTEGER)`,
|
||||
);
|
||||
this.db.exec(`CREATE TABLE IF NOT EXISTS _plugin_migrations (id TEXT PRIMARY KEY, applied_at INTEGER)`);
|
||||
}
|
||||
|
||||
private guard(sql: string): void {
|
||||
@@ -327,11 +330,21 @@ export function snapshotAllPluginDataDbs(destRoot: string): void {
|
||||
// WAL loses committed transactions, whereas the .db + its WAL is a recoverable set.
|
||||
let foldedIn = false;
|
||||
if (open) {
|
||||
try { open.snapshotInto(path.join(destDir, 'plugin.db')); foldedIn = true; }
|
||||
catch {
|
||||
try { open.checkpoint(); foldedIn = true; } catch { /* WAL not folded — keep sidecars */ }
|
||||
try { fs.copyFileSync(path.join(srcDir, 'plugin.db'), path.join(destDir, 'plugin.db')); }
|
||||
catch { /* unreadable live db — best effort */ }
|
||||
try {
|
||||
open.snapshotInto(path.join(destDir, 'plugin.db'));
|
||||
foldedIn = true;
|
||||
} catch {
|
||||
try {
|
||||
open.checkpoint();
|
||||
foldedIn = true;
|
||||
} catch {
|
||||
/* WAL not folded — keep sidecars */
|
||||
}
|
||||
try {
|
||||
fs.copyFileSync(path.join(srcDir, 'plugin.db'), path.join(destDir, 'plugin.db'));
|
||||
} catch {
|
||||
/* unreadable live db — best effort */
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const f of fs.readdirSync(srcDir, { withFileTypes: true })) {
|
||||
@@ -348,7 +361,9 @@ export function snapshotAllPluginDataDbs(destRoot: string): void {
|
||||
try {
|
||||
if (f.isDirectory()) fs.cpSync(src, dest, { recursive: true });
|
||||
else fs.copyFileSync(src, dest);
|
||||
} catch { /* skip an unreadable entry rather than fail the whole backup */ }
|
||||
} catch {
|
||||
/* skip an unreadable entry rather than fail the whole backup */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { PluginDataDb } from './plugin-data.service';
|
||||
import { DailyBudget, DEFAULT_DAILY_BUDGET } from './daily-budget';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { DailyBudget, DEFAULT_DAILY_BUDGET } from './daily-budget';
|
||||
import { PluginDataDb } from './plugin-data.service';
|
||||
|
||||
/**
|
||||
* Process-wide plugin host state, deliberately module-level (NOT a Nest
|
||||
@@ -64,7 +64,8 @@ async function seedBudget(id: string, audit: PluginCapabilityAuditRepository): P
|
||||
const now = Date.now();
|
||||
const since = new Date(now).toISOString().slice(0, 10) + 'T00:00:00';
|
||||
const rows = await audit.budgetSeed(id, since);
|
||||
let ai = 0, notify = 0;
|
||||
let ai = 0,
|
||||
notify = 0;
|
||||
for (const r of rows) {
|
||||
if (r.method === 'notify.send') notify += r.n;
|
||||
else ai += r.n; // ai.complete + ai.extract
|
||||
@@ -86,6 +87,9 @@ export async function budgetFor(id: string, audit: PluginCapabilityAuditReposito
|
||||
}
|
||||
|
||||
/** Today's broker usage for one plugin (admin view). Seeds the counter if unseen. */
|
||||
export async function pluginBudgetUsage(id: string, audit: PluginCapabilityAuditRepository): Promise<ReturnType<DailyBudget['used']>> {
|
||||
export async function pluginBudgetUsage(
|
||||
id: string,
|
||||
audit: PluginCapabilityAuditRepository,
|
||||
): Promise<ReturnType<DailyBudget['used']>> {
|
||||
return (await budgetFor(id, audit)).used(Date.now());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CronJob, validateCronExpression } from 'cron';
|
||||
import { JOBS_PERMISSION } from '../protocol/envelope';
|
||||
|
||||
import { CronJob, validateCronExpression } from 'cron';
|
||||
|
||||
/**
|
||||
* Host-side scheduler for a plugin's declared background jobs (#plugins).
|
||||
*
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginCapabilityAudit } from '../../../db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { PluginRpcHost } from './rpc-host';
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import { PluginRpcRegistryService } from '../../../nest-rpc/rpc-kit/registry.service';
|
||||
import { appendAudit } from './plugin-audit';
|
||||
import { getPluginDataDb } from './plugin-host-state';
|
||||
import { PluginRpcHost } from './rpc-host';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
|
||||
/** Routes inter-plugin calls/events; supplied by PluginRuntimeService (owns the supervisor). */
|
||||
export interface PluginCallRouter {
|
||||
callPlugin(callerId: string, targetId: string, fn: string, args: unknown, actingUserId: number | undefined): Promise<unknown>;
|
||||
callPlugin(
|
||||
callerId: string,
|
||||
targetId: string,
|
||||
fn: string,
|
||||
args: unknown,
|
||||
actingUserId: number | undefined,
|
||||
): Promise<unknown>;
|
||||
emitPluginEvent(sourceId: string, event: string, payload: unknown): Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,10 @@ export class RpcRateLimiter {
|
||||
private readonly bucket: TokenBucket;
|
||||
private inFlight = 0;
|
||||
|
||||
constructor(private readonly cfg: RpcLimitConfig, now: number) {
|
||||
constructor(
|
||||
private readonly cfg: RpcLimitConfig,
|
||||
now: number,
|
||||
) {
|
||||
this.bucket = new TokenBucket(cfg.burst, cfg.perSec, now);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { BadParams, ForbiddenResource } from '../../../nest-rpc/rpc-errors';
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import {
|
||||
KNOWN_METHODS,
|
||||
METHOD_PERMISSION,
|
||||
@@ -6,11 +8,9 @@ import {
|
||||
type RpcRequest,
|
||||
type RpcResponse,
|
||||
} from '../protocol/envelope';
|
||||
import type { PluginDataDb } from './plugin-data.service';
|
||||
import { auditResource, isAuditable } from './plugin-audit';
|
||||
import { BadParams, ForbiddenResource } from '../../../nest-rpc/rpc-errors';
|
||||
import { shapePluginOutput } from '../protocol/output-contract';
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import { auditResource, isAuditable } from './plugin-audit';
|
||||
import type { PluginDataDb } from './plugin-data.service';
|
||||
|
||||
// Both used to be declared here. They now live in rpc-errors.ts so decorated
|
||||
// *.rpc.ts handlers can throw them without importing the router, and are re-exported
|
||||
@@ -50,7 +50,13 @@ export interface HostDeps {
|
||||
/** Publish an event from this host's plugin to its subscribed dependents. */
|
||||
emitPluginEvent(event: string, payload: unknown): Promise<void>;
|
||||
/** Optional sink for the capability audit log (host-side, hash-chained). */
|
||||
audit?(entry: { pluginId: string; actingUserId?: number; method: string; resource: string | null; code: string }): Promise<void>;
|
||||
audit?(entry: {
|
||||
pluginId: string;
|
||||
actingUserId?: number;
|
||||
method: string;
|
||||
resource: string | null;
|
||||
code: string;
|
||||
}): Promise<void>;
|
||||
}
|
||||
|
||||
type Handler = (params: Record<string, unknown>, actingUserId: number | undefined) => unknown;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { PluginController, PluginMethod, PluginOpenMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import { asArgs, asTxOps, str } from '../../../../nest-rpc/rpc-params';
|
||||
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
|
||||
import { asArgs, asTxOps, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { PluginUserSettingsService } from '../../plugin-user-settings.service';
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import { PluginCapabilityAudit } from '../../../../db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginScheduledTasks } from '../../../../db/entities/PluginScheduledTasks.entity';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import { Users } from '../../../../db/entities/Users.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import type { PluginScheduledTasksRepository } from '../../../../db/repositories/PluginScheduledTasks.repository';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import type { UsersRepository } from '../../../../db/repositories/Users.repository';
|
||||
import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors';
|
||||
import { asPayload, num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
|
||||
import { budgetFor } from '../plugin-host-state';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginCapabilityAudit } from '../../../../db/entities/PluginCapabilityAudit.entity';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { Users } from '../../../../db/entities/Users.entity';
|
||||
import type { UsersRepository } from '../../../../db/repositories/Users.repository';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import { PluginScheduledTasks } from '../../../../db/entities/PluginScheduledTasks.entity';
|
||||
import type { PluginScheduledTasksRepository } from '../../../../db/repositories/PluginScheduledTasks.repository';
|
||||
import { RealtimeService } from '../../../realtime/realtime.service';
|
||||
import { NotificationsService } from '../../../notifications/notifications.service';
|
||||
import { LlmConfigResolver } from '../../../llm-parse/llm-config.resolver';
|
||||
import { createLlmClient } from '../../../llm-parse/llm-client.factory';
|
||||
import { asPayload, num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { UnreadableLlmResponse } from '../../../llm-parse/clients/openai-compatible.client';
|
||||
import { createLlmClient } from '../../../llm-parse/llm-client.factory';
|
||||
import type { ResolvedLlmConfig } from '../../../llm-parse/llm-config';
|
||||
import { LlmConfigResolver } from '../../../llm-parse/llm-config.resolver';
|
||||
import type { LlmExtractionInput } from '../../../llm-parse/llm-provider.interface';
|
||||
import { NotificationsService } from '../../../notifications/notifications.service';
|
||||
import { RealtimeService } from '../../../realtime/realtime.service';
|
||||
import { PluginOAuthService } from '../../oauth/plugin-oauth.service';
|
||||
import { stripEmoji } from '../../text-sanitize';
|
||||
import { budgetFor } from '../plugin-host-state';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
|
||||
/** Caps on the persistent scheduler, bounding the abuse surface. */
|
||||
const SCHED_MAX = 100; // entries per plugin
|
||||
@@ -82,7 +82,8 @@ export class HostSurfaceRpc {
|
||||
// Namespacing the event type alone does not cross the membership boundary.
|
||||
const tripId = num(params.tripId, 'tripId');
|
||||
if (ctx.actingUserId === undefined) throw new ForbiddenResource('broadcasts require an authenticated user context');
|
||||
if (!(await this.trips.findAccessible(tripId, ctx.actingUserId))) throw new ForbiddenResource(`no access to trip ${tripId}`);
|
||||
if (!(await this.trips.findAccessible(tripId, ctx.actingUserId)))
|
||||
throw new ForbiddenResource(`no access to trip ${tripId}`);
|
||||
// The host forces the plugin:{id}:{event} namespace, so a plugin cannot forge a
|
||||
// core event.
|
||||
this.realtime.broadcast(tripId, `plugin:${ctx.pluginId}:${str(params.event, 'event')}`, asPayload(params.data));
|
||||
@@ -149,7 +150,9 @@ export class HostSurfaceRpc {
|
||||
await this.takeAiBudget(ctx);
|
||||
const system = typeof params.system === 'string' ? params.system.slice(0, 4000) : undefined;
|
||||
const results = await this.runModel(config, {
|
||||
prompt: system || 'You are a helpful assistant. Reply with a JSON object of the form {"text": "..."} whose "text" field holds your answer.',
|
||||
prompt:
|
||||
system ||
|
||||
'You are a helpful assistant. Reply with a JSON object of the form {"text": "..."} whose "text" field holds your answer.',
|
||||
jsonSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
|
||||
model: config.model,
|
||||
baseUrl: config.baseUrl,
|
||||
@@ -197,13 +200,16 @@ export class HostSurfaceRpc {
|
||||
const name = str(params.name, 'name');
|
||||
const dueAt = num(params.dueAt, 'dueAt');
|
||||
const everyMs = params.everyMs != null ? num(params.everyMs, 'everyMs') : undefined;
|
||||
if (!name || name.length > SCHED_NAME_MAX) throw new BadParams(`scheduler name is required (max ${SCHED_NAME_MAX} chars)`);
|
||||
if (!Number.isFinite(dueAt) || dueAt > Date.now() + SCHED_DUE_WINDOW) throw new BadParams('scheduler dueAt out of range');
|
||||
if (!name || name.length > SCHED_NAME_MAX)
|
||||
throw new BadParams(`scheduler name is required (max ${SCHED_NAME_MAX} chars)`);
|
||||
if (!Number.isFinite(dueAt) || dueAt > Date.now() + SCHED_DUE_WINDOW)
|
||||
throw new BadParams('scheduler dueAt out of range');
|
||||
if (everyMs !== undefined && (!Number.isFinite(everyMs) || everyMs < SCHED_EVERY_MIN)) {
|
||||
throw new BadParams(`recurring interval must be >= ${SCHED_EVERY_MIN} ms`);
|
||||
}
|
||||
const json = JSON.stringify(params.payload ?? null);
|
||||
if (json.length > SCHED_PAYLOAD_MAX) throw new BadParams(`scheduler payload too large (max ${SCHED_PAYLOAD_MAX} bytes)`);
|
||||
if (json.length > SCHED_PAYLOAD_MAX)
|
||||
throw new BadParams(`scheduler payload too large (max ${SCHED_PAYLOAD_MAX} bytes)`);
|
||||
// HR5/HR6/HR7 — Plan 3j Task 7 fix (must-land 3): one atomic call, not
|
||||
// three separately-awaited ones (task-7-review.md's concurrent-cap-bypass).
|
||||
// Upsert by (plugin, name): re-scheduling the same name replaces it.
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import { DayAccommodations } from '../../../../db/entities/DayAccommodations.entity';
|
||||
import { Days } from '../../../../db/entities/Days.entity';
|
||||
import { Places } from '../../../../db/entities/Places.entity';
|
||||
import { PluginEntityMetadata } from '../../../../db/entities/PluginEntityMetadata.entity';
|
||||
import { Reservations } from '../../../../db/entities/Reservations.entity';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import type { DayAccommodationsRepository } from '../../../../db/repositories/DayAccommodations.repository';
|
||||
import type { DaysRepository } from '../../../../db/repositories/Days.repository';
|
||||
import type { PlacesRepository } from '../../../../db/repositories/Places.repository';
|
||||
import type { PluginEntityMetadataRepository } from '../../../../db/repositories/PluginEntityMetadata.repository';
|
||||
import type { ReservationsRepository } from '../../../../db/repositories/Reservations.repository';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors';
|
||||
import { num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators';
|
||||
import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types';
|
||||
import { PluginEntityMetadata } from '../../../../db/entities/PluginEntityMetadata.entity';
|
||||
import type { PluginEntityMetadataRepository } from '../../../../db/repositories/PluginEntityMetadata.repository';
|
||||
import { Trips } from '../../../../db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../../../db/repositories/Trips.repository';
|
||||
import { Places } from '../../../../db/entities/Places.entity';
|
||||
import type { PlacesRepository } from '../../../../db/repositories/Places.repository';
|
||||
import { Days } from '../../../../db/entities/Days.entity';
|
||||
import type { DaysRepository } from '../../../../db/repositories/Days.repository';
|
||||
import { Reservations } from '../../../../db/entities/Reservations.entity';
|
||||
import type { ReservationsRepository } from '../../../../db/repositories/Reservations.repository';
|
||||
import { DayAccommodations } from '../../../../db/entities/DayAccommodations.entity';
|
||||
import type { DayAccommodationsRepository } from '../../../../db/repositories/DayAccommodations.repository';
|
||||
import { num, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
|
||||
/** Core entities a plugin may attach its own db:meta to. */
|
||||
const META_ENTITY_TYPES: ReadonlySet<string> = new Set(['trip', 'place', 'day', 'reservation', 'accommodation']);
|
||||
|
||||
Reference in New Issue
Block a user