@ttxs69/dsh-trust-device 0.0.0-stage → 0.3.1
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/README.md +68 -2
- package/cordis.patch.yml +13 -0
- package/lib/client.js +317 -0
- package/lib/index.mjs +208 -0
- package/package.json +44 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sarace
|
|
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/README.md
CHANGED
|
@@ -1,3 +1,69 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ttxs69/dsh-trust-device
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness) web plugin: a **Remote Access** panel with a QR code of the authenticated URL, **sliding cookie renewal**, and a **login page for iOS home-screen web apps** (whose cookie jar is isolated from Safari).
|
|
4
|
+
|
|
5
|
+
## User flow
|
|
6
|
+
|
|
7
|
+
### One-time, on the computer
|
|
8
|
+
|
|
9
|
+
1. Keep `dsh web` behind `tailscale serve` (tailnet only) and set in the web profile:
|
|
10
|
+
`connection.trustedHosts: [<machine>.<tailnet>.ts.net]`, `connection.cookieMaxAgeDays: 90`,
|
|
11
|
+
`web-runtime.publicUrl: https://<machine>.<tailnet>.ts.net/`.
|
|
12
|
+
2. Install the plugin: `dsh plugin --profile web add @ttxs69/dsh-trust-device`. Reload the page once; a QR icon appears at the bottom of the sidebar under **远程访问**.
|
|
13
|
+
|
|
14
|
+
### New phone or tablet (any device with Tailscale on)
|
|
15
|
+
|
|
16
|
+
- **Safari / any browser**: open the computer's panel → **复制授权链接** → open it on the phone, or scan the QR with the camera. Done. Add to Home Screen from *this* page if you like a full-screen app — on iOS that Home Screen app has its own cookie jar, so see the next point.
|
|
17
|
+
- **iPhone / iPad Home Screen app (PWA)**: open `https://<machine>.<tailnet>.ts.net/__trust/pwa` in Safari (the panel's **复制 PWA 安装地址**). It says the device is not signed in → paste the authorization link → it enters the GUI → then **Share → Add to Home Screen from that page**. The installed app now signs itself in inside its own jar.
|
|
18
|
+
|
|
19
|
+
### Every day
|
|
20
|
+
|
|
21
|
+
Open the app or page and use DSH. Nothing else to do: every day of use the page silently renews the cookie, so a device you keep using never logs out.
|
|
22
|
+
|
|
23
|
+
### When a device has been idle for 90 days, or you lost it
|
|
24
|
+
|
|
25
|
+
- Idle device: the panel/PWA asks for the authorization link once; paste it from any signed-in device.
|
|
26
|
+
- Lost device: remove it from the tailnet (Tailscale admin → Machines). To end every browser session at once, delete the `client-connection/browser-session` record in `$DSH_HOME/.credentials.yaml` and restart `dsh`; every device then re-authenticates once.
|
|
27
|
+
|
|
28
|
+
## Security model
|
|
29
|
+
|
|
30
|
+
- The two `/api/__trust/*` routes run on the connection's shared `/api` channel: Host/Origin fence and cookie authentication run first, and only **owner** peers reach exact routes. Unauthenticated callers get `401`. The token URL is only ever shown to a browser that already holds an equivalent cookie.
|
|
31
|
+
- `/__trust/pwa` and its manifest are public and serve no secret; the page only forwards a token the user pastes to DSH's own exchange route.
|
|
32
|
+
- The status route decodes the browser cookie's JSON payload (`issuedAt`/`expiresAt`) for display only — the connection has already verified the signature.
|
|
33
|
+
- Cookies are HttpOnly, SameSite=Strict, host-only; the signing secret never leaves DSH's credentials store.
|
|
34
|
+
|
|
35
|
+
## Why
|
|
36
|
+
|
|
37
|
+
`dsh web` authenticates browsers with a signed cookie (default 30 days) obtained by opening a launch-token URL that is printed once at startup. Three papercuts follow: finding that URL again later, idle and daily-driver devices expiring alike, and iOS Home Screen apps never seeing the cookie Safari received. This plugin addresses all three without touching DSH's auth internals.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
dsh plugin --profile web add @ttxs69/dsh-trust-device # from npm (once published)
|
|
43
|
+
dsh plugin --profile web add /path/to/dsh-trust-device # local checkout
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The plugin's bundle patch inserts one Loader row (`inject: [connection, webServer, webApp]`); the Plugin Manager applies it without a restart. Host-side changes to a linked checkout are not hot-replaced: run `dsh plugin --profile web remove @ttxs69/dsh-trust-device` then `add` again.
|
|
47
|
+
|
|
48
|
+
## Releasing
|
|
49
|
+
|
|
50
|
+
Bump `version` in `package.json`, commit, then `git tag vX.Y.Z && git push origin vX.Y.Z`. The `release.yml` workflow checks the tag matches the package version, runs the tests, and publishes to npm via GitHub Actions Trusted Publishing (OIDC, with provenance) — no npm token is stored anywhere. CI (`npm ci`, `npm test`, `npm pack --dry-run`) runs on every push and pull request.
|
|
51
|
+
|
|
52
|
+
## Configuration
|
|
53
|
+
|
|
54
|
+
The bundle patch inserts the plugin row with a default config you can edit in the profile:
|
|
55
|
+
|
|
56
|
+
| Key | Default | Meaning |
|
|
57
|
+
|---|---|---|
|
|
58
|
+
| `renewAfterElapsedDays` | `1` | Sliding renewal: renew the cookie once it is this many days old (of use). |
|
|
59
|
+
|
|
60
|
+
UI text follows DSH's language (zh/en); the install page follows the phone's language.
|
|
61
|
+
|
|
62
|
+
## Development
|
|
63
|
+
|
|
64
|
+
- `lib/index.mjs` — host half (two authenticated routes, the public PWA page + manifest)
|
|
65
|
+
- `lib/client.js` — browser half (sidebar entry, panel, embedded QR encoder: byte mode / ECC M / versions 1–10)
|
|
66
|
+
- `npm test` — `test/qr.test.mjs`; `npm run test:e2e` — `test/e2e.mjs` (needs a live `dsh web` behind `tailscale serve`, a curl cookie jar in `DSH_COOKIE_JAR`, Google Chrome): every version 1–10 is byte-identical to the `qrcode` reference library at the same mask and decodes with jsQR
|
|
67
|
+
- `TODO.md` — roadmap
|
|
68
|
+
|
|
69
|
+
License: MIT.
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# dsh-trust-device bundle patch: one host row that reads the advertised URL and
|
|
2
|
+
# the connection's authenticated URL, exposes two owner-only exact routes on the
|
|
3
|
+
# shared /api channel, and serves the public PWA login page.
|
|
4
|
+
- insert:
|
|
5
|
+
- id: trust-device
|
|
6
|
+
name: '@ttxs69/dsh-trust-device'
|
|
7
|
+
inject:
|
|
8
|
+
- connection
|
|
9
|
+
- webServer
|
|
10
|
+
- webApp
|
|
11
|
+
config:
|
|
12
|
+
# Sliding renewal: renew the cookie once it is this many days old (of use).
|
|
13
|
+
renewAfterElapsedDays: 1
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// Browser half of dsh-trust-device. Contributes one sidebar footer action and
|
|
2
|
+
// one shell overlay. The panel shows the advertised URL, a QR of the connection's
|
|
3
|
+
// authenticated URL, and renews this browser's cookie (sliding session).
|
|
4
|
+
window.__ModuleLoader__.load({
|
|
5
|
+
id: 'dsh-trust-device',
|
|
6
|
+
factory: (require) => {
|
|
7
|
+
const React = require('react')
|
|
8
|
+
const module = { exports: {} }
|
|
9
|
+
const exports = module.exports
|
|
10
|
+
|
|
11
|
+
// ---------- tiny QR encoder (byte mode, ECC M, versions 1-10; Nayuki-style, MIT) ----------
|
|
12
|
+
const ECC_M = { 1: [1, 10], 2: [1, 16], 3: [1, 26], 4: [2, 18], 5: [2, 24], 6: [4, 16], 7: [4, 18], 8: [4, 22], 9: [5, 22], 10: [5, 26] }
|
|
13
|
+
const ALIGN = { 1: [], 2: [6, 18], 3: [6, 22], 4: [6, 26], 5: [6, 30], 6: [6, 34], 7: [6, 22, 38], 8: [6, 24, 42], 9: [6, 26, 46], 10: [6, 28, 50] }
|
|
14
|
+
const TOTAL = { 1: 26, 2: 44, 3: 70, 4: 100, 5: 134, 6: 172, 7: 196, 8: 242, 9: 292, 10: 346 }
|
|
15
|
+
// GF(256) exp/log tables, primitive polynomial 0x11D
|
|
16
|
+
const EXP = new Uint8Array(512), LOG = new Uint8Array(256)
|
|
17
|
+
for (let i = 0, x = 1; i < 255; i++) { EXP[i] = x; LOG[x] = i; x <<= 1; if (x & 0x100) x ^= 0x11D }
|
|
18
|
+
for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255]
|
|
19
|
+
const gmul = (a, b) => (a && b ? EXP[LOG[a] + LOG[b]] : 0)
|
|
20
|
+
function rsGenerator(degree) {
|
|
21
|
+
let poly = [1]
|
|
22
|
+
for (let i = 0; i < degree; i++) {
|
|
23
|
+
const next = new Array(poly.length + 1).fill(0)
|
|
24
|
+
for (let j = 0; j < poly.length; j++) { next[j] ^= poly[j]; next[j + 1] ^= gmul(poly[j], EXP[i]) }
|
|
25
|
+
poly = next
|
|
26
|
+
}
|
|
27
|
+
return poly // highest-first, poly[0] == 1
|
|
28
|
+
}
|
|
29
|
+
function rsRemainder(data, gen) {
|
|
30
|
+
const res = new Uint8Array(gen.length - 1)
|
|
31
|
+
for (const b of data) {
|
|
32
|
+
const factor = b ^ res[0]
|
|
33
|
+
res.copyWithin(0, 1); res[res.length - 1] = 0
|
|
34
|
+
for (let i = 0; i < res.length; i++) res[i] ^= gmul(gen[i + 1], factor)
|
|
35
|
+
}
|
|
36
|
+
return res
|
|
37
|
+
}
|
|
38
|
+
function buildMatrix(ver, dataCodewords) {
|
|
39
|
+
const size = ver * 4 + 17
|
|
40
|
+
const modules = Array.from({ length: size }, () => new Uint8Array(size).fill(-1)) // -1 unset, 0/1 set
|
|
41
|
+
const isFunc = Array.from({ length: size }, () => new Uint8Array(size))
|
|
42
|
+
const set = (x, y, dark) => { modules[y][x] = dark ? 1 : 0; isFunc[y][x] = 1 }
|
|
43
|
+
function finder(x, y) {
|
|
44
|
+
for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
|
|
45
|
+
const xx = x + dx, yy = y + dy
|
|
46
|
+
if (xx < 0 || yy < 0 || xx >= size || yy >= size) continue
|
|
47
|
+
// standard 7x7 finder with 1-module separator: dark where not (ring 2 or separator ring 4)
|
|
48
|
+
const dist = Math.max(Math.abs(dx), Math.abs(dy))
|
|
49
|
+
const dark = dist !== 2 && dist !== 4
|
|
50
|
+
set(xx, yy, dark)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
finder(3, 3); finder(size - 4, 3); finder(3, size - 4)
|
|
54
|
+
for (let i = 0; i < size; i++) { if (!isFunc[6][i]) set(i, 6, i % 2 === 0); if (!isFunc[i][6]) set(6, i, i % 2 === 0) }
|
|
55
|
+
const ap = ALIGN[ver]
|
|
56
|
+
for (let j = 0; j < ap.length; j++) for (let i = 0; i < ap.length; i++) {
|
|
57
|
+
// Skip the three centers that would overlap a finder pattern.
|
|
58
|
+
if ((i === 0 && j === 0) || (i === 0 && j === ap.length - 1) || (i === ap.length - 1 && j === 0)) continue
|
|
59
|
+
const cx = ap[i], cy = ap[j]
|
|
60
|
+
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1)
|
|
61
|
+
}
|
|
62
|
+
// format areas are drawn after masking; mark them as function
|
|
63
|
+
for (let i = 0; i <= 8; i++) { if (i !== 6) { isFunc[8][i] = 1; modules[8][i] = 0 }; if (i !== 8) { isFunc[i][8] = 1; modules[i][8] = 0 } }
|
|
64
|
+
for (let i = 0; i < 8; i++) { isFunc[8][size - 1 - i] = 1; modules[8][size - 1 - i] = 0; isFunc[size - 1 - i][8] = 1; modules[size - 1 - i][8] = 0 }
|
|
65
|
+
isFunc[8][8] = 1; modules[8][8] = 0
|
|
66
|
+
if (ver >= 7) for (let i = 0; i < 18; i++) { const bit = Math.floor(i / 3), mod = i % 3; isFunc[bit][size - 11 + mod] = 1; modules[bit][size - 11 + mod] = 0; isFunc[size - 11 + mod][bit] = 1; modules[size - 11 + mod][bit] = 0 }
|
|
67
|
+
// place data zigzag
|
|
68
|
+
let bi = 0
|
|
69
|
+
const bits = dataCodewords.length * 8
|
|
70
|
+
for (let right = size - 1; right >= 1; right -= 2) {
|
|
71
|
+
if (right === 6) right = 5
|
|
72
|
+
for (let vert = 0; vert < size; vert++) {
|
|
73
|
+
for (const j of [0, 1]) {
|
|
74
|
+
const x = right - j
|
|
75
|
+
const upward = ((right + 1) & 2) === 0
|
|
76
|
+
const y = upward ? size - 1 - vert : vert
|
|
77
|
+
if (!isFunc[y][x] && bi < bits) { modules[y][x] = (dataCodewords[bi >> 3] >>> (7 - (bi & 7))) & 1; bi++ }
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return { size, modules, isFunc }
|
|
82
|
+
}
|
|
83
|
+
const MASKS = [
|
|
84
|
+
(x, y) => (x + y) % 2 === 0, (x, y) => y % 2 === 0, (x, y) => x % 3 === 0, (x, y) => (x + y) % 3 === 0,
|
|
85
|
+
(x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => (x * y) % 2 + (x * y) % 3 === 0,
|
|
86
|
+
(x, y) => ((x * y) % 2 + (x * y) % 3) % 2 === 0, (x, y) => ((x + y) % 2 + (x * y) % 3) % 2 === 0,
|
|
87
|
+
]
|
|
88
|
+
function applyMask(m, mask) { const { size, modules, isFunc } = m; for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (!isFunc[y][x] && mask(x, y)) modules[y][x] ^= 1 }
|
|
89
|
+
function drawFormat(m, mask) {
|
|
90
|
+
const { size, modules } = m
|
|
91
|
+
const data = (0 << 3) | mask // ECC level M = 0
|
|
92
|
+
let rem = data
|
|
93
|
+
for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537)
|
|
94
|
+
const bits = ((data << 10) | rem) ^ 0x5412
|
|
95
|
+
for (let i = 0; i <= 5; i++) modules[i][8] = (bits >>> i) & 1
|
|
96
|
+
modules[7][8] = (bits >>> 6) & 1; modules[8][8] = (bits >>> 7) & 1; modules[8][7] = (bits >>> 8) & 1
|
|
97
|
+
for (let i = 9; i < 15; i++) modules[8][14 - i] = (bits >>> i) & 1
|
|
98
|
+
for (let i = 0; i < 8; i++) modules[8][size - 1 - i] = (bits >>> i) & 1
|
|
99
|
+
for (let i = 8; i < 15; i++) modules[size - 15 + i][8] = (bits >>> i) & 1
|
|
100
|
+
modules[size - 8][8] = 1
|
|
101
|
+
}
|
|
102
|
+
function drawVersion(m, ver) {
|
|
103
|
+
const { size, modules } = m
|
|
104
|
+
let rem = ver
|
|
105
|
+
for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25)
|
|
106
|
+
const bits = (ver << 12) | rem
|
|
107
|
+
for (let i = 0; i < 18; i++) { const bit = (bits >>> i) & 1; modules[Math.floor(i / 3)][size - 11 + (i % 3)] = bit; modules[size - 11 + (i % 3)][Math.floor(i / 3)] = bit }
|
|
108
|
+
}
|
|
109
|
+
function penalty(m) {
|
|
110
|
+
const { size, modules } = m; let s = 0
|
|
111
|
+
const run = (get) => { let n = 0; for (let a = 0; a < size; a++) { let cnt = 1; for (let b = 1; b <= size; b++) { const v = b < size ? get(b, a) : -1; if (v === get(b - 1, a) && v !== -1) cnt++; else { if (cnt >= 5) n += 3 + (cnt - 5); cnt = 1 } } } return n }
|
|
112
|
+
s += run((i, a) => modules[a][i]) + run((i, a) => modules[i][a])
|
|
113
|
+
for (let y = 0; y < size - 1; y++) for (let x = 0; x < size - 1; x++) { const c = modules[y][x]; if (c === modules[y][x + 1] && c === modules[y + 1][x] && c === modules[y + 1][x + 1]) s += 3 }
|
|
114
|
+
const pat = [1, 0, 1, 1, 1, 0, 1]
|
|
115
|
+
for (let a = 0; a < size; a++) for (let b = 0; b + 7 <= size; b++) {
|
|
116
|
+
let hx = true, vx = true
|
|
117
|
+
for (let k = 0; k < 7; k++) { if (modules[a][b + k] !== pat[k]) hx = false; if (modules[b + k][a] !== pat[k]) vx = false }
|
|
118
|
+
if (hx) s += 40; if (vx) s += 40
|
|
119
|
+
}
|
|
120
|
+
let dark = 0; for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) dark += modules[y][x]
|
|
121
|
+
const k = Math.ceil(Math.abs(dark * 20 - size * size * 10) / (size * size)) - 1
|
|
122
|
+
s += Math.max(0, k) * 10
|
|
123
|
+
return s
|
|
124
|
+
}
|
|
125
|
+
function encode(text) {
|
|
126
|
+
const bytes = new TextEncoder().encode(text)
|
|
127
|
+
let ver = 0
|
|
128
|
+
for (let v = 1; v <= 10; v++) { const [nb, ec] = ECC_M[v]; const cap = TOTAL[v] - nb * ec; const ccBits = v <= 9 ? 8 : 16; if (4 + ccBits + bytes.length * 8 <= cap * 8) { ver = v; break } }
|
|
129
|
+
if (!ver) throw new Error('text too long for QR v10')
|
|
130
|
+
const [nb, ec] = ECC_M[ver]
|
|
131
|
+
const dataLen = TOTAL[ver] - nb * ec
|
|
132
|
+
const bb = []
|
|
133
|
+
const push = (val, n) => { for (let i = n - 1; i >= 0; i--) bb.push((val >>> i) & 1) }
|
|
134
|
+
push(0x4, 4); push(bytes.length, ver <= 9 ? 8 : 16); for (const b of bytes) push(b, 8)
|
|
135
|
+
const cap = dataLen * 8; push(0, Math.min(4, cap - bb.length)); while (bb.length % 8) bb.push(0)
|
|
136
|
+
for (let pad = 0xEC; bb.length < cap; pad ^= 0xEC ^ 0x11) push(pad, 8)
|
|
137
|
+
const data = Uint8Array.from(bb.reduce((a, _, i) => (i % 8 === 0 ? a.push(0) : a, a[a.length - 1] |= bb[i] << (7 - (i % 8)), a), []))
|
|
138
|
+
// ISO 18004: data is split sequentially into short blocks first, then the
|
|
139
|
+
// last (dataLen % nb) blocks take one extra codeword each.
|
|
140
|
+
const shortLen = Math.floor(dataLen / nb), longCount = dataLen % nb
|
|
141
|
+
const gen = rsGenerator(ec); const blocks = [], eccs = []
|
|
142
|
+
for (let i = 0, off = 0; i < nb; i++) { const len = shortLen + (i >= nb - longCount ? 1 : 0); const blk = data.subarray(off, off + len); off += len; blocks.push(blk); eccs.push(rsRemainder(blk, gen)) }
|
|
143
|
+
const all = []
|
|
144
|
+
for (let i = 0; i < shortLen + 1; i++) for (let b = 0; b < nb; b++) if (i < blocks[b].length) all.push(blocks[b][i])
|
|
145
|
+
for (let i = 0; i < ec; i++) for (let b = 0; b < nb; b++) all.push(eccs[b][i])
|
|
146
|
+
const codewords = Uint8Array.from(all)
|
|
147
|
+
let best = null, bestPenalty = Infinity
|
|
148
|
+
for (let mi = 0; mi < 8; mi++) {
|
|
149
|
+
const m = buildMatrix(ver, codewords); applyMask(m, MASKS[mi]); drawFormat(m, mi); if (ver >= 7) drawVersion(m, ver)
|
|
150
|
+
const p = penalty(m); if (p < bestPenalty) { bestPenalty = p; best = m }
|
|
151
|
+
}
|
|
152
|
+
return best
|
|
153
|
+
}
|
|
154
|
+
function QrCanvas({ text, size: px = 220 }) {
|
|
155
|
+
const ref = React.useRef(null)
|
|
156
|
+
React.useEffect(() => {
|
|
157
|
+
const canvas = ref.current; if (!canvas) return
|
|
158
|
+
let m; try { m = encode(text) } catch { canvas.replaceChildren(); return }
|
|
159
|
+
const quiet = 4, n = m.size + quiet * 2, scale = Math.max(1, Math.floor(px / n))
|
|
160
|
+
canvas.width = canvas.height = n * scale
|
|
161
|
+
const g = canvas.getContext('2d'); g.fillStyle = '#fff'; g.fillRect(0, 0, canvas.width, canvas.height); g.fillStyle = '#111'
|
|
162
|
+
for (let y = 0; y < m.size; y++) for (let x = 0; x < m.size; x++) if (m.modules[y][x]) g.fillRect((x + quiet) * scale, (y + quiet) * scale, scale, scale)
|
|
163
|
+
}, [text, px])
|
|
164
|
+
return React.createElement('canvas', { ref, style: { width: px, height: px, borderRadius: 8, display: 'block' } })
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ---------- panel state ----------
|
|
168
|
+
const CLIENT_BUILD = '2026-12-04.5'
|
|
169
|
+
let open = false
|
|
170
|
+
const listeners = new Set()
|
|
171
|
+
const subscribe = (fn) => { listeners.add(fn); return () => listeners.delete(fn) }
|
|
172
|
+
const getOpen = () => open
|
|
173
|
+
const setOpen = (v) => { open = v; listeners.forEach((fn) => fn()) }
|
|
174
|
+
const RENEW_AFTER_ELAPSED_DAYS = 1
|
|
175
|
+
async function fetchStatus() {
|
|
176
|
+
const res = await fetch('/api/__trust/status?build=' + encodeURIComponent(CLIENT_BUILD) + '&ua=' + encodeURIComponent(navigator.userAgent.slice(0, 120)), { credentials: 'same-origin', cache: 'no-store' })
|
|
177
|
+
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
178
|
+
const status = await res.json()
|
|
179
|
+
// Self-heal a stale bundle (e.g. an iOS home-screen app resumed from memory):
|
|
180
|
+
// reload once when the host ships a newer client build.
|
|
181
|
+
try {
|
|
182
|
+
if (status.clientBuild && status.clientBuild !== CLIENT_BUILD && sessionStorage.getItem('trust-device-build') !== status.clientBuild) {
|
|
183
|
+
sessionStorage.setItem('trust-device-build', status.clientBuild)
|
|
184
|
+
location.reload()
|
|
185
|
+
throw new Error('reloading')
|
|
186
|
+
}
|
|
187
|
+
} catch (e) { if (e && e.message === 'reloading') throw e }
|
|
188
|
+
return status
|
|
189
|
+
}
|
|
190
|
+
// Follow the 302 to the authenticated URL; DSH's index exchange sets a fresh cookie.
|
|
191
|
+
async function renewNow() {
|
|
192
|
+
const res = await fetch('/api/__trust/renew', { credentials: 'same-origin', redirect: 'follow', cache: 'no-store' })
|
|
193
|
+
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
194
|
+
}
|
|
195
|
+
function elapsedDays(session) {
|
|
196
|
+
if (!session) return Infinity
|
|
197
|
+
const lifetime = session.expiresAt - session.issuedAt
|
|
198
|
+
return (lifetime - (session.expiresAt - Date.now())) / 86_400_000
|
|
199
|
+
}
|
|
200
|
+
// Sliding session: once this cookie is at least RENEW_AFTER_ELAPSED_DAYS old, renew quietly.
|
|
201
|
+
async function renewSilently() {
|
|
202
|
+
try {
|
|
203
|
+
const status = await fetchStatus()
|
|
204
|
+
const after = Number(status.renewAfterElapsedDays) > 0 ? Number(status.renewAfterElapsedDays) : RENEW_AFTER_ELAPSED_DAYS
|
|
205
|
+
if (elapsedDays(status.session) >= after) await renewNow()
|
|
206
|
+
} catch { /* offline or unauthenticated: try again on the next load */ }
|
|
207
|
+
}
|
|
208
|
+
const fmtDay = (ms) => new Date(ms).toLocaleDateString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' })
|
|
209
|
+
|
|
210
|
+
function FooterButton() {
|
|
211
|
+
const isOpen = React.useSyncExternalStore(subscribe, getOpen)
|
|
212
|
+
return React.createElement('button', {
|
|
213
|
+
type: 'button', title: t('title'), onClick: () => setOpen(!isOpen),
|
|
214
|
+
style: { background: 'none', border: 0, color: isOpen ? 'var(--accent, #4f8cff)' : 'inherit', cursor: 'pointer', padding: 6, display: 'flex', alignItems: 'center' },
|
|
215
|
+
}, React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
|
|
216
|
+
React.createElement('rect', { x: 3, y: 3, width: 7, height: 7, rx: 1 }), React.createElement('rect', { x: 14, y: 3, width: 7, height: 7, rx: 1 }), React.createElement('rect', { x: 3, y: 14, width: 7, height: 7, rx: 1 }),
|
|
217
|
+
React.createElement('path', { d: 'M14 14h3v3h-3zM18 18h3v3h-3z' })))
|
|
218
|
+
}
|
|
219
|
+
function Panel() {
|
|
220
|
+
const [status, setStatus] = React.useState(null)
|
|
221
|
+
const [err, setErr] = React.useState('')
|
|
222
|
+
const [copied, setCopied] = React.useState('')
|
|
223
|
+
const [more, setMore] = React.useState(false)
|
|
224
|
+
const [renewing, setRenewing] = React.useState(false)
|
|
225
|
+
React.useEffect(() => {
|
|
226
|
+
let alive = true
|
|
227
|
+
fetchStatus().then((j) => { if (alive) setStatus(j) }).catch((e) => { if (alive) setErr(String(e.message || e)) })
|
|
228
|
+
return () => { alive = false }
|
|
229
|
+
}, [])
|
|
230
|
+
const copy = async (text, label) => { try { await navigator.clipboard.writeText(text); setCopied(label); setTimeout(() => setCopied(''), 1500) } catch { setErr(t('copyFail')) } }
|
|
231
|
+
const renew = async () => {
|
|
232
|
+
setRenewing(true); setErr('')
|
|
233
|
+
try { await renewNow(); setStatus(await fetchStatus()) } catch (e) { setErr(String(e.message || e)) } finally { setRenewing(false) }
|
|
234
|
+
}
|
|
235
|
+
// Take colors from the host shell so the panel follows the DSH theme (light/dark)
|
|
236
|
+
// instead of assuming a dark surface.
|
|
237
|
+
const theme = React.useMemo(() => {
|
|
238
|
+
const btn = document.querySelector('button[title="远程访问"]')
|
|
239
|
+
const surface = (btn && btn.closest('nav, aside, [class*="sidebar"]')) || document.body
|
|
240
|
+
const cs = getComputedStyle(surface), cb = btn ? getComputedStyle(btn) : cs
|
|
241
|
+
const fg = cb.color || cs.color || '#111'
|
|
242
|
+
const bg = cs.backgroundColor && cs.backgroundColor !== 'rgba(0, 0, 0, 0)' ? cs.backgroundColor : getComputedStyle(document.body).backgroundColor
|
|
243
|
+
return { fg, bg }
|
|
244
|
+
}, [])
|
|
245
|
+
const mix = (color, pct) => 'color-mix(in srgb, ' + color + ' ' + pct + '%, transparent)'
|
|
246
|
+
const btn = { padding: '8px 14px', borderRadius: 10, border: '1px solid ' + mix(theme.fg, 22), background: mix(theme.fg, 6), color: theme.fg, cursor: 'pointer', fontSize: 14 }
|
|
247
|
+
const card = { background: theme.bg, color: theme.fg, border: '1px solid ' + mix(theme.fg, 12), borderRadius: 16, width: 'min(92vw, 380px)', padding: 22, boxShadow: '0 20px 60px rgba(0,0,0,.35)' }
|
|
248
|
+
const muted = { fontSize: 13, opacity: 0.65, lineHeight: 1.5 }
|
|
249
|
+
const qrText = status && (status.installUrl || status.url)
|
|
250
|
+
return React.createElement('div', { style: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,.55)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }, onMouseDown: (e) => { if (e.target === e.currentTarget) setOpen(false) } },
|
|
251
|
+
React.createElement('div', { style: card, role: 'dialog', 'aria-label': t('title') },
|
|
252
|
+
React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 } },
|
|
253
|
+
React.createElement('strong', { style: { fontSize: 15 } }, t('title')),
|
|
254
|
+
React.createElement('button', { type: 'button', style: { ...btn, padding: '0 8px', border: 0, fontSize: 20, lineHeight: '24px' }, onClick: () => setOpen(false), 'aria-label': t('close') }, '×')),
|
|
255
|
+
err && !status && React.createElement('p', { style: { color: '#ff7b72', fontSize: 13, margin: 0 } }, t('error', { c: err })),
|
|
256
|
+
qrText && React.createElement('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 } },
|
|
257
|
+
React.createElement('div', { style: { background: '#fff', padding: 8, borderRadius: 12, lineHeight: 0 } }, React.createElement(QrCanvas, { text: qrText, size: 200 })),
|
|
258
|
+
React.createElement('div', { style: { fontSize: 14, textAlign: 'center', lineHeight: 1.6 } },
|
|
259
|
+
t('hint1'),
|
|
260
|
+
React.createElement('br'),
|
|
261
|
+
React.createElement('b', null, t('share')), ' → ', React.createElement('b', null, t('addHs'))),
|
|
262
|
+
),
|
|
263
|
+
status && React.createElement('div', { style: { display: 'flex', justifyContent: 'center', marginTop: 16 } },
|
|
264
|
+
React.createElement('button', { type: 'button', style: { ...btn, border: 0, opacity: 0.7, textDecoration: 'underline', fontSize: 13 }, onClick: () => setMore(!more) }, more ? t('less') : t('more'))),
|
|
265
|
+
status && more && React.createElement('div', { style: { marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 } },
|
|
266
|
+
React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
|
|
267
|
+
React.createElement('button', { type: 'button', style: btn, onClick: () => copy(status.installUrl || status.url, 'link') }, copied === 'link' ? t('copied') : t('copyLink')),
|
|
268
|
+
React.createElement('button', { type: 'button', style: btn, onClick: () => copy(status.advertisedUrl, 'addr') }, copied === 'addr' ? t('copied') : t('copyAddr')),
|
|
269
|
+
status.session && React.createElement('button', { type: 'button', style: btn, disabled: renewing, onClick: renew }, renewing ? t('renewing') : t('renew'))),
|
|
270
|
+
status.session && React.createElement('p', { style: muted }, t('session', { n: Math.floor(status.session.remainingDays) })),
|
|
271
|
+
React.createElement('p', { style: muted }, t('secret')),
|
|
272
|
+
status.version && React.createElement('p', { style: { ...muted, fontSize: 11 } }, 'dsh-trust-device v' + status.version))))
|
|
273
|
+
}
|
|
274
|
+
function OverlayEntry() { const isOpen = React.useSyncExternalStore(subscribe, getOpen); return isOpen ? React.createElement(Panel) : null }
|
|
275
|
+
|
|
276
|
+
const STRINGS = {
|
|
277
|
+
title: ['远程访问', 'Remote access'],
|
|
278
|
+
hint1: ['手机相机扫码,然后在打开的页面里', 'Scan with your phone camera, then on the page that opens'],
|
|
279
|
+
share: ['分享', 'Share'], addHs: ['添加到主屏幕', 'Add to Home Screen'],
|
|
280
|
+
more: ['更多', 'More'], less: ['收起', 'Less'],
|
|
281
|
+
copyLink: ['复制二维码链接', 'Copy QR link'], copyAddr: ['复制访问地址', 'Copy address'],
|
|
282
|
+
renew: ['立即续期', 'Renew now'], renewing: ['续期中…', 'Renewing…'],
|
|
283
|
+
copied: ['已复制', 'Copied'],
|
|
284
|
+
session: ['本机登录态:剩余 {n} 天,每天使用会自动续期。', 'Signed in here for {n} more days; renews automatically with daily use.'],
|
|
285
|
+
secret: ['二维码链接等同于密码,只给信任的设备。', 'The QR link works like a password. Share it only with devices you trust.'],
|
|
286
|
+
error: ['无法读取状态(HTTP {c})', 'Could not read status (HTTP {c})'],
|
|
287
|
+
copyFail: ['复制失败', 'Copy failed'], close: ['关闭', 'Close'],
|
|
288
|
+
}
|
|
289
|
+
let lang = 'zh'
|
|
290
|
+
const t = (key, vars) => {
|
|
291
|
+
const pair = STRINGS[key] || [key, key]
|
|
292
|
+
let str = pair[lang === 'en' ? 1 : 0]
|
|
293
|
+
if (vars) for (const k of Object.keys(vars)) str = str.replace('{' + k + '}', String(vars[k]))
|
|
294
|
+
return str
|
|
295
|
+
}
|
|
296
|
+
const inject = ['slots', 'locale']
|
|
297
|
+
function apply(ctx) {
|
|
298
|
+
try {
|
|
299
|
+
const sync = () => { const active = (ctx.locale && ctx.locale.getSnapshot && ctx.locale.getSnapshot().active) || ''; lang = active.toLowerCase().startsWith('en') ? 'en' : 'zh' }
|
|
300
|
+
sync()
|
|
301
|
+
ctx.effect(() => (ctx.locale && ctx.locale.subscribe && ctx.locale.subscribe(sync)) || (() => {}), 'trust-device: locale')
|
|
302
|
+
} catch { /* locale service unavailable: stay zh */ }
|
|
303
|
+
ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register(
|
|
304
|
+
{ name: 'sidebar.footer.action', id: 'trust-device', order: 90, label: t('title') },
|
|
305
|
+
() => React.createElement(FooterButton),
|
|
306
|
+
))
|
|
307
|
+
ctx.slots.inject('shell.overlay', () => ctx.slots.register(
|
|
308
|
+
{ name: 'shell.overlay', id: 'trust-device-panel', order: 100, label: t('title') },
|
|
309
|
+
() => React.createElement(OverlayEntry),
|
|
310
|
+
))
|
|
311
|
+
void renewSilently()
|
|
312
|
+
}
|
|
313
|
+
exports.apply = apply
|
|
314
|
+
exports.inject = inject
|
|
315
|
+
return module.exports
|
|
316
|
+
},
|
|
317
|
+
})
|
package/lib/index.mjs
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Host half of dsh-trust-device.
|
|
2
|
+
//
|
|
3
|
+
// Two exact Fetch routes on the connection's shared /api channel (authenticated
|
|
4
|
+
// and owner-only by the connection before dispatch), plus one public pair outside
|
|
5
|
+
// /api: an install/login page for iOS home-screen web apps (whose cookie jar is
|
|
6
|
+
// isolated from Safari) and a per-install web app manifest whose start_url carries
|
|
7
|
+
// the launch token, so the installed app signs itself in on first launch.
|
|
8
|
+
import { createRequire } from 'node:module'
|
|
9
|
+
import { appendFileSync, readFileSync } from 'node:fs'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { fileURLToPath } from 'node:url'
|
|
13
|
+
// Opt-in diagnostics: DSH_TRUST_DEVICE_DIAG=/path/to/file
|
|
14
|
+
const diag = (...a) => {
|
|
15
|
+
try { appendFileSync(process.env.DSH_TRUST_DEVICE_DIAG || join(homedir(), '.dsh/logs/trust-device.log'), new Date().toISOString() + ' ' + a.map(String).join(' ') + '\n') } catch { /* ignore */ }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const name = 'dsh-trust-device'
|
|
19
|
+
// Build id baked into lib/client.js; a browser still running another build reloads once.
|
|
20
|
+
const CLIENT_BUILD = (() => {
|
|
21
|
+
try { return /CLIENT_BUILD = '([^']+)'/.exec(readFileSync(fileURLToPath(new URL('./client.js', import.meta.url)), 'utf8'))?.[1] ?? null } catch { return null }
|
|
22
|
+
})()
|
|
23
|
+
const VERSION = (() => {
|
|
24
|
+
try { return createRequire(import.meta.url)('../package.json').version } catch { return 'dev' }
|
|
25
|
+
})()
|
|
26
|
+
|
|
27
|
+
export const inject = ['connection', 'webServer', 'webApp']
|
|
28
|
+
|
|
29
|
+
const TOKEN_RE = /^[A-Za-z0-9_-]{8,128}$/
|
|
30
|
+
const MANIFEST_PATH = '/__trust/manifest.webmanifest'
|
|
31
|
+
const PWA_PATH = '/__trust/pwa'
|
|
32
|
+
|
|
33
|
+
// The browser cookie is "v<version>.<base64url(JSON)>.<hmac>" (dsh-client-connection
|
|
34
|
+
// browser-auth.ts). The request reaching an exact route was already verified by
|
|
35
|
+
// the connection, so decoding the JSON body here is display-only and needs no key.
|
|
36
|
+
export function readSessionCookie(request, now = Date.now()) {
|
|
37
|
+
const header = request.headers.get('cookie') ?? ''
|
|
38
|
+
for (const part of header.split(';')) {
|
|
39
|
+
const [name, ...rest] = part.trim().split('=')
|
|
40
|
+
if (!name?.startsWith('dsh-auth-')) continue
|
|
41
|
+
const value = rest.join('=')
|
|
42
|
+
const [version, body] = value.split('.')
|
|
43
|
+
if (!body) continue
|
|
44
|
+
try {
|
|
45
|
+
const padded = body.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (body.length % 4)) % 4)
|
|
46
|
+
const payload = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'))
|
|
47
|
+
if (typeof payload.issuedAt === 'number' && typeof payload.expiresAt === 'number') {
|
|
48
|
+
return { version: Number(version.slice(1)), issuedAt: payload.issuedAt, expiresAt: payload.expiresAt, remainingDays: Math.max(0, (payload.expiresAt - now) / 86_400_000) }
|
|
49
|
+
}
|
|
50
|
+
} catch { /* malformed cookie: the connection would have rejected it */ }
|
|
51
|
+
}
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function tokenFrom(url) {
|
|
56
|
+
const t = url.searchParams.get('token') ?? ''
|
|
57
|
+
return TOKEN_RE.test(t) ? t : null
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function manifest(token) {
|
|
61
|
+
return {
|
|
62
|
+
id: '/', name: 'DeepSeek Harness', short_name: 'DSH',
|
|
63
|
+
start_url: token ? PWA_PATH + '?token=' + encodeURIComponent(token) : PWA_PATH,
|
|
64
|
+
scope: '/', display: 'standalone', orientation: 'any',
|
|
65
|
+
background_color: '#121212', theme_color: '#121212', lang: 'zh',
|
|
66
|
+
icons: [
|
|
67
|
+
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
|
|
68
|
+
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
|
|
69
|
+
{ src: '/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
|
|
70
|
+
],
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The install/login page. Query `?token=` (from the computer's QR) signs THIS browser
|
|
75
|
+
// in and prepares a per-install manifest so the Home Screen app starts with the
|
|
76
|
+
// token and signs its own isolated jar in on first launch.
|
|
77
|
+
const HTML = `<!doctype html>
|
|
78
|
+
<html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
|
79
|
+
<meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
|
80
|
+
<meta name="apple-mobile-web-app-title" content="DSH"><title>DeepSeek Harness</title>
|
|
81
|
+
<style>
|
|
82
|
+
html,body{height:100%;margin:0;background:#121212;color:#eee;font:16px -apple-system,system-ui,sans-serif;-webkit-text-size-adjust:100%}
|
|
83
|
+
.c{max-width:420px;margin:0 auto;padding:max(28px,env(safe-area-inset-top)) 22px 28px;display:flex;flex-direction:column;gap:16px;min-height:100%;box-sizing:border-box}
|
|
84
|
+
.logo{width:72px;height:72px;border-radius:18px;display:block}
|
|
85
|
+
h1{font-size:22px;margin:4px 0 0}p{opacity:.75;line-height:1.55;margin:0}
|
|
86
|
+
.step{display:flex;gap:12px;align-items:flex-start;background:#1c1c1c;border-radius:12px;padding:12px 14px}
|
|
87
|
+
.step b{display:inline-flex;width:24px;height:24px;border-radius:50%;background:#4f8cff;color:#fff;align-items:center;justify-content:center;font-size:13px;flex:none;margin-top:1px}
|
|
88
|
+
.step span{line-height:1.45}
|
|
89
|
+
input{width:100%;box-sizing:border-box;padding:13px 14px;border-radius:10px;border:1px solid #333;background:#1c1c1c;color:#eee;font-size:15px}
|
|
90
|
+
button{padding:13px 16px;border-radius:12px;border:1px solid #333;background:#2a2a2a;color:#eee;font-size:16px;cursor:pointer}
|
|
91
|
+
.primary{background:#4f8cff;border-color:#4f8cff;color:#fff}
|
|
92
|
+
.s{display:flex;justify-content:center;padding:48px 0}.spin{width:28px;height:28px;border:3px solid #444;border-top-color:#4f8cff;border-radius:50%;animation:r .9s linear infinite}@keyframes r{to{transform:rotate(360deg)}}
|
|
93
|
+
.ok{color:#3fb950;font-weight:600}.share{display:inline-block;padding:0 4px;border:1px solid #555;border-radius:6px}
|
|
94
|
+
</style></head><body><div class="c" id="c"><div class="s"><div class="spin"></div></div></div>
|
|
95
|
+
<script>
|
|
96
|
+
(function(){
|
|
97
|
+
var ZH = !/^en/i.test(navigator.language || 'zh')
|
|
98
|
+
var T = function(zh, en){ return ZH ? zh : en }
|
|
99
|
+
var c = document.getElementById('c'), q = new URLSearchParams(location.search), token = q.get('token') || ''
|
|
100
|
+
function esc(s){ return String(s).replace(/[&<>"]/g, function(m){ return {'&':'&','<':'<','>':'>','"':'"'}[m] }) }
|
|
101
|
+
function spin(){ c.innerHTML = '<div class="s"><div class="spin"></div></div>' }
|
|
102
|
+
function head(extra){ return '<img class="logo" src="/icon-192.png" alt=""><h1>DeepSeek Harness</h1>' + (extra || '') }
|
|
103
|
+
function exchange(t){ return fetch('/?token=' + encodeURIComponent(t), { credentials: 'same-origin', redirect: 'follow', cache: 'no-store' }).then(function(r){ if (!r.ok) throw new Error(String(r.status)) }) }
|
|
104
|
+
function probe(){ return fetch('/api/__trust/status', { credentials: 'same-origin', cache: 'no-store' }) }
|
|
105
|
+
function enter(){ location.replace('/') }
|
|
106
|
+
// Safari: already signed in by the exchange above; tell the user how to install.
|
|
107
|
+
function installPage(){
|
|
108
|
+
if (token) { var l = document.createElement('link'); l.rel = 'manifest'; l.href = '/__trust/manifest.webmanifest?token=' + encodeURIComponent(token); document.head.appendChild(l) }
|
|
109
|
+
c.innerHTML = head('<p class="ok">✓ ' + T('这台设备已登录','This device is signed in') + '</p>') +
|
|
110
|
+
'<div class="step"><b>1</b><span>' + T('点 Safari 底部的 <span class="share">分享</span> 按钮(方框向上箭头)','Tap Safari's <span class="share">Share</span> button (square with an up arrow)') + '</span></div>' +
|
|
111
|
+
'<div class="step"><b>2</b><span>' + T('选「添加到主屏幕」,确认','Choose Add to Home Screen and confirm') + '</span></div>' +
|
|
112
|
+
'<div class="step"><b>3</b><span>' + T('以后从主屏幕打开,全屏使用,不用再登录','Open it from the Home Screen from now on; no need to sign in again') + '</span></div>' +
|
|
113
|
+
'<button class="primary" id="open">' + T('先在 Safari 里用一下','Use it in Safari for now') + '</button>' +
|
|
114
|
+
'<p style="font-size:13px">' + T('也可以不装,直接在 Safari 用。','Installing is optional; Safari works too.') + '</p>'
|
|
115
|
+
document.getElementById('open').onclick = enter
|
|
116
|
+
}
|
|
117
|
+
function form(msg){
|
|
118
|
+
c.innerHTML = head('<p>' + esc(msg) + '</p>') +
|
|
119
|
+
'<p>' + T('在电脑或已登录的设备上打开 DSH → 侧栏底部「远程访问」→ 扫码或复制授权链接,粘贴到下面。','On your computer or any signed-in device: DSH → Remote access (bottom of the sidebar) → scan or copy the link, then paste it here.') + '</p>' +
|
|
120
|
+
'<input id="u" type="url" placeholder="https://' + esc(location.host) + '/?token=…" autocomplete="off" autocapitalize="off" spellcheck="false">' +
|
|
121
|
+
'<button class="primary" id="go">' + T('登录','Sign in') + '</button>' +
|
|
122
|
+
'<p style="font-size:13px">' + T('链接等同于密码,不要转发。','The link works like a password. Do not forward it.') + '</p>'
|
|
123
|
+
var u = document.getElementById('u'), go = document.getElementById('go')
|
|
124
|
+
function submit(){ var v = u.value.trim(), t = ''; try { t = new URL(v).searchParams.get('token') || '' } catch (e) {} if (!t) { u.style.borderColor = '#ff7b72'; return } location.replace('/?token=' + encodeURIComponent(t)) }
|
|
125
|
+
go.onclick = submit; u.onkeydown = function(e){ if (e.key === 'Enter') submit() }
|
|
126
|
+
}
|
|
127
|
+
var isStandalone = window.navigator.standalone === true || window.matchMedia('(display-mode: standalone)').matches
|
|
128
|
+
if (token) {
|
|
129
|
+
exchange(token).then(function(){
|
|
130
|
+
// Inside the installed app: go straight in. In Safari: stay and guide the install.
|
|
131
|
+
if (isStandalone) enter(); else installPage()
|
|
132
|
+
}).catch(function(){ form(T('授权链接已失效(DSH 可能重启过)。请重新扫码。','This link has expired (DSH may have restarted). Scan again.')) })
|
|
133
|
+
return
|
|
134
|
+
}
|
|
135
|
+
probe().then(function(r){ if (r.ok) enter(); else form(T('这台设备还没有登录。','This device is not signed in yet.')) }).catch(function(){ form(T('暂时连不上电脑。确认 Tailscale 已连接,然后重新打开。','Cannot reach the computer right now. Check that Tailscale is connected and try again.')) })
|
|
136
|
+
})()
|
|
137
|
+
</script></body></html>`
|
|
138
|
+
|
|
139
|
+
export function apply(ctx, config) {
|
|
140
|
+
const renewAfterElapsedDays = Number(config && config.renewAfterElapsedDays) > 0 ? Number(config.renewAfterElapsedDays) : 1
|
|
141
|
+
diag('apply start')
|
|
142
|
+
const advertised = () => {
|
|
143
|
+
try {
|
|
144
|
+
return ctx.webApp.getAdvertisedUrl()
|
|
145
|
+
} catch {
|
|
146
|
+
return ctx.webServer?.getOrigin?.() ?? ''
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const authenticated = () => ctx.connection.authenticatedUrl(advertised())
|
|
150
|
+
const tokenOf = () => tokenFrom(new URL(authenticated()))
|
|
151
|
+
const absolute = (pathAndQuery) => new URL(pathAndQuery, advertised()).href
|
|
152
|
+
const noStore = { 'cache-control': 'no-store' }
|
|
153
|
+
|
|
154
|
+
const statusRoute = {
|
|
155
|
+
path: '/api/__trust/status',
|
|
156
|
+
methods: ['GET'],
|
|
157
|
+
requestBody: 'buffered',
|
|
158
|
+
fetch: async (request) => {
|
|
159
|
+
diag('status', JSON.stringify({ build: new URL(request.url).searchParams.get('build'), ua: (request.headers.get('user-agent') || '').slice(0, 110), mode: request.headers.get('sec-fetch-mode'), standalone: request.headers.get('sec-fetch-mode') === 'navigate' ? undefined : undefined }))
|
|
160
|
+
const token = tokenOf()
|
|
161
|
+
return Response.json({
|
|
162
|
+
advertisedUrl: advertised(),
|
|
163
|
+
url: authenticated(),
|
|
164
|
+
renewPath: '/api/__trust/renew',
|
|
165
|
+
pwaUrl: absolute(PWA_PATH),
|
|
166
|
+
installUrl: token ? absolute(PWA_PATH + '?token=' + encodeURIComponent(token)) : null,
|
|
167
|
+
session: readSessionCookie(request),
|
|
168
|
+
version: VERSION,
|
|
169
|
+
clientBuild: CLIENT_BUILD,
|
|
170
|
+
renewAfterElapsedDays,
|
|
171
|
+
}, { headers: noStore })
|
|
172
|
+
},
|
|
173
|
+
}
|
|
174
|
+
const renewRoute = {
|
|
175
|
+
path: '/api/__trust/renew',
|
|
176
|
+
methods: ['GET'],
|
|
177
|
+
requestBody: 'buffered',
|
|
178
|
+
fetch: async () => new Response(null, { status: 302, headers: { location: authenticated(), ...noStore } }),
|
|
179
|
+
}
|
|
180
|
+
// Wire every registration through ctx.effect so removing the plugin disposes
|
|
181
|
+
// its routes; otherwise a stale entry makes the next install fail with
|
|
182
|
+
// "already registered" and the authenticated routes silently disappear.
|
|
183
|
+
try {
|
|
184
|
+
ctx.effect(() => ctx.connection.fetch.register(statusRoute), 'trust-device: status route')
|
|
185
|
+
ctx.effect(() => ctx.connection.fetch.register(renewRoute), 'trust-device: renew route')
|
|
186
|
+
diag('fetch routes registered')
|
|
187
|
+
} catch (e) {
|
|
188
|
+
diag('fetch route registration failed: ' + (e && e.stack || e))
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Public, unauthenticated. No secret is served: the page only forwards a token
|
|
192
|
+
// the caller already holds to DSH's own exchange route; the manifest echoes it
|
|
193
|
+
// back into start_url for the device that is installing the app.
|
|
194
|
+
const regPublic = (route, label) => { try { ctx.effect(() => ctx.webServer.register(route), label); diag(label + ' registered') } catch (e) { diag(label + ' failed: ' + (e && e.stack || e)) } }
|
|
195
|
+
regPublic({
|
|
196
|
+
kind: 'exact', path: PWA_PATH,
|
|
197
|
+
handler: (_req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...noStore }); res.end(HTML) },
|
|
198
|
+
}, 'trust-device: pwa page')
|
|
199
|
+
regPublic({
|
|
200
|
+
kind: 'exact', path: MANIFEST_PATH,
|
|
201
|
+
handler: (req, res) => {
|
|
202
|
+
const token = tokenFrom(new URL(req.url ?? '/', 'http://dsh.internal'))
|
|
203
|
+
res.writeHead(200, { 'content-type': 'application/manifest+json; charset=utf-8', ...noStore })
|
|
204
|
+
res.end(JSON.stringify(manifest(token)))
|
|
205
|
+
},
|
|
206
|
+
}, 'trust-device: manifest')
|
|
207
|
+
diag('apply done')
|
|
208
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ttxs69/dsh-trust-device",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"description": "DSH: remote-access panel with QR + sliding cookie renewal for trusted devices",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "lib/index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./lib/index.mjs",
|
|
9
|
+
"./client": "./lib/client.js",
|
|
10
|
+
"./package.json": "./package.json"
|
|
11
|
+
},
|
|
12
|
+
"dsh": {
|
|
13
|
+
"bundle": {
|
|
14
|
+
"patch": "./cordis.patch.yml"
|
|
15
|
+
},
|
|
16
|
+
"client": {
|
|
17
|
+
"platform": "web",
|
|
18
|
+
"inject": [
|
|
19
|
+
"@deepseek-ai/dsh-client-runtime",
|
|
20
|
+
"@deepseek-ai/dsh-client-ui-layout",
|
|
21
|
+
"@deepseek-ai/dsh-client-ui-sidebar"
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"cordis": null,
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"files": [
|
|
28
|
+
"lib",
|
|
29
|
+
"cordis.patch.yml"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"test": "node --test test/qr.test.mjs",
|
|
33
|
+
"test:e2e": "node test/e2e.mjs",
|
|
34
|
+
"test:pack": "npm pack --dry-run"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"jsqr": "^1.4.0",
|
|
38
|
+
"qrcode": "^1.5.4"
|
|
39
|
+
},
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/ttxs69/dsh-trust-device.git"
|
|
43
|
+
},
|
|
44
|
+
"bugs": "https://github.com/ttxs69/dsh-trust-device/issues",
|
|
45
|
+
"homepage": "https://github.com/ttxs69/dsh-trust-device#readme"
|
|
46
|
+
}
|