@camstack/server 1.2.840 → 1.2.842

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 (111) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api/oauth2/oauth2-routes.js +50 -6
  3. package/dist/api/trpc/generated-cap-routers.js +16 -0
  4. package/dist/core/addon/addon-registry.service.js +4 -0
  5. package/dist/core/addon/addon-route-request.js +18 -0
  6. package/dist/main.js +8 -5
  7. package/package.json +16 -8
  8. package/system/dist/addon-routes/addon-route-registry.d.ts +27 -1
  9. package/system/dist/addon-runner.js +7 -3
  10. package/system/dist/addon-runner.mjs +7 -3
  11. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  15. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  17. package/system/dist/builtins/autotrack/index.js +1 -1
  18. package/system/dist/builtins/autotrack/index.mjs +1 -1
  19. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  21. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  22. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  23. package/system/dist/builtins/camera-grid/index.js +1 -1
  24. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  25. package/system/dist/builtins/composer/composer.addon.js +5 -5
  26. package/system/dist/builtins/composer/composer.addon.mjs +5 -5
  27. package/system/dist/builtins/console-logging/index.js +1 -1
  28. package/system/dist/builtins/console-logging/index.mjs +1 -1
  29. package/system/dist/builtins/core-blocks/composition-api.d.ts +2 -2
  30. package/system/dist/builtins/core-blocks/composition-sources.d.ts +9 -2
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +2 -0
  32. package/system/dist/builtins/core-blocks/core-blocks.addon.js +598 -395
  33. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +598 -395
  34. package/system/dist/builtins/core-blocks/fan-link-forward.d.ts +42 -0
  35. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +25 -39
  36. package/system/dist/builtins/core-blocks/fan-presets-wiring.d.ts +5 -3
  37. package/system/dist/builtins/core-blocks/migrations/helper-to-customize.d.ts +3 -1
  38. package/system/dist/builtins/core-blocks/power-source-service.d.ts +2 -0
  39. package/system/dist/builtins/core-blocks/timed-run/timed-run-service.d.ts +8 -2
  40. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  41. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  42. package/system/dist/builtins/device-manager/device-bindings-store.d.ts +8 -5
  43. package/system/dist/builtins/device-manager/device-manager.addon.js +116 -22
  44. package/system/dist/builtins/device-manager/device-manager.addon.mjs +116 -22
  45. package/system/dist/builtins/device-manager/device-row-store.d.ts +0 -52
  46. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  47. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  48. package/system/dist/builtins/keychain/index.js +4 -4
  49. package/system/dist/builtins/keychain/index.mjs +4 -4
  50. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  51. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  52. package/system/dist/builtins/local-auth/local-auth.addon.js +21 -7
  53. package/system/dist/builtins/local-auth/local-auth.addon.mjs +21 -7
  54. package/system/dist/builtins/local-auth/oauth-grants.d.ts +9 -1
  55. package/system/dist/builtins/local-auth/oauth-session-manager.d.ts +8 -0
  56. package/system/dist/builtins/local-auth/record-kinds.d.ts +2 -0
  57. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  58. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  59. package/system/dist/builtins/loki-logging/index.js +1 -1
  60. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  61. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  62. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  63. package/system/dist/builtins/platform-probe/index.js +1 -1
  64. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  65. package/system/dist/builtins/record-entries/index.js +1 -1
  66. package/system/dist/builtins/record-entries/index.mjs +1 -1
  67. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  68. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  69. package/system/dist/builtins/snapshot/index.js +1 -1
  70. package/system/dist/builtins/snapshot/index.mjs +1 -1
  71. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  72. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  73. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  74. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  75. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  76. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  77. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  78. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  79. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  80. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  81. package/system/dist/builtins/winston-logging/index.js +1 -1
  82. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  83. package/system/dist/{capture-engine-7E2O4-UN.js → capture-engine-DSrJUGYs.js} +1 -1
  84. package/system/dist/{capture-engine-B5IBWIRT.mjs → capture-engine-DySELkE_.mjs} +1 -1
  85. package/system/dist/{composition-sources-DLtc8lSL.js → composition-sources-CNfFz3Cz.js} +32 -5
  86. package/system/dist/{composition-sources-Cfqn4cly.mjs → composition-sources-DZ4E9FFU.mjs} +32 -5
  87. package/system/dist/{constants-DjsgCnZk.mjs → constants-BEXN_b1Y.mjs} +1 -1
  88. package/system/dist/{constants-Cc70YreG.js → constants-DkgFDCQ7.js} +1 -1
  89. package/system/dist/{device-ca-CVP5h3u1.mjs → device-ca-Dk_9f4MY.mjs} +1 -1
  90. package/system/dist/{device-ca-C6JqeFfK.js → device-ca-sYcSz-Fv.js} +1 -1
  91. package/system/dist/{dist-OmrC_RZs.mjs → dist-4jAoRtpT.mjs} +1700 -363
  92. package/system/dist/{dist-CLnTYKFn.js → dist-LQWK1_M4.js} +1753 -374
  93. package/system/dist/file-host-worker.js +1 -1
  94. package/system/dist/file-host-worker.mjs +1 -1
  95. package/system/dist/{hub-identity-CKQVXf4o.mjs → hub-identity-BxGHDga-.mjs} +1 -1
  96. package/system/dist/{hub-identity-TrZcnJkB.js → hub-identity-haC7V8-b.js} +1 -1
  97. package/system/dist/{hub-mdns-ciao-C8G0K1Z1.mjs → hub-mdns-ciao-Birwi8W5.mjs} +2 -2
  98. package/system/dist/{hub-mdns-ciao-ocg6suyX.js → hub-mdns-ciao-zxNvdRQz.js} +2 -2
  99. package/system/dist/index.d.ts +1 -1
  100. package/system/dist/index.js +63 -13
  101. package/system/dist/index.mjs +62 -14
  102. package/system/dist/kernel/moleculer/child-addon-call-dispatch.d.ts +1 -0
  103. package/system/dist/{legacy-integration-rows-door-BPkJUGaX.mjs → legacy-integration-rows-door-C-hOd-lt.mjs} +1 -1
  104. package/system/dist/{legacy-integration-rows-door-b6CUxtXX.js → legacy-integration-rows-door-CCtcCRjZ.js} +1 -1
  105. package/system/dist/{rename-composition-block-N7lslQJK.js → rename-composition-block-BCZeI3eY.js} +1 -1
  106. package/system/dist/{rename-composition-block-DPlsP1xF.mjs → rename-composition-block-YpAVqp4W.mjs} +1 -1
  107. package/system/dist/{restore-archive-Btc3H-Fg.mjs → restore-archive-BpC3y50e.mjs} +1 -1
  108. package/system/dist/{restore-archive-CcuEoEtj.js → restore-archive-D0Nyukhb.js} +1 -1
  109. package/system/dist/{wal-maintenance-g7yvxLMj.mjs → wal-maintenance-C7jLVFCw.mjs} +0 -0
  110. package/system/dist/{wal-maintenance-B2_uCEi5.js → wal-maintenance-CRiSNk0X.js} +0 -0
  111. package/system/package.json +1 -1
