@xkwdstore/agent 2.0.2 → 2.0.3

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.
@@ -1,1117 +1,1117 @@
1
- 'use strict';
2
-
3
- /**
4
- * Phase 14 + Phase 10 — strict browser-profile identity (marker schema 4).
5
- *
6
- * An on-disk browser profile (cookies, localStorage, cache, fingerprint) is
7
- * namespaced by an IMMUTABLE identity tuple assigned by the backend:
8
- *
9
- * <profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/<deviceUuid>/
10
- *
11
- * serverUuid immutable UUID of the backend installation (not the URL — a
12
- * URL change must not orphan profiles)
13
- * tenantUuid immutable UUID of the owning user (not the recyclable numeric
14
- * user id — a DB rebuild must not let a reused id inherit
15
- * another tenant's profiles)
16
- * accountUuid immutable UUID of the account
17
- * deviceUuid immutable UUID of the DEVICE the profile is bound to
18
- *
19
- * Phase 10 closes a silent re-binding hole: in schema 3 the PATH was keyed only
20
- * by server/tenant/account UUIDs, deviceUuid was NOT in the integrity hash, and
21
- * `_markerMatches` did not compare it — so a DIFFERENT device taking over the
22
- * same (server/tenant/account) slot silently re-stamped the marker with its own
23
- * deviceUuid and reused the previous device's cookies/fingerprint. Schema 4
24
- * binds the profile to the device in all three places:
25
- * - PATH: deviceUuid is a path component (each device gets its own
26
- * profile dir under the account);
27
- * - MARKER: schema 4; the marker is only 'ok' when schema === 4;
28
- * - INTEGRITY: deviceUuid is part of the sha256 integrity hash, and
29
- * `_markerMatches` requires marker.deviceUuid === tuple.deviceUuid.
30
- * A dir whose marker was stamped by a different device now FAILS the match and
31
- * is QUARANTINED (never re-bound) — the new device starts a fresh profile.
32
- *
33
- * Fail-closed rules (rule 17):
34
- * - ANY of the four UUIDs missing / malformed → THROW. There are NO fallbacks
35
- * (no `default` server, no `u0` tenant, no `legacy-account-*` account). A
36
- * profile is never opened with a recyclable / unknown identity.
37
- * - PATH / SYMLINK CONTAINMENT: the resolved dir must stay under profilesDir.
38
- * A `..` component, an absolute escape, or a symlink that points outside
39
- * the profiles root is rejected.
40
- *
41
- * Reuse guard (never stamp-and-reuse — rule 22 "never trust an unmarked profile"):
42
- * - marker absent → the dir is UNMARKED → QUARANTINE it (move aside),
43
- * start a genuinely fresh dir. NEVER adopt an unmarked
44
- * dir by stamping a marker over it.
45
- * - marker corrupt → QUARANTINE (tampered / half-written)
46
- * - marker tuple mismatch (incl. a DIFFERENT deviceUuid) → QUARANTINE
47
- * - marker tuple matches (same device) → reuse, refresh lastUsed
48
- *
49
- * One-time schema-3 → schema-4 migration (data-preserving, device-bound — rule
50
- * 12/13): a profile written by the schema-3 agent lives at the 3-level path
51
- * `<profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/`. On the first schema-4
52
- * resolve, if the 4-level path is empty but the 3-level path exists with a
53
- * matching schema-3 marker WHOSE deviceUuid EQUALS the requesting device, the
54
- * 3-level dir is MOVED into the device-scoped 4-level path and re-stamped
55
- * schema-4. A schema-3 profile whose deviceUuid DIFFERS is LEFT UNTOUCHED — it
56
- * belongs to another device and is never re-bound; the requesting device gets a
57
- * fresh profile (its rightful owner will migrate it when it connects).
58
- *
59
- * One-time schema-2 → schema-4 migration (data-preserving — rule 12/13):
60
- * Profiles written by the pre-Phase-14 agent live at the legacy namespaced
61
- * path `<profilesDir>/<serverKey(serverUrl)>/u<userId>/<accountUuid>/`. On the
62
- * first schema-4 resolve, if the NEW path is empty but the legacy path exists
63
- * with a matching accountUuid marker, the legacy dir is MOVED to the new
64
- * device-scoped path and stamped with a schema-4 marker. The legacy data is
65
- * preserved (a move, not a copy-and-delete); a mismatched/absent legacy marker
66
- * is left untouched (never adopt an unverifiable dir).
67
- */
68
-
69
- const fs = require('fs');
70
- const path = require('path');
71
- const crypto = require('crypto');
72
- const os = require('os');
73
- const { spawnSync } = require('child_process');
74
-
75
- const IDENTITY_FILE = 'identity.json';
76
- const SCHEMA = 4;
77
- const SCHEMA_V3 = 3;
78
- const AGENT_VERSION = process.env.AGENT_VERSION || null;
79
- const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
80
- const IS_WIN = process.platform === 'win32';
81
- const MIGRATION_JOURNAL = 'migration-journal.json';
82
- // Phase 10/18: the Windows ACL policy restricts profile paths to the owning
83
- // user + trusted OS principals only. Untrusted broad principals are forbidden.
84
- //
85
- // ── Threat model ──
86
- // The profile directory contains the browser profile (cookies, session data).
87
- // The security boundary protects against OTHER USERS on the same machine
88
- // reading or modifying the profile. It does NOT protect against a malicious
89
- // local administrator or SYSTEM — those are trusted OS principals with
90
- // operating-system-level access (take-ownership, SeBackupPrivilege, etc).
91
- // Excluding their ACEs from the DACL does not prevent a local admin from
92
- // recovering access. The real protection is that ordinary users on the machine
93
- // cannot read another user's profile.
94
- //
95
- // ── Trusted OS principals (allowed everywhere, same policy in CI and prod) ──
96
- // BUILTIN\Administrators (S-1-5-32-544) and NT AUTHORITY\SYSTEM (S-1-5-18)
97
- // are trusted because they have OS-level access regardless of the DACL.
98
- // Windows auto-adds them to directories created by elevated processes.
99
- // They are ALLOWED in the ACL — not excluded via env vars.
100
- //
101
- // ── Forbidden untrusted principals (fail-closed everywhere) ──
102
- // Everyone (S-1-1-0), BUILTIN\Users (S-1-5-32-545), Authenticated Users
103
- // (S-1-5-11) are broad untrusted groups. Any explicit or inherited ACE for
104
- // these groups fails the verification in both CI and production.
105
- //
106
- // ── Configuration ──
107
- // PROFILE_WINDOWS_ACL_ENFORCE (default true): enforcement toggle; false is
108
- // dev/test only and FAILS CLOSED in production.
109
- // PROFILE_WINDOWS_ACL_FORBIDDEN_PRINCIPALS: ADDITIONAL forbidden principals
110
- // (unioned with the default floor; can only make stricter).
111
- const DEFAULT_ACL_FORBIDDEN = ['Everyone', 'BUILTIN\\Users', 'Authenticated Users'];
112
- const TRUSTED_OS_SIDS = new Set(['S-1-5-32-544', 'S-1-5-18']); // Administrators, SYSTEM
113
-
114
- // Well-known SID mapping for forbidden principals (used to resolve configured
115
- // additions to SIDs for SID-based verification).
116
- const _PRINCIPAL_TO_SID = {
117
- 'Everyone': 'S-1-1-0',
118
- 'BUILTIN\\Users': 'S-1-5-32-545',
119
- 'Authenticated Users': 'S-1-5-11',
120
- 'BUILTIN\\Administrators': 'S-1-5-32-544',
121
- 'NT AUTHORITY\\SYSTEM': 'S-1-5-18',
122
- 'Guests': 'S-1-5-32-546',
123
- };
124
-
125
- /**
126
- * Phase 10: resolve the effective Windows ACL policy from env. Returns
127
- * { enforce: boolean, forbiddenPrincipals: string[] }. Throws
128
- * PROFILE_ACL_DISABLED_IN_PROD if enforcement is explicitly disabled in
129
- * production (the policy cannot be weakened where it matters).
130
- */
131
- function _windowsAclPolicy() {
132
- let enforce = true;
133
- const envEnforce = process.env.PROFILE_WINDOWS_ACL_ENFORCE;
134
- if (envEnforce != null && envEnforce !== '') {
135
- const v = String(envEnforce).toLowerCase();
136
- if (v === '1' || v === 'true') enforce = true;
137
- else if (v === '0' || v === 'false') {
138
- if (_isProd()) {
139
- throw new ProfileIdentityError(
140
- 'PROFILE_WINDOWS_ACL_ENFORCE=false is not permitted in production (the Windows ACL policy cannot be disabled)',
141
- 'PROFILE_ACL_DISABLED_IN_PROD',
142
- );
143
- }
144
- enforce = false;
145
- }
146
- // any unrecognized value -> default (enforce)
147
- }
148
- // Forbidden principals: the default floor is ALWAYS enforced; env additions
149
- // are unioned in (stricter only).
150
- let forbiddenPrincipals = DEFAULT_ACL_FORBIDDEN;
151
- const envExtra = process.env.PROFILE_WINDOWS_ACL_FORBIDDEN_PRINCIPALS;
152
- if (envExtra && envExtra.trim()) {
153
- const extra = envExtra.split(',').map((s) => s.trim()).filter(Boolean);
154
- forbiddenPrincipals = Array.from(new Set([...DEFAULT_ACL_FORBIDDEN, ...extra]));
155
- }
156
- return { enforce, forbiddenPrincipals };
157
- }
158
-
159
- class ProfileIdentityError extends Error {
160
- constructor(message, code) {
161
- super(message);
162
- this.code = code || 'PROFILE_IDENTITY_INCOMPLETE';
163
- this.name = 'ProfileIdentityError';
164
- }
165
- }
166
-
167
- // ── Durability + permission + journal helpers (Phase 17-19) ───────────────────
168
-
169
- function _isProd() { return process.env.NODE_ENV === 'production'; }
170
-
171
- /**
172
- * fsync a file or directory path. In PRODUCTION a fsync failure is a real
173
- * durability failure (the marker was not flushed to disk) and FAILS CLOSED —
174
- * never claim a durable marker that was not persisted (Phase 17). The one
175
- * exception is DIRECTORY fsync on Windows, which is genuinely unsupported
176
- * (ENOTSUP/EINVAL) and therefore a platform limitation, not a disk error — it
177
- * stays best-effort there regardless of NODE_ENV. In dev/test fsync is
178
- * best-effort so harnesses on filesystems that do not honor fsync still run.
179
- */
180
- function _fsyncPath(p, kind) {
181
- try {
182
- const fd = fs.openSync(p, 'r');
183
- try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
184
- } catch (err) {
185
- if (kind === 'dir' && IS_WIN) return; // dir fsync unsupported on Windows
186
- if (_isProd()) {
187
- throw new ProfileIdentityError(
188
- `marker ${kind} fsync failed in production (durability unverifiable): ${(err && err.code) || (err && err.message) || 'unknown'}`,
189
- 'PROFILE_MARKER_FSYNC_FAILED',
190
- );
191
- }
192
- // dev/test: best-effort
193
- }
194
- }
195
-
196
- /**
197
- * On Windows, restrict a profile path's ACL to the owner + trusted OS
198
- * principals only. Every Allow ACE must belong to the owner SID,
199
- * BUILTIN\Administrators (S-1-5-32-544), or NT AUTHORITY\SYSTEM (S-1-5-18).
200
- * Any other Allow ACE (another user, Everyone, Users, Authenticated Users,
201
- * Guests, unknown SIDs, custom groups) fails closed.
202
- *
203
- * The security boundary protects against OTHER USERS on the same machine.
204
- * It does NOT protect against a malicious local administrator or SYSTEM —
205
- * those are trusted OS principals with OS-level access (take-ownership,
206
- * SeBackupPrivilege, etc) that cannot be blocked via the DACL.
207
- *
208
- * On POSIX, chmod the path to `mode` (best-effort in dev, fail-closed in prod).
209
- */
210
- function _applyPerms(target, mode) {
211
- if (IS_WIN) {
212
- _applyWindowsAcl(target);
213
- return;
214
- }
215
- try {
216
- fs.chmodSync(target, mode);
217
- } catch (err) {
218
- if (_isProd()) {
219
- throw new ProfileIdentityError(
220
- `chmod ${mode.toString(8)} failed in production: ${(err && err.message) || 'unknown'}`,
221
- 'PROFILE_PERMS_FAILED',
222
- );
223
- }
224
- // dev: best-effort
225
- }
226
- }
227
-
228
- function _applyWindowsAcl(target) {
229
- const { enforce } = _windowsAclPolicy();
230
- if (!enforce) return;
231
-
232
- // Resolve the current user's SID structurally (not by localized username).
233
- const ownerSidResult = spawnSync('powershell', [
234
- '-NoProfile', '-NonInteractive', '-Command',
235
- '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
236
- ], { windowsHide: true, encoding: 'utf8' });
237
- if (ownerSidResult.status !== 0 || !ownerSidResult.stdout.trim()) {
238
- throw new ProfileIdentityError('cannot resolve current user SID for ACL verification', 'PROFILE_ACL_NO_USER');
239
- }
240
- const ownerSid = ownerSidResult.stdout.trim();
241
-
242
- let isDir = false;
243
- try { isDir = fs.statSync(target).isDirectory(); } catch { /* treat as file */ }
244
-
245
- // ALLOWLIST: only these SIDs may have Allow ACEs on the profile path.
246
- // Owner SID + trusted OS principals. Everything else fails closed.
247
- const allowedSids = new Set([
248
- ownerSid,
249
- 'S-1-5-32-544', // BUILTIN\Administrators
250
- 'S-1-5-18', // NT AUTHORITY\SYSTEM
251
- ]);
252
-
253
- // Step 1: Reset inheritance and grant owner + trusted OS principals.
254
- // Use PowerShell .NET to build a fresh protected DACL from scratch.
255
- // PS 5.1 doesn't support comma-separated enum values via ::, so use -bor.
256
- const inhFlagsExpr = isDir
257
- ? '[System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit'
258
- : '[System.Security.AccessControl.InheritanceFlags]::None';
259
- const applyScript = `
260
- $ErrorActionPreference = 'Stop'
261
- $path = '${target.replace(/'/g, "''")}'
262
- $ownerSid = '${ownerSid}'
263
- $inhFlags = ${inhFlagsExpr}
264
- $propFlags = [System.Security.AccessControl.PropagationFlags]::None
265
- $colRights = [System.Security.AccessControl.FileSystemRights]::FullControl
266
-
267
- # Create a fresh protected DACL (disable inheritance, no copy)
268
- $acl = New-Object System.Security.AccessControl.${isDir ? 'DirectorySecurity' : 'FileSecurity'}
269
- $acl.SetAccessRuleProtection($true, $false)
270
-
271
- # Owner: full control
272
- $ownerRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
273
- (New-Object System.Security.Principal.SecurityIdentifier($ownerSid)),
274
- $colRights, $inhFlags, $propFlags,
275
- [System.Security.AccessControl.AccessControlType]::Allow)
276
- $acl.AddAccessRule($ownerRule)
277
-
278
- # Administrators: full control (trusted OS principal)
279
- $adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
280
- (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')),
281
- $colRights, $inhFlags, $propFlags,
282
- [System.Security.AccessControl.AccessControlType]::Allow)
283
- $acl.AddAccessRule($adminRule)
284
-
285
- # SYSTEM: full control (trusted OS principal)
286
- $systemRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
287
- (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')),
288
- $colRights, $inhFlags, $propFlags,
289
- [System.Security.AccessControl.AccessControlType]::Allow)
290
- $acl.AddAccessRule($systemRule)
291
-
292
- # Apply the fresh DACL (instance method — works in PS 5.1+ without extra assemblies)
293
- (Get-Item -LiteralPath $path).SetAccessControl($acl)
294
- `;
295
- const applyResult = spawnSync('powershell', [
296
- '-NoProfile', '-NonInteractive', '-Command', applyScript,
297
- ], { windowsHide: true, encoding: 'utf8' });
298
-
299
- if (applyResult.status !== 0) {
300
- // Fallback: icacls (may not fully clear the DACL on Windows Server 2025)
301
- const user = os.userInfo().username;
302
- const grant = isDir ? `${user}:(OI)(CI)F` : `${user}:F`;
303
- const icaclsApply = spawnSync('icacls', [target, '/inheritance:r', '/grant:r', grant], { windowsHide: true });
304
- if (icaclsApply.status !== 0) {
305
- throw new ProfileIdentityError(
306
- 'failed to restrict the Windows ACL (both .NET and icacls apply failed)',
307
- 'PROFILE_ACL_APPLY_FAILED',
308
- );
309
- }
310
- }
311
-
312
- // Step 2: VERIFY the resulting ACL using an ALLOWLIST (not blocklist).
313
- // Every Allow ACE must belong to the owner SID, Administrators, or SYSTEM.
314
- // Any other Allow ACE (another user, unknown SID, Everyone, Users, etc.)
315
- // fails closed with PROFILE_ACL_LEAK.
316
- const verifyScript = `
317
- $ErrorActionPreference = 'Stop'
318
- $path = '${target.replace(/'/g, "''")}'
319
- $item = Get-Item -LiteralPath $path
320
- $acl = $item.GetAccessControl()
321
- $allRules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
322
- $allowed = @(
323
- '${ownerSid}',
324
- 'S-1-5-32-544',
325
- 'S-1-5-18'
326
- )
327
- $leaked = @()
328
- $ownerHasAccess = $false
329
- foreach ($rule in $allRules) {
330
- $sid = $rule.IdentityReference.Value
331
- if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) {
332
- if ($allowed -notcontains $sid) {
333
- $leaked += $sid
334
- }
335
- if ($sid -eq '${ownerSid}') { $ownerHasAccess = $true }
336
- }
337
- }
338
- $result = @{
339
- leaked = ($leaked -join '|')
340
- ownerHasAccess = $ownerHasAccess
341
- }
342
- $result | ConvertTo-Json -Compress
343
- `;
344
- const verifyResult = spawnSync('powershell', [
345
- '-NoProfile', '-NonInteractive', '-Command', verifyScript,
346
- ], { windowsHide: true, encoding: 'utf8' });
347
-
348
- if (verifyResult.status !== 0) {
349
- if (_isProd()) {
350
- throw new ProfileIdentityError(
351
- 'failed to verify the profile Windows ACL (.NET API failed in production)',
352
- 'PROFILE_ACL_VERIFY_FAILED',
353
- );
354
- }
355
- // dev/test: best-effort — skip verification if PowerShell unavailable
356
- return;
357
- }
358
-
359
- // Parse the JSON result
360
- let verifyData;
361
- try {
362
- verifyData = JSON.parse(verifyResult.stdout.trim());
363
- } catch {
364
- if (_isProd()) {
365
- throw new ProfileIdentityError(
366
- 'failed to parse ACL verification result (invalid JSON from PowerShell)',
367
- 'PROFILE_ACL_VERIFY_FAILED',
368
- );
369
- }
370
- return;
371
- }
372
-
373
- // Check: no leaked (non-allowlisted) Allow ACEs
374
- const leakedSids = (verifyData.leaked || '').split('|').filter(Boolean);
375
- if (leakedSids.length > 0) {
376
- throw new ProfileIdentityError(
377
- `Windows ACL verification failed: non-allowlisted Allow ACE(s) for SID(s): ${leakedSids.join(', ')}`,
378
- 'PROFILE_ACL_LEAK',
379
- );
380
- }
381
-
382
- // Check: owner has access
383
- if (verifyData.ownerHasAccess !== true) {
384
- throw new ProfileIdentityError(
385
- 'Windows ACL verification failed: profile owner has no Allow ACE on the profile path',
386
- 'PROFILE_ACL_OWNER_MISSING',
387
- );
388
- }
389
- }
390
-
391
- /**
392
- * Atomic JSON write with fsync (temp + fsync + rename), fail-closed fsync in
393
- * production. Used for the migration journal + quarantine sidecar. Phase 7-8:
394
- * on any failure the temp file is unlinked so a crashed/failed write never
395
- * leaves a stray `.<name>.tmp.*` on disk.
396
- */
397
- function _atomicWriteJson(filePath, value) {
398
- const dir = path.dirname(filePath);
399
- fs.mkdirSync(dir, { recursive: true });
400
- const tmp = path.join(dir, '.' + path.basename(filePath) + '.tmp.' + crypto.randomBytes(6).toString('hex'));
401
- let renamed = false;
402
- try {
403
- fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600 });
404
- _fsyncPath(tmp, 'file');
405
- fs.renameSync(tmp, filePath);
406
- renamed = true;
407
- } catch (e) {
408
- try { if (!renamed && fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* best-effort */ }
409
- throw e;
410
- }
411
- if (!IS_WIN) { try { fs.chmodSync(filePath, 0o600); } catch { /* best-effort */ } } // eslint-disable-line no-empty
412
- }
413
-
414
- /**
415
- * Append a structured migration / quarantine journal entry (Phase 19). The
416
- * journal is an append-only array at <profilesDir>/migration-journal.json,
417
- * written atomically + fsync'd so a crash mid-migration leaves a recoverable
418
- * audit record.
419
- *
420
- * Phase 9 — fail closed in PRODUCTION: the journal is an AUDIT record of a
421
- * security event (a migration, a quarantine, a quarantine FAILURE), not a
422
- * diagnostic. A journal write failure must NEVER be silently swallowed in
423
- * production — that would let a security event go unrecorded while the code
424
- * behaves as if it was journaled (rule: never claim a journal exists when its
425
- * write failed). So in production a journal write failure THROWS
426
- * PROFILE_JOURNAL_FAILED, surfacing the audit gap instead of proceeding with an
427
- * unjournaled event. In dev/test the journal stays best-effort so harnesses on
428
- * filesystems that cannot honor fsync still run (mirroring the _fsyncPath /
429
- * _applyPerms prod-only fail-closed pattern). The thrown message names only the
430
- * event type + the underlying error — journal entries carry no secrets, so the
431
- * message cannot leak a credential.
432
- */
433
- function _appendMigrationJournal(profilesDir, entry) {
434
- if (!profilesDir) return;
435
- try {
436
- const jp = path.join(profilesDir, MIGRATION_JOURNAL);
437
- let arr;
438
- try { arr = JSON.parse(fs.readFileSync(jp, 'utf8')); } catch { arr = []; }
439
- if (!Array.isArray(arr)) arr = [];
440
- arr.push(Object.assign({ ts: new Date().toISOString() }, entry));
441
- _atomicWriteJson(jp, arr);
442
- } catch (e) {
443
- if (_isProd()) {
444
- throw new ProfileIdentityError(
445
- `failed to append the migration journal entry${entry && entry.event ? ' ' + entry.event : ''}: ${(e && e.message) || 'unknown'}`,
446
- 'PROFILE_JOURNAL_FAILED',
447
- );
448
- }
449
- // dev/test: best-effort — never abort the operation on a dev filesystem.
450
- }
451
- }
452
-
453
- function _journalQuarantine(profilesDir, q, dir, reason) {
454
- _appendMigrationJournal(profilesDir, {
455
- event: q ? 'quarantine' : 'quarantine.failed',
456
- profile: path.basename(dir),
457
- reason: reason || 'unknown',
458
- ok: !!q,
459
- });
460
- }
461
-
462
- // ── Legacy path derivation (schema-2 migration + account-<id> import only) ───
463
-
464
- function serverKey(serverUrl) {
465
- if (!serverUrl) throw new ProfileIdentityError('serverUrl is required to derive a legacy profile path', 'PROFILE_LEGACY_PATH_MISSING');
466
- let normalized = String(serverUrl).trim().replace(/\/+$/, '');
467
- try {
468
- const u = new URL(normalized);
469
- normalized = (u.host || normalized) + (u.pathname || '');
470
- } catch { /* not a URL — hash as-is */ }
471
- return 's' + crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
472
- }
473
-
474
- function userKey(userId) {
475
- if (userId === undefined || userId === null || userId === '') {
476
- throw new ProfileIdentityError('userId is required to derive a legacy profile path', 'PROFILE_LEGACY_PATH_MISSING');
477
- }
478
- return 'u' + String(userId);
479
- }
480
-
481
- function accountKey(accountUuid) {
482
- if (!accountUuid || !UUID_RE.test(String(accountUuid))) {
483
- // No `legacy-account-*` fallback: a profile is never keyed by a recyclable
484
- // numeric id. The account UUID is a hard requirement.
485
- throw new ProfileIdentityError('accountUuid is required to derive a profile path', 'PROFILE_IDENTITY_INCOMPLETE');
486
- }
487
- return String(accountUuid);
488
- }
489
-
490
- function legacyProfileDir(profilesDir, accountId) {
491
- return path.join(profilesDir, `account-${accountId}`);
492
- }
493
-
494
- // ── Path / symlink containment ────────────────────────────────────────────────
495
-
496
- /**
497
- * Resolve `child` and assert it is contained under `root` (no `..` escape, no
498
- * absolute jump, no symlink that resolves outside the root). Uses realpath so a
499
- * symlink planted inside the profiles tree that points elsewhere is caught.
500
- * Returns the resolved contained path, or throws ProfileIdentityError.
501
- */
502
- function _contain(root, child) {
503
- const rootResolved = path.resolve(root);
504
- const childResolved = path.resolve(rootResolved, child);
505
- const rootWithSep = rootResolved + path.sep;
506
- if (childResolved !== rootResolved && !childResolved.startsWith(rootWithSep)) {
507
- throw new ProfileIdentityError('profile path escapes the profiles root', 'PROFILE_PATH_ESCAPE');
508
- }
509
- // Resolve the root through the filesystem too. A benign PARENT symlink
510
- // (e.g. macOS /var -> /private/var) makes every descendant's realpath resolve
511
- // under /private/var while the lexical root is under /var — comparing a
512
- // descendant's realpath against the LEXICAL root would misclassify every
513
- // profile as an escape. Comparing against the root's OWN realpath admits the
514
- // benign case while still catching a symlink planted inside the tree that
515
- // points OUT: its realpath is outside the resolved root. If the root does not
516
- // exist yet, fall back to the lexical root (equivalent to the prior behavior).
517
- let rootReal = rootResolved;
518
- try { rootReal = fs.realpathSync(rootResolved); } catch { /* root not present yet */ }
519
- const rootRealWithSep = rootReal + path.sep;
520
- // Symlink containment: realpath each existing ancestor from the root down and
521
- // ensure none resolves outside the (resolved) root. (The leaf dir may not exist yet.)
522
- let cur = rootResolved;
523
- const rel = path.relative(rootResolved, childResolved);
524
- if (rel && rel !== '.') {
525
- for (const seg of rel.split(path.sep)) {
526
- cur = path.join(cur, seg);
527
- if (fs.existsSync(cur)) {
528
- let real;
529
- try { real = fs.realpathSync(cur); } catch {
530
- throw new ProfileIdentityError('profile path component is not resolvable', 'PROFILE_PATH_ESCAPE');
531
- }
532
- if (real !== rootReal && !real.startsWith(rootRealWithSep)) {
533
- throw new ProfileIdentityError('profile path contains a symlink that escapes the profiles root', 'PROFILE_PATH_ESCAPE');
534
- }
535
- }
536
- }
537
- }
538
- return childResolved;
539
- }
540
-
541
- // ── Marker (schema 4) ─────────────────────────────────────────────────────────
542
-
543
- // Schema-4 integrity: the FULL identity tuple (incl. deviceUuid) is hashed. In
544
- // schema 3 deviceUuid was NOT hashed, so a marker's deviceUuid could be rewritten
545
- // by a different device and the integrity check still passed — the silent
546
- // re-binding hole Phase 10 closes.
547
- function _integrity(tuple) {
548
- return crypto.createHash('sha256').update([tuple.serverUuid, tuple.tenantUuid, tuple.accountUuid, tuple.deviceUuid].join('|')).digest('hex');
549
- }
550
-
551
- // Schema-3 integrity (legacy, for the schema-3 → schema-4 migration ONLY): hashed
552
- // server/tenant/account, NOT deviceUuid — the old formula a schema-3 marker was
553
- // written with.
554
- function _integrityV3(tuple) {
555
- return crypto.createHash('sha256').update([tuple.serverUuid, tuple.tenantUuid, tuple.accountUuid].join('|')).digest('hex');
556
- }
557
-
558
- // A marker matches the requested tuple ONLY when ALL four UUIDs match — incl.
559
- // deviceUuid. A dir stamped by a different device fails the match and is
560
- // quarantined rather than re-bound (Phase 10).
561
- function _markerMatches(marker, tuple) {
562
- return !!marker
563
- && marker.serverUuid === tuple.serverUuid
564
- && marker.tenantUuid === tuple.tenantUuid
565
- && marker.accountUuid === tuple.accountUuid
566
- && marker.deviceUuid === tuple.deviceUuid;
567
- }
568
-
569
- /**
570
- * Parse raw marker text into a verified schema-4 marker object, or null. Shared
571
- * by readMarkerState (on-disk) and the pre-rename temp verify (Phase 7-8) so the
572
- * two checks cannot drift apart.
573
- */
574
- function _parseMarkerContent(raw) {
575
- let data;
576
- try { data = JSON.parse(raw); }
577
- catch { return null; }
578
- if (!data || data.schema !== SCHEMA
579
- || typeof data.serverUuid !== 'string' || typeof data.tenantUuid !== 'string'
580
- || typeof data.accountUuid !== 'string' || typeof data.deviceUuid !== 'string') {
581
- return null;
582
- }
583
- // Integrity: the recorded tuple must hash to the recorded integrity value.
584
- if (data.integrity !== _integrity(data)) return null;
585
- return data;
586
- }
587
-
588
- /**
589
- * Read the schema-4 marker state from a profile dir.
590
- * 'absent' : no identity.json
591
- * 'corrupt' : present but unparseable, not schema 4, missing the tuple, or the
592
- * integrity hash does not match the recorded tuple (tampered)
593
- * 'ok' : a verified schema-4 marker
594
- */
595
- function readMarkerState(dir) {
596
- const p = path.join(dir, IDENTITY_FILE);
597
- if (!fs.existsSync(p)) return { state: 'absent', marker: null };
598
- let raw;
599
- try { raw = fs.readFileSync(p, 'utf8'); }
600
- catch { return { state: 'corrupt', marker: null }; }
601
- const data = _parseMarkerContent(raw);
602
- if (!data) return { state: 'corrupt', marker: null };
603
- return { state: 'ok', marker: data };
604
- }
605
-
606
- /** Public helper: the verified schema-3 marker for a dir, or null. */
607
- function readIdentityMarker(dir) {
608
- const { state, marker } = readMarkerState(dir);
609
- return state === 'ok' ? marker : null;
610
- }
611
-
612
- /**
613
- * Best-effort restore of a previous valid marker's raw bytes after a failed
614
- * re-write (Phase 7-8). Plain write — no perm re-apply / fsync — so this
615
- * recovery path cannot itself trip the ACL/fsync failure that aborted the
616
- * original write. Never throws: the caller's throw already signals the failure;
617
- * this just leaves the dir with its previous good marker instead of a bad/absent
618
- * one.
619
- */
620
- function _restoreMarkerRaw(finalPath, raw) {
621
- try { fs.writeFileSync(finalPath, raw, { encoding: 'utf8', mode: 0o600 }); } catch { /* best-effort */ }
622
- }
623
-
624
- /**
625
- * Write a schema-4 marker DURABLY and VERIFY it on disk (re-read + schema +
626
- * integrity check). Preserves `createdAt` from an existing matching marker.
627
- *
628
- * Durability (Phase 12, hardened Phase 17):
629
- * 1. write to a temp file (a crash never leaves a half-written final marker);
630
- * 2. fsync the temp FILE — FAIL CLOSED in production if it cannot be flushed;
631
- * 3. PRE-RENAME verify the temp content (Phase 7-8): parse + schema + integrity
632
- * + tuple match BEFORE the temp replaces the final marker, so a bad write
633
- * never clobbers an existing good marker;
634
- * 4. atomic rename temp -> final (the final marker appears whole or not at all);
635
- * 5. fsync the parent DIRECTORY (the rename / dir-entry update is persisted) —
636
- * fail closed in production on POSIX; best-effort on Windows where dir fsync
637
- * is unsupported;
638
- * 6. re-read + schema + integrity VALIDATE the on-disk marker.
639
- *
640
- * Phase 7-8 — preserve the previous valid marker + temp cleanup on failure:
641
- * - Before the destructive rename, the raw bytes of any existing VALID marker
642
- * matching the tuple are captured. If the re-write fails AFTER the rename
643
- * (post-rename verify, perms, or dir fsync in production), the previous valid
644
- * marker is RESTORED so a later recycled id is never mis-read against a
645
- * bad/absent marker. If there was no previous valid marker, the unverified
646
- * new marker is removed instead of left behind.
647
- * - On ANY failure the temp file is unlinked (a crashed/failed write never
648
- * leaves a stray `.identity.json.tmp.*` on disk).
649
- *
650
- * Restrictive perms (Phase 12, hardened Phase 18): the profile dir is 0o700 and
651
- * the marker file is 0o600 so other local users cannot read the profile identity
652
- * / cookies. On Windows this is enforced + VERIFIED via icacls (remove inherited
653
- * ACEs, grant only the current user; re-read the ACL and fail closed if a broad
654
- * principal retains access) — chmod is a no-op on Windows, so without this the
655
- * profile was effectively world-readable on Windows. On POSIX chmod is fail-
656
- * closed in production.
657
- *
658
- * Throws PROFILE_MARKER_UNVERIFIED if the written marker does not verify, or
659
- * PROFILE_MARKER_FSYNC_FAILED / PROFILE_ACL_* if durability or permissions
660
- * cannot be verified in production — never leave an unverified / under-protected
661
- * marker that a later recycled id could be mis-read against.
662
- */
663
- function writeIdentityMarker(dir, tuple, options = {}) {
664
- const existing = readIdentityMarker(dir);
665
- const final = path.join(dir, IDENTITY_FILE);
666
- // Phase 7-8: capture the previous VALID marker's raw bytes (only a marker that
667
- // is currently ok AND matches the requested tuple is worth restoring). This
668
- // read happens BEFORE any write, so it is the untouched previous marker.
669
- let prevRaw = null;
670
- if (existing && _markerMatches(existing, tuple)) {
671
- try { prevRaw = fs.readFileSync(final, 'utf8'); } catch { prevRaw = null; }
672
- }
673
- const now = new Date().toISOString();
674
- const marker = {
675
- schema: SCHEMA,
676
- serverUuid: tuple.serverUuid,
677
- tenantUuid: tuple.tenantUuid,
678
- accountUuid: tuple.accountUuid,
679
- deviceUuid: tuple.deviceUuid,
680
- createdAt: (existing && existing.createdAt) || now,
681
- lastUsed: now,
682
- agentVersion: options.agentVersion != null ? options.agentVersion : AGENT_VERSION,
683
- integrity: _integrity(tuple),
684
- };
685
- // 0o700: only the owning user may traverse/read the profile dir.
686
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
687
- _applyPerms(dir, 0o700);
688
- const tmp = path.join(dir, '.' + IDENTITY_FILE + '.tmp.' + crypto.randomBytes(6).toString('hex'));
689
- let renamed = false;
690
- try {
691
- // 1. write to a temp file with restrictive perms (0o600 — no group/other read).
692
- fs.writeFileSync(tmp, JSON.stringify(marker, null, 2), { encoding: 'utf8', mode: 0o600 });
693
- // 2. fsync the temp file's contents (fail closed in production).
694
- _fsyncPath(tmp, 'file');
695
- // 3. PRE-RENAME verify the temp content (the final marker is still the old
696
- // one, so a bad temp never destroys a good marker).
697
- const tmpMarker = _parseMarkerContent(fs.readFileSync(tmp, 'utf8'));
698
- if (!tmpMarker || !_markerMatches(tmpMarker, tuple)) {
699
- throw new ProfileIdentityError('the identity marker did not verify before rename', 'PROFILE_MARKER_UNVERIFIED');
700
- }
701
- // 4. atomic rename temp -> final (rename preserves the 0o600 mode).
702
- fs.renameSync(tmp, final);
703
- renamed = true;
704
- _applyPerms(final, 0o600);
705
- // 5. fsync the parent directory so the rename (dir-entry update) is durable.
706
- _fsyncPath(dir, 'dir');
707
- // 6. re-read + validate the on-disk marker.
708
- const verify = readMarkerState(dir);
709
- if (verify.state !== 'ok' || !_markerMatches(verify.marker, tuple)) {
710
- throw new ProfileIdentityError('the written identity marker did not verify on disk', 'PROFILE_MARKER_UNVERIFIED');
711
- }
712
- } catch (e) {
713
- // Phase 7-8: never leave a stray temp marker file on a failed write.
714
- try { if (!renamed && fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* best-effort */ }
715
- // Phase 7-8: if the rename already replaced the final marker, restore the
716
- // previous valid marker (or, if there was none, remove the unverified new
717
- // one) so the dir is never left with a bad marker a recycled id could be
718
- // mis-read against.
719
- if (renamed) {
720
- if (prevRaw !== null) _restoreMarkerRaw(final, prevRaw);
721
- else { try { fs.unlinkSync(final); } catch { /* best-effort */ } }
722
- }
723
- throw e;
724
- }
725
- }
726
-
727
- // ── Quarantine ────────────────────────────────────────────────────────────────
728
-
729
- function quarantineDir(dir, reason) {
730
- if (!fs.existsSync(dir)) return null;
731
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
732
- const q = `${dir}.quarantine-${stamp}`;
733
- try {
734
- fs.renameSync(dir, q);
735
- } catch {
736
- try { fs.renameSync(dir, `${dir}.corrupt-${stamp}`); return `${dir}.corrupt-${stamp}`; }
737
- catch { return null; }
738
- }
739
- // Phase 19: a durable, fsync'd QUARANTINE.json sidecar (was a plain
740
- // writeFileSync — not atomic, not fsync'd). Best-effort: a sidecar write
741
- // failure must never abort a quarantine.
742
- try {
743
- _atomicWriteJson(path.join(q, 'QUARANTINE.json'), { reason: reason || 'unknown', quarantinedAt: new Date().toISOString() });
744
- } catch { /* best-effort */ } // eslint-disable-line no-empty
745
- return q;
746
- }
747
-
748
- /**
749
- * Quarantine an UNTRUSTED dir and FAIL CLOSED if it cannot be moved aside
750
- * (Phase 11 — rule 22 "never trust an unmarked profile"). A bad dir that cannot
751
- * be quarantined must NEVER be stamped with a fresh marker over its existing
752
- * (untrusted) data — that would silently adopt the data. Returns the quarantine
753
- * path, or null if there was nothing to quarantine. Throws
754
- * PROFILE_QUARANTINE_FAILED if the dir exists but neither rename succeeds.
755
- * Phase 19: the outcome (success OR failure) is journaled to the migration
756
- * journal so a quarantine failure is never silent.
757
- */
758
- function _requireQuarantine(dir, reason, profilesDir) {
759
- if (!fs.existsSync(dir)) return null;
760
- const q = quarantineDir(dir, reason);
761
- if (!q) {
762
- _appendMigrationJournal(profilesDir, { event: 'quarantine.failed', profile: path.basename(dir), reason: reason || 'unknown', ok: false });
763
- throw new ProfileIdentityError(
764
- `failed to quarantine an untrusted profile dir; refusing to stamp a marker over it: ${reason || 'unknown'}`,
765
- 'PROFILE_QUARANTINE_FAILED',
766
- );
767
- }
768
- _appendMigrationJournal(profilesDir, { event: 'quarantine', profile: path.basename(dir), reason: reason || 'unknown', ok: true });
769
- return q;
770
- }
771
-
772
- function copyDirSync(src, dst) {
773
- fs.mkdirSync(dst, { recursive: true });
774
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
775
- const s = path.join(src, entry.name);
776
- const d = path.join(dst, entry.name);
777
- if (entry.isDirectory()) copyDirSync(s, d);
778
- else fs.copyFileSync(s, d);
779
- }
780
- }
781
-
782
- function dirExists(p) {
783
- try { return fs.existsSync(p) && fs.statSync(p).isDirectory(); } catch { return false; }
784
- }
785
-
786
- // ── Legacy marker readers (migration only) ────────────────────────────────────
787
-
788
- // Schema-1/2 marker reader (accountUuid only) — used by the schema-2 → schema-4
789
- // migration.
790
- function _readLegacyMarker(dir) {
791
- const p = path.join(dir, IDENTITY_FILE);
792
- if (!fs.existsSync(p)) return { state: 'absent', marker: null };
793
- let raw;
794
- try { raw = fs.readFileSync(p, 'utf8'); } catch { return { state: 'corrupt', marker: null }; }
795
- let data;
796
- try { data = JSON.parse(raw); } catch { return { state: 'corrupt', marker: null }; }
797
- if (!data || typeof data.accountUuid !== 'string') return { state: 'corrupt', marker: null };
798
- return { state: 'ok', marker: data };
799
- }
800
-
801
- // Schema-3 marker reader — used by the schema-3 → schema-4 migration ONLY.
802
- // Validates against the OLD (deviceUuid-less) integrity formula. A schema-3
803
- // marker is NEVER trusted as a current marker: readMarkerState (schema-4) reads
804
- // it as 'corrupt'. This reader exists solely to decide whether a 3-level
805
- // profile belongs to the requesting device and may be migrated forward.
806
- function _readSchema3Marker(dir) {
807
- const p = path.join(dir, IDENTITY_FILE);
808
- if (!fs.existsSync(p)) return { state: 'absent', marker: null };
809
- let raw;
810
- try { raw = fs.readFileSync(p, 'utf8'); } catch { return { state: 'corrupt', marker: null }; }
811
- let data;
812
- try { data = JSON.parse(raw); } catch { return { state: 'corrupt', marker: null }; }
813
- if (!data || data.schema !== SCHEMA_V3
814
- || typeof data.serverUuid !== 'string' || typeof data.tenantUuid !== 'string'
815
- || typeof data.accountUuid !== 'string' || typeof data.deviceUuid !== 'string') {
816
- return { state: 'corrupt', marker: null };
817
- }
818
- if (data.integrity !== _integrityV3(data)) return { state: 'corrupt', marker: null };
819
- return { state: 'ok', marker: data };
820
- }
821
-
822
- /**
823
- * Move a schema-3 namespaced profile (3-level path
824
- * `<profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/`) into the device-
825
- * scoped schema-4 path (`.../<accountUuid>/<deviceUuid>/`), preserving its data,
826
- * ONLY when the schema-3 marker's tuple — INCLUDING deviceUuid — matches the
827
- * requesting device. A profile whose schema-3 marker was stamped by a DIFFERENT
828
- * device is LEFT UNTOUCHED (never re-bound); the requesting device gets a fresh
829
- * profile. A missing/corrupt schema-3 marker is also left untouched. Returns
830
- * true if a migration happened.
831
- */
832
- function _migrateFromSchema3(profilesDir, newBase, tuple) {
833
- let oldBase;
834
- try {
835
- oldBase = _contain(profilesDir, path.join(tuple.serverUuid, tuple.tenantUuid, tuple.accountUuid));
836
- } catch {
837
- return false; // no 3-level identity to migrate from
838
- }
839
- if (!fs.existsSync(oldBase) || path.resolve(oldBase) === path.resolve(newBase)) return false;
840
- const { state, marker } = _readSchema3Marker(oldBase);
841
- if (state !== 'ok' || !marker
842
- || marker.serverUuid !== tuple.serverUuid || marker.tenantUuid !== tuple.tenantUuid
843
- || marker.accountUuid !== tuple.accountUuid || marker.deviceUuid !== tuple.deviceUuid) {
844
- return false; // belongs to another device / unmarked / corrupt — leave it
845
- }
846
- // newBase (<s>/<t>/<a>/<d>) is a SUBDIRECTORY of oldBase (<s>/<t>/<a>), so a
847
- // direct rename into itself is impossible. Move oldBase aside to a sibling
848
- // staging path, recreate the (now empty) account dir, then move the profile
849
- // into the device-scoped subdir. All on one filesystem under profilesDir →
850
- // atomic renames; on any failure, restore oldBase from staging and abort
851
- // (this device gets a fresh profile instead).
852
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
853
- const staging = `${oldBase}.migrating-${stamp}`;
854
- try {
855
- fs.renameSync(oldBase, staging);
856
- fs.mkdirSync(oldBase, { recursive: true });
857
- fs.renameSync(staging, newBase);
858
- } catch {
859
- try { if (fs.existsSync(staging) && !fs.existsSync(oldBase)) fs.renameSync(staging, oldBase); } catch { /* leave staging for inspection */ }
860
- _appendMigrationJournal(profilesDir, { event: 'migrate.schema3', result: 'failed', stage: 'move', profile: path.basename(newBase) });
861
- return false;
862
- }
863
- try {
864
- writeIdentityMarker(newBase, tuple); // upgrade to schema-4, device-bound integrity
865
- } catch {
866
- const q = quarantineDir(newBase, 'schema-4 marker failed to verify after schema-3 migration');
867
- _journalQuarantine(profilesDir, q, newBase, 'schema-4 marker failed to verify after schema-3 migration');
868
- _appendMigrationJournal(profilesDir, { event: 'migrate.schema3', result: 'failed', stage: 'marker-verify', profile: path.basename(newBase) });
869
- return false;
870
- }
871
- _appendMigrationJournal(profilesDir, { event: 'migrate.schema3', result: 'success', profile: path.basename(newBase) });
872
- return true;
873
- }
874
-
875
- /**
876
- * Resolve the profile directory for a session under the strict schema-4 identity.
877
- *
878
- * Returns { dir, migrated, fresh, quarantined }.
879
- *
880
- * @param {object} args
881
- * @param {string} args.profilesDir profiles root
882
- * @param {string} args.serverUuid immutable backend UUID (REQUIRED)
883
- * @param {string} args.tenantUuid immutable tenant UUID (REQUIRED)
884
- * @param {string} args.accountUuid immutable account UUID (REQUIRED)
885
- * @param {string} args.deviceUuid immutable device UUID (REQUIRED)
886
- * @param {string} [args.serverUrl] legacy server URL (schema-2 migration)
887
- * @param {string|number} [args.userId] legacy numeric tenant id (schema-2 migration)
888
- * @param {string|number} [args.accountId] legacy numeric account id (account-<id> import)
889
- */
890
- function resolveProfileDir(args) {
891
- const { profilesDir, serverUuid, tenantUuid, accountUuid, deviceUuid, serverUrl, userId, accountId } = args || {};
892
-
893
- // ── fail closed: every UUID is required, UUID-shaped, and the path is contained ──
894
- const tuple = { serverUuid, tenantUuid, accountUuid, deviceUuid };
895
- for (const [k, v] of Object.entries(tuple)) {
896
- if (!v || typeof v !== 'string' || !UUID_RE.test(v)) {
897
- throw new ProfileIdentityError(`profile identity is missing or malformed: ${k}`, 'PROFILE_IDENTITY_INCOMPLETE');
898
- }
899
- }
900
- // Phase 10: deviceUuid is a PATH component — each device gets its own profile
901
- // dir under the account, so a different device can never reuse this device's
902
- // on-disk cookies/fingerprint even before the marker is consulted.
903
- const base = _contain(profilesDir, path.join(serverUuid, tenantUuid, accountUuid, deviceUuid));
904
-
905
- // Case 1: schema-4 dir already exists.
906
- if (fs.existsSync(base)) {
907
- const { state, marker } = readMarkerState(base);
908
- if (state === 'ok' && _markerMatches(marker, tuple)) {
909
- writeIdentityMarker(base, tuple); // reuse, refresh lastUsed
910
- return { dir: base, migrated: false, fresh: false, quarantined: null, migrationRequired: false };
911
- }
912
- // Absent (unmarked), corrupt, or mismatched (incl. a different deviceUuid)
913
- // → quarantine, never stamp-and-reuse and never re-bind to another device.
914
- // If the bad dir CANNOT be moved aside, fail CLOSED — never stamp a marker
915
- // over untrusted data (Phase 11).
916
- const reason = state === 'absent'
917
- ? 'unmarked profile dir — never adopt an unmarked dir'
918
- : state === 'corrupt'
919
- ? 'corrupt or tampered identity marker'
920
- : `identity mismatch (marker server/tenant/account/device ≠ requested)`;
921
- const q = _requireQuarantine(base, reason, profilesDir);
922
- return { dir: _freshDir(base, tuple, profilesDir), migrated: false, fresh: true, quarantined: q, migrationRequired: false };
923
- }
924
-
925
- // Case 2: schema-4 dir absent → try a one-time schema-3 → schema-4 migration
926
- // (device-bound: only a schema-3 profile whose deviceUuid matches this device).
927
- if (_migrateFromSchema3(profilesDir, base, tuple)) {
928
- return { dir: base, migrated: true, fresh: false, quarantined: null, migrationRequired: false };
929
- }
930
-
931
- // Case 3: try a one-time schema-2 → schema-4 migration.
932
- const migrated = _migrateFromLegacy(profilesDir, base, tuple, { serverUrl, userId });
933
- if (migrated) return { dir: base, migrated: true, fresh: false, quarantined: null, migrationRequired: false };
934
-
935
- // Phase 15: NO automatic account-<id> import. A pre-hardening profile is never
936
- // silently pulled into a new account (rule 21/22 — never trust an unmarked
937
- // profile dir; never copy a legacy profile automatically). If one exists it is
938
- // surfaced as `migrationRequired` so the owner can run the EXPLICIT, safeguarded
939
- // import (importLegacyProfile). A fresh, empty profile is used meanwhile.
940
- let migrationRequired = false;
941
- if (accountId != null) {
942
- const legacy = legacyProfileDir(profilesDir, accountId);
943
- if (fs.existsSync(legacy) && fs.statSync(legacy).isDirectory()) {
944
- migrationRequired = true;
945
- }
946
- }
947
- return { dir: _freshDir(base, tuple, profilesDir), migrated: false, fresh: true, quarantined: null, migrationRequired };
948
- }
949
-
950
- function _freshDir(dir, tuple, profilesDir) {
951
- // If a pre-existing dir is in the way, it MUST be quarantined (fail closed) —
952
- // never stamp a fresh marker over untrusted existing data (Phase 11).
953
- if (fs.existsSync(dir)) _requireQuarantine(dir, 'pre-existing dir cleared before fresh profile creation', profilesDir);
954
- fs.mkdirSync(dir, { recursive: true });
955
- writeIdentityMarker(dir, tuple);
956
- return dir;
957
- }
958
-
959
- /**
960
- * Move a schema-2 namespaced profile (`<profilesDir>/s<hash>/u<id>/<accountUuid>/`)
961
- * into the new device-scoped schema-4 path (`<profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/<deviceUuid>/`),
962
- * preserving its data, ONLY when the legacy dir's marker accountUuid matches the
963
- * requested account. A missing/corrupt/mismatched legacy marker is left untouched
964
- * (never adopt an unverifiable dir). Returns true if a migration happened.
965
- */
966
- function _migrateFromLegacy(profilesDir, newBase, tuple, { serverUrl, userId }) {
967
- let legacyBase;
968
- try {
969
- legacyBase = _contain(profilesDir, path.join(serverKey(serverUrl), userKey(userId), accountKey(tuple.accountUuid)));
970
- } catch {
971
- return false; // no legacy identity to migrate from
972
- }
973
- if (!fs.existsSync(legacyBase) || legacyBase === newBase) return false;
974
- const { state, marker } = _readLegacyMarker(legacyBase);
975
- if (state !== 'ok' || !marker || String(marker.accountUuid) !== String(tuple.accountUuid)) {
976
- return false; // unverifiable or belongs to another account — leave it
977
- }
978
- try {
979
- fs.mkdirSync(path.dirname(newBase), { recursive: true });
980
- fs.renameSync(legacyBase, newBase);
981
- } catch {
982
- // rename can fail across volumes / on lock contention; fall back to a copy.
983
- try {
984
- copyDirSync(legacyBase, newBase);
985
- } catch {
986
- _appendMigrationJournal(profilesDir, { event: 'migrate.legacy', result: 'failed', stage: 'move', profile: path.basename(newBase) });
987
- return false;
988
- }
989
- }
990
- try {
991
- writeIdentityMarker(newBase, tuple);
992
- } catch {
993
- // The data moved but the marker did not verify → quarantine rather than
994
- // adopt an unmarked dir.
995
- const q = quarantineDir(newBase, 'schema-3 marker failed to verify after migration');
996
- _journalQuarantine(profilesDir, q, newBase, 'schema-3 marker failed to verify after migration');
997
- _appendMigrationJournal(profilesDir, { event: 'migrate.legacy', result: 'failed', stage: 'marker-verify', profile: path.basename(newBase) });
998
- return false;
999
- }
1000
- _appendMigrationJournal(profilesDir, { event: 'migrate.legacy', result: 'success', profile: path.basename(newBase) });
1001
- return true;
1002
- }
1003
-
1004
- /**
1005
- * List the pre-hardening `account-<id>` profile directories still living at the
1006
- * profiles root (not yet namespaced under server/tenant/account/device UUIDs).
1007
- * These are the dirs surfaced as migration_required and never adopted
1008
- * automatically. Schema-4 dirs live under `<uuid>/<uuid>/<uuid>/<uuid>/` and
1009
- * schema-2 dirs under `s<hash>/u<id>/`, so a bare `account-<digits>` entry at the
1010
- * root is unambiguously a legacy dir. Quarantined / already-imported siblings
1011
- * (`.quarantine-*`, `.imported-*`) are NOT listed.
1012
- */
1013
- function discoverLegacyProfiles(profilesDir) {
1014
- const root = path.resolve(profilesDir);
1015
- if (!dirExists(root)) return [];
1016
- const out = [];
1017
- let entries;
1018
- try { entries = fs.readdirSync(root, { withFileTypes: true }); } catch { return []; }
1019
- for (const ent of entries) {
1020
- if (!ent.isDirectory()) continue;
1021
- const m = /^account-(\d+)$/.exec(ent.name);
1022
- if (m) out.push({ accountId: m[1], dir: path.join(root, ent.name) });
1023
- }
1024
- return out;
1025
- }
1026
-
1027
- /**
1028
- * EXPLICIT, safeguarded import of a single pre-hardening `account-<id>` profile
1029
- * into the device-scoped schema-4 namespaced path. This is the ONLY path by which
1030
- * legacy data is pulled forward — resolveProfileDir never does it automatically
1031
- * (Phase 15).
1032
- *
1033
- * Safeguards (rule 21/22/23): fail closed on any missing UUID; refuse if a
1034
- * namespaced profile already exists for the account+device (conflict); copy into
1035
- * a staging dir and verify the schema-4 marker BEFORE atomic promotion; on any
1036
- * failure the original is left untouched; on success the original is renamed to
1037
- * `account-<id>.imported-<ts>` (preserved, never deleted, and no longer reported
1038
- * by discoverLegacyProfiles). Returns { dir, preservedOriginal }.
1039
- *
1040
- * @param {object} args
1041
- * @param {string} args.profilesDir
1042
- * @param {string|number} args.accountId legacy numeric account id (REQUIRED)
1043
- * @param {string} args.serverUuid
1044
- * @param {string} args.tenantUuid
1045
- * @param {string} args.accountUuid
1046
- * @param {string} args.deviceUuid
1047
- */
1048
- function importLegacyProfile(args) {
1049
- const { profilesDir, accountId, serverUuid, tenantUuid, accountUuid, deviceUuid } = args || {};
1050
- const tuple = { serverUuid, tenantUuid, accountUuid, deviceUuid };
1051
- for (const [k, v] of Object.entries(tuple)) {
1052
- if (!v || typeof v !== 'string' || !UUID_RE.test(v)) {
1053
- throw new ProfileIdentityError(`legacy import requires a complete identity; missing or malformed: ${k}`, 'PROFILE_IDENTITY_INCOMPLETE');
1054
- }
1055
- }
1056
- if (accountId == null || accountId === '') {
1057
- throw new ProfileIdentityError('legacy import requires the legacy numeric accountId', 'PROFILE_LEGACY_IMPORT_MISSING_ID');
1058
- }
1059
- const legacy = legacyProfileDir(profilesDir, String(accountId));
1060
- if (!dirExists(legacy)) {
1061
- throw new ProfileIdentityError('no pre-hardening account-<id> profile exists to import', 'PROFILE_LEGACY_IMPORT_NO_SOURCE');
1062
- }
1063
-
1064
- const target = _contain(profilesDir, path.join(serverUuid, tenantUuid, accountUuid, deviceUuid));
1065
-
1066
- // Conflict check: never overwrite an existing, verified namespaced profile.
1067
- if (fs.existsSync(target) && readIdentityMarker(target)) {
1068
- throw new ProfileIdentityError(
1069
- 'a namespaced profile already exists for this account+device; refusing to overwrite — delete it first',
1070
- 'PROFILE_LEGACY_IMPORT_CONFLICT',
1071
- );
1072
- }
1073
-
1074
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
1075
- const staging = `${target}.importing-${stamp}`;
1076
- const preserved = `${legacy}.imported-${stamp}`;
1077
-
1078
- fs.mkdirSync(path.dirname(staging), { recursive: true });
1079
- try {
1080
- // 1. temp copy into staging (original untouched)
1081
- copyDirSync(legacy, staging);
1082
- // 2. write + verify the schema-4 marker on the staging dir (fails closed)
1083
- writeIdentityMarker(staging, tuple);
1084
- // 3. atomic promotion: clear any unmarked pre-existing target (fail CLOSED
1085
- // if it cannot be quarantined — never overwrite untrusted data), then rename
1086
- if (fs.existsSync(target)) _requireQuarantine(target, 'unmarked pre-existing dir cleared before legacy import promotion', profilesDir);
1087
- fs.renameSync(staging, target);
1088
- // 4. preserve the original (renamed aside, never deleted, no longer re-discovered)
1089
- try { fs.renameSync(legacy, preserved); } catch { /* best-effort: data already promoted to target */ }
1090
- } catch (e) {
1091
- // Never leave a half-written staging dir; never touch the original on failure.
1092
- try { fs.rmSync(staging, { recursive: true, force: true }); } catch { /* ignore */ }
1093
- _appendMigrationJournal(profilesDir, { event: 'import.legacy', result: 'failed', account: String(accountId), error: (e && e.code) || 'unknown' });
1094
- if (e instanceof ProfileIdentityError) throw e;
1095
- throw new ProfileIdentityError(`legacy import failed: ${e.message}`, 'PROFILE_LEGACY_IMPORT_FAILED');
1096
- }
1097
- _appendMigrationJournal(profilesDir, { event: 'import.legacy', result: 'success', account: String(accountId), profile: path.basename(target) });
1098
- return { dir: target, preservedOriginal: preserved };
1099
- }
1100
-
1101
- module.exports = {
1102
- SCHEMA,
1103
- ProfileIdentityError,
1104
- serverKey,
1105
- userKey,
1106
- accountKey,
1107
- legacyProfileDir,
1108
- resolveProfileDir,
1109
- discoverLegacyProfiles,
1110
- importLegacyProfile,
1111
- readIdentityMarker,
1112
- readMarkerState,
1113
- writeIdentityMarker,
1114
- quarantineDir,
1115
- // Phase 10: exported for ACL-policy config unit tests.
1116
- windowsAclPolicy: _windowsAclPolicy,
1
+ 'use strict';
2
+
3
+ /**
4
+ * Phase 14 + Phase 10 — strict browser-profile identity (marker schema 4).
5
+ *
6
+ * An on-disk browser profile (cookies, localStorage, cache, fingerprint) is
7
+ * namespaced by an IMMUTABLE identity tuple assigned by the backend:
8
+ *
9
+ * <profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/<deviceUuid>/
10
+ *
11
+ * serverUuid immutable UUID of the backend installation (not the URL — a
12
+ * URL change must not orphan profiles)
13
+ * tenantUuid immutable UUID of the owning user (not the recyclable numeric
14
+ * user id — a DB rebuild must not let a reused id inherit
15
+ * another tenant's profiles)
16
+ * accountUuid immutable UUID of the account
17
+ * deviceUuid immutable UUID of the DEVICE the profile is bound to
18
+ *
19
+ * Phase 10 closes a silent re-binding hole: in schema 3 the PATH was keyed only
20
+ * by server/tenant/account UUIDs, deviceUuid was NOT in the integrity hash, and
21
+ * `_markerMatches` did not compare it — so a DIFFERENT device taking over the
22
+ * same (server/tenant/account) slot silently re-stamped the marker with its own
23
+ * deviceUuid and reused the previous device's cookies/fingerprint. Schema 4
24
+ * binds the profile to the device in all three places:
25
+ * - PATH: deviceUuid is a path component (each device gets its own
26
+ * profile dir under the account);
27
+ * - MARKER: schema 4; the marker is only 'ok' when schema === 4;
28
+ * - INTEGRITY: deviceUuid is part of the sha256 integrity hash, and
29
+ * `_markerMatches` requires marker.deviceUuid === tuple.deviceUuid.
30
+ * A dir whose marker was stamped by a different device now FAILS the match and
31
+ * is QUARANTINED (never re-bound) — the new device starts a fresh profile.
32
+ *
33
+ * Fail-closed rules (rule 17):
34
+ * - ANY of the four UUIDs missing / malformed → THROW. There are NO fallbacks
35
+ * (no `default` server, no `u0` tenant, no `legacy-account-*` account). A
36
+ * profile is never opened with a recyclable / unknown identity.
37
+ * - PATH / SYMLINK CONTAINMENT: the resolved dir must stay under profilesDir.
38
+ * A `..` component, an absolute escape, or a symlink that points outside
39
+ * the profiles root is rejected.
40
+ *
41
+ * Reuse guard (never stamp-and-reuse — rule 22 "never trust an unmarked profile"):
42
+ * - marker absent → the dir is UNMARKED → QUARANTINE it (move aside),
43
+ * start a genuinely fresh dir. NEVER adopt an unmarked
44
+ * dir by stamping a marker over it.
45
+ * - marker corrupt → QUARANTINE (tampered / half-written)
46
+ * - marker tuple mismatch (incl. a DIFFERENT deviceUuid) → QUARANTINE
47
+ * - marker tuple matches (same device) → reuse, refresh lastUsed
48
+ *
49
+ * One-time schema-3 → schema-4 migration (data-preserving, device-bound — rule
50
+ * 12/13): a profile written by the schema-3 agent lives at the 3-level path
51
+ * `<profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/`. On the first schema-4
52
+ * resolve, if the 4-level path is empty but the 3-level path exists with a
53
+ * matching schema-3 marker WHOSE deviceUuid EQUALS the requesting device, the
54
+ * 3-level dir is MOVED into the device-scoped 4-level path and re-stamped
55
+ * schema-4. A schema-3 profile whose deviceUuid DIFFERS is LEFT UNTOUCHED — it
56
+ * belongs to another device and is never re-bound; the requesting device gets a
57
+ * fresh profile (its rightful owner will migrate it when it connects).
58
+ *
59
+ * One-time schema-2 → schema-4 migration (data-preserving — rule 12/13):
60
+ * Profiles written by the pre-Phase-14 agent live at the legacy namespaced
61
+ * path `<profilesDir>/<serverKey(serverUrl)>/u<userId>/<accountUuid>/`. On the
62
+ * first schema-4 resolve, if the NEW path is empty but the legacy path exists
63
+ * with a matching accountUuid marker, the legacy dir is MOVED to the new
64
+ * device-scoped path and stamped with a schema-4 marker. The legacy data is
65
+ * preserved (a move, not a copy-and-delete); a mismatched/absent legacy marker
66
+ * is left untouched (never adopt an unverifiable dir).
67
+ */
68
+
69
+ const fs = require('fs');
70
+ const path = require('path');
71
+ const crypto = require('crypto');
72
+ const os = require('os');
73
+ const { spawnSync } = require('child_process');
74
+
75
+ const IDENTITY_FILE = 'identity.json';
76
+ const SCHEMA = 4;
77
+ const SCHEMA_V3 = 3;
78
+ const AGENT_VERSION = process.env.AGENT_VERSION || null;
79
+ const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
80
+ const IS_WIN = process.platform === 'win32';
81
+ const MIGRATION_JOURNAL = 'migration-journal.json';
82
+ // Phase 10/18: the Windows ACL policy restricts profile paths to the owning
83
+ // user + trusted OS principals only. Untrusted broad principals are forbidden.
84
+ //
85
+ // ── Threat model ──
86
+ // The profile directory contains the browser profile (cookies, session data).
87
+ // The security boundary protects against OTHER USERS on the same machine
88
+ // reading or modifying the profile. It does NOT protect against a malicious
89
+ // local administrator or SYSTEM — those are trusted OS principals with
90
+ // operating-system-level access (take-ownership, SeBackupPrivilege, etc).
91
+ // Excluding their ACEs from the DACL does not prevent a local admin from
92
+ // recovering access. The real protection is that ordinary users on the machine
93
+ // cannot read another user's profile.
94
+ //
95
+ // ── Trusted OS principals (allowed everywhere, same policy in CI and prod) ──
96
+ // BUILTIN\Administrators (S-1-5-32-544) and NT AUTHORITY\SYSTEM (S-1-5-18)
97
+ // are trusted because they have OS-level access regardless of the DACL.
98
+ // Windows auto-adds them to directories created by elevated processes.
99
+ // They are ALLOWED in the ACL — not excluded via env vars.
100
+ //
101
+ // ── Forbidden untrusted principals (fail-closed everywhere) ──
102
+ // Everyone (S-1-1-0), BUILTIN\Users (S-1-5-32-545), Authenticated Users
103
+ // (S-1-5-11) are broad untrusted groups. Any explicit or inherited ACE for
104
+ // these groups fails the verification in both CI and production.
105
+ //
106
+ // ── Configuration ──
107
+ // PROFILE_WINDOWS_ACL_ENFORCE (default true): enforcement toggle; false is
108
+ // dev/test only and FAILS CLOSED in production.
109
+ // PROFILE_WINDOWS_ACL_FORBIDDEN_PRINCIPALS: ADDITIONAL forbidden principals
110
+ // (unioned with the default floor; can only make stricter).
111
+ const DEFAULT_ACL_FORBIDDEN = ['Everyone', 'BUILTIN\\Users', 'Authenticated Users'];
112
+ const TRUSTED_OS_SIDS = new Set(['S-1-5-32-544', 'S-1-5-18']); // Administrators, SYSTEM
113
+
114
+ // Well-known SID mapping for forbidden principals (used to resolve configured
115
+ // additions to SIDs for SID-based verification).
116
+ const _PRINCIPAL_TO_SID = {
117
+ 'Everyone': 'S-1-1-0',
118
+ 'BUILTIN\\Users': 'S-1-5-32-545',
119
+ 'Authenticated Users': 'S-1-5-11',
120
+ 'BUILTIN\\Administrators': 'S-1-5-32-544',
121
+ 'NT AUTHORITY\\SYSTEM': 'S-1-5-18',
122
+ 'Guests': 'S-1-5-32-546',
123
+ };
124
+
125
+ /**
126
+ * Phase 10: resolve the effective Windows ACL policy from env. Returns
127
+ * { enforce: boolean, forbiddenPrincipals: string[] }. Throws
128
+ * PROFILE_ACL_DISABLED_IN_PROD if enforcement is explicitly disabled in
129
+ * production (the policy cannot be weakened where it matters).
130
+ */
131
+ function _windowsAclPolicy() {
132
+ let enforce = true;
133
+ const envEnforce = process.env.PROFILE_WINDOWS_ACL_ENFORCE;
134
+ if (envEnforce != null && envEnforce !== '') {
135
+ const v = String(envEnforce).toLowerCase();
136
+ if (v === '1' || v === 'true') enforce = true;
137
+ else if (v === '0' || v === 'false') {
138
+ if (_isProd()) {
139
+ throw new ProfileIdentityError(
140
+ 'PROFILE_WINDOWS_ACL_ENFORCE=false is not permitted in production (the Windows ACL policy cannot be disabled)',
141
+ 'PROFILE_ACL_DISABLED_IN_PROD',
142
+ );
143
+ }
144
+ enforce = false;
145
+ }
146
+ // any unrecognized value -> default (enforce)
147
+ }
148
+ // Forbidden principals: the default floor is ALWAYS enforced; env additions
149
+ // are unioned in (stricter only).
150
+ let forbiddenPrincipals = DEFAULT_ACL_FORBIDDEN;
151
+ const envExtra = process.env.PROFILE_WINDOWS_ACL_FORBIDDEN_PRINCIPALS;
152
+ if (envExtra && envExtra.trim()) {
153
+ const extra = envExtra.split(',').map((s) => s.trim()).filter(Boolean);
154
+ forbiddenPrincipals = Array.from(new Set([...DEFAULT_ACL_FORBIDDEN, ...extra]));
155
+ }
156
+ return { enforce, forbiddenPrincipals };
157
+ }
158
+
159
+ class ProfileIdentityError extends Error {
160
+ constructor(message, code) {
161
+ super(message);
162
+ this.code = code || 'PROFILE_IDENTITY_INCOMPLETE';
163
+ this.name = 'ProfileIdentityError';
164
+ }
165
+ }
166
+
167
+ // ── Durability + permission + journal helpers (Phase 17-19) ───────────────────
168
+
169
+ function _isProd() { return process.env.NODE_ENV === 'production'; }
170
+
171
+ /**
172
+ * fsync a file or directory path. In PRODUCTION a fsync failure is a real
173
+ * durability failure (the marker was not flushed to disk) and FAILS CLOSED —
174
+ * never claim a durable marker that was not persisted (Phase 17). The one
175
+ * exception is DIRECTORY fsync on Windows, which is genuinely unsupported
176
+ * (ENOTSUP/EINVAL) and therefore a platform limitation, not a disk error — it
177
+ * stays best-effort there regardless of NODE_ENV. In dev/test fsync is
178
+ * best-effort so harnesses on filesystems that do not honor fsync still run.
179
+ */
180
+ function _fsyncPath(p, kind) {
181
+ try {
182
+ const fd = fs.openSync(p, 'r');
183
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
184
+ } catch (err) {
185
+ if (kind === 'dir' && IS_WIN) return; // dir fsync unsupported on Windows
186
+ if (_isProd()) {
187
+ throw new ProfileIdentityError(
188
+ `marker ${kind} fsync failed in production (durability unverifiable): ${(err && err.code) || (err && err.message) || 'unknown'}`,
189
+ 'PROFILE_MARKER_FSYNC_FAILED',
190
+ );
191
+ }
192
+ // dev/test: best-effort
193
+ }
194
+ }
195
+
196
+ /**
197
+ * On Windows, restrict a profile path's ACL to the owner + trusted OS
198
+ * principals only. Every Allow ACE must belong to the owner SID,
199
+ * BUILTIN\Administrators (S-1-5-32-544), or NT AUTHORITY\SYSTEM (S-1-5-18).
200
+ * Any other Allow ACE (another user, Everyone, Users, Authenticated Users,
201
+ * Guests, unknown SIDs, custom groups) fails closed.
202
+ *
203
+ * The security boundary protects against OTHER USERS on the same machine.
204
+ * It does NOT protect against a malicious local administrator or SYSTEM —
205
+ * those are trusted OS principals with OS-level access (take-ownership,
206
+ * SeBackupPrivilege, etc) that cannot be blocked via the DACL.
207
+ *
208
+ * On POSIX, chmod the path to `mode` (best-effort in dev, fail-closed in prod).
209
+ */
210
+ function _applyPerms(target, mode) {
211
+ if (IS_WIN) {
212
+ _applyWindowsAcl(target);
213
+ return;
214
+ }
215
+ try {
216
+ fs.chmodSync(target, mode);
217
+ } catch (err) {
218
+ if (_isProd()) {
219
+ throw new ProfileIdentityError(
220
+ `chmod ${mode.toString(8)} failed in production: ${(err && err.message) || 'unknown'}`,
221
+ 'PROFILE_PERMS_FAILED',
222
+ );
223
+ }
224
+ // dev: best-effort
225
+ }
226
+ }
227
+
228
+ function _applyWindowsAcl(target) {
229
+ const { enforce } = _windowsAclPolicy();
230
+ if (!enforce) return;
231
+
232
+ // Resolve the current user's SID structurally (not by localized username).
233
+ const ownerSidResult = spawnSync('powershell', [
234
+ '-NoProfile', '-NonInteractive', '-Command',
235
+ '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
236
+ ], { windowsHide: true, encoding: 'utf8' });
237
+ if (ownerSidResult.status !== 0 || !ownerSidResult.stdout.trim()) {
238
+ throw new ProfileIdentityError('cannot resolve current user SID for ACL verification', 'PROFILE_ACL_NO_USER');
239
+ }
240
+ const ownerSid = ownerSidResult.stdout.trim();
241
+
242
+ let isDir = false;
243
+ try { isDir = fs.statSync(target).isDirectory(); } catch { /* treat as file */ }
244
+
245
+ // ALLOWLIST: only these SIDs may have Allow ACEs on the profile path.
246
+ // Owner SID + trusted OS principals. Everything else fails closed.
247
+ const allowedSids = new Set([
248
+ ownerSid,
249
+ 'S-1-5-32-544', // BUILTIN\Administrators
250
+ 'S-1-5-18', // NT AUTHORITY\SYSTEM
251
+ ]);
252
+
253
+ // Step 1: Reset inheritance and grant owner + trusted OS principals.
254
+ // Use PowerShell .NET to build a fresh protected DACL from scratch.
255
+ // PS 5.1 doesn't support comma-separated enum values via ::, so use -bor.
256
+ const inhFlagsExpr = isDir
257
+ ? '[System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit'
258
+ : '[System.Security.AccessControl.InheritanceFlags]::None';
259
+ const applyScript = `
260
+ $ErrorActionPreference = 'Stop'
261
+ $path = '${target.replace(/'/g, "''")}'
262
+ $ownerSid = '${ownerSid}'
263
+ $inhFlags = ${inhFlagsExpr}
264
+ $propFlags = [System.Security.AccessControl.PropagationFlags]::None
265
+ $colRights = [System.Security.AccessControl.FileSystemRights]::FullControl
266
+
267
+ # Create a fresh protected DACL (disable inheritance, no copy)
268
+ $acl = New-Object System.Security.AccessControl.${isDir ? 'DirectorySecurity' : 'FileSecurity'}
269
+ $acl.SetAccessRuleProtection($true, $false)
270
+
271
+ # Owner: full control
272
+ $ownerRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
273
+ (New-Object System.Security.Principal.SecurityIdentifier($ownerSid)),
274
+ $colRights, $inhFlags, $propFlags,
275
+ [System.Security.AccessControl.AccessControlType]::Allow)
276
+ $acl.AddAccessRule($ownerRule)
277
+
278
+ # Administrators: full control (trusted OS principal)
279
+ $adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
280
+ (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')),
281
+ $colRights, $inhFlags, $propFlags,
282
+ [System.Security.AccessControl.AccessControlType]::Allow)
283
+ $acl.AddAccessRule($adminRule)
284
+
285
+ # SYSTEM: full control (trusted OS principal)
286
+ $systemRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
287
+ (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')),
288
+ $colRights, $inhFlags, $propFlags,
289
+ [System.Security.AccessControl.AccessControlType]::Allow)
290
+ $acl.AddAccessRule($systemRule)
291
+
292
+ # Apply the fresh DACL (instance method — works in PS 5.1+ without extra assemblies)
293
+ (Get-Item -LiteralPath $path).SetAccessControl($acl)
294
+ `;
295
+ const applyResult = spawnSync('powershell', [
296
+ '-NoProfile', '-NonInteractive', '-Command', applyScript,
297
+ ], { windowsHide: true, encoding: 'utf8' });
298
+
299
+ if (applyResult.status !== 0) {
300
+ // Fallback: icacls (may not fully clear the DACL on Windows Server 2025)
301
+ const user = os.userInfo().username;
302
+ const grant = isDir ? `${user}:(OI)(CI)F` : `${user}:F`;
303
+ const icaclsApply = spawnSync('icacls', [target, '/inheritance:r', '/grant:r', grant], { windowsHide: true });
304
+ if (icaclsApply.status !== 0) {
305
+ throw new ProfileIdentityError(
306
+ 'failed to restrict the Windows ACL (both .NET and icacls apply failed)',
307
+ 'PROFILE_ACL_APPLY_FAILED',
308
+ );
309
+ }
310
+ }
311
+
312
+ // Step 2: VERIFY the resulting ACL using an ALLOWLIST (not blocklist).
313
+ // Every Allow ACE must belong to the owner SID, Administrators, or SYSTEM.
314
+ // Any other Allow ACE (another user, unknown SID, Everyone, Users, etc.)
315
+ // fails closed with PROFILE_ACL_LEAK.
316
+ const verifyScript = `
317
+ $ErrorActionPreference = 'Stop'
318
+ $path = '${target.replace(/'/g, "''")}'
319
+ $item = Get-Item -LiteralPath $path
320
+ $acl = $item.GetAccessControl()
321
+ $allRules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
322
+ $allowed = @(
323
+ '${ownerSid}',
324
+ 'S-1-5-32-544',
325
+ 'S-1-5-18'
326
+ )
327
+ $leaked = @()
328
+ $ownerHasAccess = $false
329
+ foreach ($rule in $allRules) {
330
+ $sid = $rule.IdentityReference.Value
331
+ if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow) {
332
+ if ($allowed -notcontains $sid) {
333
+ $leaked += $sid
334
+ }
335
+ if ($sid -eq '${ownerSid}') { $ownerHasAccess = $true }
336
+ }
337
+ }
338
+ $result = @{
339
+ leaked = ($leaked -join '|')
340
+ ownerHasAccess = $ownerHasAccess
341
+ }
342
+ $result | ConvertTo-Json -Compress
343
+ `;
344
+ const verifyResult = spawnSync('powershell', [
345
+ '-NoProfile', '-NonInteractive', '-Command', verifyScript,
346
+ ], { windowsHide: true, encoding: 'utf8' });
347
+
348
+ if (verifyResult.status !== 0) {
349
+ if (_isProd()) {
350
+ throw new ProfileIdentityError(
351
+ 'failed to verify the profile Windows ACL (.NET API failed in production)',
352
+ 'PROFILE_ACL_VERIFY_FAILED',
353
+ );
354
+ }
355
+ // dev/test: best-effort — skip verification if PowerShell unavailable
356
+ return;
357
+ }
358
+
359
+ // Parse the JSON result
360
+ let verifyData;
361
+ try {
362
+ verifyData = JSON.parse(verifyResult.stdout.trim());
363
+ } catch {
364
+ if (_isProd()) {
365
+ throw new ProfileIdentityError(
366
+ 'failed to parse ACL verification result (invalid JSON from PowerShell)',
367
+ 'PROFILE_ACL_VERIFY_FAILED',
368
+ );
369
+ }
370
+ return;
371
+ }
372
+
373
+ // Check: no leaked (non-allowlisted) Allow ACEs
374
+ const leakedSids = (verifyData.leaked || '').split('|').filter(Boolean);
375
+ if (leakedSids.length > 0) {
376
+ throw new ProfileIdentityError(
377
+ `Windows ACL verification failed: non-allowlisted Allow ACE(s) for SID(s): ${leakedSids.join(', ')}`,
378
+ 'PROFILE_ACL_LEAK',
379
+ );
380
+ }
381
+
382
+ // Check: owner has access
383
+ if (verifyData.ownerHasAccess !== true) {
384
+ throw new ProfileIdentityError(
385
+ 'Windows ACL verification failed: profile owner has no Allow ACE on the profile path',
386
+ 'PROFILE_ACL_OWNER_MISSING',
387
+ );
388
+ }
389
+ }
390
+
391
+ /**
392
+ * Atomic JSON write with fsync (temp + fsync + rename), fail-closed fsync in
393
+ * production. Used for the migration journal + quarantine sidecar. Phase 7-8:
394
+ * on any failure the temp file is unlinked so a crashed/failed write never
395
+ * leaves a stray `.<name>.tmp.*` on disk.
396
+ */
397
+ function _atomicWriteJson(filePath, value) {
398
+ const dir = path.dirname(filePath);
399
+ fs.mkdirSync(dir, { recursive: true });
400
+ const tmp = path.join(dir, '.' + path.basename(filePath) + '.tmp.' + crypto.randomBytes(6).toString('hex'));
401
+ let renamed = false;
402
+ try {
403
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600 });
404
+ _fsyncPath(tmp, 'file');
405
+ fs.renameSync(tmp, filePath);
406
+ renamed = true;
407
+ } catch (e) {
408
+ try { if (!renamed && fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* best-effort */ }
409
+ throw e;
410
+ }
411
+ if (!IS_WIN) { try { fs.chmodSync(filePath, 0o600); } catch { /* best-effort */ } } // eslint-disable-line no-empty
412
+ }
413
+
414
+ /**
415
+ * Append a structured migration / quarantine journal entry (Phase 19). The
416
+ * journal is an append-only array at <profilesDir>/migration-journal.json,
417
+ * written atomically + fsync'd so a crash mid-migration leaves a recoverable
418
+ * audit record.
419
+ *
420
+ * Phase 9 — fail closed in PRODUCTION: the journal is an AUDIT record of a
421
+ * security event (a migration, a quarantine, a quarantine FAILURE), not a
422
+ * diagnostic. A journal write failure must NEVER be silently swallowed in
423
+ * production — that would let a security event go unrecorded while the code
424
+ * behaves as if it was journaled (rule: never claim a journal exists when its
425
+ * write failed). So in production a journal write failure THROWS
426
+ * PROFILE_JOURNAL_FAILED, surfacing the audit gap instead of proceeding with an
427
+ * unjournaled event. In dev/test the journal stays best-effort so harnesses on
428
+ * filesystems that cannot honor fsync still run (mirroring the _fsyncPath /
429
+ * _applyPerms prod-only fail-closed pattern). The thrown message names only the
430
+ * event type + the underlying error — journal entries carry no secrets, so the
431
+ * message cannot leak a credential.
432
+ */
433
+ function _appendMigrationJournal(profilesDir, entry) {
434
+ if (!profilesDir) return;
435
+ try {
436
+ const jp = path.join(profilesDir, MIGRATION_JOURNAL);
437
+ let arr;
438
+ try { arr = JSON.parse(fs.readFileSync(jp, 'utf8')); } catch { arr = []; }
439
+ if (!Array.isArray(arr)) arr = [];
440
+ arr.push(Object.assign({ ts: new Date().toISOString() }, entry));
441
+ _atomicWriteJson(jp, arr);
442
+ } catch (e) {
443
+ if (_isProd()) {
444
+ throw new ProfileIdentityError(
445
+ `failed to append the migration journal entry${entry && entry.event ? ' ' + entry.event : ''}: ${(e && e.message) || 'unknown'}`,
446
+ 'PROFILE_JOURNAL_FAILED',
447
+ );
448
+ }
449
+ // dev/test: best-effort — never abort the operation on a dev filesystem.
450
+ }
451
+ }
452
+
453
+ function _journalQuarantine(profilesDir, q, dir, reason) {
454
+ _appendMigrationJournal(profilesDir, {
455
+ event: q ? 'quarantine' : 'quarantine.failed',
456
+ profile: path.basename(dir),
457
+ reason: reason || 'unknown',
458
+ ok: !!q,
459
+ });
460
+ }
461
+
462
+ // ── Legacy path derivation (schema-2 migration + account-<id> import only) ───
463
+
464
+ function serverKey(serverUrl) {
465
+ if (!serverUrl) throw new ProfileIdentityError('serverUrl is required to derive a legacy profile path', 'PROFILE_LEGACY_PATH_MISSING');
466
+ let normalized = String(serverUrl).trim().replace(/\/+$/, '');
467
+ try {
468
+ const u = new URL(normalized);
469
+ normalized = (u.host || normalized) + (u.pathname || '');
470
+ } catch { /* not a URL — hash as-is */ }
471
+ return 's' + crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
472
+ }
473
+
474
+ function userKey(userId) {
475
+ if (userId === undefined || userId === null || userId === '') {
476
+ throw new ProfileIdentityError('userId is required to derive a legacy profile path', 'PROFILE_LEGACY_PATH_MISSING');
477
+ }
478
+ return 'u' + String(userId);
479
+ }
480
+
481
+ function accountKey(accountUuid) {
482
+ if (!accountUuid || !UUID_RE.test(String(accountUuid))) {
483
+ // No `legacy-account-*` fallback: a profile is never keyed by a recyclable
484
+ // numeric id. The account UUID is a hard requirement.
485
+ throw new ProfileIdentityError('accountUuid is required to derive a profile path', 'PROFILE_IDENTITY_INCOMPLETE');
486
+ }
487
+ return String(accountUuid);
488
+ }
489
+
490
+ function legacyProfileDir(profilesDir, accountId) {
491
+ return path.join(profilesDir, `account-${accountId}`);
492
+ }
493
+
494
+ // ── Path / symlink containment ────────────────────────────────────────────────
495
+
496
+ /**
497
+ * Resolve `child` and assert it is contained under `root` (no `..` escape, no
498
+ * absolute jump, no symlink that resolves outside the root). Uses realpath so a
499
+ * symlink planted inside the profiles tree that points elsewhere is caught.
500
+ * Returns the resolved contained path, or throws ProfileIdentityError.
501
+ */
502
+ function _contain(root, child) {
503
+ const rootResolved = path.resolve(root);
504
+ const childResolved = path.resolve(rootResolved, child);
505
+ const rootWithSep = rootResolved + path.sep;
506
+ if (childResolved !== rootResolved && !childResolved.startsWith(rootWithSep)) {
507
+ throw new ProfileIdentityError('profile path escapes the profiles root', 'PROFILE_PATH_ESCAPE');
508
+ }
509
+ // Resolve the root through the filesystem too. A benign PARENT symlink
510
+ // (e.g. macOS /var -> /private/var) makes every descendant's realpath resolve
511
+ // under /private/var while the lexical root is under /var — comparing a
512
+ // descendant's realpath against the LEXICAL root would misclassify every
513
+ // profile as an escape. Comparing against the root's OWN realpath admits the
514
+ // benign case while still catching a symlink planted inside the tree that
515
+ // points OUT: its realpath is outside the resolved root. If the root does not
516
+ // exist yet, fall back to the lexical root (equivalent to the prior behavior).
517
+ let rootReal = rootResolved;
518
+ try { rootReal = fs.realpathSync(rootResolved); } catch { /* root not present yet */ }
519
+ const rootRealWithSep = rootReal + path.sep;
520
+ // Symlink containment: realpath each existing ancestor from the root down and
521
+ // ensure none resolves outside the (resolved) root. (The leaf dir may not exist yet.)
522
+ let cur = rootResolved;
523
+ const rel = path.relative(rootResolved, childResolved);
524
+ if (rel && rel !== '.') {
525
+ for (const seg of rel.split(path.sep)) {
526
+ cur = path.join(cur, seg);
527
+ if (fs.existsSync(cur)) {
528
+ let real;
529
+ try { real = fs.realpathSync(cur); } catch {
530
+ throw new ProfileIdentityError('profile path component is not resolvable', 'PROFILE_PATH_ESCAPE');
531
+ }
532
+ if (real !== rootReal && !real.startsWith(rootRealWithSep)) {
533
+ throw new ProfileIdentityError('profile path contains a symlink that escapes the profiles root', 'PROFILE_PATH_ESCAPE');
534
+ }
535
+ }
536
+ }
537
+ }
538
+ return childResolved;
539
+ }
540
+
541
+ // ── Marker (schema 4) ─────────────────────────────────────────────────────────
542
+
543
+ // Schema-4 integrity: the FULL identity tuple (incl. deviceUuid) is hashed. In
544
+ // schema 3 deviceUuid was NOT hashed, so a marker's deviceUuid could be rewritten
545
+ // by a different device and the integrity check still passed — the silent
546
+ // re-binding hole Phase 10 closes.
547
+ function _integrity(tuple) {
548
+ return crypto.createHash('sha256').update([tuple.serverUuid, tuple.tenantUuid, tuple.accountUuid, tuple.deviceUuid].join('|')).digest('hex');
549
+ }
550
+
551
+ // Schema-3 integrity (legacy, for the schema-3 → schema-4 migration ONLY): hashed
552
+ // server/tenant/account, NOT deviceUuid — the old formula a schema-3 marker was
553
+ // written with.
554
+ function _integrityV3(tuple) {
555
+ return crypto.createHash('sha256').update([tuple.serverUuid, tuple.tenantUuid, tuple.accountUuid].join('|')).digest('hex');
556
+ }
557
+
558
+ // A marker matches the requested tuple ONLY when ALL four UUIDs match — incl.
559
+ // deviceUuid. A dir stamped by a different device fails the match and is
560
+ // quarantined rather than re-bound (Phase 10).
561
+ function _markerMatches(marker, tuple) {
562
+ return !!marker
563
+ && marker.serverUuid === tuple.serverUuid
564
+ && marker.tenantUuid === tuple.tenantUuid
565
+ && marker.accountUuid === tuple.accountUuid
566
+ && marker.deviceUuid === tuple.deviceUuid;
567
+ }
568
+
569
+ /**
570
+ * Parse raw marker text into a verified schema-4 marker object, or null. Shared
571
+ * by readMarkerState (on-disk) and the pre-rename temp verify (Phase 7-8) so the
572
+ * two checks cannot drift apart.
573
+ */
574
+ function _parseMarkerContent(raw) {
575
+ let data;
576
+ try { data = JSON.parse(raw); }
577
+ catch { return null; }
578
+ if (!data || data.schema !== SCHEMA
579
+ || typeof data.serverUuid !== 'string' || typeof data.tenantUuid !== 'string'
580
+ || typeof data.accountUuid !== 'string' || typeof data.deviceUuid !== 'string') {
581
+ return null;
582
+ }
583
+ // Integrity: the recorded tuple must hash to the recorded integrity value.
584
+ if (data.integrity !== _integrity(data)) return null;
585
+ return data;
586
+ }
587
+
588
+ /**
589
+ * Read the schema-4 marker state from a profile dir.
590
+ * 'absent' : no identity.json
591
+ * 'corrupt' : present but unparseable, not schema 4, missing the tuple, or the
592
+ * integrity hash does not match the recorded tuple (tampered)
593
+ * 'ok' : a verified schema-4 marker
594
+ */
595
+ function readMarkerState(dir) {
596
+ const p = path.join(dir, IDENTITY_FILE);
597
+ if (!fs.existsSync(p)) return { state: 'absent', marker: null };
598
+ let raw;
599
+ try { raw = fs.readFileSync(p, 'utf8'); }
600
+ catch { return { state: 'corrupt', marker: null }; }
601
+ const data = _parseMarkerContent(raw);
602
+ if (!data) return { state: 'corrupt', marker: null };
603
+ return { state: 'ok', marker: data };
604
+ }
605
+
606
+ /** Public helper: the verified schema-3 marker for a dir, or null. */
607
+ function readIdentityMarker(dir) {
608
+ const { state, marker } = readMarkerState(dir);
609
+ return state === 'ok' ? marker : null;
610
+ }
611
+
612
+ /**
613
+ * Best-effort restore of a previous valid marker's raw bytes after a failed
614
+ * re-write (Phase 7-8). Plain write — no perm re-apply / fsync — so this
615
+ * recovery path cannot itself trip the ACL/fsync failure that aborted the
616
+ * original write. Never throws: the caller's throw already signals the failure;
617
+ * this just leaves the dir with its previous good marker instead of a bad/absent
618
+ * one.
619
+ */
620
+ function _restoreMarkerRaw(finalPath, raw) {
621
+ try { fs.writeFileSync(finalPath, raw, { encoding: 'utf8', mode: 0o600 }); } catch { /* best-effort */ }
622
+ }
623
+
624
+ /**
625
+ * Write a schema-4 marker DURABLY and VERIFY it on disk (re-read + schema +
626
+ * integrity check). Preserves `createdAt` from an existing matching marker.
627
+ *
628
+ * Durability (Phase 12, hardened Phase 17):
629
+ * 1. write to a temp file (a crash never leaves a half-written final marker);
630
+ * 2. fsync the temp FILE — FAIL CLOSED in production if it cannot be flushed;
631
+ * 3. PRE-RENAME verify the temp content (Phase 7-8): parse + schema + integrity
632
+ * + tuple match BEFORE the temp replaces the final marker, so a bad write
633
+ * never clobbers an existing good marker;
634
+ * 4. atomic rename temp -> final (the final marker appears whole or not at all);
635
+ * 5. fsync the parent DIRECTORY (the rename / dir-entry update is persisted) —
636
+ * fail closed in production on POSIX; best-effort on Windows where dir fsync
637
+ * is unsupported;
638
+ * 6. re-read + schema + integrity VALIDATE the on-disk marker.
639
+ *
640
+ * Phase 7-8 — preserve the previous valid marker + temp cleanup on failure:
641
+ * - Before the destructive rename, the raw bytes of any existing VALID marker
642
+ * matching the tuple are captured. If the re-write fails AFTER the rename
643
+ * (post-rename verify, perms, or dir fsync in production), the previous valid
644
+ * marker is RESTORED so a later recycled id is never mis-read against a
645
+ * bad/absent marker. If there was no previous valid marker, the unverified
646
+ * new marker is removed instead of left behind.
647
+ * - On ANY failure the temp file is unlinked (a crashed/failed write never
648
+ * leaves a stray `.identity.json.tmp.*` on disk).
649
+ *
650
+ * Restrictive perms (Phase 12, hardened Phase 18): the profile dir is 0o700 and
651
+ * the marker file is 0o600 so other local users cannot read the profile identity
652
+ * / cookies. On Windows this is enforced + VERIFIED via icacls (remove inherited
653
+ * ACEs, grant only the current user; re-read the ACL and fail closed if a broad
654
+ * principal retains access) — chmod is a no-op on Windows, so without this the
655
+ * profile was effectively world-readable on Windows. On POSIX chmod is fail-
656
+ * closed in production.
657
+ *
658
+ * Throws PROFILE_MARKER_UNVERIFIED if the written marker does not verify, or
659
+ * PROFILE_MARKER_FSYNC_FAILED / PROFILE_ACL_* if durability or permissions
660
+ * cannot be verified in production — never leave an unverified / under-protected
661
+ * marker that a later recycled id could be mis-read against.
662
+ */
663
+ function writeIdentityMarker(dir, tuple, options = {}) {
664
+ const existing = readIdentityMarker(dir);
665
+ const final = path.join(dir, IDENTITY_FILE);
666
+ // Phase 7-8: capture the previous VALID marker's raw bytes (only a marker that
667
+ // is currently ok AND matches the requested tuple is worth restoring). This
668
+ // read happens BEFORE any write, so it is the untouched previous marker.
669
+ let prevRaw = null;
670
+ if (existing && _markerMatches(existing, tuple)) {
671
+ try { prevRaw = fs.readFileSync(final, 'utf8'); } catch { prevRaw = null; }
672
+ }
673
+ const now = new Date().toISOString();
674
+ const marker = {
675
+ schema: SCHEMA,
676
+ serverUuid: tuple.serverUuid,
677
+ tenantUuid: tuple.tenantUuid,
678
+ accountUuid: tuple.accountUuid,
679
+ deviceUuid: tuple.deviceUuid,
680
+ createdAt: (existing && existing.createdAt) || now,
681
+ lastUsed: now,
682
+ agentVersion: options.agentVersion != null ? options.agentVersion : AGENT_VERSION,
683
+ integrity: _integrity(tuple),
684
+ };
685
+ // 0o700: only the owning user may traverse/read the profile dir.
686
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
687
+ _applyPerms(dir, 0o700);
688
+ const tmp = path.join(dir, '.' + IDENTITY_FILE + '.tmp.' + crypto.randomBytes(6).toString('hex'));
689
+ let renamed = false;
690
+ try {
691
+ // 1. write to a temp file with restrictive perms (0o600 — no group/other read).
692
+ fs.writeFileSync(tmp, JSON.stringify(marker, null, 2), { encoding: 'utf8', mode: 0o600 });
693
+ // 2. fsync the temp file's contents (fail closed in production).
694
+ _fsyncPath(tmp, 'file');
695
+ // 3. PRE-RENAME verify the temp content (the final marker is still the old
696
+ // one, so a bad temp never destroys a good marker).
697
+ const tmpMarker = _parseMarkerContent(fs.readFileSync(tmp, 'utf8'));
698
+ if (!tmpMarker || !_markerMatches(tmpMarker, tuple)) {
699
+ throw new ProfileIdentityError('the identity marker did not verify before rename', 'PROFILE_MARKER_UNVERIFIED');
700
+ }
701
+ // 4. atomic rename temp -> final (rename preserves the 0o600 mode).
702
+ fs.renameSync(tmp, final);
703
+ renamed = true;
704
+ _applyPerms(final, 0o600);
705
+ // 5. fsync the parent directory so the rename (dir-entry update) is durable.
706
+ _fsyncPath(dir, 'dir');
707
+ // 6. re-read + validate the on-disk marker.
708
+ const verify = readMarkerState(dir);
709
+ if (verify.state !== 'ok' || !_markerMatches(verify.marker, tuple)) {
710
+ throw new ProfileIdentityError('the written identity marker did not verify on disk', 'PROFILE_MARKER_UNVERIFIED');
711
+ }
712
+ } catch (e) {
713
+ // Phase 7-8: never leave a stray temp marker file on a failed write.
714
+ try { if (!renamed && fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* best-effort */ }
715
+ // Phase 7-8: if the rename already replaced the final marker, restore the
716
+ // previous valid marker (or, if there was none, remove the unverified new
717
+ // one) so the dir is never left with a bad marker a recycled id could be
718
+ // mis-read against.
719
+ if (renamed) {
720
+ if (prevRaw !== null) _restoreMarkerRaw(final, prevRaw);
721
+ else { try { fs.unlinkSync(final); } catch { /* best-effort */ } }
722
+ }
723
+ throw e;
724
+ }
725
+ }
726
+
727
+ // ── Quarantine ────────────────────────────────────────────────────────────────
728
+
729
+ function quarantineDir(dir, reason) {
730
+ if (!fs.existsSync(dir)) return null;
731
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
732
+ const q = `${dir}.quarantine-${stamp}`;
733
+ try {
734
+ fs.renameSync(dir, q);
735
+ } catch {
736
+ try { fs.renameSync(dir, `${dir}.corrupt-${stamp}`); return `${dir}.corrupt-${stamp}`; }
737
+ catch { return null; }
738
+ }
739
+ // Phase 19: a durable, fsync'd QUARANTINE.json sidecar (was a plain
740
+ // writeFileSync — not atomic, not fsync'd). Best-effort: a sidecar write
741
+ // failure must never abort a quarantine.
742
+ try {
743
+ _atomicWriteJson(path.join(q, 'QUARANTINE.json'), { reason: reason || 'unknown', quarantinedAt: new Date().toISOString() });
744
+ } catch { /* best-effort */ } // eslint-disable-line no-empty
745
+ return q;
746
+ }
747
+
748
+ /**
749
+ * Quarantine an UNTRUSTED dir and FAIL CLOSED if it cannot be moved aside
750
+ * (Phase 11 — rule 22 "never trust an unmarked profile"). A bad dir that cannot
751
+ * be quarantined must NEVER be stamped with a fresh marker over its existing
752
+ * (untrusted) data — that would silently adopt the data. Returns the quarantine
753
+ * path, or null if there was nothing to quarantine. Throws
754
+ * PROFILE_QUARANTINE_FAILED if the dir exists but neither rename succeeds.
755
+ * Phase 19: the outcome (success OR failure) is journaled to the migration
756
+ * journal so a quarantine failure is never silent.
757
+ */
758
+ function _requireQuarantine(dir, reason, profilesDir) {
759
+ if (!fs.existsSync(dir)) return null;
760
+ const q = quarantineDir(dir, reason);
761
+ if (!q) {
762
+ _appendMigrationJournal(profilesDir, { event: 'quarantine.failed', profile: path.basename(dir), reason: reason || 'unknown', ok: false });
763
+ throw new ProfileIdentityError(
764
+ `failed to quarantine an untrusted profile dir; refusing to stamp a marker over it: ${reason || 'unknown'}`,
765
+ 'PROFILE_QUARANTINE_FAILED',
766
+ );
767
+ }
768
+ _appendMigrationJournal(profilesDir, { event: 'quarantine', profile: path.basename(dir), reason: reason || 'unknown', ok: true });
769
+ return q;
770
+ }
771
+
772
+ function copyDirSync(src, dst) {
773
+ fs.mkdirSync(dst, { recursive: true });
774
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
775
+ const s = path.join(src, entry.name);
776
+ const d = path.join(dst, entry.name);
777
+ if (entry.isDirectory()) copyDirSync(s, d);
778
+ else fs.copyFileSync(s, d);
779
+ }
780
+ }
781
+
782
+ function dirExists(p) {
783
+ try { return fs.existsSync(p) && fs.statSync(p).isDirectory(); } catch { return false; }
784
+ }
785
+
786
+ // ── Legacy marker readers (migration only) ────────────────────────────────────
787
+
788
+ // Schema-1/2 marker reader (accountUuid only) — used by the schema-2 → schema-4
789
+ // migration.
790
+ function _readLegacyMarker(dir) {
791
+ const p = path.join(dir, IDENTITY_FILE);
792
+ if (!fs.existsSync(p)) return { state: 'absent', marker: null };
793
+ let raw;
794
+ try { raw = fs.readFileSync(p, 'utf8'); } catch { return { state: 'corrupt', marker: null }; }
795
+ let data;
796
+ try { data = JSON.parse(raw); } catch { return { state: 'corrupt', marker: null }; }
797
+ if (!data || typeof data.accountUuid !== 'string') return { state: 'corrupt', marker: null };
798
+ return { state: 'ok', marker: data };
799
+ }
800
+
801
+ // Schema-3 marker reader — used by the schema-3 → schema-4 migration ONLY.
802
+ // Validates against the OLD (deviceUuid-less) integrity formula. A schema-3
803
+ // marker is NEVER trusted as a current marker: readMarkerState (schema-4) reads
804
+ // it as 'corrupt'. This reader exists solely to decide whether a 3-level
805
+ // profile belongs to the requesting device and may be migrated forward.
806
+ function _readSchema3Marker(dir) {
807
+ const p = path.join(dir, IDENTITY_FILE);
808
+ if (!fs.existsSync(p)) return { state: 'absent', marker: null };
809
+ let raw;
810
+ try { raw = fs.readFileSync(p, 'utf8'); } catch { return { state: 'corrupt', marker: null }; }
811
+ let data;
812
+ try { data = JSON.parse(raw); } catch { return { state: 'corrupt', marker: null }; }
813
+ if (!data || data.schema !== SCHEMA_V3
814
+ || typeof data.serverUuid !== 'string' || typeof data.tenantUuid !== 'string'
815
+ || typeof data.accountUuid !== 'string' || typeof data.deviceUuid !== 'string') {
816
+ return { state: 'corrupt', marker: null };
817
+ }
818
+ if (data.integrity !== _integrityV3(data)) return { state: 'corrupt', marker: null };
819
+ return { state: 'ok', marker: data };
820
+ }
821
+
822
+ /**
823
+ * Move a schema-3 namespaced profile (3-level path
824
+ * `<profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/`) into the device-
825
+ * scoped schema-4 path (`.../<accountUuid>/<deviceUuid>/`), preserving its data,
826
+ * ONLY when the schema-3 marker's tuple — INCLUDING deviceUuid — matches the
827
+ * requesting device. A profile whose schema-3 marker was stamped by a DIFFERENT
828
+ * device is LEFT UNTOUCHED (never re-bound); the requesting device gets a fresh
829
+ * profile. A missing/corrupt schema-3 marker is also left untouched. Returns
830
+ * true if a migration happened.
831
+ */
832
+ function _migrateFromSchema3(profilesDir, newBase, tuple) {
833
+ let oldBase;
834
+ try {
835
+ oldBase = _contain(profilesDir, path.join(tuple.serverUuid, tuple.tenantUuid, tuple.accountUuid));
836
+ } catch {
837
+ return false; // no 3-level identity to migrate from
838
+ }
839
+ if (!fs.existsSync(oldBase) || path.resolve(oldBase) === path.resolve(newBase)) return false;
840
+ const { state, marker } = _readSchema3Marker(oldBase);
841
+ if (state !== 'ok' || !marker
842
+ || marker.serverUuid !== tuple.serverUuid || marker.tenantUuid !== tuple.tenantUuid
843
+ || marker.accountUuid !== tuple.accountUuid || marker.deviceUuid !== tuple.deviceUuid) {
844
+ return false; // belongs to another device / unmarked / corrupt — leave it
845
+ }
846
+ // newBase (<s>/<t>/<a>/<d>) is a SUBDIRECTORY of oldBase (<s>/<t>/<a>), so a
847
+ // direct rename into itself is impossible. Move oldBase aside to a sibling
848
+ // staging path, recreate the (now empty) account dir, then move the profile
849
+ // into the device-scoped subdir. All on one filesystem under profilesDir →
850
+ // atomic renames; on any failure, restore oldBase from staging and abort
851
+ // (this device gets a fresh profile instead).
852
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
853
+ const staging = `${oldBase}.migrating-${stamp}`;
854
+ try {
855
+ fs.renameSync(oldBase, staging);
856
+ fs.mkdirSync(oldBase, { recursive: true });
857
+ fs.renameSync(staging, newBase);
858
+ } catch {
859
+ try { if (fs.existsSync(staging) && !fs.existsSync(oldBase)) fs.renameSync(staging, oldBase); } catch { /* leave staging for inspection */ }
860
+ _appendMigrationJournal(profilesDir, { event: 'migrate.schema3', result: 'failed', stage: 'move', profile: path.basename(newBase) });
861
+ return false;
862
+ }
863
+ try {
864
+ writeIdentityMarker(newBase, tuple); // upgrade to schema-4, device-bound integrity
865
+ } catch {
866
+ const q = quarantineDir(newBase, 'schema-4 marker failed to verify after schema-3 migration');
867
+ _journalQuarantine(profilesDir, q, newBase, 'schema-4 marker failed to verify after schema-3 migration');
868
+ _appendMigrationJournal(profilesDir, { event: 'migrate.schema3', result: 'failed', stage: 'marker-verify', profile: path.basename(newBase) });
869
+ return false;
870
+ }
871
+ _appendMigrationJournal(profilesDir, { event: 'migrate.schema3', result: 'success', profile: path.basename(newBase) });
872
+ return true;
873
+ }
874
+
875
+ /**
876
+ * Resolve the profile directory for a session under the strict schema-4 identity.
877
+ *
878
+ * Returns { dir, migrated, fresh, quarantined }.
879
+ *
880
+ * @param {object} args
881
+ * @param {string} args.profilesDir profiles root
882
+ * @param {string} args.serverUuid immutable backend UUID (REQUIRED)
883
+ * @param {string} args.tenantUuid immutable tenant UUID (REQUIRED)
884
+ * @param {string} args.accountUuid immutable account UUID (REQUIRED)
885
+ * @param {string} args.deviceUuid immutable device UUID (REQUIRED)
886
+ * @param {string} [args.serverUrl] legacy server URL (schema-2 migration)
887
+ * @param {string|number} [args.userId] legacy numeric tenant id (schema-2 migration)
888
+ * @param {string|number} [args.accountId] legacy numeric account id (account-<id> import)
889
+ */
890
+ function resolveProfileDir(args) {
891
+ const { profilesDir, serverUuid, tenantUuid, accountUuid, deviceUuid, serverUrl, userId, accountId } = args || {};
892
+
893
+ // ── fail closed: every UUID is required, UUID-shaped, and the path is contained ──
894
+ const tuple = { serverUuid, tenantUuid, accountUuid, deviceUuid };
895
+ for (const [k, v] of Object.entries(tuple)) {
896
+ if (!v || typeof v !== 'string' || !UUID_RE.test(v)) {
897
+ throw new ProfileIdentityError(`profile identity is missing or malformed: ${k}`, 'PROFILE_IDENTITY_INCOMPLETE');
898
+ }
899
+ }
900
+ // Phase 10: deviceUuid is a PATH component — each device gets its own profile
901
+ // dir under the account, so a different device can never reuse this device's
902
+ // on-disk cookies/fingerprint even before the marker is consulted.
903
+ const base = _contain(profilesDir, path.join(serverUuid, tenantUuid, accountUuid, deviceUuid));
904
+
905
+ // Case 1: schema-4 dir already exists.
906
+ if (fs.existsSync(base)) {
907
+ const { state, marker } = readMarkerState(base);
908
+ if (state === 'ok' && _markerMatches(marker, tuple)) {
909
+ writeIdentityMarker(base, tuple); // reuse, refresh lastUsed
910
+ return { dir: base, migrated: false, fresh: false, quarantined: null, migrationRequired: false };
911
+ }
912
+ // Absent (unmarked), corrupt, or mismatched (incl. a different deviceUuid)
913
+ // → quarantine, never stamp-and-reuse and never re-bind to another device.
914
+ // If the bad dir CANNOT be moved aside, fail CLOSED — never stamp a marker
915
+ // over untrusted data (Phase 11).
916
+ const reason = state === 'absent'
917
+ ? 'unmarked profile dir — never adopt an unmarked dir'
918
+ : state === 'corrupt'
919
+ ? 'corrupt or tampered identity marker'
920
+ : `identity mismatch (marker server/tenant/account/device ≠ requested)`;
921
+ const q = _requireQuarantine(base, reason, profilesDir);
922
+ return { dir: _freshDir(base, tuple, profilesDir), migrated: false, fresh: true, quarantined: q, migrationRequired: false };
923
+ }
924
+
925
+ // Case 2: schema-4 dir absent → try a one-time schema-3 → schema-4 migration
926
+ // (device-bound: only a schema-3 profile whose deviceUuid matches this device).
927
+ if (_migrateFromSchema3(profilesDir, base, tuple)) {
928
+ return { dir: base, migrated: true, fresh: false, quarantined: null, migrationRequired: false };
929
+ }
930
+
931
+ // Case 3: try a one-time schema-2 → schema-4 migration.
932
+ const migrated = _migrateFromLegacy(profilesDir, base, tuple, { serverUrl, userId });
933
+ if (migrated) return { dir: base, migrated: true, fresh: false, quarantined: null, migrationRequired: false };
934
+
935
+ // Phase 15: NO automatic account-<id> import. A pre-hardening profile is never
936
+ // silently pulled into a new account (rule 21/22 — never trust an unmarked
937
+ // profile dir; never copy a legacy profile automatically). If one exists it is
938
+ // surfaced as `migrationRequired` so the owner can run the EXPLICIT, safeguarded
939
+ // import (importLegacyProfile). A fresh, empty profile is used meanwhile.
940
+ let migrationRequired = false;
941
+ if (accountId != null) {
942
+ const legacy = legacyProfileDir(profilesDir, accountId);
943
+ if (fs.existsSync(legacy) && fs.statSync(legacy).isDirectory()) {
944
+ migrationRequired = true;
945
+ }
946
+ }
947
+ return { dir: _freshDir(base, tuple, profilesDir), migrated: false, fresh: true, quarantined: null, migrationRequired };
948
+ }
949
+
950
+ function _freshDir(dir, tuple, profilesDir) {
951
+ // If a pre-existing dir is in the way, it MUST be quarantined (fail closed) —
952
+ // never stamp a fresh marker over untrusted existing data (Phase 11).
953
+ if (fs.existsSync(dir)) _requireQuarantine(dir, 'pre-existing dir cleared before fresh profile creation', profilesDir);
954
+ fs.mkdirSync(dir, { recursive: true });
955
+ writeIdentityMarker(dir, tuple);
956
+ return dir;
957
+ }
958
+
959
+ /**
960
+ * Move a schema-2 namespaced profile (`<profilesDir>/s<hash>/u<id>/<accountUuid>/`)
961
+ * into the new device-scoped schema-4 path (`<profilesDir>/<serverUuid>/<tenantUuid>/<accountUuid>/<deviceUuid>/`),
962
+ * preserving its data, ONLY when the legacy dir's marker accountUuid matches the
963
+ * requested account. A missing/corrupt/mismatched legacy marker is left untouched
964
+ * (never adopt an unverifiable dir). Returns true if a migration happened.
965
+ */
966
+ function _migrateFromLegacy(profilesDir, newBase, tuple, { serverUrl, userId }) {
967
+ let legacyBase;
968
+ try {
969
+ legacyBase = _contain(profilesDir, path.join(serverKey(serverUrl), userKey(userId), accountKey(tuple.accountUuid)));
970
+ } catch {
971
+ return false; // no legacy identity to migrate from
972
+ }
973
+ if (!fs.existsSync(legacyBase) || legacyBase === newBase) return false;
974
+ const { state, marker } = _readLegacyMarker(legacyBase);
975
+ if (state !== 'ok' || !marker || String(marker.accountUuid) !== String(tuple.accountUuid)) {
976
+ return false; // unverifiable or belongs to another account — leave it
977
+ }
978
+ try {
979
+ fs.mkdirSync(path.dirname(newBase), { recursive: true });
980
+ fs.renameSync(legacyBase, newBase);
981
+ } catch {
982
+ // rename can fail across volumes / on lock contention; fall back to a copy.
983
+ try {
984
+ copyDirSync(legacyBase, newBase);
985
+ } catch {
986
+ _appendMigrationJournal(profilesDir, { event: 'migrate.legacy', result: 'failed', stage: 'move', profile: path.basename(newBase) });
987
+ return false;
988
+ }
989
+ }
990
+ try {
991
+ writeIdentityMarker(newBase, tuple);
992
+ } catch {
993
+ // The data moved but the marker did not verify → quarantine rather than
994
+ // adopt an unmarked dir.
995
+ const q = quarantineDir(newBase, 'schema-3 marker failed to verify after migration');
996
+ _journalQuarantine(profilesDir, q, newBase, 'schema-3 marker failed to verify after migration');
997
+ _appendMigrationJournal(profilesDir, { event: 'migrate.legacy', result: 'failed', stage: 'marker-verify', profile: path.basename(newBase) });
998
+ return false;
999
+ }
1000
+ _appendMigrationJournal(profilesDir, { event: 'migrate.legacy', result: 'success', profile: path.basename(newBase) });
1001
+ return true;
1002
+ }
1003
+
1004
+ /**
1005
+ * List the pre-hardening `account-<id>` profile directories still living at the
1006
+ * profiles root (not yet namespaced under server/tenant/account/device UUIDs).
1007
+ * These are the dirs surfaced as migration_required and never adopted
1008
+ * automatically. Schema-4 dirs live under `<uuid>/<uuid>/<uuid>/<uuid>/` and
1009
+ * schema-2 dirs under `s<hash>/u<id>/`, so a bare `account-<digits>` entry at the
1010
+ * root is unambiguously a legacy dir. Quarantined / already-imported siblings
1011
+ * (`.quarantine-*`, `.imported-*`) are NOT listed.
1012
+ */
1013
+ function discoverLegacyProfiles(profilesDir) {
1014
+ const root = path.resolve(profilesDir);
1015
+ if (!dirExists(root)) return [];
1016
+ const out = [];
1017
+ let entries;
1018
+ try { entries = fs.readdirSync(root, { withFileTypes: true }); } catch { return []; }
1019
+ for (const ent of entries) {
1020
+ if (!ent.isDirectory()) continue;
1021
+ const m = /^account-(\d+)$/.exec(ent.name);
1022
+ if (m) out.push({ accountId: m[1], dir: path.join(root, ent.name) });
1023
+ }
1024
+ return out;
1025
+ }
1026
+
1027
+ /**
1028
+ * EXPLICIT, safeguarded import of a single pre-hardening `account-<id>` profile
1029
+ * into the device-scoped schema-4 namespaced path. This is the ONLY path by which
1030
+ * legacy data is pulled forward — resolveProfileDir never does it automatically
1031
+ * (Phase 15).
1032
+ *
1033
+ * Safeguards (rule 21/22/23): fail closed on any missing UUID; refuse if a
1034
+ * namespaced profile already exists for the account+device (conflict); copy into
1035
+ * a staging dir and verify the schema-4 marker BEFORE atomic promotion; on any
1036
+ * failure the original is left untouched; on success the original is renamed to
1037
+ * `account-<id>.imported-<ts>` (preserved, never deleted, and no longer reported
1038
+ * by discoverLegacyProfiles). Returns { dir, preservedOriginal }.
1039
+ *
1040
+ * @param {object} args
1041
+ * @param {string} args.profilesDir
1042
+ * @param {string|number} args.accountId legacy numeric account id (REQUIRED)
1043
+ * @param {string} args.serverUuid
1044
+ * @param {string} args.tenantUuid
1045
+ * @param {string} args.accountUuid
1046
+ * @param {string} args.deviceUuid
1047
+ */
1048
+ function importLegacyProfile(args) {
1049
+ const { profilesDir, accountId, serverUuid, tenantUuid, accountUuid, deviceUuid } = args || {};
1050
+ const tuple = { serverUuid, tenantUuid, accountUuid, deviceUuid };
1051
+ for (const [k, v] of Object.entries(tuple)) {
1052
+ if (!v || typeof v !== 'string' || !UUID_RE.test(v)) {
1053
+ throw new ProfileIdentityError(`legacy import requires a complete identity; missing or malformed: ${k}`, 'PROFILE_IDENTITY_INCOMPLETE');
1054
+ }
1055
+ }
1056
+ if (accountId == null || accountId === '') {
1057
+ throw new ProfileIdentityError('legacy import requires the legacy numeric accountId', 'PROFILE_LEGACY_IMPORT_MISSING_ID');
1058
+ }
1059
+ const legacy = legacyProfileDir(profilesDir, String(accountId));
1060
+ if (!dirExists(legacy)) {
1061
+ throw new ProfileIdentityError('no pre-hardening account-<id> profile exists to import', 'PROFILE_LEGACY_IMPORT_NO_SOURCE');
1062
+ }
1063
+
1064
+ const target = _contain(profilesDir, path.join(serverUuid, tenantUuid, accountUuid, deviceUuid));
1065
+
1066
+ // Conflict check: never overwrite an existing, verified namespaced profile.
1067
+ if (fs.existsSync(target) && readIdentityMarker(target)) {
1068
+ throw new ProfileIdentityError(
1069
+ 'a namespaced profile already exists for this account+device; refusing to overwrite — delete it first',
1070
+ 'PROFILE_LEGACY_IMPORT_CONFLICT',
1071
+ );
1072
+ }
1073
+
1074
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
1075
+ const staging = `${target}.importing-${stamp}`;
1076
+ const preserved = `${legacy}.imported-${stamp}`;
1077
+
1078
+ fs.mkdirSync(path.dirname(staging), { recursive: true });
1079
+ try {
1080
+ // 1. temp copy into staging (original untouched)
1081
+ copyDirSync(legacy, staging);
1082
+ // 2. write + verify the schema-4 marker on the staging dir (fails closed)
1083
+ writeIdentityMarker(staging, tuple);
1084
+ // 3. atomic promotion: clear any unmarked pre-existing target (fail CLOSED
1085
+ // if it cannot be quarantined — never overwrite untrusted data), then rename
1086
+ if (fs.existsSync(target)) _requireQuarantine(target, 'unmarked pre-existing dir cleared before legacy import promotion', profilesDir);
1087
+ fs.renameSync(staging, target);
1088
+ // 4. preserve the original (renamed aside, never deleted, no longer re-discovered)
1089
+ try { fs.renameSync(legacy, preserved); } catch { /* best-effort: data already promoted to target */ }
1090
+ } catch (e) {
1091
+ // Never leave a half-written staging dir; never touch the original on failure.
1092
+ try { fs.rmSync(staging, { recursive: true, force: true }); } catch { /* ignore */ }
1093
+ _appendMigrationJournal(profilesDir, { event: 'import.legacy', result: 'failed', account: String(accountId), error: (e && e.code) || 'unknown' });
1094
+ if (e instanceof ProfileIdentityError) throw e;
1095
+ throw new ProfileIdentityError(`legacy import failed: ${e.message}`, 'PROFILE_LEGACY_IMPORT_FAILED');
1096
+ }
1097
+ _appendMigrationJournal(profilesDir, { event: 'import.legacy', result: 'success', account: String(accountId), profile: path.basename(target) });
1098
+ return { dir: target, preservedOriginal: preserved };
1099
+ }
1100
+
1101
+ module.exports = {
1102
+ SCHEMA,
1103
+ ProfileIdentityError,
1104
+ serverKey,
1105
+ userKey,
1106
+ accountKey,
1107
+ legacyProfileDir,
1108
+ resolveProfileDir,
1109
+ discoverLegacyProfiles,
1110
+ importLegacyProfile,
1111
+ readIdentityMarker,
1112
+ readMarkerState,
1113
+ writeIdentityMarker,
1114
+ quarantineDir,
1115
+ // Phase 10: exported for ACL-policy config unit tests.
1116
+ windowsAclPolicy: _windowsAclPolicy,
1117
1117
  };