@cortexkit/opencode-antigravity-auth 3.0.41 → 3.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/cli.js +1186 -1179
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +99 -89
  4. package/dist/index.js +532 -456
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +105 -95
  7. package/dist/server.js +532 -456
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +13 -9
  11. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +33 -5
  12. package/dist/src/common-auth-embedded/routing-accessor/index.js +49 -7
  13. package/dist/src/common-auth-embedded/source-output.json +15 -15
  14. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  15. package/dist/src/plugin/request-helpers.d.ts +10 -0
  16. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  17. package/dist/src/plugin/request-helpers.js +6 -0
  18. package/dist/src/plugin/request-helpers.js.map +1 -1
  19. package/dist/src/plugin/shared/request-services.d.ts +8 -1
  20. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  21. package/dist/src/plugin/shared/request-services.js +39 -0
  22. package/dist/src/plugin/shared/request-services.js.map +1 -1
  23. package/dist/tui-build-map.json +1 -1
  24. package/dist/tui-ga-build-map.json +1 -1
  25. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +33 -5
  26. package/dist/types/src/plugin/request-helpers.d.ts +10 -0
  27. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  28. package/dist/types/src/plugin/shared/request-services.d.ts +8 -1
  29. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  30. package/package.json +2 -2
  31. package/src/common-auth-embedded/fs/refresh-file-lock.js +13 -9
  32. package/src/common-auth-embedded/routing-accessor/index.d.ts +33 -5
  33. package/src/common-auth-embedded/routing-accessor/index.js +49 -7
  34. package/src/common-auth-embedded/source-output.json +15 -15
package/dist/cli.js CHANGED
@@ -8770,657 +8770,1080 @@ var init_lock_record = __esm({
8770
8770
  }
8771
8771
  });
8772
8772
 
8773
- // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
8774
- import { randomUUID as randomUUID7 } from "node:crypto";
8775
- import { link as link2, lstat as lstat3, mkdir as mkdir7, open as open4, readdir, readFile as readFile5, rename as rename6, rm as rm4, stat as stat3, unlink as unlink6 } from "node:fs/promises";
8776
- import { basename as basename3, dirname as dirname7, join as join5 } from "node:path";
8777
- async function createExclusiveText(path2, text2) {
8778
- const tempPath = `${path2}.${randomUUID7()}.tmp`;
8779
- let handle;
8780
- try {
8781
- handle = await open4(tempPath, "wx", 384);
8782
- try {
8783
- if (leaseCreationTestHooks?.beforeWrite)
8784
- await leaseCreationTestHooks.beforeWrite(tempPath);
8785
- await handle.writeFile(text2, "utf8");
8786
- } finally {
8787
- await handle.close();
8773
+ // ../core/dist/common-auth-embedded/logger/capture-sink.js
8774
+ function createCaptureSink() {
8775
+ const records = [];
8776
+ const sink = (record3) => {
8777
+ records.push(record3);
8778
+ };
8779
+ return {
8780
+ records,
8781
+ sink,
8782
+ clear: () => {
8783
+ records.length = 0;
8784
+ }
8785
+ };
8786
+ }
8787
+ var init_capture_sink = __esm({
8788
+ "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
8789
+ "use strict";
8790
+ }
8791
+ });
8792
+
8793
+ // ../core/dist/common-auth-embedded/logger/redact.js
8794
+ function isError(value) {
8795
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
8796
+ }
8797
+ function createRedactor(options = {}) {
8798
+ const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
8799
+ function isSecretKey(key) {
8800
+ const normalized = key.toLowerCase().replace(/[-_]/g, "");
8801
+ return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
8802
+ }
8803
+ function errorEntries(error) {
8804
+ const fields2 = error;
8805
+ const entries = [
8806
+ ["name", error.name],
8807
+ ["message", error.message],
8808
+ ["stack", error.stack]
8809
+ ];
8810
+ for (const key of ["code", "status", "cause"])
8811
+ if (fields2[key] !== void 0)
8812
+ entries.push([key, fields2[key]]);
8813
+ const listed = new Set(entries.map(([key]) => key));
8814
+ for (const entry of Object.entries(error))
8815
+ if (!listed.has(entry[0]))
8816
+ entries.push(entry);
8817
+ return entries;
8818
+ }
8819
+ function walk(value, keys, seen, errorDepth = 0) {
8820
+ if (typeof value === "string") {
8821
+ return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
8788
8822
  }
8823
+ if (!value || typeof value !== "object")
8824
+ return value;
8825
+ if (seen.has(value))
8826
+ return "[Circular]";
8827
+ seen.add(value);
8789
8828
  try {
8790
- if (leaseCreationTestHooks?.beforeLink)
8791
- await leaseCreationTestHooks.beforeLink(tempPath, path2);
8792
- await link2(tempPath, path2);
8793
- } catch (error) {
8794
- const code2 = error.code;
8795
- if (code2 !== "EPERM" && code2 !== "ENOTSUP" && code2 !== "EOPNOTSUPP" && code2 !== "EXDEV")
8796
- throw error;
8797
- await writeExclusiveText(path2, text2);
8829
+ if (Array.isArray(value))
8830
+ return value.map((item) => walk(item, keys, seen, errorDepth));
8831
+ const error = isError(value);
8832
+ if (error && errorDepth >= MAX_ERROR_DEPTH)
8833
+ return "[Truncated]";
8834
+ const childDepth = error ? errorDepth + 1 : errorDepth;
8835
+ return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
8836
+ key,
8837
+ keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
8838
+ ]));
8839
+ } finally {
8840
+ seen.delete(value);
8798
8841
  }
8799
- } finally {
8800
- if (handle)
8801
- await rm4(tempPath, { force: true }).catch(() => {
8802
- });
8803
8842
  }
8843
+ return {
8844
+ redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
8845
+ // Schema keys describe arguments, not credentials; only their string values are scrubbed.
8846
+ redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
8847
+ };
8804
8848
  }