@@ -1,7 +1,7 @@
1
- import { $c as secretTreeFromPaths, $i as parseStreamParamsFormPatch, Ar as enumerateSchemaFields, Ba as runtimeFieldUnit, Bn as canonicalIconKey, Ci as locationIconKey, Ec as isCommand$1, Er as deviceStatusCapability, Fc as isSecretMarker, Fr as expandContainer, Gs as SECRET_CLEAR, Ic as isSecretMarkerLike, J as DEVICE_TEMPLATE_MAX_LENGTH, Ja as settleDeviceFeatures, Jr as generateDeviceAlias, Ki as normalizeUnit, Kr as formatMinutes, La as resolveTemplateRef, Ln as buildStreamParamsConfigSchema, Nc as isSecretClear, Oc as isDeviceConfigCap, R as DAY_NAMES, Sr as deviceManagerCapability, Tr as deviceStateCapability, Un as checkDeviceAlias, Va as runtimeStatePolicyFor, Xc as resolveSecretMarkers, Xs as WELL_KNOWN_TAB_MAP, Y as DEVICE_TEMPLATE_MAX_OUTPUT, Z as DEVICE_TEMPLATE_VALUES_CAP, al as transformSecretWrite, b as CAP_NAMES_WITH_STATUS, bc as expandCapMethods$1, br as deviceExtensionCapability, cc as collectZodSecretPaths$1, cr as createDeviceExtensionProvider, dl as DeviceRole, en as STREAM_PROFILE_META, eo as siteZoneKey, fl as DeviceType$1, gc as defineRecordKinds, ha as reconcileReportedFeatures, hl as EventCategory$1, hr as defineExtensionSlotProvider, hs as BaseAddon, il as toSecretFieldView, it as DiscoveryProposalBodySchema, jc as isKeychainStoredField, k as ConditionMirror, kr as enumerateItemArrayFields, kt as MINUTES_PER_DAY, lc as commandEffect, mt as FieldClaimSchema, nl as sleep$2, nt as DeviceStatusSchema, ol as userError, pl as errMsg$1, pt as FieldClaimModeSchema, q as DEVICE_TEMPLATE_FILTERS, rc as auditedFields, rs as implementedMethodsOf$1, rt as DeviceTombstoneSchema, s as ALL_CAPABILITY_DEFINITIONS, ui as isKernelDerivedFeature, ul as DeviceFeature, v as CAMERA_SWITCH_ORDER, vi as legacyAutoLinkIds } from "../../dist-OmrC_RZs.mjs";
1
+ import { $r as generateDeviceAlias, Ar as deviceStatusCapability, At as MINUTES_PER_DAY, Bc as isSecretClear, Cc as defineRecordKinds, Dc as expandCapMethods$1, Er as deviceManagerCapability, Fc as isDeviceConfigCap, Hc as isSecretMarker, Hn as canonicalStoredDeviceType, J as DEVICE_TEMPLATE_MAX_OUTPUT, Ja as runtimeStatePolicyFor, K as DEVICE_TEMPLATE_FILTERS, Kn as checkDeviceAlias, L as DAY_NAMES, Nc as isCommand$1, Nr as enumerateItemArrayFields, Pr as enumerateSchemaFields, Qi as normalizeUnit, Qs as SECRET_CLEAR, Rc as isKeychainStoredField, Rn as buildStreamParamsConfigSchema, Sa as reconcileReportedFeatures, Sl as EventCategory$1, Ss as BaseAddon, Uc as isSecretMarkerLike, Un as capAppliesToDeviceKind, Vn as canonicalIconKey, Wa as resolveTemplateRef, X as DEVICE_TEMPLATE_VALUES_CAP, Zr as formatMinutes, _l as DeviceFeature, aa as parseStreamParamsFormPatch, b as CAP_NAMES_WITH_STATUS, bl as errMsg$1, dl as toSecretFieldView, fl as transformSecretWrite, fr as createDeviceExtensionProvider, gc as commandEffect, gi as isKernelDerivedFeature, hc as collectZodSecretPaths$1, ht as FieldClaimSchema, k as ConditionMirror, ki as locationIconKey, kr as deviceStateCapability, ll as sleep$2, mt as FieldClaimModeSchema, nt as DeviceTombstoneSchema, ol as secretTreeFromPaths, pl as userError, q as DEVICE_TEMPLATE_MAX_LENGTH, qa as runtimeFieldUnit, rc as WELL_KNOWN_TAB_MAP, rl as resolveSecretMarkers, rt as DiscoveryProposalBodySchema, s as ALL_CAPABILITY_DEFINITIONS, so as siteZoneKey, tn as STREAM_PROFILE_META, to as settleDeviceFeatures, tt as DeviceStatusSchema, uc as auditedFields, us as implementedMethodsOf$1, v as CAMERA_SWITCH_ORDER, vl as DeviceRole, wi as legacyAutoLinkIds, wr as deviceExtensionCapability, yl as DeviceType$1, yr as defineExtensionSlotProvider, zr as expandContainer } from "../../dist-4jAoRtpT.mjs";
2
2
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
3
3
  import { a as redactLogText, i as redactLogMeta, n as isSecretArgumentKey } from "../../log-redactor-XLDrPzOi.mjs";
4
- import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-DPlsP1xF.mjs";
4
+ import { n as renameCompositionBlock, t as composedBlockIdOf } from "../../rename-composition-block-YpAVqp4W.mjs";
5
5
  import { t as prefixRange } from "../../prefix-range-Dl0znowN.mjs";
6
6
  import { t as loadPrefixed } from "../../prefix-walk-DAOBSyH1.mjs";
7
7
  import { n as purgeRetiredSettingsRows } from "../../retired-settings-keys-u6xQA6r7.mjs";
@@ -548,6 +548,25 @@ function joinRuntimeBlob(native, owned, policyFor) {
548
548
  return out;
549
549
  }
