@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.8
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 +277 -2
- package/README.zh.md +276 -0
- package/cordis.patch.yml +17 -0
- package/icon.svg +3 -0
- package/lib/client.js +1830 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +5789 -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 +99 -0
- package/lib/types/core/connection.d.ts +170 -0
- package/lib/types/core/crypto.d.ts +48 -0
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +72 -0
- package/lib/types/core/dsh-frames.d.ts +332 -0
- package/lib/types/core/envelope.d.ts +132 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/gateway-errors.d.ts +49 -0
- package/lib/types/core/hub.d.ts +127 -0
- package/lib/types/core/jobs.d.ts +204 -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 +319 -0
- package/lib/types/core/questions.d.ts +294 -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 +72 -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 +111 -0
- package/lib/types/index.d.ts +55 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +93 -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 +173 -0
- package/src/core/connection.ts +1906 -0
- package/src/core/crypto.ts +113 -0
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +209 -0
- package/src/core/dsh-frames.ts +843 -0
- package/src/core/envelope.ts +219 -0
- package/src/core/extension.ts +197 -0
- package/src/core/gateway-errors.ts +92 -0
- package/src/core/hub.ts +310 -0
- package/src/core/jobs.ts +372 -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 +381 -0
- package/src/core/questions.ts +630 -0
- package/src/core/session-meta.ts +176 -0
- package/src/core/session-permissions.ts +266 -0
- package/src/core/wire.ts +159 -0
- package/src/core/ws-frames.ts +139 -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 +359 -0
- package/src/index.ts +257 -0
- package/src/mount-once.ts +142 -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,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-connection delta windows: what a client that already holds a copy of a
|
|
3
|
+
* whole set is sent instead of the whole set again.
|
|
4
|
+
*
|
|
5
|
+
* The difference is computed here, in the bridge, because the bridge is the
|
|
6
|
+
* only place that holds what the host said last — the host itself is asked for
|
|
7
|
+
* its complete answer every time and never learns that a client is caching one.
|
|
8
|
+
* That is the whole point of this module: the saving is bytes on the wire
|
|
9
|
+
* between the bridge and the phone, not a change to any host API.
|
|
10
|
+
*
|
|
11
|
+
* Three rules live in this file and nowhere else, so the roster and the board
|
|
12
|
+
* cannot disagree about them:
|
|
13
|
+
*
|
|
14
|
+
* - a delta is only diffed against the exact set this window last sent, and
|
|
15
|
+
* only for a token this window itself issued; anything else answers a reset,
|
|
16
|
+
* because a wrong base is a wrong answer;
|
|
17
|
+
* - a change is a change of the serialised row, not of a timestamp — the host's
|
|
18
|
+
* `updatedAt` is not a change signal for every field, and a row whose body is
|
|
19
|
+
* byte-identical has not changed;
|
|
20
|
+
* - a delta that is not clearly smaller than the reset body is not worth
|
|
21
|
+
* sending: past {@link DELTA_CHANGED_RATIO} of the rows, the answer is a reset.
|
|
22
|
+
* @module dsh-remote-bridge/core/delta
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { randomBytes } from 'node:crypto'
|
|
26
|
+
|
|
27
|
+
/** Largest roster one connection's delta window retains. */
|
|
28
|
+
export const ROSTER_DELTA_MAX_ROWS = 5000
|
|
29
|
+
/** Largest board one connection's delta window retains. */
|
|
30
|
+
export const BOARD_DELTA_MAX_ROWS = 2000
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Share of the current set that may change before a reset is the cheaper
|
|
34
|
+
* answer. Bytes, not cleverness: past this point the delta carries most of the
|
|
35
|
+
* body already and the extra keys only make it bigger.
|
|
36
|
+
*/
|
|
37
|
+
export const DELTA_CHANGED_RATIO = 0.6
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Identity of this bridge process, minted once at load.
|
|
41
|
+
*
|
|
42
|
+
* Part of every token, so a token minted by an earlier boot can never be
|
|
43
|
+
* replayed into a delta against a set that boot never sent. It is not a secret
|
|
44
|
+
* on its own — the per-window secret beside it is what makes a token
|
|
45
|
+
* unguessable, and the exact comparison below is what actually decides.
|
|
46
|
+
*/
|
|
47
|
+
const BOOT_ID = randomBytes(8).toString('hex')
|
|
48
|
+
|
|
49
|
+
/** The one row field every set this module diffs is keyed by. */
|
|
50
|
+
export interface DeltaRow {
|
|
51
|
+
readonly id: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** One window's answer, before a method wraps it in its own wire shape. */
|
|
55
|
+
export type DeltaAnswer<T> =
|
|
56
|
+
| {
|
|
57
|
+
readonly mode: 'reset'
|
|
58
|
+
/** Opaque token to send back as `since`; `""` when nothing was retained. */
|
|
59
|
+
readonly token: string
|
|
60
|
+
/** The whole set, exactly as the method always published it. */
|
|
61
|
+
readonly rows: readonly T[]
|
|
62
|
+
}
|
|
63
|
+
| {
|
|
64
|
+
readonly mode: 'delta'
|
|
65
|
+
readonly token: string
|
|
66
|
+
/** Every row that is new or whose body differs from the last one sent. */
|
|
67
|
+
readonly changed: readonly T[]
|
|
68
|
+
/** Every id this window sent before and the host no longer names. */
|
|
69
|
+
readonly removed: readonly string[]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Cap on the set one window may retain. */
|
|
73
|
+
export interface DeltaLimits {
|
|
74
|
+
readonly maxRows: number
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* One connection's view of one set: the rows it last sent, and the token that
|
|
79
|
+
* set was announced under.
|
|
80
|
+
*
|
|
81
|
+
* A window is created lazily by whoever needs it and lives exactly as long as
|
|
82
|
+
* the connection that owns it (see {@link RemoteBridgeDeltas}), so two
|
|
83
|
+
* connections never share a base and a dropped connection leaks nothing.
|
|
84
|
+
*/
|
|
85
|
+
export class DeltaWindow<T extends DeltaRow> {
|
|
86
|
+
readonly #maxRows: number
|
|
87
|
+
/**
|
|
88
|
+
* This window's own secret: what makes one connection's token useless to
|
|
89
|
+
* another, and what a client cannot derive from a token it was given.
|
|
90
|
+
*/
|
|
91
|
+
readonly #secret = randomBytes(8).toString('hex')
|
|
92
|
+
readonly #sent = new Map<string, string>()
|
|
93
|
+
#revision = 0
|
|
94
|
+
#token: string | undefined
|
|
95
|
+
|
|
96
|
+
constructor(limits: DeltaLimits) {
|
|
97
|
+
this.#maxRows = limits.maxRows
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Answer one call over the current full set.
|
|
102
|
+
* @param rows - the complete set, exactly as the host answered it this time.
|
|
103
|
+
* @param since - the opaque token the client sent, if it sent one.
|
|
104
|
+
* @returns a reset carrying every row, or a delta against the last set sent.
|
|
105
|
+
*/
|
|
106
|
+
answer(rows: readonly T[], since: string | undefined): DeltaAnswer<T> {
|
|
107
|
+
const current = new Map<string, string>()
|
|
108
|
+
for (const row of rows) current.set(row.id, JSON.stringify(row))
|
|
109
|
+
// A set past the cap is not retained at all: one connection must never pin
|
|
110
|
+
// an unbounded copy of the host's state, and a reset is answered instead of
|
|
111
|
+
// pretending a base exists.
|
|
112
|
+
if (current.size > this.#maxRows) return this.#forget(rows)
|
|
113
|
+
// The only base a delta may be diffed against is the set this window sent
|
|
114
|
+
// last, named by the token it handed out with it. A token from another
|
|
115
|
+
// connection, another boot, an older answer of this one, or garbage is not
|
|
116
|
+
// that base.
|
|
117
|
+
if (since === undefined || this.#token === undefined || since !== this.#token) {
|
|
118
|
+
return this.#reset(rows, current)
|
|
119
|
+
}
|
|
120
|
+
const changed: T[] = []
|
|
121
|
+
for (const row of rows) if (this.#sent.get(row.id) !== current.get(row.id)) changed.push(row)
|
|
122
|
+
const removed: string[] = []
|
|
123
|
+
for (const id of this.#sent.keys()) if (!current.has(id)) removed.push(id)
|
|
124
|
+
// Removals are not counted against the ratio: a removal costs one id on the
|
|
125
|
+
// wire, not a row, so a wave of deletions is exactly what a delta is for.
|
|
126
|
+
if (changed.length > DELTA_CHANGED_RATIO * rows.length) return this.#reset(rows, current)
|
|
127
|
+
this.#sent.clear()
|
|
128
|
+
for (const [id, body] of current) this.#sent.set(id, body)
|
|
129
|
+
return { mode: 'delta', token: this.#nextToken(), changed, removed }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Answer the whole set and keep it as the next base.
|
|
134
|
+
* @param rows - the complete set.
|
|
135
|
+
* @param current - the set, serialised, to retain.
|
|
136
|
+
*/
|
|
137
|
+
#reset(rows: readonly T[], current: Map<string, string>): DeltaAnswer<T> {
|
|
138
|
+
this.#sent.clear()
|
|
139
|
+
for (const [id, body] of current) this.#sent.set(id, body)
|
|
140
|
+
return { mode: 'reset', token: this.#nextToken(), rows }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Answer the whole set and retain nothing.
|
|
145
|
+
*
|
|
146
|
+
* The empty token says so: this answer cannot be continued from, because
|
|
147
|
+
* there is no copy of it here to diff against. A client that sends it back is
|
|
148
|
+
* answered a reset, which is the truth rather than a wrong delta.
|
|
149
|
+
* @param rows - the complete set.
|
|
150
|
+
*/
|
|
151
|
+
#forget(rows: readonly T[]): DeltaAnswer<T> {
|
|
152
|
+
this.#sent.clear()
|
|
153
|
+
this.#token = undefined
|
|
154
|
+
this.#revision += 1
|
|
155
|
+
return { mode: 'reset', token: '', rows }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** @returns the token for the set just retained, bumping the window's revision. */
|
|
159
|
+
#nextToken(): string {
|
|
160
|
+
this.#revision += 1
|
|
161
|
+
this.#token = `d1.${BOOT_ID}.${this.#secret}.${this.#revision}`
|
|
162
|
+
return this.#token
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The delta windows one connection owns, by the name its owner keys them with.
|
|
168
|
+
*
|
|
169
|
+
* Held on the connection, so the state is released exactly when the connection
|
|
170
|
+
* is: there is no second registry to expire, and no connection's window can be
|
|
171
|
+
* read by another.
|
|
172
|
+
*/
|
|
173
|
+
export class RemoteBridgeDeltas {
|
|
174
|
+
readonly #windows = new Map<string, DeltaWindow<DeltaRow>>()
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* @param key - the window's name within this connection; one set, one key.
|
|
178
|
+
* @param limits - the cap this window retains.
|
|
179
|
+
* @returns the window, created on first use.
|
|
180
|
+
*/
|
|
181
|
+
window<T extends DeltaRow>(key: string, limits: DeltaLimits): DeltaWindow<T> {
|
|
182
|
+
const known = this.#windows.get(key)
|
|
183
|
+
if (known !== undefined) return known as DeltaWindow<T>
|
|
184
|
+
const created = new DeltaWindow<T>(limits)
|
|
185
|
+
this.#windows.set(key, created as unknown as DeltaWindow<DeltaRow>)
|
|
186
|
+
return created
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* @param key - one window's name.
|
|
191
|
+
*
|
|
192
|
+
* Drops that window and the set it retained, so its token names nothing and
|
|
193
|
+
* the next call answers a reset. Used when a connection stops being served
|
|
194
|
+
* increments at all, which must cost it no memory either.
|
|
195
|
+
*/
|
|
196
|
+
drop(key: string): void {
|
|
197
|
+
this.#windows.delete(key)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Drop every window: called when the owning connection is torn down. */
|
|
201
|
+
clear(): void {
|
|
202
|
+
this.#windows.clear()
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -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
|
+
}
|