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.
- package/CHANGELOG.md +69 -0
- package/LICENSE +21 -0
- package/README.en.md +134 -0
- package/README.md +169 -2
- package/bin/dsh-auth.mjs +260 -0
- package/cordis.patch.yml +23 -0
- package/icon.svg +21 -0
- package/lib/index.js +347 -0
- package/lib/sessions.mjs +200 -0
- package/lib/store.mjs +300 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +70 -4
package/lib/store.mjs
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device credential store shared by the Host plugin and the `dsh-auth` CLI.
|
|
3
|
+
*
|
|
4
|
+
* Credential model (borrowed from OpenChamber's `remote-clients` store):
|
|
5
|
+
* - One durable, per-device login token; the plaintext leaves this module only
|
|
6
|
+
* once, from the mint/rotate call that created it.
|
|
7
|
+
* - Only the SHA-256 hex digest is persisted. Tokens are compared in constant
|
|
8
|
+
* time over decoded hex buffers of equal length.
|
|
9
|
+
* - The store file is written atomically (temp file + rename) with mode 0600
|
|
10
|
+
* inside a 0700 directory.
|
|
11
|
+
* - Cross-process mutation is serialized with a `.lock` directory so the CLI
|
|
12
|
+
* and any future writer cannot drop each other's device records.
|
|
13
|
+
*
|
|
14
|
+
* The Host plugin itself never writes the store; it only reads it, so a CLI
|
|
15
|
+
* mutation can never be resurrected by a stale in-process snapshot.
|
|
16
|
+
*/
|
|
17
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
|
|
18
|
+
import {
|
|
19
|
+
chmodSync,
|
|
20
|
+
mkdirSync,
|
|
21
|
+
readFileSync,
|
|
22
|
+
renameSync,
|
|
23
|
+
rmSync,
|
|
24
|
+
statSync,
|
|
25
|
+
writeFileSync,
|
|
26
|
+
} from 'node:fs'
|
|
27
|
+
import { homedir } from 'node:os'
|
|
28
|
+
import { dirname, join, resolve } from 'node:path'
|
|
29
|
+
|
|
30
|
+
export const STORE_VERSION = 1
|
|
31
|
+
/** Prefix every device credential carries; the plugin uses it to skip the store read for ordinary launch tokens. */
|
|
32
|
+
export const TOKEN_PREFIX = 'dsh_dev_'
|
|
33
|
+
export const DEFAULT_LABEL = 'device'
|
|
34
|
+
export const MAX_LABEL_LENGTH = 80
|
|
35
|
+
const TOKEN_BYTES = 32
|
|
36
|
+
const HASH_PATTERN = /^[0-9a-f]{64}$/
|
|
37
|
+
const LOCK_RETRY_MS = 50
|
|
38
|
+
const LOCK_TIMEOUT_MS = 3000
|
|
39
|
+
const LOCK_STALE_MS = 30_000
|
|
40
|
+
|
|
41
|
+
/** Resolve the store path: explicit value, else `$DSH_HOME/remote-auth.json`, else `~/.dsh/remote-auth.json`. */
|
|
42
|
+
export function resolveStorePath(explicit) {
|
|
43
|
+
if (typeof explicit === 'string' && explicit.trim() !== '') return resolve(explicit.trim())
|
|
44
|
+
const home = process.env.DSH_HOME?.trim() !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh')
|
|
45
|
+
return join(home, 'remote-auth.json')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** SHA-256 hex digest of a presented token. */
|
|
49
|
+
export function hashToken(token) {
|
|
50
|
+
return createHash('sha256').update(token, 'utf8').digest('hex')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Mint one device token: a stable prefix plus 32 random bytes in base64url (43 chars). */
|
|
54
|
+
export function generateToken(prefix = TOKEN_PREFIX) {
|
|
55
|
+
return `${prefix}${randomBytes(TOKEN_BYTES).toString('base64url')}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Normalize a human label to a non-empty, length-capped display name. */
|
|
59
|
+
export function normalizeLabel(value) {
|
|
60
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
61
|
+
return (text === '' ? DEFAULT_LABEL : text).slice(0, MAX_LABEL_LENGTH)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Case-insensitive identity of a label; a re-pair of the same device rotates its token. */
|
|
65
|
+
export function labelKey(value) {
|
|
66
|
+
return normalizeLabel(value).toLowerCase()
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Fresh device id. */
|
|
70
|
+
export function generateDeviceId() {
|
|
71
|
+
return `dev_${randomBytes(12).toString('hex')}`
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const isoOrNull = (value) => {
|
|
75
|
+
if (typeof value !== 'string') return null
|
|
76
|
+
const time = Date.parse(value)
|
|
77
|
+
return Number.isFinite(time) ? new Date(time).toISOString() : null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Empty store document. */
|
|
81
|
+
export function emptyStore() {
|
|
82
|
+
return { version: STORE_VERSION, devices: [] }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Normalize any decoded JSON into a store. Malformed records are dropped rather
|
|
87
|
+
* than repaired: a record without a usable hash must not authenticate anything.
|
|
88
|
+
*/
|
|
89
|
+
export function normalizeStore(raw) {
|
|
90
|
+
if (raw === null || typeof raw !== 'object' || !Array.isArray(raw.devices)) return emptyStore()
|
|
91
|
+
const devices = []
|
|
92
|
+
for (const entry of raw.devices) {
|
|
93
|
+
if (entry === null || typeof entry !== 'object') continue
|
|
94
|
+
const id = typeof entry.id === 'string' && entry.id !== '' ? entry.id : undefined
|
|
95
|
+
const tokenHash = typeof entry.tokenHash === 'string' && HASH_PATTERN.test(entry.tokenHash)
|
|
96
|
+
? entry.tokenHash
|
|
97
|
+
: undefined
|
|
98
|
+
if (id === undefined || tokenHash === undefined) continue
|
|
99
|
+
devices.push({
|
|
100
|
+
id,
|
|
101
|
+
label: normalizeLabel(entry.label),
|
|
102
|
+
tokenHash,
|
|
103
|
+
createdAt: isoOrNull(entry.createdAt) ?? new Date().toISOString(),
|
|
104
|
+
expiresAt: isoOrNull(entry.expiresAt),
|
|
105
|
+
revokedAt: isoOrNull(entry.revokedAt),
|
|
106
|
+
clientKind: typeof entry.clientKind === 'string' && entry.clientKind !== '' ? entry.clientKind : null,
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
return { version: STORE_VERSION, devices }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Read the store synchronously (the Host auth path is synchronous).
|
|
114
|
+
* @param {string} path
|
|
115
|
+
* @returns {{ store: object, exists: boolean, mtimeMs: number, size: number }}
|
|
116
|
+
*/
|
|
117
|
+
export function readStoreFile(path) {
|
|
118
|
+
let stat
|
|
119
|
+
try {
|
|
120
|
+
stat = statSync(path)
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (error?.code === 'ENOENT') return { store: emptyStore(), exists: false, mtimeMs: -1, size: -1 }
|
|
123
|
+
throw error
|
|
124
|
+
}
|
|
125
|
+
const text = readFileSync(path, 'utf8')
|
|
126
|
+
let raw
|
|
127
|
+
try {
|
|
128
|
+
raw = JSON.parse(text)
|
|
129
|
+
} catch (error) {
|
|
130
|
+
const wrapped = new Error(`device-auth: ${path} is not valid JSON`)
|
|
131
|
+
wrapped.cause = error
|
|
132
|
+
throw wrapped
|
|
133
|
+
}
|
|
134
|
+
return { store: normalizeStore(raw), exists: true, mtimeMs: stat.mtimeMs, size: stat.size }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Atomically replace the store: 0700 directory, 0600 file, temp file + rename. */
|
|
138
|
+
export function writeStoreFile(path, store) {
|
|
139
|
+
const directory = dirname(path)
|
|
140
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 })
|
|
141
|
+
try { chmodSync(directory, 0o700) } catch { /* best effort on filesystems without modes */ }
|
|
142
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`
|
|
143
|
+
writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 })
|
|
144
|
+
try { chmodSync(temporary, 0o600) } catch { /* best effort */ }
|
|
145
|
+
renameSync(temporary, path)
|
|
146
|
+
try { chmodSync(path, 0o600) } catch { /* best effort */ }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const sleep = (ms) => new Promise((done) => { setTimeout(done, ms) })
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Serialize a cross-process read-modify-write of the store.
|
|
153
|
+
* @param {string} path - store path; the lock is `<path>.lock`.
|
|
154
|
+
* @param {() => Promise<T>} mutate - runs while the lock is held.
|
|
155
|
+
* @returns {Promise<T>}
|
|
156
|
+
*/
|
|
157
|
+
export async function withStoreLock(path, mutate) {
|
|
158
|
+
const lock = `${path}.lock`
|
|
159
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
160
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS
|
|
161
|
+
for (;;) {
|
|
162
|
+
try {
|
|
163
|
+
mkdirSync(lock)
|
|
164
|
+
break
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error?.code !== 'EEXIST') throw error
|
|
167
|
+
let stale = false
|
|
168
|
+
try {
|
|
169
|
+
stale = Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS
|
|
170
|
+
} catch {
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
if (stale) {
|
|
174
|
+
rmSync(lock, { recursive: true, force: true })
|
|
175
|
+
continue
|
|
176
|
+
}
|
|
177
|
+
if (Date.now() > deadline) throw new Error(`device-auth: timed out waiting for ${lock}; remove it if no other dsh-auth is running`)
|
|
178
|
+
await sleep(LOCK_RETRY_MS)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
return await mutate()
|
|
183
|
+
} finally {
|
|
184
|
+
rmSync(lock, { recursive: true, force: true })
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** True when the record is neither revoked nor expired at `now`. */
|
|
189
|
+
export function isActiveDevice(device, now = Date.now()) {
|
|
190
|
+
if (device.revokedAt !== null && device.revokedAt !== undefined) return false
|
|
191
|
+
if (typeof device.expiresAt === 'string' && device.expiresAt !== '') {
|
|
192
|
+
const expires = Date.parse(device.expiresAt)
|
|
193
|
+
if (Number.isFinite(expires) && expires <= now) return false
|
|
194
|
+
}
|
|
195
|
+
return true
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Find the active device whose stored hash matches `token`, comparing in
|
|
200
|
+
* constant time. Returns undefined for any token that is not a device token.
|
|
201
|
+
*/
|
|
202
|
+
export function findActiveDevice(store, token, now = Date.now()) {
|
|
203
|
+
if (typeof token !== 'string' || !token.startsWith(TOKEN_PREFIX)) return undefined
|
|
204
|
+
const candidate = Buffer.from(hashToken(token), 'hex')
|
|
205
|
+
for (const device of store.devices) {
|
|
206
|
+
if (!isActiveDevice(device, now)) continue
|
|
207
|
+
const stored = Buffer.from(device.tokenHash, 'hex')
|
|
208
|
+
if (stored.length !== candidate.length) continue
|
|
209
|
+
if (timingSafeEqual(stored, candidate)) return device
|
|
210
|
+
}
|
|
211
|
+
return undefined
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Resolve a device by exact id or by case-insensitive label. */
|
|
215
|
+
export function findDevice(store, key) {
|
|
216
|
+
const text = typeof key === 'string' ? key.trim() : ''
|
|
217
|
+
if (text === '') return undefined
|
|
218
|
+
const exact = store.devices.find((device) => device.id === text)
|
|
219
|
+
if (exact !== undefined) return exact
|
|
220
|
+
const wanted = text.toLowerCase()
|
|
221
|
+
return store.devices.find((device) => device.label.toLowerCase() === wanted)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Mint a token for `label`. Minting an already known label rotates that device
|
|
226
|
+
* in place: its id and creation time survive, old tokens stop matching, and
|
|
227
|
+
* the display label is not reset by the re-pair.
|
|
228
|
+
* @returns {{ device: object, token: string, replaced: boolean }}
|
|
229
|
+
*/
|
|
230
|
+
export function mintDevice(store, label, options = {}) {
|
|
231
|
+
const normalized = normalizeLabel(label)
|
|
232
|
+
const key = labelKey(normalized)
|
|
233
|
+
const clientKind = typeof options.clientKind === 'string' && options.clientKind !== '' ? options.clientKind : null
|
|
234
|
+
const ttlDays = Number.isFinite(options.ttlDays) && options.ttlDays > 0 ? options.ttlDays : null
|
|
235
|
+
const now = new Date()
|
|
236
|
+
const expiresAt = ttlDays === null ? null : new Date(now.getTime() + ttlDays * 86_400_000).toISOString()
|
|
237
|
+
const token = generateToken()
|
|
238
|
+
const existing = store.devices.find((device) => labelKey(device.label) === key)
|
|
239
|
+
if (existing !== undefined) {
|
|
240
|
+
existing.tokenHash = hashToken(token)
|
|
241
|
+
existing.revokedAt = null
|
|
242
|
+
existing.expiresAt = expiresAt
|
|
243
|
+
existing.clientKind = clientKind ?? existing.clientKind
|
|
244
|
+
return { device: existing, token, replaced: true }
|
|
245
|
+
}
|
|
246
|
+
if (store.devices.length >= (Number.isFinite(options.maxDevices) && options.maxDevices > 0 ? options.maxDevices : 64)) {
|
|
247
|
+
throw new Error('device-auth: device limit reached; revoke an unused device first')
|
|
248
|
+
}
|
|
249
|
+
const device = {
|
|
250
|
+
id: generateDeviceId(),
|
|
251
|
+
label: normalized,
|
|
252
|
+
tokenHash: hashToken(token),
|
|
253
|
+
createdAt: now.toISOString(),
|
|
254
|
+
expiresAt,
|
|
255
|
+
revokedAt: null,
|
|
256
|
+
clientKind,
|
|
257
|
+
}
|
|
258
|
+
store.devices.push(device)
|
|
259
|
+
return { device, token, replaced: false }
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Revoke one device; returns undefined when no device matches. */
|
|
263
|
+
export function revokeDevice(store, key) {
|
|
264
|
+
const device = findDevice(store, key)
|
|
265
|
+
if (device === undefined) return undefined
|
|
266
|
+
if (device.revokedAt === null) device.revokedAt = new Date().toISOString()
|
|
267
|
+
return device
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Revoke every active device; returns how many changed. */
|
|
271
|
+
export function revokeAllDevices(store) {
|
|
272
|
+
const now = new Date().toISOString()
|
|
273
|
+
let changed = 0
|
|
274
|
+
for (const device of store.devices) {
|
|
275
|
+
if (device.revokedAt !== null) continue
|
|
276
|
+
device.revokedAt = now
|
|
277
|
+
changed += 1
|
|
278
|
+
}
|
|
279
|
+
return changed
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Drop revoked records, keeping the file small; returns how many were removed. */
|
|
283
|
+
export function purgeRevokedDevices(store) {
|
|
284
|
+
const before = store.devices.length
|
|
285
|
+
store.devices = store.devices.filter((device) => device.revokedAt === null)
|
|
286
|
+
return before - store.devices.length
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Public (hash-free) view of one device, as printed by the CLI. */
|
|
290
|
+
export function publicDevice(device, now = Date.now()) {
|
|
291
|
+
return {
|
|
292
|
+
id: device.id,
|
|
293
|
+
label: device.label,
|
|
294
|
+
clientKind: device.clientKind ?? null,
|
|
295
|
+
createdAt: device.createdAt,
|
|
296
|
+
expiresAt: device.expiresAt ?? null,
|
|
297
|
+
revokedAt: device.revokedAt ?? null,
|
|
298
|
+
status: device.revokedAt !== null ? 'revoked' : isActiveDevice(device, now) ? 'active' : 'expired',
|
|
299
|
+
}
|
|
300
|
+
}
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,72 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-device-auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Stable, revocable per-device login tokens for the DeepSeek Harness Web UI — paired clients survive restarts without copying the rotating launch token",
|
|
5
|
+
"icon": "icon.svg",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "nypyp",
|
|
9
|
+
"homepage": "https://github.com/nypyp/dsh-device-auth#readme",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/nypyp/dsh-device-auth.git"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/nypyp/dsh-device-auth/issues"
|
|
16
|
+
},
|
|
17
|
+
"main": "lib/index.js",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./lib/index.js",
|
|
20
|
+
"./locale/*.json": "./locale/*.json",
|
|
21
|
+
"./icon": "./icon.svg",
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"bin": {
|
|
25
|
+
"dsh-auth": "./bin/dsh-auth.mjs"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"lib",
|
|
29
|
+
"bin",
|
|
30
|
+
"cordis.patch.yml",
|
|
31
|
+
"locale/*.json",
|
|
32
|
+
"icon.svg",
|
|
33
|
+
"README.md",
|
|
34
|
+
"README.en.md",
|
|
35
|
+
"CHANGELOG.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"keywords": [
|
|
39
|
+
"deepseek-harness",
|
|
40
|
+
"dsh",
|
|
41
|
+
"dsh-plugin",
|
|
42
|
+
"cordis",
|
|
43
|
+
"authentication",
|
|
44
|
+
"device-credentials",
|
|
45
|
+
"remote-access",
|
|
46
|
+
"security"
|
|
47
|
+
],
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=24.9.0",
|
|
50
|
+
"dsh": ">=0.2.2-rc.1 <0.3.0-0"
|
|
51
|
+
},
|
|
52
|
+
"dsh": {
|
|
53
|
+
"bundle": {
|
|
54
|
+
"patch": "./cordis.patch.yml"
|
|
55
|
+
},
|
|
56
|
+
"compatibility": {
|
|
57
|
+
"dshReleases": {
|
|
58
|
+
"0.2.2-rc.1": "compatible"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"publishConfig": {
|
|
63
|
+
"access": "public"
|
|
64
|
+
},
|
|
65
|
+
"scripts": {
|
|
66
|
+
"test": "node --test \"test/*.test.mjs\"",
|
|
67
|
+
"test:unit": "node --test \"test/unit.test.mjs\"",
|
|
68
|
+
"test:acceptance": "bash test/acceptance.sh",
|
|
69
|
+
"check": "node --check lib/index.js && node --check lib/store.mjs && node --check lib/sessions.mjs && node --check bin/dsh-auth.mjs && bash -n test/acceptance.sh",
|
|
70
|
+
"pack:check": "npm pack --dry-run"
|
|
71
|
+
}
|
|
72
|
+
}
|