Repository navigation
Expand file tree
/
Copy pathaudit-plugin.ts
More file actions
1315 lines (1280 loc) · 66.2 KB
/
Copy pathaudit-plugin.ts
File metadata and controls
1315 lines (1280 loc) · 66.2 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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { isServiceNotRegisteredError, type Plugin, type PluginContext } from '@objectstack/core';
import {
effectiveTenancyPosture,
resolveLocalizationContext,
type TenancyPostureSource,
type TenancyServiceResolver,
} from '@objectstack/core';
import type {
IAuditCheckpointSigner,
IAuditCheckpointSink,
IAuthService,
IClusterService,
ICommentDoorsService,
ICryptoProvider,
IDataEngine,
IHttpServer,
II18nService,
ISecurityService,
ISharingService,
} from '@objectstack/spec/contracts';
import { AUDIT_CHECKPOINT_SIGNER_SERVICE, AUDIT_CHECKPOINT_SINK_SERVICE } from '@objectstack/spec/contracts';
import type { AuditExpiryRequest, AuditExpiryRun } from './audit-seal/expiry.js';
import { registerSealedWindowFloors, type SealedFloorRegistrar } from './audit-seal/retention-floor.js';
import { AuditSealer, type AuditSealerEngine } from './audit-seal/sealer.js';
import { LocalCheckpointSigner } from './audit-seal/signer.js';
import {
SysAuditLog,
SysActivity,
SysComment,
SysCommentReaction,
SysAuditCheckpoint,
SysAuditSigningKey,
SysAuditAmendment,
} 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 AuditActorSnapshot, type AuditI18nSurface, type MessagingEmitSurface } from './audit-writers.js';
import { MENTION_EMAIL_TEMPLATES, REPLY_EMAIL_TEMPLATES } from './mention-email.js';
import { createAppActivityWriter } from './app-activity-door.js';
import { installReadAuditWriter, type ReadAuditWriterHandle } from './read-audit.js';
import { createAuthEventAuditSink } from './auth-event-audit.js';
import { createActionInvocationAuditWriter } from './action-invocation-audit.js';
import { createDataExportAuditWriter } from './data-export-audit.js';
import { createDatasetQueryAuditWriter, type DatasetQueryAuditWriter } from './dataset-query-audit.js';
import { createPackageLifecycleAuditWriter } from './package-lifecycle-audit.js';
import {
createCredentialUseAuditWriter,
installCredentialUseAudit,
type CredentialUseAuditWriter,
} from './credential-use-audit.js';
import { createScimRefusalAuditWriter } from './scim-refusal-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 {
COMMENT_REMOVE_ROUTE,
COMMENT_RESOLUTION_ROUTE,
registerCommentDoorsRoutes,
type CommentDoorsEngine,
type CommentPostingGate,
} from './comment-routes.js';
import { COMMENT_THREADS_QUERY_ROUTE } from './comment-threads-query.js';
import { createCommentDoorMember } from './comment-doors-member.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, LEDGER_AUDIT_CAPABILITY } 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;
}
/**
* Dataset-query auditing configuration — the per-dataset opt-in, closed, with
* the record-view writer's shape and for its reasons
* ({@link AuditPluginReadAuditOptions}).
*/
export interface AuditPluginDatasetQueryAuditOptions {
/**
* Saved datasets whose queries through the analytics dataset door are
* recorded as `dataset_query` rows in `sys_audit_log`: who, which dataset,
* the dimensions and measures selected, the filtered field names (never the
* values), the row count and the outcome. Absent or empty records nothing
* and buffers nothing. A name covers every package that holds a dataset of
* that name (ADR-0150 D3); each row records the holder it read in
* `metadata.dataset_package`.
*/
datasets?: readonly string[];
/** Flush once this many rows are buffered. Default 50. */
maxBatchSize?: number;
/** Flush this long after the first row 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;
/** Dataset-query auditing (`dataset_query` rows). Off unless datasets are named. */
datasetQueryAudit?: AuditPluginDatasetQueryAuditOptions;
/**
* 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>;
/**
* [ADR-0154 D2, D6] The crypto provider the audit sealer seals each
* checkpoint's seed under, and the default checkpoint signer seals its
* private key under (scope `audit_seal`). The host composes it here: `os
* serve` hands over the one provider it seals every `sys_secret` row with.
*
* A function is read once, when the sealer starts (`kernel:ready`), for a
* host that composes this plugin before it has built its provider; an
* `undefined` answer is an absent provider.
*
* Absent, nothing is sealed: an object that declares `lifecycle.seal` is
* reported once, at `error`, naming the consequence and this option as the
* fix. A host that registers its own `audit.checkpointSigner` still needs
* it, for the seeds.
*/
cryptoProvider?: ICryptoProvider | (() => ICryptoProvider | undefined);
/**
* [ADR-0154 D3] Start the audit sealer. Default `true`: every server wants
* it, and a server that cannot seal says so at `error`.
*
* Set `false` for a one-shot command — `os audit verify` and the `os
* migrate …` boots. Such a run is not a second server: a sealer started there
* would write checkpoints (and, on a first run, the signing key) from a
* read-only check or a dry run, and with no crypto provider it would report
* the sealed objects unsealed on the command's own output.
*/
armSealer?: boolean;
}
/**
* 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;
private datasetQueryWriter: DatasetQueryAuditWriter | null = null;
/** [ADR-0154 D3] The sealer, started at `kernel:ready` and stopped by `destroy()`. */
private sealer: AuditSealer | null = null;
/** [ADR-0154 D8] Takes the sealer's expiry back off the lifecycle service, on `destroy()`. */
private unregisterExpiryPrefix: (() => void) | null = null;
/**
* [ADR-0154 D8] Registers each sealed object's retention floors at its declared window
* (`audit-seal/retention-floor.ts`); set beside the expiry, run before every sealer pass.
*/
private refreshSealedFloors: (() => void) | null = null;
/**
* [#31796] The credential-use writer, built in `init()` (the `audit` slot
* carries it) and handed to the stamp hook `start()` installs, so the slot
* and the hook write through one writer.
*/
private credentialUseWriter: CredentialUseAuditWriter | null = null;
/**
* The platform's display snapshot of a user, once the writers are installed
* at `kernel:ready`; the activity door's writer reads it at each call.
*/
private actorSnapshotOf: ((api: unknown, userId: string) => Promise<AuditActorSnapshot>) | undefined;
/** [ADR-0154 D2, D6] The provider a host handed over, for an instance composed with none. */
private hostCryptoProvider: (() => ICryptoProvider | undefined) | undefined;
/** [ADR-0154 D3] Set when a host that handed its provider over is a one-shot boot. */
private hostDisarmsSealer = false;
constructor(private readonly options: AuditPluginOptions = {}) {}
/**
* [ADR-0154 D2, D6; seat ruling 6884540128 item 3] A host hands an instance
* the app composed (a stack `plugins` entry) the host's own crypto provider,
* which the sealer then seals under. It is taken only when this instance was
* composed with no `cryptoProvider`: one the app composed is never
* overridden. `armSealer: false` — the host's one-shot boot — keeps the
* sealer off; `true` leaves this instance's own `armSealer` standing, so an
* app's `armSealer: false` is never turned on.
*
* The provider is read when the sealer starts (`kernel:ready`), so a host
* hands it over before then. Resolves whether it was taken. A provider that
* answers `undefined` is an absent one: the sealer reports it once, at
* `error`, and seals nothing; the boot is never refused.
*/
adoptHostCryptoProvider(provider: () => ICryptoProvider | undefined, host: { armSealer: boolean }): boolean {
if (this.options.cryptoProvider !== undefined) return false;
this.hostCryptoProvider = provider;
if (!host.armSealer) this.hostDisarmsSealer = true;
return true;
}
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',
// [ADR-0154] The checkpoints and the signing keys, which the sealer and
// signer write, and the amendments, which the redaction amendment writer
// writes before a migration rewrites a sealed row (D7).
objects: [SysAuditLog, SysActivity, SysComment, SysCommentReaction, SysAuditCheckpoint, SysAuditSigningKey, SysAuditAmendment],
// The ledger row's record page: its fields, and every ledger row about
// the same record beside it, so a `config_change` row sits next to the
// mirror's rows about the same settings row (`sys-audit-log.page.ts`).
// A non-secret key's `config_change` row carries its readable before
// and after itself; a secret-valued key's carries only the digest.
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.
//
// The entry is gated on `view_all_audit_log`, the ledger's own read
// capability (`LEDGER_AUDIT_CAPABILITY`), not on the slot's: the slot
// carries no gate, because a group gate prunes every child before the
// child is judged, and `manage_platform_settings` there hid the entry
// from an auditor who holds the read capability and no platform-settings
// power (separation of duties). Platform administrators hold both by
// default (`ADMIN_FULL_ACCESS_CAPABILITIES`), so they still see it.
//
// #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', requiredPermissions: [LEDGER_AUDIT_CAPABILITY] },
],
},
],
});
// [#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).
//
// [#30955] And the data-export writer (`recordDataExport`): the REST
// export door resolves it per request and hands it one event per export
// it streamed, so every export of every object, this ledger included,
// leaves a run-level `export` row (`data-export-audit.ts`).
//
// [#31186] And the package lifecycle writer (`recordPackageLifecycleEvent`):
// the uninstall verb (`deletePackage` in `@objectstack/metadata-protocol`)
// resolves it per call and hands it one event per package it uninstalled,
// so the package itself leaves a `package_uninstall` row
// (`package-lifecycle-audit.ts`). [#30964] The install-local door's
// unmanaged branch hands the same writer one `package_unmanaged_import`
// event per copy it attempted, landed or not.
//
// [#31829] And the SCIM refusal writer (`recordScimRefusal`): plugin-auth's
// SCIM door hands it one event per refused `/scim/v2/*` request its bound
// admitted, so a connection's errors leave `scim_refused` rows
// (`scim-refusal-audit.ts`).
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;
}
}
};
//
// [#31796] And the credential-use writer (`recordCredentialUse`): one
// `credential_use` row per credential per use window. The two stamped
// credentials reach it through the stamp hook `start()` installs; a
// `skip_consent` OAuth client, which has no consent row to stamp, through
// this slot, from plugin-auth's OAuth stamp point
// (`credential-use-audit.ts`).
this.credentialUseWriter = createCredentialUseAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger });
//
// And the dataset-query writer (`recordDatasetQuery`): the analytics
// dataset door hands it one event per saved-dataset query that reached
// the read; it records only the datasets named in
// `datasetQueryAudit.datasets`, batched off the request path
// (`dataset-query-audit.ts`). Named nothing, it records nothing.
const datasetQueryAudit = this.options.datasetQueryAudit;
const datasetQueryWriter = createDatasetQueryAuditWriter({
getEngine: getLedgerEngine,
logger: ctx.logger,
datasets: datasetQueryAudit?.datasets ?? [],
...(datasetQueryAudit?.maxBatchSize !== undefined ? { maxBatchSize: datasetQueryAudit.maxBatchSize } : {}),
...(datasetQueryAudit?.flushIntervalMs !== undefined ? { flushIntervalMs: datasetQueryAudit.flushIntervalMs } : {}),
});
this.datasetQueryWriter = datasetQueryWriter;
if (datasetQueryWriter.auditedDatasets.length > 0) {
ctx.logger.info(
`AuditPlugin: dataset-query auditing on ${datasetQueryWriter.auditedDatasets.length} dataset(s) — `
+ `${datasetQueryWriter.auditedDatasets.join(', ')}`,
);
}
ctx.registerService('audit', {
...createAuthEventAuditSink({ getEngine: getLedgerEngine, logger: ctx.logger }),
...createActionInvocationAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
...createDataExportAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
...createPackageLifecycleAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
...this.credentialUseWriter,
...createScimRefusalAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }),
recordDatasetQuery: datasetQueryWriter.recordDatasetQuery,
// The activity door's writer: one timeline entry an app adds through
// `ctx.activity.append` (`app-activity-door.ts`).
...createAppActivityWriter({ getEngine: getLedgerEngine, getActorSnapshot: () => this.actorSnapshotOf }),
});
// [#36469] The comment doors on the `comments` slot, transport-neutrally
// (`ICommentDoorsService.handleCommentDoor`): the runtime dispatcher's
// `/comments` domain forwards to it on a kernel with no `http.server` (a
// hosted tenant kernel), where `mountCommentDoors` has nothing to mount
// on. Same registration as the mount, the comment threads read included
// (#39134); nothing is read until a request.
const commentDoors: ICommentDoorsService = {
handleCommentDoor: createCommentDoorMember((http) => registerCommentDoors(http, ctx)),
};
ctx.registerService('comments', commentDoors);
// 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.mountCommentDoors(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;
}
};
// The mention e-mail's link to the record (`mention-email.ts`): a
// Console page, composed by the auth service's `getConsoleUrl` — the
// one composer of Console page links in mail. Resolved at send time;
// without an auth service the link stays relative.
const getConsoleUrl = (path: string): string | undefined => {
let auth: { getConsoleUrl?: (path: string) => string } | undefined;
try {
auth = ctx.getService<{ getConsoleUrl?: (path: string) => string }>('auth');
} catch {
return undefined;
}
return typeof auth?.getConsoleUrl === 'function' ? auth.getConsoleUrl(path) : undefined;
};
// The mention e-mail's text: one template per catalog locale, in the
// messaging service's code-declared tier (`mention-email.ts`). A
// messaging service without the seam renders the e-mail from the
// notification's title and body alone.
const messagingAtReady = getMessaging();
if (messagingAtReady && typeof messagingAtReady.registerBuiltinTemplates === 'function') {
try {
messagingAtReady.registerBuiltinTemplates(MENTION_EMAIL_TEMPLATES);
} catch (err: any) {
ctx.logger.warn('AuditPlugin: the @mention e-mail templates were NOT registered — mention e-mails carry the notification title and comment preview with no link to the record', {
error: err?.message ?? String(err),
});
}
}
// [#36074] The reply e-mail's text: the mention e-mail's shape under the
// reply topic, registered on its own so one refusal leaves the other.
if (messagingAtReady && typeof messagingAtReady.registerBuiltinTemplates === 'function') {
try {
messagingAtReady.registerBuiltinTemplates(REPLY_EMAIL_TEMPLATES);
} catch (err: any) {
ctx.logger.warn('AuditPlugin: the comment reply e-mail templates were NOT registered — reply e-mails carry the notification title and comment preview with no link to the record', {
error: err?.message ?? String(err),
});
}
}
const auditWriters = installAuditWriters(engine as any, this.name, {
getMessaging,
getI18n,
getLocale,
getDefaultOrganizationId,
getConsoleUrl,
admitMentionRecipients: (input) =>
admitMentionRecipients({ engine: engine as any, getTenancyPosture, logger: ctx.logger as any }, input),
});
this.actorSnapshotOf = auditWriters?.resolveActorSnapshot;
ctx.logger.info('AuditPlugin: audit + activity writers installed');
// [#31796] The `credential_use` row: recognised on each credential's own
// throttled use stamp, so it adds no timer of its own
// (`credential-use-audit.ts`).
if (this.credentialUseWriter) {
installCredentialUseAudit(engine as any, this.credentialUseWriter, { packageId: this.name });
}
// [#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;
}
};
// [#26167] …and each kept row's summary is composed in the READER's
// language from the code the writer stored beside it. [#36290]
// Registered BEFORE the redaction, so the redaction runs inside it: the
// redaction judges the stored text by its declared sources and narrows
// the field-change code to this reader first, and the summary is then
// composed from what it kept.
installActivitySummaryLocale(engine as any, getI18n);
ctx.logger.info('AuditPlugin: sys_activity reader-language summaries installed');
installActivityFieldRedaction(engine as any, getSecurity, ctx.logger);
ctx.logger.info('AuditPlugin: sys_activity field redaction 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)',
);
}
// [ADR-0154 D3] The sealer starts last, once the tables it reads and
// writes are provisioned. It seals only objects that declare
// `lifecycle.seal`, re-read on every pass.
this.startSealer(engine, ctx);
});
}
/**
* Start the audit sealer (ADR-0154 D3) over the engine's storage. The
* signer and the sink are resolved per pass from the `audit.checkpointSigner`
* and `audit.checkpointSink` slots (D11), the signer falling back to the
* default local key of D6 only when no host signer is registered; the
* `cluster` service, when registered, holds the `audit.sealer` lock. A seam
* that is registered but fails to resolve stops the pass (#34280). An engine without the storage surface the sealer
* reads (a test double) starts no sealer, and neither does a one-shot
* command's boot (`armSealer: false`).
*/
private startSealer(engine: IDataEngine, ctx: PluginContext): void {
if (this.options.armSealer === false || this.hostDisarmsSealer) return;
const storage = engine as unknown as Partial<AuditSealerEngine>;
if (typeof storage.getDriverForObject !== 'function' || typeof storage.registry?.getAllObjects !== 'function') return;
const sealEngine = storage as AuditSealerEngine;
const option = this.options.cryptoProvider ?? this.hostCryptoProvider;
const crypto = typeof option === 'function' ? option() : option;
const localSigner = crypto ? new LocalCheckpointSigner({ engine: sealEngine, crypto }) : undefined;
const seam = hostSeamResolver(ctx);
this.sealer = new AuditSealer({
engine: sealEngine,
...(crypto ? { crypto } : {}),
signer: async () => (await seam<IAuditCheckpointSigner>(AUDIT_CHECKPOINT_SIGNER_SERVICE)) ?? localSigner,
sink: () => seam<IAuditCheckpointSink>(AUDIT_CHECKPOINT_SINK_SERVICE),
cluster: () => seam<IClusterService>('cluster'),
logger: ctx.logger,
beforePass: () => this.refreshSealedFloors?.(),
});
// With no crypto provider nothing is sealed and no expiry can be signed: the
// lifecycle service then keeps the sealed rows and says so (ADR-0154 D8).
if (crypto) this.registerExpiryPrefix(this.sealer, sealEngine, ctx);
this.sealer.start();
}
/**
* [ADR-0154 D8] Hand the sealer's expiry to the lifecycle service, which
* then expires each sealed object by whole checkpoints, each run's signed
* `expiry` amendment written first. Reached duck-typed, as every reap guard
* is (`ctx.getService('lifecycle')`). No lifecycle service ⇒ nothing sweeps,
* so nothing expires. A lifecycle service with no sealed expiry keeps a
* sealed object's rows past their policy and says so.
*
* Beside it, a retention floor for each sealed object at its declared window
* (`audit-seal/retention-floor.ts`): on a sealed object, a retention override
* cannot shorten the declared window. Registered now and again before every
* sealer pass, so the floors follow the registry as the pass does. A lifecycle
* service without floors gets no expiry either: its sealed rows are kept.
*/
private registerExpiryPrefix(sealer: AuditSealer, engine: AuditSealerEngine, ctx: PluginContext): void {
type LifecycleLike = SealedFloorRegistrar & {
registerExpiryPrefix?: (expiry: { plan(request: AuditExpiryRequest): Promise<AuditExpiryRun[]> }) => () => void;
};
let lifecycle: LifecycleLike | undefined;
try {
lifecycle = ctx.getService<LifecycleLike>('lifecycle');
} catch {
return;
}
if (!lifecycle || typeof lifecycle.registerExpiryPrefix !== 'function') return;
if (typeof lifecycle.registerRetentionFloor !== 'function') {
ctx.logger.error(
'AuditPlugin: the lifecycle service takes a sealed-object expiry but no retention floors, so the sealed ' +
"objects' expiry is NOT registered and their rows are kept past their window. Fix: run a lifecycle " +
'service that supports retention floors (the one @objectstack/objectql ships).',
);
return;
}
const floors = lifecycle as Required<SealedFloorRegistrar>;
let failed: string | null = null;
this.refreshSealedFloors = () => {
try {
registerSealedWindowFloors(floors, engine.registry);
failed = null;
} catch (err) {
const fault = String((err as Error)?.message ?? err);
if (failed === fault) return;
failed = fault;
ctx.logger.error(
`AuditPlugin: registering the sealed objects' retention floors FAILED (${fault}); until it succeeds a ` +
'retention override may shorten a sealed object\'s declared window. Retried before every sealer pass.',
);
}
};
this.refreshSealedFloors();
// Called as a method: the service's registration reads its own state.
this.unregisterExpiryPrefix = lifecycle.registerExpiryPrefix({ plan: (request) => sealer.expire(request) });
}
/**
* 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