550
550
  /**
551
+ * `record` with the value at a DOTTED claim path replaced, as a copy: a claim
552
+ * of `oscillationAxes.horizontal.angle` sets that leaf and keeps its siblings.
553
+ * A missing or `null` parent becomes `{}` — the cap schema's leaf defaults
554
+ * fill the rest (an axis the native reports absent, linked in Customize).
555
+ */
556
+ function setPath(record, segments, value) {
557
+ const [head, ...rest] = segments;
558
+ if (head === void 0) return { ...record };
559
+ if (rest.length === 0) return {
560
+ ...record,
561
+ [head]: value
562
+ };
563
+ const child = record[head];
564
+ return {
565
+ ...record,
566
+ [head]: setPath(isPlainRecord(child) ? child : {}, rest, value)
567
+ };
568
+ }
569
+ /**
551
570
  * The one merge. Held when a claimed field has no value yet (S5: never
552
571
  * answered from the native), when a `replace` has no native slice to overlay
553
572
  * (a partial slice is never emitted), or when the merged slice fails the cap's
@@ -563,10 +582,7 @@ function mergeOwned(native, owned, schema) {
563
582
  kind: "held",
564
583
  reason: "no native slice yet"
565
584
  };
566
- const merged = {
567
- ...native,
568
- ...owned.values
569
- };
585
+ const merged = Object.entries(owned.values).reduce((acc, [path, value]) => setPath(acc, path.split("."), value), { ...native });
570
586
  if (schema === null) return {
571
587
  kind: "slice",
572
588
  slice: merged
@@ -1492,22 +1508,22 @@ function onceLedgerNonEmpty(deps) {
1492
1508
  };
1493
1509
  }
1494
1510
  /**
1495
- * Does a capability apply to a device of type `deviceType`?
1511
+ * Does a capability apply to a device of type `deviceType` and role `role`?
1496
1512
  *
1497
- * The cap's `deviceTypes` is the ONLY declaration consulted (D4: behavioural
1498
- * cap metadata lives in the `*.cap.ts`, never in a manifest). Two deliberate
1499
- * fail-open cases:
1513
+ * The cap's `deviceTypes` and `deviceRoles` are the ONLY declarations
1514
+ * consulted (D4: behavioural cap metadata lives in the `*.cap.ts`, never in a
1515
+ * manifest). A type the cap's `deviceRoles` names binds only for those roles
1516
+ * (D1033: a heater is a switch with role `switch-heater`); the role is read
1517
+ * from the row on every pass, so a role change applies with no restart. Two
1518
+ * deliberate fail-open cases:
1500
1519
  *
1501
1520
  * - a cap that declares no `deviceTypes` (or an empty list) applies to every
1502
1521
  * device — the pre-existing, back-compatible semantics;
1503
1522
  * - an UNKNOWN `deviceType` never filters, so a missing/failed meta lookup
1504
1523
  * changes nothing (D49: a read that fails must not destroy work).
1505
1524
  */
