@deep-podder/dsh-remote-mobile 0.0.0-stage → 0.0.6

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/auth.js ADDED
@@ -0,0 +1,290 @@
1
+ // Pairing, device sessions, cookie signing and PIN rate limiting.
2
+ // All secrets are process-local random values; no external dependencies.
3
+ import { createHmac, randomBytes, randomInt, timingSafeEqual } from 'node:crypto'
4
+
5
+ const DEFAULT_PIN_TTL_MS = 5 * 60 * 1000
6
+ const DEFAULT_TOKEN_TTL_MS = 10 * 60 * 1000
7
+ const DEFAULT_COOKIE_TTL_MS = 30 * 24 * 60 * 60 * 1000
8
+ const DEFAULT_MAX_DEVICES = 8
9
+ const DEFAULT_MAX_FAILURES = 5
10
+ const DEFAULT_FAILURE_WINDOW_MS = 5 * 60 * 1000
11
+
12
+ function hmac(secret, value) {
13
+ return createHmac('sha256', secret).update(value).digest('base64url')
14
+ }
15
+
16
+ /** Constant-time string comparison that never throws on length mismatch. */
17
+ export function equals(a, b) {
18
+ if (typeof a !== 'string' || typeof b !== 'string') return false
19
+ const left = Buffer.from(a)
20
+ const right = Buffer.from(b)
21
+ if (left.length !== right.length) return false
22
+ return timingSafeEqual(left, right)
23
+ }
24
+
25
+ function randomPin() {
26
+ return String(randomInt(0, 10000)).padStart(4, '0')
27
+ }
28
+
29
+ function deviceName(userAgent) {
30
+ const ua = typeof userAgent === 'string' ? userAgent : ''
31
+ const platform = /iPhone/i.test(ua) ? 'iPhone'
32
+ : /iPad/i.test(ua) ? 'iPad'
33
+ : /Android/i.test(ua) ? 'Android'
34
+ : /Macintosh/i.test(ua) ? 'Mac'
35
+ : /Windows/i.test(ua) ? 'Windows'
36
+ : /Linux/i.test(ua) ? 'Linux'
37
+ : 'Phone'
38
+ const browser = /CriOS|Chrome/i.test(ua) ? 'Chrome'
39
+ : /FxiOS|Firefox/i.test(ua) ? 'Firefox'
40
+ : /EdgiOS|Edg/i.test(ua) ? 'Edge'
41
+ : /Safari/i.test(ua) ? 'Safari'
42
+ : 'Browser'
43
+ return `${platform} ${browser}`.slice(0, 48)
44
+ }
45
+
46
+ /**
47
+ * @param {object} options
48
+ * @param {string} options.secret persistent HMAC secret (required for cookies to survive restart)
49
+ * @param {object} [options.log]
50
+ */
51
+ export function createAuth(options = {}) {
52
+ const {
53
+ log = console,
54
+ pinTtlMs = DEFAULT_PIN_TTL_MS,
55
+ tokenTtlMs = DEFAULT_TOKEN_TTL_MS,
56
+ cookieTtlMs = DEFAULT_COOKIE_TTL_MS,
57
+ maxDevices = DEFAULT_MAX_DEVICES,
58
+ maxFailures = DEFAULT_MAX_FAILURES,
59
+ failureWindowMs = DEFAULT_FAILURE_WINDOW_MS,
60
+ } = options
61
+ if (typeof options.secret !== 'string' || options.secret.length < 32) {
62
+ throw new Error('dsh-remote-mobile: auth secret must be at least 32 characters')
63
+ }
64
+ const secret = options.secret
65
+
66
+ /** @type {Map<string, {id:string,name:string,createdAt:number,lastSeenAt:number,userAgent:string,address:string,canApprove:boolean}>} */
67
+ const devices = new Map()
68
+ /** @type {Map<string, {count:number,windowStart:number,lockedUntil:number}>} */
69
+ const failures = new Map()
70
+ let pin = randomPin()
71
+ let pinExpiresAt = Date.now() + pinTtlMs
72
+ let token = randomBytes(24).toString('base64url')
73
+ let tokenExpiresAt = Date.now() + tokenTtlMs
74
+
75
+ function rotatePin() {
76
+ pin = randomPin()
77
+ pinExpiresAt = Date.now() + pinTtlMs
78
+ return { pin, pinExpiresAt }
79
+ }
80
+
81
+ function rotateToken() {
82
+ token = randomBytes(24).toString('base64url')
83
+ tokenExpiresAt = Date.now() + tokenTtlMs
84
+ return { token, tokenExpiresAt }
85
+ }
86
+
87
+ function rotateAll() {
88
+ rotatePin()
89
+ rotateToken()
90
+ }
91
+
92
+ function ensureFresh() {
93
+ const now = Date.now()
94
+ if (tokenExpiresAt <= now) rotateToken()
95
+ if (pinExpiresAt <= now) rotatePin()
96
+ }
97
+
98
+ /**
99
+ * Drop expired per-address limiter records so a failed-pairing spray cannot
100
+ * grow the map forever. Behaviour is unchanged for live windows.
101
+ */
102
+ function pruneFailures(now) {
103
+ if (failures.size < 64) return
104
+ for (const [address, record] of failures) {
105
+ if (record.lockedUntil <= now && now - record.windowStart > failureWindowMs) failures.delete(address)
106
+ }
107
+ }
108
+
109
+ function addDevice(userAgent, address) {
110
+ const id = randomBytes(12).toString('hex')
111
+ const device = {
112
+ id,
113
+ name: deviceName(userAgent),
114
+ createdAt: Date.now(),
115
+ lastSeenAt: Date.now(),
116
+ userAgent: typeof userAgent === 'string' ? userAgent.slice(0, 200) : '',
117
+ address: address || '',
118
+ // Approval permission: every newly paired device may answer by default.
119
+ canApprove: true,
120
+ }
121
+ devices.set(id, device)
122
+ while (devices.size > maxDevices) {
123
+ let oldest = null
124
+ for (const item of devices.values()) {
125
+ if (oldest === null || item.createdAt < oldest.createdAt) oldest = item
126
+ }
127
+ if (oldest === null) break
128
+ devices.delete(oldest.id)
129
+ log.info?.(`remote-mobile: dropped oldest paired device ${oldest.id.slice(0, 6)}… (limit ${maxDevices})`)
130
+ }
131
+ return device
132
+ }
133
+
134
+ function publicDevice(device) {
135
+ return {
136
+ id: device.id,
137
+ name: device.name,
138
+ createdAt: device.createdAt,
139
+ lastSeenAt: device.lastSeenAt,
140
+ address: device.address,
141
+ // Missing on records persisted by older versions → allowed (backwards compatible).
142
+ canApprove: device.canApprove !== false,
143
+ }
144
+ }
145
+
146
+ function pairWithToken(candidateToken, userAgent, address) {
147
+ ensureFresh()
148
+ if (!equals(candidateToken, token) || Date.now() > tokenExpiresAt) {
149
+ return { ok: false, error: 'invalid-token' }
150
+ }
151
+ const device = addDevice(userAgent, address)
152
+ rotateAll()
153
+ log.info?.(`remote-mobile: paired ${device.name}`)
154
+ return { ok: true, device: publicDevice(device) }
155
+ }
156
+
157
+ function pairWithPin(candidatePin, userAgent, address) {
158
+ ensureFresh()
159
+ const now = Date.now()
160
+ pruneFailures(now)
161
+ const record = failures.get(address) || { count: 0, windowStart: now, lockedUntil: 0 }
162
+ if (record.lockedUntil > now) {
163
+ return { ok: false, error: 'rate-limited', retryAfterMs: record.lockedUntil - now }
164
+ }
165
+ if (now - record.windowStart > failureWindowMs) {
166
+ record.count = 0
167
+ record.windowStart = now
168
+ }
169
+ failures.set(address, record)
170
+ if (!(typeof candidatePin === 'string' && /^\d{4}$/.test(candidatePin)) || !equals(candidatePin, pin)) {
171
+ record.count += 1
172
+ if (record.count >= maxFailures) {
173
+ record.lockedUntil = now + failureWindowMs
174
+ record.count = 0
175
+ record.windowStart = now
176
+ log.warn?.(`remote-mobile: PIN attempts from ${address} locked out for ${Math.round(failureWindowMs / 1000)}s`)
177
+ }
178
+ return { ok: false, error: 'invalid-pin' }
179
+ }
180
+ failures.delete(address)
181
+ const device = addDevice(userAgent, address)
182
+ rotateAll()
183
+ log.info?.(`remote-mobile: paired ${device.name}`)
184
+ return { ok: true, device: publicDevice(device) }
185
+ }
186
+
187
+ function deviceFromCookie(rawCookie) {
188
+ if (typeof rawCookie !== 'string' || rawCookie.length === 0) return null
189
+ const parts = rawCookie.split('.')
190
+ if (parts.length !== 3) return null
191
+ const [id, expiresAt, signature] = parts
192
+ if (!/^[a-f0-9]{24}$/.test(id) || !/^\d{13}$/.test(expiresAt)) return null
193
+ if (!equals(hmac(secret, `device|${id}|${expiresAt}`), signature)) return null
194
+ if (Number(expiresAt) <= Date.now()) return null
195
+ const device = devices.get(id)
196
+ if (device === undefined) return null
197
+ device.lastSeenAt = Date.now()
198
+ return device
199
+ }
200
+
201
+ function cookieValue(deviceId) {
202
+ const expiresAt = String(Date.now() + cookieTtlMs)
203
+ return `${deviceId}.${expiresAt}.${hmac(secret, `device|${deviceId}|${expiresAt}`)}`
204
+ }
205
+
206
+ function cookieMaxAgeSeconds() {
207
+ return Math.floor(cookieTtlMs / 1000)
208
+ }
209
+
210
+ function revoke(deviceId) {
211
+ return devices.delete(deviceId)
212
+ }
213
+
214
+ /**
215
+ * Flip one shared paired device's approval permission.
216
+ * @param {string} deviceId paired-device id
217
+ * @param {boolean} canApprove whether this device may answer approvals
218
+ * @returns the public device, or null when the id is unknown
219
+ */
220
+ function setCanApprove(deviceId, canApprove) {
221
+ const device = devices.get(deviceId)
222
+ if (device === undefined) return null
223
+ device.canApprove = canApprove === true
224
+ return publicDevice(device)
225
+ }
226
+
227
+ function revokeAll() {
228
+ const count = devices.size
229
+ devices.clear()
230
+ return count
231
+ }
232
+
233
+ function status() {
234
+ ensureFresh()
235
+ return {
236
+ pin,
237
+ pinExpiresAt,
238
+ token,
239
+ tokenExpiresAt,
240
+ devices: [...devices.values()].map(publicDevice),
241
+ }
242
+ }
243
+
244
+ function exportState() {
245
+ return {
246
+ secret,
247
+ devices: [...devices.values()],
248
+ }
249
+ }
250
+
251
+ function importState(state) {
252
+ if (state === null || typeof state !== 'object') return
253
+ if (Array.isArray(state.devices)) {
254
+ for (const raw of state.devices) {
255
+ if (raw === null || typeof raw !== 'object') continue
256
+ if (typeof raw.id !== 'string' || !/^[a-f0-9]{24}$/.test(raw.id)) continue
257
+ devices.set(raw.id, {
258
+ id: raw.id,
259
+ name: typeof raw.name === 'string' ? raw.name.slice(0, 48) : 'Paired device',
260
+ createdAt: Number(raw.createdAt) || Date.now(),
261
+ lastSeenAt: Number(raw.lastSeenAt) || Date.now(),
262
+ userAgent: typeof raw.userAgent === 'string' ? raw.userAgent.slice(0, 200) : '',
263
+ address: typeof raw.address === 'string' ? raw.address : '',
264
+ // Older state files have no flag; absence means "may approve".
265
+ canApprove: raw.canApprove !== false,
266
+ })
267
+ if (devices.size >= maxDevices) break
268
+ }
269
+ }
270
+ }
271
+
272
+ return {
273
+ rotatePin,
274
+ rotateToken,
275
+ rotateAll,
276
+ ensureFresh,
277
+ pairWithToken,
278
+ pairWithPin,
279
+ deviceFromCookie,
280
+ cookieValue,
281
+ cookieMaxAgeSeconds,
282
+ revoke,
283
+ revokeAll,
284
+ setCanApprove,
285
+ status,
286
+ exportState,
287
+ importState,
288
+ devices: () => [...devices.values()].map(publicDevice),
289
+ }
290
+ }