@serviceme/devtools-core 2.0.2 → 2.0.4

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.
Files changed (56) hide show
  1. package/dist/{device-CDDcwDY6.mjs → device-BVcUUQ9t.mjs} +54 -19
  2. package/dist/device-BVcUUQ9t.mjs.map +1 -0
  3. package/dist/device-DCo0rgUt.mjs +793 -0
  4. package/dist/device-DCo0rgUt.mjs.map +1 -0
  5. package/dist/{device-DuAYH8bk.js → device-ihxrFR-w.js} +52 -17
  6. package/dist/device-ihxrFR-w.js.map +1 -0
  7. package/dist/device-uFAQxlNt.js +874 -0
  8. package/dist/device-uFAQxlNt.js.map +1 -0
  9. package/dist/device-yWpY_Zds.js +874 -0
  10. package/dist/device-yWpY_Zds.js.map +1 -0
  11. package/dist/device.d.mts +1 -1
  12. package/dist/device.d.ts +1 -1
  13. package/dist/device.js +1 -1
  14. package/dist/device.mjs +1 -1
  15. package/dist/{index-BI11AfMH.d.ts → index-DGXYp8J5.d.mts} +30 -15
  16. package/dist/{index-BI11AfMH.d.mts → index-DGXYp8J5.d.ts} +30 -15
  17. package/dist/index.d.mts +13 -82
  18. package/dist/index.d.ts +13 -82
  19. package/dist/index.js +72 -138
  20. package/dist/index.js.map +1 -1
  21. package/dist/index.mjs +74 -135
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/skill-linker.js +1 -1
  24. package/dist/skill-linker.mjs +1 -1
  25. package/dist/{submit-Cg7wSa3x.mjs → submit-6zQPPrOJ.mjs} +2 -2
  26. package/dist/{submit-Cg7wSa3x.mjs.map → submit-6zQPPrOJ.mjs.map} +1 -1
  27. package/dist/submit-BTdbGEAd.mjs +84 -0
  28. package/dist/submit-BTdbGEAd.mjs.map +1 -0
  29. package/dist/submit-CW9schoc.js +98 -0
  30. package/dist/submit-CW9schoc.js.map +1 -0
  31. package/dist/submit-Dy0KTHzm.js +98 -0
  32. package/dist/submit-Dy0KTHzm.js.map +1 -0
  33. package/dist/submit.js +1 -1
  34. package/dist/submit.mjs +1 -1
  35. package/dist/toolbox-BV7vLGXZ.js +614 -0
  36. package/dist/toolbox-BV7vLGXZ.js.map +1 -0
  37. package/dist/{toolbox-CbfxpNg-.mjs → toolbox-BxgnUyDU.mjs} +2 -2
  38. package/dist/{toolbox-CbfxpNg-.mjs.map → toolbox-BxgnUyDU.mjs.map} +1 -1
  39. package/dist/toolbox-GSWMRdts.js +614 -0
  40. package/dist/toolbox-GSWMRdts.js.map +1 -0
  41. package/dist/toolbox-UG4dA2TI.mjs +540 -0
  42. package/dist/toolbox-UG4dA2TI.mjs.map +1 -0
  43. package/dist/toolbox.js +1 -1
  44. package/dist/toolbox.mjs +1 -1
  45. package/dist/userHome-B97jBm5O.mjs +196 -0
  46. package/dist/userHome-B97jBm5O.mjs.map +1 -0
  47. package/dist/userHome-Baz205B7.js +498 -0
  48. package/dist/userHome-Baz205B7.js.map +1 -0
  49. package/dist/userHome-CLlsXCvW.js +518 -0
  50. package/dist/userHome-CLlsXCvW.js.map +1 -0
  51. package/dist/{userHome-CcnAQPG1.mjs → userHome-DOMLiHy7.mjs} +2 -4
  52. package/dist/userHome-DOMLiHy7.mjs.map +1 -0
  53. package/package.json +2 -2
  54. package/dist/device-CDDcwDY6.mjs.map +0 -1
  55. package/dist/device-DuAYH8bk.js.map +0 -1
  56. package/dist/userHome-CcnAQPG1.mjs.map +0 -1
