mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
Finish the plugin RPC decorator rollout
The last 20 wire methods move onto the decorators: db.* and the three unconditional methods (DbRpc), meta.* (MetaRpc) and the host-mediated surface of users/broadcasts/notify/ai/oauth/scheduler (HostSurfaceRpc). That closes the ledger at 113/113, so the legacy has() blocks in rpc-host.ts are gone and the router is down to what was never domain-specific: build the granted subset of the dispatch map, dispatch, audit, map errors. PluginHostDepsFactory was the 26-argument wiring sheet behind those blocks. With the handlers in the domains it has two dependencies left, so it is now PluginRpcHostFactory: the plugin's own sqlite handle, the inter-plugin router bound with this plugin as the caller, and the audit sink. The 18 host-to-plugin hook calls get the same treatment. They used to spell out the fn name and the timeout at each controller, which meant nothing checked that a hook:* grant on the consent screen had a consumer behind it, that the fn matched what the SDK documents, or that two call sites agreed on the budget. PluginHooks declares all 18 with @PluginHook and performs them, and the controllers call it by name. With both halves complete, requireTotalCoverage goes on: a KNOWN_METHOD without a handler, or a hook without a consumer, now fails app boot instead of surfacing as a PERMISSION_DENIED nobody can explain.
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { PluginController, PluginMethod, PluginOpenMethod } from '../rpc-kit/decorators';
|
||||
import { asArgs, asTxOps, str } from '../rpc-params';
|
||||
import type { PluginRpcContext } from '../rpc-kit/types';
|
||||
import { readUserSettingDecrypted } from '../../plugins.service';
|
||||
|
||||
/**
|
||||
* A plugin's OWN sqlite, plus the three methods the router registers unconditionally.
|
||||
*
|
||||
* Every method reads `ctx.data` fresh. It must never be captured in a field or a
|
||||
* closure: the handle is per plugin, and disable()/re-enable builds a new host while
|
||||
* the old one's dispose() may still be closing the previous handle. A captured one
|
||||
* would be both a stale-handle bug and, in a singleton like this, a cross-plugin data
|
||||
* leak, since one instance serves every plugin.
|
||||
*/
|
||||
@PluginController()
|
||||
export class DbRpc {
|
||||
@PluginMethod('db.query', { permission: 'db:own' })
|
||||
query(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
return ctx.data.query(str(params.sql, 'sql'), asArgs(params.args));
|
||||
}
|
||||
|
||||
@PluginMethod('db.exec', { permission: 'db:own' })
|
||||
exec(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
return ctx.data.exec(str(params.sql, 'sql'), asArgs(params.args));
|
||||
}
|
||||
|
||||
@PluginMethod('db.migrate', { permission: 'db:own' })
|
||||
migrate(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
return ctx.data.migrate(str(params.id, 'id'), str(params.sql, 'sql'));
|
||||
}
|
||||
|
||||
@PluginMethod('db.tx', { permission: 'db:own' })
|
||||
tx(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
return ctx.data.tx(asTxOps(params.ops));
|
||||
}
|
||||
|
||||
/**
|
||||
* Inter-plugin call. No permission of its own: the router authorises it against
|
||||
* the declared dependency edge and the target's `provides` allowlist. The acting
|
||||
* user is forwarded so the target's export runs as the caller's user.
|
||||
*/
|
||||
@PluginOpenMethod('plugins.call')
|
||||
callPlugin(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
return ctx.plugins.call(str(params.targetId, 'targetId'), str(params.fn, 'fn'), params.args, ctx.actingUserId);
|
||||
}
|
||||
|
||||
/** Same deal: the router checks the emitter's `emits` allowlist. */
|
||||
@PluginOpenMethod('events.emit')
|
||||
emitEvent(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
ctx.plugins.emit(str(params.event, 'event'), params.payload);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin's OWN per-user settings, decrypted host-side. Unconditional and not
|
||||
* cross-tenant: it only ever returns THIS plugin's config for the acting user. A
|
||||
* userless context (a job or onLoad) has no user, so it returns undefined and the
|
||||
* plugin falls back to ctx.config.
|
||||
*/
|
||||
@PluginOpenMethod('settings.get')
|
||||
getSetting(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
if (ctx.actingUserId === undefined) return { value: undefined };
|
||||
return { value: readUserSettingDecrypted(ctx.pluginId, ctx.actingUserId, str(params.key, 'key')) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { PluginController, PluginMethod } from '../rpc-kit/decorators';
|
||||
import { PluginGuards } from '../plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../rpc-errors';
|
||||
import { asPayload, num, str } from '../rpc-params';
|
||||
import type { PluginRpcContext } from '../rpc-kit/types';
|
||||
import { budgetFor } from '../plugin-host-state';
|
||||
import { DatabaseService } from '../../../database/database.service';
|
||||
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 { PluginOAuthService } from '../../plugin-oauth.service';
|
||||
import { stripEmoji } from '../../text-sanitize';
|
||||
|
||||
/** Caps on the persistent scheduler, bounding the abuse surface. */
|
||||
const SCHED_MAX = 100; // entries per plugin
|
||||
const SCHED_NAME_MAX = 128;
|
||||
const SCHED_PAYLOAD_MAX = 8 * 1024; // 8 KB JSON
|
||||
const SCHED_EVERY_MIN = 60_000; // 1 min floor for a recurring task
|
||||
const SCHED_DUE_WINDOW = 366 * 24 * 60 * 60 * 1000; // at most ~a year out
|
||||
|
||||
const AI_TEXT_MAX = 20_000;
|
||||
|
||||
/**
|
||||
* The host-mediated surface: the user lookup, the two broadcasts, notifications, the
|
||||
* LLM bridge, the OAuth token and the persistent scheduler.
|
||||
*
|
||||
* What these have in common is that the HOST owns the dangerous half. The plugin
|
||||
* supplies a prompt, a message or a target; recipient resolution, credentials,
|
||||
* channel fan-out and the event namespace stay here, and every target is scoped to
|
||||
* something the acting user may already reach.
|
||||
*/
|
||||
@PluginController()
|
||||
export class HostSurfaceRpc {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly llmConfig: LlmConfigResolver,
|
||||
private readonly oauth: PluginOAuthService,
|
||||
private readonly guards: PluginGuards,
|
||||
) {}
|
||||
|
||||
@PluginMethod('users.getById', { permission: 'db:read:users' })
|
||||
getUser(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
// Scoped to people the acting user can actually see (themselves, or someone they
|
||||
// share a trip with), so a plugin cannot enumerate every account by looping ids.
|
||||
const id = num(params.id, 'id');
|
||||
if (ctx.actingUserId === undefined) throw new ForbiddenResource('user reads require an authenticated user context');
|
||||
if (id !== ctx.actingUserId && !this.sharesATrip(ctx.actingUserId, id)) {
|
||||
throw new ForbiddenResource(`no access to user ${id}`);
|
||||
}
|
||||
return this.db.prepare('SELECT id, username, display_name, avatar FROM users WHERE id = ?').get(id);
|
||||
}
|
||||
|
||||
@PluginMethod('ws.broadcastToTrip', { permission: 'ws:broadcast:trip' })
|
||||
broadcastToTrip(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
// The TARGET is gated like a read: only a trip room the acting user belongs to.
|
||||
// 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 (!this.db.canAccessTrip(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));
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@PluginMethod('ws.broadcastToUser', { permission: 'ws:broadcast:user' })
|
||||
broadcastToUser(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
// Authorised by identity, not by a predicate: only the acting user's own sockets.
|
||||
const userId = num(params.userId, 'userId');
|
||||
if (ctx.actingUserId === undefined || userId !== ctx.actingUserId) {
|
||||
throw new ForbiddenResource('a plugin may only broadcast to the acting user');
|
||||
}
|
||||
this.realtime.broadcastToUser(userId, {
|
||||
type: `plugin:${ctx.pluginId}`,
|
||||
event: str(params.event, 'event'),
|
||||
...asPayload(params.data),
|
||||
});
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@PluginMethod('notify.send', { permission: 'notify:send' })
|
||||
async notify(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
const actor = this.guards.requireActor(ctx, 'notification');
|
||||
const input = asPayload(params.input);
|
||||
// Emoji-stripped so a bell or push notification matches the lucide-only UI; this
|
||||
// also trims and collapses whitespace, so an all-emoji title collapses to '' and
|
||||
// is rejected below.
|
||||
const title = typeof input.title === 'string' ? stripEmoji(input.title) : '';
|
||||
const body = typeof input.body === 'string' ? stripEmoji(input.body) : '';
|
||||
if (!title || title.length > 200) throw new BadParams('notification title is required (max 200 chars)');
|
||||
if (!body || body.length > 1000) throw new BadParams('notification body is required (max 1000 chars)');
|
||||
const scope = input.scope;
|
||||
// 'admin' is deliberately absent: there is no arbitrary-recipient or
|
||||
// admin-broadcast path, so a plugin cannot spam or phish through the host.
|
||||
if (scope !== 'user' && scope !== 'trip') throw new BadParams("scope must be 'user' or 'trip'");
|
||||
const targetId = num(input.targetId, 'targetId');
|
||||
if (scope === 'user' && targetId !== actor) throw new ForbiddenResource('a plugin may only notify the acting user');
|
||||
if (scope === 'trip' && !this.db.canAccessTrip(targetId, actor)) {
|
||||
throw new ForbiddenResource('the acting user is not a member of that trip');
|
||||
}
|
||||
const link = this.safeLink(input.link);
|
||||
if (!budgetFor(ctx.pluginId).take('notify', Date.now())) {
|
||||
throw new BadParams('daily notification budget exhausted (resets at UTC midnight)');
|
||||
}
|
||||
await this.notifications.send({
|
||||
event: 'plugin_notification',
|
||||
actorId: null,
|
||||
params: { title, body, ...(link ? { link } : {}) },
|
||||
scope,
|
||||
targetId,
|
||||
inApp: link ? { navigateTarget: link } : undefined,
|
||||
});
|
||||
return { sent: true };
|
||||
}
|
||||
|
||||
@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 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`);
|
||||
this.takeAiBudget(ctx);
|
||||
const system = typeof params.system === 'string' ? params.system.slice(0, 4000) : undefined;
|
||||
const results = await createLlmClient(config).extract({
|
||||
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,
|
||||
apiKey: config.apiKey,
|
||||
text: prompt,
|
||||
});
|
||||
const first = results[0] as { text?: unknown } | undefined;
|
||||
return { text: typeof first?.text === 'string' ? first.text : '' };
|
||||
}
|
||||
|
||||
@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 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`);
|
||||
if (typeof params.jsonSchema !== 'object' || params.jsonSchema === null) {
|
||||
throw new BadParams('jsonSchema (an object) is required');
|
||||
}
|
||||
this.takeAiBudget(ctx);
|
||||
const hint = typeof params.prompt === 'string' ? params.prompt.slice(0, 4000) : '';
|
||||
const results = await createLlmClient(config).extract({
|
||||
prompt: hint || 'Extract structured data from the text into the given JSON schema.',
|
||||
jsonSchema: params.jsonSchema as object,
|
||||
model: config.model,
|
||||
baseUrl: config.baseUrl,
|
||||
apiKey: config.apiKey,
|
||||
text,
|
||||
});
|
||||
return { results };
|
||||
}
|
||||
|
||||
@PluginMethod('oauth.getToken', { permission: 'oauth:client' })
|
||||
async getOAuthToken(_params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
// A userless context (a job or scheduled task) gets null rather than a refusal,
|
||||
// matching the SDK contract and its mock: a background caller cannot do anything
|
||||
// useful with RESOURCE_FORBIDDEN. The plugin never sees the refresh token.
|
||||
if (ctx.actingUserId === undefined) return { accessToken: null };
|
||||
return { accessToken: await this.oauth.getAccessToken(ctx.pluginId, ctx.actingUserId, Date.now()) };
|
||||
}
|
||||
|
||||
@PluginMethod('scheduler.set', { permission: 'jobs:run' })
|
||||
schedulerSet(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
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 (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)`);
|
||||
const existing = this.db
|
||||
.prepare('SELECT id FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?')
|
||||
.get(ctx.pluginId, name) as { id: number } | undefined;
|
||||
if (!existing) {
|
||||
const n = (this.db.prepare('SELECT COUNT(*) AS c FROM plugin_scheduled_tasks WHERE plugin_id = ?').get(ctx.pluginId) as { c: number }).c;
|
||||
if (n >= SCHED_MAX) throw new BadParams(`too many scheduled tasks (max ${SCHED_MAX})`);
|
||||
}
|
||||
// Upsert by (plugin, name): re-scheduling the same name replaces it.
|
||||
this.db
|
||||
.prepare(`INSERT INTO plugin_scheduled_tasks (plugin_id, name, due_at, payload, every_ms) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (plugin_id, name) DO UPDATE SET due_at = excluded.due_at, payload = excluded.payload, every_ms = excluded.every_ms`)
|
||||
.run(ctx.pluginId, name, Math.max(dueAt, Date.now()), json, everyMs ?? null);
|
||||
return { scheduled: true };
|
||||
}
|
||||
|
||||
@PluginMethod('scheduler.cancel', { permission: 'jobs:run' })
|
||||
schedulerCancel(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const r = this.db
|
||||
.prepare('DELETE FROM plugin_scheduled_tasks WHERE plugin_id = ? AND name = ?')
|
||||
.run(ctx.pluginId, str(params.name, 'name'));
|
||||
return { cancelled: r.changes > 0 };
|
||||
}
|
||||
|
||||
/** Two users share a trip when both are owner-or-member of the same one. */
|
||||
private sharesATrip(actingUserId: number, targetUserId: number): boolean {
|
||||
return !!this.db
|
||||
.prepare(
|
||||
`SELECT 1 FROM trips t
|
||||
LEFT JOIN trip_members m1 ON m1.trip_id = t.id AND m1.user_id = ?
|
||||
LEFT JOIN trip_members m2 ON m2.trip_id = t.id AND m2.user_id = ?
|
||||
WHERE (t.user_id = ? OR m1.user_id IS NOT NULL)
|
||||
AND (t.user_id = ? OR m2.user_id IS NOT NULL)
|
||||
LIMIT 1`,
|
||||
)
|
||||
.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');
|
||||
return config;
|
||||
}
|
||||
|
||||
private takeAiBudget(ctx: PluginRpcContext): void {
|
||||
if (!budgetFor(ctx.pluginId).take('ai', Date.now())) {
|
||||
throw new BadParams('daily AI budget exhausted (resets at UTC midnight)');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In-app paths only. A bare startsWith check misses `/\evil.com` and `/<tab>/…`,
|
||||
* which browsers normalize to protocol-relative, so resolve against a throwaway
|
||||
* origin and require the result to stay on it.
|
||||
*/
|
||||
private safeLink(value: unknown): string | undefined {
|
||||
if (typeof value !== 'string' || value === '') return undefined;
|
||||
let safe: string | null = null;
|
||||
try {
|
||||
const u = new URL(value, 'http://x.invalid');
|
||||
if (u.origin === 'http://x.invalid') safe = u.pathname + u.search + u.hash;
|
||||
} catch {
|
||||
/* invalid, rejected below */
|
||||
}
|
||||
if (!safe) throw new BadParams('link must be an in-app path starting with /');
|
||||
return safe.slice(0, 512);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { PluginController, PluginMethod } from '../rpc-kit/decorators';
|
||||
import { PluginGuards } from '../plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../rpc-errors';
|
||||
import { num, str } from '../rpc-params';
|
||||
import type { PluginRpcContext } from '../rpc-kit/types';
|
||||
import { DatabaseService } from '../../../database/database.service';
|
||||
|
||||
/** Core entities a plugin may attach its own db:meta to. */
|
||||
const META_ENTITY_TYPES: ReadonlySet<string> = new Set(['trip', 'place', 'day', 'reservation', 'accommodation']);
|
||||
|
||||
// Quotas: a cheap disk-DoS guard on the shared trek.db volume. Generous for real use,
|
||||
// small enough to bound abuse.
|
||||
const META_VALUE_MAX = 64 * 1024; // serialized JSON bytes per value
|
||||
const META_KEY_MAX = 256; // key length (the key is attacker-controlled too)
|
||||
const META_KEYS_MAX = 100; // keys per (plugin, entity)
|
||||
|
||||
/** Which edit permission an entity type rides on. Accommodations ride on days. */
|
||||
const EDIT_ACTION: Record<string, string> = {
|
||||
trip: 'trip_edit',
|
||||
place: 'place_edit',
|
||||
reservation: 'reservation_edit',
|
||||
day: 'day_edit',
|
||||
accommodation: 'day_edit',
|
||||
};
|
||||
|
||||
/** Each of these tables has a NOT NULL trip_id, so the gate resolves the owning trip. */
|
||||
const ENTITY_TABLE: Record<string, string> = {
|
||||
place: 'places',
|
||||
day: 'days',
|
||||
reservation: 'reservations',
|
||||
accommodation: 'day_accommodations',
|
||||
};
|
||||
|
||||
/**
|
||||
* A plugin's OWN namespaced key/value store, attached to a core entity (#plugins).
|
||||
*
|
||||
* The rows are not core data, but the entity they hang off must belong to a trip the
|
||||
* acting user can access, so a plugin cannot stash or read metadata against another
|
||||
* tenant's rows. Writes additionally need that entity's edit permission, so a
|
||||
* read-only member cannot overwrite metadata an editor created.
|
||||
*
|
||||
* Every row is tagged with the plugin id, so one plugin never sees another's keys.
|
||||
*/
|
||||
@PluginController()
|
||||
export class MetaRpc {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly guards: PluginGuards,
|
||||
) {}
|
||||
|
||||
@PluginMethod('meta.get', { permission: 'db:meta' })
|
||||
get(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = 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;
|
||||
if (!row) return null;
|
||||
try {
|
||||
return JSON.parse(row.value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod('meta.set', { permission: 'db:meta' })
|
||||
set(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = 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);
|
||||
if (json.length > META_VALUE_MAX) throw new BadParams(`metadata value too large (>${META_VALUE_MAX} bytes)`);
|
||||
const exists = this.db
|
||||
.prepare('SELECT 1 FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=? AND key=?')
|
||||
.get(ctx.pluginId, entityType, entityId, key);
|
||||
if (!exists) {
|
||||
const { n } = this.db
|
||||
.prepare('SELECT COUNT(*) AS n FROM plugin_entity_metadata WHERE plugin_id=? AND entity_type=? AND entity_id=?')
|
||||
.get(ctx.pluginId, entityType, entityId) as { n: number };
|
||||
if (n >= META_KEYS_MAX) throw new BadParams(`too many metadata keys on this ${entityType} (max ${META_KEYS_MAX})`);
|
||||
}
|
||||
this.db
|
||||
.prepare(`INSERT INTO plugin_entity_metadata (plugin_id, entity_type, entity_id, key, value, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT(plugin_id, entity_type, entity_id, key)
|
||||
DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`)
|
||||
.run(ctx.pluginId, entityType, entityId, key, json);
|
||||
return { key, value: params.value ?? null };
|
||||
}
|
||||
|
||||
@PluginMethod('meta.list', { permission: 'db:meta' })
|
||||
list(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = 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 }>;
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const r of rows) {
|
||||
try {
|
||||
out[r.key] = JSON.parse(r.value);
|
||||
} catch {
|
||||
out[r.key] = null;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@PluginMethod('meta.delete', { permission: 'db:meta' })
|
||||
delete(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
const { entityType, entityId } = 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'));
|
||||
return { deleted: res.changes > 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the target and gates it: a supported entity type, an entity that
|
||||
* resolves to a trip the acting user can access, and for a write that entity's own
|
||||
* edit permission.
|
||||
*/
|
||||
private resolveEntity(
|
||||
params: Record<string, unknown>,
|
||||
ctx: PluginRpcContext,
|
||||
write: boolean,
|
||||
): { 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('|')})`);
|
||||
}
|
||||
const entityId = num(params.entityId, 'entityId');
|
||||
if (ctx.actingUserId === undefined) throw new ForbiddenResource('metadata requires an authenticated user context');
|
||||
const tripId = this.entityTrip(entityType, entityId);
|
||||
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)) {
|
||||
throw new ForbiddenResource(`no permission to edit ${entityType} ${entityId}`);
|
||||
}
|
||||
return { entityType, entityId };
|
||||
}
|
||||
|
||||
private entityTrip(entityType: string, entityId: number): number | undefined {
|
||||
if (entityType === 'trip') {
|
||||
return (this.db.prepare('SELECT id FROM trips WHERE id = ?').get(entityId) as { id: number } | undefined)?.id;
|
||||
}
|
||||
// The table name comes from a fixed map, never from the request.
|
||||
const table = ENTITY_TABLE[entityType];
|
||||
return (this.db.prepare(`SELECT trip_id FROM ${table} WHERE id = ?`).get(entityId) as { trip_id: number } | undefined)?.trip_id;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user