Repository navigation
Expand file tree
/
Copy pathaudit-plugin.ts
More file actions
865 lines (840 loc) · 43 KB
/
Copy pathaudit-plugin.ts
File metadata and controls
865 lines (840 loc) · 43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type { Plugin, PluginContext } from '@objectstack/core';
import {
effectiveTenancyPosture,
resolveLocalizationContext,
type TenancyPostureSource,
type TenancyServiceResolver,
} from '@objectstack/core';
import type {
IAuthService,
IDataEngine,
IHttpServer,
II18nService,
ISecurityService,
ISharingService,
} from '@objectstack/spec/contracts';
import { SysAuditLog, SysActivity, SysComment, SysCommentReaction } from './objects/index.js';
import { SysAuditLogDetailPage } from './sys-audit-log.page.js';
// `sys_notification` was parked here "until that [ADR-0030] migration lands".
// It has landed, so the contribution moved to @objectstack/service-messaging —
// the service that writes the row on every `emit()` (#4154). This plugin never
// wrote it directly (it routes through messaging's ingress, see
// `getMessaging()` in audit-writers.ts), and it is an OPTIONAL pair in the CLI,
// so registering another service's ingress object here made that service's
// core path depend on this plugin being installed. `sys_attachment` moved to
// @objectstack/service-storage for the same ownership reason (ADR-0052 §3: a
// file↔record link belongs with storage, not the compliance ledger).
import { installAuditWriters, type AuditI18nSurface, type MessagingEmitSurface } from './audit-writers.js';
import { installReadAuditWriter, type ReadAuditWriterHandle } from './read-audit.js';
import { createAuthEventAuditSink } from './auth-event-audit.js';
import { createActionInvocationAuditWriter } from './action-invocation-audit.js';
import { installCommentAccessHooks, installCommentReadVisibility } from './comment-access-hooks.js';
import {
COMMENT_REACTION_REMOVE_ROUTE,
platformCallerResolver,
registerCommentReactionRoutes,
type CommentReactionEngine,
} from './comment-reaction-routes.js';
import { admitMentionRecipients } from './mention-recipient-gate.js';
import { installActivityReadVisibility } from './activity-read-visibility.js';
import { installActivityFieldRedaction } from './activity-field-redaction.js';
import { installActivitySummaryLocale } from './activity-summary-message.js';
import { installAuditLogFieldRedaction } from './audit-log-field-redaction.js';
import { installAuditLogReadVisibility } from './audit-log-read-visibility.js';
import type { FieldVisibilitySource } from './served-fields.js';
import { installParentFieldQueryGuards } from './parent-field-query-guard.js';
import type { ParentObjectReadAdmission } from './parent-record-read-gate.js';
/**
* [#8992] Read/view audit configuration — the per-object opt-in, closed.
*
* Not a global flag with exceptions: the maintainer's 2026-08-16 ruling chose a
* closed opt-in deliberately, because on a compliance surface the failure modes
* of the two shapes are not symmetric. A global flag that forgets an exception
* over-collects (noisy, expensive, and it buries the views an auditor is
* looking for); an opt-in that forgets an object under-collects, which is
* visible the moment anyone asks the question this capability exists to answer.
*/
export interface AuditPluginReadAuditOptions {
/**
* Objects whose RECORD-DETAIL views are recorded as `read` rows in
* `sys_audit_log`. Absent or empty installs no hook at all — a deployment
* that opts nothing in pays nothing on its read path.
*
* ⛔ Scope is record-detail views only (a read that materialized one record
* and pinned its primary key). List and search results are NOT audited: that
* is a deferred follow-up, and a deferral that leaked rows anyway would not
* be one.
*/
objects?: readonly string[];
/** Flush once this many views are buffered. Default 50. */
maxBatchSize?: number;
/** Flush this long after the first view of a batch. Default 2000ms. */
flushIntervalMs?: number;
}
/** Constructor options for {@link AuditPlugin}. */
export interface AuditPluginOptions {
/** [#8992] Record-view auditing. Off unless objects are named. */
readAudit?: AuditPluginReadAuditOptions;
/**
* Host locale resolver: the language this plugin writes the title of the
* @mention notification it emits in. Called with the write's organization
* (`tenantId`) and the mentioned recipient (`userId`). [#26167]
* `sys_activity.summary` is not written in it: the summary is stored in
* English and served in each reader's own locale.
*
* **Precedence: host first, settings second.** When given, this resolver is
* asked first. When it answers nothing (`undefined`, `null` or a blank
* string), the plugin uses the locale it resolves without this option: the
* deployment's settings-derived `localization.locale` (ADR-0053, read
* through `resolveLocalizationContext`). Two faults fall back the same way,
* and neither fails the audited write: a throw (or a rejected promise), and
* an answer that is not a well-formed BCP-47 locale tag (`zh_CN`, a
* non-string). Each fault is logged once at `warn`. An accepted answer is
* used in its canonical form (`zh-cn` → `zh-CN`).
*
* Absent, the settings-derived locale is the only source, exactly as for a
* plugin built without this option. The writer memoizes the answer per
* tenant/user scope for a short TTL, so an implementation may read its own
* storage directly. The locale only picks the message catalog: a locale the
* deployment's i18n service has no catalog for degrades the way a
* settings-derived one does, to the service's declared fallback and then to
* the English literal.
*/
getLocale?: (tenantId?: string, userId?: string) => string | undefined | Promise<string | undefined>;
}
/**
* The host half of the write locale ({@link AuditPluginOptions.getLocale}).
*
* Answers the resolver's locale when it is usable, else `undefined`, which
* sends the caller on to the settings-derived locale. A throw is caught here
* rather than left to the writer: the writer turns a thrown lookup into NO
* locale (English summaries), where the host's fault should cost only the
* host's half. Each fault is reported once per install — the writer asks per
* tenant/user scope, so a broken resolver would otherwise log once per scope.
*/
function createHostLocaleReader(
resolver: NonNullable<AuditPluginOptions['getLocale']>,
logger: PluginContext['logger'],
): (tenantId?: string, userId?: string) => Promise<string | undefined> {
const fallsBack =
'activity summaries and @mention notification titles fall back to the settings-derived locale (localization.locale)';
let throwReported = false;
let malformedReported = false;
return async (tenantId, userId) => {
let answer: unknown;
try {
answer = await resolver(tenantId, userId);
} catch (err) {
if (!throwReported) {
throwReported = true;
logger.warn(
`AuditPlugin: the host getLocale resolver threw — ${fallsBack} wherever it throws. Reported once.`,
{ err: err instanceof Error ? err.message : String(err) },
);
}
return undefined;
}
if (answer === undefined || answer === null) return undefined;
if (typeof answer === 'string') {
const trimmed = answer.trim();
if (trimmed === '') return undefined;
try {
const [canonical] = Intl.getCanonicalLocales(trimmed);
if (canonical) return canonical;
} catch {
// Not a well-formed BCP-47 tag — reported below.
}
}
if (!malformedReported) {
malformedReported = true;
const shown = typeof answer === 'string' ? JSON.stringify(answer) : `a ${typeof answer}`;
logger.warn(
`AuditPlugin: the host getLocale resolver answered ${shown}, which is not a well-formed BCP-47 locale tag — `
+ `${fallsBack} wherever it does. Reported once.`,
);
}
return undefined;
};
}
/**
* [#22913] What is lost when one of this plugin's objects has no storage — the
* CONSEQUENCE half of {@link provisionFailureLine}, said concretely per object.
* `sys_audit_log` / `sys_activity` are written as a side effect of audited
* writes, so their loss is invisible to the writer; a comment or a reaction is
* written by its own request, which fails.
*/
function lostWithoutStorage(objectName: string): string {
switch (objectName) {
case 'sys_audit_log':
return 'Audited writes keep succeeding, but the `sys_audit_log` rows that record who did what, and the ' +
'`sys_activity` rows written after them, cannot land, and nothing retries them.';
case 'sys_activity':
return "Audited writes keep succeeding, but their `sys_activity` rows (a record's activity timeline and the " +
'recent-activity feed) cannot land, and nothing retries them.';
case 'sys_comment':
return 'Every comment write fails until it exists.';
case 'sys_comment_reaction':
return 'Every comment reaction write fails until it exists.';
default:
return 'Every write to it fails until it exists.';
}
}
/**
* [#22913] The ONE line `provisionSystemTables` prints when an object's DDL
* throws — at `error`, carrying both halves AGENTS.md "Degradation log levels"
* asks of a durability degradation: ① the consequence, and that the deployment
* keeps looking healthy; ② the fix. Both remedies named were measured to create
* the missing storage once the driver fault is gone.
*/
function provisionFailureLine(objectName: string): string {
return (
`AuditPlugin: could not provision ${objectName} storage — its storage was NOT created. ` +
`${lostWithoutStorage(objectName)} The boot still completes and the deployment keeps looking healthy. ` +
"Fix: resolve the driver's refusal (in this record's meta), then restart, since this provisioning runs on " +
`every boot, or run \`os migrate apply\`, which creates the missing storage (\`os migrate plan\` lists it as ` +
`\`create_table:${objectName}\`). If the boot log also carries \`Schema sync FAILED for object ` +
`'${objectName}'\`, that is the same refusal.`
);
}
/**
* [#22984] Whether the engine's `ObjectQLPlugin` resolved `skipSchemaSync` (the
* option, else `OS_SKIP_SCHEMA_SYNC=1`). `ObjectQLPlugin.init()` publishes that
* value on the engine instance as an undeclared property, read here with the same
* optional-probe posture `provisionSystemTables` uses for `getDriverForObject`:
* an engine nothing published it on (a test double, a foreign engine) reads as
* not set. ⛔ Never a second read of the environment: the option and the env var
* must not disagree between the engine's boot and this plugin's.
*/
function bootSchemaSyncSkipped(engine: IDataEngine): boolean {
return (engine as unknown as { skipSchemaSync?: unknown }).skipSchemaSync === true;
}
/**
* [#22984] The ONE line `provisionSystemTables` prints when that flag is set —
* at `info`, see "Why the flag skips this provisioning" on that method.
*/
function provisionSkippedLine(objectNames: readonly string[]): string {
return (
`AuditPlugin: ${objectNames.join(', ')} NOT provisioned at boot — the boot's schema sync is skipped ` +
"(`skipSchemaSync` / OS_SKIP_SCHEMA_SYNC=1), declaring this deployment's DDL managed out-of-band, so this " +
'plugin issues none either. `os migrate apply` creates any that are missing (`os migrate plan` lists them ' +
'as `create_table`).'
);
}
/**
* AuditPlugin
*
* Registers the sys_audit_log / sys_activity / sys_comment / sys_comment_reaction
* system objects
* and installs ObjectQL hook subscribers that automatically write audit
* trail + activity stream rows on every data mutation.
*
* Implements ROADMAP M10.1 (CRM production-readiness).
*/
export class AuditPlugin implements Plugin {
name = 'com.objectstack.audit';
type = 'standard' as const;
version = '1.0.0';
dependencies = ['com.objectstack.engine.objectql'];
/**
* [#8144] The `audit` slot — the ledger's WRITE ingress for events that are
* not CRUD (`login`/`logout` today). Declared here because `init()` registers
* it unconditionally, which is what ADR-0116 / `plugin-order.ts` reads this
* field to mean.
*/
providesServices = ['audit'];
/**
* [#8992] The record-view writer's handle, held so `destroy()` can flush the
* tail. A batched ledger that never flushes on shutdown loses its last batch
* on every clean restart — silently, because the reads it describes all
* succeeded.
*/
private readAuditWriter: ReadAuditWriterHandle | null = null;
constructor(private readonly options: AuditPluginOptions = {}) {}
async init(ctx: PluginContext): Promise<void> {
// Register audit system objects via the manifest service.
ctx.getService<{ register(m: any): void }>('manifest').register({
id: 'com.objectstack.audit',
name: 'Audit',
version: '1.0.0',
type: 'plugin',
scope: 'system',
defaultDatasource: 'cloud',
namespace: 'sys',
objects: [SysAuditLog, SysActivity, SysComment, SysCommentReaction],
// The ledger row's record page: its fields, and every ledger row about
// the same record beside it, so a `config_change` row's digest sits next
// to the mirror's row that carries the value (`sys-audit-log.page.ts`).
pages: [SysAuditLogDetailPage],
// ADR-0029 D7 — contribute the one Audit Log entry into the Setup app's
// `group_diagnostics` slot. The plugin owns sys_audit_log (K2), so the
// entry lives and dies with this plugin and needs no item gate.
//
// #23890 — ONE entry, and it opens the console's audit browser (the
// `audit:log` registry key, objectui `registerSystemComponents.tsx`):
// filters by action, object, actor and date, a drawer that pretty-prints
// a change's before and after JSON, and `sys_audit_log`'s served list
// views (Writes, Auth, Record Views, …) offered as presets. The object
// list is reached from the page's "Open as list" link, not from the menu;
// both halves of that page are at the console pin this entry was measured
// against (objectui#12667). It used to sit beside a second entry onto the
// object list (`nav_audit_log_browser` was the page's own id until then):
// two doors onto the same rows.
//
// The id is the one the object-list entry carried: users' sidebar pins
// (`nav:<id>`) and the Setup labels in `@objectstack/platform-objects`
// key on it, and the retired id is tombstoned there.
navigationContributions: [
{
app: 'setup',
group: 'group_diagnostics',
priority: 100,
items: [
{ id: 'nav_audit_logs', type: 'component', label: 'Audit Log', componentRef: 'audit:log', icon: 'scroll-text' },
],
},
],
});
// [#8144] The non-CRUD write ingress. Registered in init() — plugin-auth
// resolves it lazily and calls it from better-auth's session lifecycle
// hooks, i.e. at request time, so the engine is resolved per call rather
// than captured: the service exists from init() while `objectql` only
// resolves at kernel:ready, and every caller arrives long after both.
//
// [#27908] The same slot carries the action-invocation writer
// (`recordActionInvocation`): the two action doors in `@objectstack/runtime`
// resolve it per request and hand it one event per invocation, naming the
// door it came through (ruling 6513869839 on #27681, parameter 3).
const getLedgerEngine = (): IDataEngine | undefined => {
try {
return ctx.getService<IDataEngine>('objectql');
} catch {
// Same fallback alias `start()` uses below — some kernels register
// the engine as `data`.
try {
return ctx.getService<IDataEngine>('data');
} catch {
return undefined;
}
}
};
ctx.registerService('audit', {
...createAuthEventAuditSink({ getEngine: getLedgerEngine, logger: ctx.logger }),
...createActionInvocationAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
});
// ADR-0029 D8 — contribute this plugin's object translations to the i18n
// service on kernel:ready (the i18n plugin may register after this one).
if (typeof (ctx as any).hook === 'function') {
(ctx as any).hook('kernel:ready', async () => {
try {
const i18n = ctx.getService<II18nService>('i18n');
if (i18n && typeof i18n.loadTranslations === 'function') {
const { AuditTranslations } = await import('./translations/index.js');
for (const [locale, data] of Object.entries(AuditTranslations)) {
i18n.loadTranslations(locale, data as Record<string, unknown>);
}
}
} catch { /* i18n optional */ }
});
}
ctx.logger.info('Audit Plugin initialized');
}
async start(ctx: PluginContext): Promise<void> {
this.mountUnreactDoor(ctx);
// ObjectQL engine is only resolvable after the kernel is ready.
ctx.hook('kernel:ready', async () => {
let engine: IDataEngine | null = null;
try {
engine = ctx.getService<IDataEngine>('objectql');
} catch {
// Fallback alias used in some kernels.
try {
engine = ctx.getService<IDataEngine>('data');
} catch { /* ignore */ }
}
if (!engine) {
ctx.logger.warn('AuditPlugin: ObjectQL engine not available — audit writers NOT installed');
return;
}
// Create the physical tables for this plugin's system objects up-front so
// a freshly provisioned env is consistent from the start (see
// provisionSystemTables).
await this.provisionSystemTables(engine, ctx);
// Resolve the messaging service lazily at hook time so collaboration
// @mention / assignment notifications go through the ADR-0030 single
// ingress (emit) instead of writing sys_notification directly. Messaging
// may register after audit; lazy resolution tolerates either order.
const getMessaging = (): MessagingEmitSurface | undefined => {
try {
return ctx.getService<MessagingEmitSurface>('messaging');
} catch {
return undefined;
}
};
// framework#3039 — localize the collaboration notification titles to the
// workspace default locale (ADR-0053 `localization.locale`), and
// [#26167] activity summaries to each reader's. Both seams resolve
// lazily and tolerate absence: no i18n / no settings degrades to English.
const getI18n = (): AuditI18nSurface | undefined => {
try {
return ctx.getService<AuditI18nSurface>('i18n');
} catch {
return undefined;
}
};
// The host's resolver, when given, is asked first (`getLocale` on
// AuditPluginOptions documents the precedence); without a usable answer
// the settings-derived locale below decides, as it does with no option.
const readHostLocale = this.options.getLocale
? createHostLocaleReader(this.options.getLocale, ctx.logger)
: undefined;
const getLocale = async (tenantId?: string, userId?: string): Promise<string | undefined> => {
if (readHostLocale) {
const hostLocale = await readHostLocale(tenantId, userId);
if (hostLocale !== undefined) return hostLocale;
}
let settings: unknown;
try {
settings = ctx.getService('settings');
} catch {
settings = undefined;
}
const { locale } = await resolveLocalizationContext({ ql: engine, settings, organizationId: tenantId, userId });
return locale;
};
// [ADR-0131 D9] The organization an activity row about an org-less record
// derives: the `tenancy` service's Default Organization under `single`,
// none under a wall. Resolved at write time — AuthPlugin registers the
// service, and the answer is memoized there.
const getDefaultOrganizationId = async (): Promise<string | null | undefined> => {
let tenancy: { defaultOrgId?: () => Promise<string | null> } | undefined;
try {
tenancy = ctx.getService<{ defaultOrgId?: () => Promise<string | null> }>('tenancy');
} catch {
return undefined;
}
return typeof tenancy?.defaultOrgId === 'function' ? tenancy.defaultOrgId() : undefined;
};
// A mention notification previews its comment and links its record, so
// it reaches only a mentioned user who can READ both — judged in that
// user's own envelope, their organization claim vetted under the
// posture the request path reads (`mention-recipient-gate.ts`).
const getTenancyPosture = () => {
try {
return effectiveTenancyPosture(ctx.getService<TenancyPostureSource>('tenancy'));
} catch {
return undefined;
}
};
const auditWriters = installAuditWriters(engine as any, this.name, {
getMessaging,
getI18n,
getLocale,
getDefaultOrganizationId,
admitMentionRecipients: (input) =>
admitMentionRecipients({ engine: engine as any, getTenancyPosture, logger: ctx.logger as any }, input),
});
ctx.logger.info('AuditPlugin: audit + activity writers installed');
// [#8992] Record-view auditing — the `read` half of the ledger. Installed
// only over the objects this deployment opted in, and returns null when
// that set is empty, so the default posture costs a read exactly nothing.
const readAuditObjects = this.options.readAudit?.objects ?? [];
this.readAuditWriter = installReadAuditWriter(engine, {
objects: readAuditObjects,
packageId: this.name,
logger: ctx.logger,
...(this.options.readAudit?.maxBatchSize !== undefined
? { maxBatchSize: this.options.readAudit.maxBatchSize }
: {}),
...(this.options.readAudit?.flushIntervalMs !== undefined
? { flushIntervalMs: this.options.readAudit.flushIntervalMs }
: {}),
});
if (this.readAuditWriter) {
ctx.logger.info(
`AuditPlugin: record-view auditing installed on ${this.readAuditWriter.auditedObjects.length} object(s) — `
+ `${this.readAuditWriter.auditedObjects.join(', ')}`,
);
}
// #4630 — record-level authorization for sys_comment: a comment's access
// derives from the record its `thread_id` names, exactly as an
// attachment's derives from its parent (service-storage's
// installAttachmentAccessHooks / installAttachmentReadVisibility). Both
// halves are needed: the hooks gate writes, the middleware is the only
// seam that filters `count()` (→ list `total`) like `find()`. Orthogonal
// to `enforceFeedsCapability` above, which gates `enable.feeds`, not
// access. The sharing service resolves lazily so plugin order doesn't
// matter; without it the edit checks degrade to parent read visibility.
// [#22566] The same two installers gate `sys_comment_reaction`: a
// reaction is readable exactly when its comment is, and created only on a
// comment the caller can read (`comment-access-hooks.ts`, module header).
if (typeof (engine as any).registerHook === 'function') {
installCommentAccessHooks(
engine as any,
() => {
try {
// Typed with the slot's contract (#4251): the gate consults
// `checkEdit` only, but it consults the REAL interface.
return ctx.getService<ISharingService>('sharing');
} catch {
return null;
}
},
ctx.logger,
// [#21755] The deployment's i18n lookup for the not-visible refusal's
// sentence — resolved per refusal (ADR-0029 D8: i18n may register
// after this plugin), the override address plugin-security's own
// not-visible refusal renders through.
() => {
const i18n = ctx.getService<II18nService>('i18n');
const t = i18n?.t;
if (typeof t !== 'function') return undefined;
return (key: string, loc: string, params?: Record<string, unknown>) => t.call(i18n, key, loc, params);
},
// [ADR-0055] The security service, for its master-detail write check:
// a `controlled_by_parent` parent is judged through its master, as its
// own update is. Resolved per check (the security plugin may start
// after this one); a kernel without it composes no master check.
() => {
try {
return ctx.getService<ISecurityService>('security');
} catch {
return null;
}
},
// A comment's display identity (author name and avatar) is the
// session user's own, read by the same resolution the record
// history's actor columns are written with.
auditWriters
? (hookCtx, userId) => auditWriters.resolveActorSnapshot(hookCtx?.api, userId)
: undefined,
);
if (typeof (engine as any).registerMiddleware === 'function') {
// [ADR-0139 E7] The thread gate writes one ReadableIds leaf per parent
// object, and only where the security service answers `canReadObject`
// (`parent-record-read-gate.ts`). Resolved on every read.
installCommentReadVisibility(engine as any, ctx.logger, () => {
try {
return ctx.getService<ParentObjectReadAdmission>('security');
} catch {
return undefined;
}
});
} else {
ctx.logger.warn(
'AuditPlugin: engine has no middleware seam — sys_comment and sys_comment_reaction READ visibility NOT ' +
'installed (comments on records the caller cannot read, and their reactions, would be listable)',
);
}
ctx.logger.info('AuditPlugin: sys_comment and sys_comment_reaction record-level access gates installed');
}
// sys_activity READ visibility — an activity row is readable when the
// record it is about (`object_name`, `record_id`) is readable, decided by
// the same caller-scoped parent read the sys_comment gate above asks.
// The object is append-only with `apiMethods: ['get', 'list']`, so the
// read side is the whole gate. Without the middleware seam it cannot be
// installed, and that is said rather than left silent.
if (typeof (engine as any).registerMiddleware === 'function') {
// [#21154] A query that filters, sorts, searches, groups or aggregates
// by a value-bearing column of the activity stream or the ledger is
// judged before the read gate below runs its pre-scan — a read-time
// redaction narrows only what is served, so such a predicate would
// select on a value the reader is not served. The security service is
// resolved on every read, as for the redaction.
installParentFieldQueryGuards(
engine as any,
() => {
try {
const sec = ctx.getService<FieldVisibilitySource>('security');
return sec && typeof sec.getReadableFields === 'function' ? sec : undefined;
} catch {
return undefined;
}
},
ctx.logger,
);
// The parent-record gates ask the security service's object-level read
// admission before they read a parent object as the caller, so an
// object the caller cannot read is skipped without a logged denial
// (`parent-record-read-gate.ts`). Resolved on every read, as below.
const getReadAdmission = (): ParentObjectReadAdmission | undefined => {
try {
return ctx.getService<ParentObjectReadAdmission>('security');
} catch {
return undefined;
}
};
installActivityReadVisibility(engine as any, ctx.logger, getReadAdmission);
ctx.logger.info('AuditPlugin: sys_activity parent-record read visibility installed');
// [#21081] …and of each row it keeps, the value-bearing columns serve a
// parent field only to a reader the security service serves that field
// unmasked. The service is resolved on EVERY read, for the reason the
// approval snapshot gives: the security plugin may register after this
// one, and a resolver captured now would pin "no service" — i.e. never
// redact — for the life of the process. `getService` throws on an empty
// slot, so a deployment without the security plugin (no field-level
// security anywhere) serves rows exactly as before.
const getSecurity = (): FieldVisibilitySource | undefined => {
try {
const sec = ctx.getService<FieldVisibilitySource>('security');
return sec && typeof sec.getReadableFields === 'function' ? sec : undefined;
} catch {
return undefined;
}
};
installActivityFieldRedaction(engine as any, getSecurity, ctx.logger);
ctx.logger.info('AuditPlugin: sys_activity field redaction installed');
// [#26167] …and each kept row's summary is composed in the READER's
// language from the code the writer stored beside it. Registered after
// the redaction, so it runs inside it: the redaction judges the
// composed text by the same declared sources as the stored one.
installActivitySummaryLocale(engine as any, getI18n);
ctx.logger.info('AuditPlugin: sys_activity reader-language summaries installed');
// [#21155] The compliance ledger's before/after snapshots take the same
// narrowing, through the same answer and the same resolver: a ledger
// reader is not field-unrestricted by default. An auditor who must see
// every field is granted it by a set that unmasks those fields.
installAuditLogFieldRedaction(engine as any, getSecurity, ctx.logger);
ctx.logger.info('AuditPlugin: sys_audit_log field redaction installed');
// [#21175] …and the ledger's rows take the activity stream's parent-record
// gate: a row about a record is served only to a caller who can read it.
// Middleware runs in registration order, so on the ledger the #21154
// query guard above judges a query first (a refused query never pays
// this gate's pre-scan), and the field redaction narrows only the rows
// this gate keeps.
installAuditLogReadVisibility(engine as any, ctx.logger, getReadAdmission);
ctx.logger.info('AuditPlugin: sys_audit_log parent-record read visibility installed');
} else {
ctx.logger.warn(
'AuditPlugin: engine has no middleware seam — sys_activity READ visibility and field redaction, and ' +
'sys_audit_log READ visibility and field redaction, NOT installed (activity and ledger rows about ' +
'records the caller cannot read would be listable, and an activity row or a ledger snapshot would ' +
'serve every parent field value it carries)',
);
}
});
}
/**
* Provision the physical tables for this plugin's system objects up-front.
*
* A freshly provisioned env that READS one of these tables before anything
* created it — the home page's recent-activity feed queries sys_activity
* before any mutation has happened — hits SQLite "no such table", which the
* engine logs as a `Find operation failed` ERROR on every load. Creating the
* tables at kernel:ready (once the engine + registry are ready) makes a new
* env consistent from the start. A WRITE does not create a missing table
* either: the SQL driver's insert fails with the same "no such table".
*
* `syncObjectSchema` is idempotent — the SQL driver only creates a table when
* it is absent (and alters to add columns) — so this is safe on every boot,
* and a no-op for objects whose table already exists. Per-object failures are
* isolated so one bad object can't block the rest.
*
* ## Why a failed provision is an `error` (#22913)
*
* When an object's DDL throws here, the boot still completes and the
* deployment serves as healthy, but the table does not exist. For
* `sys_audit_log` / `sys_activity` the loss is invisible: they are written as
* a SIDE EFFECT of audited writes, which keep succeeding while their audit
* rows have nowhere to land. That is the durability class AGENTS.md
* "Degradation log levels" sends to `error`, with the consequence and the
* fix in the first line. Both remedies the line names were measured to
* create a missing table once the driver fault is gone: a restart (this
* method runs on every boot that runs DDL) and `os migrate apply` (`os migrate
* plan` lists it as `create_table`). The line is only ever printed on a boot
* that runs DDL: under `OS_SKIP_SCHEMA_SYNC` this method issues none (see "Why
* the flag skips this provisioning" below). The flag is still not named as a
* fix here: it creates nothing, it only stops the attempt. Where the driver
* also refused the engine's own boot sync of the same table, that sync's
* `Schema sync FAILED for object` line, which this one points at, already
* names the flag for a deployment that meant to manage DDL out-of-band.
*
* ## Why the flag skips this provisioning (#22984)
*
* `skipSchemaSync` / `OS_SKIP_SCHEMA_SYNC=1` declares a deployment's DDL
* managed out-of-band ("Use after running migrations manually"), and the
* engine's boot honours it. This method is boot-time DDL too, so it honours
* the same declaration: it reads the value `ObjectQLPlugin` resolved, from
* the engine (`bootSchemaSyncSkipped`), and when it is set it returns
* before any DDL. It issues no existence probe either, because the flag
* protects a cold-start budget. It says so once, at `info`, naming what it did
* not provision and why. Not `warn`: nothing is degraded, because the operator
* declared this. If a table is in fact missing, the audit writers report the
* missing-table failure at `error` on the first write that needs it, and
* `os migrate apply`, the documented path, was measured to create all four
* tables. `syncObjectSchema` itself stays ungated, because it is also how a
* runtime publish gives a new object its table.
*
* ## Why this method reports where each table landed (#4887)
*
* `syncObjectSchema` returns `void` and exits SILENTLY on three conditions
* the plugin cannot see from the outside: the object is not in the registry,
* no driver resolves for it, or the resolved driver has no `syncSchema`. A
* caller that only catches throws therefore cannot tell "created" from "did
* nothing" — and neither could a reader of the log, because this method said
* nothing at all on success.
*
* That silence cost a whole misdiagnosis. #4887 reported these tables as
* "never provisioned" because they were absent from the primary SQLite file,
* and concluded the guard below had bailed out. It had not: `sys_audit_log`
* (`lifecycle.class: 'audit'`) and `sys_activity` (`lifecycle.class:
* 'telemetry'`) are routed by ADR-0057 §3.6 to the dedicated `telemetry`
* datasource whenever one is registered — which `os dev` provisions by
* default as a SIBLING FILE (`dev.db` → `dev.telemetry.db`). Their tables
* were created, in that other store. `sys_comment` carries no lifecycle
* class, stays on the primary, and was the one the reporter found. So the
* provisioning loop reports the resolved datasource per object, and calls out
* the split explicitly when it is in effect: a table that is "missing" from
* the database you are looking at, and a table that was never created, are
* different problems, and the log now distinguishes them.
*/
private async provisionSystemTables(engine: IDataEngine, ctx: PluginContext): Promise<void> {
const objects = [SysAuditLog, SysActivity, SysComment, SysCommentReaction];
// [#22984] FIRST: a deployment that declared its DDL managed out-of-band
// gets none from here either. See "Why the flag skips this provisioning".
if (bootSchemaSyncSkipped(engine)) {
ctx.logger.info(provisionSkippedLine(objects.map((obj) => obj.name)));
return;
}
// `syncObjectSchema` lives on the concrete ObjectQL engine, not the
// IDataEngine contract; engines/drivers without on-demand DDL (e.g. an
// in-memory test double) simply skip provisioning.
const sync = (engine as unknown as { syncObjectSchema?: (name: string) => Promise<void> }).syncObjectSchema;
if (typeof sync !== 'function') {
// #4887 — this return used to be silent, so "provisioning was skipped
// wholesale" and "provisioning ran fine" produced identical logs. Name
// the consequence, not just the condition.
ctx.logger.warn(
'AuditPlugin: this engine exposes no syncObjectSchema() — sys_audit_log / sys_activity / sys_comment / ' +
'sys_comment_reaction were NOT ' +
'provisioned up-front and stay lazy-created on first WRITE. An env that READS one first (the home page ' +
'activity feed queries sys_activity before any mutation) will log "no such table" until something writes to it.',
);
return;
}
// Same optional-probe posture as `syncObjectSchema` above: `getDriverForObject`
// is public on the concrete ObjectQL engine but not part of IDataEngine, so
// engines that lack it simply report no datasource — never an error.
const resolveDriver = (engine as unknown as {
getDriverForObject?: (name: string) => { name?: string } | undefined;
}).getDriverForObject;
// Declared on IDataEngine (optional — engines with no named-driver registry
// omit it), so no cast is needed here.
const defaultDatasource = engine.getDefaultDriverName?.();
const placements: string[] = [];
const offDefault: string[] = [];
for (const obj of objects) {
try {
await sync.call(engine, obj.name);
} catch (err) {
// A DURABILITY degradation, so `error` (AGENTS.md "Degradation log
// levels"; see "Why a failed provision is an `error`" above). Once per
// object per boot, never per write. The boot is deliberately NOT failed:
// refusing to boot is a separate policy call. The driver's refusal goes
// in meta, not in the message: a multi-line driver error would split the
// record, and only its first fragment would carry the level.
ctx.logger.error(provisionFailureLine(obj.name), undefined, {
object: obj.name,
error: (err as Error)?.message ?? String(err),
});
continue;
}
if (typeof resolveDriver !== 'function') continue;
let datasource: string | undefined;
try {
datasource = resolveDriver.call(engine, obj.name)?.name;
} catch {
datasource = undefined;
}
if (!datasource) {
// The second of the two silent exits #4887 asked to make audible: the
// call above resolved without throwing, but no driver backs this object,
// so `syncObjectSchema` returned having issued no DDL at all.
ctx.logger.warn(
`AuditPlugin: ${obj.name} resolves to NO datasource driver — syncObjectSchema() returned without creating its ` +
'storage. Reads and writes against it will fail with "no such table" until a driver backs its datasource.',
);
continue;
}
placements.push(`${obj.name}→${datasource}`);
if (defaultDatasource !== undefined && datasource !== defaultDatasource) offDefault.push(`${obj.name}→${datasource}`);
}
if (placements.length > 0) {
ctx.logger.info(`AuditPlugin: system tables provisioned — ${placements.join(', ')}`);
}
if (offDefault.length > 0) {
ctx.logger.info(
`AuditPlugin: ${offDefault.join(', ')} live on a NON-default datasource (ADR-0057 §3.6 lifecycle-class ` +
`separation), not on '${defaultDatasource}'. Their tables exist in that store — on SQLite, a different FILE. ` +
'Anything that reads them without naming the object (raw SQL on the default datasource) will report ' +
'"no such table" even though provisioning succeeded.',
);
}
}
/**
* Mount the unreact door (`comment-reaction-routes.ts`) on the kernel's HTTP
* server: a member removes their own comment reaction, and only theirs,
* without an object-level `delete` grant (maintainer ruling 6422861164,
* letter A). Every service the door reads is read per request, so a provider
* that registers after this hook is still seen. A kernel with no HTTP server
* mounts nothing, and says so.
*/
private mountUnreactDoor(ctx: PluginContext): void {
const optional = <T>(name: string): T | undefined => {
try {
return ctx.getService<T>(name) ?? undefined;
} catch {
return undefined;
}
};
// `http.server` is the canonical name; `http-server` the deprecated alias.
const http = optional<IHttpServer>('http.server') ?? optional<IHttpServer>('http-server');
if (!http) {
ctx.logger.warn(
`AuditPlugin: no HTTP server is registered, so the unreact door (DELETE ${COMMENT_REACTION_REMOVE_ROUTE}) ` +
'is not mounted, and a member whose grants carry no delete on sys_comment_reaction cannot remove their own reaction.',
);
return;
}
const getEngine = () => optional<IDataEngine>('objectql') ?? optional<IDataEngine>('data');
registerCommentReactionRoutes(http, {
getEngine: () => getEngine() as unknown as CommentReactionEngine | undefined,
resolveCaller: platformCallerResolver({
getEngine,
getAuth: () => optional<IAuthService>('auth'),
tenancy: tenancyServiceResolver(ctx),
}),
});
ctx.logger.info(`AuditPlugin: unreact door mounted at DELETE ${COMMENT_REACTION_REMOVE_ROUTE}`);
}
/**
* [#8992] Flush the record-view tail on shutdown.
*
* Batching is what keeps the ledger write off the read path, and the price of
* a buffer is that a clean shutdown can take the last batch with it. The
* views in it already returned 200, so nothing else would ever report the
* loss. `stop()` cancels the timer and drains what is left; it never throws
* (the batcher's `persist` reports and swallows), so this can never turn a
* clean shutdown into a failed one.
*/
async destroy(): Promise<void> {
const writer = this.readAuditWriter;
this.readAuditWriter = null;
if (writer) await writer.stop();
}
}
/**
* How the unreact door reaches the `tenancy` service: the kernel's async
* accessor, read per request and classified by the composition
* (`classifyAdmissionTenancyPosture`). A `tenancy` service never registered is
* a kernel with no organization wall; one that is registered and cannot answer
* is the outage the door answers. A host with no async accessor registers no
* `tenancy` service either, and no posture is read.
*/
function tenancyServiceResolver(ctx: PluginContext): TenancyServiceResolver | undefined {
const kernel = ctx.getKernel?.() as
| { getServiceAsync?: <T>(name: string, scopeId?: string) => Promise<T> }
| undefined;
if (!kernel || typeof kernel.getServiceAsync !== 'function') return undefined;
return () => kernel.getServiceAsync!<TenancyPostureSource>('tenancy');
}