forked from setube/stackprism
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackprism_bridge_py.test.mjs
More file actions
3697 lines (3411 loc) · 149 KB
/
Copy pathstackprism_bridge_py.test.mjs
File metadata and controls
3697 lines (3411 loc) · 149 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 assert from 'node:assert/strict'
import { spawn, spawnSync } from 'node:child_process'
import { once } from 'node:events'
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
import net from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
import { bridgePageScript, bridgePageStyle } from '../agent-skill/stackprism-site-experience/scripts/bridge/bridge-page-assets.mjs'
import identifiers from './fixtures/bridge-protocol-identifiers.json' with { type: 'json' }
import urlPolicyCases from './fixtures/bridge-url-policy-cases.json' with { type: 'json' }
const request = {
url: 'https://93.184.216.34/app?view=one#frag',
mode: 'experience',
waitMs: 0,
include: ['tech'],
viewports: [],
options: { targetMode: 'reuse_or_new_tab' }
}
const readJson = async response => ({ status: response.status, body: await response.json(), headers: response.headers })
const readBytes = async response => ({
status: response.status,
body: Buffer.from(await response.arrayBuffer()),
headers: response.headers
})
const waitForFileSync = filePath => {
const deadline = Date.now() + 2000
const waitBuffer = new Int32Array(new SharedArrayBuffer(4))
while (!existsSync(filePath) && Date.now() < deadline) Atomics.wait(waitBuffer, 0, 0, 25)
assert.equal(existsSync(filePath), true, `expected file to exist: ${filePath}`)
}
const sensitiveFailedError = (ready, created, config) => {
const sensitiveUrl = `${created.body.bridgeUrl}&token=secret&apiToken=${ready.apiToken}&bridgeToken=${config.bridgeToken}#frag`
return {
code: 'TARGET_TAB_CLOSED',
message: `Target closed while loading ${sensitiveUrl}`,
details: {
url: sensitiveUrl,
token: config.bridgeToken,
nonce: config.nonce,
nested: {
authorization: `Bearer ${ready.apiToken}`,
values: [config.bridgeToken, config.nonce, sensitiveUrl]
}
}
}
}
const assertErrorIsRedacted = (error, blockedValues) => {
const serialized = JSON.stringify(error)
for (const value of blockedValues) assert.equal(serialized.includes(value), false, value)
assert.doesNotMatch(serialized, /spbt?_[A-Za-z0-9_-]{8,}/)
assert.doesNotMatch(serialized, /\bn_[A-Za-z0-9_-]{8,}\b/)
assert.doesNotMatch(serialized, /token=secret|apiToken=|bridgeToken=|#frag/)
assert.match(serialized, /\[redacted/)
}
const assertJsonSecurityHeaders = (envelope, { referrerPolicy = false } = {}) => {
assert.match(envelope.headers.get('content-type') || '', /^application\/json; charset=utf-8\b/)
assert.equal(envelope.headers.get('cache-control'), 'no-store')
assert.equal(envelope.headers.get('x-content-type-options'), 'nosniff')
if (referrerPolicy) assert.equal(envelope.headers.get('referrer-policy'), 'no-referrer')
}
const createCapture = async ready =>
readJson(
await fetch(`${ready.baseUrl}/v1/captures`, {
method: 'POST',
headers: { Authorization: `Bearer ${ready.apiToken}`, 'Content-Type': 'application/json' },
body: JSON.stringify(request)
})
)
const loadBridgeConfig = async bridgeUrl => {
const bridgePage = await fetch(bridgeUrl)
const html = await bridgePage.text()
return JSON.parse(html.match(/<script id="stackprism-agent-bridge-config" type="application\/json" nonce="[^"]+">([^<]+)/)[1])
}
const loadBridgePage = async bridgeUrl => {
const response = await fetch(bridgeUrl)
return { response, html: await response.text() }
}
const statusBody = (captureId, config, body) => ({
captureId,
sessionId: config.sessionId,
nonce: config.nonce,
protocolVersion: 1,
...body
})
const percentEncodeFirstPayloadChar = value =>
`${value.slice(0, 2)}%${value.charCodeAt(2).toString(16).toUpperCase().padStart(2, '0')}${value.slice(3)}`
const percentEncodeBridgeParam = (bridgeUrl, name) => {
const url = new URL(bridgeUrl)
const value = url.searchParams.get(name)
return bridgeUrl.replace(`${name}=${value}`, `${name}=${percentEncodeFirstPayloadChar(value)}`)
}
const acceptFinalUrl = async (ready, captureId, bridgeToken, finalUrl = request.url) => {
const requestEnvelope = await readJson(
await fetch(`${ready.baseUrl}/v1/captures/${captureId}/request`, { headers: { Authorization: `Bearer ${bridgeToken}` } })
)
assert.equal(requestEnvelope.status, 200)
assertJsonSecurityHeaders(requestEnvelope)
const response = await fetch(`${ready.baseUrl}/v1/captures/${captureId}/status`, {
method: 'POST',
headers: { Authorization: `Bearer ${bridgeToken}`, 'Content-Type': 'application/json' },
body: JSON.stringify(
statusBody(captureId, requestEnvelope.body, {
status: 'running',
phase: 'target_loaded',
sequence: 1,
finalUrl,
targetNetworkAddress: '93.184.216.34'
})
)
})
const envelope = await readJson(response)
assert.equal(envelope.status, 200)
assertJsonSecurityHeaders(envelope)
assert.equal(envelope.body.phase, 'target_loaded')
}
const profileFor = (captureId, overrides = {}) => ({
schema: 'stackprism.site_experience_profile.v1',
captureId,
generatedAt: new Date(0).toISOString(),
target: {},
browserContext: { extensionCapabilities: {} },
techProfile: {},
visualProfile: {},
layoutProfile: {},
componentProfile: {},
interactionProfile: {},
uxProfile: {},
assetProfile: {},
evidence: {},
limitations: [],
agentGuidance: {},
...overrides
})
const startPythonBridge = async () => {
const child = spawn('python3', ['agent-skill/stackprism-site-experience/scripts/stackprism_bridge.py'], {
cwd: new URL('..', import.meta.url),
env: { ...process.env, STACKPRISM_BRIDGE_NO_OPEN: '1' },
stdio: ['pipe', 'pipe', 'pipe']
})
const ready = await readFirstStdoutJson(child)
return { child, ready }
}
const startPythonBridgeWithEnv = env =>
spawn('python3', ['agent-skill/stackprism-site-experience/scripts/stackprism_bridge.py'], {
cwd: new URL('..', import.meta.url),
env: { ...process.env, STACKPRISM_BRIDGE_NO_OPEN: '1', ...env },
stdio: ['pipe', 'pipe', 'pipe']
})
const readFirstStdoutJson = async child => {
let stdout = ''
return new Promise((resolve, reject) => {
const cleanup = () => {
child.stdout.off('data', onData)
child.off('exit', onExit)
}
const onData = chunk => {
stdout += String(chunk)
const newline = stdout.indexOf('\n')
if (newline < 0) return
cleanup()
const line = stdout.slice(0, newline)
try {
resolve(JSON.parse(line))
} catch (error) {
reject(Object.assign(new Error('PYTHON_BRIDGE_READY_PARSE_FAILED'), { cause: error, stdout }))
}
}
const onExit = code => {
cleanup()
reject(Object.assign(new Error('PYTHON_BRIDGE_EXITED_BEFORE_READY'), { code, stdout }))
}
child.stdout.on('data', onData)
child.once('exit', onExit)
})
}
const listenOnLoopback = () =>
new Promise((resolve, reject) => {
const server = net.createServer()
server.once('error', reject)
server.listen(0, '127.0.0.1', () => resolve(server))
})
const pythonOneShot = script => {
const result = spawnSync('python3', ['-c', `import json\n${script}`], {
cwd: new URL('..', import.meta.url),
env: {
...process.env,
STACKPRISM_BRIDGE_NO_OPEN: '1',
PYTHONPATH: 'agent-skill/stackprism-site-experience/scripts',
PYTHONWARNINGS: 'ignore'
},
encoding: 'utf8'
})
assert.equal(result.status, 0, result.stderr)
return JSON.parse(result.stdout)
}
test('python fallback prints ready json and serves health', async () => {
const { child, ready } = await startPythonBridge()
try {
assert.equal(ready.event, 'stackprism-bridge-ready')
assert.match(ready.apiToken, /^spb_[A-Za-z0-9_-]{43}$/)
const health = await readJson(await fetch(ready.healthUrl))
assert.equal(health.status, 200)
assert.equal(health.body.service, 'stackprism-agent-bridge')
assert.equal(health.body.protocolVersion, 1)
const resourcePolicy = await pythonOneShot(`
from stackprism_bridge_lib.server_factory import create_server
server, _ready = create_server(0)
print(json.dumps({
"request_queue_size": server.request_queue_size,
"timeout": server.timeout,
"create_limit": server.rate_limits["create"],
"query_limit": server.rate_limits["query"],
}, sort_keys=True))
server.server_close()
`)
assert.equal(resourcePolicy.request_queue_size, 20)
assert.equal(resourcePolicy.timeout, 35)
assert.equal(resourcePolicy.create_limit, 10)
assert.equal(resourcePolicy.query_limit, 120)
} finally {
child.kill('SIGTERM')
await once(child, 'exit')
}
})
test('python fallback exits when stdin closes', async () => {
const { child } = await startPythonBridge()
child.stdin.end()
const [code] = await once(child, 'exit')
assert.equal(code, 0)
})
test('python fallback exits and closes listener on SIGTERM', async () => {
const { child, ready } = await startPythonBridge()
const health = await readJson(await fetch(ready.healthUrl))
assert.equal(health.status, 200)
child.kill('SIGTERM')
const [code] = await once(child, 'exit')
assert.equal(code, 0)
await assert.rejects(() => fetch(ready.healthUrl), /fetch failed/)
})
test('python fallback rate limits capture creation and api status reads', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.server_factory import create_server
import json
import threading
import urllib.error
import urllib.request
server, ready = create_server(0, rate_limits={"createLimitPerMinute": 1, "queryLimitPerMinute": 1})
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
request_body = json.dumps(${JSON.stringify(request)}).encode("utf-8")
def call(method, path, token, body=None):
req = urllib.request.Request(
ready["baseUrl"] + path,
data=body,
method=method,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=3) as response:
return response.status, json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
return exc.code, json.loads(exc.read().decode("utf-8"))
try:
first_status, first = call("POST", "/v1/captures", ready["apiToken"], request_body)
second_status, second = call("POST", "/v1/captures", ready["apiToken"])
query1_status, query1 = call("GET", "/v1/captures/" + first["id"], ready["apiToken"])
query2_status, query2 = call("GET", "/v1/captures/" + first["id"], ready["apiToken"])
print(json.dumps({
"first_status": first_status,
"second_status": second_status,
"second_code": second["error"]["code"],
"query1_status": query1_status,
"query2_status": query2_status,
"query2_code": query2["error"]["code"],
}, sort_keys=True))
finally:
server.shutdown()
server.server_close()
`)
assert.equal(parsed.first_status, 200)
assert.equal(parsed.second_status, 429)
assert.equal(parsed.second_code, 'RATE_LIMITED')
assert.equal(parsed.query1_status, 200)
assert.equal(parsed.query2_status, 429)
assert.equal(parsed.query2_code, 'RATE_LIMITED')
})
test('python fallback rate limits api profile reads', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.server_factory import create_server
import json
import threading
import urllib.error
import urllib.request
server, ready = create_server(0, rate_limits={"queryLimitPerMinute": 1})
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
request_body = json.dumps(${JSON.stringify(request)}).encode("utf-8")
def call(method, path, token, body=None):
req = urllib.request.Request(
ready["baseUrl"] + path,
data=body,
method=method,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=3) as response:
return response.status, json.loads(response.read().decode("utf-8")), dict(response.headers)
except urllib.error.HTTPError as exc:
return exc.code, json.loads(exc.read().decode("utf-8")), dict(exc.headers)
try:
create_status, created, _create_headers = call("POST", "/v1/captures", ready["apiToken"], request_body)
profile1_status, profile1, profile1_headers = call("GET", "/v1/captures/" + created["id"] + "/profile", ready["apiToken"])
profile2_status, profile2, _profile2_headers = call("GET", "/v1/captures/" + created["id"] + "/profile", ready["apiToken"])
print(json.dumps({
"create_status": create_status,
"profile1_status": profile1_status,
"profile1_code": profile1["error"]["code"],
"profile1_referrer_policy": profile1_headers.get("Referrer-Policy"),
"profile2_status": profile2_status,
"profile2_code": profile2["error"]["code"],
}, sort_keys=True))
finally:
server.shutdown()
server.server_close()
`)
assert.equal(parsed.create_status, 200)
assert.equal(parsed.profile1_status, 409)
assert.equal(parsed.profile1_code, 'INVALID_REQUEST')
assert.equal(parsed.profile1_referrer_policy, 'no-referrer')
assert.equal(parsed.profile2_status, 429)
assert.equal(parsed.profile2_code, 'RATE_LIMITED')
})
test('python fallback uses random port only when unset and reports occupied port portably', async () => {
const child = startPythonBridgeWithEnv({})
try {
const ready = await readFirstStdoutJson(child)
assert.equal(ready.event, 'stackprism-bridge-ready')
assert.match(ready.baseUrl, /^http:\/\/127\.0\.0\.1:\d+$/)
} finally {
child.kill('SIGTERM')
await once(child, 'exit')
}
const invalid = startPythonBridgeWithEnv({ STACKPRISM_BRIDGE_PORT: '' })
let invalidStdout = ''
invalid.stdout.on('data', chunk => {
invalidStdout += String(chunk)
})
const [invalidStderr] = await once(invalid.stderr, 'data')
const invalidParsed = JSON.parse(String(invalidStderr).trim())
assert.equal(invalidParsed.error.code, 'BRIDGE_INVALID_ENV')
assert.equal(invalidStdout, '')
assert.equal(String(invalidStderr).includes('spb_'), false)
const [invalidCode] = await once(invalid, 'exit')
assert.notEqual(invalidCode, 0)
const occupied = await listenOnLoopback()
const { port } = occupied.address()
const blocked = startPythonBridgeWithEnv({ STACKPRISM_BRIDGE_PORT: String(port) })
let blockedStdout = ''
blocked.stdout.on('data', chunk => {
blockedStdout += String(chunk)
})
try {
const [stderr] = await once(blocked.stderr, 'data')
const parsed = JSON.parse(String(stderr).trim())
assert.equal(parsed.error.code, 'PORT_IN_USE')
assert.equal(blockedStdout, '')
assert.equal(String(stderr).includes('spb_'), false)
const [code] = await once(blocked, 'exit')
assert.notEqual(code, 0)
} finally {
await new Promise(resolve => occupied.close(resolve))
}
})
test('python fallback reports non-port startup failures with bridge start code', () => {
const parsed = pythonOneShot(`
import stackprism_bridge
def fail_create_server(_port):
raise OSError("cannot bind")
errors = []
def capture_fail_start(code, message):
errors.append({"code": code, "message": message})
return 1
stackprism_bridge.create_server = fail_create_server
stackprism_bridge.fail_start = capture_fail_start
print(json.dumps({"exit": stackprism_bridge.main(), "error": errors[0]}))
`)
assert.equal(parsed.exit, 1)
assert.equal(parsed.error.code, 'BRIDGE_START_FAILED')
assert.equal(parsed.error.message, 'Failed to start bridge server.')
})
test('python fallback sanitizer redacts screenshot download ids', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.protocol import sanitize_bridge_error
sanitized = sanitize_bridge_error({
"code": "INVALID_REQUEST",
"message": "screenshot shot_${'a'.repeat(43)} failed",
"details": {
"url": "http://127.0.0.1:17370/v1/captures/cap_1234567890123456789012/screenshot-download/shot_${'b'.repeat(43)}",
},
})
print(json.dumps(sanitized, sort_keys=True))
`)
assert.equal(parsed.message, 'screenshot [redacted-id] failed')
assert.equal(JSON.stringify(parsed).includes('shot_'), false)
})
test('python fallback server factory validates browser open environment before binding', () => {
const parsed = pythonOneShot(`
import json as json_module
from stackprism_bridge_lib.server_factory import create_server
results = []
for env in (
{"STACKPRISM_BROWSER_OPEN_COMMAND": "bad\\0cmd"},
{"STACKPRISM_BROWSER_OPEN_COMMAND": "python3", "STACKPRISM_BROWSER_OPEN_ARGS_JSON": json_module.dumps(["bad\\0arg"])},
):
try:
server, _ready = create_server(0, env=env)
except ValueError as exc:
results.append({"code": getattr(exc, "code", None), "message": str(exc)})
else:
server.server_close()
raise AssertionError("create_server accepted invalid browser open environment")
print(json.dumps(results))
`)
assert.deepEqual(
parsed.map(item => item.code),
['BRIDGE_INVALID_ENV', 'BRIDGE_INVALID_ENV']
)
assert.equal(
parsed.every(item => /Browser open environment contains NUL/.test(item.message)),
true
)
})
test('python fallback creates captures with same basic error envelope', async () => {
const { child, ready } = await startPythonBridge()
try {
const unauthorized = await readJson(
await fetch(`${ready.baseUrl}/v1/captures`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request)
})
)
assert.equal(unauthorized.status, 401)
assert.equal(unauthorized.body.error.code, 'UNAUTHORIZED')
const created = await createCapture(ready)
assert.equal(created.status, 200)
assert.match(created.body.id, /^cap_[A-Za-z0-9_-]{22}$/)
assert.equal(created.body.status, 'queued')
assert.deepEqual([...new URL(created.body.bridgeUrl).searchParams.keys()].sort(), ['capture', 'nonce', 'session'])
assert.equal(created.body.bridgeUrl.includes(ready.apiToken), false)
assert.equal(created.body.bridgeUrl.includes('apiToken'), false)
assert.equal(created.body.bridgeUrl.includes('bridgeToken'), false)
assert.doesNotMatch(created.body.bridgeUrl, /spbt?_[A-Za-z0-9_-]{20,}/)
const status = await readJson(
await fetch(`${ready.baseUrl}/v1/captures/${created.body.id}`, {
headers: { Authorization: `Bearer ${ready.apiToken}` }
})
)
assert.equal(status.status, 200)
assert.equal('error' in status.body, false)
} finally {
child.kill('SIGTERM')
await once(child, 'exit')
}
})
test('python fallback protocol helpers cover all bridge identifier kinds', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.protocol import html_escape_script_json, is_known_bridge_error_code, new_csp_nonce, random_id, redact_url, safe_equal, valid_id
from stackprism_bridge_lib.status import validate_status_update
values = {
"apiToken": random_id("spb_", 32),
"bridgeToken": random_id("spbt_", 32),
"captureId": random_id("cap_", 16),
"sessionId": random_id("s_", 16),
"nonce": random_id("n_", 16),
"profileTransferId": random_id("xfer_", 16),
"cspNonce": new_csp_nonce(),
}
print(json.dumps({
"valid": {kind: valid_id(kind, value) for kind, value in values.items()},
"unknown": valid_id("unknown", values["apiToken"]),
"redacted": redact_url("https://example.com/app?token=secret#frag"),
"credential_redacted": redact_url("https://user:pass@example.com:8443/app?token=secret#frag"),
"render_error_code": is_known_bridge_error_code("BRIDGE_PAGE_RENDER_FAILED"),
"safe_equal_same": safe_equal("same-token", "same-token"),
"safe_equal_short": safe_equal("same-token", "same"),
"safe_equal_long_tail": safe_equal("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaax", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaay"),
"missing_phase_validation": validate_status_update(
{"id": values["captureId"], "sessionId": values["sessionId"], "nonce": values["nonce"], "status": "running", "sequence": 1},
{
"captureId": values["captureId"],
"sessionId": values["sessionId"],
"nonce": values["nonce"],
"protocolVersion": 1,
"status": "running",
"phase": "request_loaded",
"sequence": 2,
},
)[0],
"escaped": html_escape_script_json({"value": "</script><script>alert(1)</script>&\\u2028\\u2029"}),
}, sort_keys=True))
`)
assert.deepEqual(parsed.valid, {
apiToken: true,
bridgeToken: true,
captureId: true,
sessionId: true,
nonce: true,
profileTransferId: true,
cspNonce: true
})
assert.equal(parsed.unknown, false)
assert.equal(parsed.redacted, 'https://example.com/app?[redacted]')
assert.equal(parsed.credential_redacted, 'https://example.com:8443/app?[redacted]')
assert.equal(parsed.render_error_code, true)
assert.equal(parsed.safe_equal_same, true)
assert.equal(parsed.safe_equal_short, false)
assert.equal(parsed.safe_equal_long_tail, false)
assert.equal(parsed.missing_phase_validation, true)
assert.equal(parsed.escaped.includes('</script>'), false)
assert.equal(parsed.escaped.includes('<script>'), false)
assert.equal(parsed.escaped.includes('&'), false)
assert.match(parsed.escaped, /\\u2028/)
assert.match(parsed.escaped, /\\u2029/)
})
test('python fallback bridge page renderer validates CSP nonce', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.bridge_page import render_bridge_page_html
try:
render_bridge_page_html('bad" nonce', {"value": "https://example.com/"})
result = {"raised": False}
except ValueError as error:
result = {"raised": True, "message": str(error)}
print(json.dumps(result, sort_keys=True))
`)
assert.equal(parsed.raised, true)
assert.equal(parsed.message, 'INVALID_CSP_NONCE')
})
test('python fallback bridge page assets match javascript bridge assets', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.bridge_page_assets import BRIDGE_PAGE_SCRIPT, BRIDGE_PAGE_STYLE
print(json.dumps({
"script": BRIDGE_PAGE_SCRIPT,
"style": BRIDGE_PAGE_STYLE,
}, sort_keys=True))
`)
assert.equal(parsed.style, bridgePageStyle)
assert.equal(parsed.script, bridgePageScript)
})
test('python fallback bridge page reports renderer nonce failures over HTTP', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.server_factory import create_server
import stackprism_bridge_lib.bridge_page as bridge_page
import stackprism_bridge_lib.protocol as protocol
import threading
import urllib.error
import urllib.request
server, ready = create_server(0, env={"STACKPRISM_BRIDGE_NO_OPEN": "1"})
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
payload = json.dumps(${JSON.stringify(request)}).encode("utf-8")
create_request = urllib.request.Request(
ready["baseUrl"] + "/v1/captures",
data=payload,
headers={"Authorization": "Bearer " + ready["apiToken"], "Content-Type": "application/json"},
method="POST",
)
created = json.loads(urllib.request.urlopen(create_request, timeout=5).read().decode("utf-8"))
bridge_page.new_csp_nonce = lambda: 'bad" nonce'
try:
urllib.request.urlopen(created["bridgeUrl"], timeout=5)
first = {"status": 200}
except urllib.error.HTTPError as error:
first = {"status": error.code, "body": json.loads(error.read().decode("utf-8"))}
bridge_page.new_csp_nonce = protocol.new_csp_nonce
retry = urllib.request.urlopen(created["bridgeUrl"], timeout=5)
result = {"first": first, "retry": {"status": retry.status, "content_type": retry.headers.get("content-type"), "body_prefix": retry.read(32).decode("utf-8")}}
finally:
server.shutdown()
server.server_close()
print(json.dumps(result, sort_keys=True))
`)
assert.equal(parsed.first.status, 500)
assert.equal(parsed.first.body.error.code, 'BRIDGE_PAGE_RENDER_FAILED')
assert.equal(parsed.retry.status, 200)
assert.match(parsed.retry.content_type, /^text\/html; charset=utf-8\b/)
assert.match(parsed.retry.body_prefix, /^<!doctype html>/)
})
test('python fallback validates documented identifier fixtures', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.protocol import valid_id
identifiers = ${JSON.stringify(identifiers)}
results = {}
for kind, examples in identifiers.items():
results[kind] = {
"valid": [valid_id(kind, value) for value in examples["valid"]],
"invalid": [valid_id(kind, value) for value in examples["invalid"]],
}
print(json.dumps(results, sort_keys=True))
`)
for (const [kind, results] of Object.entries(parsed)) {
assert.deepEqual(
results.valid,
identifiers[kind].valid.map(() => true),
`${kind} valid fixtures should pass`
)
assert.deepEqual(
results.invalid,
identifiers[kind].invalid.map(() => false),
`${kind} invalid fixtures should fail`
)
}
})
test('python fallback open-browser helper validates env and URL before spawning', () => {
const parsed = pythonOneShot(`
import stackprism_bridge_lib.open_browser as open_browser_module
from stackprism_bridge_lib.open_browser import open_browser, windows_command_candidates
def exploding_popen(*_args, **_kwargs):
raise RuntimeError("/Users/example/secret-browser failed")
checks = {
"nul_env": open_browser("http://127.0.0.1:1/bridge", {"STACKPRISM_BROWSER_OPEN_COMMAND": "bad\\0cmd"}),
"nul_json_args": open_browser(
"http://127.0.0.1:1/bridge",
{"STACKPRISM_BROWSER_OPEN_COMMAND": "python3", "STACKPRISM_BROWSER_OPEN_ARGS_JSON": json.dumps(["bad\\0arg"])},
),
"invalid_url": open_browser("http://127.0.0.1:1/bridge\\nnext", {"STACKPRISM_BRIDGE_NO_OPEN": "1"}),
"credential_url": open_browser("http://user:pass@127.0.0.1:1/bridge", {"STACKPRISM_BRIDGE_NO_OPEN": "1"}),
"invalid_scheme": open_browser("file:///tmp/stackprism.html", {"STACKPRISM_BRIDGE_NO_OPEN": "1"}),
"missing_command": open_browser("http://127.0.0.1:1/bridge", {"STACKPRISM_BROWSER_OPEN_COMMAND": "/definitely/missing/stackprism-browser"}),
"invalid_timeout": open_browser("http://127.0.0.1:1/bridge", {"STACKPRISM_BROWSER_OPEN_COMMAND": "python3", "STACKPRISM_BROWSER_OPEN_TIMEOUT_MS": "30001"}),
"open_failed": open_browser(
"http://127.0.0.1:1/bridge",
{"STACKPRISM_BROWSER_OPEN_COMMAND": "python3", "STACKPRISM_BROWSER_OPEN_ARGS_JSON": json.dumps(["-c", "import sys; sys.exit(7)"]), "STACKPRISM_BROWSER_OPEN_TIMEOUT_MS": "1000"},
),
"windows_candidates": windows_command_candidates(r"C:\\Program Files\\Browser\\browser", {"PATHEXT": ".EXE;.CMD"}),
}
open_browser_module.subprocess.Popen = exploding_popen
checks["spawn_failed"] = open_browser("http://127.0.0.1:1/bridge", {"STACKPRISM_BROWSER_OPEN_COMMAND": "python3"})
print(json.dumps({name: result for name, result in checks.items()}, sort_keys=True))
`)
assert.deepEqual(parsed.nul_env, [false, { reason: 'BRIDGE_INVALID_ENV', message: 'Browser open environment contains NUL.' }])
assert.deepEqual(parsed.nul_json_args, [false, { reason: 'BRIDGE_INVALID_ENV', message: 'Browser open environment contains NUL.' }])
assert.deepEqual(parsed.invalid_url, [false, { reason: 'invalid_url' }])
assert.deepEqual(parsed.credential_url, [false, { reason: 'invalid_url' }])
assert.deepEqual(parsed.invalid_scheme, [false, { reason: 'invalid_scheme', allowed: ['http', 'https'] }])
assert.deepEqual(parsed.missing_command, [false, { reason: 'command_not_found' }])
assert.deepEqual(parsed.invalid_timeout, [false, { reason: 'invalid_open_timeout' }])
assert.deepEqual(parsed.windows_candidates, ['C:\\Program Files\\Browser\\browser.EXE', 'C:\\Program Files\\Browser\\browser.CMD'])
assert.deepEqual(parsed.open_failed, [false, { reason: 'open_failed', exitCode: 7 }])
assert.deepEqual(parsed.spawn_failed, [false, { reason: 'spawn_failed' }])
})
test('python fallback open-browser helper appends bridge URL as one argv', () => {
const tempDir = mkdtempSync(join(tmpdir(), 'stackprism-open-'))
const argvPath = join(tempDir, 'argv.json')
const bridgeUrl = 'http://127.0.0.1:17370/bridge?session=s&capture=c&nonce=n value"quote;&cmd=$(echo bad)'
const script = 'import json, sys; open(sys.argv[1], "w").write(json.dumps(sys.argv[2:]))'
try {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.open_browser import open_browser
print(json.dumps(open_browser(${JSON.stringify(bridgeUrl)}, {
"STACKPRISM_BROWSER_OPEN_COMMAND": "python3",
"STACKPRISM_BROWSER_OPEN_ARGS_JSON": json.dumps(["-c", ${JSON.stringify(script)}, ${JSON.stringify(argvPath)}]),
})))
`)
assert.deepEqual(parsed, [true, {}])
waitForFileSync(argvPath)
assert.deepEqual(JSON.parse(readFileSync(argvPath, 'utf8')), [bridgeUrl])
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
})
test('python fallback open-browser helper selects platform default opener without shell parsing', () => {
const parsed = pythonOneShot(`
from stackprism_bridge_lib.open_browser import resolve_browser_open_command
checks = {
"darwin": resolve_browser_open_command({}, "Darwin"),
"windows": resolve_browser_open_command({}, "Windows"),
"linux": resolve_browser_open_command({}, "Linux"),
"custom": resolve_browser_open_command({
"STACKPRISM_BROWSER_OPEN_COMMAND": "/usr/bin/google-chrome",
"STACKPRISM_BROWSER_OPEN_ARGS_JSON": json.dumps(["--profile-directory=Default"]),
}, "Linux"),
"windows_custom": resolve_browser_open_command({
"STACKPRISM_BROWSER_OPEN_COMMAND": r"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"STACKPRISM_BROWSER_OPEN_ARGS_JSON": json.dumps(["--profile-directory=Profile 2"]),
}, "Windows"),
"linux_firefox": resolve_browser_open_command({
"STACKPRISM_BROWSER_OPEN_COMMAND": "firefox",
"STACKPRISM_BROWSER_OPEN_ARGS_JSON": json.dumps(["-P", "stackprism-dev"]),
}, "Linux"),
}
print(json.dumps(checks, sort_keys=True))
`)
assert.deepEqual(parsed.darwin, [true, { command: 'open', args: [] }])
assert.deepEqual(parsed.windows, [true, { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler'] }])
assert.deepEqual(parsed.linux, [true, { command: 'xdg-open', args: [] }])
assert.deepEqual(parsed.custom, [true, { command: '/usr/bin/google-chrome', args: ['--profile-directory=Default'] }])
assert.deepEqual(parsed.windows_custom, [
true,
{ command: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', args: ['--profile-directory=Profile 2'] }
])
assert.deepEqual(parsed.linux_firefox, [true, { command: 'firefox', args: ['-P', 'stackprism-dev'] }])
})
test('python fallback bridge page has CSP nonce and script-safe config', async () => {
const { child, ready } = await startPythonBridge()
try {
const created = await createCapture(ready)
const { response, html } = await loadBridgePage(created.body.bridgeUrl)
const csp = response.headers.get('content-security-policy')
const cspNonce = csp.match(/script-src 'nonce-([^']+)'/)?.[1]
assert.equal(response.status, 200)
assert.equal(response.headers.get('cache-control'), 'no-store')
assert.equal(response.headers.get('referrer-policy'), 'no-referrer')
assert.equal(response.headers.get('x-content-type-options'), 'nosniff')
assert.equal(response.headers.get('cross-origin-opener-policy'), 'same-origin')
assert.equal(response.headers.get('permissions-policy'), 'camera=(), microphone=(), geolocation=(), payment=(), usb=()')
assert.equal(csp.includes('unsafe-inline'), false)
assert.match(csp, /default-src 'none'/)
assert.match(csp, /frame-ancestors 'none'/)
assert.match(csp, /connect-src 'self'/)
assert.match(csp, /img-src data: blob:/)
assert.doesNotMatch(csp, /img-src[^;]*'self'/)
assert.match(csp, /base-uri 'none'/)
assert.match(csp, /form-action 'none'/)
assert.ok(cspNonce)
assert.match(csp, new RegExp(`style-src 'nonce-${cspNonce}'`))
assert.equal(response.headers.get('x-frame-options'), 'DENY')
assert.match(html, /meta name="stackprism-agent-bridge" content="1"/)
assert.match(html, /<link rel="icon" href="data:image\/svg\+xml,%3Csvg/)
assert.match(html, /id="bridgeCard" class="bridge-card" data-status="waiting_extension" aria-labelledby="bridge-title" tabindex="-1"/)
assert.match(html, /id="progressBar"/)
assert.match(html, /id="targetUrl" class="target-url" title="" target="_blank" rel="noopener noreferrer" aria-disabled="true"/)
assert.match(
html,
/id="openTargetUrl" class="preview-button target-open-link" target="_blank" rel="noopener noreferrer" aria-disabled="true" tabindex="-1"/
)
assert.match(html, /id="targetScreenshot"/)
assert.match(html, /id="targetScreenshot" alt=""/)
assert.match(html, /id="screenshotMeta"/)
assert.match(html, /id="screenshotDownload"/)
assert.match(html, /id="copyScreenshot"/)
assert.match(html, /id="downloadProfile"/)
assert.match(html, /class="preview-button profile-download-button"/)
assert.match(html, /id="copyAllInfo"/)
assert.match(html, /id="copyStatus"/)
assert.match(html, /id="modalCopyStatus"/)
assert.match(html, /id="screenshotTileValue"/)
assert.match(html, /id="screenshotStateBadge" class="state-chip" data-state="pending"/)
assert.match(html, /id="screenshotEmpty"/)
assert.match(html, /id="stepSummary" class="step-summary" role="status" aria-live="polite"/)
assert.match(html, /id="toggleSteps" class="flow-toggle" type="button" aria-controls="captureSteps" aria-expanded="false"/)
assert.match(html, /<ol id="captureSteps" class="steps" aria-label="采集步骤" role="list">/)
assert.match(html, /data-phase="bridge_connected" aria-current="step"/)
assert.match(html, /id="profileContentSection"/)
assert.match(html, /id="profileContentGrid"/)
assert.match(html, /id="screenshotModal"/)
assert.match(html, /id="modalDownload"/)
assert.match(html, /id="modalCopyScreenshot"/)
assert.match(html, /id="modalClose"/)
assert.match(html, /id="modalScreenshot" class="modal-image" alt=""/)
assert.match(html, /addEventListener\('click',openScreenshot\)/)
assert.match(html, /navigator\.clipboard\.writeText/)
assert.match(html, /new ClipboardItem/)
assert.match(html, /showCopyStatus\('已复制全部信息。'\)/)
assert.match(html, /flashCopyButton\('已复制'\)/)
assert.match(html, /const clipboardScreenshotBlob=async/)
assert.match(html, /createImageBitmap\(blob\)/)
assert.match(html, /'image\/png':blob/)
assert.match(html, /复制截图失败:浏览器未允许写入剪切板,或截图格式无法转换。/)
assert.match(html, /截图预览无法加载/)
assert.match(html, /截图预览无法加载,可重新采集或下载 Profile 查看图片链接。/)
assert.match(html, /downloadBlob\(await fetchScreenshotBlob\(\),screenshotFilename\(\)\)/)
assert.match(html, /currentProfileBlob=null,currentProfileFetchPromise=null/)
assert.match(html, /const ensureProfileCached=\(\)=>/)
assert.match(html, /downloadBlob\(await ensureProfileCached\(\),profileFilename\(\)\)/)
assert.match(html, /if\(status==='completed'\)ensureProfileCached\(\)\.catch\(\(\)=>\{\}\)/)
assert.match(html, /\/profile-download/)
assert.doesNotMatch(html, /config\.captureId\+'\/profile'/)
assert.match(
html,
/button:not\(:disabled\),a\[href\],input:not\(:disabled\),select:not\(:disabled\),textarea:not\(:disabled\),\[tabindex\]:not\(\[tabindex="-1"\]\)/
)
assert.match(html, /currentScreenshot\?\.mimeType==='image\/png'\?'png'/)
assert.match(html, /currentScreenshot\?\.mimeType==='image\/webp'\?'webp'/)
assert.match(html, /currentScreenshotObjectUrl=URL\.createObjectURL\(blob\)/)
assert.match(html, /el\.targetScreenshot\.alt='目标页面截图预览'/)
assert.match(html, /el\.targetScreenshot\.alt=''/)
assert.match(html, /color-scheme:light dark/)
assert.match(html, /@media \(prefers-color-scheme:dark\)/)
assert.match(html, /class="result-grid"/)
assert.match(html, /class="summary-grid"/)
assert.match(html, /class="screenshot-panel"/)
assert.match(html, /border-radius:16px/)
assert.match(html, /\.summary-grid\{display:grid;grid-template-columns:repeat\(4,minmax\(0,1fr\)\)/)
assert.match(html, /grid-template-columns:repeat\(auto-fit,minmax\(min\(100%,300px\),1fr\)\)/)
assert.match(html, /\.target-copy\{min-width:0\}/)
assert.match(html, /\.target-url\{margin:0;display:-webkit-box;overflow:hidden;overflow-wrap:anywhere;word-break:break-word/)
assert.match(html, /\.target-actions\{display:flex;min-width:0;flex-wrap:wrap;gap:10px;justify-content:flex-end\}/)
assert.match(
html,
/\.target-open-link\{min-width:132px;display:inline-flex;align-items:center;justify-content:center;text-decoration:none\}/
)
assert.match(html, /\.content-card \*\{min-width:0;max-width:100%;overflow-wrap:anywhere;word-break:break-word\}/)
assert.match(html, /\.content-card\{min-width:0;min-height:88px;padding:10px;overflow:hidden/)
assert.match(html, /\.content-card ul\{display:grid;min-width:0;gap:3px/)
assert.match(html, /\.content-card li\{min-width:0;line-height:1\.38;white-space:normal\}/)
assert.doesNotMatch(html, /@media \(max-width:980px\)\{[^}]*\.content-grid/)
assert.doesNotMatch(html, /@media \(max-width:760px\)\{[^}]*\.content-grid/)
assert.match(html, /--sp-neutral-line:#e5e9ee/)
assert.match(html, /grid-template-columns:minmax\(0,1\.22fr\) minmax\(320px,\.82fr\)/)
assert.match(html, /class="summary-handoff" aria-label="摘要包含"/)
assert.match(html, /摘要包含/)
assert.match(html, /技术栈/)
assert.match(html, /首屏结构/)
assert.match(html, /height:clamp\(190px,14vw,230px\)/)
assert.match(html, /object-fit:cover/)
assert.match(html, /object-position:top center/)
assert.match(html, /-webkit-line-clamp:2/)
assert.match(html, /\.target-url\[href\]\{cursor:pointer\}/)
assert.match(html, /\.target-url\[href\]:hover\{text-decoration:underline/)
assert.match(html, /targetHrefFor=value=>/)
assert.match(html, /url\.pathname\.includes\('\[redacted\]'\)/)
assert.match(html, /url\.search\.includes\('\[redacted\]'\)/)
assert.match(html, /setTargetUrl\(targetText\)/)
assert.match(html, /setTargetLink\(el\.openTargetUrl,targetHref\)/)
assert.match(html, /node\.removeAttribute\('aria-disabled'\)/)
assert.match(html, /\.bridge-header\{position:relative;display:block/)
assert.match(html, /\.summary-handoff\{display:none\}/)
assert.match(html, /class="target-actions"/)
assert.match(html, /class="preview-button primary target-copy-button"/)
assert.match(html, /class="flow-panel"/)
assert.match(html, /grid-template-columns:repeat\(8,minmax\(0,1fr\)\)/)
assert.match(html, /grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/)
assert.match(html, /\.bridge-card\[data-status="completed"\] \.status-panel\{display:none\}/)
assert.match(html, /\.bridge-card\[data-status="completed"\]:not\(\[data-steps-open="true"\]\) \.steps\{display:none\}/)
assert.match(html, /\.state-chip\[data-state="ready"\]/)
assert.match(html, /setScreenshotState\('截图可用','ready'\)/)
assert.match(html, /setStepsOpen\(false\)/)
assert.match(html, /addEventListener\('click',\(\)=>setStepsOpen\(!stepsOpen,true\)\)/)
assert.match(
html,
/\.preview-button:disabled,.modal-close:disabled,.preview-button\[aria-disabled="true"\]\{cursor:not-allowed;opacity:1;background:#f7fbfa/
)
assert.match(html, /setCopyStatus\(modalOpen\(\)\?el\.modalCopyStatus:el\.copyStatus,value,type\)/)
assert.match(html, /const restore=el\.screenshotFrame\.disabled\?el\.bridgeCard:el\.screenshotFrame/)
assert.match(html, /if\(current\|\|failedCurrent\)step\.setAttribute\('aria-current','step'\)/)
assert.match(html, /else step\.removeAttribute\('aria-current'\)/)
assert.match(html, /!el\.screenshotModal\.contains\(document\.activeElement\)/)
assert.match(html, /step\.classList\.toggle\('failed',failedCurrent\)/)
assert.match(html, /\.step\.failed/)
assert.match(html, /\.bridge-card\[data-status="failed"\] \.progress span/)
assert.match(html, /\.copy-status\[data-state="error"\]\{background:#2a1211;border-color:#7f1d1d;color:#fca5a5\}/)
assert.match(html, /color:#fca5a5/)
assert.match(html, /color:#fbbf24/)
assert.match(html, /disconnected:'连接已关闭'/)
assert.match(html, /const targetText=preview\.targetUrl\|\|config\.targetUrl\|\|'等待读取目标网址'/)
assert.match(html, /el\.targetUrl\.title=targetText/)
assert.match(html, /本机 bridge 服务已关闭,当前页面无法继续读取状态。/)
assert.doesNotMatch(html, /Bridge status unavailable/)
assert.match(html, /data-phase="profiling_experience"/)
assert.match(html, /本机通道/)
assert.match(html, /连接本机 Agent 与当前浏览器 profile,展示本次采集结果。/)
assert.match(html, /采集目标/)
assert.match(html, /id="targetHelper" class="target-helper"/)
assert.match(html, /采集完成后可复制给本机 Coding Agent 使用。/)
assert.match(html, /已生成 Agent 可读摘要,可复制给本机 Coding Agent 使用。/)
assert.match(html, /面向复刻任务整理技术栈、视觉结构、交互路径与资产线索。/)
assert.match(html, /复刻重点/)
assert.match(html, /先看 Agent 可读内容/)
assert.match(html, /本页只服务当前一次采集/)
assert.match(html, /摘要不含 token、nonce、raw JSON 或截图 data URL/)
assert.match(html, /Agent 可读内容/)
assert.match(html, /完整 Profile 可在本页完成后下载/)
assert.match(html, new RegExp(`id="stackprism-agent-bridge-config" type="application/json" nonce="${cspNonce}"`))
assert.match(html, new RegExp(`<style nonce="${cspNonce}"`))
assert.match(html, new RegExp(`<script nonce="${cspNonce}"`))
assert.match(html, /fetch\('\/v1\/captures\/'\+config\.captureId/)
assert.match(html, /textContent=value/)
assert.match(html, /"bridgeToken":"spbt_[A-Za-z0-9_-]{43}"/)
assert.match(html, /"targetUrl":"https:\/\/93\.184\.216\.34\/app\?\[redacted\]"/)
assert.doesNotMatch(html, /"targetHref":/)
const second = await readJson(await fetch(created.body.bridgeUrl))
assert.equal(second.status, 409)
assert.equal(second.body.error.code, 'INVALID_REQUEST')
assert.doesNotMatch(JSON.stringify(second.body), /spbt_[A-Za-z0-9_-]{43}/)
} finally {
child.kill('SIGTERM')
await once(child, 'exit')
}
})
test('python fallback bridge page rejects cross-site navigation before token render', async () => {
const { child, ready } = await startPythonBridge()
try {
const created = await createCapture(ready)
const blockedReferer = await fetch(created.body.bridgeUrl, { headers: { Referer: 'https://attacker.example/page' } })
const blockedRefererText = await blockedReferer.text()
assert.equal(blockedReferer.status, 403)
assert.match(blockedRefererText, /ORIGIN_NOT_ALLOWED/)
assert.doesNotMatch(blockedRefererText, /spbt_[A-Za-z0-9_-]{43}/)
const blockedFetchSite = await fetch(created.body.bridgeUrl, { headers: { 'Sec-Fetch-Site': 'cross-site' } })
const blockedFetchSiteText = await blockedFetchSite.text()
assert.equal(blockedFetchSite.status, 403)
assert.match(blockedFetchSiteText, /ORIGIN_NOT_ALLOWED/)
assert.doesNotMatch(blockedFetchSiteText, /spbt_[A-Za-z0-9_-]{43}/)
const firstAllowed = await fetch(created.body.bridgeUrl)
const firstAllowedText = await firstAllowed.text()
assert.equal(firstAllowed.status, 200)
assert.match(firstAllowedText, /"bridgeToken":"spbt_[A-Za-z0-9_-]{43}"/)
const secondAllowed = await readJson(await fetch(created.body.bridgeUrl))
assert.equal(secondAllowed.status, 409)
assert.equal(secondAllowed.body.error.code, 'INVALID_REQUEST')
assert.doesNotMatch(JSON.stringify(secondAllowed.body), /spbt_[A-Za-z0-9_-]{43}/)
} finally {
child.kill('SIGTERM')
await once(child, 'exit')
}
})
test('python fallback bridge page does not reflect hostile query fragments or error messages', () => {
const parsed = pythonOneShot(`
import re
import threading
import urllib.error
import urllib.parse