@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.7
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 +202 -0
- package/README.i18n.yaml +6 -0
- package/README.md +243 -2
- package/README.zh.md +244 -0
- package/cordis.patch.yml +17 -0
- package/lib/client.js +1830 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +3744 -0
- package/lib/types/client/PairEntry.d.ts +16 -0
- package/lib/types/client/PairPanel.d.ts +55 -0
- package/lib/types/client/icons.d.ts +18 -0
- package/lib/types/client/index.d.ts +35 -0
- package/lib/types/client/locales.d.ts +42 -0
- package/lib/types/client/pair-token.d.ts +73 -0
- package/lib/types/client/semantic.d.ts +28 -0
- package/lib/types/core/approvals.d.ts +75 -0
- package/lib/types/core/connection.d.ts +119 -0
- package/lib/types/core/crypto.d.ts +48 -0
- package/lib/types/core/devices.d.ts +72 -0
- package/lib/types/core/dsh-frames.d.ts +181 -0
- package/lib/types/core/envelope.d.ts +98 -0
- package/lib/types/core/gateway-errors.d.ts +49 -0
- package/lib/types/core/hub.d.ts +101 -0
- package/lib/types/core/loopback.d.ts +35 -0
- package/lib/types/core/owner-peer.d.ts +49 -0
- package/lib/types/core/pairing.d.ts +61 -0
- package/lib/types/core/protocol.d.ts +89 -0
- package/lib/types/core/questions.d.ts +246 -0
- package/lib/types/core/session-meta.d.ts +105 -0
- package/lib/types/core/session-permissions.d.ts +134 -0
- package/lib/types/core/wire.d.ts +115 -0
- package/lib/types/core/ws-frames.d.ts +61 -0
- package/lib/types/host/dsh-home.d.ts +16 -0
- package/lib/types/host/pair-origin.d.ts +44 -0
- package/lib/types/host/routes.d.ts +27 -0
- package/lib/types/host/websocket.d.ts +104 -0
- package/lib/types/index.d.ts +40 -0
- package/package.json +87 -3
- package/src/client/PairEntry.tsx +151 -0
- package/src/client/PairPanel.tsx +183 -0
- package/src/client/icons.tsx +72 -0
- package/src/client/index.ts +81 -0
- package/src/client/locales.ts +72 -0
- package/src/client/pair-token.ts +104 -0
- package/src/client/panel.module.css +344 -0
- package/src/client/semantic.ts +37 -0
- package/src/core/approvals.ts +142 -0
- package/src/core/connection.ts +1090 -0
- package/src/core/crypto.ts +113 -0
- package/src/core/devices.ts +209 -0
- package/src/core/dsh-frames.ts +486 -0
- package/src/core/envelope.ts +173 -0
- package/src/core/gateway-errors.ts +92 -0
- package/src/core/hub.ts +238 -0
- package/src/core/loopback.ts +60 -0
- package/src/core/owner-peer.ts +70 -0
- package/src/core/pairing.ts +113 -0
- package/src/core/protocol.ts +120 -0
- package/src/core/questions.ts +454 -0
- package/src/core/session-meta.ts +176 -0
- package/src/core/session-permissions.ts +266 -0
- package/src/core/wire.ts +155 -0
- package/src/core/ws-frames.ts +125 -0
- package/src/css-modules.d.ts +6 -0
- package/src/host/dsh-home.ts +42 -0
- package/src/host/pair-origin.ts +77 -0
- package/src/host/routes.ts +85 -0
- package/src/host/websocket.ts +325 -0
- package/src/index.ts +205 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pairing cryptography: base64url codecs, the SHA-256 the roster stores
|
|
3
|
+
* instead of secrets, and the ES256 (ECDSA P-256 + SHA-256) verification that
|
|
4
|
+
* admits a phone into the device roster.
|
|
5
|
+
*
|
|
6
|
+
* Nothing here is mocked away in tests: a test generates a real P-256 key pair
|
|
7
|
+
* with node:crypto and signs with it, so a broken curve check, a DER-vs-raw
|
|
8
|
+
* signature mismatch or a swapped digest fails the suite.
|
|
9
|
+
* @module dsh-remote-bridge/core/crypto
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { createHash, createPublicKey, randomBytes, timingSafeEqual, verify as cryptoVerify } from 'node:crypto'
|
|
13
|
+
|
|
14
|
+
/** Length of a raw (IEEE P1363, r||s) P-256 signature. */
|
|
15
|
+
export const ES256_SIGNATURE_BYTES = 64
|
|
16
|
+
|
|
17
|
+
const BASE64URL_RE = /^[A-Za-z0-9_-]+$/
|
|
18
|
+
|
|
19
|
+
/** Encode bytes as unpadded base64url. */
|
|
20
|
+
export function base64UrlEncode(bytes: Uint8Array): string {
|
|
21
|
+
return Buffer.from(bytes).toString('base64url')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Decode unpadded base64url text.
|
|
26
|
+
* @returns the bytes, or undefined when the text is not base64url.
|
|
27
|
+
*/
|
|
28
|
+
export function base64UrlDecode(text: string): Buffer | undefined {
|
|
29
|
+
if (text === '' || !BASE64URL_RE.test(text)) return undefined
|
|
30
|
+
const bytes = Buffer.from(text, 'base64url')
|
|
31
|
+
// Buffer.from is lenient: it drops unknown characters and stops early, so a
|
|
32
|
+
// re-encode is the only proof the text was canonical.
|
|
33
|
+
return bytes.toString('base64url') === text ? bytes : undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Lowercase hex SHA-256 of a byte string or UTF-8 text. */
|
|
37
|
+
export function sha256Hex(input: Uint8Array | string): string {
|
|
38
|
+
return createHash('sha256').update(input).digest('hex')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Cryptographically random unpadded base64url string of `byteLength` bytes. */
|
|
42
|
+
export function randomBase64Url(byteLength: number): string {
|
|
43
|
+
return base64UrlEncode(randomBytes(byteLength))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Compare two strings without leaking where they differ. Both sides are
|
|
48
|
+
* hashed first so the comparison is over two equal-length digests: a plain
|
|
49
|
+
* `===` on a token would return early on the first differing byte.
|
|
50
|
+
*/
|
|
51
|
+
export function constantTimeEqualText(left: string, right: string): boolean {
|
|
52
|
+
const a = createHash('sha256').update(left).digest()
|
|
53
|
+
const b = createHash('sha256').update(right).digest()
|
|
54
|
+
return timingSafeEqual(a, b)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @returns the token's stored hash: what the roster keeps in place of the secret. */
|
|
58
|
+
export function tokenHash(token: string): string {
|
|
59
|
+
return sha256Hex(token)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Fingerprint of a public key: SHA-256 over the DER of the SPKI exactly as the
|
|
64
|
+
* client sent it. It is the human-comparable identity of the device, and the
|
|
65
|
+
* roster pins it next to the key so a swapped key is visible.
|
|
66
|
+
* @returns the hex fingerprint, or undefined when the SPKI does not decode.
|
|
67
|
+
*/
|
|
68
|
+
export function fingerprintOfSpki(spkiBase64Url: string): string | undefined {
|
|
69
|
+
const der = base64UrlDecode(spkiBase64Url)
|
|
70
|
+
if (der === undefined) return undefined
|
|
71
|
+
return sha256Hex(der)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Whether an SPKI blob is an EC P-256 public key this bridge will verify against. */
|
|
75
|
+
export function isP256Spki(spkiBase64Url: string): boolean {
|
|
76
|
+
return importP256Spki(spkiBase64Url) !== undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Import a client-supplied SPKI blob, refusing anything that is not EC P-256.
|
|
81
|
+
* The curve check is not decoration: node would happily verify a P-384 key and
|
|
82
|
+
* the bridge would accept a device that can never be interoperable.
|
|
83
|
+
*/
|
|
84
|
+
function importP256Spki(spkiBase64Url: string): ReturnType<typeof createPublicKey> | undefined {
|
|
85
|
+
const der = base64UrlDecode(spkiBase64Url)
|
|
86
|
+
if (der === undefined) return undefined
|
|
87
|
+
let key: ReturnType<typeof createPublicKey>
|
|
88
|
+
try {
|
|
89
|
+
key = createPublicKey({ key: der, format: 'der', type: 'spki' })
|
|
90
|
+
} catch {
|
|
91
|
+
return undefined
|
|
92
|
+
}
|
|
93
|
+
if (key.asymmetricKeyType !== 'ec') return undefined
|
|
94
|
+
return key.asymmetricKeyDetails?.namedCurve === 'prime256v1' ? key : undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Verify one ES256 signature over a message.
|
|
99
|
+
* @param spkiBase64Url - the device's base64url SPKI, P-256.
|
|
100
|
+
* @param signatureBase64Url - base64url of the raw 64-byte r||s signature.
|
|
101
|
+
* @param message - the exact bytes that were signed.
|
|
102
|
+
* @returns whether the signature is valid for that key.
|
|
103
|
+
*/
|
|
104
|
+
export function verifyEs256(spkiBase64Url: string, signatureBase64Url: string, message: Uint8Array): boolean {
|
|
105
|
+
const key = importP256Spki(spkiBase64Url)
|
|
106
|
+
if (key === undefined) return false
|
|
107
|
+
const signature = base64UrlDecode(signatureBase64Url)
|
|
108
|
+
// WebCrypto, iOS CryptoKit and every other ES256 producer emit raw r||s. A
|
|
109
|
+
// DER blob would otherwise be accepted by node's default encoding, so the
|
|
110
|
+
// length is checked instead of leaving the encoding to the verifier.
|
|
111
|
+
if (signature === undefined || signature.length !== ES256_SIGNATURE_BYTES) return false
|
|
112
|
+
return cryptoVerify('sha256', message, { key, dsaEncoding: 'ieee-p1363' }, signature)
|
|
113
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The paired-device roster: `$DSH_HOME/remote-bridge/devices.json`.
|
|
3
|
+
*
|
|
4
|
+
* What is stored is deliberately not a credential. Each row keeps the device's
|
|
5
|
+
* public key, its fingerprint, and the SHA-256 of the bearer token it was
|
|
6
|
+
* issued — never the token itself, so a leaked roster file grants nothing. The
|
|
7
|
+
* directory is 0700 and the file 0600, written through a temporary file plus
|
|
8
|
+
* rename, and a file that cannot be parsed is moved aside instead of being
|
|
9
|
+
* silently treated as an empty roster (which would quietly un-pair every phone
|
|
10
|
+
* and then overwrite the evidence on the next write).
|
|
11
|
+
* @module dsh-remote-bridge/core/devices
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { randomBytes } from 'node:crypto'
|
|
15
|
+
import { chmod, mkdir, open, readFile, rename } from 'node:fs/promises'
|
|
16
|
+
import { dirname } from 'node:path'
|
|
17
|
+
import { base64UrlEncode, constantTimeEqualText, fingerprintOfSpki, isP256Spki, randomBase64Url, tokenHash } from './crypto.ts'
|
|
18
|
+
|
|
19
|
+
/** Entropy of one device bearer token. */
|
|
20
|
+
export const DEVICE_TOKEN_BYTES = 32
|
|
21
|
+
/** Entropy of one device id. */
|
|
22
|
+
export const DEVICE_ID_BYTES = 12
|
|
23
|
+
/** On-disk schema version of the roster file. */
|
|
24
|
+
export const ROSTER_VERSION = 1
|
|
25
|
+
|
|
26
|
+
/** One paired device as the bridge keeps it. */
|
|
27
|
+
export interface DeviceRecord {
|
|
28
|
+
readonly deviceId: string
|
|
29
|
+
/** base64url SPKI of the device's P-256 key. */
|
|
30
|
+
readonly pubKey: string
|
|
31
|
+
/** SHA-256 hex of the SPKI DER: the human-comparable identity of the device. */
|
|
32
|
+
readonly fingerprint: string
|
|
33
|
+
readonly createdAt: number
|
|
34
|
+
readonly lastSeenAt: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A roster row plus the one field that never leaves the file. */
|
|
38
|
+
interface StoredDevice extends DeviceRecord {
|
|
39
|
+
readonly tokenHash: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** What one successful enrollment hands back to the caller exactly once. */
|
|
43
|
+
export interface EnrollmentResult {
|
|
44
|
+
readonly deviceId: string
|
|
45
|
+
/** The bearer token: returned to the enrolling connection and never persisted again. */
|
|
46
|
+
readonly deviceToken: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface DeviceRosterOptions {
|
|
50
|
+
/** Absolute path of the roster file. */
|
|
51
|
+
readonly file: string
|
|
52
|
+
readonly now?: () => number
|
|
53
|
+
readonly log?: (message: string) => void
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isStoredDevice(value: unknown): value is StoredDevice {
|
|
57
|
+
if (typeof value !== 'object' || value === null) return false
|
|
58
|
+
const row = value as Record<string, unknown>
|
|
59
|
+
return typeof row.deviceId === 'string' && row.deviceId !== ''
|
|
60
|
+
&& typeof row.pubKey === 'string' && row.pubKey !== ''
|
|
61
|
+
&& typeof row.fingerprint === 'string' && row.fingerprint !== ''
|
|
62
|
+
&& typeof row.tokenHash === 'string' && row.tokenHash !== ''
|
|
63
|
+
&& typeof row.createdAt === 'number'
|
|
64
|
+
&& typeof row.lastSeenAt === 'number'
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The persisted, revocable device roster.
|
|
69
|
+
*
|
|
70
|
+
* Revocation is a file edit: protocol v1 has no revoke method, so an operator
|
|
71
|
+
* removes the row (or deletes the file) and restarts. The in-memory copy is
|
|
72
|
+
* loaded once per process.
|
|
73
|
+
*/
|
|
74
|
+
export class DeviceRoster {
|
|
75
|
+
readonly #file: string
|
|
76
|
+
readonly #now: () => number
|
|
77
|
+
readonly #log: (message: string) => void
|
|
78
|
+
readonly #devices = new Map<string, StoredDevice>()
|
|
79
|
+
#loaded: Promise<void> | undefined
|
|
80
|
+
|
|
81
|
+
constructor(options: DeviceRosterOptions) {
|
|
82
|
+
this.#file = options.file
|
|
83
|
+
this.#now = options.now ?? (() => Date.now())
|
|
84
|
+
this.#log = options.log ?? (() => undefined)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Read the roster once. A missing file is an empty roster; an unreadable or
|
|
89
|
+
* malformed one is moved aside and reported, never silently zeroed.
|
|
90
|
+
* @returns when the in-memory roster reflects the file.
|
|
91
|
+
*/
|
|
92
|
+
load(): Promise<void> {
|
|
93
|
+
this.#loaded ??= this.#read()
|
|
94
|
+
return this.#loaded
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** @returns every paired device, without the token hash. */
|
|
98
|
+
devices(): readonly DeviceRecord[] {
|
|
99
|
+
return [...this.#devices.values()].map(({ tokenHash: _ignored, ...record }) => record)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Resolve a bearer token to its device.
|
|
104
|
+
* @returns the device, or undefined when the token is unknown.
|
|
105
|
+
*/
|
|
106
|
+
authenticate(token: string): DeviceRecord | undefined {
|
|
107
|
+
if (token === '') return undefined
|
|
108
|
+
// The frozen design asks for a fixed-length comparison on the token path. A
|
|
109
|
+
// Map lookup would compare the stored hash with the map's own early-exit
|
|
110
|
+
// equality, so every row is compared instead — including after a match, so
|
|
111
|
+
// the number of rows examined does not depend on which one matched. The
|
|
112
|
+
// roster is a handful of phones, so the scan costs nothing.
|
|
113
|
+
const presented = tokenHash(token)
|
|
114
|
+
let matched: StoredDevice | undefined
|
|
115
|
+
for (const row of this.#devices.values()) {
|
|
116
|
+
if (constantTimeEqualText(row.tokenHash, presented)) matched = row
|
|
117
|
+
}
|
|
118
|
+
if (matched === undefined) return undefined
|
|
119
|
+
const { tokenHash: _ignored, ...record } = matched
|
|
120
|
+
return record
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Admit one device for a public key it has already proven possession of.
|
|
125
|
+
* @param pubKey - base64url SPKI of the device's P-256 key.
|
|
126
|
+
* @returns the enrollment, or undefined when the key is not an acceptable P-256 SPKI.
|
|
127
|
+
*/
|
|
128
|
+
async enroll(pubKey: string): Promise<EnrollmentResult | undefined> {
|
|
129
|
+
if (!isP256Spki(pubKey)) return undefined
|
|
130
|
+
const fingerprint = fingerprintOfSpki(pubKey)
|
|
131
|
+
if (fingerprint === undefined) return undefined
|
|
132
|
+
const now = this.#now()
|
|
133
|
+
const deviceId = `dev_${randomBase64Url(DEVICE_ID_BYTES)}`
|
|
134
|
+
const token = base64UrlEncode(randomBytes(DEVICE_TOKEN_BYTES))
|
|
135
|
+
this.#devices.set(tokenHash(token), { deviceId, pubKey, fingerprint, createdAt: now, lastSeenAt: now, tokenHash: tokenHash(token) })
|
|
136
|
+
await this.#persist()
|
|
137
|
+
return { deviceId, deviceToken: token }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Record that a device just reconnected; the file is refreshed at most once per call. */
|
|
141
|
+
async touch(deviceId: string): Promise<void> {
|
|
142
|
+
let touched: StoredDevice | undefined
|
|
143
|
+
for (const row of this.#devices.values()) {
|
|
144
|
+
if (row.deviceId !== deviceId) continue
|
|
145
|
+
touched = { ...row, lastSeenAt: this.#now() }
|
|
146
|
+
this.#devices.set(row.tokenHash, touched)
|
|
147
|
+
break
|
|
148
|
+
}
|
|
149
|
+
if (touched !== undefined) await this.#persist()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async #read(): Promise<void> {
|
|
153
|
+
let text: string
|
|
154
|
+
try {
|
|
155
|
+
text = await readFile(this.#file, 'utf8')
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
|
|
158
|
+
this.#log(`device roster ${this.#file} is unreadable (${String(error)}); continuing with an empty roster`)
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
let parsed: unknown
|
|
162
|
+
try {
|
|
163
|
+
parsed = JSON.parse(text)
|
|
164
|
+
} catch {
|
|
165
|
+
await this.#quarantine('is not JSON')
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
const rows = (parsed as { devices?: unknown } | null)?.devices
|
|
169
|
+
if (!Array.isArray(rows) || !rows.every(isStoredDevice)) {
|
|
170
|
+
await this.#quarantine('has no valid device table')
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
for (const row of rows) this.#devices.set(row.tokenHash, row)
|
|
174
|
+
this.#log(`device roster ${this.#file}: ${rows.length} paired device(s)`)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Move a corrupt roster aside so the failure survives and the next write cannot erase it. */
|
|
178
|
+
async #quarantine(reason: string): Promise<void> {
|
|
179
|
+
const target = `${this.#file}.corrupt-${this.#now()}`
|
|
180
|
+
try {
|
|
181
|
+
await rename(this.#file, target)
|
|
182
|
+
this.#log(`device roster ${this.#file} ${reason}; moved to ${target} and starting empty`)
|
|
183
|
+
} catch (error) {
|
|
184
|
+
this.#log(`device roster ${this.#file} ${reason} and could not be moved aside (${String(error)}); starting empty`)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Write the roster atomically: same directory, 0600 from creation, flushed
|
|
190
|
+
* before the rename so a crash cannot leave a truncated file in place.
|
|
191
|
+
*/
|
|
192
|
+
async #persist(): Promise<void> {
|
|
193
|
+
const directory = dirname(this.#file)
|
|
194
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
195
|
+
const payload = JSON.stringify({ version: ROSTER_VERSION, devices: [...this.#devices.values()] }, null, 2)
|
|
196
|
+
const temporary = `${this.#file}.${process.pid}.${randomBase64Url(6)}.tmp`
|
|
197
|
+
const handle = await open(temporary, 'w', 0o600)
|
|
198
|
+
try {
|
|
199
|
+
await handle.writeFile(payload, 'utf8')
|
|
200
|
+
await handle.sync()
|
|
201
|
+
} finally {
|
|
202
|
+
await handle.close()
|
|
203
|
+
}
|
|
204
|
+
await rename(temporary, this.#file)
|
|
205
|
+
// The mode is set at creation; the explicit chmod also covers a rename over
|
|
206
|
+
// a pre-existing file with wider permissions.
|
|
207
|
+
await chmod(this.#file, 0o600)
|
|
208
|
+
}
|
|
209
|
+
}
|