@@ -0,0 +1,793 @@
1
+ import { G as getServicemeHome, O as getDeviceJsonPath } from "./userHome-B97jBm5O.mjs";
2
+ import * as fsp from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ import * as os from "node:os";
5
+ import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
6
+ import { setTimeout } from "node:timers/promises";
7
+ //#region src/device/deviceAuth.ts
8
+ /**
9
+ * deviceAuth — Device request signing helpers for device auth headers.
10
+ *
11
+ * **Boundary exception copy.** The single source of truth for the
12
+ * `x-ms-device-*` header names + the signature algorithms now lives in
13
+ * `@serviceme/devtools-shared` (`device-auth.ts`), consumed by the
14
+ * extension signer and the server verifier. ADL-003 forbids
15
+ * core → shared (and shared → core), so this module keeps a
16
+ * byte-for-byte copy as the documented exception. Keep it in lock-step
17
+ * with `packages/serviceme-shared/src/device-auth.ts`.
18
+ *
19
+ * See `docs/architecture/phase-5-device-header-spec.md` §5 for the wire
20
+ * format. Legacy (v1) basis is `METHOD\nPATH\nTIMESTAMP\nBODY\nSECRET`
21
+ * hashed with a secret-suffix SHA-256; v2 basis is
22
+ * `METHOD\nPATH?QUERY\nTIMESTAMP\nNONCE\nBODY\nSECRET` MACed with real
23
+ * HMAC-SHA-256 keyed by the device secret and signed over the full
24
+ * path-with-query. Both output lowercase hex.
25
+ */
26
+ /** Canonical header names — MUST match `@serviceme/devtools-shared`'s `DeviceAuthHeaders`. */
27
+ const DeviceAuthHeaders = {
28
+ deviceId: "x-ms-device-id",
29
+ deviceSecret: "x-ms-device-secret",
30
+ signature: "x-ms-device-signature",
31
+ timestamp: "x-ms-device-timestamp",
32
+ secretVersion: "x-ms-device-secret-version",
33
+ /** v2 only — algorithm self-declaration so the server can verify
34
+ * both schemes during the legacy-client rollout window. */
35
+ sigAlg: "x-ms-device-sig-alg",
36
+ /** v2 only — one-time value folded into the signature basis and
37
+ * checked against a server-side replay cache. */
38
+ nonce: "x-ms-device-nonce"
39
+ };
40
+ /** v2 signature algorithm identifier carried in `x-ms-device-sig-alg`. */
41
+ const DEVICE_SIG_ALG_V2 = "hmac-sha256-v2";
42
+ /**
43
+ * Legacy (v1) secret-suffix SHA-256 over the canonical basis. Retained
44
+ * for backward compatibility with fielded verifiers/clients that
45
+ * predate v2; new code should use `createDeviceRequestSignatureV2`.
46
+ */
47
+ function createDeviceRequestSignature(params) {
48
+ const basis = [
49
+ params.method.toUpperCase(),
50
+ params.path,
51
+ String(params.timestamp),
52
+ params.body,
53
+ params.secret
54
+ ].join("\n");
55
+ return createHash("sha256").update(basis).digest("hex");
56
+ }
57
+ /**
58
+ * Compute the v2 HMAC-SHA-256 hex digest over the canonical basis
59
+ * (path-with-query + nonce).
60
+ *
61
+ * Server contract (`apps/server/src/lib/auth/device-signature-guard.ts`)
62
+ * is line-for-line identical: same LF-joined basis, same lowercase hex
63
+ * output. Any divergence breaks `device-signature-guard.test.ts`.
64
+ */
65
+ function createDeviceRequestSignatureV2(params) {
66
+ const basis = [
67
+ params.method.toUpperCase(),
68
+ params.path,
69
+ String(params.timestamp),
70
+ params.nonce,
71
+ params.body,
72
+ params.secret
73
+ ].join("\n");
74
+ return createHmac("sha256", params.secret).update(basis).digest("hex");
75
+ }
76
+ /**
77
+ * Build the v2 header map. The `path` parameter MUST include the exact
78
+ * query string sent on the wire, and the `body` parameter MUST be the
79
+ * exact byte sequence sent on the wire (no whitespace
80
+ * re-canonicalization between client serialization and signature basis
81
+ * construction).
82
+ */
83
+ function buildSignedHeaders(params) {
84
+ const timestamp = params.timestamp ?? Date.now();
85
+ const nonce = params.nonce ?? randomUUID();
86
+ const signature = createDeviceRequestSignatureV2({
87
+ method: params.method,
88
+ path: params.path,
89
+ timestamp,
90
+ nonce,
91
+ body: params.body,
92
+ secret: params.deviceSecret
93
+ });
94
+ return {
95
+ [DeviceAuthHeaders.deviceId]: params.publicId,
96
+ [DeviceAuthHeaders.deviceSecret]: params.deviceSecret,
97
+ [DeviceAuthHeaders.signature]: signature,
98
+ [DeviceAuthHeaders.timestamp]: String(timestamp),
99
+ [DeviceAuthHeaders.secretVersion]: String(params.secretVersion),
100
+ [DeviceAuthHeaders.sigAlg]: DEVICE_SIG_ALG_V2,
101
+ [DeviceAuthHeaders.nonce]: nonce
102
+ };
103
+ }
104
+ //#endregion
105
+ //#region src/device/InstallationId.ts
106
+ /**
107
+ * InstallationId — Derive a stable per-machine identifier from
108
+ * `os.hostname()` + `os.userInfo()`.
109
+ *
110
+ * Per `docs/architecture/phase-5-auth-device-toolbox.md § P5-2 (并入本文时对应 § P5-2 拆分)` B2,
111
+ * `installationId` MUST survive Extension re-installs but vary across
112
+ * machines. We compute a UUID v5-style hash over hostname + username +
113
+ * platform so the result is:
114
+ * - deterministic (same machine → same id)
115
+ * - collision-resistant (SHA-256, 128-bit truncated)
116
+ * - browser-safe (no PII survives — username never enters output)
117
+ *
118
+ * Note: this intentionally differs from `vscode.env.machineId`, which
119
+ * is per-Extension-install and uses a different algorithm. The two
120
+ * coexist: `installationId` is what gets sent to the server, while
121
+ * `machineId` (raw `os.hostname()`) is for diagnostics.
122
+ *
123
+ * Refs:
124
+ * - 4.功能规划.md §2.2 — `InstallationId.ts os.hostname() + os.userInfo() 哈希生成`
125
+ * - 3.功能拆分.md B2 — installationId semantics
126
+ */
127
+ /** Hex-encoded SHA-256 input. Format: `<hostname>|<username>|<platform>|<nodeVersion>`. */
128
+ function fingerprintMaterial() {
129
+ let username = "unknown";
130
+ try {
131
+ username = os.userInfo().username;
132
+ } catch {
133
+ username = process.env.USER ?? process.env.USERNAME ?? "unknown";
134
+ }
135
+ return [
136
+ os.hostname(),
137
+ username,
138
+ os.platform(),
139
+ os.arch(),
140
+ process.versions.node ?? "unknown"
141
+ ].join("|");
142
+ }
143
+ /**
144
+ * Returns a deterministic installation id for the current machine.
145
+ * Use this when you need an id that survives Extension reinstalls
146
+ * but stays stable across restarts on the same machine.
147
+ */
148
+ function deriveInstallationId() {
149
+ const material = fingerprintMaterial();
150
+ return formatAsV4(createHash("sha256").update(material).digest("hex").slice(0, 32));
151
+ }
152
+ /**
153
+ * Returns a random installation id (UUID v4). Use this for fresh
154
+ * installs when no fingerprint input is available (e.g. containerized
155
+ * CI runners where `os.hostname()` is meaningless).
156
+ */
157
+ function randomInstallationId() {
158
+ return randomUUID();
159
+ }
160
+ /** SHA-256 fingerprint material exposed for tests + diagnostics. */
161
+ function fingerprintSource() {
162
+ return fingerprintMaterial();
163
+ }
164
+ function formatAsV4(hex32) {
165
+ const chars = hex32.split("");
166
+ const versionIdx = 12;
167
+ const variantIdx = 16;
168
+ chars[versionIdx] = (parseInt(chars[versionIdx] ?? "8", 16) & 0 | 4).toString(16);
169
+ chars[variantIdx] = (parseInt(chars[variantIdx] ?? "8", 16) & 3 | 8).toString(16);
170
+ const formatted = chars.join("");
171
+ return `${formatted.slice(0, 8)}-${formatted.slice(8, 12)}-${formatted.slice(12, 16)}-${formatted.slice(16, 20)}-${formatted.slice(20, 32)}`;
172
+ }
173
+ //#endregion
174
+ //#region src/device/Enroller.ts
175
+ /**
176
+ * Enroller — State machine for `device.enroll` and `device.rotate-secret`.
177
+ *
178
+ * States per `2.需求澄清.md` §1.2:
179
+ * anonymous → pending → claimed → expired
180
+ *
181
+ * - `anonymous` (initial): no device has ever enrolled. Server returns
182
+ * a fresh `publicId` + secret.
183
+ * - `pending`: enrollment HTTP call has been issued but the server
184
+ * hasn't confirmed yet. In-flight state — never persisted.
185
+ * - `claimed`: user has linked this device to their account (via
186
+ * `/api/v1/devices/claim`). Sticky binding locks future re-enrolls
187
+ * to the same `userId` (server-side matrix).
188
+ * - `expired`: server returned a device-expiry error. Forces a fresh
189
+ * enroll on next call.
190
+ *
191
+ * `--force` semantics: any non-anonymous state can be force-reset to
192
+ * `anonymous` by wiping the local identity file. The next enroll will
193
+ * be treated as a brand-new install by the server (no sticky binding).
194
+ *
195
+ * The Enroller is the **state machine**; the actual HTTP I/O is the
196
+ * caller's responsibility (the `DeviceSyncClient` in Phase 5.4 wires
197
+ * the server). This split keeps the Enroller unit-testable without
198
+ * a live server.
199
+ *
200
+ * Refs:
201
+ * - 4.功能规划.md §2.2 — `Enroller.ts anonymous → pending → claimed → expired`
202
+ * - `2.需求澄清.md` §1.2 — binding-state machine
203
+ */
204
+ /** 32 bytes of HMAC secret material — matches the server's `device-registration.ts:73-80` generator. */
205
+ const SECRET_BYTES = 32;
206
+ /** Server returns `publicId` as 32-char hex (16 bytes). Match the wire length. */
207
+ const PUBLIC_ID_BYTES = 16;
208
+ const defaultRandomBytes = (size) => {
209
+ return randomBytes(size);
210
+ };
211
+ /** Sentinel error — re-enroll on a claimed device without auth. */
212
+ var DeviceReenrollRequiresAuthError = class extends Error {
213
+ constructor(message = "Re-enroll on a claimed device requires current device credentials or the bound user") {
214
+ super(message);
215
+ this.name = "DeviceReenrollRequiresAuthError";
216
+ }
217
+ };
218
+ /** Sentinel error — server returned a 410 / version-mismatch after rotation. */
219
+ var DeviceSecretVersionMismatchError = class extends Error {
220
+ constructor(message = "Device secret version mismatch — server has rotated past the local copy") {
221
+ super(message);
222
+ this.name = "DeviceSecretVersionMismatchError";
223
+ }
224
+ };
225
+ var Enroller = class {
226
+ constructor(opts) {
227
+ this.inflight = null;
228
+ this.identity = opts.identityStore;
229
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
230
+ this.random = opts.randomBytes ?? defaultRandomBytes;
231
+ this.enrollRequest = opts.enrollRequest;
232
+ }
233
+ /**
234
+ * Read the current binding state without touching the disk.
235
+ * Returns `anonymous` when no identity is stored.
236
+ */
237
+ async currentState() {
238
+ return (await this.identity.read())?.bindingState ?? "anonymous";
239
+ }
240
+ /**
241
+ * Drive the enrollment flow.
242
+ *
243
+ * @param force when true, drop the local identity and start fresh
244
+ * (server treats this as a brand-new install).
245
+ * @param requireAuth when true, refuse to silently re-enroll an
246
+ * existing claimed device — throw
247
+ * `DeviceReenrollRequiresAuthError` instead.
248
+ */
249
+ /**
250
+ * Resolve when any in-flight enrollment completes. Returns immediately
251
+ * when no enrollment is in progress. Allows callers (e.g. the extension's
252
+ * `buildDeviceAuthHeaders`) to wait for a concurrent `syncDeviceInfo()`
253
+ * enrollment before attempting to read the identity from the store.
254
+ */
255
+ async waitForEnrollment() {
256
+ if (this.inflight) await this.inflight;
257
+ }
258
+ async enroll(opts = {}) {
259
+ if (this.inflight) return this.inflight;
260
+ const promise = this.runEnroll(opts);
261
+ this.inflight = promise;
262
+ try {
263
+ return await promise;
264
+ } finally {
265
+ if (this.inflight === promise) this.inflight = null;
266
+ }
267
+ }
268
+ /** Test seam — surface the underlying identity store. */
269
+ getIdentityStore() {
270
+ return this.identity;
271
+ }
272
+ /** True when an enrollment is currently in-flight. Used by callers (e.g. the extension's `buildDeviceAuthHeaders`) to skip triggering a competing enrollment. */
273
+ isEnrolling() {
274
+ return this.inflight !== null;
275
+ }
276
+ async runEnroll(opts) {
277
+ const { written } = await this.identity.mutate(async (current) => {
278
+ const existing = opts.force ? null : current;
279
+ if (!opts.force && current) {
280
+ if (current.bindingState === "expired") {} else if (opts.requireAuth && (current.bindingState === "claimed" || current.bindingState === "pending")) throw new DeviceReenrollRequiresAuthError();
281
+ }
282
+ const installationId = current?.installationId ?? deriveInstallationId();
283
+ const machineId = current?.machineId ?? "unknown";
284
+ const platform = current?.platform ?? "unknown";
285
+ let response;
286
+ if (this.enrollRequest) response = await this.enrollRequest({
287
+ installationId,
288
+ machineId,
289
+ platform,
290
+ existing,
291
+ force: Boolean(opts.force),
292
+ requireAuth: Boolean(opts.requireAuth)
293
+ });
294
+ else response = synthesizeEnrollResponse(this.random, existing);
295
+ return { next: {
296
+ version: current?.version ?? 1,
297
+ installationId,
298
+ machineId,
299
+ platform,
300
+ hostname: current?.hostname,
301
+ publicId: response.publicId,
302
+ secretVersion: response.secretVersion,
303
+ bindingState: response.bindingState,
304
+ deviceSecret: response.deviceSecret,
305
+ previousDeviceSecret: existing?.deviceSecret,
306
+ previousSecretExpiresAt: opts.force || response.secretVersion === (existing?.secretVersion ?? 0) + 1 ? void 0 : existing?.previousSecretExpiresAt,
307
+ lastEnrollAt: this.now().toISOString(),
308
+ lastSyncAt: existing?.lastSyncAt,
309
+ lastSyncError: void 0
310
+ } };
311
+ });
312
+ return {
313
+ publicId: written.publicId,
314
+ bindingState: written.bindingState,
315
+ expiresAt: deriveExpiresAt(written, this.now)
316
+ };
317
+ }
318
+ /**
319
+ * Rotate the HMAC secret. Keeps the previous secret for the grace
320
+ * window (default 7 days per `2.需求澄清.md` §1.2) — the
321
+ * `previousSecretExpiresAt` is stamped on the persisted identity.
322
+ */
323
+ async rotateSecret(opts = {}) {
324
+ const gracePeriodDays = opts.gracePeriodDays ?? 7;
325
+ const now = this.now();
326
+ const newSecret = this.random(SECRET_BYTES).toString("hex");
327
+ const { written } = await this.identity.mutate(async (current) => {
328
+ if (!current) throw new Error("Cannot rotate-secret without a prior enrollment");
329
+ const graceExpiresAt = new Date(now.getTime() + gracePeriodDays * 24 * 60 * 60 * 1e3);
330
+ return { next: {
331
+ ...current,
332
+ deviceSecret: newSecret,
333
+ previousDeviceSecret: current.deviceSecret,
334
+ previousSecretExpiresAt: graceExpiresAt.toISOString(),
335
+ secretVersion: current.secretVersion + 1,
336
+ lastEnrollAt: now.toISOString()
337
+ } };
338
+ });
339
+ return {
340
+ publicId: written.publicId,
341
+ secretVersion: written.secretVersion,
342
+ gracePeriodDays
343
+ };
344
+ }
345
+ /**
346
+ * Mark the device as `expired`. Used when the server returns a
347
+ * device-expiry response; the next `enroll()` call forces a fresh
348
+ * round-trip.
349
+ */
350
+ async markExpired() {
351
+ await this.identity.mutate(async (current) => {
352
+ if (!current) return {
353
+ next: current ?? await emptyIdentity(this.random),
354
+ result: void 0
355
+ };
356
+ return { next: {
357
+ ...current,
358
+ bindingState: "expired"
359
+ } };
360
+ });
361
+ }
362
+ /**
363
+ * Mark the device as `claimed`. Called by the bridge after a
364
+ * successful `device.claim` server response.
365
+ */
366
+ async markClaimed() {
367
+ await this.identity.mutate(async (current) => {
368
+ if (!current) throw new Error("Cannot mark-claimed without a prior enrollment");
369
+ return { next: {
370
+ ...current,
371
+ bindingState: "claimed",
372
+ lastSyncAt: this.now().toISOString(),
373
+ lastSyncError: void 0
374
+ } };
375
+ });
376
+ }
377
+ };
378
+ function deriveExpiresAt(_identity, _now) {}
379
+ function synthesizeEnrollResponse(random, existing) {
380
+ const publicId = existing?.publicId ?? random(PUBLIC_ID_BYTES).toString("hex");
381
+ const secretVersion = (existing?.secretVersion ?? 0) + 1;
382
+ return {
383
+ publicId,
384
+ deviceSecret: random(SECRET_BYTES).toString("hex"),
385
+ secretVersion,
386
+ bindingState: existing?.bindingState === "claimed" ? "claimed" : "anonymous"
387
+ };
388
+ }
389
+ async function emptyIdentity(random) {
390
+ return {
391
+ version: 1,
392
+ installationId: deriveInstallationId(),
393
+ machineId: "unknown",
394
+ platform: "unknown",
395
+ publicId: random(PUBLIC_ID_BYTES).toString("hex"),
396
+ secretVersion: 1,
397
+ bindingState: "anonymous",
398
+ deviceSecret: random(SECRET_BYTES).toString("hex"),
399
+ lastEnrollAt: (/* @__PURE__ */ new Date()).toISOString()
400
+ };
401
+ }
402
+ //#endregion
403
+ //#region src/device/types.ts
404
+ /**
405
+ * Schema version of the on-disk `device.json` file. Bumped when the
406
+ * shape changes incompatibly. IdentityStore checks this on read and
407
+ * either migrates (versions ≤ 1) or refuses (versions > supported).
408
+ */
409
+ const DEVICE_JSON_SCHEMA_VERSION = 1;
410
+ //#endregion
411
+ //#region src/device/IdentityStore.ts
412
+ /**
413
+ * IdentityStore — Atomic JSON persistence for the device identity file.
414
+ *
415
+ * Stores the `PersistedDeviceIdentity` (incl. the HMAC secret cleartext)
416
+ * at `~/.serviceme/device.json` (per `phase-5-device-header-spec.md`
417
+ * §3.1). Writes are atomic via `write-tmp + fsync + rename`, matching
418
+ * the `SkillStore` / `ToolboxStore` precedent. Concurrent writes are
419
+ * serialized with a mkdir-based file lock (POSIX-atomic) — proper
420
+ * cross-process locking is deferred to Phase 6+ per the open spec.
421
+ *
422
+ * The file mode is `0600` (owner read/write only) so the cleartext
423
+ * secret stays safe at rest. On Windows the mode hint is a no-op
424
+ * (Windows uses ACLs) but `writeFile` still succeeds.
425
+ *
426
+ * Migration — IdentityStore auto-detects a v0-shape (pre-Phase-5.2)
427
+ * file written by the Extension's old `globalState` blob:
428
+ * { version: 1, claimed: false, publicKeyFingerprint: null }
429
+ * In that case the file is migrated forward to the v1 schema on the
430
+ * next write (the data fields are empty and a fresh enroll is required).
431
+ * The full Extension `globalState` → JSON migration happens in the
432
+ * Phase 5.5 adapter (`apps/extension/.../DeviceService.ts`) since the
433
+ * adapter holds the live `globalState` access.
434
+ *
435
+ * Refs:
436
+ * - 4.功能规划.md §2.2 — `IdentityStore.ts 持久化到 ~/.config/serviceme/device.json, 原子写`
437
+ * - `docs/architecture/phase-5-device-header-spec.md` §3.1, §2.5
438
+ */
439
+ const FILE_MODE = 384;
440
+ const LOCK_DIR_MODE = 448;
441
+ const DEFAULT_LOCK_TIMEOUT_MS = 5e3;
442
+ const DEFAULT_LOCK_RETRY_MS = 25;
443
+ const LOCK_STALE_GRACE_MS = 200;
444
+ const TMP_SUFFIX = ".tmp";
445
+ /**
446
+ * Default file backend — uses `node:fs/promises` with the canonical
447
+ * tmp-then-rename atomic-write pattern.
448
+ */
449
+ var FsIdentityFileBackend = class {
450
+ async exists(filePath) {
451
+ try {
452
+ await fsp.access(filePath);
453
+ return true;
454
+ } catch {
455
+ return false;
456
+ }
457
+ }
458
+ async read(filePath) {
459
+ try {
460
+ const buf = await fsp.readFile(filePath, "utf8");
461
+ return migratePersistedIdentity(JSON.parse(buf));
462
+ } catch (err) {
463
+ if (isNodeError(err) && err.code === "ENOENT") return null;
464
+ throw err;
465
+ }
466
+ }
467
+ async write(filePath, payload) {
468
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
469
+ const tmpPath = `${filePath}${TMP_SUFFIX}`;
470
+ const bytes = Buffer.from(JSON.stringify(payload, null, " "), "utf8");
471
+ await fsp.rm(tmpPath, { force: true });
472
+ const handle = await fsp.open(tmpPath, "w", FILE_MODE);
473
+ try {
474
+ await handle.writeFile(bytes);
475
+ await handle.sync();
476
+ } finally {
477
+ await handle.close();
478
+ }
479
+ await fsp.rename(tmpPath, filePath);
480
+ await fsp.chmod(filePath, FILE_MODE).catch(() => void 0);
481
+ return {
482
+ bytesWritten: bytes.byteLength,
483
+ tmpPath
484
+ };
485
+ }
486
+ async delete(filePath) {
487
+ await fsp.rm(filePath, { force: true });
488
+ }
489
+ };
490
+ /**
491
+ * Reconcile an unknown on-disk shape into the current `PersistedDeviceIdentity`.
492
+ *
493
+ * - v1 IdentityStore files (current shape) pass through unchanged.
494
+ * - v0 bootstrap files (`{ version: 1, claimed: false, publicKeyFingerprint: null }`)
495
+ * are recognized by their placeholder keys and discarded; the next
496
+ * enroll writes a fresh identity.
497
+ * - Anything else throws — refuse to silently drop user data.
498
+ */
499
+ function migratePersistedIdentity(parsed) {
500
+ if (!isRecord(parsed)) throw new Error("device.json: top-level must be an object");
501
+ const version = parsed.version;
502
+ if (version === 1) {
503
+ if (parsed.publicId === void 0 && parsed.deviceSecret === void 0 && ("claimed" in parsed || "publicKeyFingerprint" in parsed)) return null;
504
+ return parsed;
505
+ }
506
+ if (typeof version === "number" && version < 1) return null;
507
+ throw new Error(`device.json: unsupported schema version ${String(version)}`);
508
+ }
509
+ function isRecord(value) {
510
+ return typeof value === "object" && value !== null;
511
+ }
512
+ function isNodeError(value) {
513
+ return value instanceof Error && typeof value.code === "string";
514
+ }
515
+ const LOCK_PID_FILE = "pid";
516
+ /**
517
+ * Check whether a process is still alive (best-effort, cross-platform).
518
+ * Returns `false` for any PID we cannot verify as alive.
519
+ */
520
+ function isProcessAlive(pid) {
521
+ try {
522
+ process.kill(pid, 0);
523
+ return true;
524
+ } catch {
525
+ return false;
526
+ }
527
+ }
528
+ /**
529
+ * mkdir-based advisory file lock with stale-lock recovery.
530
+ *
531
+ * POSIX mkdir is atomic; on Windows modern filesystems (NTFS) it's also
532
+ * atomic at the API level. Sufficient for single-host, single-user
533
+ * scenarios (which is the SERVICEME threat model).
534
+ *
535
+ * Stale lock recovery: a `pid` file inside the lock directory records the
536
+ * owner's PID. On `EEXIST`, if the recorded PID is no longer alive, the
537
+ * lock directory is forcibly removed and acquisition retried immediately.
538
+ * This prevents permanent lockout when a process crashes without calling
539
+ * `release()`.
540
+ */
541
+ var FileLock = class {
542
+ constructor(filePath, timeoutMs, retryMs) {
543
+ this.acquired = false;
544
+ this.dirPath = `${filePath}.lock`;
545
+ this.pidFilePath = path.join(this.dirPath, LOCK_PID_FILE);
546
+ this.timeoutMs = timeoutMs;
547
+ this.retryMs = retryMs;
548
+ }
549
+ async acquire() {
550
+ const start = Date.now();
551
+ while (true) try {
552
+ await fsp.mkdir(this.dirPath, { mode: LOCK_DIR_MODE });
553
+ await fsp.writeFile(this.pidFilePath, String(process.pid), "utf8").catch(() => void 0);
554
+ this.acquired = true;
555
+ return;
556
+ } catch (err) {
557
+ if (!isNodeError(err) || err.code !== "EEXIST") throw err;
558
+ if (await this.isStaleLock()) {
559
+ await fsp.rm(this.dirPath, {
560
+ recursive: true,
561
+ force: true
562
+ });
563
+ continue;
564
+ }
565
+ if (Date.now() - start >= this.timeoutMs) throw new Error(`IdentityStore lock acquisition timed out for ${this.dirPath}`);
566
+ await setTimeout(this.retryMs);
567
+ }
568
+ }
569
+ async isStaleLock() {
570
+ let pidStr;
571
+ try {
572
+ pidStr = await fsp.readFile(this.pidFilePath, "utf8");
573
+ } catch {
574
+ try {
575
+ const stat = await fsp.stat(this.dirPath);
576
+ return Date.now() - stat.mtimeMs > LOCK_STALE_GRACE_MS;
577
+ } catch {
578
+ return false;
579
+ }
580
+ }
581
+ const pid = Number.parseInt(pidStr.trim(), 10);
582
+ if (!Number.isFinite(pid) || pid <= 0) return true;
583
+ return !isProcessAlive(pid);
584
+ }
585
+ async release() {
586
+ if (!this.acquired) return;
587
+ this.acquired = false;
588
+ await fsp.rm(this.dirPath, {
589
+ recursive: true,
590
+ force: true
591
+ });
592
+ }
593
+ };
594
+ var IdentityStore = class {
595
+ constructor(opts = {}) {
596
+ this.filePath = opts.filePath ?? getDeviceJsonPath();
597
+ this.backend = opts.backend ?? new FsIdentityFileBackend();
598
+ this.hooks = opts.hooks ?? {};
599
+ this.lockTimeoutMs = opts.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;
600
+ this.lockRetryMs = opts.lockRetryMs ?? DEFAULT_LOCK_RETRY_MS;
601
+ }
602
+ /** Absolute path to the underlying JSON file (test seam). */
603
+ getFilePath() {
604
+ return this.filePath;
605
+ }
606
+ /** True when the JSON file already exists on disk. */
607
+ async exists() {
608
+ return this.backend.exists(this.filePath);
609
+ }
610
+ /** Read the persisted identity; returns `null` when no identity is stored. */
611
+ async read() {
612
+ return this.backend.read(this.filePath);
613
+ }
614
+ /**
615
+ * Atomically write the given identity. Concurrent writers are
616
+ * serialized via the file lock; the read-modify-write happens
617
+ * inside the lock so callers can't see a partial state.
618
+ */
619
+ async write(next) {
620
+ await this.hooks.beforeWrite?.(next);
621
+ const lock = new FileLock(this.filePath, this.lockTimeoutMs, this.lockRetryMs);
622
+ await lock.acquire();
623
+ try {
624
+ const stamped = {
625
+ ...next,
626
+ version: 1
627
+ };
628
+ const result = await this.backend.write(this.filePath, stamped);
629
+ await this.hooks.afterWrite?.(stamped);
630
+ return result;
631
+ } finally {
632
+ await lock.release();
633
+ }
634
+ }
635
+ /**
636
+ * Read-modify-write under the same lock. The mutator receives the
637
+ * current identity (or `null` on first call) and returns the
638
+ * replacement. Throwing inside the mutator aborts the write.
639
+ */
640
+ async mutate(mutator) {
641
+ const lock = new FileLock(this.filePath, this.lockTimeoutMs, this.lockRetryMs);
642
+ await lock.acquire();
643
+ try {
644
+ const { next, result } = await mutator(await this.backend.read(this.filePath));
645
+ const stamped = {
646
+ ...next,
647
+ version: 1
648
+ };
649
+ await this.hooks.beforeWrite?.(stamped);
650
+ await this.backend.write(this.filePath, stamped);
651
+ await this.hooks.afterWrite?.(stamped);
652
+ return {
653
+ result,
654
+ written: stamped
655
+ };
656
+ } finally {
657
+ await lock.release();
658
+ }
659
+ }
660
+ /** Wipe the persisted identity (used by `device.enroll --force`). */
661
+ async clear() {
662
+ await this.backend.delete(this.filePath);
663
+ }
664
+ /**
665
+ * Resolve the installation metadata for the current machine.
666
+ * Pure helper — no I/O, just `os.*` calls.
667
+ */
668
+ resolveInstallationMetadata() {
669
+ return {
670
+ installationId: "",
671
+ machineId: os.hostname(),
672
+ platform: os.platform()
673
+ };
674
+ }
675
+ /**
676
+ * Ensure the parent directory exists (`~/.serviceme/`). Idempotent.
677
+ * Useful when the bootstrap phase5 placeholder wasn't run yet.
678
+ */
679
+ async ensureHome() {
680
+ await fsp.mkdir(getServicemeHome(), { recursive: true });
681
+ await fsp.mkdir(path.dirname(this.filePath), { recursive: true });
682
+ }
683
+ };
684
+ //#endregion
685
+ //#region src/device/DeviceCore.ts
686
+ var DeviceCore = class {
687
+ constructor(opts = {}) {
688
+ this.identity = opts.identityStore ?? new IdentityStore();
689
+ this.enroller = new Enroller({
690
+ identityStore: this.identity,
691
+ enrollRequest: opts.enrollRequest,
692
+ now: opts.now
693
+ });
694
+ this.resolveInstallationId = opts.resolveInstallationId ?? deriveInstallationId;
695
+ }
696
+ /** Read-only snapshot of the device status (matches `device.status` wire shape). */
697
+ async status() {
698
+ const stored = await this.identity.read();
699
+ return stored ? {
700
+ bindingState: stored.bindingState,
701
+ identity: projectIdentity(stored),
702
+ metadata: projectMetadata(stored),
703
+ lastSyncAt: stored.lastSyncAt,
704
+ lastSyncError: stored.lastSyncError
705
+ } : { bindingState: "anonymous" };
706
+ }
707
+ /** Enroll (or re-enroll) the device. */
708
+ async enroll(opts = {}) {
709
+ return this.enroller.enroll(opts);
710
+ }
711
+ /** Wait for any in-flight enrollment to finish. Use before `buildSignedHeaders` so that a concurrent `syncDeviceInfo` enrollment has time to write the identity to the store. */
712
+ async waitForEnrollment() {
713
+ await this.enroller.waitForEnrollment();
714
+ }
715
+ /** True when an enrollment is currently in-flight. Used by callers to skip triggering a competing enrollment. */
716
+ isEnrolling() {
717
+ return this.enroller.isEnrolling();
718
+ }
719
+ /** Rotate the HMAC secret while keeping the previous one for the grace window. */
720
+ async rotateSecret(opts = {}) {
721
+ const result = await this.enroller.rotateSecret(opts);
722
+ const stored = await this.identity.read();
723
+ return {
724
+ ...result,
725
+ gracePeriodEndsAt: stored?.previousSecretExpiresAt
726
+ };
727
+ }
728
+ /** Build the v2 signed header map for an outbound request. The path
729
+ * MUST include the query string (v2 signs it). */
730
+ async buildSignedHeaders(input) {
731
+ const stored = await this.identity.read();
732
+ if (!stored) return null;
733
+ return buildSignedHeaders({
734
+ method: input.method,
735
+ path: input.path,
736
+ body: input.body,
737
+ publicId: stored.publicId,
738
+ deviceSecret: stored.deviceSecret,
739
+ secretVersion: stored.secretVersion
740
+ });
741
+ }
742
+ /** Raw stored identity (CLI/extension internal use). Test seam too. */
743
+ async readIdentity() {
744
+ return this.identity.read();
745
+ }
746
+ /** Wipe the local identity (the `--force` path before re-enroll). */
747
+ async clear() {
748
+ await this.identity.clear();
749
+ }
750
+ /** Mark the device as claimed (called by the bridge after a successful claim). */
751
+ async markClaimed() {
752
+ await this.enroller.markClaimed();
753
+ }
754
+ /** Mark the device as expired (server returned an expiry response). */
755
+ async markExpired() {
756
+ await this.enroller.markExpired();
757
+ }
758
+ /** Expose the identity store (CLI uses it for direct file access in tests). */
759
+ getIdentityStore() {
760
+ return this.identity;
761
+ }
762
+ /** Expose the enroller (CLI uses it for state inspection). */
763
+ getEnroller() {
764
+ return this.enroller;
765
+ }
766
+ /** Header name constants — re-exported from `deviceAuth.ts`. */
767
+ getHeaderNames() {
768
+ return DeviceAuthHeaders;
769
+ }
770
+ /** Compute the installation id for the current machine. */
771
+ getInstallationId() {
772
+ return this.resolveInstallationId();
773
+ }
774
+ };
775
+ function projectIdentity(stored) {
776
+ return {
777
+ publicId: stored.publicId,
778
+ secretVersion: stored.secretVersion,
779
+ bindingState: stored.bindingState
780
+ };
781
+ }
782
+ function projectMetadata(stored) {
783
+ return {
784
+ installationId: stored.installationId,
785
+ machineId: stored.machineId,
786
+ platform: stored.platform,
787
+ hostname: stored.hostname
788
+ };
789
+ }
790
+ //#endregion
791
+ export { DeviceReenrollRequiresAuthError as a, deriveInstallationId as c, DeviceAuthHeaders as d, buildSignedHeaders as f, DEVICE_JSON_SCHEMA_VERSION as i, fingerprintSource as l, FsIdentityFileBackend as n, DeviceSecretVersionMismatchError as o, createDeviceRequestSignature as p, IdentityStore as r, Enroller as s, DeviceCore as t, randomInstallationId as u };
792
+
793
+ //# sourceMappingURL=device-DCo0rgUt.mjs.map