-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapproval-service.ts
More file actions
2360 lines (2205 loc) · 104 KB
/
Copy pathapproval-service.ts
File metadata and controls
2360 lines (2205 loc) · 104 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,
canonicalApproverType,
type ApprovalNodeConfig,
} from '@objectstack/spec/automation';
import type {
IApprovalService,
ApprovalRequestRow,
ApprovalActionRow,
ApprovalDecisionInput,
ApprovalDecisionResult,
ApprovalRecallInput,
ApprovalRecallResult,
ApprovalSendBackInput,
ApprovalSendBackResult,
ApprovalResubmitInput,
ApprovalResubmitResult,
ApprovalStatus,
SharingExecutionContext,
} from '@objectstack/spec/contracts';
import { isGrantActive } from '@objectstack/core';
/**
* 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 }): 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>;
}
/**
* 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';
/** 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;
/**
* 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;
/** 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;
}
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,
} 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();
}
function rowFromAction(row: any): ApprovalActionRow {
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). The column shipped in #3268 but this
// contract mapping didn't — the raw engine row carried the fileIds while
// every consumer of listActions saw none (caught by browser verification).
attachments: Array.isArray(row.attachments) && row.attachments.length ? row.attachments.map(String) : 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;
}
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;
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(/\/$/, '');
}
/** 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;
}
/**
* 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[]> },
): 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;
const ids = await this.resolveApproverSpec(a, record, organizationId, now, opts?.substitutions);
// per_group (#3266): tag each resolved id with this spec's group. An
// approver without an explicit `group` forms its own group keyed by
// position, so a plain per-approver list still behaves predictably.
const groupKey = a.group != null && String(a.group) !== '' ? String(a.group) : `#${idx}`;
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) {
return this.applyOooDelegation(String((record as any)[a.value] ?? ''), now, organizationId, substitutions);
}
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 this.expandBusinessUnitUsers(String(a.value), organizationId);
if (users.length) return users;
} else if (type === 'position') {
const users = await this.expandPositionUsers(String(a.value), organizationId);
if (users.length) return users;
} else if (type === 'org_membership_level') {
const users = await this.expandMembershipTierUsers(String(a.value), organizationId);
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 { /* fall through */ }
return [`${a.type}:${a.value}`];
}
/** Flat team — `sys_team` is better-auth's collaboration grouping (no hierarchy). */
private async expandTeamUsers(teamId: string): Promise<string[]> {
if (!teamId) return [];
let rows: any[] = [];
try {
rows = await this.engine.find('sys_team_member', {
filter: { team_id: teamId },
fields: ['user_id'],
limit: 10000,
context: SYSTEM_CTX,
} as any);
} catch { rows = []; }
return Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
}
/** Recursive department — walks `sys_business_unit.parent_business_unit_id`. */
private async expandBusinessUnitUsers(businessUnitId: string, organizationId?: string | null): Promise<string[]> {
if (!businessUnitId) return [];
// Seed sanity check: skip if dept doesn't exist or is inactive within tenant.
try {
const seed = await this.engine.find('sys_business_unit', {
filter: organizationId
? { id: businessUnitId, organization_id: organizationId }
: { id: businessUnitId },
fields: ['id', 'active'],
limit: 1,
context: SYSTEM_CTX,
} as any);
const seedRow: any = Array.isArray(seed) ? seed[0] : null;
if (!seedRow || seedRow.active === false) return [];
} catch { return []; }
const seen = new Set<string>([businessUnitId]);
const queue: string[] = [businessUnitId];
while (queue.length) {
const parent = queue.shift()!;
let kids: any[] = [];
try {
const filter: any = { parent_business_unit_id: parent, active: { $ne: false } };
if (organizationId) filter.organization_id = organizationId;
kids = await this.engine.find('sys_business_unit', { filter, fields: ['id'], limit: 1000, context: SYSTEM_CTX } as any);
} catch { kids = []; }
for (const k of kids ?? []) {
const kid = String((k as any).id ?? '');
if (kid && !seen.has(kid)) { seen.add(kid); queue.push(kid); }
}
}
let rows: any[] = [];
try {
rows = await this.engine.find('sys_business_unit_member', {
filter: { business_unit_id: { $in: Array.from(seen) } },
fields: ['user_id'],
limit: 10000,
context: SYSTEM_CTX,
} as any);
} catch { rows = []; }
return Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
}
/**
* Position holders (ADR-0090 D3): `sys_user_position` is the platform-owned
* assignment table, keyed by the position's machine name (ADR-0057 D4),
* unioned with the better-auth membership string (`sys_member.role`) as a
* transition source — the same semantics as `PositionGraphService` in
* `plugin-sharing`, so an approval routes to exactly the users the sharing
* engine would expand for the same position.
*/
private async expandPositionUsers(positionName: string, organizationId?: string | null): Promise<string[]> {
if (!positionName) return [];
const users = new Set<string>();
const filter: any = { position: positionName };
if (organizationId) filter.organization_id = organizationId;
try {
const rows = await this.engine.find('sys_user_position', {
filter, fields: ['user_id'], limit: 10000, context: SYSTEM_CTX,
} as any);
for (const r of (rows ?? []) as any[]) {
const uid = String(r.user_id ?? '');
if (uid) users.add(uid);
}
} catch { /* table may not exist on minimal stacks — union source below still applies */ }
// ADR-0057 D4 transition source: pre-migration stacks still carry the
// position name in better-auth's `sys_member.role` column, so the same
// lookup serves a position name here and a membership tier for
// `org_membership_level` — the column is one, the two concepts are not.
for (const uid of await this.expandMembershipTierUsers(positionName, organizationId)) users.add(uid);
return Array.from(users);
}
/**
* better-auth org-membership tier (`sys_member.role`: owner/admin/member) —
* NOT positions. Named for the projection (`org_membership_level`, ADR-0057
* D7 / ADR-0090 D3), not for better-auth's column: the column name is theirs
* and stays, the platform-facing word does not.
*/
private async expandMembershipTierUsers(tier: string, organizationId?: string | null): Promise<string[]> {
if (!tier) return [];
const filter: any = { role: tier };
if (organizationId) filter.organization_id = organizationId;
let rows: any[] = [];
try {
rows = await this.engine.find('sys_member', { filter, fields: ['user_id'], limit: 10000, context: SYSTEM_CTX } as any);
} catch { rows = []; }
return Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
}
private async lookupManager(userId: string): Promise<string | null> {
try {
const rows = await this.engine.find('sys_user', {
filter: { id: userId }, fields: ['id', 'manager_id'], limit: 1, context: SYSTEM_CTX,
} as any);
const row: any = Array.isArray(rows) ? rows[0] : null;
return row?.manager_id ? String(row.manager_id) : null;
} catch { return null; }
}
/**
* Out-of-office auto-skip (#1322 M1). Given an individually-routed approver
* id, follow any active `sys_approval_delegation` chain and return the id the
* slot should actually go to — the delegate acts under their own identity, so
* no impersonation is involved. Returns `[userId]` unchanged when there is no
* active delegation. Each hop is appended to `collector` (when supplied) so
* the caller can audit + notify (M4).
*
* The chain (A out → B, B out → C, …) is bounded by {@link OOO_MAX_CHAIN} and
* stops on a self-reference or a cycle, so a mis-declared loop degrades to the
* last reachable delegate rather than hanging.
*/
private async applyOooDelegation(
userId: string,
now: number,
organizationId?: string | null,
collector?: OooSubstitution[],
): Promise<string[]> {
const start = String(userId ?? '').trim();
if (!start) return [];
let current = start;
const visited = new Set<string>([current]);
for (let hop = 0; hop < OOO_MAX_CHAIN; hop++) {
const del = await this.lookupActiveDelegation(current, now, organizationId);
if (!del) break;
const to = String(del.delegate_id ?? '').trim();
if (!to || to === current || visited.has(to)) break; // no-op / self / cycle
collector?.push({ from: current, to, reason: del.reason != null ? String(del.reason) : null });
visited.add(to);
current = to;
}
return [current];
}
/**
* The active OOO delegation for a delegator at `now`, or null. Validity is the
* shared `isGrantActive` half-open window (ADR-0091 D2), enforced here at
* resolution time — never by a background job. When several rows are active,
* the one expiring soonest wins (the most specific coverage window).
*/
private async lookupActiveDelegation(
delegatorId: string,
now: number,
organizationId?: string | null,
): Promise<any | null> {
if (!delegatorId) return null;
let rows: any[] = [];
try {
rows = await this.engine.find('sys_approval_delegation', {
filter: { delegator_id: delegatorId },
fields: ['id', 'delegator_id', 'delegate_id', 'valid_from', 'valid_until', 'reason', 'organization_id'],
limit: 50,
context: SYSTEM_CTX,
} as any);
} catch { return null; } // table absent on minimal stacks — no OOO, resolve as-is
const active = (rows ?? []).filter((r: any) =>
isGrantActive(r, now)
// A null-org rule applies across tenants; a scoped rule only within its tenant.
&& (organizationId == null || r.organization_id == null || String(r.organization_id) === String(organizationId)));
if (!active.length) return null;
active.sort((a: any, b: any) => {
const au = a.valid_until ? Date.parse(String(a.valid_until)) : Number.POSITIVE_INFINITY;
const bu = b.valid_until ? Date.parse(String(b.valid_until)) : Number.POSITIVE_INFINITY;
return au - bu;
});
return active[0];
}
/** Mirror a request status onto a business-object field, if configured. */
private async mirrorStatusField(object: string, recordId: string, field: string, status: string): Promise<void> {
try {
await this.engine.update(object, { id: recordId, [field]: status }, { context: SYSTEM_CTX });
} catch (err: any) {
this.logger?.warn?.(`[approvals] mirrorStatusField failed: ${err?.message ?? err}`);
}
}
// ── ADR-0019: Approval-as-flow-node ──────────────────────────
//
// A flow's Approval node opens a request via `openNodeRequest` (carrying its
// own approvers/behavior config and the suspended run id), then suspends. A
// later `decide` finalizes it and resumes the flow run down the matching
// `approve`/`reject` edge. The record lock is enforced by a beforeUpdate hook
// keyed on a *pending* request, so finalizing auto-releases it.
/**
* Open a pending approval request on behalf of a flow's Approval node. The
* node config (approvers / behavior / status field) is snapshotted on the row
* so a decision can be made without any process to resolve against.
*/
async openNodeRequest(
input: {
object: string;
recordId: string;
runId: string;
nodeId: string;
config: ApprovalNodeConfig;
flowName?: string;
/** Authored flow label, snapshotted for inbox display. */
flowLabel?: string;
/** Authored node label, snapshotted for inbox display. */
nodeLabel?: string;
submitterId?: string | null;
record?: any;
organizationId?: string | null;
},
context: SharingExecutionContext,
): Promise<ApprovalRequestRow> {
if (!input.object) throw new Error('VALIDATION_FAILED: object is required');
if (!input.recordId) throw new Error('VALIDATION_FAILED: recordId is required');
if (!input.runId) throw new Error('VALIDATION_FAILED: runId is required');
// One pending request per (object, record).
const existing = await this.engine.find('sys_approval_request', {
where: { object_name: input.object, record_id: input.recordId, status: 'pending' },
limit: 1, context: SYSTEM_CTX,
});
if (Array.isArray(existing) && existing[0]) {
throw new Error(`DUPLICATE_REQUEST: a pending approval already exists for ${input.object}/${input.recordId}`);
}
const ctxOrg = (context as any)?.organizationId ?? (context as any)?.tenantId ?? input.organizationId ?? null;
const nowDate = this.clock.now();
// OOO auto-skip (#1322 M1): reroute individually-routed approvers who are
// out of office. Collected hops drive the audit + notification below (M4).
const substitutions: OooSubstitution[] = [];
// Group membership per resolved approver (#3266) — snapshotted so quorum /
// per_group finalization is decided against the slate resolved at OPEN time
// (OOO-substituted), not re-resolved live at each decision.
const groups: Record<string, string[]> = {};
const approvers = await this.expandApprovers(
{ approvers: input.config.approvers }, input.record, ctxOrg, { now: nowDate.getTime(), substitutions, groups },
);
const now = nowDate.toISOString();
const id = uid('areq');
const processName = `flow:${input.flowName ?? input.nodeId}`;
// Display labels ride the config snapshot (no schema migration needed);
// `rowFromRequest` surfaces them as `process_label` / `step_label`.
const configSnapshot: any = { ...input.config };
if (input.flowLabel) configSnapshot.__flowLabel = input.flowLabel;
if (input.nodeLabel) configSnapshot.__nodeLabel = input.nodeLabel;
// Snapshot the resolved approver→group map for quorum/per_group tallying.
if (input.config.behavior === 'quorum' || input.config.behavior === 'per_group') {
configSnapshot.__approverGroups = groups;
}
// ADR-0044 round numbering: rounds of a revise loop share the run — count
// this (run, node)'s prior requests; the new one is round N+1. Stamped on
// the snapshot (precedent: __flowLabel), so no schema migration.
try {
const prior = await this.engine.find('sys_approval_request', {
where: { flow_run_id: input.runId, flow_node_id: input.nodeId }, limit: 500, context: SYSTEM_CTX,
});
const n = Array.isArray(prior) ? prior.length : 0;
if (n > 0) configSnapshot.__round = n + 1;
} catch { /* round display is best-effort */ }
const row: any = {
id,
process_name: processName,
object_name: input.object,
record_id: input.recordId,
submitter_id: input.submitterId ?? context.userId ?? null,
status: 'pending',
current_step: input.nodeId,
current_step_index: 0,
pending_approvers: approvers.join(','),
payload_json: input.record != null ? JSON.stringify(input.record) : null,
flow_run_id: input.runId,
flow_node_id: input.nodeId,
node_config_json: JSON.stringify(configSnapshot),
organization_id: ctxOrg,
created_at: now,
updated_at: now,
};
await this.engine.insert('sys_approval_request', row, { context: SYSTEM_CTX });
await this.syncApproverIndex(id, approvers, ctxOrg, now);
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: id, organization_id: ctxOrg,
step_name: input.nodeId, step_index: 0, action: 'submit',
actor_id: input.submitterId ?? context.userId ?? null, comment: null, created_at: now,
}, { context: SYSTEM_CTX });
// OOO substitution audit + notification (#1322 M4). Each hop that rerouted
// an approver away from an out-of-office user is recorded on the request's
// audit trail (a system action, no human actor) and notified to both the
// delegate — who now owns the slot — and the skipped approver.
for (const sub of substitutions) {
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: id, organization_id: ctxOrg,
step_name: input.nodeId, step_index: 0, action: 'ooo_substitute',
actor_id: null,
comment: `${sub.from} → ${sub.to}${sub.reason ? ` — ${sub.reason}` : ''}`,
created_at: now,
}, { context: SYSTEM_CTX });
await this.notify({
topic: 'approval.ooo_substituted',
audience: [sub.to],
source: { object: 'sys_approval_request', id },
dedupKey: `approval-ooo-${id}-${sub.to}`,
payload: {
title: 'Approval routed to you (out-of-office cover)',
message: `You are covering an approval on ${input.object}/${input.recordId} while ${sub.from} is out of office.`,
actionUrl: '/system/approvals',
},
});
await this.notify({
topic: 'approval.ooo_skipped',
audience: [sub.from],
source: { object: 'sys_approval_request', id },
dedupKey: `approval-ooo-skip-${id}-${sub.from}`,
payload: {
title: 'Approval routed to your delegate',
message: `An approval on ${input.object}/${input.recordId} was routed to ${sub.to} while you are out of office.`,
actionUrl: '/system/approvals',
},
});
}
// Record lock (when `lockRecord !== false`) is enforced by the beforeUpdate
// hook keyed on the now-pending request; no extra write needed here.
if (input.config.approvalStatusField) {
await this.mirrorStatusField(input.object, input.recordId, input.config.approvalStatusField, 'pending');
}
return rowFromRequest(row);
}
/**
* True when the approve tally satisfies the node's `behavior` (#3266):
* - `unanimous` — every resolved approver approved.
* - `quorum` — at least `minApprovals` distinct approvals (default = all).
* - `per_group` — every group reached `minApprovals` approvals (default 1).
* Thresholds are clamped to the resolvable count / group size, so a mis-set
* value can never deadlock a request.
*/
private isApprovalSatisfied(
behavior: string,
config: ApprovalNodeConfig,
original: string[],
groupMap: Record<string, string[]>,
approved: Set<string>,
): boolean {
if (behavior === 'unanimous') {
return original.length > 0 && original.every(a => approved.has(a));
}
if (behavior === 'quorum') {
const n = original.length || 1;
const need = Math.min(Math.max(1, config.minApprovals ?? n), n);
// Count distinct approvals (robust to OOO/reassign changing who holds a slot).
return approved.size >= need;
}
if (behavior === 'per_group') {
const perGroupNeed = Math.max(1, config.minApprovals ?? 1);
const size: Record<string, number> = {};
for (const gs of Object.values(groupMap)) for (const g of gs) size[g] = (size[g] ?? 0) + 1;
const groups = Object.keys(size);
if (!groups.length) return true; // nothing to gate
const got: Record<string, number> = {};
for (const a of approved) for (const g of (groupMap[a] ?? [])) got[g] = (got[g] ?? 0) + 1;
return groups.every(g => (got[g] ?? 0) >= Math.min(perGroupNeed, size[g]));
}
return true; // first_response and unknown → first approval finalizes
}
/**
* Record a decision on a node-driven request. Honours the node's `behavior`
* (#3266): `first_response` finalizes on the first approval; `unanimous`,
* `quorum`, and `per_group` hold the request open until their tally is met
* (see {@link ApprovalService.isApprovalSatisfied}). A rejection always
* finalizes the node (one veto). When the request finalizes, returns the
* suspended run id + node id so the caller (or {@link ApprovalService.decide})
* can resume the flow down the matching branch.
*/
async decideNode(
requestId: string,
input: { decision: 'approve' | 'reject'; actorId: string; comment?: string; attachments?: string[] },
context: SharingExecutionContext,
): Promise<{ request: ApprovalRequestRow; runId: string | null; nodeId: string | null; finalized: boolean; decision: 'approve' | 'reject' }> {
if (!requestId) throw new Error('VALIDATION_FAILED: requestId is required');
if (!input?.actorId) throw new Error('VALIDATION_FAILED: actorId is required');
if (input.decision !== 'approve' && input.decision !== 'reject') {
throw new Error('VALIDATION_FAILED: decision must be approve|reject');
}
// Read the raw row to reach flow_* correlation + the node config snapshot.
const rawRows = await this.engine.find('sys_approval_request', {
where: { id: requestId }, limit: 1, context: SYSTEM_CTX,
});
const raw: any = Array.isArray(rawRows) ? rawRows[0] : null;
if (!raw) throw new Error(`REQUEST_NOT_FOUND: ${requestId}`);
if (raw.status !== 'pending') throw new Error(`INVALID_STATE: request is ${raw.status}`);
const pendingApprovers = csvSplit(raw.pending_approvers);
if (!context.isSystem && !pendingApprovers.includes(input.actorId)) {
throw new Error(`FORBIDDEN: actor '${input.actorId}' is not a pending approver`);
}
const config = parseJson<ApprovalNodeConfig>(raw.node_config_json, { approvers: [], behavior: 'first_response' } as any);
const org = raw.organization_id ?? null;
const nodeId: string | null = raw.flow_node_id ?? raw.current_step ?? null;
const runId: string | null = raw.flow_run_id ?? null;
const now = this.clock.now().toISOString();
// Audit the decision first so the quorum/per_group tally below sees it.
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: requestId, organization_id: org,
step_name: nodeId, step_index: 0, action: input.decision,
actor_id: input.actorId, comment: input.comment ?? null,
attachments: input.attachments?.length ? input.attachments : null,
created_at: now,
}, { context: SYSTEM_CTX });
// Multi-approver aggregation on approve (#3266). A rejection always
// finalizes the node (one veto), so only the approve path can hold it open.
// `first_response` finalizes on the first approval (falls straight through).
const behavior = config.behavior ?? 'first_response';
if (input.decision === 'approve' && behavior !== 'first_response') {
const acts = await this.engine.find('sys_approval_action', {
where: { request_id: requestId, step_index: 0, action: 'approve' }, limit: 1000, context: SYSTEM_CTX,
});
const approved = new Set<string>((acts ?? []).map((a: any) => String(a.actor_id ?? '')).filter(Boolean));
// quorum / per_group tally against the OPEN-time snapshot (already
// OOO-substituted). unanimous re-resolves for back-compat with requests
// opened before the snapshot existed.
const snapshotGroups = (config as any).__approverGroups as Record<string, string[]> | undefined;
let original: string[];
let groupMap: Record<string, string[]>;
if (snapshotGroups && (behavior === 'quorum' || behavior === 'per_group')) {
groupMap = snapshotGroups;
original = Object.keys(snapshotGroups);
} else {
original = await this.expandApprovers(
{ approvers: config.approvers }, parseJson(raw.payload_json, undefined), org,
);
groupMap = {};
}
if (!this.isApprovalSatisfied(behavior, config, original, groupMap, approved)) {
const stillPending = original.filter(a => !approved.has(a));
await this.engine.update('sys_approval_request', {
id: requestId, pending_approvers: stillPending.join(','), updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, stillPending, org, now);
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, nodeId, finalized: false, decision: input.decision };
}
}
const finalStatus = input.decision === 'approve' ? 'approved' : 'rejected';
await this.engine.update('sys_approval_request', {
id: requestId, status: finalStatus, pending_approvers: null, completed_at: now, updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, [], org, now);
if (config.approvalStatusField) {
await this.mirrorStatusField(raw.object_name, raw.record_id, config.approvalStatusField, finalStatus);
}
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, nodeId, finalized: true, decision: input.decision };
}
/**
* Public contract entrypoint (ADR-0019). Records a decision on a node-driven
* request via {@link ApprovalService.decideNode} and, when it finalizes,
* resumes the owning flow run down the matching `approve` / `reject` edge.
*/
async decide(
requestId: string,
input: ApprovalDecisionInput,
context: SharingExecutionContext,
): Promise<ApprovalDecisionResult> {
const result = await this.decideNode(requestId, input, context);
let resumed = false;
if (result.finalized && result.runId && typeof this.automation?.resume === 'function') {
const branchLabel = result.decision === 'approve'
? APPROVAL_BRANCH_LABELS.approve
: APPROVAL_BRANCH_LABELS.reject;
try {
await this.automation.resume(result.runId, {
branchLabel,
output: { decision: result.decision, requestId },
});
resumed = true;
} catch (err: any) {
this.logger?.warn?.('[approvals] resume after decision failed', {
request: requestId, run: result.runId, error: err?.message ?? String(err),
});
}
}
return {
request: result.request,
finalized: result.finalized,
decision: result.decision,
runId: result.runId,
resumed,
};
}
/**
* Withdraw a pending request (submitter only). Finalises the row as
* `recalled`, releases the record lock (keyed on pending status), mirrors
* the status field when configured, and resumes the owning flow run down
* the `reject` branch with `output.decision = 'recall'` — leaving the run
* suspended forever would leak it.
*
* ADR-0044: also valid on the LATEST `returned` request of its run — the
* submitter abandons the revision window instead of resubmitting. The run
* is then paused at the revise wait node (no reject edge), so it is
* terminally cancelled via {@link ApprovalResumeSurface.cancelRun} rather
* than resumed.
*/
async recall(
requestId: string,
input: ApprovalRecallInput,
context: SharingExecutionContext,
): Promise<ApprovalRecallResult> {
if (!requestId) throw new Error('VALIDATION_FAILED: requestId is required');
if (!input?.actorId) throw new Error('VALIDATION_FAILED: actorId is required');
const rawRows = await this.engine.find('sys_approval_request', {
where: { id: requestId }, limit: 1, context: SYSTEM_CTX,
});
const raw: any = Array.isArray(rawRows) ? rawRows[0] : null;
if (!raw) throw new Error(`REQUEST_NOT_FOUND: ${requestId}`);
const inReviseWindow = raw.status === 'returned';
if (raw.status !== 'pending' && !inReviseWindow) {
throw new Error(`INVALID_STATE: request is ${raw.status}`);
}
if (!context.isSystem && raw.submitter_id && String(raw.submitter_id) !== String(input.actorId)) {
throw new Error(`FORBIDDEN: only the submitter may recall this request`);
}
// A returned request is only recallable while it is still the run's live
// frontier — a resubmitted (or later-node) request supersedes it.
if (inReviseWindow) await this.assertLatestForRun(raw);
const config = parseJson<ApprovalNodeConfig>(raw.node_config_json, { approvers: [], behavior: 'first_response' } as any);
const org = raw.organization_id ?? null;
const nodeId: string | null = raw.flow_node_id ?? raw.current_step ?? null;
const runId: string | null = raw.flow_run_id ?? null;
const now = this.clock.now().toISOString();
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: requestId, organization_id: org,
step_name: nodeId, step_index: 0, action: 'recall',
actor_id: input.actorId, comment: input.comment ?? null, created_at: now,
}, { context: SYSTEM_CTX });
await this.engine.update('sys_approval_request', {
id: requestId, status: 'recalled', pending_approvers: null, completed_at: now, updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, [], org, now);
if (config.approvalStatusField) {
await this.mirrorStatusField(raw.object_name, raw.record_id, config.approvalStatusField, 'recalled');
}
let resumed = false;
if (inReviseWindow) {