-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathauth.ts
More file actions
1895 lines (1791 loc) · 77.7 KB
/
Copy pathauth.ts
File metadata and controls
1895 lines (1791 loc) · 77.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Unified authentication for DKG node interfaces (HTTP API, MCP, WebSocket, etc.).
*
* Uses bearer tokens stored on disk. Tokens are auto-generated on first start.
* Any interface that needs auth calls `verifyToken(token)` against the loaded set.
*/
import { randomBytes, createHmac, timingSafeEqual, createHash } from 'node:crypto';
import { readFile, writeFile, mkdir, chmod } from 'node:fs/promises';
import { readFileSync, statSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { existsSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { dkgDir } from './config.js';
export type RequestAuthPrincipal = {
kind: 'agent' | 'node-admin';
agentAddress: string;
};
export interface HttpAuthGuardOptions {
resolvePrincipal?: (token: string) => RequestAuthPrincipal;
authSources?: RequestAuthSource[];
}
interface RequestAuthBaseContext {
principal: RequestAuthPrincipal;
csrf: {
required: boolean;
validated: boolean;
};
}
export type RequestAuthContext =
| (RequestAuthBaseContext & {
source: 'authorization-header';
token: string;
})
| (RequestAuthBaseContext & {
source: 'events-query';
token: string;
})
| (RequestAuthBaseContext & {
source: 'dashboard-session';
internalCredentialToken: string;
dashboardSession: {
sessionId?: string;
source?: 'loopback' | 'exchange';
expiresAt?: number;
};
});
const REQUEST_AUTH_CONTEXT = Symbol('dkg.requestAuthContext');
export function setRequestAuthContext(req: IncomingMessage, context: RequestAuthContext): void {
(req as IncomingMessage & { [REQUEST_AUTH_CONTEXT]?: RequestAuthContext })[REQUEST_AUTH_CONTEXT] = context;
}
export function getRequestAuthContext(req: IncomingMessage): RequestAuthContext | undefined {
return (req as IncomingMessage & { [REQUEST_AUTH_CONTEXT]?: RequestAuthContext })[REQUEST_AUTH_CONTEXT];
}
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface AuthConfig {
/** Master switch — when false, all requests are allowed (default: true). */
enabled?: boolean;
/** Pre-configured tokens. If empty, one is auto-generated on first start. */
tokens?: string[];
}
// ---------------------------------------------------------------------------
// Token file management
// ---------------------------------------------------------------------------
function tokenFilePath(): string {
return join(dkgDir(), 'auth.token');
}
function generateToken(): string {
return randomBytes(32).toString('base64url');
}
/**
* Load tokens from disk + config. Auto-generates a token file if none exists.
* Returns the set of valid tokens.
*/
export async function loadTokens(authConfig?: AuthConfig): Promise<Set<string>> {
const tokens = new Set<string>();
const fileTokens = new Set<string>();
// auth.ts:203). Track config-pinned
// tokens separately from file-derived ones so reconciliation /
// rotation can preserve them when a token happens to live in BOTH
// sources (a real-world rollout shape — operators sync the same
// admin token across config and `auth.token`).
const configTokens = new Set<string>();
if (authConfig?.tokens) {
for (const t of authConfig.tokens) {
if (t.length > 0) {
tokens.add(t);
configTokens.add(t);
}
}
}
// Load or generate the file-based token
const filePath = tokenFilePath();
if (existsSync(filePath)) {
try {
const raw = await readFile(filePath, 'utf-8');
for (const line of raw.split('\n')) {
const t = line.trim();
if (t.length > 0 && !t.startsWith('#')) {
tokens.add(t);
fileTokens.add(t);
}
}
} catch {
// Unreadable — generate a fresh one
}
}
if (tokens.size === 0) {
const token = generateToken();
tokens.add(token);
fileTokens.add(token);
await mkdir(dirname(filePath), { recursive: true });
await writeFile(filePath, `# DKG node API token — treat this like a password\n${token}\n`, { mode: 0o600 });
await chmod(filePath, 0o600);
}
// CLI-11: record the file snapshot so `verifyToken`'s mtime-gated
// reconciliation knows which tokens originated on disk and can
// subtract them when the file is rewritten. Without this snapshot
// the reconciler would only ever ADD newly-discovered tokens and
// leave stale file tokens alive forever (the very rotation bug
// CLI-11 documents).
try {
const st = statSync(filePath);
const raw = readFileSync(filePath);
const contentHash = createHash('sha256').update(raw).digest('hex');
lastFileSnapshot.set(tokens, {
mtimeMs: st.mtimeMs,
size: st.size,
contentHash,
fileTokens,
configTokens,
});
} catch {
/* file vanished mid-load — next verifyToken call will reconcile */
}
return tokens;
}
// ---------------------------------------------------------------------------
// Verification (interface-agnostic)
// ---------------------------------------------------------------------------
/**
* CLI-11 (.
*
* The original `verifyToken` was a pure `Set.has` lookup. That meant
* once the daemon had loaded `auth.token` at boot, *no* file rewrite
* could ever revoke an issued token until the operator restarted the
* process. `dkg auth rotate` (which simply rewrites the file) was a
* quiet no-op against the running token set — the audit flagged this
* as the spec §18 rotation gap.
*
* We now reconcile the in-memory `validTokens` set with the on-disk
* `auth.token` file every time `verifyToken` runs, but only when the
* file's size, mtime, OR content hash has changed since the last
* reconciliation. The cost is one `statSync` per call plus a cheap
* short-circuit on size+mtime; the sha256 is only recomputed when
* those differ, which is in the same order of magnitude as the
* existing `Set.has` and well below the cost of every other path
* the daemon executes per request.
*
* Why not `mtimeMs` alone: on coarse filesystems (or when
* `dkg auth rotate` runs twice in the same millisecond — rare but
* observable in CI on fast disks) two consecutive rewrites can share
* the same mtime, and a `stat`-only guard would silently skip the
* second reconciliation and leave the previous token valid. Atomic
* `rename(tmp, auth.token)` also preserves the destination mtime on
* some platforms. Hashing the bytes closes the hole unconditionally
* .
*
* Tokens added programmatically (e.g. via the future `rotateToken`
* API or pinned in `config.auth.tokens`) are preserved across
* reconciliation: the algorithm compares the *file-derived* subset
* with what's now on disk, removes the stale file tokens, and adds
* the new ones — without touching tokens that never came from disk.
*/
// auth.ts:203). The snapshot now also
// remembers `configTokens` — the tokens supplied via
// `loadTokens({ tokens: [...] })` (config-pinned). Without this,
// reconcileFileTokens could not tell whether a "file token" was ALSO
// pinned by config, and a normal rotate path would `validTokens.delete(t)`
// on a value that the config still wanted, silently revoking a
// configured admin token until restart whenever the same secret
// happened to be both file-backed AND config-backed (a documented and
// supported overlap — operators frequently pre-seed `auth.token` with
// the same value they write into config so both `dkg auth` flows stay
// consistent during a config rollout).
const lastFileSnapshot = new WeakMap<
Set<string>,
{
mtimeMs: number;
size: number;
contentHash: string;
fileTokens: Set<string>;
configTokens: Set<string>;
}
>();
function reconcileFileTokens(validTokens: Set<string>): void {
const filePath = tokenFilePath();
let rawBuf: Buffer;
let mtimeMs = -1;
let size = -1;
try {
rawBuf = readFileSync(filePath);
const st = statSync(filePath);
mtimeMs = st.mtimeMs;
size = st.size;
} catch (err: any) {
// ENOENT path). If the
// token file is missing AND we had previously loaded tokens from
// it, those tokens MUST be revoked from `validTokens`: `dkg auth
// revoke` rewrites the file to empty or deletes it, and operators
// expect the in-memory set to follow suit. The previous revision
// `return`ed silently on ENOENT, leaving the last file-derived
// token valid forever.
if (err && err.code === 'ENOENT') {
const snapshot = lastFileSnapshot.get(validTokens);
if (snapshot) {
// auth.ts:203). When the token
// file vanishes, every token that was BACKED ONLY by the
// file is now stale; tokens that are ALSO config-pinned
// remain valid because the config never went away. Pre-r31-14
// this branch deleted the entire `fileTokens` set, which on
// the overlap shape ("same admin token in both auth.token
// and config.auth.tokens") silently revoked a configured
// admin credential until process restart.
for (const oldTok of snapshot.fileTokens) {
if (snapshot.configTokens.has(oldTok)) continue;
validTokens.delete(oldTok);
}
lastFileSnapshot.delete(validTokens);
}
}
return;
}
// fast-path gap). The
// previous revision short-circuited on matching `{mtimeMs, size}`
// before hashing. That's unsafe on coarse-mtime filesystems (HFS+
// 1s resolution, certain network mounts, CI tmpfs): a rotate that
// rewrites `auth.token` with a new token of the same length within
// the same second leaves `mtimeMs` and `size` unchanged and the
// old token stays hot. Always hash the bytes — the file is tiny
// (one or two lines) and hashing is O(µs).
const contentHash = createHash('sha256').update(rawBuf).digest('hex');
const snapshot = lastFileSnapshot.get(validTokens);
if (snapshot && snapshot.contentHash === contentHash) {
// Bytes unchanged — keep fileTokens, just refresh stat metadata so
// future reads don't trip debug warnings about skew.
if (snapshot.mtimeMs !== mtimeMs || snapshot.size !== size) {
lastFileSnapshot.set(validTokens, {
mtimeMs,
size,
contentHash,
fileTokens: snapshot.fileTokens,
configTokens: snapshot.configTokens,
});
}
return;
}
const newFileTokens = new Set<string>();
for (const line of rawBuf.toString('utf-8').split('\n')) {
const t = line.trim();
if (t.length > 0 && !t.startsWith('#')) newFileTokens.add(t);
}
if (snapshot) {
// auth.ts:203). Preserve config-pinned
// tokens during file rotation. the loop only checked
// `!newFileTokens.has(oldTok)` and deleted from `validTokens`
// unconditionally — but `loadTokens()` merges config-pinned and
// file-derived tokens into the SAME `Set` (and into `fileTokens`
// when the value happens to appear on disk too). A normal rotate
// that drops the value from `auth.token` would then revoke the
// configured admin token in-memory until restart. Track config
// provenance separately and skip deletion when the token is still
// pinned by config.
for (const oldTok of snapshot.fileTokens) {
if (newFileTokens.has(oldTok)) continue;
if (snapshot.configTokens.has(oldTok)) continue;
validTokens.delete(oldTok);
}
}
for (const t of newFileTokens) validTokens.add(t);
lastFileSnapshot.set(validTokens, {
mtimeMs,
size,
contentHash,
fileTokens: newFileTokens,
// configTokens are immutable for the lifetime of `validTokens` —
// they're sourced from the AuthConfig handed to loadTokens(). If
// no snapshot exists yet (loadTokens crashed mid-stat), fall back
// to an empty set — that just means we have nothing to preserve.
configTokens: snapshot?.configTokens ?? new Set<string>(),
});
}
/**
* Verify a bearer token against the loaded token set.
* This is the single entry point any interface (HTTP, MCP, WS) should use.
*
* Performs an mtime-gated hot-reload of the on-disk `auth.token` file
* on every call — see `reconcileFileTokens` above for the rationale.
*/
export function reconcileValidTokens(validTokens: Set<string>): void {
reconcileFileTokens(validTokens);
}
export function verifyToken(token: string | undefined, validTokens: Set<string>): boolean {
if (!token) return false;
reconcileValidTokens(validTokens);
return validTokens.has(token);
}
// ---------------------------------------------------------------------------
// CLI-11 — programmatic rotation / revocation API
// ---------------------------------------------------------------------------
/**
* Generate a fresh token, rewrite `auth.token` so it contains *only* the
* new value, and update the supplied in-memory `validTokens` set so the
* old file-derived token is invalidated immediately. Config-pinned
* tokens (passed via `loadTokens({ tokens: [...] })`) are preserved.
*
* Returns the new token (never logged — caller decides what to do).
*/
export async function rotateToken(validTokens: Set<string>): Promise<string> {
const filePath = tokenFilePath();
await mkdir(dirname(filePath), { recursive: true });
const fresh = generateToken();
// Capture the pre-rotation file-derived tokens BEFORE we drop the
// snapshot — the rotation contract is that every token that came
// from `auth.token` must be invalidated in-memory once the file has
// been rewritten. If we relied on `reconcileFileTokens` alone, a
// reset snapshot would short-circuit the remove-old-tokens step
// (see reconcileFileTokens: the removal loop is gated on the old
// snapshot existing). Config-pinned tokens — those added via
// `loadTokens({ tokens: [...] })` — are not part of `fileTokens`
// and therefore survive rotation unchanged.
const previous = lastFileSnapshot.get(validTokens);
await writeFile(
filePath,
`# DKG node API token — treat this like a password\n${fresh}\n`,
{ mode: 0o600 },
);
await chmod(filePath, 0o600);
if (previous) {
// auth.ts:203). Same overlap-aware
// delete: tokens that are ALSO config-pinned MUST NOT be removed
// from the in-memory set just because they no longer appear in
// the rotated file. Operators rely on config-pinned admin tokens
// staying valid across `dkg auth rotate`.
for (const oldTok of previous.fileTokens) {
if (previous.configTokens.has(oldTok)) continue;
validTokens.delete(oldTok);
}
}
// Force the next reconcile to actually re-read the file even if the
// OS reused the previous mtime (e.g. on filesystems with low
// resolution like ext3 / FAT32 / certain CI tmpfs).
lastFileSnapshot.delete(validTokens);
reconcileFileTokens(validTokens);
// auth.ts:203). The reconcile above ran
// with no snapshot, so the new snapshot it just wrote has an EMPTY
// configTokens set (reconcile uses `snapshot?.configTokens ??
// new Set()`). Re-seed the configTokens from the pre-rotation
// snapshot so subsequent rotates / reconciles still know which
// tokens are config-pinned.
if (previous && previous.configTokens.size > 0) {
const post = lastFileSnapshot.get(validTokens);
if (post) {
lastFileSnapshot.set(validTokens, {
mtimeMs: post.mtimeMs,
size: post.size,
contentHash: post.contentHash,
fileTokens: post.fileTokens,
configTokens: new Set(previous.configTokens),
});
}
}
return fresh;
}
/**
* Revoke a single token. Returns `true` if the token was previously
* known to this auth surface (in-memory or file-backed) and has now
* been invalidated; returns `false` if the token was not present at
* all.
*
* the previous revision was a
* synchronous `validTokens.delete(token)` only — but `verifyToken()`
* calls `reconcileFileTokens()` on every invocation, and that
* reconciliation re-adds any token that still appears on disk in
* `auth.token`. So calling `revokeToken()` against a file-derived
* credential was a no-op the very next request: the in-memory set
* was reset from the still-unchanged file. The contract advertised
* by the JSDoc ("surgically kill a leaked credential") was therefore
* broken for the most common case (the file-backed admin token).
*
* Fix: persist the removal. If the token was loaded from
* `auth.token`, rewrite the file to exclude it (and its snapshot
* entry) BEFORE deleting from the in-memory set, so the next
* reconcile sees a file that no longer contains the revoked token
* and leaves it out. Tokens that were never file-backed (e.g.
* config-pinned via `loadTokens({ tokens: [...] })`) take the
* original purely-in-memory path — those are not at risk of being
* re-added by reconciliation because they are not in the snapshot's
* `fileTokens`.
*/
export async function revokeToken(
token: string,
validTokens: Set<string>,
): Promise<boolean> {
// Snapshot the file-backed tokens BEFORE we mutate the in-memory
// set so we can decide whether the rewrite is needed. The snapshot
// is the source of truth for what reconcileFileTokens will treat
// as "file-derived" on the next call.
const snapshot = lastFileSnapshot.get(validTokens);
const wasFileToken = snapshot?.fileTokens.has(token) ?? false;
if (wasFileToken) {
const filePath = tokenFilePath();
let raw: string;
try {
raw = readFileSync(filePath).toString('utf-8');
} catch (err: any) {
// File vanished between the snapshot and now. Pre-fix, this
// branch deleted ONLY the requested `token` from `validTokens`
// and then dropped the snapshot. But the snapshot is exactly
// what `reconcileFileTokens()` consults to subtract
// file-derived tokens on the ENOENT path — once it's gone,
// every OTHER token that was originally loaded from the
// now-missing file (`auth.token` containing `[A, B]`,
// `revokeToken(A)` after
// file deletion → only A removed; B stays valid forever).
//
// Fix: if the token file is gone, EVERY token it used to back
// is now stale — eagerly revoke ALL of `snapshot.fileTokens`
// and drop the snapshot so subsequent `verifyToken()` calls do
// not re-add anything. This matches the contract of
// `reconcileFileTokens()` ENOENT (which would have removed
// them on the next call had the snapshot still been there).
if (err && err.code === 'ENOENT') {
let removedAny = false;
if (snapshot) {
// auth.ts:203). Bulk-revoke
// file-derived tokens, but preserve overlap with config —
// a token that happened to live in BOTH `auth.token` and
// `config.auth.tokens` should remain valid because the
// config never went away. The explicitly-revoked `token`
// is still removed below regardless of provenance (the
// operator asked for that one specifically).
for (const fileTok of snapshot.fileTokens) {
if (snapshot.configTokens.has(fileTok)) continue;
if (validTokens.delete(fileTok)) removedAny = true;
}
}
// Belt-and-suspenders: also delete the explicitly-revoked
// token in case the caller passed something not present in
// the snapshot (e.g. a config-pinned token that happened to
// collide with the file's prior contents). The operator
// explicitly named THIS token — honour the request even if
// it's config-pinned.
if (validTokens.delete(token)) removedAny = true;
lastFileSnapshot.delete(validTokens);
return removedAny;
}
throw err;
}
// Preserve comments and any other tokens; only strip lines that
// exactly match the revoked token. Empty lines and `#`-prefixed
// comment lines are kept so operators don't lose their notes.
const lines = raw.split('\n');
const kept: string[] = [];
let removedAny = false;
for (const line of lines) {
const t = line.trim();
if (t.length > 0 && !t.startsWith('#') && t === token) {
removedAny = true;
continue;
}
kept.push(line);
}
if (removedAny) {
// Atomic-ish rewrite: same path, mode preserved at 0o600 so
// the file stays operator-only readable. We deliberately do
// NOT re-add a `# ...` header here because we are PRESERVING
// whatever header (if any) was already on disk — the rewrite
// is purely a delete-by-content.
let next = kept.join('\n');
// Guarantee a trailing newline so future appends don't end up
// on the same line as the last surviving token.
if (!next.endsWith('\n')) next = `${next}\n`;
await writeFile(filePath, next, { mode: 0o600 });
try {
await chmod(filePath, 0o600);
} catch {
// chmod is best-effort on platforms (e.g. Windows) that
// don't enforce POSIX modes. The writeFile mode hint above
// is already authoritative on those that do.
}
// Drop the cached snapshot so the next reconcile re-reads the
// (now strictly smaller) file and rebuilds `fileTokens` —
// otherwise the snapshot's old `fileTokens` would still claim
// the revoked token was file-backed and skip the removal.
lastFileSnapshot.delete(validTokens);
}
}
return validTokens.delete(token);
}
// ---------------------------------------------------------------------------
// CLI-10 — signed-request verifier (spec §18)
// ---------------------------------------------------------------------------
/**
* Default ±5 min freshness window for signed requests, matching the
* AWS Sig V4 / OAuth 1.0 conventions documented in spec §18.
*/
export const SIGNED_REQUEST_FRESHNESS_WINDOW_MS = 5 * 60 * 1000;
/**
* In-memory nonce store: `nonce → expiryEpochMs`. Cleared on process
* exit (restart-tolerant by design — a long-paused replay has its
* timestamp blocked by the freshness window check anyway). The store
* is bounded: any nonce older than the freshness window is pruned on
* the next access.
*/
const seenNonces = new Map<string, number>();
function pruneNonces(now: number): void {
if (seenNonces.size === 0) return;
for (const [nonce, expiry] of seenNonces) {
if (expiry <= now) seenNonces.delete(nonce);
}
}
export interface SignedRequestInput {
method: string;
path: string;
/** Raw request body (Buffer or string). Used to compute the signature payload. */
body: Buffer | string;
/** Timestamp string supplied by the client (typically ISO-8601). */
timestamp: string;
/** Nonce supplied by the client; rejected on second sighting. */
nonce?: string;
/** Hex signature supplied by the client. */
signature: string;
/** Bearer token used as the HMAC secret. */
token: string;
/** Optional override of the freshness window (for tests / spec changes). */
freshnessWindowMs?: number;
/** Optional clock override (for tests). */
now?: number;
}
export type SignedRequestOutcome =
| { ok: true }
| {
ok: false;
reason:
| 'missing-fields'
| 'stale-timestamp'
| 'replayed-nonce'
| 'bad-signature';
};
/**
* Canonical string fed into the HMAC for {@link verifySignedRequest}.
*
* ```
* METHOD\n
* normalised-path\n
* timestamp\n
* nonce\n
* sha256(body-hex)
* ```
*
* Binds method, path, timestamp, nonce, and a hash of the body — so a
* captured signature cannot be replayed:
* - against a different endpoint (path/method bound),
* - with a fresh nonce swapped in (nonce bound),
* - against the same endpoint with a tampered body (body hash bound).
*
* Callers that still compute HMAC over the legacy `timestamp + body`
* payload will fail verification — this is intentional.
*/
/**
* Strict lowercase-or-mixed-case hex validation.
*
* `Buffer.from(hex, 'hex')`
* silently truncates at the first non-hex character, so a header like
* `<valid-hmac>zz` decodes to the original valid bytes and then passes
* `timingSafeEqual`. Validate the string is purely hex and of the
* exact expected length BEFORE handing it to `Buffer.from`.
*
* @param s the string to validate
* @param expectedCharLen the required length in hex characters
* (typically 2 × HMAC-SHA256 byte length = 64)
*/
function isStrictHexOfLength(s: unknown, expectedCharLen: number): boolean {
if (typeof s !== 'string') return false;
if (s.length !== expectedCharLen) return false;
// Must be even-length (handled above via expected length) AND all
// characters hex. We allow both lowercase and uppercase so a client
// that emits `A-F` is accepted, but no whitespace, no 0x prefix, no
// punctuation. `/^[0-9a-f]+$/i` also rejects empty strings.
return /^[0-9a-f]+$/i.test(s);
}
/**
* Derive the canonical request path bound into the signed-request HMAC.
*
* binding only `pathname`
* left query parameters unsigned — an attacker could swap
* `/api/query?graph=...` for `/api/query?graph=...&poison=...` without
* invalidating the signature. Several protected daemon routes read
* `url.searchParams`, so this was a real tamper surface.
*
* Now binds `pathname + search` (including the leading `?` when present).
* Clients computing the HMAC MUST use this exact representation. The
* helper is exported so callers can share it instead of re-implementing
* the canonicalisation and drifting.
*/
export function canonicalRequestPath(req: IncomingMessage): string {
const u = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
return `${u.pathname}${u.search}`;
}
export function canonicalSignedRequestPayload(
method: string,
path: string,
timestamp: string,
nonce: string | undefined,
body: Buffer | string,
): string {
const bodyBuf = Buffer.isBuffer(body) ? body : Buffer.from(body ?? '', 'utf-8');
const bodyHashHex = createHash('sha256').update(bodyBuf).digest('hex');
return [
(method ?? '').toUpperCase(),
path ?? '',
timestamp ?? '',
nonce ?? '',
bodyHashHex,
].join('\n');
}
/**
* Verify a signed request per spec §18.
*
* Required headers (mapped into `SignedRequestInput`):
* - `x-dkg-timestamp` ISO-8601 or numeric epoch-ms
* - `x-dkg-signature` hex-encoded HMAC-SHA256(token,
* canonicalSignedRequestPayload(method, path, ts,
* nonce, body))
* - `x-dkg-nonce` REQUIRED — opaque, single-use; rejects replay.
*
* The HMAC covers METHOD + PATH + TIMESTAMP + NONCE + SHA256(BODY) so:
* - a captured signature cannot be replayed against another
* endpoint/verb (method + path are bound);
* - swapping the nonce to bypass the replay cache does not yield a
* valid signature (nonce is bound);
* - tampering the body breaks the hash and invalidates the signature.
*
* Nonce is REQUIRED: a signature without a nonce is rejected as
* `missing-fields`. Callers upgrading from the prior
* "timestamp + body only" scheme must regenerate signatures.
*
* Returns a discriminated result describing why a request was refused —
* callers can map each `reason` to the appropriate HTTP status (401
* for everything except `missing-fields`, which is 400).
*/
export function verifySignedRequest(input: SignedRequestInput): SignedRequestOutcome {
if (!input.timestamp || !input.signature || !input.token || !input.nonce) {
return { ok: false, reason: 'missing-fields' };
}
const windowMs = input.freshnessWindowMs ?? SIGNED_REQUEST_FRESHNESS_WINDOW_MS;
const now = input.now ?? Date.now();
const tsMs = Date.parse(input.timestamp);
const tsEpoch = Number.isNaN(tsMs) ? Number(input.timestamp) : tsMs;
if (!Number.isFinite(tsEpoch)) {
return { ok: false, reason: 'stale-timestamp' };
}
if (Math.abs(now - tsEpoch) > windowMs) {
return { ok: false, reason: 'stale-timestamp' };
}
pruneNonces(now);
// the replay cache used to
// be keyed by the raw nonce string, so two different bearer tokens
// that happened to pick the same nonce would reject each other for
// the full freshness window. That's a trivial cross-client DoS (any
// caller that emits `nonce=aaa...` blocks every other caller that
// picks the same value) and also a false-positive: a replay is only
// a problem when it's the SAME credential reusing the SAME nonce.
// Scope the key by `sha256(token)+":"+nonce` so each credential has
// its own nonce namespace; collisions across credentials no longer
// cross-block.
const nonceScope = createHash('sha256').update(input.token).digest('hex');
const nonceKey = `${nonceScope}:${input.nonce}`;
if (seenNonces.has(nonceKey)) {
return { ok: false, reason: 'replayed-nonce' };
}
const payload = canonicalSignedRequestPayload(
input.method,
input.path,
input.timestamp,
input.nonce,
input.body,
);
const expected = createHmac('sha256', input.token).update(payload).digest('hex');
// `Buffer.from(hex, 'hex')` does NOT
// reject malformed hex — Node silently truncates at the first non-hex
// character. `<valid-hmac>zz` decodes to the original valid bytes,
// which then passes length + timingSafeEqual. Validate the supplied
// signature is a pure, even-length hex string of the expected length
// BEFORE decoding. Reject everything else with `bad-signature`.
if (!isStrictHexOfLength(input.signature, expected.length)) {
return { ok: false, reason: 'bad-signature' };
}
// Constant-time comparison so a partial-match attacker can't
// distinguish "first byte wrong" from "all bytes wrong" via timing.
let supplied: Buffer;
let want: Buffer;
try {
supplied = Buffer.from(input.signature, 'hex');
want = Buffer.from(expected, 'hex');
} catch {
return { ok: false, reason: 'bad-signature' };
}
if (supplied.length !== want.length || !timingSafeEqual(supplied, want)) {
return { ok: false, reason: 'bad-signature' };
}
seenNonces.set(nonceKey, now + windowMs);
return { ok: true };
}
/**
* Extract a bearer token from an HTTP Authorization header value.
* Accepts: "Bearer <token>" or just "<token>".
*/
export function extractBearerToken(headerValue: string | undefined): string | undefined {
if (!headerValue) return undefined;
const trimmed = headerValue.trim();
if (trimmed.startsWith('Bearer ')) return trimmed.slice(7).trim();
if (trimmed.startsWith('bearer ')) return trimmed.slice(7).trim();
return trimmed;
}
// ---------------------------------------------------------------------------
// HTTP middleware
// ---------------------------------------------------------------------------
const PUBLIC_GET_PATHS = new Set([
'/api/status',
'/api/chain/rpc-health',
'/.well-known/skill.md',
'/.well-known/skill-importer.md',
// Exact match — `/ui-custom` etc. would otherwise bypass auth via a loose prefix.
'/ui',
]);
// Trailing slash required; `startsWith('/ui/')` excludes `/ui-custom`.
const PUBLIC_GET_PREFIXES = [
'/ui/',
'/apps/',
];
// HEAD allowlist is narrower than GET: only paths whose built-in handlers explicitly claim HEAD
// (status.ts `/api/status`, `/api/chain/rpc-health`, `/.well-known/skill.md`). Adding /ui or /apps prefixes
// without a built-in claim would let `HEAD /ui/foo` fall through to route plugins unauthenticated (round-7).
const PUBLIC_HEAD_PATHS = new Set([
'/api/status',
'/api/chain/rpc-health',
'/.well-known/skill.md',
'/.well-known/skill-importer.md',
]);
function isPublicPath(method: string, pathname: string): boolean {
if (method === 'GET') {
if (PUBLIC_GET_PATHS.has(pathname)) return true;
for (const prefix of PUBLIC_GET_PREFIXES) {
if (pathname.startsWith(prefix)) return true;
}
return false;
}
if (method === 'HEAD') return PUBLIC_HEAD_PATHS.has(pathname);
return false;
}
export type RequestAuthDecision =
| { ok: true; context: RequestAuthContext; credentialToken: string }
| { ok: false; status: 403; error: string };
export interface RequestAuthSource {
resolve: (
req: IncomingMessage,
validTokens: Set<string>,
corsOrigin?: string | null,
) => RequestAuthDecision | null;
}
function defaultRequestPrincipal(): RequestAuthPrincipal {
return { kind: 'node-admin', agentAddress: 'unknown' };
}
function resolveRequestPrincipal(token: string, options?: HttpAuthGuardOptions): RequestAuthPrincipal {
return options?.resolvePrincipal?.(token) ?? defaultRequestPrincipal();
}
export function resolveRequestAuthDecision(
req: IncomingMessage,
validTokens: Set<string>,
options?: HttpAuthGuardOptions,
corsOrigin?: string | null,
): RequestAuthDecision | null {
const url = new URL(req.url ?? '/', `http://${req.headers.host}`);
const pathname = url.pathname;
const token = extractBearerToken(req.headers.authorization);
if (token && verifyToken(token, validTokens)) {
return {
ok: true,
credentialToken: token,
context: {
source: 'authorization-header',
token,
principal: resolveRequestPrincipal(token, options),
csrf: { required: false, validated: false },
},
};
}
const hasEventsQueryToken = pathname === '/api/events' && url.searchParams.has('token');
if (hasEventsQueryToken) {
const queryToken = url.searchParams.get('token') ?? undefined;
if (queryToken && verifyToken(queryToken, validTokens)) {
return {
ok: true,
credentialToken: queryToken,
context: {
source: 'events-query',
token: queryToken,
principal: resolveRequestPrincipal(queryToken, options),
csrf: { required: false, validated: false },
},
};
}
}
const explicitAuthAttempt = Boolean(token) || hasEventsQueryToken;
if (explicitAuthAttempt) return null;
for (const source of options?.authSources ?? []) {
const decision = source.resolve(req, validTokens, corsOrigin);
if (decision) return decision;
}
return null;
}
/**
* CLI-10 /.
*
* the previous revision of this file
* added a coarse `token:method:pathname:content-length` fingerprint
* dedup for body-less Bearer requests so a leaked Bearer could not be
* silently replayed. That dedup was too aggressive: two consecutive
* legitimate `POST /api/local-agent-integrations/:id/refresh` calls
* share a fingerprint and the second one was 401-rejected for 60 s.
* Similarly, any idempotent body-less `DELETE` retried within a minute
* failed with a confusing replay error.
*
* Replay protection that REJECTS legitimate retries is worse than no
* replay protection: it breaks correct clients while still leaving the
* strict replay window (60 s) available to an attacker who records the
* wire. The proper transport-layer defence against Bearer replay is
* the signed-request scheme (x-dkg-timestamp + x-dkg-nonce +
* x-dkg-signature) which binds every request to a unique nonce and a
* freshness window, and which is already enforced above — including
* synchronous zero-body verification. Clients that do not opt into
* signed-request mode now get no transport-layer replay defence; they
* must handle idempotence at the application layer or upgrade to
* signed requests. That is the correct trade-off because:
*
* 1. Idempotent operations (`refresh`, `DELETE`) MUST be safe to
* retry. Transport replay defence must not violate that.
* 2. Non-idempotent operations (e.g. `POST /publish`) are body-bearing
* in practice, so the old fingerprint never fired for them anyway.
* 3. The signed-request scheme provides proper per-request nonce
* enforcement for callers that need it.
*
* The fingerprint cache and its helpers have therefore been removed.
* The symbols below stay exported-but-empty for a release so any test
* that still references them keeps compiling; the cache is a no-op.
*/
/**
* HTTP auth guard. Returns `true` if the request is allowed to
* proceed, `false` if a 401 response was sent.
*
* For body-carrying signed requests (the only case where the HMAC
* cannot be verified synchronously from headers alone) the guard
* returns a `Promise<boolean>` that resolves AFTER the body has been
* drained and the HMAC has been verified — so callers that `await`
* the result are guaranteed not to run their handler until the
* signature is confirmed. The
* older response-time guard remains installed as defense-in-depth for
* legacy callers that don't `await`, but the supported contract is to
* always `await` the return value.
*
* Usage in the server handler:
* if (!(await httpAuthGuard(req, res, authEnabled, validTokens))) return;
*
* Body-less paths (GET / HEAD / OPTIONS / public paths / unsigned
* requests / framing-bodyless signed requests) still resolve
* synchronously to a bare `boolean` so existing fast-path callers do
* not pay an awaiting cost on hot routes.
*/
export function httpAuthGuard(
req: IncomingMessage,
res: ServerResponse,
authEnabled: boolean,
validTokens: Set<string>,
corsOrigin?: string | null,
options?: HttpAuthGuardOptions,
): boolean | Promise<boolean> {
if (!authEnabled) return true;
if (req.method === 'OPTIONS') return true;
const pathname = new URL(req.url ?? '/', `http://${req.headers.host}`).pathname;
if (isPublicPath(req.method ?? '', pathname)) return true;
const authDecision = resolveRequestAuthDecision(req, validTokens, options, corsOrigin);
if (authDecision?.ok === false) {
res.writeHead(authDecision.status, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': corsOrigin ?? '*',
});
res.end(JSON.stringify({ error: authDecision.error }));
return false;
}
if (authDecision?.ok === true) {
setRequestAuthContext(req, authDecision.context);
const acceptedCredentialToken = authDecision.credentialToken;
const now = Date.now();
// CLI-10: stale-timestamp gate. If the client opted into the
// signed-request scheme by sending `x-dkg-timestamp`, enforce the
// freshness window even before signature verification — a stale
// timestamp is by itself a replay vector regardless of whether
// the signature happens to be valid for that timestamp.
const tsHeader = req.headers['x-dkg-timestamp'];
if (typeof tsHeader === 'string' && tsHeader.length > 0) {
const tsMs = Date.parse(tsHeader);
const tsEpoch = Number.isNaN(tsMs) ? Number(tsHeader) : tsMs;
if (
!Number.isFinite(tsEpoch) ||
Math.abs(now - tsEpoch) > SIGNED_REQUEST_FRESHNESS_WINDOW_MS
) {
res.writeHead(401, {
'Content-Type': 'application/json',
'WWW-Authenticate': 'Bearer realm="dkg-node"',
'Access-Control-Allow-Origin': corsOrigin ?? '*',
});
res.end(
JSON.stringify({ error: 'Stale or unparseable x-dkg-timestamp' }),
);
return false;
}
}