-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapproval-service.ts
More file actions
3593 lines (3388 loc) · 164 KB
/
Copy pathapproval-service.ts
File metadata and controls
3593 lines (3388 loc) · 164 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 { createHash, randomBytes } from 'node:crypto';
import {
APPROVAL_BRANCH_LABELS,
approverTypeIsOrgScoped,
canonicalApproverType,
normalizeDecisionOutputs,
type ApprovalNodeConfig,
} from '@objectstack/spec/automation';
import { ExpressionEngine, collectCelRootIdentifiers } from '@objectstack/formula';
import {
ADMIN_FULL_ACCESS,
ORGANIZATION_ADMIN_GRANTS,
BUILTIN_IDENTITY_PLATFORM_ADMIN,
BUILTIN_IDENTITY_ORG_OWNER,
BUILTIN_IDENTITY_ORG_ADMIN,
} from '@objectstack/spec/identity';
import type {
IApprovalService,
ApprovalRequestRow,
ApprovalActionRow,
ApprovalActionAttachment,
ApprovalDecisionInput,
ApprovalDecisionResult,
ApprovalRecallInput,
ApprovalRecallResult,
ApprovalSendBackInput,
ApprovalSendBackResult,
ApprovalResubmitInput,
ApprovalResubmitResult,
ApprovalStatus,
SharingExecutionContext,
} from '@objectstack/spec/contracts';
import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts';
import { isFileIdToken } from '@objectstack/spec/data';
import { isGrantActive } from '@objectstack/core';
import {
filterApproversWhoCanRead,
resolveApproverDirectoryOrg,
type ApproverOrgScopeDeps,
type ApproverOrgScopeEngine,
} from './approver-org-scope.js';
/**
* Node-era approval runtime (ADR-0019).
*
* Approval is no longer a standalone engine — it is a **flow node**. A flow's
* Approval node opens a request via {@link ApprovalService.openNodeRequest} and
* the run suspends; a human decision via {@link ApprovalService.decide}
* finalises the request and resumes the owning run down the matching
* `approve` / `reject` edge.
*
* This service owns the durable approval *state* — `sys_approval_request` /
* `sys_approval_action`, approver resolution (team / department / position /
* role / manager graph), and the optional status-field mirror — plus the decision
* API. It does not author processes, submit, or walk multi-step machinery
* anymore; that orchestration lives on the one automation engine.
*/
export interface ApprovalEngine {
find(object: string, options?: any): Promise<any[]>;
insert(object: string, data: any, options?: any): Promise<any>;
update(object: string, idOrData: any, dataOrOptions?: any, options?: any): Promise<any>;
delete(object: string, options?: any): Promise<any>;
}
export interface ApprovalClock { now(): Date }
/**
* Minimal automation surface the service uses to resume a suspended flow run
* once a decision finalises a node-driven request. Optional — attached by the
* plugin when an automation engine is present (see `approval-node.ts`).
*/
export interface ApprovalResumeSurface {
resume?(runId: string, signal?: {
output?: Record<string, unknown>;
branchLabel?: string;
/**
* #3801: the engine refuses a resume of an `approval` suspension unless
* the signal carries this marker — the proof that the resume is the tail
* of a decision THIS service already authorized and recorded, not a raw
* `POST …/runs/:runId/resume` around it. Every resume below stamps it via
* {@link ApprovalService.serviceResume}.
*/
[RESUME_AUTHORITY_SERVICE]?: true;
}): Promise<unknown>;
/** Flow definition lookup, used to derive step-progress display data. */
getFlow?(name: string): Promise<any | null>;
/**
* Terminally cancel a suspended run (ADR-0044). Used when a recall lands
* during a revision window — the run is paused at the revise wait node,
* which has no reject edge to resume down.
*/
cancelRun?(runId: string, reason?: string): Promise<unknown>;
/**
* Look up a run's recorded outcome (#3456). Used by the dead-run sweep to ask
* "is the run behind this pending request still alive?".
*
* The contract that makes the sweep safe is the answer for a run that is
* merely SUSPENDED (the normal state of a run waiting on an approval): the
* engine writes no execution-log entry until a run reaches a terminal state,
* so a suspended run resolves to `null`, never to a status. The sweep
* therefore acts only on an explicit terminal-failure status and treats
* `null` — unknown run, evicted log, no durable store, no automation engine —
* as "still alive".
*/
getRun?(runId: string): Promise<{ status?: string } | null>;
}
/**
* Optional messaging surface (ADR-0012 `messaging` service). When attached,
* thread interactions (reassign / remind / request-info / comment) notify the
* affected users; without it they degrade to audit-only.
*/
export interface ApprovalMessagingSurface {
emit(input: {
topic: string;
audience: string[];
payload?: Record<string, unknown>;
severity?: string;
dedupKey?: string;
source?: { object: string; id: string };
actorId?: string;
}): Promise<unknown>;
}
/** Minimum time between submitter reminders on one request. */
export const REMIND_COOLDOWN_MS = 4 * 60 * 60 * 1000;
/** Named job under which the SLA escalation scan is registered (ADR-0042). */
export const ESCALATION_JOB_NAME = 'approvals-sla-escalation';
/** Default interval between SLA escalation scans. */
export const ESCALATION_SCAN_INTERVAL_MS = 5 * 60 * 1000;
/** Reserved actor id for machine decisions made by the SLA scanner. */
export const SLA_ACTOR_ID = 'system:sla';
/** Reserved actor id for requests abandoned because their run died (#3456). */
export const DEAD_RUN_ACTOR_ID = 'system:dead-run';
/**
* Run statuses that mean "this run will never resume", so a request still
* pending on it is orphaned (#3456). A CLOSED set, deliberately: the dead-run
* sweep treats every other answer — `paused` (a run waiting on its approval,
* the normal case), `running`, an unknown status, or no answer at all — as
* alive, so an unrecognised state can never cost someone a live approval.
*
* `completed` belongs here with the failure states. The approval node only
* writes a request row on the path where it also suspends the run, and every
* in-band transition (decide / recall / send-back / resubmit) finalises the
* request *before* it resumes the run — so a completed run with a still-pending
* request means the run was resumed out of band and left the request behind.
*/
const TERMINAL_RUN_STATUSES: ReadonlySet<string> = new Set([
'completed', 'failed', 'cancelled', 'timed_out',
]);
/** Default lifetime of an actionable-link token (ADR-0043). */
export const ACTION_TOKEN_TTL_MS = 72 * 60 * 60 * 1000;
/** Outcome of redeeming (or peeking) an actionable-link token. */
export type ActionTokenOutcome =
| { ok: true; action: 'approve' | 'reject'; request: ApprovalRequestRow; approverId: string }
| { ok: false; reason: 'invalid' | 'expired' | 'consumed' | 'not_pending' | 'not_approver'; request?: ApprovalRequestRow };
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const;
/**
* Who is acting, for the purpose of a data write made on their behalf (#3783).
*
* Reads the AUTHENTICATED principal off the execution context — deliberately not
* `input.actorId`. When this was written the two could still disagree: every
* public entrypoint took `actorId` from the request body (`body.actorId ??
* context.userId`, see the REST approval routes) and the service only checked
* that it named a pending approver, never that it was the caller. That was
* called tolerable on an audit row — but the same unchecked value was the
* authorization key, so it was in fact impersonation, and #3800 closed it:
* {@link ApprovalService.resolveActor} now pins the actor to an identity the
* server can prove belongs to the caller. This helper stays the separate,
* stricter answer for a DATA WRITE, which wants the bare human id and never a
* `type:value` slot literal or a machine sentinel.
*
* A caller holding a trustworthy actor with no session behind it — the ADR-0043
* action link, whose token cryptographically binds exactly one approver — puts
* that actor ON the context instead of relying on this.
*
* `null` for a machine caller (the SLA sweep passes {@link SYSTEM_CTX}), so a
* reserved sentinel like {@link SLA_ACTOR_ID} can never surface as a `userId`.
*/
function actingUserId(context: SharingExecutionContext | undefined): string | null {
const userId = (context as { userId?: unknown } | undefined)?.userId;
return typeof userId === 'string' && userId ? userId : null;
}
/**
* Max hops when following an OOO delegation chain (#1322 M1): A out → B, B out
* → C, … Bounds the walk so a mis-configured chain can't loop or resolve
* unboundedly; a cycle or self-reference also stops it early.
*/
const OOO_MAX_CHAIN = 8;
/**
* Approver types resolved by QUERYING a graph rather than by taking `value`
* literally (#3807). Each can legitimately come back empty — an unstaffed
* position, an emptied team, a mis-pointed unit — and the caller then falls
* back to a `type:value` literal that no user can act on. They are listed here
* so that dead end gets one warning instead of passing in silence.
*
* `user` / `field` are deliberately absent: they resolve to the id they were
* given without a lookup, so there is no "expanded to nobody" state to report.
* `business_unit` / `bu` are the accepted dialects of `department`.
*/
const GRAPH_APPROVER_TYPES: ReadonlySet<string> = new Set([
'team', 'department', 'business_unit', 'bu', 'position', 'org_membership_level', 'manager',
]);
/** One OOO delegation hop applied while resolving an approver (#1322 M1/M4). */
interface OooSubstitution {
/** The approver who was skipped (out of office). */
from: string;
/** The delegate the slot was routed to. */
to: string;
/** The delegator's declared reason, if any. */
reason: string | null;
}
/**
* The CLOSED set of namespace roots an `expression` approver may reference
* (#3447 P2). Three explicit times/sources, no `record`, no bare field names:
* `record` means "the record at event time" everywhere else on the platform
* (flow conditions: trigger snapshot; hooks: the write payload), so binding it
* here — to either time — would silently alias one meaning to the other. The
* runtime CEL env treats unknown roots as `dyn` (→ `null` → an empty slate),
* so out-of-contract roots MUST be rejected before evaluation; both this
* pre-check and the lint rule read the roots via
* {@link collectCelRootIdentifiers} so they can never drift.
*/
const APPROVER_EXPRESSION_ROOTS = new Set(['current', 'trigger', 'vars']);
/**
* Evaluation context an approval node hands to `expression` approvers
* (#3447 P2). `current` (the live record) is supplied by openNodeRequest's
* re-read; these two carry the other roots.
*/
export interface ApproverExpressionContext {
/** Submit-time snapshot (the flow's `$record`) — bound as `trigger.*`. */
trigger?: Record<string, unknown> | null;
/** Flow variables at node entry (nested by dotted key) — bound as `vars.*`. */
vars?: Record<string, unknown> | null;
}
/**
* Non-request outcome of {@link ApprovalService.openNodeRequest}: the node
* resolved an empty approver slate and its `onEmptyApprovers: 'auto_approve'`
* policy waved it through (#3447 P2). No `sys_approval_request` row exists —
* nobody was ever asked — so the node must complete down its `approve` edge
* instead of suspending.
*/
export interface ApprovalNodeAutoOutcome {
autoApproved: true;
reason: 'empty_approvers';
}
function uid(prefix: string): string {
const g: any = globalThis as any;
if (g.crypto?.randomUUID) return `${prefix}_${g.crypto.randomUUID()}`;
return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}
function parseJson<T = any>(raw: unknown, fallback: T): T {
if (raw == null || raw === '') return fallback;
if (typeof raw === 'string') {
try { return JSON.parse(raw) as T; } catch { return fallback; }
}
return raw as T;
}
function csvSplit(raw: unknown): string[] {
if (!raw) return [];
if (Array.isArray(raw)) return raw.map(String).filter(Boolean);
return String(raw).split(',').map(s => s.trim()).filter(Boolean);
}
/**
* Humanize a machine name for display fallback: strips a `flow:` prefix and
* title-cases underscore/dash segments (`flow:manager_review` → "Manager
* Review"). Used only when no authored label was snapshotted on the row.
*/
function prettifyMachineName(raw: string | null | undefined): string | undefined {
if (!raw) return undefined;
const base = String(raw).replace(/^flow:/, '').trim();
if (!base) return undefined;
return base
.split(/[_\-\s]+/)
.filter(Boolean)
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ');
}
function rowFromRequest(row: any): ApprovalRequestRow {
// Authored display labels ride the node-config snapshot (`__flowLabel` /
// `__nodeLabel`) so they survive without a schema migration; fall back to a
// prettified machine name for rows written before labels were captured.
const cfg = parseJson<any>(row.node_config_json, undefined);
return {
id: String(row.id),
organization_id: row.organization_id ?? undefined,
process_name: String(row.process_name ?? ''),
object_name: String(row.object_name ?? ''),
record_id: String(row.record_id ?? ''),
submitter_id: row.submitter_id ?? undefined,
submitter_comment: row.submitter_comment ?? undefined,
status: (row.status as ApprovalStatus) ?? 'pending',
current_step: row.current_step ?? undefined,
current_step_index: row.current_step_index ?? undefined,
pending_approvers: csvSplit(row.pending_approvers),
payload: parseJson(row.payload_json, undefined),
flow_run_id: row.flow_run_id ?? undefined,
flow_node_id: row.flow_node_id ?? undefined,
completed_at: row.completed_at ?? undefined,
created_at: row.created_at ?? undefined,
updated_at: row.updated_at ?? undefined,
// The row is created at submission time; expose the stable inbox-facing name.
submitted_at: row.created_at ?? undefined,
process_label: cfg?.__flowLabel ?? prettifyMachineName(row.process_name),
step_label: cfg?.__nodeLabel ?? prettifyMachineName(row.current_step),
sla_due_at: slaDueAt(row.created_at, cfg),
// ADR-0044 revision round (rides the config snapshot; absent ⇒ round 1).
round: typeof cfg?.__round === 'number' ? cfg.__round : undefined,
// #3447 P2: the node's author-declared decision outputs, surfaced so a
// decision UI can render input fields for them and POST `outputs` on
// approve/reject. Per-request (each node declares its own), which is why
// this rides the row instead of the static action params. Two shapes for
// version skew: `decision_outputs` stays the bare KEY list an older
// console renders as text inputs; `decision_output_defs` carries the
// normalized typed declarations a picker-aware console prefers.
...(() => {
const defs = normalizeDecisionOutputs(cfg?.decisionOutputs);
return defs.length
? { decision_outputs: defs.map(d => d.key), decision_output_defs: defs }
: {};
})(),
} as any;
}
/** `created_at + escalation.timeoutHours`, when the node declares an SLA. */
function slaDueAt(createdAt: unknown, cfg: any): string | undefined {
const hours = cfg?.escalation?.timeoutHours;
if (typeof hours !== 'number' || hours <= 0 || !createdAt) return undefined;
const t = Date.parse(String(createdAt));
if (Number.isNaN(t)) return undefined;
return new Date(t + hours * 3600_000).toISOString();
}
/**
* Normalize one raw `attachments` entry into an {@link ApprovalActionAttachment}.
*
* `sys_approval_action.attachments` is a `Field.file` (multiple), so the column
* **stores opaque `sys_file` ids** — that is the stored form of every media
* field (ADR-0104 D3). What arrives here is whichever of three forms the read
* path produced:
*
* 1. the **expanded** `{ id, name, size, mimeType, url }` the ObjectQL read
* path resolves a stored id into — the normal case;
* 2. a **bare id**, when there was nothing to expand it into (storage service
* absent, file not committed);
* 3. a **legacy inline blob** (`{ file_id, name, mime_type, url, … }`) written
* before file-as-reference, until the backfill converts it.
*
* The original mapping did `String(entry)`, which turned form 1 into the
* literal `"[object Object]"` — so the inbox timeline showed a nameless,
* un-openable attachment chip (#3266 follow-up; caught by browser verification).
*
* Note the casing: the expanded form carries `mimeType`, the legacy blob
* `mime_type`. Both are accepted for the duration of the migration window.
*/
function normalizeActionAttachment(entry: any): ApprovalActionAttachment | undefined {
if (entry == null) return undefined;
// Form 2 — a bare reference. `isFileIdToken` is the platform's single arbiter
// of "is this string an opaque file id, or a URL?", shared with the engine's
// read resolver, so the two cannot disagree about what counts as an id.
if (typeof entry === 'string') {
const id = entry.trim();
if (!id) return undefined;
return isFileIdToken(id) ? { id } : { id, url: id };
}
if (typeof entry === 'object') {
// Forms 1 and 3 — `file_id` is the legacy blob's key for the same thing.
const id = entry.id ?? entry.file_id;
if (id == null || String(id) === '') return undefined;
const mimeType = entry.mimeType ?? entry.mime_type;
return {
id: String(id),
name: typeof entry.name === 'string' ? entry.name : undefined,
url: typeof entry.url === 'string' ? entry.url : undefined,
mimeType: typeof mimeType === 'string' ? mimeType : undefined,
size: typeof entry.size === 'number' ? entry.size : undefined,
};
}
return undefined;
}
function rowFromAction(row: any): ApprovalActionRow {
const attachments = Array.isArray(row.attachments)
? row.attachments.map(normalizeActionAttachment).filter((a: ApprovalActionAttachment | undefined): a is ApprovalActionAttachment => !!a)
: [];
return {
id: String(row.id),
request_id: String(row.request_id),
step_name: row.step_name ?? undefined,
step_index: row.step_index ?? undefined,
action: row.action,
actor_id: row.actor_id ?? undefined,
comment: row.comment ?? undefined,
// Decision attachments (#3266): rich descriptors carrying the display name +
// download URL, so consumers label/open them without reading `sys_file`.
attachments: attachments.length ? attachments : undefined,
created_at: row.created_at ?? undefined,
};
}
export interface ApprovalServiceOptions {
engine: ApprovalEngine;
clock?: ApprovalClock;
logger?: { info?: (msg: any, ...rest: any[]) => void; warn?: (msg: any, ...rest: any[]) => void; error?: (msg: any, ...rest: any[]) => void; debug?: (msg: any, ...rest: any[]) => void };
/**
* Optional automation surface used to resume a suspended flow run when a
* decision finalises a request. Usually attached after construction via
* {@link ApprovalService.attachAutomation} once the automation engine is
* available.
*/
automation?: ApprovalResumeSurface;
/** Optional messaging service for thread notifications. */
messaging?: ApprovalMessagingSurface;
/**
* Absolute origin prefixed onto actionable links (ADR-0043), e.g.
* `https://app.example.com`. Defaults to relative URLs, which work inside
* the Console and IM webviews; outbound email needs the absolute form.
*/
publicBaseUrl?: string;
/**
* [ADR-0105 D9] The tenancy posture in force. Cross-organization approver
* targeting is a `group`-posture capability; the resolver refuses the
* declaration under any other posture rather than silently ignoring it.
* Absent (a stack booted with no tenancy service) reads as "unknown" and the
* guard stands down.
*/
tenancyPosture?: () => string | undefined;
}
export class ApprovalService implements IApprovalService {
private readonly engine: ApprovalEngine;
private readonly clock: ApprovalClock;
private readonly logger?: ApprovalServiceOptions['logger'];
private automation?: ApprovalResumeSurface;
private messaging?: ApprovalMessagingSurface;
private publicBaseUrl: string;
private tenancyPosture?: () => string | undefined;
constructor(opts: ApprovalServiceOptions) {
this.engine = opts.engine;
this.clock = opts.clock ?? { now: () => new Date() };
this.logger = opts.logger;
this.automation = opts.automation;
this.messaging = opts.messaging;
this.publicBaseUrl = (opts.publicBaseUrl ?? '').replace(/\/$/, '');
this.tenancyPosture = opts.tenancyPosture;
}
/** Attach (or replace) the ADR-0105 D9 posture provider. */
attachTenancyPosture(provider: () => string | undefined): void {
this.tenancyPosture = provider;
}
/** Deps bundle for the ADR-0105 D9 org-scope helpers. */
private get orgScopeDeps(): ApproverOrgScopeDeps {
return {
engine: this.engine as unknown as ApproverOrgScopeEngine,
posture: this.tenancyPosture,
logger: this.logger,
};
}
/**
* [ADR-0105 D9] Which organization's directory resolves ONE approver spec.
* Absent declaration ⇒ the request's own organization (unchanged, no reads).
*/
private async directoryOrgFor(a: any, requestOrgId: string | null | undefined): Promise<string | null | undefined> {
const rawType = String(a?.type ?? '');
return resolveApproverDirectoryOrg(
this.orgScopeDeps,
a?.organization,
requestOrgId,
rawType,
approverTypeIsOrgScoped(rawType),
);
}
/** Attach (or replace) the automation surface used to resume flow runs. */
attachAutomation(automation: ApprovalResumeSurface): void {
this.automation = automation;
}
/** Attach (or replace) the messaging surface used for thread notifications. */
attachMessaging(messaging: ApprovalMessagingSurface): void {
this.messaging = messaging;
}
/** Best-effort notification fan-out — failures only log. */
private async notify(input: {
topic: string;
audience: string[];
payload?: Record<string, unknown>;
dedupKey?: string;
source?: { object: string; id: string };
actorId?: string;
}): Promise<number> {
const audience = input.audience.filter(a => a && !a.includes(':'));
if (!this.messaging || !audience.length) return 0;
// Deep-link the inbox (#2678 P1.5): a notification about one request should
// land on that request, not the bare inbox. Rewritten centrally so every
// call site — and any future one — inherits it; the query param is read by
// the console inbox to auto-open the drawer.
let payload = input.payload;
if (
payload?.actionUrl === '/system/approvals'
&& input.source?.object === 'sys_approval_request'
&& input.source.id
) {
payload = { ...payload, actionUrl: `/system/approvals?request=${encodeURIComponent(input.source.id)}` };
}
try {
await this.messaging.emit({ severity: 'info', ...input, payload, audience });
return audience.length;
} catch (err: any) {
this.logger?.warn?.('[approvals] notification failed', {
topic: input.topic, error: err?.message ?? String(err),
});
return 0;
}
}
/** Load a request row and assert it is still pending. */
private async loadPendingRow(requestId: string): Promise<any> {
if (!requestId) throw new Error('VALIDATION_FAILED: requestId is required');
const rows = await this.engine.find('sys_approval_request', {
where: { id: requestId }, limit: 1, context: SYSTEM_CTX,
});
const raw: any = Array.isArray(rows) ? rows[0] : null;
if (!raw) throw new Error(`REQUEST_NOT_FOUND: ${requestId}`);
if (raw.status !== 'pending') throw new Error(`INVALID_STATE: request is ${raw.status}`);
return raw;
}
/**
* Privileged-override gate (#3424). A stuck approval — one routed to a
* position/team with no holders (so its `pending_approvers` is only an
* unresolvable `type:value` literal) or to approvers who have all since left —
* is otherwise undecidable: no concrete user is in the slate, so every normal
* `decide` / `reassign` / `recall` is `FORBIDDEN` and (with `lockRecord`) the
* record stays locked forever with no in-product recovery. A platform or
* tenant admin — the same posture the engine's superuser bypass already
* trusts — may always act on a PENDING request to release it: approve, reject,
* reassign it to a real approver, or recall it.
*
* A platform admin crosses the tenant wall (matching the unscoped
* `admin_full_access` evidence); a tenant admin may override only within their
* own org (or an org-less request). A system context always passes. Signals are
* read defensively off the resolved exec context (`permissions` / `positions` /
* the derived `posture`, ADR-0095) so any transport that resolves through the
* shared authz resolver lights this up without extra wiring.
*/
private isOverrideActor(context: SharingExecutionContext, requestOrg?: string | null): boolean {
if (!context) return false;
if (context.isSystem) return true;
const perms = Array.isArray(context.permissions) ? context.permissions : [];
const positions = Array.isArray(context.positions) ? context.positions : [];
const posture = (context as any).posture;
const isPlatformAdmin = posture === 'PLATFORM_ADMIN'
|| perms.includes(ADMIN_FULL_ACCESS)
|| positions.includes(BUILTIN_IDENTITY_PLATFORM_ADMIN);
if (isPlatformAdmin) return true;
const isTenantAdmin = posture === 'TENANT_ADMIN'
|| ORGANIZATION_ADMIN_GRANTS.some((n) => perms.includes(n))
|| positions.includes(BUILTIN_IDENTITY_ORG_OWNER)
|| positions.includes(BUILTIN_IDENTITY_ORG_ADMIN);
if (!isTenantAdmin) return false;
// A tenant admin's authority stops at their own org; a null-org request is
// global and any admin may release it.
const actorTenant = (context as any).tenantId ?? (context as any).organizationId ?? null;
return requestOrg == null || (actorTenant != null && String(requestOrg) === String(actorTenant));
}
/**
* Pin the acting identity to the AUTHENTICATED CALLER (#3800).
*
* Every public entrypoint accepts an `actorId`, and the REST routes fill it
* from `body.actorId ?? body.actor_id ?? context.userId` — so before this
* gate the body won. The authorization checks downstream all read that value
* (`pending_approvers.includes(input.actorId)`, `submitter_id === actorId`),
* which made the body-supplied string not merely the audit label but the key
* that opens the door: any authenticated user could name a pending approver
* and have that approver's decision recorded and the owning flow resumed.
* #3783 drew this line for the data-write identity ({@link actingUserId});
* this closes the authorization half.
*
* A caller may still name an identity OTHER than their bare user id, because
* a slot legitimately can be keyed by one: `resolveApproverSpec` stores the
* `type:value` literal when a graph lookup yields nothing, and an author may
* write an email as a `user` approver. So the rule is not "actorId must equal
* userId" — it is **"actorId must be an identity the SERVER can prove belongs
* to the caller"**. Anything else is `FORBIDDEN`.
*
* A system context is exempt and keeps its explicit actor: the SLA sweep
* passes the reserved {@link SLA_ACTOR_ID} sentinel, and the ADR-0043 action
* link passes the approver its single-use token is cryptographically bound to
* (having also put them on the context). Those are the only two callers that
* hold a trustworthy actor with no session behind them.
*
* A caller with NO identity at all cannot act. That case is reachable: the
* REST anonymous-deny only fires when `api.requireAuth` is set, so without it
* an anonymous request previously decided approvals outright by naming one.
*/
private async resolveActor(
actorId: string | undefined,
context: SharingExecutionContext,
): Promise<string> {
// The machine callers — their actor is server-minted, not caller-supplied.
if (context?.isSystem) {
if (!actorId) throw new Error('VALIDATION_FAILED: actorId is required');
return actorId;
}
const uid = actingUserId(context);
if (!uid) {
throw new Error('FORBIDDEN: an approval action requires an authenticated caller');
}
// The common case: no actor named, or the caller named themselves.
if (!actorId || String(actorId) === uid) return uid;
// Named something else — allow it ONLY if the server can prove the caller
// holds that identity. `positions` is resolved by the shared authz resolver
// (never client-supplied); `role:` is the ADR-0090 D3 deprecated spelling
// that 15.x-era slots and the Console's own identity list still carry.
const named = String(actorId);
for (const position of context.positions ?? []) {
if (named === `position:${position}` || named === `role:${position}`) return named;
}
// Email last — it costs a read, so only when nothing cheaper matched.
if (named.includes('@') && await this.callerHasEmail(uid, named)) return named;
throw new Error(
`FORBIDDEN: cannot act as '${named}' — an approval action is recorded against the authenticated caller`,
);
}
/** Does `userId`'s own account carry `email`? (Slots keyed by email, #3800.) */
private async callerHasEmail(userId: string, email: string): Promise<boolean> {
try {
const rows = await this.engine.find('sys_user', {
where: { id: userId }, limit: 1, context: SYSTEM_CTX,
});
const row: any = Array.isArray(rows) ? rows[0] : null;
return !!row?.email && String(row.email).toLowerCase() === email.toLowerCase();
} catch {
return false;
}
}
/**
* Expand the approvers on an Approval node into user IDs by querying the
* graph tables for `team:` / `department:` / `position:` /
* `org_membership_level:` / `manager:` approver types. Falls back to a
* prefixed literal (`type:value`) when graph lookups produce nothing — so
* existing fixtures and flows that rely on substring matching keep working.
*
* **Graph semantics:**
* - `team` → flat members of `sys_team` (better-auth; no BFS)
* - `department` → recursive BFS of `sys_business_unit.parent_business_unit_id`
* → members of every descendant via `sys_business_unit_member`
* - `position` → holders via `sys_user_position` ∪ `sys_member.role`
* transition source (ADR-0090 D3 / ADR-0057 D4)
* - `org_membership_level`
* → users with `sys_member.role = value` in tenant — the
* better-auth MEMBERSHIP TIER (owner/admin/member), not a
* position; author `position` for org positions
* - `manager` → `sys_user.manager_id` of `record[value] ?? record.owner_id`
* - `field` → literal user id stored in `record[value]`
* - `user` → literal value
*
* `role` is accepted as the deprecated spelling of `org_membership_level`
* (ADR-0090 D3) for one window: it resolves identically and logs a warning.
*
* **Out-of-office (#1322 M1):** individually-routed approvers — the ones that
* resolve to a specific person (`user` / `field` / `manager`) — are passed
* through {@link ApprovalService.applyOooDelegation}, which reroutes them onto
* an active delegate when the resolved user has declared OOO. Group/graph
* approvers (`team` / `department` / `position` / `org_membership_level`) are
* left untouched: a group still has its other members, and position-routed
* leave is already covered by ADR-0091 job delegation. Pass an `opts.now` /
* `opts.substitutions` collector to record the hops for audit + notification.
*/
private async expandApprovers(
step: any,
record?: any,
organizationId?: string | null,
opts?: {
now?: number;
substitutions?: OooSubstitution[];
groups?: Record<string, string[]>;
/** #3447 P2: `trigger`/`vars` roots for `expression` approvers. */
exprCtx?: ApproverExpressionContext;
/**
* #3447 P2 audit collector: what each dynamic spec resolved FROM (the
* live field value / the expression's intermediate values), snapshotted
* as `__resolvedFrom` so "why these people" stays answerable later.
*/
resolvedFrom?: Record<string, unknown>;
},
): Promise<string[]> {
if (!step || !Array.isArray(step.approvers)) return [];
const now = opts?.now ?? this.clock.now().getTime();
const out: string[] = [];
const specs: any[] = step.approvers;
for (let idx = 0; idx < specs.length; idx++) {
const a = specs[idx];
if (!a) continue;
// Approvers without an explicit `group` each form their own group keyed
// by position (#3266), so a plain per-approver list behaves predictably.
const groupKey = a.group != null && String(a.group) !== '' ? String(a.group) : `#${idx}`;
// #3447 P2: `expression` approvers resolve OUTSIDE resolveApproverSpec —
// a graph-expanded expression (resolveAs: department/…) must key each
// intermediate value as its own per_group group, which the flat string[]
// contract of resolveApproverSpec cannot carry.
if (canonicalApproverType(String(a.type)) === 'expression') {
const resolved = await this.resolveExpressionApprovers(
a, record, organizationId, now, opts?.substitutions, opts?.exprCtx,
);
if (opts?.resolvedFrom) opts.resolvedFrom[`expression#${idx}`] = resolved.raw;
for (const entry of resolved.slots) {
if (!entry.id) continue;
out.push(entry.id);
if (opts?.groups) {
(opts.groups[entry.id] ??= []).push(entry.subGroup ? `${groupKey}:${entry.subGroup}` : groupKey);
}
}
continue;
}
if (opts?.resolvedFrom && canonicalApproverType(String(a.type)) === 'field' && a.value != null) {
opts.resolvedFrom[`field:${a.value}`] = (record as any)?.[a.value] ?? null;
}
const ids = await this.resolveApproverSpec(a, record, organizationId, now, opts?.substitutions);
// per_group (#3266): tag each resolved id with this spec's group.
for (const u of ids) {
if (!u) continue;
out.push(u);
if (opts?.groups) (opts.groups[u] ??= []).push(groupKey);
}
}
return out.filter(Boolean);
}
/**
* Resolve ONE approver spec to concrete approver identities, applying OOO
* substitution (#1322) to individually-routed types. Extracted from
* {@link ApprovalService.expandApprovers} so the caller can tag each spec's
* resolved ids with a group (#3266) without duplicating the resolution logic.
* Returns the `type:value` literal as a single-element fallback when a graph
* lookup yields nothing — same behaviour as before the extraction.
*/
private async resolveApproverSpec(
a: any,
record: any,
organizationId: string | null | undefined,
now: number,
substitutions?: OooSubstitution[],
): Promise<string[]> {
// ADR-0090 D3: `role` is the deprecated spelling of `org_membership_level`.
// Resolve on the canonical type, but keep the AUTHORED spelling in the
// `type:value` fallback below — stored `sys_approval_approver` rows and
// `pending_approvers` slots from 15.x carry the old literal.
const type = canonicalApproverType(String(a.type));
if (type !== a.type) {
this.logger?.warn?.(
`[approvals] approver type '${a.type}' is deprecated (ADR-0090 D3) — author '${type}' instead`,
{ deprecated: a.type, canonical: type },
);
}
if (type === 'user') {
return this.applyOooDelegation(String(a.value), now, organizationId, substitutions);
}
if (type === 'field' && record) {
// #3447: a record field can name MANY approvers — a multi-select user
// field arrives as an array (or a legacy CSV string). Fan each out into
// its own slot and OOO-substitute per person; collapsing to `String(...)`
// (→ `'u1,u2'`) would mint one bogus approver id and skip every delegate.
const out: string[] = [];
for (const id of csvSplit((record as any)[a.value])) {
out.push(...await this.applyOooDelegation(id, now, organizationId, substitutions));
}
return out;
}
// [ADR-0105 D9] WHERE this approver is looked up — the request's own
// organization unless the spec targets another one in the same group.
// Resolution failures propagate: they are routing bugs, and this call is
// OUTSIDE the swallowing try below on purpose (see the catch's comment).
const directoryOrg = await this.directoryOrgFor(a, organizationId);
const crossOrg = directoryOrg !== organizationId;
// A cross-org slate is filtered to the people who can actually READ the
// request (D2 union); same-org routing is untouched and does no extra read.
const bounded = async (users: string[]): Promise<string[]> => (
crossOrg
? filterApproversWhoCanRead(this.orgScopeDeps, users, organizationId, {
approverType: type, value: a.value != null ? String(a.value) : undefined,
directoryOrgId: directoryOrg,
})
: users
);
try {
if (type === 'team') {
const users = await this.expandTeamUsers(String(a.value));
if (users.length) return users;
} else if (type === 'department' || type === 'business_unit' || type === 'bu') {
const users = await bounded(await this.expandBusinessUnitUsers(String(a.value), directoryOrg));
if (users.length) return users;
} else if (type === 'position') {
const users = await bounded(await this.expandPositionUsers(String(a.value), directoryOrg));
if (users.length) return users;
} else if (type === 'org_membership_level') {
const users = await bounded(await this.expandMembershipTierUsers(String(a.value), directoryOrg));
if (users.length) return users;
} else if (type === 'manager' && record) {
const subject = (record as any)[a.value] ?? (record as any).owner_id;
if (subject) {
const mgr = await this.lookupManager(String(subject));
if (mgr) return this.applyOooDelegation(mgr, now, organizationId, substitutions);
}
}
} catch { /* a directory lookup failed → fall through to the literal slot */ }
// #3508: `queue` is declared-but-unenforced — there is no queue branch
// above, so a queue approver always lands here and the `queue:<id>` slot
// routes to nobody. The spec marks it non-authorable
// (NON_AUTHORABLE_APPROVER_TYPES) so designers stop offering it; warn for
// the stored flows that still carry one, so the silent dead slot is at
// least visible to operators.
if (type === 'queue') {
this.logger?.warn?.(
`[approvals] approver type 'queue' is not implemented — the slot resolves to nobody (#3508)`,
{ value: a.value },
);
} else if (GRAPH_APPROVER_TYPES.has(type)) {
// #3807 follow-up — every OTHER way to land here is a graph type whose
// lookup produced nobody, and the literal below is a slot no user can
// ever act on. That silence is what let #3807 hide: a `department`
// approver pointing at a seeded (env-wide) unit resolved to
// `department:<id>` on every request, the request opened with an empty
// slate, and nothing in the logs said so — the first symptom was a
// permanently stuck approval (#3424). The fallback itself stays (a
// literal keeps 15.x slots and substring fixtures working); it just
// stops being invisible.
this.logger?.warn?.(
`[approvals] approver '${type}:${a.value}' expanded to nobody — the slot routes to no one `
+ `and the request cannot advance until someone is added or the approver is re-pointed (#3807)`,
{ type, value: a.value, organizationId: organizationId ?? null },
);
}
return [`${a.type}:${a.value}`];
}
/**
* Resolve an `expression` approver (#3447 P2): evaluate its CEL source at
* node entry against the three explicit roots — `current` (live record),
* `trigger` (submit snapshot), `vars` (flow variables) — then expand the
* result into people per `resolveAs`.
*
* Every failure here THROWS (config/parse errors as `VALIDATION_FAILED`,
* evaluation faults as `EXPRESSION_FAILED`) so the approval node fails
* loudly instead of opening a request routed to nobody — an approver
* expression that cannot run is a routing bug, never "condition not met".
* Error messages carry the correct spelling because their primary reader is
* the AI author fixing the flow on the next validate pass.
*
* Returns `slots` (approver id + optional per_group sub-key) and `raw` (the
* expression's own values, pre-expansion) for the `__resolvedFrom` audit.
*/
private async resolveExpressionApprovers(
a: any,
liveRecord: any,
organizationId: string | null | undefined,
now: number,
substitutions?: OooSubstitution[],
exprCtx?: ApproverExpressionContext,
): Promise<{ slots: Array<{ id: string; subGroup?: string }>; raw: string[] }> {
const source = String(a.value ?? '').trim();
if (!source) {
throw new Error('VALIDATION_FAILED: expression approver has an empty expression');
}
// Closed-root pre-check. The runtime env resolves ANY unknown root as dyn →
// null, so `record.x` / a bare field would silently yield an empty slate;
// reject it here with the correct spelling instead.
const parsed = collectCelRootIdentifiers(source);
if (!parsed.ok) {
throw new Error(`VALIDATION_FAILED: expression approver does not parse: ${parsed.error} — source: \`${source}\``);
}
const illegal = parsed.roots.filter(r => !APPROVER_EXPRESSION_ROOTS.has(r));
if (illegal.length) {
const hint = illegal.includes('record') || illegal.includes('previous')
? `\`record\`/\`previous\` are not bound here — write \`current.<field>\` for the record's live state `
+ `at node entry, or \`trigger.<field>\` for the submit-time snapshot (\`vars.previous\` carries the pre-update row)`
: `did you mean \`current.<field>\` (live record), \`trigger.<field>\` (submit snapshot), or \`vars.<name>\` (flow variable)?`;
throw new Error(
`VALIDATION_FAILED: expression approver references \`${illegal.join('`, `')}\` — `
+ `only \`current.*\`, \`trigger.*\` and \`vars.*\` are available; ${hint}. Source: \`${source}\``,
);
}
const result = ExpressionEngine.evaluate(
{ dialect: 'cel', source },
{ extra: { current: liveRecord ?? {}, trigger: exprCtx?.trigger ?? {}, vars: exprCtx?.vars ?? {} } },
);
if (!result.ok) {
throw new Error(
`EXPRESSION_FAILED: expression approver failed to evaluate (${result.error.kind}): `
+ `${result.error.message} — source: \`${source}\``,
);
}
// Normalize to a string list: a user-id/CSV string, an array of ids, or
// null/empty (an EMPTY slate — legal, handled by onEmptyApprovers). Any
// other shape is a config bug, rejected loudly.
const value = result.value as unknown;
let raw: string[];
if (value == null || value === '') {
raw = [];
} else if (typeof value === 'string') {
raw = csvSplit(value);
} else if (Array.isArray(value)) {
const bad = value.find(v => v != null && typeof v !== 'string' && typeof v !== 'number');
if (bad !== undefined) {
throw new Error(
`EXPRESSION_FAILED: expression approver must yield ids (string / CSV / string array), `
+ `got an array containing ${typeof bad} — source: \`${source}\``,
);
}
raw = value.map(v => String(v ?? '').trim()).filter(Boolean);
} else {
throw new Error(
`EXPRESSION_FAILED: expression approver must yield ids (string / CSV / string array), `
+ `got ${typeof value} — source: \`${source}\``,
);
}
// `resolveAs` expansion. `user` (default): each value IS a person —
// individually routed, so OOO delegation applies (#1322). Graph kinds
// re-expand each value through the same lookups the static types use; a
// group still has its other members, so like the static graph types they
// are NOT OOO-substituted, and with per_group each intermediate value
// forms its own sub-group (one sign-off per returned department). A value
// whose expansion is empty keeps a `<kind>:<value>` literal slot — same
// unstaffed-target behaviour (and #3424 admin rescue) as the static types.
const resolveAs = String(a.resolveAs ?? 'user');
if (resolveAs === 'user') {
const slots: Array<{ id: string }> = [];
for (const id of raw) {
for (const routed of await this.applyOooDelegation(id, now, organizationId, substitutions)) {
slots.push({ id: routed });
}
}
return { slots, raw };
}
// [ADR-0105 D9] An expression that re-expands into a graph kind consults the
// same org-scoped directories the static types do, so it honours the same
// targeting. Resolved once for the whole slate, before the per-value loop —
// the declaration is a property of the spec, not of what the CEL returned.
const directoryOrg = await this.directoryOrgFor(a, organizationId);
const crossOrg = directoryOrg !== organizationId;
const slots: Array<{ id: string; subGroup: string }> = [];
for (const key of raw) {
let users: string[] = [];
try {
if (resolveAs === 'department') users = await this.expandBusinessUnitUsers(key, directoryOrg);
else if (resolveAs === 'position') users = await this.expandPositionUsers(key, directoryOrg);
else if (resolveAs === 'team') users = await this.expandTeamUsers(key);
else {
throw new Error(
`VALIDATION_FAILED: expression approver has unknown resolveAs '${resolveAs}' — `
+ `use 'user', 'department', 'position', or 'team'`,
);
}
} catch (err: any) {
if (String(err?.message ?? '').startsWith('VALIDATION_FAILED')) throw err;
users = [];
}
if (crossOrg && users.length) {
users = await filterApproversWhoCanRead(this.orgScopeDeps, users, organizationId, {
approverType: resolveAs, value: key, directoryOrgId: directoryOrg,
});
}
if (!users.length) {
slots.push({ id: `${resolveAs}:${key}`, subGroup: key });