Repository navigation
Expand file tree
/
Copy pathapprovals-plugin.ts
More file actions
721 lines (698 loc) · 37.3 KB
/
Copy pathapprovals-plugin.ts
File metadata and controls
721 lines (698 loc) · 37.3 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type { Plugin, PluginContext } from '@objectstack/core';
import type {
IHttpServer,
II18nService,
IJobService,
IObjectQLEngine,
} from '@objectstack/spec/contracts';
import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts';
import { SysApprovalRequest } from './sys-approval-request.object.js';
import { SysApprovalAction } from './sys-approval-action.object.js';
import { SysApprovalApprover } from './sys-approval-approver.object.js';
import { SysApprovalToken } from './sys-approval-token.object.js';
import { SysApprovalDelegation } from './sys-approval-delegation.object.js';
import { SysApprovalRequestDetailPage } from './sys-approval-request.page.js';
import { renderConfirmPage, renderResultPage } from './action-link-pages.js';
import {
ApprovalService,
requestVisibilitySourceOf,
slotLabelSourceOf,
ESCALATION_JOB_NAME,
ESCALATION_SCAN_INTERVAL_MS,
type ApprovalEngine,
type ApprovalMessagingSurface,
type ApproverQueueSource,
type ObjectReadAdmission,
} from './approval-service.js';
import {
bindApprovalLockHook,
bindDelegationWriteGuard,
bindRecordDeleteCancelHook,
unbindAllHooks,
} from './lifecycle-hooks.js';
import { bindSnapshotRedactionMiddleware } from './payload-redaction-middleware.js';
import { bindSnapshotPredicateGuard } from './payload-predicate-guard.js';
import { bindRequestChildReadGates, bindRequestReadGate } from './request-read-gate.js';
import { bindReaderLocaleLabelsMiddleware } from './reader-locale-labels-middleware.js';
import type { FieldVisibilitySource } from './payload-redaction.js';
import { registerApprovalNode, type ApprovalAutomationSurface } from './approval-node.js';
import { backfillActionSlots } from './action-slot-backfill.js';
import { backfillApprovalDisplayLabels } from './display-label-backfill.js';
import { backfillProcessPackages, logProcessPackageBackfill, type FlowHolderSource } from './stored-process-package-backfill.js';
import { APPROVAL_EMAIL_TEMPLATES } from './approval-email-templates.js';
import { resolvePublicBaseUrl } from './public-base-url.js';
export interface ApprovalsPluginOptions {
/** Disable runtime registration (schemas still register). */
disableService?: boolean;
/**
* Interval between SLA escalation scans (ADR-0042). Defaults to
* {@link ESCALATION_SCAN_INTERVAL_MS} (5 min). Only takes effect when a
* `job` service is installed; without one, SLA stays display-only.
*/
escalationScanIntervalMs?: number;
/**
* Absolute origin for links in outbound notifications — the approval
* e-mail's link to the request, and ADR-0043's action link — e.g.
* `https://app.example.com`. Unset, it resolves from `OS_AUTH_URL`
* (legacy `BETTER_AUTH_URL`), then `OS_BASE_URL`; with none of them set the
* links are relative and the plugin warns once at start
* (`public-base-url.ts`).
*/
publicBaseUrl?: string;
/**
* Disable the record-lock hook. Schema + service stay intact; only the
* engine-level lock wiring is suppressed. Useful when a caller wants the
* manual API only (e.g. tests).
*/
disableAutoHooks?: boolean;
/**
* [#8652] Objects on which a user who can READ the target business record may
* also see that record's approval requests and full action history —
* **read-only**. No approval action is delivered through this tier: approve,
* reject, reassign, recall and comment keep authorizing exactly as they do
* now, on the pending-approver slate, the submitter, or admin override.
*
* ```ts
* new ApprovalsServicePlugin({ recordReaderVisibleObjects: ['exam_sheet'] })
* ```
*
* **Two sources, either one suffices.** This option is the HOST's half, for a
* host that builds the plugin itself. The other half is the object's own
* metadata — `enable: { approvalsVisibleToReaders: true }` — which a
* config-driven app (whose host builds this plugin with no options) can
* write. The service reads that declaration from the object's live
* registered definition on every read, so an object registered after boot
* takes effect and a removed flag stops widening, with no restart.
*
* **Default OFF.** Omitted (or empty), with no object declaring the flag,
* leaves visibility precisely as it is today — submitter ∪ current approver ∪
* historical actor, plus the admin override — so an existing deployment's
* confidentiality posture is unchanged on upgrade. Opting in is per object
* and deliberate: enabling it for a ledger object does not enable it anywhere
* else.
*
* **What an enabled object exposes**, so the opt-in is informed — on the
* approvals door and, for a deployment that grants read on
* `sys_approval_request`, on the generic data door alike (one rule serves
* both, `request-read-gate.ts`): the request
* row (including its `payload` snapshot of the record at submission time) and
* the full action history — actor, decision, timestamp, the action's COMMENT
* text, and any decision attachments. Enable it on objects whose approval
* commentary the record's readers are meant to see.
*
* Anchored on the existing record-read permission: the platform asks the
* engine to read the record as the caller, so object CRUD and RLS decide.
* There is no new permission, role or grant type, and no host-side hook.
*/
recordReaderVisibleObjects?: string[];
}
/**
* ApprovalsServicePlugin — registers sys_approval_{request,action}, the
* `approvals` service, the `approval` flow node executor (ADR-0019), and the
* record-lock hook.
*
* ADR-0019: approval is no longer a standalone process engine. A flow's
* Approval node opens a request and suspends the run; a decision via the
* service resumes it down the matching branch.
*/
export class ApprovalsServicePlugin implements Plugin {
name = 'com.objectstack.service.approvals';
version = '1.0.0';
type = 'standard' as const;
dependencies = ['com.objectstack.engine.objectql'];
private readonly options: ApprovalsPluginOptions;
private service?: ApprovalService;
private engine?: IObjectQLEngine;
private escalationJobScheduled = false;
/**
* Captured where the job is scheduled, not resolved at teardown: `destroy()`
* — the hook the kernel actually calls — takes NO `PluginContext`
* (`Plugin.destroy?(): Promise<void> | void`, core `types.ts`). Holding the
* very service the schedule was placed with also means the cancel cannot miss
* it because the registry has already been torn down around us.
*/
private jobService?: IJobService;
constructor(options: ApprovalsPluginOptions = {}) {
this.options = options;
}
async init(ctx: PluginContext): Promise<void> {
ctx.getService<{ register(m: any): void }>('manifest').register({
id: 'com.objectstack.service.approvals',
name: 'Approvals Service',
version: '1.0.0',
type: 'plugin',
scope: 'system',
defaultDatasource: 'cloud',
namespace: 'sys',
objects: [SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalToken, SysApprovalDelegation],
// The request's record-detail page (a full page, default for every
// sys_approval_request record): the decision panel, the request's
// fields, and its timeline. This plugin owns the object, so it ships its
// page too — the shape plugin-auth ships sys_user's. The page and its
// body are documented on `SysApprovalRequestDetailPage`.
pages: [SysApprovalRequestDetailPage],
// ADR-0029 D7 — contribute the Approvals entries into the Setup app's
// `group_approvals` slot. This plugin owns these objects (K2.b), so it
// ships their menu too; when the plugin isn't installed the slot is empty.
//
// #7234 — order inside the slot is ARRAY ORDER: `applyNavContributions`
// does `group.children.push(...c.items)` per contribution (sorted by
// `priority`), so the inbox being first in this array is what puts it
// above the raw tables. Do not reorder without meaning to.
//
// The inbox entry is the working surface (decision actions, node
// progress, drawer); the three object entries below stay as the
// admin/diagnostic view of the engine's own tables — reachable only here,
// behind `group_approvals`' `manage_platform_settings` gate.
//
// `nav_approval_requests` names `all_requests` explicitly: an entry that
// names no view opens the object's first declared list view, so an
// administrator's page would otherwise depend on `listViews` order (it
// opened the caller-scoped `my_pending` until that view moved off first
// place). The two other object entries' objects declare no caller-scoped
// view.
navigationContributions: [
{
app: 'setup',
group: 'group_approvals',
priority: 100,
items: [
{ id: 'nav_approvals_inbox', type: 'component', label: 'Approvals Inbox', componentRef: 'approvals:inbox', icon: 'list-checks' },
{ id: 'nav_approval_requests', type: 'object', label: 'Requests', objectName: 'sys_approval_request', viewName: 'all_requests', icon: 'inbox', requiresObject: 'sys_approval_request' },
{ id: 'nav_approval_actions', type: 'object', label: 'Action History', objectName: 'sys_approval_action', icon: 'history', requiresObject: 'sys_approval_action' },
{ id: 'nav_approval_delegations', type: 'object', label: 'Delegations (OOO)', objectName: 'sys_approval_delegation', icon: 'user-clock', requiresObject: 'sys_approval_delegation' },
],
},
],
});
// 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 { ApprovalsTranslations } = await import('./translations/index.js');
for (const [locale, data] of Object.entries(ApprovalsTranslations)) {
i18n.loadTranslations(locale, data as Record<string, unknown>);
}
}
} catch { /* i18n optional */ }
});
}
ctx.logger.info('ApprovalsServicePlugin: schemas registered');
}
async start(ctx: PluginContext): Promise<void> {
if (this.options.disableService) return;
// This plugin needs the engine SEEN WHOLE, not the data plane: it binds
// `registerHook` / `unregisterHooksByPackage` below. That is `objectql`,
// whose ledger entry (`CoreServiceContracts`) records it as "the SAME
// instance as `data`, seen whole" — so the alias fallback resolves the same
// object and is typed as the same contract.
let engine: IObjectQLEngine | null = null;
try { engine = ctx.getService<IObjectQLEngine>('objectql'); }
catch { try { engine = ctx.getService<IObjectQLEngine>('data'); } catch { /* ignore */ } }
if (!engine) {
ctx.logger.warn('ApprovalsServicePlugin: no ObjectQL engine — service NOT registered');
return;
}
this.engine = engine;
// The deployment's `i18n` service, read LAZILY at question time: it is
// contributed by another plugin (ADR-0029 D8) and may start after this
// one, so a reading taken here would pin its absence for the life of the
// process. `getService` THROWS on an empty slot. The one read both i18n
// consumers below ask, so they cannot disagree about which service exists.
const i18nService = (): II18nService | undefined => {
try {
const i18n = ctx.getService<II18nService>('i18n');
return typeof i18n?.t === 'function' ? i18n : undefined;
} catch {
return undefined;
}
};
// [#30509] The origin approval links are built under: the option, else the
// deployment's configured address — never a guessed one.
const publicBase = resolvePublicBaseUrl(this.options.publicBaseUrl);
if (!publicBase.url) {
ctx.logger.warn(
`ApprovalsServicePlugin: no public base URL (${publicBase.problem}) — approval e-mails link to the request with a relative URL, which a mail client cannot open. Set OS_BASE_URL (or OS_AUTH_URL) to this deployment's address, or pass the publicBaseUrl option.`,
);
}
this.service = new ApprovalService({
engine: engine as ApprovalEngine,
logger: ctx.logger,
publicBaseUrl: publicBase.url,
// [#8652] Read-only record-reader visibility. Default OFF — an absent
// option reaches the service as an empty set. This is the host's half
// only: an object's own `enable.approvalsVisibleToReaders` is read by
// the service per call, from the live registry (#22560), never folded
// into this set here, where the registry is still filling.
recordReaderVisibleObjects: this.options.recordReaderVisibleObjects,
// [ADR-0105 D9] Cross-organization approver targeting is a `group`-posture
// capability. Read LAZILY (not captured at start) because the tenancy
// service resolves its posture during its own start, which may not have
// run yet; an unresolvable posture reads as "unknown" and the guard
// stands down rather than refusing a legitimate flow on a minimal stack.
tenancyPosture: () => {
try {
const tenancy = ctx.getService<{ posture?: string }>('tenancy');
const posture = tenancy?.posture;
return typeof posture === 'string' && posture ? posture : undefined;
} catch {
return undefined;
}
},
// [#11993] Deployment override lookup for user-facing refusal copy.
// Resolved LAZILY for the reason the two providers above are: the i18n
// service is contributed by another plugin (ADR-0029 D8) and may start
// after this one. Without it the service still renders the built-in
// catalog in the caller's locale; with it, a deployment's own
// `translation` for `errors.approval_recall_not_submitter` wins — the
// override address the catalog documents, made real for this emitter.
messageTranslator: () => {
const i18n = i18nService();
if (!i18n) return undefined;
return (key: string, locale: string, params?: Record<string, unknown>) =>
i18n.t(key, locale, params);
},
// [#24863] The same service, for the approvals door's flow, step and
// object labels in the reader's locale (`reader-locale-labels.ts`).
// Without one, the door serves the labels as stored.
i18nServiceSource: i18nService,
// [ADR-0142 D6] The queue service a `queue` approver expands through.
// Resolved LAZILY for the reason the providers above are: plugin-sharing
// registers it and may start after this one. Absent, a queue approver
// expands to nobody and the warning says why.
ownershipQueues: () => {
try {
return ctx.getService<ApproverQueueSource>(OWNERSHIP_QUEUE_SERVICE);
} catch {
return undefined;
}
},
});
// [#10749] Field-visibility authority for payload-snapshot redaction.
// Resolved LAZILY on every read, for the same reason `tenancyPosture` is:
// the security plugin may register after this one, and a resolver captured
// at start would pin `undefined` for the life of the process — which here
// means "never redact", i.e. the leak this seam closes, silently reopened
// by load order. `getService` THROWS on an empty slot, so an absent
// security plugin degrades to serving snapshots exactly as before.
const fieldVisibility = (): FieldVisibilitySource | undefined => {
try {
const sec = ctx.getService<FieldVisibilitySource>('security');
return sec && typeof sec.getReadableFields === 'function' ? sec : undefined;
} catch {
return undefined;
}
};
this.service.attachFieldVisibility({
getReadableFields: (object: string, context?: unknown) => {
const sec = fieldVisibility();
return sec
? sec.getReadableFields(object, context)
: Promise.resolve(undefined);
},
// [#20964] The masked-for-this-caller answer, from the same service: the
// read projection counts a masked field readable, so the service door
// narrows by both. A service without the member answers `undefined`
// here, which the redaction reads as "cannot tell" and fails closed on
// (`resolveReadableSnapshotFields`). The generic data door below is
// handed the service itself and reads the same member directly.
getQueryableFields: (object: string, context?: unknown) => {
const sec = fieldVisibility();
return sec && typeof sec.getQueryableFields === 'function'
? sec.getQueryableFields(object, context)
: Promise.resolve(undefined);
},
});
// [#23637] The same service's object-level read admission (`canReadObject`),
// asked before a lookup target is read as the reader, so a target object
// the reader may not read at all is skipped without a logged denial
// (`ApprovalService.admittedTargetObjects`). Resolved on every read, as
// above; an absent service, or one without the member, leaves every
// target to the caller-scoped read.
this.service.attachObjectReadAdmission(() => {
try {
return ctx.getService<ObjectReadAdmission>('security');
} catch {
return undefined;
}
});
// Record lock: block edits to a record while it has a pending request.
// Record-delete cancel (#13568): void a record's pending requests when the
// record itself is deleted — the other half of the lock's lifecycle, and
// the reason `disableAutoHooks` now suppresses BOTH (a deployment that
// wants no engine-level approval wiring wants neither half; leaving the
// lock off and the cancel on would be a shape nobody asked for).
// Delegation write-guard: a self-service OOO delegation may only name the
// acting user as delegator (#1322 follow-up). All bind under the same
// package id, so unbindAllHooks clears them together.
if (!this.options.disableAutoHooks) {
try {
unbindAllHooks(engine);
// [#23618] The refusal's title is narrowed by the writer's served fields,
// through the same lazily-resolved authority the snapshot redaction reads.
// …and it is worded in the writer's locale, with the object's label in
// that locale, through the same lazily-read `i18n` service.
bindApprovalLockHook(engine, ctx.logger, fieldVisibility, i18nService);
bindRecordDeleteCancelHook(engine, this.service, ctx.logger);
bindDelegationWriteGuard(engine, ctx.logger);
// [#10749] Generic-door snapshot redaction. Registered here so the
// service door and the generic data door narrow together — see
// `payload-redaction-middleware.ts` on why one door covered alone is
// worse than none.
bindSnapshotRedactionMiddleware(engine as any, fieldVisibility, ctx.logger);
// [#21154] …and its query half: the redaction narrows only what a read
// hands back, so a filter or a group key over the snapshot would select
// on a value the reader is not served. See `payload-predicate-guard.ts`.
bindSnapshotPredicateGuard(engine as any, fieldVisibility, ctx.logger);
} catch (err: any) {
ctx.logger.warn?.('[approvals] failed to bind approval hooks', { error: err?.message });
}
}
// [#22559] The generic data door's read gate: a read of
// `sys_approval_request` there returns only the requests this service's
// own door would serve the caller — one visibility rule for both doors
// (`request-read-gate.ts`). Bound whenever the service runs, NOT behind
// `disableAutoHooks`: that switch is the record lock's (a caller driving
// the manual API), and a read through the generic door needs the gate
// whichever API wrote the row.
// [#22589] …and its child tables, `sys_approval_action` (the decision log)
// and `sys_approval_approver` (the approver index): a row there is served
// only when its request is, by the same source.
if (typeof (engine as any).registerMiddleware === 'function') {
const visibility = requestVisibilitySourceOf(this.service);
bindRequestReadGate(engine as any, visibility, ctx.logger);
bindRequestChildReadGates(engine as any, visibility, ctx.logger);
// [#27041] …and the flow and step labels in the reader's language, by
// the approvals door's own lookup (`reader-locale-labels-middleware.ts`).
// Bound beside the gate, not behind `disableAutoHooks`, for the gate's
// reason: the approvals door localizes whenever the service runs.
bindReaderLocaleLabelsMiddleware(engine as any, i18nService, ctx.logger);
} else {
ctx.logger.warn(
'ApprovalsServicePlugin: the ObjectQL engine has no middleware seam — reads of sys_approval_request, '
+ 'sys_approval_action and sys_approval_approver through the generic data door are NOT narrowed to the '
+ 'approval requests the caller may see. Grant no read on those objects to non-administrators on this stack, '
+ 'and withdraw the member baseline\'s read on sys_approval_request (member_default).',
);
}
ctx.registerService('approvals', this.service);
ctx.logger.info('ApprovalsServicePlugin: service registered');
// Optional messaging service (ADR-0012): thread interactions (reassign /
// remind / request-info / comment) notify users when present; without it
// they degrade to audit-only.
try {
// `messaging` has no contract in the ledger, so this is the named local
// surface the service itself already declares — not `any`. It omits
// members on purpose; omitting one it USES would be a compile error at
// the `attachMessaging` call, which is the whole point.
const messaging = ctx.getService<ApprovalMessagingSurface>('messaging');
if (messaging && typeof messaging.emit === 'function') {
this.service.attachMessaging(messaging);
// [#30509] The approval e-mail's text: title, body, and the link to
// the request. A messaging service without the seam renders the
// e-mail from the title and body alone.
if (typeof messaging.registerBuiltinTemplates === 'function') {
try {
messaging.registerBuiltinTemplates(APPROVAL_EMAIL_TEMPLATES);
} catch (err: any) {
ctx.logger.warn('ApprovalsServicePlugin: the approval e-mail templates were NOT registered — approval e-mails carry the notice title and body with no link to the request', {
error: err?.message ?? String(err),
});
}
}
}
} catch { /* messaging not installed */ }
// SLA escalation clock (ADR-0042): a plugin-internal job, deliberately
// NOT a flow trigger (ADR-0041 §1). Interval sweep + one catch-up scan at
// boot so a restart doesn't extend a breach by a scan period. Wired on
// kernel:ready — the job service may start after this plugin. No `job`
// service → SLA stays display-only.
const wireEscalationClock = async () => {
try {
const jobs = ctx.getService<IJobService>('job');
if (!jobs || typeof jobs.schedule !== 'function' || !this.service) return;
const svc = this.service;
const intervalMs = this.options.escalationScanIntervalMs ?? ESCALATION_SCAN_INTERVAL_MS;
// Both sweeps ride this one clock: they walk the same `pending` set, and
// the dead-run release (#3456) is reconciliation with the same "catch up
// after a restart" requirement — a run killed BY the restart is exactly
// the shape no in-band handler can clean up.
// Genuinely independent — an escalation failure must not strand locked
// records, and vice versa, so neither can short-circuit the other.
const sweep = async () => {
const results = await Promise.allSettled([
svc.runEscalations(),
svc.releaseDeadRunRequests(),
// #4469 — the other half of the dead-run picture, and the one no
// sweeper could see: a request already TERMINAL whose run is gone.
// Read-only by design (it reports; it never rewrites a decision
// that really happened), so it rides the same clock purely to make
// the finding surface without an operator knowing to go looking.
svc.inspectStrandedRequests(),
]);
for (const r of results) {
if (r.status === 'rejected') {
ctx.logger.warn?.('[approvals] periodic sweep leg failed', {
error: (r.reason as any)?.message ?? String(r.reason),
});
}
}
};
await jobs.schedule(ESCALATION_JOB_NAME, { type: 'interval', intervalMs }, sweep);
this.jobService = jobs;
this.escalationJobScheduled = true;
void sweep().catch((err: any) => {
ctx.logger.warn?.('[approvals] boot sweep failed', { error: err?.message });
});
ctx.logger.info('ApprovalsServicePlugin: SLA escalation scan scheduled', { intervalMs });
} catch { /* job service not installed */ }
};
// Actionable-link pages (ADR-0043): session-less confirm + redemption,
// mounted straight on the host Hono app. GET only renders; the decision
// happens exclusively on the POST (mail-gateway prefetch safe).
const mountActionPages = async () => {
try {
// [#4251 B5] Canonical name FIRST. This read was `http-server`-only,
// and `http-server` is the deprecated alias: the ledger records
// `http.server` as canonical and as "the ONLY name present on all
// provider paths" — `runtime.ts`'s `config.server` path registers no
// alias at all. On that path this lookup threw, the catch below
// swallowed it, and the ADR-0043 action pages silently never mounted,
// so every approval e-mail link 404'd. Same latent alias-only miss
// #4393 fixed in metadata/cloud-connection; per-name `try` because
// `getService` THROWS on an empty slot, so `a() ?? b()` in one `try`
// never reaches `b`.
const readServer = (name: string): IHttpServer | undefined => {
try { return ctx.getService<IHttpServer>(name); } catch { return undefined; }
};
const http = readServer('http.server') ?? readServer('http-server');
const rawApp = http && typeof http.getRawApp === 'function' ? http.getRawApp() : null;
if (!rawApp) ctx.logger.info('ApprovalsServicePlugin: no raw HTTP app on this kernel — the actionable-link pages are not mounted here; they are served through the HTTP dispatcher\'s /approvals/act domain, which calls the approvals service\'s handleActionPage');
if (!rawApp || !this.service) return;
const svc = this.service;
const ACT_PATH = '/api/v1/approvals/act';
const html = (c: any, body: string, status = 200) =>
c.body(body, status, { 'Content-Type': 'text/html; charset=utf-8' });
rawApp.get(ACT_PATH, async (c: any) => {
const token = String(c.req.query('token') ?? '');
const peek = await svc.peekActionToken(token);
if (!peek.ok) return html(c, renderResultPage(peek.reason, peek.request), 200);
return html(c, renderConfirmPage({
request: peek.request, action: peek.action, approverId: peek.approverId,
token, actPath: ACT_PATH,
}));
});
rawApp.post(ACT_PATH, async (c: any) => {
let token = '';
try {
const body = await c.req.parseBody();
token = String(body?.token ?? '');
} catch { /* fall through to invalid */ }
const out = await svc.redeemActionToken(token);
if (!out.ok) return html(c, renderResultPage(out.reason, out.request), 200);
return html(c, renderResultPage(out.action === 'approve' ? 'approved' : 'rejected', out.request));
});
ctx.logger.info(`ApprovalsServicePlugin: actionable-link pages mounted at ${ACT_PATH}`);
} catch { /* http server not installed */ }
};
// Pending-approver index backfill (issue #1745): rebuild the normalized
// sys_approval_approver rows from the pending_approvers CSV so requests
// written before the index existed (or drifted past a crashed sync) are
// queryable. Idempotent; cost tracks the live pending queue.
const backfillApproverIndex = async () => {
try {
const svc = this.service;
if (!svc) return;
const out = await svc.rebuildApproverIndex();
if (out.inserted > 0 || out.deleted > 0) {
ctx.logger.info('ApprovalsServicePlugin: approver index rebuilt', out);
}
} catch (err: any) {
ctx.logger.warn?.('[approvals] approver index backfill failed', { error: err?.message });
}
};
// Action-slot backfill (#21411): move the slot literals rows written
// before `acted_as` existed still hold in `actor_id`, null the machine
// sentinels earlier writers stored there (ADR-0118 D1), and give the votes
// a pending request's tally still counts their `acted_as`. Every slot
// reader reads `acted_as` with no fallback to `actor_id`, so this runs at
// boot rather than waiting for an operator. Idempotent; see the module.
//
// `error`, not `warn`: a failed run leaves the system looking normal while
// in-flight multi-approver tallies have lost the votes they already
// counted and holders have lost sight of position-slot history.
const slotEngine = engine as ApprovalEngine;
const backfillSlots = async () => {
try {
const svc = this.service;
const out = await backfillActionSlots(slotEngine, svc ? { labels: slotLabelSourceOf(svc) } : {});
if (out.literalsMoved > 0 || out.sentinelsCleared > 0 || out.votesStamped > 0) {
ctx.logger.info('ApprovalsServicePlugin: action slots backfilled', out);
}
} catch (err: any) {
ctx.logger.error(
'[approvals] action-slot backfill failed — approvals recorded before the slot column existed are '
+ 'missing from multi-approver tallies and from the already-acted visibility of the slot\'s holders, '
+ 'and stored machine actors still sit in the actor lookup where every join drops them, while '
+ 'everything else looks healthy. The repair is idempotent and runs at every boot: fix the cause '
+ 'below and restart.',
err instanceof Error ? err : undefined,
{ error: err?.message ?? String(err) },
);
}
};
// Display-label backfill (#23889): fill the approval lists' display columns
// on rows written before they existed, from stored data and by the live
// writers' own rules, null-only and idempotent; see the module. After the
// action-slot backfill, whose `acted_as` writes it labels if that pass could
// not. `warn`: a failed run leaves list cells blank — visibly — and changes
// no fact any decision, filter or index reads; the next boot retries.
const backfillDisplayLabels = async () => {
try {
const svc = this.service;
if (!svc) return;
const out = await backfillApprovalDisplayLabels(slotEngine, slotLabelSourceOf(svc));
if (out.requestsFilled > 0 || out.actionsFilled > 0) {
ctx.logger.info('ApprovalsServicePlugin: approval display labels backfilled', out);
}
} catch (err: any) {
ctx.logger.warn?.(
'[approvals] display-label backfill failed — approval list cells for rows written before the label '
+ 'columns stay blank until a later boot fills them',
{ error: err?.message ?? String(err) },
);
}
};
if (typeof (ctx as any).hook === 'function') {
(ctx as any).hook('kernel:ready', wireEscalationClock);
(ctx as any).hook('kernel:ready', mountActionPages);
(ctx as any).hook('kernel:ready', backfillApproverIndex);
(ctx as any).hook('kernel:ready', backfillSlots);
(ctx as any).hook('kernel:ready', backfillDisplayLabels);
// [ADR-0150 D8 row R7] Open requests gain the package that holds their
// flow, once the registry's bare-name holders are sealed
// (`kernel:bootstrapped`): before that, a package of this boot could
// still register and change who holds a name. The ambiguous set is
// reported, never bound; never fails the boot. A kernel that dispatches
// no boot-phase hook runs no pass. See `stored-process-package-backfill.ts`.
(ctx as any).hook('kernel:bootstrapped', async () => {
try {
let ql: { registry?: { bareNameHoldersAreSealed?: boolean } } | undefined;
let flows: Partial<FlowHolderSource> | undefined;
try { ql = ctx.getService<typeof ql>('objectql'); } catch { ql = undefined; }
try { flows = ctx.getService<Partial<FlowHolderSource>>('automation'); } catch { flows = undefined; }
if (ql?.registry?.bareNameHoldersAreSealed !== true) return;
if (!flows || typeof flows.flowHolder !== 'function') return;
const report = await backfillProcessPackages(slotEngine as any, flows as FlowHolderSource);
logProcessPackageBackfill(report, ctx.logger as any);
} catch (err: any) {
ctx.logger.warn?.(
'[approvals] the sys_approval_request.process_package backfill did not finish: open requests that name no '
+ 'package keep naming none, each reads its flow through its run, and the next boot tries again.',
{ error: err?.message ?? String(err) },
);
}
});
} else {
await wireEscalationClock();
await mountActionPages();
await backfillApproverIndex();
await backfillSlots();
await backfillDisplayLabels();
}
// ADR-0019: contribute the `approval` node to the flow engine when one is
// present. The node lets a flow suspend on an approval and resume on
// decision; the service is wired to the same engine so `decide()` can
// resume the suspended run.
//
// #4771 — the degradation must be LOUD (#4632). This used to be one
// try/catch logging at `info`, and dev's default log level is `warn`: the
// one line that says "every `approval` node in this deployment is dead"
// was invisible in exactly the deployment where it is true, while the flow
// registration was warning about `approval` in the deployments where it is
// false. The catch is also narrowed to the service *lookup*, so a genuine
// failure inside registerApprovalNode surfaces as itself instead of being
// relabelled "no automation engine".
let automation: ApprovalAutomationSurface | undefined;
try {
automation = ctx.getService<ApprovalAutomationSurface>('automation');
} catch {
automation = undefined; // no automation service registered in this stack
}
if (automation && typeof automation.registerNodeExecutor === 'function') {
this.service.attachAutomation(automation);
registerApprovalNode(automation, this.service, ctx.logger);
} else {
ctx.logger.warn(
'ApprovalsServicePlugin: no automation engine — the `approval` flow node is NOT registered. '
+ 'Every ADR-0019 approval flow in this deployment fails at execution time with NO_EXECUTOR. '
+ 'Add @objectstack/service-automation to the stack to enable them.',
);
}
}
/**
* The kernel's teardown hook (`Plugin.destroy?()`, core `types.ts`) — the
* ONLY teardown entry point `ObjectKernel.performShutdown()` and
* `LiteKernel.destroy()` invoke.
*
* [#10371] IT USED TO BE `stop()`, WHICH NOTHING CALLED. `Plugin` declares
* `init()`, `start?()` and `destroy?()` and no `stop()`, so the kernel walked
* past this plugin at shutdown: the SLA escalation job stayed scheduled and
* this plugin's ObjectQL hooks stayed bound to an engine the kernel had
* finished with. `start()` IS on the interface, so the pair read as symmetric
* in review — that asymmetry is what let the same shape survive in six
* packages at once.
*
* This member owns no timer of its own (the escalation clock belongs to
* `service-job`), so it never cost a merge-queue eviction the way the
* `plugin-reports` / `service-messaging` members did (#9371). The class is
* the same one either way: a teardown the kernel does not reach.
*/
async destroy(): Promise<void> {
if (this.escalationJobScheduled) {
try {
await this.jobService?.cancel?.(ESCALATION_JOB_NAME);
} catch { /* ignore */ }
this.escalationJobScheduled = false;
this.jobService = undefined;
}
if (this.engine) {
try { unbindAllHooks(this.engine); } catch { /* ignore */ }
}
}
/**
* Retained alias for {@link destroy}. Kept because it is public API of an
* exported class, and removing it would break an embedder who learned to call
* it directly precisely BECAUSE the kernel never did. The parameter is now
* optional and ignored: `destroy()` takes no context, so teardown uses the
* job service captured when the escalation clock was wired. Prefer kernel
* shutdown; direct callers keep working unchanged.
*/
async stop(_ctx?: PluginContext): Promise<void> {
await this.destroy();
}
}