@serviceme/devtools-core 2.0.0 → 2.0.2

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