sentinelayer-cli 0.4.5 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +996 -998
- package/bin/create-sentinelayer.js +5 -5
- package/bin/sentinelayer-cli.js +4 -4
- package/bin/sl.js +5 -5
- package/package.json +63 -63
- package/src/agents/jules/config/definition.js +160 -209
- package/src/agents/jules/config/system-prompt.js +182 -175
- package/src/agents/jules/error-intake.js +51 -51
- package/src/agents/jules/fix-cycle.js +17 -377
- package/src/agents/jules/loop.js +450 -367
- package/src/agents/jules/pulse.js +10 -327
- package/src/agents/jules/stream.js +186 -186
- package/src/agents/jules/swarm/file-scanner.js +74 -74
- package/src/agents/jules/swarm/index.js +11 -11
- package/src/agents/jules/swarm/orchestrator.js +362 -362
- package/src/agents/jules/swarm/pattern-hunter.js +123 -123
- package/src/agents/jules/swarm/sub-agent.js +309 -308
- package/src/agents/jules/tools/aidenid-email.js +189 -0
- package/src/agents/jules/tools/auth-audit.js +1691 -557
- package/src/agents/jules/tools/dispatch.js +335 -327
- package/src/agents/jules/tools/file-edit.js +2 -180
- package/src/agents/jules/tools/file-read.js +2 -100
- package/src/agents/jules/tools/frontend-analyze.js +570 -570
- package/src/agents/jules/tools/glob.js +2 -168
- package/src/agents/jules/tools/grep.js +2 -228
- package/src/agents/jules/tools/index.js +29 -29
- package/src/agents/jules/tools/path-guards.js +2 -161
- package/src/agents/jules/tools/runtime-audit.js +507 -503
- package/src/agents/jules/tools/shell.js +2 -383
- package/src/agents/jules/tools/url-policy.js +100 -100
- package/src/agents/persona-visuals.js +61 -0
- package/src/agents/shared-tools/dispatch-core.js +315 -0
- package/src/agents/shared-tools/file-edit.js +180 -0
- package/src/agents/shared-tools/file-read.js +100 -0
- package/src/agents/shared-tools/glob.js +168 -0
- package/src/agents/shared-tools/grep.js +228 -0
- package/src/agents/shared-tools/index.js +46 -0
- package/src/agents/shared-tools/path-guards.js +161 -0
- package/src/agents/shared-tools/shell.js +383 -0
- package/src/ai/aidenid.js +1009 -972
- package/src/ai/client.js +553 -508
- package/src/ai/domain-target-store.js +268 -268
- package/src/ai/identity-store.js +270 -270
- package/src/ai/proxy.js +137 -0
- package/src/ai/site-store.js +145 -145
- package/src/audit/agents/architecture.js +180 -180
- package/src/audit/agents/compliance.js +179 -179
- package/src/audit/agents/documentation.js +165 -165
- package/src/audit/agents/performance.js +145 -145
- package/src/audit/agents/security.js +215 -215
- package/src/audit/agents/testing.js +172 -172
- package/src/audit/orchestrator.js +557 -557
- package/src/audit/package.js +204 -204
- package/src/audit/registry.js +284 -284
- package/src/audit/replay.js +103 -103
- package/src/auth/gate.js +371 -126
- package/src/auth/http.js +611 -270
- package/src/auth/service.js +1106 -891
- package/src/auth/session-store.js +813 -359
- package/src/cli.js +252 -252
- package/src/commands/ai/identity-lifecycle.js +1338 -1338
- package/src/commands/ai/provision-governance.js +1272 -1272
- package/src/commands/ai/shared.js +147 -147
- package/src/commands/ai.js +11 -11
- package/src/commands/apply.js +12 -12
- package/src/commands/audit.js +1166 -1166
- package/src/commands/auth.js +419 -375
- package/src/commands/chat.js +191 -191
- package/src/commands/config.js +184 -184
- package/src/commands/cost.js +311 -311
- package/src/commands/daemon/core.js +850 -850
- package/src/commands/daemon/extended.js +1048 -1048
- package/src/commands/daemon/shared.js +213 -213
- package/src/commands/daemon.js +11 -11
- package/src/commands/guide.js +174 -174
- package/src/commands/ingest.js +58 -58
- package/src/commands/init.js +55 -55
- package/src/commands/legacy-args.js +10 -10
- package/src/commands/mcp.js +461 -461
- package/src/commands/omargate.js +29 -21
- package/src/commands/persona.js +20 -20
- package/src/commands/plugin.js +260 -260
- package/src/commands/policy.js +132 -132
- package/src/commands/prompt.js +238 -238
- package/src/commands/review.js +704 -704
- package/src/commands/scan.js +872 -866
- package/src/commands/spec.js +716 -716
- package/src/commands/swarm.js +651 -651
- package/src/commands/telemetry.js +202 -202
- package/src/commands/watch.js +511 -510
- package/src/config/agent-dictionary.js +182 -182
- package/src/config/io.js +56 -56
- package/src/config/paths.js +18 -18
- package/src/config/schema.js +55 -55
- package/src/config/service.js +184 -184
- package/src/cost/budget.js +235 -235
- package/src/cost/history.js +188 -188
- package/src/cost/tracker.js +171 -171
- package/src/daemon/artifact-lineage.js +534 -534
- package/src/daemon/assignment-ledger.js +770 -770
- package/src/daemon/ast-parser-layer.js +258 -258
- package/src/daemon/budget-governor.js +633 -633
- package/src/daemon/callgraph-overlay.js +646 -646
- package/src/daemon/error-worker.js +626 -626
- package/src/daemon/fix-cycle.js +377 -0
- package/src/daemon/hybrid-mapper.js +929 -929
- package/src/daemon/jira-lifecycle.js +632 -632
- package/src/daemon/operator-control.js +657 -657
- package/src/daemon/pulse.js +327 -0
- package/src/daemon/reliability-lane.js +471 -471
- package/src/daemon/watchdog.js +971 -971
- package/src/guide/generator.js +316 -316
- package/src/ingest/engine.js +918 -918
- package/src/interactive/index.js +97 -95
- package/src/legacy-cli.js +2994 -2592
- package/src/mcp/registry.js +695 -695
- package/src/memory/blackboard.js +301 -301
- package/src/memory/retrieval.js +581 -581
- package/src/plugin/manifest.js +553 -553
- package/src/policy/packs.js +144 -144
- package/src/prompt/generator.js +118 -118
- package/src/review/ai-review.js +679 -669
- package/src/review/local-review.js +1305 -1295
- package/src/review/omargate-interactive.js +68 -0
- package/src/review/omargate-orchestrator.js +300 -0
- package/src/review/persona-prompts.js +296 -0
- package/src/review/replay.js +235 -235
- package/src/review/report.js +664 -664
- package/src/review/scan-modes.js +42 -0
- package/src/review/spec-binding.js +487 -487
- package/src/scaffold/generator.js +67 -67
- package/src/scaffold/templates.js +150 -150
- package/src/scan/generator.js +418 -418
- package/src/scan/gh-secrets.js +107 -107
- package/src/spec/generator.js +519 -519
- package/src/spec/regenerate.js +237 -237
- package/src/spec/templates.js +91 -91
- package/src/swarm/dashboard.js +247 -247
- package/src/swarm/factory.js +363 -363
- package/src/swarm/pentest.js +934 -934
- package/src/swarm/registry.js +419 -419
- package/src/swarm/report.js +158 -158
- package/src/swarm/runtime.js +576 -576
- package/src/swarm/scenario-dsl.js +272 -272
- package/src/telemetry/ledger.js +302 -302
- package/src/telemetry/session-tracker.js +234 -118
- package/src/telemetry/sync.js +203 -199
- package/src/ui/command-hints.js +13 -0
- package/src/ui/markdown.js +220 -220
|
@@ -1,557 +1,1691 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
const
|
|
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
|
-
return
|
|
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
|
-
if (
|
|
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
|
-
const
|
|
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
|
-
const
|
|
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
|
-
function
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
if (
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
if (
|
|
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
|
-
const
|
|
424
|
-
const
|
|
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
|
-
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
5
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
6
|
+
import { assertPermittedAuditTarget } from "./url-policy.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Jules Tanaka — Authenticated Page Audit
|
|
10
|
+
*
|
|
11
|
+
* Provisions an AIdenID ephemeral identity, uses Playwright to log in,
|
|
12
|
+
* then inspects authenticated pages (DevTools console, DOM, headers).
|
|
13
|
+
* Falls back gracefully when AIdenID or Playwright unavailable.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export async function authAudit(input = {}) {
|
|
17
|
+
const operation = String(input.operation || "").trim();
|
|
18
|
+
const requestId = createAuditRequestId();
|
|
19
|
+
if (!AUTH_OPS.has(operation)) {
|
|
20
|
+
const message = "Unknown operation: " + (operation || "<empty>") + ". Valid: " + [...AUTH_OPS].join(", ");
|
|
21
|
+
return finalizeAuditEnvelope(operation || "unknown", requestId, buildUnavailableAuditResponse(
|
|
22
|
+
requestId,
|
|
23
|
+
"AUTH_AUDIT_UNKNOWN_OPERATION",
|
|
24
|
+
message
|
|
25
|
+
));
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const result = await AUTH_DISPATCH[operation]({ ...input, requestId, operation });
|
|
29
|
+
return finalizeAuditEnvelope(operation, requestId, result);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
const code = error instanceof AuthAuditError ? "AUTH_AUDIT_VALIDATION_FAILED" : "AUTH_AUDIT_EXECUTION_FAILED";
|
|
32
|
+
const message = normalizeErrorMessage(error, "Auth audit failed");
|
|
33
|
+
const diagnostics = extractErrorDiagnostics(error, operation || "auth_audit");
|
|
34
|
+
return finalizeAuditEnvelope(operation, requestId, buildUnavailableAuditResponse(requestId, code, message, diagnostics));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const AUTH_OPS = new Set([
|
|
39
|
+
"provision_test_identity",
|
|
40
|
+
"authenticated_page_check",
|
|
41
|
+
"check_auth_flow_security",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
const AUTH_DISPATCH = {
|
|
45
|
+
provision_test_identity: provisionTestIdentity,
|
|
46
|
+
authenticated_page_check: authenticatedPageCheck,
|
|
47
|
+
check_auth_flow_security: checkAuthFlowSecurity,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const AUTH_PLAYWRIGHT_EXEC_TIMEOUT_MS = 60_000;
|
|
51
|
+
const AUTH_PLAYWRIGHT_EXEC_MAX_RETRIES = 3;
|
|
52
|
+
const AUTH_PLAYWRIGHT_EXEC_BASE_BACKOFF_MS = 300;
|
|
53
|
+
const AUTH_PLAYWRIGHT_EXEC_TOTAL_BUDGET_MS = 180_000;
|
|
54
|
+
const AUTH_PLAYWRIGHT_EXEC_MIN_ATTEMPT_TIMEOUT_MS = 2_000;
|
|
55
|
+
const AUTH_AIDENID_PROVISION_TIMEOUT_MS = 12_000;
|
|
56
|
+
const AUTH_AIDENID_PROVISION_MAX_RETRIES = 2;
|
|
57
|
+
const AUTH_AIDENID_PROVISION_BASE_BACKOFF_MS = 300;
|
|
58
|
+
const AUTH_AIDENID_PROVISION_TOTAL_BUDGET_MS =
|
|
59
|
+
(AUTH_AIDENID_PROVISION_TIMEOUT_MS * (AUTH_AIDENID_PROVISION_MAX_RETRIES + 1))
|
|
60
|
+
+ (AUTH_AIDENID_PROVISION_BASE_BACKOFF_MS * AUTH_AIDENID_PROVISION_MAX_RETRIES * 2);
|
|
61
|
+
const AUTH_AIDENID_PROVISION_MIN_ATTEMPT_TIMEOUT_MS = 1_500;
|
|
62
|
+
const AUTH_AUDIT_PROVIDER_BREAKER_FAILURE_THRESHOLD = 3;
|
|
63
|
+
const AUTH_AUDIT_PROVIDER_BREAKER_WINDOW_MS = 5 * 60 * 1000;
|
|
64
|
+
const AUTH_AUDIT_PROVIDER_BREAKER_COOLDOWN_MS = 2 * 60 * 1000;
|
|
65
|
+
const AUTH_AUDIT_PROVIDER_BREAKER_ENTRY_TTL_MS = 15 * 60 * 1000;
|
|
66
|
+
const AUTH_AUDIT_PROVIDER_SCOPE_DEFAULT = "default";
|
|
67
|
+
const AUTH_AUDIT_PROVIDER_BREAKERS = new Map();
|
|
68
|
+
const AUTH_AUDIT_PROVIDER_BREAKER_STATE_FILE_ENV = "SENTINELAYER_AUTH_AUDIT_BREAKER_STATE_FILE";
|
|
69
|
+
const AUTH_AUDIT_PROVIDER_BREAKER_STATE_FILE_DEFAULT = "";
|
|
70
|
+
const AUTH_AUDIT_PROVIDER_AIDENID = "aidenid";
|
|
71
|
+
const AUTH_AUDIT_PROVIDER_PLAYWRIGHT_TARGET = "playwright-target";
|
|
72
|
+
const AUTH_MUTATION_ALLOWED_ENV = "SENTINELAYER_ALLOW_AUTH_MUTATION";
|
|
73
|
+
const AUTH_AUDIT_ENVELOPE_ENV = "SENTINELAYER_AUTH_AUDIT_ENVELOPE";
|
|
74
|
+
const AUTH_AUDIT_ENVELOPE_VERSION = "v2";
|
|
75
|
+
const RETRYABLE_PLAYWRIGHT_EXEC_ERROR_CODES = new Set([
|
|
76
|
+
"ETIMEDOUT",
|
|
77
|
+
"ECONNRESET",
|
|
78
|
+
"EPIPE",
|
|
79
|
+
"EAI_AGAIN",
|
|
80
|
+
"ECONNABORTED",
|
|
81
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
82
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
83
|
+
]);
|
|
84
|
+
const RETRYABLE_AIDENID_PROVISION_ERROR_CODES = new Set([
|
|
85
|
+
"ETIMEDOUT",
|
|
86
|
+
"ECONNRESET",
|
|
87
|
+
"ECONNREFUSED",
|
|
88
|
+
"EAI_AGAIN",
|
|
89
|
+
"ENOTFOUND",
|
|
90
|
+
"ECONNABORTED",
|
|
91
|
+
"AIDENID_ATTEMPT_TIMEOUT",
|
|
92
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
93
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
94
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
95
|
+
]);
|
|
96
|
+
const RETRYABLE_AIDENID_PROVISION_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
|
|
97
|
+
const RETRYABLE_AIDENID_PROVISION_MESSAGE_PATTERNS = [
|
|
98
|
+
/\bfetch failed\b/i,
|
|
99
|
+
/\bnetwork(?:\s+|-)error\b/i,
|
|
100
|
+
/\btimed?\s*out\b/i,
|
|
101
|
+
/\b(?:econnreset|econnrefused|eai_again|enotfound|etimedout)\b/i,
|
|
102
|
+
/\bconnection\b.*\b(?:reset|closed|terminated)\b/i,
|
|
103
|
+
];
|
|
104
|
+
|
|
105
|
+
let AUTH_AUDIT_PROVIDER_BREAKERS_HYDRATED = false;
|
|
106
|
+
const AUTH_AUDIT_JITTER_SECRET = randomBytes(16).toString("hex");
|
|
107
|
+
let AUTH_AUDIT_JITTER_COUNTER = 0;
|
|
108
|
+
|
|
109
|
+
function createAuditRequestId() {
|
|
110
|
+
try {
|
|
111
|
+
return randomUUID();
|
|
112
|
+
} catch {
|
|
113
|
+
const ts = Date.now().toString(36);
|
|
114
|
+
const rand = randomBytes(16).toString("hex");
|
|
115
|
+
return `authaudit-${ts}-${rand}`;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function normalizeErrorMessage(error, fallback) {
|
|
120
|
+
const fallbackMessage = String(fallback || "Auth audit failed");
|
|
121
|
+
if (error instanceof Error && error.message) {
|
|
122
|
+
return sanitizeAuditErrorMessage(error.message, fallbackMessage);
|
|
123
|
+
}
|
|
124
|
+
const normalized = String(error || "").trim();
|
|
125
|
+
return sanitizeAuditErrorMessage(normalized || fallbackMessage, fallbackMessage);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function sanitizeAuditErrorMessage(message, fallback = "Auth audit failed") {
|
|
129
|
+
const fallbackMessage = String(fallback || "Auth audit failed");
|
|
130
|
+
const normalized = String(message || "").trim();
|
|
131
|
+
const candidate = normalized || fallbackMessage;
|
|
132
|
+
const sanitized = candidate
|
|
133
|
+
.replace(/\bbearer\s+[a-z0-9._~+/=-]+\b/gi, "bearer [REDACTED]")
|
|
134
|
+
.replace(/\b(token|secret|password|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)\b\s*[:=]\s*["']?[^"'\s,;]+["']?/gi, "$1=[REDACTED]")
|
|
135
|
+
.replace(/\b[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+\b/gi, "[REDACTED_JWT]")
|
|
136
|
+
.replace(/\bhttps?:\/\/[^\s"'`]+/gi, (rawUrl) => sanitizeDiagnosticUrl(rawUrl))
|
|
137
|
+
.replace(/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/gi, "<redacted-email>");
|
|
138
|
+
if (sanitized.length <= 512) {
|
|
139
|
+
return sanitized;
|
|
140
|
+
}
|
|
141
|
+
return `${sanitized.slice(0, 509)}...`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function sanitizeDiagnosticUrl(rawUrl) {
|
|
145
|
+
const candidate = String(rawUrl || "").trim();
|
|
146
|
+
if (!candidate) {
|
|
147
|
+
return "<redacted-url>";
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const parsed = new URL(candidate);
|
|
151
|
+
if (!parsed.hostname) {
|
|
152
|
+
return "<redacted-url>";
|
|
153
|
+
}
|
|
154
|
+
return `${parsed.protocol}//${parsed.host}/<redacted-path>`;
|
|
155
|
+
} catch {
|
|
156
|
+
return "<redacted-url>";
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function buildUnavailableAuditResponse(requestId, code, message, options = {}) {
|
|
161
|
+
const safeMessage = sanitizeAuditErrorMessage(message, "Auth audit unavailable");
|
|
162
|
+
const errorPayload = {
|
|
163
|
+
code,
|
|
164
|
+
message: safeMessage,
|
|
165
|
+
requestId,
|
|
166
|
+
retryable: options.retryable === true,
|
|
167
|
+
};
|
|
168
|
+
const phase = String(options.phase || "").trim();
|
|
169
|
+
if (phase) {
|
|
170
|
+
errorPayload.phase = phase;
|
|
171
|
+
}
|
|
172
|
+
const parsedStatusCode = Number.parseInt(String(options.statusCode || ""), 10);
|
|
173
|
+
if (Number.isInteger(parsedStatusCode) && parsedStatusCode > 0) {
|
|
174
|
+
errorPayload.statusCode = parsedStatusCode;
|
|
175
|
+
}
|
|
176
|
+
const errorCode = String(options.errorCode || "").trim();
|
|
177
|
+
if (errorCode) {
|
|
178
|
+
errorPayload.errorCode = errorCode.toUpperCase();
|
|
179
|
+
}
|
|
180
|
+
if (options.retryTelemetry && typeof options.retryTelemetry === "object") {
|
|
181
|
+
errorPayload.retryTelemetry = options.retryTelemetry;
|
|
182
|
+
}
|
|
183
|
+
if (options.providerBreaker && typeof options.providerBreaker === "object") {
|
|
184
|
+
errorPayload.providerBreaker = options.providerBreaker;
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
available: false,
|
|
188
|
+
requestId,
|
|
189
|
+
reason: safeMessage,
|
|
190
|
+
error: errorPayload,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function extractErrorDiagnostics(error, phase = "auth_audit") {
|
|
195
|
+
const diagnostics = {
|
|
196
|
+
phase: String(phase || "auth_audit").trim().slice(0, 64) || "auth_audit",
|
|
197
|
+
};
|
|
198
|
+
const statusCode = resolveAidenidProvisionStatusCode(error);
|
|
199
|
+
if (Number.isInteger(statusCode) && statusCode > 0) {
|
|
200
|
+
diagnostics.statusCode = statusCode;
|
|
201
|
+
}
|
|
202
|
+
let errorCode = resolveAidenidProvisionErrorCode(error);
|
|
203
|
+
if (!errorCode && error instanceof Error) {
|
|
204
|
+
errorCode = String(error.name || "").trim().toUpperCase();
|
|
205
|
+
}
|
|
206
|
+
if (errorCode) {
|
|
207
|
+
diagnostics.errorCode = errorCode.toUpperCase();
|
|
208
|
+
}
|
|
209
|
+
return diagnostics;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function isAuditEnvelopeV2Enabled() {
|
|
213
|
+
const normalized = String(process.env[AUTH_AUDIT_ENVELOPE_ENV] || "").trim().toLowerCase();
|
|
214
|
+
return normalized === "" || normalized === "true" || normalized === "1" || normalized === AUTH_AUDIT_ENVELOPE_VERSION;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function buildAuditDataEnvelope(payload) {
|
|
218
|
+
const data = { ...(payload && typeof payload === "object" ? payload : {}) };
|
|
219
|
+
delete data.ok;
|
|
220
|
+
delete data.operation;
|
|
221
|
+
delete data.envelope;
|
|
222
|
+
delete data.data;
|
|
223
|
+
return data;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function finalizeAuditEnvelope(operation, requestId, payload) {
|
|
227
|
+
const normalizedPayload = payload && typeof payload === "object" ? { ...payload } : { result: payload };
|
|
228
|
+
const normalizedRequestId = String(normalizedPayload.requestId || requestId || createAuditRequestId());
|
|
229
|
+
normalizedPayload.requestId = normalizedRequestId;
|
|
230
|
+
if (!Object.prototype.hasOwnProperty.call(normalizedPayload, "available")) {
|
|
231
|
+
normalizedPayload.available = !normalizedPayload.error;
|
|
232
|
+
}
|
|
233
|
+
if (!isAuditEnvelopeV2Enabled()) {
|
|
234
|
+
return normalizedPayload;
|
|
235
|
+
}
|
|
236
|
+
normalizedPayload.ok = normalizedPayload.available === true;
|
|
237
|
+
normalizedPayload.operation = String(operation || normalizedPayload.operation || "unknown");
|
|
238
|
+
normalizedPayload.envelope = AUTH_AUDIT_ENVELOPE_VERSION;
|
|
239
|
+
if (normalizedPayload.ok) {
|
|
240
|
+
normalizedPayload.data = buildAuditDataEnvelope(normalizedPayload);
|
|
241
|
+
} else {
|
|
242
|
+
if (!normalizedPayload.error || typeof normalizedPayload.error !== "object") {
|
|
243
|
+
normalizedPayload.error = {
|
|
244
|
+
code: "AUTH_AUDIT_FAILED",
|
|
245
|
+
message: String(normalizedPayload.reason || "Auth audit failed"),
|
|
246
|
+
requestId: normalizedRequestId,
|
|
247
|
+
retryable: false,
|
|
248
|
+
};
|
|
249
|
+
} else if (!normalizedPayload.error.requestId) {
|
|
250
|
+
normalizedPayload.error = {
|
|
251
|
+
...normalizedPayload.error,
|
|
252
|
+
requestId: normalizedRequestId,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
normalizedPayload.reason = String(
|
|
256
|
+
normalizedPayload.reason
|
|
257
|
+
|| normalizedPayload.error.message
|
|
258
|
+
|| "Auth audit failed"
|
|
259
|
+
);
|
|
260
|
+
normalizedPayload.data = null;
|
|
261
|
+
}
|
|
262
|
+
return normalizedPayload;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function resolveAidenidProvisionStatusCode(error) {
|
|
266
|
+
if (!(error instanceof Error)) {
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
const directStatus = Number.parseInt(String(error.statusCode || error.status || ""), 10);
|
|
270
|
+
if (Number.isInteger(directStatus) && directStatus > 0) {
|
|
271
|
+
return directStatus;
|
|
272
|
+
}
|
|
273
|
+
const statusMatch = String(error.message || "").match(/\bstatus\s+(\d{3})\b/i);
|
|
274
|
+
if (!statusMatch) {
|
|
275
|
+
return 0;
|
|
276
|
+
}
|
|
277
|
+
const parsed = Number.parseInt(statusMatch[1], 10);
|
|
278
|
+
return Number.isInteger(parsed) ? parsed : 0;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function resolveAidenidProvisionErrorCode(error) {
|
|
282
|
+
if (!(error instanceof Error)) {
|
|
283
|
+
return "";
|
|
284
|
+
}
|
|
285
|
+
const explicitCode = String(error.errorCode || "").toUpperCase();
|
|
286
|
+
if (explicitCode) {
|
|
287
|
+
return explicitCode;
|
|
288
|
+
}
|
|
289
|
+
const directCode = String(error.code || "").toUpperCase();
|
|
290
|
+
if (directCode) {
|
|
291
|
+
return directCode;
|
|
292
|
+
}
|
|
293
|
+
const cause = error.cause;
|
|
294
|
+
if (!cause || typeof cause !== "object") {
|
|
295
|
+
return "";
|
|
296
|
+
}
|
|
297
|
+
return String(cause.code || cause.errno || "").toUpperCase();
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function classifyAidenidProvisionFailure(error) {
|
|
301
|
+
const classification = {
|
|
302
|
+
retryable: false,
|
|
303
|
+
statusCode: 0,
|
|
304
|
+
errorCode: "",
|
|
305
|
+
};
|
|
306
|
+
if (!(error instanceof Error)) {
|
|
307
|
+
return classification;
|
|
308
|
+
}
|
|
309
|
+
classification.errorCode = resolveAidenidProvisionErrorCode(error);
|
|
310
|
+
classification.statusCode = resolveAidenidProvisionStatusCode(error);
|
|
311
|
+
if (typeof error.retryable === "boolean") {
|
|
312
|
+
classification.retryable = error.retryable;
|
|
313
|
+
return classification;
|
|
314
|
+
}
|
|
315
|
+
if (error.name === "AbortError" || error.name === "TimeoutError") {
|
|
316
|
+
classification.retryable = true;
|
|
317
|
+
return classification;
|
|
318
|
+
}
|
|
319
|
+
if (RETRYABLE_AIDENID_PROVISION_ERROR_CODES.has(classification.errorCode)) {
|
|
320
|
+
classification.retryable = true;
|
|
321
|
+
return classification;
|
|
322
|
+
}
|
|
323
|
+
if (RETRYABLE_AIDENID_PROVISION_STATUS_CODES.has(classification.statusCode)) {
|
|
324
|
+
classification.retryable = true;
|
|
325
|
+
return classification;
|
|
326
|
+
}
|
|
327
|
+
const normalized = `${error.name} ${error.message || ""}`.toLowerCase();
|
|
328
|
+
classification.retryable = RETRYABLE_AIDENID_PROVISION_MESSAGE_PATTERNS.some((pattern) => pattern.test(normalized));
|
|
329
|
+
return classification;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function isRetryableAidenidProvisionError(error) {
|
|
333
|
+
return classifyAidenidProvisionFailure(error).retryable;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function deriveAidenidBackoffSeed(requestId) {
|
|
337
|
+
const normalizedRequestId = String(requestId || "").trim();
|
|
338
|
+
const counter = AUTH_AUDIT_JITTER_COUNTER++;
|
|
339
|
+
const seedMaterial = `${AUTH_AUDIT_JITTER_SECRET}:${normalizedRequestId || "fallback"}:${counter}`;
|
|
340
|
+
return createHash("sha256").update(seedMaterial).digest().readUInt32BE(0);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function computeAidenidProvisionBackoffMs(
|
|
344
|
+
attempt,
|
|
345
|
+
baseBackoffMs = AUTH_AIDENID_PROVISION_BASE_BACKOFF_MS,
|
|
346
|
+
jitterSeed = 0
|
|
347
|
+
) {
|
|
348
|
+
const cappedBase = Math.max(1, Number.isFinite(baseBackoffMs) ? Math.trunc(baseBackoffMs) : AUTH_AIDENID_PROVISION_BASE_BACKOFF_MS);
|
|
349
|
+
const exponential = Math.min(2500, cappedBase * Math.pow(2, Math.max(0, attempt)));
|
|
350
|
+
const normalizedSeed = Number.isFinite(jitterSeed) ? Math.abs(Math.trunc(jitterSeed)) : 0;
|
|
351
|
+
const deterministicJitter = ((Math.max(0, attempt) * 1664525 + 1013904223 + normalizedSeed) % 1000) / 1000;
|
|
352
|
+
const jitterFactor = 0.5 + (deterministicJitter * 0.5);
|
|
353
|
+
return Math.max(1, Math.trunc(exponential * jitterFactor));
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function normalizeAidenidTotalBudgetMs(value) {
|
|
357
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
358
|
+
return AUTH_AIDENID_PROVISION_TOTAL_BUDGET_MS;
|
|
359
|
+
}
|
|
360
|
+
return Math.max(1, Math.trunc(value));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function normalizeProviderBreakerScope(scope) {
|
|
364
|
+
const normalized = String(scope || "").trim().toLowerCase();
|
|
365
|
+
if (!normalized) {
|
|
366
|
+
return AUTH_AUDIT_PROVIDER_SCOPE_DEFAULT;
|
|
367
|
+
}
|
|
368
|
+
return normalized.replace(/[^a-z0-9._:/-]/g, "-").replace(/-+/g, "-").slice(0, 120) || AUTH_AUDIT_PROVIDER_SCOPE_DEFAULT;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function deriveProviderBreakerScope(options = {}) {
|
|
372
|
+
const explicitScope = normalizeProviderBreakerScope(
|
|
373
|
+
options.contextId || options.scopeId || options.repoScope || ""
|
|
374
|
+
);
|
|
375
|
+
if (explicitScope !== AUTH_AUDIT_PROVIDER_SCOPE_DEFAULT) {
|
|
376
|
+
return explicitScope;
|
|
377
|
+
}
|
|
378
|
+
const parts = [];
|
|
379
|
+
const urlCandidate = String(options.targetUrl || options.apiUrl || "").trim();
|
|
380
|
+
if (urlCandidate) {
|
|
381
|
+
try {
|
|
382
|
+
const parsed = new URL(urlCandidate);
|
|
383
|
+
if (parsed.hostname) {
|
|
384
|
+
parts.push(parsed.hostname.toLowerCase());
|
|
385
|
+
}
|
|
386
|
+
} catch {
|
|
387
|
+
// Fall through to non-URL scoped dimensions.
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
const orgScope = normalizeProviderBreakerScope(options.orgId || options.organizationId || "");
|
|
391
|
+
if (orgScope !== AUTH_AUDIT_PROVIDER_SCOPE_DEFAULT) {
|
|
392
|
+
parts.push(`org-${orgScope}`);
|
|
393
|
+
}
|
|
394
|
+
const projectScope = normalizeProviderBreakerScope(options.projectId || "");
|
|
395
|
+
if (projectScope !== AUTH_AUDIT_PROVIDER_SCOPE_DEFAULT) {
|
|
396
|
+
parts.push(`proj-${projectScope}`);
|
|
397
|
+
}
|
|
398
|
+
const repoScope = normalizeProviderBreakerScope(process.env.GITHUB_REPOSITORY || "");
|
|
399
|
+
if (repoScope !== AUTH_AUDIT_PROVIDER_SCOPE_DEFAULT) {
|
|
400
|
+
parts.push(`repo-${repoScope}`);
|
|
401
|
+
}
|
|
402
|
+
if (parts.length === 0) {
|
|
403
|
+
const workspaceFallback = createHash("sha256")
|
|
404
|
+
.update(process.cwd())
|
|
405
|
+
.digest("hex")
|
|
406
|
+
.slice(0, 20);
|
|
407
|
+
parts.push(`ws-${workspaceFallback}`);
|
|
408
|
+
}
|
|
409
|
+
return normalizeProviderBreakerScope(parts.join(":"));
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function getProviderBreakerKey(provider, scope) {
|
|
413
|
+
return `${provider}:${scope}`;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function getProviderBreakerStatePath() {
|
|
417
|
+
const configuredPath = String(
|
|
418
|
+
process.env[AUTH_AUDIT_PROVIDER_BREAKER_STATE_FILE_ENV] || AUTH_AUDIT_PROVIDER_BREAKER_STATE_FILE_DEFAULT
|
|
419
|
+
).trim();
|
|
420
|
+
if (!configuredPath) {
|
|
421
|
+
return "";
|
|
422
|
+
}
|
|
423
|
+
const repoScope = String(process.env.GITHUB_REPOSITORY || "local").trim() || "local";
|
|
424
|
+
const runScope = String(process.env.GITHUB_RUN_ID || process.pid || "0").trim();
|
|
425
|
+
const scopeSuffix = createHash("sha256")
|
|
426
|
+
.update(`${repoScope}:${runScope}`)
|
|
427
|
+
.digest("hex")
|
|
428
|
+
.slice(0, 12);
|
|
429
|
+
const resolvedPath = path.isAbsolute(configuredPath)
|
|
430
|
+
? configuredPath
|
|
431
|
+
: path.resolve(process.cwd(), configuredPath);
|
|
432
|
+
const ext = path.extname(resolvedPath) || ".json";
|
|
433
|
+
const base = resolvedPath.endsWith(ext) ? resolvedPath.slice(0, -ext.length) : resolvedPath;
|
|
434
|
+
return `${base}.${scopeSuffix}${ext}`;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function hydrateProviderBreakerState() {
|
|
438
|
+
if (AUTH_AUDIT_PROVIDER_BREAKERS_HYDRATED) {
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
AUTH_AUDIT_PROVIDER_BREAKERS_HYDRATED = true;
|
|
442
|
+
const statePath = getProviderBreakerStatePath();
|
|
443
|
+
if (!statePath || !fs.existsSync(statePath)) {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const nowMs = Date.now();
|
|
447
|
+
try {
|
|
448
|
+
const raw = fs.readFileSync(statePath, "utf-8");
|
|
449
|
+
const parsed = JSON.parse(raw);
|
|
450
|
+
const entries = Array.isArray(parsed?.entries) ? parsed.entries : [];
|
|
451
|
+
for (const entry of entries) {
|
|
452
|
+
const lastUpdatedAtMs = Number.isFinite(entry?.lastUpdatedAtMs)
|
|
453
|
+
? Math.max(0, Math.trunc(entry.lastUpdatedAtMs))
|
|
454
|
+
: Number.isFinite(entry?.windowStartedAt)
|
|
455
|
+
? Math.max(0, Math.trunc(entry.windowStartedAt))
|
|
456
|
+
: 0;
|
|
457
|
+
if (lastUpdatedAtMs > 0 && (nowMs - lastUpdatedAtMs) > AUTH_AUDIT_PROVIDER_BREAKER_ENTRY_TTL_MS) {
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
const provider = String(entry?.provider || "").trim().toLowerCase();
|
|
461
|
+
if (!provider) {
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const scope = normalizeProviderBreakerScope(entry?.scope);
|
|
465
|
+
const key = getProviderBreakerKey(provider, scope);
|
|
466
|
+
AUTH_AUDIT_PROVIDER_BREAKERS.set(key, {
|
|
467
|
+
key,
|
|
468
|
+
provider,
|
|
469
|
+
scope,
|
|
470
|
+
consecutiveFailures: Number.isFinite(entry?.consecutiveFailures) ? Math.max(0, Math.trunc(entry.consecutiveFailures)) : 0,
|
|
471
|
+
windowStartedAt: Number.isFinite(entry?.windowStartedAt) ? Math.max(0, Math.trunc(entry.windowStartedAt)) : 0,
|
|
472
|
+
openUntilMs: Number.isFinite(entry?.openUntilMs) ? Math.max(0, Math.trunc(entry.openUntilMs)) : 0,
|
|
473
|
+
lastFailureCode: String(entry?.lastFailureCode || "").trim().toUpperCase(),
|
|
474
|
+
lastUpdatedAtMs,
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
} catch {
|
|
478
|
+
// Fall back to in-memory behavior if persisted state cannot be loaded.
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function persistProviderBreakerState(nowMs = Date.now()) {
|
|
483
|
+
const statePath = getProviderBreakerStatePath();
|
|
484
|
+
if (!statePath) {
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
try {
|
|
488
|
+
fs.mkdirSync(path.dirname(statePath), { recursive: true });
|
|
489
|
+
const payload = {
|
|
490
|
+
version: 1,
|
|
491
|
+
updatedAtMs: nowMs,
|
|
492
|
+
entries: [...AUTH_AUDIT_PROVIDER_BREAKERS.values()].map((state) => ({
|
|
493
|
+
provider: state.provider,
|
|
494
|
+
scope: state.scope,
|
|
495
|
+
consecutiveFailures: state.consecutiveFailures,
|
|
496
|
+
windowStartedAt: state.windowStartedAt,
|
|
497
|
+
openUntilMs: state.openUntilMs,
|
|
498
|
+
lastFailureCode: state.lastFailureCode,
|
|
499
|
+
lastUpdatedAtMs: state.lastUpdatedAtMs || nowMs,
|
|
500
|
+
})),
|
|
501
|
+
};
|
|
502
|
+
const tmpPath = `${statePath}.${process.pid}.tmp`;
|
|
503
|
+
fs.writeFileSync(tmpPath, JSON.stringify(payload), "utf-8");
|
|
504
|
+
fs.renameSync(tmpPath, statePath);
|
|
505
|
+
} catch {
|
|
506
|
+
// Persistence is best-effort; in-memory safeguards remain active.
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function sweepProviderBreakers(nowMs = Date.now()) {
|
|
511
|
+
let mutated = false;
|
|
512
|
+
for (const [breakerKey, state] of AUTH_AUDIT_PROVIDER_BREAKERS.entries()) {
|
|
513
|
+
const isOpen = Number(state.openUntilMs || 0) > nowMs;
|
|
514
|
+
const lastUpdatedAtMs = Number(state.lastUpdatedAtMs || state.windowStartedAt || 0);
|
|
515
|
+
if (isOpen) {
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (lastUpdatedAtMs > 0 && (nowMs - lastUpdatedAtMs) > AUTH_AUDIT_PROVIDER_BREAKER_ENTRY_TTL_MS) {
|
|
519
|
+
AUTH_AUDIT_PROVIDER_BREAKERS.delete(breakerKey);
|
|
520
|
+
mutated = true;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (mutated) {
|
|
524
|
+
persistProviderBreakerState(nowMs);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function getProviderBreakerState(provider, scope) {
|
|
529
|
+
hydrateProviderBreakerState();
|
|
530
|
+
const normalizedProvider = String(provider || "").trim().toLowerCase();
|
|
531
|
+
if (!normalizedProvider) {
|
|
532
|
+
return null;
|
|
533
|
+
}
|
|
534
|
+
const normalizedScope = normalizeProviderBreakerScope(scope);
|
|
535
|
+
const breakerKey = getProviderBreakerKey(normalizedProvider, normalizedScope);
|
|
536
|
+
const nowMs = Date.now();
|
|
537
|
+
sweepProviderBreakers(nowMs);
|
|
538
|
+
if (!AUTH_AUDIT_PROVIDER_BREAKERS.has(breakerKey)) {
|
|
539
|
+
AUTH_AUDIT_PROVIDER_BREAKERS.set(breakerKey, {
|
|
540
|
+
key: breakerKey,
|
|
541
|
+
provider: normalizedProvider,
|
|
542
|
+
scope: normalizedScope,
|
|
543
|
+
consecutiveFailures: 0,
|
|
544
|
+
windowStartedAt: 0,
|
|
545
|
+
openUntilMs: 0,
|
|
546
|
+
lastFailureCode: "",
|
|
547
|
+
lastUpdatedAtMs: nowMs,
|
|
548
|
+
});
|
|
549
|
+
persistProviderBreakerState(nowMs);
|
|
550
|
+
}
|
|
551
|
+
return AUTH_AUDIT_PROVIDER_BREAKERS.get(breakerKey);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function getProviderBreakerSnapshot(provider, scope, nowMs = Date.now()) {
|
|
555
|
+
const state = getProviderBreakerState(provider, scope);
|
|
556
|
+
if (!state) {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
const remainingCooldownMs = state.openUntilMs > nowMs ? state.openUntilMs - nowMs : 0;
|
|
560
|
+
return {
|
|
561
|
+
key: state.key,
|
|
562
|
+
provider: state.provider,
|
|
563
|
+
scope: state.scope,
|
|
564
|
+
consecutiveFailures: state.consecutiveFailures,
|
|
565
|
+
windowStartedAt: state.windowStartedAt || 0,
|
|
566
|
+
remainingCooldownMs,
|
|
567
|
+
cooldownUntilMs: state.openUntilMs || 0,
|
|
568
|
+
lastFailureCode: state.lastFailureCode || "",
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function enforceProviderBreaker(provider, scope, requestId) {
|
|
573
|
+
const state = getProviderBreakerState(provider, scope);
|
|
574
|
+
if (!state) {
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
const nowMs = Date.now();
|
|
578
|
+
if (state.openUntilMs > nowMs) {
|
|
579
|
+
const snapshot = getProviderBreakerSnapshot(provider, scope, nowMs);
|
|
580
|
+
const blocked = new AuthAuditError(
|
|
581
|
+
`Provider circuit is open for ${state.provider}/${state.scope}; retry after cooldown (requestId=${requestId}).`
|
|
582
|
+
);
|
|
583
|
+
blocked.errorCode = "AUTH_AUDIT_PROVIDER_CIRCUIT_OPEN";
|
|
584
|
+
blocked.retryable = false;
|
|
585
|
+
blocked.providerBreaker = snapshot;
|
|
586
|
+
throw blocked;
|
|
587
|
+
}
|
|
588
|
+
if (state.openUntilMs > 0 && state.openUntilMs <= nowMs) {
|
|
589
|
+
state.consecutiveFailures = 0;
|
|
590
|
+
state.windowStartedAt = nowMs;
|
|
591
|
+
state.openUntilMs = 0;
|
|
592
|
+
state.lastFailureCode = "";
|
|
593
|
+
state.lastUpdatedAtMs = nowMs;
|
|
594
|
+
AUTH_AUDIT_PROVIDER_BREAKERS.set(state.key, state);
|
|
595
|
+
persistProviderBreakerState(nowMs);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function recordProviderBreakerSuccess(provider, scope) {
|
|
600
|
+
const state = getProviderBreakerState(provider, scope);
|
|
601
|
+
if (!state) {
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
state.consecutiveFailures = 0;
|
|
605
|
+
state.windowStartedAt = 0;
|
|
606
|
+
state.openUntilMs = 0;
|
|
607
|
+
state.lastFailureCode = "";
|
|
608
|
+
state.lastUpdatedAtMs = Date.now();
|
|
609
|
+
AUTH_AUDIT_PROVIDER_BREAKERS.set(state.key, state);
|
|
610
|
+
persistProviderBreakerState(state.lastUpdatedAtMs);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function recordProviderBreakerFailure(provider, scope, errorCode = "") {
|
|
614
|
+
const state = getProviderBreakerState(provider, scope);
|
|
615
|
+
if (!state) {
|
|
616
|
+
return null;
|
|
617
|
+
}
|
|
618
|
+
const nowMs = Date.now();
|
|
619
|
+
if (!state.windowStartedAt || (nowMs - state.windowStartedAt) > AUTH_AUDIT_PROVIDER_BREAKER_WINDOW_MS) {
|
|
620
|
+
state.windowStartedAt = nowMs;
|
|
621
|
+
state.consecutiveFailures = 0;
|
|
622
|
+
}
|
|
623
|
+
state.consecutiveFailures += 1;
|
|
624
|
+
state.lastFailureCode = String(errorCode || "").trim().toUpperCase();
|
|
625
|
+
if (state.consecutiveFailures >= AUTH_AUDIT_PROVIDER_BREAKER_FAILURE_THRESHOLD) {
|
|
626
|
+
state.openUntilMs = nowMs + AUTH_AUDIT_PROVIDER_BREAKER_COOLDOWN_MS;
|
|
627
|
+
}
|
|
628
|
+
state.lastUpdatedAtMs = nowMs;
|
|
629
|
+
AUTH_AUDIT_PROVIDER_BREAKERS.set(state.key, state);
|
|
630
|
+
persistProviderBreakerState(nowMs);
|
|
631
|
+
return getProviderBreakerSnapshot(provider, scope, nowMs);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function isAbortSignalLike(signal) {
|
|
635
|
+
return Boolean(
|
|
636
|
+
signal &&
|
|
637
|
+
typeof signal === "object" &&
|
|
638
|
+
typeof signal.aborted === "boolean" &&
|
|
639
|
+
typeof signal.addEventListener === "function" &&
|
|
640
|
+
typeof signal.removeEventListener === "function"
|
|
641
|
+
);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function composeAbortSignals(primarySignal, secondarySignal) {
|
|
645
|
+
const hasPrimary = isAbortSignalLike(primarySignal);
|
|
646
|
+
const hasSecondary = isAbortSignalLike(secondarySignal);
|
|
647
|
+
if (!hasPrimary && !hasSecondary) {
|
|
648
|
+
return { signal: undefined, cleanup: () => {} };
|
|
649
|
+
}
|
|
650
|
+
if (!hasPrimary) {
|
|
651
|
+
return { signal: secondarySignal, cleanup: () => {} };
|
|
652
|
+
}
|
|
653
|
+
if (!hasSecondary) {
|
|
654
|
+
return { signal: primarySignal, cleanup: () => {} };
|
|
655
|
+
}
|
|
656
|
+
const mergedController = new AbortController();
|
|
657
|
+
const forwardAbort = () => {
|
|
658
|
+
if (!mergedController.signal.aborted) {
|
|
659
|
+
mergedController.abort();
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
if (primarySignal.aborted || secondarySignal.aborted) {
|
|
663
|
+
forwardAbort();
|
|
664
|
+
return { signal: mergedController.signal, cleanup: () => {} };
|
|
665
|
+
}
|
|
666
|
+
primarySignal.addEventListener("abort", forwardAbort, { once: true });
|
|
667
|
+
secondarySignal.addEventListener("abort", forwardAbort, { once: true });
|
|
668
|
+
return {
|
|
669
|
+
signal: mergedController.signal,
|
|
670
|
+
cleanup: () => {
|
|
671
|
+
primarySignal.removeEventListener("abort", forwardAbort);
|
|
672
|
+
secondarySignal.removeEventListener("abort", forwardAbort);
|
|
673
|
+
},
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
async function provisionEmailIdentityWithRetry(provisionEmailIdentity, options = {}) {
|
|
678
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
|
|
679
|
+
? Math.trunc(options.timeoutMs)
|
|
680
|
+
: AUTH_AIDENID_PROVISION_TIMEOUT_MS;
|
|
681
|
+
const maxRetries = Number.isInteger(options.maxRetries) && options.maxRetries >= 0
|
|
682
|
+
? options.maxRetries
|
|
683
|
+
: AUTH_AIDENID_PROVISION_MAX_RETRIES;
|
|
684
|
+
const baseBackoffMs = Number.isFinite(options.baseBackoffMs) && options.baseBackoffMs > 0
|
|
685
|
+
? Math.trunc(options.baseBackoffMs)
|
|
686
|
+
: AUTH_AIDENID_PROVISION_BASE_BACKOFF_MS;
|
|
687
|
+
const requestOptions = options.requestOptions && typeof options.requestOptions === "object"
|
|
688
|
+
? { ...options.requestOptions }
|
|
689
|
+
: {};
|
|
690
|
+
const requestId = String(options.requestId || createAuditRequestId());
|
|
691
|
+
const jitterSeed = Number.isFinite(options.jitterSeed)
|
|
692
|
+
? Math.abs(Math.trunc(options.jitterSeed))
|
|
693
|
+
: deriveAidenidBackoffSeed(requestId);
|
|
694
|
+
const totalBudgetMs = normalizeAidenidTotalBudgetMs(options.totalBudgetMs);
|
|
695
|
+
const minAttemptTimeoutMs = Number.isFinite(options.minAttemptTimeoutMs) && options.minAttemptTimeoutMs > 0
|
|
696
|
+
? Math.trunc(options.minAttemptTimeoutMs)
|
|
697
|
+
: AUTH_AIDENID_PROVISION_MIN_ATTEMPT_TIMEOUT_MS;
|
|
698
|
+
const effectiveMinAttemptTimeoutMs = Math.max(1, Math.min(timeoutMs, minAttemptTimeoutMs));
|
|
699
|
+
const attemptMetrics = [];
|
|
700
|
+
const retryWindowStartedAt = Date.now();
|
|
701
|
+
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
|
|
702
|
+
const elapsedMs = Date.now() - retryWindowStartedAt;
|
|
703
|
+
const remainingBudgetMs = totalBudgetMs - elapsedMs;
|
|
704
|
+
if (remainingBudgetMs <= 0) {
|
|
705
|
+
const exhausted = new AuthAuditError(
|
|
706
|
+
`AIdenID provisioning retry budget exhausted after ${attempt} attempt(s) (requestId=${requestId})`
|
|
707
|
+
);
|
|
708
|
+
exhausted.errorCode = "AIDENID_RETRY_BUDGET_EXHAUSTED";
|
|
709
|
+
exhausted.retryable = false;
|
|
710
|
+
exhausted.retryTelemetry = {
|
|
711
|
+
requestId,
|
|
712
|
+
attempts: attempt,
|
|
713
|
+
totalBudgetMs,
|
|
714
|
+
minAttemptTimeoutMs: effectiveMinAttemptTimeoutMs,
|
|
715
|
+
totalElapsedMs: elapsedMs,
|
|
716
|
+
attemptMetrics,
|
|
717
|
+
};
|
|
718
|
+
throw exhausted;
|
|
719
|
+
}
|
|
720
|
+
if (remainingBudgetMs < effectiveMinAttemptTimeoutMs) {
|
|
721
|
+
const exhausted = new AuthAuditError(
|
|
722
|
+
`AIdenID provisioning remaining retry budget (${remainingBudgetMs}ms) fell below minimum attempt window (${effectiveMinAttemptTimeoutMs}ms) (requestId=${requestId})`
|
|
723
|
+
);
|
|
724
|
+
exhausted.errorCode = "AIDENID_RETRY_BUDGET_EXHAUSTED";
|
|
725
|
+
exhausted.retryable = false;
|
|
726
|
+
exhausted.retryTelemetry = {
|
|
727
|
+
requestId,
|
|
728
|
+
attempts: attempt,
|
|
729
|
+
totalBudgetMs,
|
|
730
|
+
minAttemptTimeoutMs: effectiveMinAttemptTimeoutMs,
|
|
731
|
+
totalElapsedMs: elapsedMs,
|
|
732
|
+
attemptMetrics,
|
|
733
|
+
};
|
|
734
|
+
throw exhausted;
|
|
735
|
+
}
|
|
736
|
+
const attemptTimeoutMs = Math.max(effectiveMinAttemptTimeoutMs, Math.min(timeoutMs, remainingBudgetMs));
|
|
737
|
+
const attemptStartedAt = Date.now();
|
|
738
|
+
const attemptMetric = {
|
|
739
|
+
attempt: attempt + 1,
|
|
740
|
+
timeoutMs: attemptTimeoutMs,
|
|
741
|
+
budgetBeforeAttemptMs: remainingBudgetMs,
|
|
742
|
+
};
|
|
743
|
+
try {
|
|
744
|
+
const attemptPromise = provisionEmailIdentity({
|
|
745
|
+
...requestOptions,
|
|
746
|
+
fetchImpl: async (resource, init = {}) => {
|
|
747
|
+
const callerSignal = isAbortSignalLike(init.signal) ? init.signal : undefined;
|
|
748
|
+
const controller = new AbortController();
|
|
749
|
+
const timeoutHandle = setTimeout(() => controller.abort(), attemptTimeoutMs);
|
|
750
|
+
const { signal: compositeSignal, cleanup: cleanupCompositeSignal } = composeAbortSignals(callerSignal, controller.signal);
|
|
751
|
+
const nextInit = {
|
|
752
|
+
...init,
|
|
753
|
+
...(compositeSignal ? { signal: compositeSignal } : {}),
|
|
754
|
+
};
|
|
755
|
+
try {
|
|
756
|
+
const response = await fetch(resource, nextInit);
|
|
757
|
+
if (response && RETRYABLE_AIDENID_PROVISION_STATUS_CODES.has(Number(response.status || 0))) {
|
|
758
|
+
if (response.body && typeof response.body.cancel === "function") {
|
|
759
|
+
try {
|
|
760
|
+
await response.body.cancel();
|
|
761
|
+
} catch {
|
|
762
|
+
// No-op: retry classification still applies if body drain fails.
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
const transientHttpError = new AuthAuditError(`AIdenID transient HTTP ${response.status}`);
|
|
766
|
+
transientHttpError.errorCode = "AIDENID_HTTP_RETRYABLE";
|
|
767
|
+
transientHttpError.statusCode = Number(response.status || 0);
|
|
768
|
+
transientHttpError.retryable = true;
|
|
769
|
+
throw transientHttpError;
|
|
770
|
+
}
|
|
771
|
+
return response;
|
|
772
|
+
} catch (error) {
|
|
773
|
+
if (callerSignal && callerSignal.aborted === true) {
|
|
774
|
+
const aborted = new AuthAuditError("AIdenID provisioning aborted by caller");
|
|
775
|
+
aborted.errorCode = "AIDENID_ABORTED_BY_CALLER";
|
|
776
|
+
aborted.retryable = false;
|
|
777
|
+
throw aborted;
|
|
778
|
+
}
|
|
779
|
+
const failure = classifyAidenidProvisionFailure(error);
|
|
780
|
+
if (failure.retryable) {
|
|
781
|
+
const wrapped = new AuthAuditError(normalizeErrorMessage(error, "AIdenID provisioning transport failed"));
|
|
782
|
+
wrapped.errorCode = failure.errorCode || "AIDENID_TRANSPORT_RETRYABLE";
|
|
783
|
+
wrapped.statusCode = failure.statusCode || 0;
|
|
784
|
+
wrapped.retryable = true;
|
|
785
|
+
throw wrapped;
|
|
786
|
+
}
|
|
787
|
+
throw error;
|
|
788
|
+
} finally {
|
|
789
|
+
clearTimeout(timeoutHandle);
|
|
790
|
+
cleanupCompositeSignal();
|
|
791
|
+
}
|
|
792
|
+
},
|
|
793
|
+
});
|
|
794
|
+
const result = await Promise.race([
|
|
795
|
+
attemptPromise,
|
|
796
|
+
new Promise((_, reject) => {
|
|
797
|
+
const timer = setTimeout(() => {
|
|
798
|
+
const timeoutError = new AuthAuditError(
|
|
799
|
+
`AIdenID provisioning attempt ${attempt + 1} timed out after ${attemptTimeoutMs}ms (requestId=${requestId})`
|
|
800
|
+
);
|
|
801
|
+
timeoutError.errorCode = "AIDENID_ATTEMPT_TIMEOUT";
|
|
802
|
+
timeoutError.retryable = true;
|
|
803
|
+
reject(timeoutError);
|
|
804
|
+
}, attemptTimeoutMs);
|
|
805
|
+
attemptPromise.finally(() => clearTimeout(timer));
|
|
806
|
+
}),
|
|
807
|
+
]);
|
|
808
|
+
attemptMetric.durationMs = Date.now() - attemptStartedAt;
|
|
809
|
+
attemptMetric.outcome = "success";
|
|
810
|
+
attemptMetrics.push(attemptMetric);
|
|
811
|
+
const retryTelemetry = {
|
|
812
|
+
requestId,
|
|
813
|
+
attempts: attempt + 1,
|
|
814
|
+
totalBudgetMs,
|
|
815
|
+
minAttemptTimeoutMs: effectiveMinAttemptTimeoutMs,
|
|
816
|
+
totalElapsedMs: Date.now() - retryWindowStartedAt,
|
|
817
|
+
attemptMetrics,
|
|
818
|
+
};
|
|
819
|
+
if (result && typeof result === "object" && !Array.isArray(result)) {
|
|
820
|
+
return {
|
|
821
|
+
...result,
|
|
822
|
+
retryTelemetry,
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
return {
|
|
826
|
+
value: result,
|
|
827
|
+
retryTelemetry,
|
|
828
|
+
};
|
|
829
|
+
} catch (error) {
|
|
830
|
+
const failure = classifyAidenidProvisionFailure(error);
|
|
831
|
+
attemptMetric.durationMs = Date.now() - attemptStartedAt;
|
|
832
|
+
attemptMetric.outcome = failure.retryable ? "retryable_error" : "terminal_error";
|
|
833
|
+
attemptMetric.errorCode = failure.errorCode || "AIDENID_PROVISION_FAILED";
|
|
834
|
+
attemptMetric.statusCode = failure.statusCode || 0;
|
|
835
|
+
attemptMetrics.push(attemptMetric);
|
|
836
|
+
if (!failure.retryable || attempt >= maxRetries) {
|
|
837
|
+
const reason = normalizeErrorMessage(error, "AIdenID provisioning failed");
|
|
838
|
+
const terminal = new AuthAuditError(
|
|
839
|
+
`AIdenID provisioning failed after ${attempt + 1} attempt(s) (requestId=${requestId}): ${reason}`
|
|
840
|
+
);
|
|
841
|
+
terminal.errorCode = failure.errorCode || "AIDENID_PROVISION_FAILED";
|
|
842
|
+
terminal.retryable = false;
|
|
843
|
+
terminal.retryTelemetry = {
|
|
844
|
+
requestId,
|
|
845
|
+
attempts: attempt + 1,
|
|
846
|
+
totalBudgetMs,
|
|
847
|
+
minAttemptTimeoutMs: effectiveMinAttemptTimeoutMs,
|
|
848
|
+
totalElapsedMs: Date.now() - retryWindowStartedAt,
|
|
849
|
+
attemptMetrics,
|
|
850
|
+
};
|
|
851
|
+
throw terminal;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
const backoffMs = computeAidenidProvisionBackoffMs(attempt, baseBackoffMs, jitterSeed);
|
|
855
|
+
const remainingAfterAttemptMs = totalBudgetMs - (Date.now() - retryWindowStartedAt);
|
|
856
|
+
if (remainingAfterAttemptMs <= 0) {
|
|
857
|
+
break;
|
|
858
|
+
}
|
|
859
|
+
await sleep(Math.min(backoffMs, remainingAfterAttemptMs));
|
|
860
|
+
}
|
|
861
|
+
const exhausted = new AuthAuditError(`AIdenID provisioning failed after retry budget was exhausted (requestId=${requestId})`);
|
|
862
|
+
exhausted.errorCode = "AIDENID_RETRY_BUDGET_EXHAUSTED";
|
|
863
|
+
exhausted.retryable = false;
|
|
864
|
+
exhausted.retryTelemetry = {
|
|
865
|
+
requestId,
|
|
866
|
+
attempts: maxRetries + 1,
|
|
867
|
+
totalBudgetMs,
|
|
868
|
+
minAttemptTimeoutMs: effectiveMinAttemptTimeoutMs,
|
|
869
|
+
totalElapsedMs: Date.now() - retryWindowStartedAt,
|
|
870
|
+
attemptMetrics,
|
|
871
|
+
};
|
|
872
|
+
throw exhausted;
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function normalizeHeaderValue(value) {
|
|
876
|
+
const normalized = String(value || "").trim();
|
|
877
|
+
return normalized || "";
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function evaluateAuthenticatedHeaderFindings(targetUrl, headers = {}, authSignals = {}) {
|
|
881
|
+
const findings = [];
|
|
882
|
+
const normalizedHeaders = headers && typeof headers === "object" ? headers : {};
|
|
883
|
+
const csp = normalizeHeaderValue(normalizedHeaders["content-security-policy"]);
|
|
884
|
+
const hsts = normalizeHeaderValue(normalizedHeaders["strict-transport-security"]);
|
|
885
|
+
const xFrameOptions = normalizeHeaderValue(normalizedHeaders["x-frame-options"]);
|
|
886
|
+
let requiresHsts = false;
|
|
887
|
+
try {
|
|
888
|
+
requiresHsts = new URL(targetUrl).protocol === "https:";
|
|
889
|
+
} catch {
|
|
890
|
+
requiresHsts = String(targetUrl || "").startsWith("https://");
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
if (!csp) {
|
|
894
|
+
findings.push({
|
|
895
|
+
severity: "P2",
|
|
896
|
+
title: "Authenticated page missing Content-Security-Policy header",
|
|
897
|
+
file: targetUrl,
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
if (requiresHsts && !hsts) {
|
|
901
|
+
findings.push({
|
|
902
|
+
severity: "P1",
|
|
903
|
+
title: "Authenticated page missing Strict-Transport-Security header",
|
|
904
|
+
file: targetUrl,
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
if (!xFrameOptions) {
|
|
908
|
+
findings.push({
|
|
909
|
+
severity: "P2",
|
|
910
|
+
title: "Authenticated page missing X-Frame-Options header",
|
|
911
|
+
file: targetUrl,
|
|
912
|
+
});
|
|
913
|
+
} else if (!/^(deny|sameorigin)$/i.test(xFrameOptions)) {
|
|
914
|
+
findings.push({
|
|
915
|
+
severity: "P2",
|
|
916
|
+
title: "Authenticated page has weak X-Frame-Options policy: " + xFrameOptions,
|
|
917
|
+
file: targetUrl,
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
if (authSignals && typeof authSignals === "object") {
|
|
922
|
+
authSignals.headerPolicyPassed = findings.length === 0;
|
|
923
|
+
authSignals.headerPolicyFindingCount = findings.length;
|
|
924
|
+
}
|
|
925
|
+
return findings;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async function provisionTestIdentity(input) {
|
|
929
|
+
const requestId = String(input.requestId || createAuditRequestId());
|
|
930
|
+
const providerKey = AUTH_AUDIT_PROVIDER_AIDENID;
|
|
931
|
+
const providerScope = deriveProviderBreakerScope({
|
|
932
|
+
contextId: input.providerContextId || input.contextId || input.scopeId,
|
|
933
|
+
apiUrl: input.apiUrl,
|
|
934
|
+
orgId: input.orgId || input.aidenidOrgId,
|
|
935
|
+
projectId: input.projectId || input.aidenidProjectId,
|
|
936
|
+
});
|
|
937
|
+
try {
|
|
938
|
+
enforceProviderBreaker(providerKey, providerScope, requestId);
|
|
939
|
+
const executeRequested = input.execute === true;
|
|
940
|
+
const allowLiveProvision = input.allowProvisioning === true || process.env.SENTINELAYER_ALLOW_LIVE_IDENTITY_PROVISION === "1";
|
|
941
|
+
if (executeRequested && !allowLiveProvision) {
|
|
942
|
+
return buildUnavailableAuditResponse(
|
|
943
|
+
requestId,
|
|
944
|
+
"AIDENID_PROVISION_APPROVAL_REQUIRED",
|
|
945
|
+
"Live AIdenID provisioning requires explicit allowProvisioning=true (or SENTINELAYER_ALLOW_LIVE_IDENTITY_PROVISION=1)."
|
|
946
|
+
);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const { provisionEmailIdentity, resolveAidenIdCredentials } = await import("../../../ai/aidenid.js");
|
|
950
|
+
const creds = await resolveAidenIdCredentials();
|
|
951
|
+
if (!creds.apiKey) {
|
|
952
|
+
return buildUnavailableAuditResponse(
|
|
953
|
+
requestId,
|
|
954
|
+
"AIDENID_API_KEY_MISSING",
|
|
955
|
+
"AIdenID API key not configured (set AIDENID_API_KEY)"
|
|
956
|
+
);
|
|
957
|
+
}
|
|
958
|
+
const result = await provisionEmailIdentityWithRetry(provisionEmailIdentity, {
|
|
959
|
+
timeoutMs: AUTH_AIDENID_PROVISION_TIMEOUT_MS,
|
|
960
|
+
maxRetries: AUTH_AIDENID_PROVISION_MAX_RETRIES,
|
|
961
|
+
baseBackoffMs: AUTH_AIDENID_PROVISION_BASE_BACKOFF_MS,
|
|
962
|
+
totalBudgetMs: AUTH_AIDENID_PROVISION_TOTAL_BUDGET_MS,
|
|
963
|
+
minAttemptTimeoutMs: AUTH_AIDENID_PROVISION_MIN_ATTEMPT_TIMEOUT_MS,
|
|
964
|
+
requestId,
|
|
965
|
+
requestOptions: {
|
|
966
|
+
apiUrl: creds.apiUrl,
|
|
967
|
+
apiKey: creds.apiKey,
|
|
968
|
+
tags: ["jules-audit", "frontend-test"],
|
|
969
|
+
ttlSeconds: 3600,
|
|
970
|
+
dryRun: !executeRequested,
|
|
971
|
+
},
|
|
972
|
+
});
|
|
973
|
+
const identity = result && typeof result === "object"
|
|
974
|
+
? (Object.prototype.hasOwnProperty.call(result, "identity") ? result.identity : (Object.prototype.hasOwnProperty.call(result, "value") ? result.value : result))
|
|
975
|
+
: result;
|
|
976
|
+
const retryTelemetry = result && typeof result === "object" && result.retryTelemetry
|
|
977
|
+
? result.retryTelemetry
|
|
978
|
+
: null;
|
|
979
|
+
recordProviderBreakerSuccess(providerKey, providerScope);
|
|
980
|
+
return { available: true, requestId, dryRun: !executeRequested, identity, retryTelemetry };
|
|
981
|
+
} catch (err) {
|
|
982
|
+
const message = "AIdenID provisioning failed: " + normalizeErrorMessage(err, "unknown error");
|
|
983
|
+
const retryable = isRetryableAidenidProvisionError(err);
|
|
984
|
+
let providerBreaker = err && typeof err === "object" && err.providerBreaker ? err.providerBreaker : null;
|
|
985
|
+
if (retryable) {
|
|
986
|
+
providerBreaker = recordProviderBreakerFailure(providerKey, providerScope, err && typeof err === "object" ? err.errorCode : "") || providerBreaker;
|
|
987
|
+
} else if (!providerBreaker) {
|
|
988
|
+
providerBreaker = getProviderBreakerSnapshot(providerKey, providerScope);
|
|
989
|
+
}
|
|
990
|
+
return buildUnavailableAuditResponse(requestId, "AIDENID_PROVISION_FAILED", message, {
|
|
991
|
+
retryable,
|
|
992
|
+
retryTelemetry: err && typeof err === "object" && err.retryTelemetry ? err.retryTelemetry : null,
|
|
993
|
+
providerBreaker,
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/**
|
|
999
|
+
* Run Playwright to authenticate and inspect the page.
|
|
1000
|
+
* - Runtime values loaded from a secure temp context file (credentials not exposed in process env)
|
|
1001
|
+
* - Auth verification checks URL change + cookie presence (not just click success)
|
|
1002
|
+
* - Console errors redacted to prevent sensitive data leakage
|
|
1003
|
+
* - Cookie values never captured (names + flags only)
|
|
1004
|
+
* - Temp script/context cleanup in finally block (not just success path)
|
|
1005
|
+
*/
|
|
1006
|
+
async function authenticatedPageCheck(input) {
|
|
1007
|
+
const requestId = String(input.requestId || createAuditRequestId());
|
|
1008
|
+
const providerKey = AUTH_AUDIT_PROVIDER_PLAYWRIGHT_TARGET;
|
|
1009
|
+
const url = input.url;
|
|
1010
|
+
if (!url) throw new AuthAuditError("authenticated_page_check requires url");
|
|
1011
|
+
const targetUrl = resolveAuthAuditTarget(url, input, "authenticated_page_check.target");
|
|
1012
|
+
const providerScope = deriveProviderBreakerScope({
|
|
1013
|
+
contextId: input.providerContextId || input.contextId || input.scopeId,
|
|
1014
|
+
targetUrl,
|
|
1015
|
+
});
|
|
1016
|
+
|
|
1017
|
+
const loginUrlCandidate = input.loginUrl || targetUrl + "/login";
|
|
1018
|
+
const loginUrl = resolveAuthAuditTarget(loginUrlCandidate, input, "authenticated_page_check.login");
|
|
1019
|
+
const allowAuthMutation = input.allowAuthMutation === true || process.env[AUTH_MUTATION_ALLOWED_ENV] === "1";
|
|
1020
|
+
|
|
1021
|
+
try {
|
|
1022
|
+
enforceProviderBreaker(providerKey, providerScope, requestId);
|
|
1023
|
+
const authContextJson = JSON.stringify({
|
|
1024
|
+
email: input.email || "",
|
|
1025
|
+
password: input.password || "",
|
|
1026
|
+
emailField: input.emailField || "",
|
|
1027
|
+
passwordField: input.passwordField || "",
|
|
1028
|
+
submitSelector: input.submitSelector || "",
|
|
1029
|
+
});
|
|
1030
|
+
// Use scrubbed env — strip API keys/tokens from child process
|
|
1031
|
+
const { buildScrubbedEnv } = await import("./shell.js");
|
|
1032
|
+
const env = {
|
|
1033
|
+
...buildScrubbedEnv(),
|
|
1034
|
+
SL_AUDIT_TARGET_URL: targetUrl,
|
|
1035
|
+
SL_AUDIT_LOGIN_URL: loginUrl,
|
|
1036
|
+
SL_AUDIT_ALLOW_AUTH_MUTATION: allowAuthMutation ? "1" : "0",
|
|
1037
|
+
};
|
|
1038
|
+
|
|
1039
|
+
const output = await runPlaywrightAuditScriptWithRetry(null, env, {
|
|
1040
|
+
scriptSource: PLAYWRIGHT_AUTH_SCRIPT,
|
|
1041
|
+
stdinPayload: authContextJson,
|
|
1042
|
+
});
|
|
1043
|
+
|
|
1044
|
+
const result = JSON.parse(output.trim());
|
|
1045
|
+
const findings = [];
|
|
1046
|
+
for (const cookie of (result.cookies || [])) {
|
|
1047
|
+
if (cookie.sensitive && !cookie.httpOnly) {
|
|
1048
|
+
findings.push({ severity: "P1", title: "Sensitive cookie '" + cookie.name + "' missing httpOnly flag", file: targetUrl });
|
|
1049
|
+
}
|
|
1050
|
+
if (cookie.sensitive && !cookie.secure) {
|
|
1051
|
+
findings.push({ severity: "P1", title: "Sensitive cookie '" + cookie.name + "' missing Secure flag", file: targetUrl });
|
|
1052
|
+
}
|
|
1053
|
+
if (cookie.sensitive && cookie.sameSite === "None") {
|
|
1054
|
+
findings.push({ severity: "P2", title: "Sensitive cookie '" + cookie.name + "' has SameSite=None", file: targetUrl });
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
findings.push(...evaluateAuthenticatedHeaderFindings(targetUrl, result.headers || {}, result.authSignals || {}));
|
|
1058
|
+
recordProviderBreakerSuccess(providerKey, providerScope);
|
|
1059
|
+
return { available: true, requestId, method: "playwright", mutationAllowed: allowAuthMutation, findings, ...result };
|
|
1060
|
+
} catch (err) {
|
|
1061
|
+
const code = err instanceof AuthAuditError ? "AUTH_AUDIT_VALIDATION_FAILED" : "AUTH_AUDIT_PLAYWRIGHT_FAILED";
|
|
1062
|
+
const baseMessage = err instanceof AuthAuditError ? err.message : "Playwright auth audit failed: " + normalizeErrorMessage(err, "unknown error");
|
|
1063
|
+
const retryable = isRetryablePlaywrightExecutionError(err);
|
|
1064
|
+
let providerBreaker = err && typeof err === "object" && err.providerBreaker ? err.providerBreaker : null;
|
|
1065
|
+
if (retryable) {
|
|
1066
|
+
providerBreaker = recordProviderBreakerFailure(providerKey, providerScope, err && typeof err === "object" ? err.errorCode : "") || providerBreaker;
|
|
1067
|
+
} else if (!providerBreaker) {
|
|
1068
|
+
providerBreaker = getProviderBreakerSnapshot(providerKey, providerScope);
|
|
1069
|
+
}
|
|
1070
|
+
return buildUnavailableAuditResponse(requestId, code, baseMessage, {
|
|
1071
|
+
retryable,
|
|
1072
|
+
providerBreaker,
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
// Playwright script as a constant — no string interpolation of URLs/credentials.
|
|
1078
|
+
// Dynamic auth context is read from stdin at runtime to avoid local credential temp files.
|
|
1079
|
+
const PLAYWRIGHT_AUTH_SCRIPT = `
|
|
1080
|
+
const { chromium } = require('playwright');
|
|
1081
|
+
const fs = require('node:fs');
|
|
1082
|
+
|
|
1083
|
+
(async () => {
|
|
1084
|
+
const targetUrl = process.env.SL_AUDIT_TARGET_URL;
|
|
1085
|
+
const loginUrl = process.env.SL_AUDIT_LOGIN_URL;
|
|
1086
|
+
const allowAuthMutation = process.env.SL_AUDIT_ALLOW_AUTH_MUTATION === '1';
|
|
1087
|
+
let context = {};
|
|
1088
|
+
try {
|
|
1089
|
+
let stdinPayload = fs.readFileSync(0, 'utf-8');
|
|
1090
|
+
if (stdinPayload) {
|
|
1091
|
+
context = JSON.parse(stdinPayload) || {};
|
|
1092
|
+
}
|
|
1093
|
+
stdinPayload = '';
|
|
1094
|
+
} catch {
|
|
1095
|
+
context = {};
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
let email = context.email || '';
|
|
1099
|
+
let password = context.password || '';
|
|
1100
|
+
const emailSelector = context.emailField || 'input[type="email"]';
|
|
1101
|
+
const passwordSelector = context.passwordField || 'input[type="password"]';
|
|
1102
|
+
const submitSelector = context.submitSelector || 'button[type="submit"]';
|
|
1103
|
+
if (Object.prototype.hasOwnProperty.call(context, 'password')) delete context.password;
|
|
1104
|
+
if (Object.prototype.hasOwnProperty.call(context, 'token')) delete context.token;
|
|
1105
|
+
if (Object.prototype.hasOwnProperty.call(context, 'secret')) delete context.secret;
|
|
1106
|
+
|
|
1107
|
+
let browser = null;
|
|
1108
|
+
const results = { authenticated: false, authSignals: {}, errors: [], cookies: [], headers: {}, domStats: {}, executionFailed: false };
|
|
1109
|
+
results.authSignals.mutationAllowed = allowAuthMutation;
|
|
1110
|
+
function normalizePath(value) {
|
|
1111
|
+
const normalized = String(value || '/').replace(/\\/+$/, '');
|
|
1112
|
+
return normalized || '/';
|
|
1113
|
+
}
|
|
1114
|
+
function didLeaveLoginSurface(currentValue, loginValue) {
|
|
1115
|
+
try {
|
|
1116
|
+
const currentUrl = new URL(currentValue);
|
|
1117
|
+
const loginParsed = new URL(loginValue);
|
|
1118
|
+
return (
|
|
1119
|
+
currentUrl.origin !== loginParsed.origin ||
|
|
1120
|
+
normalizePath(currentUrl.pathname) !== normalizePath(loginParsed.pathname)
|
|
1121
|
+
);
|
|
1122
|
+
} catch {
|
|
1123
|
+
return String(currentValue || '') !== String(loginValue || '');
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
function sanitizeErrorText(value) {
|
|
1127
|
+
return String(value || '')
|
|
1128
|
+
.replace(/\\s+/g, ' ')
|
|
1129
|
+
.replace(/Bearer\\s+[^\\s,;]+/gi, 'Bearer [REDACTED]')
|
|
1130
|
+
.replace(/\\b(?:authorization|x-api-key|api-key|token|access_token|refresh_token|id_token|session|cookie|set-cookie|secret|password|passwd)\\b\\s*[:=]\\s*["']?[^"'\\s,;]+/gi, '$1=[REDACTED]')
|
|
1131
|
+
.replace(/\\b[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{8,}\\b/g, '[REDACTED_JWT]')
|
|
1132
|
+
.replace(/\\b(?:gh[pousr]_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9]{16,}|AIza[0-9A-Za-z-_]{20,}|xox[baprs]-[0-9A-Za-z-]{10,})\\b/g, '[REDACTED_TOKEN]')
|
|
1133
|
+
.replace(/\\b[A-Fa-f0-9]{32,}\\b/g, '[REDACTED_HEX]')
|
|
1134
|
+
.replace(/\\b[A-Za-z0-9_-]{40,}\\b/g, '[REDACTED_TOKEN]')
|
|
1135
|
+
.slice(0, 200);
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
try {
|
|
1139
|
+
browser = await chromium.launch({ headless: true });
|
|
1140
|
+
const page = await browser.newPage();
|
|
1141
|
+
page.on('console', msg => {
|
|
1142
|
+
if (msg.type() === 'error') {
|
|
1143
|
+
const text = sanitizeErrorText(msg.text());
|
|
1144
|
+
results.errors.push({ type: 'console', text });
|
|
1145
|
+
}
|
|
1146
|
+
});
|
|
1147
|
+
page.on('pageerror', err => {
|
|
1148
|
+
const text = sanitizeErrorText(err && err.message ? err.message : String(err || ''));
|
|
1149
|
+
results.errors.push({ type: 'pageerror', text });
|
|
1150
|
+
});
|
|
1151
|
+
|
|
1152
|
+
if (email && password && loginUrl) {
|
|
1153
|
+
await page.goto(loginUrl, { waitUntil: 'networkidle', timeout: 30000 });
|
|
1154
|
+
if (allowAuthMutation) {
|
|
1155
|
+
await page.fill(emailSelector, email);
|
|
1156
|
+
await page.fill(passwordSelector, password);
|
|
1157
|
+
await page.click(submitSelector);
|
|
1158
|
+
let navigationError = null;
|
|
1159
|
+
await page.waitForNavigation({ waitUntil: 'networkidle', timeout: 15000 }).catch((err) => {
|
|
1160
|
+
navigationError = sanitizeErrorText(err && err.message ? err.message : 'navigation timeout');
|
|
1161
|
+
});
|
|
1162
|
+
if (navigationError) {
|
|
1163
|
+
results.authSignals.navigationTimeout = true;
|
|
1164
|
+
results.errors.push({ type: 'navigation', text: navigationError });
|
|
1165
|
+
}
|
|
1166
|
+
results.authSignals.mutationPerformed = true;
|
|
1167
|
+
} else {
|
|
1168
|
+
results.authSignals.mutationPerformed = false;
|
|
1169
|
+
}
|
|
1170
|
+
const authVerificationMaxAttempts = allowAuthMutation ? 3 : 1;
|
|
1171
|
+
let verificationAttemptsUsed = 0;
|
|
1172
|
+
let urlChanged = false;
|
|
1173
|
+
let authCookiePresent = false;
|
|
1174
|
+
let loginFormVisible = true;
|
|
1175
|
+
for (let verificationAttempt = 1; verificationAttempt <= authVerificationMaxAttempts; verificationAttempt += 1) {
|
|
1176
|
+
verificationAttemptsUsed = verificationAttempt;
|
|
1177
|
+
const currentUrl = page.url();
|
|
1178
|
+
const postCookies = await page.context().cookies();
|
|
1179
|
+
urlChanged = didLeaveLoginSurface(currentUrl, loginUrl);
|
|
1180
|
+
authCookiePresent = postCookies.some(c => /(?:^|[-_])(session|token|auth|jwt)(?:$|[-_])/i.test(c.name) && (c.httpOnly || c.secure));
|
|
1181
|
+
loginFormVisible = await page.evaluate((emailSel, passwordSel) => (
|
|
1182
|
+
Boolean(document.querySelector(emailSel) && document.querySelector(passwordSel))
|
|
1183
|
+
), emailSelector, passwordSelector).catch(() => false);
|
|
1184
|
+
const navigationSucceeded = results.authSignals.navigationTimeout !== true;
|
|
1185
|
+
results.authenticated = navigationSucceeded && !loginFormVisible && urlChanged && authCookiePresent;
|
|
1186
|
+
if (results.authenticated) {
|
|
1187
|
+
break;
|
|
1188
|
+
}
|
|
1189
|
+
if (verificationAttempt < authVerificationMaxAttempts) {
|
|
1190
|
+
await page.waitForTimeout(400 * verificationAttempt);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
results.authSignals = {
|
|
1194
|
+
urlChanged,
|
|
1195
|
+
authCookiePresent,
|
|
1196
|
+
loginFormVisible,
|
|
1197
|
+
authVerificationAttemptsUsed: verificationAttemptsUsed,
|
|
1198
|
+
authVerificationMaxAttempts,
|
|
1199
|
+
};
|
|
1200
|
+
results.authSignals.authVerificationRetried = verificationAttemptsUsed > 1;
|
|
1201
|
+
results.authSignals.mutationAllowed = allowAuthMutation;
|
|
1202
|
+
results.authSignals.mutationPerformed = allowAuthMutation ? true : false;
|
|
1203
|
+
email = '';
|
|
1204
|
+
password = '';
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
const targetResponse = await page.goto(targetUrl, { waitUntil: 'networkidle', timeout: 30000 });
|
|
1208
|
+
|
|
1209
|
+
const cookies = await page.context().cookies();
|
|
1210
|
+
results.cookies = cookies.map(c => ({
|
|
1211
|
+
name: c.name, domain: c.domain,
|
|
1212
|
+
httpOnly: c.httpOnly, secure: c.secure,
|
|
1213
|
+
sameSite: c.sameSite,
|
|
1214
|
+
sensitive: /session|token|auth|jwt/i.test(c.name),
|
|
1215
|
+
}));
|
|
1216
|
+
|
|
1217
|
+
results.domStats = await page.evaluate(() => ({
|
|
1218
|
+
title: document.title,
|
|
1219
|
+
nodeCount: document.querySelectorAll('*').length,
|
|
1220
|
+
formCount: document.querySelectorAll('form').length,
|
|
1221
|
+
inputCount: document.querySelectorAll('input').length,
|
|
1222
|
+
}));
|
|
1223
|
+
|
|
1224
|
+
const response = targetResponse || null;
|
|
1225
|
+
const targetLoginFormVisible = await page.evaluate((emailSel, passwordSel) => (
|
|
1226
|
+
Boolean(document.querySelector(emailSel) && document.querySelector(passwordSel))
|
|
1227
|
+
), emailSelector, passwordSelector).catch(() => true);
|
|
1228
|
+
const targetStatus = response ? response.status() : null;
|
|
1229
|
+
const targetStatusOk = typeof targetStatus === 'number' ? targetStatus < 400 : false;
|
|
1230
|
+
results.authSignals.targetLoginFormVisible = targetLoginFormVisible;
|
|
1231
|
+
results.authSignals.targetStatus = targetStatus;
|
|
1232
|
+
results.authSignals.targetStatusOk = targetStatusOk;
|
|
1233
|
+
if (results.authenticated) {
|
|
1234
|
+
results.authenticated = !targetLoginFormVisible && targetStatusOk;
|
|
1235
|
+
}
|
|
1236
|
+
if (response) {
|
|
1237
|
+
const h = response.headers();
|
|
1238
|
+
results.headers = {
|
|
1239
|
+
'content-security-policy': h['content-security-policy'] || null,
|
|
1240
|
+
'x-frame-options': h['x-frame-options'] || null,
|
|
1241
|
+
'strict-transport-security': h['strict-transport-security'] || null,
|
|
1242
|
+
'cache-control': h['cache-control'] || null,
|
|
1243
|
+
};
|
|
1244
|
+
const normalizedFramePolicy = String(results.headers['x-frame-options'] || '').trim().toLowerCase();
|
|
1245
|
+
const headerPolicyBreaches = [];
|
|
1246
|
+
if (!results.headers['content-security-policy']) {
|
|
1247
|
+
headerPolicyBreaches.push('missing_content_security_policy');
|
|
1248
|
+
}
|
|
1249
|
+
if (String(targetUrl || '').startsWith('https://') && !results.headers['strict-transport-security']) {
|
|
1250
|
+
headerPolicyBreaches.push('missing_strict_transport_security');
|
|
1251
|
+
}
|
|
1252
|
+
if (!normalizedFramePolicy) {
|
|
1253
|
+
headerPolicyBreaches.push('missing_x_frame_options');
|
|
1254
|
+
} else if (!(normalizedFramePolicy === 'deny' || normalizedFramePolicy === 'sameorigin')) {
|
|
1255
|
+
headerPolicyBreaches.push('weak_x_frame_options');
|
|
1256
|
+
}
|
|
1257
|
+
results.authSignals.headerPolicyBreaches = headerPolicyBreaches;
|
|
1258
|
+
results.authSignals.headerPolicyPassed = headerPolicyBreaches.length === 0;
|
|
1259
|
+
results.authSignals.headerPolicyFailed = headerPolicyBreaches.length > 0;
|
|
1260
|
+
} else {
|
|
1261
|
+
results.authSignals.headerPolicyBreaches = ['target_response_unavailable'];
|
|
1262
|
+
results.authSignals.headerPolicyPassed = false;
|
|
1263
|
+
results.authSignals.headerPolicyFailed = true;
|
|
1264
|
+
}
|
|
1265
|
+
} catch (err) {
|
|
1266
|
+
results.executionFailed = true;
|
|
1267
|
+
const text = sanitizeErrorText('Playwright error: ' + (err && err.message ? err.message : ''));
|
|
1268
|
+
results.errors.push({ type: 'playwright', text });
|
|
1269
|
+
} finally {
|
|
1270
|
+
try { console.log(JSON.stringify(results)); } catch {}
|
|
1271
|
+
if (browser) {
|
|
1272
|
+
await browser.close().catch(() => {});
|
|
1273
|
+
}
|
|
1274
|
+
if (results.executionFailed) {
|
|
1275
|
+
process.exitCode = 1;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
})();
|
|
1279
|
+
`;
|
|
1280
|
+
|
|
1281
|
+
const MAX_AUTH_REDIRECT_HOPS = 5;
|
|
1282
|
+
const AUTH_FLOW_FETCH_TIMEOUT_MS = 10_000;
|
|
1283
|
+
const AUTH_FLOW_FETCH_MAX_RETRIES = 2;
|
|
1284
|
+
const AUTH_FLOW_FETCH_BASE_BACKOFF_MS = 200;
|
|
1285
|
+
const RETRYABLE_AUTH_FLOW_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
|
|
1286
|
+
const RETRYABLE_AUTH_FLOW_ERROR_CODES = new Set([
|
|
1287
|
+
"ECONNRESET",
|
|
1288
|
+
"EAI_AGAIN",
|
|
1289
|
+
"ENOTFOUND",
|
|
1290
|
+
"ECONNREFUSED",
|
|
1291
|
+
"ETIMEDOUT",
|
|
1292
|
+
"ECONNABORTED",
|
|
1293
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
1294
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
1295
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
1296
|
+
]);
|
|
1297
|
+
const RETRYABLE_AUTH_FLOW_MESSAGE_PATTERNS = [
|
|
1298
|
+
/\bfetch failed\b/i,
|
|
1299
|
+
/\bnetwork(?:\s+|-)error\b/i,
|
|
1300
|
+
/\bsocket hang up\b/i,
|
|
1301
|
+
/\btimed?\s*out\b/i,
|
|
1302
|
+
/\b(?:econnreset|eai_again|enotfound|econnrefused|etimedout)\b/i,
|
|
1303
|
+
/\btemporary(?:\s+|-)failure\b/i,
|
|
1304
|
+
/\bconnection\b.*\b(?:reset|terminated|closed)\b/i,
|
|
1305
|
+
];
|
|
1306
|
+
const AUTH_FLOW_LOCAL_TEST_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
|
|
1307
|
+
const DEFAULT_APPROVED_AUTH_AUDIT_HOSTS = new Set(["example.com", "www.example.com"]);
|
|
1308
|
+
const AUTH_AUDIT_ALLOWED_HOSTS_ENV = "SENTINELAYER_AUTH_AUDIT_ALLOWED_HOSTS";
|
|
1309
|
+
|
|
1310
|
+
function computePlaywrightBackoffMs(attempt, baseBackoffMs = AUTH_PLAYWRIGHT_EXEC_BASE_BACKOFF_MS) {
|
|
1311
|
+
const cappedBase = Math.max(1, Number.isFinite(baseBackoffMs) ? Math.trunc(baseBackoffMs) : AUTH_PLAYWRIGHT_EXEC_BASE_BACKOFF_MS);
|
|
1312
|
+
const exponential = Math.min(4000, cappedBase * Math.pow(2, Math.max(0, attempt)));
|
|
1313
|
+
const deterministicJitter = ((Math.max(0, attempt) * 1103515245 + 12345) % 1000) / 1000;
|
|
1314
|
+
const jitterFactor = 0.5 + (deterministicJitter * 0.5);
|
|
1315
|
+
return Math.max(1, Math.trunc(exponential * jitterFactor));
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
function isRetryablePlaywrightExecutionError(error) {
|
|
1319
|
+
if (!(error instanceof Error)) {
|
|
1320
|
+
return false;
|
|
1321
|
+
}
|
|
1322
|
+
if (error.name === "AbortError" || error.name === "TimeoutError") {
|
|
1323
|
+
return true;
|
|
1324
|
+
}
|
|
1325
|
+
const code = String(error.code || "").toUpperCase();
|
|
1326
|
+
if (RETRYABLE_PLAYWRIGHT_EXEC_ERROR_CODES.has(code)) {
|
|
1327
|
+
return true;
|
|
1328
|
+
}
|
|
1329
|
+
if (error.killed === true && (error.signal === "SIGTERM" || error.signal === "SIGKILL")) {
|
|
1330
|
+
return true;
|
|
1331
|
+
}
|
|
1332
|
+
const causeCode = String(error.cause?.code || error.cause?.errno || "").toUpperCase();
|
|
1333
|
+
return RETRYABLE_PLAYWRIGHT_EXEC_ERROR_CODES.has(causeCode);
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
function normalizeAuthAuditErrorMessage(error, fallbackMessage) {
|
|
1337
|
+
if (error instanceof Error && error.message) {
|
|
1338
|
+
return error.message;
|
|
1339
|
+
}
|
|
1340
|
+
const normalized = String(error || "").trim();
|
|
1341
|
+
return normalized || fallbackMessage;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
export async function runPlaywrightAuditScriptWithRetry(scriptPath, env, options = {}) {
|
|
1345
|
+
const scriptSource = String(options.scriptSource || "");
|
|
1346
|
+
const runArgs = scriptSource ? ["-e", scriptSource] : (scriptPath ? [scriptPath] : []);
|
|
1347
|
+
if (runArgs.length === 0) {
|
|
1348
|
+
throw new AuthAuditError("Playwright auth audit failed: missing script path");
|
|
1349
|
+
}
|
|
1350
|
+
const stdinPayload = String(options.stdinPayload || "");
|
|
1351
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
|
|
1352
|
+
? Math.trunc(options.timeoutMs)
|
|
1353
|
+
: AUTH_PLAYWRIGHT_EXEC_TIMEOUT_MS;
|
|
1354
|
+
const maxRetries = Number.isInteger(options.maxRetries) && options.maxRetries >= 0
|
|
1355
|
+
? options.maxRetries
|
|
1356
|
+
: AUTH_PLAYWRIGHT_EXEC_MAX_RETRIES;
|
|
1357
|
+
const baseBackoffMs = Number.isFinite(options.baseBackoffMs) && options.baseBackoffMs > 0
|
|
1358
|
+
? Math.trunc(options.baseBackoffMs)
|
|
1359
|
+
: AUTH_PLAYWRIGHT_EXEC_BASE_BACKOFF_MS;
|
|
1360
|
+
const totalBudgetMs = Number.isFinite(options.totalBudgetMs) && options.totalBudgetMs > 0
|
|
1361
|
+
? Math.trunc(options.totalBudgetMs)
|
|
1362
|
+
: AUTH_PLAYWRIGHT_EXEC_TOTAL_BUDGET_MS;
|
|
1363
|
+
const minAttemptTimeoutMs = Number.isFinite(options.minAttemptTimeoutMs) && options.minAttemptTimeoutMs > 0
|
|
1364
|
+
? Math.trunc(options.minAttemptTimeoutMs)
|
|
1365
|
+
: AUTH_PLAYWRIGHT_EXEC_MIN_ATTEMPT_TIMEOUT_MS;
|
|
1366
|
+
const execute = typeof options.exec === "function" ? options.exec : execFileSync;
|
|
1367
|
+
const now = typeof options.now === "function" ? options.now : Date.now;
|
|
1368
|
+
const sleepFn = typeof options.sleep === "function" ? options.sleep : sleep;
|
|
1369
|
+
const retryWindowStartedAt = now();
|
|
1370
|
+
|
|
1371
|
+
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
|
|
1372
|
+
const elapsedMs = now() - retryWindowStartedAt;
|
|
1373
|
+
const remainingBudgetMs = totalBudgetMs - elapsedMs;
|
|
1374
|
+
if (remainingBudgetMs <= 0) {
|
|
1375
|
+
throw new AuthAuditError(
|
|
1376
|
+
`Playwright auth audit failed: retry budget exhausted after ${attempt} attempt(s) over ${totalBudgetMs}ms`
|
|
1377
|
+
);
|
|
1378
|
+
}
|
|
1379
|
+
if (remainingBudgetMs < minAttemptTimeoutMs) {
|
|
1380
|
+
throw new AuthAuditError(
|
|
1381
|
+
`Playwright auth audit failed: remaining retry budget (${remainingBudgetMs}ms) below minimum attempt timeout (${minAttemptTimeoutMs}ms)`
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
const attemptTimeoutMs = Math.max(minAttemptTimeoutMs, Math.min(timeoutMs, remainingBudgetMs));
|
|
1385
|
+
try {
|
|
1386
|
+
return execute(process.execPath, runArgs, {
|
|
1387
|
+
encoding: "utf-8",
|
|
1388
|
+
timeout: attemptTimeoutMs,
|
|
1389
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1390
|
+
env,
|
|
1391
|
+
input: stdinPayload,
|
|
1392
|
+
});
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
if (!isRetryablePlaywrightExecutionError(error) || attempt >= maxRetries) {
|
|
1395
|
+
const reason = normalizeAuthAuditErrorMessage(error, "Playwright execution failed");
|
|
1396
|
+
throw new AuthAuditError(`Playwright auth audit failed after ${attempt + 1} attempt(s): ${reason}`);
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
const backoffMs = computePlaywrightBackoffMs(attempt, baseBackoffMs);
|
|
1400
|
+
const remainingAfterAttemptMs = totalBudgetMs - (now() - retryWindowStartedAt);
|
|
1401
|
+
if (remainingAfterAttemptMs <= 0) {
|
|
1402
|
+
throw new AuthAuditError(
|
|
1403
|
+
`Playwright auth audit failed: retry budget exhausted after ${attempt + 1} attempt(s) over ${totalBudgetMs}ms`
|
|
1404
|
+
);
|
|
1405
|
+
}
|
|
1406
|
+
await sleepFn(Math.min(backoffMs, remainingAfterAttemptMs));
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
throw new AuthAuditError("Playwright auth audit failed after retry budget was exhausted");
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
function computeAuthFlowBackoffMs(attempt) {
|
|
1413
|
+
const computed = AUTH_FLOW_FETCH_BASE_BACKOFF_MS * Math.pow(2, Math.max(0, attempt));
|
|
1414
|
+
return Math.min(1000, computed);
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
function resolveAuthFlowErrorCode(error) {
|
|
1418
|
+
if (!(error instanceof Error)) {
|
|
1419
|
+
return "";
|
|
1420
|
+
}
|
|
1421
|
+
const directCode = String(error.code || "").toUpperCase();
|
|
1422
|
+
if (directCode) {
|
|
1423
|
+
return directCode;
|
|
1424
|
+
}
|
|
1425
|
+
const cause = error.cause;
|
|
1426
|
+
if (!cause || typeof cause !== "object") {
|
|
1427
|
+
return "";
|
|
1428
|
+
}
|
|
1429
|
+
return String(cause.code || cause.errno || "").toUpperCase();
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
function isRetryableAuthFlowError(error) {
|
|
1433
|
+
if (!(error instanceof Error)) {
|
|
1434
|
+
return false;
|
|
1435
|
+
}
|
|
1436
|
+
if (error.name === "AbortError" || error.name === "TimeoutError") {
|
|
1437
|
+
return true;
|
|
1438
|
+
}
|
|
1439
|
+
const code = resolveAuthFlowErrorCode(error);
|
|
1440
|
+
if (RETRYABLE_AUTH_FLOW_ERROR_CODES.has(code)) {
|
|
1441
|
+
return true;
|
|
1442
|
+
}
|
|
1443
|
+
const normalized = `${error.name} ${error.message || ""}`.toLowerCase();
|
|
1444
|
+
if (error.name === "TypeError") {
|
|
1445
|
+
return RETRYABLE_AUTH_FLOW_MESSAGE_PATTERNS.some((pattern) => pattern.test(normalized));
|
|
1446
|
+
}
|
|
1447
|
+
return RETRYABLE_AUTH_FLOW_MESSAGE_PATTERNS.some((pattern) => pattern.test(normalized));
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
function isAllowedHttpAuthFlowTarget(urlObject) {
|
|
1451
|
+
if (urlObject.protocol !== "http:") {
|
|
1452
|
+
return true;
|
|
1453
|
+
}
|
|
1454
|
+
if (process.env.NODE_ENV !== "test") {
|
|
1455
|
+
return false;
|
|
1456
|
+
}
|
|
1457
|
+
return AUTH_FLOW_LOCAL_TEST_HOSTS.has(urlObject.hostname);
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
function isUnapprovedAuthAuditBypassEnabled() {
|
|
1461
|
+
if (process.env.NODE_ENV === "test") {
|
|
1462
|
+
return true;
|
|
1463
|
+
}
|
|
1464
|
+
if (process.env.SENTINELAYER_ALLOW_UNAPPROVED_AUTH_AUDIT_TARGETS === "1") {
|
|
1465
|
+
return true;
|
|
1466
|
+
}
|
|
1467
|
+
return false;
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
function normalizeHostEntry(value) {
|
|
1471
|
+
return String(value || "").trim().toLowerCase();
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
function resolveApprovedAuthAuditHosts(input) {
|
|
1475
|
+
const approvedHosts = new Set(DEFAULT_APPROVED_AUTH_AUDIT_HOSTS);
|
|
1476
|
+
const hostLists = [];
|
|
1477
|
+
if (Array.isArray(input?.approvedHosts)) {
|
|
1478
|
+
hostLists.push(input.approvedHosts);
|
|
1479
|
+
}
|
|
1480
|
+
if (Array.isArray(input?.approvedHostnames)) {
|
|
1481
|
+
hostLists.push(input.approvedHostnames);
|
|
1482
|
+
}
|
|
1483
|
+
const envHosts = String(process.env[AUTH_AUDIT_ALLOWED_HOSTS_ENV] || "")
|
|
1484
|
+
.split(",")
|
|
1485
|
+
.map((entry) => normalizeHostEntry(entry))
|
|
1486
|
+
.filter(Boolean);
|
|
1487
|
+
hostLists.push(envHosts);
|
|
1488
|
+
for (const list of hostLists) {
|
|
1489
|
+
for (const host of list) {
|
|
1490
|
+
const normalized = normalizeHostEntry(host);
|
|
1491
|
+
if (normalized) {
|
|
1492
|
+
approvedHosts.add(normalized);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
return approvedHosts;
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
function assertApprovedAuthAuditTarget(parsed, input, operation) {
|
|
1500
|
+
if (isUnapprovedAuthAuditBypassEnabled()) {
|
|
1501
|
+
return parsed;
|
|
1502
|
+
}
|
|
1503
|
+
const allowLiveProvision = input?.allowProvisioning === true || process.env.SENTINELAYER_ALLOW_LIVE_IDENTITY_PROVISION === "1";
|
|
1504
|
+
const approvedTargetId = String(input?.approvedTargetId || "").trim();
|
|
1505
|
+
if (!allowLiveProvision || !approvedTargetId) {
|
|
1506
|
+
throw new AuthAuditError(
|
|
1507
|
+
`Live ${operation} requires allowProvisioning=true and approvedTargetId to prevent unapproved outbound probing.`
|
|
1508
|
+
);
|
|
1509
|
+
}
|
|
1510
|
+
const approvedHosts = resolveApprovedAuthAuditHosts(input);
|
|
1511
|
+
const normalizedHost = normalizeHostEntry(parsed.hostname);
|
|
1512
|
+
if (!approvedHosts.has(normalizedHost)) {
|
|
1513
|
+
throw new AuthAuditError(
|
|
1514
|
+
`Blocked unapproved auth audit host for ${operation}: ${normalizedHost}. ` +
|
|
1515
|
+
`Add host to approvedHosts or ${AUTH_AUDIT_ALLOWED_HOSTS_ENV}.`
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
return parsed;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
function assertSecureAuthFlowTarget(urlValue, options = {}) {
|
|
1522
|
+
let parsed;
|
|
1523
|
+
try {
|
|
1524
|
+
parsed = assertPermittedAuditTarget(urlValue, {
|
|
1525
|
+
operation: "check_auth_flow_security",
|
|
1526
|
+
allowPrivateTargets: options.allowPrivateTargets === true,
|
|
1527
|
+
});
|
|
1528
|
+
} catch (error) {
|
|
1529
|
+
throw new AuthAuditError(error.message);
|
|
1530
|
+
}
|
|
1531
|
+
assertApprovedAuthAuditTarget(parsed, options.auditInput || {}, "check_auth_flow_security");
|
|
1532
|
+
if (!isAllowedHttpAuthFlowTarget(parsed)) {
|
|
1533
|
+
throw new AuthAuditError(
|
|
1534
|
+
`HTTPS downgrade detected in auth flow target: ${parsed.toString()}`
|
|
1535
|
+
);
|
|
1536
|
+
}
|
|
1537
|
+
return parsed;
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
async function fetchWithTimeout(url, options, timeoutMs) {
|
|
1541
|
+
const callerSignal = isAbortSignalLike(options?.signal) ? options.signal : undefined;
|
|
1542
|
+
const controller = new AbortController();
|
|
1543
|
+
const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
|
|
1544
|
+
const { signal: compositeSignal, cleanup: cleanupCompositeSignal } = composeAbortSignals(callerSignal, controller.signal);
|
|
1545
|
+
try {
|
|
1546
|
+
return await fetch(url, {
|
|
1547
|
+
...options,
|
|
1548
|
+
...(compositeSignal ? { signal: compositeSignal } : {}),
|
|
1549
|
+
});
|
|
1550
|
+
} finally {
|
|
1551
|
+
clearTimeout(timeoutHandle);
|
|
1552
|
+
cleanupCompositeSignal();
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
async function fetchLoginResponseWithRetry(currentUrl) {
|
|
1557
|
+
for (let attempt = 0; attempt <= AUTH_FLOW_FETCH_MAX_RETRIES; attempt += 1) {
|
|
1558
|
+
try {
|
|
1559
|
+
const response = await fetchWithTimeout(currentUrl, {
|
|
1560
|
+
method: "GET",
|
|
1561
|
+
redirect: "manual",
|
|
1562
|
+
}, AUTH_FLOW_FETCH_TIMEOUT_MS);
|
|
1563
|
+
if (!RETRYABLE_AUTH_FLOW_STATUS_CODES.has(response.status)) {
|
|
1564
|
+
return response;
|
|
1565
|
+
}
|
|
1566
|
+
if (attempt >= AUTH_FLOW_FETCH_MAX_RETRIES) {
|
|
1567
|
+
throw new AuthAuditError(
|
|
1568
|
+
`Auth flow header fetch failed after ${attempt + 1} attempt(s): HTTP ${response.status}`
|
|
1569
|
+
);
|
|
1570
|
+
}
|
|
1571
|
+
} catch (error) {
|
|
1572
|
+
if (error instanceof AuthAuditError) {
|
|
1573
|
+
throw error;
|
|
1574
|
+
}
|
|
1575
|
+
if (!isRetryableAuthFlowError(error) || attempt >= AUTH_FLOW_FETCH_MAX_RETRIES) {
|
|
1576
|
+
const message = error instanceof Error ? error.message : String(error || "request failed");
|
|
1577
|
+
throw new AuthAuditError(`Auth flow header fetch failed after ${attempt + 1} attempt(s): ${message}`);
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
await sleep(computeAuthFlowBackoffMs(attempt));
|
|
1581
|
+
}
|
|
1582
|
+
throw new AuthAuditError("Auth flow header fetch failed after retry budget was exhausted");
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
async function checkAuthFlowSecurity(input) {
|
|
1586
|
+
const requestId = String(input.requestId || createAuditRequestId());
|
|
1587
|
+
const loginUrlCandidate = input.loginUrl || input.url;
|
|
1588
|
+
if (!loginUrlCandidate) throw new AuthAuditError("check_auth_flow_security requires loginUrl or url");
|
|
1589
|
+
const allowPrivateTargets = input.allowPrivateTargets === true;
|
|
1590
|
+
const loginUrl = assertSecureAuthFlowTarget(loginUrlCandidate, { allowPrivateTargets, auditInput: input }).toString();
|
|
1591
|
+
|
|
1592
|
+
const findings = [];
|
|
1593
|
+
try {
|
|
1594
|
+
const { headers, finalUrl, crossOriginRedirect } = await fetchLoginHeaders(loginUrl, { allowPrivateTargets, auditInput: input });
|
|
1595
|
+
|
|
1596
|
+
if (crossOriginRedirect) {
|
|
1597
|
+
findings.push({
|
|
1598
|
+
severity: "P1",
|
|
1599
|
+
title: "Login flow redirects cross-origin before header checks",
|
|
1600
|
+
file: loginUrl,
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
if (!headers["strict-transport-security"]) {
|
|
1605
|
+
findings.push({ severity: "P1", title: "Login page missing HSTS header", file: finalUrl || loginUrl });
|
|
1606
|
+
}
|
|
1607
|
+
if (!headers["content-security-policy"]) {
|
|
1608
|
+
findings.push({ severity: "P2", title: "Login page missing CSP header", file: finalUrl || loginUrl });
|
|
1609
|
+
}
|
|
1610
|
+
if (headers["x-powered-by"]) {
|
|
1611
|
+
findings.push({
|
|
1612
|
+
severity: "P2",
|
|
1613
|
+
title: "Login page exposes X-Powered-By: " + headers["x-powered-by"],
|
|
1614
|
+
file: finalUrl || loginUrl,
|
|
1615
|
+
});
|
|
1616
|
+
}
|
|
1617
|
+
} catch (err) {
|
|
1618
|
+
if (err instanceof AuthAuditError && /HTTPS downgrade detected/.test(err.message)) {
|
|
1619
|
+
findings.push({
|
|
1620
|
+
severity: "P1",
|
|
1621
|
+
title: err.message,
|
|
1622
|
+
file: loginUrl,
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
return {
|
|
1626
|
+
...buildUnavailableAuditResponse(
|
|
1627
|
+
requestId,
|
|
1628
|
+
"AUTH_FLOW_CHECK_FAILED",
|
|
1629
|
+
"auth flow check failed: " + normalizeErrorMessage(err, "unknown error")
|
|
1630
|
+
),
|
|
1631
|
+
loginUrl,
|
|
1632
|
+
findings,
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
return { available: true, requestId, loginUrl, findings };
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
async function fetchLoginHeaders(loginUrl, options = {}) {
|
|
1639
|
+
let currentUrl = loginUrl;
|
|
1640
|
+
const visitedUrls = new Set();
|
|
1641
|
+
let redirectCount = 0;
|
|
1642
|
+
|
|
1643
|
+
while (true) {
|
|
1644
|
+
if (redirectCount > MAX_AUTH_REDIRECT_HOPS) {
|
|
1645
|
+
throw new AuthAuditError(
|
|
1646
|
+
`Exceeded ${MAX_AUTH_REDIRECT_HOPS} redirects while checking auth flow (last=${currentUrl})`
|
|
1647
|
+
);
|
|
1648
|
+
}
|
|
1649
|
+
const currentParsedUrl = assertSecureAuthFlowTarget(currentUrl, options);
|
|
1650
|
+
if (visitedUrls.has(currentUrl)) {
|
|
1651
|
+
throw new AuthAuditError("Redirect loop detected while checking auth headers");
|
|
1652
|
+
}
|
|
1653
|
+
visitedUrls.add(currentUrl);
|
|
1654
|
+
|
|
1655
|
+
const response = await fetchLoginResponseWithRetry(currentUrl);
|
|
1656
|
+
const headers = Object.fromEntries(response.headers.entries());
|
|
1657
|
+
|
|
1658
|
+
if (response.status >= 300 && response.status < 400) {
|
|
1659
|
+
const location = response.headers.get("location");
|
|
1660
|
+
if (!location) {
|
|
1661
|
+
return { headers, finalUrl: currentUrl, crossOriginRedirect: false };
|
|
1662
|
+
}
|
|
1663
|
+
const nextParsedUrl = assertSecureAuthFlowTarget(new URL(location, currentParsedUrl).toString(), options);
|
|
1664
|
+
if (nextParsedUrl.origin !== currentParsedUrl.origin) {
|
|
1665
|
+
return { headers, finalUrl: currentUrl, crossOriginRedirect: true };
|
|
1666
|
+
}
|
|
1667
|
+
currentUrl = nextParsedUrl.toString();
|
|
1668
|
+
redirectCount += 1;
|
|
1669
|
+
continue;
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
return { headers, finalUrl: currentUrl, crossOriginRedirect: false };
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
function resolveAuthAuditTarget(urlValue, input, operation) {
|
|
1677
|
+
try {
|
|
1678
|
+
const parsed = assertPermittedAuditTarget(urlValue, {
|
|
1679
|
+
operation,
|
|
1680
|
+
allowPrivateTargets: input.allowPrivateTargets === true,
|
|
1681
|
+
});
|
|
1682
|
+
assertApprovedAuthAuditTarget(parsed, input, operation);
|
|
1683
|
+
return parsed.toString();
|
|
1684
|
+
} catch (error) {
|
|
1685
|
+
throw new AuthAuditError(error.message);
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
export class AuthAuditError extends Error {
|
|
1690
|
+
constructor(message) { super(message); this.name = "AuthAuditError"; }
|
|
1691
|
+
}
|