@camstack/system 1.2.455 → 1.2.457

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 (133) hide show
  1. package/dist/addon-runner.js +96 -10
  2. package/dist/addon-runner.mjs +96 -10
  3. package/dist/{agent-https-CLWrOO3o.mjs → agent-https-CK9Z4sSR.mjs} +32 -5
  4. package/dist/{agent-https-CCvlRQKV.js → agent-https-CoyOZ3pC.js} +37 -4
  5. package/dist/auth/auth-manager.d.ts +9 -0
  6. package/dist/auth/legacy-token-tables.d.ts +16 -0
  7. package/dist/auth/user-management-internal.d.ts +9 -28
  8. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  9. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  10. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  11. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  12. package/dist/builtins/alerts/alerts.addon.js +2 -2
  13. package/dist/builtins/alerts/alerts.addon.mjs +2 -2
  14. package/dist/builtins/autotrack/index.js +1 -1
  15. package/dist/builtins/autotrack/index.mjs +1 -1
  16. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  17. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  18. package/dist/builtins/calendars/calendars.addon.js +1 -1
  19. package/dist/builtins/calendars/calendars.addon.mjs +1 -1
  20. package/dist/builtins/camera-grid/index.js +1 -1
  21. package/dist/builtins/camera-grid/index.mjs +1 -1
  22. package/dist/builtins/composer/composer.addon.js +2 -2
  23. package/dist/builtins/composer/composer.addon.mjs +2 -2
  24. package/dist/builtins/console-logging/console-destination.d.ts +1 -2
  25. package/dist/builtins/console-logging/index.js +1 -4
  26. package/dist/builtins/console-logging/index.mjs +1 -4
  27. package/dist/builtins/core-blocks/core-blocks.addon.js +2 -2
  28. package/dist/builtins/core-blocks/core-blocks.addon.mjs +2 -2
  29. package/dist/builtins/device-history/capture/capture-engine.d.ts +6 -0
  30. package/dist/builtins/device-history/device-history.addon.js +441 -83
  31. package/dist/builtins/device-history/device-history.addon.mjs +441 -83
  32. package/dist/builtins/device-history/query/history-query.d.ts +35 -9
  33. package/dist/builtins/device-history/query/point-shape.d.ts +33 -0
  34. package/dist/builtins/device-history/retention/retention.d.ts +1 -1
  35. package/dist/builtins/device-history/rollup/rollup-engine.d.ts +2 -0
  36. package/dist/builtins/device-history/rollup/rollup-math.d.ts +6 -0
  37. package/dist/builtins/device-history/store/history-store.d.ts +7 -0
  38. package/dist/builtins/device-history/store/series-registry.d.ts +26 -1
  39. package/dist/builtins/device-manager/device-manager.addon.js +1 -1
  40. package/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  41. package/dist/builtins/hub-forwarder/hub-forwarder-destination.d.ts +1 -2
  42. package/dist/builtins/hub-forwarder/index.js +1 -4
  43. package/dist/builtins/hub-forwarder/index.mjs +1 -4
  44. package/dist/builtins/keychain/index.js +4 -4
  45. package/dist/builtins/keychain/index.mjs +4 -4
  46. package/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  47. package/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  48. package/dist/builtins/local-auth/auth-schema.d.ts +4 -7
  49. package/dist/builtins/local-auth/local-auth.addon.d.ts +7 -8
  50. package/dist/builtins/local-auth/local-auth.addon.js +1086 -1329
  51. package/dist/builtins/local-auth/local-auth.addon.mjs +1085 -1326
  52. package/dist/builtins/local-auth/preferences-record-kinds.d.ts +27 -0
  53. package/dist/builtins/local-auth/record-kinds.d.ts +4 -3
  54. package/dist/builtins/local-auth/user-preferences-store.d.ts +56 -0
  55. package/dist/builtins/local-network/local-network.addon.d.ts +8 -0
  56. package/dist/builtins/local-network/local-network.addon.js +30 -5
  57. package/dist/builtins/local-network/local-network.addon.mjs +30 -5
  58. package/dist/builtins/loki-logging/index.js +323 -7
  59. package/dist/builtins/loki-logging/index.mjs +323 -7
  60. package/dist/builtins/loki-logging/loki-destination.d.ts +20 -3
  61. package/dist/builtins/loki-logging/loki-read.d.ts +51 -0
  62. package/dist/builtins/native-metrics/native-metrics.addon.js +290 -112
  63. package/dist/builtins/native-metrics/native-metrics.addon.mjs +290 -112
  64. package/dist/builtins/native-metrics/node-metrics-history-recorder.d.ts +106 -35
  65. package/dist/builtins/platform-probe/index.js +1 -1
  66. package/dist/builtins/platform-probe/index.mjs +1 -1
  67. package/dist/builtins/record-entries/index.js +1 -1
  68. package/dist/builtins/record-entries/index.mjs +1 -1
  69. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  70. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  71. package/dist/builtins/snapshot/index.js +1 -1
  72. package/dist/builtins/snapshot/index.mjs +1 -1
  73. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  74. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  75. package/dist/builtins/sqlite-storage/index.js +1 -1
  76. package/dist/builtins/sqlite-storage/index.mjs +1 -1
  77. package/dist/builtins/sqlite-storage/records/records-engine-types.d.ts +1 -0
  78. package/dist/builtins/sqlite-storage/records/records-provider.d.ts +13 -0
  79. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +52 -6
  80. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +52 -6
  81. package/dist/builtins/storage-orchestrator/location-history-recorder.d.ts +76 -0
  82. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts +9 -0
  83. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +144 -1
  84. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +144 -1
  85. package/dist/builtins/system-config/system-config.addon.js +3 -3
  86. package/dist/builtins/system-config/system-config.addon.mjs +3 -3
  87. package/dist/builtins/winston-logging/index.js +165 -3
  88. package/dist/builtins/winston-logging/index.mjs +165 -3
  89. package/dist/builtins/winston-logging/log-file-cursor.d.ts +12 -0
  90. package/dist/builtins/winston-logging/log-file-index-store.d.ts +11 -0
  91. package/dist/builtins/winston-logging/log-file-index.d.ts +77 -0
  92. package/dist/builtins/winston-logging/log-file-read-client.d.ts +44 -0
  93. package/dist/builtins/winston-logging/log-file-read-protocol.d.ts +41 -0
  94. package/dist/builtins/winston-logging/log-file-read-worker.d.ts +1 -0
  95. package/dist/builtins/winston-logging/log-file-reader.d.ts +51 -0
  96. package/dist/builtins/winston-logging/winston-destination.d.ts +20 -2
  97. package/dist/{composition-sources-CSzD5_qX.mjs → composition-sources-B_jeZDRJ.mjs} +1 -1
  98. package/dist/{composition-sources-BxUkLNSo.js → composition-sources-qKyvMAvc.js} +1 -1
  99. package/dist/{constants-DruwCkfp.js → constants-B_X9cWEK.js} +1 -1
  100. package/dist/{constants-DOlYt1t1.mjs → constants-cxKcZRMi.mjs} +1 -1
  101. package/dist/{device-ca-uFbTyY_o.mjs → device-ca-BB6nHAL5.mjs} +1 -1
  102. package/dist/{device-ca-QPBgfqVY.js → device-ca-CVK3YcR_.js} +1 -1
  103. package/dist/{dist-DjQ8C-ku.js → dist-C89nqNnn.js} +721 -154
  104. package/dist/{dist-BpSENkRJ.mjs → dist-Dhux90yB.mjs} +668 -155
  105. package/dist/file-host-worker.js +1 -1
  106. package/dist/file-host-worker.mjs +1 -1
  107. package/dist/{hub-mdns-ciao-DlgkFJVY.mjs → hub-mdns-ciao-B8olZqqd.mjs} +20 -13
  108. package/dist/{hub-mdns-ciao-Bkrvgnma.js → hub-mdns-ciao-DB1Y9agt.js} +20 -13
  109. package/dist/index.d.ts +3 -4
  110. package/dist/index.js +145 -24
  111. package/dist/index.mjs +138 -22
  112. package/dist/kernel/config-schema.d.ts +5 -0
  113. package/dist/kernel/moleculer/accessory-prune-gate.d.ts +55 -0
  114. package/dist/log-file-read-protocol-B7M3X3bT.mjs +785 -0
  115. package/dist/log-file-read-protocol-D0WcLbIV.js +817 -0
  116. package/dist/log-file-read-worker.js +64 -0
  117. package/dist/log-file-read-worker.mjs +64 -0
  118. package/dist/log-read-filter-Bi066jwU.js +134 -0
  119. package/dist/log-read-filter-D7Ev3zm-.mjs +93 -0
  120. package/dist/logging/log-manager.d.ts +10 -6
  121. package/dist/logging/log-read-filter.d.ts +43 -0
  122. package/dist/{phase6-declare-gate-DrmTtz7F.js → phase6-declare-gate-BO-_jLh_.js} +1 -1
  123. package/dist/{phase6-declare-gate-JQUqgQgq.mjs → phase6-declare-gate-x9ZCbQJP.mjs} +1 -1
  124. package/dist/{restore-archive-4OP0EYg6.js → restore-archive-4DOUR5Gu.js} +1 -1
  125. package/dist/{restore-archive-YFSJRtKy.mjs → restore-archive-DyOaPeAr.mjs} +1 -1
  126. package/dist/tls/cert-issue.d.ts +16 -1
  127. package/dist/tls/cert-manager.d.ts +6 -0
  128. package/dist/tls/index.d.ts +1 -1
  129. package/dist/{wal-maintenance-TyuOEVy1.mjs → wal-maintenance-BMiX6UIa.mjs} +0 -0
  130. package/dist/{wal-maintenance-Bl0ZKjVR.js → wal-maintenance-DVN-DiVP.js} +0 -0
  131. package/package.json +1 -1
  132. package/dist/auth/admin-token-manager.d.ts +0 -51
  133. package/dist/auth/scoped-token-manager.d.ts +0 -25
@@ -1,10 +1,10 @@
1
1
  import { i as __require, o as __toESM, t as __commonJSMin } from "../../chunk-CNf5ZN-e.mjs";
2
- import { Ct as buildDeviceEnrollmentLink, D as DEVICE_NONCE_TTL_MS, E as DEVICE_ENROLLMENT_TTL_MS, Kt as deviceCredentialsCapability, Li as defineRecordKinds, Xi as makeSecretMarker, _a as userError, a as ApiKeyRecordSchema, it as SsoBridgeClaimsSchema, ln as formatDeviceRevoker, lt as TokenScopeSchema, nt as ScopedTokenSchema, qi as isSecretMarker, qr as BaseAddon, ut as UserRecordSchema, vt as authProviderCapability, wr as userManagementCapability, wt as buildDeviceSignatureMessage, y as CredentialTokenClaimsSchema } from "../../dist-BpSENkRJ.mjs";
2
+ import { $ as PreferenceDeviceIdSchema, D as DEVICE_ENROLLMENT_TTL_MS, Ea as userError, En as isCredentialTokenPayload, Et as authProviderCapability, Ki as defineRecordKinds, Mt as buildDeviceSignatureMessage, Nr as userManagementCapability, Q as PREFERENCES_MAX_VALUE_BYTES, _n as formatDeviceRevoker, a as ApiKeyRecordSchema, aa as makeSecretMarker, b as CredentialTokenClaimsSchema, dt as SsoBridgeClaimsSchema, en as deviceCredentialsCapability, et as PreferenceNamespaceSchema, g as CREDENTIAL_TOKEN_AUDIENCE, gt as TokenScopeSchema, jt as buildDeviceEnrollmentLink, k as DEVICE_NONCE_TTL_MS, lt as ScopedTokenSchema, na as isSecretMarker, ni as BaseAddon, tt as PreferenceValueSchema, vt as UserRecordSchema } from "../../dist-Dhux90yB.mjs";
3
3
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
4
4
  import { t as require_safe_buffer } from "../../safe-buffer-B1OjL1I9.mjs";
5
5
  import { t as require_ms } from "../../ms-CgH2OFlD.mjs";
6
- import { _ as setProcessJwtSigningKey, a as importDevicePublicKey, c as rebuildDeviceCaCertificate, d as JWT_SIGNING_KEY_REF, g as processJwtSigningKey, h as loadJwtSigningKey, i as generateDeviceCa, l as verifyDeviceLeaf, m as getProcessJwtSigningKeyState, n as DEVICE_CA_KEY_REF, o as issueDeviceLeaf, r as DEVICE_CA_SETTINGS_SECTION, s as loadDeviceCa, t as DEVICE_CA_FIELD, u as verifyDeviceSignature } from "../../device-ca-uFbTyY_o.mjs";
7
- import { t as resolvePhase6UseRecordsPathForHub } from "../../phase6-declare-gate-JQUqgQgq.mjs";
6
+ import { _ as setProcessJwtSigningKey, a as importDevicePublicKey, c as rebuildDeviceCaCertificate, d as JWT_SIGNING_KEY_REF, g as processJwtSigningKey, h as loadJwtSigningKey, i as generateDeviceCa, l as verifyDeviceLeaf, m as getProcessJwtSigningKeyState, n as DEVICE_CA_KEY_REF, o as issueDeviceLeaf, r as DEVICE_CA_SETTINGS_SECTION, s as loadDeviceCa, t as DEVICE_CA_FIELD, u as verifyDeviceSignature } from "../../device-ca-BB6nHAL5.mjs";
7
+ import { t as resolvePhase6UseRecordsPathForHub } from "../../phase6-declare-gate-x9ZCbQJP.mjs";
8
8
  import { z } from "zod";
9
9
  import * as crypto$1 from "node:crypto";
10
10
  import { X509Certificate, createHash, randomUUID, timingSafeEqual } from "node:crypto";
