@sparkelf/dsh-mobile-bridge-server 0.1.0 → 0.2.0
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/THIRD_PARTY_NOTICES.md +11 -0
- package/package.json +1 -1
- package/src/deepseek-logo.svg +22 -0
- package/src/phone.ts +377 -46
- package/src/server.ts +342 -84
- package/src/store.ts +132 -31
- package/src/live.spec.ts +0 -108
- package/src/server.spec.ts +0 -181
- package/src/store.spec.ts +0 -40
package/src/store.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* bindings; and short-lived email verification codes. Persisted as one JSON
|
|
5
|
-
* document with atomic replacement.
|
|
2
|
+
* File-backed identities, stable desktop bridges, mobile devices, session
|
|
3
|
+
* tokens, and short-lived email verification codes.
|
|
6
4
|
* @module @sparkelf/dsh-mobile-bridge-server/store
|
|
7
5
|
*/
|
|
8
6
|
|
|
@@ -10,41 +8,80 @@ import { createHash, createHmac, randomBytes, randomInt, timingSafeEqual } from
|
|
|
10
8
|
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
11
9
|
import { join } from 'node:path'
|
|
12
10
|
|
|
13
|
-
/** One registered
|
|
11
|
+
/** One registered login identity. */
|
|
14
12
|
export interface UserRecord {
|
|
15
13
|
key: string
|
|
16
14
|
provider: string
|
|
17
15
|
externalId: string
|
|
18
|
-
bridge: string | null
|
|
19
16
|
}
|
|
20
17
|
|
|
21
|
-
/** One
|
|
18
|
+
/** One desktop installation authorized to reconnect under a stable id. */
|
|
19
|
+
export interface BridgeRecord {
|
|
20
|
+
id: string
|
|
21
|
+
tokenHash: string
|
|
22
|
+
createdAt: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** One paired phone browser. Online state is projected by the relay runtime. */
|
|
26
|
+
export interface DeviceRecord {
|
|
27
|
+
id: string
|
|
28
|
+
bridgeId: string
|
|
29
|
+
name: string
|
|
30
|
+
ip: string
|
|
31
|
+
pairedAt: number
|
|
32
|
+
lastSeenAt: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface TokenRecord {
|
|
36
|
+
userKey: string
|
|
37
|
+
deviceId: string | null
|
|
38
|
+
}
|
|
39
|
+
|
|
22
40
|
interface CodeRecord {
|
|
23
41
|
code: string
|
|
24
42
|
expiresAt: number
|
|
25
43
|
}
|
|
26
44
|
|
|
27
|
-
/** Persisted store document. */
|
|
28
45
|
interface StoreDocument {
|
|
46
|
+
version: 2
|
|
29
47
|
users: Record<string, UserRecord>
|
|
30
|
-
tokens: Record<string,
|
|
48
|
+
tokens: Record<string, TokenRecord>
|
|
31
49
|
codes: Record<string, CodeRecord>
|
|
50
|
+
bridges: Record<string, BridgeRecord>
|
|
51
|
+
devices: Record<string, DeviceRecord>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface LegacyStoreDocument {
|
|
55
|
+
users?: Record<string, UserRecord & { bridge?: string | null }>
|
|
56
|
+
codes?: Record<string, CodeRecord>
|
|
32
57
|
}
|
|
33
58
|
|
|
34
59
|
/** Verification code lifetime in milliseconds. */
|
|
35
60
|
export const CODE_TTL_MS = 5 * 60_000
|
|
36
61
|
|
|
37
|
-
/** File-backed
|
|
62
|
+
/** File-backed account and device store with atomic writes. */
|
|
38
63
|
export class UserStore {
|
|
39
64
|
private doc: StoreDocument
|
|
40
65
|
|
|
41
66
|
constructor(private file: string, private tokenSecret: string) {
|
|
42
67
|
try {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
68
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8')) as StoreDocument | LegacyStoreDocument
|
|
69
|
+
if ('version' in parsed && parsed.version === 2) {
|
|
70
|
+
this.doc = parsed
|
|
71
|
+
} else {
|
|
72
|
+
const legacy = parsed as LegacyStoreDocument
|
|
73
|
+
const users = Object.fromEntries(Object.entries(legacy.users ?? {}).map(([key, user]) => [key, {
|
|
74
|
+
key: user.key,
|
|
75
|
+
provider: user.provider,
|
|
76
|
+
externalId: user.externalId,
|
|
77
|
+
}]))
|
|
78
|
+
this.doc = { version: 2, users, tokens: {}, codes: legacy.codes ?? {}, bridges: {}, devices: {} }
|
|
79
|
+
this.save()
|
|
80
|
+
}
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
83
|
+
this.doc = { version: 2, users: {}, tokens: {}, codes: {}, bridges: {}, devices: {} }
|
|
46
84
|
}
|
|
47
|
-
this.doc.codes ??= {}
|
|
48
85
|
}
|
|
49
86
|
|
|
50
87
|
private save(): void {
|
|
@@ -55,11 +92,38 @@ export class UserStore {
|
|
|
55
92
|
|
|
56
93
|
private mintToken(key: string): string {
|
|
57
94
|
const token = createHmac('sha256', this.tokenSecret).update(key + ':' + randomBytes(8).toString('hex')).digest('hex')
|
|
58
|
-
this.doc.tokens[token] = key
|
|
95
|
+
this.doc.tokens[token] = { userKey: key, deviceId: null }
|
|
59
96
|
this.save()
|
|
60
97
|
return token
|
|
61
98
|
}
|
|
62
99
|
|
|
100
|
+
private bridgeTokenHash(token: string): string {
|
|
101
|
+
return createHmac('sha256', this.tokenSecret).update('bridge:' + token).digest('hex')
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Register a desktop identity on first use or authenticate its existing token. */
|
|
105
|
+
authenticateBridge(id: string, token: string): void {
|
|
106
|
+
const tokenHash = this.bridgeTokenHash(token)
|
|
107
|
+
const record = this.doc.bridges[id]
|
|
108
|
+
if (record === undefined) {
|
|
109
|
+
this.doc.bridges[id] = { id, tokenHash, createdAt: Date.now() }
|
|
110
|
+
this.save()
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
const expected = Buffer.from(record.tokenHash, 'hex')
|
|
114
|
+
const actual = Buffer.from(tokenHash, 'hex')
|
|
115
|
+
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) throw new Error('invalid bridge credentials')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Authenticate an existing desktop identity without creating one. */
|
|
119
|
+
verifyBridge(id: string, token: string): void {
|
|
120
|
+
const record = this.doc.bridges[id]
|
|
121
|
+
if (record === undefined) throw new Error('invalid bridge credentials')
|
|
122
|
+
const expected = Buffer.from(record.tokenHash, 'hex')
|
|
123
|
+
const actual = Buffer.from(this.bridgeTokenHash(token), 'hex')
|
|
124
|
+
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) throw new Error('invalid bridge credentials')
|
|
125
|
+
}
|
|
126
|
+
|
|
63
127
|
/** Mint a six-digit verification code for one email, replacing any pending one. */
|
|
64
128
|
issueEmailCode(email: string): string {
|
|
65
129
|
const key = email.trim().toLowerCase()
|
|
@@ -83,36 +147,73 @@ export class UserStore {
|
|
|
83
147
|
this.save()
|
|
84
148
|
}
|
|
85
149
|
|
|
86
|
-
/** Log in through a verified identity, creating the
|
|
150
|
+
/** Log in through a verified identity, creating the identity on first sight. */
|
|
87
151
|
loginExternal(provider: string, externalId: string): string {
|
|
88
152
|
const key = provider + ':' + externalId
|
|
89
|
-
if (
|
|
90
|
-
this.doc.users[key] = { key, provider, externalId, bridge: null }
|
|
91
|
-
}
|
|
153
|
+
if (this.doc.users[key] === undefined) this.doc.users[key] = { key, provider, externalId }
|
|
92
154
|
return this.mintToken(key)
|
|
93
155
|
}
|
|
94
156
|
|
|
95
|
-
/** Resolve a session token to its
|
|
157
|
+
/** Resolve a session token to its login identity. */
|
|
96
158
|
userFor(token: string): string | undefined {
|
|
97
|
-
return this.doc.tokens[token]
|
|
159
|
+
return this.doc.tokens[token]?.userKey
|
|
98
160
|
}
|
|
99
161
|
|
|
100
|
-
/**
|
|
101
|
-
|
|
102
|
-
const
|
|
103
|
-
if (
|
|
104
|
-
this.doc.
|
|
162
|
+
/** Pair a token with a new or previously authenticated phone device. */
|
|
163
|
+
bindDevice(token: string, bridgeId: string, details: { name: string; ip: string }, existingDeviceId?: string): DeviceRecord {
|
|
164
|
+
const session = this.doc.tokens[token]
|
|
165
|
+
if (session === undefined) throw new Error('unknown token')
|
|
166
|
+
const existing = existingDeviceId === undefined ? undefined : this.doc.devices[existingDeviceId]
|
|
167
|
+
const now = Date.now()
|
|
168
|
+
const device = existing?.bridgeId === bridgeId
|
|
169
|
+
? { ...existing, name: details.name, ip: details.ip, lastSeenAt: now }
|
|
170
|
+
: { id: randomBytes(12).toString('hex'), bridgeId, name: details.name, ip: details.ip, pairedAt: now, lastSeenAt: now }
|
|
171
|
+
this.doc.devices[device.id] = device
|
|
172
|
+
session.deviceId = device.id
|
|
105
173
|
this.save()
|
|
106
|
-
return
|
|
174
|
+
return device
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Resolve a session token to its active phone device. */
|
|
178
|
+
deviceFor(token: string): DeviceRecord | undefined {
|
|
179
|
+
const deviceId = this.doc.tokens[token]?.deviceId
|
|
180
|
+
return deviceId === null || deviceId === undefined ? undefined : this.doc.devices[deviceId]
|
|
107
181
|
}
|
|
108
182
|
|
|
109
|
-
/**
|
|
183
|
+
/** Resolve a phone session to the stable desktop bridge id. */
|
|
110
184
|
bridgeFor(token: string): string | null {
|
|
111
|
-
|
|
112
|
-
|
|
185
|
+
return this.deviceFor(token)?.bridgeId ?? null
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Record the latest address and activity time for a paired device. */
|
|
189
|
+
touchDevice(id: string, ip: string): DeviceRecord {
|
|
190
|
+
const device = this.doc.devices[id]
|
|
191
|
+
if (device === undefined) throw new Error('unknown device')
|
|
192
|
+
const next = { ...device, ip, lastSeenAt: Date.now() }
|
|
193
|
+
this.doc.devices[id] = next
|
|
194
|
+
this.save()
|
|
195
|
+
return next
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** List all devices paired with one stable desktop bridge. */
|
|
199
|
+
devicesForBridge(bridgeId: string): DeviceRecord[] {
|
|
200
|
+
return Object.values(this.doc.devices)
|
|
201
|
+
.filter(device => device.bridgeId === bridgeId)
|
|
202
|
+
.sort((left, right) => right.pairedAt - left.pairedAt)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Remove one device and revoke every session token associated with it. */
|
|
206
|
+
revokeDevice(bridgeId: string, deviceId: string): void {
|
|
207
|
+
const device = this.doc.devices[deviceId]
|
|
208
|
+
if (device === undefined || device.bridgeId !== bridgeId) throw new Error('unknown device')
|
|
209
|
+
delete this.doc.devices[deviceId]
|
|
210
|
+
for (const [token, session] of Object.entries(this.doc.tokens)) {
|
|
211
|
+
if (session.deviceId === deviceId) delete this.doc.tokens[token]
|
|
212
|
+
}
|
|
213
|
+
this.save()
|
|
113
214
|
}
|
|
114
215
|
|
|
115
|
-
/** Stable fingerprint for
|
|
216
|
+
/** Stable fingerprint for persistence diagnostics. */
|
|
116
217
|
fingerprint(): string {
|
|
117
218
|
return createHash('sha256').update(JSON.stringify(this.doc)).digest('hex').slice(0, 12)
|
|
118
219
|
}
|
package/src/live.spec.ts
DELETED
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Live dress rehearsal against a real local Harness web on :3080. Self-skips
|
|
3
|
-
* in CI or anywhere the loopback web is absent; on a dev box it proves the
|
|
4
|
-
* encrypted chain: phone-side crypto through the blind server pipe to the
|
|
5
|
-
* desktop relay and back, reading the real stock HTML as ciphertext on wire.
|
|
6
|
-
* @module @sparkelf/dsh-mobile-bridge-server/live
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import { mkdtempSync } from 'node:fs'
|
|
10
|
-
import { createServer, type Server } from 'node:http'
|
|
11
|
-
import { AddressInfo } from 'node:net'
|
|
12
|
-
import { tmpdir } from 'node:os'
|
|
13
|
-
import { join } from 'node:path'
|
|
14
|
-
import WebSocket from 'ws'
|
|
15
|
-
import { afterAll, describe, expect, it } from 'vitest'
|
|
16
|
-
import { decryptJSON, deriveKey, encryptJSON } from '../../mobile-bridge/src/crypto.ts'
|
|
17
|
-
import { relayToLocalWeb, type RelayRequest } from '../../mobile-bridge/src/index.ts'
|
|
18
|
-
import { createBridgeServer } from './server.ts'
|
|
19
|
-
import { UserStore } from './store.ts'
|
|
20
|
-
|
|
21
|
-
const LIVE_PORT = Number(process.env.LIVE_HARNESS_PORT ?? 3080)
|
|
22
|
-
|
|
23
|
-
let reachable = false
|
|
24
|
-
try {
|
|
25
|
-
const probe = await fetch(`http://127.0.0.1:${LIVE_PORT}/`, { signal: AbortSignal.timeout(3000) })
|
|
26
|
-
reachable = probe.ok
|
|
27
|
-
} catch {
|
|
28
|
-
reachable = false
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
let bridge: Server
|
|
32
|
-
let bridgePort: number
|
|
33
|
-
let liveCodes: string[] = []
|
|
34
|
-
|
|
35
|
-
if (reachable) {
|
|
36
|
-
const store = new UserStore(join(mkdtempSync(join(tmpdir(), 'mbs-live-')), 'u.json'), '0123456789abcdef')
|
|
37
|
-
const codes: string[] = []
|
|
38
|
-
bridge = createBridgeServer(store, { mailer: async (_email, code) => { codes.push(code) } })
|
|
39
|
-
liveCodes = codes
|
|
40
|
-
await new Promise<void>(resolve => bridge.listen(0, resolve))
|
|
41
|
-
bridgePort = (bridge.address() as AddressInfo).port
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
afterAll(async () => {
|
|
45
|
-
if (reachable) await new Promise(resolve => bridge.close(resolve))
|
|
46
|
-
})
|
|
47
|
-
|
|
48
|
-
describe.skipIf(!reachable)('live rehearsal against the real Harness web', () => {
|
|
49
|
-
it('reads the stock UI through the encrypted tunnel after email login', async () => {
|
|
50
|
-
const base = `http://127.0.0.1:${bridgePort}`
|
|
51
|
-
await fetch(base + '/bridge/api/email/code', {
|
|
52
|
-
method: 'POST',
|
|
53
|
-
body: JSON.stringify({ email: 'rehearsal@example.com' }),
|
|
54
|
-
})
|
|
55
|
-
const login = await fetch(base + '/bridge/api/login/email', {
|
|
56
|
-
method: 'POST',
|
|
57
|
-
body: JSON.stringify({ email: 'rehearsal@example.com', code: liveCodes.at(-1) ?? '' }),
|
|
58
|
-
})
|
|
59
|
-
expect(login.status).toBe(200)
|
|
60
|
-
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''
|
|
61
|
-
|
|
62
|
-
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
63
|
-
await fetch(base + '/bridge/api/bind', {
|
|
64
|
-
method: 'POST',
|
|
65
|
-
headers: { cookie, 'content-type': 'application/json' },
|
|
66
|
-
body: JSON.stringify({ bridge: start.code }),
|
|
67
|
-
})
|
|
68
|
-
|
|
69
|
-
const desktopKey = await deriveKey('', 'livepair')
|
|
70
|
-
const phoneKey = await deriveKey('', 'livepair')
|
|
71
|
-
const bridgeSocket = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/bridge?code=${start.code}`)
|
|
72
|
-
await new Promise<void>((resolve, reject) => { bridgeSocket.on('open', () => resolve()); bridgeSocket.on('error', reject) })
|
|
73
|
-
bridgeSocket.on('message', raw => {
|
|
74
|
-
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
75
|
-
if (wire.blob === undefined) return
|
|
76
|
-
const blobIn = wire.blob
|
|
77
|
-
void (async () => {
|
|
78
|
-
const request = await decryptJSON<RelayRequest>(desktopKey, blobIn)
|
|
79
|
-
await relayToLocalWeb({ ...request, id: wire.id }, LIVE_PORT, frame => {
|
|
80
|
-
void (async () => {
|
|
81
|
-
if (frame.end) { bridgeSocket.send(JSON.stringify({ id: frame.id, end: true })); return }
|
|
82
|
-
if (frame.stream) { bridgeSocket.send(JSON.stringify({ id: frame.id, stream: true, blob: await encryptJSON(desktopKey, { stream: true, status: frame.status, headers: frame.headers }) })); return }
|
|
83
|
-
if (frame.chunk !== undefined) { bridgeSocket.send(JSON.stringify({ id: frame.id, chunk: await encryptJSON(desktopKey, { d: frame.chunk }) })); return }
|
|
84
|
-
bridgeSocket.send(JSON.stringify({ id: frame.id, blob: await encryptJSON(desktopKey, { status: frame.status, headers: frame.headers, body: frame.body, bodyEncoding: 'base64' }) }))
|
|
85
|
-
})()
|
|
86
|
-
})
|
|
87
|
-
})()
|
|
88
|
-
})
|
|
89
|
-
|
|
90
|
-
const client = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/client`, { headers: { cookie } })
|
|
91
|
-
await new Promise<void>((resolve, reject) => { client.on('open', () => resolve()); client.on('error', reject) })
|
|
92
|
-
const answer = new Promise<string>(resolve => {
|
|
93
|
-
client.on('message', raw => {
|
|
94
|
-
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
95
|
-
if (wire.blob === undefined) return
|
|
96
|
-
void decryptJSON<{ body: string }>(phoneKey, wire.blob).then(full => resolve(Buffer.from(full.body, 'base64').toString('utf8')))
|
|
97
|
-
})
|
|
98
|
-
})
|
|
99
|
-
const blob = await encryptJSON(phoneKey, { method: 'GET', path: '/', headers: { accept: 'text/html' }, body: '', bodyEncoding: 'base64' })
|
|
100
|
-
client.send(JSON.stringify({ id: 'live1', blob }))
|
|
101
|
-
|
|
102
|
-
const html = await answer
|
|
103
|
-
expect(html).toContain('__DSH_BOOT__')
|
|
104
|
-
|
|
105
|
-
client.close()
|
|
106
|
-
bridgeSocket.close()
|
|
107
|
-
}, 20000)
|
|
108
|
-
})
|
package/src/server.spec.ts
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
import { mkdtempSync } from 'node:fs'
|
|
2
|
-
import { createServer, type Server } from 'node:http'
|
|
3
|
-
import { AddressInfo } from 'node:net'
|
|
4
|
-
import { tmpdir } from 'node:os'
|
|
5
|
-
import { join } from 'node:path'
|
|
6
|
-
import WebSocket from 'ws'
|
|
7
|
-
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
|
8
|
-
import { decryptJSON, deriveKey, encryptJSON } from '../../mobile-bridge/src/crypto.ts'
|
|
9
|
-
import { relayToLocalWeb, type RelayRequest } from '../../mobile-bridge/src/index.ts'
|
|
10
|
-
import { createBridgeServer } from './server.ts'
|
|
11
|
-
import { UserStore } from './store.ts'
|
|
12
|
-
|
|
13
|
-
let local: Server
|
|
14
|
-
let bridge: Server
|
|
15
|
-
let localPort: number
|
|
16
|
-
let bridgePort: number
|
|
17
|
-
let sentCodes: { email: string; code: string }[]
|
|
18
|
-
const wireLog: string[] = []
|
|
19
|
-
|
|
20
|
-
beforeAll(async () => {
|
|
21
|
-
local = createServer((req, res) => {
|
|
22
|
-
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
|
|
23
|
-
res.end('<!doctype html><head></head><body>stock web secret-marker</body>')
|
|
24
|
-
})
|
|
25
|
-
await new Promise<void>(resolve => local.listen(0, resolve))
|
|
26
|
-
localPort = (local.address() as AddressInfo).port
|
|
27
|
-
sentCodes = []
|
|
28
|
-
const store = new UserStore(join(mkdtempSync(join(tmpdir(), 'mbs-')), 'u.json'), '0123456789abcdef')
|
|
29
|
-
bridge = createBridgeServer(store, {
|
|
30
|
-
mailer: async (email, code) => { sentCodes.push({ email, code }) },
|
|
31
|
-
})
|
|
32
|
-
await new Promise<void>(resolve => bridge.listen(0, resolve))
|
|
33
|
-
bridgePort = (bridge.address() as AddressInfo).port
|
|
34
|
-
})
|
|
35
|
-
|
|
36
|
-
afterAll(async () => {
|
|
37
|
-
await new Promise(resolve => bridge.close(resolve))
|
|
38
|
-
await new Promise(resolve => local.close(resolve))
|
|
39
|
-
})
|
|
40
|
-
|
|
41
|
-
describe('bridge server end to end', () => {
|
|
42
|
-
it('emails a code, logs in, and binds', async () => {
|
|
43
|
-
const base = `http://127.0.0.1:${bridgePort}`
|
|
44
|
-
await fetch(base + '/bridge/api/email/code', { method: 'POST', body: JSON.stringify({ email: 'dee@example.com' }) })
|
|
45
|
-
const code = sentCodes.at(-1)?.code ?? ''
|
|
46
|
-
const login = await fetch(base + '/bridge/api/login/email', {
|
|
47
|
-
method: 'POST',
|
|
48
|
-
body: JSON.stringify({ email: 'dee@example.com', code }),
|
|
49
|
-
})
|
|
50
|
-
expect(login.status).toBe(200)
|
|
51
|
-
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''
|
|
52
|
-
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
53
|
-
const bind = await fetch(base + '/bridge/api/bind', {
|
|
54
|
-
method: 'POST',
|
|
55
|
-
headers: { cookie, 'content-type': 'application/json' },
|
|
56
|
-
body: JSON.stringify({ bridge: start.code }),
|
|
57
|
-
})
|
|
58
|
-
expect(bind.status).toBe(200)
|
|
59
|
-
})
|
|
60
|
-
|
|
61
|
-
it('pipes encrypted frames blindly: the phone reads the stock web, the wire stays ciphertext', async () => {
|
|
62
|
-
const base = `http://127.0.0.1:${bridgePort}`
|
|
63
|
-
await fetch(base + '/bridge/api/email/code', { method: 'POST', body: JSON.stringify({ email: 'phone@example.com' }) })
|
|
64
|
-
const code = sentCodes.at(-1)?.code ?? ''
|
|
65
|
-
const login = await fetch(base + '/bridge/api/login/email', {
|
|
66
|
-
method: 'POST',
|
|
67
|
-
body: JSON.stringify({ email: 'phone@example.com', code }),
|
|
68
|
-
})
|
|
69
|
-
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? ''
|
|
70
|
-
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
71
|
-
await fetch(base + '/bridge/api/bind', {
|
|
72
|
-
method: 'POST',
|
|
73
|
-
headers: { cookie, 'content-type': 'application/json' },
|
|
74
|
-
body: JSON.stringify({ bridge: start.code }),
|
|
75
|
-
})
|
|
76
|
-
|
|
77
|
-
const pairingSecret = 'deadbeef'
|
|
78
|
-
const desktopKey = await deriveKey('user-pass', pairingSecret)
|
|
79
|
-
const phoneKey = await deriveKey('user-pass', pairingSecret)
|
|
80
|
-
|
|
81
|
-
// Desktop side: decrypt phone frames, answer from the local web, encrypt back.
|
|
82
|
-
const bridgeSocket = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/bridge?code=${start.code}`)
|
|
83
|
-
await new Promise<void>((resolve, reject) => { bridgeSocket.on('open', () => resolve()); bridgeSocket.on('error', reject) })
|
|
84
|
-
bridgeSocket.on('message', raw => {
|
|
85
|
-
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
86
|
-
wireLog.push(String(raw))
|
|
87
|
-
if (wire.blob === undefined) return
|
|
88
|
-
const blobIn = wire.blob
|
|
89
|
-
void (async () => {
|
|
90
|
-
const request = await decryptJSON<RelayRequest>(desktopKey, blobIn)
|
|
91
|
-
await relayToLocalWeb({ ...request, id: wire.id }, localPort, frame => {
|
|
92
|
-
void (async () => {
|
|
93
|
-
if (frame.end) { bridgeSocket.send(JSON.stringify({ id: frame.id, end: true })); return }
|
|
94
|
-
if (frame.stream) { bridgeSocket.send(JSON.stringify({ id: frame.id, stream: true, blob: await encryptJSON(desktopKey, { stream: true, status: frame.status, headers: frame.headers }) })); return }
|
|
95
|
-
if (frame.chunk !== undefined) { bridgeSocket.send(JSON.stringify({ id: frame.id, chunk: await encryptJSON(desktopKey, { d: frame.chunk }) })); return }
|
|
96
|
-
bridgeSocket.send(JSON.stringify({ id: frame.id, blob: await encryptJSON(desktopKey, { status: frame.status, headers: frame.headers, body: frame.body, bodyEncoding: 'base64' }) }))
|
|
97
|
-
})()
|
|
98
|
-
})
|
|
99
|
-
})()
|
|
100
|
-
})
|
|
101
|
-
|
|
102
|
-
// Phone side (simulated service worker): encrypted request, decrypted response.
|
|
103
|
-
const client = new WebSocket(`ws://127.0.0.1:${bridgePort}/ws/client`, { headers: { cookie } })
|
|
104
|
-
await new Promise<void>((resolve, reject) => { client.on('open', () => resolve()); client.on('error', reject) })
|
|
105
|
-
const answer = new Promise<{ status: number; html: string }>(resolve => {
|
|
106
|
-
client.on('message', raw => {
|
|
107
|
-
const wire = JSON.parse(String(raw)) as { id: string; blob?: string }
|
|
108
|
-
wireLog.push(String(raw))
|
|
109
|
-
if (wire.blob === undefined) return
|
|
110
|
-
void decryptJSON<{ status: number; body: string }>(phoneKey, wire.blob).then(full => {
|
|
111
|
-
resolve({ status: full.status, html: Buffer.from(full.body, 'base64').toString('utf8') })
|
|
112
|
-
})
|
|
113
|
-
})
|
|
114
|
-
})
|
|
115
|
-
const blob = await encryptJSON(phoneKey, { method: 'GET', path: '/', headers: { accept: 'text/html' }, body: '', bodyEncoding: 'base64' })
|
|
116
|
-
client.send(JSON.stringify({ id: 'p1', blob }))
|
|
117
|
-
|
|
118
|
-
const result = await answer
|
|
119
|
-
expect(result.status).toBe(200)
|
|
120
|
-
expect(result.html).toContain('stock web secret-marker')
|
|
121
|
-
for (const line of wireLog) expect(line).not.toContain('secret-marker')
|
|
122
|
-
|
|
123
|
-
client.close()
|
|
124
|
-
bridgeSocket.close()
|
|
125
|
-
})
|
|
126
|
-
|
|
127
|
-
it('auto-logs in a phone that presents a live pairing code', async () => {
|
|
128
|
-
const base = `http://127.0.0.1:${bridgePort}`
|
|
129
|
-
const start = await fetch(base + '/bridge/api/bridge/start', { method: 'POST', body: '{}' }).then(response => response.json()) as { code: string }
|
|
130
|
-
const login = await fetch(base + '/bridge/api/login/bridge', {
|
|
131
|
-
method: 'POST',
|
|
132
|
-
body: JSON.stringify({ code: start.code }),
|
|
133
|
-
})
|
|
134
|
-
expect(login.status).toBe(200)
|
|
135
|
-
expect(login.headers.get('set-cookie')).toContain('mbs=')
|
|
136
|
-
const me = await fetch(base + '/bridge/api/me', { headers: { cookie: login.headers.get('set-cookie')?.split(';')[0] ?? '' } })
|
|
137
|
-
expect(await me.json()).toMatchObject({ bridge: start.code })
|
|
138
|
-
const offline = await fetch(base + '/bridge/api/login/bridge', { method: 'POST', body: JSON.stringify({ code: 'zzzzzz' }) })
|
|
139
|
-
expect(offline.status).toBe(401)
|
|
140
|
-
})
|
|
141
|
-
|
|
142
|
-
it('optionally challenges a scan with an owner email code', async () => {
|
|
143
|
-
const base = `http://127.0.0.1:${bridgePort}`
|
|
144
|
-
const start = await fetch(base + '/bridge/api/bridge/start', {
|
|
145
|
-
method: 'POST',
|
|
146
|
-
body: JSON.stringify({ email2fa: 'owner@example.com' }),
|
|
147
|
-
}).then(response => response.json()) as { code: string }
|
|
148
|
-
const challenged = await fetch(base + '/bridge/api/login/bridge', {
|
|
149
|
-
method: 'POST',
|
|
150
|
-
body: JSON.stringify({ code: start.code }),
|
|
151
|
-
}).then(response => response.json()) as { challenge?: string }
|
|
152
|
-
expect(challenged.challenge).toBe('email')
|
|
153
|
-
const mail = sentCodes.filter(entry => entry.email === 'owner@example.com').at(-1)
|
|
154
|
-
const verified = await fetch(base + '/bridge/api/login/bridge/verify', {
|
|
155
|
-
method: 'POST',
|
|
156
|
-
body: JSON.stringify({ code: start.code, emailCode: mail?.code ?? '' }),
|
|
157
|
-
})
|
|
158
|
-
expect(verified.status).toBe(200)
|
|
159
|
-
expect(verified.headers.get('set-cookie')).toContain('mbs=')
|
|
160
|
-
const replay = await fetch(base + '/bridge/api/login/bridge/verify', {
|
|
161
|
-
method: 'POST',
|
|
162
|
-
body: JSON.stringify({ code: start.code, emailCode: mail?.code ?? '' }),
|
|
163
|
-
})
|
|
164
|
-
expect(replay.status).toBe(401)
|
|
165
|
-
})
|
|
166
|
-
|
|
167
|
-
it('rejects wrong codes and unknown providers', async () => {
|
|
168
|
-
const base = `http://127.0.0.1:${bridgePort}`
|
|
169
|
-
await fetch(base + '/bridge/api/email/code', { method: 'POST', body: JSON.stringify({ email: 'x@example.com' }) })
|
|
170
|
-
const bad = await fetch(base + '/bridge/api/login/email', {
|
|
171
|
-
method: 'POST',
|
|
172
|
-
body: JSON.stringify({ email: 'x@example.com', code: '000000' }),
|
|
173
|
-
})
|
|
174
|
-
expect(bad.status).toBe(401)
|
|
175
|
-
const unknown = await fetch(base + '/bridge/api/login/external', {
|
|
176
|
-
method: 'POST',
|
|
177
|
-
body: JSON.stringify({ provider: 'wechat', payload: { code: 'c1' } }),
|
|
178
|
-
})
|
|
179
|
-
expect(unknown.status).toBe(401)
|
|
180
|
-
})
|
|
181
|
-
})
|
package/src/store.spec.ts
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { mkdtempSync, writeFileSync } from 'node:fs'
|
|
2
|
-
import { tmpdir } from 'node:os'
|
|
3
|
-
import { join } from 'node:path'
|
|
4
|
-
import { describe, expect, it } from 'vitest'
|
|
5
|
-
import { UserStore } from './store.ts'
|
|
6
|
-
|
|
7
|
-
function freshStore() {
|
|
8
|
-
const file = join(mkdtempSync(join(tmpdir(), 'mbs-')), 'users.json')
|
|
9
|
-
return new UserStore(file, '0123456789abcdef')
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
describe('user store', () => {
|
|
13
|
-
it('issues and consumes email codes once', () => {
|
|
14
|
-
const store = freshStore()
|
|
15
|
-
const code = store.issueEmailCode('Dee@Example.com')
|
|
16
|
-
expect(code).toMatch(/^\d{6}$/)
|
|
17
|
-
store.consumeEmailCode('dee@example.com', code)
|
|
18
|
-
expect(() => store.consumeEmailCode('dee@example.com', code)).toThrow(/invalid/)
|
|
19
|
-
expect(() => store.issueEmailCode('not-an-email')).toThrow(/invalid email/)
|
|
20
|
-
})
|
|
21
|
-
|
|
22
|
-
it('logs in external providers and creates the user on first sight', () => {
|
|
23
|
-
const store = freshStore()
|
|
24
|
-
const token = store.loginExternal('wechat', 'wx-open-1')
|
|
25
|
-
expect(store.userFor(token)).toBe('wechat:wx-open-1')
|
|
26
|
-
const emailToken = store.loginExternal('email', 'dee@example.com')
|
|
27
|
-
expect(store.userFor(emailToken)).toBe('email:dee@example.com')
|
|
28
|
-
store.bind(token, 'ff00ff')
|
|
29
|
-
expect(store.bridgeFor(token)).toBe('ff00ff')
|
|
30
|
-
})
|
|
31
|
-
|
|
32
|
-
it('persists across instances via the json file', () => {
|
|
33
|
-
const file = join(mkdtempSync(join(tmpdir(), 'mbs-')), 'users.json')
|
|
34
|
-
writeFileSync(file, JSON.stringify({ users: {}, tokens: {}, codes: {} }))
|
|
35
|
-
const first = new UserStore(file, '0123456789abcdef')
|
|
36
|
-
first.loginExternal('email', 'carol@example.com')
|
|
37
|
-
const second = new UserStore(file, '0123456789abcdef')
|
|
38
|
-
expect(second.loginExternal('email', 'carol@example.com')).toBeTruthy()
|
|
39
|
-
})
|
|
40
|
-
})
|