1506
- function capAppliesToDeviceType(def, deviceType) {
1507
- if (deviceType === void 0) return true;
1508
- const declared = def?.deviceTypes;
1509
- if (!declared || declared.length === 0) return true;
1510
- return declared.some((t) => t === deviceType);
1525
+ function capAppliesToDeviceType(def, deviceType, role) {
1526
+ return capAppliesToDeviceKind(def, deviceType, role);
1511
1527
  }
1512
1528
  /**
1513
1529
  * An addon's identity, with the node it happens to run on stripped.
@@ -1531,13 +1547,13 @@ function addonIdentityOf(addonId) {
1531
1547
  * addon are ONE provider — the defect this exists to make unrepresentable.
1532
1548
  * Gated only by the cap's declared `deviceTypes` (D4), like step 2's auto-bind.
1533
1549
  */
1534
- function collectionBindings(deps, deviceId, deviceType) {
1550
+ function collectionBindings(deps, deviceId, deviceType, role) {
1535
1551
  const registry = deps.capabilityRegistry;
1536
1552
  if (!registry) return [];
1537
1553
  const out = [];
1538
1554
  for (const declared of registry.listCapabilities()) {
1539
1555
  if (declared.mode !== "collection") continue;
1540
- if (!capAppliesToDeviceType(registry.getDefinition(declared.name), deviceType)) continue;
1556
+ if (!capAppliesToDeviceType(registry.getDefinition(declared.name), deviceType, role)) continue;
1541
1557
  const nativeAddonId = registry.getNativeAddonId(declared.name, deviceId);
1542
1558
  const seen = /* @__PURE__ */ new Set();
1543
1559
  for (const addonId of [...declared.providers, ...nativeAddonId ? [nativeAddonId] : []]) {
@@ -1591,10 +1607,11 @@ async function resolveBindingsForDevice(deps, deviceId, row, pass) {
1591
1607
  const storeKey = String(deviceId);
1592
1608
  const perDevice = pass.store.deviceBindings[storeKey] ?? {};
1593
1609
  const deviceType = resolveDeviceType(deps, row, deviceId);
1610
+ const deviceRole = row?.meta.role ?? null;
1594
1611
  const presence = await resolveDevicePresence(deps, row, deviceId, pass.ledgerNonEmpty);
1595
1612
  const entries = [];
1596
1613
  const seenCaps = /* @__PURE__ */ new Set();
1597
- const collectionEntries = collectionBindings(deps, deviceId, deviceType);
1614
+ const collectionEntries = collectionBindings(deps, deviceId, deviceType, deviceRole);
1598
1615
  for (const entry of collectionEntries) {
1599
1616
  entries.push(entry);
1600
1617
  seenCaps.add(entry.capName);
@@ -1629,7 +1646,7 @@ async function resolveBindingsForDevice(deps, deviceId, row, pass) {
1629
1646
  const skippedForType = [];
1630
1647
  for (const capName of deps.capabilityRegistry.getCapsWithDefaultWrapper()) {
1631
1648
  if (seenCaps.has(capName)) continue;
1632
- if (!capAppliesToDeviceType(deps.capabilityRegistry.getDefinition(capName), deviceType)) {
1649
+ if (!capAppliesToDeviceType(deps.capabilityRegistry.getDefinition(capName), deviceType, deviceRole)) {
1633
1650
  skippedForType.push(capName);
1634
1651
  continue;
1635
1652
  }
@@ -6985,7 +7002,7 @@ async function registerDevice(pctx, input) {
6985
7002
  throw new Error(`[device-manager] registerDevice: device ${id} (${addonId}/${stableId}) was removed — refusing to resurrect it`);
6986
7003
  }
6987
7004
  if (Array.isArray(input.secretConfigPaths)) pctx.secretConfigPaths.set(id, input.secretConfigPaths);
6988
- const { isFirstRegistration, exportFingerprint, fingerprintChanged, storedFeatures, inheritedLocation, inheritedDescendantIds, inheritFailed } = await pctx.metaStore.withMetaWriteLock(async () => {
7005
+ const { isFirstRegistration, exportFingerprint, fingerprintChanged, storedFeatures, inheritedLocation, inheritedDescendantIds, inheritFailed, filledRole } = await pctx.metaStore.withMetaWriteLock(async () => {
6989
7006
  const existingRow = await pctx.metaStore.rows.get(id);
6990
7007
  const existingMeta = existingRow?.meta;
6991
7008
  const wasRegistered = existingRow?.registered ?? false;
@@ -7017,6 +7034,9 @@ async function registerDevice(pctx, input) {
7017
7034
  exportFingerprint: fingerprint
7018
7035
  });
7019
7036
  if (existingMeta?.alias === void 0) await pctx.metaStore.rows.patch(id, { alias: await freeAliasFor(pctx.metaStore.rows, resolvedName, id, await readReservedAliases(pctx)) });
7037
+ const providerRole = typeof input.role === "string" && input.role.length > 0 ? input.role : null;
7038
+ const roleToFill = existingMeta?.role == null ? providerRole : null;
7039
+ if (roleToFill !== null) await pctx.metaStore.rows.patch(id, { role: roleToFill });
7020
7040
  const descendantsFilled = [];
7021
7041
  const descendantsFailed = [];
7022
7042
  if (inherited !== null) for (const descendant of await collectDescendants(pctx.metaStore, id)) {
@@ -7038,9 +7058,30 @@ async function registerDevice(pctx, input) {
7038
7058
  fingerprintChanged: existingMeta?.exportFingerprint !== fingerprint,
7039
7059
  inheritedLocation: inherited,
7040
7060
  inheritedDescendantIds: descendantsFilled,
7041
- inheritFailed: descendantsFailed
7061
+ inheritFailed: descendantsFailed,
7062
+ filledRole: roleToFill
7042
7063
  };
7043
7064
  });
7065
+ if (filledRole !== null) {
7066
+ pctx.host.ctx.eventBus.emit({
7067
+ id: randomUUID(),
7068
+ timestamp: /* @__PURE__ */ new Date(),
7069
+ source: {
7070
+ type: "device",
7071
+ id
7072
+ },
7073
+ category: EventCategory$1.DeviceMetaChanged,
7074
+ data: {
7075
+ deviceId: id,
7076
+ field: "role",
7077
+ value: filledRole
7078
+ }
7079
+ });
7080
+ pctx.host.ctx.logger.info("registerDevice: filled the missing role from the provider", {
7081
+ tags: { deviceId: id },
7082
+ meta: { role: filledRole }
7083
+ });
7084
+ }
7044
7085
  if (Object.keys(config).length > 0) await pctx.settings.writeDeviceStore(id, config);
7045
7086
  pctx.metaStore.idToAddonId.set(id, addonId);
7046
7087
  if (inheritedLocation !== null) {
@@ -9810,6 +9851,58 @@ var FleetReadCensus = class FleetReadCensus {
9810
9851
  //#endregion
9811
9852
  //#region src/builtins/device-manager/device-row-store.ts
9812
9853
  /**
9854
+ * `device-manager:devices` — ONE ROW PER DEVICE.
9855
+ *
9856
+ * ## What this replaces
9857
+ *
9858
+ * The device-manager used to keep its whole fleet in three JSON blobs on the
9859
+ * addon-settings row set (`deviceMeta`, `deviceMetadata`, `deviceIndex`).
9860
+ * Measured on the live hub 2026-08-19: 467 KB + 87 KB + 70 KB = 625 KB of the
9861
+ * table's 627 KB, and EVERY read of any of them read and `JSON.parse`d all
9862
+ * three, synchronously, on hub-main's event loop — `ctx.settings.readAddonStore`
9863
+ * lands in `SqliteSettingsBackend.getAllAddon`, which is prefix-scoped to the
9864
+ * addon but not to the key. A V8 profile of that boot had hub-main's JS thread
9865
+ * 99.9% busy for 76 s with 64% of it inside `getAllAddon`, ~89% of that entered
9866
+ * through the meta store, and every runner's first store read queued behind it.
9867
+ *
9868
+ * Writing was worse than reading. `ConfigManager.createSettingsView`'s
9869
+ * `writeAddonStore` is `setAllAddon(addonId, { ...existing, ...patch })`, and
9870
+ * `setAllAddon` DELETEs and re-INSERTs every row of the addon — so renaming one
9871
+ * camera rewrote 625 KB.
9872
+ *
9873
+ * A row per device makes the per-device question a primary-key lookup and the
9874
+ * per-device write a single-row upsert touching only the columns named.
9875
+ *
9876
+ * ## Why `deviceIndex` has no column and no collection
9877
+ *
9878
+ * `deviceIndex` was `Record<addonId, stableId[]>` — pure derivation: `addonId`
9879
+ * and `stableId` are fields of every row, so "this addon's devices" is
9880
+ * `where: { addonId }`. It carried exactly one bit that is NOT derivable:
9881
+ * membership meant "`registerDevice` has run at least once", which is how
9882
+ * `registerDevice` tells a FIRST registration (emit `DeviceRegistered`) from a
9883
+ * meta refresh. `allocateDeviceId` writes a row without registering, so row
9884
+ * existence alone cannot answer it. That bit is the {@link registered} column,
9885
+ * and nothing else of `deviceIndex` survives.
9886
+ *
9887
+ * ## Why metadata is a column and not a second collection
9888
+ *
9889
+ * `deviceMetadata` lived in its own blob for ONE reason: a blob write is
9890
+ * whole-value, so a lifecycle writer (`registerDevice` / `setName` / …) that
9891
+ * had to preserve a `metadata` field would eventually clobber a concurrent
9892
+ * `setMetadata`. Single-writer-per-blob was the fix. Column writes have no such
9893
+ * problem — `set` names its columns and leaves the rest of the row untouched —
9894
+ * so the split has no reason to exist and metadata rides on the device's own
9895
+ * row.
9896
+ *
9897
+ * ## Adding a column later
9898
+ *
9899
+ * `declareCollection` is additive ONLY when SQLite can `ALTER TABLE … ADD
9900
+ * COLUMN` it. A new `NOT NULL` column without a `defaultValue` cannot be added
9901
+ * to a populated table, so the backend counts it as non-additive and REBUILDS
9902
+ * the collection — dropping every row. Any column added here after ship must
9903
+ * either be nullable or carry a `defaultValue`.
9904
+ */
9905
+ /**
9813
9906
  * @durable class=ledger owner=device-manager
9814
9907
  * write="one row per device, written by `allocateDeviceId` (identity placeholder),
9815
9908
  * `registerDevice` (full reconcile) and every meta setter (single-column patch);
@@ -10049,7 +10142,8 @@ function decodeDeviceRow(data) {
10049
10142
  const deviceId = readNumber(data["deviceId"]);
10050
10143
  const addonId = readString(data["addonId"]);
10051
10144
  const stableId = readString(data["stableId"]);
10052
- const type = readString(data["type"]);
10145
+ const storedType = readString(data["type"]);
10146
+ const type = storedType === void 0 ? void 0 : canonicalStoredDeviceType(storedType);
10053
10147
  const name = readString(data["name"]);
10054
10148
  if (deviceId === void 0 || addonId === void 0 || stableId === void 0 || type === void 0 || name === void 0) return null;
10055
10149
  const location = readString(data["location"]);
@@ -1,55 +1,3 @@
1
- /**
2
- * `device-manager:devices` — ONE ROW PER DEVICE.
3
- *
4
- * ## What this replaces
5
- *
6
- * The device-manager used to keep its whole fleet in three JSON blobs on the
7
- * addon-settings row set (`deviceMeta`, `deviceMetadata`, `deviceIndex`).
8
- * Measured on the live hub 2026-08-19: 467 KB + 87 KB + 70 KB = 625 KB of the
9
- * table's 627 KB, and EVERY read of any of them read and `JSON.parse`d all
10
- * three, synchronously, on hub-main's event loop — `ctx.settings.readAddonStore`
11
- * lands in `SqliteSettingsBackend.getAllAddon`, which is prefix-scoped to the
12
- * addon but not to the key. A V8 profile of that boot had hub-main's JS thread
13
- * 99.9% busy for 76 s with 64% of it inside `getAllAddon`, ~89% of that entered
14
- * through the meta store, and every runner's first store read queued behind it.
15
- *
16
- * Writing was worse than reading. `ConfigManager.createSettingsView`'s
17
- * `writeAddonStore` is `setAllAddon(addonId, { ...existing, ...patch })`, and
18
- * `setAllAddon` DELETEs and re-INSERTs every row of the addon — so renaming one
19
- * camera rewrote 625 KB.
20
- *
21
- * A row per device makes the per-device question a primary-key lookup and the
22
- * per-device write a single-row upsert touching only the columns named.
23
- *
24
- * ## Why `deviceIndex` has no column and no collection
25
- *
26
- * `deviceIndex` was `Record<addonId, stableId[]>` — pure derivation: `addonId`
27
- * and `stableId` are fields of every row, so "this addon's devices" is
28
- * `where: { addonId }`. It carried exactly one bit that is NOT derivable:
29
- * membership meant "`registerDevice` has run at least once", which is how
30
- * `registerDevice` tells a FIRST registration (emit `DeviceRegistered`) from a
31
- * meta refresh. `allocateDeviceId` writes a row without registering, so row
32
- * existence alone cannot answer it. That bit is the {@link registered} column,
33
- * and nothing else of `deviceIndex` survives.
34
- *
35
- * ## Why metadata is a column and not a second collection
36
- *
37
- * `deviceMetadata` lived in its own blob for ONE reason: a blob write is
38
- * whole-value, so a lifecycle writer (`registerDevice` / `setName` / …) that
39
- * had to preserve a `metadata` field would eventually clobber a concurrent
40
- * `setMetadata`. Single-writer-per-blob was the fix. Column writes have no such
41
- * problem — `set` names its columns and leaves the rest of the row untouched —
42
- * so the split has no reason to exist and metadata rides on the device's own
43
- * row.
44
- *
45
- * ## Adding a column later
46
- *
47
- * `declareCollection` is additive ONLY when SQLite can `ALTER TABLE … ADD
48
- * COLUMN` it. A new `NOT NULL` column without a `defaultValue` cannot be added
49
- * to a populated table, so the backend counts it as non-additive and REBUILDS
50
- * the collection — dropping every row. Any column added here after ship must
51
- * either be nullable or carry a `defaultValue`.
52
- */
53
1
  import type { ChildLayout, CollectionColumn, CollectionIndex, DeviceDisplayOverride, IScopedLogger, MutationFilter, QueryFilter, SettingsRecord, SettingsStoreClient } from "@camstack/types";
54
2
  import type { RetiredRowStore } from "../sqlite-storage/retired-settings-keys.js";
55
3
  import type { PersistedDeviceMeta } from "./device-meta-types.js";
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-CLnTYKFn.js");
6
+ const require_dist = require("../../dist-LQWK1_M4.js");
7
7
  const require_formatter = require("../../formatter-xbxeV4GD.js");
8
8
  //#region src/builtins/hub-forwarder/hub-forwarder-destination.ts
9
9
  var DEFAULT_OUTBOUND_BUFFER_SIZE = 500;
@@ -1,4 +1,4 @@
1
- import { Ei as logDestinationCapability, hs as BaseAddon } from "../../dist-OmrC_RZs.mjs";
1
+ import { Mi as logDestinationCapability, Ss as BaseAddon } from "../../dist-4jAoRtpT.mjs";
2
2
  import { t as formatLogLine } from "../../formatter-DkYZ4LXp.mjs";
3
3
  //#region src/builtins/hub-forwarder/hub-forwarder-destination.ts
4
4
  var DEFAULT_OUTBOUND_BUFFER_SIZE = 500;
@@ -3,11 +3,11 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-CLnTYKFn.js");
7
- const require_device_ca = require("../../device-ca-C6JqeFfK.js");
6
+ const require_dist = require("../../dist-LQWK1_M4.js");
7
+ const require_device_ca = require("../../device-ca-sYcSz-Fv.js");
8
8
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
9
- const require_legacy_integration_rows_door = require("../../legacy-integration-rows-door-b6CUxtXX.js");
10
- const require_constants = require("../../constants-Cc70YreG.js");
9
+ const require_legacy_integration_rows_door = require("../../legacy-integration-rows-door-CCtcCRjZ.js");
10
+ const require_constants = require("../../constants-DkgFDCQ7.js");
11
11
  const require_platform_key_source = require("../../platform-key-source-Di7HrlGR.js");
12
12
  let node_crypto = require("node:crypto");
13
13
  let _camstack_types_node = require("@camstack/types/node");
@@ -1,8 +1,8 @@
1
- import { Ct as KEYCHAIN_RESET_TRIGGER_ACTOR, Kc as parseSecretRef, Tt as KeychainResetRecordSchema, Uc as normalizeSecretOwner, _i as keychainCapability, gc as defineRecordKinds, gi as keychainAdminCapability, hl as EventCategory, hs as BaseAddon, wt as KeychainAuditEntrySchema, xc as formatSecretScope } from "../../dist-OmrC_RZs.mjs";
2
- import { d as JWT_SIGNING_KEY_REF, n as DEVICE_CA_KEY_REF, p as SYSTEM_SECRET_OWNER } from "../../device-ca-CVP5h3u1.mjs";
1
+ import { $c as parseSecretRef, Cc as defineRecordKinds, Ci as keychainCapability, Et as KeychainResetRecordSchema, Oc as formatSecretScope, Si as keychainAdminCapability, Sl as EventCategory, Ss as BaseAddon, Tt as KeychainAuditEntrySchema, Xc as normalizeSecretOwner, wt as KEYCHAIN_RESET_TRIGGER_ACTOR } from "../../dist-4jAoRtpT.mjs";
2
+ import { d as JWT_SIGNING_KEY_REF, n as DEVICE_CA_KEY_REF, p as SYSTEM_SECRET_OWNER } from "../../device-ca-Dk_9f4MY.mjs";
3
3
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
4
- import { t as LEGACY_INTEGRATION_ROWS_TABLE } from "../../legacy-integration-rows-door-BPkJUGaX.mjs";
5
- import { a as MESH_CA_KEY_REF } from "../../constants-DjsgCnZk.mjs";
4
+ import { t as LEGACY_INTEGRATION_ROWS_TABLE } from "../../legacy-integration-rows-door-C-hOd-lt.mjs";
5
+ import { a as MESH_CA_KEY_REF } from "../../constants-BEXN_b1Y.mjs";
6
6
  import { n as getPlatformKeychainKey } from "../../platform-key-source-BWlq0jjn.mjs";
7
7
  import { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
8
8
  import { restrictDirToOwnerSync, restrictFileToOwnerSync, writeOwnerOnlyFileSync } from "@camstack/types/node";
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("../../chunk-Cek0wNdY.js");
3
- const require_dist = require("../../dist-CLnTYKFn.js");
3
+ const require_dist = require("../../dist-LQWK1_M4.js");
4
4
  let node_fs = require("node:fs");
5
5
  let node_path = require("node:path");
6
6
  node_path = require_chunk.__toESM(node_path);
@@ -1,4 +1,4 @@
1
- import { Ai as mayWriteToLocation, Gt as RECORDING_SOURCE_CAMSTACK_ADDON, Jt as RecordingStatusSchema, dc as createEvent, hl as EventCategory, hs as BaseAddon, pl as errMsg } from "../../dist-OmrC_RZs.mjs";
1
+ import { Ii as mayWriteToLocation, Kt as RECORDING_SOURCE_CAMSTACK_ADDON, Sl as EventCategory, Ss as BaseAddon, Yt as RecordingStatusSchema, bl as errMsg, vc as createEvent } from "../../dist-4jAoRtpT.mjs";
2
2
  import { constants } from "node:fs";
3
3
  import path from "node:path";
4
4
  import * as fsp from "node:fs/promises";
@@ -3,10 +3,10 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-CLnTYKFn.js");
6
+ const require_dist = require("../../dist-LQWK1_M4.js");
7
7
  const require_safe_buffer$1 = require("../../safe-buffer-D3aoa-7X.js");
8
8
  const require_ms$1 = require("../../ms-LB3giGoU.js");
9
- const require_device_ca = require("../../device-ca-C6JqeFfK.js");
9
+ const require_device_ca = require("../../device-ca-sYcSz-Fv.js");
10
10
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
11
11
  let zod = require("zod");
12
12
  let node_crypto = require("node:crypto");
@@ -6091,6 +6091,7 @@ var AuthManager = class {
6091
6091
  ...payload.scopes !== void 0 ? { scopes: payload.scopes } : {},
6092
6092
  ...payload.redirectUri !== void 0 ? { redirectUri: payload.redirectUri } : {},
6093
6093
  ...payload.integrationId !== void 0 ? { integrationId: payload.integrationId } : {},
6094
+ ...payload.instanceId !== void 0 ? { instanceId: payload.instanceId } : {},
6094
6095
  ...payload.jti !== void 0 ? { jti: payload.jti } : {},
6095
6096
  ...payload.sessionId !== void 0 ? { sessionId: payload.sessionId } : {},
6096
6097
  ...payload.refreshTtl !== void 0 ? { refreshTtl: payload.refreshTtl } : {},
@@ -6137,6 +6138,7 @@ var AuthManager = class {
6137
6138
  const scopes = Array.isArray(decoded["scopes"]) ? decoded["scopes"] : void 0;
6138
6139
  const redirectUri = typeof decoded["redirectUri"] === "string" ? decoded["redirectUri"] : void 0;
6139
6140
  const integrationId = typeof decoded["integrationId"] === "string" ? decoded["integrationId"] : void 0;
6141
+ const instanceId = typeof decoded["instanceId"] === "string" ? decoded["instanceId"] : void 0;
6140
6142
  const jti = typeof decoded["jti"] === "string" ? decoded["jti"] : void 0;
6141
6143
  const sessionId = typeof decoded["sessionId"] === "string" ? decoded["sessionId"] : void 0;
6142
6144
  const linkIntent = typeof decoded["linkIntent"] === "string" ? decoded["linkIntent"] : void 0;
@@ -6158,6 +6160,7 @@ var AuthManager = class {
6158
6160
  ...scopes !== void 0 ? { scopes } : {},
6159
6161
  ...redirectUri !== void 0 ? { redirectUri } : {},
6160
6162
  ...integrationId !== void 0 ? { integrationId } : {},
6163
+ ...instanceId !== void 0 ? { instanceId } : {},
6161
6164
  ...jti !== void 0 ? { jti } : {},
6162
6165
  ...sessionId !== void 0 ? { sessionId } : {},
6163
6166
  ...refreshTtl !== void 0 ? { refreshTtl } : {},
@@ -7445,6 +7448,7 @@ var OauthSessionBodySchema = zod.z.object({
7445
7448
  userId: zod.z.string(),
7446
7449
  username: zod.z.string(),
7447
7450
  integrationId: zod.z.string(),
7451
+ instanceId: zod.z.string().optional(),
7448
7452
  scopes: zod.z.array(require_dist.TokenScopeSchema),
7449
7453
  createdAt: zod.z.number(),
7450
7454
  lastUsedAt: zod.z.number(),
@@ -11597,12 +11601,14 @@ function createOauthGrants(ssoBridge, sessionManager) {
11597
11601
  * every integration; the refresh lifetime is the knob, because a refresh is
11598
11602
  * re-checked against the session every time it is used.
11599
11603
  */
11600
- async function mintPair(userId, username, scopes, hubUrl, sessionId, refreshTtl) {
11604
+ async function mintPair(userId, username, scopes, hubUrl, sessionId, refreshTtl, instanceId) {
11605
+ const instanceClaim = instanceId !== null ? { instanceId } : {};
11601
11606
  const access = await ssoBridge.signBridgeToken({
11602
11607
  claims: {
11603
11608
  ...baseClaims(userId, username, scopes, hubUrl),
11604
11609
  provider: "oauth-access",
11605
- sessionId
11610
+ sessionId,
11611
+ ...instanceClaim
11606
11612
  },
11607
11613
  ttlSec: TTL["oauth-access"]
11608
11614
  });
@@ -11611,6 +11617,7 @@ function createOauthGrants(ssoBridge, sessionManager) {
11611
11617
  ...baseClaims(userId, username, scopes, hubUrl),
11612
11618
  provider: "oauth-refresh",
11613
11619
  sessionId,
11620
+ ...instanceClaim,
11614
11621
  refreshTtl
11615
11622
  },
11616
11623
  ttlSec: refreshTtl
@@ -11636,6 +11643,7 @@ function createOauthGrants(ssoBridge, sessionManager) {
11636
11643
  provider: "oauth-code",
11637
11644
  redirectUri: input.redirectUri,
11638
11645
  integrationId: input.integrationId,
11646
+ ...input.instanceId !== void 0 ? { instanceId: input.instanceId } : {},
11639
11647
  jti,
11640
11648
  ...input.codeChallenge ? { codeChallenge: input.codeChallenge } : {},
11641
11649
  ...input.refreshTtlSec !== void 0 ? { refreshTtl: input.refreshTtlSec } : {}
@@ -11665,9 +11673,10 @@ function createOauthGrants(ssoBridge, sessionManager) {
11665
11673
  userId: claims.userId,
11666
11674
  username: claims.username,
11667
11675
  integrationId: typeof claims.integrationId === "string" ? claims.integrationId : "<unknown>",
11676
+ instanceId: typeof claims.instanceId === "string" ? claims.instanceId : null,
11668
11677
  scopes
11669
11678
  });
11670
- return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", session.id, readRefreshTtl(claims.refreshTtl));
11679
+ return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", session.id, readRefreshTtl(claims.refreshTtl), session.instanceId);
11671
11680
  },
11672
11681
  async oauthRefresh(input) {
11673
11682
  const claims = await ssoBridge.verifyBridgeToken({ token: input.refreshToken });
@@ -11678,7 +11687,7 @@ function createOauthGrants(ssoBridge, sessionManager) {
11678
11687
  if (!session || session.revokedAt != null) return null;
11679
11688
  await sessionManager.touch(sessionId);
11680
11689
  const scopes = claims.scopes ?? [];
11681
- return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", sessionId, readRefreshTtl(claims.refreshTtl));
11690
+ return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", sessionId, readRefreshTtl(claims.refreshTtl), session.instanceId);
11682
11691
  },
11683
11692
  async oauthVerifyAccessToken(input) {
11684
11693
  const claims = await ssoBridge.verifyBridgeToken({ token: input.token });
@@ -11690,7 +11699,8 @@ function createOauthGrants(ssoBridge, sessionManager) {
11690
11699
  return {
11691
11700
  userId: claims.userId,
11692
11701
  username: claims.username,
11693
- scopes: claims.scopes ?? []
11702
+ scopes: claims.scopes ?? [],
11703
+ ...session.instanceId !== null ? { instanceId: session.instanceId } : {}
11694
11704
  };
11695
11705
  }
11696
11706
  };
@@ -11702,6 +11712,7 @@ function sessionToBody(session) {
11702
11712
  userId: session.userId,
11703
11713
  username: session.username,
11704
11714
  integrationId: session.integrationId,
11715
+ ...session.instanceId !== null ? { instanceId: session.instanceId } : {},
11705
11716
  scopes: session.scopes,
11706
11717
  createdAt: session.createdAt,
11707
11718
  lastUsedAt: session.lastUsedAt,
@@ -11714,6 +11725,7 @@ function rowToSession(id, body) {
11714
11725
  userId: body.userId,
11715
11726
  username: body.username,
11716
11727
  integrationId: body.integrationId,
11728
+ instanceId: body.instanceId ?? null,
11717
11729
  scopes: body.scopes,
11718
11730
  createdAt: body.createdAt,
11719
11731
  lastUsedAt: body.lastUsedAt,
@@ -11745,6 +11757,7 @@ var OauthSessionManager = class {
11745
11757
  userId: input.userId,
11746
11758
  username: input.username,
11747
11759
  integrationId: input.integrationId,
11760
+ instanceId: input.instanceId ?? null,
11748
11761
  scopes: input.scopes.map((s) => ({ ...s })),
11749
11762
  createdAt: now,
11750
11763
  lastUsedAt: now,
@@ -12064,6 +12077,7 @@ var LocalAuthAddon = class extends require_dist.BaseAddon {
12064
12077
  userId: s.userId,
12065
12078
  username: s.username,
12066
12079
  integrationId: s.integrationId,
12080
+ instanceId: s.instanceId,
12067
12081
  scopes: s.scopes,
12068
12082
  createdAt: s.createdAt,
12069
12083
  lastUsedAt: s.lastUsedAt,
@@ -1,8 +1,8 @@
1
1
  import { i as __require, o as __toESM, t as __commonJSMin } from "../../chunk-CNf5ZN-e.mjs";
2
- import { Dn as authProviderCapability, E as CREDENTIAL_TOKEN_AUDIENCE, Fc as isSecretMarker, Fn as buildDeviceSignatureMessage, Gr as formatDeviceRevoker, Ht as PreferenceNamespaceSchema, It as PREFERENCES_MAX_VALUE_BYTES, N as CredentialTokenClaimsSchema, Pn as buildDeviceEnrollmentLink, Rc as makeSecretMarker, So as userManagementCapability, Ut as PreferenceValueSchema, V as DEVICE_ENROLLMENT_TTL_MS, Vt as PreferenceDeviceIdSchema, W as DEVICE_NONCE_TTL_MS, an as SsoBridgeClaimsSchema, fn as TokenScopeSchema, gc as defineRecordKinds, hs as BaseAddon, mn as UserRecordSchema, ol as userError, rn as ScopedTokenSchema, si as isCredentialTokenPayload, yr as deviceCredentialsCapability } from "../../dist-OmrC_RZs.mjs";
2
+ import { B as DEVICE_ENROLLMENT_TTL_MS, Cc as defineRecordKinds, Cr as deviceCredentialsCapability, E as CREDENTIAL_TOKEN_AUDIENCE, Fn as buildDeviceEnrollmentLink, Gc as makeSecretMarker, Hc as isSecretMarker, Ht as PreferenceDeviceIdSchema, In as buildDeviceSignatureMessage, Lt as PREFERENCES_MAX_VALUE_BYTES, M as CredentialTokenClaimsSchema, On as authProviderCapability, Ss as BaseAddon, U as DEVICE_NONCE_TTL_MS, Ut as PreferenceNamespaceSchema, Wt as PreferenceValueSchema, Xr as formatDeviceRevoker, hn as UserRecordSchema, in as ScopedTokenSchema, ko as userManagementCapability, pi as isCredentialTokenPayload, pl as userError, pn as TokenScopeSchema, sn as SsoBridgeClaimsSchema } from "../../dist-4jAoRtpT.mjs";
3
3
  import { t as require_safe_buffer } from "../../safe-buffer-B1OjL1I9.mjs";
4
4
  import { t as require_ms } from "../../ms-CgH2OFlD.mjs";
5
- 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-CVP5h3u1.mjs";
5
+ 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-Dk_9f4MY.mjs";
6
6
  import { t as require_read_all_rows } from "../../read-all-rows-TaPqdWNF.mjs";
7
7
  import { z } from "zod";
8
8
  import * as crypto$1 from "node:crypto";
@@ -6081,6 +6081,7 @@ var AuthManager = class {
6081
6081
  ...payload.scopes !== void 0 ? { scopes: payload.scopes } : {},
6082
6082
  ...payload.redirectUri !== void 0 ? { redirectUri: payload.redirectUri } : {},
6083
6083
  ...payload.integrationId !== void 0 ? { integrationId: payload.integrationId } : {},
6084
+ ...payload.instanceId !== void 0 ? { instanceId: payload.instanceId } : {},
6084
6085
  ...payload.jti !== void 0 ? { jti: payload.jti } : {},
6085
6086
  ...payload.sessionId !== void 0 ? { sessionId: payload.sessionId } : {},
6086
6087
  ...payload.refreshTtl !== void 0 ? { refreshTtl: payload.refreshTtl } : {},
@@ -6127,6 +6128,7 @@ var AuthManager = class {
6127
6128
  const scopes = Array.isArray(decoded["scopes"]) ? decoded["scopes"] : void 0;
6128
6129
  const redirectUri = typeof decoded["redirectUri"] === "string" ? decoded["redirectUri"] : void 0;
6129
6130
  const integrationId = typeof decoded["integrationId"] === "string" ? decoded["integrationId"] : void 0;
6131
+ const instanceId = typeof decoded["instanceId"] === "string" ? decoded["instanceId"] : void 0;
6130
6132
  const jti = typeof decoded["jti"] === "string" ? decoded["jti"] : void 0;
6131
6133
  const sessionId = typeof decoded["sessionId"] === "string" ? decoded["sessionId"] : void 0;
6132
6134
  const linkIntent = typeof decoded["linkIntent"] === "string" ? decoded["linkIntent"] : void 0;
@@ -6148,6 +6150,7 @@ var AuthManager = class {
6148
6150
  ...scopes !== void 0 ? { scopes } : {},
6149
6151
  ...redirectUri !== void 0 ? { redirectUri } : {},
6150
6152
  ...integrationId !== void 0 ? { integrationId } : {},
6153
+ ...instanceId !== void 0 ? { instanceId } : {},
6151
6154
  ...jti !== void 0 ? { jti } : {},
6152
6155
  ...sessionId !== void 0 ? { sessionId } : {},
6153
6156
  ...refreshTtl !== void 0 ? { refreshTtl } : {},
@@ -7435,6 +7438,7 @@ var OauthSessionBodySchema = z.object({
7435
7438
  userId: z.string(),
7436
7439
  username: z.string(),
7437
7440
  integrationId: z.string(),
7441
+ instanceId: z.string().optional(),
7438
7442
  scopes: z.array(TokenScopeSchema),
7439
7443
  createdAt: z.number(),
7440
7444
  lastUsedAt: z.number(),
@@ -11586,12 +11590,14 @@ function createOauthGrants(ssoBridge, sessionManager) {
11586
11590
  * every integration; the refresh lifetime is the knob, because a refresh is
11587
11591
  * re-checked against the session every time it is used.
11588
11592
  */
11589
- async function mintPair(userId, username, scopes, hubUrl, sessionId, refreshTtl) {
11593
+ async function mintPair(userId, username, scopes, hubUrl, sessionId, refreshTtl, instanceId) {
11594
+ const instanceClaim = instanceId !== null ? { instanceId } : {};
11590
11595
  const access = await ssoBridge.signBridgeToken({
11591
11596
  claims: {
11592
11597
  ...baseClaims(userId, username, scopes, hubUrl),
11593
11598
  provider: "oauth-access",
11594
- sessionId
11599
+ sessionId,
11600
+ ...instanceClaim
11595
11601
  },
11596
11602
  ttlSec: TTL["oauth-access"]
11597
11603
  });
@@ -11600,6 +11606,7 @@ function createOauthGrants(ssoBridge, sessionManager) {
11600
11606
  ...baseClaims(userId, username, scopes, hubUrl),
11601
11607
  provider: "oauth-refresh",
11602
11608
  sessionId,
11609
+ ...instanceClaim,
11603
11610
  refreshTtl
11604
11611
  },
11605
11612
  ttlSec: refreshTtl
@@ -11625,6 +11632,7 @@ function createOauthGrants(ssoBridge, sessionManager) {
11625
11632
  provider: "oauth-code",
11626
11633
  redirectUri: input.redirectUri,
11627
11634
  integrationId: input.integrationId,
11635
+ ...input.instanceId !== void 0 ? { instanceId: input.instanceId } : {},
11628
11636
  jti,
11629
11637
  ...input.codeChallenge ? { codeChallenge: input.codeChallenge } : {},
11630
11638
  ...input.refreshTtlSec !== void 0 ? { refreshTtl: input.refreshTtlSec } : {}
@@ -11654,9 +11662,10 @@ function createOauthGrants(ssoBridge, sessionManager) {
11654
11662
  userId: claims.userId,
11655
11663
  username: claims.username,
11656
11664
  integrationId: typeof claims.integrationId === "string" ? claims.integrationId : "<unknown>",
11665
+ instanceId: typeof claims.instanceId === "string" ? claims.instanceId : null,
11657
11666
  scopes
11658
11667
  });
11659
- return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", session.id, readRefreshTtl(claims.refreshTtl));
11668
+ return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", session.id, readRefreshTtl(claims.refreshTtl), session.instanceId);
11660
11669
  },
11661
11670
  async oauthRefresh(input) {
11662
11671
  const claims = await ssoBridge.verifyBridgeToken({ token: input.refreshToken });
@@ -11667,7 +11676,7 @@ function createOauthGrants(ssoBridge, sessionManager) {
11667
11676
  if (!session || session.revokedAt != null) return null;
11668
11677
  await sessionManager.touch(sessionId);
11669
11678
  const scopes = claims.scopes ?? [];
11670
- return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", sessionId, readRefreshTtl(claims.refreshTtl));
11679
+ return mintPair(claims.userId, claims.username, scopes, claims.hubUrl ?? "", sessionId, readRefreshTtl(claims.refreshTtl), session.instanceId);
11671
11680
  },
11672
11681
  async oauthVerifyAccessToken(input) {
11673
11682
  const claims = await ssoBridge.verifyBridgeToken({ token: input.token });
@@ -11679,7 +11688,8 @@ function createOauthGrants(ssoBridge, sessionManager) {
11679
11688
  return {
11680
11689
  userId: claims.userId,
11681
11690
  username: claims.username,
11682
- scopes: claims.scopes ?? []
11691
+ scopes: claims.scopes ?? [],
11692
+ ...session.instanceId !== null ? { instanceId: session.instanceId } : {}
11683
11693
  };
11684
11694
  }
11685
11695
  };
@@ -11691,6 +11701,7 @@ function sessionToBody(session) {
11691
11701
  userId: session.userId,
11692
11702
  username: session.username,
11693
11703
  integrationId: session.integrationId,
11704
+ ...session.instanceId !== null ? { instanceId: session.instanceId } : {},
11694
11705
  scopes: session.scopes,
11695
11706
  createdAt: session.createdAt,
11696
11707
  lastUsedAt: session.lastUsedAt,
@@ -11703,6 +11714,7 @@ function rowToSession(id, body) {
11703
11714
  userId: body.userId,
11704
11715
  username: body.username,
11705
11716
  integrationId: body.integrationId,
11717
+ instanceId: body.instanceId ?? null,
11706
11718
  scopes: body.scopes,
11707
11719
  createdAt: body.createdAt,
11708
11720
  lastUsedAt: body.lastUsedAt,
@@ -11734,6 +11746,7 @@ var OauthSessionManager = class {
11734
11746
  userId: input.userId,
11735
11747
  username: input.username,
11736
11748
  integrationId: input.integrationId,
11749
+ instanceId: input.instanceId ?? null,
11737
11750
  scopes: input.scopes.map((s) => ({ ...s })),
11738
11751
  createdAt: now,
11739
11752
  lastUsedAt: now,
@@ -12053,6 +12066,7 @@ var LocalAuthAddon = class extends BaseAddon {
12053
12066
  userId: s.userId,
12054
12067
  username: s.username,
12055
12068
  integrationId: s.integrationId,
12069
+ instanceId: s.instanceId,
12056
12070
  scopes: s.scopes,
12057
12071
  createdAt: s.createdAt,
12058
12072
  lastUsedAt: s.lastUsedAt,