@@ -29,7 +29,7 @@ function parseRecord$2(kind, schema, data) {
29
29
  *
30
30
  * No boundary accepts one (the tRPC context has no branch for them) and
31
31
  * nothing creates them any more: what is left is the rows a hub may still
32
- * hold, so an operator can see and delete them. Scoped tokens (`cst_`) are
32
+ * hold, so an operator can see and delete them. Tokens (`auth.mintToken`) are
33
33
  * the credential for scripts and integrations.
34
34
  */
35
35
  var import_read_all_rows = require_read_all_rows();
@@ -182,7 +182,7 @@ function genSalt(rounds, seed_length, callback) {
182
182
  * @returns {!Promise} If `callback` has been omitted
183
183
  * @throws {Error} If `callback` is present but not a function
184
184
  */
185
- function hash$2(password, salt, callback, progressCallback) {
185
+ function hash$1(password, salt, callback, progressCallback) {
186
186
  function _async(callback) {
187
187
  if (typeof password === "string" && typeof salt === "number") genSalt(salt, function(err, salt) {
188
188
  _hash(password, salt, callback, progressCallback);
@@ -235,7 +235,7 @@ function compare(password, hashValue, callback, progressCallback) {
235
235
  nextTick(callback.bind(this, null, false));
236
236
  return;
237
237
  }
238
- hash$2(password, hashValue.substring(0, 29), function(err, comp) {
238
+ hash$1(password, hashValue.substring(0, 29), function(err, comp) {
239
239
  if (err) callback(err);
240
240
  else callback(null, safeStringCompare(comp, hashValue));
241
241
  }, progressCallback);
@@ -6108,13 +6108,29 @@ var AuthManager = class {
6108
6108
  * before signing, so nothing outside the schema is ever signed.
6109
6109
  */
6110
6110
  signCredentialToken(claims) {
6111
- return import_jsonwebtoken.sign(CredentialTokenClaimsSchema.parse(claims), this.jwtSecret);
6111
+ return import_jsonwebtoken.sign(CredentialTokenClaimsSchema.parse(claims), this.jwtSecret, { audience: CREDENTIAL_TOKEN_AUDIENCE });
6112
6112
  }
6113
+ /**
6114
+ * Verify a session-family JWT: a login session, an account link, a bridge or
6115
+ * challenge token. A MINTED token is refused here even though it carries a
6116
+ * valid signature (D895): every surface that calls this wants a person's
6117
+ * session, and a share link or a script's token must never pass for one.
6118
+ * Minted tokens verify only through {@link verifyCredentialToken}.
6119
+ */
6113
6120
  verifyToken(token) {
6114
- return import_jsonwebtoken.verify(token, this.jwtSecret);
6121
+ const payload = import_jsonwebtoken.verify(token, this.jwtSecret);
6122
+ if (isCredentialTokenPayload(payload)) throw new Error("A minted token is not a session credential");
6123
+ return payload;
6124
+ }
6125
+ /** Verify a minted token (`auth.mintToken`): its signature AND its audience. Throws when invalid. */
6126
+ verifyCredentialToken(token) {
6127
+ const payload = import_jsonwebtoken.verify(token, this.jwtSecret, { audience: CREDENTIAL_TOKEN_AUDIENCE });
6128
+ const claims = CredentialTokenClaimsSchema.safeParse(payload);
6129
+ if (!claims.success) throw new Error("Not a minted token");
6130
+ return claims.data;
6115
6131
  }
6116
6132
  async hashPassword(password) {
6117
- return hash$2(password, 10);
6133
+ return hash$1(password, 10);
6118
6134
  }
6119
6135
  async comparePassword(password, hash) {
6120
6136
  return compare(password, hash);
@@ -6505,19 +6521,11 @@ var AuthAuditLog = class {
6505
6521
  }
6506
6522
  };
6507
6523
  //#endregion
6508
- //#region src/auth/admin-token-manager.ts
6509
- /**
6510
- * Admin tokens (`csa_…`) — the one credential an ops script can hold that
6511
- * acts as an administrator, minted deliberately and kept on a short leash.
6512
- *
6513
- * Before phase-6 cutover: mint a spare `csa_` token, verify it against the hub,
6514
- * and keep the records-adopt snapshot — a boot guard mistake locks operators out.
6515
- */
6524
+ //#region src/auth/legacy-token-tables.ts
6516
6525
  /**
6517
6526
  * @durable class=config owner=local-auth
6518
- * write="an admin creates a token (after re-authentication); `lastUsedAt` is
6519
- * rewritten at most once a minute while it is used; `revoke` stamps revokedAt"
6520
- * retention="the daily reap deletes rows expired or revoked more than 30 days ago"
6527
+ * write="none since D895 — the pre-D892 rows are kept on disk, read by nothing"
6528
+ * retention="the operator drops the table by hand"
6521
6529
  */
6522
6530
  var ADMIN_TOKENS_COLLECTION = "admin_tokens";
6523
6531
  var ADMIN_TOKENS_COLUMNS = [
@@ -6567,210 +6575,6 @@ var ADMIN_TOKENS_COLUMNS = [
6567
6575
  type: "INTEGER"
6568
6576
  }
6569
6577
  ];
6570
- var ADMIN_TOKEN_PREFIX = "csa_";
6571
- var ADMIN_TOKEN_MAX_LIFETIME_MS = 90 * 864e5;
6572
- var DEAD_RETENTION_MS = 30 * 864e5;
6573
- var TOUCH_EVERY_MS = 6e4;
6574
- function hash$1(token) {
6575
- return crypto$1.createHash("sha256").update(token).digest("hex");
6576
- }
6577
- function parse(data) {
6578
- const { id, createdBy, name, tokenHash, tokenPrefix, createdAt, expiresAt } = data;
6579
- if (typeof id !== "string" || typeof createdBy !== "string" || typeof name !== "string" || typeof tokenHash !== "string" || typeof tokenPrefix !== "string" || typeof createdAt !== "number" || typeof expiresAt !== "number") return null;
6580
- return {
6581
- id,
6582
- createdBy,
6583
- name,
6584
- tokenHash,
6585
- tokenPrefix,
6586
- createdAt,
6587
- expiresAt,
6588
- lastUsedAt: typeof data["lastUsedAt"] === "number" ? data["lastUsedAt"] : null,
6589
- revokedAt: typeof data["revokedAt"] === "number" ? data["revokedAt"] : null
6590
- };
6591
- }
6592
- function parseBody(id, body) {
6593
- return parse({
6594
- id,
6595
- ...body
6596
- });
6597
- }
6598
- function storedToBody(stored) {
6599
- return {
6600
- createdBy: stored.createdBy,
6601
- name: stored.name,
6602
- tokenHash: stored.tokenHash,
6603
- tokenPrefix: stored.tokenPrefix,
6604
- createdAt: stored.createdAt,
6605
- expiresAt: stored.expiresAt,
6606
- lastUsedAt: stored.lastUsedAt,
6607
- revokedAt: stored.revokedAt
6608
- };
6609
- }
6610
- function summary(stored) {
6611
- const { tokenHash: _hash, ...record } = stored;
6612
- return record;
6613
- }
6614
- var AdminTokenManager = class {
6615
- now;
6616
- kind;
6617
- store;
6618
- constructor(deps, now = Date.now) {
6619
- this.now = now;
6620
- if ("adminTokensKind" in deps) {
6621
- this.kind = deps.adminTokensKind;
6622
- this.store = deps.store ?? null;
6623
- } else {
6624
- this.kind = null;
6625
- this.store = deps;
6626
- }
6627
- }
6628
- /** Mint a token for `createdBy`. Refuses an expiry in the past or past 90 days. */
6629
- async create(input) {
6630
- const at = this.now();
6631
- if (!(input.expiresAt > at) || input.expiresAt > at + 7776e6) throw userError("system.admin-token-expiry-too-long", void 0, "An admin token must expire within 90 days");
6632
- const name = input.name.trim().slice(0, 80);
6633
- if (name.length === 0) throw userError("system.admin-token-name-required", void 0, "An admin token needs a name");
6634
- const token = `${ADMIN_TOKEN_PREFIX}${crypto$1.randomBytes(32).toString("base64url")}`;
6635
- const stored = {
6636
- id: crypto$1.randomUUID(),
6637
- createdBy: input.createdBy,
6638
- name,
6639
- tokenHash: hash$1(token),
6640
- tokenPrefix: token.slice(0, 12),
6641
- createdAt: at,
6642
- expiresAt: input.expiresAt,
6643
- lastUsedAt: null,
6644
- revokedAt: null
6645
- };
6646
- const kind = this.kind;
6647
- if (kind !== null) {
6648
- const body = storedToBody(stored);
6649
- const parsed = localAuthRecordKinds["admin-tokens"].schema.safeParse(body);
6650
- if (!parsed.success) throw new Error(parsed.error.message);
6651
- await kind.put({
6652
- id: stored.id,
6653
- expiresAt: stored.expiresAt,
6654
- data: parsed.data
6655
- });
6656
- return {
6657
- token,
6658
- record: summary(stored)
6659
- };
6660
- }
6661
- await this.store.insert.mutate({
6662
- collection: ADMIN_TOKENS_COLLECTION,
6663
- record: {
6664
- id: stored.id,
6665
- data: { ...stored }
6666
- }
6667
- });
6668
- return {
6669
- token,
6670
- record: summary(stored)
6671
- };
6672
- }
6673
- /** The live record behind `token`, or `null` (unknown, revoked, expired, not a `csa_`). */
6674
- async validate(token) {
6675
- if (!token.startsWith("csa_")) return null;
6676
- const tokenHash = hash$1(token);
6677
- const kind = this.kind;
6678
- let stored = null;
6679
- if (kind !== null) {
6680
- const row = (await kind.query({
6681
- where: { tokenHash },
6682
- limit: 1
6683
- })).records[0];
6684
- stored = row === void 0 ? null : parseBody(row.id, row.data);
6685
- } else {
6686
- const first = (await this.store.query.query({
6687
- collection: ADMIN_TOKENS_COLLECTION,
6688
- filter: { where: { tokenHash } }
6689
- }))[0];
6690
- stored = first === void 0 ? null : parse(first.data);
6691
- }
6692
- if (stored === null || stored.revokedAt !== null) return null;
6693
- const at = this.now();
6694
- if (stored.expiresAt <= at) return null;
6695
- if (stored.lastUsedAt === null || at - stored.lastUsedAt > TOUCH_EVERY_MS) {
6696
- const next = {
6697
- ...stored,
6698
- lastUsedAt: at
6699
- };
6700
- if (kind !== null) kind.put({
6701
- id: stored.id,
6702
- expiresAt: stored.expiresAt,
6703
- data: storedToBody(next)
6704
- }).catch(() => {});
6705
- else this.store.update.mutate({
6706
- collection: ADMIN_TOKENS_COLLECTION,
6707
- id: stored.id,
6708
- data: { ...next }
6709
- }).catch(() => {});
6710
- }
6711
- return summary(stored);
6712
- }
6713
- /** Every token not yet reaped, newest first (no hashes). */
6714
- async list() {
6715
- const kind = this.kind;
6716
- if (kind !== null) return (await (0, import_read_all_rows.readAllRows)(kind)).map((row) => parseBody(row.id, row.data)).filter((r) => r !== null).map(summary).toSorted((a, b) => b.createdAt - a.createdAt);
6717
- return (await this.store.query.query({ collection: ADMIN_TOKENS_COLLECTION })).map((row) => parse(row.data)).filter((r) => r !== null).map(summary).toSorted((a, b) => b.createdAt - a.createdAt);
6718
- }
6719
- /** Revoke one token. `false` when unknown or already revoked. */
6720
- async revoke(id) {
6721
- const kind = this.kind;
6722
- let stored = null;
6723
- if (kind !== null) {
6724
- const row = await kind.get(id);
6725
- stored = row === null ? null : parseBody(row.id, row.data);
6726
- } else {
6727
- const first = (await this.store.query.query({
6728
- collection: ADMIN_TOKENS_COLLECTION,
6729
- filter: { where: { id } }
6730
- }))[0];
6731
- stored = first === void 0 ? null : parse(first.data);
6732
- }
6733
- if (stored === null || stored.revokedAt !== null) return false;
6734
- const next = {
6735
- ...stored,
6736
- revokedAt: this.now()
6737
- };
6738
- if (kind !== null) await kind.put({
6739
- id,
6740
- expiresAt: next.expiresAt,
6741
- data: storedToBody(next)
6742
- });
6743
- else await this.store.update.mutate({
6744
- collection: ADMIN_TOKENS_COLLECTION,
6745
- id,
6746
- data: { ...next }
6747
- });
6748
- return true;
6749
- }
6750
- /** Revoke every live token `userId` created (the user was deleted). */
6751
- async revokeAllCreatedBy(userId) {
6752
- let revoked = 0;
6753
- for (const token of await this.list()) if (token.createdBy === userId && token.revokedAt === null) {
6754
- if (await this.revoke(token.id)) revoked++;
6755
- }
6756
- return revoked;
6757
- }
6758
- /** Delete rows expired or revoked more than 30 days ago. */
6759
- async reap() {
6760
- const horizon = this.now() - DEAD_RETENTION_MS;
6761
- let deleted = 0;
6762
- for (const token of await this.list()) if ((token.revokedAt ?? token.expiresAt) < horizon) {
6763
- const kind = this.kind;
6764
- if (kind !== null) await kind.delete(token.id);
6765
- else await this.store.delete.mutate({
6766
- collection: ADMIN_TOKENS_COLLECTION,
6767
- key: token.id
6768
- });
6769
- deleted++;
6770
- }
6771
- return deleted;
6772
- }
6773
- };
6774
6578
  //#endregion
6775
6579
  //#region src/auth/device-credential-manager.ts
6776
6580
  /**
@@ -7382,82 +7186,80 @@ var DeviceCredentialManager = class {
7382
7186
  }
7383
7187
  };
7384
7188
  //#endregion
7385
- //#region src/auth/session-revocation-bus.ts
7386
- var BUS_KEY = Symbol.for("camstack.login-sessions.revocation-bus");
7387
- function listeners() {
7388
- const existing = Reflect.get(globalThis, BUS_KEY);
7389
- if (existing instanceof Set) return existing;
7390
- const created = /* @__PURE__ */ new Set();
7391
- Reflect.set(globalThis, BUS_KEY, created);
7392
- return created;
7393
- }
7394
- /** Subscribe; returns the unsubscribe. */
7395
- function onSessionsRevoked(listener) {
7396
- const set = listeners();
7397
- set.add(listener);
7398
- return () => {
7399
- set.delete(listener);
7400
- };
7401
- }
7402
- /** Announce an ended batch. A listener that throws never reaches the revoke. */
7403
- function announceSessionsRevoked(event, onListenerError) {
7404
- if (event.sessionIds.length === 0 && !event.allOfUser) return;
7405
- for (const listener of [...listeners()]) try {
7406
- listener(event);
7407
- } catch (error) {
7408
- onListenerError?.(error);
7409
- }
7410
- }
7411
- //#endregion
7412
- //#region src/auth/login-session-manager.ts
7189
+ //#region src/builtins/local-auth/auth-schema.ts
7413
7190
  /**
7414
- * Login sessions — the server-side record behind every session token.
7415
- *
7416
- * A session token used to be a self-contained 30-day JWT: nothing on the hub
7417
- * knew it existed, so logout revoked nothing, a password change left every
7418
- * other device signed in, and a deleted user's sessions lived until they
7419
- * expired. Now every login creates a row here and the token carries its id
7420
- * (`sid`); the hub checks the row on every request (`check`, an in-memory
7421
- * lookup), so revoking a row ends the session at once.
7422
- *
7423
- * Two kinds of client:
7424
- * - **refreshable** — gets a short access token (default 2 h) and an opaque
7425
- * refresh token (`csr_…`, stored hashed). `refresh` rotates the refresh
7426
- * token and slides the session's expiry; presenting a rotated-out refresh
7427
- * token after a short grace window is treated as theft and revokes the
7428
- * whole session.
7429
- * - **legacy** — a client from before refresh tokens: its access token lives
7430
- * as long as the session, and it renews through the handoff-code pair
7431
- * (`extend`). Kept for one release so installed viewer apps keep working.
7432
- *
7433
- * `legacyCutoff(userId)` covers tokens minted before sessions existed (no
7434
- * `sid`): a token of that user issued before the cutoff is refused. Revoking
7435
- * all of a user's sessions moves the cutoff, so a password change or a user
7436
- * deletion also ends their pre-session tokens.
7437
- *
7438
- * Mirror: every row is held in memory (a homelab hub has tens of sessions) and
7439
- * written through to the store; revocations update the mirror FIRST, so a
7440
- * store hiccup can delay persistence but never the revocation itself.
7191
+ * @durable class=config owner=local-auth
7192
+ * write="an operator creates a user, or `ensureAdminExists` seeds the configured
7193
+ * admin on first boot (or resets its password on the operator's one-shot
7194
+ * RESET_ADMIN_PASSWORD trigger); updated on scope, isAdmin and password edits"
7195
+ * retention="none — a row goes only when an operator deletes the user. A
7196
+ * `declareCollection` that adds a PK/UNIQUE/NOT-NULL-without-default column
7197
+ * REBUILDS the table: every account is wiped and only the configured admin
7198
+ * comes back on the next boot."
7441
7199
  */
7200
+ var USERS_COLLECTION$1 = "users";
7201
+ /**
7202
+ * @durable class=config owner=local-auth
7203
+ * write="an operator mints an API key; `validateToken` rewrites `lastUsedAt` on
7204
+ * every request the key authorises"
7205
+ * retention="none — an explicit `revoke` is the only delete. API keys have no
7206
+ * expiry column and no sweep, so a key lives until someone removes it (or the
7207
+ * destructive `declareCollection` rebuild takes the table)."
7208
+ */
7209
+ var API_KEYS_COLLECTION = "api_keys";
7210
+ /**
7211
+ * @durable class=config owner=local-auth
7212
+ * write="none since D895 — the pre-D892 scoped-token rows are kept on disk,
7213
+ * read by nothing (a scoped token is a `credential-tokens` row)"
7214
+ * retention="the operator drops the table by hand"
7215
+ */
7216
+ var SCOPED_TOKENS_COLLECTION = "scoped_tokens";
7442
7217
  /**
7443
7218
  * @durable class=ledger owner=local-auth
7444
- * write="one row per login (password, passkey, SSO, handoff, session exchange);
7445
- * rewritten on every refresh / renewal (expiry slides, refresh hash rotates)
7446
- * and on revocation"
7447
- * retention="the daily reap deletes rows expired more than 7 days ago and rows
7448
- * revoked more than 30 days ago. A session the user keeps refreshing lives as
7449
- * long as it is used."
7219
+ * write="one row per redeemed OAuth code — every completed account link through
7220
+ * `oauthExchangeCode`; `touch` rewrites `lastUsedAt` on each refresh"
7221
+ * retention="ONLY revoked rows are pruned: the daily sweep deletes sessions
7222
+ * revoked more than OAUTH_REVOKED_RETENTION_MS (30 d) ago. An ACTIVE session
7223
+ * has `revokedAt` NULL, never expires and is never swept — the table grows one
7224
+ * row per login until an operator revokes the link."
7450
7225
  */
7451
- var LOGIN_SESSIONS_COLLECTION = "login_sessions";
7226
+ var OAUTH_SESSIONS_COLLECTION = "oauth_sessions";
7227
+ /**
7228
+ * TOTP enrollment table — split off from `users` to avoid the
7229
+ * destructive drop-+-recreate migration `ensureTable` performs when a
7230
+ * new column is added to a typed schema (see `sqlite-settings-backend.ts`).
7231
+ *
7232
+ * Lifecycle:
7233
+ * - Setup: row inserted with `confirmedAt = null` and a fresh secret.
7234
+ * - Confirm: a valid code from the secret flips `confirmedAt` to now().
7235
+ * - Disable: the row is deleted (next setup starts fresh).
7236
+ *
7237
+ * "Enabled" means `confirmedAt != null`. A half-enrolled row (`confirmedAt
7238
+ * = null`) is INACTIVE — `verifyTotp` returns false until confirmation.
7239
+ *
7240
+ * @durable class=config owner=local-auth
7241
+ * write="`setup` inserts a keychain marker for the user's seed (D878; deleting any pending row
7242
+ * first); `confirm` flips `confirmedAt` once a valid code proves possession"
7243
+ * retention="`disable` deletes the row, and `setup` deletes before re-inserting.
7244
+ * Nothing else prunes — deleting a USER does not cascade here, so their
7245
+ * enrollment row outlives the account."
7246
+ */
7247
+ var USER_TOTP_COLLECTION = "user_totp";
7452
7248
  /**
7249
+ * External sign-in identities linked to local users (D782): one row per
7250
+ * `(provider, subject)` — the row id IS the identity, so one identity maps to
7251
+ * one user by primary key. Written only by the identity's owner completing a
7252
+ * "Link" flow from their profile (bound to their session).
7253
+ *
7453
7254
  * @durable class=config owner=local-auth
7454
- * write="revoking all of a user's sessions (logout everywhere, password change or
7455
- * reset, user deletion) sets that user's cutoff to now"
7456
- * retention="none — one row per user who ever had all sessions revoked; it only
7457
- * ever matters for tokens minted before sessions existed, and is harmless after."
7255
+ * write="`ExternalIdentityManager.link` when a signed-in user completes a
7256
+ * link flow; `unlink` from the profile or the Users page"
7257
+ * retention="`unlink` deletes one row; deleting the user deletes all of its
7258
+ * rows (`deleteUser` → `removeAllForUser`). A row whose provider instance
7259
+ * was renamed or removed stays, inert, until someone unlinks it."
7458
7260
  */
7459
- var LOGIN_SESSION_CUTOFFS_COLLECTION = "login_session_cutoffs";
7460
- var LOGIN_SESSIONS_COLUMNS = [
7261
+ var USER_EXTERNAL_IDENTITIES_COLLECTION = "user_external_identities";
7262
+ var USERS_COLUMNS = [
7461
7263
  {
7462
7264
  name: "id",
7463
7265
  type: "TEXT",
@@ -7465,813 +7267,241 @@ var LOGIN_SESSIONS_COLUMNS = [
7465
7267
  notNull: true
7466
7268
  },
7467
7269
  {
7468
- name: "userId",
7270
+ name: "username",
7469
7271
  type: "TEXT",
7470
- notNull: true
7272
+ notNull: true,
7273
+ unique: true
7471
7274
  },
7472
7275
  {
7473
- name: "method",
7276
+ name: "passwordHash",
7474
7277
  type: "TEXT",
7475
7278
  notNull: true
7476
7279
  },
7477
7280
  {
7478
- name: "refreshable",
7281
+ name: "isAdmin",
7479
7282
  type: "BOOLEAN",
7480
7283
  notNull: true
7481
7284
  },
7482
7285
  {
7483
- name: "createdAt",
7484
- type: "INTEGER",
7485
- notNull: true
7286
+ name: "allowedProviders",
7287
+ type: "JSON"
7486
7288
  },
7487
7289
  {
7488
- name: "lastUsedAt",
7489
- type: "INTEGER",
7490
- notNull: true
7290
+ name: "allowedDevices",
7291
+ type: "JSON"
7491
7292
  },
7492
7293
  {
7493
- name: "expiresAt",
7494
- type: "INTEGER",
7495
- notNull: true
7294
+ name: "scopes",
7295
+ type: "JSON"
7496
7296
  },
7497
7297
  {
7498
- name: "revokedAt",
7499
- type: "INTEGER"
7298
+ name: "createdAt",
7299
+ type: "INTEGER",
7300
+ notNull: true
7500
7301
  },
7501
7302
  {
7502
- name: "revokedReason",
7503
- type: "TEXT"
7303
+ name: "updatedAt",
7304
+ type: "INTEGER",
7305
+ notNull: true
7306
+ }
7307
+ ];
7308
+ var API_KEYS_COLUMNS = [
7309
+ {
7310
+ name: "id",
7311
+ type: "TEXT",
7312
+ primaryKey: true,
7313
+ notNull: true
7504
7314
  },
7505
7315
  {
7506
- name: "refreshHash",
7507
- type: "TEXT"
7316
+ name: "label",
7317
+ type: "TEXT",
7318
+ notNull: true
7508
7319
  },
7509
7320
  {
7510
- name: "previousRefreshHash",
7511
- type: "TEXT"
7321
+ name: "isAdmin",
7322
+ type: "BOOLEAN",
7323
+ notNull: true
7512
7324
  },
7513
7325
  {
7514
- name: "rotatedAt",
7326
+ name: "tokenHash",
7327
+ type: "TEXT",
7328
+ notNull: true,
7329
+ unique: true
7330
+ },
7331
+ {
7332
+ name: "tokenPrefix",
7333
+ type: "TEXT",
7334
+ notNull: true
7335
+ },
7336
+ {
7337
+ name: "allowedProviders",
7338
+ type: "JSON"
7339
+ },
7340
+ {
7341
+ name: "allowedDevices",
7342
+ type: "JSON"
7343
+ },
7344
+ {
7345
+ name: "createdAt",
7346
+ type: "INTEGER",
7347
+ notNull: true
7348
+ },
7349
+ {
7350
+ name: "lastUsedAt",
7515
7351
  type: "INTEGER"
7352
+ }
7353
+ ];
7354
+ var USER_TOTP_COLUMNS = [
7355
+ {
7356
+ name: "userId",
7357
+ type: "TEXT",
7358
+ primaryKey: true,
7359
+ notNull: true
7516
7360
  },
7517
7361
  {
7518
- name: "client",
7519
- type: "TEXT"
7362
+ name: "secret",
7363
+ type: "TEXT",
7364
+ notNull: true
7520
7365
  },
7521
7366
  {
7522
- name: "ip",
7523
- type: "TEXT"
7367
+ name: "confirmedAt",
7368
+ type: "INTEGER"
7524
7369
  },
7525
7370
  {
7526
- name: "credentialId",
7371
+ name: "createdAt",
7372
+ type: "INTEGER",
7373
+ notNull: true
7374
+ }
7375
+ ];
7376
+ var USER_EXTERNAL_IDENTITIES_COLUMNS = [
7377
+ {
7378
+ name: "id",
7379
+ type: "TEXT",
7380
+ primaryKey: true,
7381
+ notNull: true
7382
+ },
7383
+ {
7384
+ name: "provider",
7385
+ type: "TEXT",
7386
+ notNull: true
7387
+ },
7388
+ {
7389
+ name: "subject",
7390
+ type: "TEXT",
7391
+ notNull: true
7392
+ },
7393
+ {
7394
+ name: "issuer",
7395
+ type: "TEXT",
7396
+ notNull: true
7397
+ },
7398
+ {
7399
+ name: "userId",
7400
+ type: "TEXT",
7401
+ notNull: true
7402
+ },
7403
+ {
7404
+ name: "label",
7527
7405
  type: "TEXT"
7406
+ },
7407
+ {
7408
+ name: "linkedAt",
7409
+ type: "INTEGER",
7410
+ notNull: true
7528
7411
  }
7529
7412
  ];
7530
- var LOGIN_SESSION_CUTOFFS_COLUMNS = [{
7531
- name: "userId",
7532
- type: "TEXT",
7533
- primaryKey: true,
7534
- notNull: true
7535
- }, {
7536
- name: "notBefore",
7537
- type: "INTEGER",
7538
- notNull: true
7539
- }];
7540
- var METHODS = [
7541
- "password",
7542
- "passkey",
7543
- "sso",
7544
- "handoff",
7545
- "exchange",
7546
- "device-certificate"
7413
+ var SCOPED_TOKENS_COLUMNS = [
7414
+ {
7415
+ name: "id",
7416
+ type: "TEXT",
7417
+ primaryKey: true,
7418
+ notNull: true
7419
+ },
7420
+ {
7421
+ name: "userId",
7422
+ type: "TEXT",
7423
+ notNull: true
7424
+ },
7425
+ {
7426
+ name: "name",
7427
+ type: "TEXT",
7428
+ notNull: true
7429
+ },
7430
+ {
7431
+ name: "tokenHash",
7432
+ type: "TEXT",
7433
+ notNull: true,
7434
+ unique: true
7435
+ },
7436
+ {
7437
+ name: "tokenPrefix",
7438
+ type: "TEXT",
7439
+ notNull: true
7440
+ },
7441
+ {
7442
+ name: "scopes",
7443
+ type: "JSON"
7444
+ },
7445
+ {
7446
+ name: "expiresAt",
7447
+ type: "INTEGER"
7448
+ },
7449
+ {
7450
+ name: "lastUsedAt",
7451
+ type: "INTEGER"
7452
+ },
7453
+ {
7454
+ name: "createdAt",
7455
+ type: "INTEGER",
7456
+ notNull: true
7457
+ }
7458
+ ];
7459
+ var OAUTH_SESSIONS_COLUMNS = [
7460
+ {
7461
+ name: "id",
7462
+ type: "TEXT",
7463
+ primaryKey: true,
7464
+ notNull: true
7465
+ },
7466
+ {
7467
+ name: "userId",
7468
+ type: "TEXT",
7469
+ notNull: true
7470
+ },
7471
+ {
7472
+ name: "username",
7473
+ type: "TEXT",
7474
+ notNull: true
7475
+ },
7476
+ {
7477
+ name: "integrationId",
7478
+ type: "TEXT",
7479
+ notNull: true
7480
+ },
7481
+ {
7482
+ name: "scopes",
7483
+ type: "JSON"
7484
+ },
7485
+ {
7486
+ name: "createdAt",
7487
+ type: "INTEGER",
7488
+ notNull: true
7489
+ },
7490
+ {
7491
+ name: "lastUsedAt",
7492
+ type: "INTEGER",
7493
+ notNull: true
7494
+ },
7495
+ {
7496
+ name: "revokedAt",
7497
+ type: "INTEGER"
7498
+ }
7547
7499
  ];
7548
- var REFRESH_TOKEN_PREFIX = "csr_";
7549
7500
  /**
7550
- * A rotated-out refresh token is still honoured this long: two tabs (or a
7551
- * retry after a dropped response) may present the same token a moment apart.
7552
- * After it, the old token is evidence of a copy and ends the session.
7553
- */
7554
- var REFRESH_REUSE_GRACE_MS = 3e4;
7555
- var EXPIRED_RETENTION_MS = 7 * 864e5;
7556
- var REVOKED_RETENTION_MS = 30 * 864e5;
7557
- /** Longest client label kept (a User-Agent can be huge). */
7558
- var MAX_CLIENT_LABEL = 200;
7559
- function hashToken(token) {
7560
- return crypto$1.createHash("sha256").update(token).digest("hex");
7561
- }
7562
- function str(data, key) {
7563
- const value = data[key];
7564
- return typeof value === "string" && value.length > 0 ? value : null;
7565
- }
7566
- function num(data, key) {
7567
- const value = data[key];
7568
- return typeof value === "number" && Number.isFinite(value) ? value : null;
7569
- }
7570
- function parseSession$1(data) {
7571
- const id = str(data, "id");
7572
- const userId = str(data, "userId");
7573
- const createdAt = num(data, "createdAt");
7574
- const lastUsedAt = num(data, "lastUsedAt");
7575
- const expiresAt = num(data, "expiresAt");
7576
- const method = METHODS.find((m) => m === data["method"]);
7577
- if (id === null || userId === null || createdAt === null || expiresAt === null) return null;
7578
- return {
7579
- id,
7580
- userId,
7581
- method: method ?? "password",
7582
- refreshable: data["refreshable"] === true || data["refreshable"] === 1,
7583
- createdAt,
7584
- lastUsedAt: lastUsedAt ?? createdAt,
7585
- expiresAt,
7586
- revokedAt: num(data, "revokedAt"),
7587
- revokedReason: str(data, "revokedReason"),
7588
- refreshHash: str(data, "refreshHash"),
7589
- previousRefreshHash: str(data, "previousRefreshHash"),
7590
- rotatedAt: num(data, "rotatedAt"),
7591
- client: str(data, "client"),
7592
- ip: str(data, "ip"),
7593
- credentialId: str(data, "credentialId")
7594
- };
7595
- }
7596
- function toLoginSessionSummary(record) {
7597
- const { refreshHash: _r, previousRefreshHash: _p, rotatedAt: _t, ...summary } = record;
7598
- return summary;
7599
- }
7600
- function sessionToBody$1(session) {
7601
- const { id: _id, ...body } = session;
7602
- return body;
7603
- }
7604
- var LoginSessionManager = class {
7605
- sessions = /* @__PURE__ */ new Map();
7606
- /** refresh hash (current or previous) → session id */
7607
- byRefreshHash = /* @__PURE__ */ new Map();
7608
- cutoffs = /* @__PURE__ */ new Map();
7609
- now;
7610
- logger;
7611
- sessionsKind;
7612
- cutoffsKind;
7613
- store;
7614
- constructor(deps, options = {}) {
7615
- if ("sessionsKind" in deps) {
7616
- this.sessionsKind = deps.sessionsKind;
7617
- this.cutoffsKind = deps.cutoffsKind;
7618
- this.store = deps.legacyStore ?? null;
7619
- } else {
7620
- this.sessionsKind = null;
7621
- this.cutoffsKind = null;
7622
- this.store = deps;
7623
- }
7624
- this.now = options.now ?? Date.now;
7625
- this.logger = options.logger ?? null;
7626
- }
7627
- /** Load every row into the mirror. Call once at init, before serving. */
7628
- async load() {
7629
- const sessionsKind = this.sessionsKind;
7630
- if (sessionsKind !== null) {
7631
- const rows = await (0, import_read_all_rows.readAllRows)(sessionsKind);
7632
- for (const row of rows) {
7633
- const record = parseSession$1({
7634
- id: row.id,
7635
- ...row.data
7636
- });
7637
- if (record !== null) this.remember(record);
7638
- }
7639
- const cutoffs = await (0, import_read_all_rows.readAllRows)(this.cutoffsKind);
7640
- for (const row of cutoffs) this.cutoffs.set(row.id, row.data.notBefore);
7641
- return;
7642
- }
7643
- const rows = await this.store.query.query({ collection: LOGIN_SESSIONS_COLLECTION });
7644
- for (const row of rows) {
7645
- const record = parseSession$1(row.data);
7646
- if (record !== null) this.remember(record);
7647
- }
7648
- const cutoffs = await this.store.query.query({ collection: LOGIN_SESSION_CUTOFFS_COLLECTION });
7649
- for (const row of cutoffs) {
7650
- const userId = str(row.data, "userId");
7651
- const notBefore = num(row.data, "notBefore");
7652
- if (userId !== null && notBefore !== null) this.cutoffs.set(userId, notBefore);
7653
- }
7654
- }
7655
- async create(input) {
7656
- const at = this.now();
7657
- const refreshToken = input.refreshable ? this.newRefreshToken() : null;
7658
- const session = {
7659
- id: crypto$1.randomUUID(),
7660
- userId: input.userId,
7661
- method: input.method,
7662
- refreshable: input.refreshable,
7663
- createdAt: at,
7664
- lastUsedAt: at,
7665
- expiresAt: at + input.lifetimeMs,
7666
- revokedAt: null,
7667
- revokedReason: null,
7668
- refreshHash: refreshToken === null ? null : hashToken(refreshToken),
7669
- previousRefreshHash: null,
7670
- rotatedAt: null,
7671
- client: input.client === void 0 ? null : input.client.slice(0, MAX_CLIENT_LABEL),
7672
- ip: input.ip ?? null,
7673
- credentialId: input.credentialId ?? null
7674
- };
7675
- const sessionsKind = this.sessionsKind;
7676
- if (sessionsKind !== null) {
7677
- const parsed = localAuthRecordKinds["login-sessions"].schema.safeParse(sessionToBody$1(session));
7678
- if (!parsed.success) throw new Error(parsed.error.message);
7679
- await sessionsKind.put({
7680
- id: session.id,
7681
- at: session.createdAt,
7682
- expiresAt: session.expiresAt,
7683
- data: parsed.data
7684
- });
7685
- } else await this.store.insert.mutate({
7686
- collection: LOGIN_SESSIONS_COLLECTION,
7687
- record: {
7688
- id: session.id,
7689
- data: { ...session }
7690
- }
7691
- });
7692
- this.remember(session);
7693
- return {
7694
- session,
7695
- refreshToken
7696
- };
7697
- }
7698
- /** Is `sessionId` a live session right now? Synchronous: the hub asks on every request. */
7699
- check(sessionId) {
7700
- const session = this.sessions.get(sessionId);
7701
- if (session === void 0) return { state: "unknown" };
7702
- if (session.revokedAt !== null) return { state: "revoked" };
7703
- if (session.expiresAt <= this.now()) return { state: "expired" };
7704
- return {
7705
- state: "active",
7706
- session
7707
- };
7708
- }
7709
- /** Epoch ms before which a pre-session (no `sid`) token of `userId` is refused; 0 = none. */
7710
- legacyCutoff(userId) {
7711
- return this.cutoffs.get(userId) ?? 0;
7712
- }
7713
- /**
7714
- * The session a refresh token belongs to, WITHOUT rotating it - so the
7715
- * refresh path can judge the session (its device credential) before it
7716
- * spends the token. `null` when the token names no session.
7717
- */
7718
- peekByRefreshToken(refreshToken) {
7719
- if (!refreshToken.startsWith("csr_")) return null;
7720
- const sessionId = this.byRefreshHash.get(hashToken(refreshToken));
7721
- return sessionId === void 0 ? null : this.sessions.get(sessionId) ?? null;
7722
- }
7723
- /** Swap a refresh token for a rotated one, sliding the session's expiry to now + `lifetimeMs`. */
7724
- async refresh(refreshToken, lifetimeMs) {
7725
- if (!refreshToken.startsWith("csr_")) return {
7726
- ok: false,
7727
- reason: "unknown"
7728
- };
7729
- const presented = hashToken(refreshToken);
7730
- const sessionId = this.byRefreshHash.get(presented);
7731
- const session = sessionId === void 0 ? void 0 : this.sessions.get(sessionId);
7732
- if (session === void 0) return {
7733
- ok: false,
7734
- reason: "unknown"
7735
- };
7736
- if (session.revokedAt !== null) return {
7737
- ok: false,
7738
- reason: "revoked"
7739
- };
7740
- const at = this.now();
7741
- if (session.expiresAt <= at) return {
7742
- ok: false,
7743
- reason: "expired"
7744
- };
7745
- if (presented !== session.refreshHash) {
7746
- if (!(presented === session.previousRefreshHash && session.rotatedAt !== null && at - session.rotatedAt <= REFRESH_REUSE_GRACE_MS)) {
7747
- await this.revoke(session.id, "refresh-reuse");
7748
- this.logger?.warn("A rotated-out refresh token was presented — session revoked", { meta: {
7749
- sessionId: session.id,
7750
- userId: session.userId
7751
- } });
7752
- return {
7753
- ok: false,
7754
- reason: "reused"
7755
- };
7756
- }
7757
- }
7758
- const next = this.newRefreshToken();
7759
- const updated = {
7760
- ...session,
7761
- lastUsedAt: at,
7762
- expiresAt: at + lifetimeMs,
7763
- previousRefreshHash: session.refreshHash,
7764
- refreshHash: hashToken(next),
7765
- rotatedAt: at
7766
- };
7767
- this.replace(session, updated);
7768
- await this.persist(updated);
7769
- return {
7770
- ok: true,
7771
- session: updated,
7772
- refreshToken: next
7773
- };
7774
- }
7775
- /** Renew an active session (legacy client): slide its expiry. `null` when it is not active. */
7776
- async extend(sessionId, lifetimeMs) {
7777
- const check = this.check(sessionId);
7778
- if (check.state !== "active") return null;
7779
- const at = this.now();
7780
- const updated = {
7781
- ...check.session,
7782
- lastUsedAt: at,
7783
- expiresAt: at + lifetimeMs
7784
- };
7785
- this.replace(check.session, updated);
7786
- await this.persist(updated);
7787
- return updated;
7788
- }
7789
- /** End one session. `false` when it was unknown or already ended. */
7790
- async revoke(sessionId, reason) {
7791
- const session = this.sessions.get(sessionId);
7792
- if (session === void 0 || session.revokedAt !== null) return false;
7793
- const updated = {
7794
- ...session,
7795
- revokedAt: this.now(),
7796
- revokedReason: reason
7797
- };
7798
- this.replace(session, updated);
7799
- this.announce([updated.id], session.userId, false, null, reason);
7800
- await this.persist(updated);
7801
- return true;
7802
- }
7803
- /**
7804
- * End every live session of `userId` except `exceptSessionId`, and move the
7805
- * user's legacy cutoff to now (pre-session tokens die too). Returns how many
7806
- * sessions ended.
7807
- */
7808
- async revokeAllForUser(userId, options) {
7809
- const at = this.now();
7810
- this.cutoffs.set(userId, at);
7811
- const ended = [];
7812
- for (const session of this.sessions.values()) {
7813
- if (session.userId !== userId || session.revokedAt !== null) continue;
7814
- if (session.id === options.exceptSessionId) continue;
7815
- const updated = {
7816
- ...session,
7817
- revokedAt: at,
7818
- revokedReason: options.reason
7819
- };
7820
- this.replace(session, updated);
7821
- ended.push(updated);
7822
- }
7823
- this.announce(ended.map((s) => s.id), userId, true, options.exceptSessionId ?? null, options.reason);
7824
- await this.persistCutoff(userId, at);
7825
- for (const session of ended) await this.persist(session);
7826
- return ended.length;
7827
- }
7828
- /** End every live session opened by device credential `credentialId`. Returns how many. */
7829
- async revokeByCredential(credentialId, reason = "credential-revoked") {
7830
- const at = this.now();
7831
- const ended = [];
7832
- for (const session of this.sessions.values()) {
7833
- if (session.credentialId !== credentialId || session.revokedAt !== null) continue;
7834
- const updated = {
7835
- ...session,
7836
- revokedAt: at,
7837
- revokedReason: reason
7838
- };
7839
- this.replace(session, updated);
7840
- ended.push(updated);
7841
- }
7842
- this.announce(ended.map((s) => s.id), null, false, null, reason);
7843
- for (const session of ended) await this.persist(session);
7844
- return ended.length;
7845
- }
7846
- /** `userId`'s live sessions, newest first. */
7847
- listForUser(userId) {
7848
- return this.listActive().filter((s) => s.userId === userId);
7849
- }
7850
- /** Every live session, newest first. */
7851
- listActive() {
7852
- const at = this.now();
7853
- return [...this.sessions.values()].filter((s) => s.revokedAt === null && s.expiresAt > at).toSorted((a, b) => b.createdAt - a.createdAt).map(toLoginSessionSummary);
7854
- }
7855
- /** Delete rows expired more than 7 days ago or revoked more than 30. Returns how many. */
7856
- async reap() {
7857
- const at = this.now();
7858
- const dead = [...this.sessions.values()].filter((s) => s.revokedAt !== null && at - s.revokedAt > REVOKED_RETENTION_MS || s.revokedAt === null && at - s.expiresAt > EXPIRED_RETENTION_MS);
7859
- for (const session of dead) {
7860
- this.forget(session);
7861
- const sessionsKind = this.sessionsKind;
7862
- if (sessionsKind !== null) await sessionsKind.delete(session.id);
7863
- else await this.store.delete.mutate({
7864
- collection: LOGIN_SESSIONS_COLLECTION,
7865
- key: session.id
7866
- });
7867
- }
7868
- return dead.length;
7869
- }
7870
- /** Tell the hub which sessions just ended — right after the mirror, before the store write. */
7871
- announce(sessionIds, userId, allOfUser, exceptSessionId, reason) {
7872
- announceSessionsRevoked({
7873
- sessionIds,
7874
- userId,
7875
- allOfUser,
7876
- exceptSessionId,
7877
- reason
7878
- }, (error) => this.logger?.error("A session-revocation listener threw — the revoke stands", { meta: { error: error instanceof Error ? error.message : String(error) } }));
7879
- }
7880
- newRefreshToken() {
7881
- return `${REFRESH_TOKEN_PREFIX}${crypto$1.randomBytes(32).toString("base64url")}`;
7882
- }
7883
- remember(session) {
7884
- this.sessions.set(session.id, session);
7885
- if (session.refreshHash !== null) this.byRefreshHash.set(session.refreshHash, session.id);
7886
- if (session.previousRefreshHash !== null) this.byRefreshHash.set(session.previousRefreshHash, session.id);
7887
- }
7888
- forget(session) {
7889
- this.sessions.delete(session.id);
7890
- if (session.refreshHash !== null) this.byRefreshHash.delete(session.refreshHash);
7891
- if (session.previousRefreshHash !== null) this.byRefreshHash.delete(session.previousRefreshHash);
7892
- }
7893
- replace(previous, next) {
7894
- this.forget(previous);
7895
- this.remember(next);
7896
- }
7897
- async persist(session) {
7898
- try {
7899
- const sessionsKind = this.sessionsKind;
7900
- if (sessionsKind !== null) {
7901
- const parsed = localAuthRecordKinds["login-sessions"].schema.safeParse(sessionToBody$1(session));
7902
- if (!parsed.success) throw new Error(parsed.error.message);
7903
- await sessionsKind.put({
7904
- id: session.id,
7905
- at: session.createdAt,
7906
- expiresAt: session.expiresAt,
7907
- data: parsed.data
7908
- });
7909
- } else await this.store.update.mutate({
7910
- collection: LOGIN_SESSIONS_COLLECTION,
7911
- id: session.id,
7912
- data: { ...session }
7913
- });
7914
- } catch (error) {
7915
- this.logger?.error("Login session write failed — the change holds until restart", { meta: {
7916
- sessionId: session.id,
7917
- error: error instanceof Error ? error.message : String(error)
7918
- } });
7919
- }
7920
- }
7921
- async persistCutoff(userId, notBefore) {
7922
- try {
7923
- const cutoffsKind = this.cutoffsKind;
7924
- if (cutoffsKind !== null) {
7925
- const parsed = localAuthRecordKinds["login-session-cutoffs"].schema.safeParse({ notBefore });
7926
- if (!parsed.success) throw new Error(parsed.error.message);
7927
- await cutoffsKind.put({
7928
- id: userId,
7929
- data: parsed.data
7930
- });
7931
- } else {
7932
- await this.store.delete.mutate({
7933
- collection: LOGIN_SESSION_CUTOFFS_COLLECTION,
7934
- key: userId
7935
- });
7936
- await this.store.insert.mutate({
7937
- collection: LOGIN_SESSION_CUTOFFS_COLLECTION,
7938
- record: {
7939
- id: userId,
7940
- data: {
7941
- userId,
7942
- notBefore
7943
- }
7944
- }
7945
- });
7946
- }
7947
- } catch (error) {
7948
- this.logger?.error("Login session cutoff write failed — it holds until restart", { meta: {
7949
- userId,
7950
- error: error instanceof Error ? error.message : String(error)
7951
- } });
7952
- }
7953
- }
7954
- };
7955
- //#endregion
7956
- //#region src/builtins/local-auth/auth-schema.ts
7957
- /**
7958
- * @durable class=config owner=local-auth
7959
- * write="an operator creates a user, or `ensureAdminExists` seeds the configured
7960
- * admin on first boot (or resets its password on the operator's one-shot
7961
- * RESET_ADMIN_PASSWORD trigger); updated on scope, isAdmin and password edits"
7962
- * retention="none — a row goes only when an operator deletes the user. A
7963
- * `declareCollection` that adds a PK/UNIQUE/NOT-NULL-without-default column
7964
- * REBUILDS the table: every account is wiped and only the configured admin
7965
- * comes back on the next boot."
7966
- */
7967
- var USERS_COLLECTION$1 = "users";
7968
- /**
7969
- * @durable class=config owner=local-auth
7970
- * write="an operator mints an API key; `validateToken` rewrites `lastUsedAt` on
7971
- * every request the key authorises"
7972
- * retention="none — an explicit `revoke` is the only delete. API keys have no
7973
- * expiry column and no sweep, so a key lives until someone removes it (or the
7974
- * destructive `declareCollection` rebuild takes the table)."
7975
- */
7976
- var API_KEYS_COLLECTION = "api_keys";
7977
- /**
7978
- * @durable class=config owner=local-auth
7979
- * write="an operator or the CLI mints a scoped token; `validate` fires
7980
- * `updateLastUsed` on every accepted call"
7981
- * retention="`revoke` deletes one. The daily sweep `reapExpired` drops rows past
7982
- * `expiresAt` — a NULL expiry is a deliberate never-expires token and BETWEEN
7983
- * never matches it. `cleanupOrphans` drops tokens owned by the legacy 'system'
7984
- * id or by a user that no longer exists."
7985
- */
7986
- var SCOPED_TOKENS_COLLECTION = "scoped_tokens";
7987
- /**
7988
- * @durable class=ledger owner=local-auth
7989
- * write="one row per redeemed OAuth code — every completed account link through
7990
- * `oauthExchangeCode`; `touch` rewrites `lastUsedAt` on each refresh"
7991
- * retention="ONLY revoked rows are pruned: the daily sweep deletes sessions
7992
- * revoked more than OAUTH_REVOKED_RETENTION_MS (30 d) ago. An ACTIVE session
7993
- * has `revokedAt` NULL, never expires and is never swept — the table grows one
7994
- * row per login until an operator revokes the link."
7995
- */
7996
- var OAUTH_SESSIONS_COLLECTION = "oauth_sessions";
7997
- /**
7998
- * TOTP enrollment table — split off from `users` to avoid the
7999
- * destructive drop-+-recreate migration `ensureTable` performs when a
8000
- * new column is added to a typed schema (see `sqlite-settings-backend.ts`).
8001
- *
8002
- * Lifecycle:
8003
- * - Setup: row inserted with `confirmedAt = null` and a fresh secret.
8004
- * - Confirm: a valid code from the secret flips `confirmedAt` to now().
8005
- * - Disable: the row is deleted (next setup starts fresh).
8006
- *
8007
- * "Enabled" means `confirmedAt != null`. A half-enrolled row (`confirmedAt
8008
- * = null`) is INACTIVE — `verifyTotp` returns false until confirmation.
8009
- *
8010
- * @durable class=config owner=local-auth
8011
- * write="`setup` inserts a keychain marker for the user's seed (D878; deleting any pending row
8012
- * first); `confirm` flips `confirmedAt` once a valid code proves possession"
8013
- * retention="`disable` deletes the row, and `setup` deletes before re-inserting.
8014
- * Nothing else prunes — deleting a USER does not cascade here, so their
8015
- * enrollment row outlives the account."
8016
- */
8017
- var USER_TOTP_COLLECTION = "user_totp";
8018
- /**
8019
- * External sign-in identities linked to local users (D782): one row per
8020
- * `(provider, subject)` — the row id IS the identity, so one identity maps to
8021
- * one user by primary key. Written only by the identity's owner completing a
8022
- * "Link" flow from their profile (bound to their session).
8023
- *
8024
- * @durable class=config owner=local-auth
8025
- * write="`ExternalIdentityManager.link` when a signed-in user completes a
8026
- * link flow; `unlink` from the profile or the Users page"
8027
- * retention="`unlink` deletes one row; deleting the user deletes all of its
8028
- * rows (`deleteUser` → `removeAllForUser`). A row whose provider instance
8029
- * was renamed or removed stays, inert, until someone unlinks it."
8030
- */
8031
- var USER_EXTERNAL_IDENTITIES_COLLECTION = "user_external_identities";
8032
- var USERS_COLUMNS = [
8033
- {
8034
- name: "id",
8035
- type: "TEXT",
8036
- primaryKey: true,
8037
- notNull: true
8038
- },
8039
- {
8040
- name: "username",
8041
- type: "TEXT",
8042
- notNull: true,
8043
- unique: true
8044
- },
8045
- {
8046
- name: "passwordHash",
8047
- type: "TEXT",
8048
- notNull: true
8049
- },
8050
- {
8051
- name: "isAdmin",
8052
- type: "BOOLEAN",
8053
- notNull: true
8054
- },
8055
- {
8056
- name: "allowedProviders",
8057
- type: "JSON"
8058
- },
8059
- {
8060
- name: "allowedDevices",
8061
- type: "JSON"
8062
- },
8063
- {
8064
- name: "scopes",
8065
- type: "JSON"
8066
- },
8067
- {
8068
- name: "createdAt",
8069
- type: "INTEGER",
8070
- notNull: true
8071
- },
8072
- {
8073
- name: "updatedAt",
8074
- type: "INTEGER",
8075
- notNull: true
8076
- }
8077
- ];
8078
- var API_KEYS_COLUMNS = [
8079
- {
8080
- name: "id",
8081
- type: "TEXT",
8082
- primaryKey: true,
8083
- notNull: true
8084
- },
8085
- {
8086
- name: "label",
8087
- type: "TEXT",
8088
- notNull: true
8089
- },
8090
- {
8091
- name: "isAdmin",
8092
- type: "BOOLEAN",
8093
- notNull: true
8094
- },
8095
- {
8096
- name: "tokenHash",
8097
- type: "TEXT",
8098
- notNull: true,
8099
- unique: true
8100
- },
8101
- {
8102
- name: "tokenPrefix",
8103
- type: "TEXT",
8104
- notNull: true
8105
- },
8106
- {
8107
- name: "allowedProviders",
8108
- type: "JSON"
8109
- },
8110
- {
8111
- name: "allowedDevices",
8112
- type: "JSON"
8113
- },
8114
- {
8115
- name: "createdAt",
8116
- type: "INTEGER",
8117
- notNull: true
8118
- },
8119
- {
8120
- name: "lastUsedAt",
8121
- type: "INTEGER"
8122
- }
8123
- ];
8124
- var USER_TOTP_COLUMNS = [
8125
- {
8126
- name: "userId",
8127
- type: "TEXT",
8128
- primaryKey: true,
8129
- notNull: true
8130
- },
8131
- {
8132
- name: "secret",
8133
- type: "TEXT",
8134
- notNull: true
8135
- },
8136
- {
8137
- name: "confirmedAt",
8138
- type: "INTEGER"
8139
- },
8140
- {
8141
- name: "createdAt",
8142
- type: "INTEGER",
8143
- notNull: true
8144
- }
8145
- ];
8146
- var USER_EXTERNAL_IDENTITIES_COLUMNS = [
8147
- {
8148
- name: "id",
8149
- type: "TEXT",
8150
- primaryKey: true,
8151
- notNull: true
8152
- },
8153
- {
8154
- name: "provider",
8155
- type: "TEXT",
8156
- notNull: true
8157
- },
8158
- {
8159
- name: "subject",
8160
- type: "TEXT",
8161
- notNull: true
8162
- },
8163
- {
8164
- name: "issuer",
8165
- type: "TEXT",
8166
- notNull: true
8167
- },
8168
- {
8169
- name: "userId",
8170
- type: "TEXT",
8171
- notNull: true
8172
- },
8173
- {
8174
- name: "label",
8175
- type: "TEXT"
8176
- },
8177
- {
8178
- name: "linkedAt",
8179
- type: "INTEGER",
8180
- notNull: true
8181
- }
8182
- ];
8183
- var SCOPED_TOKENS_COLUMNS = [
8184
- {
8185
- name: "id",
8186
- type: "TEXT",
8187
- primaryKey: true,
8188
- notNull: true
8189
- },
8190
- {
8191
- name: "userId",
8192
- type: "TEXT",
8193
- notNull: true
8194
- },
8195
- {
8196
- name: "name",
8197
- type: "TEXT",
8198
- notNull: true
8199
- },
8200
- {
8201
- name: "tokenHash",
8202
- type: "TEXT",
8203
- notNull: true,
8204
- unique: true
8205
- },
8206
- {
8207
- name: "tokenPrefix",
8208
- type: "TEXT",
8209
- notNull: true
8210
- },
8211
- {
8212
- name: "scopes",
8213
- type: "JSON"
8214
- },
8215
- {
8216
- name: "expiresAt",
8217
- type: "INTEGER"
8218
- },
8219
- {
8220
- name: "lastUsedAt",
8221
- type: "INTEGER"
8222
- },
8223
- {
8224
- name: "createdAt",
8225
- type: "INTEGER",
8226
- notNull: true
8227
- }
8228
- ];
8229
- var OAUTH_SESSIONS_COLUMNS = [
8230
- {
8231
- name: "id",
8232
- type: "TEXT",
8233
- primaryKey: true,
8234
- notNull: true
8235
- },
8236
- {
8237
- name: "userId",
8238
- type: "TEXT",
8239
- notNull: true
8240
- },
8241
- {
8242
- name: "username",
8243
- type: "TEXT",
8244
- notNull: true
8245
- },
8246
- {
8247
- name: "integrationId",
8248
- type: "TEXT",
8249
- notNull: true
8250
- },
8251
- {
8252
- name: "scopes",
8253
- type: "JSON"
8254
- },
8255
- {
8256
- name: "createdAt",
8257
- type: "INTEGER",
8258
- notNull: true
8259
- },
8260
- {
8261
- name: "lastUsedAt",
8262
- type: "INTEGER",
8263
- notNull: true
8264
- },
8265
- {
8266
- name: "revokedAt",
8267
- type: "INTEGER"
8268
- }
8269
- ];
8270
- /**
8271
- * Declare every auth collection with the typed schema. Called by
8272
- * `LocalAuthAddon.onInitialize` before constructing the per-collection
8273
- * managers. Idempotent — `declareCollection` is a no-op when the
8274
- * collection has already been declared (same shape).
7501
+ * Declare every auth collection with the typed schema. Called by
7502
+ * `LocalAuthAddon.onInitialize` before constructing the per-collection
7503
+ * managers. Idempotent — `declareCollection` is a no-op when the
7504
+ * collection has already been declared (same shape).
8275
7505
  */
8276
7506
  async function declareAuthSchema(store, options) {
8277
7507
  const skip = new Set(options?.skipCollections ?? []);
@@ -8361,7 +7591,10 @@ async function declareAuthSchema(store, options) {
8361
7591
  * use `storageAdmin.dropCollection` with `expectRows` after verify (see
8362
7592
  * `docs/design/records-phase-6-auth-migration.md`).
8363
7593
  *
8364
- * Before hub restart: mint and test an admin token (`csa_`); snapshot every kind.
7594
+ * Before hub restart: mint and test an admin token (`auth.mintToken` with `'*'`); snapshot every kind.
7595
+ *
7596
+ * `scoped-tokens` and `admin-tokens` hold pre-D892 rows read by nothing since
7597
+ * D895; they stay declared so the layout is unchanged.
8365
7598
  */
8366
7599
  var DAY_MS = 864e5;
8367
7600
  var UserBodySchema = UserRecordSchema.omit({ id: true });
@@ -8470,7 +7703,7 @@ var _localAuthRecordKinds = defineRecordKinds({
8470
7703
  "scoped-tokens": {
8471
7704
  schema: ScopedTokenBodySchema,
8472
7705
  class: "config",
8473
- writeTrigger: "operator or CLI mints a scoped token; validate updates lastUsedAt",
7706
+ writeTrigger: "none since D895 — legacy rows kept on disk for the operator to drop",
8474
7707
  device: "none",
8475
7708
  at: "none",
8476
7709
  indexes: [{
@@ -8481,16 +7714,13 @@ var _localAuthRecordKinds = defineRecordKinds({
8481
7714
  name: "user",
8482
7715
  fields: ["userId"]
8483
7716
  }],
8484
- retention: {
8485
- owner: "local-auth",
8486
- reason: "daily reap of expired and orphan tokens; NULL expiresAt never matches BETWEEN"
8487
- },
7717
+ retention: { none: "the operator drops the legacy rows by hand (D895)" },
8488
7718
  adoptsFrom: SCOPED_TOKENS_COLLECTION
8489
7719
  },
8490
7720
  "admin-tokens": {
8491
7721
  schema: AdminTokenBodySchema,
8492
7722
  class: "config",
8493
- writeTrigger: "admin mints after re-auth; validate touches lastUsedAt; revoke stamps revokedAt",
7723
+ writeTrigger: "none since D895 — legacy rows kept on disk for the operator to drop",
8494
7724
  device: "none",
8495
7725
  at: "none",
8496
7726
  indexes: [{
@@ -8501,10 +7731,7 @@ var _localAuthRecordKinds = defineRecordKinds({
8501
7731
  name: "created_by",
8502
7732
  fields: ["createdBy"]
8503
7733
  }],
8504
- retention: {
8505
- owner: "local-auth",
8506
- reason: "daily reap deletes rows expired or revoked more than 30 days ago"
8507
- },
7734
+ retention: { none: "the operator drops the legacy rows by hand (D895)" },
8508
7735
  adoptsFrom: ADMIN_TOKENS_COLLECTION
8509
7736
  },
8510
7737
  "login-sessions": {
@@ -8616,8 +7843,8 @@ var _localAuthRecordKinds = defineRecordKinds({
8616
7843
  var localAuthRecordKinds = _localAuthRecordKinds;
8617
7844
  var localAuthUsersRecordKind = _localAuthRecordKinds.users;
8618
7845
  var localAuthApiKeysRecordKind = _localAuthRecordKinds["api-keys"];
8619
- var localAuthScopedTokensRecordKind = _localAuthRecordKinds["scoped-tokens"];
8620
- var localAuthAdminTokensRecordKind = _localAuthRecordKinds["admin-tokens"];
7846
+ _localAuthRecordKinds["scoped-tokens"];
7847
+ _localAuthRecordKinds["admin-tokens"];
8621
7848
  var localAuthLoginSessionsRecordKind = _localAuthRecordKinds["login-sessions"];
8622
7849
  var localAuthLoginSessionCutoffsRecordKind = _localAuthRecordKinds["login-session-cutoffs"];
8623
7850
  var localAuthOauthSessionsRecordKind = _localAuthRecordKinds["oauth-sessions"];
@@ -8641,214 +7868,586 @@ var LOCAL_AUTH_RECORDS_LEGACY_COLLECTIONS = [
8641
7868
  ];
8642
7869
  function localAuthRecordStoresOf(records) {
8643
7870
  return {
8644
- users: records.kind(localAuthUsersRecordKind),
8645
- apiKeys: records.kind(localAuthApiKeysRecordKind),
8646
- scopedTokens: records.kind(localAuthScopedTokensRecordKind),
8647
- adminTokens: records.kind(localAuthAdminTokensRecordKind),
8648
- loginSessions: records.kind(localAuthLoginSessionsRecordKind),
8649
- loginSessionCutoffs: records.kind(localAuthLoginSessionCutoffsRecordKind),
8650
- oauthSessions: records.kind(localAuthOauthSessionsRecordKind),
8651
- userTotp: records.kind(localAuthUserTotpRecordKind),
8652
- userExternalIdentities: records.kind(localAuthUserExternalIdentitiesRecordKind),
8653
- deviceCredentials: records.kind(localAuthDeviceCredentialsRecordKind),
8654
- authAudit: records.kind(localAuthAuthAuditRecordKind)
7871
+ users: records.kind(localAuthUsersRecordKind),
7872
+ apiKeys: records.kind(localAuthApiKeysRecordKind),
7873
+ loginSessions: records.kind(localAuthLoginSessionsRecordKind),
7874
+ loginSessionCutoffs: records.kind(localAuthLoginSessionCutoffsRecordKind),
7875
+ oauthSessions: records.kind(localAuthOauthSessionsRecordKind),
7876
+ userTotp: records.kind(localAuthUserTotpRecordKind),
7877
+ userExternalIdentities: records.kind(localAuthUserExternalIdentitiesRecordKind),
7878
+ deviceCredentials: records.kind(localAuthDeviceCredentialsRecordKind),
7879
+ authAudit: records.kind(localAuthAuthAuditRecordKind)
7880
+ };
7881
+ }
7882
+ //#endregion
7883
+ //#region src/auth/session-revocation-bus.ts
7884
+ var BUS_KEY = Symbol.for("camstack.login-sessions.revocation-bus");
7885
+ function listeners() {
7886
+ const existing = Reflect.get(globalThis, BUS_KEY);
7887
+ if (existing instanceof Set) return existing;
7888
+ const created = /* @__PURE__ */ new Set();
7889
+ Reflect.set(globalThis, BUS_KEY, created);
7890
+ return created;
7891
+ }
7892
+ /** Subscribe; returns the unsubscribe. */
7893
+ function onSessionsRevoked(listener) {
7894
+ const set = listeners();
7895
+ set.add(listener);
7896
+ return () => {
7897
+ set.delete(listener);
7898
+ };
7899
+ }
7900
+ /** Announce an ended batch. A listener that throws never reaches the revoke. */
7901
+ function announceSessionsRevoked(event, onListenerError) {
7902
+ if (event.sessionIds.length === 0 && !event.allOfUser) return;
7903
+ for (const listener of [...listeners()]) try {
7904
+ listener(event);
7905
+ } catch (error) {
7906
+ onListenerError?.(error);
7907
+ }
7908
+ }
7909
+ //#endregion
7910
+ //#region src/auth/login-session-manager.ts
7911
+ /**
7912
+ * Login sessions — the server-side record behind every session token.
7913
+ *
7914
+ * A session token used to be a self-contained 30-day JWT: nothing on the hub
7915
+ * knew it existed, so logout revoked nothing, a password change left every
7916
+ * other device signed in, and a deleted user's sessions lived until they
7917
+ * expired. Now every login creates a row here and the token carries its id
7918
+ * (`sid`); the hub checks the row on every request (`check`, an in-memory
7919
+ * lookup), so revoking a row ends the session at once.
7920
+ *
7921
+ * Two kinds of client:
7922
+ * - **refreshable** — gets a short access token (default 2 h) and an opaque
7923
+ * refresh token (`csr_…`, stored hashed). `refresh` rotates the refresh
7924
+ * token and slides the session's expiry; presenting a rotated-out refresh
7925
+ * token after a short grace window is treated as theft and revokes the
7926
+ * whole session.
7927
+ * - **legacy** — a client from before refresh tokens: its access token lives
7928
+ * as long as the session, and it renews through the handoff-code pair
7929
+ * (`extend`). Kept for one release so installed viewer apps keep working.
7930
+ *
7931
+ * `legacyCutoff(userId)` covers tokens minted before sessions existed (no
7932
+ * `sid`): a token of that user issued before the cutoff is refused. Revoking
7933
+ * all of a user's sessions moves the cutoff, so a password change or a user
7934
+ * deletion also ends their pre-session tokens.
7935
+ *
7936
+ * Mirror: every row is held in memory (a homelab hub has tens of sessions) and
7937
+ * written through to the store; revocations update the mirror FIRST, so a
7938
+ * store hiccup can delay persistence but never the revocation itself.
7939
+ */
7940
+ /**
7941
+ * @durable class=ledger owner=local-auth
7942
+ * write="one row per login (password, passkey, SSO, handoff, session exchange);
7943
+ * rewritten on every refresh / renewal (expiry slides, refresh hash rotates)
7944
+ * and on revocation"
7945
+ * retention="the daily reap deletes rows expired more than 7 days ago and rows
7946
+ * revoked more than 30 days ago. A session the user keeps refreshing lives as
7947
+ * long as it is used."
7948
+ */
7949
+ var LOGIN_SESSIONS_COLLECTION = "login_sessions";
7950
+ /**
7951
+ * @durable class=config owner=local-auth
7952
+ * write="revoking all of a user's sessions (logout everywhere, password change or
7953
+ * reset, user deletion) sets that user's cutoff to now"
7954
+ * retention="none — one row per user who ever had all sessions revoked; it only
7955
+ * ever matters for tokens minted before sessions existed, and is harmless after."
7956
+ */
7957
+ var LOGIN_SESSION_CUTOFFS_COLLECTION = "login_session_cutoffs";
7958
+ var LOGIN_SESSIONS_COLUMNS = [
7959
+ {
7960
+ name: "id",
7961
+ type: "TEXT",
7962
+ primaryKey: true,
7963
+ notNull: true
7964
+ },
7965
+ {
7966
+ name: "userId",
7967
+ type: "TEXT",
7968
+ notNull: true
7969
+ },
7970
+ {
7971
+ name: "method",
7972
+ type: "TEXT",
7973
+ notNull: true
7974
+ },
7975
+ {
7976
+ name: "refreshable",
7977
+ type: "BOOLEAN",
7978
+ notNull: true
7979
+ },
7980
+ {
7981
+ name: "createdAt",
7982
+ type: "INTEGER",
7983
+ notNull: true
7984
+ },
7985
+ {
7986
+ name: "lastUsedAt",
7987
+ type: "INTEGER",
7988
+ notNull: true
7989
+ },
7990
+ {
7991
+ name: "expiresAt",
7992
+ type: "INTEGER",
7993
+ notNull: true
7994
+ },
7995
+ {
7996
+ name: "revokedAt",
7997
+ type: "INTEGER"
7998
+ },
7999
+ {
8000
+ name: "revokedReason",
8001
+ type: "TEXT"
8002
+ },
8003
+ {
8004
+ name: "refreshHash",
8005
+ type: "TEXT"
8006
+ },
8007
+ {
8008
+ name: "previousRefreshHash",
8009
+ type: "TEXT"
8010
+ },
8011
+ {
8012
+ name: "rotatedAt",
8013
+ type: "INTEGER"
8014
+ },
8015
+ {
8016
+ name: "client",
8017
+ type: "TEXT"
8018
+ },
8019
+ {
8020
+ name: "ip",
8021
+ type: "TEXT"
8022
+ },
8023
+ {
8024
+ name: "credentialId",
8025
+ type: "TEXT"
8026
+ }
8027
+ ];
8028
+ var LOGIN_SESSION_CUTOFFS_COLUMNS = [{
8029
+ name: "userId",
8030
+ type: "TEXT",
8031
+ primaryKey: true,
8032
+ notNull: true
8033
+ }, {
8034
+ name: "notBefore",
8035
+ type: "INTEGER",
8036
+ notNull: true
8037
+ }];
8038
+ var METHODS = [
8039
+ "password",
8040
+ "passkey",
8041
+ "sso",
8042
+ "handoff",
8043
+ "exchange",
8044
+ "device-certificate"
8045
+ ];
8046
+ var REFRESH_TOKEN_PREFIX = "csr_";
8047
+ /**
8048
+ * A rotated-out refresh token is still honoured this long: two tabs (or a
8049
+ * retry after a dropped response) may present the same token a moment apart.
8050
+ * After it, the old token is evidence of a copy and ends the session.
8051
+ */
8052
+ var REFRESH_REUSE_GRACE_MS = 3e4;
8053
+ var EXPIRED_RETENTION_MS = 7 * 864e5;
8054
+ var REVOKED_RETENTION_MS = 30 * 864e5;
8055
+ /** Longest client label kept (a User-Agent can be huge). */
8056
+ var MAX_CLIENT_LABEL = 200;
8057
+ function hashToken(token) {
8058
+ return crypto$1.createHash("sha256").update(token).digest("hex");
8059
+ }
8060
+ function str(data, key) {
8061
+ const value = data[key];
8062
+ return typeof value === "string" && value.length > 0 ? value : null;
8063
+ }
8064
+ function num(data, key) {
8065
+ const value = data[key];
8066
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
8067
+ }
8068
+ function parseSession$1(data) {
8069
+ const id = str(data, "id");
8070
+ const userId = str(data, "userId");
8071
+ const createdAt = num(data, "createdAt");
8072
+ const lastUsedAt = num(data, "lastUsedAt");
8073
+ const expiresAt = num(data, "expiresAt");
8074
+ const method = METHODS.find((m) => m === data["method"]);
8075
+ if (id === null || userId === null || createdAt === null || expiresAt === null) return null;
8076
+ return {
8077
+ id,
8078
+ userId,
8079
+ method: method ?? "password",
8080
+ refreshable: data["refreshable"] === true || data["refreshable"] === 1,
8081
+ createdAt,
8082
+ lastUsedAt: lastUsedAt ?? createdAt,
8083
+ expiresAt,
8084
+ revokedAt: num(data, "revokedAt"),
8085
+ revokedReason: str(data, "revokedReason"),
8086
+ refreshHash: str(data, "refreshHash"),
8087
+ previousRefreshHash: str(data, "previousRefreshHash"),
8088
+ rotatedAt: num(data, "rotatedAt"),
8089
+ client: str(data, "client"),
8090
+ ip: str(data, "ip"),
8091
+ credentialId: str(data, "credentialId")
8655
8092
  };
8656
8093
  }
8657
- //#endregion
8658
- //#region src/auth/scoped-token-manager.ts
8659
- var TOKENS_COLLECTION = "scoped_tokens";
8660
- var TOKEN_PREFIX = "cst_";
8661
- function parseToken(data) {
8662
- return parseRecord$2("scoped-token", ScopedTokenSchema, data);
8663
- }
8664
- function tokenToBody(token) {
8665
- const { id: _id, ...body } = token;
8666
- return body;
8094
+ function toLoginSessionSummary(record) {
8095
+ const { refreshHash: _r, previousRefreshHash: _p, rotatedAt: _t, ...summary } = record;
8096
+ return summary;
8667
8097
  }
8668
- function rowToToken(id, body) {
8669
- return parseToken({
8670
- id,
8671
- ...body
8672
- });
8098
+ function sessionToBody$1(session) {
8099
+ const { id: _id, ...body } = session;
8100
+ return body;
8673
8101
  }
8674
- /**
8675
- * Manages scoped API tokens with restricted addon/route/capability access.
8676
- */
8677
- var ScopedTokenManager = class {
8678
- kind;
8102
+ var LoginSessionManager = class {
8103
+ sessions = /* @__PURE__ */ new Map();
8104
+ /** refresh hash (current or previous) → session id */
8105
+ byRefreshHash = /* @__PURE__ */ new Map();
8106
+ cutoffs = /* @__PURE__ */ new Map();
8107
+ now;
8108
+ logger;
8109
+ sessionsKind;
8110
+ cutoffsKind;
8679
8111
  store;
8680
- constructor(deps) {
8681
- if ("scopedTokensKind" in deps) {
8682
- this.kind = deps.scopedTokensKind;
8112
+ constructor(deps, options = {}) {
8113
+ if ("sessionsKind" in deps) {
8114
+ this.sessionsKind = deps.sessionsKind;
8115
+ this.cutoffsKind = deps.cutoffsKind;
8683
8116
  this.store = deps.legacyStore ?? null;
8684
8117
  } else {
8685
- this.kind = null;
8118
+ this.sessionsKind = null;
8119
+ this.cutoffsKind = null;
8686
8120
  this.store = deps;
8687
8121
  }
8122
+ this.now = options.now ?? Date.now;
8123
+ this.logger = options.logger ?? null;
8124
+ }
8125
+ /** Load every row into the mirror. Call once at init, before serving. */
8126
+ async load() {
8127
+ const sessionsKind = this.sessionsKind;
8128
+ if (sessionsKind !== null) {
8129
+ const rows = await (0, import_read_all_rows.readAllRows)(sessionsKind);
8130
+ for (const row of rows) {
8131
+ const record = parseSession$1({
8132
+ id: row.id,
8133
+ ...row.data
8134
+ });
8135
+ if (record !== null) this.remember(record);
8136
+ }
8137
+ const cutoffs = await (0, import_read_all_rows.readAllRows)(this.cutoffsKind);
8138
+ for (const row of cutoffs) this.cutoffs.set(row.id, row.data.notBefore);
8139
+ return;
8140
+ }
8141
+ const rows = await this.store.query.query({ collection: LOGIN_SESSIONS_COLLECTION });
8142
+ for (const row of rows) {
8143
+ const record = parseSession$1(row.data);
8144
+ if (record !== null) this.remember(record);
8145
+ }
8146
+ const cutoffs = await this.store.query.query({ collection: LOGIN_SESSION_CUTOFFS_COLLECTION });
8147
+ for (const row of cutoffs) {
8148
+ const userId = str(row.data, "userId");
8149
+ const notBefore = num(row.data, "notBefore");
8150
+ if (userId !== null && notBefore !== null) this.cutoffs.set(userId, notBefore);
8151
+ }
8152
+ }
8153
+ async create(input) {
8154
+ const at = this.now();
8155
+ const refreshToken = input.refreshable ? this.newRefreshToken() : null;
8156
+ const session = {
8157
+ id: crypto$1.randomUUID(),
8158
+ userId: input.userId,
8159
+ method: input.method,
8160
+ refreshable: input.refreshable,
8161
+ createdAt: at,
8162
+ lastUsedAt: at,
8163
+ expiresAt: at + input.lifetimeMs,
8164
+ revokedAt: null,
8165
+ revokedReason: null,
8166
+ refreshHash: refreshToken === null ? null : hashToken(refreshToken),
8167
+ previousRefreshHash: null,
8168
+ rotatedAt: null,
8169
+ client: input.client === void 0 ? null : input.client.slice(0, MAX_CLIENT_LABEL),
8170
+ ip: input.ip ?? null,
8171
+ credentialId: input.credentialId ?? null
8172
+ };
8173
+ const sessionsKind = this.sessionsKind;
8174
+ if (sessionsKind !== null) {
8175
+ const parsed = localAuthRecordKinds["login-sessions"].schema.safeParse(sessionToBody$1(session));
8176
+ if (!parsed.success) throw new Error(parsed.error.message);
8177
+ await sessionsKind.put({
8178
+ id: session.id,
8179
+ at: session.createdAt,
8180
+ expiresAt: session.expiresAt,
8181
+ data: parsed.data
8182
+ });
8183
+ } else await this.store.insert.mutate({
8184
+ collection: LOGIN_SESSIONS_COLLECTION,
8185
+ record: {
8186
+ id: session.id,
8187
+ data: { ...session }
8188
+ }
8189
+ });
8190
+ this.remember(session);
8191
+ return {
8192
+ session,
8193
+ refreshToken
8194
+ };
8195
+ }
8196
+ /** Is `sessionId` a live session right now? Synchronous: the hub asks on every request. */
8197
+ check(sessionId) {
8198
+ const session = this.sessions.get(sessionId);
8199
+ if (session === void 0) return { state: "unknown" };
8200
+ if (session.revokedAt !== null) return { state: "revoked" };
8201
+ if (session.expiresAt <= this.now()) return { state: "expired" };
8202
+ return {
8203
+ state: "active",
8204
+ session
8205
+ };
8206
+ }
8207
+ /** Epoch ms before which a pre-session (no `sid`) token of `userId` is refused; 0 = none. */
8208
+ legacyCutoff(userId) {
8209
+ return this.cutoffs.get(userId) ?? 0;
8210
+ }
8211
+ /**
8212
+ * The session a refresh token belongs to, WITHOUT rotating it - so the
8213
+ * refresh path can judge the session (its device credential) before it
8214
+ * spends the token. `null` when the token names no session.
8215
+ */
8216
+ peekByRefreshToken(refreshToken) {
8217
+ if (!refreshToken.startsWith("csr_")) return null;
8218
+ const sessionId = this.byRefreshHash.get(hashToken(refreshToken));
8219
+ return sessionId === void 0 ? null : this.sessions.get(sessionId) ?? null;
8220
+ }
8221
+ /** Swap a refresh token for a rotated one, sliding the session's expiry to now + `lifetimeMs`. */
8222
+ async refresh(refreshToken, lifetimeMs) {
8223
+ if (!refreshToken.startsWith("csr_")) return {
8224
+ ok: false,
8225
+ reason: "unknown"
8226
+ };
8227
+ const presented = hashToken(refreshToken);
8228
+ const sessionId = this.byRefreshHash.get(presented);
8229
+ const session = sessionId === void 0 ? void 0 : this.sessions.get(sessionId);
8230
+ if (session === void 0) return {
8231
+ ok: false,
8232
+ reason: "unknown"
8233
+ };
8234
+ if (session.revokedAt !== null) return {
8235
+ ok: false,
8236
+ reason: "revoked"
8237
+ };
8238
+ const at = this.now();
8239
+ if (session.expiresAt <= at) return {
8240
+ ok: false,
8241
+ reason: "expired"
8242
+ };
8243
+ if (presented !== session.refreshHash) {
8244
+ if (!(presented === session.previousRefreshHash && session.rotatedAt !== null && at - session.rotatedAt <= REFRESH_REUSE_GRACE_MS)) {
8245
+ await this.revoke(session.id, "refresh-reuse");
8246
+ this.logger?.warn("A rotated-out refresh token was presented — session revoked", { meta: {
8247
+ sessionId: session.id,
8248
+ userId: session.userId
8249
+ } });
8250
+ return {
8251
+ ok: false,
8252
+ reason: "reused"
8253
+ };
8254
+ }
8255
+ }
8256
+ const next = this.newRefreshToken();
8257
+ const updated = {
8258
+ ...session,
8259
+ lastUsedAt: at,
8260
+ expiresAt: at + lifetimeMs,
8261
+ previousRefreshHash: session.refreshHash,
8262
+ refreshHash: hashToken(next),
8263
+ rotatedAt: at
8264
+ };
8265
+ this.replace(session, updated);
8266
+ await this.persist(updated);
8267
+ return {
8268
+ ok: true,
8269
+ session: updated,
8270
+ refreshToken: next
8271
+ };
8272
+ }
8273
+ /** Renew an active session (legacy client): slide its expiry. `null` when it is not active. */
8274
+ async extend(sessionId, lifetimeMs) {
8275
+ const check = this.check(sessionId);
8276
+ if (check.state !== "active") return null;
8277
+ const at = this.now();
8278
+ const updated = {
8279
+ ...check.session,
8280
+ lastUsedAt: at,
8281
+ expiresAt: at + lifetimeMs
8282
+ };
8283
+ this.replace(check.session, updated);
8284
+ await this.persist(updated);
8285
+ return updated;
8286
+ }
8287
+ /** End one session. `false` when it was unknown or already ended. */
8288
+ async revoke(sessionId, reason) {
8289
+ const session = this.sessions.get(sessionId);
8290
+ if (session === void 0 || session.revokedAt !== null) return false;
8291
+ const updated = {
8292
+ ...session,
8293
+ revokedAt: this.now(),
8294
+ revokedReason: reason
8295
+ };
8296
+ this.replace(session, updated);
8297
+ this.announce([updated.id], session.userId, false, null, reason);
8298
+ await this.persist(updated);
8299
+ return true;
8300
+ }
8301
+ /**
8302
+ * End every live session of `userId` except `exceptSessionId`, and move the
8303
+ * user's legacy cutoff to now (pre-session tokens die too). Returns how many
8304
+ * sessions ended.
8305
+ */
8306
+ async revokeAllForUser(userId, options) {
8307
+ const at = this.now();
8308
+ this.cutoffs.set(userId, at);
8309
+ const ended = [];
8310
+ for (const session of this.sessions.values()) {
8311
+ if (session.userId !== userId || session.revokedAt !== null) continue;
8312
+ if (session.id === options.exceptSessionId) continue;
8313
+ const updated = {
8314
+ ...session,
8315
+ revokedAt: at,
8316
+ revokedReason: options.reason
8317
+ };
8318
+ this.replace(session, updated);
8319
+ ended.push(updated);
8320
+ }
8321
+ this.announce(ended.map((s) => s.id), userId, true, options.exceptSessionId ?? null, options.reason);
8322
+ await this.persistCutoff(userId, at);
8323
+ for (const session of ended) await this.persist(session);
8324
+ return ended.length;
8688
8325
  }
8689
- async create(userId, name, scopes, expiresAt) {
8690
- const rawToken = `${TOKEN_PREFIX}${crypto$1.randomBytes(32).toString("hex")}`;
8691
- const tokenHash = crypto$1.createHash("sha256").update(rawToken).digest("hex");
8692
- const tokenPrefix = rawToken.slice(0, 12);
8693
- const record = {
8694
- id: crypto$1.randomUUID(),
8695
- userId,
8696
- name,
8697
- tokenHash,
8698
- tokenPrefix,
8699
- scopes: scopes.map((s) => ({ ...s })),
8700
- expiresAt,
8701
- lastUsedAt: void 0,
8702
- createdAt: Date.now()
8703
- };
8704
- const kind = this.kind;
8705
- if (kind !== null) {
8706
- const body = tokenToBody(record);
8707
- const parsed = localAuthRecordKinds["scoped-tokens"].schema.safeParse(body);
8708
- if (!parsed.success) throw new Error(parsed.error.message);
8709
- await kind.put({
8710
- id: record.id,
8711
- expiresAt: record.expiresAt ?? void 0,
8712
- data: parsed.data
8713
- });
8714
- return {
8715
- token: rawToken,
8716
- record
8326
+ /** End every live session opened by device credential `credentialId`. Returns how many. */
8327
+ async revokeByCredential(credentialId, reason = "credential-revoked") {
8328
+ const at = this.now();
8329
+ const ended = [];
8330
+ for (const session of this.sessions.values()) {
8331
+ if (session.credentialId !== credentialId || session.revokedAt !== null) continue;
8332
+ const updated = {
8333
+ ...session,
8334
+ revokedAt: at,
8335
+ revokedReason: reason
8717
8336
  };
8337
+ this.replace(session, updated);
8338
+ ended.push(updated);
8718
8339
  }
8719
- await this.store.insert.mutate({
8720
- collection: TOKENS_COLLECTION,
8721
- record: {
8722
- id: record.id,
8723
- data: { ...record }
8724
- }
8725
- });
8726
- return {
8727
- token: rawToken,
8728
- record
8729
- };
8340
+ this.announce(ended.map((s) => s.id), null, false, null, reason);
8341
+ for (const session of ended) await this.persist(session);
8342
+ return ended.length;
8730
8343
  }
8731
- async validate(rawToken) {
8732
- if (!rawToken.startsWith(TOKEN_PREFIX)) return null;
8733
- const tokenHash = crypto$1.createHash("sha256").update(rawToken).digest("hex");
8734
- const kind = this.kind;
8735
- let record = null;
8736
- if (kind !== null) {
8737
- const row = (await kind.query({
8738
- where: { tokenHash },
8739
- limit: 1
8740
- })).records[0];
8741
- record = row === void 0 ? null : rowToToken(row.id, row.data);
8742
- } else {
8743
- const results = await this.store.query.query({
8744
- collection: TOKENS_COLLECTION,
8745
- filter: { where: { tokenHash } }
8344
+ /** `userId`'s live sessions, newest first. */
8345
+ listForUser(userId) {
8346
+ return this.listActive().filter((s) => s.userId === userId);
8347
+ }
8348
+ /** Every live session, newest first. */
8349
+ listActive() {
8350
+ const at = this.now();
8351
+ return [...this.sessions.values()].filter((s) => s.revokedAt === null && s.expiresAt > at).toSorted((a, b) => b.createdAt - a.createdAt).map(toLoginSessionSummary);
8352
+ }
8353
+ /** Delete rows expired more than 7 days ago or revoked more than 30. Returns how many. */
8354
+ async reap() {
8355
+ const at = this.now();
8356
+ const dead = [...this.sessions.values()].filter((s) => s.revokedAt !== null && at - s.revokedAt > REVOKED_RETENTION_MS || s.revokedAt === null && at - s.expiresAt > EXPIRED_RETENTION_MS);
8357
+ for (const session of dead) {
8358
+ this.forget(session);
8359
+ const sessionsKind = this.sessionsKind;
8360
+ if (sessionsKind !== null) await sessionsKind.delete(session.id);
8361
+ else await this.store.delete.mutate({
8362
+ collection: LOGIN_SESSIONS_COLLECTION,
8363
+ key: session.id
8746
8364
  });
8747
- record = results.length === 0 ? null : parseToken(results[0].data);
8748
8365
  }
8749
- if (record === null) return null;
8750
- if (record.expiresAt !== void 0 && record.expiresAt !== null && Date.now() > record.expiresAt) return null;
8751
- this.updateLastUsed(record.id).catch(() => {});
8752
- return record;
8366
+ return dead.length;
8753
8367
  }
8754
- matchesScope(token, addonId, capability) {
8755
- for (const scope of token.scopes) switch (scope.type) {
8756
- case "addon":
8757
- if (addonId && scope.target === addonId) return true;
8758
- break;
8759
- case "capability":
8760
- if (capability && scope.target === capability) return true;
8761
- break;
8762
- }
8763
- return false;
8368
+ /** Tell the hub which sessions just ended — right after the mirror, before the store write. */
8369
+ announce(sessionIds, userId, allOfUser, exceptSessionId, reason) {
8370
+ announceSessionsRevoked({
8371
+ sessionIds,
8372
+ userId,
8373
+ allOfUser,
8374
+ exceptSessionId,
8375
+ reason
8376
+ }, (error) => this.logger?.error("A session-revocation listener threw — the revoke stands", { meta: { error: error instanceof Error ? error.message : String(error) } }));
8764
8377
  }
8765
- async revoke(tokenId) {
8766
- const kind = this.kind;
8767
- if (kind !== null) {
8768
- if (await kind.get(tokenId) === null) return false;
8769
- await kind.delete(tokenId);
8770
- return true;
8771
- }
8772
- if ((await this.store.query.query({
8773
- collection: TOKENS_COLLECTION,
8774
- filter: { where: { id: tokenId } }
8775
- })).length === 0) return false;
8776
- await this.store.delete.mutate({
8777
- collection: TOKENS_COLLECTION,
8778
- key: tokenId
8779
- });
8780
- return true;
8378
+ newRefreshToken() {
8379
+ return `${REFRESH_TOKEN_PREFIX}${crypto$1.randomBytes(32).toString("base64url")}`;
8781
8380
  }
8782
- async listForUser(userId) {
8783
- const kind = this.kind;
8784
- if (kind !== null) return (await (0, import_read_all_rows.readAllRows)(kind, { where: { userId } })).map((row) => rowToToken(row.id, row.data));
8785
- return (await this.store.query.query({
8786
- collection: TOKENS_COLLECTION,
8787
- filter: { where: { userId } }
8788
- })).map((r) => parseToken(r.data));
8381
+ remember(session) {
8382
+ this.sessions.set(session.id, session);
8383
+ if (session.refreshHash !== null) this.byRefreshHash.set(session.refreshHash, session.id);
8384
+ if (session.previousRefreshHash !== null) this.byRefreshHash.set(session.previousRefreshHash, session.id);
8789
8385
  }
8790
- async updateLastUsed(tokenId) {
8791
- const kind = this.kind;
8792
- if (kind !== null) {
8793
- const row = await kind.get(tokenId);
8794
- if (row === null) return;
8795
- const next = {
8796
- ...rowToToken(row.id, row.data),
8797
- lastUsedAt: Date.now()
8798
- };
8799
- const body = tokenToBody(next);
8800
- const parsed = localAuthRecordKinds["scoped-tokens"].schema.safeParse(body);
8801
- if (!parsed.success) return;
8802
- await kind.put({
8803
- id: tokenId,
8804
- expiresAt: next.expiresAt ?? void 0,
8805
- data: parsed.data
8806
- });
8807
- return;
8808
- }
8809
- const results = await this.store.query.query({
8810
- collection: TOKENS_COLLECTION,
8811
- filter: { where: { id: tokenId } }
8812
- });
8813
- if (results.length === 0) return;
8814
- const existing = parseToken(results[0].data);
8815
- await this.store.update.mutate({
8816
- collection: TOKENS_COLLECTION,
8817
- id: tokenId,
8818
- data: {
8819
- ...existing,
8820
- lastUsedAt: Date.now()
8821
- }
8822
- });
8386
+ forget(session) {
8387
+ this.sessions.delete(session.id);
8388
+ if (session.refreshHash !== null) this.byRefreshHash.delete(session.refreshHash);
8389
+ if (session.previousRefreshHash !== null) this.byRefreshHash.delete(session.previousRefreshHash);
8823
8390
  }
8824
- async reapExpired(nowMs = Date.now()) {
8825
- const kind = this.kind;
8826
- if (kind !== null) return kind.deleteWhere({ where: { expiresAt: {
8827
- gte: 1,
8828
- lte: nowMs - 1
8829
- } } });
8830
- const { deleted } = await this.store.deleteWhere.mutate({
8831
- collection: TOKENS_COLLECTION,
8832
- filter: { whereBetween: { expiresAt: [1, nowMs - 1] } }
8833
- });
8834
- return deleted;
8391
+ replace(previous, next) {
8392
+ this.forget(previous);
8393
+ this.remember(next);
8835
8394
  }
8836
- async cleanupOrphans(validUserIds) {
8837
- const kind = this.kind;
8838
- const all = kind !== null ? (await (0, import_read_all_rows.readAllRows)(kind)).map((row) => rowToToken(row.id, row.data)) : (await this.store.query.query({
8839
- collection: TOKENS_COLLECTION,
8840
- filter: {}
8841
- })).map((e) => parseToken(e.data));
8842
- let removed = 0;
8843
- for (const record of all) if (record.userId === "system" || !validUserIds.has(record.userId)) {
8844
- if (kind !== null) await kind.delete(record.id);
8845
- else await this.store.delete.mutate({
8846
- collection: TOKENS_COLLECTION,
8847
- key: record.id
8395
+ async persist(session) {
8396
+ try {
8397
+ const sessionsKind = this.sessionsKind;
8398
+ if (sessionsKind !== null) {
8399
+ const parsed = localAuthRecordKinds["login-sessions"].schema.safeParse(sessionToBody$1(session));
8400
+ if (!parsed.success) throw new Error(parsed.error.message);
8401
+ await sessionsKind.put({
8402
+ id: session.id,
8403
+ at: session.createdAt,
8404
+ expiresAt: session.expiresAt,
8405
+ data: parsed.data
8406
+ });
8407
+ } else await this.store.update.mutate({
8408
+ collection: LOGIN_SESSIONS_COLLECTION,
8409
+ id: session.id,
8410
+ data: { ...session }
8848
8411
  });
8849
- removed++;
8412
+ } catch (error) {
8413
+ this.logger?.error("Login session write failed — the change holds until restart", { meta: {
8414
+ sessionId: session.id,
8415
+ error: error instanceof Error ? error.message : String(error)
8416
+ } });
8417
+ }
8418
+ }
8419
+ async persistCutoff(userId, notBefore) {
8420
+ try {
8421
+ const cutoffsKind = this.cutoffsKind;
8422
+ if (cutoffsKind !== null) {
8423
+ const parsed = localAuthRecordKinds["login-session-cutoffs"].schema.safeParse({ notBefore });
8424
+ if (!parsed.success) throw new Error(parsed.error.message);
8425
+ await cutoffsKind.put({
8426
+ id: userId,
8427
+ data: parsed.data
8428
+ });
8429
+ } else {
8430
+ await this.store.delete.mutate({
8431
+ collection: LOGIN_SESSION_CUTOFFS_COLLECTION,
8432
+ key: userId
8433
+ });
8434
+ await this.store.insert.mutate({
8435
+ collection: LOGIN_SESSION_CUTOFFS_COLLECTION,
8436
+ record: {
8437
+ id: userId,
8438
+ data: {
8439
+ userId,
8440
+ notBefore
8441
+ }
8442
+ }
8443
+ });
8444
+ }
8445
+ } catch (error) {
8446
+ this.logger?.error("Login session cutoff write failed — it holds until restart", { meta: {
8447
+ userId,
8448
+ error: error instanceof Error ? error.message : String(error)
8449
+ } });
8850
8450
  }
8851
- return removed;
8852
8451
  }
8853
8452
  };
8854
8453
  //#endregion
@@ -8963,6 +8562,211 @@ var DeviceCaStore = class {
8963
8562
  return this.loaded;
8964
8563
  }
8965
8564
  };
8565
+ var localAuthPreferencesRecordKinds = defineRecordKinds({ "user-preferences": {
8566
+ schema: z.object({
8567
+ userId: z.string().min(1),
8568
+ namespace: PreferenceNamespaceSchema,
8569
+ value: PreferenceValueSchema,
8570
+ revision: z.number().int().positive(),
8571
+ updatedAt: z.number().int(),
8572
+ updatedByDevice: PreferenceDeviceIdSchema.nullable()
8573
+ }),
8574
+ class: "config",
8575
+ writeTrigger: "a signed-in user saves one of their account preference namespaces (preferences.put) or deletes it",
8576
+ device: "none",
8577
+ at: "none",
8578
+ indexes: [{
8579
+ name: "user",
8580
+ fields: ["userId"]
8581
+ }],
8582
+ retention: { none: "a row goes when its user deletes the namespace, or with the user (deleteUser wipes every row of theirs)" },
8583
+ maxDataBytes: PREFERENCES_MAX_VALUE_BYTES + 4 * 1024
8584
+ } });
8585
+ /** Namespaces cannot hold `:`, so the id splits unambiguously. */
8586
+ function userPreferenceRecordId(userId, namespace) {
8587
+ return `${userId}:${namespace}`;
8588
+ }
8589
+ //#endregion
8590
+ //#region src/builtins/local-auth/user-preferences-store.ts
8591
+ /**
8592
+ * Per-user account preferences (D894): one row per `(userId, namespace)`.
8593
+ *
8594
+ * Every method takes the OWNER's id as its first argument and touches only
8595
+ * that user's rows; the hub router stamps it from the principal, and nothing
8596
+ * here accepts a second user id.
8597
+ *
8598
+ * The poll (`changedSince`) is answered from an in-memory mirror of each
8599
+ * user's `namespace → revision`, loaded once on first touch. This store is the
8600
+ * kind's only writer (one in-process instance in `local-auth`), so the mirror
8601
+ * cannot fall behind the rows; a poll that finds nothing changed reads no row.
8602
+ * Writes of one user are serialized, so a read-modify-write never interleaves.
8603
+ */
8604
+ /** A write the limits refuse; nothing was stored. */
8605
+ var PreferencesLimitError = class extends Error {
8606
+ reason;
8607
+ constructor(reason, message) {
8608
+ super(message);
8609
+ this.reason = reason;
8610
+ this.name = "PreferencesLimitError";
8611
+ }
8612
+ };
8613
+ /**
8614
+ * The limit refusal behind `error`, or `null`. By name and field, not
8615
+ * `instanceof`: the store and its caller may load different copies of this
8616
+ * module.
8617
+ */
8618
+ function preferencesLimitReasonOf(error) {
8619
+ if (!(error instanceof Error) || error.name !== "PreferencesLimitError") return null;
8620
+ const reason = Reflect.get(error, "reason");
8621
+ return reason === "value-too-large" || reason === "too-many-namespaces" ? reason : null;
8622
+ }
8623
+ /** The page size of a per-user scan; one page covers a user within the limit. */
8624
+ var USER_SCAN_PAGE = 40;
8625
+ /** The page size of the boot orphan sweep over every user's rows. */
8626
+ var ORPHAN_SCAN_PAGE = 500;
8627
+ function toRow(body) {
8628
+ return {
8629
+ namespace: body.namespace,
8630
+ value: body.value,
8631
+ revision: body.revision,
8632
+ updatedAt: body.updatedAt,
8633
+ updatedByDevice: body.updatedByDevice
8634
+ };
8635
+ }
8636
+ function byNamespace(a, b) {
8637
+ return a.namespace < b.namespace ? -1 : a.namespace > b.namespace ? 1 : 0;
8638
+ }
8639
+ var UserPreferencesStore = class {
8640
+ kind;
8641
+ now;
8642
+ /** `userId → namespace → revision`; absent until the user is first touched. */
8643
+ mirrors = /* @__PURE__ */ new Map();
8644
+ locks = /* @__PURE__ */ new Map();
8645
+ constructor(kind, options = {}) {
8646
+ this.kind = kind;
8647
+ this.now = options.now ?? Date.now;
8648
+ }
8649
+ /** The caller's rows; `namespaces` narrows them (unknown ones are simply absent). */
8650
+ async get(userId, namespaces) {
8651
+ if (namespaces === void 0) return (await this.scanUser(userId)).map((r) => toRow(r.data)).toSorted(byNamespace);
8652
+ return (await this.kind.getMany([...new Set(namespaces)].map((ns) => userPreferenceRecordId(userId, ns)))).filter((r) => r.data.userId === userId).map((r) => toRow(r.data)).toSorted(byNamespace);
8653
+ }
8654
+ async put(userId, input) {
8655
+ const bytes = Buffer.byteLength(JSON.stringify(input.value), "utf8");
8656
+ if (bytes > 262144) throw new PreferencesLimitError("value-too-large", `preferences: ${input.namespace} is ${bytes} bytes, the limit is ${PREFERENCES_MAX_VALUE_BYTES}`);
8657
+ return this.serialized(userId, async () => {
8658
+ const mirror = await this.mirrorOf(userId);
8659
+ const id = userPreferenceRecordId(userId, input.namespace);
8660
+ const existing = await this.kind.get(id);
8661
+ const currentRevision = existing?.data.revision ?? 0;
8662
+ if (input.baseRevision !== void 0 && input.baseRevision !== currentRevision) return {
8663
+ status: "conflict",
8664
+ current: existing === null ? null : toRow(existing.data)
8665
+ };
8666
+ if (existing === null && mirror.size >= 32) throw new PreferencesLimitError("too-many-namespaces", `preferences: a user holds at most 32 namespaces`);
8667
+ const body = {
8668
+ userId,
8669
+ namespace: input.namespace,
8670
+ value: input.value,
8671
+ revision: currentRevision + 1,
8672
+ updatedAt: this.now(),
8673
+ updatedByDevice: input.deviceId ?? null
8674
+ };
8675
+ await this.kind.put({
8676
+ id,
8677
+ data: body
8678
+ }, { ifRev: existing?.rev ?? 0 });
8679
+ mirror.set(input.namespace, body.revision);
8680
+ return {
8681
+ status: "saved",
8682
+ row: toRow(body)
8683
+ };
8684
+ });
8685
+ }
8686
+ /** `false` when the namespace did not exist. */
8687
+ async delete(userId, namespace) {
8688
+ return this.serialized(userId, async () => {
8689
+ const mirror = await this.mirrorOf(userId);
8690
+ const deleted = await this.kind.delete(userPreferenceRecordId(userId, namespace));
8691
+ mirror.delete(namespace);
8692
+ return deleted;
8693
+ });
8694
+ }
8695
+ /**
8696
+ * What the client is missing: every row whose revision differs from the one
8697
+ * it holds (or that it does not list), and every listed namespace now gone.
8698
+ */
8699
+ async changedSince(userId, known) {
8700
+ const mirror = await this.mirrorOf(userId);
8701
+ const changed = [];
8702
+ for (const [namespace, revision] of mirror) if (known[namespace] !== revision) changed.push(namespace);
8703
+ const deleted = Object.keys(known).filter((namespace) => !mirror.has(namespace)).toSorted();
8704
+ return {
8705
+ rows: [...changed.length === 0 ? [] : await this.get(userId, changed)],
8706
+ deleted
8707
+ };
8708
+ }
8709
+ /** Every row of `userId` goes (user delete). Returns how many. */
8710
+ async wipeUser(userId) {
8711
+ return this.serialized(userId, async () => {
8712
+ const rows = await this.scanUser(userId);
8713
+ const removed = rows.length === 0 ? 0 : await this.kind.deleteMany(rows.map((r) => r.id));
8714
+ this.mirrors.delete(userId);
8715
+ return removed;
8716
+ });
8717
+ }
8718
+ /** Rows whose user is not in `liveUserIds` go (boot sweep). Returns how many. */
8719
+ async wipeOrphans(liveUserIds) {
8720
+ const orphans = /* @__PURE__ */ new Set();
8721
+ let cursor;
8722
+ do {
8723
+ const page = await this.kind.query({
8724
+ order: "id",
8725
+ limit: ORPHAN_SCAN_PAGE,
8726
+ ...cursor !== void 0 ? { cursor } : {}
8727
+ });
8728
+ for (const row of page.records) if (!liveUserIds.has(row.data.userId)) orphans.add(row.data.userId);
8729
+ cursor = page.nextCursor ?? void 0;
8730
+ } while (cursor !== void 0);
8731
+ let removed = 0;
8732
+ for (const userId of orphans) removed += await this.wipeUser(userId);
8733
+ return removed;
8734
+ }
8735
+ async mirrorOf(userId) {
8736
+ const cached = this.mirrors.get(userId);
8737
+ if (cached !== void 0) return cached;
8738
+ const rows = await this.scanUser(userId);
8739
+ const raced = this.mirrors.get(userId);
8740
+ if (raced !== void 0) return raced;
8741
+ const mirror = new Map(rows.map((r) => [r.data.namespace, r.data.revision]));
8742
+ this.mirrors.set(userId, mirror);
8743
+ return mirror;
8744
+ }
8745
+ async scanUser(userId) {
8746
+ const out = [];
8747
+ let cursor;
8748
+ do {
8749
+ const page = await this.kind.query({
8750
+ where: { userId },
8751
+ limit: USER_SCAN_PAGE,
8752
+ ...cursor !== void 0 ? { cursor } : {}
8753
+ });
8754
+ out.push(...page.records);
8755
+ cursor = page.nextCursor ?? void 0;
8756
+ } while (cursor !== void 0);
8757
+ return out;
8758
+ }
8759
+ /** Run `task` after every earlier write of the same user has settled. */
8760
+ serialized(userId, task) {
8761
+ const next = (this.locks.get(userId) ?? Promise.resolve()).then(task, task);
8762
+ const settled = next.catch(() => void 0);
8763
+ this.locks.set(userId, settled);
8764
+ settled.then(() => {
8765
+ if (this.locks.get(userId) === settled) this.locks.delete(userId);
8766
+ });
8767
+ return next;
8768
+ }
8769
+ };
8966
8770
  //#endregion
8967
8771
  //#region src/auth/user-management-internal.ts
8968
8772
  /** Process-global, so every bundled copy of this module agrees on the key. */
@@ -12466,17 +12270,16 @@ var LocalAuthAddon = class extends BaseAddon {
12466
12270
  authManager = null;
12467
12271
  userManager = null;
12468
12272
  apiKeyManager = null;
12469
- scopedTokenManager = null;
12470
12273
  oauthSessionManager = null;
12471
12274
  reapTimer = null;
12472
12275
  totpManager = null;
12473
12276
  externalIdentities = null;
12474
12277
  signingKeyKeeper = null;
12475
12278
  loginSessions = null;
12476
- adminTokens = null;
12477
12279
  auditLog = null;
12478
12280
  deviceCredentials = null;
12479
12281
  deviceCa = null;
12282
+ preferences = null;
12480
12283
  constructor() {
12481
12284
  super({});
12482
12285
  }
@@ -12495,21 +12298,18 @@ var LocalAuthAddon = class extends BaseAddon {
12495
12298
  if (store && records) {
12496
12299
  const useRecords = await resolvePhase6UseRecordsPathForHub(this.ctx, "local-auth", localAuthRecordKinds, LOCAL_AUTH_RECORDS_LEGACY_COLLECTIONS);
12497
12300
  const authStores = useRecords ? localAuthRecordStoresOf(records) : null;
12301
+ await records.declare(localAuthPreferencesRecordKinds);
12302
+ this.preferences = new UserPreferencesStore(records.kind(localAuthPreferencesRecordKinds["user-preferences"]));
12498
12303
  const legacyStoreAccess = { getStore: () => store };
12499
12304
  await declareAuthSchema(store, { ...useRecords ? { skipCollections: LOCAL_AUTH_RECORDS_LEGACY_COLLECTIONS } : {} });
12500
12305
  this.userManager = authStores === null ? new UserManager(legacyStoreAccess, this.authManager) : new UserManager({
12501
12306
  usersKind: authStores.users,
12502
12307
  legacyStore: store
12503
12308
  }, this.authManager);
12504
- this.adminTokens = authStores === null ? new AdminTokenManager(store) : new AdminTokenManager({ adminTokensKind: authStores.adminTokens });
12505
12309
  this.apiKeyManager = authStores === null ? new ApiKeyManager(legacyStoreAccess) : new ApiKeyManager({
12506
12310
  apiKeysKind: authStores.apiKeys,
12507
12311
  legacyStore: store
12508
12312
  });
12509
- this.scopedTokenManager = authStores === null ? new ScopedTokenManager(store) : new ScopedTokenManager({
12510
- scopedTokensKind: authStores.scopedTokens,
12511
- legacyStore: store
12512
- });
12513
12313
  this.oauthSessionManager = authStores === null ? new OauthSessionManager(store) : new OauthSessionManager({
12514
12314
  oauthSessionsKind: authStores.oauthSessions,
12515
12315
  legacyStore: store
@@ -12570,8 +12370,12 @@ var LocalAuthAddon = class extends BaseAddon {
12570
12370
  });
12571
12371
  const liveUsers = await this.userManager.listAll();
12572
12372
  const liveIds = new Set(liveUsers.map((u) => u.id));
12573
- const removed = await this.scopedTokenManager.cleanupOrphans(liveIds);
12574
- if (removed > 0) this.ctx.logger.warn(`cleaned up ${removed} orphan scoped-token(s) on boot`);
12373
+ try {
12374
+ const orphanPrefs = await this.preferences.wipeOrphans(liveIds);
12375
+ if (orphanPrefs > 0) this.ctx.logger.warn(`cleaned up ${orphanPrefs} orphan account-preference row(s) on boot`);
12376
+ } catch (err) {
12377
+ this.ctx.logger.warn("account-preference orphan sweep failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
12378
+ }
12575
12379
  await this.reapAuthRows();
12576
12380
  this.reapTimer = setInterval(() => {
12577
12381
  this.reapAuthRows();
@@ -12685,29 +12489,6 @@ var LocalAuthAddon = class extends BaseAddon {
12685
12489
  await this.apiKeyManager.revoke(input.id);
12686
12490
  return { success: true };
12687
12491
  },
12688
- createScopedToken: async (input) => {
12689
- if (!this.scopedTokenManager) throw new Error("Scoped token management not available");
12690
- const { token, record } = await this.scopedTokenManager.create(input.userId, input.name, input.scopes, input.expiresAt);
12691
- return {
12692
- token,
12693
- record
12694
- };
12695
- },
12696
- revokeScopedToken: async (input) => {
12697
- if (!this.scopedTokenManager) throw new Error("Scoped token management not available");
12698
- if (!await this.scopedTokenManager.revoke(input.id)) throw new Error(`Scoped token not found: ${input.id}`);
12699
- return { success: true };
12700
- },
12701
- validateScopedToken: async (input) => {
12702
- if (!this.scopedTokenManager || !this.userManager) return null;
12703
- const record = await this.scopedTokenManager.validate(input.token);
12704
- if (record === null) return null;
12705
- return await this.userManager.findById(record.userId) === null ? null : record;
12706
- },
12707
- listScopedTokens: async (input) => {
12708
- if (!this.scopedTokenManager) return [];
12709
- return this.scopedTokenManager.listForUser(input.userId);
12710
- },
12711
12492
  oauthIssueCode: async (input) => {
12712
12493
  return lazyOauthGrants().oauthIssueCode(input);
12713
12494
  },
@@ -12949,7 +12730,9 @@ var LocalAuthAddon = class extends BaseAddon {
12949
12730
  if (this.deviceCredentials === null) throw userError("device.credentials-unavailable", void 0, "Device credentials not available");
12950
12731
  return this.deviceCredentials;
12951
12732
  };
12733
+ const preferences = this.preferences;
12952
12734
  return {
12735
+ ...preferences !== null ? { preferences } : {},
12953
12736
  sessions: {
12954
12737
  create: (input) => sessions().create(input),
12955
12738
  refresh: (token, lifetimeMs) => sessions().refresh(token, lifetimeMs),
@@ -12974,22 +12757,6 @@ var LocalAuthAddon = class extends BaseAddon {
12974
12757
  revoke: (id, by) => devices().revoke(id, by),
12975
12758
  list: (input) => devices().list(input)
12976
12759
  },
12977
- adminTokens: {
12978
- create: async (input) => {
12979
- if (this.adminTokens === null) throw new Error("Admin tokens not available");
12980
- return this.adminTokens.create(input);
12981
- },
12982
- validate: async (token) => {
12983
- if (this.adminTokens === null || this.userManager === null) return null;
12984
- const record = await this.adminTokens.validate(token);
12985
- if (record === null) return null;
12986
- const creator = await this.userManager.findById(record.createdBy);
12987
- return creator !== null && creator.isAdmin ? record : null;
12988
- },
12989
- list: async () => this.adminTokens === null ? [] : this.adminTokens.list(),
12990
- revoke: async (id) => this.adminTokens === null ? false : this.adminTokens.revoke(id)
12991
- },
12992
- scopedTokens: { revoke: async (id) => this.scopedTokenManager === null ? false : this.scopedTokenManager.revoke(id) },
12993
12760
  oauthSessions: { revoke: async (id) => {
12994
12761
  if (this.oauthSessionManager === null) return false;
12995
12762
  const session = await this.oauthSessionManager.getById(id);
@@ -13030,18 +12797,15 @@ var LocalAuthAddon = class extends BaseAddon {
13030
12797
  async endAllAccess(userId) {
13031
12798
  const steps = [
13032
12799
  ["sessions", async () => this.loginSessions?.revokeAllForUser(userId, { reason: "user-deleted" })],
13033
- ["scoped tokens", async () => {
13034
- for (const token of await this.scopedTokenManager?.listForUser(userId) ?? []) await this.scopedTokenManager?.revoke(token.id);
13035
- }],
13036
12800
  ["oauth sessions", async () => {
13037
12801
  for (const session of await this.oauthSessionManager?.list() ?? []) if (session.userId === userId && session.revokedAt === null) await this.oauthSessionManager?.markRevoked(session.id);
13038
12802
  }],
13039
- ["admin tokens", async () => this.adminTokens?.revokeAllCreatedBy(userId)],
13040
12803
  ["device credentials", async () => {
13041
12804
  for (const id of await this.deviceCredentials?.revokeAllForUser(userId, "user-deleted") ?? []) await this.loginSessions?.revokeByCredential(id);
13042
12805
  }],
13043
12806
  ["totp", async () => this.totpManager?.disable(userId)],
13044
- ["sign-in links", async () => this.externalIdentities?.removeAllForUser(userId)]
12807
+ ["sign-in links", async () => this.externalIdentities?.removeAllForUser(userId)],
12808
+ ["account preferences", async () => this.preferences?.wipeUser(userId)]
13045
12809
  ];
13046
12810
  for (const [what, step] of steps) try {
13047
12811
  await step();
@@ -13053,25 +12817,22 @@ var LocalAuthAddon = class extends BaseAddon {
13053
12817
  }
13054
12818
  }
13055
12819
  /**
13056
- * Drop auth rows that are dead but were never removed: scoped tokens past
13057
- * their expiry, and OAuth sessions revoked longer ago than
13058
- * {@link OAUTH_REVOKED_RETENTION_MS}.
12820
+ * Drop auth rows that are dead but were never removed: OAuth sessions
12821
+ * revoked longer ago than {@link OAUTH_REVOKED_RETENTION_MS}, dead login
12822
+ * sessions, old audit rows, dead device credentials. (Tokens are the hub's
12823
+ * `credential-tokens` rows, reaped there.)
13059
12824
  *
13060
- * Neither row could authorise anything — `validate` rejects an expired
13061
- * token, and every consumer treats a missing session exactly like a revoked
13062
- * one. So this is hygiene, and it is best-effort: a failed sweep is logged
12825
+ * No such row could authorise anything — every consumer treats a missing
12826
+ * session exactly like a revoked one. So this is hygiene, and it is best-effort: a failed sweep is logged
13063
12827
  * and the next tick tries again. It must never be able to fail boot.
13064
12828
  */
13065
12829
  async reapAuthRows() {
13066
12830
  try {
13067
- const tokens = await this.scopedTokenManager?.reapExpired() ?? 0;
13068
12831
  const sessions = await this.oauthSessionManager?.reapRevoked(Date.now() - OAUTH_REVOKED_RETENTION_MS) ?? 0;
13069
12832
  const logins = await this.loginSessions?.reap() ?? 0;
13070
- await this.adminTokens?.reap();
13071
12833
  await this.auditLog?.reap();
13072
12834
  await this.deviceCredentials?.reap();
13073
- if (tokens > 0 || sessions > 0 || logins > 0) this.ctx.logger.info("auth retention swept", { meta: {
13074
- expiredTokens: tokens,
12835
+ if (sessions > 0 || logins > 0) this.ctx.logger.info("auth retention swept", { meta: {
13075
12836
  revokedSessions: sessions,
13076
12837
  deadLoginSessions: logins
13077
12838
  } });
@@ -13089,15 +12850,13 @@ var LocalAuthAddon = class extends BaseAddon {
13089
12850
  this.authManager = null;
13090
12851
  this.userManager = null;
13091
12852
  this.apiKeyManager = null;
13092
- this.scopedTokenManager = null;
13093
12853
  this.oauthSessionManager = null;
13094
12854
  this.externalIdentities = null;
13095
12855
  this.loginSessions = null;
13096
- this.adminTokens = null;
13097
12856
  this.auditLog = null;
13098
12857
  this.deviceCredentials = null;
13099
12858
  this.deviceCa = null;
13100
12859
  }
13101
12860
  };
13102
12861
  //#endregion
13103
- export { LocalAuthAddon, LocalAuthAddon as default, ApiKeyManager as S, AuthAuditLog as _, attachUserManagementInternal as a, SettingsReadUnavailableError as b, ScopedTokenManager as c, onSessionsRevoked as d, DeviceCredentialManager as f, AdminTokenManager as g, ADMIN_TOKEN_PREFIX as h, USER_MANAGEMENT_INTERNAL as i, LoginSessionManager as l, ADMIN_TOKEN_MAX_LIFETIME_MS as m, FIRST_BOOT_ADMIN_USERNAME as n, getUserManagementInternal as o, PREVIOUS_LEAF_GRACE_MS as p, UserManager as r, DeviceCaStore as s, FIRST_BOOT_ADMIN_PASSWORD as t, REFRESH_TOKEN_PREFIX as u, AuthManager as v, isSettingsReadUnavailable as x, parseTokenExpiry as y };
12862
+ export { LocalAuthAddon, LocalAuthAddon as default, SettingsReadUnavailableError as _, attachUserManagementInternal as a, DeviceCaStore as c, onSessionsRevoked as d, DeviceCredentialManager as f, parseTokenExpiry as g, AuthManager as h, USER_MANAGEMENT_INTERNAL as i, LoginSessionManager as l, AuthAuditLog as m, FIRST_BOOT_ADMIN_USERNAME as n, getUserManagementInternal as o, PREVIOUS_LEAF_GRACE_MS as p, UserManager as r, preferencesLimitReasonOf as s, FIRST_BOOT_ADMIN_PASSWORD as t, REFRESH_TOKEN_PREFIX as u, isSettingsReadUnavailable as v, ApiKeyManager as y };