-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathdevice-pairing.test.ts
More file actions
1915 lines (1727 loc) · 60.6 KB
/
Copy pathdevice-pairing.test.ts
File metadata and controls
1915 lines (1727 loc) · 60.6 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
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { PAIRING_SETUP_BOOTSTRAP_PROFILE } from "../shared/device-bootstrap-profile.js";
import { createSuiteTempRootTracker } from "../test-helpers/temp-dir.js";
import { issueDeviceBootstrapToken, verifyDeviceBootstrapToken } from "./device-bootstrap.js";
import {
approveBootstrapDevicePairing,
approveDevicePairing,
clearDevicePairing,
ensureDeviceToken,
getPairedDevice,
hasEffectivePairedDeviceRole,
listEffectivePairedDeviceRoles,
listDevicePairing,
removePairedDevice,
requestDevicePairing,
rejectDevicePairing,
revokeDeviceToken,
rotateDeviceToken,
updatePairedDeviceMetadata,
verifyDeviceToken,
type PairedDevice,
type RotateDeviceTokenResult,
} from "./device-pairing.js";
import { resolvePairingPaths } from "./pairing-files.js";
async function setupPairedOperatorDevice(baseDir: string, scopes: string[]) {
const request = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes,
},
baseDir,
);
await approveDevicePairing(request.request.requestId, { callerScopes: scopes }, baseDir);
}
async function setupPairedNodeDevice(baseDir: string) {
const request = await requestDevicePairing(
{
deviceId: "node-1",
publicKey: "public-key-node-1",
role: "node",
scopes: [],
},
baseDir,
);
await approveDevicePairing(request.request.requestId, { callerScopes: [] }, baseDir);
}
async function setupPairedBrowserOperatorDevice(baseDir: string) {
const request = await requestDevicePairing(
{
deviceId: "browser-device-1",
publicKey: "public-key-browser-1",
clientId: "openclaw-control-ui",
clientMode: "webchat",
role: "operator",
scopes: ["operator.read"],
},
baseDir,
);
await approveDevicePairing(
request.request.requestId,
{ callerScopes: ["operator.read"] },
baseDir,
);
}
async function setupOperatorToken(scopes: string[]) {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, scopes);
const paired = await getPairedDevice("device-1", baseDir);
const token = requireToken(paired?.tokens?.operator?.token);
return { baseDir, token };
}
function verifyOperatorToken(params: { baseDir: string; token: string; scopes: string[] }) {
return verifyDeviceToken({
deviceId: "device-1",
token: params.token,
role: "operator",
scopes: params.scopes,
baseDir: params.baseDir,
});
}
function requireToken(token: string | undefined): string {
expect(typeof token).toBe("string");
if (typeof token !== "string") {
throw new Error("expected device token to be issued");
}
return token;
}
function requireValue<T>(value: T | null | undefined, message: string): T {
if (value == null) {
throw new Error(message);
}
return value;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireRecord(value: unknown, message: string): Record<string, unknown> {
if (!isRecord(value)) {
throw new Error(message);
}
return value;
}
function expectRecordFields(
value: unknown,
message: string,
expected: Record<string, unknown>,
): Record<string, unknown> {
const record = requireRecord(value, message);
for (const [key, expectedValue] of Object.entries(expected)) {
expect(record[key], `${message}.${key}`).toEqual(expectedValue);
}
return record;
}
function expectArrayIncludesAll(value: unknown, expected: readonly unknown[], message: string) {
expect(Array.isArray(value), `${message} must be an array`).toBe(true);
for (const expectedValue of expected) {
expect(value as unknown[], `${message} must include ${String(expectedValue)}`).toContain(
expectedValue,
);
}
}
function requireRotatedEntry(result: RotateDeviceTokenResult) {
expect(result.ok).toBe(true);
if (!result.ok) {
throw new Error(`expected rotated token entry, got ${result.reason}`);
}
return result.entry;
}
async function overwritePairedOperatorTokenScopes(baseDir: string, scopes: string[]) {
const { pairedPath } = resolvePairingPaths(baseDir, "devices");
const pairedByDeviceId = JSON.parse(await readFile(pairedPath, "utf8")) as Record<
string,
PairedDevice
>;
const device = requireValue(pairedByDeviceId["device-1"], "expected paired device device-1");
const operatorToken = requireValue(device.tokens?.operator, "expected paired operator token");
operatorToken.scopes = scopes;
await writeFile(pairedPath, JSON.stringify(pairedByDeviceId, null, 2));
}
async function mutatePairedDevice(
baseDir: string,
deviceId: string,
mutate: (device: PairedDevice) => void,
) {
const { pairedPath } = resolvePairingPaths(baseDir, "devices");
const pairedByDeviceId = JSON.parse(await readFile(pairedPath, "utf8")) as Record<
string,
PairedDevice
>;
const device = requireValue(pairedByDeviceId[deviceId], `expected paired device ${deviceId}`);
mutate(device);
await writeFile(pairedPath, JSON.stringify(pairedByDeviceId, null, 2));
}
async function clearPairedOperatorApprovalBaseline(baseDir: string) {
await mutatePairedDevice(baseDir, "device-1", (device) => {
delete device.approvedScopes;
delete device.scopes;
});
}
const suiteRootTracker = createSuiteTempRootTracker({ prefix: "openclaw-device-pairing-" });
async function makeDevicePairingDir(): Promise<string> {
return await suiteRootTracker.make("case");
}
describe("device pairing tokens", () => {
beforeAll(async () => {
await suiteRootTracker.setup();
});
afterAll(async () => {
await suiteRootTracker.cleanup();
});
test("reuses existing pending requests for the same device", async () => {
const baseDir = await makeDevicePairingDir();
const first = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
},
baseDir,
);
const second = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
},
baseDir,
);
expect(first.created).toBe(true);
expect(second.created).toBe(false);
expect(second.request.requestId).toBe(first.request.requestId);
});
test("recovers when pairing state files were written as arrays", async () => {
const baseDir = await makeDevicePairingDir();
const paths = resolvePairingPaths(baseDir, "devices");
await mkdir(paths.dir, { recursive: true });
await writeFile(paths.pendingPath, "[]", "utf8");
await writeFile(paths.pairedPath, "[]", "utf8");
const pending = await requestDevicePairing(
{
deviceId: "device-array-state",
publicKey: "public-key-array-state",
role: "operator",
scopes: ["operator.read"],
},
baseDir,
);
const approved = await approveDevicePairing(
pending.request.requestId,
{ callerScopes: ["operator.read"] },
baseDir,
);
const approvedRecord = expectRecordFields(approved, "approved result", {
status: "approved",
});
expectRecordFields(approvedRecord.device, "approved device", {
deviceId: "device-array-state",
});
expect(Array.isArray(JSON.parse(await readFile(paths.pendingPath, "utf8")))).toBe(false);
const pairedByDeviceId = requireRecord(
JSON.parse(await readFile(paths.pairedPath, "utf8")),
"paired devices",
);
expectRecordFields(pairedByDeviceId["device-array-state"], "paired device", {
deviceId: "device-array-state",
});
});
test("re-requesting with identical params preserves the original ts to prevent queue-jumping", async () => {
// Regression: refreshPendingDevicePairingRequest must not bump ts to Date.now().
// An attacker who reconnects with the same key/role/scopes could otherwise
// silently move their request to the top of the implicit --latest approval queue.
const baseDir = await makeDevicePairingDir();
const first = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.read"],
},
baseDir,
);
const originalTs = first.request.ts - 1_000;
const paths = resolvePairingPaths(baseDir, "devices");
const pendingById = JSON.parse(await readFile(paths.pendingPath, "utf8")) as Record<
string,
{ ts: number }
>;
const pending = requireValue(
pendingById[first.request.requestId],
"expected pending pairing request",
);
pending.ts = originalTs;
await writeFile(paths.pendingPath, JSON.stringify(pendingById, null, 2));
const second = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.read"],
},
baseDir,
);
expect(second.created).toBe(false);
expect(second.request.requestId).toBe(first.request.requestId);
expect(second.request.ts).toBe(originalTs);
});
test("supersedes pending requests when requested roles/scopes change", async () => {
const baseDir = await makeDevicePairingDir();
const first = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "node",
scopes: [],
},
baseDir,
);
const second = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.read", "operator.write"],
},
baseDir,
);
expect(second.created).toBe(true);
expect(second.request.requestId).not.toBe(first.request.requestId);
expect(second.request.role).toBe("operator");
expectArrayIncludesAll(second.request.roles, ["node", "operator"], "request roles");
expectArrayIncludesAll(
second.request.scopes,
["operator.read", "operator.write"],
"request scopes",
);
const list = await listDevicePairing(baseDir);
expect(list.pending).toHaveLength(1);
expect(list.pending[0]?.requestId).toBe(second.request.requestId);
await approveDevicePairing(
second.request.requestId,
{ callerScopes: ["operator.read", "operator.write"] },
baseDir,
);
const paired = await getPairedDevice("device-1", baseDir);
expectArrayIncludesAll(paired?.roles, ["node", "operator"], "paired roles");
expectArrayIncludesAll(paired?.scopes, ["operator.read", "operator.write"], "paired scopes");
});
test("approves mixed node and operator requests with admin caller scopes", async () => {
const baseDir = await makeDevicePairingDir();
const request = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
roles: ["node", "operator"],
scopes: ["operator.read", "operator.write", "operator.talk.secrets"],
},
baseDir,
);
const approved = await approveDevicePairing(
request.request.requestId,
{ callerScopes: ["operator.admin", "operator.pairing"] },
baseDir,
);
expectRecordFields(approved, "approved result", {
status: "approved",
requestId: request.request.requestId,
});
const paired = await getPairedDevice("device-1", baseDir);
expect(paired && listEffectivePairedDeviceRoles(paired)).toEqual(["node", "operator"]);
expect(paired?.tokens?.node?.scopes).toStrictEqual([]);
expect(paired?.tokens?.operator?.scopes).toEqual([
"operator.read",
"operator.talk.secrets",
"operator.write",
]);
await expect(
verifyDeviceToken({
deviceId: "device-1",
token: requireToken(paired?.tokens?.node?.token),
role: "node",
scopes: [],
baseDir,
}),
).resolves.toEqual({ ok: true });
await expect(
verifyDeviceToken({
deviceId: "device-1",
token: requireToken(paired?.tokens?.operator?.token),
role: "operator",
scopes: ["operator.read"],
baseDir,
}),
).resolves.toEqual({ ok: true });
});
test("preserves existing operator token scopes when approving a scope upgrade", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, ["operator.read"]);
const upgrade = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.write"],
},
baseDir,
);
const approved = await approveDevicePairing(
upgrade.request.requestId,
{ callerScopes: ["operator.read", "operator.write"] },
baseDir,
);
expectRecordFields(approved, "approved result", { status: "approved" });
const paired = await getPairedDevice("device-1", baseDir);
expect(paired?.approvedScopes).toEqual(["operator.read", "operator.write"]);
expect(paired?.tokens?.operator?.scopes).toEqual(["operator.read", "operator.write"]);
});
test("does not widen a down-scoped operator token when approving a scope upgrade", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, ["operator.read", "operator.write"]);
await overwritePairedOperatorTokenScopes(baseDir, ["operator.read"]);
const upgrade = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.talk.secrets"],
},
baseDir,
);
const approved = await approveDevicePairing(
upgrade.request.requestId,
{ callerScopes: ["operator.read", "operator.talk.secrets", "operator.write"] },
baseDir,
);
expectRecordFields(approved, "approved result", { status: "approved" });
const paired = await getPairedDevice("device-1", baseDir);
expect(paired?.approvedScopes).toEqual([
"operator.read",
"operator.write",
"operator.talk.secrets",
]);
expect(paired?.tokens?.operator?.scopes).toEqual(["operator.read", "operator.talk.secrets"]);
expect(paired?.tokens?.operator?.scopes).not.toContain("operator.write");
});
test("preserves requested non-operator scopes on newly minted role tokens", async () => {
const baseDir = await makeDevicePairingDir();
const request = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "node",
scopes: ["node.exec"],
},
baseDir,
);
const approved = await approveDevicePairing(request.request.requestId, baseDir);
expectRecordFields(approved, "approved result", {
status: "approved",
requestId: request.request.requestId,
});
const paired = await getPairedDevice("device-1", baseDir);
expect(paired?.tokens?.node?.scopes).toEqual(["node.exec"]);
await expect(
verifyDeviceToken({
deviceId: "device-1",
token: requireToken(paired?.tokens?.node?.token),
role: "node",
scopes: ["node.exec"],
baseDir,
}),
).resolves.toEqual({ ok: true });
});
test.each([
{
name: "node custom scope",
roles: ["node"],
scopes: ["vault.admin"],
scope: "vault.admin",
callerScopes: [],
},
{
name: "operator custom scope",
roles: ["operator"],
scopes: ["vault.admin"],
scope: "vault.admin",
callerScopes: ["operator.pairing"],
},
{
name: "node requesting operator scope",
roles: ["node"],
scopes: ["operator.read"],
scope: "operator.read",
callerScopes: ["operator.read"],
},
])("rejects requested scopes outside requested roles: $name", async (params) => {
const baseDir = await makeDevicePairingDir();
const request = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
roles: params.roles,
scopes: params.scopes,
},
baseDir,
);
await expect(
approveDevicePairing(
request.request.requestId,
{ callerScopes: params.callerScopes },
baseDir,
),
).resolves.toEqual({
status: "forbidden",
reason: "scope-outside-requested-roles",
scope: params.scope,
});
await expect(getPairedDevice("device-1", baseDir)).resolves.toBeNull();
});
test("preserves existing non-operator scopes during operator-only mixed-role repairs", async () => {
const baseDir = await makeDevicePairingDir();
const initial = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "node",
scopes: ["node.exec"],
},
baseDir,
);
const approvedInitial = await approveDevicePairing(initial.request.requestId, baseDir);
expectRecordFields(approvedInitial, "initial approved result", {
status: "approved",
requestId: initial.request.requestId,
});
const repair = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
roles: ["node", "operator"],
scopes: ["operator.read"],
},
baseDir,
);
const approvedRepair = await approveDevicePairing(
repair.request.requestId,
{ callerScopes: ["operator.read"] },
baseDir,
);
expectRecordFields(approvedRepair, "repair approved result", {
status: "approved",
requestId: repair.request.requestId,
});
const paired = await getPairedDevice("device-1", baseDir);
expect(paired?.tokens?.node?.scopes).toEqual(["node.exec"]);
expect(paired?.tokens?.operator?.scopes).toEqual(["operator.read"]);
await expect(
verifyDeviceToken({
deviceId: "device-1",
token: requireToken(paired?.tokens?.node?.token),
role: "node",
scopes: ["node.exec"],
baseDir,
}),
).resolves.toEqual({ ok: true });
});
test("keeps superseded requests interactive when an existing pending request is interactive", async () => {
const baseDir = await makeDevicePairingDir();
const first = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "node",
scopes: [],
silent: false,
},
baseDir,
);
expect(first.request.silent).toBe(false);
const second = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.read"],
silent: true,
},
baseDir,
);
expect(second.created).toBe(true);
expect(second.request.requestId).not.toBe(first.request.requestId);
expect(second.request.silent).toBe(false);
});
test("rejects bootstrap token replay before pending scope escalation can be approved", async () => {
const baseDir = await makeDevicePairingDir();
const issued = await issueDeviceBootstrapToken({
baseDir,
roles: ["operator"],
scopes: ["operator.approvals", "operator.read", "operator.write"],
});
await expect(
verifyDeviceBootstrapToken({
token: issued.token,
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.read"],
baseDir,
}),
).resolves.toEqual({ ok: true });
const first = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.read"],
},
baseDir,
);
await expect(
verifyDeviceBootstrapToken({
token: issued.token,
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.write", "operator.approvals"],
baseDir,
}),
).resolves.toEqual({ ok: false, reason: "bootstrap_token_invalid" });
const pending = await listDevicePairing(baseDir);
expect(pending.pending).toHaveLength(1);
expect(pending.pending[0]?.scopes).toEqual(["operator.read"]);
await approveDevicePairing(
first.request.requestId,
{ callerScopes: ["operator.read"] },
baseDir,
);
const paired = await getPairedDevice("device-1", baseDir);
expect(paired?.scopes).toEqual(["operator.read"]);
expect(paired?.approvedScopes).toEqual(["operator.read"]);
expect(paired?.tokens?.operator?.scopes).toEqual(["operator.read"]);
});
test("rejecting a bootstrap-bound pending request revokes the bootstrap token", async () => {
const baseDir = await makeDevicePairingDir();
const issued = await issueDeviceBootstrapToken({ baseDir });
await expect(
verifyDeviceBootstrapToken({
token: issued.token,
deviceId: "bootstrap-reject-device",
publicKey: "bootstrap-reject-public-key",
role: "node",
scopes: [],
baseDir,
}),
).resolves.toEqual({ ok: true });
const pending = await requestDevicePairing(
{
deviceId: "bootstrap-reject-device",
publicKey: "bootstrap-reject-public-key",
role: "node",
roles: ["node"],
scopes: [],
},
baseDir,
);
await expect(rejectDevicePairing(pending.request.requestId, baseDir)).resolves.toEqual({
requestId: pending.request.requestId,
deviceId: "bootstrap-reject-device",
});
await expect(
verifyDeviceBootstrapToken({
token: issued.token,
deviceId: "bootstrap-reject-device",
publicKey: "bootstrap-reject-public-key",
role: "node",
scopes: [],
baseDir,
}),
).resolves.toEqual({ ok: false, reason: "bootstrap_token_invalid" });
});
test("fails closed for operator approvals when caller scopes are omitted", async () => {
const baseDir = await makeDevicePairingDir();
const request = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
scopes: ["operator.admin"],
},
baseDir,
);
await expect(approveDevicePairing(request.request.requestId, baseDir)).resolves.toEqual({
status: "forbidden",
reason: "caller-scopes-required",
scope: "operator.admin",
});
const approved = await approveDevicePairing(
request.request.requestId,
{
callerScopes: ["operator.admin"],
},
baseDir,
);
expectRecordFields(approved, "approved result", {
status: "approved",
requestId: request.request.requestId,
});
});
test("metadata refresh can update display metadata but not approved role and scope fields", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedNodeDevice(baseDir);
await updatePairedDeviceMetadata(
"node-1",
{
displayName: "renamed-node",
platform: "iOS 26.5.0",
role: "operator",
roles: ["operator"],
scopes: ["operator.admin"],
approvedScopes: ["operator.admin"],
tokens: {},
publicKey: "attacker-key",
} as unknown as Parameters<typeof updatePairedDeviceMetadata>[1],
baseDir,
);
const paired = await getPairedDevice("node-1", baseDir);
expect(paired?.displayName).toBe("renamed-node");
expect(paired?.platform).toBe("iOS 26.5.0");
expect(paired?.publicKey).toBe("public-key-node-1");
expect(paired?.role).toBe("node");
expect(paired?.roles).toEqual(["node"]);
expect(paired?.scopes).toStrictEqual([]);
expect(paired?.approvedScopes).toStrictEqual([]);
expect(typeof paired?.tokens?.node?.token).toBe("string");
expect(paired?.tokens?.operator).toBeUndefined();
});
test("metadata refresh persists last-seen fields and reports missing devices", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedNodeDevice(baseDir);
await expect(
updatePairedDeviceMetadata(
"node-1",
{
lastSeenAtMs: 4321,
lastSeenReason: "bg_app_refresh",
},
baseDir,
),
).resolves.toBe(true);
await expect(updatePairedDeviceMetadata("missing", { lastSeenAtMs: 1 }, baseDir)).resolves.toBe(
false,
);
const paired = await getPairedDevice("node-1", baseDir);
expectRecordFields(paired, "paired device", {
lastSeenAtMs: 4321,
lastSeenReason: "bg_app_refresh",
});
});
test("approval access metadata initializes paired device last-seen fields", async () => {
const baseDir = await makeDevicePairingDir();
const request = await requestDevicePairing(
{
deviceId: "node-1",
publicKey: "public-key-node-1",
role: "node",
scopes: [],
displayName: "pending-name",
remoteIp: "127.0.0.1",
},
baseDir,
);
const firstSeenAtMs = Date.now();
const approved = await approveDevicePairing(
request.request.requestId,
{
callerScopes: [],
accessMetadata: {
displayName: "connected-name",
remoteIp: "10.0.0.1",
lastSeenAtMs: firstSeenAtMs,
lastSeenReason: "connect",
},
},
baseDir,
);
expectRecordFields(approved, "approved result", { status: "approved" });
const paired = await getPairedDevice("node-1", baseDir);
expectRecordFields(paired, "paired device", {
displayName: "connected-name",
remoteIp: "10.0.0.1",
lastSeenAtMs: firstSeenAtMs,
lastSeenReason: "connect",
});
});
test("repair approvals preserve paired device last-seen fields without access metadata", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedNodeDevice(baseDir);
await updatePairedDeviceMetadata(
"node-1",
{
lastSeenAtMs: 1234,
lastSeenReason: "bg_app_refresh",
},
baseDir,
);
const repair = await requestDevicePairing(
{
deviceId: "node-1",
publicKey: "public-key-node-1",
role: "node",
scopes: [],
},
baseDir,
);
await approveDevicePairing(repair.request.requestId, { callerScopes: [] }, baseDir);
const paired = await getPairedDevice("node-1", baseDir);
expectRecordFields(paired, "paired device", {
lastSeenAtMs: 1234,
lastSeenReason: "bg_app_refresh",
});
});
test("device token verification refreshes paired device last-seen metadata", async () => {
const { baseDir, token } = await setupOperatorToken(["operator.read"]);
const beforeVerifyAtMs = Date.now();
await expect(
verifyDeviceToken({
deviceId: "device-1",
token,
role: "operator",
scopes: ["operator.read"],
baseDir,
}),
).resolves.toEqual({ ok: true });
const paired = await getPairedDevice("device-1", baseDir);
expect(paired?.lastSeenReason).toBe("device-token-auth");
expect(typeof paired?.lastSeenAtMs).toBe("number");
expect(paired?.lastSeenAtMs ?? 0).toBeGreaterThanOrEqual(beforeVerifyAtMs);
});
test("generates base64url device tokens with 256-bit entropy output length", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, ["operator.admin"]);
const paired = await getPairedDevice("device-1", baseDir);
const token = requireToken(paired?.tokens?.operator?.token);
expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(Buffer.from(token, "base64url")).toHaveLength(32);
});
test("allows down-scoping from admin and preserves approved scope baseline", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, ["operator.admin"]);
const downscoped = await rotateDeviceToken({
deviceId: "device-1",
role: "operator",
scopes: ["operator.read"],
baseDir,
});
expect(downscoped.ok).toBe(true);
let paired = await getPairedDevice("device-1", baseDir);
expect(paired?.tokens?.operator?.scopes).toEqual(["operator.read"]);
expect(paired?.scopes).toEqual(["operator.admin"]);
expect(paired?.approvedScopes).toEqual(["operator.admin"]);
const reused = await rotateDeviceToken({
deviceId: "device-1",
role: "operator",
baseDir,
});
expect(reused.ok).toBe(true);
paired = await getPairedDevice("device-1", baseDir);
expect(paired?.tokens?.operator?.scopes).toEqual(["operator.read"]);
});
test("preserves existing token scopes when approving a repair without requested scopes", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, ["operator.admin"]);
const repair = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
},
baseDir,
);
await approveDevicePairing(
repair.request.requestId,
{ callerScopes: ["operator.admin"] },
baseDir,
);
const paired = await getPairedDevice("device-1", baseDir);
expect(paired?.scopes).toEqual(["operator.admin"]);
expect(paired?.approvedScopes).toEqual(["operator.admin"]);
expect(paired?.tokens?.operator?.scopes).toEqual([
"operator.admin",
"operator.read",
"operator.write",
]);
});
test("rejects repair without requested scopes when caller cannot approve inherited token scopes", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, ["operator.admin"]);
const before = await getPairedDevice("device-1", baseDir);
const repair = await requestDevicePairing(
{
deviceId: "device-1",
publicKey: "public-key-1",
role: "operator",
},
baseDir,
);
await expect(
approveDevicePairing(
repair.request.requestId,
{ callerScopes: ["operator.pairing"] },
baseDir,
),
).resolves.toEqual({
status: "forbidden",
reason: "caller-missing-scope",
scope: "operator.admin",
});
const after = await getPairedDevice("device-1", baseDir);
expect(after?.tokens?.operator?.token).toEqual(before?.tokens?.operator?.token);
expect(after?.tokens?.operator?.scopes).toEqual([
"operator.admin",
"operator.read",
"operator.write",
]);
});
test("rejects scope escalation when rotating a token and leaves state unchanged", async () => {
const baseDir = await makeDevicePairingDir();
await setupPairedOperatorDevice(baseDir, ["operator.read"]);
const before = await getPairedDevice("device-1", baseDir);
const rotated = await rotateDeviceToken({
deviceId: "device-1",
role: "operator",
scopes: ["operator.admin"],
baseDir,
});
expect(rotated).toEqual({ ok: false, reason: "scope-outside-approved-baseline" });
const after = await getPairedDevice("device-1", baseDir);
expect(after?.tokens?.operator?.token).toEqual(before?.tokens?.operator?.token);
expect(after?.tokens?.operator?.scopes).toEqual(["operator.read"]);
expect(after?.scopes).toEqual(["operator.read"]);
expect(after?.approvedScopes).toEqual(["operator.read"]);
});
test("rejects omitted-scope rotation when caller cannot hold the current token scopes", async () => {