8805
- async function writeExclusiveText(path2, text2) {
8806
- const handle = await open4(path2, "wx", 384);
8807
- let createdStat;
8849
+ var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
8850
+ var init_redact = __esm({
8851
+ "../core/dist/common-auth-embedded/logger/redact.js"() {
8852
+ "use strict";
8853
+ SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
8854
+ TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
8855
+ MASK = "***REDACTED***";
8856
+ MAX_ERROR_DEPTH = 8;
8857
+ defaultRedactor = createRedactor();
8858
+ redact = defaultRedactor.redact;
8859
+ redactStrings = defaultRedactor.redactStrings;
8860
+ }
8861
+ });
8862
+
8863
+ // ../core/dist/common-auth-embedded/logger/engine.js
8864
+ import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
8865
+ import { open as open4 } from "node:fs/promises";
8866
+ import { dirname as dirname7, resolve as resolve4 } from "node:path";
8867
+ function chmodPrivate(path2) {
8808
8868
  try {
8809
- createdStat = await handle.stat();
8869
+ chmodSync(path2, 384);
8810
8870
  } catch {
8811
- createdStat = void 0;
8812
8871
  }
8872
+ }
8873
+ function rotateIfNeeded(f) {
8813
8874
  try {
8814
- if (leaseCreationTestHooks?.beforeWrite)
8815
- await leaseCreationTestHooks.beforeWrite(path2);
8816
- await handle.writeFile(text2, "utf8");
8817
- } catch (error) {
8818
- try {
8819
- const current = await lstat3(path2).catch(() => void 0);
8820
- if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
8821
- await rm4(path2, { force: true }).catch(() => {
8822
- });
8875
+ if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
8876
+ return;
8877
+ for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
8878
+ if (existsSync(`${f}.${i}`)) {
8879
+ const rotated2 = `${f}.${i + 1}`;
8880
+ renameSync(`${f}.${i}`, rotated2);
8881
+ chmodPrivate(rotated2);
8823
8882
  }
8824
- } catch {
8825
8883
  }
8826
- throw error;
8827
- } finally {
8828
- await handle.close();
8884
+ const rotated = `${f}.1`;
8885
+ renameSync(f, rotated);
8886
+ chmodPrivate(rotated);
8887
+ } catch {
8829
8888
  }
8830
8889
  }
8831
- function isStagingName(name, lockName) {
8832
- const prefix = `${lockName}.`;
8833
- const suffix = ".tmp";
8834
- if (!name.startsWith(prefix) || !name.endsWith(suffix))
8835
- return false;
8836
- return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
8890
+ async function closeWindowsFile(sink) {
8891
+ const { file, handle } = sink;
8892
+ sink.file = void 0;
8893
+ sink.handle = void 0;
8894
+ if (file && handle)
8895
+ await privateOperation(file, "log-close", () => handle.close());
8837
8896
  }
8838
- function sameStagingFile(a, b) {
8839
- return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
8897
+ async function openWindowsFile(sink, file) {
8898
+ await ensurePrivateDirectory(dirname7(file));
8899
+ try {
8900
+ await verifyPrivate(file, "file", true);
8901
+ } catch (error) {
8902
+ if (error.code !== "ENOENT")
8903
+ throw error;
8904
+ try {
8905
+ await createPrivateBytes(file, "");
8906
+ } catch (creationError) {
8907
+ if (creationError.code !== "EEXIST")
8908
+ throw creationError;
8909
+ await verifyPrivate(file, "file", true);
8910
+ }
8911
+ }
8912
+ sink.handle = await privateOperation(file, "log-open", () => open4(file, "a"));
8913
+ sink.file = file;
8914
+ return sink.handle;
8840
8915
  }
8841
- async function readStagedOwner(path2) {
8842
- const before = await lstat3(path2);
8843
- if (!before.isFile() || before.isSymbolicLink())
8844
- return void 0;
8845
- if (before.size > STAGING_SWEEP_MAX_BYTES)
8846
- return void 0;
8847
- const handle = await open4(path2, "r");
8848
- let text2;
8916
+ async function flushWindowsFile(sink, file, text2) {
8917
+ file = resolve4(file);
8849
8918
  try {
8850
- if (!sameStagingFile(before, await handle.stat()))
8851
- return void 0;
8852
- text2 = await handle.readFile("utf8");
8853
- } finally {
8854
- await handle.close();
8919
+ if (sink.file !== file)
8920
+ await closeWindowsFile(sink);
8921
+ let handle = sink.handle ?? await openWindowsFile(sink, file);
8922
+ const info = await privateOperation(file, "log-stat", () => handle.stat());
8923
+ if (info.size >= MAX_BYTES) {
8924
+ await closeWindowsFile(sink);
8925
+ for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
8926
+ const source = i === 0 ? file : `${file}.${i}`;
8927
+ const target = `${file}.${i + 1}`;
8928
+ try {
8929
+ await verifyPrivate(source, "file", true);
8930
+ } catch (error) {
8931
+ if (error.code === "ENOENT")
8932
+ continue;
8933
+ throw error;
8934
+ }
8935
+ try {
8936
+ await verifyPrivate(target, "file", true);
8937
+ } catch (error) {
8938
+ if (error.code !== "ENOENT")
8939
+ throw error;
8940
+ }
8941
+ await replaceWindowsFile(source, target);
8942
+ await verifyPrivate(target, "file");
8943
+ }
8944
+ handle = await openWindowsFile(sink, file);
8945
+ }
8946
+ await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
8947
+ } catch (error) {
8948
+ await closeWindowsFile(sink).catch(() => {
8949
+ });
8950
+ throw error;
8855
8951
  }
8856
- let record3;
8952
+ }
8953
+ function safeSerialize(data) {
8857
8954
  try {
8858
- record3 = JSON.parse(text2);
8955
+ return ` ${JSON.stringify(data)}`;
8859
8956
  } catch {
8860
- return void 0;
8957
+ return " [unserializable]";
8861
8958
  }
8862
- if (!record3 || typeof record3 !== "object" || Array.isArray(record3))
8863
- return void 0;
8864
- const keys = Object.keys(record3).sort();
8865
- if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
8866
- return void 0;
8867
- const { ownerId, expiresAt } = record3;
8868
- if (typeof ownerId !== "string" || !STAGING_UUID.test(ownerId))
8869
- return void 0;
8870
- if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
8871
- return void 0;
8872
- return { identity: before, expiresAt };
8873
8959
  }
8874
- async function sweepAbandonedStaging(lockPath, ttlMs, now) {
8875
- const directory = dirname7(lockPath);
8876
- const lockName = basename3(lockPath);
8877
- const hooks = stagingSweepTestHooks;
8878
- const names = await (hooks?.readdir ?? readdir)(directory);
8879
- const candidates = names.filter((name) => isStagingName(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES);
8880
- const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
8881
- for (const name of candidates) {
8882
- const path2 = join5(directory, name);
8883
- try {
8884
- if (now() - (await lstat3(path2)).mtimeMs < marginMs)
8885
- continue;
8886
- const staged = await readStagedOwner(path2);
8887
- if (!staged || !(staged.expiresAt < now() - marginMs))
8888
- continue;
8889
- if (hooks?.beforeUnlink)
8890
- await hooks.beforeUnlink(path2);
8891
- const current = await readStagedOwner(path2);
8892
- if (!current || !sameStagingFile(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
8893
- continue;
8894
- await (hooks?.unlink ?? unlink6)(path2);
8895
- } catch {
8896
- }
8960
+ function createEngine(options) {
8961
+ let logFileSource;
8962
+ let initLevelSource;
8963
+ let runtimeLevel;
8964
+ let redactor = createRedactor();
8965
+ let captureSink;
8966
+ let buffer = [];
8967
+ let timer;
8968
+ let orderedSink = Promise.resolve();
8969
+ let sinkError;
8970
+ const windowsFile = {};
8971
+ function queueWindows(operation) {
8972
+ const next = orderedSink.then(operation);
8973
+ orderedSink = next.catch((error) => {
8974
+ sinkError = error;
8975
+ });
8976
+ return next;
8897
8977
  }
8898
- }
8899
- function startStagingSweep(lockPath, ttlMs, now) {
8900
- if (sweptLockPaths.has(lockPath))
8901
- return;
8902
- sweptLockPaths.add(lockPath);
8903
- const sweep = Promise.resolve().then(() => sweepAbandonedStaging(lockPath, ttlMs, now)).catch(() => {
8904
- });
8905
- pendingStagingSweeps.add(sweep);
8906
- void sweep.finally(() => pendingStagingSweeps.delete(sweep));
8907
- }
8908
- function isLostMarkerRaceError(error) {
8909
- const code2 = error?.code;
8910
- return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
8911
- }
8912
- function sameMarkerDirectory(created, current) {
8913
- if (created.dev !== current.dev || created.ino !== current.ino)
8914
- return false;
8915
- if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
8916
- return false;
8917
- return true;
8918
- }
8919
- function acquireRefreshFileLock(options) {
8920
- return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
8921
- }
8922
- async function acquireRefreshFileLockWithClock(options) {
8923
- const lockPath = lockPathFor(options.path, options.name);
8924
- const legacyOwnerPath = join5(lockPath, "owner.json");
8925
- const ownerId = randomUUID7();
8926
- const now = options.now ?? Date.now;
8927
- let renewTimer = null;
8928
- let released = false;
8929
- let releaseConfirmed = false;
8930
- let loss;
8931
- let resolveLoss;
8932
- const lostPromise = new Promise((resolve24) => {
8933
- resolveLoss = resolve24;
8934
- });
8935
- function notifyTimerStep(event) {
8936
- try {
8937
- const result = options.onRenewalTimer?.(event);
8938
- if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
8939
- void Promise.resolve(result).catch(() => {
8940
- });
8941
- }
8942
- } catch {
8943
- }
8978
+ function configure(next) {
8979
+ if (windowsPrivateFiles && next.file !== logFileSource)
8980
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
8981
+ });
8982
+ logFileSource = next.file;
8983
+ initLevelSource = next.level;
8984
+ redactor = createRedactor(next);
8985
+ captureSink = next.captureSink;
8944
8986
  }
8945
- function cancelRenewalTimer() {
8946
- if (!renewTimer)
8947
- return;
8948
- clearRefreshLockRenewalTimeout(renewTimer);
8949
- renewTimer = null;
8950
- notifyTimerStep("cancelled");
8987
+ function setLogLevel3(l) {
8988
+ if (l === void 0 || l in ORDER)
8989
+ runtimeLevel = l;
8951
8990
  }
8952
- function recordLoss(reason, owner) {
8953
- if (loss || released)
8954
- return;
8955
- loss = Object.freeze({
8956
- reason,
8957
- expectedOwnerId: ownerId,
8958
- ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
8959
- ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
8960
- });
8961
- cancelRenewalTimer();
8962
- resolveLoss(loss);
8991
+ function logFilePath() {
8992
+ if (logFileSource === void 0)
8993
+ return void 0;
8994
+ const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
8995
+ return resolved || void 0;
8963
8996
  }
8964
- let terminalIOError;
8965
- let renewalInFlight = null;
8966
- const evictPath = `${lockPath}.evicting`;
8967
- const evictOwnerPath = join5(evictPath, "owner.json");
8968
- const evictOwnerId = randomUUID7();
8969
- const EVICT_TTL = 5e3;
8970
- const MAX_STEAL_ATTEMPTS = 8;
8971
- function isChangingLockCreate(error) {
8972
- return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
8997
+ function configuredLevel() {
8998
+ if (runtimeLevel)
8999
+ return runtimeLevel;
9000
+ const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
9001
+ if (floor && floor in ORDER)
9002
+ return floor;
9003
+ return "info";
8973
9004
  }
8974
- async function readOwner() {
8975
- if (windowsPrivateFiles) {
8976
- try {
8977
- return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
8978
- } catch (error) {
8979
- if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
8980
- throw error;
8981
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
8982
- return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
8983
- }
9005
+ function flushLogs3(close = true) {
9006
+ if (timer) {
9007
+ clearTimeout(timer);
9008
+ timer = void 0;
8984
9009
  }
9010
+ if (!buffer.length) {
9011
+ if (windowsPrivateFiles)
9012
+ return queueWindows(async () => {
9013
+ if (close)
9014
+ await closeWindowsFile(windowsFile);
9015
+ if (sinkError)
9016
+ throw sinkError;
9017
+ });
9018
+ return;
9019
+ }
9020
+ let file;
8985
9021
  try {
8986
- return JSON.parse(await readFile5(lockPath, "utf8"));
8987
- } catch (error) {
8988
- const code2 = error.code;
8989
- if (code2 !== "EISDIR")
8990
- throw error;
8991
- return JSON.parse(await readFile5(legacyOwnerPath, "utf8"));
9022
+ file = logFilePath();
9023
+ } catch {
9024
+ buffer = [];
9025
+ if (windowsPrivateFiles && close)
9026
+ return queueWindows(() => closeWindowsFile(windowsFile));
9027
+ return;
9028
+ }
9029
+ const text2 = buffer.join("");
9030
+ buffer = [];
9031
+ if (!file) {
9032
+ if (windowsPrivateFiles && close)
9033
+ return queueWindows(() => closeWindowsFile(windowsFile));
9034
+ return;
8992
9035
  }
8993
- }
8994
- async function writeOwner() {
8995
9036
  if (windowsPrivateFiles) {
8996
- const owner = await readOwner();
8997
- const remaining = Number(owner?.expiresAt) - now();
8998
- await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
8999
- `, {
9000
- deadline: performance.now() + Math.max(0, remaining),
9001
- beforeRename: async () => {
9002
- const current = await readOwner();
9003
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9004
- throw new LockOwnershipError({
9005
- target: options.path,
9006
- name: options.name
9007
- });
9008
- }
9037
+ return queueWindows(async () => {
9038
+ try {
9039
+ await flushWindowsFile(windowsFile, file, text2);
9040
+ } finally {
9041
+ if (close)
9042
+ await closeWindowsFile(windowsFile);
9009
9043
  }
9010
9044
  });
9011
- return;
9012
9045
  }
9013
- const tempPath = `${lockPath}.${randomUUID7()}.tmp`;
9014
- let handle;
9015
- let created = false;
9016
9046
  try {
9017
- handle = await open4(tempPath, "wx", 384);
9018
- created = true;
9019
- await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9020
- `, "utf8");
9021
- await handle.chmod(384);
9022
- await handle.close();
9023
- handle = void 0;
9024
- const current = await readOwner();
9025
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9026
- throw new LockOwnershipError({
9027
- target: options.path,
9028
- name: options.name
9029
- });
9030
- }
9031
- await rename6(tempPath, lockPath);
9032
- created = false;
9033
- } finally {
9034
- await handle?.close().catch(() => {
9035
- });
9036
- if (created)
9037
- await rm4(tempPath, { force: true }).catch(() => {
9038
- });
9047
+ rotateIfNeeded(file);
9048
+ if (existsSync(file))
9049
+ chmodPrivate(file);
9050
+ appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
9051
+ } catch {
9039
9052
  }
9040
9053
  }
9041
- async function createLease() {
9042
- const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9043
- `;
9044
- if (windowsPrivateFiles)
9045
- await createPrivateBytes(lockPath, bytes);
9046
- else
9047
- await createExclusiveText(lockPath, bytes);
9054
+ function schedule2() {
9055
+ if (!timer)
9056
+ timer = setTimeout(() => {
9057
+ timer = void 0;
9058
+ const flushed = flushLogs3(false);
9059
+ if (flushed instanceof Promise)
9060
+ void flushed.catch(() => {
9061
+ });
9062
+ }, 500);
9048
9063
  }
9049
- async function leaseContention(error) {
9050
- const code2 = error.code;
9051
- if (code2 !== "EEXIST" && code2 !== "EISDIR")
9052
- return false;
9053
- if (windowsPrivateFiles) {
9054
- if (options.onStep)
9055
- await options.onStep("lease-contention-read-ready");
9064
+ function emit(channel3, level, message, data) {
9065
+ if (logFileSource === void 0 && captureSink === void 0)
9066
+ return;
9067
+ try {
9068
+ if (ORDER[level] > ORDER[configuredLevel()])
9069
+ return;
9070
+ const scrubbedMessage = redactor.redactStrings(message);
9071
+ let scrubbedData;
9056
9072
  try {
9057
- if (code2 === "EISDIR") {
9058
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9059
- await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
9060
- } else
9061
- await readOwner();
9062
- } catch (readError) {
9063
- if (readError.code !== "ENOENT")
9064
- throw readError;
9073
+ scrubbedData = redactor.redact(data);
9074
+ } catch {
9075
+ scrubbedData = "[unserializable]";
9065
9076
  }
9066
- }
9067
- return true;
9068
- }
9069
- async function tryAcquire() {
9070
- if (windowsPrivateFiles)
9071
- await ensurePrivateDirectory(dirname7(lockPath));
9072
- try {
9073
- await createLease();
9074
- return true;
9075
- } catch (error) {
9076
- const code2 = error.code;
9077
- if (await leaseContention(error))
9078
- return false;
9079
- if (code2 === "ENOENT") {
9080
- if (windowsPrivateFiles)
9081
- await ensurePrivateDirectory(dirname7(lockPath));
9082
- else
9083
- await mkdir7(dirname7(lockPath), { recursive: true });
9084
- try {
9085
- await createLease();
9086
- return true;
9087
- } catch (retryError) {
9088
- if (await leaseContention(retryError))
9089
- return false;
9090
- throw retryError;
9091
- }
9077
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel3}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
9078
+ try {
9079
+ captureSink?.({
9080
+ channel: channel3,
9081
+ level,
9082
+ message: scrubbedMessage,
9083
+ data: scrubbedData
9084
+ });
9085
+ } catch {
9092
9086
  }
9093
- throw error;
9087
+ if (logFileSource === void 0)
9088
+ return;
9089
+ buffer.push(line);
9090
+ if (buffer.length >= 50) {
9091
+ const flushed = flushLogs3(false);
9092
+ if (flushed instanceof Promise)
9093
+ void flushed.catch(() => {
9094
+ });
9095
+ } else
9096
+ schedule2();
9097
+ } catch {
9094
9098
  }
9095
9099
  }
9096
- async function backoff() {
9097
- await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
9100
+ function createLogger5(channel3) {
9101
+ return {
9102
+ error: (m, d) => emit(channel3, "error", m, d),
9103
+ warn: (m, d) => emit(channel3, "warn", m, d),
9104
+ info: (m, d) => emit(channel3, "info", m, d),
9105
+ debug: (m, d) => emit(channel3, "debug", m, d),
9106
+ trace: (m, d) => emit(channel3, "trace", m, d)
9107
+ };
9098
9108
  }
9099
- async function readLockState(notifyReady = true) {
9100
- if (notifyReady && options.onStep)
9101
- await options.onStep("lock-read-ready");
9102
- let owner;
9103
- try {
9104
- owner = await readOwner();
9105
- } catch (error) {
9106
- if (error instanceof DisappearedLockRecordError)
9107
- return { status: "missing" };
9108
- if (windowsPrivateFiles && error.code !== "ENOENT")
9109
- throw error;
9110
- }
9111
- const expiresAt = Number(owner?.expiresAt);
9112
- if (Number.isFinite(expiresAt) && expiresAt > now())
9113
- return { status: "live" };
9114
- if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
9115
- return {
9116
- status: "stale",
9117
- identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
9118
- };
9119
- }
9120
- try {
9121
- const current = await stat3(lockPath);
9122
- const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
9123
- if (legacyExpiry > now())
9124
- return { status: "live" };
9125
- return {
9126
- status: "stale",
9127
- identity: {
9128
- kind: "stat",
9129
- dev: current.dev,
9130
- ino: current.ino,
9131
- mtimeMs: current.mtimeMs,
9132
- expiresAt: legacyExpiry
9133
- }
9134
- };
9135
- } catch (error) {
9136
- if (error.code === "ENOENT") {
9137
- if (options.onStep)
9138
- await options.onStep("lock-missing");
9139
- return { status: "missing" };
9140
- }
9141
- throw error;
9109
+ function reset() {
9110
+ if (windowsPrivateFiles)
9111
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
9112
+ });
9113
+ sinkError = void 0;
9114
+ buffer = [];
9115
+ if (timer) {
9116
+ clearTimeout(timer);
9117
+ timer = void 0;
9142
9118
  }
9119
+ logFileSource = void 0;
9120
+ initLevelSource = void 0;
9121
+ runtimeLevel = void 0;
9122
+ redactor = createRedactor();
9123
+ captureSink = void 0;
9143
9124
  }
9144
- function sameStaleLock(observed, current) {
9145
- if (current.status !== "stale")
9146
- return false;
9147
- const identity3 = current.identity;
9148
- if (observed.kind === "owner" && identity3.kind === "owner") {
9149
- return observed.ownerId === identity3.ownerId && observed.expiresAt === identity3.expiresAt;
9150
- }
9151
- return observed.kind === "stat" && identity3.kind === "stat" && observed.dev === identity3.dev && observed.ino === identity3.ino && observed.mtimeMs === identity3.mtimeMs && observed.expiresAt === identity3.expiresAt;
9125
+ if (options)
9126
+ configure(options);
9127
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
9128
+ }
9129
+ function createLoggerInstance(options) {
9130
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
9131
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
9132
+ }
9133
+ function initLogger(options) {
9134
+ defaultEngine.configure(options);
9135
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
9136
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
9137
+ }
9138
+ function setLogLevel(l) {
9139
+ defaultEngine.setLogLevel(l);
9140
+ }
9141
+ function flushLogs() {
9142
+ return defaultEngine.flushLogs();
9143
+ }
9144
+ function createLogger2(channel3) {
9145
+ return defaultEngine.createLogger(channel3);
9146
+ }
9147
+ async function flushForTest() {
9148
+ return defaultEngine.flushLogs();
9149
+ }
9150
+ function resetLoggerForTest() {
9151
+ defaultEngine.reset();
9152
+ }
9153
+ var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
9154
+ var init_engine = __esm({
9155
+ "../core/dist/common-auth-embedded/logger/engine.js"() {
9156
+ "use strict";
9157
+ init_private_files();
9158
+ init_redact();
9159
+ ORDER = {
9160
+ error: 0,
9161
+ warn: 1,
9162
+ info: 2,
9163
+ debug: 3,
9164
+ trace: 4
9165
+ };
9166
+ MAX_BYTES = 5 * 1024 * 1024;
9167
+ ROTATE_KEEP = 3;
9168
+ defaultEngine = createEngine();
9152
9169
  }
9153
- async function ownsEvictionMarker() {
9170
+ });
9171
+
9172
+ // ../core/dist/common-auth-embedded/logger/index.js
9173
+ var logger_exports = {};
9174
+ __export(logger_exports, {
9175
+ createCaptureSink: () => createCaptureSink,
9176
+ createLogger: () => createLogger2,
9177
+ createLoggerInstance: () => createLoggerInstance,
9178
+ createRedactor: () => createRedactor,
9179
+ flushForTest: () => flushForTest,
9180
+ flushLogs: () => flushLogs,
9181
+ initLogger: () => initLogger,
9182
+ redact: () => redact,
9183
+ redactStrings: () => redactStrings,
9184
+ resetLoggerForTest: () => resetLoggerForTest,
9185
+ setLogLevel: () => setLogLevel
9186
+ });
9187
+ var init_logger2 = __esm({
9188
+ "../core/dist/common-auth-embedded/logger/index.js"() {
9189
+ "use strict";
9190
+ init_capture_sink();
9191
+ init_engine();
9192
+ init_redact();
9193
+ }
9194
+ });
9195
+
9196
+ // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
9197
+ import { randomUUID as randomUUID7 } from "node:crypto";
9198
+ import { link as link2, lstat as lstat3, mkdir as mkdir7, open as open5, readdir, readFile as readFile5, rename as rename6, rm as rm4, stat as stat3, unlink as unlink6 } from "node:fs/promises";
9199
+ import { basename as basename3, dirname as dirname8, join as join5 } from "node:path";
9200
+ async function createExclusiveText(path2, text2) {
9201
+ const tempPath = `${path2}.${randomUUID7()}.tmp`;
9202
+ let handle;
9203
+ try {
9204
+ handle = await open5(tempPath, "wx", 384);
9154
9205
  try {
9155
- const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
9156
- return owner?.ownerId === evictOwnerId;
9206
+ if (leaseCreationTestHooks?.beforeWrite)
9207
+ await leaseCreationTestHooks.beforeWrite(tempPath);
9208
+ await handle.writeFile(text2, "utf8");
9209
+ } finally {
9210
+ await handle.close();
9211
+ }
9212
+ try {
9213
+ if (leaseCreationTestHooks?.beforeLink)
9214
+ await leaseCreationTestHooks.beforeLink(tempPath, path2);
9215
+ await link2(tempPath, path2);
9157
9216
  } catch (error) {
9158
- if (windowsPrivateFiles && error.code !== "ENOENT")
9217
+ const code2 = error.code;
9218
+ if (code2 !== "EPERM" && code2 !== "ENOTSUP" && code2 !== "EOPNOTSUPP" && code2 !== "EXDEV")
9159
9219
  throw error;
9160
- return false;
9220
+ await writeExclusiveText(path2, text2);
9161
9221
  }
9162
- }
9163
- async function removeLeaseObject(path2) {
9164
- if (windowsPrivateFiles)
9165
- await privateOperation(path2, "remove", () => rm4(path2, { recursive: true, force: true }));
9166
- else
9167
- await rm4(path2, { recursive: true, force: true }).catch(() => {
9222
+ } finally {
9223
+ if (handle)
9224
+ await rm4(tempPath, { force: true }).catch(() => {
9168
9225
  });
9169
9226
  }
9170
- function isRetryableRemoval(error, path2) {
9171
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
9172
- return false;
9173
- return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
9227
+ }
9228
+ async function writeExclusiveText(path2, text2) {
9229
+ const handle = await open5(path2, "wx", 384);
9230
+ let createdStat;
9231
+ try {
9232
+ createdStat = await handle.stat();
9233
+ } catch {
9234
+ createdStat = void 0;
9174
9235
  }
9175
- async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
9176
- let original;
9177
- let delayMs = 5;
9178
- while (await stillOwned()) {
9179
- try {
9180
- await removeLeaseObject(path2);
9181
- return;
9182
- } catch (error) {
9183
- if (!isRetryableRemoval(error, path2))
9184
- throw error;
9185
- original ??= error;
9236
+ try {
9237
+ if (leaseCreationTestHooks?.beforeWrite)
9238
+ await leaseCreationTestHooks.beforeWrite(path2);
9239
+ await handle.writeFile(text2, "utf8");
9240
+ } catch (error) {
9241
+ try {
9242
+ const current = await lstat3(path2).catch(() => void 0);
9243
+ if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
9244
+ await rm4(path2, { force: true }).catch(() => {
9245
+ });
9186
9246
  }
9187
- const remainingMs = deadline - performance.now();
9188
- if (remainingMs <= 0)
9189
- throw original;
9190
- await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9191
- if (performance.now() >= deadline)
9192
- throw original;
9193
- delayMs = Math.min(delayMs * 2, 50);
9247
+ } catch {
9194
9248
  }
9249
+ throw error;
9250
+ } finally {
9251
+ await handle.close();
9195
9252
  }
9196
- async function releaseEvictionMarker(deadline) {
9197
- let ownedDirectory;
9198
- await removeOwnedLeaseObject(evictPath, async () => {
9199
- if (!windowsPrivateFiles)
9200
- return ownsEvictionMarker();
9201
- const current = await lstat3(evictPath).catch((error) => {
9202
- if (error.code !== "ENOENT")
9203
- throw error;
9204
- return void 0;
9205
- });
9206
- if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9207
- return false;
9208
- if (await ownsEvictionMarker()) {
9209
- ownedDirectory = current;
9210
- return true;
9211
- }
9212
- if (!ownedDirectory)
9213
- return false;
9214
- try {
9215
- await stat3(evictOwnerPath);
9216
- return false;
9217
- } catch (error) {
9218
- if (error.code !== "ENOENT")
9219
- throw error;
9220
- return true;
9221
- }
9222
- }, deadline);
9253
+ }
9254
+ function isStagingName(name, lockName) {
9255
+ const prefix = `${lockName}.`;
9256
+ const suffix = ".tmp";
9257
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
9258
+ return false;
9259
+ return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
9260
+ }
9261
+ function sameStagingFile(a, b) {
9262
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
9263
+ }
9264
+ async function readStagedOwner(path2) {
9265
+ const before = await lstat3(path2);
9266
+ if (!before.isFile() || before.isSymbolicLink())
9267
+ return void 0;
9268
+ if (before.size > STAGING_SWEEP_MAX_BYTES)
9269
+ return void 0;
9270
+ const handle = await open5(path2, "r");
9271
+ let text2;
9272
+ try {
9273
+ if (!sameStagingFile(before, await handle.stat()))
9274
+ return void 0;
9275
+ text2 = await handle.readFile("utf8");
9276
+ } finally {
9277
+ await handle.close();
9223
9278
  }
9224
- async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
9225
- if (!created)
9226
- return false;
9227
- let stillOurs = false;
9228
- try {
9229
- await removeOwnedLeaseObject(evictPath, async () => {
9230
- stillOurs = false;
9231
- const st = await lstat3(evictPath).catch(() => void 0);
9232
- if (!st || !sameMarkerDirectory(created, st))
9233
- return false;
9234
- stillOurs = true;
9235
- try {
9236
- await stat3(evictOwnerPath);
9237
- return false;
9238
- } catch (error) {
9239
- return error.code === "ENOENT";
9240
- }
9241
- }, deadline);
9242
- } catch {
9243
- }
9244
- return stillOurs;
9279
+ let record3;
9280
+ try {
9281
+ record3 = JSON.parse(text2);
9282
+ } catch {
9283
+ return void 0;
9245
9284
  }
9246
- async function tryAcquireEvictionMarker(deadline) {
9247
- if (windowsPrivateFiles)
9248
- await createPrivateDirectoryExclusive(evictPath);
9249
- else
9250
- await mkdir7(evictPath);
9251
- let created;
9285
+ if (!record3 || typeof record3 !== "object" || Array.isArray(record3))
9286
+ return void 0;
9287
+ const keys = Object.keys(record3).sort();
9288
+ if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
9289
+ return void 0;
9290
+ const { ownerId, expiresAt } = record3;
9291
+ if (typeof ownerId !== "string" || !STAGING_UUID.test(ownerId))
9292
+ return void 0;
9293
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
9294
+ return void 0;
9295
+ return { identity: before, expiresAt };
9296
+ }
9297
+ async function sweepAbandonedStaging(lockPath, ttlMs, now) {
9298
+ const directory = dirname8(lockPath);
9299
+ const lockName = basename3(lockPath);
9300
+ const hooks = stagingSweepTestHooks;
9301
+ const names = await (hooks?.readdir ?? readdir)(directory);
9302
+ const candidates = names.filter((name) => isStagingName(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES);
9303
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
9304
+ for (const name of candidates) {
9305
+ const path2 = join5(directory, name);
9252
9306
  try {
9253
- const st = await lstat3(evictPath);
9254
- created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
9307
+ if (now() - (await lstat3(path2)).mtimeMs < marginMs)
9308
+ continue;
9309
+ const staged = await readStagedOwner(path2);
9310
+ if (!staged || !(staged.expiresAt < now() - marginMs))
9311
+ continue;
9312
+ if (hooks?.beforeUnlink)
9313
+ await hooks.beforeUnlink(path2);
9314
+ const current = await readStagedOwner(path2);
9315
+ if (!current || !sameStagingFile(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
9316
+ continue;
9317
+ await (hooks?.unlink ?? unlink6)(path2);
9255
9318
  } catch {
9256
- created = void 0;
9257
9319
  }
9320
+ }
9321
+ }
9322
+ function startStagingSweep(lockPath, ttlMs, now) {
9323
+ if (sweptLockPaths.has(lockPath))
9324
+ return;
9325
+ sweptLockPaths.add(lockPath);
9326
+ const sweep = Promise.resolve().then(() => sweepAbandonedStaging(lockPath, ttlMs, now)).catch(() => {
9327
+ });
9328
+ pendingStagingSweeps.add(sweep);
9329
+ void sweep.finally(() => pendingStagingSweeps.delete(sweep));
9330
+ }
9331
+ function isLostMarkerRaceError(error) {
9332
+ const code2 = error?.code;
9333
+ return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
9334
+ }
9335
+ function sameMarkerDirectory(created, current) {
9336
+ if (created.dev !== current.dev || created.ino !== current.ino)
9337
+ return false;
9338
+ if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
9339
+ return false;
9340
+ return true;
9341
+ }
9342
+ function acquireRefreshFileLock(options) {
9343
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
9344
+ }
9345
+ async function acquireRefreshFileLockWithClock(options) {
9346
+ const lockPath = lockPathFor(options.path, options.name);
9347
+ const legacyOwnerPath = join5(lockPath, "owner.json");
9348
+ const ownerId = randomUUID7();
9349
+ const now = options.now ?? Date.now;
9350
+ let renewTimer = null;
9351
+ let released = false;
9352
+ let releaseConfirmed = false;
9353
+ let loss;
9354
+ let resolveLoss;
9355
+ const lostPromise = new Promise((resolve24) => {
9356
+ resolveLoss = resolve24;
9357
+ });
9358
+ function notifyTimerStep(event) {
9258
9359
  try {
9259
- await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
9260
- const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
9261
- if (injected !== void 0)
9262
- throw injected;
9263
- const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
9264
- `;
9265
- if (windowsPrivateFiles)
9266
- await createPrivateBytes(evictOwnerPath, bytes);
9267
- else
9268
- await writeExclusiveText(evictOwnerPath, bytes);
9269
- } catch (error) {
9270
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9271
- if (isLostMarkerRaceError(error) && !stillOurs)
9272
- return false;
9273
- try {
9274
- await releaseEvictionMarker(deadline);
9275
- } catch {
9360
+ const result = options.onRenewalTimer?.(event);
9361
+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
9362
+ void Promise.resolve(result).catch(() => {
9363
+ });
9276
9364
  }
9277
- throw error;
9365
+ } catch {
9278
9366
  }
9279
- if (options.onStep)
9280
- await options.onStep("eviction-marker-acquired");
9281
- return true;
9282
9367
  }
9283
- async function recoverStaleEvictionMarker(deadline) {
9284
- let evictStat;
9285
- try {
9286
- evictStat = await stat3(evictPath);
9287
- } catch (error) {
9288
- if (error.code === "ENOENT")
9289
- return "missing";
9290
- throw error;
9291
- }
9368
+ function cancelRenewalTimer() {
9369
+ if (!renewTimer)
9370
+ return;
9371
+ clearRefreshLockRenewalTimeout(renewTimer);
9372
+ renewTimer = null;
9373
+ notifyTimerStep("cancelled");
9374
+ }
9375
+ function recordLoss(reason, owner) {
9376
+ if (loss || released)
9377
+ return;
9378
+ loss = Object.freeze({
9379
+ reason,
9380
+ expectedOwnerId: ownerId,
9381
+ ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
9382
+ ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
9383
+ });
9384
+ cancelRenewalTimer();
9385
+ resolveLoss(loss);
9386
+ }
9387
+ let terminalIOError;
9388
+ let renewalInFlight = null;
9389
+ const evictPath = `${lockPath}.evicting`;
9390
+ const evictOwnerPath = join5(evictPath, "owner.json");
9391
+ const evictOwnerId = randomUUID7();
9392
+ const EVICT_TTL = 5e3;
9393
+ const MAX_STEAL_ATTEMPTS = 8;
9394
+ function isChangingLockCreate(error) {
9395
+ return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
9396
+ }
9397
+ async function readOwner() {
9292
9398
  if (windowsPrivateFiles) {
9293
9399
  try {
9294
- await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9295
- } catch (error) {
9296
- if (error.code === "ENOENT")
9297
- return "missing";
9298
- throw error;
9299
- }
9300
- }
9301
- if (evictStat.mtimeMs + EVICT_TTL > now()) {
9302
- let hasOwner = true;
9303
- try {
9304
- await stat3(evictOwnerPath);
9400
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
9305
9401
  } catch (error) {
9306
- if (error.code === "ENOENT")
9307
- hasOwner = false;
9308
- else
9309
- return "fresh";
9402
+ if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
9403
+ throw error;
9404
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9405
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
9310
9406
  }
9311
- if (hasOwner)
9312
- return "fresh";
9313
- if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
9314
- return "fresh";
9315
9407
  }
9316
- if (options.onStep)
9317
- await options.onStep("stale-marker-stat");
9318
- const claimedPath = `${evictPath}.${randomUUID7()}`;
9319
9408
  try {
9320
- await rename6(evictPath, claimedPath);
9409
+ return JSON.parse(await readFile5(lockPath, "utf8"));
9321
9410
  } catch (error) {
9322
- if (error.code === "ENOENT")
9323
- return "missing";
9324
- throw error;
9411
+ const code2 = error.code;
9412
+ if (code2 !== "EISDIR")
9413
+ throw error;
9414
+ return JSON.parse(await readFile5(legacyOwnerPath, "utf8"));
9325
9415
  }
9326
- if (options.onStep)
9327
- await options.onStep("stale-marker-claimed");
9328
- const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9329
- await removeOwnedLeaseObject(claimedPath, async () => {
9330
- if (!claimedIdentity)
9331
- return true;
9332
- const current = await lstat3(claimedPath).catch((error) => {
9333
- if (error.code !== "ENOENT")
9334
- throw error;
9335
- return void 0;
9416
+ }
9417
+ async function writeOwner() {
9418
+ if (windowsPrivateFiles) {
9419
+ const owner = await readOwner();
9420
+ const remaining = Number(owner?.expiresAt) - now();
9421
+ await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9422
+ `, {
9423
+ deadline: performance.now() + Math.max(0, remaining),
9424
+ beforeRename: async () => {
9425
+ const current = await readOwner();
9426
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9427
+ throw new LockOwnershipError({
9428
+ target: options.path,
9429
+ name: options.name
9430
+ });
9431
+ }
9432
+ }
9336
9433
  });
9337
- return !!current && sameMarkerDirectory(claimedIdentity, current);
9338
- }, deadline);
9339
- return "recovered";
9434
+ return;
9435
+ }
9436
+ const tempPath = `${lockPath}.${randomUUID7()}.tmp`;
9437
+ let handle;
9438
+ let created = false;
9439
+ try {
9440
+ handle = await open5(tempPath, "wx", 384);
9441
+ created = true;
9442
+ await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9443
+ `, "utf8");
9444
+ await handle.chmod(384);
9445
+ await handle.close();
9446
+ handle = void 0;
9447
+ const current = await readOwner();
9448
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9449
+ throw new LockOwnershipError({
9450
+ target: options.path,
9451
+ name: options.name
9452
+ });
9453
+ }
9454
+ await rename6(tempPath, lockPath);
9455
+ created = false;
9456
+ } finally {
9457
+ await handle?.close().catch(() => {
9458
+ });
9459
+ if (created)
9460
+ await rm4(tempPath, { force: true }).catch(() => {
9461
+ });
9462
+ }
9340
9463
  }
9341
- async function withEvictionMarker(action, deadline) {
9464
+ async function createLease() {
9465
+ const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9466
+ `;
9467
+ if (windowsPrivateFiles)
9468
+ await createPrivateBytes(lockPath, bytes);
9469
+ else
9470
+ await createExclusiveText(lockPath, bytes);
9471
+ }
9472
+ async function leaseContention(error) {
9473
+ const code2 = error.code;
9474
+ if (code2 !== "EEXIST" && code2 !== "EISDIR")
9475
+ return false;
9476
+ if (windowsPrivateFiles) {
9477
+ if (options.onStep)
9478
+ await options.onStep("lease-contention-read-ready");
9479
+ try {
9480
+ if (code2 === "EISDIR") {
9481
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9482
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
9483
+ } else
9484
+ await readOwner();
9485
+ } catch (readError) {
9486
+ if (readError.code !== "ENOENT")
9487
+ throw readError;
9488
+ }
9489
+ }
9490
+ return true;
9491
+ }
9492
+ async function tryAcquire() {
9493
+ if (windowsPrivateFiles)
9494
+ await ensurePrivateDirectory(dirname8(lockPath));
9342
9495
  try {
9343
- if (!await tryAcquireEvictionMarker(deadline))
9344
- return false;
9496
+ await createLease();
9497
+ return true;
9345
9498
  } catch (error) {
9346
- if (error.code === "EEXIST") {
9347
- if (windowsPrivateFiles) {
9348
- try {
9349
- await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9350
- await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
9351
- } catch (ownerError) {
9352
- if (ownerError.code !== "ENOENT")
9353
- throw ownerError;
9354
- }
9355
- }
9499
+ const code2 = error.code;
9500
+ if (await leaseContention(error))
9356
9501
  return false;
9502
+ if (code2 === "ENOENT") {
9503
+ if (windowsPrivateFiles)
9504
+ await ensurePrivateDirectory(dirname8(lockPath));
9505
+ else
9506
+ await mkdir7(dirname8(lockPath), { recursive: true });
9507
+ try {
9508
+ await createLease();
9509
+ return true;
9510
+ } catch (retryError) {
9511
+ if (await leaseContention(retryError))
9512
+ return false;
9513
+ throw retryError;
9514
+ }
9357
9515
  }
9358
9516
  throw error;
9359
9517
  }
9360
- let actionFailed = false;
9361
- let actionError;
9518
+ }
9519
+ async function backoff() {
9520
+ await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
9521
+ }
9522
+ async function readLockState(notifyReady = true) {
9523
+ if (notifyReady && options.onStep)
9524
+ await options.onStep("lock-read-ready");
9525
+ let owner;
9362
9526
  try {
9363
- await action();
9527
+ owner = await readOwner();
9364
9528
  } catch (error) {
9365
- actionFailed = true;
9366
- actionError = error;
9529
+ if (error instanceof DisappearedLockRecordError)
9530
+ return { status: "missing" };
9531
+ if (windowsPrivateFiles && error.code !== "ENOENT")
9532
+ throw error;
9533
+ }
9534
+ const expiresAt = Number(owner?.expiresAt);
9535
+ if (Number.isFinite(expiresAt) && expiresAt > now())
9536
+ return { status: "live" };
9537
+ if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
9538
+ return {
9539
+ status: "stale",
9540
+ identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
9541
+ };
9367
9542
  }
9368
9543
  try {
9369
- await releaseEvictionMarker(deadline);
9544
+ const current = await stat3(lockPath);
9545
+ const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
9546
+ if (legacyExpiry > now())
9547
+ return { status: "live" };
9548
+ return {
9549
+ status: "stale",
9550
+ identity: {
9551
+ kind: "stat",
9552
+ dev: current.dev,
9553
+ ino: current.ino,
9554
+ mtimeMs: current.mtimeMs,
9555
+ expiresAt: legacyExpiry
9556
+ }
9557
+ };
9370
9558
  } catch (error) {
9371
- if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
9372
- lockPath,
9373
- legacyOwnerPath,
9374
- evictOwnerPath
9375
- ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
9376
- throw actionError;
9559
+ if (error.code === "ENOENT") {
9560
+ if (options.onStep)
9561
+ await options.onStep("lock-missing");
9562
+ return { status: "missing" };
9563
+ }
9377
9564
  throw error;
9378
9565
  }
9379
- if (actionFailed)
9380
- throw actionError;
9381
- return true;
9382
9566
  }
9383
- async function relinquishLockAfterMarkerLoss() {
9384
- for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
9385
- if (options.onStep)
9386
- await options.onStep("relinquish-read");
9387
- let owner;
9388
- try {
9389
- owner = await readOwner();
9390
- } catch (error) {
9391
- if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
9392
- throw error;
9393
- return;
9394
- }
9395
- if (owner?.ownerId !== ownerId)
9396
- return;
9567
+ function sameStaleLock(observed, current) {
9568
+ if (current.status !== "stale")
9569
+ return false;
9570
+ const identity3 = current.identity;
9571
+ if (observed.kind === "owner" && identity3.kind === "owner") {
9572
+ return observed.ownerId === identity3.ownerId && observed.expiresAt === identity3.expiresAt;
9573
+ }
9574
+ return observed.kind === "stat" && identity3.kind === "stat" && observed.dev === identity3.dev && observed.ino === identity3.ino && observed.mtimeMs === identity3.mtimeMs && observed.expiresAt === identity3.expiresAt;
9575
+ }
9576
+ async function ownsEvictionMarker() {
9577
+ try {
9578
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
9579
+ return owner?.ownerId === evictOwnerId;
9580
+ } catch (error) {
9581
+ if (windowsPrivateFiles && error.code !== "ENOENT")
9582
+ throw error;
9583
+ return false;
9584
+ }
9585
+ }
9586
+ async function removeLeaseObject(path2) {
9587
+ if (windowsPrivateFiles)
9588
+ await privateOperation(path2, "remove", () => rm4(path2, { recursive: true, force: true }));
9589
+ else
9590
+ await rm4(path2, { recursive: true, force: true }).catch(() => {
9591
+ });
9592
+ }
9593
+ function isRetryableRemoval(error, path2) {
9594
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
9595
+ return false;
9596
+ return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
9597
+ }
9598
+ async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
9599
+ let original;
9600
+ let delayMs = 5;
9601
+ while (await stillOwned()) {
9397
9602
  try {
9398
- await rm4(lockPath, { recursive: true, force: true });
9603
+ await removeLeaseObject(path2);
9399
9604
  return;
9400
9605
  } catch (error) {
9401
- if (windowsPrivateFiles)
9606
+ if (!isRetryableRemoval(error, path2))
9402
9607
  throw error;
9403
- await backoff();
9608
+ original ??= error;
9404
9609
  }
9610
+ const remainingMs = deadline - performance.now();
9611
+ if (remainingMs <= 0)
9612
+ throw original;
9613
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9614
+ if (performance.now() >= deadline)
9615
+ throw original;
9616
+ delayMs = Math.min(delayMs * 2, 50);
9405
9617
  }
9406
9618
  }
9407
- function scheduleRenewal() {
9408
- if (!options.renew || released || loss)
9409
- return;
9410
- const intervalMs = options.renewIntervalMs ?? Math.max(1e3, Math.floor(options.ttlMs / 3));
9411
- renewTimer = setRefreshLockRenewalTimeout(() => {
9412
- renewTimer = null;
9413
- const renewal = (async () => {
9414
- let shouldReschedule = !released;
9415
- try {
9416
- const markerAcquired = await withEvictionMarker(async () => {
9417
- const owner = await readOwner();
9418
- const currentNow = now();
9419
- if (released || loss) {
9420
- shouldReschedule = false;
9421
- return;
9422
- }
9423
- if (owner?.ownerId !== ownerId) {
9619
+ async function releaseEvictionMarker(deadline) {
9620
+ let ownedDirectory;
9621
+ await removeOwnedLeaseObject(evictPath, async () => {
9622
+ if (!windowsPrivateFiles)
9623
+ return ownsEvictionMarker();
9624
+ const current = await lstat3(evictPath).catch((error) => {
9625
+ if (error.code !== "ENOENT")
9626
+ throw error;
9627
+ return void 0;
9628
+ });
9629
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9630
+ return false;
9631
+ if (await ownsEvictionMarker()) {
9632
+ ownedDirectory = current;
9633
+ return true;
9634
+ }
9635
+ if (!ownedDirectory)
9636
+ return false;
9637
+ try {
9638
+ await stat3(evictOwnerPath);
9639
+ return false;
9640
+ } catch (error) {
9641
+ if (error.code !== "ENOENT")
9642
+ throw error;
9643
+ return true;
9644
+ }
9645
+ }, deadline);
9646
+ }
9647
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
9648
+ if (!created)
9649
+ return false;
9650
+ let stillOurs = false;
9651
+ try {
9652
+ await removeOwnedLeaseObject(evictPath, async () => {
9653
+ stillOurs = false;
9654
+ const st = await lstat3(evictPath).catch(() => void 0);
9655
+ if (!st || !sameMarkerDirectory(created, st))
9656
+ return false;
9657
+ stillOurs = true;
9658
+ try {
9659
+ await stat3(evictOwnerPath);
9660
+ return false;
9661
+ } catch (error) {
9662
+ return error.code === "ENOENT";
9663
+ }
9664
+ }, deadline);
9665
+ } catch {
9666
+ }
9667
+ return stillOurs;
9668
+ }
9669
+ async function tryAcquireEvictionMarker(deadline) {
9670
+ if (windowsPrivateFiles)
9671
+ await createPrivateDirectoryExclusive(evictPath);
9672
+ else
9673
+ await mkdir7(evictPath);
9674
+ let created;
9675
+ try {
9676
+ const st = await lstat3(evictPath);
9677
+ created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
9678
+ } catch {
9679
+ created = void 0;
9680
+ }
9681
+ try {
9682
+ await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
9683
+ const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
9684
+ if (injected !== void 0)
9685
+ throw injected;
9686
+ const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
9687
+ `;
9688
+ if (windowsPrivateFiles)
9689
+ await createPrivateBytes(evictOwnerPath, bytes);
9690
+ else
9691
+ await writeExclusiveText(evictOwnerPath, bytes);
9692
+ } catch (error) {
9693
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9694
+ if (isLostMarkerRaceError(error) && !stillOurs)
9695
+ return false;
9696
+ try {
9697
+ await releaseEvictionMarker(deadline);
9698
+ } catch {
9699
+ }
9700
+ throw error;
9701
+ }
9702
+ if (options.onStep)
9703
+ await options.onStep("eviction-marker-acquired");
9704
+ return true;
9705
+ }
9706
+ async function recoverStaleEvictionMarker(deadline) {
9707
+ let evictStat;
9708
+ try {
9709
+ evictStat = await stat3(evictPath);
9710
+ } catch (error) {
9711
+ if (error.code === "ENOENT")
9712
+ return "missing";
9713
+ throw error;
9714
+ }
9715
+ if (windowsPrivateFiles) {
9716
+ try {
9717
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9718
+ } catch (error) {
9719
+ if (error.code === "ENOENT")
9720
+ return "missing";
9721
+ throw error;
9722
+ }
9723
+ }
9724
+ if (evictStat.mtimeMs + EVICT_TTL > now()) {
9725
+ let hasOwner = true;
9726
+ try {
9727
+ await stat3(evictOwnerPath);
9728
+ } catch (error) {
9729
+ if (error.code === "ENOENT")
9730
+ hasOwner = false;
9731
+ else
9732
+ return "fresh";
9733
+ }
9734
+ if (hasOwner)
9735
+ return "fresh";
9736
+ if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
9737
+ return "fresh";
9738
+ }
9739
+ if (options.onStep)
9740
+ await options.onStep("stale-marker-stat");
9741
+ const claimedPath = `${evictPath}.${randomUUID7()}`;
9742
+ try {
9743
+ await rename6(evictPath, claimedPath);
9744
+ } catch (error) {
9745
+ if (error.code === "ENOENT")
9746
+ return "missing";
9747
+ throw error;
9748
+ }
9749
+ if (options.onStep)
9750
+ await options.onStep("stale-marker-claimed");
9751
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9752
+ await removeOwnedLeaseObject(claimedPath, async () => {
9753
+ if (!claimedIdentity)
9754
+ return true;
9755
+ const current = await lstat3(claimedPath).catch((error) => {
9756
+ if (error.code !== "ENOENT")
9757
+ throw error;
9758
+ return void 0;
9759
+ });
9760
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
9761
+ }, deadline);
9762
+ return "recovered";
9763
+ }
9764
+ async function withEvictionMarker(action, deadline) {
9765
+ try {
9766
+ if (!await tryAcquireEvictionMarker(deadline))
9767
+ return false;
9768
+ } catch (error) {
9769
+ if (error.code === "EEXIST") {
9770
+ if (windowsPrivateFiles) {
9771
+ try {
9772
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9773
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
9774
+ } catch (ownerError) {
9775
+ if (ownerError.code !== "ENOENT")
9776
+ throw ownerError;
9777
+ }
9778
+ }
9779
+ return false;
9780
+ }
9781
+ throw error;
9782
+ }
9783
+ let actionFailed = false;
9784
+ let actionError;
9785
+ try {
9786
+ await action();
9787
+ } catch (error) {
9788
+ actionFailed = true;
9789
+ actionError = error;
9790
+ }
9791
+ try {
9792
+ await releaseEvictionMarker(deadline);
9793
+ } catch (error) {
9794
+ if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
9795
+ lockPath,
9796
+ legacyOwnerPath,
9797
+ evictOwnerPath
9798
+ ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
9799
+ throw actionError;
9800
+ throw error;
9801
+ }
9802
+ if (actionFailed)
9803
+ throw actionError;
9804
+ return true;
9805
+ }
9806
+ async function relinquishLockAfterMarkerLoss() {
9807
+ for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
9808
+ if (options.onStep)
9809
+ await options.onStep("relinquish-read");
9810
+ let owner;
9811
+ try {
9812
+ owner = await readOwner();
9813
+ } catch (error) {
9814
+ if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
9815
+ throw error;
9816
+ return;
9817
+ }
9818
+ if (owner?.ownerId !== ownerId)
9819
+ return;
9820
+ try {
9821
+ await rm4(lockPath, { recursive: true, force: true });
9822
+ return;
9823
+ } catch (error) {
9824
+ if (windowsPrivateFiles)
9825
+ throw error;
9826
+ await backoff();
9827
+ }
9828
+ }
9829
+ }
9830
+ function scheduleRenewal() {
9831
+ if (!options.renew || released || loss)
9832
+ return;
9833
+ const intervalMs = options.renewIntervalMs ?? Math.max(1e3, Math.floor(options.ttlMs / 3));
9834
+ renewTimer = setRefreshLockRenewalTimeout(() => {
9835
+ renewTimer = null;
9836
+ const renewal = (async () => {
9837
+ let shouldReschedule = !released;
9838
+ try {
9839
+ const markerAcquired = await withEvictionMarker(async () => {
9840
+ const owner = await readOwner();
9841
+ const currentNow = now();
9842
+ if (released || loss) {
9843
+ shouldReschedule = false;
9844
+ return;
9845
+ }
9846
+ if (owner?.ownerId !== ownerId) {
9424
9847
  recordLoss("taken-over", owner);
9425
9848
  shouldReschedule = false;
9426
9849
  return;
@@ -9661,17 +10084,15 @@ async function acquireRefreshFileLockWithClock(options) {
9661
10084
  removalConfirmed = true;
9662
10085
  }, deadline);
9663
10086
  changingRecordError = void 0;
9664
- if (markerAcquired) {
9665
- if (windowsPrivateFiles && !removalConfirmed)
9666
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
9667
- code: "EIO"
9668
- });
9669
- releaseConfirmed = removalConfirmed;
10087
+ if (markerAcquired && removalConfirmed) {
10088
+ releaseConfirmed = true;
9670
10089
  return;
9671
10090
  }
9672
- if (signal?.aborted)
9673
- return;
9674
- await recoverStaleEvictionMarker(deadline);
10091
+ if (!markerAcquired) {
10092
+ if (signal?.aborted)
10093
+ return;
10094
+ await recoverStaleEvictionMarker(deadline);
10095
+ }
9675
10096
  } catch (error) {
9676
10097
  const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
9677
10098
  lockPath,
@@ -9701,6 +10122,9 @@ async function acquireRefreshFileLockWithClock(options) {
9701
10122
  throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
9702
10123
  code: "ETIMEDOUT"
9703
10124
  });
10125
+ createLogger2("fs").warn("File lock release deadline expired", {
10126
+ lockPath
10127
+ });
9704
10128
  }
9705
10129
  };
9706
10130
  }
@@ -9708,6 +10132,7 @@ var leaseCreationTestHooks, STAGING_UUID, STAGING_SWEEP_MIN_AGE_MS, STAGING_SWEE
9708
10132
  var init_refresh_file_lock = __esm({
9709
10133
  "../core/dist/common-auth-embedded/fs/refresh-file-lock.js"() {
9710
10134
  "use strict";
10135
+ init_logger2();
9711
10136
  init_lock_record();
9712
10137
  init_private_files();
9713
10138
  init_with_lock();
@@ -9724,12 +10149,12 @@ var init_refresh_file_lock = __esm({
9724
10149
  });
9725
10150
 
9726
10151
  // ../core/dist/common-auth-embedded/fs/with-lock.js
9727
- import { join as join6, resolve as resolve4 } from "node:path";
10152
+ import { join as join6, resolve as resolve5 } from "node:path";
9728
10153
  function lockPathFor(target, name) {
9729
10154
  return `${target}.${name}.lock`;
9730
10155
  }
9731
10156
  function isChangingLockRecord(error, target, name) {
9732
- const path2 = resolve4(lockPathFor(target, name));
10157
+ const path2 = resolve5(lockPathFor(target, name));
9733
10158
  const paths = [path2, join6(path2, "owner.json")];
9734
10159
  return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path2], "create") || isWindowsAccessDeniedCreate(error, [`${path2}.evicting`], "directory-create"));
9735
10160
  }
@@ -12473,617 +12898,194 @@ async function publishRoster(rt, plan, options = {}) {
12473
12898
  const enabled = plan.finalize.find((ref) => ref.id === row.id)?.enabled ?? row.enabled;
12474
12899
  if (!enabled || row.type !== "oauth" || row.identity === void 0)
12475
12900
  continue;
12476
- if (identities.has(row.identity))
12477
- throw refusal2("publishRoster", row.id, "invalid-input", "the final enabled roster repeats a known identity");
12478
- identities.add(row.identity);
12479
- }
12480
- for (const row of survivors) {
12481
- if (row.identity !== void 0 && row.fingerprint !== void 0 && survivors.some((other) => other.id !== row.id && other.identity !== void 0 && other.identity !== row.identity && other.fingerprint === row.fingerprint))
12482
- throw refusal2("publishRoster", row.id, "attribution", "the resulting pool gives the same secret different known identities");
12483
- }
12484
- for (const row of finalized)
12485
- if (row.identity !== void 0 && removed.some((old) => old.identity !== void 0 && old.identity !== row.identity && old.fingerprint === row.fingerprint))
12486
- throw refusal2("publishRoster", row.id, "attribution", "the staged secret belonged to a different known identity");
12487
- await protectIn(tx, plan.operationId, options.protect);
12488
- const receipt2 = {
12489
- operationId: plan.operationId,
12490
- planDigest,
12491
- phase: "committed",
12492
- removed: removed.map((row) => ({
12493
- id: row.id,
12494
- credentialEpoch: row.credentialEpoch ?? 1
12495
- })),
12496
- finalized: plan.finalize.map((ref, index) => ({
12497
- id: ref.id,
12498
- credentialEpoch: finalized[index]?.credentialEpoch ?? 1,
12499
- reservation: ref.reservation,
12500
- enabled: ref.enabled
12501
- }))
12502
- };
12503
- for (const ref of plan.remove)
12504
- tx.dropRosterRows(ref.id);
12505
- for (const ref of plan.finalize) {
12506
- const raw = tx.rosterRow(ref.id);
12507
- raw.enabled = ref.enabled;
12508
- const entry = { ...tx.entry(ref.id) };
12509
- delete entry.staged;
12510
- if (ref.enabled)
12511
- delete entry.disabledReason;
12512
- else
12513
- entry.disabledReason = ref.disabledReason;
12514
- tx.setEntry(ref.id, entry);
12515
- }
12516
- const preserved = tx.roster().filter((raw) => !isRecord4(raw) || typeof raw.id !== "string" || rows.find((row) => row.id === raw.id)?.invalid === "roster");
12517
- tx.config.accounts = [
12518
- ...plan.order.map((id) => tx.rosterRow(id)),
12519
- ...preserved
12520
- ];
12521
- saveReceipt(tx, receipt2);
12522
- await tx.syncState();
12523
- await tx.commitConfig({ durable: true, publicationDecision: true });
12524
- return { outcome: "published", receipt: await cleanup(tx, receipt2) };
12525
- }, { completeTorn: false });
12526
- if (result)
12527
- return result;
12528
- await locks.releaseAll();
12529
- if (attempt >= 1)
12530
- throw refusal2("publishRoster", plan.operationId, "row-key-changed", "a named row changed lock key twice during publication", true);
12531
- }
12532
- });
12533
- }
12534
- var init_publication = __esm({
12535
- "../core/dist/common-auth-embedded/store/publication.js"() {
12536
- "use strict";
12537
- init_hooks();
12538
- init_mutate();
12539
- init_rows();
12540
- init_runtime();
12541
- init_schema();
12542
- }
12543
- });
12544
-
12545
- // ../core/dist/common-auth-embedded/store/pull.js
12546
- var PullScheduler;
12547
- var init_pull = __esm({
12548
- "../core/dist/common-auth-embedded/store/pull.js"() {
12549
- "use strict";
12550
- init_attribution();
12551
- init_errors();
12552
- init_mutate();
12553
- init_refresh_lock();
12554
- init_runtime();
12555
- PullScheduler = class {
12556
- rt;
12557
- hook;
12558
- onFailure;
12559
- firedAtLoad;
12560
- logger;
12561
- inflight = /* @__PURE__ */ new Set();
12562
- constructor(rt, hook, onFailure, firedAtLoad, logger2) {
12563
- this.rt = rt;
12564
- this.hook = hook;
12565
- this.onFailure = onFailure;
12566
- this.firedAtLoad = firedAtLoad;
12567
- this.logger = logger2;
12568
- }
12569
- fire(id, reason) {
12570
- if (!this.hook)
12571
- return;
12572
- if (reason === "load") {
12573
- if (this.firedAtLoad.has(id))
12574
- return;
12575
- this.firedAtLoad.add(id);
12576
- }
12577
- const run = this.run(id, reason);
12578
- this.inflight.add(run);
12579
- void run.finally(() => this.inflight.delete(run));
12580
- }
12581
- /** Resolves once every pull fired so far has settled. */
12582
- async settled() {
12583
- while (this.inflight.size > 0)
12584
- await Promise.allSettled([...this.inflight]);
12585
- }
12586
- async run(id, reason) {
12587
- const rt = this.rt();
12588
- const { ctx } = rt;
12589
- const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
12590
- const progress = { writes: 0 };
12591
- try {
12592
- const request2 = await withTransaction(ctx, locks, progress, { operation: "pull", rowId: id }, async (tx) => {
12593
- if (tx.reservation(id) !== void 0)
12594
- return void 0;
12595
- await tx.completeTorn();
12596
- const row = tx.row(id);
12597
- if (row?.unbound && row.enabled && row.type === "oauth" && row.credential && !row.invalid)
12598
- requireBound("pull", row);
12599
- if (!row?.candidate || row.type !== "oauth")
12600
- return void 0;
12601
- if (!row.hasEntry) {
12602
- tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
12603
- await tx.commitConfig();
12604
- }
12605
- const current = tx.row(id);
12606
- if (!current?.credential || current.credentialEpoch === void 0)
12607
- return void 0;
12608
- return {
12609
- id,
12610
- credential: current.credential,
12611
- credentialEpoch: current.credentialEpoch,
12612
- ...current.identity !== void 0 ? { identity: current.identity } : {},
12613
- reason
12614
- };
12615
- }, { completeTorn: false });
12616
- await locks.releaseAll();
12617
- if (!request2) {
12618
- this.firedAtLoad.delete(id);
12619
- return;
12620
- }
12621
- await ctx.hold?.("pull-before-request", id);
12622
- let observation;
12623
- try {
12624
- observation = await this.hook?.(request2);
12625
- } catch (cause) {
12626
- throw new PoolOperationError({
12627
- operation: "pull",
12628
- rowId: id,
12629
- phase: "pull",
12630
- retryable: true,
12631
- kind: "pull",
12632
- message: "the quota pull rejected",
12633
- cause
12634
- });
12635
- }
12636
- const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
12637
- await publish(id, {
12638
- credentialEpoch: request2.credentialEpoch,
12639
- ...request2.identity !== void 0 ? { identity: request2.identity } : {}
12640
- }, observation);
12641
- } catch (error) {
12642
- this.firedAtLoad.delete(id);
12643
- const failure = toFailure(error, "pull", id, progress);
12644
- if (this.onFailure) {
12645
- try {
12646
- await this.onFailure(id, failure);
12647
- } catch (hookError) {
12648
- this.logger?.warn("pull failure hook threw", {
12649
- rowId: id,
12650
- error: hookError instanceof Error ? hookError.message : String(hookError)
12651
- });
12652
- }
12653
- } else {
12654
- this.logger?.warn("quota pull failed", {
12655
- rowId: id,
12656
- kind: failure.kind
12657
- });
12658
- }
12659
- } finally {
12660
- await locks.releaseAll();
12661
- }
12662
- }
12663
- };
12664
- }
12665
- });
12666
-
12667
- // ../core/dist/common-auth-embedded/logger/capture-sink.js
12668
- function createCaptureSink() {
12669
- const records = [];
12670
- const sink = (record3) => {
12671
- records.push(record3);
12672
- };
12673
- return {
12674
- records,
12675
- sink,
12676
- clear: () => {
12677
- records.length = 0;
12678
- }
12679
- };
12680
- }
12681
- var init_capture_sink = __esm({
12682
- "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
12683
- "use strict";
12684
- }
12685
- });
12686
-
12687
- // ../core/dist/common-auth-embedded/logger/redact.js
12688
- function isError(value) {
12689
- return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
12690
- }
12691
- function createRedactor(options = {}) {
12692
- const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
12693
- function isSecretKey(key) {
12694
- const normalized = key.toLowerCase().replace(/[-_]/g, "");
12695
- return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
12696
- }
12697
- function errorEntries(error) {
12698
- const fields2 = error;
12699
- const entries = [
12700
- ["name", error.name],
12701
- ["message", error.message],
12702
- ["stack", error.stack]
12703
- ];
12704
- for (const key of ["code", "status", "cause"])
12705
- if (fields2[key] !== void 0)
12706
- entries.push([key, fields2[key]]);
12707
- const listed = new Set(entries.map(([key]) => key));
12708
- for (const entry of Object.entries(error))
12709
- if (!listed.has(entry[0]))
12710
- entries.push(entry);
12711
- return entries;
12712
- }
12713
- function walk(value, keys, seen, errorDepth = 0) {
12714
- if (typeof value === "string") {
12715
- return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
12716
- }
12717
- if (!value || typeof value !== "object")
12718
- return value;
12719
- if (seen.has(value))
12720
- return "[Circular]";
12721
- seen.add(value);
12722
- try {
12723
- if (Array.isArray(value))
12724
- return value.map((item) => walk(item, keys, seen, errorDepth));
12725
- const error = isError(value);
12726
- if (error && errorDepth >= MAX_ERROR_DEPTH)
12727
- return "[Truncated]";
12728
- const childDepth = error ? errorDepth + 1 : errorDepth;
12729
- return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
12730
- key,
12731
- keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
12732
- ]));
12733
- } finally {
12734
- seen.delete(value);
12735
- }
12736
- }
12737
- return {
12738
- redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
12739
- // Schema keys describe arguments, not credentials; only their string values are scrubbed.
12740
- redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
12741
- };
12742
- }
12743
- var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
12744
- var init_redact = __esm({
12745
- "../core/dist/common-auth-embedded/logger/redact.js"() {
12746
- "use strict";
12747
- SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
12748
- TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
12749
- MASK = "***REDACTED***";
12750
- MAX_ERROR_DEPTH = 8;
12751
- defaultRedactor = createRedactor();
12752
- redact = defaultRedactor.redact;
12753
- redactStrings = defaultRedactor.redactStrings;
12754
- }
12755
- });
12756
-
12757
- // ../core/dist/common-auth-embedded/logger/engine.js
12758
- import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
12759
- import { open as open5 } from "node:fs/promises";
12760
- import { dirname as dirname8, resolve as resolve5 } from "node:path";
12761
- function chmodPrivate(path2) {
12762
- try {
12763
- chmodSync(path2, 384);
12764
- } catch {
12765
- }
12766
- }
12767
- function rotateIfNeeded(f) {
12768
- try {
12769
- if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
12770
- return;
12771
- for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
12772
- if (existsSync(`${f}.${i}`)) {
12773
- const rotated2 = `${f}.${i + 1}`;
12774
- renameSync(`${f}.${i}`, rotated2);
12775
- chmodPrivate(rotated2);
12776
- }
12777
- }
12778
- const rotated = `${f}.1`;
12779
- renameSync(f, rotated);
12780
- chmodPrivate(rotated);
12781
- } catch {
12782
- }
12783
- }
12784
- async function closeWindowsFile(sink) {
12785
- const { file, handle } = sink;
12786
- sink.file = void 0;
12787
- sink.handle = void 0;
12788
- if (file && handle)
12789
- await privateOperation(file, "log-close", () => handle.close());
12790
- }
12791
- async function openWindowsFile(sink, file) {
12792
- await ensurePrivateDirectory(dirname8(file));
12793
- try {
12794
- await verifyPrivate(file, "file", true);
12795
- } catch (error) {
12796
- if (error.code !== "ENOENT")
12797
- throw error;
12798
- try {
12799
- await createPrivateBytes(file, "");
12800
- } catch (creationError) {
12801
- if (creationError.code !== "EEXIST")
12802
- throw creationError;
12803
- await verifyPrivate(file, "file", true);
12804
- }
12805
- }
12806
- sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
12807
- sink.file = file;
12808
- return sink.handle;
12809
- }
12810
- async function flushWindowsFile(sink, file, text2) {
12811
- file = resolve5(file);
12812
- try {
12813
- if (sink.file !== file)
12814
- await closeWindowsFile(sink);
12815
- let handle = sink.handle ?? await openWindowsFile(sink, file);
12816
- const info = await privateOperation(file, "log-stat", () => handle.stat());
12817
- if (info.size >= MAX_BYTES) {
12818
- await closeWindowsFile(sink);
12819
- for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
12820
- const source = i === 0 ? file : `${file}.${i}`;
12821
- const target = `${file}.${i + 1}`;
12822
- try {
12823
- await verifyPrivate(source, "file", true);
12824
- } catch (error) {
12825
- if (error.code === "ENOENT")
12826
- continue;
12827
- throw error;
12828
- }
12829
- try {
12830
- await verifyPrivate(target, "file", true);
12831
- } catch (error) {
12832
- if (error.code !== "ENOENT")
12833
- throw error;
12834
- }
12835
- await replaceWindowsFile(source, target);
12836
- await verifyPrivate(target, "file");
12837
- }
12838
- handle = await openWindowsFile(sink, file);
12839
- }
12840
- await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
12841
- } catch (error) {
12842
- await closeWindowsFile(sink).catch(() => {
12843
- });
12844
- throw error;
12845
- }
12846
- }
12847
- function safeSerialize(data) {
12848
- try {
12849
- return ` ${JSON.stringify(data)}`;
12850
- } catch {
12851
- return " [unserializable]";
12852
- }
12853
- }
12854
- function createEngine(options) {
12855
- let logFileSource;
12856
- let initLevelSource;
12857
- let runtimeLevel;
12858
- let redactor = createRedactor();
12859
- let captureSink;
12860
- let buffer = [];
12861
- let timer;
12862
- let orderedSink = Promise.resolve();
12863
- let sinkError;
12864
- const windowsFile = {};
12865
- function queueWindows(operation) {
12866
- const next = orderedSink.then(operation);
12867
- orderedSink = next.catch((error) => {
12868
- sinkError = error;
12869
- });
12870
- return next;
12871
- }
12872
- function configure(next) {
12873
- if (windowsPrivateFiles && next.file !== logFileSource)
12874
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
12875
- });
12876
- logFileSource = next.file;
12877
- initLevelSource = next.level;
12878
- redactor = createRedactor(next);
12879
- captureSink = next.captureSink;
12880
- }
12881
- function setLogLevel3(l) {
12882
- if (l === void 0 || l in ORDER)
12883
- runtimeLevel = l;
12884
- }
12885
- function logFilePath() {
12886
- if (logFileSource === void 0)
12887
- return void 0;
12888
- const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
12889
- return resolved || void 0;
12890
- }
12891
- function configuredLevel() {
12892
- if (runtimeLevel)
12893
- return runtimeLevel;
12894
- const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
12895
- if (floor && floor in ORDER)
12896
- return floor;
12897
- return "info";
12898
- }
12899
- function flushLogs3(close = true) {
12900
- if (timer) {
12901
- clearTimeout(timer);
12902
- timer = void 0;
12903
- }
12904
- if (!buffer.length) {
12905
- if (windowsPrivateFiles)
12906
- return queueWindows(async () => {
12907
- if (close)
12908
- await closeWindowsFile(windowsFile);
12909
- if (sinkError)
12910
- throw sinkError;
12911
- });
12912
- return;
12913
- }
12914
- let file;
12915
- try {
12916
- file = logFilePath();
12917
- } catch {
12918
- buffer = [];
12919
- if (windowsPrivateFiles && close)
12920
- return queueWindows(() => closeWindowsFile(windowsFile));
12921
- return;
12922
- }
12923
- const text2 = buffer.join("");
12924
- buffer = [];
12925
- if (!file) {
12926
- if (windowsPrivateFiles && close)
12927
- return queueWindows(() => closeWindowsFile(windowsFile));
12928
- return;
12929
- }
12930
- if (windowsPrivateFiles) {
12931
- return queueWindows(async () => {
12932
- try {
12933
- await flushWindowsFile(windowsFile, file, text2);
12934
- } finally {
12935
- if (close)
12936
- await closeWindowsFile(windowsFile);
12937
- }
12938
- });
12939
- }
12940
- try {
12941
- rotateIfNeeded(file);
12942
- if (existsSync(file))
12943
- chmodPrivate(file);
12944
- appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
12945
- } catch {
12946
- }
12947
- }
12948
- function schedule2() {
12949
- if (!timer)
12950
- timer = setTimeout(() => {
12951
- timer = void 0;
12952
- const flushed = flushLogs3(false);
12953
- if (flushed instanceof Promise)
12954
- void flushed.catch(() => {
12955
- });
12956
- }, 500);
12957
- }
12958
- function emit(channel3, level, message, data) {
12959
- if (logFileSource === void 0 && captureSink === void 0)
12960
- return;
12961
- try {
12962
- if (ORDER[level] > ORDER[configuredLevel()])
12963
- return;
12964
- const scrubbedMessage = redactor.redactStrings(message);
12965
- let scrubbedData;
12966
- try {
12967
- scrubbedData = redactor.redact(data);
12968
- } catch {
12969
- scrubbedData = "[unserializable]";
12970
- }
12971
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel3}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
12972
- try {
12973
- captureSink?.({
12974
- channel: channel3,
12975
- level,
12976
- message: scrubbedMessage,
12977
- data: scrubbedData
12978
- });
12979
- } catch {
12980
- }
12981
- if (logFileSource === void 0)
12982
- return;
12983
- buffer.push(line);
12984
- if (buffer.length >= 50) {
12985
- const flushed = flushLogs3(false);
12986
- if (flushed instanceof Promise)
12987
- void flushed.catch(() => {
12988
- });
12989
- } else
12990
- schedule2();
12991
- } catch {
12992
- }
12993
- }
12994
- function createLogger5(channel3) {
12995
- return {
12996
- error: (m, d) => emit(channel3, "error", m, d),
12997
- warn: (m, d) => emit(channel3, "warn", m, d),
12998
- info: (m, d) => emit(channel3, "info", m, d),
12999
- debug: (m, d) => emit(channel3, "debug", m, d),
13000
- trace: (m, d) => emit(channel3, "trace", m, d)
13001
- };
13002
- }
13003
- function reset() {
13004
- if (windowsPrivateFiles)
13005
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
13006
- });
13007
- sinkError = void 0;
13008
- buffer = [];
13009
- if (timer) {
13010
- clearTimeout(timer);
13011
- timer = void 0;
12901
+ if (identities.has(row.identity))
12902
+ throw refusal2("publishRoster", row.id, "invalid-input", "the final enabled roster repeats a known identity");
12903
+ identities.add(row.identity);
12904
+ }
12905
+ for (const row of survivors) {
12906
+ if (row.identity !== void 0 && row.fingerprint !== void 0 && survivors.some((other) => other.id !== row.id && other.identity !== void 0 && other.identity !== row.identity && other.fingerprint === row.fingerprint))
12907
+ throw refusal2("publishRoster", row.id, "attribution", "the resulting pool gives the same secret different known identities");
12908
+ }
12909
+ for (const row of finalized)
12910
+ if (row.identity !== void 0 && removed.some((old) => old.identity !== void 0 && old.identity !== row.identity && old.fingerprint === row.fingerprint))
12911
+ throw refusal2("publishRoster", row.id, "attribution", "the staged secret belonged to a different known identity");
12912
+ await protectIn(tx, plan.operationId, options.protect);
12913
+ const receipt2 = {
12914
+ operationId: plan.operationId,
12915
+ planDigest,
12916
+ phase: "committed",
12917
+ removed: removed.map((row) => ({
12918
+ id: row.id,
12919
+ credentialEpoch: row.credentialEpoch ?? 1
12920
+ })),
12921
+ finalized: plan.finalize.map((ref, index) => ({
12922
+ id: ref.id,
12923
+ credentialEpoch: finalized[index]?.credentialEpoch ?? 1,
12924
+ reservation: ref.reservation,
12925
+ enabled: ref.enabled
12926
+ }))
12927
+ };
12928
+ for (const ref of plan.remove)
12929
+ tx.dropRosterRows(ref.id);
12930
+ for (const ref of plan.finalize) {
12931
+ const raw = tx.rosterRow(ref.id);
12932
+ raw.enabled = ref.enabled;
12933
+ const entry = { ...tx.entry(ref.id) };
12934
+ delete entry.staged;
12935
+ if (ref.enabled)
12936
+ delete entry.disabledReason;
12937
+ else
12938
+ entry.disabledReason = ref.disabledReason;
12939
+ tx.setEntry(ref.id, entry);
12940
+ }
12941
+ const preserved = tx.roster().filter((raw) => !isRecord4(raw) || typeof raw.id !== "string" || rows.find((row) => row.id === raw.id)?.invalid === "roster");
12942
+ tx.config.accounts = [
12943
+ ...plan.order.map((id) => tx.rosterRow(id)),
12944
+ ...preserved
12945
+ ];
12946
+ saveReceipt(tx, receipt2);
12947
+ await tx.syncState();
12948
+ await tx.commitConfig({ durable: true, publicationDecision: true });
12949
+ return { outcome: "published", receipt: await cleanup(tx, receipt2) };
12950
+ }, { completeTorn: false });
12951
+ if (result)
12952
+ return result;
12953
+ await locks.releaseAll();
12954
+ if (attempt >= 1)
12955
+ throw refusal2("publishRoster", plan.operationId, "row-key-changed", "a named row changed lock key twice during publication", true);
13012
12956
  }
