@sparkelf/dsh-mobile-bridge-server 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/QR_SCANNER_LICENSE +21 -0
- package/THIRD_PARTY_NOTICES.md +12 -0
- package/ZXING_CPP_LICENSE +201 -0
- package/ZXING_WASM_LICENSE +21 -0
- package/package.json +20 -4
- package/src/phone.ts +566 -73
- package/src/server.ts +106 -8
- package/src/wechat.spec.ts +0 -38
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SparkElf contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 Nimiq, danimoh
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/THIRD_PARTY_NOTICES.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Third-party notices
|
|
2
2
|
|
|
3
|
+
## qr-scanner
|
|
4
|
+
|
|
5
|
+
Camera scanning uses qr-scanner 1.4.2 by Nimiq. qr-scanner is distributed under the MIT License; the complete license text is included in `QR_SCANNER_LICENSE` and is deployed with the runtime file.
|
|
6
|
+
|
|
7
|
+
## zxing-wasm
|
|
8
|
+
|
|
9
|
+
Non-native browser profiles use zxing-wasm 3.1.3 by Ze-Zheng Wu. zxing-wasm is distributed under the MIT License; the complete license text is included in `ZXING_WASM_LICENSE`.
|
|
10
|
+
|
|
11
|
+
## ZXing-C++
|
|
12
|
+
|
|
13
|
+
zxing-wasm embeds the ZXing-C++ reader. ZXing-C++ is distributed under the Apache License 2.0; the complete license text is included in `ZXING_CPP_LICENSE`.
|
|
14
|
+
|
|
3
15
|
## DeepSeek logo
|
|
4
16
|
|
|
5
17
|
The DeepSeek logo in `src/deepseek-logo.svg` is copied from DeepSeek Harness and remains Copyright (c) 2026 DeepSeek. It is distributed under the MIT License included below.
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright {yyyy} {name of copyright owner}
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Ze-Zheng Wu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,16 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sparkelf/dsh-mobile-bridge-server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Multi-user bridge server connecting mobile browsers to local DeepSeek Harness instances through outbound tunnels.",
|
|
6
|
+
"license": "MIT",
|
|
6
7
|
"main": "src/index.ts",
|
|
7
8
|
"types": "src/index.ts",
|
|
8
9
|
"bin": {
|
|
9
10
|
"dsh-mobile-bridge-server": "src/index.ts"
|
|
10
11
|
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src/deepseek-logo.svg",
|
|
14
|
+
"src/index.ts",
|
|
15
|
+
"src/phone.ts",
|
|
16
|
+
"src/server.ts",
|
|
17
|
+
"src/store.ts",
|
|
18
|
+
"src/wechat-scheme.ts",
|
|
19
|
+
"src/wechat.ts",
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"QR_SCANNER_LICENSE",
|
|
22
|
+
"THIRD_PARTY_NOTICES.md",
|
|
23
|
+
"ZXING_CPP_LICENSE",
|
|
24
|
+
"ZXING_WASM_LICENSE"
|
|
25
|
+
],
|
|
11
26
|
"dependencies": {
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"ws": "^8.18.0"
|
|
27
|
+
"nodemailer": "9.0.5",
|
|
28
|
+
"qr-scanner": "1.4.2",
|
|
29
|
+
"ws": "^8.18.0",
|
|
30
|
+
"zxing-wasm": "3.1.3"
|
|
15
31
|
}
|
|
16
32
|
}
|
package/src/phone.ts
CHANGED
|
@@ -51,6 +51,18 @@ self.addEventListener('activate', event => { event.waitUntil(self.clients.claim(
|
|
|
51
51
|
self.addEventListener('message', event => {
|
|
52
52
|
if (!event.data) return
|
|
53
53
|
if (event.data.type === 'pair') {
|
|
54
|
+
if (wsValue) wsValue.close(1000, 'pair replaced')
|
|
55
|
+
wsValue = null
|
|
56
|
+
wsPromise = null
|
|
57
|
+
if (!revoked) {
|
|
58
|
+
const replacedError = new Error('pair replaced')
|
|
59
|
+
for (const entry of pending.values()) {
|
|
60
|
+
if (entry.websocketPort) { entry.websocketPort.postMessage({ kind: 'websocket-error', message: replacedError.message }); entry.websocketPort.close() }
|
|
61
|
+
else if (entry.controller) void entry.controller.abort(replacedError)
|
|
62
|
+
else entry.reject(replacedError)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
pending.clear()
|
|
54
66
|
pairValue = event.data.pair
|
|
55
67
|
keyPromise = null
|
|
56
68
|
revoked = false
|
|
@@ -62,6 +74,11 @@ self.addEventListener('message', event => {
|
|
|
62
74
|
}
|
|
63
75
|
if (event.data.type === 'application-websocket') {
|
|
64
76
|
const port = event.ports[0]
|
|
77
|
+
if (revoked) {
|
|
78
|
+
port.start()
|
|
79
|
+
pending.set('q' + (++counter), { websocketPort: port })
|
|
80
|
+
return
|
|
81
|
+
}
|
|
65
82
|
event.waitUntil(openApplicationSocket(event.data, port).catch(error => {
|
|
66
83
|
console.error('[dsh-mobile-bridge] application websocket setup failed', error)
|
|
67
84
|
port.postMessage({ kind: 'websocket-error', message: error.message })
|
|
@@ -70,6 +87,7 @@ self.addEventListener('message', event => {
|
|
|
70
87
|
})
|
|
71
88
|
|
|
72
89
|
let wsPromise = null
|
|
90
|
+
let wsValue = null
|
|
73
91
|
let counter = 0
|
|
74
92
|
const pending = new Map()
|
|
75
93
|
|
|
@@ -77,36 +95,41 @@ function wsReady() {
|
|
|
77
95
|
if (wsPromise) return wsPromise
|
|
78
96
|
wsPromise = new Promise((resolve, reject) => {
|
|
79
97
|
const ws = new WebSocket(location.origin.replace(/^http/, 'ws') + '/ws/client')
|
|
98
|
+
wsValue = ws
|
|
80
99
|
ws.onopen = () => resolve(ws)
|
|
81
100
|
ws.onerror = () => {
|
|
82
|
-
wsPromise = null
|
|
83
101
|
const error = new Error('bridge socket failed')
|
|
84
102
|
console.error('[dsh-mobile-bridge] bridge socket failed', error)
|
|
85
103
|
reject(error)
|
|
86
104
|
}
|
|
87
105
|
ws.onclose = event => {
|
|
106
|
+
const isCurrent = wsValue === ws
|
|
107
|
+
if (!isCurrent) return
|
|
108
|
+
wsValue = null
|
|
88
109
|
wsPromise = null
|
|
89
110
|
const error = new Error('bridge socket closed')
|
|
111
|
+
// 普通传输断开结算请求并触发重连;4003 定向下线保留现有请求为静默终态,直到用户离开 modal。
|
|
90
112
|
const settlePending = () => {
|
|
91
113
|
for (const entry of pending.values()) {
|
|
92
114
|
if (entry.websocketPort) {
|
|
93
|
-
|
|
115
|
+
entry.websocketPort.postMessage({ kind: 'websocket-error', message: error.message })
|
|
94
116
|
entry.websocketPort.close()
|
|
95
|
-
} else if (entry.controller)
|
|
96
|
-
|
|
97
|
-
else entry.reject(error)
|
|
117
|
+
} else if (entry.controller) {
|
|
118
|
+
void entry.controller.abort(error).catch(streamError => { console.error('[dsh-mobile-bridge] event stream settlement failed', streamError) })
|
|
119
|
+
} else entry.reject(error)
|
|
98
120
|
}
|
|
99
121
|
pending.clear()
|
|
100
122
|
}
|
|
101
|
-
if (event.code === 4003) {
|
|
123
|
+
if (event.code === 4003 && isCurrent) {
|
|
102
124
|
pairValue = null
|
|
103
125
|
keyPromise = null
|
|
104
126
|
revoked = true
|
|
105
127
|
void caches.open(PAIR_CACHE).then(cache => cache.put(PAIR_CACHE_KEY, new Response(JSON.stringify({ revoked: true }), { headers: { 'content-type': 'application/json' } }))).catch(error => { console.error('[dsh-mobile-bridge] revoked pair persistence failed', error) })
|
|
106
128
|
void self.clients.matchAll({ type: 'window' })
|
|
107
|
-
.then(clients =>
|
|
108
|
-
|
|
109
|
-
|
|
129
|
+
.then(clients => {
|
|
130
|
+
for (const client of clients) client.postMessage({ type: 'dsh-mobile-bridge:revoked' })
|
|
131
|
+
})
|
|
132
|
+
.catch(error => { console.error('[dsh-mobile-bridge] revoked client notification failed', error) })
|
|
110
133
|
return
|
|
111
134
|
}
|
|
112
135
|
settlePending()
|
|
@@ -190,7 +213,10 @@ self.addEventListener('fetch', event => {
|
|
|
190
213
|
console.error('[dsh-mobile-bridge] persisted pair state failed', error)
|
|
191
214
|
return new Response('Mobile Bridge pair state failed', { status: 500 })
|
|
192
215
|
}
|
|
193
|
-
if (revoked)
|
|
216
|
+
if (revoked) {
|
|
217
|
+
if (event.request.mode === 'navigate') return revokedResponse()
|
|
218
|
+
return new Promise(() => {})
|
|
219
|
+
}
|
|
194
220
|
if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
|
|
195
221
|
const key = await keyPromise
|
|
196
222
|
const request = event.request
|
|
@@ -329,20 +355,20 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
329
355
|
var $ = function (id) { return document.getElementById(id) }
|
|
330
356
|
var COPY = {
|
|
331
357
|
zh: {
|
|
332
|
-
preferences: '显示偏好', title: '移动连接', scanFirst: '扫描桌面端显示的配对二维码', openScanner: '打开相机扫码', scannerTitle: '扫描配对二维码', closeScanner: '关闭相机', cameraStarting: '正在打开相机', cameraReady: '将二维码放入扫描框', cameraUnavailable: '无法使用相机,请检查浏览器相机权限。', invalidPairQr: '请扫描桌面端显示的 Mobile Bridge 配对二维码。', email: '邮箱', emailPlaceholder: 'name@example.com',
|
|
358
|
+
preferences: '显示偏好', title: '移动连接', scanFirst: '扫描桌面端显示的配对二维码', openScanner: '打开相机扫码', scannerTitle: '扫描配对二维码', closeScanner: '关闭相机', cameraStarting: '正在打开相机', cameraReady: '将二维码放入扫描框', cameraFocused: '正在连续对焦,请将二维码放入扫描框', cameraAdjusting: '正在自动调焦', cameraLocked: '已锁定清晰焦点,请将二维码放入扫描框', qrDetected: '已识别,正在连接', cameraUnavailable: '无法使用相机,请检查浏览器相机权限。', invalidPairQr: '请扫描桌面端显示的 Mobile Bridge 配对二维码。', email: '邮箱', emailPlaceholder: 'name@example.com',
|
|
333
359
|
code: '验证码', codePlaceholder: '6 位验证码', send: '发送', sending: '发送中', sent: '验证码已发送',
|
|
334
360
|
pairingCode: '配对码', pairingPlaceholder: '6 位字符', connect: '登录并连接', connecting: '正在连接', light: '浅色', dark: '深色',
|
|
335
361
|
ownerCode: '桌面所有者邮箱收到验证码,请输入', passphrase: '输入桌面端设置的加密口令', cancelled: '已取消',
|
|
336
|
-
serviceWorkerUnsupported: '此浏览器不支持 Service Worker。', serviceWorkerTimeout: '移动连接初始化超时,请重新扫描最新二维码。',
|
|
362
|
+
serviceWorkerUnsupported: '此浏览器不支持 Service Worker。', serviceWorkerTimeout: '移动连接初始化超时,请重新扫描最新二维码。', serviceWorkerUpdateFailed: '移动连接更新失败,请刷新页面后重新扫描。',
|
|
337
363
|
unknownPair: '配对码无效或桌面端已离线,请扫描最新二维码。', expiredPair: '配对码已过期,请扫描最新二维码。',
|
|
338
364
|
usedPair: '配对码已使用,请扫描最新二维码。', invalidCode: '验证码无效或已过期。'
|
|
339
365
|
},
|
|
340
366
|
en: {
|
|
341
|
-
preferences: 'Display preferences', title: 'Mobile connection', scanFirst: 'Scan the pairing QR shown on the desktop', openScanner: 'Open camera scanner', scannerTitle: 'Scan pairing QR', closeScanner: 'Close camera', cameraStarting: 'Opening camera', cameraReady: 'Place the QR code inside the frame', cameraUnavailable: 'The camera is unavailable. Check this browser’s camera permission.', invalidPairQr: 'Scan the Mobile Bridge pairing QR shown on the desktop.', email: 'Email', emailPlaceholder: 'name@example.com',
|
|
367
|
+
preferences: 'Display preferences', title: 'Mobile connection', scanFirst: 'Scan the pairing QR shown on the desktop', openScanner: 'Open camera scanner', scannerTitle: 'Scan pairing QR', closeScanner: 'Close camera', cameraStarting: 'Opening camera', cameraReady: 'Place the QR code inside the frame', cameraFocused: 'Continuous focus active. Place the QR code inside the frame', cameraAdjusting: 'Adjusting focus automatically', cameraLocked: 'Sharpest focus locked. Place the QR code inside the frame', qrDetected: 'QR recognized. Connecting', cameraUnavailable: 'The camera is unavailable. Check this browser’s camera permission.', invalidPairQr: 'Scan the Mobile Bridge pairing QR shown on the desktop.', email: 'Email', emailPlaceholder: 'name@example.com',
|
|
342
368
|
code: 'Verification code', codePlaceholder: '6-digit code', send: 'Send', sending: 'Sending', sent: 'Code sent',
|
|
343
369
|
pairingCode: 'Pairing code', pairingPlaceholder: '6 characters', connect: 'Sign in and connect', connecting: 'Connecting', light: 'Light', dark: 'Dark',
|
|
344
370
|
ownerCode: 'Enter the code sent to the desktop owner email', passphrase: 'Enter the passphrase configured on the desktop', cancelled: 'Cancelled',
|
|
345
|
-
serviceWorkerUnsupported: 'This browser does not support Service Workers.', serviceWorkerTimeout: 'Mobile connection setup timed out. Scan the latest QR code again.',
|
|
371
|
+
serviceWorkerUnsupported: 'This browser does not support Service Workers.', serviceWorkerTimeout: 'Mobile connection setup timed out. Scan the latest QR code again.', serviceWorkerUpdateFailed: 'Mobile connection update failed. Refresh the page and scan again.',
|
|
346
372
|
unknownPair: 'The pairing code is invalid or the desktop is offline. Scan the latest QR code.', expiredPair: 'The pairing code expired. Scan the latest QR code.',
|
|
347
373
|
usedPair: 'The pairing code was already used. Scan the latest QR code.', invalidCode: 'The verification code is invalid or expired.'
|
|
348
374
|
}
|
|
@@ -387,6 +413,7 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
387
413
|
if (message === 'invalid or expired code') return tr('invalidCode')
|
|
388
414
|
if (message === 'serviceWorkerUnsupported') return tr('serviceWorkerUnsupported')
|
|
389
415
|
if (message === 'serviceWorkerTimeout') return tr('serviceWorkerTimeout')
|
|
416
|
+
if (message === 'serviceWorkerUpdateFailed') return tr('serviceWorkerUpdateFailed')
|
|
390
417
|
if (message === 'cancelled') return tr('cancelled')
|
|
391
418
|
return message
|
|
392
419
|
}
|
|
@@ -417,32 +444,173 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
417
444
|
registration.active.postMessage({ type: 'pair', pair: pair }, [channel.port2])
|
|
418
445
|
})
|
|
419
446
|
}
|
|
447
|
+
function activateLatestWorker(registration) {
|
|
448
|
+
return registration.update().then(function () {
|
|
449
|
+
var worker = registration.installing || registration.waiting
|
|
450
|
+
if (!worker || worker.state === 'activated') return registration
|
|
451
|
+
return new Promise(function (resolve, reject) {
|
|
452
|
+
var timer = setTimeout(function () {
|
|
453
|
+
worker.removeEventListener('statechange', changed)
|
|
454
|
+
reject(new Error('serviceWorkerTimeout'))
|
|
455
|
+
}, 10000)
|
|
456
|
+
function changed() {
|
|
457
|
+
if (worker.state === 'activated') {
|
|
458
|
+
clearTimeout(timer)
|
|
459
|
+
worker.removeEventListener('statechange', changed)
|
|
460
|
+
resolve(registration)
|
|
461
|
+
} else if (worker.state === 'redundant') {
|
|
462
|
+
clearTimeout(timer)
|
|
463
|
+
worker.removeEventListener('statechange', changed)
|
|
464
|
+
reject(new Error('serviceWorkerUpdateFailed'))
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
worker.addEventListener('statechange', changed)
|
|
468
|
+
changed()
|
|
469
|
+
})
|
|
470
|
+
})
|
|
471
|
+
}
|
|
472
|
+
|
|
420
473
|
function registerSw(pair) {
|
|
421
474
|
if (!('serviceWorker' in navigator)) return Promise.reject(new Error('serviceWorkerUnsupported'))
|
|
422
|
-
return navigator.serviceWorker.register('/sw.js', { scope: '/' })
|
|
475
|
+
return navigator.serviceWorker.register('/sw.js', { scope: '/', updateViaCache: 'none' })
|
|
476
|
+
.then(activateLatestWorker)
|
|
423
477
|
.then(function () { return navigator.serviceWorker.ready })
|
|
424
478
|
.then(function (registration) { return persistPair(registration, pair) })
|
|
425
479
|
.then(waitForControl)
|
|
426
480
|
}
|
|
427
481
|
function navigateToHarness() {
|
|
428
|
-
|
|
429
|
-
|
|
482
|
+
var navigate = function () {
|
|
483
|
+
history.replaceState(null, '', '/')
|
|
484
|
+
location.assign('/')
|
|
485
|
+
}
|
|
486
|
+
if (document.readyState === 'loading') {
|
|
487
|
+
// 先提交 landing 的 DOM 生命周期,再在下一帧切换 Harness,避免两次顶层 navigation 相互取消。
|
|
488
|
+
document.addEventListener('DOMContentLoaded', function () { requestAnimationFrame(navigate) }, { once: true })
|
|
489
|
+
} else navigate()
|
|
430
490
|
}
|
|
431
491
|
|
|
492
|
+
var scannerInstance = null
|
|
493
|
+
var scannerSession = 0
|
|
432
494
|
var scannerStream = null
|
|
433
|
-
var
|
|
434
|
-
var
|
|
435
|
-
var
|
|
436
|
-
var
|
|
437
|
-
var
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
function
|
|
441
|
-
|
|
442
|
-
|
|
495
|
+
var scannerDecodeFrame = 0
|
|
496
|
+
var scannerDecodeUsesVideoCallback = false
|
|
497
|
+
var scannerDecodeBusy = false
|
|
498
|
+
var scannerDecodeFailed = false
|
|
499
|
+
var scannerLastDecodeAt = 0
|
|
500
|
+
var scannerDecodeCanvas = document.createElement('canvas')
|
|
501
|
+
var scannerScriptPromises = {}
|
|
502
|
+
var scannerWasmOverrides = { locateFile: function () { return '/bridge/zxing-reader.wasm' } }
|
|
503
|
+
var scannerResultTimer = 0
|
|
504
|
+
var scannerDiagnosticSocket = null
|
|
505
|
+
var scannerDiagnosticTimer = 0
|
|
506
|
+
var scannerAdjustmentTimer = 0
|
|
507
|
+
var scannerAnalysisCanvas = document.createElement('canvas')
|
|
508
|
+
var scannerAdjustmentIndex = 0
|
|
509
|
+
var scannerAttempts = 0
|
|
510
|
+
var scannerOpenedAt = 0
|
|
511
|
+
var scannerLastError = ''
|
|
512
|
+
|
|
513
|
+
function reportScanner(event, detail) {
|
|
514
|
+
if (!scannerDiagnosticSocket || scannerDiagnosticSocket.readyState !== WebSocket.OPEN) return
|
|
515
|
+
scannerDiagnosticSocket.send(JSON.stringify(Object.assign({ event: event }, detail || {})))
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function scannerTrackSettings() {
|
|
519
|
+
var stream = $('scannerVideo').srcObject
|
|
520
|
+
var track = stream && stream.getVideoTracks()[0]
|
|
521
|
+
return track && typeof track.getSettings === 'function' ? track.getSettings() : {}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function loadScannerScript(source, globalName) {
|
|
525
|
+
if (window[globalName]) return Promise.resolve(window[globalName])
|
|
526
|
+
if (scannerScriptPromises[source]) return scannerScriptPromises[source]
|
|
527
|
+
scannerScriptPromises[source] = new Promise(function (resolve, reject) {
|
|
528
|
+
var script = document.createElement('script')
|
|
529
|
+
script.src = source
|
|
530
|
+
script.onload = function () { resolve(window[globalName]) }
|
|
531
|
+
script.onerror = function () { reject(new Error('Failed to load scanner resource: ' + source)) }
|
|
532
|
+
document.head.appendChild(script)
|
|
533
|
+
})
|
|
534
|
+
return scannerScriptPromises[source]
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function supportsNativeQrDetector() {
|
|
538
|
+
if (typeof window.BarcodeDetector !== 'function' || typeof window.BarcodeDetector.getSupportedFormats !== 'function') return Promise.resolve(false)
|
|
539
|
+
return window.BarcodeDetector.getSupportedFormats()
|
|
540
|
+
.then(function (formats) { return formats.includes('qr_code') })
|
|
541
|
+
.catch(function (error) {
|
|
542
|
+
console.info('[dsh-mobile-bridge] native BarcodeDetector capability check failed', error)
|
|
543
|
+
reportScanner('error', { state: 'barcode-detector', name: error.name, message: error.message, stack: error.stack })
|
|
544
|
+
return false
|
|
545
|
+
})
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// 诊断通道只发送 camera/decoder 结构化状态,不发送相机画面、cookie 或配对文本。
|
|
549
|
+
function startScannerDiagnostics() {
|
|
550
|
+
scannerAttempts = 0
|
|
551
|
+
scannerLastError = ''
|
|
552
|
+
scannerOpenedAt = Date.now()
|
|
553
|
+
scannerDiagnosticSocket = new WebSocket(location.origin.replace(/^http/, 'ws') + '/ws/scanner')
|
|
554
|
+
scannerDiagnosticSocket.onopen = function () {
|
|
555
|
+
reportScanner('open', { state: 'capability-pending' })
|
|
556
|
+
}
|
|
557
|
+
scannerDiagnosticSocket.onerror = function () {
|
|
558
|
+
console.error('[dsh-mobile-bridge] scanner diagnostics socket failed', new Error('Scanner diagnostics WebSocket failed'))
|
|
559
|
+
}
|
|
560
|
+
scannerDiagnosticTimer = setInterval(function () {
|
|
561
|
+
var settings = scannerTrackSettings()
|
|
562
|
+
reportScanner('scan', {
|
|
563
|
+
attempts: scannerAttempts,
|
|
564
|
+
elapsedMs: Date.now() - scannerOpenedAt,
|
|
565
|
+
width: settings.width,
|
|
566
|
+
height: settings.height,
|
|
567
|
+
frameRate: settings.frameRate,
|
|
568
|
+
facingMode: settings.facingMode,
|
|
569
|
+
focusMode: settings.focusMode,
|
|
570
|
+
exposureMode: settings.exposureMode,
|
|
571
|
+
zoom: settings.zoom,
|
|
572
|
+
focusDistance: settings.focusDistance,
|
|
573
|
+
exposureCompensation: settings.exposureCompensation,
|
|
574
|
+
message: scannerLastError
|
|
575
|
+
})
|
|
576
|
+
}, 2000)
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function stopScannerDiagnostics(reason) {
|
|
580
|
+
clearInterval(scannerDiagnosticTimer)
|
|
581
|
+
scannerDiagnosticTimer = 0
|
|
582
|
+
reportScanner('close', { state: reason, attempts: scannerAttempts, elapsedMs: Date.now() - scannerOpenedAt })
|
|
583
|
+
if (scannerDiagnosticSocket) scannerDiagnosticSocket.close(1000, 'scanner closed')
|
|
584
|
+
scannerDiagnosticSocket = null
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// 相机轨道只属于取景页;关闭、识别成功和页面离开都会销毁 scanner 并释放设备。
|
|
588
|
+
function stopScanner(reason) {
|
|
589
|
+
scannerSession += 1
|
|
590
|
+
clearTimeout(scannerResultTimer)
|
|
591
|
+
scannerResultTimer = 0
|
|
592
|
+
clearTimeout(scannerAdjustmentTimer)
|
|
593
|
+
scannerAdjustmentTimer = 0
|
|
594
|
+
stopScannerDiagnostics(reason || 'closed')
|
|
595
|
+
var video = $('scannerVideo')
|
|
596
|
+
if (scannerDecodeFrame) {
|
|
597
|
+
if (scannerDecodeUsesVideoCallback) video.cancelVideoFrameCallback(scannerDecodeFrame)
|
|
598
|
+
else cancelAnimationFrame(scannerDecodeFrame)
|
|
599
|
+
}
|
|
600
|
+
scannerDecodeFrame = 0
|
|
601
|
+
scannerDecodeBusy = false
|
|
602
|
+
scannerDecodeFailed = false
|
|
603
|
+
var activeStream = video.srcObject
|
|
604
|
+
if (activeStream) activeStream.getTracks().forEach(function (track) { track.stop() })
|
|
605
|
+
if (scannerInstance) scannerInstance.destroy()
|
|
606
|
+
scannerInstance = null
|
|
443
607
|
if (scannerStream) scannerStream.getTracks().forEach(function (track) { track.stop() })
|
|
444
608
|
scannerStream = null
|
|
445
|
-
|
|
609
|
+
video.srcObject = null
|
|
610
|
+
var frame = $('scannerFrame')
|
|
611
|
+
frame.className = 'scannerFrame'
|
|
612
|
+
frame.removeAttribute('style')
|
|
613
|
+
$('wasmOutlinePolygon').removeAttribute('points')
|
|
446
614
|
$('scanner').hidden = true
|
|
447
615
|
document.body.classList.remove('scannerOpen')
|
|
448
616
|
}
|
|
@@ -452,68 +620,393 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
452
620
|
$('scannerStatus').classList.toggle('error', error)
|
|
453
621
|
}
|
|
454
622
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
var
|
|
458
|
-
|
|
459
|
-
stopScanner()
|
|
460
|
-
location.assign('/bridge/' + target.hash)
|
|
623
|
+
function scannerRangeValue(range, ratio) {
|
|
624
|
+
var step = typeof range.step === 'number' && range.step > 0 ? range.step : 0.1
|
|
625
|
+
var raw = range.min + (range.max - range.min) * ratio
|
|
626
|
+
return Math.min(range.max, Math.max(range.min, Math.round((raw - range.min) / step) * step + range.min))
|
|
461
627
|
}
|
|
462
628
|
|
|
463
|
-
function
|
|
629
|
+
function scannerSharpness() {
|
|
464
630
|
var video = $('scannerVideo')
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
631
|
+
var region = scannerRegion(video)
|
|
632
|
+
var size = 192
|
|
633
|
+
scannerAnalysisCanvas.width = size
|
|
634
|
+
scannerAnalysisCanvas.height = size
|
|
635
|
+
var context = scannerAnalysisCanvas.getContext('2d')
|
|
636
|
+
context.drawImage(video, region.x, region.y, region.width, region.height, 0, 0, size, size)
|
|
637
|
+
var pixels = context.getImageData(0, 0, size, size).data
|
|
638
|
+
var edge = 0
|
|
639
|
+
var clipped = 0
|
|
640
|
+
var samples = 0
|
|
641
|
+
for (var y = 1; y < size; y += 1) {
|
|
642
|
+
for (var x = 1; x < size; x += 1) {
|
|
643
|
+
var offset = (y * size + x) * 4
|
|
644
|
+
var left = offset - 4
|
|
645
|
+
var up = offset - size * 4
|
|
646
|
+
var value = (pixels[offset] + pixels[offset + 1] * 2 + pixels[offset + 2]) / 4
|
|
647
|
+
var leftValue = (pixels[left] + pixels[left + 1] * 2 + pixels[left + 2]) / 4
|
|
648
|
+
var upValue = (pixels[up] + pixels[up + 1] * 2 + pixels[up + 2]) / 4
|
|
649
|
+
edge += Math.abs(value - leftValue) + Math.abs(value - upValue)
|
|
650
|
+
if (value > 248) clipped += 1
|
|
651
|
+
samples += 1
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return Math.max(0, edge / (samples * 2) - clipped / samples * 80)
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// 对设备真实支持的焦距各评估一次ROI清晰度,随后锁定最高分,不再无限往返调焦。
|
|
658
|
+
function startScannerAdjustments(track, capabilities) {
|
|
659
|
+
clearTimeout(scannerAdjustmentTimer)
|
|
660
|
+
scannerAdjustmentIndex = 0
|
|
661
|
+
var plans = []
|
|
662
|
+
var focusModes = Array.isArray(capabilities.focusMode) ? capabilities.focusMode : []
|
|
663
|
+
var zoomRange = capabilities.zoom
|
|
664
|
+
var exposureRange = capabilities.exposureCompensation
|
|
665
|
+
var basePlan = {}
|
|
666
|
+
if (zoomRange && typeof zoomRange.min === 'number' && typeof zoomRange.max === 'number' && zoomRange.max > zoomRange.min) {
|
|
667
|
+
var limitedZoom = { min: zoomRange.min, max: Math.min(zoomRange.max, Math.max(zoomRange.min, 1.5)), step: zoomRange.step }
|
|
668
|
+
basePlan.zoom = scannerRangeValue(limitedZoom, 0.5)
|
|
669
|
+
}
|
|
670
|
+
if (exposureRange && typeof exposureRange.min === 'number' && typeof exposureRange.max === 'number' && exposureRange.min < 0) {
|
|
671
|
+
var negativeExposure = { min: exposureRange.min, max: Math.min(0, exposureRange.max), step: exposureRange.step }
|
|
672
|
+
basePlan.exposureCompensation = scannerRangeValue(negativeExposure, 0.45)
|
|
673
|
+
}
|
|
674
|
+
var focusRange = capabilities.focusDistance
|
|
675
|
+
if (focusModes.includes('manual') && focusRange && typeof focusRange.min === 'number' && typeof focusRange.max === 'number' && focusRange.max > focusRange.min) {
|
|
676
|
+
;[0, 0.34, 0.67, 1].forEach(function (ratio) {
|
|
677
|
+
plans.push(Object.assign({}, basePlan, { focusMode: 'manual', focusDistance: scannerRangeValue(focusRange, ratio) }))
|
|
678
|
+
})
|
|
679
|
+
}
|
|
680
|
+
reportScanner('controls', {
|
|
681
|
+
state: plans.length ? 'adjustment-ready' : 'adjustment-unavailable',
|
|
682
|
+
zoomMin: zoomRange && zoomRange.min,
|
|
683
|
+
zoomMax: zoomRange && zoomRange.max,
|
|
684
|
+
focusMin: focusRange && focusRange.min,
|
|
685
|
+
focusMax: focusRange && focusRange.max,
|
|
686
|
+
exposureMin: exposureRange && exposureRange.min,
|
|
687
|
+
exposureMax: exposureRange && exposureRange.max
|
|
688
|
+
})
|
|
689
|
+
if (plans.length === 0) return
|
|
690
|
+
var best = null
|
|
691
|
+
var evaluateNext = function () {
|
|
692
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
693
|
+
if (scannerAdjustmentIndex >= plans.length) {
|
|
694
|
+
if (!best) {
|
|
695
|
+
reportScanner('controls', { state: 'adjustment-failed' })
|
|
478
696
|
return
|
|
479
|
-
} catch (error) {
|
|
480
|
-
console.info('[dsh-mobile-bridge] camera QR rejected', error)
|
|
481
|
-
setScannerStatus('invalidPairQr', true)
|
|
482
697
|
}
|
|
698
|
+
track.applyConstraints({ advanced: [best.plan] })
|
|
699
|
+
.then(function () {
|
|
700
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
701
|
+
var settings = scannerTrackSettings()
|
|
702
|
+
setScannerStatus('cameraLocked', false)
|
|
703
|
+
reportScanner('adjustment', { state: 'locked', sharpness: best.score, zoom: settings.zoom, focusDistance: settings.focusDistance, focusMode: settings.focusMode, exposureCompensation: settings.exposureCompensation })
|
|
704
|
+
})
|
|
705
|
+
.catch(function (error) {
|
|
706
|
+
console.info('[dsh-mobile-bridge] camera focus lock failed', error)
|
|
707
|
+
reportScanner('error', { state: 'focus-lock', name: error.name, message: error.message, stack: error.stack })
|
|
708
|
+
})
|
|
709
|
+
return
|
|
483
710
|
}
|
|
711
|
+
var plan = plans[scannerAdjustmentIndex]
|
|
712
|
+
scannerAdjustmentIndex += 1
|
|
713
|
+
track.applyConstraints({ advanced: [plan] })
|
|
714
|
+
.then(function () {
|
|
715
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
716
|
+
scannerAdjustmentTimer = setTimeout(function () {
|
|
717
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
718
|
+
var settings = scannerTrackSettings()
|
|
719
|
+
var score = Math.round(scannerSharpness() * 100) / 100
|
|
720
|
+
if (!best || score > best.score) best = { plan: plan, score: score }
|
|
721
|
+
var label = tr('cameraAdjusting')
|
|
722
|
+
if (typeof settings.zoom === 'number') label += ' · ' + settings.zoom.toFixed(1) + '×'
|
|
723
|
+
$('scannerStatus').textContent = label
|
|
724
|
+
$('scannerStatus').classList.remove('error')
|
|
725
|
+
reportScanner('adjustment', { state: 'sample', sharpness: score, zoom: settings.zoom, focusDistance: settings.focusDistance, focusMode: settings.focusMode, exposureCompensation: settings.exposureCompensation })
|
|
726
|
+
evaluateNext()
|
|
727
|
+
}, 1000)
|
|
728
|
+
})
|
|
729
|
+
.catch(function (error) {
|
|
730
|
+
console.info('[dsh-mobile-bridge] automatic camera adjustment failed', error)
|
|
731
|
+
reportScanner('error', { state: 'adjustment', name: error.name, message: error.message, stack: error.stack })
|
|
732
|
+
evaluateNext()
|
|
733
|
+
})
|
|
484
734
|
}
|
|
485
|
-
|
|
735
|
+
scannerAdjustmentTimer = setTimeout(evaluateNext, 1600)
|
|
486
736
|
}
|
|
487
737
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
setScannerStatus('cameraUnavailable', true)
|
|
496
|
-
return
|
|
738
|
+
// 浏览器能力是相机控制的事实源;先请求高分辨率和曝光,再启动一次性焦点评估。
|
|
739
|
+
function configureScannerTrack() {
|
|
740
|
+
var stream = $('scannerVideo').srcObject
|
|
741
|
+
var track = stream && stream.getVideoTracks()[0]
|
|
742
|
+
if (!track || typeof track.getCapabilities !== 'function' || typeof track.applyConstraints !== 'function') {
|
|
743
|
+
reportScanner('controls', { state: 'capabilities-unavailable' })
|
|
744
|
+
return Promise.resolve(false)
|
|
497
745
|
}
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
746
|
+
var capabilities = track.getCapabilities()
|
|
747
|
+
var advanced = {}
|
|
748
|
+
if (Array.isArray(capabilities.focusMode) && capabilities.focusMode.includes('continuous')) advanced.focusMode = 'continuous'
|
|
749
|
+
if (Array.isArray(capabilities.exposureMode) && capabilities.exposureMode.includes('continuous')) advanced.exposureMode = 'continuous'
|
|
750
|
+
if (capabilities.pointsOfInterest) advanced.pointsOfInterest = [{ x: 0.5, y: 0.5 }]
|
|
751
|
+
var exposureRange = capabilities.exposureCompensation
|
|
752
|
+
if (exposureRange && typeof exposureRange.min === 'number' && typeof exposureRange.max === 'number' && exposureRange.min < 0) {
|
|
753
|
+
var negativeExposure = { min: exposureRange.min, max: Math.min(0, exposureRange.max), step: exposureRange.step }
|
|
754
|
+
advanced.exposureCompensation = scannerRangeValue(negativeExposure, 0.45)
|
|
755
|
+
}
|
|
756
|
+
var zoomRange = capabilities.zoom
|
|
757
|
+
if (zoomRange && typeof zoomRange.min === 'number' && typeof zoomRange.max === 'number' && zoomRange.max > zoomRange.min) {
|
|
758
|
+
var limitedZoom = { min: zoomRange.min, max: Math.min(zoomRange.max, Math.max(zoomRange.min, 1.5)), step: zoomRange.step }
|
|
759
|
+
advanced.zoom = scannerRangeValue(limitedZoom, 0.5)
|
|
760
|
+
}
|
|
761
|
+
return (Object.keys(advanced).length === 0 ? Promise.resolve() : track.applyConstraints({ advanced: [advanced] }))
|
|
762
|
+
.catch(function (error) {
|
|
763
|
+
console.info('[dsh-mobile-bridge] initial camera controls unavailable', error)
|
|
764
|
+
reportScanner('error', { state: 'controls', name: error.name, message: error.message, stack: error.stack })
|
|
503
765
|
})
|
|
504
766
|
.then(function () {
|
|
505
|
-
|
|
506
|
-
|
|
767
|
+
var settings = scannerTrackSettings()
|
|
768
|
+
reportScanner('controls', { state: 'initial-applied', focusMode: settings.focusMode, exposureMode: settings.exposureMode, zoom: settings.zoom, focusDistance: settings.focusDistance, exposureCompensation: settings.exposureCompensation })
|
|
769
|
+
startScannerAdjustments(track, capabilities)
|
|
770
|
+
return settings.focusMode === 'continuous'
|
|
507
771
|
})
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function relayHostname(hostname) {
|
|
775
|
+
return hostname.startsWith('www.') ? hostname.slice(4) : hostname
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// 摄像头二维码是外部输入;只允许当前 relay 的 www/apex 别名、精确配对路径和 hash。
|
|
779
|
+
function parseScannedPair(value) {
|
|
780
|
+
var target = new URL(value)
|
|
781
|
+
var sameRelay = target.protocol === location.protocol && target.port === location.port && relayHostname(target.hostname) === relayHostname(location.hostname)
|
|
782
|
+
if (!sameRelay || target.pathname !== '/bridge/' || !target.hash) throw new Error('invalidPairQr')
|
|
783
|
+
return target
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
function acceptScannedPair(target) {
|
|
787
|
+
stopScanner('accepted')
|
|
788
|
+
location.assign(target.href)
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function onScannerResult(result) {
|
|
792
|
+
if (scannerResultTimer) return
|
|
793
|
+
reportScanner('decoded', { corners: result.cornerPoints.length })
|
|
794
|
+
try {
|
|
795
|
+
var target = parseScannedPair(result.data)
|
|
796
|
+
clearTimeout(scannerAdjustmentTimer)
|
|
797
|
+
scannerAdjustmentTimer = 0
|
|
798
|
+
$('scannerFrame').classList.remove('invalid')
|
|
799
|
+
setScannerStatus('qrDetected', false)
|
|
800
|
+
reportScanner('accepted', { valid: true, corners: result.cornerPoints.length })
|
|
801
|
+
scannerResultTimer = setTimeout(function () {
|
|
802
|
+
scannerResultTimer = 0
|
|
803
|
+
acceptScannedPair(target)
|
|
804
|
+
}, 320)
|
|
805
|
+
} catch (error) {
|
|
806
|
+
console.info('[dsh-mobile-bridge] camera QR rejected', error)
|
|
807
|
+
$('scannerFrame').classList.add('invalid')
|
|
808
|
+
setScannerStatus('invalidPairQr', true)
|
|
809
|
+
reportScanner('rejected', { valid: false, corners: result.cornerPoints.length, name: error.name, message: error.message, stack: error.stack })
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function scannerRegion(video) {
|
|
814
|
+
var size = Math.round(Math.min(video.videoWidth, video.videoHeight) * 2 / 3)
|
|
815
|
+
var outputSize = Math.min(size, 800)
|
|
816
|
+
return {
|
|
817
|
+
x: Math.round((video.videoWidth - size) / 2),
|
|
818
|
+
y: Math.round((video.videoHeight - size) / 2),
|
|
819
|
+
width: size,
|
|
820
|
+
height: size,
|
|
821
|
+
downScaledWidth: outputSize,
|
|
822
|
+
downScaledHeight: outputSize
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
function finishScannerStart(session, profile) {
|
|
827
|
+
return configureScannerTrack().then(function (continuousFocus) {
|
|
828
|
+
if (session !== scannerSession) return false
|
|
829
|
+
var settings = scannerTrackSettings()
|
|
830
|
+
setScannerStatus(continuousFocus ? 'cameraFocused' : 'cameraReady', false)
|
|
831
|
+
reportScanner('camera', {
|
|
832
|
+
state: 'ready',
|
|
833
|
+
name: profile,
|
|
834
|
+
width: settings.width,
|
|
835
|
+
height: settings.height,
|
|
836
|
+
frameRate: settings.frameRate,
|
|
837
|
+
facingMode: settings.facingMode,
|
|
838
|
+
focusMode: settings.focusMode,
|
|
839
|
+
exposureMode: settings.exposureMode,
|
|
840
|
+
zoom: settings.zoom,
|
|
841
|
+
focusDistance: settings.focusDistance,
|
|
842
|
+
exposureCompensation: settings.exposureCompensation
|
|
843
|
+
})
|
|
844
|
+
return true
|
|
845
|
+
})
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
function startNativeScanner(session, QrScanner) {
|
|
849
|
+
if (session !== scannerSession) return Promise.resolve()
|
|
850
|
+
$('scannerFrame').classList.remove('manual')
|
|
851
|
+
scannerInstance = new QrScanner($('scannerVideo'), function (result) {
|
|
852
|
+
scannerAttempts += 1
|
|
853
|
+
onScannerResult(result)
|
|
854
|
+
}, {
|
|
855
|
+
onDecodeError: function (error) {
|
|
856
|
+
scannerAttempts += 1
|
|
857
|
+
scannerLastError = error && error.message ? error.message : String(error)
|
|
858
|
+
},
|
|
859
|
+
preferredCamera: 'environment',
|
|
860
|
+
maxScansPerSecond: 12,
|
|
861
|
+
calculateScanRegion: scannerRegion,
|
|
862
|
+
highlightScanRegion: true,
|
|
863
|
+
highlightCodeOutline: true,
|
|
864
|
+
overlay: $('scannerFrame'),
|
|
865
|
+
returnDetailedScanResult: true
|
|
866
|
+
})
|
|
867
|
+
reportScanner('library', { state: 'ready', name: 'native-barcode-detector' })
|
|
868
|
+
return scannerInstance.start().then(function () { return finishScannerStart(session, 'native-barcode-detector') })
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function drawWasmOutline(position, size) {
|
|
872
|
+
var points = [position.topLeft, position.topRight, position.bottomRight, position.bottomLeft]
|
|
873
|
+
.map(function (point) { return point.x.toFixed(1) + ',' + point.y.toFixed(1) })
|
|
874
|
+
.join(' ')
|
|
875
|
+
$('wasmOutline').setAttribute('viewBox', '0 0 ' + size + ' ' + size)
|
|
876
|
+
$('wasmOutlinePolygon').setAttribute('points', points)
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
function scheduleWasmScan(session) {
|
|
880
|
+
if (session !== scannerSession || !scannerInstance || scannerDecodeBusy || scannerResultTimer) return
|
|
881
|
+
var video = $('scannerVideo')
|
|
882
|
+
if (typeof video.requestVideoFrameCallback === 'function') {
|
|
883
|
+
scannerDecodeUsesVideoCallback = true
|
|
884
|
+
scannerDecodeFrame = video.requestVideoFrameCallback(function (now) { scanWasmFrame(session, now) })
|
|
885
|
+
} else {
|
|
886
|
+
scannerDecodeUsesVideoCallback = false
|
|
887
|
+
scannerDecodeFrame = requestAnimationFrame(function (now) { scanWasmFrame(session, now) })
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
function scanWasmFrame(session, now) {
|
|
892
|
+
scannerDecodeFrame = 0
|
|
893
|
+
if (session !== scannerSession || !scannerInstance) return
|
|
894
|
+
if (now - scannerLastDecodeAt < 140) { scheduleWasmScan(session); return }
|
|
895
|
+
scannerLastDecodeAt = now
|
|
896
|
+
var video = $('scannerVideo')
|
|
897
|
+
var region = scannerRegion(video)
|
|
898
|
+
var outputSize = Math.min(region.width, 720)
|
|
899
|
+
scannerDecodeCanvas.width = outputSize
|
|
900
|
+
scannerDecodeCanvas.height = outputSize
|
|
901
|
+
var context = scannerDecodeCanvas.getContext('2d')
|
|
902
|
+
context.drawImage(video, region.x, region.y, region.width, region.height, 0, 0, outputSize, outputSize)
|
|
903
|
+
var image = context.getImageData(0, 0, outputSize, outputSize)
|
|
904
|
+
scannerDecodeBusy = true
|
|
905
|
+
scannerAttempts += 1
|
|
906
|
+
window.ZXingWASM.readBarcodes(image, {
|
|
907
|
+
formats: ['QRCode'],
|
|
908
|
+
tryHarder: true,
|
|
909
|
+
tryRotate: true,
|
|
910
|
+
tryInvert: true,
|
|
911
|
+
tryDownscale: false,
|
|
912
|
+
tryDenoise: true,
|
|
913
|
+
binarizer: 'LocalAverage',
|
|
914
|
+
maxNumberOfSymbols: 1
|
|
915
|
+
}).then(function (results) {
|
|
916
|
+
if (session !== scannerSession) return
|
|
917
|
+
var result = results.find(function (candidate) { return candidate.isValid })
|
|
918
|
+
if (!result) {
|
|
919
|
+
scannerLastError = 'No QR code found'
|
|
920
|
+
return
|
|
921
|
+
}
|
|
922
|
+
scannerLastError = ''
|
|
923
|
+
drawWasmOutline(result.position, outputSize)
|
|
924
|
+
onScannerResult({
|
|
925
|
+
data: result.text,
|
|
926
|
+
cornerPoints: [result.position.topLeft, result.position.topRight, result.position.bottomRight, result.position.bottomLeft]
|
|
927
|
+
})
|
|
928
|
+
}).catch(function (error) {
|
|
929
|
+
console.error('[dsh-mobile-bridge] ZXing WASM frame decode failed', error)
|
|
930
|
+
if (session !== scannerSession) return
|
|
931
|
+
scannerDecodeFailed = true
|
|
932
|
+
setScannerStatus('cameraUnavailable', true)
|
|
933
|
+
reportScanner('error', { state: 'zxing-decode', name: error.name, message: error.message, stack: error.stack })
|
|
934
|
+
}).then(function () {
|
|
935
|
+
scannerDecodeBusy = false
|
|
936
|
+
if (session === scannerSession && scannerInstance && !scannerDecodeFailed) scheduleWasmScan(session)
|
|
937
|
+
})
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
function startWasmScanner(session) {
|
|
941
|
+
if (session !== scannerSession) return Promise.resolve()
|
|
942
|
+
var video = $('scannerVideo')
|
|
943
|
+
var frame = $('scannerFrame')
|
|
944
|
+
frame.classList.add('manual')
|
|
945
|
+
reportScanner('library', { state: 'ready', name: 'zxing-wasm' })
|
|
946
|
+
return navigator.mediaDevices.getUserMedia({
|
|
947
|
+
audio: false,
|
|
948
|
+
video: { facingMode: { ideal: 'environment' }, width: { ideal: 1440 }, height: { ideal: 1920 } }
|
|
949
|
+
}).then(function (stream) {
|
|
950
|
+
if (session !== scannerSession) {
|
|
951
|
+
stream.getTracks().forEach(function (track) { track.stop() })
|
|
952
|
+
return false
|
|
953
|
+
}
|
|
954
|
+
scannerStream = stream
|
|
955
|
+
scannerInstance = { destroy: function () {} }
|
|
956
|
+
video.srcObject = stream
|
|
957
|
+
return video.play().then(function () { return true })
|
|
958
|
+
}).then(function (started) {
|
|
959
|
+
if (!started || session !== scannerSession) return
|
|
960
|
+
return finishScannerStart(session, 'zxing-wasm').then(function (ready) {
|
|
961
|
+
if (ready) scheduleWasmScan(session)
|
|
511
962
|
})
|
|
963
|
+
})
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function openScanner() {
|
|
967
|
+
var session = scannerSession + 1
|
|
968
|
+
scannerSession = session
|
|
969
|
+
scannerDecodeFailed = false
|
|
970
|
+
scannerLastDecodeAt = 0
|
|
971
|
+
$('scanner').hidden = false
|
|
972
|
+
document.body.classList.add('scannerOpen')
|
|
973
|
+
setScannerStatus('cameraStarting', false)
|
|
974
|
+
startScannerDiagnostics()
|
|
975
|
+
supportsNativeQrDetector().then(function (nativeDetector) {
|
|
976
|
+
if (session !== scannerSession) return
|
|
977
|
+
if (nativeDetector) {
|
|
978
|
+
reportScanner('library', { state: 'loading', name: 'qr-scanner' })
|
|
979
|
+
return loadScannerScript('/bridge/qr-scanner.js', 'QrScanner')
|
|
980
|
+
.then(function (QrScanner) { return startNativeScanner(session, QrScanner) })
|
|
981
|
+
}
|
|
982
|
+
reportScanner('library', { state: 'loading', name: 'zxing-wasm' })
|
|
983
|
+
return loadScannerScript('/bridge/zxing-reader.js', 'ZXingWASM')
|
|
984
|
+
.then(function (ZXingWASM) {
|
|
985
|
+
if (session !== scannerSession) return
|
|
986
|
+
return ZXingWASM.prepareZXingModule({
|
|
987
|
+
overrides: scannerWasmOverrides,
|
|
988
|
+
fireImmediately: true
|
|
989
|
+
})
|
|
990
|
+
})
|
|
991
|
+
.then(function () { return startWasmScanner(session) })
|
|
992
|
+
}).catch(function (error) {
|
|
993
|
+
console.error('[dsh-mobile-bridge] camera start failed', error)
|
|
994
|
+
if (session !== scannerSession) return
|
|
995
|
+
var video = $('scannerVideo')
|
|
996
|
+
var activeStream = video.srcObject
|
|
997
|
+
if (activeStream) activeStream.getTracks().forEach(function (track) { track.stop() })
|
|
998
|
+
if (scannerInstance) scannerInstance.destroy()
|
|
999
|
+
scannerInstance = null
|
|
1000
|
+
scannerStream = null
|
|
1001
|
+
video.srcObject = null
|
|
1002
|
+
setScannerStatus('cameraUnavailable', true)
|
|
1003
|
+
reportScanner('error', { state: 'camera-start', name: error.name, message: error.message, stack: error.stack })
|
|
1004
|
+
})
|
|
512
1005
|
}
|
|
513
1006
|
|
|
514
1007
|
$('openScanner').onclick = openScanner
|
|
515
|
-
$('closeScanner').onclick = stopScanner
|
|
516
|
-
window.addEventListener('pagehide', stopScanner)
|
|
1008
|
+
$('closeScanner').onclick = function () { stopScanner('closed') }
|
|
1009
|
+
window.addEventListener('pagehide', function () { stopScanner('pagehide') })
|
|
517
1010
|
|
|
518
1011
|
var fragment = location.hash.slice(1)
|
|
519
1012
|
if (fragment) {
|
package/src/server.ts
CHANGED
|
@@ -11,8 +11,9 @@
|
|
|
11
11
|
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
12
12
|
import { readFileSync } from 'node:fs'
|
|
13
13
|
import { createRequire } from 'node:module'
|
|
14
|
+
import { dirname, resolve } from 'node:path'
|
|
14
15
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
|
15
|
-
import { WebSocket, WebSocketServer } from 'ws'
|
|
16
|
+
import { WebSocket, WebSocketServer, type RawData } from 'ws'
|
|
16
17
|
import { SW_SOURCE, CLIENT_SOURCE, SOCKET_CLIENT_SOURCE } from './phone.ts'
|
|
17
18
|
import { UserStore, type DeviceRecord } from './store.ts'
|
|
18
19
|
import type { WechatConfig } from './wechat.ts'
|
|
@@ -36,7 +37,11 @@ export interface BridgeServerOptions {
|
|
|
36
37
|
|
|
37
38
|
const COOKIE = 'mbs'
|
|
38
39
|
const require = createRequire(import.meta.url)
|
|
39
|
-
const
|
|
40
|
+
const QR_SCANNER_SOURCE = readFileSync(require.resolve('qr-scanner'), 'utf8')
|
|
41
|
+
const QR_SCANNER_WORKER_SOURCE = readFileSync(require.resolve('qr-scanner/qr-scanner-worker.min.js'), 'utf8')
|
|
42
|
+
const ZXING_READER_ENTRY = require.resolve('zxing-wasm/reader')
|
|
43
|
+
const ZXING_READER_SOURCE = readFileSync(resolve(dirname(ZXING_READER_ENTRY), '../../iife/reader/index.js'), 'utf8')
|
|
44
|
+
const ZXING_READER_WASM = readFileSync(require.resolve('zxing-wasm/reader/zxing_reader.wasm'))
|
|
40
45
|
const DEEPSEEK_LOGO = readFileSync(new URL('./deepseek-logo.svg', import.meta.url), 'utf8')
|
|
41
46
|
const DEEPSEEK_LOGO_DATA_URL = 'data:image/svg+xml;base64,' + Buffer.from(DEEPSEEK_LOGO).toString('base64')
|
|
42
47
|
|
|
@@ -70,7 +75,13 @@ h1{margin:0;font-size:22px;line-height:1.35;font-weight:650}
|
|
|
70
75
|
.scannerClose:hover{background:rgb(255 255 255/.16)}
|
|
71
76
|
.scannerStage{position:relative;min-height:0;overflow:hidden;background:#000}
|
|
72
77
|
.scanner video{display:block;width:100%;height:100%;object-fit:cover}
|
|
73
|
-
.scannerFrame{
|
|
78
|
+
.scannerFrame{border:2px solid #6f89ff;border-radius:8px;box-shadow:0 0 0 200vmax rgb(0 0 0/.34)}
|
|
79
|
+
.scannerFrame.manual{position:absolute;top:50%;left:50%;width:min(67vw,320px);aspect-ratio:1;transform:translate(-50%,-50%)}
|
|
80
|
+
.wasmOutline{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
|
|
81
|
+
.wasmOutline polygon{fill:rgb(69 196 129/.16);stroke:#45c481;stroke-width:4;vector-effect:non-scaling-stroke}
|
|
82
|
+
.scannerFrame.invalid .wasmOutline polygon{fill:rgb(255 104 120/.14);stroke:#ff6878}
|
|
83
|
+
.scannerFrame .code-outline-highlight{fill:rgb(69 196 129/.16)!important;stroke:#45c481!important;stroke-width:4!important;stroke-dasharray:none!important}
|
|
84
|
+
.scannerFrame.invalid .code-outline-highlight{fill:rgb(255 104 120/.14)!important;stroke:#ff6878!important}
|
|
74
85
|
.scannerStatus{min-height:48px;margin:0;padding:14px 20px 0;color:#c6cedb;text-align:center}
|
|
75
86
|
.scannerStatus.error{color:#ff9aa2}
|
|
76
87
|
body.scannerOpen{overflow:hidden}
|
|
@@ -96,8 +107,8 @@ p.err{min-height:20px;margin:12px 0 0;color:var(--danger);font-size:13px;line-he
|
|
|
96
107
|
@media(max-width:340px){main{padding:0 2px}.brand img{width:168px}.preferences{justify-content:flex-start}.preferences button{padding:0 8px}.codeRow{grid-template-columns:minmax(0,1fr) 82px}}
|
|
97
108
|
@media(prefers-reduced-motion:reduce){button{transition:none}}
|
|
98
109
|
</style></head><body>
|
|
99
|
-
<main aria-labelledby="title"><header class="brand"><img src="${DEEPSEEK_LOGO_DATA_URL}" alt="DeepSeek"><span class="product">Harness Mobile</span></header><nav class="preferences" aria-label="显示偏好"><div class="segmented"><button id="langZh" type="button" aria-pressed="true">中文</button><button id="langEn" type="button" aria-pressed="false">EN</button></div><div class="segmented"><button id="themeLight" type="button" aria-pressed="false" data-i18n="light">浅色</button><button id="themeDark" type="button" aria-pressed="true" data-i18n="dark">深色</button></div></nav><div class="intro"><h1 id="title" data-i18n="title">移动连接</h1></div><section class="scanFirst" id="scanFirst"><p data-i18n="scanFirst">请扫描桌面端二维码</p><button id="openScanner" class="scanButton" type="button" data-i18n="openScanner">打开相机扫码</button></section><section id="loginForm" hidden><div class="field"><label for="e" data-i18n="email">邮箱</label><input id="e" type="email" inputmode="email" autocomplete="email" placeholder="name@example.com" data-i18n-placeholder="emailPlaceholder"></div><div class="codeRow"><div class="field"><label for="c" data-i18n="code">验证码</label><input id="c" inputmode="numeric" autocomplete="one-time-code" placeholder="6 位验证码" data-i18n-placeholder="codePlaceholder"></div><button id="s" class="ghost" type="button" data-i18n="send">发送</button></div><div class="field"><label for="b" data-i18n="pairingCode">配对码</label><input id="b" autocomplete="off" placeholder="6 位字符" data-i18n-placeholder="pairingPlaceholder"></div><button id="l" type="button" data-i18n="connect">登录并连接</button><p class="err" id="x" role="alert"></p></section></main><section id="scanner" class="scanner" role="dialog" aria-modal="true" aria-labelledby="scannerTitle" hidden><header class="scannerHeader"><h2 id="scannerTitle" data-i18n="scannerTitle">扫描配对二维码</h2><button id="closeScanner" class="scannerClose" type="button" aria-label="关闭相机" data-i18n-aria-label="closeScanner">×</button></header><div class="scannerStage"><video id="scannerVideo" autoplay muted playsinline></video><div class="scannerFrame" aria-hidden="true"></div></div><p id="scannerStatus" class="scannerStatus" role="status" data-i18n="cameraStarting">正在打开相机</p></section>
|
|
100
|
-
<script src="/bridge/
|
|
110
|
+
<main aria-labelledby="title"><header class="brand"><img src="${DEEPSEEK_LOGO_DATA_URL}" alt="DeepSeek"><span class="product">Harness Mobile</span></header><nav class="preferences" aria-label="显示偏好"><div class="segmented"><button id="langZh" type="button" aria-pressed="true">中文</button><button id="langEn" type="button" aria-pressed="false">EN</button></div><div class="segmented"><button id="themeLight" type="button" aria-pressed="false" data-i18n="light">浅色</button><button id="themeDark" type="button" aria-pressed="true" data-i18n="dark">深色</button></div></nav><div class="intro"><h1 id="title" data-i18n="title">移动连接</h1></div><section class="scanFirst" id="scanFirst"><p data-i18n="scanFirst">请扫描桌面端二维码</p><button id="openScanner" class="scanButton" type="button" data-i18n="openScanner">打开相机扫码</button></section><section id="loginForm" hidden><div class="field"><label for="e" data-i18n="email">邮箱</label><input id="e" type="email" inputmode="email" autocomplete="email" placeholder="name@example.com" data-i18n-placeholder="emailPlaceholder"></div><div class="codeRow"><div class="field"><label for="c" data-i18n="code">验证码</label><input id="c" inputmode="numeric" autocomplete="one-time-code" placeholder="6 位验证码" data-i18n-placeholder="codePlaceholder"></div><button id="s" class="ghost" type="button" data-i18n="send">发送</button></div><div class="field"><label for="b" data-i18n="pairingCode">配对码</label><input id="b" autocomplete="off" placeholder="6 位字符" data-i18n-placeholder="pairingPlaceholder"></div><button id="l" type="button" data-i18n="connect">登录并连接</button><p class="err" id="x" role="alert"></p></section></main><section id="scanner" class="scanner" role="dialog" aria-modal="true" aria-labelledby="scannerTitle" hidden><header class="scannerHeader"><h2 id="scannerTitle" data-i18n="scannerTitle">扫描配对二维码</h2><button id="closeScanner" class="scannerClose" type="button" aria-label="关闭相机" data-i18n-aria-label="closeScanner">×</button></header><div class="scannerStage"><video id="scannerVideo" autoplay muted playsinline></video><div id="scannerFrame" class="scannerFrame" aria-hidden="true"><svg id="wasmOutline" class="wasmOutline" aria-hidden="true"><polygon id="wasmOutlinePolygon"></polygon></svg></div></div><p id="scannerStatus" class="scannerStatus" role="status" data-i18n="cameraStarting">正在打开相机</p></section>
|
|
111
|
+
<script src="/bridge/client.js"></script></body></html>`
|
|
101
112
|
|
|
102
113
|
function json(res: ServerResponse, status: number, body: unknown): void {
|
|
103
114
|
res.writeHead(status, { 'content-type': 'application/json' })
|
|
@@ -188,6 +199,50 @@ function requestDeviceName(req: IncomingMessage): string {
|
|
|
188
199
|
return browser === '' ? platform : platform + ' · ' + browser
|
|
189
200
|
}
|
|
190
201
|
|
|
202
|
+
const SCANNER_DIAGNOSTIC_EVENTS = new Set(['open', 'library', 'controls', 'camera', 'scan', 'adjustment', 'decoded', 'accepted', 'rejected', 'error', 'close'])
|
|
203
|
+
const SCANNER_STRING_FIELDS = new Map([['state', 80], ['name', 80], ['message', 320], ['facingMode', 80], ['focusMode', 80], ['exposureMode', 80]])
|
|
204
|
+
const SCANNER_NUMBER_FIELDS = new Set(['attempts', 'elapsedMs', 'width', 'height', 'frameRate', 'corners', 'zoom', 'focusDistance', 'zoomMin', 'zoomMax', 'focusMin', 'focusMax', 'sharpness'])
|
|
205
|
+
const SCANNER_SIGNED_NUMBER_FIELDS = new Set(['exposureMin', 'exposureMax', 'exposureCompensation'])
|
|
206
|
+
|
|
207
|
+
function rawDataByteLength(raw: RawData): number {
|
|
208
|
+
return Array.isArray(raw) ? raw.reduce((total, part) => total + part.byteLength, 0) : raw.byteLength
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Scanner diagnostics are an unauthenticated public ingress; only bounded, non-secret telemetry fields reach the server log.
|
|
212
|
+
function scannerDiagnostic(value: unknown): Record<string, string | number | boolean> {
|
|
213
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('scanner diagnostic must be an object')
|
|
214
|
+
const input = value as Record<string, unknown>
|
|
215
|
+
if (typeof input.event !== 'string' || !SCANNER_DIAGNOSTIC_EVENTS.has(input.event)) throw new Error('scanner diagnostic event is invalid')
|
|
216
|
+
const output: Record<string, string | number | boolean> = { event: input.event }
|
|
217
|
+
for (const [field, maxLength] of SCANNER_STRING_FIELDS) {
|
|
218
|
+
const fieldValue = input[field]
|
|
219
|
+
if (fieldValue === undefined) continue
|
|
220
|
+
if (typeof fieldValue !== 'string') throw new Error('scanner diagnostic ' + field + ' must be a string')
|
|
221
|
+
output[field] = fieldValue.slice(0, maxLength)
|
|
222
|
+
}
|
|
223
|
+
if (input.stack !== undefined) {
|
|
224
|
+
if (typeof input.stack !== 'string') throw new Error('scanner diagnostic stack must be a string')
|
|
225
|
+
output.stack = input.stack
|
|
226
|
+
}
|
|
227
|
+
for (const field of SCANNER_NUMBER_FIELDS) {
|
|
228
|
+
const fieldValue = input[field]
|
|
229
|
+
if (fieldValue === undefined) continue
|
|
230
|
+
if (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue) || fieldValue < 0) throw new Error('scanner diagnostic ' + field + ' must be a non-negative number')
|
|
231
|
+
output[field] = fieldValue
|
|
232
|
+
}
|
|
233
|
+
for (const field of SCANNER_SIGNED_NUMBER_FIELDS) {
|
|
234
|
+
const fieldValue = input[field]
|
|
235
|
+
if (fieldValue === undefined) continue
|
|
236
|
+
if (typeof fieldValue !== 'number' || !Number.isFinite(fieldValue)) throw new Error('scanner diagnostic ' + field + ' must be a finite number')
|
|
237
|
+
output[field] = fieldValue
|
|
238
|
+
}
|
|
239
|
+
if (input.valid !== undefined) {
|
|
240
|
+
if (typeof input.valid !== 'boolean') throw new Error('scanner diagnostic valid must be a boolean')
|
|
241
|
+
output.valid = input.valid
|
|
242
|
+
}
|
|
243
|
+
return output
|
|
244
|
+
}
|
|
245
|
+
|
|
191
246
|
/**
|
|
192
247
|
* Build the public bridge, pairing-ticket lifecycle, device registry, and
|
|
193
248
|
* ciphertext relay around stable desktop identities.
|
|
@@ -285,9 +340,24 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
285
340
|
res.end(DEEPSEEK_LOGO)
|
|
286
341
|
return
|
|
287
342
|
}
|
|
288
|
-
if (url.pathname === '/bridge/
|
|
289
|
-
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': '
|
|
290
|
-
res.end(
|
|
343
|
+
if (url.pathname === '/bridge/qr-scanner.js') {
|
|
344
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
345
|
+
res.end(QR_SCANNER_SOURCE)
|
|
346
|
+
return
|
|
347
|
+
}
|
|
348
|
+
if (url.pathname === '/bridge/qr-scanner-worker.min.js') {
|
|
349
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
350
|
+
res.end(QR_SCANNER_WORKER_SOURCE)
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
if (url.pathname === '/bridge/zxing-reader.js') {
|
|
354
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
355
|
+
res.end(ZXING_READER_SOURCE)
|
|
356
|
+
return
|
|
357
|
+
}
|
|
358
|
+
if (url.pathname === '/bridge/zxing-reader.wasm') {
|
|
359
|
+
res.writeHead(200, { 'content-type': 'application/wasm', 'cache-control': 'no-store' })
|
|
360
|
+
res.end(ZXING_READER_WASM)
|
|
291
361
|
return
|
|
292
362
|
}
|
|
293
363
|
if (url.pathname === '/bridge/client.js') {
|
|
@@ -467,6 +537,34 @@ export function createBridgeServer(store: UserStore, options: BridgeServerRuntim
|
|
|
467
537
|
const wss = new WebSocketServer({ noServer: true })
|
|
468
538
|
http.on('upgrade', (req, socket, head) => {
|
|
469
539
|
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
540
|
+
if (url.pathname === '/ws/scanner') {
|
|
541
|
+
const origin = req.headers.origin
|
|
542
|
+
const host = req.headers.host ?? ''
|
|
543
|
+
if (typeof origin !== 'string' || (origin !== 'https://' + host && origin !== 'http://' + host)) { socket.destroy(); return }
|
|
544
|
+
wss.handleUpgrade(req, socket, head, scanner => {
|
|
545
|
+
const id = randomBytes(4).toString('hex')
|
|
546
|
+
let messages = 0
|
|
547
|
+
const lifetime = setTimeout(() => { scanner.close(1000, 'scanner timeout') }, 10 * 60_000)
|
|
548
|
+
console.info('[mobile-bridge scanner]', { id, event: 'connected', ip: requestIp(req), device: requestDeviceName(req) })
|
|
549
|
+
scanner.on('message', (raw, isBinary) => {
|
|
550
|
+
try {
|
|
551
|
+
if (isBinary) { scanner.close(1003, 'binary scanner diagnostic unsupported'); return }
|
|
552
|
+
if (rawDataByteLength(raw) > 8192) { scanner.close(1009, 'scanner diagnostic too large'); return }
|
|
553
|
+
messages += 1
|
|
554
|
+
if (messages > 180) { scanner.close(1008, 'scanner diagnostic limit reached'); return }
|
|
555
|
+
console.info('[mobile-bridge scanner]', { id, ...scannerDiagnostic(JSON.parse(String(raw))) })
|
|
556
|
+
} catch (error) {
|
|
557
|
+
console.warn('[mobile-bridge scanner]', { id, event: 'invalid', error })
|
|
558
|
+
scanner.close(1003, 'invalid scanner diagnostic')
|
|
559
|
+
}
|
|
560
|
+
})
|
|
561
|
+
scanner.on('close', (code, reason) => {
|
|
562
|
+
clearTimeout(lifetime)
|
|
563
|
+
console.info('[mobile-bridge scanner]', { id, event: 'disconnected', code, reason: String(reason).slice(0, 123), messages })
|
|
564
|
+
})
|
|
565
|
+
})
|
|
566
|
+
return
|
|
567
|
+
}
|
|
470
568
|
if (url.pathname === '/ws/bridge') {
|
|
471
569
|
const bridgeId = url.searchParams.get('bridgeId') ?? ''
|
|
472
570
|
const code = bridgeTickets.get(bridgeId)
|
package/src/wechat.spec.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest'
|
|
2
|
-
import { wechatConfigFromEnv, wechatMiniprogramVerifier, wechatVerifier } from './wechat.ts'
|
|
3
|
-
import { generateScheme } from './wechat-scheme.ts'
|
|
4
|
-
|
|
5
|
-
function stubFetch(body: unknown): typeof fetch {
|
|
6
|
-
return (async () => new Response(JSON.stringify(body), { status: 200 })) as typeof fetch
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
describe('wechat verifiers', () => {
|
|
10
|
-
it('open-platform verifier returns unionid when present, openid otherwise', async () => {
|
|
11
|
-
const withUnion = wechatVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ access_token: 't', openid: 'od-1', unionid: 'uu-1' }))
|
|
12
|
-
await expect(withUnion({ code: 'c1' })).resolves.toBe('uu-1')
|
|
13
|
-
const openOnly = wechatVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ access_token: 't', openid: 'od-2' }))
|
|
14
|
-
await expect(openOnly({ code: 'c2' })).resolves.toBe('od-2')
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
it('miniprogram verifier uses jscode2session and surfaces provider errors', async () => {
|
|
18
|
-
const verify = wechatMiniprogramVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ openid: 'mp-1' }))
|
|
19
|
-
await expect(verify({ code: 'wx-code' })).resolves.toBe('mp-1')
|
|
20
|
-
const failing = wechatMiniprogramVerifier({ appId: 'a', appSecret: 's' }, stubFetch({ errcode: 40029, errmsg: 'invalid code' }))
|
|
21
|
-
await expect(failing({ code: 'bad' })).rejects.toThrow(/invalid code/)
|
|
22
|
-
await expect(verify({})).rejects.toThrow(/missing/)
|
|
23
|
-
})
|
|
24
|
-
|
|
25
|
-
it('generates a URL Scheme from the openlink', async () => {
|
|
26
|
-
const fetchImpl = (async (url: string | URL | Request) => {
|
|
27
|
-
const target = String(url)
|
|
28
|
-
if (target.includes('/cgi-bin/token')) return new Response(JSON.stringify({ access_token: 'tok-1', expires_in: 7200 }), { status: 200 })
|
|
29
|
-
return new Response(JSON.stringify({ errcode: 0, openlink: 'weixin://dl/business/?t=abc' }), { status: 200 })
|
|
30
|
-
}) as typeof fetch
|
|
31
|
-
await expect(generateScheme({ appId: 'a', appSecret: 's' }, 'pair=xyz', fetchImpl)).resolves.toBe('weixin://dl/business/?t=abc')
|
|
32
|
-
})
|
|
33
|
-
|
|
34
|
-
it('enables only when env carries both credentials', () => {
|
|
35
|
-
expect(wechatConfigFromEnv({})).toBeUndefined()
|
|
36
|
-
expect(wechatConfigFromEnv({ WECHAT_APP_ID: 'a', WECHAT_APP_SECRET: 'b' })).toEqual({ appId: 'a', appSecret: 'b' })
|
|
37
|
-
})
|
|
38
|
-
})
|