dsh-device-auth 0.0.0-stage → 0.2.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.
@@ -0,0 +1,23 @@
1
+ # dsh-device-auth bundle layer.
2
+ #
3
+ # 1. Insert the Host plugin that accepts durable per-device tokens in addition
4
+ # to this process's launch token.
5
+ # 2. Stop printing the launch URL: it is the only place the rotating launch
6
+ # token reaches the journal. With this layer a device login link is printed
7
+ # explicitly by `dsh-auth add|rotate`, which satisfies "credentials never
8
+ # appear in logs unless an explicit command prints them".
9
+ #
10
+ # `config` is replaced wholesale by a patch, so the web-runtime row restates
11
+ # every field of the shipped config (the command-line wiring is unchanged).
12
+ - insert:
13
+ - id: device-auth
14
+ name: 'dsh-device-auth'
15
+ config:
16
+ storePath: !!js dshHomePath('remote-auth.json')
17
+ - id: web-runtime
18
+ name: '@deepseek-ai/dsh-web-app'
19
+ config:
20
+ openBrowser: !!js ctx.webStartup.openBrowser
21
+ printUrl: false
22
+ publicUrl: !!js ctx.webStartup.publicUrl
23
+ surfaceContext: true
package/icon.svg ADDED
@@ -0,0 +1,21 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128" role="img" aria-label="Device credentials">
2
+ <defs>
3
+ <linearGradient id="bg" x1="16" y1="8" x2="112" y2="120" gradientUnits="userSpaceOnUse">
4
+ <stop offset="0" stop-color="#4d6bfe"/>
5
+ <stop offset="1" stop-color="#2a3fae"/>
6
+ </linearGradient>
7
+ <linearGradient id="glow" x1="64" y1="30" x2="64" y2="100" gradientUnits="userSpaceOnUse">
8
+ <stop offset="0" stop-color="#ffffff" stop-opacity="0.95"/>
9
+ <stop offset="1" stop-color="#dfe6ff" stop-opacity="0.85"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect x="4" y="4" width="120" height="120" rx="28" fill="url(#bg)"/>
13
+ <rect x="10" y="10" width="108" height="108" rx="23" fill="none" stroke="#ffffff" stroke-opacity="0.18" stroke-width="2"/>
14
+ <g fill="none" stroke="url(#glow)" stroke-linecap="round" stroke-linejoin="round">
15
+ <rect x="34" y="26" width="60" height="76" rx="12" stroke-width="6"/>
16
+ <path d="M34 44h60" stroke-width="6" stroke-opacity="0.65"/>
17
+ <circle cx="64" cy="64" r="9.5" stroke-width="5.5"/>
18
+ <path d="M64 73.5v16" stroke-width="5.5"/>
19
+ <path d="M57.5 82.5H64" stroke-width="4.5" stroke-opacity="0.8"/>
20
+ </g>
21
+ </svg>
package/lib/index.js ADDED
@@ -0,0 +1,347 @@
1
+ /**
2
+ * dsh-device-auth — stable, revocable per-device credentials for the DSH Web UI.
3
+ *
4
+ * DeepSeek Harness mints one random launch token per process and exposes it
5
+ * only through the startup URL, so every paired remote client breaks on
6
+ * restart. This plugin adds a durable credential layer *without* touching the
7
+ * installed Harness packages:
8
+ *
9
+ * - It reads device token hashes from a store file (`remote-auth.json`), and
10
+ * wraps the live `connection` service instance methods `authorizeConnect` /
11
+ * `authorizeIndex`. Their callers dispatch dynamically per request, so a
12
+ * wrapper is enough to accept additional tokens. A matching device token is
13
+ * swapped for this process's real launch token and the original
14
+ * implementation runs unchanged: the Host/Origin fence, the 302/303
15
+ * redirect, the signed cookie, the audience binding and the 30-day lifetime
16
+ * all stay the original ones.
17
+ *
18
+ * - It indexes every cookie minted during a device exchange by its hash and
19
+ * device id (`remote-auth-sessions.json`), and wraps `admit` plus
20
+ * `authorizeIndex` to reject a session whose device was revoked. That makes
21
+ * revocation immediate for the revoked device, while cookies minted with the
22
+ * real launch token (or before this plugin existed) keep working unchanged.
23
+ *
24
+ * Everything else (the printed launch URL, the browser cookie flow, the
25
+ * trusted-host fence, `--public-url`) behaves exactly as before; unknown
26
+ * tokens are delegated untouched. Because the plugin lives in the user's
27
+ * profile it survives `npm i -g @deepseek-ai/dsh@<next>` upgrades, and it fails
28
+ * loudly instead of silently degrading when a future Harness version stops
29
+ * exposing the wrapped methods.
30
+ *
31
+ * The device store is only read here. Mutations (add/rotate/revoke) are made by
32
+ * the `dsh-auth` CLI under a cross-process lock, so a stale in-process snapshot
33
+ * can never resurrect a revoked device. The session index is a derived cache:
34
+ * it only ever grants a rejection, never authentication, so a lost or racy
35
+ * write degrades to "cookie delegated to the original check" rather than to a
36
+ * bypass.
37
+ */
38
+ import { readFileSync, statSync } from 'node:fs'
39
+
40
+ import {
41
+ TOKEN_PREFIX,
42
+ findActiveDevice,
43
+ isActiveDevice,
44
+ normalizeStore,
45
+ } from './store.mjs'
46
+ import {
47
+ cookieHeaderOf,
48
+ cookiePairsFromHeader,
49
+ hashCookiePair,
50
+ mergeSession,
51
+ readSessionsFile,
52
+ resolveSessionsPath,
53
+ sessionFromSetCookie,
54
+ writeSessionsFile,
55
+ } from './sessions.mjs'
56
+
57
+ /** Stable Cordis plugin name. */
58
+ export const name = 'device-auth'
59
+
60
+ /** The connection service must exist before the wrappers can be installed. */
61
+ export const inject = ['connection']
62
+
63
+ /** Base used only to parse request URLs and the authenticated launch URL. */
64
+ const URL_BASE = 'http://dsh.invalid'
65
+
66
+ /** Cache key from nanosecond mtime and size; undefined when the file is absent. */
67
+ function fileKey(path) {
68
+ try {
69
+ const stat = statSync(path, { bigint: true })
70
+ return `${String(stat.mtimeNs)}:${String(stat.size)}`
71
+ } catch {
72
+ return undefined
73
+ }
74
+ }
75
+
76
+ /** Extract the single `token` query value from a path or absolute URL. */
77
+ function tokenFromUrl(rawUrl) {
78
+ if (typeof rawUrl !== 'string' || rawUrl === '') return undefined
79
+ let url
80
+ try {
81
+ url = new URL(rawUrl, URL_BASE)
82
+ } catch {
83
+ return undefined
84
+ }
85
+ const values = url.searchParams.getAll('token')
86
+ return values.length === 1 ? values[0] : undefined
87
+ }
88
+
89
+ /** Return `rawUrl` with its token query swapped, preserving its absolute/relative shape. */
90
+ function withToken(rawUrl, token) {
91
+ const url = new URL(rawUrl, URL_BASE)
92
+ url.searchParams.set('token', token)
93
+ const absolute = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(rawUrl)
94
+ return absolute ? url.href : `${url.pathname}${url.search}`
95
+ }
96
+
97
+ /** Clone a Fetch `Request` (or an IncomingMessage-like object) with a rewritten URL. */
98
+ function withRewrittenRequest(request, token) {
99
+ const nextUrl = withToken(request.url, token)
100
+ if (typeof Request !== 'undefined' && request instanceof Request) {
101
+ return new Request(nextUrl, { method: request.method, headers: request.headers })
102
+ }
103
+ return { ...request, url: nextUrl }
104
+ }
105
+
106
+ /** Collect `Set-Cookie` values written by one call while letting it run normally. */
107
+ function captureSetCookies(response, run) {
108
+ const originalWriteHead = response?.writeHead
109
+ if (typeof originalWriteHead !== 'function') return { cookies: [], result: run() }
110
+ const cookies = []
111
+ response.writeHead = function captureWriteHead(status, headers, ...rest) {
112
+ const value = headers?.['set-cookie'] ?? headers?.['Set-Cookie']
113
+ if (Array.isArray(value)) for (const entry of value) cookies.push(String(entry))
114
+ else if (value !== undefined) cookies.push(String(value))
115
+ return originalWriteHead.call(this, status, headers, ...rest)
116
+ }
117
+ try {
118
+ const result = run()
119
+ return { cookies, result }
120
+ } finally {
121
+ response.writeHead = originalWriteHead
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Install the plugin.
127
+ * @param {import('@deepseek-ai/cordis').Context} ctx
128
+ * @param {{ storePath: string, sessionsPath?: string, prefix?: string }} config
129
+ */
130
+ export function apply(ctx, config) {
131
+ const storePath = typeof config?.storePath === 'string' ? config.storePath.trim() : ''
132
+ if (storePath === '') {
133
+ throw new Error('device-auth: config.storePath must name the device credential store (use !!js dshHomePath(\'remote-auth.json\'))')
134
+ }
135
+ const sessionsPath = resolveSessionsPath(storePath, config?.sessionsPath)
136
+ const prefix = typeof config?.prefix === 'string' && config.prefix !== '' ? config.prefix : TOKEN_PREFIX
137
+
138
+ /** Last device-store snapshot, keyed by mtime+size so a CLI mutation is visible on the next request. */
139
+ let snapshot = { key: undefined, devices: [], exists: false }
140
+ let sessionSnapshot = { key: undefined, sessions: [] }
141
+ let warnedAt = 0
142
+ const warn = (message) => {
143
+ const now = Date.now()
144
+ if (now - warnedAt < 60_000) return
145
+ warnedAt = now
146
+ console.warn(`device-auth: ${message}`)
147
+ }
148
+
149
+ /** Read device records, fail closed (no devices) on an unreadable store. */
150
+ const devices = () => {
151
+ const key = fileKey(storePath)
152
+ if (key === undefined) {
153
+ snapshot = { key: 'missing', devices: [], exists: false }
154
+ return snapshot.devices
155
+ }
156
+ if (snapshot.key === key) return snapshot.devices
157
+ try {
158
+ const store = normalizeStore(JSON.parse(readFileSync(storePath, 'utf8')))
159
+ snapshot = { key, devices: store.devices, exists: true }
160
+ return snapshot.devices
161
+ } catch (error) {
162
+ warn(`ignoring unreadable store ${storePath}: ${error.message}`)
163
+ snapshot = { key, devices: [], exists: true }
164
+ return snapshot.devices
165
+ }
166
+ }
167
+
168
+ /** Read device records without the cache: revocation must be visible on the very next request. */
169
+ const devicesFresh = () => {
170
+ try {
171
+ return normalizeStore(JSON.parse(readFileSync(storePath, 'utf8'))).devices
172
+ } catch (error) {
173
+ if (error?.code !== 'ENOENT') warn(`cannot read ${storePath}: ${error.message}`)
174
+ return []
175
+ }
176
+ }
177
+
178
+ /** Read the cookie→device index, cached by nanosecond mtime and size. */
179
+ const sessions = () => {
180
+ const key = fileKey(sessionsPath)
181
+ if (key === undefined) {
182
+ sessionSnapshot = { key: 'missing', sessions: [] }
183
+ return sessionSnapshot.sessions
184
+ }
185
+ if (sessionSnapshot.key === key) return sessionSnapshot.sessions
186
+ try {
187
+ const { sessions: records } = readSessionsFile(sessionsPath)
188
+ sessionSnapshot = { key, sessions: records }
189
+ return records
190
+ } catch (error) {
191
+ warn(`ignoring session index ${sessionsPath}: ${error.message}`)
192
+ sessionSnapshot = { key, sessions: [] }
193
+ return sessionSnapshot.sessions
194
+ }
195
+ }
196
+
197
+ /** Map a presented request's cookies to a device that is no longer active. */
198
+ const revokedDeviceOf = (request) => {
199
+ const pairs = cookiePairsFromHeader(cookieHeaderOf(request))
200
+ if (pairs.length === 0) return undefined
201
+ const index = sessions()
202
+ if (index.length === 0) return undefined
203
+ const byHash = new Map()
204
+ for (const session of index) {
205
+ const mapped = byHash.get(session.cookieHash)
206
+ if (mapped === undefined) byHash.set(session.cookieHash, [session.deviceId])
207
+ else if (!mapped.includes(session.deviceId)) mapped.push(session.deviceId)
208
+ }
209
+ const records = devicesFresh()
210
+ for (const pair of pairs) {
211
+ const deviceIds = byHash.get(hashCookiePair(pair))
212
+ if (deviceIds === undefined) continue
213
+ for (const deviceId of deviceIds) {
214
+ const device = records.find((record) => record.id === deviceId)
215
+ if (device === undefined || !isActiveDevice(device)) return deviceId
216
+ }
217
+ }
218
+ return undefined
219
+ }
220
+
221
+ /** Record the cookies just minted for a device exchange; failures never block the response. */
222
+ const recordMintedSessions = (setCookies, deviceId) => {
223
+ if (!Array.isArray(setCookies) || setCookies.length === 0) return
224
+ try {
225
+ const { sessions: current } = readSessionsFile(sessionsPath)
226
+ let changed = false
227
+ for (const setCookie of setCookies) {
228
+ const parsed = sessionFromSetCookie(setCookie)
229
+ if (parsed === undefined) continue
230
+ const entry = {
231
+ cookieHash: hashCookiePair(parsed.pair),
232
+ deviceId,
233
+ issuedAt: new Date().toISOString(),
234
+ expiresAt: parsed.expiresAt,
235
+ }
236
+ if (mergeSession(current, entry)) changed = true
237
+ }
238
+ if (changed) {
239
+ writeSessionsFile(sessionsPath, current)
240
+ sessionSnapshot = { key: fileKey(sessionsPath) ?? 'written', sessions: current }
241
+ }
242
+ } catch (error) {
243
+ warn(`could not record sessions for ${deviceId}: ${error instanceof Error ? error.message : String(error)}`)
244
+ }
245
+ }
246
+
247
+ /** The current process's real launch token, read through the documented service method. */
248
+ const launchToken = (connection) => {
249
+ try {
250
+ const url = new URL(connection.authenticatedUrl(`${URL_BASE}/`))
251
+ return url.searchParams.get('token') ?? undefined
252
+ } catch {
253
+ return undefined
254
+ }
255
+ }
256
+
257
+ /** A device token matching an active record, or undefined. */
258
+ const matchedDevice = (presented) => {
259
+ if (typeof presented !== 'string' || !presented.startsWith(prefix)) return undefined
260
+ return findActiveDevice({ devices: devices() }, presented)
261
+ }
262
+
263
+ let wrappedConnection
264
+ let restoreWrappers
265
+
266
+ const ensureWrapped = () => {
267
+ const connection = ctx.get('connection')
268
+ if (connection === undefined || connection === null) return
269
+ if (wrappedConnection === connection) return
270
+
271
+ const originalConnect = connection.authorizeConnect
272
+ const originalIndex = connection.authorizeIndex
273
+ const originalAdmit = connection.admit
274
+ if (typeof originalConnect !== 'function' || typeof originalIndex !== 'function' || typeof originalAdmit !== 'function') {
275
+ throw new Error('device-auth: unsupported Harness version: the connection service no longer exposes authorizeConnect/authorizeIndex/admit; refusing to activate a silent no-op')
276
+ }
277
+
278
+ const wrappedConnect = function deviceAuthorizeConnect(request, response) {
279
+ const device = matchedDevice(tokenFromUrl(request?.url))
280
+ const token = device === undefined ? undefined : launchToken(connection)
281
+ if (token === undefined || typeof request?.url !== 'string') {
282
+ return originalConnect.call(connection, request, response)
283
+ }
284
+ const originalUrl = request.url
285
+ const { cookies, result } = captureSetCookies(response, () => {
286
+ try {
287
+ request.url = withToken(originalUrl, token)
288
+ return originalConnect.call(connection, request, response)
289
+ } finally {
290
+ request.url = originalUrl
291
+ }
292
+ })
293
+ recordMintedSessions(cookies, device.id)
294
+ return result
295
+ }
296
+
297
+ const wrappedIndex = function deviceAuthorizeIndex(request, response, secure) {
298
+ if (revokedDeviceOf(request) !== undefined) {
299
+ response.writeHead(401, { 'cache-control': 'no-store' })
300
+ response.end('unauthorized')
301
+ return false
302
+ }
303
+ const device = matchedDevice(tokenFromUrl(request?.url))
304
+ const token = device === undefined ? undefined : launchToken(connection)
305
+ if (token === undefined || typeof request?.url !== 'string') {
306
+ return originalIndex.call(connection, request, response, secure)
307
+ }
308
+ const { cookies, result } = captureSetCookies(response, () =>
309
+ originalIndex.call(connection, withRewrittenRequest(request, token), response, secure))
310
+ recordMintedSessions(cookies, device.id)
311
+ return result
312
+ }
313
+
314
+ const wrappedAdmit = function deviceAdmit(request) {
315
+ if (revokedDeviceOf(request) !== undefined) return { rejection: 401 }
316
+ return originalAdmit.call(connection, request)
317
+ }
318
+
319
+ connection.authorizeConnect = wrappedConnect
320
+ connection.authorizeIndex = wrappedIndex
321
+ connection.admit = wrappedAdmit
322
+ wrappedConnection = connection
323
+ restoreWrappers = () => {
324
+ if (connection.authorizeConnect === wrappedConnect) connection.authorizeConnect = originalConnect
325
+ if (connection.authorizeIndex === wrappedIndex) connection.authorizeIndex = originalIndex
326
+ if (connection.admit === wrappedAdmit) connection.admit = originalAdmit
327
+ wrappedConnection = undefined
328
+ restoreWrappers = undefined
329
+ }
330
+ }
331
+
332
+ ctx.effect(() => {
333
+ ensureWrapped()
334
+ // A profile config reload may replace the connection plugin instance.
335
+ const off = ctx.on('app-boot/config-reload', () => {
336
+ try {
337
+ ensureWrapped()
338
+ } catch (error) {
339
+ console.error(`device-auth: ${error instanceof Error ? error.message : String(error)}`)
340
+ }
341
+ })
342
+ return () => {
343
+ off?.()
344
+ restoreWrappers?.()
345
+ }
346
+ }, 'device-auth: connection authorization wrapper')
347
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Session index for the durable device credentials.
3
+ *
4
+ * A device token is exchanged by the real `client-connection` implementation,
5
+ * which mints an ordinary signed cookie. That cookie carries no device
6
+ * identity, so revoking the device could not evict a session it already holds.
7
+ *
8
+ * This module closes that gap without touching the cookie format or the signing
9
+ * secret: when an exchange happens for a device token, the plugin records
10
+ * `sha256(<cookie-name>=<cookie-value>)` with the device id. On every later
11
+ * request the plugin hashes the presented cookies and rejects a request whose
12
+ * cookie belongs to a revoked or expired device. Only hashes are stored.
13
+ *
14
+ * The map is an append-only index keyed by cookie hash:
15
+ * - a revoked device is rejected on its next request;
16
+ * - cookies minted with the real launch token (or before this plugin existed)
17
+ * have no entry and are delegated to the original authentication unchanged;
18
+ * - a deleted cookie entry cannot help an attacker: without a cookie the
19
+ * original authentication rejects the request anyway.
20
+ */
21
+ import { createHash } from 'node:crypto'
22
+ import { chmodSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
23
+ import { dirname, join } from 'node:path'
24
+
25
+ export const SESSIONS_VERSION = 1
26
+ export const SESSIONS_FILE_NAME = 'remote-auth-sessions.json'
27
+ const MAX_SESSIONS = 4096
28
+ const HASH_PATTERN = /^[0-9a-f]{64}$/
29
+ const PRUNE_MARGIN_MS = 60_000
30
+
31
+ /** The session index lives beside the credential store. */
32
+ export function resolveSessionsPath(storePath, explicit) {
33
+ if (typeof explicit === 'string' && explicit.trim() !== '') return explicit.trim()
34
+ return join(dirname(storePath), SESSIONS_FILE_NAME)
35
+ }
36
+
37
+ /** SHA-256 hex digest of one `name=value` cookie pair. */
38
+ export function hashCookiePair(pair) {
39
+ return createHash('sha256').update(pair, 'utf8').digest('hex')
40
+ }
41
+
42
+ /** Normalize one `name=value` pair (trim, drop surrounding whitespace only). */
43
+ export function normalizeCookiePair(pair) {
44
+ if (typeof pair !== 'string') return undefined
45
+ const trimmed = pair.trim()
46
+ const at = trimmed.indexOf('=')
47
+ if (at <= 0) return undefined
48
+ return `${trimmed.slice(0, at).trim()}=${trimmed.slice(at + 1).trim()}`
49
+ }
50
+
51
+ /**
52
+ * Turn one `Set-Cookie` header value into a `name=value` pair plus its expiry.
53
+ * @returns {{ pair: string, expiresAt: string | null } | undefined}
54
+ */
55
+ export function sessionFromSetCookie(setCookie, now = Date.now()) {
56
+ if (typeof setCookie !== 'string') return undefined
57
+ const segments = setCookie.split(';')
58
+ const pair = normalizeCookiePair(segments[0])
59
+ if (pair === undefined) return undefined
60
+ let expiresAt = null
61
+ for (const segment of segments.slice(1)) {
62
+ const at = segment.indexOf('=')
63
+ if (at === -1) continue
64
+ const name = segment.slice(0, at).trim().toLowerCase()
65
+ const value = segment.slice(at + 1).trim()
66
+ if (name === 'max-age') {
67
+ const seconds = Number(value)
68
+ if (Number.isFinite(seconds) && seconds > 0) expiresAt = new Date(now + seconds * 1000).toISOString()
69
+ } else if (name === 'expires' && expiresAt === null) {
70
+ const time = Date.parse(value)
71
+ if (Number.isFinite(time)) expiresAt = new Date(time).toISOString()
72
+ }
73
+ }
74
+ return { pair, expiresAt }
75
+ }
76
+
77
+ /** Read a Cookie request header (string) into normalized `name=value` pairs. */
78
+ export function cookiePairsFromHeader(headerValue) {
79
+ if (typeof headerValue !== 'string' || headerValue.trim() === '') return []
80
+ const pairs = []
81
+ for (const segment of headerValue.split(';')) {
82
+ const pair = normalizeCookiePair(segment)
83
+ if (pair !== undefined) pairs.push(pair)
84
+ }
85
+ return pairs
86
+ }
87
+
88
+ /** Read the Cookie header from a Node request or a Fetch `Request`. */
89
+ export function cookieHeaderOf(request) {
90
+ const headers = request?.headers
91
+ if (headers === undefined || headers === null) return undefined
92
+ if (typeof headers.get === 'function') {
93
+ const value = headers.get('cookie')
94
+ return value === null || value === undefined ? undefined : String(value)
95
+ }
96
+ const value = headers.cookie ?? headers.Cookie
97
+ return typeof value === 'string' ? value : undefined
98
+ }
99
+
100
+ const isoOrNull = (value) => {
101
+ if (typeof value !== 'string') return null
102
+ const time = Date.parse(value)
103
+ return Number.isFinite(time) ? new Date(time).toISOString() : null
104
+ }
105
+
106
+ /** Empty session index. */
107
+ export function emptySessions() {
108
+ return { version: SESSIONS_VERSION, sessions: [] }
109
+ }
110
+
111
+ /** Normalize decoded JSON into the session index; malformed entries are dropped. */
112
+ export function normalizeSessions(raw) {
113
+ if (raw === null || typeof raw !== 'object' || !Array.isArray(raw.sessions)) return emptySessions()
114
+ const sessions = []
115
+ const seen = new Set()
116
+ for (const entry of raw.sessions) {
117
+ if (entry === null || typeof entry !== 'object') continue
118
+ const cookieHash = typeof entry.cookieHash === 'string' && HASH_PATTERN.test(entry.cookieHash)
119
+ ? entry.cookieHash
120
+ : undefined
121
+ const deviceId = typeof entry.deviceId === 'string' && entry.deviceId !== '' ? entry.deviceId : undefined
122
+ const key = cookieHash === undefined || deviceId === undefined ? undefined : `${cookieHash}:${deviceId}`
123
+ if (key === undefined || seen.has(key)) continue
124
+ seen.add(key)
125
+ sessions.push({
126
+ cookieHash,
127
+ deviceId,
128
+ issuedAt: isoOrNull(entry.issuedAt) ?? new Date().toISOString(),
129
+ expiresAt: isoOrNull(entry.expiresAt),
130
+ })
131
+ }
132
+ return { version: SESSIONS_VERSION, sessions }
133
+ }
134
+
135
+ /**
136
+ * Read the session index synchronously (the Host authentication path is sync).
137
+ * A missing file is an empty index, never an error.
138
+ */
139
+ export function readSessionsFile(path) {
140
+ let stat
141
+ try {
142
+ stat = statSync(path)
143
+ } catch (error) {
144
+ if (error?.code === 'ENOENT') return { sessions: [], exists: false, mtimeMs: -1, size: -1 }
145
+ throw error
146
+ }
147
+ const raw = JSON.parse(readFileSync(path, 'utf8'))
148
+ const store = normalizeSessions(raw)
149
+ return { sessions: store.sessions, exists: true, mtimeMs: stat.mtimeMs, size: stat.size }
150
+ }
151
+
152
+ /** Atomically replace the session index (0700 directory, 0600 file). */
153
+ export function writeSessionsFile(path, sessions) {
154
+ const directory = dirname(path)
155
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
156
+ try { chmodSync(directory, 0o700) } catch { /* best effort */ }
157
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`
158
+ writeFileSync(temporary, `${JSON.stringify({ version: SESSIONS_VERSION, sessions }, null, 2)}\n`, { mode: 0o600 })
159
+ try { chmodSync(temporary, 0o600) } catch { /* best effort */ }
160
+ renameSync(temporary, path)
161
+ try { chmodSync(path, 0o600) } catch { /* best effort */ }
162
+ }
163
+
164
+ /** Drop expired entries, keeping at most `MAX_SESSIONS` newest records. */
165
+ export function pruneSessions(sessions, now = Date.now()) {
166
+ const kept = sessions.filter((session) => {
167
+ if (typeof session.expiresAt !== 'string') return true
168
+ const expires = Date.parse(session.expiresAt)
169
+ return !Number.isFinite(expires) || expires + PRUNE_MARGIN_MS > now
170
+ })
171
+ if (kept.length <= MAX_SESSIONS) return kept
172
+ return kept.slice(kept.length - MAX_SESSIONS)
173
+ }
174
+
175
+ /**
176
+ * Add or refresh one mapped session and drop expired records.
177
+ * @returns {boolean} whether the index changed
178
+ */
179
+ export function mergeSession(sessions, entry, now = Date.now()) {
180
+ const pruned = pruneSessions(sessions, now)
181
+ const index = pruned.findIndex((session) => session.cookieHash === entry.cookieHash && session.deviceId === entry.deviceId)
182
+ if (index !== -1) pruned.splice(index, 1)
183
+ pruned.push(entry)
184
+ const final = pruneSessions(pruned, now)
185
+ const same = final.length === sessions.length
186
+ && final.every((session, at) => session.cookieHash === sessions[at]?.cookieHash
187
+ && session.deviceId === sessions[at]?.deviceId
188
+ && session.expiresAt === sessions[at]?.expiresAt)
189
+ if (same) return false
190
+ sessions.splice(0, sessions.length, ...final)
191
+ return true
192
+ }
193
+
194
+ /** Remove every session mapped to one device; returns how many were removed. */
195
+ export function removeSessionsForDevice(sessions, deviceId) {
196
+ const before = sessions.length
197
+ const kept = sessions.filter((session) => session.deviceId !== deviceId)
198
+ sessions.splice(0, sessions.length, ...kept)
199
+ return before - kept.length
200
+ }