13013
- logFileSource = void 0;
13014
- initLevelSource = void 0;
13015
- runtimeLevel = void 0;
13016
- redactor = createRedactor();
13017
- captureSink = void 0;
13018
- }
13019
- if (options)
13020
- configure(options);
13021
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
13022
- }
13023
- function createLoggerInstance(options) {
13024
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
13025
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
13026
- }
13027
- function initLogger(options) {
13028
- defaultEngine.configure(options);
13029
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
13030
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
13031
- }
13032
- function setLogLevel(l) {
13033
- defaultEngine.setLogLevel(l);
13034
- }
13035
- function flushLogs() {
13036
- return defaultEngine.flushLogs();
13037
- }
13038
- function createLogger2(channel3) {
13039
- return defaultEngine.createLogger(channel3);
13040
- }
13041
- async function flushForTest() {
13042
- return defaultEngine.flushLogs();
13043
- }
13044
- function resetLoggerForTest() {
13045
- defaultEngine.reset();
12957
+ });
13046
12958
  }
13047
- var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
13048
- var init_engine = __esm({
13049
- "../core/dist/common-auth-embedded/logger/engine.js"() {
12959
+ var init_publication = __esm({
12960
+ "../core/dist/common-auth-embedded/store/publication.js"() {
13050
12961
  "use strict";
13051
- init_private_files();
13052
- init_redact();
13053
- ORDER = {
13054
- error: 0,
13055
- warn: 1,
13056
- info: 2,
13057
- debug: 3,
13058
- trace: 4
13059
- };
13060
- MAX_BYTES = 5 * 1024 * 1024;
13061
- ROTATE_KEEP = 3;
13062
- defaultEngine = createEngine();
12962
+ init_hooks();
12963
+ init_mutate();
12964
+ init_rows();
12965
+ init_runtime();
12966
+ init_schema();
13063
12967
  }
13064
12968
  });
13065
12969
 
13066
- // ../core/dist/common-auth-embedded/logger/index.js
13067
- var logger_exports = {};
13068
- __export(logger_exports, {
13069
- createCaptureSink: () => createCaptureSink,
13070
- createLogger: () => createLogger2,
13071
- createLoggerInstance: () => createLoggerInstance,
13072
- createRedactor: () => createRedactor,
13073
- flushForTest: () => flushForTest,
13074
- flushLogs: () => flushLogs,
13075
- initLogger: () => initLogger,
13076
- redact: () => redact,
13077
- redactStrings: () => redactStrings,
13078
- resetLoggerForTest: () => resetLoggerForTest,
13079
- setLogLevel: () => setLogLevel
13080
- });
13081
- var init_logger2 = __esm({
13082
- "../core/dist/common-auth-embedded/logger/index.js"() {
12970
+ // ../core/dist/common-auth-embedded/store/pull.js
12971
+ var PullScheduler;
12972
+ var init_pull = __esm({
12973
+ "../core/dist/common-auth-embedded/store/pull.js"() {
13083
12974
  "use strict";
13084
- init_capture_sink();
13085
- init_engine();
13086
- init_redact();
12975
+ init_attribution();
12976
+ init_errors();
12977
+ init_mutate();
12978
+ init_refresh_lock();
12979
+ init_runtime();
12980
+ PullScheduler = class {
12981
+ rt;
12982
+ hook;
12983
+ onFailure;
12984
+ firedAtLoad;
12985
+ logger;
12986
+ inflight = /* @__PURE__ */ new Set();
12987
+ constructor(rt, hook, onFailure, firedAtLoad, logger2) {
12988
+ this.rt = rt;
12989
+ this.hook = hook;
12990
+ this.onFailure = onFailure;
12991
+ this.firedAtLoad = firedAtLoad;
12992
+ this.logger = logger2;
12993
+ }
12994
+ fire(id, reason) {
12995
+ if (!this.hook)
12996
+ return;
12997
+ if (reason === "load") {
12998
+ if (this.firedAtLoad.has(id))
12999
+ return;
13000
+ this.firedAtLoad.add(id);
13001
+ }
13002
+ const run = this.run(id, reason);
13003
+ this.inflight.add(run);
13004
+ void run.finally(() => this.inflight.delete(run));
13005
+ }
13006
+ /** Resolves once every pull fired so far has settled. */
13007
+ async settled() {
13008
+ while (this.inflight.size > 0)
13009
+ await Promise.allSettled([...this.inflight]);
13010
+ }
13011
+ async run(id, reason) {
13012
+ const rt = this.rt();
13013
+ const { ctx } = rt;
13014
+ const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
13015
+ const progress = { writes: 0 };
13016
+ try {
13017
+ const request2 = await withTransaction(ctx, locks, progress, { operation: "pull", rowId: id }, async (tx) => {
13018
+ if (tx.reservation(id) !== void 0)
13019
+ return void 0;
13020
+ await tx.completeTorn();
13021
+ const row = tx.row(id);
13022
+ if (row?.unbound && row.enabled && row.type === "oauth" && row.credential && !row.invalid)
13023
+ requireBound("pull", row);
13024
+ if (!row?.candidate || row.type !== "oauth")
13025
+ return void 0;
13026
+ if (!row.hasEntry) {
13027
+ tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
13028
+ await tx.commitConfig();
13029
+ }
13030
+ const current = tx.row(id);
13031
+ if (!current?.credential || current.credentialEpoch === void 0)
13032
+ return void 0;
13033
+ return {
13034
+ id,
13035
+ credential: current.credential,
13036
+ credentialEpoch: current.credentialEpoch,
13037
+ ...current.identity !== void 0 ? { identity: current.identity } : {},
13038
+ reason
13039
+ };
13040
+ }, { completeTorn: false });
13041
+ await locks.releaseAll();
13042
+ if (!request2) {
13043
+ this.firedAtLoad.delete(id);
13044
+ return;
13045
+ }
13046
+ await ctx.hold?.("pull-before-request", id);
13047
+ let observation;
13048
+ try {
13049
+ observation = await this.hook?.(request2);
13050
+ } catch (cause) {
13051
+ throw new PoolOperationError({
13052
+ operation: "pull",
13053
+ rowId: id,
13054
+ phase: "pull",
13055
+ retryable: true,
13056
+ kind: "pull",
13057
+ message: "the quota pull rejected",
13058
+ cause
13059
+ });
13060
+ }
13061
+ const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
13062
+ await publish(id, {
13063
+ credentialEpoch: request2.credentialEpoch,
13064
+ ...request2.identity !== void 0 ? { identity: request2.identity } : {}
13065
+ }, observation);
13066
+ } catch (error) {
13067
+ this.firedAtLoad.delete(id);
13068
+ const failure = toFailure(error, "pull", id, progress);
13069
+ if (this.onFailure) {
13070
+ try {
13071
+ await this.onFailure(id, failure);
13072
+ } catch (hookError) {
13073
+ this.logger?.warn("pull failure hook threw", {
13074
+ rowId: id,
13075
+ error: hookError instanceof Error ? hookError.message : String(hookError)
13076
+ });
13077
+ }
13078
+ } else {
13079
+ this.logger?.warn("quota pull failed", {
13080
+ rowId: id,
13081
+ kind: failure.kind
13082
+ });
13083
+ }
13084
+ } finally {
13085
+ await locks.releaseAll();
13086
+ }
13087
+ }
13088
+ };
13087
13089
  }
13088
13090
  });
13089
13091
 
@@ -24460,6 +24462,9 @@ function createLoggerInstance2(options) {
24460
24462
  const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine2(options);
24461
24463
  return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
24462
24464
  }
24465
+ function createLogger3(channel3) {
24466
+ return defaultEngine2.createLogger(channel3);
24467
+ }
24463
24468
  var ORDER2, MAX_BYTES2, ROTATE_KEEP2, defaultEngine2;
24464
24469
  var init_engine2 = __esm({
24465
24470
  "src/common-auth-embedded/logger/engine.js"() {
@@ -28823,6 +28828,7 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
28823
28828
  init_private_files2();
28824
28829
 
28825
28830
  // src/common-auth-embedded/fs/refresh-file-lock.js
28831
+ init_logger3();
28826
28832
  import { randomUUID as randomUUID14 } from "node:crypto";
28827
28833
  import { link as link3, lstat as lstat8, mkdir as mkdir13, open as open9, readdir as readdir5, readFile as readFile11, rename as rename11, rm as rm6, stat as stat12, unlink as unlink12 } from "node:fs/promises";
28828
28834
  import { basename as basename6, dirname as dirname18, join as join17 } from "node:path";
@@ -29777,17 +29783,15 @@ async function acquireRefreshFileLockWithClock2(options) {
29777
29783
  removalConfirmed = true;
29778
29784
  }, deadline);
29779
29785
  changingRecordError = void 0;
29780
- if (markerAcquired) {
29781
- if (windowsPrivateFiles2 && !removalConfirmed)
29782
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
29783
- code: "EIO"
29784
- });
29785
- releaseConfirmed = removalConfirmed;
29786
+ if (markerAcquired && removalConfirmed) {
29787
+ releaseConfirmed = true;
29786
29788
  return;
29787
29789
  }
29788
- if (signal?.aborted)
29789
- return;
29790
- await recoverStaleEvictionMarker(deadline);
29790
+ if (!markerAcquired) {
29791
+ if (signal?.aborted)
29792
+ return;
29793
+ await recoverStaleEvictionMarker(deadline);
29794
+ }
29791
29795
  } catch (error) {
29792
29796
  const changingRecord = windowsPrivateFiles2 && (isChangingLockCreate(error) || isWindowsAccessDeniedRead2(error, [
29793
29797
  lockPath,
@@ -29817,6 +29821,9 @@ async function acquireRefreshFileLockWithClock2(options) {
29817
29821
  throw changingRecordError ?? removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
29818
29822
  code: "ETIMEDOUT"
29819
29823
  });
29824
+ createLogger3("fs").warn("File lock release deadline expired", {
29825
+ lockPath
29826
+ });
29820
29827
  }
29821
29828
  };
29822
29829
  }