@gruu6y/page-clean-login 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/proxies.mjs CHANGED
@@ -5,6 +5,7 @@ import { join } from "node:path";
5
5
  export const PROXY_FILE_NAME = "proxies.json";
6
6
  export const PROXY_TYPES = ["http", "https", "socks5"];
7
7
  export const PROXY_STATUSES = ["untested", "testing", "ok", "error"];
8
+ export const PROXY_BULK_LIMIT = 200;
8
9
 
9
10
  const CONTROL = /[\u0000-\u001f\u007f]/;
10
11
  const NUL = /\u0000/;
@@ -167,6 +168,7 @@ export function validateUpdate(body) {
167
168
  if ("port" in input) changes.port = readPort(input.port, true);
168
169
  if ("username" in input) changes.username = readUsername(input.username);
169
170
  if ("password" in input) changes.password = readPassword(input.password);
171
+ else if (input.clearPassword === true) changes.password = "";
170
172
  if (!Object.keys(changes).length) {
171
173
  throw new ProxyInputError("invalid_body", "No proxy fields were provided.");
172
174
  }
@@ -191,7 +193,229 @@ export function validateProbe(body, stored = null) {
191
193
  };
192
194
  }
193
195
 
196
+ export function proxyConnectionKey(proxy) {
197
+ const type = typeof proxy?.type === "string" ? proxy.type.trim().toLowerCase() : "";
198
+ let host = typeof proxy?.host === "string" ? proxy.host.trim().toLowerCase() : "";
199
+ if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
200
+ const port = Number(proxy?.port);
201
+ const username = typeof proxy?.username === "string" ? proxy.username.trim() : "";
202
+ return `${type}|${host}|${Number.isFinite(port) ? port : ""}|${username}`;
203
+ }
204
+
205
+ function safeDecodeComponent(value) {
206
+ if (!value) return "";
207
+ try {
208
+ return decodeURIComponent(value);
209
+ } catch {
210
+ return value;
211
+ }
212
+ }
213
+
214
+ function cleanLabelText(value) {
215
+ return String(value ?? "").replace(/[<>\u0000-\u001f\u007f]/g, "").trim();
216
+ }
217
+
218
+ function uniqueProxyName(base, usedNames) {
219
+ const clean = cleanLabelText(base).slice(0, LIMITS.name) || "proxy";
220
+ if (!usedNames.has(clean)) {
221
+ usedNames.add(clean);
222
+ return clean;
223
+ }
224
+ for (let suffix = 2; suffix < 100_000; suffix += 1) {
225
+ const tag = `-${suffix}`;
226
+ const candidate = `${clean.slice(0, Math.max(1, LIMITS.name - tag.length))}${tag}`;
227
+ if (!usedNames.has(candidate)) {
228
+ usedNames.add(candidate);
229
+ return candidate;
230
+ }
231
+ }
232
+ return clean;
233
+ }
234
+
235
+ function splitLineLabel(line) {
236
+ const match = /^(\S+)(?:\s+(.+))?$/.exec(line);
237
+ if (!match) return { spec: line, label: "" };
238
+ const spec = match[1];
239
+ const label = cleanLabelText(match[2] ?? "");
240
+ return { spec, label };
241
+ }
242
+
243
+ function parseHostPortAndAuth(spec, fallbackType = "http") {
244
+ const atIndex = spec.lastIndexOf("@");
245
+ let user = "";
246
+ let pass = "";
247
+ let target = spec;
248
+ if (atIndex >= 0) {
249
+ const authPart = spec.slice(0, atIndex);
250
+ target = spec.slice(atIndex + 1);
251
+ const colon = authPart.indexOf(":");
252
+ if (colon < 0) return { ok: false, reason: "invalid_auth" };
253
+ user = safeDecodeComponent(authPart.slice(0, colon));
254
+ pass = safeDecodeComponent(authPart.slice(colon + 1));
255
+ }
256
+
257
+ if (target.startsWith("[")) {
258
+ const bracket = /^\[([^\]]+)\]:(\d{1,5})(?::([^:]*):(.*))?$/.exec(target);
259
+ if (!bracket) return { ok: false, reason: "invalid_port" };
260
+ return {
261
+ ok: true,
262
+ type: fallbackType,
263
+ host: bracket[1],
264
+ port: bracket[2],
265
+ username: atIndex >= 0 ? user : bracket[3] ?? "",
266
+ password: atIndex >= 0 ? pass : bracket[4] ?? "",
267
+ };
268
+ }
269
+
270
+ const parts = target.split(":");
271
+ if (parts.length === 2) {
272
+ return { ok: true, type: fallbackType, host: parts[0], port: parts[1], username: user, password: pass };
273
+ }
274
+ if (atIndex < 0 && parts.length >= 4 && /^\d{1,5}$/.test(parts[1])) {
275
+ if (parts.length > 4 && !parts[0].includes(".")) {
276
+ return { ok: false, reason: "invalid_host" };
277
+ }
278
+ return {
279
+ ok: true,
280
+ type: fallbackType,
281
+ host: parts[0],
282
+ port: parts[1],
283
+ username: parts[2],
284
+ password: parts.slice(3).join(":"),
285
+ };
286
+ }
287
+ return { ok: false, reason: parts.length === 1 ? "invalid_port" : "invalid_format" };
288
+ }
289
+
290
+ function parseProxyLine(line, fallbackType = "http") {
291
+ let working = line;
292
+ let pipedLabel = "";
293
+ const piped = /^([^|\s]+)\|([a-z][a-z0-9+.-]*:\/\/.+)$/i.exec(working);
294
+ if (piped) {
295
+ pipedLabel = cleanLabelText(piped[1]);
296
+ working = piped[2];
297
+ }
298
+
299
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(working)) {
300
+ const { spec, label: trailingLabel } = splitLineLabel(working);
301
+ let parsed;
302
+ try {
303
+ parsed = new URL(spec);
304
+ } catch {
305
+ return { ok: false, reason: "invalid_url" };
306
+ }
307
+ const rawScheme = parsed.protocol.slice(0, -1).toLowerCase();
308
+ const type = rawScheme === "socks5h" ? "socks5" : rawScheme;
309
+ if (!PROXY_TYPES.includes(type)) return { ok: false, reason: "invalid_type" };
310
+ if (!parsed.port) return { ok: false, reason: "invalid_port" };
311
+ const hashLabel = cleanLabelText(safeDecodeComponent(parsed.hash.replace(/^#/, "")));
312
+ return {
313
+ ok: true,
314
+ type,
315
+ host: parsed.hostname,
316
+ port: parsed.port,
317
+ username: safeDecodeComponent(parsed.username),
318
+ password: safeDecodeComponent(parsed.password),
319
+ label: pipedLabel || trailingLabel || hashLabel,
320
+ };
321
+ }
322
+
323
+ const hashIdx = working.indexOf(" #");
324
+ let body = working;
325
+ let hashLabel = "";
326
+ if (hashIdx >= 0) {
327
+ body = working.slice(0, hashIdx).trim();
328
+ hashLabel = cleanLabelText(working.slice(hashIdx + 2));
329
+ }
330
+ const { spec, label: spaceLabel } = splitLineLabel(body);
331
+ const parsed = parseHostPortAndAuth(spec, fallbackType);
332
+ if (!parsed.ok) return parsed;
333
+ return { ...parsed, label: pipedLabel || spaceLabel || hashLabel };
334
+ }
335
+
336
+ // Parse plain-text proxy lines into validated create payloads without ever
337
+ // echoing raw passwords or lines back in duplicate/invalid reports.
338
+ export function parseBulkProxies(
339
+ text,
340
+ { defaultType = "http", prefix = "", existingNames = [], existingKeys = [], limit = PROXY_BULK_LIMIT } = {},
341
+ ) {
342
+ const normalizedDefault = String(defaultType ?? "http").trim().toLowerCase();
343
+ const fallbackType = PROXY_TYPES.includes(normalizedDefault) ? normalizedDefault : "http";
344
+ const maxItems = Number.isInteger(limit) && limit > 0 ? limit : PROXY_BULK_LIMIT;
345
+ const safePrefix = cleanLabelText(prefix);
346
+ const usedNames = new Set(
347
+ (Array.isArray(existingNames) ? existingNames : [])
348
+ .filter((name) => typeof name === "string")
349
+ .map((name) => name.trim())
350
+ .filter(Boolean),
351
+ );
352
+ const seenKeys = new Set(
353
+ (Array.isArray(existingKeys) ? existingKeys : []).filter(
354
+ (key) => typeof key === "string" && key,
355
+ ),
356
+ );
357
+ const items = [];
358
+ const duplicates = [];
359
+ const invalid = [];
360
+ let truncated = 0;
361
+
362
+ const lines = typeof text === "string" ? text.split(/\r?\n/) : [];
363
+ for (let index = 0; index < lines.length; index += 1) {
364
+ const raw = lines[index].trim();
365
+ if (!raw || raw.startsWith("#") || raw.startsWith("//")) continue;
366
+ const line = index + 1;
367
+ if (items.length >= maxItems) {
368
+ truncated += 1;
369
+ continue;
370
+ }
371
+ const parsed = parseProxyLine(raw, fallbackType);
372
+ if (!parsed.ok) {
373
+ invalid.push({ line, reason: parsed.reason || "invalid_format" });
374
+ continue;
375
+ }
376
+ const baseLabel = parsed.label
377
+ ? (safePrefix ? `${safePrefix} ${parsed.label}` : parsed.label)
378
+ : (() => {
379
+ const hostDisplay = parsed.host.includes(":") && !parsed.host.startsWith("[")
380
+ ? `[${parsed.host}]`
381
+ : parsed.host;
382
+ return safePrefix ? `${safePrefix}-${hostDisplay}:${parsed.port}` : `${hostDisplay}:${parsed.port}`;
383
+ })();
384
+ let validated;
385
+ try {
386
+ validated = validateCreate({
387
+ name: "placeholder",
388
+ type: parsed.type,
389
+ host: parsed.host,
390
+ port: parsed.port,
391
+ username: parsed.username,
392
+ password: parsed.password,
393
+ });
394
+ } catch (error) {
395
+ invalid.push({
396
+ line,
397
+ reason: error instanceof ProxyInputError ? error.code : "invalid_format",
398
+ });
399
+ continue;
400
+ }
401
+ const key = proxyConnectionKey(validated);
402
+ if (seenKeys.has(key)) {
403
+ duplicates.push({ line, reason: "duplicate" });
404
+ continue;
405
+ }
406
+ seenKeys.add(key);
407
+ validated.name = uniqueProxyName(baseLabel, usedNames);
408
+ items.push(validated);
409
+ }
410
+
411
+ return { items, duplicates, invalid, truncated };
412
+ }
413
+
194
414
  export function publicProxy(record) {
415
+ const status = PROXY_STATUSES.includes(record.status) ? record.status : "untested";
416
+ const exitStatus = PROXY_STATUSES.includes(record.exitStatus) && record.exitStatus !== "testing"
417
+ ? record.exitStatus
418
+ : status === "testing" ? "untested" : status;
195
419
  return {
196
420
  id: record.id,
197
421
  name: record.name,
@@ -202,9 +426,11 @@ export function publicProxy(record) {
202
426
  hasPassword: Boolean(record.password),
203
427
  region: record.region || "",
204
428
  exitIp: record.exitIp || "",
205
- status: PROXY_STATUSES.includes(record.status) ? record.status : "untested",
429
+ status,
430
+ exitStatus,
206
431
  latency: Number.isFinite(record.latency) ? record.latency : null,
207
432
  latencyByProvider: normalizeLatencyMap(record.latencyByProvider),
433
+ probeByProvider: normalizeProbeByProvider(record.probeByProvider),
208
434
  lastCheckedAt: record.lastCheckedAt || null,
209
435
  error: record.error || "",
210
436
  errorCode: record.errorCode || "",
@@ -218,6 +444,10 @@ export function publicProxy(record) {
218
444
  scoreErrorCode: record.scoreErrorCode || "",
219
445
  createdAt: record.createdAt,
220
446
  updatedAt: record.updatedAt,
447
+ connectionUpdatedAt: timestampOr(
448
+ record.connectionUpdatedAt,
449
+ record.updatedAt || record.createdAt || null,
450
+ ),
221
451
  };
222
452
  }
223
453
 
@@ -269,10 +499,40 @@ export function normalizeLatencyMap(raw) {
269
499
  return out;
270
500
  }
271
501
 
502
+ export function normalizeProbeByProvider(raw) {
503
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
504
+ const out = {};
505
+ for (const [id, entry] of Object.entries(raw)) {
506
+ if (!id || id.length > LIMITS.id || CONTROL.test(id)) continue;
507
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
508
+ const ok = entry.ok === true;
509
+ const ms = Number(entry.ms);
510
+ const item = {
511
+ ok,
512
+ ms: ok && Number.isFinite(ms) && ms >= 0 ? Math.round(ms) : null,
513
+ host: textOr(entry.host, LIMITS.host),
514
+ at: timestampOr(entry.at, ""),
515
+ };
516
+ if (ok && entry.handshake === true) item.handshake = true;
517
+ if (!ok) {
518
+ item.error = textOr(entry.error, LIMITS.error);
519
+ item.errorCode = textOr(entry.errorCode, LIMITS.errorCode);
520
+ }
521
+ out[id] = item;
522
+ }
523
+ return out;
524
+ }
525
+
272
526
  function timestampOr(value, fallback) {
273
527
  return typeof value === "string" && value.length <= LIMITS.timestamp ? value : fallback;
274
528
  }
275
529
 
530
+ function bumpTimestamp(previous) {
531
+ const nowMs = Date.now();
532
+ const prevMs = Date.parse(previous || "");
533
+ return new Date(Number.isFinite(prevMs) && nowMs <= prevMs ? prevMs + 1 : nowMs).toISOString();
534
+ }
535
+
276
536
  function normalizeStored(raw, now) {
277
537
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
278
538
  const id = textOr(raw.id, LIMITS.id);
@@ -289,14 +549,21 @@ function normalizeStored(raw, now) {
289
549
  const status = PROXY_STATUSES.includes(raw.status) && raw.status !== "testing"
290
550
  ? raw.status
291
551
  : "untested";
552
+ const exitStatus = PROXY_STATUSES.includes(raw.exitStatus) && raw.exitStatus !== "testing"
553
+ ? raw.exitStatus
554
+ : status;
555
+ const createdAt = timestampOr(raw.createdAt, now);
556
+ const updatedAt = timestampOr(raw.updatedAt, now);
292
557
  return {
293
558
  id,
294
559
  ...fields,
295
560
  region: textOr(raw.region, LIMITS.region),
296
561
  exitIp: textOr(raw.exitIp, LIMITS.exitIp),
297
562
  status,
563
+ exitStatus,
298
564
  latency: Number.isFinite(raw.latency) && raw.latency >= 0 ? Math.round(raw.latency) : null,
299
565
  latencyByProvider: normalizeLatencyMap(raw.latencyByProvider),
566
+ probeByProvider: normalizeProbeByProvider(raw.probeByProvider),
300
567
  lastCheckedAt: raw.lastCheckedAt ? timestampOr(raw.lastCheckedAt, null) : null,
301
568
  error: textOr(raw.error, LIMITS.error),
302
569
  errorCode: textOr(raw.errorCode, LIMITS.errorCode),
@@ -306,8 +573,9 @@ function normalizeStored(raw, now) {
306
573
  scoreCheckedAt: raw.scoreCheckedAt ? timestampOr(raw.scoreCheckedAt, null) : null,
307
574
  scoreError: textOr(raw.scoreError, LIMITS.error),
308
575
  scoreErrorCode: textOr(raw.scoreErrorCode, LIMITS.errorCode),
309
- createdAt: timestampOr(raw.createdAt, now),
310
- updatedAt: timestampOr(raw.updatedAt, now),
576
+ createdAt,
577
+ updatedAt,
578
+ connectionUpdatedAt: timestampOr(raw.connectionUpdatedAt, updatedAt || createdAt),
311
579
  };
312
580
  } catch {
313
581
  return null;
@@ -461,7 +729,10 @@ export function createProxyStore({ dataDir }) {
461
729
  region: "",
462
730
  exitIp: "",
463
731
  status: "untested",
732
+ exitStatus: "untested",
464
733
  latency: null,
734
+ latencyByProvider: {},
735
+ probeByProvider: {},
465
736
  lastCheckedAt: null,
466
737
  error: "",
467
738
  errorCode: "",
@@ -473,6 +744,7 @@ export function createProxyStore({ dataDir }) {
473
744
  scoreErrorCode: "",
474
745
  createdAt: now,
475
746
  updatedAt: now,
747
+ connectionUpdatedAt: now,
476
748
  };
477
749
  // randomUUID collisions are vanishingly unlikely, but ids are the API's
478
750
  // addressing scheme, so never let two records share one.
@@ -500,14 +772,16 @@ export function createProxyStore({ dataDir }) {
500
772
  ) {
501
773
  throw new ProxyInputError("name_taken", "A proxy with that name already exists.", 409);
502
774
  }
503
- const now = new Date().toISOString();
775
+ const now = bumpTimestamp(previous.updatedAt);
504
776
  const next = { ...previous, ...changes, updatedAt: now };
505
777
  if (connectionKey(previous) !== connectionKey(next)) {
506
778
  next.region = "";
507
779
  next.exitIp = "";
508
780
  next.status = "untested";
781
+ next.exitStatus = "untested";
509
782
  next.latency = null;
510
783
  next.latencyByProvider = {};
784
+ next.probeByProvider = {};
511
785
  next.lastCheckedAt = null;
512
786
  next.error = "";
513
787
  next.errorCode = "";
@@ -517,6 +791,7 @@ export function createProxyStore({ dataDir }) {
517
791
  next.scoreCheckedAt = null;
518
792
  next.scoreError = "";
519
793
  next.scoreErrorCode = "";
794
+ next.connectionUpdatedAt = bumpTimestamp(previous.connectionUpdatedAt || previous.updatedAt);
520
795
  }
521
796
  const before = records;
522
797
  records = records.slice();
@@ -550,7 +825,14 @@ export function createProxyStore({ dataDir }) {
550
825
  const index = records.findIndex((item) => item.id === id);
551
826
  if (index < 0) return null;
552
827
  const previous = records[index];
553
- if (expectedUpdatedAt && previous.updatedAt !== expectedUpdatedAt) return null;
828
+ const connectionRevision = previous.connectionUpdatedAt || previous.updatedAt;
829
+ if (
830
+ expectedUpdatedAt &&
831
+ expectedUpdatedAt !== connectionRevision &&
832
+ expectedUpdatedAt !== previous.updatedAt
833
+ ) {
834
+ return null;
835
+ }
554
836
  const now = new Date().toISOString();
555
837
  const probe = result.target && typeof result.target === "object" ? result.target : null;
556
838
  // A two-leg probe stays a two-leg probe even when the provider leg
@@ -575,13 +857,30 @@ export function createProxyStore({ dataDir }) {
575
857
  ? (Number.isFinite(result.exitLatency) ? result.exitLatency : null)
576
858
  : result.latency;
577
859
  const previousLatency = Number.isFinite(previous.latency) ? previous.latency : null;
860
+ const checkedAt = timestampOr(result.checkedAt, now);
861
+ const exitOk = providerProbe
862
+ ? (result.exitOk === true
863
+ ? true
864
+ : result.exitOk === false
865
+ ? false
866
+ : Number.isFinite(result.exitLatency)
867
+ ? true
868
+ : null)
869
+ : Boolean(result.ok);
870
+ const previousExitStatus =
871
+ PROXY_STATUSES.includes(previous.exitStatus) && previous.exitStatus !== "testing"
872
+ ? previous.exitStatus
873
+ : previous.status === "testing"
874
+ ? "untested"
875
+ : previous.status || "untested";
578
876
  const next = {
579
877
  ...previous,
580
878
  status: result.ok ? "ok" : "error",
879
+ exitStatus: exitOk === true ? "ok" : exitOk === false ? "error" : previousExitStatus,
581
880
  latency: result.ok && Number.isFinite(exitLatency)
582
881
  ? Math.round(exitLatency)
583
882
  : providerProbe
584
- ? previousLatency
883
+ ? (Number.isFinite(exitLatency) ? Math.round(exitLatency) : previousLatency)
585
884
  : null,
586
885
  // A provider test is two legs: the provider round trip and the exit
587
886
  // lookup. When the exit lookup did not answer, keep what the row
@@ -591,9 +890,25 @@ export function createProxyStore({ dataDir }) {
591
890
  exitIp: providerProbe && !exitIp ? previous.exitIp || "" : exitIp,
592
891
  error: result.ok ? "" : textOr(result.error, LIMITS.error, "The proxy test failed."),
593
892
  errorCode: result.ok ? "" : textOr(result.errorCode, LIMITS.errorCode),
594
- lastCheckedAt: timestampOr(result.checkedAt, now),
893
+ lastCheckedAt: checkedAt,
595
894
  updatedAt: now,
596
895
  };
896
+ if (providerProbe) {
897
+ const probes = normalizeProbeByProvider(previous.probeByProvider);
898
+ const probeEntry = {
899
+ ok: result.ok === true,
900
+ ms: result.ok === true && Number.isFinite(result.latency) ? Math.round(result.latency) : null,
901
+ host: textOr(probe.host, LIMITS.host),
902
+ at: checkedAt || "",
903
+ };
904
+ if (result.ok === true && result.tlsOnly === true) probeEntry.handshake = true;
905
+ if (!probeEntry.ok) {
906
+ probeEntry.error = next.error;
907
+ probeEntry.errorCode = next.errorCode;
908
+ }
909
+ probes[probe.provider] = probeEntry;
910
+ next.probeByProvider = probes;
911
+ }
597
912
  if (providerProbe && result.ok && Number.isFinite(result.latency)) {
598
913
  const entries = normalizeLatencyMap(previous.latencyByProvider);
599
914
  const measured = {
@@ -626,7 +941,14 @@ export function createProxyStore({ dataDir }) {
626
941
  const index = records.findIndex((item) => item.id === id);
627
942
  if (index < 0) return null;
628
943
  const previous = records[index];
629
- if (expectedUpdatedAt && previous.updatedAt !== expectedUpdatedAt) return null;
944
+ const connectionRevision = previous.connectionUpdatedAt || previous.updatedAt;
945
+ if (
946
+ expectedUpdatedAt &&
947
+ expectedUpdatedAt !== connectionRevision &&
948
+ expectedUpdatedAt !== previous.updatedAt
949
+ ) {
950
+ return null;
951
+ }
630
952
  const now = new Date().toISOString();
631
953
  const ok = result?.ok === true && validScore(result.score) !== null;
632
954
  const next = {
@@ -276,8 +276,17 @@ async function requestOverStream(
276
276
  return readHttpResponse(new BufferedReader(stream), { acceptAnyStatus });
277
277
  }
278
278
 
279
+ function connectProxyTransport(proxy, sockets, options = {}) {
280
+ return connectTcp(proxy.host, proxy.port, sockets).then((socket) => {
281
+ if (proxy.type !== "https") return socket;
282
+ return upgradeTls(socket, proxy.host, sockets, {
283
+ tlsRejectUnauthorized: options.proxyTlsRejectUnauthorized ?? options.tlsRejectUnauthorized,
284
+ });
285
+ });
286
+ }
287
+
279
288
  async function connectTunnel(endpoint, proxy, sockets, options) {
280
- const socket = await connectTcp(proxy.host, proxy.port, sockets);
289
+ const socket = await connectProxyTransport(proxy, sockets, options);
281
290
  const port = endpoint.port || (endpoint.protocol === "https:" ? "443" : "80");
282
291
  const authority = `${endpoint.hostname}:${port}`;
283
292
  const auth = proxyAuthorization(proxy);
@@ -306,7 +315,7 @@ async function connectTunnel(endpoint, proxy, sockets, options) {
306
315
  async function viaHttpProxy(endpoint, proxy, sockets, options) {
307
316
  const acceptAnyStatus = options.acceptAnyStatus === true;
308
317
  if (endpoint.protocol === "http:") {
309
- const socket = await connectTcp(proxy.host, proxy.port, sockets);
318
+ const socket = await connectProxyTransport(proxy, sockets, options);
310
319
  const reply = await requestOverStream(socket, endpoint, {
311
320
  absolute: true,
312
321
  proxyAuth: proxyAuthorization(proxy),
@@ -31,11 +31,13 @@
31
31
  // Off by default, per account, by an explicit click. Installing the plugin
32
32
  // enables nothing, and there is no "enable all".
33
33
 
34
- import { mkdir, readFile, writeFile } from "node:fs/promises";
34
+ import { randomUUID } from "node:crypto";
35
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
35
36
  import { join } from "node:path";
36
37
  import { pluginDataDir } from "./paths.mjs";
37
38
  import { accountDir, readAccountMeta, readIdentity } from "./account-identity.mjs";
38
39
  import { readAuthKeys } from "./account-keys.mjs";
40
+ import { readNativeLoginKeys } from "./magpie-logins.mjs";
39
41
  import { readAuthEntries, readAuthExpiries } from "./signin-writeback.mjs";
40
42
  import { SIGNIN_TERMINAL_STATES } from "./signin-flow.mjs";
41
43
 
@@ -220,15 +222,18 @@ export function createRenewHosting(options = {}) {
220
222
  historyLimit = HOSTING_HISTORY_LIMIT,
221
223
  readExpiries = readAuthExpiries,
222
224
  readKeys = readAuthKeys,
225
+ readNativeKeys = readNativeLoginKeys,
223
226
  readEntries = readAuthEntries,
224
227
  } = options;
225
228
 
226
229
  const file = join(dataDir, RENEW_HOSTING_FILE);
227
230
  let policies = null;
228
231
  let running = null;
232
+ let startingRun = false;
229
233
  let timer = null;
230
234
  let stopped = false;
231
235
  let ticking = false;
236
+ let saveChain = Promise.resolve();
232
237
 
233
238
  async function load() {
234
239
  if (policies) return policies;
@@ -248,13 +253,27 @@ export function createRenewHosting(options = {}) {
248
253
  }
249
254
 
250
255
  async function save() {
251
- const payload = {
252
- version: RENEW_HOSTING_VERSION,
253
- updatedAt: new Date(now()).toISOString(),
254
- accounts: [...policies.values()],
256
+ const run = async () => {
257
+ const payload = {
258
+ version: RENEW_HOSTING_VERSION,
259
+ updatedAt: new Date(now()).toISOString(),
260
+ accounts: [...policies.values()],
261
+ };
262
+ await mkdir(dataDir, { recursive: true });
263
+ const temp = join(dataDir, `.${RENEW_HOSTING_FILE}.${process.pid}.${randomUUID()}.tmp`);
264
+ try {
265
+ await writeFile(temp, `${JSON.stringify(payload, null, 2)}\n`, {
266
+ encoding: "utf8",
267
+ mode: 0o600,
268
+ });
269
+ await rename(temp, file);
270
+ } catch (error) {
271
+ await rm(temp, { force: true }).catch(() => {});
272
+ throw error;
273
+ }
255
274
  };
256
- await mkdir(dataDir, { recursive: true });
257
- await writeFile(file, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
275
+ saveChain = saveChain.then(run, run);
276
+ return saveChain;
258
277
  }
259
278
 
260
279
  function assertAccount(provider, key) {
@@ -330,6 +349,15 @@ export function createRenewHosting(options = {}) {
330
349
  };
331
350
  }
332
351
  if (!readKeys(env).has(key)) {
352
+ if (typeof readNativeKeys === "function" && readNativeKeys(env).has(key)) {
353
+ return {
354
+ ok: false,
355
+ code: "not_hostable",
356
+ status: 409,
357
+ message:
358
+ "Built-in accounts are signed in through magpie directly and cannot be renewed in the background.",
359
+ };
360
+ }
333
361
  return {
334
362
  ok: false,
335
363
  code: "not_signed_in",
@@ -583,18 +611,24 @@ export function createRenewHosting(options = {}) {
583
611
  // The one-at-a-time and sign-in exclusion guards still apply.
584
612
  async function runNow(provider, key) {
585
613
  assertAccount(provider, key);
586
- await load();
587
- const entry = policies.get(entryId(provider, key));
588
- if (!entry?.enabled) {
589
- throw new RenewHostingError("not_enabled", "Enable hosting for this account first.", 409);
590
- }
591
- if (running || signInBusy() || identityCheckBusy()) {
614
+ if (startingRun || running || signInBusy() || identityCheckBusy()) {
592
615
  throw new RenewHostingError("busy", "A sign-in is already running; try again when it finishes.", 409);
593
616
  }
594
- const check = await eligibility(provider, key);
595
- if (!check.ok) throw new RenewHostingError(check.code, check.message, check.status);
596
- void perform(entry, check, { manual: true });
597
- return { ok: true, running: publicRunning() };
617
+ startingRun = true;
618
+ try {
619
+ await load();
620
+ const entry = policies.get(entryId(provider, key));
621
+ if (!entry?.enabled) {
622
+ throw new RenewHostingError("not_enabled", "Enable hosting for this account first.", 409);
623
+ }
624
+ const check = await eligibility(provider, key);
625
+ if (!check.ok) throw new RenewHostingError(check.code, check.message, check.status);
626
+ running = { provider: entry.provider, key: entry.key, startedAt: now(), manual: true };
627
+ void perform(entry, check, { manual: true });
628
+ return { ok: true, running: publicRunning() };
629
+ } finally {
630
+ startingRun = false;
631
+ }
598
632
  }
599
633
 
600
634
  async function cancel() {
@@ -615,9 +649,19 @@ export function createRenewHosting(options = {}) {
615
649
  if (signInBusy()) return { ran: false, reason: "signin_busy" };
616
650
  if (identityCheckBusy()) return { ran: false, reason: "check_busy" };
617
651
  const expiries = readExpiries(env);
652
+ const liveKeys = readKeys(env);
618
653
  const at = now();
654
+ let dirty = false;
619
655
  for (const entry of policies.values()) {
620
656
  if (!entry.enabled) continue;
657
+ if (!liveKeys.has(entry.key)) {
658
+ entry.enabled = false;
659
+ entry.pausedReason = "signed_out";
660
+ entry.updatedAt = at;
661
+ entry.nextDueAt = null;
662
+ dirty = true;
663
+ continue;
664
+ }
621
665
  const expiresAt = expiries[entry.key];
622
666
  // No usable expiry: the credential is gone or never had one. Leave it
623
667
  // alone rather than guessing; the next inspect tells the user why.
@@ -638,6 +682,10 @@ export function createRenewHosting(options = {}) {
638
682
  if (at < expiresAt - lead) continue;
639
683
  if (isFiniteNumber(entry.nextDueAt) && at < entry.nextDueAt) continue;
640
684
  if (isFiniteNumber(entry.lastAt) && at - entry.lastAt < minGapMs) continue;
685
+ if (dirty) {
686
+ await save();
687
+ dirty = false;
688
+ }
641
689
  const check = await eligibility(entry.provider, entry.key);
642
690
  if (!check.ok) {
643
691
  await record(entry, { at, outcome: "error", code: check.code, message: check.message });
@@ -646,6 +694,7 @@ export function createRenewHosting(options = {}) {
646
694
  await perform(entry, check, { manual: false });
647
695
  return { ran: true, provider: entry.provider, key: entry.key };
648
696
  }
697
+ if (dirty) await save();
649
698
  return { ran: false };
650
699
  } finally {
651
700
  ticking = false;
@@ -681,6 +730,17 @@ export function createRenewHosting(options = {}) {
681
730
  }
682
731
  }
683
732
 
733
+ async function removeAccount(provider, key) {
734
+ assertAccount(provider, key);
735
+ await load();
736
+ const removed = policies.delete(entryId(provider, key));
737
+ if (running && running.provider === provider && running.key === key) {
738
+ await cancel();
739
+ }
740
+ if (removed) await save();
741
+ return { removed };
742
+ }
743
+
684
744
  return {
685
745
  file,
686
746
  enable,
@@ -690,6 +750,7 @@ export function createRenewHosting(options = {}) {
690
750
  snapshot,
691
751
  runNow,
692
752
  cancel,
753
+ removeAccount,
693
754
  tick,
694
755
  start,
695
756
  stop,